UNPKG

@mastra/core

Version:
386 lines (385 loc) • 18.6 kB
// src/loop/shared/provider-error-details.ts /** * Diagnostic fields of a provider HTTP failure (AI SDK `APICallError`). * * When a provider's error body doesn't match the shape the AI SDK expects, the * error `message` falls back to the HTTP status text ("Bad Request"), and the * real explanation is only in `responseBody`. These helpers pull out the fields * worth keeping without trusting the error object: getters may throw, fields * may be any type, and bodies may be huge. */ const MAX_PERSISTED_RESPONSE_BODY_LENGTH = 2e3; function capPersistedText(text) { return text.length > 2e3 ? `${text.slice(0, MAX_PERSISTED_RESPONSE_BODY_LENGTH)}…` : text; } const REQUEST_ID_HEADERS = ["request-id", "x-request-id"]; function readField$1(error, field) { try { return error[field]; } catch { return; } } function readRequestId(headers) { if (!headers || typeof headers !== "object") return void 0; for (const header of REQUEST_ID_HEADERS) { const value = readField$1(headers, header); if (typeof value === "string" && value.trim()) return value.trim(); } } function readRequestedModel(requestBody) { if (!requestBody || typeof requestBody !== "object") return void 0; const model = readField$1(requestBody, "model"); return typeof model === "string" && model.trim() ? model.trim() : void 0; } function readProviderErrorDetails(error) { if (error === null || typeof error !== "object" && typeof error !== "function") return {}; const details = {}; const statusCode = readField$1(error, "statusCode"); if (typeof statusCode === "number" && Number.isInteger(statusCode)) details.statusCode = statusCode; const responseBody = readField$1(error, "responseBody"); if (typeof responseBody === "string" && responseBody.trim()) details.responseBody = capPersistedText(responseBody); const requestId = readRequestId(readField$1(error, "responseHeaders")); if (requestId) details.requestId = requestId; const modelId = readRequestedModel(readField$1(error, "requestBodyValues")); if (modelId) details.modelId = modelId; return details; } /** * The provider's own explanation from a response body: `error.message` (Anthropic, * OpenAI), a top-level `message` or string `detail` (FastAPI backends such as the * ChatGPT Codex endpoint), or the raw text when the body isn't JSON. */ function providerExplanation(responseBody) { try { const parsed = JSON.parse(responseBody); if (parsed && typeof parsed === "object") { const nested = typeof parsed.error === "object" ? parsed.error?.message : parsed.error; if (typeof nested === "string" && nested.trim()) return nested.trim(); if (typeof parsed.message === "string" && parsed.message.trim()) return parsed.message.trim(); if (typeof parsed.detail === "string" && parsed.detail.trim()) return parsed.detail.trim(); } } catch {} return responseBody.trim(); } /** * Human-readable one-liner for a provider HTTP failure, at most `maxLength` * characters, or undefined when the error carries no HTTP details. Example: * `Bad Request (HTTP 400): prompt is too long (request id req_123)`. * * The explanation is parsed from the full body (a truncated JSON body would not * parse), and the request id is always kept when the text has to be shortened. */ function describeProviderError(message, error, maxLength) { const details = readProviderErrorDetails(error); if (details.statusCode === void 0 && details.responseBody === void 0) return void 0; let text = message; if (details.statusCode !== void 0) text += ` (HTTP ${details.statusCode})`; if (details.responseBody !== void 0) { const explanation = providerExplanation(readField$1(error, "responseBody")); if (explanation && explanation !== message) text += `: ${explanation}`; } else if (details.statusCode !== void 0) text += ": empty response body"; const suffix = details.requestId ? ` (request id ${details.requestId})` : ""; const room = Math.max(0, maxLength - suffix.length); if (text.length > room) text = `${text.slice(0, Math.max(0, room - 1))}…`; return text + suffix; } // src/error/provider-error.ts const MAX_OBJECT_DEPTH = 4; const ENVELOPE_TYPES = /* @__PURE__ */ new Set(["error", "response.failed"]); const SYMBOLIC_STATUS = /^[A-Z][A-Z0-9_]+$/; const BILLING_EXHAUSTED = /insufficient[_ ]quota|insufficient (?:balance|credits?)|credits? exhausted|credit balance|payment required/i; const USAGE_CAPPED = /usage (?:limit|cap)|quota (?:exceeded|exhausted|reached)|exceeded (?:your )?current quota|weekly limit|monthly limit/i; const RENEWS_WITHIN_THE_HOUR = /per[_ -]?(?:second|minute|hour|min|sec)\b|\b[rt]pm\b/i; const ACCESS_DENIED_WORDING = /invalid[_ ]api[_ ]key|incorrect api key|api key not valid|authentication[_ ]error|permission_?(?:denied|error)|access[_ ]?denied/i; const ACCESS_DENIED_CODE = new RegExp(`${ACCESS_DENIED_WORDING.source}|unauthorized|authentication|forbidden`, "i"); const CONTEXT_OVERFLOW = [ /context[_ ]length[_ ]exceeded/i, /maximum context length/i, /maximum prompt length/i, /prompt is too long/i, /input is too long/i, /exceed(?:s|ed|ing)?\b[^.]{0,40}\bcontext (?:window|length|limit|size)/i, /input token count[^.]{0,40}exceeds the maximum/i, /reduce the length of the (?:messages|prompt|input)/i ]; const MODEL_REJECTED = /model_not_found|model not found|no[_ ]?such[_ ]?model|not_found_error|invalid[_ ]model|unsupported[_ ]model|\bmodel\b[^.]{0,40}\bis not supported\b|unsupported[_ ]parameter|unsupported[_ ]value/i; const TOOL_HISTORY_REJECTED = /no tool output found for (?:function|tool) call|tool_call_ids[^.]{0,40}(?:response|respond)|tool_use[^.]{0,40}tool_result/i; const INVALID_REQUEST_CODE = /invalid_request_error|invalid_prompt/i; const INVALID_REQUEST_ENVELOPE = /^invalid_request_error$/i; const TIMED_OUT = /timed ?out|timeout|deadline[_ ]exceeded/i; const RATE_LIMITED = /rate[_ ]limit|too many requests|resource_exhausted|throttl/i; const UNAVAILABLE = /internal server error|server_error|internal_error|service[_ ]?unavailable|temporarily[_ ]?unavailable|bad gateway|overloaded/i; const HTTP_REASON_PHRASE = /^(?:bad request|unauthorized|payment required|forbidden|not found|method not allowed|not acceptable|proxy authentication required|request timeout|conflict|gone|length required|precondition failed|(?:payload|content|request entity) too large|(?:request-)?uri too long|unsupported media type|(?:requested )?range not satisfiable|expectation failed|i'm a teapot|misdirected request|unprocessable (?:entity|content)|locked|failed dependency|too early|upgrade required|precondition required|too many requests|request header fields too large|unavailable for legal reasons|internal server error|not implemented|bad gateway|service unavailable|gateway timeout|http version not supported|variant also negotiates|insufficient storage|loop detected|not extended|network authentication required)\.?$/i; const PROVIDER_CALL_ERROR_NAME = /^(?:AI_)?APICallError$/; const ACCESS_DENIED_PHRASE = /^(?:unauthorized|forbidden)\.?$/i; const MARKUP_OR_JSON = /^\s*[[{<]/; function readField(record, key) { try { return record[key]; } catch { return; } } function parseJsonObject(text) { const trimmed = text.trim(); if (!trimmed.startsWith("{")) return void 0; try { return JSON.parse(trimmed); } catch { return; } } function collect(value, facts, depth) { if (depth > MAX_OBJECT_DEPTH || value === null || value === void 0) return; if (typeof value === "string") { facts.texts.push(value); collect(parseJsonObject(value), facts, depth); return; } if (typeof value !== "object" || facts.seen.has(value)) return; facts.seen.add(value); const statusCode = readField(value, "statusCode"); if (typeof statusCode === "number" && Number.isInteger(statusCode)) facts.statusCode ??= statusCode; const code = readField(value, "code"); if (typeof code === "number" && Number.isInteger(code) && code >= 400 && code < 600) facts.statusCode ??= code; const status = readField(value, "status"); if (typeof status === "string" && SYMBOLIC_STATUS.test(status.trim())) facts.codes.push(status.trim()); const saved = readField(value, "codes"); const savedCodes = Array.isArray(saved) ? saved : []; for (const candidate of [ code, readField(value, "type"), ...savedCodes ]) if (typeof candidate === "string" && candidate.trim() && !ENVELOPE_TYPES.has(candidate)) facts.codes.push(candidate); const name = readField(value, "name"); if (typeof name === "string") facts.texts.push(name); for (const key of [ "message", "reason", "detail", "responseBody" ]) collect(readField(value, key), facts, depth); for (const key of [ "error", "data", "response", "cause" ]) collect(readField(value, key), facts, depth + 1); } function collectFacts(error) { const facts = { codes: [], texts: [], seen: /* @__PURE__ */ new WeakSet() }; collect(error, facts, 0); return facts; } function classifyProviderError(error) { const facts = collectFacts(error); const evidence = [...facts.codes, ...facts.texts].join("\n"); const verdict = providerVerdict(facts.statusCode, facts.codes.join("\n"), evidence); if (verdict === "invalid_request") return narrowInvalidRequest(evidence, facts.statusCode, facts.codes); if (verdict === "unavailable" && isContextOverflow(evidence)) return "context_overflow"; if (verdict) return verdict; return usageKind(evidence) ?? terminalKindFromWording(evidence) ?? transientKindFromWording(evidence) ?? providerCallPhraseKind(error, facts.texts) ?? "unknown"; } function providerCallPhraseKind(error, texts) { if (typeof error !== "object" || error === null) return void 0; const name = readField(error, "name"); if (typeof name !== "string" || !PROVIDER_CALL_ERROR_NAME.test(name)) return void 0; const message = readField(error, "message"); if (typeof message === "string" && ACCESS_DENIED_PHRASE.test(message.trim())) return "auth"; return texts.some((text) => HTTP_REASON_PHRASE.test(text.trim())) ? "invalid_request" : void 0; } function providerVerdict(status, codes, evidence) { if (status === 401 || status === 403 || ACCESS_DENIED_CODE.test(codes)) return "auth"; if (status === 402 || BILLING_EXHAUSTED.test(codes)) return "quota"; if (status === 429 || RATE_LIMITED.test(codes)) return usageKind(evidence) ?? "rate_limited"; if (status === 408 || status === 504 || TIMED_OUT.test(codes)) return "timeout"; if (status !== void 0 && status >= 500 || UNAVAILABLE.test(codes)) return "unavailable"; if (status === 400 || status === 404 || status === 422 || INVALID_REQUEST_CODE.test(codes)) return "invalid_request"; } function narrowInvalidRequest(evidence, status, codes) { if (BILLING_EXHAUSTED.test(evidence)) return "quota"; const uncodedRejection = status === 400 && codes.every((code) => INVALID_REQUEST_ENVELOPE.test(code)); if (uncodedRejection && usageKind(evidence) === "quota") return "quota"; if (uncodedRejection && RATE_LIMITED.test(evidence)) return "rate_limited"; return terminalKindFromWording(evidence) ?? "invalid_request"; } function usageKind(evidence) { if (BILLING_EXHAUSTED.test(evidence)) return "quota"; if (USAGE_CAPPED.test(evidence)) return RENEWS_WITHIN_THE_HOUR.test(evidence) ? "rate_limited" : "quota"; } function terminalKindFromWording(evidence) { if (ACCESS_DENIED_WORDING.test(evidence)) return "auth"; if (isContextOverflow(evidence)) return "context_overflow"; if (MODEL_REJECTED.test(evidence)) return "model_rejected"; if (TOOL_HISTORY_REJECTED.test(evidence)) return "tool_history_rejected"; if (INVALID_REQUEST_CODE.test(evidence)) return "invalid_request"; } function isContextOverflow(evidence) { return CONTEXT_OVERFLOW.some((pattern) => pattern.test(evidence)); } function transientKindFromWording(evidence) { if (TIMED_OUT.test(evidence)) return "timeout"; if (RATE_LIMITED.test(evidence)) return "rate_limited"; if (UNAVAILABLE.test(evidence)) return "unavailable"; } /** The JSON-safe facts worth carrying next to a failure's name and message, on the wire and in history. */ function providerErrorFacts(error) { const facts = collectFacts(error); const result = {}; if (facts.statusCode !== void 0) result.statusCode = facts.statusCode; const codes = [...new Set(facts.codes)]; if (codes.length > 0) result.codes = codes; const reason = reasonToPersist(error); if (reason !== void 0) result.reason = capPersistedText(reason); return result; } function reasonToPersist(error) { if (typeof error !== "object" || error === null) return void 0; const reason = producedByProvider(error) ? innermostReason(error, 0) : reasonBehindCause(readField(error, "cause"), 1); return ["message", "responseBody"].some((field) => { const saved = readField(error, field); return typeof saved === "string" && saved.trim() === reason; }) ? void 0 : reason; } /** The innermost sentence a provider wrote for a person, unwrapped from envelopes, stringified layers and a wrapped provider response. */ function providerErrorReason(error) { const reason = innermostReason(error, 0); return reason === void 0 ? void 0 : capPersistedText(reason); } function providerRequestId(error) { return firstAlongCauses(error, requestIdOf, 0); } function providerModelId(error) { return firstAlongCauses(error, modelIdOf, 0); } function firstAlongCauses(error, read, depth) { if (depth > MAX_OBJECT_DEPTH || typeof error !== "object" || error === null) return void 0; return read(error) ?? firstAlongCauses(readField(error, "cause"), read, depth + 1); } function requestIdOf(error) { return nonBlank(readField(error, "requestId")) ?? readRequestId(readField(error, "responseHeaders")); } function modelIdOf(error) { return nonBlank(readField(error, "modelId")) ?? readRequestedModel(readField(error, "requestBodyValues")); } function nonBlank(value) { return typeof value === "string" && value.trim() ? value.trim() : void 0; } function innermostReason(error, depth) { if (depth > MAX_OBJECT_DEPTH || error === null || error === void 0) return void 0; if (typeof error === "string") { const trimmed = error.trim(); const parsed = parseJsonObject(trimmed); if (parsed !== void 0) return innermostReason(parsed, depth); return !trimmed || HTTP_REASON_PHRASE.test(trimmed) ? void 0 : trimmed; } if (typeof error !== "object") return void 0; for (const key of ["reason", "detail"]) { const own = readField(error, key); const ownReason = typeof own === "string" ? innermostReason(own, depth) : void 0; if (ownReason) return ownReason; } for (const key of [ "error", "response", "data" ]) { const nested = innermostReason(readField(error, key), depth + 1); if (nested) return nested; } const body = readField(error, "responseBody"); const bodyReason = typeof body === "string" ? bodyExplanation(body, depth) : void 0; if (bodyReason) return bodyReason; const causeReason = reasonBehindCause(readField(error, "cause"), depth + 1); if (causeReason) return causeReason; const message = readField(error, "message"); return typeof message === "string" ? innermostReason(message, depth) : void 0; } function bodyExplanation(body, depth) { const parsed = parseJsonObject(body); if (parsed !== void 0) return innermostReason(parsed, depth); return MARKUP_OR_JSON.test(body) ? void 0 : innermostReason(body, depth); } function reasonBehindCause(cause, depth) { if (depth > MAX_OBJECT_DEPTH || typeof cause !== "object" || cause === null) return void 0; if (producedByProvider(cause)) return innermostReason(cause, depth); return reasonBehindCause(readField(cause, "cause"), depth + 1); } function producedByProvider(value) { const type = readField(value, "type"); return typeof readField(value, "statusCode") === "number" || typeof readField(value, "responseBody") === "string" || typeof type === "string" && ENVELOPE_TYPES.has(type); } // src/loop/shared/record-terminal-error-message.ts const FALLBACK_ERROR_NAME = "Error"; const FALLBACK_ERROR_MESSAGE = "Unknown error"; /** * Read one string field off an unknown error without letting a throwing getter * or proxy escape. Blank and whitespace-only values count as absent so a * persisted record never holds an empty string. */ function readErrorField(error, field) { let value; try { value = error[field]; } catch { return; } if (typeof value !== "string") return void 0; return value.trim().length > 0 ? value : void 0; } /** * Reduce an unknown terminal error to the JSON-safe identity that gets stored. * Never mutates the supplied error and never invokes `toJSON`, so a hostile or * circular error object cannot change what lands in history — or break it. */ function toPersistedErrorIdentity(error) { if (error === null || typeof error !== "object" && typeof error !== "function") return { name: FALLBACK_ERROR_NAME, message: FALLBACK_ERROR_MESSAGE }; return { name: readErrorField(error, "name") ?? FALLBACK_ERROR_NAME, message: readErrorField(error, "message") ?? FALLBACK_ERROR_MESSAGE, ...readProviderErrorDetails(error), ...providerErrorFacts(error) }; } /** * Record a terminal failure as an `error` part on the failed attempt's * assistant message, creating that message when the attempt produced no * output. Returns the message carrying the part, or undefined when there was * no assistant record to attach it to and none could be created. */ function recordTerminalErrorMessage({ messageList, attemptId, activeId, error }) { const errorPart = { type: "error", error: toPersistedErrorIdentity(error) }; const messages = messageList.get.all.db(); const target = (attemptId ? messages.find((message) => message.id === attemptId) : void 0) ?? (activeId ? messages.find((message) => message.id === activeId) : void 0); const targetParts = target?.role === "assistant" ? target.content?.parts : void 0; if (target && Array.isArray(targetParts)) { if (targetParts.some((part) => part?.type === "error")) return target; targetParts.push(errorPart); messageList.add(target, "response", { merge: false }); return target; } const message = { id: [activeId, attemptId].find((candidate) => candidate && !messages.some((message) => message.id === candidate)) ?? globalThis.crypto.randomUUID(), role: "assistant", createdAt: /* @__PURE__ */ new Date(), content: { format: 2, parts: [errorPart] } }; messageList.add(message, "response", { merge: false }); return message; } export { providerErrorReason as a, describeProviderError as c, classifyProviderError as i, readProviderErrorDetails as l, toPersistedErrorIdentity as n, providerModelId as o, PROVIDER_CALL_ERROR_NAME as r, providerRequestId as s, recordTerminalErrorMessage as t }; //# sourceMappingURL=error-CH1omHDL.js.map