tokens = $tokens ?? new ConfirmTokenStore(); $this->pins = $pins ?? new RunPinService(); $this->applier = $applier ?? new ResultApplier(); $this->resolver = $resolver ?? new AssignmentResolver(); $this->outcomeBuilder = $outcomeBuilder ?? new ConfirmOutcomeBuilder( $this->resolver ); $this->syncRunner = $syncRunner ?? new SyncConfirmRunner( $this->applier, $this->outcomeBuilder, $this->tokens ); $this->revalidator = $revalidator ?? new ConfirmRevalidator( $this->pins, $this->resolver ); } /** * Read-only precheck: whether `confirm_token`/`expected_product_count` * correspond to a real, owned, resolvable preview, with no state change * (no claim, no token spend). Callers that charge a cost for a * confirm-content-run call before running it (the MCP execution * pipeline's daily AI-generation budget) must run this first, since a * syntactically-valid-but-nonexistent or count-mismatched token can * never make a real AI call no matter how many times it is presented, * and charging the shared budget before finding that out lets a caller * drain it for free by repeating a fabricated token. * * @param array{confirm_token:string,expected_product_count:int} $input Ability input, already schema-validated. * @param int $user_id Acting user id. * A token that was already claimed (a repeat of a run that is finished or * still running) is valid but never generates again: confirm() only * returns its stored outcome or the in-use error, so it costs nothing. * * @param array{confirm_token:string,expected_product_count:int} $input Ability input, already schema-validated. * @param int $user_id Acting user id. * @return WP_Error|bool `aipt_ability_token_expired`/`aipt_ability_count_mismatch` on a doomed call; true for a first confirm whose cost is real; false for a repeat that makes no AI call. */ public function precheck( array $input, int $user_id ) { $token = (string) ( $input['confirm_token'] ?? '' ); $data = $this->tokens->get( $token ); if ( null === $data || (int) ( $data['user_id'] ?? 0 ) !== $user_id ) { return $this->expiredError(); } if ( ! empty( $data['claimed'] ) ) { return false; } if ( ! AgentBulkGenerationGate::allows( (int) ( $data['product_count'] ?? 0 ) ) ) { return AgentBulkGenerationGate::denial( (string) ( $data['generator'] ?? '' ) ); } $expected_count = (int) ( $input['expected_product_count'] ?? 0 ); if ( $expected_count !== (int) ( $data['product_count'] ?? -1 ) ) { return new WP_Error( 'aipt_ability_count_mismatch', __( 'The product count no longer matches this preview. Run preview-content-run again, or retry with the expected count.', 'ai-product-tools' ), array( 'status' => 409, 'expected' => (int) ( $data['product_count'] ?? 0 ), ) ); } return true; } /** * @param array{confirm_token:string,expected_product_count:int} $input Ability input, already schema-validated. * @param int $user_id Acting user id. * @return array|WP_Error Confirm response, or an error. */ public function confirm( array $input, int $user_id ) { $token = (string) ( $input['confirm_token'] ?? '' ); $data = $this->tokens->get( $token ); if ( null === $data || (int) ( $data['user_id'] ?? 0 ) !== $user_id ) { return $this->expiredError(); } if ( ! empty( $data['claimed'] ) ) { return $this->alreadyClaimedResult( $data ); } if ( ! AgentBulkGenerationGate::allows( (int) ( $data['product_count'] ?? 0 ) ) ) { return AgentBulkGenerationGate::denial( (string) ( $data['generator'] ?? '' ) ); } if ( ! $this->tokens->claim( $token ) ) { return new WP_Error( 'aipt_ability_token_in_use', __( 'Another request is already confirming this run. Please wait and try again.', 'ai-product-tools' ), array( 'status' => 409 ) ); } $fresh = $this->tokens->get( $token ); if ( null === $fresh ) { $this->tokens->release( $token ); return $this->expiredError(); } if ( ! empty( $fresh['claimed'] ) ) { $this->tokens->release( $token ); return $this->alreadyClaimedResult( $fresh ); } try { return $this->runClaimed( $input, $fresh, $token, $user_id ); } finally { $this->tokens->release( $token ); } } /** * What a caller who finds this token already claimed must see: the * run's real, final outcome once $data says it is finished, or the same * in-use error a concurrent claim() loser hears while it is still a * mid-run progress checkpoint — never a snapshot that can look terminal * (e.g. status 'completed') while products still remain. * * @param array $data Stored token data already known to carry `claimed`. * @return array|WP_Error */ private function alreadyClaimedResult( array $data ) { if ( empty( $data['finished'] ) ) { return new WP_Error( 'aipt_ability_token_in_use', __( 'Another request is already confirming this run. Please wait and try again.', 'ai-product-tools' ), array( 'status' => 409 ) ); } return is_array( $data['outcome'] ?? null ) ? $data['outcome'] : $this->expiredError(); } /** * Everything that runs once this attempt has won the token's claim. * * @param array $input Ability input, already schema-validated. * @param array $data The token's stored preview-time data. * @param string $token Raw confirm token. * @param int $user_id Acting user id. * @return array|WP_Error Confirm response, or an error. */ private function runClaimed( array $input, array $data, string $token, int $user_id ) { $expected_count = (int) ( $input['expected_product_count'] ?? 0 ); if ( $expected_count !== (int) $data['product_count'] ) { return new WP_Error( 'aipt_ability_count_mismatch', __( 'The product count no longer matches this preview. Run preview-content-run again, or retry with the expected count.', 'ai-product-tools' ), array( 'status' => 409, 'expected' => (int) $data['product_count'] ) ); } $precheck = $this->revalidator->recheckBeforeRun( (string) $data['generator'], (string) $data['destination'], (int) $data['pin_id'] ); if ( $precheck instanceof WP_Error ) { return $precheck; } $pin = $precheck; $generator = (string) $data['generator']; $destination = (string) $data['destination']; $overwrite = (string) $data['overwrite']; $groups_by_product = (array) $data['groups_by_product']; list( $remaining, $skipped ) = $this->revalidator->reResolveProducts( $generator, (array) $data['product_ids'], $pin, $groups_by_product ); $blueprints_echo = $this->outcomeBuilder->blueprintsEcho( $generator, $pin, $remaining ); $run_pin_echo = array( 'id' => $pin['id'], 'hash' => $pin['hash'], 'created_at' => $this->isoDate( (string) $pin['createdAt'] ) ); if ( empty( $remaining ) ) { return $this->finish( $token, 'failed', $generator, $run_pin_echo, $blueprints_echo, array(), array(), array(), $skipped, array(), array() ); } $sync_cap = max( 1, min( 5, (int) apply_filters( 'aipt_ability_sync_product_limit', 5 ) ) ); if ( count( $remaining ) <= $sync_cap ) { $rate_error = AbilityRateLimiter::consume( $user_id, count( $remaining ) ); if ( null !== $rate_error ) { return $rate_error; } return $this->runSync( $token, $generator, $remaining, $pin, $destination, $overwrite, $user_id, $skipped, $run_pin_echo, $blueprints_echo ); } $rate_error = AbilityRateLimiter::consume( $user_id, 1 ); if ( null !== $rate_error ) { return $rate_error; } return $this->runAboveCap( $token, $generator, $remaining, $pin, $destination, $overwrite, $skipped, $run_pin_echo, $blueprints_echo ); } /** * Run each remaining product synchronously, in order, updating the * stored outcome after every product so a timeout leaves a truthful * 'partial' outcome behind for a retry to read (nothing is re-run). * * @param string $token Raw confirm token. * @param string $generator Generator key. * @param int[] $remaining Product ids to run, in order. * @param array $pin Loaded run pin. * @param string $destination 'apply' | 'review'. * @param string $overwrite 'replace' | 'empty_only'. * @param int $user_id Acting user id. * @param array $skipped Already-decided skipped entries. * @param array $run_pin_echo Response `run_pin` shape. * @param array $blueprints_echo Response `blueprints` shape. * @return array */ private function runSync( string $token, string $generator, array $remaining, array $pin, string $destination, string $overwrite, int $user_id, array $skipped, array $run_pin_echo, array $blueprints_echo ): array { $run = $this->syncRunner->run( $token, $generator, $remaining, $pin, $destination, $overwrite, $user_id, $skipped, $run_pin_echo, $blueprints_echo ); $status = $this->outcomeBuilder->computeStatus( $run['applied'], $run['staged'], $run['held_back'], $run['failed'] ); return $this->finish( $token, $status, $generator, $run_pin_echo, $blueprints_echo, $run['applied'], $run['staged'], $run['held_back'], $skipped, $run['failed'], $run['plan_limits'] ); } /** * Above the sync cap: a one-time Automation job on Business, else (or on * job-creation failure) a deep link — both consume exactly 1 unit. * * @param string $token Raw confirm token. * @param string $generator Generator key. * @param int[] $remaining Product ids still eligible. * @param array $pin Loaded run pin. * @param string $destination 'apply' | 'review'. * @param string $overwrite 'replace' | 'empty_only'. * @param array $skipped Already-decided skipped entries. * @param array $run_pin_echo Response `run_pin` shape. * @param array $blueprints_echo Response `blueprints` shape. * @return array|WP_Error `aipt_ability_draft_review_unavailable` (403) when this would queue a 'review' job Automation's own draft routing cannot honor. */ private function runAboveCap( string $token, string $generator, array $remaining, array $pin, string $destination, string $overwrite, array $skipped, array $run_pin_echo, array $blueprints_echo ) { if ( apply_filters( 'aipt_automation_surface_is_business', false ) ) { if ( 'review' === $destination && ! apply_filters( 'aipt_draft_review_enabled', false ) ) { return new WP_Error( 'aipt_ability_draft_review_unavailable', __( 'Queuing this run through Automation needs the review queue for background jobs, which is not available on this plan.', 'ai-product-tools' ), array( 'status' => 403 ) ); } $job_id = $this->tryCreateJob( $generator, $remaining, $pin, $destination, $overwrite ); if ( $job_id > 0 ) { $outcome = $this->finish( $token, 'queued', $generator, $run_pin_echo, $blueprints_echo, array(), array(), array(), $skipped, array(), array() ); $outcome['job_id'] = $job_id; $outcome['job_url'] = function_exists( 'admin_url' ) ? admin_url( 'admin.php?page=aipt-automation-jobs&jobId=' . $job_id ) : ''; $this->tokens->recordOutcome( $token, $outcome ); return $outcome; } } $deep_link = AutomationJobLauncher::deepLinkPayload( $generator, $pin, $remaining, count( $remaining ), 0 )['deepLink']; $outcome = $this->finish( $token, 'deep_link', $generator, $run_pin_echo, $blueprints_echo, array(), array(), array(), $skipped, array(), array() ); $outcome['deep_link'] = $deep_link; $this->tokens->recordOutcome( $token, $outcome ); return $outcome; } /** * @param string $generator Generator key. * @param int[] $remaining Product ids. * @param array $pin Loaded run pin. * @param string $destination 'apply' | 'review'. * @param string $overwrite 'replace' | 'empty_only'. * @return int Created job id, or 0 when creation was refused/failed. */ private function tryCreateJob( string $generator, array $remaining, array $pin, string $destination, string $overwrite ): int { $status = ( 'review' === $destination && (bool) apply_filters( 'aipt_content_review_enabled', false ) ) ? 'draft' : 'published'; $nonce = function_exists( 'wp_create_nonce' ) ? wp_create_nonce( 'wp_rest' ) : ''; $payload = array( 'name' => sprintf( /* translators: %s: generator label (e.g. "Product title"). */ __( 'Confirm-content-run: %s', 'ai-product-tools' ), Generators::label( $generator ) ), 'toolType' => Generators::automationToolType( $generator ), 'settings' => array( 'provider' => get_option( 'aipt_api_provider', '' ), 'model' => get_option( 'aipt_model', '' ), 'contentSettings' => array( 'status' => $status ), 'blueprint' => array( 'mode' => 'blueprint', 'runPinId' => $pin['id'], 'runPinHash' => $pin['hash'], 'pinnedAt' => $pin['createdAt'], 'blueprints' => $pin['blueprints'], 'overwrite' => $overwrite, 'trustExistingPin' => true, ), ), 'schedule' => array( 'type' => 'once' ), 'productFilter' => array( 'includeIds' => implode( ',', $remaining ) ), 'totalProducts' => count( $remaining ), ); $job_response = AutomationJobLauncher::createJob( $payload, (string) $nonce ); if ( $job_response instanceof WP_Error || $job_response->get_status() >= 400 ) { return 0; } $data = $job_response->get_data(); return (int) ( $data['data']['id'] ?? 0 ); } /** * Build the final response shape and store it as the token's outcome. * * @return array */ private function finish( string $token, string $status, string $generator, array $run_pin_echo, array $blueprints_echo, array $applied, array $staged, array $held_back, array $skipped, array $failed, array $plan_limits ): array { $outcome = $this->outcomeBuilder->responseShape( $status, $generator, $run_pin_echo, $blueprints_echo, $applied, $staged, $held_back, $skipped, $failed, $plan_limits ); if ( ! empty( $held_back ) ) { $pin = array( 'id' => $run_pin_echo['id'] ); $ids = array_column( $held_back, 'product_id' ); $outcome['deep_link'] = AutomationJobLauncher::deepLinkPayload( $generator, $pin, $ids, count( $ids ), 0 )['deepLink']; } $this->tokens->recordOutcome( $token, $outcome ); return $outcome; } /** * @return WP_Error */ private function expiredError(): WP_Error { return new WP_Error( 'aipt_ability_token_expired', __( 'This preview expired. Run preview-content-run again.', 'ai-product-tools' ), array( 'status' => 410 ) ); } /** * @param string $mysql_datetime A stored MySQL UTC datetime, or an already-ISO string. * @return string ISO 8601. */ private function isoDate( string $mysql_datetime ): string { $timestamp = strtotime( $mysql_datetime . ' UTC' ); return false !== $timestamp ? gmdate( 'c', $timestamp ) : $mysql_datetime; } }