openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
297 lines (296 loc) • 13.1 kB
JavaScript
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
//#region src/agents/failover/message-patterns.ts
const EXECUTION_APPROVAL_FAILURE_MESSAGES = /* @__PURE__ */ new Set([
"Codex node execution approval expired before a decision. Retry the action and approve the new request.",
"Codex node execution was denied. Retry the action and choose Allow once or Allow always to continue.",
"Codex node execution requires an available approval reviewer."
]);
/** Node launch refusals are not provider failures; only known, bounded copy is public. */
function resolveExecutionApprovalFailureMessage(e) {
const t = e?.trim().replace(/\s+\|\s+INVALID_REQUEST$/, "");
return t && EXECUTION_APPROVAL_FAILURE_MESSAGES.has(t) ? t : void 0;
}
const STATED_TOKEN_SIZES_RE = /(?:\btpm\b|tokens per minute)[^.\n]*?\blimit\s+([\d,]+)[^.\n]*?\brequested\s+([\d,]+)/i;
function readStatedTokenCount(e) {
const t = Number(e?.replaceAll(",", ""));
return Number.isFinite(t) && t > 0 ? t : void 0;
}
function isProviderRequestSizeCeilingError(e) {
if (!e) return false;
const t = STATED_TOKEN_SIZES_RE.exec(e);
const n = readStatedTokenCount(t?.[1]);
const r = readStatedTokenCount(t?.[2]);
return n !== void 0 && r !== void 0 && r > n;
}
const INCOMPLETE_ASSISTANT_STREAM_RE = /^(?:[\w -]*stream ended (?:before (?:message_?stop|(?:a )?terminal (?:finish reason|response event|event))|without (?:a terminal )?finish[_ ]reason|with an incomplete frame)|Responses stream ended with unresolved tool calls)[.!]?$/i;
const MALFORMED_SSE_MESSAGE_RE = /^Error reading response: malformed server-sent event JSON\.$/i;
const TERMINATED_TRANSPORT_MESSAGE_RE = /^terminated$/i;
const PRE_DISPATCH_TOOL_CALL_REJECTION_MESSAGES = /* @__PURE__ */ new Set([
"Provider completed tool call with malformed JSON arguments",
"Provider completed stream with an incomplete tool call",
"Provider returned an incomplete or malformed tool call",
"Mistral completed tool call has invalid JSON arguments",
"Responses stream completed tool call with invalid JSON arguments"
]);
const GATEWAY_INVALID_TOOL_INPUT_RE = /^Upstream returned invalid tool input for '[^'\r\n]{1,128}'\.?$/;
function isPreDispatchToolCallRejectionMessage(e) {
if (e === void 0) return false;
return PRE_DISPATCH_TOOL_CALL_REJECTION_MESSAGES.has(e) || GATEWAY_INVALID_TOOL_INPUT_RE.test(e.trim());
}
const PERIODIC_USAGE_LIMIT_RE = /\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b|已达到 Token Plan 用量上限|已达到每[日周月天](?:\/每[日周月天])*使用上限|(?:配额|额度)已用尽/i;
const HIGH_CONFIDENCE_AUTH_PERMANENT_PATTERNS = [
/api[_ ]?key[_ ]?(?:revoked|deactivated|deleted)/i,
/deactivated[_ ]workspace/i,
"key has been disabled",
"key has been revoked",
"account has been deactivated",
"not allowed for this organization"
];
const AMBIGUOUS_AUTH_ERROR_PATTERNS = [
/(?:invalid[_ ]?api[_ ]?key(?![a-z0-9])|api[_ ]?key(?:[_ ]?(?:is[_ ]?)?(?:invalid(?![a-z0-9])|not[_ ]?valid(?![a-z0-9]))))/i,
/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,
"permission_error"
];
const COMMON_AUTH_ERROR_PATTERNS = [
"incorrect api key",
"invalid token",
"authentication",
"re-authenticate",
"oauth token refresh failed",
"unauthorized",
"forbidden",
"access denied",
"insufficient permissions",
"insufficient permission",
/missing scopes?:/i,
/(? e instanceof RegExp ? e.test(n) : n.includes(e));
}
function matchesFormatErrorPattern(e) {
return matchesErrorPatterns(e, ERROR_PATTERNS.format);
}
function isUnsupportedReasoningEffortParameterError(e) {
if (/supported values(?: are)?:/i.test(e)) return false;
return /\b(?:unknown|unrecognized|unsupported|unexpected)\s+(?:field|parameter|(?:keyword\s+)?argument)\s*:?\s*["'`\\]*reasoning_effort(?![\w./-])/i.test(e) || /(?<![\w./-])reasoning_effort["'`\\]*\s+(?:parameter\s+)?(?:is\s+)?(?:not supported|unsupported)\b/i.test(e);
}
function isSessionTranscriptValidationErrorMessage(e) {
return /\b(?:invalid session transcript entry|persisted legacy session transcripts require doctor\/import migration)\b/i.test(e);
}
function isRateLimitErrorMessage(e) {
return matchesErrorPatterns(e, ERROR_PATTERNS.rateLimit);
}
function isTimeoutErrorMessage(e) {
return matchesErrorPatterns(e, ERROR_PATTERNS.timeout);
}
const PROVIDER_COMPLETED_ERROR_FINISH_REASON_PATTERNS = [/\bfinish_reason:\s*error\b/i, /\breason:\s*error\b/i];
function isProviderCompletedErrorFinishReasonMessage(e) {
return matchesErrorPatterns(e, PROVIDER_COMPLETED_ERROR_FINISH_REASON_PATTERNS);
}
function isPeriodicUsageLimitErrorMessage(e) {
return PERIODIC_USAGE_LIMIT_RE.test(e);
}
function isBillingErrorMessage(e) {
const t = normalizeLowercaseStringOrEmpty(e);
if (!t) return false;
if ([...e.matchAll(/(?:^|\n)##\s+\S/g)].length > 1) return false;
if (matchesErrorPatterns(t, ERROR_PATTERNS.billing)) return true;
if (!BILLING_ERROR_HEAD_RE.test(e)) return false;
return [
"upgrade",
"credits",
"payment",
"purchase",
"subscription",
"plan"
].some((e) => t.includes(e));
}
function isAuthPermanentErrorMessage(e) {
return matchesErrorPatterns(e, ERROR_PATTERNS.authPermanent);
}
function isAuthErrorMessage(e) {
return !resolveExecutionApprovalFailureMessage(e) && matchesErrorPatterns(e, ERROR_PATTERNS.auth);
}
function isOverloadedErrorMessage(e) {
return matchesErrorPatterns(e, ERROR_PATTERNS.overloaded);
}
function isServerErrorMessage(e) {
const t = normalizeLowercaseStringOrEmpty(e);
if (!t) return false;
if (STATUS_INTERNAL_SERVER_ERROR_WITH_500_RE.test(t) || HTTP_5XX_STATUS_RE.test(t)) return true;
const n = t.replace(STATUS_INTERNAL_SERVER_ERROR_RE, "").trim();
if (n === "") return true;
return matchesErrorPatterns(n, ERROR_PATTERNS.serverError);
}
/** `All models failed (3): provider/model: text | provider/model: text` */
const FAILOVER_AGGREGATE_PREFIX_RE = /^all(?: [\w-]+)? models failed \(\d+\):\s*/i;
const FAILOVER_AGGREGATE_LEG_SPLIT_RE = /\s\|\s|;\s(?=\S+\/\S+:\s)/;
/** `anthropic/claude-opus-5: You've hit your session limit` */
const FAILOVER_LEG_ROUTE_PREFIX_RE = /^\S+\/\S+:\s+/;
/**
* A chain summary concatenates every leg, so it outgrows the length guard that keeps
* provider text bounded, and a hint the provider did give is thrown away. Read the legs
* individually, preferring the first, which is the route the user actually chose.
*/
function splitFailoverAggregateLegs(e) {
const t = e.trim().replace(FAILOVER_AGGREGATE_PREFIX_RE, "");
if (t === e.trim()) return [];
return t.split(FAILOVER_AGGREGATE_LEG_SPLIT_RE).map((e) => e.trim().replace(FAILOVER_LEG_ROUTE_PREFIX_RE, "").trim()).filter(Boolean);
}
//#endregion
export { matchesFormatErrorPattern as _, isAuthPermanentErrorMessage as a, isPeriodicUsageLimitErrorMessage as c, isProviderRequestSizeCeilingError as d, isRateLimitErrorMessage as f, isUnsupportedReasoningEffortParameterError as g, isTimeoutErrorMessage as h, isAuthErrorMessage as i, isPreDispatchToolCallRejectionMessage as l, isSessionTranscriptValidationErrorMessage as m, MALFORMED_SSE_MESSAGE_RE as n, isBillingErrorMessage as o, isServerErrorMessage as p, TERMINATED_TRANSPORT_MESSAGE_RE as r, isOverloadedErrorMessage as s, INCOMPLETE_ASSISTANT_STREAM_RE as t, isProviderCompletedErrorFinishReasonMessage as u, resolveExecutionApprovalFailureMessage as v, splitFailoverAggregateLegs as y };