xref: /plugin/dokullm/action.php (revision d8e646eeef40a6869c6ad7fa046c5adb5f0bc545)
1<?php
2/**
3 * DokuWiki Plugin dokullm (Action Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 * @author  Costin Stroie <costinstroie@eridu.eu.org>
7 */
8
9// must be run within Dokuwiki
10if (!defined('DOKU_INC')) {
11    die();
12}
13
14/**
15 * Main action component for the dokullm plugin
16 *
17 * This class handles:
18 * - Registering event handlers for page rendering and AJAX calls
19 * - Adding JavaScript to edit pages
20 * - Processing AJAX requests from the frontend
21 * - Handling page template loading with metadata support
22 * - Adding copy page button to page tools
23 *
24 * The plugin provides integration with LLM APIs for text processing
25 * operations directly within the DokuWiki editor.
26 *
27 * Configuration options:
28 * - api_url: The LLM API endpoint URL
29 * - api_key: Authentication key for the API (optional)
30 * - model: The model identifier to use for requests
31 * - timeout: Request timeout in seconds
32 * - profile: Profile for prompt templates
33 * - temperature: Temperature setting for response randomness (0.0-1.0)
34 * - top_p: Top-p (nucleus sampling) setting (0.0-1.0)
35 * - top_k: Top-k setting (integer >= 1)
36 * - min_p: Minimum probability threshold (0.0-1.0)
37 * - think: Whether to enable thinking in LLM responses (boolean)
38 * - show_copy_button: Whether to show the copy page button (boolean)
39 * - replace_id: Whether to replace template ID when copying (boolean)
40 */
41class action_plugin_dokullm extends DokuWiki_Action_Plugin
42{
43    /**
44     * Register the event handlers for this plugin
45     *
46     * Hooks into:
47     * - TPL_METAHEADER_OUTPUT: To add JavaScript to edit pages
48     * - AJAX_CALL_UNKNOWN: To handle plugin-specific AJAX requests
49     *
50     * @param Doku_Event_Handler $controller The event handler controller
51     */
52    public function register(Doku_Event_Handler $controller)
53    {
54        $controller->register_hook('DOKUWIKI_STARTED', 'AFTER', $this, 'handleDokuwikiStarted');
55        $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'handleMetaHeaders');
56        $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handleAjax');
57        $controller->register_hook('COMMON_PAGETPL_LOAD', 'BEFORE', $this, 'handleTemplate');
58        $controller->register_hook('MENU_ITEMS_ASSEMBLY', 'AFTER', $this, 'addCopyPageButton', array());
59        $controller->register_hook('INDEXER_TASKS_RUN', 'AFTER', $this, 'handlePageSave');
60    }
61
62
63    /**
64     * Insert metadata line after the first title in DokuWiki format
65     *
66     * If the first line starts with '=', insert the metadata after it.
67     * Otherwise, insert at the very beginning.
68     *
69     * @param string $text The text content
70     * @param string $metadataLine The metadata line to insert
71     * @return string The text with metadata inserted
72     */
73    private function insertMetadataAfterTitle($text, $metadataLine) {
74        // Check if the first line is a title (starts with = in DokuWiki)
75        $lines = explode("\n", $text);
76        if (count($lines) > 0 && trim($lines[0]) !== '' && trim($lines[0])[0] === '=') {
77            // Insert after the first line (the title)
78            array_splice($lines, 1, 0, $metadataLine);
79            return implode("\n", $lines);
80        } else {
81            // Insert at the very beginning
82            return $metadataLine . "\n" . $text;
83        }
84    }
85
86
87    /**
88     * Add JavaScript to the page header for edit pages
89     *
90     * This method checks if we're on an edit or preview page and adds
91     * the plugin's JavaScript file to the page header.
92     *
93     * @param Doku_Event $event The event object
94     * @param mixed $param Additional parameters
95     */
96    public function handleMetaHeaders(Doku_Event $event, $param)
97    {
98        global $INFO;
99        // Only add JS to edit pages
100        if ($INFO['act'] == 'edit' || $INFO['act'] == 'preview') {
101            $event->data['script'][] = array(
102                'type' => 'text/javascript',
103                'src' => DOKU_BASE . 'lib/plugins/dokullm/script.js',
104                '_data' => 'dokullm'
105            );
106        }
107    }
108
109
110    /**
111     * Add dokullm configuration to JSINFO
112     *
113     * @param Doku_Event $event The event object
114     * @param mixed $param Additional parameters
115     */
116    public function handleDokuwikiStarted(Doku_Event $event, $param)
117    {
118        global $JSINFO;
119
120        if (!isset($JSINFO['plugins'])) {
121            $JSINFO['plugins'] = [];
122        }
123
124        $JSINFO['plugins']['dokullm'] = [
125            'enable_chromadb' => $this->getConf('enable_chromadb')
126        ];
127    }
128
129
130    /**
131     * Handle AJAX requests for the plugin
132     *
133     * Processes AJAX calls with the identifier 'plugin_dokullm' and
134     * routes them to the appropriate text processing method.
135     *
136     * @param Doku_Event $event The event object
137     * @param mixed $param Additional parameters
138     */
139    public function handleAjax(Doku_Event $event, $param)
140    {
141        if ($event->data !== 'plugin_dokullm') {
142            return;
143        }
144
145        $event->stopPropagation();
146        $event->preventDefault();
147
148        // Handle the AJAX request
149        $this->processRequest();
150    }
151
152
153    /**
154     * Process the AJAX request and return JSON response
155     *
156     * Extracts action, text, prompt, metadata, and template parameters from the request,
157     * validates the input, and calls the appropriate processing method.
158     * Returns JSON encoded result or error.
159     *
160     * @return void
161     */
162    private function processRequest()
163    {
164        global $INPUT;
165        // Get form data
166        $action = $INPUT->str('action');
167        $text = $INPUT->str('text');
168        $prompt = $INPUT->str('prompt', '');
169        $template = $INPUT->str('template', '');
170        $examples = $INPUT->str('examples', '');
171        $previous = $INPUT->str('previous', '');
172        // Parse examples - split by newline and filter out empty lines
173        $examplesList = array_filter(array_map('trim', explode("\n", $examples)));
174        // Create metadata object with prompt, template, examples, and previous
175        $metadata = [
176            'prompt' => $prompt,
177            'template' => $template,
178            'examples' => $examplesList,
179            'previous' => $previous
180        ];
181        // Handle the special case of get_actions action
182        if ($action === 'get_actions') {
183            try {
184                $actions = $this->getActions();
185                echo json_encode(['result' => $actions]);
186            } catch (Exception $e) {
187                http_status(500);
188                echo json_encode(['error' => $e->getMessage()]);
189            }
190            return;
191        }
192        // Handle the special case of get_template action
193        if ($action === 'get_template') {
194            try {
195                $templateId = $template;
196                $templateContent = $this->getPageContent($templateId);
197                if ($templateContent === false) {
198                    throw new Exception('Template not found: ' . $templateId);
199                }
200                echo json_encode(['result' => ['content' => $templateContent]]);
201            } catch (Exception $e) {
202                http_status(500);
203                echo json_encode(['error' => $e->getMessage()]);
204            }
205            return;
206        }
207        // Handle the special case of find_template action
208        if ($action === 'find_template') {
209            try {
210                $searchText = $INPUT->str('text');
211                $template = $this->findTemplate($searchText);
212                if (!empty($template)) {
213                    echo json_encode(['result' => ['template' => $template[0]]]);
214                } else {
215                    echo json_encode(['result' => ['template' => null]]);
216                }
217            } catch (Exception $e) {
218                http_status(500);
219                echo json_encode(['error' => $e->getMessage()]);
220            }
221            return;
222        }
223        // Validate input
224        if (empty($text)) {
225            http_status(400);
226            echo json_encode(['error' => 'No text provided']);
227            return;
228        }
229        // Create ChromaDB client only if enabled
230        $chromaClient = null;
231        if ($this->getConf('enable_chromadb')) {
232            $chromaClient = new \dokuwiki\plugin\dokullm\ChromaDBClient(
233                $this->getConf('chroma_host'),
234                $this->getConf('chroma_port'),
235                $this->getConf('chroma_tenant'),
236                $this->getConf('chroma_database'),
237                $this->getConf('chroma_collection'),
238                $this->getConf('ollama_host'),
239                $this->getConf('ollama_port'),
240                $this->getConf('ollama_embeddings_model')
241            );
242        }
243        $client = new \dokuwiki\plugin\dokullm\LlmClient(
244            $this->getConf('api_url'),
245            $this->getConf('api_key'),
246            $this->getConf('model'),
247            $this->getConf('timeout'),
248            $this->getConf('temperature'),
249            $this->getConf('top_p'),
250            $this->getConf('top_k'),
251            $this->getConf('min_p'),
252            $this->getConf('think', false),
253            $this->getConf('profile', 'default'),
254            $chromaClient,
255            $ID
256        );
257        try {
258            $result = $client->process($action, $text, $metadata);
259            echo json_encode(['result' => $result]);
260        } catch (Exception $e) {
261            http_status(500);
262            echo json_encode(['error' => $e->getMessage()]);
263        }
264    }
265
266
267    /**
268     * Get action definitions from the DokuWiki table at dokullm:profiles:PROFILE
269     *
270     * Parses the table containing action definitions with the following columns:
271     *
272     * - ID: The action identifier, which corresponds to the prompt name
273     * - Label: The text displayed on the button
274     * - Description: A detailed description of the action, used as a tooltip
275     * - Icon: The icon displayed on the button (can be empty)
276     * - Result: The action to perform with the LLM result:
277     *   - show: Display the result in a modal dialog
278     *   - append: Add the result to the end of the current content
279     *   - replace: Replace the selected content with the result
280     *   - insert: Insert the result at the cursor position
281     *
282     * The parsing stops after the first table ends to avoid processing
283     * additional tables that might contain disabled or work-in-progress commands.
284     *
285     * The ID can be either:
286     * - A simple word (e.g., "summary")
287     * - A link to a page in the profile namespace (e.g., "[[.:default:summarize]]")
288     *
289     * For page links, the actual ID is extracted as the last part after the final ':'
290     *
291     * @return array Array of action definitions, each containing:
292     *               - id: string, the action identifier
293     *               - label: string, the button label
294     *               - description: string, the action description
295     *               - icon: string, the icon name
296     *               - result: string, the result handling method
297     */
298    private function getActions()
299    {
300        // Get the content of the profile page
301        $profile = $this->getConf('profile', 'default');
302        $content = $this->getPageContent('dokullm:profiles:' . $profile);
303        // Return empty list if page doesn't exist
304        if ($content === false) {
305            return [];
306        }
307        // Parse the table from the page content
308        $actions = [];
309        $lines = explode("\n", $content);
310        $inTable = false;
311        foreach ($lines as $line) {
312            // Check if this is a table row
313            if (preg_match('/^\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|$/', $line, $matches)) {
314                $inTable = true;
315                // Skip header row
316                if (trim($matches[1]) === 'ID' || trim($matches[1]) === 'id') {
317                    continue;
318                }
319                // Extract ID from either simple text or page link
320                $rawId = trim($matches[1]);
321                $id = $rawId;
322                // Check if ID is a page link in format [[namespace:page]] or [[.:namespace:page]]
323                if (preg_match('/\[\[\.?:?([^\]]+)\]\]/', $rawId, $linkMatches)) {
324                    // Extract the actual page path
325                    $pagePath = $linkMatches[1];
326                    // Get the last part after the final ':' as the ID
327                    $pathParts = explode(':', $pagePath);
328                    $id = end($pathParts);
329                }
330                // Append the action definition
331                $actions[] = [
332                    'id' => $id,
333                    'label' => trim($matches[2]),
334                    'description' => trim($matches[3]),
335                    'icon' => trim($matches[4]),
336                    'result' => trim($matches[5])
337                ];
338            } else if ($inTable) {
339                // We've exited the table, so stop parsing
340                break;
341            }
342        }
343        // Return the actions definitions
344        return $actions;
345    }
346
347
348    /**
349     * Get the content of a DokuWiki page
350     *
351     * Retrieves the raw content of a DokuWiki page by its ID.
352     * Used for loading template and example page content for context.
353     *
354     * @param string $pageId The page ID to retrieve
355     * @return string|false The page content or false if not found/readable
356     * @throws Exception If access is denied
357     */
358    private function getPageContent($pageId)
359    {
360        // Clean the ID and check ACL
361        $cleanId = cleanID($pageId);
362        if (auth_quickaclcheck($cleanId) < AUTH_READ) {
363            throw new Exception('You are not allowed to read this file');
364        }
365
366        // Convert page ID to file path
367        $pageFile = wikiFN($cleanId);
368        // Check if file exists and is readable
369        if (file_exists($pageFile) && is_readable($pageFile)) {
370            return file_get_contents($pageFile);
371        }
372        return false;
373    }
374
375    /**
376     * Find an appropriate template based on the provided text
377     *
378     * Uses ChromaDB to search for the most relevant template based on the content.
379     *
380     * @param string $text The text to use for finding a template
381     * @return array The template ID array or empty array if none found
382     * @throws Exception If an error occurs during the search
383     */
384    private function findTemplate($text) {
385        try {
386            // Create ChromaDB client only if enabled
387            $chromaClient = null;
388            if ($this->getConf('enable_chromadb')) {
389                $chromaClient = new \dokuwiki\plugin\dokullm\ChromaDBClient(
390                    $this->getConf('chroma_host'),
391                    $this->getConf('chroma_port'),
392                    $this->getConf('chroma_tenant'),
393                    $this->getConf('chroma_database'),
394                    $this->getConf('chroma_collection'),
395                    $this->getConf('ollama_host'),
396                    $this->getConf('ollama_port'),
397                    $this->getConf('ollama_embeddings_model')
398                );
399            }
400            $client = new \dokuwiki\plugin\dokullm\LlmClient(
401                $this->getConf('api_url'),
402                $this->getConf('api_key'),
403                $this->getConf('model'),
404                $this->getConf('timeout'),
405                $this->getConf('temperature'),
406                $this->getConf('top_p'),
407                $this->getConf('top_k'),
408                $this->getConf('min_p'),
409                $this->getConf('think', false),
410                $this->getConf('profile', 'default'),
411                $chromaClient,
412                $ID
413            );
414            // Query ChromaDB for the most relevant template
415            $template = $client->queryChromaDBTemplate($text);
416            return $template;
417        } catch (Exception $e) {
418            throw new Exception('Error finding template: ' . $e->getMessage());
419        }
420    }
421
422
423    /**
424     * Handle page save event and send page to ChromaDB
425     *
426     * This method is triggered after a page is saved and sends the page content
427     * to ChromaDB for indexing.
428     *
429     * @param Doku_Event $event The event object
430     * @param mixed $param Additional parameters
431     */
432    public function handlePageSave(Doku_Event $event, $param)
433    {
434        global $ID;
435        // Only process if we have a valid page ID
436        if (empty($ID)) {
437            return;
438        }
439        // Get the page content
440        $content = rawWiki($ID);
441        // Skip empty pages
442        if (empty($content)) {
443            return;
444        }
445        try {
446            // Send page to ChromaDB
447            $this->sendPageToChromaDB($ID, $content);
448        } catch (Exception $e) {
449            // Log error but don't stop execution
450            \dokuwiki\Logger::error('dokullm: Error sending page to ChromaDB: ' . $e->getMessage());
451        }
452    }
453
454
455    /**
456     * Send page content to ChromaDB
457     *
458     * @param string $pageId The page ID
459     * @param string $content The page content
460     * @return void
461     */
462    private function sendPageToChromaDB($pageId, $content)
463    {
464        // Skip if ChromaDB is disabled
465        if (!$this->getConf('enable_chromadb')) {
466            return;
467        }
468        // Convert page ID to file path format for ChromaDB
469        $filePath = wikiFN($pageId);
470        try {
471            // Get configuration values
472            $chromaHost = $this->getConf('chroma_host');
473            $chromaPort = $this->getConf('chroma_port');
474            $chromaTenant = $this->getConf('chroma_tenant');
475            $chromaDatabase = $this->getConf('chroma_database');
476            $ollamaHost = $this->getConf('ollama_host');
477            $ollamaPort = $this->getConf('ollama_port');
478            $ollamaModel = $this->getConf('ollama_embeddings_model');
479            // Use the existing ChromaDB client to process the file
480            $chroma = new \dokuwiki\plugin\dokullm\ChromaDBClient(
481                $chromaHost,
482                $chromaPort,
483                $chromaTenant,
484                $chromaDatabase,
485                $this->getConf('chroma_collection'),
486                $ollamaHost,
487                $ollamaPort,
488                $ollamaModel
489            );
490            // Use the first part of the document ID as collection name, fallback to 'documents'
491            $idParts = explode(':', $pageId);
492            $collectionName = isset($idParts[0]) && !empty($idParts[0]) ? $idParts[0] : 'documents';
493            // Process the file directly
494            $result = $chroma->processSingleFile($filePath, $collectionName, false);
495            // Log success or failure
496            if ($result['status'] === 'success') {
497                \dokuwiki\Logger::debug('dokullm: Successfully sent page to ChromaDB: ' . $pageId);
498            } else if ($result['status'] === 'skipped') {
499                \dokuwiki\Logger::debug('dokullm: Skipped sending page to ChromaDB: ' . $pageId . ' - ' . $result['message']);
500            } else {
501                \dokuwiki\Logger::error('dokullm: Error sending page to ChromaDB: ' . $pageId . ' - ' . $result['message']);
502            }
503        } catch (Exception $e) {
504            throw $e;
505        }
506    }
507
508
509   /**
510     * Handler to load page template.
511     *
512     * @param Doku_Event $event  event object by reference
513     * @param mixed      $param  [the parameters passed as fifth argument to register_hook() when this
514     *                           handler was registered]
515     * @return void
516     */
517    public function handleTemplate(Doku_Event &$event, $param) {
518        if (strlen($_REQUEST['copyfrom']) > 0) {
519            $template_id = $_REQUEST['copyfrom'];
520            if (auth_quickaclcheck($template_id) >= AUTH_READ) {
521                $tpl = io_readFile(wikiFN($template_id));
522                if ($this->getConf('replace_id')) {
523                    $id = $event->data['id'];
524                    $tpl = str_replace($template_id, $id, $tpl);
525                }
526                // Add LLM_TEMPLATE metadata if the original page ID contains 'template'
527                if (strpos($template_id, 'template') !== false) {
528                    $tpl = $this->insertMetadataAfterTitle($tpl, '~~LLM_TEMPLATE:' . $template_id . '~~');
529                }
530                $event->data['tpl'] = $tpl;
531                $event->preventDefault();
532            }
533        }
534    }
535
536
537
538   /**
539     * Add 'Copy page' button to page tools, SVG based
540     *
541     * @param Doku_Event $event
542     */
543    public function addCopyPageButton(Doku_Event $event)
544    {
545        global $INFO;
546        if ($event->data['view'] != 'page' || !$this->getConf('show_copy_button')) {
547            return;
548        }
549        if (! $INFO['exists']) {
550            return;
551        }
552        array_splice($event->data['items'], -1, 0, [new \dokuwiki\plugin\dokullm\MenuItem()]);
553    }
554}
555