'no-key-saved', self::KEY_INVALID_FORMAT => 'a-key-that-looks-wrong', self::AUTH_INVALID_KEY => 'a-key-the-provider-rejects', self::CONTENT_BLOCKED => 'a-safety-filter-or-a-cut-off-answer-only-stops-that-one-item', self::TRUNCATED_OUTPUT => 'a-safety-filter-or-a-cut-off-answer-only-stops-that-one-item', ); const HELP_REFERENCE_SECTION = 'the-full-reference'; /** * The API host each provider's requests go to, for the * WP_ACCESSIBLE_HOSTS advice of a REQUESTS_BLOCKED failure. */ const PROVIDER_HOSTS = array( 'openai' => 'api.openai.com', 'gemini' => 'generativelanguage.googleapis.com', 'claude' => 'api.anthropic.com', 'openrouter' => 'openrouter.ai', ); /** * Display names for the AIPT provider ids. */ const PROVIDER_LABELS = array( 'openai' => 'OpenAI', 'gemini' => 'Gemini', 'claude' => 'Claude', 'openrouter' => 'OpenRouter', ); /** @var string */ private $reason; /** @var int|null */ private $http_status; /** @var string */ private $provider_error_type; /** @var int|null */ private $retry_after_seconds; /** @var string */ private $provider; /** * @param string $message Technical, ErrorHandler-formatted message (unchanged `getMessage()` contract). * @param string $reason One of this class's reason constants. * @param int|null $http_status HTTP response status, when the failure came from a response. * @param string $provider_error_type Raw provider error type/code/status, for logs only (never shown to a merchant). * @param int|null $retry_after_seconds Seconds the provider asked the caller to wait, when supplied. * @param string $provider AIPT provider id ('openai', 'gemini', 'claude', 'openrouter'). * @param \Throwable|null $previous Previous exception, when wrapping one. * @param int $code Exception code; 0 except where an existing caller reads getCode() (the AI capability gate keeps its 503). */ public function __construct( string $message, string $reason, ?int $http_status = null, string $provider_error_type = '', ?int $retry_after_seconds = null, string $provider = '', ?\Throwable $previous = null, int $code = 0 ) { parent::__construct( $message, $code, $previous ); $this->reason = $reason; $this->http_status = $http_status; $this->provider_error_type = $provider_error_type; $this->retry_after_seconds = $retry_after_seconds; $this->provider = $provider; } /** * No key is saved for the provider. The message keeps the factories' * existing technical wording, which names where the resolver looked. * * @param string $provider AIPT provider id. * @param string $source_label Where the credential resolver looked, e.g. "Not configured". * @return self */ public static function keyMissing( string $provider, string $source_label ): self { return new self( sprintf( /* translators: 1: provider id (openai/gemini/claude/openrouter), 2: source label (e.g. "Not configured"). */ __( '%1$s API key is not configured (resolved source: %2$s). Configure it in Settings > Connectors or AI Product Tools > API.', 'ai-product-tools' ), $provider, $source_label ), self::KEY_MISSING, null, '', null, $provider ); } /** * The site's AI capability gate refused the call. Keeps the gate's own * "[code] message" text and its HTTP status as the exception code, so a * caller that reads getCode() still sees 503. * * @param \WP_Error $gate AiSupportGate::guard()'s error. * @param string $provider AIPT provider id, when known. * @return self */ public static function aiDisabled( \WP_Error $gate, string $provider = '' ): self { $data = $gate->get_error_data(); $status = ( is_array( $data ) && isset( $data['status'] ) ) ? (int) $data['status'] : 503; return new self( '[' . $gate->get_error_code() . '] ' . $gate->get_error_message(), self::AI_DISABLED, $status, (string) $gate->get_error_code(), null, $provider, null, $status ); } /** * The provider id is not one of the four the plugin supports. * * @param string $provider The unsupported id as given. * @return self */ public static function unsupportedProvider( string $provider ): self { return new self( sprintf( /* translators: %s: the provider id that was requested. */ __( 'Unsupported AI provider: %s.', 'ai-product-tools' ), $provider ), self::UNSUPPORTED_PROVIDER, null, '', null, $provider ); } public function reason(): string { return $this->reason; } public function httpStatus(): ?int { return $this->http_status; } public function providerErrorType(): string { return $this->provider_error_type; } public function retryAfterSeconds(): ?int { return $this->retry_after_seconds; } public function provider(): string { return $this->provider; } /** * The specific, already-safe-for-display image-loading cause for an * `image_unavailable` failure - VisionImageEncoder's own exception * message ("Unsupported image type.", "Image too large (>20MB).", a * fetch or HTTP failure, ...), carried as the previous exception by * every client's vision-encoding catch block. Empty when this is not an * `image_unavailable` failure, or carries no such detail. * * @return string */ public function imageUnavailableDetail(): string { if ( self::IMAGE_UNAVAILABLE !== $this->reason ) { return ''; } $previous = $this->getPrevious(); return ( $previous instanceof \Throwable ) ? $previous->getMessage() : ''; } public function isRetryable(): bool { return self::isRetryableReason( $this->reason ); } public function isRunWide(): bool { return self::isRunWideReason( $this->reason ); } public static function isRetryableReason( string $reason ): bool { return in_array( $reason, self::RETRYABLE_REASONS, true ); } public static function isRunWideReason( string $reason ): bool { return in_array( $reason, self::RUN_WIDE_REASONS, true ); } public static function isKnownReason( string $reason ): bool { return in_array( $reason, self::REASONS, true ); } /** * The HTTP status a route reports for a classified provider failure: * 400 for a setup problem only the merchant can fix (no key, an * unsupported id, an OpenRouter privacy setting, blocked outgoing * requests), 503 for AI turned off or a failure worth retrying shortly, * 502 otherwise. Never the status the provider answered with, which * stays in httpStatus() for diagnostics. Shared by every admin route * that reports one, so the mapping cannot drift between them. * * @param string $reason One of this class's reason constants. * @return int */ public static function httpStatusFor( string $reason ): int { if ( self::AI_DISABLED === $reason ) { return 503; } if ( in_array( $reason, array( self::KEY_MISSING, self::UNSUPPORTED_PROVIDER, self::DATA_POLICY_BLOCKED, self::REQUESTS_BLOCKED ), true ) ) { return 400; } if ( in_array( $reason, array( self::RATE_LIMITED, self::PROVIDER_UNAVAILABLE, self::NETWORK_TIMEOUT, self::NETWORK_ERROR ), true ) ) { return 503; } return 502; } /** * The reason for a request that failed before any response came back * (the `WP_Error` a `wp_remote_*()` call returned), shared by every * provider client: WordPress refusing to send it at all, a timeout, or * any other connection failure. * * @param \WP_Error $error The transport error. * @return string One of this class's reason constants. */ public static function transportReason( \WP_Error $error ): string { if ( 'http_request_not_executed' === $error->get_error_code() ) { return self::REQUESTS_BLOCKED; } $lower = strtolower( $error->get_error_message() ); return ( false !== strpos( $lower, 'timed out' ) || false !== strpos( $lower, 'timeout' ) ) ? self::NETWORK_TIMEOUT : self::NETWORK_ERROR; } /** * Where a merchant can read what a failure means and how to fix it: the * section of the provider errors documentation for this reason. A reason * this class does not define still gets the page's full reference table, * which lists every message the plugin shows. * * @param string $reason One of this class's reason constants. * @return string Absolute https URL. */ public static function helpUrl( string $reason ): string { $section = self::HELP_SECTIONS[ $reason ] ?? self::HELP_REFERENCE_SECTION; return self::HELP_PAGE_URL . '#' . $section; } /** * Display name for an AIPT provider id ("OpenAI" for "openai"), used to * build merchant-facing sentences. * * @param string $provider AIPT provider id. * @return string */ public static function providerLabel( string $provider ): string { $id = strtolower( trim( $provider ) ); if ( isset( self::PROVIDER_LABELS[ $id ] ) ) { return self::PROVIDER_LABELS[ $id ]; } return '' !== $id ? ucfirst( $id ) : __( 'The AI provider', 'ai-product-tools' ); } /** * The merchant-facing message for this failure. * * @param string $fallback_provider Provider id to name when the exception carries none. * @param bool $with_next_steps Add {@see self::nextSteps()} for a failure that keeps * happening. Admin surfaces pass true (displayMessage(), * toResponseArray()); the storefront chatbot keeps the * bare sentence, since a shopper cannot act on it. * @return string */ public function merchantMessage( string $fallback_provider = '', bool $with_next_steps = false ): string { $provider = '' !== $this->provider ? $this->provider : $fallback_provider; $context = array(); $image_detail = $this->imageUnavailableDetail(); if ( '' !== $image_detail ) { $context['imageUnavailableDetail'] = $image_detail; } $host = self::PROVIDER_HOSTS[ strtolower( trim( $provider ) ) ] ?? ''; if ( self::REQUESTS_BLOCKED === $this->reason && '' !== $host ) { $context['providerHost'] = $host; } $label = self::providerLabel( $provider ); $message = self::userMessage( $this->reason, $label, $context ); $next = $with_next_steps ? self::nextSteps( $this->reason, $label ) : ''; return '' !== $next ? $message . ' ' . $next : $message; } /** * What the merchant can do when a failure keeps happening, for the * reasons whose own sentence only says "try again": a rate limit that * returns on every run is the account's own ceiling (Help Scout #921, * Gemini's free tier), not a blip, and only the merchant can lift it. * * @param string $reason One of this class's reason constants. * @param string $provider_label Display name of the provider, e.g. "OpenAI". * @return string The sentence, or '' for a reason that needs none. */ public static function nextSteps( string $reason, string $provider_label ): string { if ( self::RATE_LIMITED !== $reason ) { return ''; } return sprintf( /* translators: %s: AI provider name, e.g. "Gemini". */ __( 'If this keeps happening, your %s plan allows fewer requests than this run sends: set a pause between requests in Settings > AI connection, raise the limit with the provider, or choose another model.', 'ai-product-tools' ), $provider_label ); } /** * The `providerError` shape every generation response carries for a * failed provider call, on the content structure path and the custom * prompt path alike. `runWide` tells a caller that later requests to the * same provider would fail the same way, so a batch should stop. * `helpUrl` is the documentation section for this reason * ({@see self::helpUrl()}). * * @param string $fallback_provider Provider id to use when the exception carries none. * @return array{code:string,reason:string,message:string,provider:string,retryable:bool,runWide:bool,httpStatus:int|null,retryAfter:int|null,helpUrl:string} */ public function toResponseArray( string $fallback_provider = '' ): array { $provider = '' !== $this->provider ? $this->provider : $fallback_provider; return array( 'code' => 'aipt_provider_error', 'reason' => $this->reason, 'message' => $this->merchantMessage( $provider, true ), 'provider' => $provider, 'retryable' => $this->isRetryable(), 'runWide' => $this->isRunWide(), 'httpStatus' => $this->http_status, 'retryAfter' => $this->retry_after_seconds, 'helpUrl' => self::helpUrl( $this->reason ), ); } /** * The message to show a merchant for any caught failure: the translated * sentence for a classified provider failure, otherwise the exception's * own text made safe for display. The technical text of a provider * failure is never returned here; whoever catches it logs it. * * @param \Throwable $e The caught failure. * @param string $provider Provider id to name when the exception carries none. * @return string */ public static function displayMessage( \Throwable $e, string $provider = '' ): string { if ( $e instanceof self ) { return $e->merchantMessage( $provider, true ); } return \AIPT\Core\ErrorHandler::sanitize_error_for_display( $e->getMessage() ); } /** * The `providerError` for a caught failure, or null when it is not a * classified provider failure. * * @param \Throwable $e The caught failure. * @param string $provider Provider id to use when the exception carries none. * @return array|null See toResponseArray(). */ public static function providerErrorFor( \Throwable $e, string $provider = '' ): ?array { return $e instanceof self ? $e->toResponseArray( $provider ) : null; } /** * Build the merchant-facing, translated, actionable sentence for a * classified reason. Safe to call with any reason string, including one * this class does not define, so a caller never needs to guard the call. * * @param string $reason One of this class's reason constants. * @param string $provider_label Display name of the provider, e.g. "OpenAI". * @param array $context Optional. 'credentialSourceLabel' (string) names where the * rejected key is saved, e.g. "WordPress Connectors"; when * omitted, it is resolved from CredentialResolver, falling * back to a generic "the plugin settings" phrase. * 'providerHost' (string) names the API host to allow for a * REQUESTS_BLOCKED failure, e.g. "api.openai.com". * @return string */ public static function userMessage( string $reason, string $provider_label, array $context = array() ): string { switch ( $reason ) { case self::AUTH_INVALID_KEY: $source = isset( $context['credentialSourceLabel'] ) && is_string( $context['credentialSourceLabel'] ) && '' !== $context['credentialSourceLabel'] ? $context['credentialSourceLabel'] : self::resolve_credential_source_label( $provider_label ); if ( '' === $source ) { $source = __( 'the plugin settings', 'ai-product-tools' ); } return sprintf( /* translators: 1: AI provider name, e.g. "OpenAI". 2: where the API key is saved, e.g. "WordPress Connectors" or "the plugin settings". */ __( '%1$s rejected the saved API key. Update it in %2$s.', 'ai-product-tools' ), $provider_label, $source ); case self::AUTH_FORBIDDEN: return sprintf( /* translators: %s: AI provider name, e.g. "OpenAI". */ __( 'Your %s API key does not have access to this model or action.', 'ai-product-tools' ), $provider_label ); case self::MODEL_NOT_FOUND: return sprintf( /* translators: %s: AI provider name, e.g. "OpenAI". */ __( '%s does not offer the selected model. Choose another model.', 'ai-product-tools' ), $provider_label ); case self::REQUESTS_BLOCKED: $host = isset( $context['providerHost'] ) && is_string( $context['providerHost'] ) ? trim( $context['providerHost'] ) : ''; if ( '' !== $host ) { return sprintf( /* translators: 1: AI provider name, e.g. "OpenAI". 2: the provider's API host, e.g. "api.openai.com". */ __( 'This site blocks outgoing requests (WP_HTTP_BLOCK_EXTERNAL in wp-config.php), so %1$s cannot be reached. Add %2$s to WP_ACCESSIBLE_HOSTS or ask your host to allow it.', 'ai-product-tools' ), $provider_label, $host ); } return sprintf( /* translators: %s: AI provider name, e.g. "OpenAI". */ __( "This site blocks outgoing requests (WP_HTTP_BLOCK_EXTERNAL in wp-config.php), so %s cannot be reached. Add the provider's API host to WP_ACCESSIBLE_HOSTS or ask your host to allow it.", 'ai-product-tools' ), $provider_label ); case self::DATA_POLICY_BLOCKED: return sprintf( /* translators: %s: AI provider name, e.g. "OpenRouter". */ __( "%s has no provider for this model that your account's privacy settings allow. Change them at openrouter.ai/settings/privacy (free models have their own setting) or choose another model.", 'ai-product-tools' ), $provider_label ); case self::QUOTA_EXHAUSTED: return sprintf( /* translators: %s: AI provider name, e.g. "OpenAI". */ __( 'Your %s account has no quota or credit left. Check your billing with the provider.', 'ai-product-tools' ), $provider_label ); case self::RATE_LIMITED: return sprintf( /* translators: %s: AI provider name, e.g. "OpenAI". */ __( '%s is limiting requests right now. Try again in a minute.', 'ai-product-tools' ), $provider_label ); case self::PROVIDER_UNAVAILABLE: return sprintf( /* translators: %s: AI provider name, e.g. "OpenAI". */ __( '%s is overloaded or unavailable right now. Try again in a few minutes.', 'ai-product-tools' ), $provider_label ); case self::NETWORK_TIMEOUT: case self::NETWORK_ERROR: return sprintf( /* translators: %s: AI provider name, e.g. "OpenAI". */ __( "Could not reach %s. Check the site's connection and whether a firewall or security plugin blocks outbound requests, then try again.", 'ai-product-tools' ), $provider_label ); case self::CONTENT_BLOCKED: return sprintf( /* translators: %s: AI provider name, e.g. "OpenAI". */ __( '%s declined to answer because of its safety filters.', 'ai-product-tools' ), $provider_label ); case self::TRUNCATED_OUTPUT: return sprintf( /* translators: %s: AI provider name, e.g. "OpenAI". */ __( '%s stopped before finishing the answer.', 'ai-product-tools' ), $provider_label ); case self::REQUEST_TOO_LARGE: return sprintf( /* translators: %s: AI provider name, e.g. "OpenAI". */ __( 'The request was too large for %s. Shorten the product content or choose a model with a larger context window.', 'ai-product-tools' ), $provider_label ); case self::IMAGE_UNAVAILABLE: $detail = isset( $context['imageUnavailableDetail'] ) && is_string( $context['imageUnavailableDetail'] ) ? trim( $context['imageUnavailableDetail'] ) : ''; if ( '' !== $detail ) { return sprintf( /* translators: 1: AI provider name, e.g. "OpenAI". 2: the specific image problem, e.g. "Image too large (>20MB)." */ __( 'The image could not be loaded to send to %1$s: %2$s', 'ai-product-tools' ), $provider_label, $detail ); } return sprintf( /* translators: %s: AI provider name, e.g. "OpenAI". */ __( 'The image could not be loaded to send to %s. Check that the file exists and that the site can read it.', 'ai-product-tools' ), $provider_label ); case self::KEY_MISSING: return sprintf( /* translators: %s: AI provider name, e.g. "OpenAI". */ __( 'No %s API key is saved. Add one in Settings > Connectors or AI Product Tools > API.', 'ai-product-tools' ), $provider_label ); case self::KEY_INVALID_FORMAT: return sprintf( /* translators: %s: AI provider name, e.g. "OpenAI". */ __( "This does not look like a valid %s API key. Check that you copied the whole key from the provider's dashboard.", 'ai-product-tools' ), $provider_label ); case self::WORKSPACE_REQUIRED: return sprintf( /* translators: %s: AI provider name, e.g. "Claude". */ __( 'This %s API key is not scoped to a workspace. Add the Workspace ID for this key in Settings > Connection (or where you entered the key) and try again.', 'ai-product-tools' ), $provider_label ); case self::AI_DISABLED: return sprintf( /* translators: %s: AI provider name, e.g. "OpenAI". */ __( 'AI features are turned off on this site, so %s cannot be used. Set WP_AI_SUPPORT to true to turn them back on.', 'ai-product-tools' ), $provider_label ); case self::UNSUPPORTED_PROVIDER: return sprintf( /* translators: %s: the AI provider id that was requested. */ __( '%s is not a supported AI provider. Choose OpenAI, Gemini, Claude or OpenRouter in the settings.', 'ai-product-tools' ), $provider_label ); case self::INVALID_SCHEMA_REQUEST: case self::BAD_REQUEST: case self::MALFORMED_RESPONSE: return sprintf( /* translators: %s: AI provider name, e.g. "OpenAI". */ __( '%s could not process the request. Details were logged for troubleshooting.', 'ai-product-tools' ), $provider_label ); default: return sprintf( /* translators: %s: AI provider name, e.g. "OpenAI". */ __( '%s could not complete this request. Details were logged for troubleshooting.', 'ai-product-tools' ), $provider_label ); } } /** * Resolve the saved credential's source label for the auth_invalid_key * message, e.g. "WordPress Connectors". Returns an empty string (the * caller then falls back to a generic phrase) when the resolver cannot * run or finds nothing, so a lookup failure never surfaces as a fatal. * * @param string $provider_label Display name; lowercases to the raw AIPT provider id. * @return string */ private static function resolve_credential_source_label( string $provider_label ): string { if ( ! class_exists( CredentialResolver::class ) ) { return ''; } try { $label = CredentialResolver::instance()->getSourceLabel( strtolower( $provider_label ) ); if ( ! is_string( $label ) || '' === $label ) { return ''; } return __( 'Not configured', 'ai-product-tools' ) === $label ? '' : $label; } catch ( \Throwable $e ) { return ''; } } }