openai_client ) { $this->openai_client = new AIEditor_OpenAI_Client(); } return $this->openai_client; } /** * Return the local tool runner. * * @return AIEditor_Tool_Runner */ private function get_tool_runner() { if ( null === $this->tool_runner ) { $this->tool_runner = new AIEditor_Tool_Runner( $this->get_openai_client() ); } return $this->tool_runner; } /** * Return the system prompt builder. * * @return AIEditor_Prompt_Builder */ private function get_prompt_builder() { if ( null === $this->prompt_builder ) { $this->prompt_builder = new AIEditor_Prompt_Builder(); } return $this->prompt_builder; } /** * Supported AI Editor model keys. * * @return array */ private function get_supported_models() { return AIEditor_Model_Config::get_supported_model_keys(); } /** * Return the saved reasoning-effort setting for Responses requests. * * @param array $options Plugin settings. * @return string */ private function get_reasoning_effort_setting( $options ) { $reasoning_effort = isset( $options['ai_editor_reasoning_effort'] ) ? sanitize_text_field( $options['ai_editor_reasoning_effort'] ) : AIEditor_Model_Config::get_default_reasoning_effort(); $model_key = isset( $options['ai_editor_model'] ) ? $options['ai_editor_model'] : AIEditor_Model_Config::get_recommended_model_key(); return AIEditor_Model_Config::normalize_reasoning_effort( $reasoning_effort, AIEditor_Model_Config::get_openai_model_name( $model_key ) ); } /** * Return the OpenAI HTTP timeout window for the selected reasoning effort. * * @param string $reasoning_effort Reasoning-effort key. * @return int Timeout in seconds. */ private function get_openai_timeout_for_reasoning_effort( $reasoning_effort ) { return AIEditor_Model_Config::get_openai_timeout_for_reasoning_effort( $reasoning_effort ); } /** * Register all routes for the endpoint. */ public function register_routes() { register_rest_route( 'ai-editor/v1', '/responses', array( 'methods' => 'POST', 'callback' => array( $this, 'responses_api' ), 'permission_callback' => array( $this, 'openai_api_permissions_check' ), 'args' => array( 'messages' => array( 'required' => true, 'type' => 'array', ), 'functions' => array( 'required' => false, 'type' => 'array', ), 'selection' => array( 'required' => false, 'type' => 'object', ), 'request_mode' => array( 'required' => false, 'type' => 'string', ), 'previous_response_id' => array( 'required' => false, 'type' => 'string', ), ), ) ); register_rest_route( 'ai-editor/v1', '/responses/status/(?P[A-Za-z0-9_-]+)', array( 'methods' => 'GET', 'callback' => array( $this, 'responses_status_api' ), 'permission_callback' => array( $this, 'openai_api_permissions_check' ), 'args' => array( 'response_id' => array( 'required' => true, 'type' => 'string', ), ), ) ); register_rest_route( 'ai-editor/v1', '/responses/cancel', array( 'methods' => 'POST', 'callback' => array( $this, 'responses_cancel_api' ), 'permission_callback' => array( $this, 'openai_api_permissions_check' ), 'args' => array( 'response_id' => array( 'required' => true, 'type' => 'string', ), ), ) ); } /** * Handle the OpenAI Responses API request. * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response */ public function responses_api( $request ) { $messages = $request->get_param( 'messages' ); $functions = AIEditor_OpenAI_Utils::normalize_tool_definitions( $request->get_param( 'functions' ) ); $tools = $this->get_openai_tools( $functions ); $available_tool_names = $this->get_tool_names( $tools ); $selection = $request->get_param( 'selection' ); $tool_context = $this->get_tool_context( $selection ); $request_mode = $request->get_param( 'request_mode' ); $previous_response_id = $request->get_param( 'previous_response_id' ); $options = get_option( 'ai_editor_settings' ); $api_key = isset( $options['ai_editor_api_key'] ) ? $options['ai_editor_api_key'] : ''; $model = isset( $options['ai_editor_model'] ) ? $options['ai_editor_model'] : AIEditor_Model_Config::get_recommended_model_key(); $reasoning_effort = $this->get_reasoning_effort_setting( $options ); $openai_timeout = $this->get_openai_timeout_for_reasoning_effort( $reasoning_effort ); if ( empty( $api_key ) ) { return new WP_Error( 'api_key_missing', __( 'Enter your OpenAI API key in Settings -> AI Editor.', 'ai-editor' ), array( 'status' => 400 ) ); } if ( ! in_array( $model, $this->get_supported_models(), true ) ) { return new WP_Error( 'unsupported_model', __( AIEditor_Model_Config::get_supported_models_message(), 'ai-editor' ), array( 'status' => 400 ) ); } $matched_insert_keyword_blocks = array(); $matched_insert_keyword_details = array(); if ( is_array( $selection ) ) { $matched_insert_keyword_blocks = ! empty( $selection['insertKeywordBlockNames'] ) && is_array( $selection['insertKeywordBlockNames'] ) ? array_values( array_filter( $selection['insertKeywordBlockNames'], 'is_string' ) ) : array(); $matched_insert_keyword_details = ! empty( $selection['insertKeywordMatchDetails'] ) && is_array( $selection['insertKeywordMatchDetails'] ) ? array_values( array_filter( $selection['insertKeywordMatchDetails'], static function ( $detail ) { return is_array( $detail ) && ! empty( $detail['block'] ) && ! empty( $detail['matched'] ); } ) ) : array(); } $system_message = $this->get_system_message( $model, $request_mode, $selection, $messages ); $openai_model = $this->get_gpt_model( $model ); $input_items = AIEditor_OpenAI_Utils::build_input_items( $messages ); $prompt_cache_key = AIEditor_OpenAI_Utils::build_prompt_cache_key( $openai_model, $request_mode, $system_message ); $prompt_cache_retention = AIEditor_OpenAI_Utils::get_prompt_cache_retention( $openai_model ); $payload = array( 'model' => $openai_model, 'instructions' => $system_message, 'input' => $input_items, 'tools' => $tools, 'background' => true, 'parallel_tool_calls' => false, 'reasoning' => array( 'effort' => $reasoning_effort, ), 'tool_choice' => 'auto', 'prompt_cache_key' => $prompt_cache_key, 'previous_response_id' => ! empty( $previous_response_id ) ? $previous_response_id : null, ); if ( '' !== $prompt_cache_retention ) { $payload['prompt_cache_retention'] = $prompt_cache_retention; } $response = $this->get_openai_client()->create_response( $payload, $api_key, $openai_timeout ); if ( is_wp_error( $response ) ) { return $response; } $response_data = $response['data']; $response_meta = $response['meta']; $initial_usage = AIEditor_OpenAI_Utils::extract_openai_usage_summary( $response_data ); if ( 200 !== $response_meta['status'] ) { return $this->get_openai_client()->build_error_response( $response_data, $response_meta['status'] ); } if ( empty( $response_data['status'] ) || 'completed' !== $response_data['status'] ) { if ( ! empty( $response_data['id'] ) ) { $this->store_response_tool_state( $response_data['id'], $tools, $tool_context ); } return new WP_REST_Response( array( 'data' => array( 'id' => isset( $response_data['id'] ) ? $response_data['id'] : '', 'status' => isset( $response_data['status'] ) ? $response_data['status'] : 'in_progress', 'markup' => '', 'content' => '', 'output' => isset( $response_data['output'] ) ? $response_data['output'] : array(), 'raw_response' => $response_data, ), 'meta' => array( 'resolved_model' => $openai_model, 'resolved_system_message' => $system_message, 'tool_name' => '', 'tool_names' => array(), 'tool_calls' => array(), 'available_tool_names' => $available_tool_names, 'available_tools' => $tools, 'usage' => $initial_usage, 'prompt_cache_key' => $prompt_cache_key, 'prompt_cache_retention' => $prompt_cache_retention, 'openai_http_timeout' => $openai_timeout, 'matched_insert_keyword_blocks' => $matched_insert_keyword_blocks, 'matched_insert_keyword_details' => $matched_insert_keyword_details, ), ), 200 ); } $loop_result = $this->get_tool_runner()->run( $response_data, $api_key, $openai_model, $tools, $reasoning_effort, $openai_timeout, $tool_context ); if ( is_wp_error( $loop_result ) ) { return $loop_result; } $final_response_data = $loop_result['response_data']; $replacement_markup = $loop_result['markup']; $reply_message = $loop_result['reply']; $history_action = $loop_result['history_action']; $tool_name = $loop_result['tool_name']; $tool_names = $loop_result['tool_names']; $final_usage = AIEditor_OpenAI_Utils::extract_openai_usage_summary( $final_response_data ); $response_array = array( 'data' => array( 'id' => isset( $final_response_data['id'] ) ? $final_response_data['id'] : '', 'status' => isset( $final_response_data['status'] ) ? $final_response_data['status'] : '', 'markup' => $replacement_markup, 'content' => $reply_message ? $reply_message : $this->get_tool_runner()->extract_response_text( $final_response_data ), 'history_action' => $history_action, 'output' => isset( $final_response_data['output'] ) ? $final_response_data['output'] : array(), 'raw_response' => $final_response_data, ), 'meta' => array( 'resolved_model' => $openai_model, 'resolved_system_message' => $system_message, 'tool_name' => $tool_name, 'tool_names' => $tool_names, 'tool_calls' => $loop_result['tool_calls'], 'tool_outputs' => $loop_result['tool_outputs'], 'available_tool_names' => $available_tool_names, 'available_tools' => $tools, 'usage' => $final_usage, 'prompt_cache_key' => $prompt_cache_key, 'prompt_cache_retention' => $prompt_cache_retention, 'openai_http_timeout' => $openai_timeout, 'matched_insert_keyword_blocks' => $matched_insert_keyword_blocks, 'matched_insert_keyword_details' => $matched_insert_keyword_details, ), ); return new WP_REST_Response( $response_array, 200 ); } /** * Poll an existing background response and normalize the completed output. * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response */ public function responses_status_api( $request ) { $response_id = $request->get_param( 'response_id' ); $options = get_option( 'ai_editor_settings' ); $api_key = isset( $options['ai_editor_api_key'] ) ? $options['ai_editor_api_key'] : ''; $model = isset( $options['ai_editor_model'] ) ? $options['ai_editor_model'] : AIEditor_Model_Config::get_recommended_model_key(); $reasoning_effort = $this->get_reasoning_effort_setting( $options ); $openai_timeout = $this->get_openai_timeout_for_reasoning_effort( $reasoning_effort ); $openai_model = $this->get_gpt_model( $model ); $tool_state = $this->get_stored_response_tool_state( $response_id ); $tools = isset( $tool_state['tools'] ) && is_array( $tool_state['tools'] ) ? $tool_state['tools'] : array(); $tool_context = isset( $tool_state['tool_context'] ) && is_array( $tool_state['tool_context'] ) ? $tool_state['tool_context'] : array(); $available_tool_names = $this->get_tool_names( $tools ); if ( empty( $api_key ) ) { return new WP_Error( 'api_key_missing', __( 'Enter your OpenAI API key in Settings -> AI Editor.', 'ai-editor' ), array( 'status' => 400 ) ); } if ( ! in_array( $model, $this->get_supported_models(), true ) ) { return new WP_Error( 'unsupported_model', __( AIEditor_Model_Config::get_supported_models_message(), 'ai-editor' ), array( 'status' => 400 ) ); } $response = $this->get_openai_client()->retrieve_response( $response_id, $api_key, $openai_timeout ); if ( is_wp_error( $response ) ) { return $response; } $response_data = $response['data']; $response_meta = $response['meta']; $usage_summary = AIEditor_OpenAI_Utils::extract_openai_usage_summary( $response_data ); if ( 200 !== $response_meta['status'] ) { return $this->get_openai_client()->build_error_response( $response_data, $response_meta['status'] ); } if ( empty( $response_data['status'] ) || 'completed' !== $response_data['status'] ) { return new WP_REST_Response( array( 'data' => array( 'id' => isset( $response_data['id'] ) ? $response_data['id'] : $response_id, 'status' => isset( $response_data['status'] ) ? $response_data['status'] : 'in_progress', 'markup' => '', 'content' => '', 'output' => isset( $response_data['output'] ) ? $response_data['output'] : array(), 'raw_response' => $response_data, ), 'meta' => array( 'resolved_model' => $openai_model, 'resolved_system_message' => '', 'tool_name' => '', 'tool_names' => array(), 'tool_calls' => array(), 'available_tool_names' => $available_tool_names, 'available_tools' => $tools, 'usage' => $usage_summary, 'openai_http_timeout' => $openai_timeout, ), ), 200 ); } $loop_result = $this->get_tool_runner()->run( $response_data, $api_key, $openai_model, $tools, $reasoning_effort, $openai_timeout, $tool_context ); if ( is_wp_error( $loop_result ) ) { return $loop_result; } $final_response_data = $loop_result['response_data']; $final_usage = AIEditor_OpenAI_Utils::extract_openai_usage_summary( $final_response_data ); $this->delete_stored_response_tools( $response_id ); return new WP_REST_Response( array( 'data' => array( 'id' => isset( $final_response_data['id'] ) ? $final_response_data['id'] : $response_id, 'status' => isset( $final_response_data['status'] ) ? $final_response_data['status'] : 'completed', 'markup' => $loop_result['markup'], 'content' => $loop_result['reply'] ? $loop_result['reply'] : $this->get_tool_runner()->extract_response_text( $final_response_data ), 'history_action' => $loop_result['history_action'], 'output' => isset( $final_response_data['output'] ) ? $final_response_data['output'] : array(), 'raw_response' => $final_response_data, ), 'meta' => array( 'resolved_model' => $openai_model, 'resolved_system_message' => '', 'tool_name' => $loop_result['tool_name'], 'tool_names' => $loop_result['tool_names'], 'tool_calls' => $loop_result['tool_calls'], 'tool_outputs' => $loop_result['tool_outputs'], 'available_tool_names' => $available_tool_names, 'available_tools' => $tools, 'usage' => $final_usage, 'openai_http_timeout' => $openai_timeout, ), ), 200 ); } /** * Cancel an existing background response. * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response */ public function responses_cancel_api( $request ) { $response_id = $request->get_param( 'response_id' ); $options = get_option( 'ai_editor_settings' ); $api_key = isset( $options['ai_editor_api_key'] ) ? $options['ai_editor_api_key'] : ''; if ( empty( $api_key ) ) { return new WP_Error( 'api_key_missing', __( 'Enter your OpenAI API key in Settings -> AI Editor.', 'ai-editor' ), array( 'status' => 400 ) ); } $response = $this->get_openai_client()->cancel_response( $response_id, $api_key ); if ( is_wp_error( $response ) ) { return $response; } if ( 200 !== $response['meta']['status'] ) { return $this->get_openai_client()->build_error_response( $response['data'], $response['meta']['status'] ); } $this->delete_stored_response_tools( $response_id ); return new WP_REST_Response( array( 'data' => array( 'id' => isset( $response['data']['id'] ) ? $response['data']['id'] : $response_id, 'status' => isset( $response['data']['status'] ) ? $response['data']['status'] : 'cancelled', 'raw_response' => $response['data'], ), ), 200 ); } /** * Get the GPT model based on the model identifier. * * @param string $model The model identifier. * @return string The GPT model name. */ public function get_gpt_model( $model ) { return AIEditor_Model_Config::get_openai_model_name( $model ); } /** * Get the system message based on the model. * * @param string $model The model identifier. * @return string The system message. */ public function get_system_message( $model, $request_mode = 'insert', $selection = null, $messages = array() ) { return $this->get_prompt_builder()->build_system_message( $model, $request_mode, $selection, $messages ); } /** * Merge browser-provided AI Editor tools with server-side ability tools. * * @param array|null $functions Browser-provided tool definitions. * @return array */ private function get_openai_tools( $functions ) { $tools = is_array( $functions ) ? $functions : array(); if ( class_exists( 'AIEditor_Ability_Tools' ) ) { $ability_tools = AIEditor_Ability_Tools::get_openai_tools(); if ( is_array( $ability_tools ) && ! empty( $ability_tools ) ) { $tools = array_merge( $tools, $ability_tools ); } } return $tools; } /** * Build private context available to local tool execution. * * @param array|null $selection Selection snapshot from the editor. * @return array */ private function get_tool_context( $selection ) { $context = array(); if ( ! is_array( $selection ) || empty( $selection['currentDocument'] ) || ! is_array( $selection['currentDocument'] ) ) { return $context; } $current_document = $selection['currentDocument']; $context['current_document'] = array( 'id' => isset( $current_document['id'] ) ? absint( $current_document['id'] ) : 0, 'type' => isset( $current_document['type'] ) ? sanitize_key( (string) $current_document['type'] ) : '', 'title' => isset( $current_document['title'] ) ? sanitize_text_field( (string) $current_document['title'] ) : '', 'status' => isset( $current_document['status'] ) ? sanitize_key( (string) $current_document['status'] ) : '', ); return $context; } /** * Return tool names from OpenAI tool definitions for browser debugging. * * @param array $tools OpenAI tool definitions. * @return array */ private function get_tool_names( $tools ) { if ( ! is_array( $tools ) ) { return array(); } $names = array(); foreach ( $tools as $tool ) { if ( ! is_array( $tool ) || empty( $tool['name'] ) || ! is_string( $tool['name'] ) ) { continue; } $names[] = $tool['name']; } return array_values( array_unique( $names ) ); } /** * Store tools for a background response so polling can continue tool calls. * * @param string $response_id OpenAI response id. * @param array $tools OpenAI tool definitions. * @param array $tool_context Private context for local tool execution. */ private function store_response_tool_state( $response_id, $tools, $tool_context = array() ) { if ( ! function_exists( 'set_transient' ) || empty( $response_id ) ) { return; } set_transient( $this->get_response_tools_transient_key( $response_id ), array( 'tools' => $tools, 'tool_context' => is_array( $tool_context ) ? $tool_context : array(), ), 10 * MINUTE_IN_SECONDS ); } /** * Return stored tool state for a background response. * * @param string $response_id OpenAI response id. * @return array */ private function get_stored_response_tool_state( $response_id ) { if ( ! function_exists( 'get_transient' ) || empty( $response_id ) ) { return array(); } $state = get_transient( $this->get_response_tools_transient_key( $response_id ) ); if ( ! is_array( $state ) ) { return array(); } if ( isset( $state['tools'] ) && is_array( $state['tools'] ) ) { return $state; } return array( 'tools' => $state, 'tool_context' => array(), ); } /** * Delete stored tools for a background response. * * @param string $response_id OpenAI response id. */ private function delete_stored_response_tools( $response_id ) { if ( ! function_exists( 'delete_transient' ) || empty( $response_id ) ) { return; } delete_transient( $this->get_response_tools_transient_key( $response_id ) ); } /** * Return the transient key used to store response tools. * * @param string $response_id OpenAI response id. * @return string */ private function get_response_tools_transient_key( $response_id ) { return 'ai_editor_response_tools_' . md5( (string) $response_id ); } /** * Check if the user has permission to access the endpoint. * * @param WP_REST_Request $request Full data about the request. * @return bool|WP_Error */ public function openai_api_permissions_check( $request ) { if ( ! is_user_logged_in() ) { return new WP_Error( 'ai_editor_rest_forbidden', __( 'You must be logged in to access AI Editor endpoints.', 'ai-editor' ), array( 'status' => rest_authorization_required_code() ) ); } if ( ! current_user_can( 'manage_options' ) ) { return new WP_Error( 'ai_editor_rest_forbidden', __( 'Only administrators can access AI Editor endpoints.', 'ai-editor' ), array( 'status' => 403 ) ); } return true; } } // Hook the class to the REST API. add_action( 'rest_api_init', function () { $ai_editor_endpoint = new AIEditor_OpenAI_Endpoint(); $ai_editor_endpoint->register_routes(); } );