user_key(); default: return ''; } } /** * Sensible default model id per provider, used when the merchant leaves the * shared Model field blank. * * @param string $provider Provider slug. * @return string */ protected function default_model_for( $provider ) { switch ( $provider ) { case 'openai': // Latest OpenAI flagship (merchant can pick any model in Settings). $model = 'gpt-4o'; break; case 'anthropic': // Latest fast Claude (Haiku 4.5). $model = 'claude-haiku-4-5-20251001'; break; case 'gemini': // Latest fast Gemini. $model = 'gemini-2.5-flash'; break; default: $model = self::DEFAULT_MODEL; } /** * Filter the default model used for a given provider when none is set. * * @param string $model Default model id. * @param string $provider Provider slug. */ return (string) apply_filters( 'arwc_ai_provider_default_model', $model, $provider ); } /** * The AI proxy URL (filterable). Empty string disables proxy mode. * * @return string */ public function proxy_url() { return trim( (string) apply_filters( 'arwc_ai_proxy_url', self::DEFAULT_PROXY_URL ) ); } /** * Whether AI runs through the AgenticTrack proxy (no per-site key needed). * * A merchant-supplied key always wins (they opted to use their own account); * otherwise, if a proxy URL is configured, we use it. * * @return bool */ public function uses_proxy() { return '' === $this->user_key() && '' !== $this->proxy_url(); } /** * Whether this store is on a local/development domain (localhost, *.local, * *.test, …). The built-in AI proxy authenticates by the public site URL, so a * local site is a common cause of confusing AI failures — we detect it to give * a clearer message and point local testers at their own provider key. * * @return bool */ public function is_local_site() { $host = wp_parse_url( home_url(), PHP_URL_HOST ); $host = is_string( $host ) ? strtolower( $host ) : ''; if ( '' === $host ) { return false; } if ( in_array( $host, array( 'localhost', '127.0.0.1', '::1' ), true ) ) { return true; } foreach ( array( '.local', '.test', '.localhost' ) as $suffix ) { if ( substr( $host, -strlen( $suffix ) ) === $suffix ) { return true; } } return false; } /** * Whether AI, as currently configured, cannot run because it would rely on the * built-in proxy from a local/dev site. When true, the UI should surface the * "use your own key" note rather than a free-quota counter that won't apply. * * @return bool */ public function proxy_blocked_locally() { return $this->uses_proxy() && $this->is_local_site(); } /** * User-facing note for when AI can't run on a local/dev site via the built-in * service. Empty when AI can run (Pro live site, or own provider key). * * @return string */ public function env_note() { if ( $this->proxy_blocked_locally() ) { return __( 'AI fixes need a publicly reachable store or your own API key — this looks like a local/dev site. Add a provider key under Settings → AI to use AI here.', 'agentictrack-agent-readiness-for-woocommerce' ); } return ''; } /** * A short hint appended to built-in-service AI errors: on a local/dev site the * built-in service often can't be used, so steer testers to their own key. * * @return string Empty unless the built-in proxy is in use on a local site. */ protected function ai_env_hint() { if ( $this->uses_proxy() && $this->is_local_site() ) { return __( 'Note: this looks like a local/development site, which the built-in AI service can’t always reach. For local testing, choose a provider and add your own API key (OpenAI, Anthropic, Gemini, or OpenRouter) under Agent Readiness → Settings.', 'agentictrack-agent-readiness-for-woocommerce' ); } return ''; } /** * Whether AI can run at all for the selected provider. * * For a direct provider (OpenAI / Anthropic / Gemini / explicit OpenRouter) this * means the merchant has supplied that provider's key. For the default ('auto') * it means either a per-site OpenRouter key OR the AgenticTrack AI service. * * @return bool */ public function is_configured() { $provider = $this->active_provider(); if ( in_array( $provider, array( 'openai', 'anthropic', 'gemini', 'openrouter' ), true ) ) { return '' !== $this->provider_key( $provider ); } return '' !== $this->user_key() || '' !== $this->proxy_url(); } /** * Hard call cap for one run (filterable, clamped 1–20). * * @return int */ public function call_cap() { $cap = (int) apply_filters( 'arwc_ai_call_cap', self::MAX_CALLS_PER_RUN ); return max( 1, min( 20, $cap ) ); } /** * Hard output-token cap per request (filterable, clamped 64–1000). * * @return int */ public function token_cap() { $cap = (int) apply_filters( 'arwc_ai_token_cap', self::MAX_TOKENS ); return max( 64, min( 1000, $cap ) ); } /** * Remaining calls in this run. * * @return int */ public function calls_remaining() { return max( 0, $this->call_cap() - $this->calls ); } /** * HTTP timeout for a completion, in seconds. * * AI generations can be slow (provider cold starts, long routes), so this is * generous by default and filterable for slow hosts. Clamped 10–120s. * * @return int */ public function request_timeout() { $timeout = (int) apply_filters( 'arwc_ai_timeout', 60 ); return max( 10, min( 120, $timeout ) ); } /** * Test whether an OpenRouter API key is accepted, without spending tokens. * * Hits the authenticated `/key` info endpoint: a 200 confirms the key works * (and returns credit usage/limit), a 401 means it was rejected. Pass a key to * test an as-yet-unsaved value from the settings field; otherwise the saved * option is used. Returns a small info array on success or a WP_Error whose * message is safe to show the merchant. * * @param string $key Optional key to test (falls back to the saved option). * @return array|WP_Error */ public function test_key( $key = '' ) { $key = trim( (string) $key ); if ( '' === $key ) { $key = trim( (string) get_option( self::OPTION_API_KEY, '' ) ); } if ( '' === $key ) { return new WP_Error( 'arwc_ai_no_key', __( 'Enter an OpenRouter API key first, then test it.', 'agentictrack-agent-readiness-for-woocommerce' ) ); } $response = wp_remote_get( self::KEY_ENDPOINT, array( 'timeout' => 15, 'headers' => array( 'Authorization' => 'Bearer ' . $key, 'Content-Type' => 'application/json', ), ) ); if ( is_wp_error( $response ) ) { return $response; } $code = (int) wp_remote_retrieve_response_code( $response ); if ( 401 === $code || 403 === $code ) { return new WP_Error( 'arwc_ai_unauthorized', __( 'OpenRouter rejected this API key. Double-check it and save again.', 'agentictrack-agent-readiness-for-woocommerce' ) ); } if ( 200 !== $code ) { return new WP_Error( 'arwc_ai_key_http', sprintf( /* translators: %d: HTTP status code. */ __( 'Could not verify the key (HTTP %d).', 'agentictrack-agent-readiness-for-woocommerce' ), $code ) ); } $data = json_decode( (string) wp_remote_retrieve_body( $response ), true ); $info = ( is_array( $data ) && isset( $data['data'] ) && is_array( $data['data'] ) ) ? $data['data'] : array(); return array( 'ok' => true, 'label' => isset( $info['label'] ) ? (string) $info['label'] : '', 'usage' => isset( $info['usage'] ) && is_numeric( $info['usage'] ) ? (float) $info['usage'] : null, 'limit' => array_key_exists( 'limit', $info ) && is_numeric( $info['limit'] ) ? (float) $info['limit'] : null, ); } /** * Fetch the live list of available OpenRouter models for the model picker. * * Hits the public `/models` catalogue (auth is optional; the key is sent when * present so any account-specific availability is reflected). The result is * cached in a transient for 6h so opening Settings does not call out every * time; pass $force to bypass the cache. Returns a list of * `[ 'id' => ..., 'name' => ..., 'prompt' => ..., 'completion' => ... ]` or a * WP_Error on failure (fail soft — the field stays usable as free text). * * @param bool $force Skip the cache and re-fetch. * @return array>|WP_Error */ public function list_models( $force = false ) { if ( ! $force ) { $cached = get_transient( self::MODELS_TRANSIENT ); if ( is_array( $cached ) ) { return $cached; } } $headers = array( 'Content-Type' => 'application/json' ); $key = trim( (string) get_option( self::OPTION_API_KEY, '' ) ); if ( '' !== $key ) { $headers['Authorization'] = 'Bearer ' . $key; } $response = wp_remote_get( self::MODELS_ENDPOINT, array( 'timeout' => 20, 'headers' => $headers, ) ); if ( is_wp_error( $response ) ) { return $response; } $code = (int) wp_remote_retrieve_response_code( $response ); if ( 200 !== $code ) { return new WP_Error( 'arwc_models_http', sprintf( /* translators: %d: HTTP status code. */ __( 'Could not load the model list (HTTP %d).', 'agentictrack-agent-readiness-for-woocommerce' ), $code ) ); } $data = json_decode( (string) wp_remote_retrieve_body( $response ), true ); if ( ! is_array( $data ) || empty( $data['data'] ) || ! is_array( $data['data'] ) ) { return new WP_Error( 'arwc_models_bad', __( 'The model list could not be read.', 'agentictrack-agent-readiness-for-woocommerce' ) ); } $models = array(); foreach ( $data['data'] as $model ) { if ( empty( $model['id'] ) ) { continue; } $pricing = isset( $model['pricing'] ) && is_array( $model['pricing'] ) ? $model['pricing'] : array(); $models[] = array( 'id' => (string) $model['id'], 'name' => isset( $model['name'] ) ? (string) $model['name'] : (string) $model['id'], 'prompt' => isset( $pricing['prompt'] ) ? (string) $pricing['prompt'] : '', 'completion' => isset( $pricing['completion'] ) ? (string) $pricing['completion'] : '', ); } usort( $models, static function ( $a, $b ) { return strcmp( $a['id'], $b['id'] ); } ); set_transient( self::MODELS_TRANSIENT, $models, 6 * HOUR_IN_SECONDS ); return $models; } /** * Run a single chat completion. * * Enforces the call cap (refusing once exhausted) and the token cap. Returns * the assistant's plain-text content, or a WP_Error on any failure. Fails * closed: a missing key, exhausted cap, network error, non-200, or * unparseable body all return WP_Error and write nothing. * * @param string $system System prompt. * @param string $user User prompt. * @return string|WP_Error */ public function complete( $system, $user ) { // When the merchant has selected a specific provider to use with their own // key, send the request straight to that provider (isolated from the default // OpenRouter / AgenticTrack-service path below). $provider = $this->active_provider(); if ( in_array( $provider, array( 'openai', 'anthropic', 'gemini' ), true ) ) { return $this->complete_direct_provider( $provider, $system, $user ); } if ( ! $this->is_configured() ) { return new WP_Error( 'arwc_ai_no_key', __( 'AI is not available yet. It works out of the box on the AgenticTrack proxy, or you can add your own OpenRouter API key under Agent Readiness settings.', 'agentictrack-agent-readiness-for-woocommerce' ) ); } if ( $this->calls >= $this->call_cap() ) { return new WP_Error( 'arwc_ai_cap_reached', __( 'AI usage cap reached for this run. Run again to continue.', 'agentictrack-agent-readiness-for-woocommerce' ) ); } $this->calls++; $model = trim( (string) get_option( self::OPTION_MODEL, '' ) ); if ( '' === $model ) { /** * Filter the default AI model used when the merchant hasn't chosen one. * Must be a free (":free") model to work through the proxy. * * @param string $model Default model id. */ $model = (string) apply_filters( 'arwc_ai_default_model', self::DEFAULT_MODEL ); } $payload = array( 'model' => $model, 'max_tokens' => $this->token_cap(), 'temperature' => 0.2, 'messages' => array( array( 'role' => 'system', 'content' => (string) $system, ), array( 'role' => 'user', 'content' => (string) $user, ), ), ); if ( $this->uses_proxy() ) { // Proxy mode: the OpenRouter key lives on the proxy, never here. We send // the site URL and license so the proxy can authorize and rate-limit. $payload['site'] = get_site_url(); $payload['license'] = (string) get_option( ARWC_License::OPTION_LICENSE_KEY, '' ); $endpoint = $this->proxy_url(); $headers = array( 'Content-Type' => 'application/json' ); } else { // Direct mode: the merchant's own key authenticates straight to OpenRouter. $endpoint = self::ENDPOINT; $headers = array( 'Authorization' => 'Bearer ' . $this->user_key(), 'Content-Type' => 'application/json', 'HTTP-Referer' => home_url( '/' ), 'X-Title' => 'AgenticTrack', ); } $response = wp_remote_post( $endpoint, array( 'timeout' => $this->request_timeout(), 'headers' => $headers, 'body' => wp_json_encode( $payload ), ) ); if ( is_wp_error( $response ) ) { // Turn a raw cURL timeout into actionable guidance. if ( false !== stripos( $response->get_error_message(), 'timed out' ) ) { return new WP_Error( 'arwc_ai_timeout', sprintf( /* translators: %d: timeout in seconds. */ __( 'The AI request timed out after %d seconds. This is a network/provider delay, not the plugin — try again, choose a faster model, or raise the timeout via the arwc_ai_timeout filter.', 'agentictrack-agent-readiness-for-woocommerce' ), $this->request_timeout() ) ); } return $response; } $code = (int) wp_remote_retrieve_response_code( $response ); $data = json_decode( (string) wp_remote_retrieve_body( $response ), true ); if ( 200 !== $code ) { $retry_after = wp_remote_retrieve_header( $response, 'retry-after' ); return new WP_Error( 'arwc_ai_http_error', $this->friendly_http_message( $code, $data, $retry_after ) ); } // Accept OpenRouter's native shape and a proxy that returns { content }. // We deliberately use ONLY the real answer `content` — never // `message.reasoning`. Reasoning models put their chain-of-thought there, // and surfacing it would leak the model's internal planning (raw prompt + // "let's craft…" scaffolding) into the product description. If a reasoning // model returns a null content, we fail closed with a clear message rather // than write that scaffolding to the store. $content = ''; if ( is_array( $data ) ) { if ( ! empty( $data['choices'][0]['message']['content'] ) ) { $content = (string) $data['choices'][0]['message']['content']; } elseif ( ! empty( $data['content'] ) && is_string( $data['content'] ) ) { $content = (string) $data['content']; } } return $this->finalize_content( $content ); } /** * Map an AI/proxy HTTP status to a clean, user-facing message. * * The proxy returns a clean top-level `message` for its own gates (no licence, * model not allowed, rate limited) — that is trusted verbatim. Anything else * (including OpenRouter free-tier 429/404 passed through the proxy) is mapped to * a friendly "try again" style message so the merchant never sees a raw error. * * @param int $code HTTP status code. * @param array|null $data Decoded response body. * @param string $retry_after Optional Retry-After header value (seconds). * @return string */ protected function friendly_http_message( $code, $data, $retry_after = '' ) { // The local/dev hint is only relevant to reachability/auth failures — NOT to // a model-config rejection (the proxy was clearly reached). Only append it // for auth-style codes so a "model not allowed" error isn't muddied by it. $env = in_array( (int) $code, array( 401, 403 ), true ) ? $this->ai_env_hint() : ''; // Trust the proxy's own clean, specific message when it sends one. if ( is_array( $data ) && ! empty( $data['message'] ) && is_string( $data['message'] ) ) { return trim( (string) $data['message'] . ' ' . $this->retry_after_phrase( $retry_after ) . ' ' . $env ); } switch ( $code ) { case 401: case 403: return trim( __( 'AI needs an active Pro licence, and it could not be verified for this request. Check your licence under Agent Readiness → Settings.', 'agentictrack-agent-readiness-for-woocommerce' ) . ' ' . $env ); case 400: case 404: return __( 'The AI service hasn’t enabled this model yet. If you’re the store owner, allow openai/gpt-4o-mini on your AI proxy (set the ALLOWED_MODELS env var); otherwise add your own AI provider key under Agent Readiness → Settings.', 'agentictrack-agent-readiness-for-woocommerce' ); case 402: return __( 'The AI service is temporarily unavailable. Please try again in a little while.', 'agentictrack-agent-readiness-for-woocommerce' ); case 429: // The free shared models rate-limit frequently. On the built-in // service, point the merchant to the real escape hatch: their own // provider key gives dedicated limits and no shared queue. $retry = $this->retry_after_phrase( $retry_after ); if ( $this->uses_proxy() ) { $msg = __( 'The free AI service is busy right now — the shared free models rate-limit when lots of stores use them at once. Wait a minute and try again, or, for dedicated limits with no waiting, add your own AI provider key (OpenAI, Anthropic, Gemini, or OpenRouter) under Agent Readiness → Settings.', 'agentictrack-agent-readiness-for-woocommerce' ); return trim( $msg . ( '' !== $retry ? ' ' . $retry : '' ) ); } $msg = __( 'OpenRouter is rate-limiting this model right now (common on free models). Wait a minute and try again, or choose a different model under Agent Readiness → Settings.', 'agentictrack-agent-readiness-for-woocommerce' ); return trim( $msg . ( '' !== $retry ? ' ' . $retry : '' ) ); } if ( $code >= 500 ) { return __( 'The AI service is temporarily unavailable. Please try again in a little while.', 'agentictrack-agent-readiness-for-woocommerce' ); } return sprintf( /* translators: %d: HTTP status code. */ __( 'AI request failed (HTTP %d). Please try again.', 'agentictrack-agent-readiness-for-woocommerce' ), $code ); } /** * Turn a Retry-After header value into a short "Try again in N" phrase, so a * rate-limit error can tell the merchant WHEN to retry when the upstream says. * Accepts a delay in seconds (the common form); an HTTP-date form is ignored * (we only promise the phrase when we can state it simply). * * @param string $retry_after Retry-After header value. * @return string Empty string when unknown. */ protected function retry_after_phrase( $retry_after ) { $retry_after = trim( (string) $retry_after ); if ( '' === $retry_after || ! is_numeric( $retry_after ) ) { return ''; } $seconds = (int) round( (float) $retry_after ); if ( $seconds < 1 ) { return ''; } if ( $seconds < 90 ) { return sprintf( /* translators: %d: number of seconds to wait. */ _n( 'Try again in about %d second.', 'Try again in about %d seconds.', $seconds, 'agentictrack-agent-readiness-for-woocommerce' ), $seconds ); } $minutes = (int) max( 1, round( $seconds / 60 ) ); return sprintf( /* translators: %d: number of minutes to wait. */ _n( 'Try again in about %d minute.', 'Try again in about %d minutes.', $minutes, 'agentictrack-agent-readiness-for-woocommerce' ), $minutes ); } /** * Run a completion against a directly-selected provider using the merchant's * own key. Enforces the same call cap as {@see complete()} and fails closed. * * @param string $provider Provider slug ('openai' | 'anthropic' | 'gemini'). * @param string $system System prompt. * @param string $user User prompt. * @return string|WP_Error */ protected function complete_direct_provider( $provider, $system, $user ) { $key = $this->provider_key( $provider ); if ( '' === $key ) { return new WP_Error( 'arwc_ai_no_key', sprintf( /* translators: %s: provider name, e.g. "OpenAI (ChatGPT)". */ __( 'Add your %s API key under Agent Readiness → Settings, or switch the AI provider back to AgenticTrack.', 'agentictrack-agent-readiness-for-woocommerce' ), $this->provider_label( $provider ) ) ); } if ( $this->calls >= $this->call_cap() ) { return new WP_Error( 'arwc_ai_cap_reached', __( 'AI usage cap reached for this run. Run again to continue.', 'agentictrack-agent-readiness-for-woocommerce' ) ); } $this->calls++; $model = trim( (string) get_option( self::OPTION_MODEL, '' ) ); if ( '' === $model ) { $model = $this->default_model_for( $provider ); } switch ( $provider ) { case 'openai': return $this->dispatch_openai( $key, $model, (string) $system, (string) $user ); case 'anthropic': return $this->dispatch_anthropic( $key, $model, (string) $system, (string) $user ); case 'gemini': return $this->dispatch_gemini( $key, $model, (string) $system, (string) $user ); } return new WP_Error( 'arwc_ai_provider', __( 'Unknown AI provider.', 'agentictrack-agent-readiness-for-woocommerce' ) ); } /** * Send a request and normalise WordPress transport errors (incl. timeouts). * * @param string $endpoint Endpoint URL. * @param array $args wp_remote_post args. * @return array{code:int,data:mixed}|WP_Error */ protected function do_post( $endpoint, array $args ) { $args['timeout'] = $this->request_timeout(); $response = wp_remote_post( $endpoint, $args ); if ( is_wp_error( $response ) ) { if ( false !== stripos( $response->get_error_message(), 'timed out' ) ) { return new WP_Error( 'arwc_ai_timeout', sprintf( /* translators: %d: timeout in seconds. */ __( 'The AI request timed out after %d seconds. Try again, choose a faster model, or raise the timeout via the arwc_ai_timeout filter.', 'agentictrack-agent-readiness-for-woocommerce' ), $this->request_timeout() ) ); } return $response; } return array( 'code' => (int) wp_remote_retrieve_response_code( $response ), 'data' => json_decode( (string) wp_remote_retrieve_body( $response ), true ), ); } /** * OpenAI (ChatGPT) chat-completions call. * * @param string $key API key. * @param string $model Model id. * @param string $system System prompt. * @param string $user User prompt. * @return string|WP_Error */ protected function dispatch_openai( $key, $model, $system, $user ) { $result = $this->do_post( self::ENDPOINT_OPENAI, array( 'headers' => array( 'Authorization' => 'Bearer ' . $key, 'Content-Type' => 'application/json', ), 'body' => wp_json_encode( array( 'model' => $model, 'max_tokens' => $this->token_cap(), 'temperature' => 0.2, 'messages' => array( array( 'role' => 'system', 'content' => $system, ), array( 'role' => 'user', 'content' => $user, ), ), ) ), ) ); if ( is_wp_error( $result ) ) { return $result; } if ( 200 !== $result['code'] ) { return new WP_Error( 'arwc_ai_http_error', $this->provider_http_message( 'openai', $result['code'], $result['data'] ) ); } $data = $result['data']; $content = ( is_array( $data ) && ! empty( $data['choices'][0]['message']['content'] ) ) ? (string) $data['choices'][0]['message']['content'] : ''; return $this->finalize_content( $content ); } /** * Anthropic (Claude) messages call. * * @param string $key API key. * @param string $model Model id. * @param string $system System prompt. * @param string $user User prompt. * @return string|WP_Error */ protected function dispatch_anthropic( $key, $model, $system, $user ) { $result = $this->do_post( self::ENDPOINT_ANTHROPIC, array( 'headers' => array( 'x-api-key' => $key, 'anthropic-version' => '2023-06-01', 'Content-Type' => 'application/json', ), 'body' => wp_json_encode( array( 'model' => $model, 'max_tokens' => $this->token_cap(), 'temperature' => 0.2, 'system' => $system, 'messages' => array( array( 'role' => 'user', 'content' => $user, ), ), ) ), ) ); if ( is_wp_error( $result ) ) { return $result; } if ( 200 !== $result['code'] ) { return new WP_Error( 'arwc_ai_http_error', $this->provider_http_message( 'anthropic', $result['code'], $result['data'] ) ); } // Claude returns an array of content blocks; concatenate the text ones. $content = ''; $data = $result['data']; if ( is_array( $data ) && ! empty( $data['content'] ) && is_array( $data['content'] ) ) { foreach ( $data['content'] as $block ) { if ( is_array( $block ) && isset( $block['type'], $block['text'] ) && 'text' === $block['type'] ) { $content .= (string) $block['text']; } } } return $this->finalize_content( $content ); } /** * Google Gemini generateContent call. * * @param string $key API key. * @param string $model Model id. * @param string $system System prompt. * @param string $user User prompt. * @return string|WP_Error */ protected function dispatch_gemini( $key, $model, $system, $user ) { // The key travels in a header (x-goog-api-key), not the URL, so it never // lands in server/proxy access logs. $endpoint = self::ENDPOINT_GEMINI . rawurlencode( $model ) . ':generateContent'; $result = $this->do_post( $endpoint, array( 'headers' => array( 'x-goog-api-key' => $key, 'Content-Type' => 'application/json', ), 'body' => wp_json_encode( array( 'system_instruction' => array( 'parts' => array( array( 'text' => $system ) ), ), 'contents' => array( array( 'role' => 'user', 'parts' => array( array( 'text' => $user ) ), ), ), 'generationConfig' => array( 'maxOutputTokens' => $this->token_cap(), 'temperature' => 0.2, ), ) ), ) ); if ( is_wp_error( $result ) ) { return $result; } if ( 200 !== $result['code'] ) { return new WP_Error( 'arwc_ai_http_error', $this->provider_http_message( 'gemini', $result['code'], $result['data'] ) ); } $content = ''; $data = $result['data']; if ( is_array( $data ) && ! empty( $data['candidates'][0]['content']['parts'] ) && is_array( $data['candidates'][0]['content']['parts'] ) ) { foreach ( $data['candidates'][0]['content']['parts'] as $part ) { if ( is_array( $part ) && isset( $part['text'] ) ) { $content .= (string) $part['text']; } } } return $this->finalize_content( $content ); } /** * Strip any chain-of-thought markup a model may inline in its answer, trim the * result, and turn an empty result into a clean error. * * Some hybrid/"reasoning" models wrap their internal thinking in … * (or similar) tags *inside* the content itself. We remove those so the model's * scaffolding can never end up saved as a product description or attribute. * * @param string $content Raw content. * @return string|WP_Error */ protected function finalize_content( $content ) { $content = (string) $content; // Remove … / … / … // blocks (case-insensitive, across newlines). $content = (string) preg_replace( '#<(think|thinking|reasoning)\b[^>]*>.*?#is', '', $content ); // Remove a dangling opener with no closer (model cut off mid-thought). $content = (string) preg_replace( '#<(think|thinking|reasoning)\b[^>]*>.*$#is', '', $content ); $content = trim( $content ); if ( '' === $content ) { return new WP_Error( 'arwc_ai_bad_response', __( 'The AI model didn\'t return usable text — this usually means a “reasoning” model was selected. Leave the Model field blank to use the recommended default, or pick a non-reasoning free model under Agent Readiness → Settings, then try again.', 'agentictrack-agent-readiness-for-woocommerce' ) ); } return $content; } /** * Map a direct provider's HTTP error to a clean, user-facing message. * * @param string $provider Provider slug. * @param int $code HTTP status code. * @param mixed $data Decoded response body. * @return string */ protected function provider_http_message( $provider, $code, $data ) { $label = $this->provider_label( $provider ); $detail = ''; if ( is_array( $data ) && isset( $data['error'] ) ) { if ( is_array( $data['error'] ) && ! empty( $data['error']['message'] ) ) { $detail = (string) $data['error']['message']; } elseif ( is_string( $data['error'] ) ) { $detail = $data['error']; } } switch ( $code ) { case 401: case 403: return sprintf( /* translators: %s: provider name. */ __( '%s rejected the API key. Double-check it under Agent Readiness → Settings and save again.', 'agentictrack-agent-readiness-for-woocommerce' ), $label ); case 429: return sprintf( /* translators: %s: provider name. */ __( '%s is rate-limiting right now. Wait a moment and try again.', 'agentictrack-agent-readiness-for-woocommerce' ), $label ); case 400: case 404: if ( '' !== $detail ) { return sprintf( /* translators: 1: provider name, 2: provider error detail. */ __( '%1$s could not process the request: %2$s', 'agentictrack-agent-readiness-for-woocommerce' ), $label, $detail ); } return sprintf( /* translators: %s: provider name. */ __( '%s could not process the request. Check the model id under Agent Readiness → Settings.', 'agentictrack-agent-readiness-for-woocommerce' ), $label ); } if ( $code >= 500 ) { return sprintf( /* translators: %s: provider name. */ __( '%s is temporarily unavailable. Please try again shortly.', 'agentictrack-agent-readiness-for-woocommerce' ), $label ); } return sprintf( /* translators: 1: provider name, 2: HTTP status code. */ __( '%1$s request failed (HTTP %2$d). Please try again.', 'agentictrack-agent-readiness-for-woocommerce' ), $label, $code ); } }