UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 32.3 kB
import{i as e}from"./transcript-record-coerce-CPLgmAk9.mjs";import{i as t}from"./transcript-global-singleton-DIJgobpU.mjs";import{b as n,l as r}from"./transcript-plugin-instance-invocation-7y9lfaeO.mjs";import{_ as i,a,c as o,f as s,h as c,l,m as u,r as d,s as f}from"./transcript-redact-BJEzMNLa.mjs";import{t as p}from"./transcript-sqlite-error-diagnostics-CLL4Z7ly.mjs";import{i as m,n as h}from"./transcript-string-coerce-DTk-8HSr.mjs";import{n as g}from"./transcript-json-coercion-Cy9rPWP2.mjs";import{c as _}from"./transcript-number-coercion-D2B2TTt-.mjs";import"./transcript-errors-B-oBGrpW.mjs";import{t as v}from"./transcript-provider-id-yVCdeNBg.mjs";import"./transcript-diagnostics-YP3O061O.mjs";import{a as y,c as b,d as x,f as ee,i as te,l as S,m as C,n as w,o as ne,p as re,r as T,s as ie,t as E,u as D}from"./transcript-message-patterns-P_OD_IrF.mjs";import{isTransientNetworkError as ae}from"@openclaw/ai/diagnostics";function escapeMarkdownText(e){return e.replace(/[!-/:-@[-`{-~]/g,`\\$&`)}const O=/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,k=/context window exceeded: estimated input \d+ leaves only \d+ output tokens within the \d+-token context\./i,A={"assistant-error":[k,/prompt is too long/i,/request_too_large/i,/input length and `?max_tokens`? exceed context limit: [\d,]+ \+ [\d,]+ > [\d,]+/i,/input is too long for requested model/i,/exceeds the context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/exceeds the limit of \d+/i,/(?:exceeds the available context size|context size has been exceeded)/i,/decoder prompt \(length [\d,]+\)(?: plus the number of requested output tokens \(at least 1\))? is longer than the maximum model length of [\d,]+/i,/engine prompt length [\d,]+ exceeds the max_model_len [\d,]+/i,/`?inputs`? tokens \+ `?max_new_tokens`? must be <= [\d,]+/i,/`?inputs`? must have less than [\d,]+ tokens/i,/greater than the context length|model is loaded with context length of only \d[\d,]* tokens, which is not enough/i,/context window exceeds limit/i,/exceeded model token limit/i,/tokens? in request more than max tokens? allowed/i,/prompt exceeds max(?:imum)? length/i,/range of input length should be \[1, [\d,]+\]/i,/length of prompt_tokens \([\d,]+\) must be less than max_seq_len \([\d,]+\)/i,/too large for model with \d+ maximum context length/i,O,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i,/^413\s*(?:status code)?\s*\(no body\)/i],"failover-explicit":[k,/request_too_large/i,/context_overflow/i,O,/invalid_argument[\s\S]*maximum number of tokens/i,/request exceeds the maximum size/i,/context length exceeded/i,/maximum context length/i,/prompt is too long/i,/prompt too long/i,/exceeds model context window/i,/model token limit/i,/input exceeds[\s\S]*maximum number of tokens/i,/^(?=[\s\S]*context window)(?=[\s\S]*ran out of (?:room|space))/i,/request size exceeds[\s\S]*context window/i,/context overflow:/i,/exceed context limit/i,/exceeds the model'?s maximum context/i,/max_tokens[\s\S]*exceed[\s\S]*context/i,/input(?: length[\s\S]*exceed[\s\S]*context| \([\d,]+\s*tokens?\) is longer than (?:the )?model'?s context length)/i,/413[\s\S]*too large/i,/context_window_exceeded/i,/input length [\d,]+\s+tokens? exceeds the model limit/i,/`?inputs`? tokens \+ `?max_new_tokens`? must be <= [\d,]+/i,/`?inputs`? must have less than [\d,]+ tokens/i,/上下文过长|上下文超出|上下文长度超|超出最大上下文|请压缩上下文/],"provider-fallback":[/\binput token count exceeds the maximum number of input tokens\b/i,/\binput is too long for this model\b/i,/\binput exceeds the maximum number of tokens\b/i,/\bollama error:\s*context length exceeded(?:,\s*too many tokens)?\b/i,/\btotal tokens?.*exceeds? (?:the )?(?:model(?:'s)? )?(?:max|maximum|limit)/i,/\b(?:(?:request|prompt) \(\d[\d,]*\s*tokens?\) exceeds (?:the )?available context size|context size has been exceeded)\b/i,/\binput (?:is )?too long for (?:the )?model\b/i],"failover-hint":[/context.*overflow|context window.*(too (?:large|long)|exceed|over|limit|max(?:imum)?|requested|sent|tokens)|prompt.*(too (?:large|long)|exceed|over|limit|max(?:imum)?)|(?:request|input).*(?:context|window|length|token).*(too (?:large|long)|exceed|over|limit|max(?:imum)?)/i],"context-window-too-small":[/context window.*(too small|minimum is)/i],"tpm-rate-limit-hint":[/\btpm\b|tokens per minute/i],"rate-limit-hint":[/rate limit|too many requests|requests per (?:minute|hour|day)|quota|throttl|429\b|tokens per day/i]};function matchesContextOverflowMessage(e,t){return A[t].some(t=>t.test(e))}t(Symbol.for(`openclaw.settledOAuthRefreshFailures`),()=>/* @__PURE__ */ new WeakMap);const j=/OAuth token refresh failed for ([^:]+):/i,M=/^[a-z0-9][a-z0-9._-]*$/,N=/\bclaude-cli\b.+?\b(failed to authenticate|401\s+invalid authentication credentials)\b/is;function isClaudeCliExpiredOAuthMessage(e){return N.test(e)}function isOAuthRefreshFailureMessage(e){let t=e.toLowerCase();return t.includes(`oauth token refresh failed`)||t.includes(`access token could not be refreshed`)||t.includes(`authentication session could not be refreshed automatically`)||isClaudeCliExpiredOAuthMessage(e)}function extractOAuthRefreshFailureProvider(e){if(isClaudeCliExpiredOAuthMessage(e))return`claude-cli`;let t=e.match(j)?.[1]?.trim();return t&&t.length>0?t:null}function sanitizeOAuthRefreshFailureProvider(e){let t=e?r(e).replaceAll("`",``).trim():``,n=v(t);return n&&M.test(n)?n:null}function classifyOAuthRefreshFailureReason(e){let t=e.toLowerCase();return P.find(([,e])=>e.some(e=>t.includes(e)))?.[0]??(isClaudeCliExpiredOAuthMessage(e)?`revoked`:null)}const P=[[`refresh_token_reused`,[`refresh_token_reused`]],[`expired`,[`refresh_token_expired`]],[`invalid_grant`,[`invalid_grant`]],[`token_invalidated`,[`token_invalidated`]],[`sign_in_again`,[`sign_in_again`,`signing in again`,`sign in again`,`log in again`]],[`invalid_refresh_token`,[`invalid_refresh_token`,`invalid refresh token`]],[`revoked`,[`revoked`]]];function classifyOAuthRefreshFailure(e){return isOAuthRefreshFailureMessage(e)?{provider:sanitizeOAuthRefreshFailureProvider(extractOAuthRefreshFailureProvider(e)),reason:classifyOAuthRefreshFailureReason(e)}:null}const F=/image dimensions exceed max allowed size for many-image requests:\s*(\d+)\s*pixels/i,I=/messages\.(\d+)\.content\.(\d+)\.image/i,L=/image exceeds\s*(\d+(?:\.\d+)?)\s*mb/i;function parseImageDimensionError(e){if(!/image dimensions exceed max allowed size/i.test(e))return null;let t=e.match(F),n=e.match(I);return{maxDimensionPx:t?.[1]?Number.parseInt(t[1],10):void 0,messageIndex:n?.[1]?Number.parseInt(n[1],10):void 0,contentIndex:n?.[2]?Number.parseInt(n[2],10):void 0}}function isImageDimensionErrorMessage(e){return!!parseImageDimensionError(e)}function parseImageSizeError(e){if(!/image exceeds[\s\S]*mb/i.test(e))return null;let t=e.match(L);return{maxMb:t?.[1]?Number.parseFloat(t[1]):void 0}}function isImageSizeError(e){return!!(e&&parseImageSizeError(e))}function isModelNotFoundErrorMessage(e){let t=e.trim();return/no endpoints found for/i.test(t)||/\brouter not found\b/i.test(t)||/unknown model/i.test(t)||/\bmodel\b[^\r\n]{0,120}?\b(?:was|is|has been) retired\b/i.test(t)||/\b[a-z0-9][a-z0-9._:/-]* was retired at \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} [+-]\d{4} [a-z]+ \(ref:/i.test(t)||/model(?:[_\-\s])?not(?:[_\-\s])?found|\bmodel\b.{0,60}?\bnot found\b/i.test(t)||/\b404\b/.test(t)&&/not(?:[_\-\s])?found/i.test(t)||/not_found_error/i.test(t)||/\bnot supported model\b/i.test(t)||/\bmodel\b[^.]{0,120}?\bis not supported when using\b[^.]{0,80}?\bwith a ChatGPT account\b/i.test(t)||/model:\s*[a-z0-9._/-]+/i.test(t)&&/not(?:[_\-\s])?found/i.test(t)||/models\/[^\s]+ is not found/i.test(t)||/model/i.test(t)&&/does not exist/i.test(t)||/selected model/i.test(t)&&/not(?:[_\-\s])?found/i.test(t)||/model/i.test(t)&&/deprecated/i.test(t)&&/(upgrade|transition) to/i.test(t)||/\bmodel\b(?:\s+(?!(?:parameters?|params?|fields?|options?|arguments?|settings?|names?|propert(?:y|ies)|endpoints?|versions?)\b)[`'"]?[\w./:@-]+[`'"]?)?\s+(?:is|was|has been) deprecated\b(?![^.\r\n]{0,80}\b(?:will|scheduled|soon)\b)/i.test(t)||/stealth model/i.test(t)&&/find it here/i.test(t)||/is not a valid model id/i.test(t)||/invalid model/i.test(t)&&!/invalid model reference/i.test(t)}const R=/^(?:no body(?: response)?|no response body|status code \(no body\))$/i,z=/^\[(?:(?:Malformed|Oversized) diagnostic JSON redacted|Unserializable)\]$/,B=/* @__PURE__ */ new Set([`session_expired`,`billing`,`auth_permanent`,`auth`]);function stripErrorPrefix(e){return e.replace(/^error:\s*/i,``).trim()}function inferSignalStatus(e){if(Number.isFinite(e.status))return e.status;let t=stripErrorPrefix(e.message?.trim()??``);return o(t)?.code??l(t)?.code}function isExplicitNoBodyHttpMessage(e,t){let n=e?.trim();if(!n)return!1;let r=stripErrorPrefix(n),i=o(r);return(!i||i.code===t)&&R.test(i?.rest??r)}function isUnclassifiedNoBodyHttpSignal(e){let t=inferSignalStatus(e);if(t!==400&&t!==422)return!1;let n=e.message?.trim();return!n||isExplicitNoBodyHttpMessage(n,t)}const V=[`insufficient credits`,`insufficient quota`,`credit balance`,`insufficient balance`,`plans & billing`,`add more credits`,`top up`],H=[`upgrade your plan`,`upgrade plan`,`current plan`,`subscription`],U=[`daily`,`weekly`,`monthly`],W=[`try again`,`retry`,`temporary`,`cooldown`],G=[`usage limit`,`rate limit`,`organization usage`],K=[`organization`,`workspace`],q=[`billing period`,`exceeded`,`reached`,`exhausted`],J=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+(?:payment required\b|.*used up your points\b|no available asset for api access\b)/i,oe=/^\s*402\b/i,se=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function includesAnyHint(e,t){return t.some(t=>e.includes(t))}function hasExplicit402BillingSignal(e){return includesAnyHint(e,V)||includesAnyHint(e,H)&&e.includes(`limit`)||e.includes(`billing hard limit`)||e.includes(`hard limit reached`)||e.includes(`maximum allowed`)&&e.includes(`limit`)}function hasQuotaRefreshWindowSignal(e){return e.includes(`subscription quota limit`)&&(e.includes(`automatic quota refresh`)||e.includes(`rolling time window`))}function hasRetryable402TransientSignal(e){let t=includesAnyHint(e,U),n=e.includes(`spend limit`)||e.includes(`spending limit`),r=includesAnyHint(e,K);return includesAnyHint(e,W)&&includesAnyHint(e,G)||t&&(e.includes(`usage limit`)||n)||t&&e.includes(`limit`)&&e.includes(`reset`)||r&&e.includes(`limit`)&&(n||includesAnyHint(e,q))}function hasKnownBareLeading402Signal(e){return hasQuotaRefreshWindowSignal(e)||hasExplicit402BillingSignal(e)||b(e)||hasRetryable402TransientSignal(e)}function normalize402Message(e){return m(e)?.replace(se,``).replace(/\bhttps?:\/\/[^\s<>"']+/g,` `).trim()??``}function classify402Message(e){let t=normalize402Message(e);return t?hasQuotaRefreshWindowSignal(t)?`rate_limit`:hasExplicit402BillingSignal(t)?`billing`:b(t)||hasRetryable402TransientSignal(t)?`rate_limit`:`billing`:`billing`}function classifyFailoverReasonFrom402Text(e){if(J.test(e))return classify402Message(e);if(!oe.test(e))return null;let t=normalize402Message(e);return!t||!hasKnownBareLeading402Signal(t)?null:classify402Message(e)}function toReasonClassification(e){return{kind:`reason`,reason:e}}function toPluginClassification(e){return e===`context_overflow`?{kind:`context_overflow`}:toReasonClassification(e)}function failoverReasonFromClassification(e){return e?e.kind===`reason`?e.reason:`context_overflow`:null}function classifyFailoverClassificationFromHttpStatus(e,t,n,r,i,a){let s=failoverReasonFromClassification(n);if(e===void 0||!Number.isFinite(e))return null;if(e===402){if(!t)return toReasonClassification(`billing`);if(o(t.trim())?.code===402){let e=classifyFailoverReasonFrom402Text(t);return e?toReasonClassification(e):typeof r==`number`?toReasonClassification(classify402Message(t)):n}return toReasonClassification(classify402Message(t))}if(e===429)return a?.preserveProviderSignalClassification&&(s===`billing`||s===`rate_limit`)?n:s===`billing`&&!isAmbiguousGeneric429BalanceMessage(t??``)||t&&isBilling429MessageForProvider(t,i)?toReasonClassification(`billing`):toReasonClassification(`rate_limit`);if(e===401||e===403)return a?.preserveProviderSignalClassification&&n?n:t&&w(t)?toReasonClassification(`auth_permanent`):toReasonClassification(s===`billing`?`billing`:`auth`);if(e===408)return toReasonClassification(`timeout`);if(e===410)return B.has(s)||s===`model_not_found`?n:toReasonClassification(`timeout`);if(n?.kind===`context_overflow`)return n;if(e===404)return B.has(s)||s===`format`?n:toReasonClassification(`model_not_found`);if(e===529)return toReasonClassification(`overloaded`);if(e===499||e>=500&&e<600)return s===`overloaded`||s===`server_error`||e>=500&&s===`format`?n:toReasonClassification(e===499||e===504||e===522||e===524?`timeout`:`server_error`);if(e===400||e===422){if(n&&s!==`server_error`)return n;let r=stripErrorPrefix(t?.trim()??``),i=o(r)?.rest??r;return isUnclassifiedNoBodyHttpSignal({status:e,message:t})||z.test(i.trim())?null:toReasonClassification(`format`)}return null}const ce=/* @__PURE__ */ new Map([[`DEGENERATE_OUTPUT`,`server_error`],[`UNKNOWN_PARAMETER`,`format`],[`RESOURCE_EXHAUSTED`,`rate_limit`],[`RATE_LIMIT`,`rate_limit`],[`RATE_LIMITED`,`rate_limit`],[`RATE_LIMIT_EXCEEDED`,`rate_limit`],[`TOO_MANY_REQUESTS`,`rate_limit`],[`THROTTLED`,`rate_limit`],[`THROTTLING`,`rate_limit`],[`THROTTLINGEXCEPTION`,`rate_limit`],[`THROTTLING_EXCEPTION`,`rate_limit`],[`DEACTIVATED_WORKSPACE`,`auth_permanent`],[`SELECTED_AUTH_PROFILE_UNAVAILABLE`,`auth`],[`OVERLOADED`,`overloaded`],[`OVERLOADED_ERROR`,`overloaded`],[`EHOSTDOWN`,`timeout`],[`ENETRESET`,`timeout`],[`ERR_STREAM_PREMATURE_CLOSE`,`timeout`]]);function classifyFailoverReasonFromCode(e){let t=e?.trim().toUpperCase();return t?ce.get(t)??(ae({code:t})?`timeout`:null):null}const le=/* @__PURE__ */ new Map([[`invalid_request_error`,`format`],[`server_error`,`server_error`],[`upstream_error`,`server_error`],[`overloaded_error`,`overloaded`]]);function classifyCoreFailoverReasonFromErrorType(e){let t=m(e);return t?le.get(t)??null:null}function hasStructuredBilling429Signal(e){if(hasBillingApiErrorType(e))return!0;let t=o(e.trim());return!!(t?.rest&&hasBillingApiErrorType(t.rest))}function hasBillingApiErrorType(e){let t=m(c(e)?.type);return t?T(t)||T(t.replaceAll(`_`,` `)):!1}function isAmbiguousGeneric429BalanceMessage(e){return/\binsufficient\s+account\s+balance\b/i.test(e)&&!hasStructuredBilling429Signal(e)}function isBilling429MessageForProvider(e,t){if(!T(e))return!1;let n=m(t)??``;return[`xai`,`moonshot`,`kimi`].some(e=>n.includes(e))||!isAmbiguousGeneric429BalanceMessage(e)}const ue=/\bprevious_response_id\b.*\b(?:invalid|unknown|not found|does not exist|expired|mismatch)\b|\btool_(?:use|call)\.(?:input|arguments)\b.*\b(?:missing|required)\b|\bincorrect role information\b|\broles must alternate\b|\binput item id does not belong to this connection\b/i,de=/\b(?:invalid|expired)\b.*\bsignature\b|\bsignature\b.*\b(?:invalid|expired)\b/i;function isReplayInvalidErrorMessage(e){return ue.test(e)||/\bthinking\b/i.test(e)&&de.test(e)}function isGenericUnknownStreamErrorMessage(e){return/^\s*an unknown error occurred\.?\s*$/i.test(e)}function isExactUnknownNoDetailsError(e){return m(e)===`unknown error (no error details in response)`}function isClaudeCliAuthError(e,t){return m(t)===`claude-cli`&&/\bnot logged in\b\s*·\s*please run \/login\b|\bfailed to authenticate:\s*oauth session expired and could not be refreshed\b/i.test(e)}function isUnsupportedImageInputErrorMessage(e){let t=m(e);return t?/\bdoes not support image inputs?\b/.test(t)||/\bunsupported image input\b/.test(t)||/\bno endpoints found\b/.test(t)&&/\bsupport image input\b/.test(t):!1}const fe=/\b(?:context|window|prompt|token|tokens|input|request|model)\b/i,pe=/\b(?:too\s+(?:large|long|many)|exceed(?:s|ed|ing)?|overflow|limit|maximum|max)\b/i;function looksLikeProviderContextOverflowCandidate(e){return!b(e)&&fe.test(e)&&pe.test(e)}function isReasoningConstraintErrorMessage(e){if(!e)return!1;let t=h(e);return t.includes(`reasoning is mandatory`)||t.includes(`reasoning is required`)||t.includes(`requires reasoning`)||t.includes(`reasoning`)&&t.includes(`cannot be disabled`)}function hasRateLimitTpmHint(e){return matchesContextOverflowMessage(e,`tpm-rate-limit-hint`)}function isContextOverflowErrorFromTables(e){return!e||hasRateLimitTpmHint(e)&&!ie(e)||isReasoningConstraintErrorMessage(e)?!1:matchesContextOverflowMessage(e,`failover-explicit`)||looksLikeProviderContextOverflowCandidate(e)&&matchesContextOverflowMessage(e,`provider-fallback`)}const me=/^\s*(?:<!doctype\s+html\b|<html\b)/i,he=/<\/html>/i;function isHtmlErrorResponse(e){let t=e.trim().replace(/^error:\s*/i,``).trim(),n=o(t)?.rest??t;return me.test(n)&&he.test(n)}const ge=[[isUnsupportedImageInputErrorMessage,`format`],[isClaudeCliAuthError,`auth`],[D,`format`],[isCliSessionExpiredErrorMessage,`session_expired`],[isModelNotFoundErrorMessage,`model_not_found`],[e=>/\bworkers_ai\b.*\bquota limit exceeded\b/i.test(e),`rate_limit`],[e=>/\bmodelnotreadyexception\b/i.test(e),`overloaded`],[e=>/model(?:_is)?_deactivated|model has been deactivated/i.test(e),`model_not_found`]],_e=[[b,`rate_limit`],[te,`overloaded`],[ne,`server_error`],[e=>isStructuredServerErrorMessage(e)&&!T(e)&&!w(e)&&!E(e),`server_error`],[u,`timeout`],[e=>!!classifyOAuthRefreshFailure(e)?.reason,`auth_permanent`],[w,`auth_permanent`],[E,`auth`],[e=>isGenericUnknownStreamErrorMessage(e)||S(e)||isJsonApiInternalServerError(e),`timeout`],[isCloudCodeAssistFormatError,`format`],[isExactUnknownNoDetailsError,`no_error_details`],[x,`timeout`],[e=>matchesContextOverflowMessage(e,`assistant-error`),`context_overflow`]];function isTransportHtmlErrorStatus(e){return e===408||e===499||e!==void 0&&e>=500&&e<600}function classifyFailoverClassificationFromMessage(e,t,n){if(isImageDimensionErrorMessage(e)||isImageSizeError(e))return null;let r=ge.find(([n])=>n(e,t))?.[1];if(r)return toReasonClassification(r);if(isContextOverflowErrorFromTables(e))return{kind:`context_overflow`};if(isReplayInvalidErrorMessage(e))return toReasonClassification(`format`);let i=classifyFailoverReasonFrom402Text(e);if(i)return toReasonClassification(i);if(o(e.trim())?.code!==429&&T(e))return toReasonClassification(`billing`);if(y(e))return toReasonClassification(T(e)?`billing`:`rate_limit`);let a=_e.find(([t])=>t(e))?.[1];if(a)return toPluginClassification(a);let s=classifyCoreFailoverReasonFromErrorType(c(e)?.type??n);return s?toReasonClassification(s):classifyFailoverClassificationFromHttpStatus(inferSignalStatus({message:e}),e,null,void 0,t)}function classifyFailoverDetailCandidates(e,t){for(let n of e??[]){let e=classifyFailoverClassificationFromMessage(n,t);if(e)return e}return null}function mergeMessageAndDetailClassification(e,t){return!e||!t?e??t:e.kind===`context_overflow`?e:t.kind===`context_overflow`||t.reason===`billing`&&e.reason===`rate_limit`||e.reason===`format`?t:e}function hasIndependentTransientMessage(e,t,n){let r=e&&(o(e)?.rest??e),i=c(r),a=!i&&r?g(r):null,s=i?i.message:a?typeof a.message==`string`?a.message:void 0:r;return!!(s&&classifyFailoverReasonFromCode(s)!==t&&failoverReasonFromClassification(classifyFailoverClassificationFromMessage(s,n))===t)}function classifyFailoverSignalCore(e,t){if(C(e.message))return null;let n=inferSignalStatus(e),r=Number.isFinite(e.status)?e.status:void 0,a=e.message?classifyFailoverClassificationFromMessage(e.message,e.provider,e.errorType):null,o=mergeMessageAndDetailClassification(a,classifyFailoverDetailCandidates(e.details,e.provider)),s=classifyCoreFailoverReasonFromErrorType(e.errorType),l=s?toReasonClassification(s):null,u=r??(e.provider&&(n===401||n===403||n===429)?n:void 0),d=!!(e.message||e.code||e.errorType||n!==void 0),f=u!==void 0||e.code!==void 0||e.errorType!==void 0,p=!!(e.message&&looksLikeProviderContextOverflowCandidate(e.message)),m=d&&(f||p||!a),h=null;if(m){let n={errorMessage:e.message??``,provider:e.provider,status:u,code:e.code,errorType:e.errorType};if(h=t?.(n)??null,!h){for(let r of e.details??[])if(h=t?.({...n,errorMessage:r})??null,h)break}}let g=i(e);if(!h&&g&&n===void 0)return toReasonClassification(`tls_certificate`);if(!h&&e.message&&isTransportHtmlErrorStatus(n)&&isHtmlErrorResponse(e.message))return classifyFailoverClassificationFromHttpStatus(n,void 0,null,e.status,e.provider);let _=classifyFailoverReasonFromCode(e.code)??classifyFailoverReasonFromCode(c(e.message)?.code),v=h?toPluginClassification(h):_===`format`?toReasonClassification(`format`):mergeMessageAndDetailClassification(o??l,_?toReasonClassification(_):null);if(_===`auth_permanent`)return toReasonClassification(_);let y=classifyFailoverClassificationFromHttpStatus(n,e.message,v,e.status,e.provider,{preserveProviderSignalClassification:h!==null})??(_?toReasonClassification(_):v);if(!h&&n!==void 0&&n>=400&&n<500&&n!==408&&n!==409&&n!==410&&n!==429&&n!==499&&y?.kind===`reason`&&y.reason===_&&(_===`rate_limit`||_===`overloaded`||_===`timeout`)){let t=c(e.message);if(!(hasIndependentTransientMessage(e.message,_,e.provider)||e.details?.some(t=>hasIndependentTransientMessage(t,_,e.provider)))&&!/^throttling_?exception$/i.test(e.code??t?.code??``))return{...y,sameModelRetry:!1}}return y}function isCloudCodeAssistFormatError(e){return!isImageDimensionErrorMessage(e)&&re(e)}const Y=/internal server error|overload|temporarily unavailable|service unavailable|unknown error|server error|bad gateway|gateway timeout|upstream error|backend error|try again later|temporarily.+unable|unexpected error/i;function isJsonApiInternalServerError(e){return!h(e).includes(`"type":"api_error"`)||T(e)?!1:Y.test(e)}function isStructuredServerErrorMessage(e){let t=m(c(e)?.type);if(t===`server_error`||t===`upstream_error`)return!0;let n=h(e);return n.includes(`"type":"server_error"`)||n.includes(`"code":"server_error"`)||n.includes(`"type":"upstream_error"`)||n.includes(`"code":"upstream_error"`)}function isCliSessionExpiredErrorMessage(e){return/\b(?:session (?:not found|does not exist|expired|invalid)|conversation (?:not found|does not exist|expired|invalid)|no conversation found|no such session|invalid session|(?:session|conversation) id not found)\b/.test(h(e))}function classifyFailoverReasonCore(e,t,n){return failoverReasonFromClassification(classifyFailoverSignalCore({message:e,provider:t?.provider},n))}function collectFailoverDetailCandidates(t,r,i){if(r.length>=12)return;if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`){let e=n(String(t).trim(),1e3);if(e&&!r.includes(e)&&r.push(e),typeof t==`string`){let e=t.trim();if(e.startsWith(`{`)&&e.endsWith(`}`))try{collectFailoverDetailCandidates(JSON.parse(e),r,i)}catch{}}return}let a=e(t);if(a&&!i.has(a)){i.add(a);for(let e of[`message`,`param`,`code`,`type`,`error`,`detail`,`body`])if(collectFailoverDetailCandidates(a[e],r,i),r.length>=12)return}}function extractFailoverSignalDetails(...e){let t=[],n=/* @__PURE__ */ new Set;for(let r of e)if(collectFailoverDetailCandidates(r,t,n),t.length>=12)break;return t.length>0?t:void 0}const X=/^(?:error|(?:[a-z][\w-]*\s+)?api\s*error|openai\s*error|anthropic\s*error|gateway\s*error|codex\s*error|request failed|failed|exception)(?:\s+\d{3})?[:\s-]+/i,Z=`The AI service couldn't accept this request. Try a new conversation with /new, or choose another model in the Control UI.`,ve=/^['"]?max_(?:tokens|output_tokens|completion_tokens|new_tokens)['"]?\s*(?:[:=]\s*)?\(?(\d[\d,]*)\)?\s+exceeds?\b.{0,120}?\b(?:maximum|max|limit)\b(?:\s+(?:output\s+)?tokens?)?(?:\s+(?:is|of)|\s*[:=])?\s*\(?(\d[\d,]*)\)?(?:\D|$)/i,ye=/^A maximum of (\d{1,6}) blocks with cache_control may be provided\. Found (\d{1,6})\.$/i,Q="For details, open Settings → Logs in the Control UI or run `openclaw logs --follow` in your terminal.",be={unavailable:`The database connection was lost. This operation was rolled back; nothing from it was saved. Please retry.`,SQLITE_BUSY:`OpenClaw is busy saving your conversation. Wait a moment, then check the conversation before trying again.`,SQLITE_LOCKED:`OpenClaw is busy saving your conversation. Wait a moment, then check the conversation before trying again.`,SQLITE_FULL:`OpenClaw couldn't save your conversation because the disk is full. Free up space on the computer running OpenClaw before continuing.`,SQLITE_READONLY:`OpenClaw doesn't have permission to save your conversation. Check folder permissions on the computer running OpenClaw.`,SQLITE_IOERR:`OpenClaw couldn't save your conversation. Check the storage on the computer running OpenClaw before continuing.`,transcript_writer_fenced:`This conversation changed while OpenClaw was working. Check its latest messages before continuing.`,session_actor_reconciliation:`OpenClaw couldn't confirm the last update to this conversation. Some work may have been saved. Wait for current work to finish, then reopen the conversation and check its history before trying again. If it still fails, restart OpenClaw.`,57014:`PostgreSQL canceled a database operation or its statement timed out. Check the conversation for completed work before trying again. If it happens again, ask the operator to check PostgreSQL timeouts and server activity.`},$=`⚠️ The AI service could not recover saved conversation state (item_conflict). Retry this turn. If it still fails, run /compact or choose another model, and share the Gateway logs with the operator.`,xe={auth:"Couldn't sign in to the AI service. Sign in again under Models in the Control UI or run `openclaw configure`.",auth_permanent:"The AI service isn't accepting your login. Sign in again under Models in the Control UI or run `openclaw configure`.",format:Z,rate_limit:`The AI service needs a short break. Please try again in a few minutes.`,overloaded:`The AI service is busy. Please try again in a moment, or choose another model.`,billing:`The AI service reported a billing problem. Check your account's credit balance and usage limits before trying again.`,server_error:`The AI service is having trouble. Please try again in a moment.`,timeout:`The request took too long. Check the conversation for any completed work before trying again.`,tls_certificate:`Couldn't connect securely to the AI service. ${Q}`,context_overflow:a,model_not_found:"This model was not found. Choose another model in the Control UI or run `openclaw configure`.",session_expired:`Your AI session expired. Start a new conversation with /new. If it happens again, sign in under Models in the Control UI.`,empty_response:`The AI service returned an empty reply. Please try again.`,no_error_details:``,unclassified:``,unknown:``};function renderAssistantRequestFailureCopy(e){if(e.storageFailure)return`⚠️ ${be[e.storageFailure]} ${Q}`;if(e.code===`item_conflict`)return $;if(e.code===`incomplete_tool_call`)return`⚠️ The task couldn't finish. Some actions may have completed; check their results before continuing.`;let t=e.reason===`timeout`&&typeof e.status==`number`&&e.status>=500?`server_error`:e.reason,n=t?xe[t]:void 0;if(n)return`⚠️ ${n}`;if(e.status!==void 0&&Number.isInteger(e.status)&&e.status>=100&&e.status<=599||e.provider?.trim()||e.model?.trim())return`⚠️ OpenClaw couldn't finish this reply. ${Q}`}function renderFormatErrorCopy(e){let t=e.trim(),r=f(t)?.rest??t.replace(X,``).trim(),i=f(r)?.rest??r;for(let e=0;e<4;e++){i=(f(i)?.rest??i).replace(/^(?:bad request|unprocessable (?:entity|content))\s*:?\s*(?=[{[<])/iu,``);let e=c(i)?.message?.trim();if(!e||e===i)break;i=e}if(D(i))return"OpenClaw couldn't read this conversation's history. Ask the Gateway operator to try `openclaw doctor --fix`. If it still fails, preserve the history and contact support with the Gateway logs.";let a=i.match(/^"([\w./:-]{1,200})" does not support chat$/u)?.[1];if(a)return`${escapeMarkdownText(d(a,{mode:`tools`}))} is an embedding model and cannot chat; pick a chat model with /model (or remove it from models.providers.ollama.models).`;if(ye.test(i))return`The AI service couldn't accept this conversation. Start a new conversation with /new, or choose another model in the Control UI.`;if(ee(i))return`This model endpoint does not support reasoning_effort. Set compat.supportsReasoningEffort: false on this model in your custom provider configuration and try again.`;if(i.length>300||!ve.test(i)){if(!i||/^[{<]/u.test(i))return Z;if(i.startsWith(`[`))try{return JSON.parse(i),Z}catch{if(!/^\[[a-z_$][\w$.-]*\](?:\s|:|$)/iu.test(i))return Z}let e=d(i,{mode:`tools`}).replace(/[\p{Cc}\p{Cf}\s]+/gu,` `).trim();return e?`LLM request rejected: ${escapeMarkdownText(e.length>600?`${n(e,600)}…`:e)}`:Z}return`The reply length is set too high for this model. Lower its reply limit in the Control UI settings, or choose another model.`}function renderAssistantFormatFailureCopy(e,t){if(e.errorCode===`item_conflict`||e.errorMessage===$)return $;for(let[n,r]of[[!0,e.errorBody],[!1,e.errorMessage]]){if(typeof r!=`string`)continue;let i=c(r);if(i?.code===`item_conflict`||/^(?:LLM request rejected: )?An input item conflicts with an existing record\.$/u.test(i?.message??r.trim()))return $;if(n&&!i?.message)continue;let a=f(r)?.code;if(t!==`format`&&!(typeof e.errorType==`string`&&e.errorType.toLowerCase().includes(`invalid_request`))&&!i?.type?.toLowerCase().includes(`invalid_request`)&&a!==400&&a!==422)continue;let o=renderFormatErrorCopy(r);if(o!==`The AI service couldn't accept this request. Try a new conversation with /new, or choose another model in the Control UI.`)return o}}function renderModelLoadFailureCopy(e){if(e.errorCode!==`model_load_failed`||typeof e.errorBody!=`string`||typeof e.model!=`string`)return;let t=_(g(e.errorBody)?.requestedContextLength),r=d(e.model,{mode:`tools`}).replace(/[\p{Cc}\p{Cf}\s]+/gu,` `).trim();if(t&&r)return`Could not load model "${escapeMarkdownText(n(r,200))}" with ${t} context tokens. Wait for loading to finish on the model server, then retry, or lower the model's configured context size.`}function renderRecordedAssistantFailureCopy(e){let t=renderModelLoadFailureCopy(e);if(t)return t;let n=C(typeof e.errorMessage==`string`?e.errorMessage:void 0);if(n)return`⚠️ ${n}`;let r=typeof e.errorMessage==`string`?e.errorMessage.trim():``;if(r===`Worker inference result exceeds the transcript message limit.`)return`The worker could not save the model response because it exceeded the message size limit. Retry with a smaller response or continue on the Gateway. Earlier actions may have completed; verify their results before continuing.`;if(r===`Cloud worker could not preserve authoritative provider replay. Stop or reclaim the cloud worker, then retry locally.`)return`The worker could not preserve the model's continuation data. Stop or reclaim the worker, then retry on the Gateway. Earlier actions may have completed; verify their results before continuing.`;let i=c(r),o=typeof e.errorCode==`string`?e.errorCode:i?.code,l=f(r)?.code,u=classifyFailoverSignalCore({message:r,code:o,errorType:typeof e.errorType==`string`?e.errorType:i?.type,status:l,details:extractFailoverSignalDetails(e.errorBody)});if(u?.kind===`context_overflow`||[e.errorCode,e.errorType,r].some(e=>typeof e==`string`&&(h(e)===`context_overflow`||isContextOverflowErrorFromTables(e))))return a;let d=!u?.reason||u.reason===`format`?renderAssistantFormatFailureCopy(e,u?.reason):void 0;if(d)return d;let m=renderAssistantRequestFailureCopy({storageFailure:p(e),code:o,status:l,reason:u?.reason===`timeout`&&S(r)?`server_error`:u?.reason});return l!==void 0||u&&u.reason!==`timeout`?m:s([r,o].filter(Boolean).join(` `))??m}export{classifyFailoverReasonCore as i,renderAssistantRequestFailureCopy as n,renderRecordedAssistantFailureCopy as r,X as t};