is_available() ) {
return new WP_Error(
'ai_unavailable',
__( 'WordPress AI Client is not available on this site.', 'advanced-animation' )
);
}
if ( $post_id && ! Security::can_edit_post( $post_id ) ) {
return new WP_Error(
'edit_forbidden',
__( 'Sorry, you are not allowed to edit this post.', 'advanced-animation' )
);
}
$this->provider = $provider;
$this->model = $model;
$this->attachments = $attachments;
$this->page_content = $page_content;
$this->use_global_theme = $use_global_theme;
$this->editor = $editor;
$this->block_type_preference = $this->normalize_block_type_preference( $block_type_preference );
$direct_result = $this->maybe_run_direct_editor_action( $prompt, $selection, $post_id, $attachments );
if ( is_wp_error( $direct_result ) ) {
return $direct_result;
}
if ( is_array( $direct_result ) ) {
return $direct_result;
}
$registry = $this->build_tool_registry();
$declarations = $this->build_function_declarations( $registry );
$conversation = array_merge(
$this->normalize_history( $messages ),
array( $this->build_user_message( $prompt, $attachments ) )
);
$initial_text = $this->message_to_text( end( $conversation ) ?: array() );
$use_native = $this->detect_native_support( $initial_text, $declarations );
$system_prompt = $this->build_system_prompt( $registry, $selection, $use_native, $post_id );
$max_steps = 10;
$tool_log = array();
for ( $step = 0; $step < $max_steps; $step++ ) {
$ai_turn = $this->call_ai( $system_prompt, $conversation, 0 === $step, $declarations, $use_native );
if ( is_wp_error( $ai_turn ) ) {
return $ai_turn;
}
// Native function-call turn.
if ( 'function_calls' === $ai_turn['type'] ) {
$model_parts = array();
$response_parts = array();
foreach ( $ai_turn['calls'] as $call ) {
$tool_name = $call['name'] ?? '';
$tool = $registry->get( $tool_name );
if ( ! $tool ) {
$tool_result = array(
'success' => false,
/* translators: %s: tool name requested by the AI model */
'error' => sprintf( __( 'Unknown tool requested: %s', 'advanced-animation' ), $tool_name ),
);
} else {
$arguments = is_array( $call['args'] ) ? $call['args'] : (array) $call['args'];
$tool_context = array(
'post_id' => $post_id,
'selection' => $selection,
'page_content' => $this->page_content,
'editor' => $this->editor,
'block_type_preference' => $this->block_type_preference,
'request_source' => 'chat',
);
$tool_result = $tool->execute( $arguments, $tool_context );
}
$tool_log[] = array(
'tool' => $tool_name,
'arguments' => $call['args'],
'result' => $tool_result,
);
$model_parts[] = array(
'type' => 'functionCall',
'functionCall' => array(
'id' => $call['id'] ?? null,
'name' => $tool_name,
'args' => $call['args'] ?? null,
),
);
$response_parts[] = array(
'type' => 'functionResponse',
'functionResponse' => array(
'id' => $call['id'] ?? null,
'name' => $tool_name,
'response' => $tool_result,
),
);
}
$conversation[] = array(
'role' => 'model',
'parts' => $model_parts,
);
$conversation[] = array(
'role' => 'user',
'parts' => $response_parts,
);
continue;
}
// Text response (native final answer or manual fallback).
$ai_response = $ai_turn['text'] ?? '';
$parsed = $this->parse_response( $ai_response );
if ( is_wp_error( $parsed ) ) {
return $parsed;
}
$action = $parsed['action'] ?? '';
if ( 'final' === $action ) {
$result = $parsed['result'] ?? array();
if ( ! is_array( $result ) ) {
$result = array( 'type' => 'message', 'message' => strval( $result ) );
}
$result['tool_calls'] = $tool_log;
return $result;
}
if ( 'tool_call' === $action ) {
$tool_name = $parsed['tool'] ?? '';
$arguments = $parsed['arguments'] ?? array();
$tool = $registry->get( $tool_name );
if ( ! $tool ) {
return new WP_Error(
'unknown_tool',
/* translators: %s: tool name requested by the AI model */
sprintf( __( 'Unknown tool requested: %s', 'advanced-animation' ), $tool_name )
);
}
$tool_context = array(
'post_id' => $post_id,
'selection' => $selection,
'page_content' => $this->page_content,
'editor' => $this->editor,
'block_type_preference' => $this->block_type_preference,
'request_source' => 'chat',
);
$tool_result = $tool->execute( $arguments, $tool_context );
$tool_log[] = array(
'tool' => $tool_name,
'arguments' => $arguments,
'result' => $tool_result,
);
$conversation[] = array(
'role' => 'model',
'parts' => array(
array( 'type' => 'text', 'text' => json_encode( $parsed ) ),
),
);
$conversation[] = array(
'role' => 'user',
'parts' => array(
array(
'type' => 'text',
'text' => json_encode(
array(
'tool_result' => $tool_result,
)
),
),
),
);
continue;
}
return new WP_Error(
'invalid_action',
__( 'AI response did not contain a valid action.', 'advanced-animation' )
);
}
return new WP_Error(
'max_steps',
__( 'The AI reached the maximum number of tool steps.', 'advanced-animation' )
);
}
/**
* Deterministically handle obvious editor mutations before entering the
* agent loop. This lets smaller models generate content without requiring
* them to reliably orchestrate tool calls.
*
* @return array|WP_Error|null Direct tool result, error, or null to use the agent loop.
*/
private function maybe_run_direct_editor_action( string $prompt, ?array $selection, ?int $post_id, array $attachments ) {
if ( ! empty( $attachments ) ) {
return null;
}
$intent = $this->classify_editor_intent( $prompt, $selection );
if ( null === $intent ) {
return null;
}
if ( empty( $post_id ) && in_array( $intent['action'], array( 'add', 'full_page' ), true ) ) {
return new WP_Error(
'no_current_post',
__( 'No current post ID available for this editor action.', 'advanced-animation' )
);
}
if ( 'replace' === $intent['action'] && empty( $selection ) ) {
return array(
'type' => 'error',
'message' => __( 'Select a block or element in the editor first, then ask me to replace or update it.', 'advanced-animation' ),
);
}
$tool = $this->tool_for_direct_intent( $intent['action'] );
if ( ! $tool ) {
return null;
}
$arguments = array(
'description' => $this->build_direct_description( $prompt, $intent ),
);
if ( 'add' === $intent['action'] ) {
$arguments['position'] = $intent['position'];
if ( 'gutenberg' === $this->editor ) {
$arguments['block_type'] = $this->resolve_block_type_for_prompt( $prompt );
}
} elseif ( 'replace' === $intent['action'] && 'gutenberg' === $this->editor ) {
$arguments['block_type'] = $this->resolve_block_type_for_prompt( $prompt );
}
$context = array(
'post_id' => $post_id,
'selection' => $selection,
'page_content' => $this->page_content,
'editor' => $this->editor,
'block_type_preference' => $this->block_type_preference,
'request_source' => 'chat',
);
$result = $tool->execute( $arguments, $context );
$result['tool_calls'] = array(
array(
'tool' => $tool->name(),
'arguments' => $arguments,
'result' => $result,
'orchestration' => 'direct',
),
);
if ( empty( $result['message'] ) ) {
$result['message'] = $this->direct_success_message( $intent['action'] );
}
return $result;
}
/**
* Classify common editor commands that should not depend on model tool calling.
*/
private function classify_editor_intent( string $prompt, ?array $selection ): ?array {
$text = strtolower( trim( wp_strip_all_tags( $prompt ) ) );
if ( '' === $text ) {
return null;
}
if ( $this->contains_any( $text, array( 'do not insert', "don't insert", 'without inserting', 'preview only', 'just show', 'show me html', 'raw html' ) ) ) {
return null;
}
$mutation_words = array(
'add', 'insert', 'create', 'generate', 'build', 'make', 'put',
'replace', 'update', 'change', 'edit', 'modify', 'restyle',
'redesign', 'rewrite', 'turn', 'convert', 'transform',
);
if ( ! $this->contains_any( $text, $mutation_words ) ) {
return null;
}
if ( $this->contains_any( $text, array( 'whole page', 'entire page', 'full page', 'all sections', 'every section', 'all blocks', 'all headings', 'every heading', 'all text', 'every text', 'everything', 'sitewide', 'reorder', 'rearrange', 'swap sections', 'rewrite the page', 'redesign the page' ) ) ) {
return array(
'action' => 'full_page',
'position' => 'end',
);
}
$replace_words = array( 'replace', 'update', 'change', 'edit', 'modify', 'restyle', 'redesign', 'rewrite', 'turn', 'convert', 'transform', 'make' );
$selected_refs = array( 'selected', 'selection', 'this', 'that', 'this block', 'this section', 'this element', 'current block', 'current section', 'current element', 'it', 'dark mode', 'light mode' );
if ( ! empty( $selection ) && $this->contains_any( $text, $replace_words ) && $this->contains_any( $text, $selected_refs ) ) {
return array(
'action' => 'replace',
'position' => 'end',
);
}
if ( ! empty( $selection ) && $this->contains_any( $text, array( 'dark mode', 'light mode', 'make it dark', 'make it light' ) ) ) {
return array(
'action' => 'replace',
'position' => 'end',
);
}
$add_words = array( 'add', 'insert', 'create', 'generate', 'build', 'make', 'put' );
$add_targets = array( 'section', 'hero', 'banner', 'cta', 'call to action', 'feature', 'features', 'pricing', 'testimonial', 'card', 'cards', 'gallery', 'faq', 'footer', 'header', 'component', 'block' );
if ( $this->contains_any( $text, $add_words ) && $this->contains_any( $text, $add_targets ) ) {
return array(
'action' => 'add',
'position' => $this->detect_insert_position( $text ),
);
}
return null;
}
private function tool_for_direct_intent( string $action ): ?Tool {
if ( 'elementor' === $this->editor ) {
if ( 'add' === $action ) {
return new Elementor_Add_Html_To_Page_Tool( $this );
}
if ( 'replace' === $action ) {
return new Elementor_Replace_Selection_Tool( $this );
}
if ( 'full_page' === $action ) {
return new Elementor_Edit_Full_Page_Tool( $this );
}
return null;
}
if ( 'add' === $action ) {
return new Add_Blocks_To_Page_Tool( $this );
}
if ( 'replace' === $action ) {
return new Replace_Selected_Blocks_Tool( $this );
}
if ( 'full_page' === $action ) {
return new Edit_Full_Page_Tool( $this );
}
return null;
}
private function detect_insert_position( string $text ): string {
if ( $this->contains_any( $text, array( 'at the top', 'to the top', 'above everything', 'before everything', 'beginning of the page', 'start of the page' ) ) ) {
return 'start';
}
if ( $this->contains_any( $text, array( 'before selected', 'before this', 'above selected', 'above this' ) ) ) {
return 'before_selection';
}
if ( $this->contains_any( $text, array( 'after selected', 'after this', 'below selected', 'below this', 'under selected', 'under this' ) ) ) {
return 'after_selection';
}
return 'end';
}
private function detect_native_block_request( string $prompt ): bool {
$text = strtolower( $prompt );
return $this->contains_any(
$text,
array(
'blog posts',
'latest posts',
'post list',
'wordpress native block',
'wordpress native blocks',
'native block',
'native blocks',
'gutenberg block',
'gutenberg blocks',
'core block',
'core blocks',
'wordpress block',
'wordpress blocks',
'query loop',
'archive',
'search form',
'navigation',
'menu',
'post content',
'dynamic',
)
);
}
private function normalize_block_type_preference( string $preference ): string {
$preference = strtolower( trim( $preference ) );
return in_array( $preference, array( 'auto', 'tailwind', 'native' ), true ) ? $preference : 'auto';
}
private function resolve_block_type_for_prompt( string $prompt ): string {
if ( 'native' === $this->block_type_preference ) {
return 'native';
}
if ( 'tailwind' === $this->block_type_preference ) {
return 'tailwind';
}
return $this->detect_native_block_request( $prompt ) ? 'native' : 'tailwind';
}
private function build_direct_description( string $prompt, array $intent ): string {
$description = trim( $prompt );
if ( 'replace' === $intent['action'] ) {
return $description . "\n\nGenerate a complete replacement for the current selection. Preserve the original purpose and content unless the user explicitly asks to change it.";
}
if ( 'full_page' === $intent['action'] ) {
return $description . "\n\nApply this request to the complete current page.";
}
return $description;
}
private function direct_success_message( string $action ): string {
if ( 'replace' === $action ) {
return __( 'Selected content updated.', 'advanced-animation' );
}
if ( 'full_page' === $action ) {
return __( 'Page updated.', 'advanced-animation' );
}
return __( 'Content added to the page.', 'advanced-animation' );
}
private function contains_any( string $text, array $needles ): bool {
foreach ( $needles as $needle ) {
if ( '' !== $needle && false !== strpos( $text, $needle ) ) {
return true;
}
}
return false;
}
/**
* Generate raw Tailwind HTML for a given description.
*
* @param string $description Prompt describing the HTML to generate.
* @param array|null $selection Optional selected block context.
* @param int|null $post_id Current post ID for full-page context.
* @return string|WP_Error HTML string or error.
*/
public function generate_html( string $description, ?array $selection = null, ?int $post_id = null ) {
if ( ! $this->is_available() ) {
return new WP_Error(
'ai_unavailable',
__( 'WordPress AI Client is not available on this site.', 'advanced-animation' )
);
}
$auth = $this->assert_can_edit_optional_post( $post_id );
if ( is_wp_error( $auth ) ) {
return $auth;
}
$contextual = $this->build_contextual_prompt( $description, $selection, $post_id );
$system = 'You are a web developer building WordPress content. ' .
'Respond with a complete HTML document or section. ' .
'Use Tailwind CSS v4 utility classes for ALL styling (layout, typography, colors, spacing, responsive design). ' .
'Do NOT use ";
}
return $context;
} catch ( \Exception $e ) {
return '';
}
}
private function build_elementor_system_prompt( Tool_Registry $registry, ?array $selection, ?int $post_id = null ): string {
$schemas = wp_json_encode( $registry->get_schemas(), JSON_PRETTY_PRINT );
$selection_note = '';
if ( $selection && ! empty( $selection['elementData'] ) ) {
$rendered = $this->render_selection_context( $selection['elementData'] );
if ( ! empty( $rendered ) ) {
$selection_note = "\n\nCurrently selected element in the Elementor editor (rendered HTML + CSS context):\n" . $rendered;
}
} elseif ( $selection && ! empty( $selection['html'] ) ) {
$selection_note = "\n\nCurrently selected element in the Elementor editor (use as context):\n" .
$selection['html'];
}
$page_context = $this->build_page_context( $post_id, $selection );
$image_note = "\n- When building a section that needs images (hero backgrounds, feature images, cards, galleries), " .
"FIRST call search_unsplash_image with descriptive keywords to find suitable images, then use the returned image URLs. " .
"Do NOT invent placeholder image URLs.";
$position_note = "\n- When calling add_elementor_html_to_page, choose position based on the user's intent: " .
"'start' to add at the very top, 'end' (default) to append at the bottom, " .
"'before_selection' or 'after_selection' to insert relative to the selected element.";
$full_page_note = "\n- Call edit_elementor_full_page ONLY when the requested changes affect more than one location on the page, " .
"or when rewriting / creating the whole page. " .
"For a single new section on an existing page use add_elementor_html_to_page; for editing one selected element use replace_elementor_selection. " .
"If the page is EMPTY, prefer add_elementor_html_to_page to create the first section (edit_elementor_full_page also works and will create from scratch).";
$theme_context = $this->build_theme_context();
return 'You are an AI assistant that helps users build websites in the Elementor editor.\n\n' .
'HOW THE SYSTEM WORKS:\n' .
'- The Elementor editor uses native widgets (headings, paragraphs, images, buttons, div blocks, SVGs, etc.).\n' .
'- When you generate HTML content, it will be automatically converted to Elementor widgets on the client side.\n' .
'- CRITICAL: Always generate native HTML with a single