|
| 1 | +const MAX_MESSAGE_LENGTH = 500; |
| 2 | +const MAX_CAUSE_DEPTH = 5; |
| 3 | + |
| 4 | +type ErrorRecord = Record<string, unknown>; |
| 5 | + |
| 6 | +export type LlmErrorDetails = { |
| 7 | + name: string; |
| 8 | + message: string; |
| 9 | + stack?: string; |
| 10 | + status?: number; |
| 11 | + code?: string; |
| 12 | + type?: string; |
| 13 | + param?: string; |
| 14 | + requestId?: string; |
| 15 | + traceId?: string; |
| 16 | + causes?: LlmErrorDetails[]; |
| 17 | +}; |
| 18 | + |
| 19 | +/** |
| 20 | + * Produce a concise, credential-safe explanation from OpenAI-compatible API |
| 21 | + * errors and their underlying network causes. |
| 22 | + */ |
| 23 | +export function describeLlmError(error: unknown): string { |
| 24 | + const details = getLlmErrorDetails(error); |
| 25 | + const parts: string[] = []; |
| 26 | + |
| 27 | + if (details.status !== undefined) { |
| 28 | + const message = getProviderMessage(error) ?? details.message; |
| 29 | + parts.push(`HTTP ${details.status}: ${message}`); |
| 30 | + if (details.code) { |
| 31 | + parts.push(`code: ${details.code}`); |
| 32 | + } |
| 33 | + if (details.type) { |
| 34 | + parts.push(`type: ${details.type}`); |
| 35 | + } |
| 36 | + if (details.param) { |
| 37 | + parts.push(`param: ${details.param}`); |
| 38 | + } |
| 39 | + if (details.requestId) { |
| 40 | + parts.push(`request ID: ${details.requestId}`); |
| 41 | + } |
| 42 | + if (details.traceId) { |
| 43 | + parts.push(`trace ID: ${details.traceId}`); |
| 44 | + } |
| 45 | + return formatErrorParts(parts); |
| 46 | + } |
| 47 | + |
| 48 | + const causeMessage = findUsefulCauseMessage(details.causes ?? []); |
| 49 | + if (causeMessage && isGenericConnectionMessage(details.message)) { |
| 50 | + return `Connection error: ${causeMessage}`; |
| 51 | + } |
| 52 | + if (causeMessage && causeMessage !== details.message) { |
| 53 | + return `${details.message} (cause: ${causeMessage})`; |
| 54 | + } |
| 55 | + return details.message; |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * Extract serializable diagnostics for local logs without retaining the |
| 60 | + * original error object, which can contain circular references. |
| 61 | + */ |
| 62 | +export function getLlmErrorDetails(error: unknown): LlmErrorDetails { |
| 63 | + return getErrorDetails(error, 0, new Set<object>()); |
| 64 | +} |
| 65 | + |
| 66 | +function getErrorDetails(error: unknown, depth: number, seen: Set<object>): LlmErrorDetails { |
| 67 | + const record = isRecord(error) ? error : null; |
| 68 | + const name = safeText(record?.name) ?? (error instanceof Error ? error.name : "UnknownError"); |
| 69 | + const message = safeText(record?.message) ?? safeText(error) ?? "Unknown error"; |
| 70 | + const details: LlmErrorDetails = { name, message }; |
| 71 | + |
| 72 | + const status = record?.status; |
| 73 | + if (typeof status === "number" && Number.isFinite(status)) { |
| 74 | + details.status = status; |
| 75 | + } |
| 76 | + for (const key of ["code", "type", "param"] as const) { |
| 77 | + const value = safeText(record?.[key]); |
| 78 | + if (value) { |
| 79 | + details[key] = value; |
| 80 | + } |
| 81 | + } |
| 82 | + const requestId = safeText(record?.requestID) ?? getHeader(record?.headers, "x-request-id"); |
| 83 | + if (requestId) { |
| 84 | + details.requestId = requestId; |
| 85 | + } |
| 86 | + const traceId = getHeader(record?.headers, "x-ds-trace-id"); |
| 87 | + if (traceId) { |
| 88 | + details.traceId = traceId; |
| 89 | + } |
| 90 | + const stack = safeText(record?.stack, MAX_MESSAGE_LENGTH * 4); |
| 91 | + if (stack) { |
| 92 | + details.stack = stack; |
| 93 | + } |
| 94 | + |
| 95 | + if (record && depth < MAX_CAUSE_DEPTH && !seen.has(record)) { |
| 96 | + seen.add(record); |
| 97 | + if (record.cause !== undefined) { |
| 98 | + details.causes = [getErrorDetails(record.cause, depth + 1, seen)]; |
| 99 | + } |
| 100 | + } |
| 101 | + return details; |
| 102 | +} |
| 103 | + |
| 104 | +function getProviderMessage(error: unknown): string | undefined { |
| 105 | + if (!isRecord(error) || !isRecord(error.error)) { |
| 106 | + return undefined; |
| 107 | + } |
| 108 | + return safeText(error.error.message); |
| 109 | +} |
| 110 | + |
| 111 | +function getHeader(headers: unknown, name: string): string | undefined { |
| 112 | + if (headers && typeof (headers as { get?: unknown }).get === "function") { |
| 113 | + return safeText((headers as { get(name: string): unknown }).get(name)); |
| 114 | + } |
| 115 | + if (isRecord(headers)) { |
| 116 | + const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name); |
| 117 | + return entry ? safeText(entry[1]) : undefined; |
| 118 | + } |
| 119 | + return undefined; |
| 120 | +} |
| 121 | + |
| 122 | +function findUsefulCauseMessage(causes: LlmErrorDetails[]): string | undefined { |
| 123 | + for (const cause of causes) { |
| 124 | + if (!isGenericConnectionMessage(cause.message)) { |
| 125 | + return cause.message; |
| 126 | + } |
| 127 | + const nested = findUsefulCauseMessage(cause.causes ?? []); |
| 128 | + if (nested) { |
| 129 | + return nested; |
| 130 | + } |
| 131 | + } |
| 132 | + return undefined; |
| 133 | +} |
| 134 | + |
| 135 | +function isGenericConnectionMessage(message: string): boolean { |
| 136 | + const normalized = message.toLowerCase().replace(/\s+/g, " ").trim(); |
| 137 | + return ( |
| 138 | + normalized === "connection error" || |
| 139 | + normalized === "connection error." || |
| 140 | + normalized === "fetch failed" || |
| 141 | + normalized === "request timed out." || |
| 142 | + normalized === "request timed out" |
| 143 | + ); |
| 144 | +} |
| 145 | + |
| 146 | +function formatErrorParts(parts: string[]): string { |
| 147 | + const [first, ...metadata] = parts; |
| 148 | + return metadata.length > 0 ? `${first} [${metadata.join(", ")}]` : (first ?? "Unknown error"); |
| 149 | +} |
| 150 | + |
| 151 | +function safeText(value: unknown, maxLength = MAX_MESSAGE_LENGTH): string | undefined { |
| 152 | + if (typeof value !== "string" && typeof value !== "number") { |
| 153 | + return undefined; |
| 154 | + } |
| 155 | + const normalized = maskSensitive(String(value)).replace(/\s+/g, " ").trim(); |
| 156 | + if (!normalized) { |
| 157 | + return undefined; |
| 158 | + } |
| 159 | + return normalized.length > maxLength ? `${normalized.slice(0, maxLength)}...` : normalized; |
| 160 | +} |
| 161 | + |
| 162 | +function isRecord(value: unknown): value is ErrorRecord { |
| 163 | + return Boolean(value) && typeof value === "object"; |
| 164 | +} |
| 165 | + |
| 166 | +function maskSensitive(text: string): string { |
| 167 | + return text |
| 168 | + .replace(/(Authorization\s*[:=]\s*(?:Bearer\s+)?)[^\s,;]+/gi, "$1***MASKED***") |
| 169 | + .replace(/([?&](?:api[_-]?key|access[_-]?token|token)=)[^&\s]+/gi, "$1***MASKED***") |
| 170 | + .replace(/(["']?(?:api[_-]?key|access[_-]?token|secret)["']?\s*[:=]\s*["']?)[^",}\s]+/gi, "$1***MASKED***") |
| 171 | + .replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g, "***MASKED***"); |
| 172 | +} |
0 commit comments