ai_client_factory = $ai_client_factory; } /** * Register hooks for Abilities API integration * * Does nothing if Abilities API is not available (WP < 6.9). */ public function register(): void { if ( ! WordPressRuntimeDetector::supportsAbilitiesApi() ) { return; } add_action( 'wp_abilities_api_categories_init', [ $this, 'registerCategory' ] ); add_action( 'wp_abilities_api_init', [ $this, 'registerAbilities' ] ); } /** * Register the plugin ability category */ public function registerCategory(): void { WordPressRuntimeDetector::registerAbilityCategory( self::CATEGORY, [ 'label' => __( 'AI Product Tools', 'ai-product-tools' ), 'description' => __( 'AI-powered content generation abilities for WooCommerce: descriptions, titles, tags, SEO meta, direct provider invocation, and previewing and confirming a content template run.', 'ai-product-tools' ), ] ); } /** * Register all plugin abilities */ public function registerAbilities(): void { $this->registerGenerateDescription(); $this->registerGenerateTitle(); $this->registerGenerateTags(); $this->registerGenerateSeoMeta(); $this->registerInvokeProvider(); ContentRunAbilities::registerAbilities(); } /** * Register generate-description ability */ private function registerGenerateDescription(): void { WordPressRuntimeDetector::registerAbility( self::PREFIX . 'generate-description', [ 'label' => __( 'Generate Product Description', 'ai-product-tools' ), 'description' => __( 'Generates an AI-powered description for a WooCommerce product. This only generates; it never writes to the product.', 'ai-product-tools' ), 'category' => self::CATEGORY, 'input_schema' => [ 'type' => 'object', 'properties' => [ 'product_id' => [ 'type' => 'integer', 'description' => 'WooCommerce product ID', ], 'is_short' => [ 'type' => 'boolean', 'description' => 'Generate short description instead of full', 'default' => false, ], 'blueprint_id' => [ 'type' => 'integer', 'description' => 'Optional: a specific content template to use for this run, overriding the normal assignment resolution. Has no effect when the description generator is running in Advanced (custom prompt) mode.', ], ], 'required' => [ 'product_id' ], ], 'output_schema' => [ 'type' => 'object', 'properties' => array_merge( [ 'description' => [ 'type' => 'string', 'description' => 'Generated HTML description', ], ], self::blueprintOutputProperties() ), ], 'execute_callback' => [ $this, 'executeGenerateDescription' ], 'permission_callback' => [ $this, 'check_permissions_write' ], 'meta' => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true, 'type' => 'tool', ], 'annotations' => [ 'readonly' => false, 'destructive' => false, 'idempotent' => false, ], ], ] ); } /** * Register generate-title ability */ private function registerGenerateTitle(): void { WordPressRuntimeDetector::registerAbility( self::PREFIX . 'generate-title', [ 'label' => __( 'Generate Product Title', 'ai-product-tools' ), 'description' => __( 'Generates an AI-powered title for a WooCommerce product. This only generates; it never writes to the product.', 'ai-product-tools' ), 'category' => self::CATEGORY, 'input_schema' => [ 'type' => 'object', 'properties' => [ 'product_id' => [ 'type' => 'integer', 'description' => 'WooCommerce product ID', ], 'max_length' => [ 'type' => 'integer', 'description' => 'Maximum title length in characters. Ignored when a content template governs this product.', 'default' => 60, ], 'tone' => [ 'type' => 'string', 'description' => 'Writing tone (e.g. SEO-Focused, Professional, Creative). Ignored when a content template governs this product.', 'default' => 'SEO-Focused', ], 'blueprint_id' => [ 'type' => 'integer', 'description' => 'Optional: a specific content template to use for this run, overriding the normal assignment resolution. Has no effect when the title generator is running in Advanced (custom prompt) mode.', ], ], 'required' => [ 'product_id' ], ], 'output_schema' => [ 'type' => 'object', 'properties' => array_merge( [ 'title' => [ 'type' => 'string', 'description' => 'Generated product title', ], ], self::blueprintOutputProperties() ), ], 'execute_callback' => [ $this, 'executeGenerateTitle' ], 'permission_callback' => [ $this, 'check_permissions_write' ], 'meta' => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true, 'type' => 'tool', ], 'annotations' => [ 'readonly' => false, 'destructive' => false, 'idempotent' => false, ], ], ] ); } /** * Register generate-tags ability */ private function registerGenerateTags(): void { WordPressRuntimeDetector::registerAbility( self::PREFIX . 'generate-tags', [ 'label' => __( 'Generate Product Tags', 'ai-product-tools' ), 'description' => __( 'Generates AI-powered tags for a WooCommerce product. This only generates; it never writes to the product.', 'ai-product-tools' ), 'category' => self::CATEGORY, 'input_schema' => [ 'type' => 'object', 'properties' => [ 'product_id' => [ 'type' => 'integer', 'description' => 'WooCommerce product ID', ], 'max_tags' => [ 'type' => 'integer', 'description' => 'Maximum number of tags to generate. Ignored when a content template governs this product.', 'default' => 5, ], 'keep_existing' => [ 'type' => 'boolean', 'description' => 'Keep existing tags and add complementary ones. Ignored when a content template governs this product.', 'default' => false, ], 'blueprint_id' => [ 'type' => 'integer', 'description' => 'Optional: a specific content template to use for this run, overriding the normal assignment resolution. Has no effect when the description generator is running in Advanced (custom prompt) mode.', ], ], 'required' => [ 'product_id' ], ], 'output_schema' => [ 'type' => 'object', 'properties' => array_merge( [ 'tags' => [ 'type' => 'array', 'items' => [ 'type' => 'string' ], 'description' => 'Generated tags array', ], 'tags_text' => [ 'type' => 'string', 'description' => 'Comma-separated tags string', ], ], self::blueprintOutputProperties() ), ], 'execute_callback' => [ $this, 'executeGenerateTags' ], 'permission_callback' => [ $this, 'check_permissions_write' ], 'meta' => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true, 'type' => 'tool', ], 'annotations' => [ 'readonly' => false, 'destructive' => false, 'idempotent' => false, ], ], ] ); } /** * Register generate-seo-meta ability */ private function registerGenerateSeoMeta(): void { WordPressRuntimeDetector::registerAbility( self::PREFIX . 'generate-seo-meta', [ 'label' => __( 'Generate SEO Meta', 'ai-product-tools' ), 'description' => __( 'Generates AI-powered SEO meta title and description for a WooCommerce product. This only generates; it never writes to the product.', 'ai-product-tools' ), 'category' => self::CATEGORY, 'input_schema' => [ 'type' => 'object', 'properties' => [ 'product_id' => [ 'type' => 'integer', 'description' => 'WooCommerce product ID', ], 'blueprint_id' => [ 'type' => 'integer', 'description' => 'Optional: a specific content template to use for this run, overriding the normal assignment resolution. Has no effect when the SEO meta generator is running in Advanced (custom prompt) mode.', ], ], 'required' => [ 'product_id' ], ], 'output_schema' => [ 'type' => 'object', 'properties' => array_merge( [ 'meta_title' => [ 'type' => 'string', 'description' => 'Generated SEO meta title', ], 'meta_description' => [ 'type' => 'string', 'description' => 'Generated SEO meta description', ], ], self::blueprintOutputProperties() ), ], 'execute_callback' => [ $this, 'executeGenerateSeoMeta' ], 'permission_callback' => [ $this, 'check_permissions_write' ], 'meta' => [ 'show_in_rest' => true, 'mcp' => [ 'public' => true, 'type' => 'tool', ], 'annotations' => [ 'readonly' => false, 'destructive' => false, 'idempotent' => false, ], ], ] ); } /** * Additive output properties shared by every generate-* ability: the * governing Blueprint (or null on the Advanced path) and any plan-limit * notes, both carried through unchanged from ContentGenerationService / * SeoMetaGeneratorService. Existing keys on each ability's own output * stay as they are; this only adds to them. * * @since 2.8.0 * @return array */ private static function blueprintOutputProperties(): array { return [ 'blueprint' => [ 'type' => [ 'object', 'null' ], 'description' => 'The content template that governed this generation, or null when custom prompts (Advanced mode) produced it.', 'properties' => [ 'id' => [ 'type' => [ 'integer', 'null' ] ], 'name' => [ 'type' => 'string' ], 'revision' => [ 'type' => [ 'integer', 'null' ] ], 'builtin' => [ 'type' => 'boolean' ], ], ], 'plan_limits' => [ 'type' => 'array', 'description' => 'Any plan limits this run hit (empty when none did).', 'items' => [ 'type' => 'object', 'properties' => [ 'key' => [ 'type' => 'string' ], 'reason' => [ 'type' => 'string' ], ], ], ], ]; } /** * Register invoke-provider ability * * Exposes a generic AI prompt passthrough to Abilities API consumers. * Gated by manage_woocommerce to prevent unauthorized token spend. * * @since 2.6.0 */ private function registerInvokeProvider(): void { WordPressRuntimeDetector::registerAbility( self::PREFIX . 'invoke-provider', [ 'label' => __( 'Invoke AI Provider', 'ai-product-tools' ), 'description' => __( 'Executes a prompt against the currently configured AI provider. Useful for AI agents and tool-calling clients.', 'ai-product-tools' ), 'category' => self::CATEGORY, 'input_schema' => [ 'type' => 'object', 'properties' => [ 'prompt' => [ 'type' => 'string', 'description' => 'The user prompt to send to the AI provider.', 'minLength' => 1, 'maxLength' => 8000, ], 'provider' => [ 'type' => 'string', 'description' => 'Optional provider id (openai / gemini / claude / openrouter). Defaults to the current aipt_api_provider option.', 'enum' => [ 'openai', 'gemini', 'claude', 'openrouter' ], ], 'model' => [ 'type' => 'string', 'description' => 'Optional model identifier. Defaults to the provider default.', ], ], 'required' => [ 'prompt' ], 'additionalProperties' => false, ], 'output_schema' => [ 'type' => 'object', 'properties' => [ 'text' => [ 'type' => 'string' ], 'provider' => [ 'type' => 'string' ], 'model' => [ 'type' => 'string' ], 'tokenUsage' => [ 'type' => [ 'object', 'null' ] ], 'providerMetadata' => [ 'type' => [ 'object', 'null' ] ], ], 'required' => [ 'text', 'provider' ], ], 'execute_callback' => [ \AIPT\Core\Abilities\InvokeProviderAbility::class, 'execute' ], 'permission_callback' => [ \AIPT\Core\Abilities\InvokeProviderAbility::class, 'permission_check' ], 'meta' => [ 'show_in_rest' => true, 'mcp' => [ 'public' => false, 'type' => 'tool', ], 'annotations' => [ 'readonly' => false, 'destructive' => false, 'idempotent' => false, ], ], ] ); } /** * Execute generate-description ability * * @param array $input Validated input (product_id, is_short). * @return array|\WP_Error Generated description or error. */ public function executeGenerateDescription( array $input ) { if ( null !== ( $rate_error = AbilityRateLimiter::consume( get_current_user_id(), 1 ) ) ) { return $rate_error; } $service = $this->createContentGenerationService(); return $service->generateDescription( [ 'product_id' => absint( $input['product_id'] ), 'is_short' => ! empty( $input['is_short'] ), 'blueprintId' => isset( $input['blueprint_id'] ) ? absint( $input['blueprint_id'] ) : 0, 'origin' => 'ability', ] ); } /** * Execute generate-title ability * * @param array $input Validated input (product_id, max_length, tone). * @return array|\WP_Error Generated title or error. */ public function executeGenerateTitle( array $input ) { if ( null !== ( $rate_error = AbilityRateLimiter::consume( get_current_user_id(), 1 ) ) ) { return $rate_error; } $service = $this->createContentGenerationService(); return $service->generateTitle( [ 'product_id' => absint( $input['product_id'] ), 'max_length' => isset( $input['max_length'] ) ? absint( $input['max_length'] ) : 60, 'tone' => isset( $input['tone'] ) ? sanitize_text_field( $input['tone'] ) : 'SEO-Focused', 'blueprintId' => isset( $input['blueprint_id'] ) ? absint( $input['blueprint_id'] ) : 0, 'origin' => 'ability', ] ); } /** * Execute generate-tags ability * * @param array $input Validated input (product_id, max_tags, keep_existing). * @return array|\WP_Error Generated tags or error. */ public function executeGenerateTags( array $input ) { if ( null !== ( $rate_error = AbilityRateLimiter::consume( get_current_user_id(), 1 ) ) ) { return $rate_error; } $service = $this->createContentGenerationService(); return $service->generateTags( [ 'product_id' => absint( $input['product_id'] ), 'max_tags' => isset( $input['max_tags'] ) ? absint( $input['max_tags'] ) : 5, 'keep_existing' => ! empty( $input['keep_existing'] ), 'blueprintId' => isset( $input['blueprint_id'] ) ? absint( $input['blueprint_id'] ) : 0, 'origin' => 'ability', ] ); } /** * Execute generate-seo-meta ability * * Delegates to the SeoMeta bulk generator service for single-product generation. * * @param array $input Validated input (product_id). * @return array|\WP_Error Generated SEO meta or error. */ public function executeGenerateSeoMeta( array $input ) { if ( null !== ( $rate_error = AbilityRateLimiter::consume( get_current_user_id(), 1 ) ) ) { return $rate_error; } $product_id = absint( $input['product_id'] ); $product = wc_get_product( $product_id ); if ( ! $product ) { return new \WP_Error( 'invalid_product', __( 'Invalid product ID.', 'ai-product-tools' ), [ 'status' => 404 ] ); } $permission_error = ( new ExecutionContextBuilder() )->checkObjectPermission( [ 'type' => 'product', 'id' => $product_id ] ); if ( null !== $permission_error ) { return $permission_error; } if ( null === SeoPluginDetector::detect() ) { return new \WP_Error( 'aipt_seo_plugin_missing', __( 'No supported SEO plugin detected. Please install and activate one of: Yoast SEO, Rank Math, All in One SEO, SEOPress, SiteSEO, The SEO Framework, or Squirrly.', 'ai-product-tools' ), [ 'status' => 400 ] ); } try { $service = new \AIPT\Api\BulkGenerator\SeoMeta\SeoMetaGeneratorService(); $results = $service->bulk_generate( [ $product_id ], [ 'origin' => 'ability', 'blueprintId' => isset( $input['blueprint_id'] ) ? absint( $input['blueprint_id'] ) : 0, ] ); if ( empty( $results ) || ! isset( $results[0] ) ) { return new \WP_Error( 'generation_failed', __( 'SEO meta generation failed to produce a result.', 'ai-product-tools' ), [ 'status' => 500 ] ); } $result = $results[0]; if ( ! empty( $result['error'] ) ) { return new \WP_Error( 'generation_failed', esc_html( $result['error'] ), [ 'status' => 500 ] ); } return [ 'meta_title' => $result['meta_title'] ?? '', 'meta_description' => $result['meta_description'] ?? '', 'blueprint' => $result['blueprint'] ?? null, 'plan_limits' => isset( $result['appliedFreeDefaults'] ) && is_array( $result['appliedFreeDefaults'] ) ? $result['appliedFreeDefaults'] : [], ]; } catch ( \Throwable $e ) { return new \WP_Error( 'generation_failed', esc_html( $e->getMessage() ), [ 'status' => 500 ] ); } } /** * Check write permissions for generation abilities * * @return bool True if current user has manage_woocommerce capability. */ public function check_permissions_write(): bool { return current_user_can( 'manage_woocommerce' ); } /** * Check read permissions for informational abilities * * @return bool True if current user has manage_options capability. */ public function check_permissions(): bool { return current_user_can( 'manage_options' ); } /** * Create ContentGenerationService instance * * @return ContentGenerationService */ private function createContentGenerationService(): ContentGenerationService { $style_descriptions = [ 'Professional' => 'Use clear, concise, and formal language. Focus on features, benefits, and technical details.', 'Encouraging' => 'Use positive, motivational language that inspires confidence and action.', 'Exaggerated' => 'Use dramatic and hyperbolic language to create excitement and emphasis.', 'Friendly' => 'Use warm, conversational language that builds rapport and trust.', 'Storytelling' => 'Create a narrative that engages readers and connects emotionally.', 'Minimalist' => 'Use simple, straightforward language focusing on essential details.', 'Luxurious and Elegant' => 'Use sophisticated, refined language that conveys premium quality and exclusivity.', 'Adventurous' => 'Use dynamic, exciting language that creates a sense of exploration and discovery.', 'Educational' => 'Use informative, detailed language that explains and educates.', 'Humorous' => 'Use light-hearted, playful language with appropriate humor and wit.', ]; /** * Filter style descriptions for content generation * * @param array $style_descriptions Style name => description map. */ $style_descriptions = apply_filters( 'aipt_ability_style_descriptions', $style_descriptions ); return new ContentGenerationService( $this->ai_client_factory, $style_descriptions ); } }