namespace, '/chat/send', [ 'methods' => 'POST', 'callback' => [ $this, 'send_message' ], 'permission_callback' => [ $this, 'check_chat_permissions' ], ] ); // API to update & resend message register_rest_route( $this->namespace, '/chat/edit', [ 'methods' => 'POST', 'callback' => [ $this, 'edit_message' ], 'permission_callback' => [ $this, 'check_chat_permissions' ], ] ); // API to rate agent replay register_rest_route( $this->namespace, '/rate/agent-replay', [ 'methods' => 'POST', 'callback' => [ $this, 'rate_agent_replay' ], 'permission_callback' => [ $this, 'check_chat_permissions' ], ] ); // API to stream chat message register_rest_route( $this->namespace, '/chat/stream', [ 'methods' => 'POST', 'callback' => [ $this, 'stream_message' ], 'permission_callback' => [ $this, 'check_chat_permissions' ], ] ); // API to approve or reject a pending tool call register_rest_route( $this->namespace, '/chat/approve', [ 'methods' => 'POST', 'callback' => [ $this, 'approve_tool_call' ], 'permission_callback' => [ $this, 'check_chat_permissions' ], ] ); // API for the "Send link" card: emails a visitor their booking links. register_rest_route( $this->namespace, '/chat/manage-links', [ 'methods' => 'POST', 'callback' => [ $this, 'request_manage_links' ], 'permission_callback' => [ $this, 'check_chat_permissions' ], // Typed, so an array where text belongs is a 400 before the handler casts it. 'args' => [ 'channel' => [ 'type' => 'string' ], 'plugin' => [ 'type' => 'string' ], 'email' => [ 'type' => 'string' ], 'conversation_id' => [ 'type' => 'string' ], 'token' => [ 'type' => 'string' ], 'intent' => [ 'type' => 'string', 'enum' => [ 'reschedule', 'cancel', 'view' ], ], 'hint' => [ 'type' => 'object', 'properties' => [ 'service' => [ 'type' => 'string' ], 'date' => [ 'type' => 'string' ], ], ], ], ] ); } /** * Ask a plugin to email booking links to the address on the card. * * The body is the same for found and not found, so the chat never reveals * whether an email has bookings (see Manage_Links_Service). * * @param WP_REST_Request $request Request object. * @return \WP_REST_Response|WP_Error */ public function request_manage_links( WP_REST_Request $request ) { $conversation_id = sanitize_text_field( (string) ( $request->get_param( 'conversation_id' ) ?? '' ) ); if ( '' === $conversation_id || ! $this->public_session_valid( 'public', $conversation_id ) ) { return new WP_Error( 'aisentic_forbidden', __( 'This chat session has expired. Please reload the page.', 'aisentic' ), [ 'status' => 403 ] ); } $hint = $request->get_param( 'hint' ); $hint = is_array( $hint ) ? $hint : []; $hint['intent'] = (string) ( $request->get_param( 'intent' ) ?? '' ); return rest_ensure_response( ( new Manage_Links_Service() )->request( sanitize_key( (string) ( $request->get_param( 'plugin' ) ?? '' ) ), (string) ( $request->get_param( 'email' ) ?? '' ), $hint, $conversation_id, ( new Policy() )->getRequestIdentifier(), (string) ( $request->get_param( 'token' ) ?? '' ) ) ); } /** * Check permissions for chat endpoint * * @param WP_REST_Request $request Request object. * @return bool|WP_Error */ public function check_chat_permissions( WP_REST_Request $request ) { // Normalize the channel exactly the way the handlers do. Otherwise a value // like "Admin"/"ADMIN"/"admin " slips past the admin-auth gate below (which // matches 'admin' exactly), yet sanitizeChannel() later maps it back to // 'admin' — letting an anonymous caller drive the admin assistant agent. $channel = Sanitization::sanitizeChannel( (string) ( $request->get_param( 'channel' ) ?? 'admin' ) ); // The approve endpoint sends no channel param, so it would default to 'admin' // and gate a public approval behind manage_options while skipping the public // enabled-flag/rate-limit gates. Derive the real channel from the pending // approval record so the correct gate applies. $pending_id = sanitize_text_field( (string) ( $request->get_param( 'pending_id' ) ?? '' ) ); if ( '' !== $pending_id ) { $pending = get_transient( 'aisentic_tool_approval_' . $pending_id ); if ( is_array( $pending ) && ! empty( $pending['channel'] ) ) { $channel = Sanitization::sanitizeChannel( (string) $pending['channel'] ); } } if ( 'admin' === $channel && ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) ) { return false; } // Check rate limiting. $policy = new Policy(); $settings = new Settings(); $rate_limit = $settings->get( 'general.rateLimitPerMinute', 20 ); $identifier = $policy->getRequestIdentifier(); // Public chat is only reachable when at least one integration is switched // on. This mirrors the storefront widget gate on the server so the toggle // also governs the endpoint — otherwise the anonymous agent (and the // owner's paid tokens) would be invocable with every feature switched off. $public_agent = new Public_Agent_Settings( $settings ); if ( 'public' === $channel && ! $public_agent->any_enabled() ) { return new \WP_Error( 'aisentic_public_chat_disabled', __( 'Public chat is not available.', 'aisentic' ), [ 'status' => 403 ] ); } if ( $policy->isRateLimited( $identifier, $rate_limit ) ) { return new \WP_Error( 'aisentic_rate_limited', __( 'Too many requests. Please wait a moment before sending another message.', 'aisentic' ), [ 'status' => 429 ] ); } // Additional hourly rate limit for public chat. Reaching here with a public // channel already implies the feature is enabled (the gate above 403s // otherwise), so there is no need to re-read the setting. if ( 'public' === $channel ) { $hourly_limit = (int) $public_agent->widget( 'rateLimitPerHour', 20 ); if ( $policy->isHourlyRateLimited( $identifier, $hourly_limit ) ) { return new \WP_Error( 'aisentic_hourly_rate_limited', __( 'Session limit reached. Please try again in a little while.', 'aisentic' ), [ 'status' => 429 ] ); } } return true; } /** * Construct the channel-appropriate agent. * * Both agents share one constructor signature, so the only thing that varied * across the four handlers was which class to instantiate. Centralize it so a * constructor change lands in one place instead of four. * * @param string $channel Conversation channel ('admin' or 'public'). * @param Settings $settings Settings instance. * @param string $current_page WordPress screen ID / page context. * @param object|null $persistence Optional workflow persistence backend. * @param string|null $resume_token Optional workflow id to resume an interrupted run. * @param string[] $remembered_tool_names Integration tool names used in earlier turns. * @return Abstract_Agent */ private function make_agent( string $channel, Settings $settings, string $current_page, $persistence = null, ?string $resume_token = null, array $remembered_tool_names = [] ) { return 'admin' === $channel ? new Admin_Assistant_Agent( $settings, $current_page, $persistence, $resume_token, $remembered_tool_names ) : new Public_Chat_Agent( $settings, $current_page, $persistence, $resume_token, $remembered_tool_names ); } /** * Send message endpoint * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function send_message( WP_REST_Request $request ) { try { $conversation_id = ! empty( $request->get_param( 'conversationId' ) ) ? Sanitization::sanitizeConversationId( $request->get_param( 'conversationId' ) ) : ''; $message = ! empty( $request->get_param( 'message' ) ) ? Sanitization::sanitizeMessage( $request->get_param( 'message' ) ) : ''; $channel = ! empty( $request->get_param( 'channel' ) ) ? Sanitization::sanitizeChannel( $request->get_param( 'channel' ) ) : 'admin'; $mentioned_tools = Mention_Sanitizer::sanitize( $request->get_param( 'mentioned_tools' ) ); $current_page = sanitize_text_field( $request->get_param( 'currentPage' ) ); // Validate message. if ( empty( $message ) ) { return Error_Handler::createRestError( 'aisentic_invalid_message', __( 'Message cannot be empty.', 'aisentic' ) ); } // Get or create conversation. $conversation_repo = new Conversation_Repository(); $message_repo = new Message_Repository(); if ( $conversation_id ) { $conversation = $conversation_repo->findByUuid( $conversation_id ); if ( ! $conversation ) { return Error_Handler::createRestError( 'aisentic_conversation_not_found', __( 'Conversation not found.', 'aisentic' ), null, 404 ); } // Verify the conversation channel matches the requested channel if ( $conversation->channel !== $channel ) { return Error_Handler::createRestError( 'aisentic_forbidden', __( 'You do not have permission to access this conversation.', 'aisentic' ), null, 403 ); } // Public conversations are bound to the creating visitor's session. if ( ! $this->public_session_valid( $channel, $conversation_id ) ) { return Error_Handler::createRestError( 'aisentic_session_mismatch', __( 'This conversation belongs to a different session.', 'aisentic' ), null, 403 ); } } else { // Create new conversation. // Store user ID for both admin and public channels if user is logged in $user_id = get_current_user_id(); $conversation = $conversation_repo->create( $user_id, $channel ); if ( ! $conversation ) { return Error_Handler::createRestError( 'aisentic_conversation_create_failed', __( 'Failed to create conversation.', 'aisentic' ), null, 500 ); } $conversation_id = $conversation->uuid; $this->bind_public_conversation( $channel, $conversation_id ); // Record a one-time chat_opened analytics event for public storefront chats. $this->maybe_record_chat_opened( $channel, $conversation_id ); } // Save user message. $message_metadata = ! empty( $mentioned_tools ) ? [ 'mentioned_tools' => $mentioned_tools ] : null; $this->persist_user_message( $message_repo, $conversation_id, $message, $message_metadata ); // Get message history with increased limit to preserve full context. $messages = $message_repo->getByConversation( $conversation_id, 1000 ); // Convert to agent format (Message objects). $agent_messages = $this->build_agent_messages( $messages, $channel ); // Inject mention context into the last (user) agent message. if ( ! empty( $mentioned_tools ) ) { $context = ( new Mention_Context_Builder( new Mention_Resolver_Registry() ) )->build( $mentioned_tools ); if ( ! empty( $context ) ) { $last_idx = count( $agent_messages ) - 1; $agent_messages[ $last_idx ] = Message::make( MessageRole::USER, $context . "\n\n" . $message ); } } // Prepend product-page context to the latest turn for the public // WooCommerce sales channel (no-op off-channel or when disabled/absent). $agent_messages = $this->maybe_inject_product_context( $agent_messages, $channel, $request->get_param( 'current_product' ), new Settings() ); // Get appropriate agent. The page context is passed to the constructor // so the approval middleware matches the tools the agent will run. $settings = new Settings(); $remembered_tool_names = $this->collect_remembered_tool_names( $messages ); $agent = $this->make_agent( $channel, $settings, $current_page, null, null, $remembered_tool_names ); // Send to agent. In v3 chat() returns a workflow handler; getMessage() // resolves the final assistant message. $response = $agent->chat( $agent_messages )->getMessage(); // Save assistant response. $response_content = $response->getContent(); if ( ! empty( $response_content ) ) { $message_repo->create( $conversation_id, 'assistant', $response_content, $this->tool_activity_metadata( $agent ) ); } // Update conversation timestamp. $conversation_repo->touch( $conversation_id ); // Get updated messages once — reused for count, title check, and response. $all_messages = $message_repo->getByConversation( $conversation_id, 1000 ); $message_count = count( $all_messages ); $conversation = $conversation_repo->findByUuid( $conversation_id ); $title = ! empty( $conversation->title ) ? $conversation->title : ''; if ( 4 === $message_count && empty( $title ) ) { $title = Title_Generator::generateTitle( $conversation_id, 4 ); if ( $title ) { $conversation_repo->update( $conversation_id, [ 'title' => $title ] ); } } return $this->response( [ 'conversationId' => $conversation_id, 'title' => $title, 'messages' => array_map( function ( $msg, $index ) { return $msg->toApiFormat( $index ); }, $all_messages, array_keys( $all_messages ) ), ], __( 'Message sent successfully', 'aisentic' ), 200 ); } catch ( WorkflowInterrupt $interrupt ) { return $this->approval_required_error(); } catch ( \Throwable $e ) { return Error_Handler::exceptionToRestError( $e ); } } /** * Edit message and regenerate response * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function edit_message( WP_REST_Request $request ) { try { $conversation_id = ! empty( $request->get_param( 'conversationId' ) ) ? Sanitization::sanitizeConversationId( $request->get_param( 'conversationId' ) ) : ''; $message_index = ! empty( $request->get_param( 'messageIndex' ) ) ? intval( $request->get_param( 'messageIndex' ) ) : 0; $new_message = ! empty( $request->get_param( 'message' ) ) ? Sanitization::sanitizeMessage( $request->get_param( 'message' ) ) : ''; $channel = ! empty( $request->get_param( 'channel' ) ) ? Sanitization::sanitizeChannel( $request->get_param( 'channel' ) ) : 'admin'; $current_page = sanitize_text_field( $request->get_param( 'currentPage' ) ); // Validate inputs if ( empty( $conversation_id ) || ! is_numeric( $message_index ) || empty( $new_message ) ) { return Error_Handler::createRestError( 'aisentic_invalid_input', __( 'Invalid input parameters.', 'aisentic' ) ); } // Get conversation and verify access $conversation_repo = new Conversation_Repository(); $message_repo = new Message_Repository(); $conversation = $conversation_repo->findByUuid( $conversation_id ); if ( ! $conversation ) { return Error_Handler::createRestError( 'aisentic_conversation_not_found', __( 'Conversation not found.', 'aisentic' ), null, 404 ); } // Verify channel and permissions if ( $conversation->channel !== $channel ) { return Error_Handler::createRestError( 'aisentic_forbidden', __( 'You do not have permission to access this conversation.', 'aisentic' ), null, 403 ); } // Public conversations are bound to the creating visitor's session. if ( ! $this->public_session_valid( $channel, $conversation_id ) ) { return Error_Handler::createRestError( 'aisentic_session_mismatch', __( 'This conversation belongs to a different session.', 'aisentic' ), null, 403 ); } // Delete all messages from the specified index onwards $message_repo->deleteFromIndex( $conversation_id, $message_index ); // Create the edited user message $message_repo->create( $conversation_id, 'user', $new_message ); // Get remaining messages with increased limit to preserve full context $messages = $message_repo->getByConversation( $conversation_id, 1000 ); // Convert to agent format $agent_messages = $this->build_agent_messages( $messages, $channel ); // Prepend product-page context to the latest turn for the public // WooCommerce sales channel (no-op off-channel or when disabled/absent). $agent_messages = $this->maybe_inject_product_context( $agent_messages, $channel, $request->get_param( 'current_product' ), new Settings() ); // Get agent and send message. Page context goes through the constructor // so the approval middleware matches the executable tool set. $settings = new Settings(); $remembered_tool_names = $this->collect_remembered_tool_names( $messages ); $agent = $this->make_agent( $channel, $settings, $current_page, null, null, $remembered_tool_names ); // Get agent response. In v3 chat() returns a workflow handler; // getMessage() resolves the final assistant message. $response = $agent->chat( $agent_messages )->getMessage(); // Save assistant response $response_content = $response->getContent(); if ( ! empty( $response_content ) ) { $message_repo->create( $conversation_id, 'assistant', $response_content, $this->tool_activity_metadata( $agent ) ); } // Update conversation timestamp $conversation_repo->touch( $conversation_id ); // Get updated messages once — reused for response. $all_messages = $message_repo->getByConversation( $conversation_id, 1000 ); // Get conversation title $title = ! empty( $conversation->title ) ? $conversation->title : ''; return $this->response( [ 'conversationId' => $conversation_id, 'title' => $title, 'messages' => array_map( function ( $msg, $index ) { return $msg->toApiFormat( $index ); }, $all_messages, array_keys( $all_messages ) ), ], __( 'Message edited successfully', 'aisentic' ), 200 ); } catch ( WorkflowInterrupt $interrupt ) { return $this->approval_required_error(); } catch ( \Throwable $e ) { return Error_Handler::exceptionToRestError( $e ); } } /** * Rate agent replay * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function rate_agent_replay( WP_REST_Request $request ) { try { $message_index = ! empty( $request->get_param( 'message_index' ) ) ? intval( $request->get_param( 'message_index' ) ) : 0; $is_satisfied = ! empty( $request->get_param( 'is_satisfied' ) ) ? intval( $request->get_param( 'is_satisfied' ) ) : 0; // Validate inputs if ( ! is_numeric( $message_index ) || empty( $is_satisfied ) ) { return Error_Handler::createRestError( 'aisentic_invalid_input', __( 'Invalid input parameters.', 'aisentic' ) ); } // Get message repository $message_repo = new Message_Repository(); // Rate agent replay $result = $message_repo->rateAgentMessage( $message_index, $is_satisfied ); if ( ! $result ) { return Error_Handler::createRestError( 'aisentic_rate_agent_replay_failed', __( 'Failed to rate agent replay.', 'aisentic' ), null, 500 ); } return $this->response( [], __( 'Agent replay rated successfully', 'aisentic' ), 200 ); } catch ( \Throwable $e ) { return Error_Handler::exceptionToRestError( $e ); } } /** * Stream message endpoint (Server-Sent Events) * * @param WP_REST_Request $request Request object. * @return void */ public function stream_message( WP_REST_Request $request ) { // Initialized before the try so the WorkflowInterrupt (tool-approval) catch // block can rely on them even if execution fails before they are assigned. $conversation_id = ''; $message_repo = null; $channel = 'admin'; $current_page = ''; try { $conversation_id = ! empty( $request->get_param( 'conversationId' ) ) ? Sanitization::sanitizeConversationId( $request->get_param( 'conversationId' ) ) : ''; $message = ! empty( $request->get_param( 'message' ) ) ? Sanitization::sanitizeMessage( $request->get_param( 'message' ) ) : ''; $channel = ! empty( $request->get_param( 'channel' ) ) ? Sanitization::sanitizeChannel( $request->get_param( 'channel' ) ) : 'admin'; $mentioned_tools = Mention_Sanitizer::sanitize( $request->get_param( 'mentioned_tools' ) ); $current_page = sanitize_text_field( $request->get_param( 'currentPage' ) ); // Validate message. if ( empty( $message ) ) { wp_send_json_error( [ 'code' => 'aisentic_invalid_message', 'message' => __( 'Message cannot be empty.', 'aisentic' ), ], 400 ); exit; } // Get or create conversation. $conversation_repo = new Conversation_Repository(); $message_repo = new Message_Repository(); if ( $conversation_id ) { $conversation = $conversation_repo->findByUuid( $conversation_id ); if ( ! $conversation ) { wp_send_json_error( [ 'code' => 'aisentic_conversation_not_found', 'message' => __( 'Conversation not found.', 'aisentic' ), ], 404 ); exit; } // Verify the conversation channel matches the requested channel if ( $conversation->channel !== $channel ) { wp_send_json_error( [ 'code' => 'aisentic_forbidden', 'message' => __( 'You do not have permission to access this conversation.', 'aisentic' ), ], 403 ); exit; } // Bind public conversations to the creating visitor's session so a // leaked UUID cannot be continued from another browser. if ( ! $this->public_session_valid( $channel, $conversation_id ) ) { wp_send_json_error( [ 'code' => 'aisentic_session_mismatch', 'message' => __( 'This conversation belongs to a different session.', 'aisentic' ), ], 403 ); exit; } } else { // Create new conversation. // Store user ID for both admin and public channels if user is logged in $user_id = get_current_user_id(); $conversation = $conversation_repo->create( $user_id, $channel ); if ( ! $conversation ) { wp_send_json_error( [ 'code' => 'aisentic_conversation_create_failed', 'message' => __( 'Failed to create conversation.', 'aisentic' ), ], 500 ); exit; } $conversation_id = $conversation->uuid; $this->bind_public_conversation( $channel, $conversation_id ); // Record a one-time chat_opened analytics event for public storefront chats. $this->maybe_record_chat_opened( $channel, $conversation_id ); } // Save user message. $message_metadata = ! empty( $mentioned_tools ) ? [ 'mentioned_tools' => $mentioned_tools ] : null; $this->persist_user_message( $message_repo, $conversation_id, $message, $message_metadata ); // Get message history with increased limit to preserve full context. $messages = $message_repo->getByConversation( $conversation_id, 1000 ); // Convert to agent format (Message objects). $agent_messages = $this->build_agent_messages( $messages, $channel ); // Inject mention context into the last (user) agent message. if ( ! empty( $mentioned_tools ) ) { $context = ( new Mention_Context_Builder( new Mention_Resolver_Registry() ) )->build( $mentioned_tools ); if ( ! empty( $context ) ) { $last_idx = count( $agent_messages ) - 1; $agent_messages[ $last_idx ] = Message::make( MessageRole::USER, $context . "\n\n" . $message ); } } // Prepend product-page context to the latest turn for the public // WooCommerce sales channel (no-op off-channel or when disabled/absent). $agent_messages = $this->maybe_inject_product_context( $agent_messages, $channel, $request->get_param( 'current_product' ), new Settings() ); // Get appropriate agent. A transient-backed persistence lets a // tool-approval interrupt be resumed by the /chat/approve request, and // the page context is passed to the constructor so the approval // middleware matches the tools the workflow will run. $settings = new Settings(); $remembered_tool_names = $this->collect_remembered_tool_names( $messages ); $persistence = new Transient_Workflow_Persistence(); $agent = $this->make_agent( $channel, $settings, $current_page, $persistence, null, $remembered_tool_names ); // --- Disable output buffering --- if ( function_exists( 'apache_setenv' ) ) { apache_setenv( 'no-gzip', '1' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.runtime_configuration_apache_setenv } while ( ob_get_level() > 0 ) { ob_end_clean(); } ob_implicit_flush( true ); // Take over abort handling so a mid-stream client disconnect cannot kill // the script between emitting output and persisting the message. The // closed connection is detected explicitly in stream_agent_response(). ignore_user_abort( true ); // --- SSE headers --- header( 'Content-Type: text/event-stream; charset=UTF-8' ); header( 'Cache-Control: no-cache, no-store' ); header( 'Connection: keep-alive' ); header( 'X-Accel-Buffering: no' ); // Stream response. A tool requiring approval raises a WorkflowInterrupt, // caught below to drive the human-in-the-loop approval flow. $full_content = $this->stream_agent_response( $agent->stream( $agent_messages ), 'public' === $channel ? $conversation_id : '' ); // Persist assistant response if ( ! empty( $full_content ) ) { $message_repo->create( $conversation_id, 'assistant', $full_content, $this->tool_activity_metadata( $agent ) ); } // Update conversation timestamp $conversation_repo->touch( $conversation_id ); // Get updated messages once — reused for count, title check, and SSE done event. $all_messages = $message_repo->getByConversation( $conversation_id, 1000 ); $message_count = count( $all_messages ); $conversation = $conversation_repo->findByUuid( $conversation_id ); $title = ! empty( $conversation->title ) ? $conversation->title : ''; if ( 4 === $message_count && empty( $title ) ) { $title = Title_Generator::generateTitle( $conversation_id, 4 ); if ( $title ) { $conversation_repo->update( $conversation_id, [ 'title' => $title ] ); } } echo 'data: ' . wp_json_encode( [ 'type' => 'done', 'conversationId' => $conversation_id, 'title' => $title, 'messages' => array_map( function ( $msg, $index ) { return $msg->toApiFormat( $index ); }, $all_messages, array_keys( $all_messages ) ), ] ) . "\n\n"; flush(); } catch ( WorkflowInterrupt $interrupt ) { $this->emit_tool_approval_request( $interrupt, $conversation_id, $channel, $current_page, $message_repo ); } catch ( \Throwable $e ) { $this->emit_stream_exception( $e, 'Chat stream failed', __( 'Something went wrong while generating the response. Please try again.', 'aisentic' ) ); // Emit a terminal 'done' too so clients that resolve on 'done' don't hang // waiting for the socket to close; the preceding 'error' event carries the // failure for clients that handle it. Keeps the SSE contract symmetric. $this->emit_done( $conversation_id, '', [] ); } exit; // CRITICAL: prevents WP REST from wrapping output in JSON } /** * Approve or reject a pending tool call (human-in-the-loop). * * On approval the interrupted agent workflow is resumed from its persisted * state: the previously gated tool executes and the agent streams its * confirmation. On rejection the persisted workflow is discarded (no LLM * call) and a static acknowledgment is returned. * * @param WP_REST_Request $request Request object. * @return void */ public function approve_tool_call( WP_REST_Request $request ) { $pending_id = sanitize_text_field( $request->get_param( 'pending_id' ) ?? '' ); $action_decisions = $request->get_param( 'action_decisions' ) ?? []; if ( ! is_array( $action_decisions ) ) { $action_decisions = []; } if ( empty( $pending_id ) ) { wp_send_json_error( [ 'code' => 'aisentic_invalid_input', 'message' => __( 'pending_id is required.', 'aisentic' ), ], 400 ); exit; } // Load and delete the transient atomically $transient_key = 'aisentic_tool_approval_' . $pending_id; $pending = get_transient( $transient_key ); if ( false === $pending ) { // The transient is gone, so the workflow can never be resumed. Stamp // the stored card as expired: without this the next page load would // rehydrate it as 'pending' and offer buttons that can only 404 again. $this->mark_pending_expired( new Message_Repository(), $pending_id ); wp_send_json_error( [ 'code' => 'aisentic_approval_expired', 'message' => __( 'This confirmation expired before it was answered, so nothing was done. Ask again in the chat to redo it.', 'aisentic' ), ], 404 ); exit; } // Security: ensure this approval belongs to the requester. Anonymous public // approvals have user_id=0, so the logged-in-user check (0 !== 0) would pass // for ANY visitor — bind them to the session that created the conversation // instead. Admin approvals keep the user-id ownership check. $pending_channel = $pending['channel'] ?? 'admin'; $owns_approval = 'public' === $pending_channel ? $this->validate_conversation_session( (string) ( $pending['conversation_id'] ?? '' ), $this->ensure_visitor_token() ) : get_current_user_id() === (int) $pending['user_id']; if ( ! $owns_approval ) { wp_send_json_error( [ 'code' => 'aisentic_forbidden', 'message' => __( 'You do not have permission to approve this action.', 'aisentic' ), ], 403 ); exit; } delete_transient( $transient_key ); $workflow_token = $pending['workflow_token']; $action_ids = $pending['action_ids'] ?? []; $conversation_id = $pending['conversation_id']; $channel = $pending['channel']; $current_page = $pending['current_page'] ?? ''; $conversation_repo = new Conversation_Repository(); $message_repo = new Message_Repository(); $persistence = new Transient_Workflow_Persistence(); // --- Disable output buffering --- if ( function_exists( 'apache_setenv' ) ) { apache_setenv( 'no-gzip', '1' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.runtime_configuration_apache_setenv } while ( ob_get_level() > 0 ) { ob_end_clean(); } ob_implicit_flush( true ); // Take over abort handling so a mid-stream client disconnect cannot kill // the script between emitting output and persisting the message. The // closed connection is detected explicitly in stream_agent_response(). ignore_user_abort( true ); // --- SSE headers --- header( 'Content-Type: text/event-stream; charset=UTF-8' ); header( 'Cache-Control: no-cache, no-store' ); header( 'Connection: keep-alive' ); header( 'X-Accel-Buffering: no' ); try { // Separate action IDs into approved and rejected based on decisions. $approved_action_ids = []; $rejected_action_ids = []; foreach ( $action_ids as $id ) { // Fail-closed: a missing decision defaults to rejected. This is // the safe direction for a human-in-the-loop gate and prevents // legacy approval cards (whose synthesized action_id is the // workflow token, not the real tool call id) from silently // approving actions the admin declined. $approved = isset( $action_decisions[ $id ] ) ? (bool) $action_decisions[ $id ] : false; if ( $approved ) { $approved_action_ids[] = $id; } else { $rejected_action_ids[] = $id; } } // All rejected: discard the persisted workflow and return a static // acknowledgment without a further LLM call. if ( empty( $approved_action_ids ) ) { $this->mark_pending_status( $message_repo, $pending, 'rejected' ); $persistence->delete( $workflow_token ); $message_repo->create( $conversation_id, 'assistant', __( 'Understood. The operation has been cancelled as requested.', 'aisentic' ) ); $conversation_repo->touch( $conversation_id ); $conversation = $conversation_repo->findByUuid( $conversation_id ); $title = ! empty( $conversation->title ) ? $conversation->title : ''; $all_messages = $message_repo->getByConversation( $conversation_id, 1000 ); $this->emit_done( $conversation_id, $title, $all_messages ); exit; } // Approval: verify the interrupted workflow is still resumable BEFORE // writing any messages. If it has expired, we must not leave a decline // note claiming the remaining actions will run when they cannot. if ( ! $persistence->has( $workflow_token ) ) { $this->mark_pending_status( $message_repo, $pending, 'rejected' ); $this->emit_sse_error( __( 'This approval request has expired. Please ask again.', 'aisentic' ) ); exit; } $this->mark_pending_status( $message_repo, $pending, 'approved' ); // Partial rejection: note the declined actions in the conversation. if ( ! empty( $rejected_action_ids ) ) { $decline_note = sprintf( /* translators: %d: number of actions the admin declined. */ _n( '%d action was declined — only the remaining actions will be executed.', '%d actions were declined — only the remaining actions will be executed.', count( $rejected_action_ids ), 'aisentic' ), count( $rejected_action_ids ) ); $message_repo->create( $conversation_id, 'assistant', $decline_note ); } // Rebuild the decided request. Both approved and rejected actions must // be present: NeuronAI's ToolApproval middleware only swaps a tool's // callback to a rejection handler when the action is in the resume // request AND isRejected(). Actions absent from the request execute // normally (i.e. as if approved), so omitting rejected actions would // cause declined tools to run. $actions = array_map( function ( $id ) { $action = new Action( (string) $id, 'approved-tool' ); $action->approve(); return $action; }, $approved_action_ids ); foreach ( $rejected_action_ids as $id ) { $action = new Action( (string) $id, 'declined-tool' ); $action->reject( __( 'Declined by admin', 'aisentic' ) ); $actions[] = $action; } $decision = new ApprovalRequest( 'Tool approval decision', $actions ); $settings = new Settings(); $agent = $this->make_agent( $channel, $settings, $current_page, $persistence, $workflow_token ); $full_content = $this->stream_agent_response( $agent->stream( [], $decision ), 'public' === $channel ? $conversation_id : '' ); // Persist the assistant response, tagging it with the executed tool // outcome so later turns know the action is already done (preventing // duplicate creates). Stored in metadata only, never shown in the UI. if ( ! empty( $full_content ) ) { $message_repo->create( $conversation_id, 'assistant', $full_content, $this->executed_tool_metadata( $agent ) ); } // Update conversation timestamp $conversation_repo->touch( $conversation_id ); // Get updated messages once — reused for count, title check, and SSE done event. $all_messages = $message_repo->getByConversation( $conversation_id, 1000 ); $message_count = count( $all_messages ); $conversation = $conversation_repo->findByUuid( $conversation_id ); $title = ! empty( $conversation->title ) ? $conversation->title : ''; if ( 4 === $message_count && empty( $title ) ) { $title = Title_Generator::generateTitle( $conversation_id, 4 ); if ( $title ) { $conversation_repo->update( $conversation_id, [ 'title' => $title ] ); } } $this->emit_done( $conversation_id, $title, $all_messages ); } catch ( WorkflowInterrupt $interrupt ) { if ( '' !== $this->last_stream_content ) { $message_repo->create( $conversation_id, 'assistant', $this->last_stream_content, $this->executed_tool_metadata( $agent ) ); } // Emit the next approval card — exactly as stream_message() does for the // first wave — so the chain can continue instead of falling into the // generic catch below and surfacing as a spurious "Something went wrong". $this->emit_tool_approval_request( $interrupt, $conversation_id, $channel, $current_page, $message_repo ); } catch ( \Throwable $e ) { $this->emit_stream_exception( $e, 'Tool approval resume failed', __( 'Something went wrong while completing the action. Please try again.', 'aisentic' ) ); } exit; } /** * Record a one-time chat_opened analytics event for public (storefront) chats. * * Fired once per conversation and only for the public channel, so the * WooCommerce sales dashboard can measure how many shoppers started a chat. * Keyed on the conversation UUID so the whole funnel (chat -> search -> card -> * add-to-cart) correlates by session. * * @param string $channel Conversation channel. * @param string $conversation_id Conversation UUID (used as the analytics session id). * @return void */ private function maybe_record_chat_opened( string $channel, string $conversation_id ): void { if ( 'public' !== $channel || empty( $conversation_id ) ) { return; } ( new Wc_Analytics_Repository() )->record( 'chat_opened', $conversation_id ); } /** * Stream an agent handler's events to the client as SSE and return the * accumulated assistant text. * * Translates NeuronAI v3 stream chunks into the SSE contract the frontend * expects: ToolCallChunk -> tool_call_start, ToolResultChunk -> tool_call_end, * TextChunk -> chunk. A WorkflowInterrupt raised mid-stream (tool approval) * propagates to the caller. * * @param AgentHandler $handler The streaming agent handler. * @param string $session_id Public conversation UUID used as the analytics * session id. Empty for admin (no analytics recorded). * @return string The concatenated assistant text. * @throws \Throwable Re-thrown after closing a dangling tool indicator; the caller * drives the approval (WorkflowInterrupt) or error flow. */ private function stream_agent_response( AgentHandler $handler, string $session_id = '' ): string { $full_content = ''; $is_tool_calling = false; $this->last_stream_content = ''; try { return $this->consume_stream( $handler, $session_id, $full_content, $is_tool_calling ); } finally { $this->last_stream_content = $full_content; } } /** * Pull chunks from the agent stream, emit SSE events, and accumulate text. * * Split out from stream_agent_response() so the accumulated $full_content is * visible to the finally block even when the generator throws mid-stream. * * @param AgentHandler $handler Streaming agent handler. * @param string $session_id Public conversation UUID for analytics; empty for admin. * @param string $full_content Accumulator, updated by reference. * @param bool $is_tool_calling Tool-call SSE state, by reference. * @return string The fully accumulated assistant text. * @throws \Throwable Re-thrown after closing a dangling tool indicator; the caller drives the approval or error flow. */ private function consume_stream( AgentHandler $handler, string $session_id, string &$full_content, bool &$is_tool_calling ): string { // Text after a tool call is a new LLM round. Without a break, the two // rounds join mid-sentence ("coming upHere are"). $needs_break = false; // The model sometimes repeats the same call in one turn. One card each // is enough, so remember which tool + inputs already showed one. $shown_cards = []; try { foreach ( $handler->events() as $chunk ) { // Stop pulling tokens (and triggering further tool calls) once the client // has disconnected. connection_aborted() only flips after a write to the // dead socket following a flush() — which every branch below performs — so // it is observed on the iteration after the client leaves. The partial // $full_content gathered so far is still returned and persisted by the // caller, so work already paid for is not lost. if ( 1 === connection_aborted() ) { break; } if ( $chunk instanceof ToolCallChunk ) { // Every tool that starts says what it is doing ("Checking free times…"). $is_tool_calling = true; echo 'data: ' . wp_json_encode( Chat_Card_Payload::tool_start( $chunk->tool ) ) . "\n\n"; flush(); continue; } if ( $chunk instanceof ToolResultChunk ) { if ( $is_tool_calling ) { $is_tool_calling = false; echo 'data: ' . wp_json_encode( [ 'type' => 'tool_call_end' ] ) . "\n\n"; flush(); } $needs_break = '' !== $full_content; $tool_name = $chunk->tool->getName(); $result_str = $chunk->tool->getResult(); $result_data = json_decode( $result_str, true ); $card_key = $tool_name . '|' . wp_json_encode( $chunk->tool->getInputs() ); $card_shown = isset( $shown_cards[ $card_key ] ); $shown_cards[ $card_key ] = true; // Generic card path: any tool with Chat_Card_Contract. Taken even // when already shown, so a stale card never leaks into a later run. // Repeats are matched on the card itself, not the tool inputs. $card = Chat_Card_Payload::from_tool( $chunk->tool, $result_data ); if ( null !== $card && ! Chat_Card_Payload::is_repeat( $card, $shown_cards ) ) { echo 'data: ' . wp_json_encode( $card ) . "\n\n"; flush(); } // Record search analytics for the public sales agent, keyed on the // conversation session. Done here (not in the tool) because the tool // cannot see the session id, and this fires whether or not the tool // served the result from its transient cache. if ( '' !== $session_id && 'wc-product-search' === $tool_name && is_array( $result_data ) ) { $analytics = new Wc_Analytics_Repository(); $analytics->record( 'search_called', $session_id ); if ( (int) ( $result_data['total'] ?? 0 ) > 0 ) { $analytics->record( 'search_found', $session_id ); } } // Emit structured product data (images, variations) that the agent's prose text chunks omit. if ( 'wc-product-search' === $tool_name && ! $card_shown && is_array( $result_data ) && ! empty( $result_data['products'] ) ) { // Agent-facing result is a lean projection; pull the rich one off the tool instance for the frontend. $frontend_data = $result_data; if ( $chunk->tool instanceof Wc_Product_Search_Tool ) { // Match on the full input signature so multiple searches in one // turn (even same query, different filters) never cross their rich // payloads. Fall back to the query for older cached results that // predate the signature field. $signature = $result_data['signature'] ?? ''; $rich = '' !== $signature ? $chunk->tool->get_frontend_result( (string) $signature ) : null; if ( ! is_array( $rich ) ) { $last = $chunk->tool->get_last_frontend_result(); if ( is_array( $last ) && ( $last['query'] ?? null ) === ( $result_data['query'] ?? null ) ) { $rich = $last; } } if ( is_array( $rich ) && ! empty( $rich['products'] ) ) { $frontend_data = $rich; } } echo 'data: ' . wp_json_encode( [ 'type' => 'product_results', 'ui_hint' => $frontend_data['ui_hint'] ?? 'product_carousel', 'products' => $frontend_data['products'], 'query' => $frontend_data['query'] ?? '', ] ) . "\n\n"; flush(); } // Emit structured event data (images, ticket list) that the agent's prose text chunks omit. if ( 'eventin-event-search' === $tool_name && ! $card_shown && is_array( $result_data ) && ! empty( $result_data['events'] ) ) { // Agent-facing result is a lean projection; pull the rich one off the tool instance for the frontend. $frontend_data = $result_data; if ( $chunk->tool instanceof Eventin_Event_Search_Tool ) { // Match on the full input signature so multiple searches in one // turn never cross their rich payloads. $signature = $result_data['signature'] ?? ''; $rich = '' !== $signature ? $chunk->tool->get_frontend_result( (string) $signature ) : null; if ( ! is_array( $rich ) ) { $rich = $chunk->tool->get_last_frontend_result(); } if ( is_array( $rich ) && ! empty( $rich['events'] ) ) { $frontend_data = $rich; } } echo 'data: ' . wp_json_encode( [ 'type' => 'event_results', 'ui_hint' => $frontend_data['ui_hint'] ?? 'event_carousel', 'events' => $frontend_data['events'], 'query' => $frontend_data['query'] ?? '', ] ) . "\n\n"; flush(); } // A ticket card. if ( 'eventin-ticket-action' === $tool_name && ! $card_shown && is_array( $result_data ) && ! empty( $result_data['ok'] ) && ! empty( $result_data['mode'] ) ) { echo 'data: ' . wp_json_encode( [ 'type' => 'ticket_action', 'mode' => (string) $result_data['mode'], 'action_card' => (string) ( $result_data['action_card'] ?? 'view_event' ), 'checkout_payload' => $result_data['checkout_payload'] ?? null, 'fallback_url' => (string) ( $result_data['fallback_url'] ?? '' ), 'event_summary' => $result_data['event_summary'] ?? [], 'ticket_summary' => $result_data['ticket_summary'] ?? [], ] ) . "\n\n"; flush(); } // If the tool result contains a cart_action_payload, emit a cart_action SSE event. if ( ! $card_shown && is_array( $result_data ) && ! empty( $result_data['cart_action_payload'] ) && ! empty( $result_data['ok'] ) ) { $cart_product_id = (int) $result_data['cart_action_payload']['product_id']; $cart_quantity = (int) ( $result_data['cart_action_payload']['quantity'] ?? 1 ); // Record that a cart card was shown so the dashboard can measure the // card -> add-to-cart conversion rate. if ( '' !== $session_id ) { ( new Wc_Analytics_Repository() )->record( 'cart_card_rendered', $session_id, $cart_product_id, $cart_quantity ); } echo 'data: ' . wp_json_encode( [ 'type' => 'cart_action', 'action' => $result_data['action_card'] ?? 'add_to_cart', 'product_id' => $cart_product_id, 'quantity' => $cart_quantity, 'variation_id' => $result_data['cart_action_payload']['variation_id'] ?? null, 'product' => $result_data['product_summary'] ?? [], 'reason' => $result_data['reason'] ?? null, ] ) . "\n\n"; flush(); } continue; } if ( ! $chunk instanceof TextChunk ) { // Ignore non-content workflow events (node lifecycle, reasoning, etc.). continue; } $str = $chunk->content; if ( '' === $str ) { continue; } // Skip the break when either side already has whitespace there. if ( $needs_break && '' !== trim( substr( $full_content, -1 ) ) && '' !== trim( substr( $str, 0, 1 ) ) ) { $str = "\n\n" . $str; } $needs_break = false; $full_content .= $str; echo 'data: ' . wp_json_encode( [ 'type' => 'chunk', 'content' => $str, ] ) . "\n\n"; flush(); } } catch ( \Throwable $e ) { // A tool/LLM failure mid-stream (but NOT an approval interrupt, which // drives its own UI) leaves the client's tool spinner open — close it // before the error surfaces, then re-throw so stream_message drives the // error / approval flow unchanged. if ( $is_tool_calling && ! $e instanceof WorkflowInterrupt ) { echo 'data: ' . wp_json_encode( [ 'type' => 'tool_call_end' ] ) . "\n\n"; flush(); } throw $e; } return $full_content; } /** * Emit the terminal SSE 'done' event with the refreshed conversation. * * @param string $conversation_id Conversation UUID. * @param string $title Conversation title. * @param array $all_messages Stored messages, oldest-first. * @return void */ private function emit_done( string $conversation_id, string $title, array $all_messages ): void { echo 'data: ' . wp_json_encode( [ 'type' => 'done', 'conversationId' => $conversation_id, 'title' => $title, 'messages' => array_map( function ( $msg, $index ) { return $msg->toApiFormat( $index ); }, $all_messages, array_keys( $all_messages ) ), ] ) . "\n\n"; flush(); } /** * Emit an SSE 'error' event with a client-safe message. * * Internal exception details must never be streamed to the client; callers * log the real cause and pass a generic, translatable message here. * * @param string $message Client-safe error message. * @return void */ private function emit_sse_error( string $message ): void { echo 'data: ' . wp_json_encode( [ 'type' => 'error', 'message' => $message, ] ) . "\n\n"; flush(); } /** * Read (or mint) the anonymous visitor's session token from a cookie. * * Public conversations are bound to the browser that created them via this * token. Minting also sets the cookie for future requests and populates * $_COOKIE so the token is usable within the current request. Callers on the * streaming endpoints must invoke this BEFORE any output is sent. * * @return string The visitor session token. */ private function ensure_visitor_token(): string { $token = isset( $_COOKIE[ self::VISITOR_COOKIE ] ) ? sanitize_text_field( wp_unslash( $_COOKIE[ self::VISITOR_COOKIE ] ) ) : ''; if ( strlen( $token ) < 20 ) { $token = wp_generate_password( 32, false ); // Usable within this same request (setcookie only affects the next one). $_COOKIE[ self::VISITOR_COOKIE ] = $token; if ( ! headers_sent() ) { setcookie( self::VISITOR_COOKIE, $token, [ 'expires' => time() + self::SESSION_TTL, 'path' => defined( 'COOKIEPATH' ) && COOKIEPATH ? COOKIEPATH : '/', 'domain' => defined( 'COOKIE_DOMAIN' ) ? COOKIE_DOMAIN : '', 'secure' => is_ssl(), 'httponly' => true, 'samesite' => 'Lax', ] ); } } return $token; } /** * Deterministic binding token tying a conversation UUID to a visitor token. * * Keyed with wp_salt so the stored value cannot be forged from the UUID alone. * * @param string $conversation_id Conversation UUID. * @param string $visitor_token Visitor session token. * @return string */ private function conversation_binding_token( string $conversation_id, string $visitor_token ): string { return hash_hmac( 'sha256', $conversation_id, $visitor_token . '|' . wp_salt( 'auth' ) ); } /** * Persist the binding between a public conversation and the current visitor. * * @param string $conversation_id Conversation UUID. * @param string $visitor_token Visitor session token. * @return void */ private function bind_conversation_session( string $conversation_id, string $visitor_token ): void { set_transient( 'aisentic_conv_session_' . $conversation_id, $this->conversation_binding_token( $conversation_id, $visitor_token ), self::SESSION_TTL ); } /** * Whether the current visitor may access an existing public conversation. * * A conversation created before this binding existed (no stored token) is * trusted-on-first-use: it is bound to the current visitor now so a later, * different visitor holding the same UUID is rejected. * * @param string $conversation_id Conversation UUID. * @param string $visitor_token Visitor session token. * @return bool True when access is allowed. */ private function validate_conversation_session( string $conversation_id, string $visitor_token ): bool { $stored = get_transient( 'aisentic_conv_session_' . $conversation_id ); if ( false === $stored || '' === $stored ) { $this->bind_conversation_session( $conversation_id, $visitor_token ); return true; } return hash_equals( (string) $stored, $this->conversation_binding_token( $conversation_id, $visitor_token ) ); } /** * Whether the current visitor may access an existing conversation. * * Always true for non-public channels (admin access is already gated by * manage_options). For public, validates the visitor's session token against * the conversation's stored binding. Callers respond in their own idiom * (REST error vs. wp_send_json) on a false result. * * @param string $channel Conversation channel. * @param string $conversation_id Conversation UUID. * @return bool */ private function public_session_valid( string $channel, string $conversation_id ): bool { if ( 'public' !== $channel ) { return true; } return $this->validate_conversation_session( $conversation_id, $this->ensure_visitor_token() ); } /** * Bind a newly created public conversation to the current visitor. No-op for * non-public channels. * * @param string $channel Conversation channel. * @param string $conversation_id Conversation UUID. * @return void */ private function bind_public_conversation( string $channel, string $conversation_id ): void { if ( 'public' === $channel ) { $this->bind_conversation_session( $conversation_id, $this->ensure_visitor_token() ); } } /** * Log the real cause and emit a client-safe SSE error for a caught streaming * exception. Shared by the streaming and approval-resume catch blocks so the * mapping and logging stay in one place. * * @param \Throwable $e The caught exception. * @param string $context Log prefix identifying the failing path. * @param string $generic Fallback message for unrecognised errors. * @return void */ private function emit_stream_exception( \Throwable $e, string $context, string $generic ): void { Log::error( $context . ': ' . $e->getMessage() ); $this->emit_sse_error( Ai_Error_Message::from_throwable( $e, $generic ) ); } /** * REST error returned when a non-streaming request triggers a tool that * requires human approval. * * The human-in-the-loop approval flow is only available over the streaming * endpoint, which surfaces an approval card and can resume the workflow. The * non-streaming send/edit endpoints build the agent without resumable * persistence, so they report that confirmation is required rather than * failing with a raw framework error. * * @return WP_Error */ private function approval_required_error(): WP_Error { return Error_Handler::createRestError( 'aisentic_approval_required', __( 'This action needs your confirmation. Please send the request again from the chat to review and approve it.', 'aisentic' ), null, 409 ); } /** * Stamp a stored approval card as expired, looked up by its pending id. * * The normal status update goes through mark_pending_status(), which reads * the message id out of the approval transient. On the expiry path that * transient is exactly what is missing, so the placeholder is located by the * pending id embedded in its metadata instead. * * @param Message_Repository $message_repo Message repository. * @param string $pending_id Workflow id from the expired approval. * @return void */ private function mark_pending_expired( Message_Repository $message_repo, string $pending_id ): void { $placeholder = $message_repo->find_by_pending_approval_id( $pending_id ); if ( ! $placeholder || empty( $placeholder->metadata['pending_approval'] ) ) { return; } // Never downgrade a decision that was already recorded. if ( 'pending' !== ( $placeholder->metadata['pending_approval']['status'] ?? 'pending' ) ) { return; } $this->mark_pending_status( $message_repo, [ 'message_id' => $placeholder->id ], 'expired', $placeholder ); } /** * Update a pending-approval placeholder message to a resolved status. * * @param Message_Repository $message_repo Message repository. * @param array $pending Pending-approval transient payload. * @param string $status New status ('approved', 'rejected' or 'expired'). * @param Stored_Message|null $placeholder_msg Already-loaded placeholder, when available. * @return void */ private function mark_pending_status( Message_Repository $message_repo, array $pending, string $status, ?Stored_Message $placeholder_msg = null ): void { if ( empty( $pending['message_id'] ) ) { return; } $placeholder_msg = $placeholder_msg ?? $message_repo->findById( (int) $pending['message_id'] ); if ( $placeholder_msg && ! empty( $placeholder_msg->metadata['pending_approval'] ) ) { $updated_metadata = $placeholder_msg->metadata; $updated_metadata['pending_approval']['status'] = $status; $message_repo->update_metadata( (int) $pending['message_id'], $updated_metadata ); } } /** * Build the approval-card fields shown to the user for a tool-approval * interrupt. * * Returns a structured array with individually identifiable tool calls * so the frontend can render per-item Approve/Decline decisions. * * @param Action[] $actions Pending approval actions. * @param array $tools_by_id Live tool instances keyed by call id. * @return array{tool_label: string, tool_calls: array} */ private function build_approval_card( array $actions, array $tools_by_id ): array { $tool_calls = []; foreach ( $actions as $action ) { $tool = $tools_by_id[ $action->id ] ?? null; $label = $tool instanceof Approvable_Tool_Contract ? $tool->get_approval_label() : $action->name; $summary = $tool instanceof Approvable_Tool_Contract ? $tool->format_approval_summary() : ''; $inputs = $tool instanceof Approvable_Tool_Contract ? $tool->get_approval_inputs() : ( null !== $tool ? $tool->getInputs() : [] ); $tool_calls[] = [ 'action_id' => $action->id, 'tool_name' => $action->name, 'tool_label' => $label, 'tool_summary' => $summary, 'tool_inputs' => $inputs, ]; } if ( 1 === count( $tool_calls ) ) { $tool_label = $tool_calls[0]['tool_label']; } else { /* translators: %d: number of tool actions awaiting approval. */ $tool_label = sprintf( __( '%d actions require approval', 'aisentic' ), count( $tool_calls ) ); } return [ 'tool_label' => $tool_label, 'tool_calls' => $tool_calls, ]; } /** * Handle a tool-approval WorkflowInterrupt raised during streaming. * * Persists a placeholder assistant message and the app-level resume context, * then emits the tool_approval_request SSE event so the frontend can render * the approval card. The serialized workflow state itself is stored by the * framework persistence keyed by the workflow id; this records only the * context the /chat/approve request needs to resume it. * * @param WorkflowInterrupt $interrupt The interrupt carrying the approval request. * @param string $conversation_id Conversation UUID. * @param string $channel Conversation channel. * @param string $current_page WordPress screen ID context. * @param Message_Repository|null $message_repo Message repository. * @return void */ private function emit_tool_approval_request( WorkflowInterrupt $interrupt, string $conversation_id, string $channel, string $current_page, ?Message_Repository $message_repo ): void { if ( empty( $conversation_id ) || null === $message_repo ) { $this->emit_sse_error( __( 'Failed to process approval request.', 'aisentic' ) ); return; } $token = $interrupt->getWorkflowId(); $request = $interrupt->getRequest(); $actions = $request instanceof ApprovalRequest ? $request->getActions() : []; if ( empty( $actions ) ) { $this->emit_sse_error( __( 'No action requires approval.', 'aisentic' ) ); return; } // Map the live tool instances by call id so the rich approval card // (label, summary, resolved inputs) can be built from the Approvable tool. $tools_by_id = []; $event = $interrupt->getEvent(); if ( $event instanceof ToolCallEvent ) { foreach ( $event->toolCallMessage->getTools() as $tool ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase if ( null !== $tool->getCallId() ) { $tools_by_id[ $tool->getCallId() ] = $tool; } } } // Disclose every pending action with per-item detail. $card = $this->build_approval_card( $actions, $tools_by_id ); $tool_label = $card['tool_label']; $tool_calls = $card['tool_calls']; // Placeholder assistant message so the approval card survives a refresh. $placeholder = $message_repo->create( $conversation_id, 'assistant', '', [ 'pending_approval' => [ 'pending_id' => $token, 'tool_label' => $tool_label, 'tool_calls' => $tool_calls, 'status' => 'pending', ], ] ); // App-level resume context. This record and the serialized workflow are two // halves of one resumable approval, so both take their TTL from // Transient_Workflow_Persistence::ttl() — whichever expired first would // strand the other. set_transient( 'aisentic_tool_approval_' . $token, [ 'workflow_token' => $token, 'action_ids' => array_map( fn( $a ) => $a->id, $actions ), 'conversation_id' => $conversation_id, 'channel' => $channel, 'current_page' => $current_page, 'user_id' => get_current_user_id(), 'message_id' => $placeholder ? $placeholder->id : null, ], Transient_Workflow_Persistence::ttl() ); echo 'data: ' . wp_json_encode( [ 'type' => 'tool_approval_request', 'pending_id' => $token, 'tool_label' => $tool_label, 'tool_calls' => $tool_calls, ] ) . "\n\n"; flush(); } /** * Build metadata for the assistant message after an approved tool runs. * * Records the full tool activity (so reads/follow-up calls are reused on * later turns) and additionally tags the approved write tool under * 'executed_tool' so the agent does not repeat it. The write tool is * identified by name — the gated tool runs alongside any follow-up reads in * the same resumed turn, so picking the last activity entry would often tag * the wrong tool. * * @param mixed $agent The agent that handled the resume. * @return array|null Metadata array, or null when no tool ran. */ private function executed_tool_metadata( $agent ): ?array { if ( ! $agent instanceof \Aisentic\Agent\Abstract_Agent ) { return null; } $activity = $agent->get_tool_activity(); if ( empty( $activity ) ) { return null; } $metadata = [ 'tool_activity' => $activity ]; $approvable = $agent->get_approvable_tool_names(); foreach ( $activity as $entry ) { if ( in_array( $entry['name'] ?? '', $approvable, true ) ) { $result = $entry['result'] ?? ''; $decoded = is_string( $result ) ? json_decode( $result, true ) : null; $metadata['executed_tool'] = [ 'name' => $entry['name'], 'result' => ( null === $decoded ) ? $result : $decoded, ]; break; } } return $metadata; } /** * Build assistant-message metadata capturing the tools the agent ran this * turn, so later turns retain a record of what was fetched or done. * * @param mixed $agent The agent that handled the turn. * @return array|null Metadata array, or null when no tools ran. */ private function tool_activity_metadata( $agent ): ?array { if ( ! $agent instanceof \Aisentic\Agent\Abstract_Agent ) { return null; } $activity = $agent->get_tool_activity(); if ( empty( $activity ) ) { return null; } return [ 'tool_activity' => $activity ]; } /** * Collect the names of tools the agent already used or discovered in this * conversation. * * Read from the persisted assistant-message metadata (tool_activity and * executed_tool). The agent pre-loads the matching integration tools on * later turns, so the model can call them directly instead of failing with * "non-existing tool" when it reuses a previously discovered tool name. * * A tool the model merely searched for — e.g. it proposed a plan and asked * for confirmation before calling a write tool — never appears in * tool_activity/executed_tool, since those only record tools that actually * ran. Without also remembering searched-but-not-yet-called tools, the "yes" * that confirms the plan makes the model call that tool directly (it is * already named in the conversation) and fails with "non-existing tool" * because it was never re-discovered this turn. tool_search's own result — * "Found N tool(s):\n- name: description..." — is captured as a normal * tool_activity entry (ToolNode emits 'tool-called' for every executed * tool, including the built-in tool_search), so parsing it recovers every * name the model has ever seen, not just ones it went on to call. * * @param array $messages Message list from the repository. * @return string[] */ private function collect_remembered_tool_names( array $messages ): array { $names = []; foreach ( $messages as $msg ) { $activity = $msg->metadata['tool_activity'] ?? null; if ( is_array( $activity ) ) { foreach ( $activity as $entry ) { $name = $entry['name'] ?? ''; if ( is_string( $name ) && '' !== $name ) { $names[ $name ] = $name; } if ( 'tool_search' === $name && is_string( $entry['result'] ?? null ) ) { foreach ( $this->parse_tool_search_result( $entry['result'] ) as $found ) { $names[ $found ] = $found; } } } } $executed = $msg->metadata['executed_tool']['name'] ?? ''; if ( is_string( $executed ) && '' !== $executed ) { $names[ $executed ] = $executed; } } return array_values( $names ); } /** * Extract tool names from a tool_search result string. * * Matches NeuronAI's ToolSearchTool output format: one "- name: description" * line per discovered tool. * * @param string $result Raw tool_search tool result. * @return string[] */ private function parse_tool_search_result( string $result ): array { if ( ! preg_match_all( '/^- ([a-zA-Z0-9_-]+):/m', $result, $matches ) ) { return []; } return $matches[1]; } /** * Persist a new user message, merging into a dangling one when needed. * * A turn whose stream failed (tool error, provider hiccup) leaves its user * message without an assistant reply. Inserting the retry as another user * message produces two consecutive user messages, which the LLM provider * rejects ("expected role assistant, got user") — permanently bricking the * conversation. Instead the new message is merged into the last user * message so the sequence stays valid and the agent sees the full retry * context. * * @param Message_Repository $message_repo Message repository. * @param string $conversation_id Conversation UUID. * @param string $message New user message content. * @param array|null $metadata New message metadata. * @return void */ private function persist_user_message( Message_Repository $message_repo, string $conversation_id, string $message, ?array $metadata = null ): void { $last = $message_repo->get_last_message( $conversation_id ); if ( $last && 'user' === $last->role ) { // "Try again" resends the same text. It is already saved, so adding // it again would show the question twice (or more) in the chat. $previous = trim( (string) $last->content ); $retry = trim( $message ); if ( $previous === $retry || str_ends_with( $previous, "\n\n" . $retry ) ) { return; } $merged_metadata = $metadata; if ( is_array( $last->metadata ) ) { $merged_metadata = array_merge( $last->metadata, $metadata ?? [] ); } $message_repo->update( (int) $last->id, $conversation_id, trim( $last->content . "\n\n" . $message ), $merged_metadata ); return; } $message_repo->create( $conversation_id, 'user', $message, $metadata ); } /** * Render a compact, token-bounded summary of a single tool result. * * Product-search results are collapsed to one line per product (id, title, * price, stock) so the model retains IDs and prices from prior turns — naive * truncation dropped them once a listing exceeded the character cap and forced * the agent to re-search. Every other result is truncated as before. * * @param string $name Tool name. * @param mixed $raw Tool result (JSON string from Tool::getResult(), or scalar/array). * @return string */ private function summarize_tool_result( string $name, $raw ): string { $result = is_scalar( $raw ) ? (string) $raw : (string) wp_json_encode( $raw ); if ( 'wc-product-search' === $name ) { $compact = $this->summarize_product_search( $result ); if ( null !== $compact ) { return $compact; } } if ( 'eventin-event-search' === $name ) { $compact = Eventin_Event_Search_Tool::summarize_for_history( $result ); if ( null !== $compact ) { return $compact; } } if ( mb_strlen( $result ) > 600 ) { $result = mb_substr( $result, 0, 600 ) . '…(truncated)'; } return $result; } /** * Collapse a wc-product-search result payload into one compact line per * product: "#id title — price — stock (variable)". Returns null when the * payload has no usable product list so the caller falls back to truncation. * * @param string $json JSON-encoded product-search result. * @return string|null */ private function summarize_product_search( string $json ): ?string { $data = json_decode( $json, true ); if ( ! is_array( $data ) || empty( $data['products'] ) || ! is_array( $data['products'] ) ) { return null; } $rows = []; foreach ( $data['products'] as $product ) { if ( ! is_array( $product ) ) { continue; } $id = isset( $product['id'] ) ? (int) $product['id'] : 0; $title = isset( $product['title'] ) ? trim( wp_strip_all_tags( (string) $product['title'] ) ) : ''; $price = isset( $product['price_html'] ) ? trim( wp_strip_all_tags( (string) $product['price_html'] ) ) : ''; $stock = empty( $product['in_stock'] ) ? 'out of stock' : 'in stock'; $kind = ! empty( $product['has_variations'] ) ? ' (variable — choose a variation)' : ''; $rows[] = '#' . $id . ' ' . $title . ( '' !== $price ? ' — ' . $price : '' ) . ' — ' . $stock . $kind; } if ( empty( $rows ) ) { return null; } $summary = count( $rows ) . ' product(s): ' . implode( '; ', $rows ); // Bound the worst case (a very large listing) without losing the // per-product structure the way raw-JSON truncation did. if ( mb_strlen( $summary ) > 2000 ) { $summary = mb_substr( $summary, 0, 2000 ) . '…(more products omitted)'; } return $summary; } /** * Prepend product-page context to the latest user turn for the public * WooCommerce sales channel. * * Lets a shopper on a single-product storefront page say "does this come in * blue?" and have it resolve against the product they are currently * viewing, by prepending a short context note ahead of the turn's message * text. Reads whatever content is already on the last message (which may * have already been rewritten by the mention-context injection above) so * the two compose instead of clobbering each other. * * No-ops when the channel isn't the public sales channel, the WooCommerce * sales agent is disabled, or no valid product context was sent — so admin * chat and sites without the feature enabled are completely unaffected. * * @param array $agent_messages Windowed agent message array (Message objects). * @param string $channel Conversation channel ('admin' or 'public'). * @param mixed $current_product Raw `current_product` request param: [ id, name, permalink ]. * @param Settings $settings Settings instance. * @return array */ private function maybe_inject_product_context( array $agent_messages, string $channel, $current_product, Settings $settings ): array { if ( 'public' !== $channel || empty( $agent_messages ) ) { return $agent_messages; } // Product context is WooCommerce-specific, so this stays tied to that panel. if ( ! ( new Public_Agent_Settings( $settings ) )->is_enabled( 'woocommerce' ) ) { return $agent_messages; } if ( ! is_array( $current_product ) || empty( $current_product['name'] ) ) { return $agent_messages; } $name = sanitize_text_field( (string) $current_product['name'] ); if ( '' === $name ) { return $agent_messages; } $permalink = ! empty( $current_product['permalink'] ) ? esc_url_raw( (string) $current_product['permalink'] ) : ''; $id = ! empty( $current_product['id'] ) ? absint( $current_product['id'] ) : 0; $price = ! empty( $current_product['price'] ) ? sanitize_text_field( wp_strip_all_tags( (string) $current_product['price'] ) ) : ''; // Include the product ID the frontend already sent so the agent can pass it // straight to wc-cart-action instead of re-searching by name (which wastes a // tool call and risks name-collision mismatches). $note = 'The shopper is currently viewing this product: ' . $name . ( $id ? ' (Product ID: ' . $id . ')' : '' ) . ( '' !== $price ? ' (Price: ' . $price . ')' : '' ) . ( '' !== $permalink ? ' (' . $permalink . ')' : '' ) . '. If they say "this"/"it", assume they mean this product.' . ( $id ? ' You can use this product ID directly with wc-cart-action without searching again.' : '' ); $last_idx = count( $agent_messages ) - 1; $last = $agent_messages[ $last_idx ]; $agent_messages[ $last_idx ] = Message::make( MessageRole::from( $last->getRole() ), $note . "\n\n" . $last->getContent() ); return $agent_messages; } /** * Build the windowed agent message array from stored conversation messages. * * Only the most recent messages — capped by the channel's * contextMessageLimit setting — are replayed to the LLM, keeping token * usage bounded on long conversations. The UI and history endpoints still * receive the full conversation. The window is trimmed to start on a user * turn so the message sequence stays valid. * * @param array $messages Stored messages, ordered oldest-first. * @param string $channel Conversation channel ('admin' or 'public'). * @return array Array of NeuronAI Message objects. */ private function build_agent_messages( array $messages, string $channel ): array { $settings = new Settings(); $setting_key = 'admin' === $channel ? 'adminAssistant.contextMessageLimit' : 'publicChat.contextMessageLimit'; $default = 'admin' === $channel ? 30 : 20; $limit = (int) $settings->get( $setting_key, $default ); if ( $limit > 0 && count( $messages ) > $limit ) { $messages = array_slice( $messages, -$limit ); while ( ! empty( $messages ) && 'user' !== $messages[0]->role ) { array_shift( $messages ); } } $messages = array_values( $messages ); // Rebuild each turn's tool activity as real Tool objects, then enforce a // total character budget across the whole window. The message-count limit // alone does not bound tokens: with large product-search results on many // turns, a long conversation can still blow the input budget (public // completion is only maxTokens=1024). Newest results are the most useful, // so keep those and blank the oldest once the budget is spent. // // A call/result pair is never dropped outright, only emptied: the provider // rejects a tool_call id with no matching tool result. $budget = (int) apply_filters( 'aisentic_context_activity_note_budget', 8000, $channel ); $replayed_tools = []; foreach ( $messages as $i => $msg ) { $replayed_tools[ $i ] = $this->rebuild_tool_calls( $msg, $i ); } for ( $i = count( $messages ) - 1; $i >= 0; $i-- ) { foreach ( $replayed_tools[ $i ] as $tool ) { $result = (string) $tool->getResult(); $len = mb_strlen( $result ); if ( $len <= $budget ) { $budget -= $len; } elseif ( $budget > 0 ) { // Keep as much of this (newer) result as fits, then drop the rest. $tool->setResult( mb_substr( $result, 0, $budget ) . '…(truncated to stay within context budget)' ); $budget = 0; } else { $tool->setResult( '(result omitted to stay within context budget — call the tool again if you need it)' ); } } } $agent_messages = []; $placeholder_positions = []; foreach ( $messages as $i => $msg ) { // Skip rows whose role is not a known MessageRole (legacy/corrupt // data). MessageRole::from() would throw a \ValueError here, and this // runs before the streaming try/catch, so it would surface as a fatal // rather than a graceful error event. $role = MessageRole::tryFrom( $msg->role ); if ( null === $role ) { continue; } // Replay prior tool use as a real tool-call/tool-result pair rather // than as prose appended to the assistant's text. When history is // flattened to text, the model sees an assistant turn that merely // *narrates* calling tools, and on the next turn it imitates that // surface form — writing "Created!" without ever calling the tool. // Structured messages make the distinction between "described" and // "actually called" unambiguous. if ( [] !== $replayed_tools[ $i ] ) { $agent_messages[] = new ToolCallMessage( null, $replayed_tools[ $i ] ); $agent_messages[] = new ToolResultMessage( $replayed_tools[ $i ] ); } $content = $msg->content; // Surface completed write actions so the agent remembers it // already performed them and does not create duplicates. if ( ! empty( $msg->metadata['executed_tool']['name'] ) ) { $executed = $msg->metadata['executed_tool']; $result = is_scalar( $executed['result'] ?? null ) ? (string) $executed['result'] : wp_json_encode( $executed['result'] ?? [] ); $content .= "\n\n[Completed action — already done earlier in this conversation: tool '" . $executed['name'] . "' ran and returned: " . $result . '. Do NOT repeat this action for the same request. To change the result, call the matching update tool with the ID above.]'; } // Two kinds of row carry no content, and they are not the same // problem. // // A turn that was nothing but tool calls is already represented by // the tool-call/tool-result pair emitted above, so it is dropped // outright: an empty assistant turn breaks the alternation // HistoryTrimmer enforces, and that throw happens before the // streaming try/catch, killing every later message in the // conversation. // // The approval placeholder is only sometimes droppable, so it is // kept here and settled below, once its neighbours are known. $is_placeholder = false; if ( '' === trim( (string) $content ) ) { if ( empty( $msg->metadata['pending_approval'] ) ) { continue; } $content = __( '[An action was waiting for your approval. It was never completed.]', 'aisentic' ); $is_placeholder = true; } $agent_messages[] = Message::make( $role, $content ); if ( $is_placeholder ) { $placeholder_positions[] = count( $agent_messages ) - 1; } } return $this->settle_approval_placeholders( $agent_messages, $placeholder_positions ); } /** * Decide, per approval placeholder, whether the model should see it. * * The placeholder is an assistant row with no content, written the moment a * write tool asks for approval so the card survives a refresh. Whether it * may be dropped depends entirely on what followed it. * * An answered approval is followed by a real assistant turn, so the * placeholder is noise between two assistant turns and goes. * * An unanswered one is followed by nothing of the sort. The card can expire * (Chat_Controller stops on the expiry branch without writing a reply) or * the admin can ignore it and type something else, and the next row is then * another user turn. Dropping the placeholder there leaves two user turns * side by side, which HistoryTrimmer rejects exactly like two assistant * turns — the same permanently dead conversation, reached from the other * direction. It stays, carrying a line that also stops the model from * assuming the action went through. * * @param Message[] $agent_messages Built messages. * @param int[] $positions Indexes holding a placeholder. * @return Message[] */ private function settle_approval_placeholders( array $agent_messages, array $positions ): array { // Highest index first, so earlier positions stay valid as entries go. foreach ( array_reverse( $positions ) as $position ) { $next = $agent_messages[ $position + 1 ] ?? null; // A ToolCallMessage is an assistant turn too, so a resumed approval // that went straight back to tool calls is covered by this test. if ( $next instanceof Message && MessageRole::ASSISTANT->value === $next->getRole() ) { array_splice( $agent_messages, $position, 1 ); } } return array_values( $agent_messages ); } /** * Rebuild an assistant turn's recorded tool activity as NeuronAI Tool objects. * * Tool_Activity_Observer records name/inputs/result but not the provider's * original call id, so a deterministic one is synthesized per (message, * entry). It only has to be unique and consistent between the tool-call and * tool-result message built from the same Tool instance — the same object is * placed in both, so they can never drift apart. * * @param object $msg Stored message row. * @param int $index Position of the message within the replay window. * @return Tool[] Empty when the message recorded no tool activity. */ private function rebuild_tool_calls( $msg, int $index ): array { if ( MessageRole::ASSISTANT->value !== ( $msg->role ?? '' ) ) { return []; } $metadata = is_array( $msg->metadata ?? null ) ? $msg->metadata : []; $activity = $metadata['tool_activity'] ?? null; if ( ! is_array( $activity ) || [] === $activity ) { return []; } $tools = []; foreach ( $activity as $position => $entry ) { $name = $entry['name'] ?? ''; if ( ! is_string( $name ) || '' === $name ) { continue; } $tool = new Tool( $name ); $tool->setCallId( sprintf( 'call_aisentic_%d_%d', $index, (int) $position ) ); $tool->setInputs( is_array( $entry['inputs'] ?? null ) ? $entry['inputs'] : [] ); $tool->setResult( $this->summarize_tool_result( $name, $entry['result'] ?? null ) ); $tools[] = $tool; } return $tools; } }