openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
5 lines • 11.5 kB
JavaScript
import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{A as parseApiErrorInfo,C as formatProviderRefusalText,D as isGenericProviderInternalError,O as isKnownTransportErrorCode,T as formatTransportErrorCopy,b as extractLeadingHttpStatus,h as CONTEXT_OVERFLOW_ERROR_MESSAGE,w as formatRawAssistantErrorForUi,y as extractErrorHttpStatus}from"./redact-BT59pdZ_.mjs";import{t as classifyGatewayStorageFailure}from"./sqlite-error-diagnostics-ASl1MXPN.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{o as REPETITIVE_OUTPUT_ERROR_CODE}from"./types-B7P9E9_J.mjs";import{h as isTimeoutErrorMessage,u as isProviderCompletedErrorFinishReasonMessage,v as resolveExecutionApprovalFailureMessage}from"./message-patterns-CUldVmpX.mjs";import{k as setReplyPayloadMetadata,o as copyReplyPayloadMetadata}from"./reply-payload-C7eQHHoS.mjs";import{a as TLS_CERTIFICATE_ERROR_USER_TEXT,b as renderRateLimitOrOverloadedCopy,d as isRawApiErrorPayload,f as isStreamingJsonParseError,l as isInvalidStreamingEventOrderError,o as formatBillingErrorMessage,r as OAUTH_REFRESH_CONTENTION_USER_TEXT,s as formatDiskSpaceErrorCopy,t as AUTH_INVALID_TOKEN_USER_TEXT,u as isLikelyHttpErrorText}from"./user-copy-B1CccoqG.mjs";import{o as MODEL_REQUEST_POLICY_DENIED_TEXT}from"./errors-BBEItQ0m.mjs";import{r as isReasoningConstraintErrorMessage}from"./context-overflow-tables-B_UZ9JrK.mjs";import{a as failoverReasonFromClassification}from"./classification-rules-ByYfvIQF.mjs";import{a as renderAssistantFormatFailureCopy,c as renderModelLoadFailureCopy,i as PROVIDER_SCHEMA_REJECTION_USER_TEXT,o as renderAssistantRequestFailureCopy,s as renderFormatErrorCopy}from"./assistant-request-failure-copy-JfPT4_J9.mjs";import{t as formatSandboxToolPolicyBlockedMessage}from"./runtime-status-DDAPGR6Y.mjs";import{n as classifyFailoverSignal}from"./classify-BQDdk1iN.mjs";import{t as TOOL_REPEAT_LIMIT_CODE}from"./tool-repeat-guard-DDNpeOYG.mjs";import{t as buildAssistantFailoverSignal}from"./assistant-message-failures-DTR2sNej.mjs";import{t as REPETITIVE_OUTPUT_ERROR_MESSAGE}from"./errors-D62C9E7-.mjs";import{t as classifyProviderRuntimeFailureKind}from"./provider-runtime-failure-CoLwQkt4.mjs";
//!src/agents/embedded-agent-helpers/error-text.ts
const log=createSubsystemLogger(`errors`);const TOOL_REPEAT_LIMIT_FALLBACK=`OpenClaw stopped this turn: the model repeated the same tool call too many times. Send a new message to continue.`;const sandboxToolPolicyAuditMessages=/* @__PURE__ */ new WeakSet;const GENERIC_ASSISTANT_ERROR_TEXT=`LLM request failed.`;const SYNTHESIZED_TIMEOUT_ERROR_TEXT=`LLM request timed out.`;const RUNTIME_FAILURE_COPY={auth_refresh:"Couldn't sign in to the AI service. Sign in again under Models in the OpenClaw app or run `openclaw configure`.",refresh_contention:OAUTH_REFRESH_CONTENTION_USER_TEXT,refresh_timeout:`Signing in took too long. Try again in a moment. If it keeps happening, sign in again under Models in the OpenClaw app.`,callback_timeout:`Sign-in wasn't completed. Try signing in again. If asked for a link, paste the full link from your browser.`,callback_validation:`The sign-in link wasn't accepted. Try signing in again. If asked for a link, paste the full link from your browser.`,auth_scope:`This login doesn't have the access OpenClaw needs. Sign in again under Models in the OpenClaw app.`,auth_html:"Couldn't sign in to the AI service. Sign in again under Models in the OpenClaw app or run `openclaw configure`.",auth_invalid_token:AUTH_INVALID_TOKEN_USER_TEXT,upstream_html:"Couldn't reach the AI service. Try again in a moment. If it continues, open Settings → Logs in the OpenClaw app or run `openclaw logs --follow`.",proxy:"Couldn't connect to the AI service. For details, open Settings → Logs in the OpenClaw app or run `openclaw logs --follow`.",tls_certificate:TLS_CERTIFICATE_ERROR_USER_TEXT,model_not_found:`This model was not found. Choose another model in the OpenClaw app.`};const TOOL_CALL_INPUT_MISSING_RE=/tool_(?:use|call)\.(?:input|arguments).*?(?:field required|required)/i;const TOOL_CALL_INPUT_PATH_RE=/messages\.\d+\.content\.\d+\.tool_(?:use|call)\.(?:input|arguments)/i;function classifyAssistantErrorFacts(e,t){const n=buildAssistantFailoverSignal(e,{provider:t?.providerOwner?.id??t?.provider});const r=t?.providerOwner??null;const i=classifyFailoverSignal(n,{providerPlugin:r});return{provider:t?.provider??e.provider??t?.providerOwner?.id,model:t?.model??e.model,reason:failoverReasonFromClassification(i),status:n.status??extractErrorHttpStatus(n.message??``)?.code,providerRuntimeFailureKind:classifyProviderRuntimeFailureKind(n,{providerPlugin:r}),storageFailure:classifyGatewayStorageFailure(e),code:n.code,rateLimitResetAt:n.retryAfterMs===void 0?void 0:Date.now()+n.retryAfterMs}}function formatAssistantErrorText(e,t,n){const r=(e.errorMessage??``).trim();if(e.stopReason!==`error`&&!r)return;const i=formatProviderRefusalText(e);if(i)return i;const a=renderFormatErrorCopy(r);const o=n??classifyAssistantErrorFacts(e,t);if(o.storageFailure)return renderAssistantRequestFailureCopy(o);const{reason:s,status:c,providerRuntimeFailureKind:l}=o;if(c===403&&(e.errorType??parseApiErrorInfo(r)?.type)===`FreeTierError`)return`This model's free tier is limited to the provider's own client. Choose another model or use a paid plan.`;const u=r.match(/unknown tool[:\s]+["']?([a-z0-9_-]+)["']?/i)??r.match(/tool\s+["']?([a-z0-9_-]+)["']?\s+(?:not found|is not available)/i);if(u?.[1]&&t?.sandboxRuntime){const n=!sandboxToolPolicyAuditMessages.has(e);const r=formatSandboxToolPolicyBlockedMessage({cfg:t?.cfg,sessionKey:t?.sessionKey,agentId:t?.agentId,toolName:u[1],preparedRuntimeStatus:t.sandboxRuntime,audit:n});if(r){if(n)sandboxToolPolicyAuditMessages.add(e);return r}}const d=formatDiskSpaceErrorCopy(r);if(d)return d;const f=RUNTIME_FAILURE_COPY[l];if(f)return f;if(s===`billing`)return formatBillingErrorMessage(t?.provider,t?.model??e.model,t?.authMode);const p=s===`rate_limit`||s===`overloaded`?renderRateLimitOrOverloadedCopy({...o,reason:s,raw:r,locale:t?.cfg?.ui?.prefs?.locale,timeZone:t?.cfg?.agents?.defaults?.userTimezone}):void 0;if(p)return p;if((c===400||c===422)&&a!==`The AI service couldn't accept this request. Try a new conversation with /new, or choose another model in the OpenClaw app.`&&!a.startsWith(`LLM request rejected:`))return a;if(s===`context_overflow`)return CONTEXT_OVERFLOW_ERROR_MESSAGE;if(isReasoningConstraintErrorMessage(r))return`Reasoning is required for this model endpoint. Use /think minimal (or any non-off level) and try again.`;if(isInvalidStreamingEventOrderError(r))return`LLM request failed: provider returned an invalid streaming response. Please try again.`;if(/incorrect role information|roles must alternate|400.*role|"message".*role.*information/i.test(r))return`Message ordering conflict - please try again. If this persists, use /new to start a fresh session.`;if(r&&(TOOL_CALL_INPUT_MISSING_RE.test(r)||TOOL_CALL_INPUT_PATH_RE.test(r)))return`Session history looks corrupted (tool call input missing). Use /new to start a fresh session. If this keeps happening, reset the session or delete the corrupted chat history.`;if(l===`replay_invalid`)return`Session history or replay state is invalid. Use /new to start a fresh session and try again.`;const m=parseApiErrorInfo(r);if(l===`schema`&&m?.type?.toLowerCase().includes(`invalid_request`)&&m.message?.trim())return`LLM request rejected: ${m.message.trim()}`;if(isGenericProviderInternalError(r))return formatRawAssistantErrorForUi(r);const h=formatTransportErrorCopy(e.errorCode&&isKnownTransportErrorCode(e.errorCode)?`${r} ${e.errorCode}`:r);if(h)return h;if(isProviderCompletedErrorFinishReasonMessage(r))return formatRawAssistantErrorForUi(r);if(isTimeoutErrorMessage(r)&&!(n?.status!==void 0&&n.status>=500))return SYNTHESIZED_TIMEOUT_ERROR_TEXT;if(l===`schema`||s===`format`)return a;if(!r)return s?renderAssistantRequestFailureCopy(o):`LLM request failed with an unknown error.`;if(isRawApiErrorPayload(r)||isLikelyHttpErrorText(r))return formatRawAssistantErrorForUi(r);if(isStreamingJsonParseError(r))return`LLM streaming response contained a malformed fragment. Please try again.`;if(r.length>600)log.warn(`Long error truncated: ${truncateUtf16Safe(r,200)}`);return r.length>600?`${truncateUtf16Safe(r,600)}…`:r}function isRawAssistantErrorPassthrough(e){const t=e.friendlyError?.trim();const n=e.rawError?.trim();if(!t||!n)return false;const r=parseApiErrorInfo(n)?.message?.trim();const i=extractLeadingHttpStatus(n)?.rest?.trim();const a=t.startsWith(`LLM request rejected:`)||t.startsWith(`LLM error`)||t.startsWith(`HTTP `);return t===n&&t!==`LLM request timed out.`||n.length>600&&t===`${truncateUtf16Safe(n,600)}…`||Boolean(r&&a)||Boolean(i&&t.startsWith(`HTTP `))}function formatUserFacingAssistantErrorText(e,t){if(e.errorCode===`openclaw_repetitive_output`)return REPETITIVE_OUTPUT_ERROR_MESSAGE;if(e.errorCode===`tool_repeat_limit`)return e.errorMessage&&/^OpenClaw stopped this turn: the model called (?:[\w.-]{1,64}|a tool) with the same arguments \d+ times in a row\. Send a new message to continue\.$/.test(e.errorMessage)?e.errorMessage:TOOL_REPEAT_LIMIT_FALLBACK;const n=renderModelLoadFailureCopy(e);if(n)return n;const r=e.errorMessage?.trim();const i=resolveExecutionApprovalFailureMessage(r);if(i)return`⚠️ ${i}`;const a=classifyAssistantErrorFacts(e,t);if(!a.storageFailure&&r===`The deployment rejected this model request. Ask the administrator to check the model access policy and request settings.`)return MODEL_REQUEST_POLICY_DENIED_TEXT;const o=formatAssistantErrorText(e,t,a);const s=isRawAssistantErrorPassthrough({friendlyError:o,rawError:r});const c=o===`The AI service couldn't accept this request. Try a new conversation with /new, or choose another model in the OpenClaw app.`||o?.startsWith(`LLM request rejected:`);const l=(c?renderAssistantFormatFailureCopy(e,a.reason):void 0)??(s?c?`The AI service couldn't accept this request. Try a new conversation with /new, or choose another model in the OpenClaw app.`:void 0:o);if(l)return l.trim();return renderAssistantRequestFailureCopy(a)??`LLM request failed.`}
//!src/agents/embedded-agent-reply-source.ts
function resolveAssistantReplySource(e,t){if(t!==`telegram`||!e?.length)return;const n=e[0]?.transcriptMessage;const r=e.at(-1)?.transcriptMessage;if(n?.role!==`user`||r?.role!==`user`)return;const i=n;const a=r;const o=asOptionalRecord(i[`__openclaw`]?.transport);const s=asOptionalRecord(a[`__openclaw`]?.transport);const c=asOptionalRecord(i[`__openclaw`]?.senderIdentity);const l=asOptionalRecord(a[`__openclaw`]?.senderIdentity);if(a.provenance?.kind&&a.provenance.kind!==`external_user`||s?.channel!==`telegram`||!s.conversationRef||s.conversationRef!==o?.conversationRef||l?.accountId!==c?.accountId||typeof s.messageId!==`string`||!/^[1-9]\d{0,19}$/.test(s.messageId))return;return s.messageId}function withAssistantReplySource(e,t){if(!t||e.replyToCurrent===false||e.replyToId&&!e.replyToCurrent||e.replyToTag&&!e.replyToCurrent)return e;return setReplyPayloadMetadata(copyReplyPayloadMetadata(e,{...e,replyToId:t}),{replyToIdExplicit:Boolean(e.replyToCurrent||e.replyToTag)})}export{formatAssistantErrorText as a,SYNTHESIZED_TIMEOUT_ERROR_TEXT as i,withAssistantReplySource as n,formatUserFacingAssistantErrorText as o,GENERIC_ASSISTANT_ERROR_TEXT as r,resolveAssistantReplySource as t};