PluginProbe
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin / 1.1.7
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin v1.1.7
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.1.7, at includes/ai-copilot/search.php

2,312 lines 86.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', 'desktop-mode' ),
64 'url' => admin_url( 'index.php' ),
65 'icon' => 'dashicons-dashboard',
66 'description' => __( 'The main admin dashboard: activity, drafts, site overview.', 'desktop-mode' ),
67 ),
68 array(
69 'title' => __( 'All Posts', 'desktop-mode' ),
70 'url' => admin_url( 'edit.php' ),
71 'icon' => 'dashicons-admin-post',
72 'description' => __( 'List, edit, bulk-manage blog posts.', 'desktop-mode' ),
73 ),
74 array(
75 'title' => __( 'Add New Post', 'desktop-mode' ),
76 'url' => admin_url( 'post-new.php' ),
77 'icon' => 'dashicons-plus',
78 'description' => __( 'Create a new blog post.', 'desktop-mode' ),
79 ),
80 array(
81 'title' => __( 'Categories', 'desktop-mode' ),
82 'url' => admin_url( 'edit-tags.php?taxonomy=category' ),
83 'icon' => 'dashicons-category',
84 'description' => __( 'Manage post categories: add, rename, merge.', 'desktop-mode' ),
85 ),
86 array(
87 'title' => __( 'Tags', 'desktop-mode' ),
88 'url' => admin_url( 'edit-tags.php?taxonomy=post_tag' ),
89 'icon' => 'dashicons-tag',
90 'description' => __( 'Manage post tags.', 'desktop-mode' ),
91 ),
92 array(
93 'title' => __( 'All Pages', 'desktop-mode' ),
94 'url' => admin_url( 'edit.php?post_type=page' ),
95 'icon' => 'dashicons-admin-page',
96 'description' => __( 'List and edit static pages (About, Contact, etc.).', 'desktop-mode' ),
97 ),
98 array(
99 'title' => __( 'Add New Page', 'desktop-mode' ),
100 'url' => admin_url( 'post-new.php?post_type=page' ),
101 'icon' => 'dashicons-plus',
102 'description' => __( 'Create a new page.', 'desktop-mode' ),
103 ),
104 array(
105 'title' => __( 'Media Library', 'desktop-mode' ),
106 'url' => admin_url( 'upload.php' ),
107 'icon' => 'dashicons-admin-media',
108 'description' => __( 'Browse, upload, and manage images, files, videos.', 'desktop-mode' ),
109 ),
110 array(
111 'title' => __( 'Comments', 'desktop-mode' ),
112 'url' => admin_url( 'edit-comments.php' ),
113 'icon' => 'dashicons-admin-comments',
114 'description' => __( 'Moderate and reply to comments on posts and pages.', 'desktop-mode' ),
115 ),
116 array(
117 'title' => __( 'Themes', 'desktop-mode' ),
118 'url' => admin_url( 'themes.php' ),
119 'icon' => 'dashicons-admin-appearance',
120 'description' => __( 'Change, install, or customize the active theme.', 'desktop-mode' ),
121 ),
122 array(
123 'title' => __( 'Customize', 'desktop-mode' ),
124 'url' => admin_url( 'customize.php' ),
125 'icon' => 'dashicons-admin-customizer',
126 'description' => __( 'Live-preview theme customisation: colors, fonts, layout.', 'desktop-mode' ),
127 ),
128 array(
129 'title' => __( 'Widgets', 'desktop-mode' ),
130 'url' => admin_url( 'widgets.php' ),
131 'icon' => 'dashicons-screenoptions',
132 'description' => __( 'Manage sidebar and footer widgets.', 'desktop-mode' ),
133 ),
134 array(
135 'title' => __( 'Menus', 'desktop-mode' ),
136 'url' => admin_url( 'nav-menus.php' ),
137 'icon' => 'dashicons-menu',
138 'description' => __( 'Create and edit navigation menus.', 'desktop-mode' ),
139 ),
140 array(
141 'title' => __( 'Plugins', 'desktop-mode' ),
142 'url' => admin_url( 'plugins.php' ),
143 'icon' => 'dashicons-admin-plugins',
144 'description' => __( 'Activate, deactivate, update or delete plugins.', 'desktop-mode' ),
145 ),
146 array(
147 'title' => __( 'Add New Plugin', 'desktop-mode' ),
148 'url' => admin_url( 'plugin-install.php' ),
149 'icon' => 'dashicons-plus',
150 'description' => __( 'Search and install new plugins from the directory.', 'desktop-mode' ),
151 ),
152 array(
153 'title' => __( 'Users', 'desktop-mode' ),
154 'url' => admin_url( 'users.php' ),
155 'icon' => 'dashicons-admin-users',
156 'description' => __( 'Manage user accounts and roles.', 'desktop-mode' ),
157 ),
158 array(
159 'title' => __( 'Add New User', 'desktop-mode' ),
160 'url' => admin_url( 'user-new.php' ),
161 'icon' => 'dashicons-plus',
162 'description' => __( 'Create a new user account.', 'desktop-mode' ),
163 ),
164 array(
165 'title' => __( 'Your Profile', 'desktop-mode' ),
166 'url' => admin_url( 'profile.php' ),
167 'icon' => 'dashicons-id',
168 'description' => __( 'Edit your own profile, password, admin colour scheme.', 'desktop-mode' ),
169 ),
170 array(
171 'title' => __( 'General Settings', 'desktop-mode' ),
172 'url' => admin_url( 'options-general.php' ),
173 'icon' => 'dashicons-admin-settings',
174 'description' => __( 'Site title, tagline, URL, timezone, language.', 'desktop-mode' ),
175 ),
176 array(
177 'title' => __( 'Writing Settings', 'desktop-mode' ),
178 'url' => admin_url( 'options-writing.php' ),
179 'icon' => 'dashicons-edit',
180 'description' => __( 'Default post category, post format, remote publishing.', 'desktop-mode' ),
181 ),
182 array(
183 'title' => __( 'Reading Settings', 'desktop-mode' ),
184 'url' => admin_url( 'options-reading.php' ),
185 'icon' => 'dashicons-book',
186 'description' => __( 'Homepage, blog posts per page, search-engine visibility.', 'desktop-mode' ),
187 ),
188 array(
189 'title' => __( 'Discussion Settings', 'desktop-mode' ),
190 'url' => admin_url( 'options-discussion.php' ),
191 'icon' => 'dashicons-format-chat',
192 'description' => __( 'Comment moderation, avatars, email notifications.', 'desktop-mode' ),
193 ),
194 array(
195 'title' => __( 'Media Settings', 'desktop-mode' ),
196 'url' => admin_url( 'options-media.php' ),
197 'icon' => 'dashicons-format-image',
198 'description' => __( 'Image size settings for thumbnail / medium / large.', 'desktop-mode' ),
199 ),
200 array(
201 'title' => __( 'Permalinks', 'desktop-mode' ),
202 'url' => admin_url( 'options-permalink.php' ),
203 'icon' => 'dashicons-admin-links',
204 'description' => __( 'URL structure for posts, pages, categories, tags.', 'desktop-mode' ),
205 ),
206 array(
207 'title' => __( 'Privacy', 'desktop-mode' ),
208 'url' => admin_url( 'options-privacy.php' ),
209 'icon' => 'dashicons-privacy',
210 'description' => __( 'Privacy policy page selection and preview.', 'desktop-mode' ),
211 ),
212 array(
213 'title' => __( 'Tools', 'desktop-mode' ),
214 'url' => admin_url( 'tools.php' ),
215 'icon' => 'dashicons-admin-tools',
216 'description' => __( 'Built-in site tools.', 'desktop-mode' ),
217 ),
218 array(
219 'title' => __( 'Import', 'desktop-mode' ),
220 'url' => admin_url( 'import.php' ),
221 'icon' => 'dashicons-download',
222 'description' => __( 'Import content from other platforms (WP, Tumblr, RSS, etc.).', 'desktop-mode' ),
223 ),
224 array(
225 'title' => __( 'Export', 'desktop-mode' ),
226 'url' => admin_url( 'export.php' ),
227 'icon' => 'dashicons-upload',
228 'description' => __( 'Export all site content as XML.', 'desktop-mode' ),
229 ),
230 array(
231 'title' => __( 'Site Health', 'desktop-mode' ),
232 'url' => admin_url( 'site-health.php' ),
233 'icon' => 'dashicons-heart',
234 'description' => __( 'Performance and security recommendations for the site.', 'desktop-mode' ),
235 ),
236 array(
237 'title' => __( 'Updates', 'desktop-mode' ),
238 'url' => admin_url( 'update-core.php' ),
239 'icon' => 'dashicons-update',
240 'description' => __( 'WordPress, theme, and plugin updates.', 'desktop-mode' ),
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 the label for the "keep looking" button on an exhausted search.
674 *
675 * One full sentence per resumable tool: a noun interpolated into a shared
676 * template cannot be translated.
677 *
678 * @param string $resume_tool Tool the client would resume from.
679 * @param int $from_item 1-based index of the next item to search.
680 * @return string
681 */
682 function openstation_ai_continue_label( $resume_tool, $from_item ) {
683 switch ( $resume_tool ) {
684 case 'search_pages':
685 /* translators: %d: 1-based index of the next page to search. */
686 return sprintf( __( 'Continue searching in pages (from item %d)', 'desktop-mode' ), $from_item );
687 case 'search_comments':
688 /* translators: %d: 1-based index of the next comment to search. */
689 return sprintf( __( 'Continue searching in comments (from item %d)', 'desktop-mode' ), $from_item );
690 default:
691 /* translators: %d: 1-based index of the next post to search. */
692 return sprintf( __( 'Continue searching in posts (from item %d)', 'desktop-mode' ), $from_item );
693 }
694 }
695
696 /**
697 * Returns the tools a client may resume an exhausted search from.
698 *
699 * Single source of truth for every `resume_tool` allowlist: the REST
700 * arg sanitizer and the `$initial_tool` validation inside
701 * `openstation_ai_run_search()`. `search_comments_by_post` is
702 * deliberately absent: the `continue` payload carries no `post_id`, so
703 * it cannot truly resume — exhausted runs map it to `search_comments`
704 * when building the `continue` object.
705 *
706 * @return string[] Tool names.
707 */
708 function openstation_ai_search_resumable_tools() {
709 return array( 'search_posts', 'search_pages', 'search_comments' );
710 }
711
712 /**
713 * Projects a tool's `parameters` schema onto the provider-supported subset.
714 *
715 * The Abilities API (and plugin-supplied tools) may use the full breadth of JSON
716 * Schema, but the provider's tool-schema validator does not — and it rejects the
717 * whole request, not just the offending tool, so ONE tool with a
718 * legal-but-unsupported schema makes the entire assistant return a 400 before the
719 * model runs. Three shapes that are valid JSON Schema, but rejected here, have
720 * been seen in the wild (see the linked issue):
721 *
722 * 1. `type` as an array, e.g. ['object','null'] — an ability's GET/null
723 * run-path. The provider wants the literal string "object" at the top level.
724 * 2. A top-level `oneOf` / `anyOf` / `allOf`, e.g. "post_id OR slug". Rejected
725 * with "does not support oneOf, allOf, or anyOf at the top level".
726 * 3. `properties` as an empty PHP array, which encodes to JSON as `[]` where an
727 * object schema needs `{}`.
728 *
729 * This reshapes only the copy advertised to the model. The ability itself is
730 * untouched: `WP_Ability::execute()` still validates arguments against the real
731 * schema and `permission_callback` still gates execution, so nothing loses
732 * enforcement — the model is simply told the constraint in prose (the tool
733 * description) instead of in a schema construct the provider can't parse. Only
734 * the TOP level is constrained; a combinator nested inside a property is a real
735 * constraint the provider accepts, so it is left intact.
736 *
737 * @param mixed $schema A tool parameters schema (array), or empty/non-array.
738 * @return array A provider-safe object schema for a tool `parameters` block.
739 */
740 function openstation_ai_normalize_tool_schema( $schema ) {
741 if ( ! is_array( $schema ) || empty( $schema ) ) {
742 return array(
743 'type' => 'object',
744 'properties' => (object) array(),
745 );
746 }
747
748 // Recursively drop the WordPress-only arg-schema keys
749 // (`sanitize_callback` / `validate_callback` / `arg_options`) —
750 // see the helper's docblock for why this must run at every depth.
751 $schema = openstation_ai_strip_wp_schema_keys( $schema );
752
753 // Top-level tool parameters must be the literal "object", never a union.
754 $schema['type'] = 'object';
755
756 // Strip top-level combinators — the provider rejects them outright, and one
757 // such tool 400s the whole request. Nested combinators are left alone.
758 unset( $schema['oneOf'], $schema['allOf'], $schema['anyOf'] );
759
760 // An empty PHP array encodes as `[]`; an object schema's properties need `{}`.
761 // A schema with no `properties` at all (e.g. one whose only content was a
762 // stripped top-level combinator) gets an empty object for the same reason.
763 if ( ! isset( $schema['properties'] ) || array() === $schema['properties'] ) {
764 $schema['properties'] = (object) array();
765 }
766
767 return $schema;
768 }
769
770 /**
771 * Recursively removes the WordPress-only arg-schema keys from a tool schema.
772 *
773 * WordPress arg schemas legally extend JSON Schema with PHP-callable keys —
774 * `sanitize_callback`, `validate_callback`, and (on meta args) `arg_options`.
775 * Abilities registered from REST arg definitions carry them at every property
776 * level, and providers that validate tool schemas strictly reject any unknown
777 * field ("Invalid JSON payload received. Unknown name \"sanitize_callback\""),
778 * 400-ing the whole request over one property.
779 *
780 * The walk is structure-aware, not a blind key sweep: maps under `properties` /
781 * `patternProperties` are keyed by PROPERTY NAME, so a property that happens to
782 * be called `sanitize_callback` is preserved — only its schema value is
783 * cleaned. Recursion covers every position a subschema can occupy: property
784 * values, `items` (single schema or tuple list), array-shaped
785 * `additionalProperties`, and nested `oneOf` / `allOf` / `anyOf` branches
786 * (which are kept — only the TOP level of the tool schema strips combinators).
787 *
788 * @param array $schema A tool parameters (sub)schema.
789 * @return array The schema without WP-only keys, at any depth.
790 */
791 function openstation_ai_strip_wp_schema_keys( array $schema ) {
792 unset( $schema['sanitize_callback'], $schema['validate_callback'], $schema['arg_options'] );
793
794 foreach ( array( 'properties', 'patternProperties' ) as $map_key ) {
795 if ( isset( $schema[ $map_key ] ) && is_array( $schema[ $map_key ] ) ) {
796 foreach ( $schema[ $map_key ] as $name => $sub ) {
797 if ( is_array( $sub ) ) {
798 $schema[ $map_key ][ $name ] = openstation_ai_strip_wp_schema_keys( $sub );
799 }
800 }
801 }
802 }
803
804 if ( isset( $schema['items'] ) && is_array( $schema['items'] ) ) {
805 $items = $schema['items'];
806 $is_list = array_keys( $items ) === range( 0, count( $items ) - 1 );
807 if ( $is_list && array() !== $items ) {
808 // Tuple form — a list of schemas.
809 foreach ( $items as $i => $sub ) {
810 if ( is_array( $sub ) ) {
811 $items[ $i ] = openstation_ai_strip_wp_schema_keys( $sub );
812 }
813 }
814 $schema['items'] = $items;
815 } else {
816 $schema['items'] = openstation_ai_strip_wp_schema_keys( $items );
817 }
818 }
819
820 if ( isset( $schema['additionalProperties'] ) && is_array( $schema['additionalProperties'] ) ) {
821 $schema['additionalProperties'] = openstation_ai_strip_wp_schema_keys( $schema['additionalProperties'] );
822 }
823
824 foreach ( array( 'oneOf', 'allOf', 'anyOf' ) as $combinator ) {
825 if ( isset( $schema[ $combinator ] ) && is_array( $schema[ $combinator ] ) ) {
826 foreach ( $schema[ $combinator ] as $i => $sub ) {
827 if ( is_array( $sub ) ) {
828 $schema[ $combinator ][ $i ] = openstation_ai_strip_wp_schema_keys( $sub );
829 }
830 }
831 }
832 }
833
834 return $schema;
835 }
836
837 /**
838 * Runs the agentic content-search loop.
839 *
840 * The model receives focused tools — search_posts, search_pages,
841 * search_comments, search_comments_by_post — and a system prompt that
842 * guides it to choose the right one based on query semantics and pass the
843 * distilled keywords as `query`. "Someone said congratulations" → it calls
844 * search_comments. "I wrote about paella" → it calls search_posts. No
845 * entity_type routing from the caller is needed for a fresh search.
846 *
847 * For continuation runs ($initial_tool + $start_offset > 0), the system
848 * message primes the agent to resume from the last searched position with
849 * the same keywords.
850 *
851 * @param string $query User's natural-language search.
852 * @param string|null $initial_tool Tool name to resume from, or null for fresh search.
853 * @param int $start_offset Offset to resume from (0 for fresh).
854 * @param array $extra Extensibility context (command tools, prompt overrides, …).
855 * @return array|WP_Error
856 */
857 function openstation_ai_run_search( $query, $initial_tool = null, $start_offset = 0, array $extra = array() ) {
858 $start_offset = max( 0, (int) $start_offset );
859 $search_tools = array( 'search_posts', 'search_pages', 'search_comments', 'search_comments_by_post' );
860 $valid_tools = array_merge(
861 $search_tools,
862 array( 'list_admin_pages', 'search_wporg_plugins', 'get_php_error_log' )
863 );
864
865 // -----------------------------------------------------------------------
866 // Extensibility context — command tools from the client, PHP-registered
867 // tools from the server-side registry, system-prompt overrides, and a
868 // per-call request_id for observability fanout.
869 // -----------------------------------------------------------------------
870 $user_id = isset( $extra['user_id'] ) ? (int) $extra['user_id'] : get_current_user_id();
871 $request_id = isset( $extra['request_id'] ) && is_string( $extra['request_id'] ) && '' !== $extra['request_id']
872 ? (string) $extra['request_id']
873 : ( function_exists( 'wp_generate_uuid4' ) ? wp_generate_uuid4() : uniqid( 'openstation_ai_', true ) );
874 $command_tools_raw = isset( $extra['command_tools'] ) && is_array( $extra['command_tools'] ) ? $extra['command_tools'] : array();
875 $system_prompt_text = isset( $extra['system_prompt_text'] ) && is_string( $extra['system_prompt_text'] ) ? $extra['system_prompt_text'] : '';
876 $system_prompt_mode = isset( $extra['system_prompt_mode'] ) && in_array( $extra['system_prompt_mode'], array( 'append', 'replace' ), true )
877 ? (string) $extra['system_prompt_mode']
878 : 'append';
879
880 /**
881 * Fires once per `/ai/search` invocation, after validation and
882 * before any the provider call. First anchor in the observability trio
883 * (`openstation_ai_search_started` / `openstation_ai_tool_called`
884 * / `openstation_ai_search_completed`).
885 *
886 * @param array $context {
887 * @type string $query User query.
888 * @type int $user_id
889 * @type string $request_id UUID correlating the whole run.
890 * }
891 */
892 do_action(
893 'openstation_ai_search_started',
894 array(
895 'query' => $query,
896 'user_id' => $user_id,
897 'request_id' => $request_id,
898 )
899 );
900
901 if ( null !== $initial_tool && ! in_array( $initial_tool, openstation_ai_search_resumable_tools(), true ) ) {
902 $initial_tool = null;
903 }
904
905 // When resuming a previous exhausted run, prime the model with the
906 // starting position so it doesn't waste iterations on already-searched
907 // content.
908 $continuation_note = '';
909 if ( null !== $initial_tool && ( $start_offset > 0 || 'search_posts' !== $initial_tool ) ) {
910 $continuation_note = sprintf(
911 "\n\nNote: This is a continuation of a previous search. Begin with %s using the same search keywords at offset=%d and work forward.",
912 $initial_tool,
913 $start_offset
914 );
915 }
916
917 $instructions = "
918 You are a friendly, conversational assistant embedded in a WordPress site. You help the site owner:
919
920 1. **Find content** they've written (posts, pages, comments) by describing it in natural language.
921 2. **Navigate wp-admin** when they ask where to find something (\"where are the categories?\", \"how do I manage users?\").
922 3. **Recommend plugins** from the official WordPress.org directory when they need extra functionality.
923 4. **Check the site's error log** when they're troubleshooting something.
924 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.
925 6. **Chat** — only when no tool fits, answer conversationally.
926
927 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.
928
929 Tools (your actual tool list may include more than these — use any that fit the request):
930 - 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.
931 - list_admin_pages: returns the full catalog of wp-admin destinations. Call once per navigation query, then select the 1-3 most relevant entries.
932 - 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�
933 \" (rating is 0-100, divide by 20 to get stars).
934 - 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.
935
936 Choosing which track:
937 - \"I remember a post/page/comment about X\" → the corresponding search_* tool.
938 - \"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.
939 - \"plugin for X\" / \"recommend a plugin\" → search_wporg_plugins → present as admin_links.
940 - \"any errors?\" / \"check logs\" / troubleshooting → get_php_error_log → summarise in chat.
941 - 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\".
942 - Greeting, unclear, or chit-chat → answer_type \"chat\" with a brief helpful message (no tools needed).
943
944 Always return one of three answer_type values in the structured output:
945 - \"entity\": you identified a single post/page/comment. Fill entity_id + entity_type. admin_links = null.
946 - \"navigation\": you're recommending admin pages OR plugin install links. Fill admin_links. entity_id + entity_type = null.
947 - \"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.
948
949 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.
950 ";
951
952 if ( $continuation_note ) {
953 $instructions .= $continuation_note;
954 }
955
956 // -----------------------------------------------------------------------
957 // System-prompt extensibility. All three layers — appendix filter,
958 // client override (append/replace with capability gate), and final
959 // transform — live in `openstation_ai_compose_instructions()` so the
960 // primary run and the follow-up leg stay in lockstep. See the
961 // helper for the order of application; the filter docblocks at its
962 // `apply_filters()` call sites carry the public contract on each
963 // extension point.
964 // -----------------------------------------------------------------------
965 $prompt_context = array(
966 'query' => $query,
967 'user_id' => $user_id,
968 'request_id' => $request_id,
969 );
970
971 $instructions = openstation_ai_compose_instructions(
972 $instructions,
973 $prompt_context,
974 array(
975 'text' => $system_prompt_text,
976 'mode' => $system_prompt_mode,
977 )
978 );
979
980 // -----------------------------------------------------------------------
981 // Tool assembly — built-in search/navigation abilities + client-supplied
982 // command tools.
983 //
984 // Built-in tools are WordPress Abilities API abilities. Each is advertised
985 // to the model as a function declaration named after the ability (namespace
986 // stripped), and $ability_by_tool maps that name back to the ability so the
987 // agent loop can resolve + execute() it (permission + input/output
988 // validation happen inside execute()).
989 // -----------------------------------------------------------------------
990 $ability_by_tool = array();
991 $builtin_tools = array();
992
993 foreach ( openstation_ai_search_ability_names() as $ability_name ) {
994 $ability = function_exists( 'wp_get_ability' ) ? wp_get_ability( $ability_name ) : null;
995 if ( ! $ability instanceof WP_Ability ) {
996 continue;
997 }
998
999 $tool_name = openstation_ai_ability_tool_name( $ability_name );
1000 $ability_by_tool[ $tool_name ] = $ability_name;
1001 $valid_tools[] = $tool_name;
1002
1003 $input_schema = $ability->get_input_schema();
1004 $builtin_tools[] = array(
1005 'type' => 'function',
1006 'name' => $tool_name,
1007 'description' => (string) $ability->get_description(),
1008 'parameters' => ! empty( $input_schema )
1009 ? $input_schema
1010 : array(
1011 'type' => 'object',
1012 'properties' => (object) array(),
1013 ),
1014 );
1015 }
1016
1017 // Command tools — namespaced as `command_<slug>` on the server so
1018 // they can't collide with built-in tool names. Each takes a single
1019 // optional `args` string arg (matches the slash-command contract
1020 // where args are a single string the plugin's `run()` parses).
1021 $command_tools_by_name = array();
1022 $command_defs = array();
1023
1024 foreach ( $command_tools_raw as $cmd ) {
1025 if ( ! is_array( $cmd ) ) {
1026 continue;
1027 }
1028 $slug = isset( $cmd['slug'] ) ? (string) $cmd['slug'] : '';
1029 if ( '' === $slug || ! preg_match( '/^[a-z0-9_\-]+$/', $slug ) ) {
1030 continue;
1031 }
1032 /**
1033 * Per-tool filter on the client-supplied command list. Return
1034 * `false` to drop a command entirely before it reaches the
1035 * model — the right hook for per-role / per-command gating.
1036 *
1037 * @param bool|array $allowed Either the (possibly mutated) command
1038 * tool entry, or `false` to drop it.
1039 * @param string $slug Command slug.
1040 * @param array $context { user_id, request_id }.
1041 */
1042 $allowed = apply_filters(
1043 'openstation_ai_command_allowed',
1044 $cmd,
1045 $slug,
1046 array(
1047 'user_id' => $user_id,
1048 'request_id' => $request_id,
1049 )
1050 );
1051 if ( false === $allowed || ! is_array( $allowed ) ) {
1052 continue;
1053 }
1054 $label = isset( $allowed['label'] ) ? (string) $allowed['label'] : $slug;
1055 $description = isset( $allowed['description'] ) ? (string) $allowed['description'] : '';
1056 $hint = isset( $allowed['hint'] ) ? (string) $allowed['hint'] : '';
1057 $tool_name = 'command_' . $slug;
1058
1059 $command_tools_by_name[ $tool_name ] = array( 'slug' => $slug );
1060 $command_defs[] = array(
1061 'type' => 'function',
1062 'name' => $tool_name,
1063 'description' => trim( $label . ( '' !== $description ? '' . $description : '' ) ),
1064 'parameters' => array(
1065 'type' => 'object',
1066 'properties' => array(
1067 'args' => array(
1068 'type' => 'string',
1069 'description' => '' !== $hint
1070 ? sprintf( 'Arguments for this command. Hint: %s', $hint )
1071 : 'Arguments for this command. Leave empty when the command takes none.',
1072 ),
1073 ),
1074 'required' => array( 'args' ),
1075 'additionalProperties' => false,
1076 ),
1077 );
1078 }
1079
1080 /**
1081 * Transform the command-tool subset before merging with the
1082 * built-in + registered tools. Useful for bulk gating, renaming,
1083 * or injecting synthetic command tools.
1084 *
1085 * @param array $command_defs Command tool definitions.
1086 * @param array $context { user_id, request_id }.
1087 */
1088 $command_defs = (array) apply_filters(
1089 'openstation_ai_command_tools',
1090 $command_defs,
1091 array(
1092 'user_id' => $user_id,
1093 'request_id' => $request_id,
1094 )
1095 );
1096
1097 $tools = array_merge( $builtin_tools, $command_defs );
1098
1099 /**
1100 * Transform the full tool list (built-in abilities + command tools) just
1101 * before it goes to the provider. Fires once per run — changes apply to
1102 * every iteration in the agent loop.
1103 *
1104 * @param array $tools Full the provider tool definitions array.
1105 * @param array $context { user_id, request_id, query }.
1106 */
1107 $tools = (array) apply_filters(
1108 'openstation_ai_tools',
1109 $tools,
1110 array(
1111 'user_id' => $user_id,
1112 'request_id' => $request_id,
1113 'query' => $query,
1114 )
1115 );
1116
1117 // Normalize every tool's schema onto the provider-supported subset, AFTER the
1118 // filter so it covers the complete list the provider will receive — built-in
1119 // abilities, command tools, and anything a plugin injected. One tool with a
1120 // legal-but-unsupported schema otherwise 400s the entire request, not just its
1121 // own tool. Only the model-facing copy is reshaped; abilities still validate
1122 // arguments against their real schema in execute(). Idempotent, so a plugin
1123 // that already normalizes on the filter above is unaffected.
1124 foreach ( $tools as $ti => $tool ) {
1125 if ( is_array( $tool ) && isset( $tool['parameters'] ) ) {
1126 $tools[ $ti ]['parameters'] = openstation_ai_normalize_tool_schema( $tool['parameters'] );
1127 }
1128 }
1129
1130 // Widen the permitted-tools list with the command tools — the agent loop
1131 // rejects any `function_call` whose name isn't in here (built-in ability
1132 // names were added above).
1133 foreach ( $command_defs as $def ) {
1134 if ( isset( $def['name'] ) ) {
1135 $valid_tools[] = (string) $def['name'];
1136 }
1137 }
1138
1139 $answer_schema = openstation_ai_search_answer_schema();
1140
1141 // -----------------------------------------------------------------------
1142 // First call — user query as the sole message, instructions as system
1143 // guidance. Generation routes through the WordPress AI Client; the tools
1144 // are advertised as function declarations and dispatched by this loop.
1145 // The full ordered conversation is rebuilt and re-sent each turn.
1146 // -----------------------------------------------------------------------
1147 $messages = array( openstation_ai_user_text_message( $query ) );
1148
1149 $generation_context = array(
1150 'source' => 'ai-copilot/search',
1151 'request_id' => $request_id,
1152 );
1153
1154 $turn = openstation_ai_client_generate( $user_id, $messages, $tools, $answer_schema, $instructions, $generation_context );
1155
1156 if ( is_wp_error( $turn ) ) {
1157 return $turn;
1158 }
1159
1160 $last_tool = $initial_tool ?? 'search_posts';
1161 $last_offset = $start_offset;
1162 $last_has_more = true;
1163 $iterations = 0;
1164
1165 // Accumulate token usage across every turn and remember the last model the
1166 // AI Client resolved, for the `openstation_ai_search_completed` payload.
1167 $total_usage = array(
1168 'prompt' => 0,
1169 'completion' => 0,
1170 'total' => 0,
1171 );
1172 $last_model = null;
1173 $accrue_usage = static function ( $turn ) use ( &$total_usage, &$last_model ) {
1174 if ( ! is_array( $turn ) ) {
1175 return;
1176 }
1177 if ( isset( $turn['usage'] ) && is_array( $turn['usage'] ) ) {
1178 $total_usage['prompt'] += (int) ( $turn['usage']['prompt'] ?? 0 );
1179 $total_usage['completion'] += (int) ( $turn['usage']['completion'] ?? 0 );
1180 $total_usage['total'] += (int) ( $turn['usage']['total'] ?? 0 );
1181 }
1182 if ( isset( $turn['model'] ) && is_array( $turn['model'] ) ) {
1183 $last_model = $turn['model'];
1184 }
1185 };
1186 $accrue_usage( $turn );
1187
1188 // -----------------------------------------------------------------------
1189 // Agentic loop — each iteration either executes tool calls or returns
1190 // the final answer. The full ordered conversation (user query, assistant
1191 // turns, tool results) is accumulated in $messages and re-sent each turn.
1192 // -----------------------------------------------------------------------
1193 for ( $i = 0; $i < OPENSTATION_AI_SEARCH_MAX_ITERATIONS; $i++ ) {
1194 $function_calls = is_array( $turn['function_calls'] ?? null ) ? $turn['function_calls'] : array();
1195
1196 // No tool calls in this response → final answer.
1197 if ( empty( $function_calls ) ) {
1198 // A toolless turn with no extractable text never reaches here:
1199 // openstation_ai_client_generate() returns
1200 // `openstation_ai_empty_answer` for that case, handled with the
1201 // other generation errors above.
1202 $text = (string) ( $turn['text'] ?? '' );
1203
1204 $answer = json_decode( $text, true );
1205 if ( ! is_array( $answer ) ) {
1206 return new WP_Error( 'openstation_ai_result_parse', __( 'Could not parse structured search answer.', 'desktop-mode' ) );
1207 }
1208
1209 $answer_type = isset( $answer['answer_type'] ) && in_array( $answer['answer_type'], array( 'entity', 'navigation', 'chat' ), true )
1210 ? (string) $answer['answer_type']
1211 : 'chat';
1212 $message = isset( $answer['message'] ) ? (string) $answer['message'] : '';
1213 $entity_id = ( isset( $answer['entity_id'] ) && is_int( $answer['entity_id'] ) )
1214 ? $answer['entity_id'] : null;
1215 $entity_type = ( isset( $answer['entity_type'] ) && is_string( $answer['entity_type'] ) )
1216 ? $answer['entity_type'] : null;
1217 $admin_links = isset( $answer['admin_links'] ) && is_array( $answer['admin_links'] )
1218 ? $answer['admin_links'] : null;
1219
1220 $entity = null;
1221 if ( 'entity' === $answer_type && $entity_id && $entity_type ) {
1222 $entity = openstation_ai_search_build_entity( $entity_type, $entity_id );
1223 }
1224
1225 $final = array(
1226 'answer_type' => $answer_type,
1227 'message' => $message,
1228 'entity' => $entity,
1229 'admin_links' => $admin_links,
1230 'iterations' => $iterations + 1,
1231 'exhausted' => ! $last_has_more,
1232 'continue' => null,
1233 'request_id' => $request_id,
1234 );
1235
1236 /**
1237 * Final transform hook — fires right before the HTTP
1238 * response is returned. Plugins can rewrite `message`,
1239 * inject `admin_links`, coerce `answer_type`, etc.
1240 *
1241 * @param array $answer Final answer payload.
1242 * @param array $context { query, user_id, request_id }.
1243 */
1244 $final = (array) apply_filters(
1245 'openstation_ai_answer',
1246 $final,
1247 array(
1248 'query' => $query,
1249 'user_id' => $user_id,
1250 'request_id' => $request_id,
1251 )
1252 );
1253
1254 do_action(
1255 'openstation_ai_search_completed',
1256 array(
1257 'query' => $query,
1258 'user_id' => $user_id,
1259 'request_id' => $request_id,
1260 'answer_type' => $final['answer_type'] ?? 'chat',
1261 'iterations' => $final['iterations'] ?? 0,
1262 'usage' => $total_usage,
1263 'model' => $last_model,
1264 )
1265 );
1266
1267 return $final;
1268 }
1269
1270 // -------------------------------------------------------------------
1271 // Command-tool short-circuit.
1272 //
1273 // If the model emitted `command_<slug>`, we return immediately with
1274 // `answer_type: 'tool_call'` — the client owns the command's `run()`
1275 // function (lives in plugin JS) and executes it locally. We do NOT
1276 // send anything else back to the provider this turn — would burn tokens
1277 // for a no-op second response.
1278 // -------------------------------------------------------------------
1279 $command_tool_call = null;
1280 foreach ( $function_calls as $fc ) {
1281 $name = (string) ( $fc['name'] ?? '' );
1282 if ( isset( $command_tools_by_name[ $name ] ) ) {
1283 $raw = json_decode( $fc['arguments'] ?? '{}', true );
1284 $decoded = is_array( $raw ) ? $raw : array();
1285 $command_tool_call = array(
1286 'slug' => $command_tools_by_name[ $name ]['slug'],
1287 'args' => isset( $decoded['args'] ) ? (string) $decoded['args'] : '',
1288 );
1289 break;
1290 }
1291 }
1292 if ( null !== $command_tool_call ) {
1293 do_action(
1294 'openstation_ai_tool_called',
1295 array(
1296 'tool_name' => 'command_' . $command_tool_call['slug'],
1297 'args' => array( 'args' => $command_tool_call['args'] ),
1298 'user_id' => $user_id,
1299 'request_id' => $request_id,
1300 )
1301 );
1302
1303 $final = array(
1304 'answer_type' => 'tool_call',
1305 'message' => '',
1306 'entity' => null,
1307 'admin_links' => null,
1308 'tool' => $command_tool_call,
1309 'iterations' => $iterations + 1,
1310 'exhausted' => false,
1311 'continue' => null,
1312 'request_id' => $request_id,
1313 );
1314
1315 $final = (array) apply_filters(
1316 'openstation_ai_answer',
1317 $final,
1318 array(
1319 'query' => $query,
1320 'user_id' => $user_id,
1321 'request_id' => $request_id,
1322 )
1323 );
1324
1325 do_action(
1326 'openstation_ai_search_completed',
1327 array(
1328 'query' => $query,
1329 'user_id' => $user_id,
1330 'request_id' => $request_id,
1331 'answer_type' => 'tool_call',
1332 'iterations' => $final['iterations'] ?? 0,
1333 'usage' => $total_usage,
1334 'model' => $last_model,
1335 )
1336 );
1337
1338 return $final;
1339 }
1340
1341 // Execute each tool call and collect results as
1342 // `{ call_id, name, response }` — turned into FunctionResponse parts
1343 // for the next turn by openstation_ai_tool_result_message().
1344 $tool_outputs = array();
1345 foreach ( $function_calls as $fc ) {
1346 $tool_name = $fc['name'] ?? '';
1347 $call_id = $fc['call_id'] ?? '';
1348
1349 if ( ! in_array( $tool_name, $valid_tools, true ) ) {
1350 $tool_outputs[] = array(
1351 'call_id' => $call_id,
1352 'name' => $tool_name,
1353 'response' => array( 'error' => "Unknown tool '{$tool_name}'." ),
1354 );
1355 continue;
1356 }
1357
1358 $raw = json_decode( $fc['arguments'] ?? '{}', true );
1359 $args = is_array( $raw ) ? $raw : array();
1360 $offset = max( 0, (int) ( $args['offset'] ?? 0 ) );
1361
1362 do_action(
1363 'openstation_ai_tool_called',
1364 array(
1365 'tool_name' => $tool_name,
1366 'args' => $args,
1367 'user_id' => $user_id,
1368 'request_id' => $request_id,
1369 )
1370 );
1371
1372 // Resolve + run the ability. execute() runs the permission_callback
1373 // and validates input/output; a denial or bad input comes back as a
1374 // WP_Error, which we surface to the model as a clean tool error
1375 // (never a fatal) and report on the observability channel.
1376 $ability = isset( $ability_by_tool[ $tool_name ] ) ? wp_get_ability( $ability_by_tool[ $tool_name ] ) : null;
1377 if ( $ability instanceof WP_Ability ) {
1378 // Abilities that declare no input schema (e.g. Core's
1379 // get-*-info) reject any non-null input, so pass null when
1380 // there's no schema; otherwise hand over the decoded args.
1381 $input = empty( $ability->get_input_schema() ) ? null : $args;
1382 $result = $ability->execute( $input );
1383 } else {
1384 $result = new WP_Error( 'openstation_ai_unknown_ability', sprintf( 'Ability for tool "%s" is unavailable.', $tool_name ) );
1385 }
1386
1387 if ( is_wp_error( $result ) ) {
1388 do_action(
1389 'openstation_ai_search_error',
1390 array(
1391 'stage' => 'tool_execute',
1392 'tool_name' => $tool_name,
1393 'error' => $result->get_error_code(),
1394 'message' => $result->get_error_message(),
1395 'user_id' => $user_id,
1396 'request_id' => $request_id,
1397 )
1398 );
1399 $batch = array(
1400 'error' => $result->get_error_message(),
1401 'error_code' => $result->get_error_code(),
1402 );
1403 } else {
1404 $batch = is_array( $result ) ? $result : array( 'result' => $result );
1405 }
1406
1407 $last_tool = $tool_name;
1408 $last_offset = $offset;
1409 $last_has_more = (bool) ( $batch['has_more'] ?? false );
1410
1411 /**
1412 * Transform a tool result before it goes back to the model.
1413 * Fires for every ability-dispatched tool (including error
1414 * envelopes from a failed execute()).
1415 *
1416 * @param array $batch Tool result payload.
1417 * @param string $tool_name Tool function name.
1418 * @param array $args Decoded args from the call.
1419 * @param array $context { user_id, request_id }.
1420 */
1421 $batch = (array) apply_filters(
1422 'openstation_ai_tool_result',
1423 $batch,
1424 $tool_name,
1425 $args,
1426 array(
1427 'user_id' => $user_id,
1428 'request_id' => $request_id,
1429 )
1430 );
1431
1432 $tool_outputs[] = array(
1433 'call_id' => $call_id,
1434 'name' => $tool_name,
1435 'response' => $batch,
1436 );
1437 }
1438
1439 ++$iterations;
1440
1441 // Next turn — append the assistant's tool-call turn and our tool
1442 // results to the conversation, then regenerate with the full history.
1443 $messages[] = $turn['message'];
1444 $messages[] = openstation_ai_tool_result_message( $tool_outputs );
1445
1446 $turn = openstation_ai_client_generate( $user_id, $messages, $tools, $answer_schema, $instructions, $generation_context );
1447
1448 if ( is_wp_error( $turn ) ) {
1449 return $turn;
1450 }
1451 $accrue_usage( $turn );
1452 }
1453
1454 // -----------------------------------------------------------------------
1455 // Budget exhausted before a final answer.
1456 // -----------------------------------------------------------------------
1457 $continue = null;
1458 if ( $last_has_more ) {
1459 $next_offset = $last_offset + OPENSTATION_AI_SEARCH_BATCH_SIZE;
1460 // `search_comments_by_post` cannot resume — the continue payload
1461 // carries no post_id — so fall back to plain comment search,
1462 // keeping `tool` inside openstation_ai_search_resumable_tools().
1463 $resume_tool = 'search_comments_by_post' === $last_tool ? 'search_comments' : $last_tool;
1464 $continue = array(
1465 'tool' => $resume_tool,
1466 'entity_type' => rtrim( str_replace( 'search_', '', $resume_tool ), 's' ),
1467 'offset' => $next_offset,
1468 'label' => openstation_ai_continue_label( $resume_tool, $next_offset + 1 ),
1469 );
1470 }
1471
1472 $final = array(
1473 'answer_type' => 'chat',
1474 'message' => __( 'I searched 100 items without finding a clear match. Want me to keep looking further?', 'desktop-mode' ),
1475 'entity' => null,
1476 'admin_links' => null,
1477 'iterations' => OPENSTATION_AI_SEARCH_MAX_ITERATIONS,
1478 'exhausted' => ! $last_has_more,
1479 'continue' => $continue,
1480 'request_id' => $request_id,
1481 );
1482
1483 $final = (array) apply_filters(
1484 'openstation_ai_answer',
1485 $final,
1486 array(
1487 'query' => $query,
1488 'user_id' => $user_id,
1489 'request_id' => $request_id,
1490 )
1491 );
1492
1493 do_action(
1494 'openstation_ai_search_completed',
1495 array(
1496 'query' => $query,
1497 'user_id' => $user_id,
1498 'request_id' => $request_id,
1499 'answer_type' => 'chat',
1500 'iterations' => OPENSTATION_AI_SEARCH_MAX_ITERATIONS,
1501 'usage' => $total_usage,
1502 'model' => $last_model,
1503 )
1504 );
1505
1506 return $final;
1507 }
1508
1509 /**
1510 * Compose the final system-prompt string for an `/ai/search` call.
1511 *
1512 * One code path used by both the primary run and the follow-up leg —
1513 * keeps the voice consistent across legs and removes a class of drift
1514 * bug where the two paths's prompt-assembly drifts apart.
1515 *
1516 * Applies three layers in order:
1517 * 1. `openstation_ai_system_prompt_appendix` — stacking filter;
1518 * every plugin's return is concatenated.
1519 * 2. Client override — `system_prompt_text` + `system_prompt_mode`.
1520 * `append` always allowed; `replace` gated on
1521 * `openstation_ai_system_prompt_replace_capability`. Non-permitted
1522 * `replace` downgrades to `append` so the caller's text is
1523 * preserved rather than dropped.
1524 * 3. `openstation_ai_system_prompt` — final transform pass.
1525 *
1526 * @internal
1527 *
1528 * @param string $core Built-in instructions for this phase
1529 * (agent loop / follow-up summariser).
1530 * @param array $context { query, user_id, request_id, phase? }.
1531 * @param array $client { text, mode } client override; either field
1532 * empty means no override.
1533 * @return string Composed system prompt.
1534 */
1535 function openstation_ai_compose_instructions( $core, array $context, array $client = array() ) {
1536 $instructions = (string) $core;
1537 $user_id = isset( $context['user_id'] ) ? (int) $context['user_id'] : 0;
1538
1539 $client_text = isset( $client['text'] ) && is_string( $client['text'] ) ? $client['text'] : '';
1540 $client_mode = isset( $client['mode'] ) && in_array( $client['mode'], array( 'append', 'replace' ), true )
1541 ? (string) $client['mode']
1542 : 'append';
1543
1544 $ctx_for_filter = $context;
1545 $ctx_for_filter['client_override'] = '' !== $client_text ? $client_mode : null;
1546
1547 /**
1548 * Short-circuit extension — appended to the built-in instructions
1549 * verbatim. Use this when a plugin just wants to add domain
1550 * context (room list, product catalogue, company jargon) without
1551 * restructuring the core rules. Fires for both the primary
1552 * `/ai/search` run and the follow-up composed-reply leg.
1553 *
1554 * @param string $appendix Accumulated appendix. Default empty.
1555 * @param array $context { query, user_id, request_id, client_override, phase? }.
1556 */
1557 $server_appendix = (string) apply_filters( 'openstation_ai_system_prompt_appendix', '', $ctx_for_filter );
1558 if ( '' !== $server_appendix ) {
1559 $instructions .= "\n\n" . $server_appendix;
1560 }
1561
1562 if ( '' !== $client_text ) {
1563 if ( 'replace' === $client_mode ) {
1564 /**
1565 * Capability required for a client to send
1566 * `system_prompt: { mode: 'replace' }`. Defaults to `manage_options`
1567 * — replacing the whole prompt can effectively hijack the
1568 * assistant, so it's admin-only out of the box.
1569 *
1570 * @param string $capability Default `manage_options`.
1571 * @param array $context
1572 */
1573 $required_cap = (string) apply_filters(
1574 'openstation_ai_system_prompt_replace_capability',
1575 'manage_options',
1576 $ctx_for_filter
1577 );
1578 if ( '' === $required_cap || ( $user_id > 0 && user_can( $user_id, $required_cap ) ) ) {
1579 $instructions = $client_text;
1580 } else {
1581 // Silently downgrade to append — preserves the caller's
1582 // text rather than dropping it when the cap check fails.
1583 $instructions .= "\n\n" . $client_text;
1584 }
1585 } else {
1586 $instructions .= "\n\n" . $client_text;
1587 }
1588 }
1589
1590 /**
1591 * Final transform pass. Fires after the built-in instructions,
1592 * server appendix, and client override have all been composed.
1593 *
1594 * @param string $instructions Composed system prompt.
1595 * @param array $context
1596 */
1597 return (string) apply_filters( 'openstation_ai_system_prompt', $instructions, $ctx_for_filter );
1598 }
1599
1600 /**
1601 * Compose a natural-language reply describing the outcome of a
1602 * client-dispatched command invocation.
1603 *
1604 * Called by the REST endpoint when the client sends `follow_up` —
1605 * the second leg of the opt-in agentic flow triggered by
1606 * `wp.os.ai.ask( q, { tools: 'aiCallable', followUp: true } )`.
1607 *
1608 * Single-turn, no tools, no structured-output schema — the model
1609 * sees the original query + a summary of what happened and writes a
1610 * one/two-sentence reply in the voice of the system prompt. We reuse
1611 * the same system-prompt pipeline as the main search so plugins
1612 * appending instructions via `openstation_ai_system_prompt_appendix`
1613 * see consistent voice across the two legs.
1614 *
1615 * @param string $query Original user query.
1616 * @param array $tool { slug, args } — what ran.
1617 * @param array $outcome Tool result payload. Opaque — JSON-encoded
1618 * into the model's context so it can reason
1619 * about whatever shape the plugin returned.
1620 * @param array $extra Same shape as `openstation_ai_run_search`'s
1621 * `$extra` — carries user_id, request_id,
1622 * system-prompt overrides.
1623 * @return array|WP_Error `{ answer_type: 'chat', message, … }` or error.
1624 */
1625 function openstation_ai_run_followup( $query, array $tool, array $outcome, array $extra = array() ) {
1626 $user_id = isset( $extra['user_id'] ) ? (int) $extra['user_id'] : get_current_user_id();
1627 $request_id = isset( $extra['request_id'] ) && is_string( $extra['request_id'] ) && '' !== $extra['request_id']
1628 ? (string) $extra['request_id']
1629 : ( function_exists( 'wp_generate_uuid4' ) ? wp_generate_uuid4() : uniqid( 'openstation_ai_', true ) );
1630
1631 do_action(
1632 'openstation_ai_search_started',
1633 array(
1634 'query' => $query,
1635 'user_id' => $user_id,
1636 'request_id' => $request_id,
1637 'phase' => 'follow_up',
1638 )
1639 );
1640
1641 // Mirror the main search's system-prompt layering so voice stays
1642 // consistent between the two legs. We build a simpler core-
1643 // instructions block — no tool guidance, since this run has none.
1644 $instructions = '
1645 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.
1646
1647 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.
1648
1649 Rules:
1650 - If the outcome looks successful, confirm plainly. Example: "Done — your office light is on now."
1651 - 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.
1652 - Do NOT recommend the user try something else unless the outcome explicitly suggests it.
1653 - Do NOT describe the tool mechanism ("I called command_turn_light") — the user only cares about the real-world effect.
1654 ';
1655
1656 $system_prompt_text = isset( $extra['system_prompt_text'] ) && is_string( $extra['system_prompt_text'] ) ? $extra['system_prompt_text'] : '';
1657 $system_prompt_mode = isset( $extra['system_prompt_mode'] ) && in_array( $extra['system_prompt_mode'], array( 'append', 'replace' ), true )
1658 ? (string) $extra['system_prompt_mode']
1659 : 'append';
1660
1661 $instructions = openstation_ai_compose_instructions(
1662 $instructions,
1663 array(
1664 'query' => $query,
1665 'user_id' => $user_id,
1666 'request_id' => $request_id,
1667 'phase' => 'follow_up',
1668 ),
1669 array(
1670 'text' => $system_prompt_text,
1671 'mode' => $system_prompt_mode,
1672 )
1673 );
1674
1675 $slug = isset( $tool['slug'] ) ? (string) $tool['slug'] : '';
1676 $tool_args = isset( $tool['args'] ) ? (string) $tool['args'] : '';
1677 $outcome_json = wp_json_encode( $outcome );
1678 if ( ! is_string( $outcome_json ) ) {
1679 $outcome_json = '""';
1680 }
1681
1682 // Bound the outcome payload so a malicious or buggy plugin that
1683 // returns a 5MB blob can't inflate the provider token usage without
1684 // bound. 4 KB is enough for a status string, a small result list,
1685 // or a short error envelope — anything bigger gets truncated with
1686 // a marker so the model knows the tail was dropped.
1687 //
1688 // `mb_*` variants so truncation on a multibyte boundary
1689 // (Japanese / emoji / accented UTF-8) can't produce invalid JSON
1690 // that the provider would reject. Falls back to byte-level substr when
1691 // mbstring is unavailable (rare but possible on minimal PHP
1692 // builds).
1693 $max_outcome_len = (int) apply_filters( 'openstation_ai_followup_outcome_max_chars', 4000 );
1694 if ( $max_outcome_len > 0 ) {
1695 $has_mbstring = function_exists( 'mb_strlen' ) && function_exists( 'mb_substr' );
1696 $current_len = $has_mbstring
1697 ? mb_strlen( $outcome_json, 'UTF-8' )
1698 : strlen( $outcome_json );
1699 if ( $current_len > $max_outcome_len ) {
1700 $outcome_json = $has_mbstring
1701 ? mb_substr( $outcome_json, 0, $max_outcome_len, 'UTF-8' )
1702 : substr( $outcome_json, 0, $max_outcome_len );
1703 $outcome_json .= '…[truncated]';
1704 }
1705 }
1706
1707 $user_message = sprintf(
1708 "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.",
1709 $query,
1710 $slug,
1711 $tool_args,
1712 $outcome_json
1713 );
1714
1715 do_action(
1716 'openstation_ai_tool_called',
1717 array(
1718 'tool_name' => 'followup_summarise',
1719 'args' => array(
1720 'slug' => $slug,
1721 'tool_args' => $tool_args,
1722 ),
1723 'user_id' => $user_id,
1724 'request_id' => $request_id,
1725 )
1726 );
1727
1728 $turn = openstation_ai_client_generate(
1729 $user_id,
1730 array( openstation_ai_user_text_message( $user_message ) ),
1731 array(), // no tools — we want a plain reply
1732 null, // no JSON schema — free-form text
1733 $instructions,
1734 array(
1735 'source' => 'ai-copilot/followup',
1736 'request_id' => $request_id,
1737 )
1738 );
1739
1740 // `openstation_ai_empty_answer` is the one generation error this path
1741 // deliberately absorbs: the command DID run, so a text-less summary turn
1742 // degrades to the generic confirmation below instead of surfacing as a
1743 // failure of the command itself.
1744 $empty_answer = is_wp_error( $turn ) && 'openstation_ai_empty_answer' === $turn->get_error_code();
1745
1746 if ( is_wp_error( $turn ) && ! $empty_answer ) {
1747 do_action(
1748 'openstation_ai_search_error',
1749 array(
1750 'code' => $turn->get_error_code(),
1751 'message' => $turn->get_error_message(),
1752 'data' => $turn->get_error_data(),
1753 'user_id' => $user_id,
1754 'request_id' => $request_id,
1755 'phase' => 'follow_up',
1756 )
1757 );
1758 return $turn;
1759 }
1760
1761 $text = $empty_answer ? null : ( $turn['text'] ?? null );
1762 $fallback = false;
1763 if ( ! is_string( $text ) || '' === trim( $text ) ) {
1764 // Graceful degrade — if the provider returned nothing usable, fall
1765 // back to a generic confirmation so the caller always has a
1766 // message to show. Better than returning an error and losing
1767 // the fact that the command *did* run. We flag the degrade so
1768 // observability subscribers can distinguish a deliberate
1769 // "Done." from a silently-degraded one.
1770 $text = 'Done.';
1771 $fallback = true;
1772 }
1773
1774 $final = array(
1775 'answer_type' => 'chat',
1776 'message' => trim( $text ),
1777 'entity' => null,
1778 'admin_links' => null,
1779 'iterations' => 1,
1780 'exhausted' => false,
1781 'continue' => null,
1782 'request_id' => $request_id,
1783 'tool' => array(
1784 'slug' => $slug,
1785 'args' => $tool_args,
1786 ),
1787 'fallback' => $fallback,
1788 );
1789
1790 $final = (array) apply_filters(
1791 'openstation_ai_answer',
1792 $final,
1793 array(
1794 'query' => $query,
1795 'user_id' => $user_id,
1796 'request_id' => $request_id,
1797 'phase' => 'follow_up',
1798 )
1799 );
1800
1801 do_action(
1802 'openstation_ai_search_completed',
1803 array(
1804 'query' => $query,
1805 'user_id' => $user_id,
1806 'request_id' => $request_id,
1807 'answer_type' => 'chat',
1808 'iterations' => 1,
1809 'phase' => 'follow_up',
1810 'fallback' => $fallback,
1811 )
1812 );
1813
1814 return $final;
1815 }
1816
1817 // ---------------------------------------------------------------------------
1818 // REST endpoint
1819 // ---------------------------------------------------------------------------
1820
1821 /**
1822 * Registers the AI search REST route.
1823 */
1824 function openstation_register_ai_search_rest_route() {
1825 register_rest_route(
1826 'desktop-mode/v1',
1827 '/ai/search',
1828 array(
1829 'methods' => WP_REST_Server::CREATABLE,
1830 'callback' => 'openstation_rest_ai_search',
1831 'permission_callback' => 'openstation_rest_ai_search_permission',
1832 'args' => array(
1833 'query' => array(
1834 'required' => true,
1835 'type' => 'string',
1836 'sanitize_callback' => 'sanitize_text_field',
1837 'validate_callback' => static function ( $v ) {
1838 return is_string( $v ) && trim( $v ) !== '';
1839 },
1840 ),
1841 // `resume_tool` + `start_offset` are only set when the
1842 // client is continuing a previous search from the `continue`
1843 // object returned by an exhausted run. Fresh searches leave
1844 // both unset — the agent picks tools from query semantics.
1845 'resume_tool' => array(
1846 'required' => false,
1847 'type' => array( 'string', 'null' ),
1848 'default' => null,
1849 'sanitize_callback' => static function ( $v ) {
1850 return in_array( $v, openstation_ai_search_resumable_tools(), true )
1851 ? $v : null;
1852 },
1853 ),
1854 'start_offset' => array(
1855 'required' => false,
1856 'type' => 'integer',
1857 'default' => 0,
1858 'sanitize_callback' => 'absint',
1859 ),
1860 // Client-harvested slash-commands the user's plugins have
1861 // opted in as AI tools. Each entry: { slug, label, description?, hint? }.
1862 // The slug is namespaced server-side as `command_<slug>`
1863 // and any tool_call the model emits with that name short-
1864 // circuits back to the client for local dispatch.
1865 'command_tools' => array(
1866 'required' => false,
1867 'type' => 'array',
1868 'default' => array(),
1869 'items' => array(
1870 'type' => 'object',
1871 'properties' => array(
1872 'slug' => array( 'type' => 'string' ),
1873 'label' => array( 'type' => 'string' ),
1874 'description' => array( 'type' => 'string' ),
1875 'hint' => array( 'type' => 'string' ),
1876 ),
1877 ),
1878 ),
1879 // Free-form system-prompt override.
1880 // mode: 'append' → concatenated onto the built-in prompt (safe for everyone)
1881 // mode: 'replace' → replaces the built-in prompt entirely, gated on
1882 // `openstation_ai_system_prompt_replace_capability`
1883 // (default `manage_options`).
1884 'system_prompt_text' => array(
1885 'required' => false,
1886 'type' => 'string',
1887 'default' => '',
1888 ),
1889 'system_prompt_mode' => array(
1890 'required' => false,
1891 'type' => 'string',
1892 'default' => 'append',
1893 'sanitize_callback' => static function ( $v ) {
1894 return in_array( $v, array( 'append', 'replace' ), true ) ? $v : 'append';
1895 },
1896 ),
1897 // Follow-up leg of the agentic command-dispatch flow.
1898 // When present, the endpoint SKIPS the agent loop entirely
1899 // and runs a single-turn "summarise this outcome" call
1900 // through the provider instead. The client sends this on the
1901 // second leg of `ask( q, { tools: 'aiCallable', followUp: true } )`.
1902 'follow_up' => array(
1903 'required' => false,
1904 'type' => array( 'object', 'null' ),
1905 'default' => null,
1906 ),
1907 ),
1908 )
1909 );
1910 }
1911 add_action( 'rest_api_init', 'openstation_register_ai_search_rest_route' );
1912
1913 /**
1914 * Permission callback.
1915 *
1916 * @return bool|WP_Error
1917 */
1918 function openstation_rest_ai_search_permission() {
1919 if ( ! is_user_logged_in() || ! current_user_can( 'read' ) ) {
1920 return new WP_Error(
1921 'openstation_ai_forbidden',
1922 __( 'You must be logged in to use the AI assistant.', 'desktop-mode' ),
1923 array( 'status' => 403 )
1924 );
1925 }
1926 if ( ! openstation_ai_is_available() ) {
1927 return new WP_Error(
1928 'openstation_ai_unavailable',
1929 __( 'The AI assistant is unavailable on this site.', 'desktop-mode' ),
1930 array( 'status' => 503 )
1931 );
1932 }
1933 if ( ! openstation_ai_is_enabled( get_current_user_id() ) ) {
1934 // The message names the tab for consumers that only get text (a REST
1935 // client, `wp.os.ai.ask()`). `settings_tab` names it again as data,
1936 // so the overlay can offer a one-click link without parsing prose.
1937 return new WP_Error(
1938 'openstation_ai_disabled',
1939 __(
1940 'The AI assistant is turned off. Enable it in OpenStation Preferences → Features.',
1941 'desktop-mode'
1942 ),
1943 array(
1944 'status' => 403,
1945 'settings_tab' => 'features',
1946 )
1947 );
1948 }
1949 return true;
1950 }
1951
1952 /**
1953 * POST /desktop-mode/v1/ai/search
1954 *
1955 * @param WP_REST_Request $request
1956 * @return WP_REST_Response|WP_Error
1957 */
1958 function openstation_rest_ai_search( WP_REST_Request $request ) {
1959 // The agent loop runs up to OPENSTATION_AI_SEARCH_MAX_ITERATIONS model
1960 // round-trips, each with a tool call, which overruns a default 30s
1961 // max_execution_time. The streaming endpoint used to raise this; it is
1962 // the only path now, so it carries the limit.
1963 @set_time_limit( 120 ); // phpcs:ignore
1964
1965 $user_id = get_current_user_id();
1966 $query = $request->get_param( 'query' );
1967 $resume_tool = $request->get_param( 'resume_tool' );
1968 $start_offset = $request->get_param( 'start_offset' );
1969
1970 $command_tools = $request->get_param( 'command_tools' );
1971 if ( ! is_array( $command_tools ) ) {
1972 $command_tools = array();
1973 }
1974
1975 $extra = array(
1976 'user_id' => $user_id,
1977 'request_id' => function_exists( 'wp_generate_uuid4' ) ? wp_generate_uuid4() : uniqid( 'openstation_ai_', true ),
1978 'command_tools' => $command_tools,
1979 'system_prompt_text' => (string) $request->get_param( 'system_prompt_text' ),
1980 'system_prompt_mode' => (string) $request->get_param( 'system_prompt_mode' ),
1981 );
1982
1983 /**
1984 * Last-mile filter on the whole `/ai/search` request bundle.
1985 * Plugins get one hook to rewrite query, swap tools, or inject
1986 * metadata before the agent loop starts.
1987 *
1988 * @param array $extra Extended context (mutable).
1989 * @param array $core Core request params { query, resume_tool, start_offset }.
1990 */
1991 $extra = (array) apply_filters(
1992 'openstation_ai_request',
1993 $extra,
1994 array(
1995 'query' => $query,
1996 'resume_tool' => $resume_tool,
1997 'start_offset' => $start_offset,
1998 )
1999 );
2000
2001 // Follow-up leg — skip the agent loop, summarise the tool outcome.
2002 $follow_up = $request->get_param( 'follow_up' );
2003 if ( is_array( $follow_up ) && isset( $follow_up['tool'] ) && is_array( $follow_up['tool'] ) ) {
2004 $tool = $follow_up['tool'];
2005 $outcome = isset( $follow_up['result'] )
2006 ? ( is_array( $follow_up['result'] ) ? $follow_up['result'] : array( 'value' => $follow_up['result'] ) )
2007 : array();
2008 $result = openstation_ai_run_followup( $query, $tool, $outcome, $extra );
2009 } else {
2010 $result = openstation_ai_run_search( $query, $resume_tool, $start_offset, $extra );
2011 }
2012
2013 if ( is_wp_error( $result ) ) {
2014 $request_id = isset( $extra['request_id'] ) ? (string) $extra['request_id'] : '';
2015 do_action(
2016 'openstation_ai_search_error',
2017 array(
2018 'code' => $result->get_error_code(),
2019 'message' => $result->get_error_message(),
2020 'data' => $result->get_error_data(),
2021 'user_id' => $user_id,
2022 'request_id' => $request_id,
2023 )
2024 );
2025 return $result;
2026 }
2027
2028 return rest_ensure_response( $result );
2029 }
2030
2031 // ---------------------------------------------------------------------------
2032 // Tool: search_wporg_plugins — uses core's plugins_api() which queries
2033 // the official WordPress.org repository. Results are cached in a
2034 // 10-minute transient per query so repeated asks don't hammer w.org.
2035 // ---------------------------------------------------------------------------
2036
2037 /**
2038 * Search the WordPress.org plugin directory.
2039 *
2040 * @param string $query Search terms.
2041 * @return array Tool result payload ready for the model.
2042 */
2043 function openstation_ai_fetch_wporg_plugins( $query ) {
2044 $query = trim( (string) $query );
2045 if ( '' === $query ) {
2046 return array(
2047 'tool' => 'search_wporg_plugins',
2048 'query' => '',
2049 'results' => array(),
2050 'count' => 0,
2051 'error' => 'No search query provided.',
2052 );
2053 }
2054
2055 // Transient cache to protect the w.org API from repeated queries
2056 // within the same conversation.
2057 $cache_key = 'openstation_ai_plugins_' . md5( strtolower( $query ) );
2058 $cached = get_transient( $cache_key );
2059 if ( is_array( $cached ) ) {
2060 return $cached;
2061 }
2062
2063 if ( ! function_exists( 'plugins_api' ) ) {
2064 require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
2065 }
2066
2067 $api = plugins_api(
2068 'query_plugins',
2069 array(
2070 'search' => $query,
2071 'per_page' => 10,
2072 'fields' => array(
2073 'short_description' => true,
2074 'description' => false,
2075 'sections' => false,
2076 'requires' => true,
2077 'tested' => true,
2078 'rating' => true,
2079 'ratings' => false,
2080 'downloaded' => false,
2081 'downloadlink' => false,
2082 'last_updated' => true,
2083 'added' => false,
2084 'tags' => false,
2085 'compatibility' => false,
2086 'homepage' => true,
2087 'versions' => false,
2088 'donate_link' => false,
2089 'reviews' => false,
2090 'banners' => false,
2091 'icons' => true,
2092 'active_installs' => true,
2093 'group' => false,
2094 'contributors' => false,
2095 ),
2096 )
2097 );
2098
2099 if ( is_wp_error( $api ) ) {
2100 return array(
2101 'tool' => 'search_wporg_plugins',
2102 'query' => $query,
2103 'results' => array(),
2104 'count' => 0,
2105 'error' => $api->get_error_message(),
2106 );
2107 }
2108
2109 $results = array();
2110 $plugins = isset( $api->plugins ) && is_array( $api->plugins ) ? $api->plugins : array();
2111 foreach ( $plugins as $p ) {
2112 // Normalise — plugins_api sometimes returns arrays, sometimes objects.
2113 $p = (array) $p;
2114
2115 $slug = isset( $p['slug'] ) ? (string) $p['slug'] : '';
2116 if ( '' === $slug ) {
2117 continue;
2118 }
2119
2120 $icon = '';
2121 $icons = isset( $p['icons'] ) && is_array( $p['icons'] ) ? $p['icons'] : array();
2122 if ( isset( $icons['1x'] ) ) {
2123 $icon = (string) $icons['1x'];
2124 } elseif ( isset( $icons['default'] ) ) {
2125 $icon = (string) $icons['default'];
2126 } elseif ( isset( $icons['svg'] ) ) {
2127 $icon = (string) $icons['svg'];
2128 }
2129
2130 // Admin URL that opens the plugin-information thickbox. Includes
2131 // both &plugin=slug and the TB_iframe params so clicking it in
2132 // wp-admin behaves like a native "More details" link.
2133 $install_admin_url = admin_url(
2134 'plugin-install.php?tab=plugin-information&plugin=' . rawurlencode( $slug )
2135 . '&TB_iframe=true&width=772&height=745'
2136 );
2137
2138 $results[] = array(
2139 'name' => wp_strip_all_tags( $p['name'] ?? '' ),
2140 'slug' => $slug,
2141 'short_description' => wp_strip_all_tags( $p['short_description'] ?? '' ),
2142 'version' => (string) ( $p['version'] ?? '' ),
2143 'author' => wp_strip_all_tags( $p['author'] ?? '' ),
2144 'rating' => (int) ( $p['rating'] ?? 0 ), // 0-100
2145 'num_ratings' => (int) ( $p['num_ratings'] ?? 0 ),
2146 'active_installs' => (int) ( $p['active_installs'] ?? 0 ),
2147 'last_updated' => (string) ( $p['last_updated'] ?? '' ),
2148 'requires' => (string) ( $p['requires'] ?? '' ),
2149 'tested' => (string) ( $p['tested'] ?? '' ),
2150 'homepage' => esc_url_raw( $p['homepage'] ?? '' ),
2151 'wporg_url' => 'https://wordpress.org/plugins/' . $slug . '/',
2152 'install_admin_url' => $install_admin_url,
2153 'icon' => esc_url_raw( $icon ),
2154 );
2155 }
2156
2157 $payload = array(
2158 'tool' => 'search_wporg_plugins',
2159 'query' => $query,
2160 'results' => $results,
2161 'count' => count( $results ),
2162 );
2163
2164 set_transient( $cache_key, $payload, 10 * MINUTE_IN_SECONDS );
2165
2166 return $payload;
2167 }
2168
2169 // ---------------------------------------------------------------------------
2170 // Tool: get_php_error_log — reads the tail of the site's error log.
2171 // Admin-only; the capability check is performed in the dispatcher
2172 // BEFORE this function runs, so by the time we get here the caller is
2173 // known to hold manage_options.
2174 // ---------------------------------------------------------------------------
2175
2176 /**
2177 * Read and parse the tail of the site's PHP error log.
2178 *
2179 * Tries WP_CONTENT_DIR/debug.log first (populated by WP_DEBUG_LOG), then
2180 * falls back to the PHP ini `error_log` directive. If neither points at
2181 * a readable file the tool reports log_available=false rather than
2182 * throwing.
2183 *
2184 * @param int $lines Number of lines to return (clamped 1-500 by caller).
2185 * @return array
2186 */
2187 function openstation_ai_fetch_error_log( $lines = 50 ) {
2188 $candidates = array();
2189 if ( defined( 'WP_CONTENT_DIR' ) ) {
2190 $candidates[] = WP_CONTENT_DIR . '/debug.log';
2191 }
2192 $ini_log = (string) ini_get( 'error_log' );
2193 if ( '' !== $ini_log && 'syslog' !== $ini_log ) {
2194 $candidates[] = $ini_log;
2195 }
2196
2197 /**
2198 * Filter the list of log-file paths to probe in order. Plugins that
2199 * redirect errors somewhere non-standard can add their path here.
2200 *
2201 * @param string[] $candidates File paths, in probe order.
2202 */
2203 $candidates = (array) apply_filters( 'openstation_ai_error_log_candidates', $candidates );
2204
2205 $log_path = '';
2206 foreach ( $candidates as $path ) {
2207 if ( is_string( $path ) && is_file( $path ) && is_readable( $path ) ) {
2208 $log_path = $path;
2209 break;
2210 }
2211 }
2212
2213 if ( '' === $log_path ) {
2214 return array(
2215 'tool' => 'get_php_error_log',
2216 'log_available' => false,
2217 'message' => 'No readable error log found. Enable WP_DEBUG_LOG in wp-config.php or set php_value error_log.',
2218 'checked_paths' => array_values( $candidates ),
2219 'entries' => array(),
2220 'count' => 0,
2221 );
2222 }
2223
2224 $tail = openstation_ai_tail_file( $log_path, $lines );
2225
2226 $entries = array();
2227 foreach ( $tail as $line ) {
2228 $line = trim( $line );
2229 if ( '' === $line ) {
2230 continue;
2231 }
2232 $entries[] = openstation_ai_parse_log_line( $line );
2233 }
2234
2235 return array(
2236 'tool' => 'get_php_error_log',
2237 'log_available' => true,
2238 'source' => $log_path,
2239 'entries' => $entries,
2240 'count' => count( $entries ),
2241 );
2242 }
2243
2244 /**
2245 * Parse a PHP error_log line into { timestamp, level, message }.
2246 *
2247 * PHP's default format is `[<date>] <prefix>: <message>` where the
2248 * prefix is usually "PHP Fatal error", "PHP Warning", etc. Falls back
2249 * to a raw line when the format doesn't match.
2250 *
2251 * @param string $line
2252 * @return array
2253 */
2254 function openstation_ai_parse_log_line( $line ) {
2255 // Cap individual messages so a runaway stack trace doesn't balloon
2256 // the payload sent to the provider.
2257 $line = mb_substr( $line, 0, 600 );
2258
2259 $entry = array(
2260 'timestamp' => '',
2261 'level' => 'Log',
2262 'message' => $line,
2263 );
2264
2265 // [21-Apr-2026 10:30:22 UTC] PHP Fatal error: Uncaught Error: …
2266 if ( preg_match( '/^\[([^\]]+)\]\s*(.*)$/', $line, $m ) ) {
2267 $entry['timestamp'] = $m[1];
2268 $entry['message'] = $m[2];
2269 }
2270
2271 if ( preg_match( '/^(PHP (?:Fatal error|Parse error|Warning|Notice|Deprecated|Strict|Recoverable fatal error))/i', $entry['message'], $lm ) ) {
2272 $entry['level'] = $lm[1];
2273 $entry['message'] = trim( substr( $entry['message'], strlen( $lm[1] ) ), ":\t " );
2274 }
2275
2276 return $entry;
2277 }
2278
2279 /**
2280 * Return the last $lines of a file. Loads the file via WP_Filesystem
2281 * (the only file-read API allowed for wp.org-hosted plugins) and
2282 * slices off the trailing N+1 entries. Realistic error logs sit
2283 * in the kilobyte range when admins look at them; if a site routinely
2284 * lets logs grow into tens of MB, that's the symptom, not this read.
2285 *
2286 * @param string $path Absolute path to the file.
2287 * @param int $lines
2288 * @return string[] Lines in original order (oldest first).
2289 */
2290 function openstation_ai_tail_file( $path, $lines ) {
2291 if ( ! function_exists( 'WP_Filesystem' ) ) {
2292 require_once ABSPATH . 'wp-admin/includes/file.php';
2293 }
2294 WP_Filesystem();
2295 global $wp_filesystem;
2296 if ( ! $wp_filesystem || ! $wp_filesystem->exists( $path ) ) {
2297 return array();
2298 }
2299
2300 $contents = $wp_filesystem->get_contents( $path );
2301 if ( false === $contents || '' === $contents ) {
2302 return array();
2303 }
2304
2305 $all = preg_split( '/\r?\n/', $contents );
2306 if ( ! is_array( $all ) ) {
2307 return array();
2308 }
2309
2310 return array_slice( $all, -1 * ( $lines + 1 ) );
2311 }
2312