client_factory = $client_factory ?? array( $this, 'default_client_factory' ); $this->clock = $clock ?? array( self::class, 'default_clock' ); $this->sleeper = $sleeper ?? array( self::class, 'default_sleeper' ); } /** * @inheritDoc */ public function call( array $request ): array { $start = $this->now(); $provider = $this->resolve_provider( $request ); $gate = AiSupportGate::guard(); if ( $gate instanceof \WP_Error ) { return $this->error_result( 'aipt_ai_disabled', $gate->get_error_message(), $provider, '', 0, $start, ProviderCallException::AI_DISABLED, false, 503 ); } $model = $this->resolve_model( $request, $provider ); try { $client = call_user_func( $this->client_factory, $provider ); } catch ( ProviderCallException $e ) { return $this->error_result( 'aipt_blueprint_no_credentials', $e->getMessage(), $provider, $model, 0, $start, $e->reason(), false, $e->httpStatus() ); } catch ( \Throwable $e ) { return $this->error_result( 'aipt_blueprint_internal_error', sprintf( '[%s] Client factory threw %s: %s', $provider, get_class( $e ), $e->getMessage() ), $provider, $model, 0, $start, 'internal_error' ); } $schema = isset( $request['schema'] ) && is_array( $request['schema'] ) ? $request['schema'] : array(); $schema_name = isset( $request['schemaName'] ) && is_string( $request['schemaName'] ) && '' !== $request['schemaName'] ? $request['schemaName'] : 'aipt_blueprint_schema'; $system = isset( $request['system'] ) ? (string) $request['system'] : ''; $user = isset( $request['user'] ) ? (string) $request['user'] : ''; $max_tokens = isset( $request['maxTokens'] ) ? max( 0, (int) $request['maxTokens'] ) : 0; $validate = isset( $request['validate'] ) && is_callable( $request['validate'] ) ? $request['validate'] : null; $image = isset( $request['image'] ) && is_array( $request['image'] ) ? $request['image'] : null; $deadline = isset( $request['deadline'] ) ? (float) $request['deadline'] : ( $start + self::DEFAULT_BUDGET_SECONDS ); $max_calls = isset( $request['maxCalls'] ) ? max( 1, min( 2, (int) $request['maxCalls'] ) ) : 1; $supports_interface = $client instanceof StructuredOutputClientInterface; if ( null !== $image && ! ( $supports_interface && $this->supports_vision( $provider, $model ) ) ) { return $this->error_result( 'aipt_blueprint_unsupported_capability', 'The selected model does not support image input.', $provider, $model, 0, $start ); } $capability = $supports_interface ? $this->resolve_structured_output_capability( $provider, $model ) : null; $native = in_array( $capability, array( 'json_schema', 'tool_use', 'response_schema' ), true ); $calls = 0; $attempt_user = $native ? $user : $this->append_json_instruction( $user, $schema, $schema_name ); while ( true ) { if ( $this->now() >= $deadline ) { return $this->error_result( 'aipt_blueprint_timeout', 'No time remained before the deadline.', $provider, $model, $calls, $start ); } ++$calls; try { if ( $supports_interface ) { $options = $this->build_client_options( $native, $schema_name, $max_tokens, $image, $deadline ); /** @var StructuredOutputClientInterface $client */ $result = $client->generate_structured( $system, $attempt_user, $schema, $model, $options ); $raw_text = (string) ( $result['raw_text'] ?? '' ); $native_value = $result['decoded'] ?? null; $used_native = ! empty( $result['used_native'] ); } else { $raw_text = (string) $client->generate_description( $system, $attempt_user, $model ); $native_value = null; $used_native = false; } } catch ( \Throwable $e ) { $classification = $this->classify_provider_exception( $e ); $reason = $classification['reason']; $retryable = $classification['retryable']; $http_status = $classification['httpStatus']; $image_detail = $classification['imageUnavailableDetail']; $code = self::error_code_for_reason( $reason ); $log_message = 'internal_error' === $reason ? sprintf( '[%s] Unclassified %s on call #%d: %s', $provider, get_class( $e ), $calls, $e->getMessage() ) : $e->getMessage(); $available_wait = $this->seconds_remaining( $deadline ) - self::MIN_RETRY_SECONDS; if ( $retryable && $calls < $max_calls && $available_wait > 0 ) { $this->sleep( min( $this->retry_delay_seconds( $classification['retryAfter'] ), $available_wait ) ); if ( 'invalid_schema_request' === $reason ) { $attempt_user = $this->append_json_instruction( $user, $schema, $schema_name, array( $this->safe_message( $e ) ) ); $native = false; } continue; } return $this->error_result( $code, $log_message, $provider, $model, $calls, $start, $reason, $retryable, $http_status, array( 'imageUnavailableDetail' => $image_detail ), $classification['retryAfter'] ); } $decoded = is_array( $native_value ) ? $native_value : null; if ( null === $decoded ) { $parsed = $this->strict_parse( $raw_text ); if ( null === $parsed['value'] ) { if ( $calls < $max_calls && $this->seconds_remaining( $deadline ) >= self::MIN_RETRY_SECONDS ) { $attempt_user = $this->append_json_instruction( $user, $schema, $schema_name, array( $parsed['error'] ) ); continue; } return $this->error_result( 'aipt_blueprint_invalid_output', $parsed['error'], $provider, $model, $calls, $start ); } $decoded = $parsed['value']; } if ( null !== $validate ) { $errors = $this->validation_errors( call_user_func( $validate, $decoded ) ); if ( null !== $errors ) { if ( $calls < $max_calls && $this->seconds_remaining( $deadline ) >= self::MIN_RETRY_SECONDS ) { $attempt_user = $this->append_json_instruction( $user, $schema, $schema_name, $errors ); continue; } return $this->error_result( 'aipt_blueprint_invalid_output', implode( ' ', $errors ), $provider, $model, $calls, $start ); } } return array( 'ok' => true, 'decoded' => $decoded, 'raw' => $raw_text, 'calls' => $calls, 'native' => $used_native, 'provider' => $provider, 'model' => $model, 'durationMs' => $this->elapsed_ms( $start ), 'error' => null, ); } } /** * Default client factory: the same provider-selection/credential/gate * path and sampling defaults the bulk generators already use, so * Blueprint gets identical provider behavior rather than a parallel path. * The client comes without ProviderCallGuard: this class applies its own * deadline-aware retry, and RunScopedCaller its own run-wide stop. * * @param string $provider AIPT provider id. * @return object AIClientInterface instance. */ private function default_client_factory( string $provider ) { return AIClientFactory::create( $provider, array( 'guard' => false ) ); } /** * @return float */ private static function default_clock(): float { return microtime( true ); } private function now(): float { return (float) call_user_func( $this->clock ); } private function elapsed_ms( float $start ): int { return (int) round( ( $this->now() - $start ) * 1000 ); } private function seconds_remaining( float $deadline ): float { return $deadline - $this->now(); } /** * Resolve the provider: the request value, else the same default the * existing generators read (`aipt_api_provider` option, 'openai' default). */ private function resolve_provider( array $request ): string { $provider = isset( $request['provider'] ) && is_string( $request['provider'] ) ? trim( $request['provider'] ) : ''; return '' !== $provider ? $provider : (string) get_option( 'aipt_api_provider', 'openai' ); } /** * Resolve the model: the request value, else the same default the * existing generators read (`aipt_model` option, then the provider's * catalog default), normalized against ModelCatalog. */ private function resolve_model( array $request, string $provider ): string { $model = isset( $request['model'] ) && is_string( $request['model'] ) ? trim( $request['model'] ) : ''; if ( '' === $model ) { $model = (string) get_option( 'aipt_model', '' ); } if ( '' === $model ) { $model = ModelCatalog::get_default_model( $provider ); } return ModelCatalog::normalize_model( $provider, $model ); } /** * Whether the model's structured-output capability is a verified mode. * OpenRouter has no static ModelCatalog entry (custom routes are * validated dynamically), so its real per-model truth comes from the * client's own cached remote-catalog check instead. * * @return string|null One of 'json_schema'|'tool_use'|'response_schema'|null. */ private function resolve_structured_output_capability( string $provider, string $model ): ?string { if ( 'openrouter' === $provider ) { $capability = OpenRouterClient::supports_structured_output( $model ) ? 'json_schema' : null; } else { $capabilities = ModelCatalog::get_capabilities( $provider, $model ); $capability = $capabilities['structured_output'] ?? null; } /** * Filters the resolved structured-output capability for one * provider/model before the engine decides whether to use native * structured output. * * @param string|null $capability One of null|'json_schema'|'tool_use'|'response_schema'. * @param string $provider AIPT provider id. * @param string $model Resolved model id. */ $capability = apply_filters( 'aipt_blueprint_structured_output_capability', $capability, $provider, $model ); return is_string( $capability ) && '' !== $capability ? $capability : null; } /** * Whether the model's vision capability allows the requested image. * OpenRouter has no per-model vision gate today (mirrors existing, * ungated generate_from_vision() behavior across every provider). */ private function supports_vision( string $provider, string $model ): bool { if ( 'openrouter' === $provider ) { return true; } return $this->vision_capability_allows( ModelCatalog::get_capabilities( $provider, $model ) ); } /** * Pure helper so the vision-gate decision is unit-testable against a * synthetic capabilities array, independent of ModelCatalog's live, * hardcoded data (no shipped model currently sets vision to false). */ private function vision_capability_allows( array $capabilities ): bool { return array_key_exists( 'vision', $capabilities ) ? (bool) $capabilities['vision'] : true; } /** * Build the per-call `$options` array passed to * StructuredOutputClientInterface::generate_structured(). */ private function build_client_options( bool $native, string $schema_name, int $max_tokens, ?array $image, float $deadline ): array { $options = array( 'native' => $native, 'schema_name' => $schema_name, ); if ( $max_tokens > 0 ) { $options['max_tokens'] = $max_tokens; } if ( null !== $image ) { $options['image'] = $image; } $remaining = $this->seconds_remaining( $deadline ); if ( $remaining > 0 ) { $options['timeout'] = (int) max( 1, min( 120, floor( $remaining ) ) ); } return $options; } /** * Build the shared JSON-in-prompt fallback instruction: a compact schema * description plus "Return only JSON." - identical for every provider. * * @param string $user Original user prompt. * @param array $schema JSON schema of the expected answer. * @param string $schema_name Short schema name. * @param string[] $errors Repair-retry error list, when retrying. */ private function append_json_instruction( string $user, array $schema, string $schema_name, array $errors = array() ): string { $encoded_schema = wp_json_encode( $schema ); if ( false === $encoded_schema ) { $encoded_schema = '{}'; } $instruction = sprintf( 'Respond with ONLY one JSON object named "%s" that matches this JSON Schema exactly, with no surrounding prose and no Markdown code fence: %s Return only JSON.', $schema_name, $encoded_schema ); if ( ! empty( $errors ) ) { $instruction .= ' The previous answer was invalid for these reasons: ' . implode( '; ', array_map( 'strval', $errors ) ) . '. Correct them and return only the fixed JSON.'; } return $user . "\n\n" . $instruction; } /** * Strict parse: trim; strip at most one whole-text ``` or * ```json fence; `json_decode()` with a depth limit. Anything else is a * parse failure - no brace hunting, no regex field extraction. * * @return array{value: array|null, error: string} */ private function strict_parse( string $text ): array { $trimmed = trim( $text ); if ( '' === $trimmed ) { return array( 'value' => null, 'error' => 'The answer was empty.' ); } $fenced = $this->strip_single_code_fence( $trimmed ); if ( null !== $fenced ) { $trimmed = trim( $fenced ); } $decoded = json_decode( $trimmed, true, self::MAX_JSON_DEPTH ); if ( JSON_ERROR_NONE !== json_last_error() || ! is_array( $decoded ) ) { return array( 'value' => null, 'error' => 'The answer was not a single valid JSON object: ' . json_last_error_msg(), ); } return array( 'value' => $decoded, 'error' => '' ); } /** * Strip exactly one whole-text ``` or ```json fence. Returns null when * the text is not wrapped in exactly one such fence end to end. */ private function strip_single_code_fence( string $text ): ?string { if ( 1 === preg_match( '/^```(?:json)?\s*\n(.*)\n```$/s', $text, $matches ) ) { return $matches[1]; } return null; } /** * @param mixed $validation Return value of the caller's `validate` callable: * array{ok: bool, errors: string[]} or a plain bool. * @return string[]|null Error list when invalid, null when valid. */ private function validation_errors( $validation ): ?array { if ( is_array( $validation ) ) { if ( ! empty( $validation['ok'] ) ) { return null; } $errors = isset( $validation['errors'] ) && is_array( $validation['errors'] ) ? $validation['errors'] : array(); return ! empty( $errors ) ? array_values( array_map( 'strval', $errors ) ) : array( 'The answer did not match the expected structure.' ); } return $validation ? null : array( 'The answer did not match the expected structure.' ); } /** * Classify a caught provider/transport exception into a reason, whether * resending the same request can plausibly succeed, the HTTP status when * known, and any provider-supplied retry delay. * * A ProviderCallException (thrown by all four clients for an HTTP error * body, a transport failure or an unexpected response) maps to the data * it already carries. Every one of those clients already classifies a * real timeout or transport failure into one before it ever reaches * here, so any OTHER Throwable is a code defect in this engine's own * call path, not an unclassified provider failure: never retryable * (retrying would spend a second paid call on a bug), regardless of * what its message happens to say. * * @return array{reason: string, retryable: bool, httpStatus: int|null, retryAfter: int|null} */ private function classify_provider_exception( \Throwable $e ): array { if ( $e instanceof ProviderCallException ) { return array( 'reason' => $e->reason(), 'retryable' => $e->isRetryable(), 'httpStatus' => $e->httpStatus(), 'retryAfter' => $e->retryAfterSeconds(), 'imageUnavailableDetail' => $e->imageUnavailableDetail(), ); } return array( 'reason' => 'internal_error', 'retryable' => false, 'httpStatus' => null, 'retryAfter' => null, 'imageUnavailableDetail' => '', ); } /** * The `error.code` for a classified reason: a dedicated code for a * timeout or an internal code defect, `aipt_blueprint_provider_error` * for every other (provider) reason. * * @param string $reason One of ProviderCallException's reason constants, or this classifier's own 'internal_error'. * @return string */ private static function error_code_for_reason( string $reason ): string { if ( 'network_timeout' === $reason ) { return 'aipt_blueprint_timeout'; } if ( 'internal_error' === $reason ) { return 'aipt_blueprint_internal_error'; } return 'aipt_blueprint_provider_error'; } /** * Delay before a retryable retry: the provider's own Retry-After hint * when present, otherwise a short fixed wait - enough to matter against * a transient rate limit or overload without eating into the call's own * time budget. The caller clamps the result against the deadline. * * @param int|null $retry_after Seconds the provider asked the caller to wait. * @return float */ private function retry_delay_seconds( ?int $retry_after ): float { return ( null !== $retry_after && $retry_after > 0 ) ? (float) $retry_after : 1.5; } private function sleep( float $seconds ): void { if ( $seconds > 0 ) { call_user_func( $this->sleeper, $seconds ); } } private static function default_sleeper( float $seconds ): void { usleep( (int) round( $seconds * 1000000 ) ); } private function safe_message( \Throwable $e ): string { return ErrorHandler::sanitize_error_for_display( $e->getMessage() ); } /** * Build a failed call() result. * * `$reason` is passed whenever the failure is already classified - the * AI-disabled gate check, a classified setup failure or an unclassified * crash from the client-factory catch blocks above, and a classified or * unclassified exception from the call itself further below; every * other failure path (unsupported capability, the deadline itself, * invalid output) omits it and keeps today's behavior - `message` stays * the technical, sanitized string and `reason` mirrors `code`. When * `$reason` is given, `message` becomes the merchant-facing * userMessage() for it and the technical message is logged once instead, * so a provider failure stays diagnosable without exposing it to a merchant. * * @param string|null $reason One of ProviderCallException's reason constants, or the classifier's own 'internal_error' fallback for an unclassified exception. * @param bool $retryable Whether that reason is one a retry can plausibly fix. * @param int|null $http_status HTTP status of the failed call, when known. * @param array $context Extra, reason-specific detail for userMessage() (e.g. 'imageUnavailableDetail'). * @param int|null $retry_after Seconds the provider's own Retry-After hint asked for, when the failure carried one (RunScopedCaller's later-run cool-down). */ private function error_result( string $code, string $message, string $provider, string $model, int $calls, float $start, ?string $reason = null, bool $retryable = false, ?int $http_status = null, array $context = array(), ?int $retry_after = null ): array { $display_message = ErrorHandler::sanitize_error_for_display( $message ); if ( null !== $reason ) { ErrorHandler::log_error( $message, 'error' ); $display_message = ProviderCallException::userMessage( $reason, $this->provider_label( $provider ), $context ); } else { $reason = $code; } return array( 'ok' => false, 'decoded' => null, 'raw' => '', 'calls' => $calls, 'native' => false, 'provider' => $provider, 'model' => $model, 'durationMs' => $this->elapsed_ms( $start ), 'error' => array( 'code' => $code, 'message' => $display_message, 'reason' => $reason, 'retryable' => $retryable, 'httpStatus' => $http_status, 'provider' => $provider, 'retryAfter' => $retry_after, ), ); } /** * Display name for a provider id, used only to build the merchant-facing * userMessage() sentence. */ private function provider_label( string $provider ): string { return ProviderCallException::providerLabel( $provider ); } }