PluginProbe
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin / 1.0.0
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin v1.0.0
1.1.10 1.1.9 1.1.8 1.1.7 1.1.6 1.1.5 1.1.4 1.1.3 1.1.2 1.1.1 1.1.0 1.0.1 1.0.0 0.9.8 0.9.7 0.9.6 0.9.4 0.9.5 0.9.3 0.9.2 0.9.1 0.9.0 0.8.9 0.8.8 0.8.7 All 34 releases
desktop-mode / includes / ai-copilot / search.php

search.php in OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin 1.0.0, at includes/ai-copilot/search.php

2,439 lines 88.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * OpenStation — AI Copilot content search via the provider tool use.
4 *
5 * Agentic search loop: the user describes something in natural language and
6 * the agent calls focused tools, choosing the right one based on query
7 * semantics. Built-in tools: four content-search tools — search_posts,
8 * search_pages, search_comments, search_comments_by_post — plus
9 * list_admin_pages (admin navigation catalog), search_wporg_plugins
10 * (WordPress.org plugin directory), and get_php_error_log (error-log
11 * tail). Each content-search tool runs WordPress's native search
12 * (WP_Query `s=` / get_comments `search=`) for the keywords the model
13 * distils from the request, then returns up to 10 matching entities with
14 * their real title + content excerpt for the model to compare to the
15 * user's description. No AI pre-analysis is required — every published
16 * post/page/comment is findable. The built-in tools are WordPress Abilities
17 * (see abilities.php); client command tools are advertised alongside them and
18 * dispatched by the same loop.
19 *
20 * Focused tools instead of one routing parameter:
21 * - "I remember a comment where someone said congratulations…" → agent
22 * calls search_comments without needing a routing parameter.
23 * - "I wrote a post about paella in Canarias" → agent calls search_posts.
24 * - "Our About page mentions…" → agent calls search_pages.
25 * - Ambiguous queries → agent tries in priority order (posts → pages →
26 * comments) following the system-prompt guidance.
27 *
28 * Budget: max OPENSTATION_AI_SEARCH_MAX_ITERATIONS (10) tool-call rounds per
29 * request × OPENSTATION_AI_SEARCH_BATCH_SIZE (10) items = up to 100 entities.
30 * When the budget is exhausted the response includes a `continue` object
31 * the client uses to resume from the exact offset that was last searched.
32 *
33 * REST endpoint: POST /desktop-mode/v1/ai/search
34 *
35 * @package OpenStation
36 */
37
38 defined( 'ABSPATH' ) || exit;
39
40 /** Maximum agentic tool-call iterations per search request. */
41 const OPENSTATION_AI_SEARCH_MAX_ITERATIONS = 10;
42
43 /** Entities fetched per tool-call round. */
44 const OPENSTATION_AI_SEARCH_BATCH_SIZE = 10;
45
46 /**
47 * Returns the catalog of common WordPress admin destinations.
48 *
49 * Used by the `list_admin_pages` tool. Each entry has a human title, the
50 * wp-admin URL (rendered through admin_url() so it respects the site's
51 * real admin path), a short description, and a Dashicons icon class the
52 * UI can use when opening the URL in a legacy iframe window.
53 *
54 * Filterable via `openstation_ai_admin_page_catalog` so third-party
55 * plugins can contribute their own admin destinations (e.g. a plugin
56 * adding a top-level menu can surface its settings page here).
57 *
58 * @return array[]
59 */
60 function openstation_ai_get_admin_page_catalog() {
61 $catalog = array(
62 array(
63 'title' => 'Dashboard',
64 'url' => admin_url( 'index.php' ),
65 'icon' => 'dashicons-dashboard',
66 'description' => 'The main admin dashboard — activity, drafts, site overview.',
67 ),
68 array(
69 'title' => 'All Posts',
70 'url' => admin_url( 'edit.php' ),
71 'icon' => 'dashicons-admin-post',
72 'description' => 'List, edit, bulk-manage blog posts.',
73 ),
74 array(
75 'title' => 'Add New Post',
76 'url' => admin_url( 'post-new.php' ),
77 'icon' => 'dashicons-plus',
78 'description' => 'Create a new blog post.',
79 ),
80 array(
81 'title' => 'Categories',
82 'url' => admin_url( 'edit-tags.php?taxonomy=category' ),
83 'icon' => 'dashicons-category',
84 'description' => 'Manage post categories — add, rename, merge.',
85 ),
86 array(
87 'title' => 'Tags',
88 'url' => admin_url( 'edit-tags.php?taxonomy=post_tag' ),
89 'icon' => 'dashicons-tag',
90 'description' => 'Manage post tags.',
91 ),
92 array(
93 'title' => 'All Pages',
94 'url' => admin_url( 'edit.php?post_type=page' ),
95 'icon' => 'dashicons-admin-page',
96 'description' => 'List and edit static pages (About, Contact, etc.).',
97 ),
98 array(
99 'title' => 'Add New Page',
100 'url' => admin_url( 'post-new.php?post_type=page' ),
101 'icon' => 'dashicons-plus',
102 'description' => 'Create a new page.',
103 ),
104 array(
105 'title' => 'Media Library',
106 'url' => admin_url( 'upload.php' ),
107 'icon' => 'dashicons-admin-media',
108 'description' => 'Browse, upload, and manage images, files, videos.',
109 ),
110 array(
111 'title' => 'Comments',
112 'url' => admin_url( 'edit-comments.php' ),
113 'icon' => 'dashicons-admin-comments',
114 'description' => 'Moderate and reply to comments on posts and pages.',
115 ),
116 array(
117 'title' => 'Themes',
118 'url' => admin_url( 'themes.php' ),
119 'icon' => 'dashicons-admin-appearance',
120 'description' => 'Change, install, or customize the active theme.',
121 ),
122 array(
123 'title' => 'Customize',
124 'url' => admin_url( 'customize.php' ),
125 'icon' => 'dashicons-admin-customizer',
126 'description' => 'Live-preview theme customisation — colors, fonts, layout.',
127 ),
128 array(
129 'title' => 'Widgets',
130 'url' => admin_url( 'widgets.php' ),
131 'icon' => 'dashicons-screenoptions',
132 'description' => 'Manage sidebar and footer widgets.',
133 ),
134 array(
135 'title' => 'Menus',
136 'url' => admin_url( 'nav-menus.php' ),
137 'icon' => 'dashicons-menu',
138 'description' => 'Create and edit navigation menus.',
139 ),
140 array(
141 'title' => 'Plugins',
142 'url' => admin_url( 'plugins.php' ),
143 'icon' => 'dashicons-admin-plugins',
144 'description' => 'Activate, deactivate, update or delete plugins.',
145 ),
146 array(
147 'title' => 'Add New Plugin',
148 'url' => admin_url( 'plugin-install.php' ),
149 'icon' => 'dashicons-plus',
150 'description' => 'Search and install new plugins from the directory.',
151 ),
152 array(
153 'title' => 'Users',
154 'url' => admin_url( 'users.php' ),
155 'icon' => 'dashicons-admin-users',
156 'description' => 'Manage user accounts and roles.',
157 ),
158 array(
159 'title' => 'Add New User',
160 'url' => admin_url( 'user-new.php' ),
161 'icon' => 'dashicons-plus',
162 'description' => 'Create a new user account.',
163 ),
164 array(
165 'title' => 'Your Profile',
166 'url' => admin_url( 'profile.php' ),
167 'icon' => 'dashicons-id',
168 'description' => 'Edit your own profile, password, admin colour scheme.',
169 ),
170 array(
171 'title' => 'General Settings',
172 'url' => admin_url( 'options-general.php' ),
173 'icon' => 'dashicons-admin-settings',
174 'description' => 'Site title, tagline, URL, timezone, language.',
175 ),
176 array(
177 'title' => 'Writing Settings',
178 'url' => admin_url( 'options-writing.php' ),
179 'icon' => 'dashicons-edit',
180 'description' => 'Default post category, post format, remote publishing.',
181 ),
182 array(
183 'title' => 'Reading Settings',
184 'url' => admin_url( 'options-reading.php' ),
185 'icon' => 'dashicons-book',
186 'description' => 'Homepage, blog posts per page, search-engine visibility.',
187 ),
188 array(
189 'title' => 'Discussion Settings',
190 'url' => admin_url( 'options-discussion.php' ),
191 'icon' => 'dashicons-format-chat',
192 'description' => 'Comment moderation, avatars, email notifications.',
193 ),
194 array(
195 'title' => 'Media Settings',
196 'url' => admin_url( 'options-media.php' ),
197 'icon' => 'dashicons-format-image',
198 'description' => 'Image size settings for thumbnail / medium / large.',
199 ),
200 array(
201 'title' => 'Permalinks',
202 'url' => admin_url( 'options-permalink.php' ),
203 'icon' => 'dashicons-admin-links',
204 'description' => 'URL structure for posts, pages, categories, tags.',
205 ),
206 array(
207 'title' => 'Privacy',
208 'url' => admin_url( 'options-privacy.php' ),
209 'icon' => 'dashicons-privacy',
210 'description' => 'Privacy policy page selection and preview.',
211 ),
212 array(
213 'title' => 'Tools',
214 'url' => admin_url( 'tools.php' ),
215 'icon' => 'dashicons-admin-tools',
216 'description' => 'Built-in site tools.',
217 ),
218 array(
219 'title' => 'Import',
220 'url' => admin_url( 'import.php' ),
221 'icon' => 'dashicons-download',
222 'description' => 'Import content from other platforms (WP, Tumblr, RSS, etc.).',
223 ),
224 array(
225 'title' => 'Export',
226 'url' => admin_url( 'export.php' ),
227 'icon' => 'dashicons-upload',
228 'description' => 'Export all site content as XML.',
229 ),
230 array(
231 'title' => 'Site Health',
232 'url' => admin_url( 'site-health.php' ),
233 'icon' => 'dashicons-heart',
234 'description' => 'Performance and security recommendations for the site.',
235 ),
236 array(
237 'title' => 'Updates',
238 'url' => admin_url( 'update-core.php' ),
239 'icon' => 'dashicons-update',
240 'description' => 'WordPress, theme, and plugin updates.',
241 ),
242 );
243
244 /**
245 * Filters the wp-admin page catalog surfaced by the AI assistant.
246 *
247 * @param array[] $catalog Array of entries, each with title/url/icon/description.
248 */
249 return (array) apply_filters( 'openstation_ai_admin_page_catalog', $catalog );
250 }
251
252 // ---------------------------------------------------------------------------
253 // Final-answer JSON Schema
254 // ---------------------------------------------------------------------------
255
256 /**
257 * JSON Schema for the agent's final structured answer.
258 *
259 * @return array
260 */
261 function openstation_ai_search_answer_schema() {
262 return array(
263 'type' => 'object',
264 'additionalProperties' => false,
265 'required' => array( 'answer_type', 'message', 'entity_id', 'entity_type', 'admin_links' ),
266 'properties' => array(
267 'answer_type' => array(
268 'type' => 'string',
269 'enum' => array( 'entity', 'navigation', 'chat' ),
270 'description' => 'Classification of the answer: "entity" when you identified a specific post/page/comment the user was asking about. "navigation" when the user asked where to find something in wp-admin and you are returning admin_links. "chat" for conversational responses that don\'t involve finding content or navigation (e.g. greetings, clarifications, "I couldn\'t find anything").',
271 ),
272 'message' => array(
273 'type' => 'string',
274 'description' => 'A friendly, conversational response to show the user. Write in first person like a helpful assistant (e.g. "I found your Málaga post — this one", "Here\'s where you manage categories"). NOT a search-engine sentence ("Match found").',
275 ),
276 'entity_id' => array(
277 'anyOf' => array(
278 array( 'type' => 'integer' ),
279 array( 'type' => 'null' ),
280 ),
281 'description' => 'The WordPress ID of the matching entity. Required when answer_type is "entity"; set to null otherwise.',
282 ),
283 'entity_type' => array(
284 'anyOf' => array(
285 array(
286 'type' => 'string',
287 'enum' => array( 'post', 'page', 'comment' ),
288 ),
289 array( 'type' => 'null' ),
290 ),
291 'description' => 'Type of the matching entity. Required when answer_type is "entity"; set to null otherwise.',
292 ),
293 'admin_links' => array(
294 'anyOf' => array(
295 array(
296 'type' => 'array',
297 'items' => array(
298 'type' => 'object',
299 'additionalProperties' => false,
300 'required' => array( 'title', 'url', 'description', 'icon' ),
301 'properties' => array(
302 'title' => array( 'type' => 'string' ),
303 'url' => array( 'type' => 'string' ),
304 'description' => array( 'type' => 'string' ),
305 'icon' => array( 'type' => 'string' ),
306 ),
307 ),
308 ),
309 array( 'type' => 'null' ),
310 ),
311 'description' => 'List of 1-3 wp-admin destinations (copy verbatim from the list_admin_pages tool result). Required when answer_type is "navigation"; set to null otherwise.',
312 ),
313 ),
314 );
315 }
316
317 // ---------------------------------------------------------------------------
318 // DB queries — tool execution
319 // ---------------------------------------------------------------------------
320
321 /**
322 * Routes a tool call to the correct DB query by function name.
323 *
324 * The content-search tools (`search_posts`, `search_pages`,
325 * `search_comments`, `search_comments_by_post`) take a keyword `query`
326 * matched with WordPress's native search; `search_comments_by_post`
327 * needs an additional `post_id`. The caller passes the full decoded
328 * arguments array so this function can extract whatever it needs.
329 *
330 * @param string $tool_name Tool function name.
331 * @param array $args Decoded arguments from the model's tool call.
332 * @return array Tool result payload.
333 */
334 function openstation_ai_search_dispatch_tool( $tool_name, array $args ) {
335 $offset = max( 0, (int) ( $args['offset'] ?? 0 ) );
336 $query = isset( $args['query'] ) ? sanitize_text_field( (string) $args['query'] ) : '';
337
338 switch ( $tool_name ) {
339 case 'search_posts':
340 return openstation_ai_search_fetch_posts( 'post', $query, $offset );
341 case 'search_pages':
342 return openstation_ai_search_fetch_posts( 'page', $query, $offset );
343 case 'search_comments':
344 return openstation_ai_search_fetch_comments( $query, $offset );
345 case 'search_comments_by_post':
346 $post_id = max( 0, (int) ( $args['post_id'] ?? 0 ) );
347 return openstation_ai_search_fetch_comments_by_post( $post_id, $query, $offset );
348 case 'list_admin_pages':
349 return array(
350 'tool' => 'list_admin_pages',
351 'pages' => openstation_ai_get_admin_page_catalog(),
352 );
353 case 'search_wporg_plugins':
354 $q = isset( $args['query'] ) ? sanitize_text_field( (string) $args['query'] ) : '';
355 return openstation_ai_fetch_wporg_plugins( $q );
356 case 'get_php_error_log':
357 if ( ! current_user_can( 'manage_options' ) ) {
358 return array(
359 'tool' => 'get_php_error_log',
360 'log_available' => false,
361 'error' => 'Only administrators can access the PHP error log.',
362 'entries' => array(),
363 );
364 }
365 $lines = isset( $args['lines'] ) ? max( 1, min( 500, (int) $args['lines'] ) ) : 50;
366 return openstation_ai_fetch_error_log( $lines );
367 }
368
369 return array(
370 'tool' => $tool_name,
371 'offset' => $offset,
372 'items' => array(),
373 'count' => 0,
374 'total' => 0,
375 'has_more' => false,
376 'error' => "Unknown tool '{$tool_name}'.",
377 );
378 }
379
380 /**
381 * Keyword-searches published posts or pages with WordPress's native search
382 * (`WP_Query` `s=`), returning data rich enough for the agent to compare
383 * AND for the UI to render links.
384 *
385 * No AI analysis is required — every published post/page is searchable.
386 *
387 * @param string $post_type 'post' | 'page'.
388 * @param string $query Keyword search terms (may be empty to list newest).
389 * @param int $offset
390 * @return array
391 */
392 function openstation_ai_search_fetch_posts( $post_type, $query, $offset ) {
393 $wp_query = new WP_Query(
394 array(
395 'post_type' => $post_type,
396 'post_status' => 'publish',
397 's' => (string) $query,
398 'posts_per_page' => OPENSTATION_AI_SEARCH_BATCH_SIZE,
399 'offset' => $offset,
400 'no_found_rows' => false,
401 'update_post_term_cache' => false,
402 'update_post_meta_cache' => false,
403 )
404 );
405
406 $items = array();
407 foreach ( $wp_query->posts as $post ) {
408 $items[] = array(
409 // Identity — used to build the final entity detail.
410 'id' => $post->ID,
411 'type' => $post->post_type,
412 // Comparison data for the model — real title + content excerpt.
413 'title' => wp_strip_all_tags( $post->post_title ),
414 'excerpt' => openstation_ai_search_excerpt( $post->post_content ),
415 'date' => $post->post_date ? substr( $post->post_date, 0, 10 ) : '',
416 // Links — passed through so the UI can link to the entity
417 // once the agent identifies a match.
418 'url' => (string) get_permalink( $post ),
419 'edit_url' => (string) get_edit_post_link( $post->ID, 'raw' ),
420 );
421 }
422
423 $total = (int) $wp_query->found_posts;
424
425 return array(
426 'tool' => 'search_' . $post_type . 's',
427 'query' => (string) $query,
428 'offset' => $offset,
429 'items' => $items,
430 'count' => count( $items ),
431 'total' => $total,
432 'has_more' => ( $offset + OPENSTATION_AI_SEARCH_BATCH_SIZE ) < $total,
433 'next_offset' => $offset + OPENSTATION_AI_SEARCH_BATCH_SIZE,
434 );
435 }
436
437 /**
438 * Trims raw post/comment content into a plain-text excerpt for the model.
439 *
440 * @param string $content Raw post/comment content.
441 * @return string
442 */
443 function openstation_ai_search_excerpt( $content ) {
444 $text = wp_strip_all_tags( (string) $content );
445 $text = preg_replace( '/\s+/', ' ', trim( $text ) );
446 return (string) mb_substr( $text, 0, 300 );
447 }
448
449 /**
450 * Keyword-searches approved comments across all posts with WordPress's
451 * native comment search (`get_comments` `search=`).
452 *
453 * No AI analysis is required — every approved comment is searchable.
454 *
455 * @param string $query Keyword search terms (may be empty to list newest).
456 * @param int $offset
457 * @return array
458 */
459 function openstation_ai_search_fetch_comments( $query, $offset ) {
460 $base_args = array(
461 'status' => 'approve',
462 'type' => 'comment',
463 'search' => (string) $query,
464 );
465
466 $comments = get_comments(
467 array_merge(
468 $base_args,
469 array(
470 'number' => OPENSTATION_AI_SEARCH_BATCH_SIZE,
471 'offset' => $offset,
472 'count' => false,
473 )
474 )
475 );
476
477 $total = (int) get_comments( array_merge( $base_args, array( 'count' => true ) ) );
478
479 // Prime the parent posts in a single query so the per-comment
480 // get_post() calls below are cache hits, not N+1 round-trips.
481 $parent_ids = array_unique(
482 array_map(
483 static function ( $c ) {
484 return (int) $c->comment_post_ID;
485 },
486 $comments
487 )
488 );
489 if ( $parent_ids ) {
490 _prime_post_caches( $parent_ids, false, false );
491 }
492
493 $items = array();
494 foreach ( $comments as $comment ) {
495 $parent_post = get_post( $comment->comment_post_ID );
496 $parent_title = $parent_post ? wp_strip_all_tags( $parent_post->post_title ) : '';
497
498 $items[] = array(
499 'id' => (int) $comment->comment_ID,
500 'type' => 'comment',
501 // Comparison data — real comment text + parent post title.
502 'post_title' => $parent_title,
503 'excerpt' => openstation_ai_search_excerpt( $comment->comment_content ),
504 // Links.
505 'url' => (string) get_comment_link( $comment ),
506 'edit_url' => admin_url( 'comment.php?action=editcomment&c=' . (int) $comment->comment_ID ),
507 'post_id' => (int) $comment->comment_post_ID,
508 'post_url' => $parent_post ? (string) get_permalink( $parent_post ) : '',
509 );
510 }
511
512 return array(
513 'tool' => 'search_comments',
514 'query' => (string) $query,
515 'offset' => $offset,
516 'items' => $items,
517 'count' => count( $items ),
518 'total' => $total,
519 'has_more' => ( $offset + OPENSTATION_AI_SEARCH_BATCH_SIZE ) < $total,
520 'next_offset' => $offset + OPENSTATION_AI_SEARCH_BATCH_SIZE,
521 );
522 }
523
524 // ---------------------------------------------------------------------------
525 // Entity detail builder — final REST response
526 // ---------------------------------------------------------------------------
527
528 /**
529 * Keyword-searches approved comments on a specific post.
530 *
531 * Used by the `search_comments_by_post` tool — the model calls this after
532 * identifying a post via `search_posts`, giving it a scoped, precise set of
533 * comments to compare against the user's description. An empty `$query`
534 * lists the post's comments without keyword filtering.
535 *
536 * @param int $post_id The WordPress post ID.
537 * @param string $query Keyword search terms (may be empty).
538 * @param int $offset
539 * @return array Tool result payload.
540 */
541 function openstation_ai_search_fetch_comments_by_post( $post_id, $query, $offset ) {
542 $post_id = (int) $post_id;
543
544 if ( $post_id <= 0 ) {
545 return array(
546 'tool' => 'search_comments_by_post',
547 'post_id' => $post_id,
548 'offset' => $offset,
549 'items' => array(),
550 'count' => 0,
551 'total' => 0,
552 'has_more' => false,
553 'error' => 'post_id must be a positive integer.',
554 );
555 }
556
557 $base_args = array(
558 'post_id' => $post_id,
559 'status' => 'approve',
560 'type' => 'comment',
561 'search' => (string) $query,
562 );
563
564 $comments = get_comments(
565 array_merge(
566 $base_args,
567 array(
568 'number' => OPENSTATION_AI_SEARCH_BATCH_SIZE,
569 'offset' => $offset,
570 'count' => false,
571 )
572 )
573 );
574
575 $total = (int) get_comments( array_merge( $base_args, array( 'count' => true ) ) );
576
577 $parent_post = get_post( $post_id );
578 $parent_title = $parent_post ? wp_strip_all_tags( $parent_post->post_title ) : '';
579
580 $items = array();
581 foreach ( $comments as $comment ) {
582 $items[] = array(
583 'id' => (int) $comment->comment_ID,
584 'type' => 'comment',
585 'post_id' => $post_id,
586 'post_title' => $parent_title,
587 'excerpt' => openstation_ai_search_excerpt( $comment->comment_content ),
588 'url' => (string) get_comment_link( $comment ),
589 'edit_url' => admin_url( 'comment.php?action=editcomment&c=' . (int) $comment->comment_ID ),
590 );
591 }
592
593 return array(
594 'tool' => 'search_comments_by_post',
595 'post_id' => $post_id,
596 'post_title' => $parent_title,
597 'query' => (string) $query,
598 'offset' => $offset,
599 'items' => $items,
600 'count' => count( $items ),
601 'total' => $total,
602 'has_more' => ( $offset + OPENSTATION_AI_SEARCH_BATCH_SIZE ) < $total,
603 'next_offset' => $offset + OPENSTATION_AI_SEARCH_BATCH_SIZE,
604 );
605 }
606
607 // ---------------------------------------------------------------------------
608 // Entity detail builder — final REST response
609 // ---------------------------------------------------------------------------
610
611 /**
612 * Returns the full entity record used in the `entity` field of the REST
613 * response. All URLs are included so the UI can render direct links.
614 *
615 * Built entirely from core post/comment fields — no AI analysis meta is
616 * required. Comments opportunistically surface the `spam` / `harmful`
617 * verdict when the comment-moderation analysis happens to have run, but
618 * its absence never blocks the entity from being returned.
619 *
620 * @param string $entity_type 'post' | 'page' | 'comment'.
621 * @param int $entity_id
622 * @return array|null
623 */
624 function openstation_ai_search_build_entity( $entity_type, $entity_id ) {
625 $entity_id = (int) $entity_id;
626
627 if ( in_array( $entity_type, array( 'post', 'page' ), true ) ) {
628 $post = get_post( $entity_id );
629 if ( ! $post instanceof WP_Post ) {
630 return null;
631 }
632 return array(
633 'id' => $entity_id,
634 'type' => $post->post_type,
635 'title' => wp_strip_all_tags( $post->post_title ),
636 'status' => $post->post_status,
637 'date' => $post->post_date ? substr( $post->post_date, 0, 10 ) : '',
638 'url' => (string) get_permalink( $post ),
639 'edit_url' => (string) get_edit_post_link( $entity_id, 'raw' ),
640 'excerpt' => openstation_ai_search_excerpt( $post->post_content ),
641 );
642 }
643
644 if ( 'comment' === $entity_type ) {
645 $comment = get_comment( $entity_id );
646 if ( ! $comment instanceof WP_Comment ) {
647 return null;
648 }
649 $meta = openstation_ai_get_meta( 'comment', $entity_id );
650 $parent_post = get_post( $comment->comment_post_ID );
651 return array(
652 'id' => $entity_id,
653 'type' => 'comment',
654 'excerpt' => openstation_ai_search_excerpt( $comment->comment_content ),
655 'post_id' => (int) $comment->comment_post_ID,
656 'post_title' => $parent_post ? wp_strip_all_tags( $parent_post->post_title ) : '',
657 'post_url' => $parent_post ? (string) get_permalink( $parent_post ) : '',
658 'url' => (string) get_comment_link( $comment ),
659 'edit_url' => admin_url( 'comment.php?action=editcomment&c=' . $entity_id ),
660 'harmful' => $meta ? (bool) ( $meta['harmful'] ?? false ) : false,
661 'spam' => $meta ? (bool) ( $meta['spam'] ?? false ) : false,
662 );
663 }
664
665 return null;
666 }
667
668 // ---------------------------------------------------------------------------
669 // Agentic search loop
670 // ---------------------------------------------------------------------------
671
672 /**
673 * Returns a friendly progress message for a tool name — surfaced to the
674 * client via SSE so the user sees "Looking through your posts…" rather
675 * than the raw tool call.
676 *
677 * @param string $tool_name
678 * @return string
679 */
680 function openstation_ai_progress_message( $tool_name ) {
681 switch ( $tool_name ) {
682 case 'search_posts':
683 return 'Looking through your posts…';
684 case 'search_pages':
685 return 'Checking your pages…';
686 case 'search_comments':
687 return 'Reading through comments…';
688 case 'search_comments_by_post':
689 return 'Scanning comments on that post…';
690 case 'list_admin_pages':
691 return 'Finding the right admin page…';
692 case 'search_wporg_plugins':
693 return 'Searching the WordPress.org plugin directory…';
694 case 'get_php_error_log':
695 return 'Tailing the PHP error log…';
696 }
697 return 'Thinking…';
698 }
699
700 /**
701 * Returns the tools a client may resume an exhausted search from.
702 *
703 * Single source of truth for every `resume_tool` allowlist — the REST
704 * arg sanitizer, the SSE handler, and the `$initial_tool` validation
705 * inside `openstation_ai_run_search()`. `search_comments_by_post` is
706 * deliberately absent: the `continue` payload carries no `post_id`, so
707 * it cannot truly resume — exhausted runs map it to `search_comments`
708 * when building the `continue` object.
709 *
710 * @return string[] Tool names.
711 */
712 function openstation_ai_search_resumable_tools() {
713 return array( 'search_posts', 'search_pages', 'search_comments' );
714 }
715
716 /**
717 * Projects a tool's `parameters` schema onto the provider-supported subset.
718 *
719 * The Abilities API (and plugin-supplied tools) may use the full breadth of JSON
720 * Schema, but the provider's tool-schema validator does not — and it rejects the
721 * whole request, not just the offending tool, so ONE tool with a
722 * legal-but-unsupported schema makes the entire assistant return a 400 before the
723 * model runs. Three shapes that are valid JSON Schema, but rejected here, have
724 * been seen in the wild (see the linked issue):
725 *
726 * 1. `type` as an array, e.g. ['object','null'] — an ability's GET/null
727 * run-path. The provider wants the literal string "object" at the top level.
728 * 2. A top-level `oneOf` / `anyOf` / `allOf`, e.g. "post_id OR slug". Rejected
729 * with "does not support oneOf, allOf, or anyOf at the top level".
730 * 3. `properties` as an empty PHP array, which encodes to JSON as `[]` where an
731 * object schema needs `{}`.
732 *
733 * This reshapes only the copy advertised to the model. The ability itself is
734 * untouched: `WP_Ability::execute()` still validates arguments against the real
735 * schema and `permission_callback` still gates execution, so nothing loses
736 * enforcement — the model is simply told the constraint in prose (the tool
737 * description) instead of in a schema construct the provider can't parse. Only
738 * the TOP level is constrained; a combinator nested inside a property is a real
739 * constraint the provider accepts, so it is left intact.
740 *
741 * @param mixed $schema A tool parameters schema (array), or empty/non-array.
742 * @return array A provider-safe object schema for a tool `parameters` block.
743 */
744 function openstation_ai_normalize_tool_schema( $schema ) {
745 if ( ! is_array( $schema ) || empty( $schema ) ) {
746 return array(
747 'type' => 'object',
748 'properties' => (object) array(),
749 );
750 }
751
752 // Recursively drop the WordPress-only arg-schema keys
753 // (`sanitize_callback` / `validate_callback` / `arg_options`) —
754 // see the helper's docblock for why this must run at every depth.
755 $schema = openstation_ai_strip_wp_schema_keys( $schema );
756
757 // Top-level tool parameters must be the literal "object", never a union.
758 $schema['type'] = 'object';
759
760 // Strip top-level combinators — the provider rejects them outright, and one
761 // such tool 400s the whole request. Nested combinators are left alone.
762 unset( $schema['oneOf'], $schema['allOf'], $schema['anyOf'] );
763
764 // An empty PHP array encodes as `[]`; an object schema's properties need `{}`.
765 // A schema with no `properties` at all (e.g. one whose only content was a
766 // stripped top-level combinator) gets an empty object for the same reason.
767 if ( ! isset( $schema['properties'] ) || array() === $schema['properties'] ) {
768 $schema['properties'] = (object) array();
769 }
770
771 return $schema;
772 }
773
774 /**
775 * Recursively removes the WordPress-only arg-schema keys from a tool schema.
776 *
777 * WordPress arg schemas legally extend JSON Schema with PHP-callable keys —
778 * `sanitize_callback`, `validate_callback`, and (on meta args) `arg_options`.
779 * Abilities registered from REST arg definitions carry them at every property
780 * level, and providers that validate tool schemas strictly reject any unknown
781 * field ("Invalid JSON payload received. Unknown name \"sanitize_callback\""),
782 * 400-ing the whole request over one property.
783 *
784 * The walk is structure-aware, not a blind key sweep: maps under `properties` /
785 * `patternProperties` are keyed by PROPERTY NAME, so a property that happens to
786 * be called `sanitize_callback` is preserved — only its schema value is
787 * cleaned. Recursion covers every position a subschema can occupy: property
788 * values, `items` (single schema or tuple list), array-shaped
789 * `additionalProperties`, and nested `oneOf` / `allOf` / `anyOf` branches
790 * (which are kept — only the TOP level of the tool schema strips combinators).
791 *
792 * @param array $schema A tool parameters (sub)schema.
793 * @return array The schema without WP-only keys, at any depth.
794 */
795 function openstation_ai_strip_wp_schema_keys( array $schema ) {
796 unset( $schema['sanitize_callback'], $schema['validate_callback'], $schema['arg_options'] );
797
798 foreach ( array( 'properties', 'patternProperties' ) as $map_key ) {
799 if ( isset( $schema[ $map_key ] ) && is_array( $schema[ $map_key ] ) ) {
800 foreach ( $schema[ $map_key ] as $name => $sub ) {
801 if ( is_array( $sub ) ) {
802 $schema[ $map_key ][ $name ] = openstation_ai_strip_wp_schema_keys( $sub );
803 }
804 }
805 }
806 }
807
808 if ( isset( $schema['items'] ) && is_array( $schema['items'] ) ) {
809 $items = $schema['items'];
810 $is_list = array_keys( $items ) === range( 0, count( $items ) - 1 );
811 if ( $is_list && array() !== $items ) {
812 // Tuple form — a list of schemas.
813 foreach ( $items as $i => $sub ) {
814 if ( is_array( $sub ) ) {
815 $items[ $i ] = openstation_ai_strip_wp_schema_keys( $sub );
816 }
817 }
818 $schema['items'] = $items;
819 } else {
820 $schema['items'] = openstation_ai_strip_wp_schema_keys( $items );
821 }
822 }
823
824 if ( isset( $schema['additionalProperties'] ) && is_array( $schema['additionalProperties'] ) ) {
825 $schema['additionalProperties'] = openstation_ai_strip_wp_schema_keys( $schema['additionalProperties'] );
826 }
827
828 foreach ( array( 'oneOf', 'allOf', 'anyOf' ) as $combinator ) {
829 if ( isset( $schema[ $combinator ] ) && is_array( $schema[ $combinator ] ) ) {
830 foreach ( $schema[ $combinator ] as $i => $sub ) {
831 if ( is_array( $sub ) ) {
832 $schema[ $combinator ][ $i ] = openstation_ai_strip_wp_schema_keys( $sub );
833 }
834 }
835 }
836 }
837
838 return $schema;
839 }
840
841 /**
842 * Runs the agentic content-search loop.
843 *
844 * The model receives focused tools — search_posts, search_pages,
845 * search_comments, search_comments_by_post — and a system prompt that
846 * guides it to choose the right one based on query semantics and pass the
847 * distilled keywords as `query`. "Someone said congratulations" → it calls
848 * search_comments. "I wrote about paella" → it calls search_posts. No
849 * entity_type routing from the caller is needed for a fresh search.
850 *
851 * For continuation runs ($initial_tool + $start_offset > 0), the system
852 * message primes the agent to resume from the last searched position with
853 * the same keywords.
854 *
855 * @param string $query User's natural-language search.
856 * @param string|null $initial_tool Tool name to resume from, or null for fresh search.
857 * @param int $start_offset Offset to resume from (0 for fresh).
858 * @param callable|null $on_progress Optional progress emitter for SSE ticks.
859 * @param array $extra Extensibility context (command tools, prompt overrides, …).
860 * @return array|WP_Error
861 */
862 function openstation_ai_run_search( $query, $initial_tool = null, $start_offset = 0, $on_progress = null, array $extra = array() ) {
863 /**
864 * Progress emitter — sends a tick to the caller if they provided a
865 * callable; no-op otherwise. Callers use this to render real-time
866 * status to the user via SSE.
867 */
868 $emit = static function ( array $event ) use ( $on_progress ) {
869 if ( is_callable( $on_progress ) ) {
870 $on_progress( $event );
871 }
872 };
873 $start_offset = max( 0, (int) $start_offset );
874 $search_tools = array( 'search_posts', 'search_pages', 'search_comments', 'search_comments_by_post' );
875 $valid_tools = array_merge(
876 $search_tools,
877 array( 'list_admin_pages', 'search_wporg_plugins', 'get_php_error_log' )
878 );
879
880 // -----------------------------------------------------------------------
881 // Extensibility context — command tools from the client, PHP-registered
882 // tools from the server-side registry, system-prompt overrides, and a
883 // per-call request_id for observability fanout.
884 // -----------------------------------------------------------------------
885 $user_id = isset( $extra['user_id'] ) ? (int) $extra['user_id'] : get_current_user_id();
886 $request_id = isset( $extra['request_id'] ) && is_string( $extra['request_id'] ) && '' !== $extra['request_id']
887 ? (string) $extra['request_id']
888 : ( function_exists( 'wp_generate_uuid4' ) ? wp_generate_uuid4() : uniqid( 'openstation_ai_', true ) );
889 $command_tools_raw = isset( $extra['command_tools'] ) && is_array( $extra['command_tools'] ) ? $extra['command_tools'] : array();
890 $system_prompt_text = isset( $extra['system_prompt_text'] ) && is_string( $extra['system_prompt_text'] ) ? $extra['system_prompt_text'] : '';
891 $system_prompt_mode = isset( $extra['system_prompt_mode'] ) && in_array( $extra['system_prompt_mode'], array( 'append', 'replace' ), true )
892 ? (string) $extra['system_prompt_mode']
893 : 'append';
894
895 /**
896 * Fires once per `/ai/search` invocation, after validation and
897 * before any the provider call. First anchor in the observability trio
898 * (`openstation_ai_search_started` / `openstation_ai_tool_called`
899 * / `openstation_ai_search_completed`).
900 *
901 * @param array $context {
902 * @type string $query User query.
903 * @type int $user_id
904 * @type string $request_id UUID correlating the whole run.
905 * }
906 */
907 do_action(
908 'openstation_ai_search_started',
909 array(
910 'query' => $query,
911 'user_id' => $user_id,
912 'request_id' => $request_id,
913 )
914 );
915
916 if ( null !== $initial_tool && ! in_array( $initial_tool, openstation_ai_search_resumable_tools(), true ) ) {
917 $initial_tool = null;
918 }
919
920 // When resuming a previous exhausted run, prime the model with the
921 // starting position so it doesn't waste iterations on already-searched
922 // content.
923 $continuation_note = '';
924 if ( null !== $initial_tool && ( $start_offset > 0 || 'search_posts' !== $initial_tool ) ) {
925 $continuation_note = sprintf(
926 "\n\nNote: This is a continuation of a previous search. Begin with %s using the same search keywords at offset=%d and work forward.",
927 $initial_tool,
928 $start_offset
929 );
930 }
931
932 $instructions = "
933 You are a friendly, conversational assistant embedded in a WordPress site. You help the site owner:
934
935 1. **Find content** they've written (posts, pages, comments) by describing it in natural language.
936 2. **Navigate wp-admin** when they ask where to find something (\"where are the categories?\", \"how do I manage users?\").
937 3. **Recommend plugins** from the official WordPress.org directory when they need extra functionality.
938 4. **Check the site's error log** when they're troubleshooting something.
939 5. **Answer anything else your tools can** — you may have more tools than the ones described below (WordPress and other plugins register their own, e.g. site / user / environment / version info). Your actual tool list is authoritative: whenever a tool can answer the request, call it and summarise the result, even if it isn't in the list below.
940 6. **Chat** — only when no tool fits, answer conversationally.
941
942 Tone: warm, concise, helpful. First person (\"I found this post…\", \"Here's where you'll find that…\"). Not a search engine tone — no \"Match found\" or robot phrasing.
943
944 Tools (your actual tool list may include more than these — use any that fit the request):
945 - search_posts / search_pages / search_comments / search_comments_by_post(post_id, query, offset): keyword content-lookup tools backed by WordPress's native search. Distil the user's description into the essential search keywords and pass them as `query` (e.g. \"that long post about making paella\" → query \"paella\"). Inspect the returned title + excerpt and stop once you find a good match. If has_more is true and nothing matched, call the same tool with next_offset (reuse the same query), or try different keywords. When the query mentions BOTH a post and a comment on that post, call search_posts first to identify the post, THEN search_comments_by_post with the ID. If keyword search returns nothing, broaden or simplify the keywords before giving up.
946 - list_admin_pages: returns the full catalog of wp-admin destinations. Call once per navigation query, then select the 1-3 most relevant entries.
947 - search_wporg_plugins(query): searches the official WordPress.org plugin directory. Use when the user asks for a plugin recommendation (\"a plugin for X\", \"is there a plugin that does Y?\"). Returns up to 10 plugins with ratings, install counts, and admin install URLs. Present the best 3-5 as admin_links with titles like \"Plugin Name · 5M+ installs · 4.8�
948 \" (rating is 0-100, divide by 20 to get stars).
949 - get_php_error_log(lines): reads the tail of the site's PHP error log. Admin-only (the tool itself checks). Use when the user asks \"any errors?\", \"check the logs\", \"what's broken?\", troubleshooting. Each entry has { timestamp, level, message }. Summarise the most important errors (Fatal > Warning > Notice) in your message; don't copy-paste everything.
950
951 Choosing which track:
952 - \"I remember a post/page/comment about X\" → the corresponding search_* tool.
953 - \"where can I find X?\", \"how do I manage Y?\", \"create/add/new …\", \"take me to …\", \"open …\", \"switch/activate …\", or any navigate/do intent → list_admin_pages, then suggest the 1-3 best destinations as admin_links (answer_type \"navigation\"). You suggest the link; the user opens it — never assume it's opened.
954 - \"plugin for X\" / \"recommend a plugin\" → search_wporg_plugins → present as admin_links.
955 - \"any errors?\" / \"check logs\" / troubleshooting → get_php_error_log → summarise in chat.
956 - Any other factual question about the site (its version, PHP/environment, the current user, or anything one of your other tools covers) → call that tool, then summarise its result with answer_type \"chat\".
957 - Greeting, unclear, or chit-chat → answer_type \"chat\" with a brief helpful message (no tools needed).
958
959 Always return one of three answer_type values in the structured output:
960 - \"entity\": you identified a single post/page/comment. Fill entity_id + entity_type. admin_links = null.
961 - \"navigation\": you're recommending admin pages OR plugin install links. Fill admin_links. entity_id + entity_type = null.
962 - \"chat\": you're answering conversationally — including results summarised from any tool (error logs, environment/version info, other plugins' tools), greetings, and \"nothing found\" answers. entity_id + entity_type + admin_links all null.
963
964 The message field is always a friendly sentence or two shown directly to the user. Make it sound like a person, not a log line.
965 ";
966
967 if ( $continuation_note ) {
968 $instructions .= $continuation_note;
969 }
970
971 // -----------------------------------------------------------------------
972 // System-prompt extensibility. All three layers — appendix filter,
973 // client override (append/replace with capability gate), and final
974 // transform — live in `openstation_ai_compose_instructions()` so the
975 // primary run and the follow-up leg stay in lockstep. See the
976 // helper for the order of application; the filter docblocks at its
977 // `apply_filters()` call sites carry the public contract on each
978 // extension point.
979 // -----------------------------------------------------------------------
980 $prompt_context = array(
981 'query' => $query,
982 'user_id' => $user_id,
983 'request_id' => $request_id,
984 );
985
986 $instructions = openstation_ai_compose_instructions(
987 $instructions,
988 $prompt_context,
989 array(
990 'text' => $system_prompt_text,
991 'mode' => $system_prompt_mode,
992 )
993 );
994
995 // -----------------------------------------------------------------------
996 // Tool assembly — built-in search/navigation abilities + client-supplied
997 // command tools.
998 //
999 // Built-in tools are WordPress Abilities API abilities. Each is advertised
1000 // to the model as a function declaration named after the ability (namespace
1001 // stripped), and $ability_by_tool maps that name back to the ability so the
1002 // agent loop can resolve + execute() it (permission + input/output
1003 // validation happen inside execute()).
1004 // -----------------------------------------------------------------------
1005 $ability_by_tool = array();
1006 $builtin_tools = array();
1007
1008 foreach ( openstation_ai_search_ability_names() as $ability_name ) {
1009 $ability = function_exists( 'wp_get_ability' ) ? wp_get_ability( $ability_name ) : null;
1010 if ( ! $ability instanceof WP_Ability ) {
1011 continue;
1012 }
1013
1014 $tool_name = openstation_ai_ability_tool_name( $ability_name );
1015 $ability_by_tool[ $tool_name ] = $ability_name;
1016 $valid_tools[] = $tool_name;
1017
1018 $input_schema = $ability->get_input_schema();
1019 $builtin_tools[] = array(
1020 'type' => 'function',
1021 'name' => $tool_name,
1022 'description' => (string) $ability->get_description(),
1023 'parameters' => ! empty( $input_schema )
1024 ? $input_schema
1025 : array(
1026 'type' => 'object',
1027 'properties' => (object) array(),
1028 ),
1029 );
1030 }
1031
1032 // Command tools — namespaced as `command_<slug>` on the server so
1033 // they can't collide with built-in tool names. Each takes a single
1034 // optional `args` string arg (matches the slash-command contract
1035 // where args are a single string the plugin's `run()` parses).
1036 $command_tools_by_name = array();
1037 $command_defs = array();
1038
1039 foreach ( $command_tools_raw as $cmd ) {
1040 if ( ! is_array( $cmd ) ) {
1041 continue;
1042 }
1043 $slug = isset( $cmd['slug'] ) ? (string) $cmd['slug'] : '';
1044 if ( '' === $slug || ! preg_match( '/^[a-z0-9_\-]+$/', $slug ) ) {
1045 continue;
1046 }
1047 /**
1048 * Per-tool filter on the client-supplied command list. Return
1049 * `false` to drop a command entirely before it reaches the
1050 * model — the right hook for per-role / per-command gating.
1051 *
1052 * @param bool|array $allowed Either the (possibly mutated) command
1053 * tool entry, or `false` to drop it.
1054 * @param string $slug Command slug.
1055 * @param array $context { user_id, request_id }.
1056 */
1057 $allowed = apply_filters(
1058 'openstation_ai_command_allowed',
1059 $cmd,
1060 $slug,
1061 array(
1062 'user_id' => $user_id,
1063 'request_id' => $request_id,
1064 )
1065 );
1066 if ( false === $allowed || ! is_array( $allowed ) ) {
1067 continue;
1068 }
1069 $label = isset( $allowed['label'] ) ? (string) $allowed['label'] : $slug;
1070 $description = isset( $allowed['description'] ) ? (string) $allowed['description'] : '';
1071 $hint = isset( $allowed['hint'] ) ? (string) $allowed['hint'] : '';
1072 $tool_name = 'command_' . $slug;
1073
1074 $command_tools_by_name[ $tool_name ] = array( 'slug' => $slug );
1075 $command_defs[] = array(
1076 'type' => 'function',
1077 'name' => $tool_name,
1078 'description' => trim( $label . ( '' !== $description ? '' . $description : '' ) ),
1079 'parameters' => array(
1080 'type' => 'object',
1081 'properties' => array(
1082 'args' => array(
1083 'type' => 'string',
1084 'description' => '' !== $hint
1085 ? sprintf( 'Arguments for this command. Hint: %s', $hint )
1086 : 'Arguments for this command. Leave empty when the command takes none.',
1087 ),
1088 ),
1089 'required' => array( 'args' ),
1090 'additionalProperties' => false,
1091 ),
1092 );
1093 }
1094
1095 /**
1096 * Transform the command-tool subset before merging with the
1097 * built-in + registered tools. Useful for bulk gating, renaming,
1098 * or injecting synthetic command tools.
1099 *
1100 * @param array $command_defs Command tool definitions.
1101 * @param array $context { user_id, request_id }.
1102 */
1103 $command_defs = (array) apply_filters(
1104 'openstation_ai_command_tools',
1105 $command_defs,
1106 array(
1107 'user_id' => $user_id,
1108 'request_id' => $request_id,
1109 )
1110 );
1111
1112 $tools = array_merge( $builtin_tools, $command_defs );
1113
1114 /**
1115 * Transform the full tool list (built-in abilities + command tools) just
1116 * before it goes to the provider. Fires once per run — changes apply to
1117 * every iteration in the agent loop.
1118 *
1119 * @param array $tools Full the provider tool definitions array.
1120 * @param array $context { user_id, request_id, query }.
1121 */
1122 $tools = (array) apply_filters(
1123 'openstation_ai_tools',
1124 $tools,
1125 array(
1126 'user_id' => $user_id,
1127 'request_id' => $request_id,
1128 'query' => $query,
1129 )
1130 );
1131
1132 // Normalize every tool's schema onto the provider-supported subset, AFTER the
1133 // filter so it covers the complete list the provider will receive — built-in
1134 // abilities, command tools, and anything a plugin injected. One tool with a
1135 // legal-but-unsupported schema otherwise 400s the entire request, not just its
1136 // own tool. Only the model-facing copy is reshaped; abilities still validate
1137 // arguments against their real schema in execute(). Idempotent, so a plugin
1138 // that already normalizes on the filter above is unaffected.
1139 foreach ( $tools as $ti => $tool ) {
1140 if ( is_array( $tool ) && isset( $tool['parameters'] ) ) {
1141 $tools[ $ti ]['parameters'] = openstation_ai_normalize_tool_schema( $tool['parameters'] );
1142 }
1143 }
1144
1145 // Widen the permitted-tools list with the command tools — the agent loop
1146 // rejects any `function_call` whose name isn't in here (built-in ability
1147 // names were added above).
1148 foreach ( $command_defs as $def ) {
1149 if ( isset( $def['name'] ) ) {
1150 $valid_tools[] = (string) $def['name'];
1151 }
1152 }
1153
1154 $answer_schema = openstation_ai_search_answer_schema();
1155
1156 $emit(
1157 array(
1158 'phase' => 'start',
1159 'message' => 'Thinking about your question…',
1160 )
1161 );
1162
1163 // -----------------------------------------------------------------------
1164 // First call — user query as the sole message, instructions as system
1165 // guidance. Generation routes through the WordPress AI Client; the tools
1166 // are advertised as function declarations and dispatched by this loop.
1167 // The full ordered conversation is rebuilt and re-sent each turn.
1168 // -----------------------------------------------------------------------
1169 $messages = array( openstation_ai_user_text_message( $query ) );
1170
1171 $turn = openstation_ai_client_generate( $user_id, $messages, $tools, $answer_schema, $instructions );
1172
1173 if ( is_wp_error( $turn ) ) {
1174 return $turn;
1175 }
1176
1177 $last_tool = $initial_tool ?? 'search_posts';
1178 $last_offset = $start_offset;
1179 $last_has_more = true;
1180 $iterations = 0;
1181
1182 // Accumulate token usage across every turn and remember the last model the
1183 // AI Client resolved, for the `openstation_ai_search_completed` payload.
1184 $total_usage = array(
1185 'prompt' => 0,
1186 'completion' => 0,
1187 'total' => 0,
1188 );
1189 $last_model = null;
1190 $accrue_usage = static function ( $turn ) use ( &$total_usage, &$last_model ) {
1191 if ( ! is_array( $turn ) ) {
1192 return;
1193 }
1194 if ( isset( $turn['usage'] ) && is_array( $turn['usage'] ) ) {
1195 $total_usage['prompt'] += (int) ( $turn['usage']['prompt'] ?? 0 );
1196 $total_usage['completion'] += (int) ( $turn['usage']['completion'] ?? 0 );
1197 $total_usage['total'] += (int) ( $turn['usage']['total'] ?? 0 );
1198 }
1199 if ( isset( $turn['model'] ) && is_array( $turn['model'] ) ) {
1200 $last_model = $turn['model'];
1201 }
1202 };
1203 $accrue_usage( $turn );
1204
1205 // -----------------------------------------------------------------------
1206 // Agentic loop — each iteration either executes tool calls or returns
1207 // the final answer. The full ordered conversation (user query, assistant
1208 // turns, tool results) is accumulated in $messages and re-sent each turn.
1209 // -----------------------------------------------------------------------
1210 for ( $i = 0; $i < OPENSTATION_AI_SEARCH_MAX_ITERATIONS; $i++ ) {
1211 $function_calls = is_array( $turn['function_calls'] ?? null ) ? $turn['function_calls'] : array();
1212
1213 // No tool calls in this response → final answer.
1214 if ( empty( $function_calls ) ) {
1215 $emit(
1216 array(
1217 'phase' => 'composing',
1218 'message' => 'Putting together your answer…',
1219 )
1220 );
1221 $text = $turn['text'] ?? null;
1222 if ( ! is_string( $text ) ) {
1223 // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
1224 error_log( '[WP OpenStation AI] AI Client returned no text in the final turn.' );
1225 return new WP_Error(
1226 'openstation_ai_empty',
1227 'The AI provider returned no text in the final turn.'
1228 );
1229 }
1230
1231 $answer = json_decode( $text, true );
1232 if ( ! is_array( $answer ) ) {
1233 return new WP_Error( 'openstation_ai_result_parse', 'Could not parse structured search answer.' );
1234 }
1235
1236 $answer_type = isset( $answer['answer_type'] ) && in_array( $answer['answer_type'], array( 'entity', 'navigation', 'chat' ), true )
1237 ? (string) $answer['answer_type']
1238 : 'chat';
1239 $message = isset( $answer['message'] ) ? (string) $answer['message'] : '';
1240 $entity_id = ( isset( $answer['entity_id'] ) && is_int( $answer['entity_id'] ) )
1241 ? $answer['entity_id'] : null;
1242 $entity_type = ( isset( $answer['entity_type'] ) && is_string( $answer['entity_type'] ) )
1243 ? $answer['entity_type'] : null;
1244 $admin_links = isset( $answer['admin_links'] ) && is_array( $answer['admin_links'] )
1245 ? $answer['admin_links'] : null;
1246
1247 $entity = null;
1248 if ( 'entity' === $answer_type && $entity_id && $entity_type ) {
1249 $entity = openstation_ai_search_build_entity( $entity_type, $entity_id );
1250 }
1251
1252 $final = array(
1253 'answer_type' => $answer_type,
1254 'message' => $message,
1255 'entity' => $entity,
1256 'admin_links' => $admin_links,
1257 'iterations' => $iterations + 1,
1258 'exhausted' => ! $last_has_more,
1259 'continue' => null,
1260 'request_id' => $request_id,
1261 );
1262
1263 /**
1264 * Final transform hook — fires right before the HTTP
1265 * response is returned. Plugins can rewrite `message`,
1266 * inject `admin_links`, coerce `answer_type`, etc.
1267 *
1268 * @param array $answer Final answer payload.
1269 * @param array $context { query, user_id, request_id }.
1270 */
1271 $final = (array) apply_filters(
1272 'openstation_ai_answer',
1273 $final,
1274 array(
1275 'query' => $query,
1276 'user_id' => $user_id,
1277 'request_id' => $request_id,
1278 )
1279 );
1280
1281 do_action(
1282 'openstation_ai_search_completed',
1283 array(
1284 'query' => $query,
1285 'user_id' => $user_id,
1286 'request_id' => $request_id,
1287 'answer_type' => $final['answer_type'] ?? 'chat',
1288 'iterations' => $final['iterations'] ?? 0,
1289 'usage' => $total_usage,
1290 'model' => $last_model,
1291 )
1292 );
1293
1294 return $final;
1295 }
1296
1297 // -------------------------------------------------------------------
1298 // Command-tool short-circuit.
1299 //
1300 // If the model emitted `command_<slug>`, we return immediately with
1301 // `answer_type: 'tool_call'` — the client owns the command's `run()`
1302 // function (lives in plugin JS) and executes it locally. We do NOT
1303 // send anything else back to the provider this turn — would burn tokens
1304 // for a no-op second response.
1305 // -------------------------------------------------------------------
1306 $command_tool_call = null;
1307 foreach ( $function_calls as $fc ) {
1308 $name = (string) ( $fc['name'] ?? '' );
1309 if ( isset( $command_tools_by_name[ $name ] ) ) {
1310 $raw = json_decode( $fc['arguments'] ?? '{}', true );
1311 $decoded = is_array( $raw ) ? $raw : array();
1312 $command_tool_call = array(
1313 'slug' => $command_tools_by_name[ $name ]['slug'],
1314 'args' => isset( $decoded['args'] ) ? (string) $decoded['args'] : '',
1315 );
1316 break;
1317 }
1318 }
1319 if ( null !== $command_tool_call ) {
1320 do_action(
1321 'openstation_ai_tool_called',
1322 array(
1323 'tool_name' => 'command_' . $command_tool_call['slug'],
1324 'args' => array( 'args' => $command_tool_call['args'] ),
1325 'user_id' => $user_id,
1326 'request_id' => $request_id,
1327 )
1328 );
1329
1330 $final = array(
1331 'answer_type' => 'tool_call',
1332 'message' => '',
1333 'entity' => null,
1334 'admin_links' => null,
1335 'tool' => $command_tool_call,
1336 'iterations' => $iterations + 1,
1337 'exhausted' => false,
1338 'continue' => null,
1339 'request_id' => $request_id,
1340 );
1341
1342 $final = (array) apply_filters(
1343 'openstation_ai_answer',
1344 $final,
1345 array(
1346 'query' => $query,
1347 'user_id' => $user_id,
1348 'request_id' => $request_id,
1349 )
1350 );
1351
1352 do_action(
1353 'openstation_ai_search_completed',
1354 array(
1355 'query' => $query,
1356 'user_id' => $user_id,
1357 'request_id' => $request_id,
1358 'answer_type' => 'tool_call',
1359 'iterations' => $final['iterations'] ?? 0,
1360 'usage' => $total_usage,
1361 'model' => $last_model,
1362 )
1363 );
1364
1365 return $final;
1366 }
1367
1368 // Execute each tool call and collect results as
1369 // `{ call_id, name, response }` — turned into FunctionResponse parts
1370 // for the next turn by openstation_ai_tool_result_message().
1371 $tool_outputs = array();
1372 foreach ( $function_calls as $fc ) {
1373 $tool_name = $fc['name'] ?? '';
1374 $call_id = $fc['call_id'] ?? '';
1375
1376 if ( ! in_array( $tool_name, $valid_tools, true ) ) {
1377 $tool_outputs[] = array(
1378 'call_id' => $call_id,
1379 'name' => $tool_name,
1380 'response' => array( 'error' => "Unknown tool '{$tool_name}'." ),
1381 );
1382 continue;
1383 }
1384
1385 $raw = json_decode( $fc['arguments'] ?? '{}', true );
1386 $args = is_array( $raw ) ? $raw : array();
1387 $offset = max( 0, (int) ( $args['offset'] ?? 0 ) );
1388
1389 $emit(
1390 array(
1391 'phase' => 'tool_call',
1392 'tool' => $tool_name,
1393 'message' => openstation_ai_progress_message( $tool_name ),
1394 )
1395 );
1396
1397 do_action(
1398 'openstation_ai_tool_called',
1399 array(
1400 'tool_name' => $tool_name,
1401 'args' => $args,
1402 'user_id' => $user_id,
1403 'request_id' => $request_id,
1404 )
1405 );
1406
1407 // Resolve + run the ability. execute() runs the permission_callback
1408 // and validates input/output; a denial or bad input comes back as a
1409 // WP_Error, which we surface to the model as a clean tool error
1410 // (never a fatal) and report on the observability channel.
1411 $ability = isset( $ability_by_tool[ $tool_name ] ) ? wp_get_ability( $ability_by_tool[ $tool_name ] ) : null;
1412 if ( $ability instanceof WP_Ability ) {
1413 // Abilities that declare no input schema (e.g. Core's
1414 // get-*-info) reject any non-null input, so pass null when
1415 // there's no schema; otherwise hand over the decoded args.
1416 $input = empty( $ability->get_input_schema() ) ? null : $args;
1417 $result = $ability->execute( $input );
1418 } else {
1419 $result = new WP_Error( 'openstation_ai_unknown_ability', sprintf( 'Ability for tool "%s" is unavailable.', $tool_name ) );
1420 }
1421
1422 if ( is_wp_error( $result ) ) {
1423 do_action(
1424 'openstation_ai_search_error',
1425 array(
1426 'stage' => 'tool_execute',
1427 'tool_name' => $tool_name,
1428 'error' => $result->get_error_code(),
1429 'message' => $result->get_error_message(),
1430 'user_id' => $user_id,
1431 'request_id' => $request_id,
1432 )
1433 );
1434 $batch = array(
1435 'error' => $result->get_error_message(),
1436 'error_code' => $result->get_error_code(),
1437 );
1438 } else {
1439 $batch = is_array( $result ) ? $result : array( 'result' => $result );
1440 }
1441
1442 $last_tool = $tool_name;
1443 $last_offset = $offset;
1444 $last_has_more = (bool) ( $batch['has_more'] ?? false );
1445
1446 /**
1447 * Transform a tool result before it goes back to the model.
1448 * Fires for every ability-dispatched tool (including error
1449 * envelopes from a failed execute()).
1450 *
1451 * @param array $batch Tool result payload.
1452 * @param string $tool_name Tool function name.
1453 * @param array $args Decoded args from the call.
1454 * @param array $context { user_id, request_id }.
1455 */
1456 $batch = (array) apply_filters(
1457 'openstation_ai_tool_result',
1458 $batch,
1459 $tool_name,
1460 $args,
1461 array(
1462 'user_id' => $user_id,
1463 'request_id' => $request_id,
1464 )
1465 );
1466
1467 $tool_outputs[] = array(
1468 'call_id' => $call_id,
1469 'name' => $tool_name,
1470 'response' => $batch,
1471 );
1472 }
1473
1474 ++$iterations;
1475
1476 // Next turn — append the assistant's tool-call turn and our tool
1477 // results to the conversation, then regenerate with the full history.
1478 $messages[] = $turn['message'];
1479 $messages[] = openstation_ai_tool_result_message( $tool_outputs );
1480
1481 $turn = openstation_ai_client_generate( $user_id, $messages, $tools, $answer_schema, $instructions );
1482
1483 if ( is_wp_error( $turn ) ) {
1484 return $turn;
1485 }
1486 $accrue_usage( $turn );
1487 }
1488
1489 // -----------------------------------------------------------------------
1490 // Budget exhausted before a final answer.
1491 // -----------------------------------------------------------------------
1492 $continue = null;
1493 if ( $last_has_more ) {
1494 $next_offset = $last_offset + OPENSTATION_AI_SEARCH_BATCH_SIZE;
1495 // `search_comments_by_post` cannot resume — the continue payload
1496 // carries no post_id — so fall back to plain comment search,
1497 // keeping `tool` inside openstation_ai_search_resumable_tools().
1498 $resume_tool = 'search_comments_by_post' === $last_tool ? 'search_comments' : $last_tool;
1499 $type_label = str_replace( 'search_', '', $resume_tool ) . 's';
1500 $continue = array(
1501 'tool' => $resume_tool,
1502 'entity_type' => rtrim( str_replace( 'search_', '', $resume_tool ), 's' ),
1503 'offset' => $next_offset,
1504 'label' => sprintf( 'Continue searching in %s (from item %d)', $type_label, $next_offset + 1 ),
1505 );
1506 }
1507
1508 $final = array(
1509 'answer_type' => 'chat',
1510 'message' => 'I searched 100 items without finding a clear match. Want me to keep looking further?',
1511 'entity' => null,
1512 'admin_links' => null,
1513 'iterations' => OPENSTATION_AI_SEARCH_MAX_ITERATIONS,
1514 'exhausted' => ! $last_has_more,
1515 'continue' => $continue,
1516 'request_id' => $request_id,
1517 );
1518
1519 $final = (array) apply_filters(
1520 'openstation_ai_answer',
1521 $final,
1522 array(
1523 'query' => $query,
1524 'user_id' => $user_id,
1525 'request_id' => $request_id,
1526 )
1527 );
1528
1529 do_action(
1530 'openstation_ai_search_completed',
1531 array(
1532 'query' => $query,
1533 'user_id' => $user_id,
1534 'request_id' => $request_id,
1535 'answer_type' => 'chat',
1536 'iterations' => OPENSTATION_AI_SEARCH_MAX_ITERATIONS,
1537 'usage' => $total_usage,
1538 'model' => $last_model,
1539 )
1540 );
1541
1542 return $final;
1543 }
1544
1545 /**
1546 * Compose the final system-prompt string for an `/ai/search` call.
1547 *
1548 * One code path used by both the primary run and the follow-up leg —
1549 * keeps the voice consistent across legs and removes a class of drift
1550 * bug where the two paths's prompt-assembly drifts apart.
1551 *
1552 * Applies three layers in order:
1553 * 1. `openstation_ai_system_prompt_appendix` — stacking filter;
1554 * every plugin's return is concatenated.
1555 * 2. Client override — `system_prompt_text` + `system_prompt_mode`.
1556 * `append` always allowed; `replace` gated on
1557 * `openstation_ai_system_prompt_replace_capability`. Non-permitted
1558 * `replace` downgrades to `append` so the caller's text is
1559 * preserved rather than dropped.
1560 * 3. `openstation_ai_system_prompt` — final transform pass.
1561 *
1562 * @internal
1563 *
1564 * @param string $core Built-in instructions for this phase
1565 * (agent loop / follow-up summariser).
1566 * @param array $context { query, user_id, request_id, phase? }.
1567 * @param array $client { text, mode } client override; either field
1568 * empty means no override.
1569 * @return string Composed system prompt.
1570 */
1571 function openstation_ai_compose_instructions( $core, array $context, array $client = array() ) {
1572 $instructions = (string) $core;
1573 $user_id = isset( $context['user_id'] ) ? (int) $context['user_id'] : 0;
1574
1575 $client_text = isset( $client['text'] ) && is_string( $client['text'] ) ? $client['text'] : '';
1576 $client_mode = isset( $client['mode'] ) && in_array( $client['mode'], array( 'append', 'replace' ), true )
1577 ? (string) $client['mode']
1578 : 'append';
1579
1580 $ctx_for_filter = $context;
1581 $ctx_for_filter['client_override'] = '' !== $client_text ? $client_mode : null;
1582
1583 /**
1584 * Short-circuit extension — appended to the built-in instructions
1585 * verbatim. Use this when a plugin just wants to add domain
1586 * context (room list, product catalogue, company jargon) without
1587 * restructuring the core rules. Fires for both the primary
1588 * `/ai/search` run and the follow-up composed-reply leg.
1589 *
1590 * @param string $appendix Accumulated appendix. Default empty.
1591 * @param array $context { query, user_id, request_id, client_override, phase? }.
1592 */
1593 $server_appendix = (string) apply_filters( 'openstation_ai_system_prompt_appendix', '', $ctx_for_filter );
1594 if ( '' !== $server_appendix ) {
1595 $instructions .= "\n\n" . $server_appendix;
1596 }
1597
1598 if ( '' !== $client_text ) {
1599 if ( 'replace' === $client_mode ) {
1600 /**
1601 * Capability required for a client to send
1602 * `system_prompt: { mode: 'replace' }`. Defaults to `manage_options`
1603 * — replacing the whole prompt can effectively hijack the
1604 * assistant, so it's admin-only out of the box.
1605 *
1606 * @param string $capability Default `manage_options`.
1607 * @param array $context
1608 */
1609 $required_cap = (string) apply_filters(
1610 'openstation_ai_system_prompt_replace_capability',
1611 'manage_options',
1612 $ctx_for_filter
1613 );
1614 if ( '' === $required_cap || ( $user_id > 0 && user_can( $user_id, $required_cap ) ) ) {
1615 $instructions = $client_text;
1616 } else {
1617 // Silently downgrade to append — preserves the caller's
1618 // text rather than dropping it when the cap check fails.
1619 $instructions .= "\n\n" . $client_text;
1620 }
1621 } else {
1622 $instructions .= "\n\n" . $client_text;
1623 }
1624 }
1625
1626 /**
1627 * Final transform pass. Fires after the built-in instructions,
1628 * server appendix, and client override have all been composed.
1629 *
1630 * @param string $instructions Composed system prompt.
1631 * @param array $context
1632 */
1633 return (string) apply_filters( 'openstation_ai_system_prompt', $instructions, $ctx_for_filter );
1634 }
1635
1636 /**
1637 * Compose a natural-language reply describing the outcome of a
1638 * client-dispatched command invocation.
1639 *
1640 * Called by the REST endpoint when the client sends `follow_up` —
1641 * the second leg of the opt-in agentic flow triggered by
1642 * `wp.os.ai.ask( q, { tools: 'aiCallable', followUp: true } )`.
1643 *
1644 * Single-turn, no tools, no structured-output schema — the model
1645 * sees the original query + a summary of what happened and writes a
1646 * one/two-sentence reply in the voice of the system prompt. We reuse
1647 * the same system-prompt pipeline as the main search so plugins
1648 * appending instructions via `openstation_ai_system_prompt_appendix`
1649 * see consistent voice across the two legs.
1650 *
1651 * @param string $query Original user query.
1652 * @param array $tool { slug, args } — what ran.
1653 * @param array $outcome Tool result payload. Opaque — JSON-encoded
1654 * into the model's context so it can reason
1655 * about whatever shape the plugin returned.
1656 * @param array $extra Same shape as `openstation_ai_run_search`'s
1657 * `$extra` — carries user_id, request_id,
1658 * system-prompt overrides.
1659 * @return array|WP_Error `{ answer_type: 'chat', message, … }` or error.
1660 */
1661 function openstation_ai_run_followup( $query, array $tool, array $outcome, array $extra = array() ) {
1662 $user_id = isset( $extra['user_id'] ) ? (int) $extra['user_id'] : get_current_user_id();
1663 $request_id = isset( $extra['request_id'] ) && is_string( $extra['request_id'] ) && '' !== $extra['request_id']
1664 ? (string) $extra['request_id']
1665 : ( function_exists( 'wp_generate_uuid4' ) ? wp_generate_uuid4() : uniqid( 'openstation_ai_', true ) );
1666
1667 do_action(
1668 'openstation_ai_search_started',
1669 array(
1670 'query' => $query,
1671 'user_id' => $user_id,
1672 'request_id' => $request_id,
1673 'phase' => 'follow_up',
1674 )
1675 );
1676
1677 // Mirror the main search's system-prompt layering so voice stays
1678 // consistent between the two legs. We build a simpler core-
1679 // instructions block — no tool guidance, since this run has none.
1680 $instructions = '
1681 You are the same friendly WordPress assistant that just dispatched a command on behalf of the user. You now have the result of that command.
1682
1683 Write a SHORT reply (one or two sentences, first person, warm and conversational) describing what happened. Match the voice the site owner set in their system prompt — do not restart small talk, just confirm what you did.
1684
1685 Rules:
1686 - If the outcome looks successful, confirm plainly. Example: "Done — your office light is on now."
1687 - If the outcome looks like an error (has an `error` field, a failure message, or obviously negative content), apologise briefly and paraphrase what went wrong. Do not invent details the outcome did not include.
1688 - Do NOT recommend the user try something else unless the outcome explicitly suggests it.
1689 - Do NOT describe the tool mechanism ("I called command_turn_light") — the user only cares about the real-world effect.
1690 ';
1691
1692 $system_prompt_text = isset( $extra['system_prompt_text'] ) && is_string( $extra['system_prompt_text'] ) ? $extra['system_prompt_text'] : '';
1693 $system_prompt_mode = isset( $extra['system_prompt_mode'] ) && in_array( $extra['system_prompt_mode'], array( 'append', 'replace' ), true )
1694 ? (string) $extra['system_prompt_mode']
1695 : 'append';
1696
1697 $instructions = openstation_ai_compose_instructions(
1698 $instructions,
1699 array(
1700 'query' => $query,
1701 'user_id' => $user_id,
1702 'request_id' => $request_id,
1703 'phase' => 'follow_up',
1704 ),
1705 array(
1706 'text' => $system_prompt_text,
1707 'mode' => $system_prompt_mode,
1708 )
1709 );
1710
1711 $slug = isset( $tool['slug'] ) ? (string) $tool['slug'] : '';
1712 $tool_args = isset( $tool['args'] ) ? (string) $tool['args'] : '';
1713 $outcome_json = wp_json_encode( $outcome );
1714 if ( ! is_string( $outcome_json ) ) {
1715 $outcome_json = '""';
1716 }
1717
1718 // Bound the outcome payload so a malicious or buggy plugin that
1719 // returns a 5MB blob can't inflate the provider token usage without
1720 // bound. 4 KB is enough for a status string, a small result list,
1721 // or a short error envelope — anything bigger gets truncated with
1722 // a marker so the model knows the tail was dropped.
1723 //
1724 // `mb_*` variants so truncation on a multibyte boundary
1725 // (Japanese / emoji / accented UTF-8) can't produce invalid JSON
1726 // that the provider would reject. Falls back to byte-level substr when
1727 // mbstring is unavailable (rare but possible on minimal PHP
1728 // builds).
1729 $max_outcome_len = (int) apply_filters( 'openstation_ai_followup_outcome_max_chars', 4000 );
1730 if ( $max_outcome_len > 0 ) {
1731 $has_mbstring = function_exists( 'mb_strlen' ) && function_exists( 'mb_substr' );
1732 $current_len = $has_mbstring
1733 ? mb_strlen( $outcome_json, 'UTF-8' )
1734 : strlen( $outcome_json );
1735 if ( $current_len > $max_outcome_len ) {
1736 $outcome_json = $has_mbstring
1737 ? mb_substr( $outcome_json, 0, $max_outcome_len, 'UTF-8' )
1738 : substr( $outcome_json, 0, $max_outcome_len );
1739 $outcome_json .= '…[truncated]';
1740 }
1741 }
1742
1743 $user_message = sprintf(
1744 "Original user request: %s\n\nYou invoked the command `%s` with args `%s`. It returned:\n\n```json\n%s\n```\n\nWrite your short confirmation / apology now.",
1745 $query,
1746 $slug,
1747 $tool_args,
1748 $outcome_json
1749 );
1750
1751 do_action(
1752 'openstation_ai_tool_called',
1753 array(
1754 'tool_name' => 'followup_summarise',
1755 'args' => array(
1756 'slug' => $slug,
1757 'tool_args' => $tool_args,
1758 ),
1759 'user_id' => $user_id,
1760 'request_id' => $request_id,
1761 )
1762 );
1763
1764 $turn = openstation_ai_client_generate(
1765 $user_id,
1766 array( openstation_ai_user_text_message( $user_message ) ),
1767 array(), // no tools — we want a plain reply
1768 null, // no JSON schema — free-form text
1769 $instructions
1770 );
1771
1772 if ( is_wp_error( $turn ) ) {
1773 do_action(
1774 'openstation_ai_search_error',
1775 array(
1776 'code' => $turn->get_error_code(),
1777 'message' => $turn->get_error_message(),
1778 'data' => $turn->get_error_data(),
1779 'user_id' => $user_id,
1780 'request_id' => $request_id,
1781 'phase' => 'follow_up',
1782 )
1783 );
1784 return $turn;
1785 }
1786
1787 $text = $turn['text'] ?? null;
1788 $fallback = false;
1789 if ( ! is_string( $text ) || '' === trim( $text ) ) {
1790 // Graceful degrade — if the provider returned nothing usable, fall
1791 // back to a generic confirmation so the caller always has a
1792 // message to show. Better than returning an error and losing
1793 // the fact that the command *did* run. We flag the degrade so
1794 // observability subscribers can distinguish a deliberate
1795 // "Done." from a silently-degraded one.
1796 $text = 'Done.';
1797 $fallback = true;
1798 }
1799
1800 $final = array(
1801 'answer_type' => 'chat',
1802 'message' => trim( $text ),
1803 'entity' => null,
1804 'admin_links' => null,
1805 'iterations' => 1,
1806 'exhausted' => false,
1807 'continue' => null,
1808 'request_id' => $request_id,
1809 'tool' => array(
1810 'slug' => $slug,
1811 'args' => $tool_args,
1812 ),
1813 'fallback' => $fallback,
1814 );
1815
1816 $final = (array) apply_filters(
1817 'openstation_ai_answer',
1818 $final,
1819 array(
1820 'query' => $query,
1821 'user_id' => $user_id,
1822 'request_id' => $request_id,
1823 'phase' => 'follow_up',
1824 )
1825 );
1826
1827 do_action(
1828 'openstation_ai_search_completed',
1829 array(
1830 'query' => $query,
1831 'user_id' => $user_id,
1832 'request_id' => $request_id,
1833 'answer_type' => 'chat',
1834 'iterations' => 1,
1835 'phase' => 'follow_up',
1836 'fallback' => $fallback,
1837 )
1838 );
1839
1840 return $final;
1841 }
1842
1843 // ---------------------------------------------------------------------------
1844 // REST endpoint
1845 // ---------------------------------------------------------------------------
1846
1847 /**
1848 * Registers the AI search REST route.
1849 */
1850 function openstation_register_ai_search_rest_route() {
1851 register_rest_route(
1852 'desktop-mode/v1',
1853 '/ai/search',
1854 array(
1855 'methods' => WP_REST_Server::CREATABLE,
1856 'callback' => 'openstation_rest_ai_search',
1857 'permission_callback' => 'openstation_rest_ai_search_permission',
1858 'args' => array(
1859 'query' => array(
1860 'required' => true,
1861 'type' => 'string',
1862 'sanitize_callback' => 'sanitize_text_field',
1863 'validate_callback' => static function ( $v ) {
1864 return is_string( $v ) && trim( $v ) !== '';
1865 },
1866 ),
1867 // `resume_tool` + `start_offset` are only set when the
1868 // client is continuing a previous search from the `continue`
1869 // object returned by an exhausted run. Fresh searches leave
1870 // both unset — the agent picks tools from query semantics.
1871 'resume_tool' => array(
1872 'required' => false,
1873 'type' => array( 'string', 'null' ),
1874 'default' => null,
1875 'sanitize_callback' => static function ( $v ) {
1876 return in_array( $v, openstation_ai_search_resumable_tools(), true )
1877 ? $v : null;
1878 },
1879 ),
1880 'start_offset' => array(
1881 'required' => false,
1882 'type' => 'integer',
1883 'default' => 0,
1884 'sanitize_callback' => 'absint',
1885 ),
1886 // Client-harvested slash-commands the user's plugins have
1887 // opted in as AI tools. Each entry: { slug, label, description?, hint? }.
1888 // The slug is namespaced server-side as `command_<slug>`
1889 // and any tool_call the model emits with that name short-
1890 // circuits back to the client for local dispatch.
1891 'command_tools' => array(
1892 'required' => false,
1893 'type' => 'array',
1894 'default' => array(),
1895 'items' => array(
1896 'type' => 'object',
1897 'properties' => array(
1898 'slug' => array( 'type' => 'string' ),
1899 'label' => array( 'type' => 'string' ),
1900 'description' => array( 'type' => 'string' ),
1901 'hint' => array( 'type' => 'string' ),
1902 ),
1903 ),
1904 ),
1905 // Free-form system-prompt override.
1906 // mode: 'append' → concatenated onto the built-in prompt (safe for everyone)
1907 // mode: 'replace' → replaces the built-in prompt entirely, gated on
1908 // `openstation_ai_system_prompt_replace_capability`
1909 // (default `manage_options`).
1910 'system_prompt_text' => array(
1911 'required' => false,
1912 'type' => 'string',
1913 'default' => '',
1914 ),
1915 'system_prompt_mode' => array(
1916 'required' => false,
1917 'type' => 'string',
1918 'default' => 'append',
1919 'sanitize_callback' => static function ( $v ) {
1920 return in_array( $v, array( 'append', 'replace' ), true ) ? $v : 'append';
1921 },
1922 ),
1923 // Follow-up leg of the agentic command-dispatch flow.
1924 // When present, the endpoint SKIPS the agent loop entirely
1925 // and runs a single-turn "summarise this outcome" call
1926 // through the provider instead. The client sends this on the
1927 // second leg of `ask( q, { tools: 'aiCallable', followUp: true } )`.
1928 'follow_up' => array(
1929 'required' => false,
1930 'type' => array( 'object', 'null' ),
1931 'default' => null,
1932 ),
1933 ),
1934 )
1935 );
1936 }
1937 add_action( 'rest_api_init', 'openstation_register_ai_search_rest_route' );
1938
1939 /**
1940 * Permission callback.
1941 *
1942 * @return bool|WP_Error
1943 */
1944 function openstation_rest_ai_search_permission() {
1945 if ( ! is_user_logged_in() || ! current_user_can( 'read' ) ) {
1946 return new WP_Error(
1947 'openstation_ai_forbidden',
1948 'You must be logged in to use the AI assistant.',
1949 array( 'status' => 403 )
1950 );
1951 }
1952 if ( ! openstation_ai_is_available() ) {
1953 return new WP_Error(
1954 'openstation_ai_unavailable',
1955 'The AI assistant is unavailable on this site.',
1956 array( 'status' => 503 )
1957 );
1958 }
1959 if ( ! openstation_ai_is_enabled( get_current_user_id() ) ) {
1960 return new WP_Error(
1961 'openstation_ai_disabled',
1962 'The AI assistant is turned off. Enable it in OpenStation Preferences → Features.',
1963 array( 'status' => 403 )
1964 );
1965 }
1966 return true;
1967 }
1968
1969 /**
1970 * POST /desktop-mode/v1/ai/search
1971 *
1972 * @param WP_REST_Request $request
1973 * @return WP_REST_Response|WP_Error
1974 */
1975 function openstation_rest_ai_search( WP_REST_Request $request ) {
1976 $user_id = get_current_user_id();
1977 $query = $request->get_param( 'query' );
1978 $resume_tool = $request->get_param( 'resume_tool' );
1979 $start_offset = $request->get_param( 'start_offset' );
1980
1981 $command_tools = $request->get_param( 'command_tools' );
1982 if ( ! is_array( $command_tools ) ) {
1983 $command_tools = array();
1984 }
1985
1986 $extra = array(
1987 'user_id' => $user_id,
1988 'request_id' => function_exists( 'wp_generate_uuid4' ) ? wp_generate_uuid4() : uniqid( 'openstation_ai_', true ),
1989 'command_tools' => $command_tools,
1990 'system_prompt_text' => (string) $request->get_param( 'system_prompt_text' ),
1991 'system_prompt_mode' => (string) $request->get_param( 'system_prompt_mode' ),
1992 );
1993
1994 /**
1995 * Last-mile filter on the whole `/ai/search` request bundle.
1996 * Plugins get one hook to rewrite query, swap tools, or inject
1997 * metadata before the agent loop starts.
1998 *
1999 * @param array $extra Extended context (mutable).
2000 * @param array $core Core request params { query, resume_tool, start_offset }.
2001 */
2002 $extra = (array) apply_filters(
2003 'openstation_ai_request',
2004 $extra,
2005 array(
2006 'query' => $query,
2007 'resume_tool' => $resume_tool,
2008 'start_offset' => $start_offset,
2009 )
2010 );
2011
2012 // Follow-up leg — skip the agent loop, summarise the tool outcome.
2013 $follow_up = $request->get_param( 'follow_up' );
2014 if ( is_array( $follow_up ) && isset( $follow_up['tool'] ) && is_array( $follow_up['tool'] ) ) {
2015 $tool = $follow_up['tool'];
2016 $outcome = isset( $follow_up['result'] )
2017 ? ( is_array( $follow_up['result'] ) ? $follow_up['result'] : array( 'value' => $follow_up['result'] ) )
2018 : array();
2019 $result = openstation_ai_run_followup( $query, $tool, $outcome, $extra );
2020 } else {
2021 $result = openstation_ai_run_search( $query, $resume_tool, $start_offset, null, $extra );
2022 }
2023
2024 if ( is_wp_error( $result ) ) {
2025 $request_id = isset( $extra['request_id'] ) ? (string) $extra['request_id'] : '';
2026 do_action(
2027 'openstation_ai_search_error',
2028 array(
2029 'code' => $result->get_error_code(),
2030 'message' => $result->get_error_message(),
2031 'data' => $result->get_error_data(),
2032 'user_id' => $user_id,
2033 'request_id' => $request_id,
2034 )
2035 );
2036 return $result;
2037 }
2038
2039 return rest_ensure_response( $result );
2040 }
2041
2042 // ---------------------------------------------------------------------------
2043 // Tool: search_wporg_plugins — uses core's plugins_api() which queries
2044 // the official WordPress.org repository. Results are cached in a
2045 // 10-minute transient per query so repeated asks don't hammer w.org.
2046 // ---------------------------------------------------------------------------
2047
2048 /**
2049 * Search the WordPress.org plugin directory.
2050 *
2051 * @param string $query Search terms.
2052 * @return array Tool result payload ready for the model.
2053 */
2054 function openstation_ai_fetch_wporg_plugins( $query ) {
2055 $query = trim( (string) $query );
2056 if ( '' === $query ) {
2057 return array(
2058 'tool' => 'search_wporg_plugins',
2059 'query' => '',
2060 'results' => array(),
2061 'count' => 0,
2062 'error' => 'No search query provided.',
2063 );
2064 }
2065
2066 // Transient cache to protect the w.org API from repeated queries
2067 // within the same conversation.
2068 $cache_key = 'openstation_ai_plugins_' . md5( strtolower( $query ) );
2069 $cached = get_transient( $cache_key );
2070 if ( is_array( $cached ) ) {
2071 return $cached;
2072 }
2073
2074 if ( ! function_exists( 'plugins_api' ) ) {
2075 require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
2076 }
2077
2078 $api = plugins_api(
2079 'query_plugins',
2080 array(
2081 'search' => $query,
2082 'per_page' => 10,
2083 'fields' => array(
2084 'short_description' => true,
2085 'description' => false,
2086 'sections' => false,
2087 'requires' => true,
2088 'tested' => true,
2089 'rating' => true,
2090 'ratings' => false,
2091 'downloaded' => false,
2092 'downloadlink' => false,
2093 'last_updated' => true,
2094 'added' => false,
2095 'tags' => false,
2096 'compatibility' => false,
2097 'homepage' => true,
2098 'versions' => false,
2099 'donate_link' => false,
2100 'reviews' => false,
2101 'banners' => false,
2102 'icons' => true,
2103 'active_installs' => true,
2104 'group' => false,
2105 'contributors' => false,
2106 ),
2107 )
2108 );
2109
2110 if ( is_wp_error( $api ) ) {
2111 return array(
2112 'tool' => 'search_wporg_plugins',
2113 'query' => $query,
2114 'results' => array(),
2115 'count' => 0,
2116 'error' => $api->get_error_message(),
2117 );
2118 }
2119
2120 $results = array();
2121 $plugins = isset( $api->plugins ) && is_array( $api->plugins ) ? $api->plugins : array();
2122 foreach ( $plugins as $p ) {
2123 // Normalise — plugins_api sometimes returns arrays, sometimes objects.
2124 $p = (array) $p;
2125
2126 $slug = isset( $p['slug'] ) ? (string) $p['slug'] : '';
2127 if ( '' === $slug ) {
2128 continue;
2129 }
2130
2131 $icon = '';
2132 $icons = isset( $p['icons'] ) && is_array( $p['icons'] ) ? $p['icons'] : array();
2133 if ( isset( $icons['1x'] ) ) {
2134 $icon = (string) $icons['1x'];
2135 } elseif ( isset( $icons['default'] ) ) {
2136 $icon = (string) $icons['default'];
2137 } elseif ( isset( $icons['svg'] ) ) {
2138 $icon = (string) $icons['svg'];
2139 }
2140
2141 // Admin URL that opens the plugin-information thickbox. Includes
2142 // both &plugin=slug and the TB_iframe params so clicking it in
2143 // wp-admin behaves like a native "More details" link.
2144 $install_admin_url = admin_url(
2145 'plugin-install.php?tab=plugin-information&plugin=' . rawurlencode( $slug )
2146 . '&TB_iframe=true&width=772&height=745'
2147 );
2148
2149 $results[] = array(
2150 'name' => wp_strip_all_tags( $p['name'] ?? '' ),
2151 'slug' => $slug,
2152 'short_description' => wp_strip_all_tags( $p['short_description'] ?? '' ),
2153 'version' => (string) ( $p['version'] ?? '' ),
2154 'author' => wp_strip_all_tags( $p['author'] ?? '' ),
2155 'rating' => (int) ( $p['rating'] ?? 0 ), // 0-100
2156 'num_ratings' => (int) ( $p['num_ratings'] ?? 0 ),
2157 'active_installs' => (int) ( $p['active_installs'] ?? 0 ),
2158 'last_updated' => (string) ( $p['last_updated'] ?? '' ),
2159 'requires' => (string) ( $p['requires'] ?? '' ),
2160 'tested' => (string) ( $p['tested'] ?? '' ),
2161 'homepage' => esc_url_raw( $p['homepage'] ?? '' ),
2162 'wporg_url' => 'https://wordpress.org/plugins/' . $slug . '/',
2163 'install_admin_url' => $install_admin_url,
2164 'icon' => esc_url_raw( $icon ),
2165 );
2166 }
2167
2168 $payload = array(
2169 'tool' => 'search_wporg_plugins',
2170 'query' => $query,
2171 'results' => $results,
2172 'count' => count( $results ),
2173 );
2174
2175 set_transient( $cache_key, $payload, 10 * MINUTE_IN_SECONDS );
2176
2177 return $payload;
2178 }
2179
2180 // ---------------------------------------------------------------------------
2181 // Tool: get_php_error_log — reads the tail of the site's error log.
2182 // Admin-only; the capability check is performed in the dispatcher
2183 // BEFORE this function runs, so by the time we get here the caller is
2184 // known to hold manage_options.
2185 // ---------------------------------------------------------------------------
2186
2187 /**
2188 * Read and parse the tail of the site's PHP error log.
2189 *
2190 * Tries WP_CONTENT_DIR/debug.log first (populated by WP_DEBUG_LOG), then
2191 * falls back to the PHP ini `error_log` directive. If neither points at
2192 * a readable file the tool reports log_available=false rather than
2193 * throwing.
2194 *
2195 * @param int $lines Number of lines to return (clamped 1-500 by caller).
2196 * @return array
2197 */
2198 function openstation_ai_fetch_error_log( $lines = 50 ) {
2199 $candidates = array();
2200 if ( defined( 'WP_CONTENT_DIR' ) ) {
2201 $candidates[] = WP_CONTENT_DIR . '/debug.log';
2202 }
2203 $ini_log = (string) ini_get( 'error_log' );
2204 if ( '' !== $ini_log && 'syslog' !== $ini_log ) {
2205 $candidates[] = $ini_log;
2206 }
2207
2208 /**
2209 * Filter the list of log-file paths to probe in order. Plugins that
2210 * redirect errors somewhere non-standard can add their path here.
2211 *
2212 * @param string[] $candidates File paths, in probe order.
2213 */
2214 $candidates = (array) apply_filters( 'openstation_ai_error_log_candidates', $candidates );
2215
2216 $log_path = '';
2217 foreach ( $candidates as $path ) {
2218 if ( is_string( $path ) && is_file( $path ) && is_readable( $path ) ) {
2219 $log_path = $path;
2220 break;
2221 }
2222 }
2223
2224 if ( '' === $log_path ) {
2225 return array(
2226 'tool' => 'get_php_error_log',
2227 'log_available' => false,
2228 'message' => 'No readable error log found. Enable WP_DEBUG_LOG in wp-config.php or set php_value error_log.',
2229 'checked_paths' => array_values( $candidates ),
2230 'entries' => array(),
2231 'count' => 0,
2232 );
2233 }
2234
2235 $tail = openstation_ai_tail_file( $log_path, $lines );
2236
2237 $entries = array();
2238 foreach ( $tail as $line ) {
2239 $line = trim( $line );
2240 if ( '' === $line ) {
2241 continue;
2242 }
2243 $entries[] = openstation_ai_parse_log_line( $line );
2244 }
2245
2246 return array(
2247 'tool' => 'get_php_error_log',
2248 'log_available' => true,
2249 'source' => $log_path,
2250 'entries' => $entries,
2251 'count' => count( $entries ),
2252 );
2253 }
2254
2255 /**
2256 * Parse a PHP error_log line into { timestamp, level, message }.
2257 *
2258 * PHP's default format is `[<date>] <prefix>: <message>` where the
2259 * prefix is usually "PHP Fatal error", "PHP Warning", etc. Falls back
2260 * to a raw line when the format doesn't match.
2261 *
2262 * @param string $line
2263 * @return array
2264 */
2265 function openstation_ai_parse_log_line( $line ) {
2266 // Cap individual messages so a runaway stack trace doesn't balloon
2267 // the payload sent to the provider.
2268 $line = mb_substr( $line, 0, 600 );
2269
2270 $entry = array(
2271 'timestamp' => '',
2272 'level' => 'Log',
2273 'message' => $line,
2274 );
2275
2276 // [21-Apr-2026 10:30:22 UTC] PHP Fatal error: Uncaught Error: …
2277 if ( preg_match( '/^\[([^\]]+)\]\s*(.*)$/', $line, $m ) ) {
2278 $entry['timestamp'] = $m[1];
2279 $entry['message'] = $m[2];
2280 }
2281
2282 if ( preg_match( '/^(PHP (?:Fatal error|Parse error|Warning|Notice|Deprecated|Strict|Recoverable fatal error))/i', $entry['message'], $lm ) ) {
2283 $entry['level'] = $lm[1];
2284 $entry['message'] = trim( substr( $entry['message'], strlen( $lm[1] ) ), ":\t " );
2285 }
2286
2287 return $entry;
2288 }
2289
2290 /**
2291 * Return the last $lines of a file. Loads the file via WP_Filesystem
2292 * (the only file-read API allowed for wp.org-hosted plugins) and
2293 * slices off the trailing N+1 entries. Realistic error logs sit
2294 * in the kilobyte range when admins look at them; if a site routinely
2295 * lets logs grow into tens of MB, that's the symptom, not this read.
2296 *
2297 * @param string $path Absolute path to the file.
2298 * @param int $lines
2299 * @return string[] Lines in original order (oldest first).
2300 */
2301 function openstation_ai_tail_file( $path, $lines ) {
2302 if ( ! function_exists( 'WP_Filesystem' ) ) {
2303 require_once ABSPATH . 'wp-admin/includes/file.php';
2304 }
2305 WP_Filesystem();
2306 global $wp_filesystem;
2307 if ( ! $wp_filesystem || ! $wp_filesystem->exists( $path ) ) {
2308 return array();
2309 }
2310
2311 $contents = $wp_filesystem->get_contents( $path );
2312 if ( false === $contents || '' === $contents ) {
2313 return array();
2314 }
2315
2316 $all = preg_split( '/\r?\n/', $contents );
2317 if ( ! is_array( $all ) ) {
2318 return array();
2319 }
2320
2321 return array_slice( $all, -1 * ( $lines + 1 ) );
2322 }
2323
2324 // ---------------------------------------------------------------------------
2325 // Streaming endpoint (Server-Sent Events)
2326 //
2327 // EventSource can't send POST or custom headers, so we ride admin-ajax.php
2328 // which handles cookie-based auth natively. The nonce goes in the URL.
2329 // Output buffering is forcibly disabled and every emit is flushed so the
2330 // browser receives progress ticks in real time.
2331 // ---------------------------------------------------------------------------
2332
2333 /**
2334 * Admin-ajax handler for the streaming search endpoint.
2335 *
2336 * URL: /wp-admin/admin-ajax.php?action=openstation_ai_search_stream
2337 * &nonce=<rest_nonce>
2338 * &query=<user question>
2339 * &resume_tool=<search_posts|…> (optional)
2340 * &start_offset=<int> (optional)
2341 *
2342 * Emits SSE events:
2343 * data: { "event": "progress", "phase": "tool_call", "message": "…" }
2344 * data: { "event": "done", "result": { … } }
2345 * data: { "event": "error", "message": "…" }
2346 */
2347 function openstation_ai_ajax_search_stream() {
2348 $nonce = isset( $_GET['nonce'] ) ? sanitize_text_field( wp_unslash( $_GET['nonce'] ) ) : '';
2349 if ( ! wp_verify_nonce( $nonce, 'wp_rest' ) ) {
2350 status_header( 403 );
2351 exit;
2352 }
2353 if ( ! is_user_logged_in() || ! current_user_can( 'read' ) ) {
2354 status_header( 403 );
2355 exit;
2356 }
2357 $user_id = get_current_user_id();
2358 if ( ! openstation_ai_is_available() ) {
2359 status_header( 503 );
2360 exit;
2361 }
2362 if ( ! openstation_ai_is_enabled( $user_id ) ) {
2363 status_header( 403 );
2364 exit;
2365 }
2366
2367 $query = isset( $_GET['query'] ) ? sanitize_text_field( wp_unslash( $_GET['query'] ) ) : ''; // phpcs:ignore WordPress.Security
2368 if ( trim( $query ) === '' ) {
2369 status_header( 400 );
2370 exit;
2371 }
2372
2373 $resume_tool = isset( $_GET['resume_tool'] ) ? sanitize_key( wp_unslash( $_GET['resume_tool'] ) ) : null; // phpcs:ignore WordPress.Security
2374 $start_offset = isset( $_GET['start_offset'] ) ? absint( $_GET['start_offset'] ) : 0; // phpcs:ignore WordPress.Security
2375 if ( null !== $resume_tool && ! in_array( $resume_tool, openstation_ai_search_resumable_tools(), true ) ) {
2376 $resume_tool = null;
2377 }
2378
2379 // SSE headers — tell nginx to stop buffering, tell the browser this is
2380 // a persistent event stream.
2381 header( 'Content-Type: text/event-stream; charset=utf-8' );
2382 header( 'Cache-Control: no-cache, no-store, must-revalidate' );
2383 header( 'X-Accel-Buffering: no' );
2384 header( 'Connection: keep-alive' );
2385
2386 // Let other requests from this user proceed (release session lock).
2387 if ( session_status() === PHP_SESSION_ACTIVE ) {
2388 session_write_close();
2389 }
2390
2391 // Kill any output buffers PHP set up, otherwise nothing flushes until
2392 // the request ends — which defeats the whole point of streaming.
2393 while ( ob_get_level() > 0 ) {
2394 @ob_end_flush(); // phpcs:ignore
2395 }
2396 @ini_set( 'output_buffering', 'off' ); // phpcs:ignore
2397 @ini_set( 'zlib.output_compression', 'off' ); // phpcs:ignore
2398 @set_time_limit( 120 ); // phpcs:ignore
2399
2400 $emit = static function ( array $payload ) {
2401 echo 'data: ' . wp_json_encode( $payload ) . "\n\n";
2402 @ob_flush(); // phpcs:ignore
2403 flush();
2404 };
2405
2406 // Initial tick so the EventSource opens immediately and the JS can
2407 // start showing "Thinking…" without waiting for the first model call.
2408 $emit( array( 'event' => 'open' ) );
2409
2410 $result = openstation_ai_run_search(
2411 $query,
2412 $resume_tool,
2413 $start_offset,
2414 function ( $progress ) use ( $emit ) {
2415 $emit( array_merge( array( 'event' => 'progress' ), $progress ) );
2416 }
2417 );
2418
2419 if ( is_wp_error( $result ) ) {
2420 $emit(
2421 array(
2422 'event' => 'error',
2423 'message' => $result->get_error_message(),
2424 'code' => $result->get_error_code(),
2425 )
2426 );
2427 } else {
2428 $emit(
2429 array(
2430 'event' => 'done',
2431 'result' => $result,
2432 )
2433 );
2434 }
2435
2436 exit;
2437 }
2438 add_action( 'wp_ajax_openstation_ai_search_stream', 'openstation_ai_ajax_search_stream' );
2439