import { APIError } from "@letta-ai/letta-client/core/error"; import { CLOUD_API_UNAVAILABLE_MESSAGE, isCloudApiShutdownRejection, } from "@/utils/cloud-api-shutdown"; import { formatConversationBusyErrorMessage, isConversationBusyErrorText, } from "@/utils/conversation-busy-error"; import { buildAgentTerminalLink, buildChatWebUrl } from "./app-urls"; import { getErrorContext } from "./error-context"; import { checkZaiError } from "./zai-errors"; const LETTA_USAGE_URL = buildChatWebUrl("/preferences/usage"); export const KEY_OR_CREDITS_REQUIRED_MESSAGE = `This model needs your own API key or Letta credits. Run /connect to add a provider key, or buy credits at ${LETTA_USAGE_URL}.`; const LETTA_AGENTS_URL = buildChatWebUrl("/agents"); export type ErrorDisplaySurface = "plain" | "terminal"; export interface FormatErrorDetailsOptions { automaticRetry?: boolean; surface?: ErrorDisplaySurface; unclassifiedFallback?: "generic"; } const GENERIC_ERROR_MESSAGE = "The request failed. Please try again."; function formatConversationBusyErrorForDisplay( errorText: string, runId: string | undefined, options: FormatErrorDetailsOptions, ): string | null { if (!isConversationBusyErrorText(errorText)) return null; return formatConversationBusyErrorMessage({ automaticRetry: options.automaticRetry ?? false, runId, }); } function extractReasonList(value: unknown): string[] { if (!Array.isArray(value)) return []; return value .filter((reason): reason is string => typeof reason === "string") .map((reason) => reason.toLowerCase()); } interface CloudflareEdgeErrorInfo { code?: string; statusText?: string; host?: string; rayId?: string; } const CLOUDFLARE_EDGE_5XX_MARKER_PATTERN = /(^|\s)(502|52[0-6])\s*[^<|]*\|\s*(?:502|52[0-6])\s*:\s*([^<]+)/i)?.[1] ?.trim() ?? text.match(/([^<]+)<\/span>/i)?.[1]?.trim(); const host = text.match(/utm_campaign=([a-z0-9.-]+)/i)?.[1] ?? text.match(/]*truncate[^>]*>([a-z0-9.-]+)<\/span>/i)?.[1]; const rayId = text.match( /Cloudflare Ray ID:\s*(?:]*>)?([a-z0-9]+)(?:<\/strong>)?/i, )?.[1] ?? text.match(/Cloudflare Ray ID:\s*([a-z0-9]+)/i)?.[1]; if (!code && !statusText && !host && !rayId) return undefined; return { code, statusText, host, rayId }; } export function checkCloudflareEdgeError(text: string): string | undefined { const info = parseCloudflareEdgeError(text); if (!info) return undefined; const codeLabel = info.code ? `Cloudflare ${info.code}` : "Cloudflare"; const statusSegment = info.statusText ? `: ${info.statusText}` : " upstream error"; const hostSegment = info.host ? ` for ${info.host}` : ""; const raySegment = info.rayId ? ` (Ray ID: ${info.rayId})` : ""; return `${codeLabel}${statusSegment}${hostSegment}${raySegment}. This is usually a temporary edge/origin outage. Please retry in a moment.`; } export function formatTelemetryErrorMessage( message: string | null | undefined, ): string { if (!message) return "Unknown error"; return checkCloudflareEdgeError(message) ?? message; } function getErrorReasons(e: APIError): string[] { const reasons = new Set(); const errorBody = e.error; if (errorBody && typeof errorBody === "object") { const body = errorBody as Record; for (const reason of extractReasonList(body.reasons)) { reasons.add(reason); } if (body.error && typeof body.error === "object") { const nested = body.error as Record; for (const reason of extractReasonList(nested.reasons)) { reasons.add(reason); } } } const message = e.message?.toLowerCase() ?? ""; for (const knownReason of [ "not-enough-credits", "model-unknown", "byok-not-available-on-free-tier", "free-usage-exceeded", "premium-usage-exceeded", "standard-usage-exceeded", "basic-usage-exceeded", "context-window-size-not-supported", "agents-limit-exceeded", "exceeded-quota", ]) { if (message.includes(knownReason)) { reasons.add(knownReason); } } return Array.from(reasons); } function hasErrorReason( e: APIError, reason: string, reasons?: string[], ): boolean { const allReasons = reasons ?? getErrorReasons(e); return allReasons.includes(reason.toLowerCase()); } function getReasonText(e: APIError): string | undefined { const errorBody = e.error; if (!errorBody || typeof errorBody !== "object") { return undefined; } const body = errorBody as Record; if (typeof body.reason_text === "string") { return body.reason_text; } if (body.error && typeof body.error === "object") { const nested = body.error as Record; if (typeof nested.reason_text === "string") { return nested.reason_text; } } return undefined; } function getRateLimitResetMs(e: APIError): number | undefined { if (e.status !== 429) return undefined; const errorBody = e.error; if (errorBody && typeof errorBody === "object") { if ("reasons" in errorBody && Array.isArray(errorBody.reasons)) { if (errorBody.reasons.includes("exceeded-quota")) { if ( "timeToQuotaResetMs" in errorBody && typeof errorBody.timeToQuotaResetMs === "number" ) { return errorBody.timeToQuotaResetMs; } return 0; } } } return undefined; } function findAndFormatCloudflareEdgeError(e: unknown): string | undefined { if (typeof e === "string") return checkCloudflareEdgeError(e); if (typeof e !== "object" || e === null) return undefined; if (e instanceof Error) { const msg = checkCloudflareEdgeError(e.message); if (msg) return msg; } const obj = e as Record; if (typeof obj.detail === "string") { const msg = checkCloudflareEdgeError(obj.detail); if (msg) return msg; } if (typeof obj.message === "string") { const msg = checkCloudflareEdgeError(obj.message); if (msg) return msg; } if (obj.error && typeof obj.error === "object") { const errObj = obj.error as Record; if (typeof errObj.detail === "string") { const msg = checkCloudflareEdgeError(errObj.detail); if (msg) return msg; } if (typeof errObj.message === "string") { const msg = checkCloudflareEdgeError(errObj.message); if (msg) return msg; } if (errObj.error && typeof errObj.error === "object") { const inner = errObj.error as Record; if (typeof inner.detail === "string") { const msg = checkCloudflareEdgeError(inner.detail); if (msg) return msg; } if (typeof inner.message === "string") { const msg = checkCloudflareEdgeError(inner.message); if (msg) return msg; } } } return undefined; } export function isProviderStreamDisconnectErrorText(text: string): boolean { const normalized = text.toLowerCase(); return ( normalized.includes("connection error during streaming") || normalized.includes("incomplete chunked read") || normalized.includes( "peer closed connection without sending complete message body", ) || normalized.includes("remoteprotocolerror") ); } export function checkProviderStreamDisconnectError( text: string, ): string | undefined { if (!isProviderStreamDisconnectErrorText(text)) return undefined; const provider = getProviderDisplayName(); return `${provider} closed the streaming connection before completing the response. Letta Code retries this automatically when it is safe; if it keeps happening, retry or switch models with /model.`; } function findAndFormatProviderStreamDisconnectError( e: unknown, ): string | undefined { if (typeof e === "string") return checkProviderStreamDisconnectError(e); if (typeof e !== "object" || e === null) return undefined; if (e instanceof Error) { const msg = checkProviderStreamDisconnectError(e.message); if (msg) return msg; } const obj = e as Record; if (typeof obj.detail === "string") { const msg = checkProviderStreamDisconnectError(obj.detail); if (msg) return msg; } if (typeof obj.message === "string") { const msg = checkProviderStreamDisconnectError(obj.message); if (msg) return msg; } if (obj.error && typeof obj.error === "object") { const errObj = obj.error as Record; if (typeof errObj.detail === "string") { const msg = checkProviderStreamDisconnectError(errObj.detail); if (msg) return msg; } if (typeof errObj.message === "string") { const msg = checkProviderStreamDisconnectError(errObj.message); if (msg) return msg; } if (errObj.error && typeof errObj.error === "object") { const inner = errObj.error as Record; if (typeof inner.detail === "string") { const msg = checkProviderStreamDisconnectError(inner.detail); if (msg) return msg; } if (typeof inner.message === "string") { const msg = checkProviderStreamDisconnectError(inner.message); if (msg) return msg; } } } return undefined; } function formatResetTime(ms: number): string { const now = new Date(); const resetTime = new Date(now.getTime() + ms); const timeStr = resetTime.toLocaleTimeString([], { hour: "numeric", minute: "2-digit", }); const totalMinutes = Math.ceil(ms / 60000); const hours = Math.floor(totalMinutes / 60); const minutes = totalMinutes % 60; let durationStr: string; if (hours > 0 && minutes > 0) { durationStr = `${hours}h ${minutes}m`; } else if (hours > 0) { durationStr = `${hours}h`; } else { durationStr = `${minutes}m`; } return `Resets at ${timeStr} (${durationStr})`; } function getResourceLimitMessage(e: APIError): string | undefined { if (e.status !== 402) return undefined; const errorBody = e.error; if (errorBody && typeof errorBody === "object") { if ( "error" in errorBody && typeof errorBody.error === "string" && errorBody.error.includes("You have reached your limit for") ) { return errorBody.error; } } if (e.message?.includes("You have reached your limit for")) { const match = e.message.match(/"error":"([^"]+)"/); if (match) { return match[1]; } } return undefined; } function isAgentLimitError(e: APIError, reasons?: string[]): boolean { if (e.status !== 429) return false; return hasErrorReason(e, "agents-limit-exceeded", reasons); } function isCreditExhaustedError(e: APIError, reasons?: string[]): boolean { if (e.status !== 402) return false; return hasErrorReason(e, "not-enough-credits", reasons); } function isLettaHostedModelContext(): boolean { const { modelLabel } = getErrorContext(); return modelLabel?.startsWith("letta/") || false; } function getLettaHostedQuotaMessage( e: APIError, reasons: string[], ): string | undefined { if (e.status !== 402 || !isLettaHostedModelContext()) return undefined; if ( reasons.includes("basic-usage-exceeded") && reasons.includes("not-enough-credits") ) { return `You've reached the quota for this Letta-hosted model. Upgrade your plan for more quota, or purchase credits at ${LETTA_USAGE_URL}.`; } return undefined; } function getTierUsageLimitMessage(reasons: string[]): string | undefined { if (reasons.includes("premium-usage-exceeded")) { return `You've reached your Premium model usage limit. Try switching to Standard or Basic hosted models with /model. View your plan and usage at ${LETTA_USAGE_URL}, or connect your own provider keys with /connect.`; } if (reasons.includes("standard-usage-exceeded")) { return `You've reached your Standard model usage limit. Try switching to Basic hosted models with /model. View your plan and usage at ${LETTA_USAGE_URL}, or connect your own provider keys with /connect.`; } if (reasons.includes("basic-usage-exceeded")) { return `You've reached your Basic model usage limit. Try switching models with /model, view your plan and usage at ${LETTA_USAGE_URL}, or connect your own provider keys with /connect.`; } return undefined; } const CHATGPT_USAGE_LIMIT_HINT = "Switch models with /model, or connect your own provider keys with /connect."; export function checkChatGptUsageLimitError(text: string): string | undefined { if (!text.includes("usage_limit_reached")) return undefined; const jsonStart = text.indexOf("{"); if (jsonStart < 0) { return `ChatGPT usage limit reached. ${CHATGPT_USAGE_LIMIT_HINT}`; } try { const parsed = JSON.parse(text.slice(jsonStart)); const errorObj = parsed.error || parsed; if (errorObj.type !== "usage_limit_reached") return undefined; const planType = errorObj.plan_type; const planInfo = planType ? ` (${planType} plan)` : ""; let resetInfo = "Try again later"; if ( typeof errorObj.resets_in_seconds === "number" && errorObj.resets_in_seconds > 0 ) { resetInfo = formatResetTime(errorObj.resets_in_seconds * 1000); } else if (typeof errorObj.resets_at === "number") { const resetMs = errorObj.resets_at * 1000 - Date.now(); if (resetMs > 0) { resetInfo = formatResetTime(resetMs); } } return `ChatGPT usage limit reached${planInfo}. ${resetInfo}.\n${CHATGPT_USAGE_LIMIT_HINT}`; } catch { return `ChatGPT usage limit reached. ${CHATGPT_USAGE_LIMIT_HINT}`; } } function findAndFormatChatGptUsageLimit(e: unknown): string | undefined { if (typeof e === "string") return checkChatGptUsageLimitError(e); if (typeof e !== "object" || e === null) return undefined; if (e instanceof Error) { const msg = checkChatGptUsageLimitError(e.message); if (msg) return msg; } const obj = e as Record; if (obj.error && typeof obj.error === "object") { const errObj = obj.error as Record; if (errObj.error && typeof errObj.error === "object") { const inner = errObj.error as Record; if (typeof inner.detail === "string") { const msg = checkChatGptUsageLimitError(inner.detail); if (msg) return msg; } } if (typeof errObj.detail === "string") { const msg = checkChatGptUsageLimitError(errObj.detail); if (msg) return msg; } } return undefined; } const ENCRYPTED_CONTENT_HINT = [ "", "This occurs when the conversation contains messages with encrypted", "reasoning from a different OpenAI authentication scope (e.g. switching", "between ChatGPT OAuth and an OpenAI API key).", "Use /clear to start a new conversation.", ].join("\n"); function findEncryptedContentDetail(e: unknown): string | undefined { if (typeof e !== "object" || e === null) return undefined; const obj = e as Record; if ( typeof obj.detail === "string" && obj.detail.includes("invalid_encrypted_content") ) { return obj.detail; } if (obj.error && typeof obj.error === "object") { const errObj = obj.error as Record; if (errObj.error && typeof errObj.error === "object") { const inner = errObj.error as Record; if ( typeof inner.detail === "string" && inner.detail.includes("invalid_encrypted_content") ) { return inner.detail; } } if ( typeof errObj.detail === "string" && errObj.detail.includes("invalid_encrypted_content") ) { return errObj.detail; } } return undefined; } function checkEncryptedContentError(e: unknown): string | undefined { const detail = findEncryptedContentDetail(e); if (!detail) { try { const errorStr = typeof e === "string" ? e : JSON.stringify(e); if (!errorStr.includes("invalid_encrypted_content")) return undefined; } catch { return undefined; } return ( "OpenAI error: Encrypted content could not be verified — organization mismatch." + ENCRYPTED_CONTENT_HINT ); } try { const jsonStart = detail.indexOf("{"); if (jsonStart >= 0) { const parsed = JSON.parse(detail.slice(jsonStart)); const innerError = parsed.error || parsed; if (innerError.code === "invalid_encrypted_content") { const msg = String( innerError.message || "Encrypted content verification failed.", ).replaceAll('"', '\\"'); return [ "OpenAI error:", " {", ` type: "${innerError.type || "invalid_request_error"}",`, ` code: "${innerError.code}",`, ` message: "${msg}"`, " }", ENCRYPTED_CONTENT_HINT, ].join("\n"); } } } catch {} return ( "OpenAI error: Encrypted content could not be verified — organization mismatch." + ENCRYPTED_CONTENT_HINT ); } export function isEncryptedContentError(e: unknown): boolean { return findEncryptedContentDetail(e) !== undefined; } export function formatErrorDetails( e: unknown, agentId?: string, conversationId?: string, options: FormatErrorDetailsOptions = {}, ): string { let runId: string | undefined; const surface = options.surface ?? "terminal"; const fallback = (raw: string): string => options.unclassifiedFallback === "generic" ? GENERIC_ERROR_MESSAGE : raw; if (isCloudApiShutdownRejection(e)) { return CLOUD_API_UNAVAILABLE_MESSAGE; } const encryptedContentMsg = checkEncryptedContentError(e); if (encryptedContentMsg) return encryptedContentMsg; const chatGptUsageLimitMsg = findAndFormatChatGptUsageLimit(e); if (chatGptUsageLimitMsg) return chatGptUsageLimitMsg; const cloudflareEdgeMsg = findAndFormatCloudflareEdgeError(e); if (cloudflareEdgeMsg) return cloudflareEdgeMsg; const providerStreamDisconnectMsg = findAndFormatProviderStreamDisconnectError(e); if (providerStreamDisconnectMsg) return providerStreamDisconnectMsg; const errorText = e instanceof APIError ? e.message : e instanceof Error ? e.message : typeof e === "string" ? e : undefined; if (errorText) { const zaiMsg = checkZaiError(errorText); if (zaiMsg) return zaiMsg; } if (e instanceof APIError) { const reasons = getErrorReasons(e); const rateLimitResetMs = getRateLimitResetMs(e); if (rateLimitResetMs !== undefined) { const resetInfo = rateLimitResetMs > 0 ? formatResetTime(rateLimitResetMs) : "Try again later"; return `You've hit your usage limit. ${resetInfo}. View usage: ${LETTA_USAGE_URL}`; } if (isAgentLimitError(e, reasons)) { const { billingTier } = getErrorContext(); if (billingTier?.toLowerCase() === "free") { return `You've reached the agent limit (3) for the Free Plan. Delete agents at: ${LETTA_AGENTS_URL}\nOr upgrade to Pro for unlimited agents at: ${LETTA_USAGE_URL}`; } return `You've reached your agent limit. Delete agents at: ${LETTA_AGENTS_URL}\nOr check your plan at: ${LETTA_USAGE_URL}`; } if (hasErrorReason(e, "model-unknown", reasons)) { return `The selected model is not currently available for this account or provider. Run /model and press R to refresh available models, then choose an available model or connect a provider with /connect.`; } if (hasErrorReason(e, "context-window-size-not-supported", reasons)) { return `The selected context window is not supported for this model. Switch models with /model or pick a model with a larger context window.`; } const resourceLimitMsg = getResourceLimitMessage(e); if (resourceLimitMsg) { const match = resourceLimitMsg.match(/limit for (\w+)/); const resourceType = match ? match[1] : "resources"; return `${resourceLimitMsg}\nUpgrade at: ${LETTA_USAGE_URL}\nDelete ${resourceType} at: ${LETTA_AGENTS_URL}`; } if (isCreditExhaustedError(e, reasons)) { const reasonText = getReasonText(e); if (reasonText) { return reasonText; } const lettaHostedQuotaMsg = getLettaHostedQuotaMessage(e, reasons); if (lettaHostedQuotaMsg) return lettaHostedQuotaMsg; return KEY_OR_CREDITS_REQUIRED_MESSAGE; } const lettaHostedQuotaMsg = getLettaHostedQuotaMessage(e, reasons); if (lettaHostedQuotaMsg) return lettaHostedQuotaMsg; const tierUsageLimitMsg = getTierUsageLimitMessage(reasons); if (tierUsageLimitMsg) return tierUsageLimitMsg; if (hasErrorReason(e, "byok-not-available-on-free-tier", reasons)) { const { modelDisplayName } = getErrorContext(); const modelInfo = modelDisplayName ? ` (${modelDisplayName})` : ""; return `Selected BYOK model${modelInfo} is not available on the Free plan. Switch to a free hosted model with /model (glm-4.7 or minimax-m2.1), or upgrade at ${LETTA_USAGE_URL}.`; } if (hasErrorReason(e, "free-usage-exceeded", reasons)) { return `You've reached the Free plan hosted model usage limit. Switch to free hosted models with /model (glm-4.7 or minimax-m2.1), upgrade at ${LETTA_USAGE_URL}, or connect your own provider keys with /connect.`; } if (e.error && typeof e.error === "object" && "error" in e.error) { const errorData = e.error.error; if (errorData && typeof errorData === "object") { const type = "type" in errorData ? errorData.type : undefined; const message = "message" in errorData ? errorData.message : "An error occurred"; const detail = "detail" in errorData ? errorData.detail : undefined; const errorType = type ? `[${type}] ` : ""; const errorDetail = detail ? `\nDetail: ${detail}` : ""; if ("run_id" in e.error && typeof e.error.run_id === "string") { runId = e.error.run_id; } const baseError = `${errorType}${message}${errorDetail}`; const conversationBusyMessage = formatConversationBusyErrorForDisplay( baseError, runId, options, ); if (conversationBusyMessage) return conversationBusyMessage; if (options.unclassifiedFallback === "generic") return fallback(baseError); return runId && agentId ? `${baseError}\n${createAgentLink(runId, agentId, conversationId, surface)}` : baseError; } } if (e.error && typeof e.error === "object") { const detail = "detail" in e.error ? e.error.detail : undefined; if ("run_id" in e.error && typeof e.error.run_id === "string") { runId = e.error.run_id; } const baseError = detail && typeof detail === "string" ? detail : e.message; const conversationBusyMessage = formatConversationBusyErrorForDisplay( baseError, runId, options, ); if (conversationBusyMessage) return conversationBusyMessage; if (options.unclassifiedFallback === "generic") return fallback(baseError); return runId && agentId ? `${baseError}\n${createAgentLink(runId, agentId, conversationId, surface)}` : baseError; } return fallback(e.message); } if (e instanceof Error) { return fallback(e.message); } if (typeof e === "object" && e !== null) { const obj = e as Record; if (typeof obj.message === "string") { return fallback(obj.message); } if (typeof obj.error === "string") { return fallback(obj.error); } if (typeof obj.detail === "string") { return fallback(obj.detail); } try { return fallback(JSON.stringify(e, null, 2)); } catch { return fallback("[Error: Unable to serialize error object]"); } } return fallback(String(e)); } const DEFAULT_RETRY_MESSAGE = "Unexpected downstream LLM API error, retrying..."; export function getRetryStatusMessage( errorDetail: string | null | undefined, ): string | null { if (!errorDetail) return DEFAULT_RETRY_MESSAGE; if (isCloudflareEdge52xErrorText(errorDetail)) return "Cloudflare transient error, retrying..."; if (checkZaiError(errorDetail)) return "Z.ai API error, retrying..."; if (errorDetail.includes("Anthropic API is overloaded")) return "Anthropic API is overloaded, retrying..."; if ( errorDetail.includes("ChatGPT API error") || errorDetail.includes("ChatGPT server error") ) { return "OpenAI ChatGPT backend connection failed, retrying..."; } if ( errorDetail.includes("upstream connect error") || errorDetail.includes("Connection error during streaming") || errorDetail.includes("incomplete chunked read") || errorDetail.includes("connection termination") ) { const provider = getProviderDisplayName(); return `${provider} streaming connection dropped, retrying...`; } if (errorDetail.includes("OpenAI API error")) return "OpenAI API error, retrying..."; return DEFAULT_RETRY_MESSAGE; } const ENDPOINT_TYPE_DISPLAY_NAMES: Record = { openai: "OpenAI", anthropic: "Anthropic", chatgpt_oauth: "OpenAI", google_ai: "Google AI", google_vertex: "Google Vertex", bedrock: "AWS Bedrock", openrouter: "OpenRouter", minimax: "MiniMax", zai: "zAI", }; function getProviderDisplayName(): string { const { modelEndpointType } = getErrorContext(); if (!modelEndpointType) return "LLM"; return ENDPOINT_TYPE_DISPLAY_NAMES[modelEndpointType] ?? modelEndpointType; } function createAgentLink( runId: string, agentId: string, conversationId: string | undefined, surface: ErrorDisplaySurface, ): string { const agentRef = surface === "terminal" ? buildAgentTerminalLink(agentId, { conversationId }) : agentId; return `View agent: ${agentRef} (run: ${runId})`; }