'Agent needs a request.', 'token' => '', 'msg' => 'Empty request', 'model' => 'AIKCT Agent', 'agent' => array('action' => 'none', 'execution' => $execution), ); } $context = self::build_context($post_id, $request); $fallback_action = self::detect_action($prompt); $proxy = new kctaiproxy($ai_mode, $ai_provider, $ai_model); if (!$proxy->status) { $plan = self::build_plan($prompt, $context, $fallback_action, $execution); return array( 'output' => 'Agent cannot run because the selected provider is not available. Please enable the provider and add a usable key.', 'token' => '', 'msg' => 'Provider unavailable', 'model' => 'AIKCT Agent', 'agent' => array('action' => $fallback_action, 'execution' => $execution, 'plan' => $plan), ); } $planner_prompt = self::build_planner_prompt($prompt, $context, $execution, $fallback_action); $planner_result = $proxy->sendRequest($planner_prompt); $planner_output = isset($planner_result['output']) ? (string) $planner_result['output'] : ''; $decision = self::parse_planner_decision($planner_output, $fallback_action, $prompt, $context, $execution); $action = $decision['action']; $plan = self::build_plan($prompt, $context, $action, $execution, $decision); if (self::action_requires_content($action) && trim($context['content']) === '' && trim($context['selected_text']) === '' && trim($context['title']) === '') { return array( 'output' => self::format_plan($plan) . "\n\nAgent did not find any content in the current editor or saved post. Please make sure the editor content is loaded, then try again.", 'token' => '', 'msg' => 'Missing editor content', 'model' => 'AIKCT Agent', 'agent' => array( 'mode' => 'agent', 'action' => $action, 'execution' => $execution, 'plan' => $plan, 'planner' => $decision, 'post_id' => $post_id, 'context' => array('title' => $context['title'], 'word_count' => 0), ), ); } $agent_prompt = self::build_agent_prompt($prompt, $context, $action, $plan, $decision); $use_chatlog = $action === 'answer_with_context' && $chatlog !== ''; $result = $use_chatlog ? $proxy->sendRequest($agent_prompt, $chatlog) : $proxy->sendRequest($agent_prompt); $output = isset($result['output']) ? (string) $result['output'] : ''; $execution_result = self::execute_action($post_id, $action, $execution, $output, $decision); $result['agent'] = array( 'mode' => 'agent', 'action' => $action, 'execution' => $execution, 'plan' => $plan, 'planner' => $decision, 'post_id' => $post_id, 'context' => array( 'title' => isset($context['title']) ? $context['title'] : '', 'word_count' => isset($context['word_count']) ? $context['word_count'] : 0, ), 'execution_result' => $execution_result, ); if (!empty($execution_result['message'])) { $result['output'] .= "\n\n" . $execution_result['message']; } $result['output'] = self::format_plan($plan) . "\n\n" . $result['output']; return $result; } private static function build_context($post_id, $request = array()) { $post = $post_id ? get_post($post_id) : null; $editor_title = isset($request['editor_title']) ? sanitize_text_field(wp_unslash($request['editor_title'])) : ''; $editor_content = isset($request['editor_content']) ? wp_kses_post(wp_unslash($request['editor_content'])) : ''; $selected_text = isset($request['selected_text']) ? sanitize_textarea_field(wp_unslash($request['selected_text'])) : ''; $editor_content_text = trim(wp_strip_all_tags($editor_content, false)); if (!$post) { return array( 'post_id' => 0, 'title' => $editor_title, 'content' => $editor_content_text, 'selected_text' => $selected_text, 'excerpt' => '', 'categories' => array(), 'tags' => array(), 'word_count' => self::count_words($editor_content_text), 'url' => get_home_url(), ); } $saved_content = wp_strip_all_tags($post->post_content, false); $content = $editor_content_text !== '' ? $editor_content_text : $saved_content; return array( 'post_id' => $post->ID, 'title' => $editor_title !== '' ? $editor_title : get_the_title($post), 'content' => $content, 'selected_text' => $selected_text, 'excerpt' => wp_strip_all_tags($post->post_excerpt, false), 'categories' => wp_get_post_terms($post->ID, 'category', array('fields' => 'names')), 'tags' => wp_get_post_terms($post->ID, 'post_tag', array('fields' => 'names')), 'word_count' => self::count_words($content), 'url' => get_permalink($post), ); } private static function detect_action($prompt) { $text = strtolower(remove_accents($prompt)); if (strpos($text, 'tag') !== false || strpos($text, 'tags') !== false || strpos($text, 'the bai') !== false || strpos($text, 'tu khoa') !== false) { return 'generate_tags'; } if (strpos($text, 'excerpt') !== false || strpos($text, 'meta description') !== false || strpos($text, 'mo ta') !== false) { return 'generate_excerpt'; } if (strpos($text, 'title') !== false || strpos($text, 'tieu de') !== false || strpos($text, 'headline') !== false || strpos($text, 'stt') !== false) { return 'generate_title'; } if (strpos($text, 'rewrite') !== false || strpos($text, 'viet lai') !== false) { return 'rewrite_current_post'; } if (strpos($text, 'translate') !== false || strpos($text, 'dich') !== false) { return 'translate_current_post'; } return 'answer_with_context'; } private static function allowed_actions() { return array('translate_current_post', 'rewrite_current_post', 'generate_title', 'generate_tags', 'generate_excerpt', 'answer_with_context'); } private static function action_requires_content($action) { return in_array($action, array('translate_current_post', 'rewrite_current_post', 'generate_title', 'generate_tags', 'generate_excerpt'), true); } private static function build_planner_prompt($user_prompt, $context, $execution, $fallback_action) { $content = isset($context['content']) ? self::excerpt_text($context['content'], 1800) : ''; $selected_text = isset($context['selected_text']) ? self::excerpt_text($context['selected_text'], 900) : ''; $categories = !empty($context['categories']) ? implode(', ', $context['categories']) : 'None'; $tags = !empty($context['tags']) ? implode(', ', $context['tags']) : 'None'; return "You are the AIKCT Agent Planner for WordPress.\n" . "Choose exactly one supported action for the user's request. Return JSON only. Do not include markdown, prose, or hidden reasoning.\n\n" . "Supported actions:\n" . "- translate_current_post: translate the selected text or current post content.\n" . "- rewrite_current_post: rewrite or improve the selected text or current post content.\n" . "- generate_title: create or replace the WordPress post title/headline.\n" . "- generate_tags: create post tags/keywords.\n" . "- generate_excerpt: create a post excerpt or meta description.\n" . "- answer_with_context: answer a question using the current post context without applying changes.\n\n" . "JSON schema:\n" . "{\"action\":\"translate_current_post|rewrite_current_post|generate_title|generate_tags|generate_excerpt|answer_with_context\",\"target\":\"selected_text|current_post|title|excerpt|tags|reply\",\"language\":\"short language if relevant\",\"reason\":\"short visible reason\",\"steps\":[\"short step 1\",\"short step 2\",\"short step 3\"],\"requires_context\":true,\"can_apply\":true}\n\n" . "If the request asks to add, set, update, save, or create a post title, choose generate_title and target title.\n" . "If the request asks to complete an edit to the WordPress post, set can_apply to true.\n\n" . "User request: " . $user_prompt . "\n" . "Execution mode: " . $execution . "\n" . "Fallback action if unsure: " . $fallback_action . "\n" . "Post title: " . (isset($context['title']) ? $context['title'] : '') . "\n" . "Word count: " . (isset($context['word_count']) ? (int) $context['word_count'] : 0) . "\n" . "Categories: " . $categories . "\n" . "Tags: " . $tags . "\n" . "Selected text excerpt:\n" . ($selected_text !== '' ? $selected_text : 'None') . "\n" . "Current editor content excerpt:\n" . ($content !== '' ? $content : 'None'); } private static function parse_planner_decision($planner_output, $fallback_action, $user_prompt, $context, $execution) { $decision = self::fallback_decision($fallback_action, $user_prompt, $context, $execution); $raw = trim((string) $planner_output); if ($raw === '') { return $decision; } $raw = preg_replace('/^```(?:json)?\s*/i', '', $raw); $raw = preg_replace('/\s*```$/', '', $raw); if (preg_match('/\{.*\}/s', $raw, $matches)) { $raw = $matches[0]; } $parsed = json_decode($raw, true); if (!is_array($parsed)) { return $decision; } $allowed = self::allowed_actions(); if (!empty($parsed['action']) && in_array($parsed['action'], $allowed, true)) { $decision['action'] = $parsed['action']; } if (!empty($parsed['target'])) { $decision['target'] = sanitize_key($parsed['target']); } if (!empty($parsed['language'])) { $decision['language'] = sanitize_text_field($parsed['language']); } if (!empty($parsed['reason'])) { $decision['reason'] = sanitize_text_field($parsed['reason']); } if (isset($parsed['requires_context'])) { $decision['requires_context'] = (bool) $parsed['requires_context']; } if (isset($parsed['can_apply'])) { $decision['can_apply'] = (bool) $parsed['can_apply']; } if (!empty($parsed['steps']) && is_array($parsed['steps'])) { $steps = array(); foreach ($parsed['steps'] as $step) { $step = trim(sanitize_text_field($step)); if ($step !== '') { $steps[] = $step; } } if (!empty($steps)) { $decision['steps'] = array_slice($steps, 0, 5); } } return $decision; } private static function fallback_decision($fallback_action, $user_prompt, $context, $execution) { $source = trim($context['selected_text']) !== '' ? 'selected_text' : (trim($context['content']) !== '' ? 'current_post' : 'reply'); return array( 'action' => $fallback_action, 'target' => $fallback_action === 'generate_tags' ? 'tags' : ($fallback_action === 'generate_excerpt' ? 'excerpt' : ($fallback_action === 'generate_title' ? 'title' : $source)), 'language' => '', 'reason' => 'Planner fallback selected the closest supported action from the request.', 'steps' => array( 'Read the current WordPress editor context.', 'Choose the matching supported agent action.', 'Run the selected action with the selected provider/model.', in_array($execution, array('auto', 'update_draft'), true) ? 'Apply the supported result to the editor UI only; do not save the post.' : 'Return the result without changing the editor.', ), 'requires_context' => self::action_requires_content($fallback_action), 'can_apply' => in_array($execution, array('auto', 'update_draft'), true) && $fallback_action !== 'answer_with_context', ); } private static function build_plan($user_prompt, $context, $action, $execution, $decision = array()) { $source = trim($context['selected_text']) !== '' ? 'selected_text' : (trim($context['content']) !== '' ? 'current_editor_content' : 'saved_post_or_empty'); $steps = !empty($decision['steps']) && is_array($decision['steps']) ? $decision['steps'] : array( 'Read the current WordPress editor context.', 'Infer the requested task and choose the matching agent action.', 'Call the selected AI provider/model with the post context.', in_array($execution, array('auto', 'update_draft'), true) ? 'Apply the supported result to the editor UI only; do not save the post.' : 'Return the result without changing the editor.', ); return array( 'goal' => $user_prompt, 'context_source' => $source, 'context_words' => isset($context['word_count']) ? (int) $context['word_count'] : 0, 'action' => $action, 'execution' => $execution, 'target' => isset($decision['target']) ? $decision['target'] : '', 'language' => isset($decision['language']) ? $decision['language'] : '', 'reason' => isset($decision['reason']) ? $decision['reason'] : '', 'steps' => $steps, 'guardrails' => array( 'Use only the current post context for transformations.', 'Do not update the draft when context or result is empty.', 'Keep the final response focused on the requested action.', ), ); } private static function format_plan($plan) { $steps = isset($plan['steps']) && is_array($plan['steps']) ? $plan['steps'] : array(); $lines = array_map('esc_html', $steps); $reason = !empty($plan['reason']) ? '

Decision: ' . esc_html($plan['reason']) . '

' : ''; return '
' . 'Agent Plan' . '

Action: ' . esc_html($plan['action']) . ' · Target: ' . esc_html(isset($plan['target']) ? $plan['target'] : '') . ' · Context: ' . esc_html($plan['context_source']) . ' (' . esc_html((string) $plan['context_words']) . ' words) · Execution: ' . esc_html($plan['execution']) . '

' . $reason . '
  1. ' . implode('
  2. ', $lines) . '
' . '
'; } private static function build_agent_prompt($user_prompt, $context, $action, $plan, $decision = array()) { $categories = !empty($context['categories']) ? implode(', ', $context['categories']) : 'None'; $tags = !empty($context['tags']) ? implode(', ', $context['tags']) : 'None'; $content = isset($context['content']) ? $context['content'] : ''; $selected_text = isset($context['selected_text']) ? $context['selected_text'] : ''; $instructions = array( 'You are AIKCT Pro Agent, a WordPress content agent.', 'You understand the current post context before answering.', 'Use the provided agent plan as the execution plan. Do not output hidden chain-of-thought.', 'Do not invent facts that are not present in the provided context.', 'If the task asks to transform the current post, return only the transformed content unless a short note is necessary.', 'If generating a title/headline, return one clean title only. Do not include labels, quotes, markdown, or explanation.', 'If generating tags, return a comma-separated tag list only.', 'If generating excerpt/meta description, return one concise paragraph only.', ); return implode("\n", $instructions) . "\n\nAgent action: " . $action . "\nPlanner decision: " . wp_json_encode($decision) . "\nAgent visible plan: " . wp_json_encode($plan) . "\nUser request: " . $user_prompt . "\n\nCurrent WordPress post context:" . "\nPost ID: " . (int) $context['post_id'] . "\nTitle: " . $context['title'] . "\nURL: " . $context['url'] . "\nCategories: " . $categories . "\nTags: " . $tags . "\nExcerpt: " . $context['excerpt'] . "\nSelected text, if any:\n" . ($selected_text !== '' ? $selected_text : 'None') . "\nContent:\n" . $content; } private static function count_words($content) { $content = trim(wp_strip_all_tags($content)); if ($content === '') { return 0; } preg_match_all('/[^\s]+/u', $content, $matches); return isset($matches[0]) ? count($matches[0]) : 0; } private static function excerpt_text($content, $limit) { $content = trim(wp_strip_all_tags($content, false)); if (strlen($content) <= $limit) { return $content; } return substr($content, 0, $limit) . '...'; } private static function execute_action($post_id, $action, $execution, $output, $decision = array()) { $should_apply = $execution === 'update_draft' || ($execution === 'auto' && !empty($decision['can_apply']) && $action !== 'answer_with_context'); if (!$should_apply || !$post_id) { return array('applied' => false, 'message' => ''); } if (!current_user_can('edit_post', $post_id)) { return array('applied' => false, 'message' => 'Agent did not apply changes because the current user cannot edit this post.'); } $clean_output = trim(wp_kses_post($output)); if ($clean_output === '') { return array('applied' => false, 'message' => 'Agent did not apply changes because the result was empty.'); } $plain_output = strtolower(remove_accents(wp_strip_all_tags($clean_output))); if (strpos($plain_output, 'invalid response from api') !== false || strpos($plain_output, 'encountered invalidated oauth token') !== false || strpos($plain_output, 'api error') !== false || strpos($plain_output, 'not_found_error') !== false) { return array('applied' => false, 'message' => 'Agent did not update the draft because the provider returned an API error.'); } if (strpos($plain_output, 'khong co noi dung') !== false || strpos($plain_output, 'no content') !== false) { return array('applied' => false, 'message' => 'Agent did not update the draft because the result says no content was found.'); } if (in_array($action, array('translate_current_post', 'rewrite_current_post'), true)) { return array( 'applied' => true, 'message' => 'Agent applied the content to the editor only. Review it, then save/update the post manually.', 'post_content' => $clean_output, 'should_save' => false, ); } if ($action === 'generate_title') { $title = self::clean_single_line_output($clean_output); if ($title === '') { return array('applied' => false, 'message' => 'Agent did not update the title because the generated title was empty.'); } return array( 'applied' => true, 'message' => 'Agent applied the title to the editor only. Review it, then save/update the post manually.', 'post_title' => $title, 'should_save' => false, ); } if ($action === 'generate_excerpt') { $excerpt = self::clean_single_line_output($clean_output); if ($excerpt === '') { return array('applied' => false, 'message' => 'Agent did not update the excerpt because the generated excerpt was empty.'); } return array( 'applied' => true, 'message' => 'Agent applied the excerpt to the editor only. Review it, then save/update the post manually.', 'post_excerpt' => $excerpt, 'should_save' => false, ); } if ($action === 'generate_tags') { $tags = array_filter(array_map('trim', preg_split('/[,;\n]+/', wp_strip_all_tags($clean_output)))); if (!empty($tags)) { return array( 'applied' => true, 'message' => 'Agent applied tags to the editor only. Review them, then save/update the post manually.', 'post_tags' => array_values($tags), 'should_save' => false, ); } } return array('applied' => false, 'message' => $execution === 'insert' ? 'Agent result is ready. Use Add to Content to insert it.' : ''); } private static function clean_single_line_output($output) { $text = trim(wp_strip_all_tags($output)); $text = preg_replace('/^\s*(title|headline|tieu de|tiêu đề)\s*[::-]\s*/iu', '', $text); $text = preg_replace('/\s+/', ' ', $text); $text = trim($text, " \t\n\r\0\x0B\"'“”‘’`"); return $text; } } }