xref: /plugin/dokullm/action.php (revision f5cd15525c131a89f6fb8e0187b176b27ed399ea)
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        try {
303            $content = $this->getPageContent('dokullm:profiles:' . $profile);
304        } catch (Exception $e) {
305            // If access is denied or page doesn't exist, return empty list
306            return [];
307        }
308        // Return empty list if page doesn't exist
309        if ($content === false) {
310            return [];
311        }
312        // Parse the table from the page content
313        $actions = [];
314        $lines = explode("\n", $content);
315        $inTable = false;
316        foreach ($lines as $line) {
317            // Check if this is a table row
318            if (preg_match('/^\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|$/', $line, $matches)) {
319                $inTable = true;
320                // Skip header row
321                if (trim($matches[1]) === 'ID' || trim($matches[1]) === 'id') {
322                    continue;
323                }
324                // Extract ID from either simple text or page link
325                $rawId = trim($matches[1]);
326                $id = $rawId;
327                // Check if ID is a page link in format [[namespace:page]] or [[.:namespace:page]]
328                if (preg_match('/\[\[\.?:?([^\]]+)\]\]/', $rawId, $linkMatches)) {
329                    // Extract the actual page path
330                    $pagePath = $linkMatches[1];
331                    // Get the last part after the final ':' as the ID
332                    $pathParts = explode(':', $pagePath);
333                    $id = end($pathParts);
334                }
335                // Append the action definition
336                $actions[] = [
337                    'id' => $id,
338                    'label' => trim($matches[2]),
339                    'description' => trim($matches[3]),
340                    'icon' => trim($matches[4]),
341                    'result' => trim($matches[5])
342                ];
343            } else if ($inTable) {
344                // We've exited the table, so stop parsing
345                break;
346            }
347        }
348        // Return the actions definitions
349        return $actions;
350    }
351
352
353    /**
354     * Get the content of a DokuWiki page
355     *
356     * Retrieves the raw content of a DokuWiki page by its ID.
357     * Used for loading template and example page content for context.
358     *
359     * @param string $pageId The page ID to retrieve
360     * @return string|false The page content or false if not found/readable
361     * @throws Exception If access is denied
362     */
363    private function getPageContent($pageId)
364    {
365        // Clean the ID and check ACL
366        $cleanId = cleanID($pageId);
367        if (auth_quickaclcheck($cleanId) < AUTH_READ) {
368            throw new Exception('You are not allowed to read this file');
369        }
370
371        // Convert page ID to file path
372        $pageFile = wikiFN($cleanId);
373        // Check if file exists and is readable
374        if (file_exists($pageFile) && is_readable($pageFile)) {
375            return file_get_contents($pageFile);
376        }
377        return false;
378    }
379
380    /**
381     * Find an appropriate template based on the provided text
382     *
383     * Uses ChromaDB to search for the most relevant template based on the content.
384     *
385     * @param string $text The text to use for finding a template
386     * @return array The template ID array or empty array if none found
387     * @throws Exception If an error occurs during the search
388     */
389    private function findTemplate($text) {
390        try {
391            // Create ChromaDB client only if enabled
392            $chromaClient = null;
393            if ($this->getConf('enable_chromadb')) {
394                $chromaClient = new \dokuwiki\plugin\dokullm\ChromaDBClient(
395                    $this->getConf('chroma_host'),
396                    $this->getConf('chroma_port'),
397                    $this->getConf('chroma_tenant'),
398                    $this->getConf('chroma_database'),
399                    $this->getConf('chroma_collection'),
400                    $this->getConf('ollama_host'),
401                    $this->getConf('ollama_port'),
402                    $this->getConf('ollama_embeddings_model')
403                );
404            }
405            $client = new \dokuwiki\plugin\dokullm\LlmClient(
406                $this->getConf('api_url'),
407                $this->getConf('api_key'),
408                $this->getConf('model'),
409                $this->getConf('timeout'),
410                $this->getConf('temperature'),
411                $this->getConf('top_p'),
412                $this->getConf('top_k'),
413                $this->getConf('min_p'),
414                $this->getConf('think', false),
415                $this->getConf('profile', 'default'),
416                $chromaClient,
417                $ID
418            );
419            // Query ChromaDB for the most relevant template
420            $template = $client->queryChromaDBTemplate($text);
421            return $template;
422        } catch (Exception $e) {
423            throw new Exception('Error finding template: ' . $e->getMessage());
424        }
425    }
426
427
428    /**
429     * Handle page save event and send page to ChromaDB
430     *
431     * This method is triggered after a page is saved and sends the page content
432     * to ChromaDB for indexing.
433     *
434     * @param Doku_Event $event The event object
435     * @param mixed $param Additional parameters
436     */
437    public function handlePageSave(Doku_Event $event, $param)
438    {
439        global $ID;
440        // Only process if we have a valid page ID
441        if (empty($ID)) {
442            return;
443        }
444
445        // Check ACL before accessing page content
446        if (auth_quickaclcheck($ID) < AUTH_READ) {
447            // Log error but don't stop execution
448            \dokuwiki\Logger::error('dokullm: Access denied for page: ' . $ID);
449            return;
450        }
451
452        // Get the page content
453        $content = rawWiki($ID);
454        // Skip empty pages
455        if (empty($content)) {
456            return;
457        }
458        try {
459            // Send page to ChromaDB
460            $this->sendPageToChromaDB($ID, $content);
461        } catch (Exception $e) {
462            // Log error but don't stop execution
463            \dokuwiki\Logger::error('dokullm: Error sending page to ChromaDB: ' . $e->getMessage());
464        }
465    }
466
467
468    /**
469     * Send page content to ChromaDB
470     *
471     * @param string $pageId The page ID
472     * @param string $content The page content
473     * @return void
474     */
475    private function sendPageToChromaDB($pageId, $content)
476    {
477        // Skip if ChromaDB is disabled
478        if (!$this->getConf('enable_chromadb')) {
479            return;
480        }
481        // Convert page ID to file path format for ChromaDB
482        $filePath = wikiFN($pageId);
483        try {
484            // Get configuration values
485            $chromaHost = $this->getConf('chroma_host');
486            $chromaPort = $this->getConf('chroma_port');
487            $chromaTenant = $this->getConf('chroma_tenant');
488            $chromaDatabase = $this->getConf('chroma_database');
489            $ollamaHost = $this->getConf('ollama_host');
490            $ollamaPort = $this->getConf('ollama_port');
491            $ollamaModel = $this->getConf('ollama_embeddings_model');
492            // Use the existing ChromaDB client to process the file
493            $chroma = new \dokuwiki\plugin\dokullm\ChromaDBClient(
494                $chromaHost,
495                $chromaPort,
496                $chromaTenant,
497                $chromaDatabase,
498                $this->getConf('chroma_collection'),
499                $ollamaHost,
500                $ollamaPort,
501                $ollamaModel
502            );
503            // Use the first part of the document ID as collection name, fallback to 'documents'
504            $idParts = explode(':', $pageId);
505            $collectionName = isset($idParts[0]) && !empty($idParts[0]) ? $idParts[0] : 'documents';
506            // Process the file directly
507            $result = $chroma->processSingleFile($filePath, $collectionName, false);
508            // Log success or failure
509            if ($result['status'] === 'success') {
510                \dokuwiki\Logger::debug('dokullm: Successfully sent page to ChromaDB: ' . $pageId);
511            } else if ($result['status'] === 'skipped') {
512                \dokuwiki\Logger::debug('dokullm: Skipped sending page to ChromaDB: ' . $pageId . ' - ' . $result['message']);
513            } else {
514                \dokuwiki\Logger::error('dokullm: Error sending page to ChromaDB: ' . $pageId . ' - ' . $result['message']);
515            }
516        } catch (Exception $e) {
517            throw $e;
518        }
519    }
520
521
522   /**
523     * Handler to load page template.
524     *
525     * @param Doku_Event $event  event object by reference
526     * @param mixed      $param  [the parameters passed as fifth argument to register_hook() when this
527     *                           handler was registered]
528     * @return void
529     */
530    public function handleTemplate(Doku_Event &$event, $param) {
531        if (strlen($_REQUEST['copyfrom']) > 0) {
532            $template_id = $_REQUEST['copyfrom'];
533            if (auth_quickaclcheck($template_id) >= AUTH_READ) {
534                $tpl = io_readFile(wikiFN($template_id));
535                if ($this->getConf('replace_id')) {
536                    $id = $event->data['id'];
537                    $tpl = str_replace($template_id, $id, $tpl);
538                }
539                // Add LLM_TEMPLATE metadata if the original page ID contains 'template'
540                if (strpos($template_id, 'template') !== false) {
541                    $tpl = $this->insertMetadataAfterTitle($tpl, '~~LLM_TEMPLATE:' . $template_id . '~~');
542                }
543                $event->data['tpl'] = $tpl;
544                $event->preventDefault();
545            }
546        }
547    }
548
549
550
551   /**
552     * Add 'Copy page' button to page tools, SVG based
553     *
554     * @param Doku_Event $event
555     */
556    public function addCopyPageButton(Doku_Event $event)
557    {
558        global $INFO;
559        if ($event->data['view'] != 'page' || !$this->getConf('show_copy_button')) {
560            return;
561        }
562        if (! $INFO['exists']) {
563            return;
564        }
565        array_splice($event->data['items'], -1, 0, [new \dokuwiki\plugin\dokullm\MenuItem()]);
566    }
567}
568