llm-error-classifier.ts 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. /**
  2. * Shared LLM error classifier — single source of truth for both daemon
  3. * (`runtime=llm-client`, `runtime=Vercel` finishStep) and the legacy local runtime
  4. * plugin (`finish-step` / `error` events).
  5. *
  6. * Why shared instead of two parallel copies:
  7. * • The metric label `error_reason` on `llm_call_total` and
  8. * `tool_call_total` consumes a fixed bounded enum. If daemon and
  9. * plugin classify the same error differently, we get two different
  10. * time series for the same incident — Grafana dashboards break.
  11. * • The plugin only sees the post-SDK normalised shape (a plain
  12. * `{ statusCode, errorMessage, finishReason }` triple) while the daemon
  13. * sees the raw thrown value (often `APICallError` or a `DOMException`).
  14. * Both inputs collapse into the same enum here.
  15. *
  16. * Adding a new bucket: append to `LLM_ERROR_REASONS`, update the matching
  17. * branch in `classifyLLMError`, and bump the
  18. * `metrics-runtime.test.ts > schema enum sync` snapshot if needed.
  19. */
  20. export const LLM_ERROR_REASONS = [
  21. 'abort',
  22. 'timeout',
  23. 'rate_limited',
  24. 'tpm_rate_limited',
  25. 'usage_limit',
  26. 'credits_exhausted',
  27. 'auth',
  28. 'bad_request',
  29. 'not_found',
  30. 'content_filter',
  31. 'server_error',
  32. 'overloaded',
  33. 'network',
  34. 'empty_response',
  35. 'unknown',
  36. 'length',
  37. ] as const;
  38. export type LLMErrorReason = (typeof LLM_ERROR_REASONS)[number];
  39. export type LLMMetricErrorKind = LLMErrorReason;
  40. export const LLM_RETRY_REASONS = [
  41. 'timeout',
  42. 'network',
  43. 'rate_limited',
  44. 'tpm_rate_limited',
  45. 'overloaded',
  46. ] as const;
  47. export type LLMRetryReason = (typeof LLM_RETRY_REASONS)[number];
  48. export type LLMRetryDecision =
  49. | { retryable: true; reason: LLMRetryReason }
  50. | { retryable: false; reason: LLMMetricErrorKind };
  51. export type LLMErrorSignal =
  52. | 'usage_limit'
  53. | 'credits_exhausted'
  54. | 'tpm_rate_limit'
  55. | 'content_filter'
  56. | 'network'
  57. | 'empty_response'
  58. | 'length';
  59. export interface LLMErrorFacts {
  60. explicitAbort: boolean;
  61. timeout: boolean;
  62. httpStatus?: number;
  63. upstreamStatusCode?: number;
  64. providerMessageCode?: number;
  65. existingProtocolCode?: number;
  66. signals: ReadonlySet<LLMErrorSignal>;
  67. }
  68. export interface LLMErrorInput {
  69. raw?: unknown;
  70. finishReason?: string;
  71. errorMessage?: string;
  72. statusCode?: number;
  73. explicitAbort?: boolean;
  74. }
  75. export interface NormalizedLLMError {
  76. facts: LLMErrorFacts;
  77. sanitizedMessage?: string;
  78. }
  79. export interface LLMProtocolClassification {
  80. code: number;
  81. message?: string;
  82. }
  83. const EMPTY_FACTS = (): LLMErrorFacts => ({
  84. explicitAbort: false,
  85. timeout: false,
  86. signals: new Set<LLMErrorSignal>(),
  87. });
  88. const SAFE_NETWORK_CODES = new Set([
  89. 'ECONNREFUSED',
  90. 'ECONNRESET',
  91. 'ENOTFOUND',
  92. 'ETIMEDOUT',
  93. 'ESOCKETTIMEDOUT',
  94. 'ECONNABORTED',
  95. 'ERR_CONNECTION_REFUSED',
  96. 'ERR_CONNECTION_RESET',
  97. 'ERR_CONNECTION_CLOSED',
  98. 'ERR_NETWORK_IO_SUSPENDED',
  99. 'ERR_NETWORK_CHANGED',
  100. 'ERR_NAME_NOT_RESOLVED',
  101. 'ERR_INTERNET_DISCONNECTED',
  102. 'ERR_ADDRESS_UNREACHABLE',
  103. 'ERR_PROXY_CONNECTION_FAILED',
  104. 'ERR_HTTP2_PROTOCOL_ERROR',
  105. 'ERR_TIMED_OUT',
  106. 'ERR_CONNECTION_TIMED_OUT',
  107. 'UND_ERR_CONNECT_TIMEOUT',
  108. 'UND_ERR_HEADERS_TIMEOUT',
  109. 'UND_ERR_BODY_TIMEOUT',
  110. ]);
  111. const CONNECTION_ERROR_MESSAGE_RE = /Connection error\.?/i;
  112. const ABORT_MESSAGE_RE = /\babort(?:ed|ing)?\b/i;
  113. const TRANSIENT_TIMEOUT_MESSAGE_RE =
  114. /\b(?:timed?\s*out|timeout|ETIMEDOUT|ESOCKETTIMEDOUT|ECONNABORTED|UND_ERR_(?:CONNECT|HEADERS|BODY)_TIMEOUT)\b/i;
  115. const TRANSIENT_NETWORK_MESSAGE_RE =
  116. /\b(?:ECONNREFUSED|ECONNRESET|ENOTFOUND|fetch failed|network)\b/i;
  117. const SAFE_TRANSPORT_NETWORK_MESSAGE_RE = /\b(?:ECONNREFUSED|ECONNRESET|ENOTFOUND|fetch failed)\b/i;
  118. const CHROMIUM_NETWORK_MESSAGE_RE =
  119. /\bnet::ERR_(?:CONNECTION_(?:RESET|CLOSED|REFUSED)|NETWORK_IO_SUSPENDED|NETWORK_CHANGED|NAME_NOT_RESOLVED|INTERNET_DISCONNECTED|ADDRESS_UNREACHABLE|PROXY_CONNECTION_FAILED|HTTP2_PROTOCOL_ERROR)\b/i;
  120. const CHROMIUM_TIMEOUT_MESSAGE_RE = /\bnet::ERR_(?:TIMED_OUT|CONNECTION_TIMED_OUT)\b/i;
  121. const LLM_USAGE_LIMIT_UPSTREAM_STATUS_CODES = [2056, 2067] as const;
  122. const LLM_USAGE_LIMIT_UPSTREAM_STATUS_CODE_SET = new Set<number>(
  123. LLM_USAGE_LIMIT_UPSTREAM_STATUS_CODES,
  124. );
  125. const LLM_USAGE_LIMIT_UPSTREAM_STATUS_CODE_RE = /\b(?:2056|2067)\b/u;
  126. function isLLMUsageLimitUpstreamStatusCode(statusCode: number | undefined): boolean {
  127. return statusCode !== undefined && LLM_USAGE_LIMIT_UPSTREAM_STATUS_CODE_SET.has(statusCode);
  128. }
  129. /** Best-effort, bounded and no-throw extraction of stable LLM error facts. */
  130. export function normalizeLLMError(input: LLMErrorInput): NormalizedLLMError {
  131. try {
  132. const facts = EMPTY_FACTS();
  133. const signals = facts.signals as Set<LLMErrorSignal>;
  134. facts.explicitAbort = input.explicitAbort === true || input.finishReason === 'aborted';
  135. if (input.finishReason === 'length') signals.add('length');
  136. if (input.finishReason === 'content-filter' || input.finishReason === 'content_filter') {
  137. signals.add('content_filter');
  138. }
  139. const extracted = safeExtract(input.raw);
  140. facts.httpStatus ??= validHttpStatus(input.statusCode) ?? extracted.httpStatus;
  141. facts.upstreamStatusCode ??= extracted.upstreamStatusCode;
  142. facts.providerMessageCode ??= extracted.providerMessageCode;
  143. facts.existingProtocolCode ??= extracted.existingProtocolCode;
  144. facts.explicitAbort ||= extracted.explicitAbort === true;
  145. facts.timeout ||= extracted.timeout === true;
  146. if (extracted.network) signals.add('network');
  147. const visibleMessage = extracted.message ?? input.errorMessage;
  148. const legacy = extractLegacyMessageFacts(visibleMessage);
  149. facts.httpStatus ??= legacy.httpStatus;
  150. facts.upstreamStatusCode ??= legacy.upstreamStatusCode;
  151. facts.existingProtocolCode ??= legacy.existingProtocolCode;
  152. const message = legacy.message ?? visibleMessage;
  153. applyMessageSignals(message, facts, signals);
  154. applyNumericSignals(facts, signals);
  155. return { facts, ...(message ? { sanitizedMessage: message } : {}) };
  156. } catch {
  157. return {
  158. facts: EMPTY_FACTS(),
  159. ...(typeof input.errorMessage === 'string' ? { sanitizedMessage: input.errorMessage } : {}),
  160. };
  161. }
  162. }
  163. export function toLLMMetricErrorKind(facts: LLMErrorFacts): LLMMetricErrorKind {
  164. try {
  165. if (facts.explicitAbort) return 'abort';
  166. if (facts.signals.has('credits_exhausted')) return 'credits_exhausted';
  167. if (facts.signals.has('usage_limit')) return 'usage_limit';
  168. if (facts.signals.has('tpm_rate_limit')) return 'tpm_rate_limited';
  169. if (facts.timeout && effectiveHttpStatus(facts) === 529) return 'overloaded';
  170. if (facts.timeout) return 'timeout';
  171. if (facts.signals.has('content_filter')) return 'content_filter';
  172. if (facts.signals.has('empty_response')) return 'empty_response';
  173. if (facts.signals.has('length')) return 'length';
  174. switch (facts.existingProtocolCode) {
  175. case LLM_ERROR_CODES.USAGE_LIMIT_EXCEEDED:
  176. return 'usage_limit';
  177. case LLM_ERROR_CODES.LLM_CREDITS_EXHAUSTED:
  178. return 'credits_exhausted';
  179. case LLM_ERROR_CODES.LLM_TPM_RATE_LIMITED:
  180. return 'tpm_rate_limited';
  181. case LLM_ERROR_CODES.LLM_RATE_LIMITED:
  182. return 'rate_limited';
  183. case LLM_ERROR_CODES.LLM_AUTH_ERROR:
  184. return 'auth';
  185. case LLM_ERROR_CODES.LLM_CLUSTER_OVERLOADED:
  186. return 'overloaded';
  187. }
  188. const status = effectiveHttpStatus(facts);
  189. if (status === 429) return 'rate_limited';
  190. if (status === 401 || status === 403) return 'auth';
  191. if (status === 404) return 'not_found';
  192. if (status !== undefined && status >= 400 && status < 500) return 'bad_request';
  193. if (status === 529) return 'overloaded';
  194. if (facts.signals.has('network')) return 'network';
  195. if (status !== undefined && status >= 500) return 'server_error';
  196. return 'unknown';
  197. } catch {
  198. return 'unknown';
  199. }
  200. }
  201. /**
  202. * Strict transport-retry policy shared by all hosts that opt into framework retry.
  203. *
  204. * Product quota, credits, auth and explicit cancellation always win over an outer
  205. * transient-looking HTTP status. Only the bounded allowlist below is retryable;
  206. * generic 5xx and unknown failures deliberately fail closed.
  207. */
  208. export function toLLMRetryDecision(normalized: NormalizedLLMError): LLMRetryDecision {
  209. const { facts } = normalized;
  210. const metricKind = toLLMMetricErrorKind(facts);
  211. if (
  212. facts.explicitAbort ||
  213. facts.signals.has('usage_limit') ||
  214. facts.signals.has('credits_exhausted') ||
  215. facts.signals.has('content_filter') ||
  216. metricKind === 'abort' ||
  217. metricKind === 'usage_limit' ||
  218. metricKind === 'credits_exhausted' ||
  219. metricKind === 'auth'
  220. ) {
  221. return { retryable: false, reason: metricKind };
  222. }
  223. const status = effectiveHttpStatus(facts);
  224. if (
  225. facts.existingProtocolCode === LLM_ERROR_CODES.LLM_AUTH_ERROR ||
  226. status === 401 ||
  227. status === 403
  228. ) {
  229. return { retryable: false, reason: 'auth' };
  230. }
  231. if (facts.timeout) return { retryable: true, reason: 'timeout' };
  232. if (facts.signals.has('network')) return { retryable: true, reason: 'network' };
  233. switch (facts.existingProtocolCode) {
  234. case LLM_ERROR_CODES.LLM_RATE_LIMITED:
  235. return { retryable: true, reason: 'rate_limited' };
  236. case LLM_ERROR_CODES.LLM_TPM_RATE_LIMITED:
  237. return { retryable: true, reason: 'tpm_rate_limited' };
  238. case LLM_ERROR_CODES.LLM_CLUSTER_OVERLOADED:
  239. return { retryable: true, reason: 'overloaded' };
  240. }
  241. if (status === 429) {
  242. return {
  243. retryable: true,
  244. reason: facts.signals.has('tpm_rate_limit') ? 'tpm_rate_limited' : 'rate_limited',
  245. };
  246. }
  247. if (status === 529) return { retryable: true, reason: 'overloaded' };
  248. return { retryable: false, reason: metricKind };
  249. }
  250. export function toLLMProtocolClassification(
  251. normalized: NormalizedLLMError,
  252. ): LLMProtocolClassification | null {
  253. try {
  254. const { facts, sanitizedMessage } = normalized;
  255. const httpStatus = effectiveHttpStatus(facts);
  256. let code: number | undefined;
  257. if (
  258. facts.existingProtocolCode &&
  259. Object.values(LLM_ERROR_CODES).includes(facts.existingProtocolCode as LLMErrorStatusCode)
  260. ) {
  261. code = facts.existingProtocolCode;
  262. } else if (facts.signals.has('credits_exhausted')) {
  263. code = LLM_ERROR_CODES.LLM_CREDITS_EXHAUSTED;
  264. } else if (isLLMUsageLimitUpstreamStatusCode(facts.upstreamStatusCode)) {
  265. code = LLM_ERROR_CODES.USAGE_LIMIT_EXCEEDED;
  266. } else if (httpStatus === 429 && facts.signals.has('tpm_rate_limit')) {
  267. code = LLM_ERROR_CODES.LLM_TPM_RATE_LIMITED;
  268. } else if (httpStatus === 529) {
  269. code = LLM_ERROR_CODES.LLM_CLUSTER_OVERLOADED;
  270. } else if (httpStatus !== undefined) {
  271. code = mapUpstreamHttpError(httpStatus);
  272. } else if (facts.timeout) {
  273. code = LLM_ERROR_CODES.LLM_UPSTREAM_ERROR;
  274. }
  275. return code === undefined
  276. ? null
  277. : { code, ...(sanitizedMessage ? { message: sanitizedMessage } : {}) };
  278. } catch {
  279. return null;
  280. }
  281. }
  282. interface SafeExtracted {
  283. httpStatus?: number;
  284. upstreamStatusCode?: number;
  285. providerMessageCode?: number;
  286. existingProtocolCode?: number;
  287. explicitAbort?: boolean;
  288. timeout?: boolean;
  289. network?: boolean;
  290. message?: string;
  291. }
  292. function safeExtract(raw: unknown): SafeExtracted {
  293. const out: SafeExtracted = {};
  294. const seen = new WeakSet<object>();
  295. const queue: Array<{ value: unknown; depth: number }> = [{ value: raw, depth: 0 }];
  296. let visited = 0;
  297. while (queue.length > 0 && visited++ < 32) {
  298. const item = queue.shift()!;
  299. if (item.depth > 4 || typeof item.value !== 'object' || item.value === null) continue;
  300. if (seen.has(item.value)) continue;
  301. seen.add(item.value);
  302. if (
  303. item.value instanceof Error ||
  304. (typeof DOMException !== 'undefined' && item.value instanceof DOMException)
  305. ) {
  306. const builtinError = item.value;
  307. if (builtinError.name === 'AbortError') out.explicitAbort = true;
  308. if (/TimeoutError/u.test(builtinError.name)) out.timeout = true;
  309. if (!out.message && builtinError.message) out.message = sanitizeMessage(builtinError.message);
  310. }
  311. let descriptors: PropertyDescriptorMap;
  312. try {
  313. descriptors = Object.getOwnPropertyDescriptors(item.value);
  314. } catch {
  315. continue;
  316. }
  317. const value = (key: string): unknown => {
  318. const descriptor = descriptors[key];
  319. return descriptor && 'value' in descriptor ? descriptor.value : undefined;
  320. };
  321. const name = value('name');
  322. const code = value('code');
  323. if (name === 'AbortError') out.explicitAbort = true;
  324. if (typeof name === 'string' && /TimeoutError/u.test(name)) out.timeout = true;
  325. if (typeof code === 'string' && SAFE_NETWORK_CODES.has(code)) {
  326. out.network = true;
  327. if (isLLMTransportTimeoutCode(code)) out.timeout = true;
  328. }
  329. const statusCode = validHttpStatus(value('statusCode')) ?? validHttpStatus(value('status'));
  330. out.httpStatus ??= statusCode;
  331. if (name === 'APICallError' && statusCode === undefined && item.value instanceof Error) {
  332. out.network = true;
  333. }
  334. const upstream = validInteger(value('status_code'));
  335. out.upstreamStatusCode ??= upstream;
  336. const existing = validInteger(value('errorCode'));
  337. out.existingProtocolCode ??= existing;
  338. const providerCode = validInteger(value('code'));
  339. if (providerCode !== undefined && providerCode < 10000)
  340. out.providerMessageCode ??= providerCode;
  341. const statusMessage = value('status_message') ?? value('status_msg');
  342. const message = value('message');
  343. if (typeof statusMessage === 'string') out.message = sanitizeMessage(statusMessage);
  344. else if (!out.message && typeof message === 'string') out.message = sanitizeMessage(message);
  345. const responseBody = value('responseBody');
  346. if (typeof responseBody === 'string' && responseBody.length <= 64_000) {
  347. try {
  348. queue.push({ value: JSON.parse(responseBody), depth: item.depth + 1 });
  349. } catch {
  350. /* compatibility fallback */
  351. }
  352. }
  353. for (const key of ['cause', 'error', 'data']) {
  354. queue.push({ value: value(key), depth: item.depth + 1 });
  355. }
  356. }
  357. return out;
  358. }
  359. function validInteger(value: unknown): number | undefined {
  360. return typeof value === 'number' &&
  361. Number.isSafeInteger(value) &&
  362. value >= 0 &&
  363. value <= 2_000_000_000
  364. ? value
  365. : undefined;
  366. }
  367. function validHttpStatus(value: unknown): number | undefined {
  368. const n = validInteger(value);
  369. return n !== undefined && n >= 100 && n <= 599 ? n : undefined;
  370. }
  371. function sanitizeMessage(message: string): string {
  372. return message.slice(0, 4096);
  373. }
  374. function extractLegacyMessageFacts(message: string | undefined): {
  375. httpStatus?: number;
  376. upstreamStatusCode?: number;
  377. existingProtocolCode?: number;
  378. message?: string;
  379. } {
  380. if (!message) return {};
  381. const boundedMessage = sanitizeMessage(message);
  382. const extracted = tryExtractFromPayload({ message: boundedMessage });
  383. const classified = classifyLLMErrorToCode(boundedMessage);
  384. const statusCode = validInteger(extracted.statusCode);
  385. const httpStatus = validHttpStatus(statusCode);
  386. return {
  387. ...(httpStatus !== undefined ? { httpStatus } : {}),
  388. ...(statusCode !== undefined && httpStatus === undefined
  389. ? { upstreamStatusCode: statusCode }
  390. : {}),
  391. ...(classified ? { existingProtocolCode: classified.status_code } : {}),
  392. ...(extracted.message ? { message: sanitizeMessage(extracted.message) } : {}),
  393. };
  394. }
  395. function applyNumericSignals(facts: LLMErrorFacts, signals: Set<LLMErrorSignal>): void {
  396. const httpStatus = effectiveHttpStatus(facts);
  397. if (
  398. facts.upstreamStatusCode === 1400010161 ||
  399. facts.providerMessageCode === 1008 ||
  400. httpStatus === 402
  401. )
  402. signals.add('credits_exhausted');
  403. if (isLLMUsageLimitUpstreamStatusCode(facts.upstreamStatusCode)) signals.add('usage_limit');
  404. if (
  405. httpStatus === 429 &&
  406. [2045, 2046, 2047, 1039, 1041].includes(facts.providerMessageCode ?? -1)
  407. )
  408. signals.add('tpm_rate_limit');
  409. }
  410. function effectiveHttpStatus(facts: LLMErrorFacts): number | undefined {
  411. return validHttpStatus(facts.upstreamStatusCode) ?? facts.httpStatus;
  412. }
  413. function applyMessageSignals(
  414. message: string | undefined,
  415. facts: LLMErrorFacts,
  416. signals: Set<LLMErrorSignal>,
  417. ): void {
  418. if (!message) return;
  419. if (/\brequest was aborted\b/i.test(message)) facts.explicitAbort = true;
  420. if (/\b429\b/u.test(message) || /rate[_\s-]?limit(?:ed)?/i.test(message))
  421. facts.httpStatus ??= 429;
  422. if (/\b529\b/u.test(message) || /cluster\s+overload/i.test(message)) facts.httpStatus ??= 529;
  423. if (/\b(?:2045|2046|2047|1039|1041)\b/u.test(message)) signals.add('tpm_rate_limit');
  424. if (
  425. LLM_USAGE_LIMIT_UPSTREAM_STATUS_CODE_RE.test(message) ||
  426. /usage[_\s-](?:limit[_\s-])?(?:reached|exceeded|not[_\s-]included)/i.test(message)
  427. )
  428. signals.add('usage_limit');
  429. if (
  430. /\b(?:1400010161|1008)\b/u.test(message) ||
  431. /credits?\s+exhausted|insufficient\s+balance/i.test(message)
  432. )
  433. signals.add('credits_exhausted');
  434. if (
  435. ABORT_MESSAGE_RE.test(message) ||
  436. TRANSIENT_TIMEOUT_MESSAGE_RE.test(message) ||
  437. CHROMIUM_TIMEOUT_MESSAGE_RE.test(message)
  438. )
  439. facts.timeout = true;
  440. if (
  441. CONNECTION_ERROR_MESSAGE_RE.test(message) ||
  442. TRANSIENT_NETWORK_MESSAGE_RE.test(message) ||
  443. CHROMIUM_NETWORK_MESSAGE_RE.test(message)
  444. )
  445. signals.add('network');
  446. if (/\bempty.?response/i.test(message)) signals.add('empty_response');
  447. const hasStructuredError =
  448. facts.existingProtocolCode !== undefined || effectiveHttpStatus(facts) !== undefined;
  449. if (!hasStructuredError && /\b(content.?filter|content.?policy|safety|blocked)\b/i.test(message))
  450. signals.add('content_filter');
  451. }
  452. /**
  453. * Plugin-friendly classifier — accepts a structured triple instead of a
  454. * thrown value. Mirrors the daemon-side `classifyLLMError` minus the
  455. * SDK-instance branches (no `APICallError.isInstance`, no `DOMException`).
  456. *
  457. * Returns `undefined` when there's no signal of an error at all (success
  458. * path); callers stamp `error_reason: ''` in that case so the metric
  459. * label set stays consistent across success / failure paths (the metric
  460. * registry freezes label keys on first observation).
  461. */
  462. export interface FinishStepClassifierInput {
  463. finishReason?: string;
  464. statusCode?: number;
  465. errorMessage?: string;
  466. }
  467. export function classifyFinishStepError(
  468. input: FinishStepClassifierInput,
  469. ): LLMErrorReason | undefined {
  470. const { finishReason, statusCode, errorMessage } = input;
  471. if (finishReason === 'length') return 'length';
  472. if (finishReason === 'content-filter' || finishReason === 'content_filter') {
  473. return 'content_filter';
  474. }
  475. if (typeof statusCode === 'number') {
  476. if (statusCode === 429) return 'rate_limited';
  477. if (statusCode === 401 || statusCode === 403) return 'auth';
  478. if (statusCode === 404) return 'not_found';
  479. if (statusCode >= 400 && statusCode < 500) return 'bad_request';
  480. }
  481. if (errorMessage) {
  482. if (
  483. ABORT_MESSAGE_RE.test(errorMessage) ||
  484. TRANSIENT_TIMEOUT_MESSAGE_RE.test(errorMessage) ||
  485. CHROMIUM_TIMEOUT_MESSAGE_RE.test(errorMessage)
  486. ) {
  487. return 'timeout';
  488. }
  489. if (
  490. CONNECTION_ERROR_MESSAGE_RE.test(errorMessage) ||
  491. TRANSIENT_NETWORK_MESSAGE_RE.test(errorMessage) ||
  492. CHROMIUM_NETWORK_MESSAGE_RE.test(errorMessage)
  493. ) {
  494. return 'network';
  495. }
  496. if (/\bempty.?response/i.test(errorMessage)) return 'empty_response';
  497. if (/\b(content.?filter|content.?policy|safety|blocked)/i.test(errorMessage)) {
  498. return 'content_filter';
  499. }
  500. }
  501. if (typeof statusCode === 'number' && statusCode >= 500) return 'server_error';
  502. if (finishReason === 'error') return 'unknown';
  503. return undefined;
  504. }
  505. /**
  506. * Daemon-side classifier — accepts a raw thrown value (`APICallError`
  507. * instance, `DOMException`, plain `Error`, anything). Falls through to
  508. * `classifyFinishStepError` for the message-pattern branches and the
  509. * statusCode branches when the value carries those fields.
  510. *
  511. * Plugin code should prefer `classifyFinishStepError` directly because the
  512. * SDK has already normalised the shape. Daemon code uses this entry point.
  513. */
  514. export function classifyLLMError(err: unknown): LLMErrorReason {
  515. // DOMException AbortError or Error message-text "timeout/abort" — same
  516. // bucket whether it came from `AbortController.abort()` or a server-side
  517. // 504 with no explicit status.
  518. const isAbort =
  519. (typeof DOMException !== 'undefined' &&
  520. err instanceof DOMException &&
  521. err.name === 'AbortError') ||
  522. (err instanceof Error &&
  523. (ABORT_MESSAGE_RE.test(err.message) ||
  524. TRANSIENT_TIMEOUT_MESSAGE_RE.test(err.message) ||
  525. CHROMIUM_TIMEOUT_MESSAGE_RE.test(err.message)));
  526. if (isAbort) return 'timeout';
  527. // Vercel AI SDK's APICallError carries statusCode but isn't a subclass of
  528. // Error in older versions. Detect via duck-typing on `name === 'APICallError'`
  529. // (or via the SDK's `isInstance` when available — see daemon shim).
  530. const errorCode = extractErrorCode(err);
  531. const errorMessage = extractErrorMessage(err);
  532. const apiStatus = extractAPICallErrorStatus(err);
  533. if (apiStatus !== undefined) {
  534. if (apiStatus === 429) return 'rate_limited';
  535. if (apiStatus === 401 || apiStatus === 403) return 'auth';
  536. if (apiStatus === 404) return 'not_found';
  537. if (apiStatus >= 400 && apiStatus < 500) return 'bad_request';
  538. if (errorCode !== undefined && SAFE_NETWORK_CODES.has(errorCode)) {
  539. return isLLMTransportTimeoutCode(errorCode) ? 'timeout' : 'network';
  540. }
  541. if (errorMessage !== undefined) {
  542. if (isLLMTransportTimeoutSignal(errorMessage)) return 'timeout';
  543. if (isLLMTransportNetworkSignal(errorMessage)) return 'network';
  544. }
  545. if (apiStatus >= 500) return 'server_error';
  546. // statusCode === undefined on APICallError is the SDK's "no response
  547. // came back at all" sentinel — treat as a network error.
  548. }
  549. if (errorCode !== undefined && SAFE_NETWORK_CODES.has(errorCode)) {
  550. return isLLMTransportTimeoutCode(errorCode) ? 'timeout' : 'network';
  551. }
  552. const isAPICallErrorWithoutStatus =
  553. apiStatus === undefined && err instanceof Error && err.name === 'APICallError';
  554. if (isAPICallErrorWithoutStatus) return 'network';
  555. if (
  556. err instanceof TypeError ||
  557. (err instanceof Error &&
  558. (CONNECTION_ERROR_MESSAGE_RE.test(err.message) ||
  559. TRANSIENT_NETWORK_MESSAGE_RE.test(err.message) ||
  560. CHROMIUM_NETWORK_MESSAGE_RE.test(err.message)))
  561. ) {
  562. return 'network';
  563. }
  564. if (
  565. err instanceof Error &&
  566. /\b(content.?filter|content.?policy|safety|blocked)/i.test(err.message)
  567. ) {
  568. return 'content_filter';
  569. }
  570. if (err instanceof Error && /\bempty.?response/i.test(err.message)) {
  571. return 'empty_response';
  572. }
  573. return 'unknown';
  574. }
  575. /**
  576. * Best-effort extraction of `statusCode` from an unknown thrown value. We
  577. * read the field directly so this module stays free of the `ai` package
  578. * dependency (which `@mavis/shared` cannot import — it would pull the
  579. * Vercel AI SDK into the plugin bundle).
  580. */
  581. function extractAPICallErrorStatus(err: unknown): number | undefined {
  582. if (typeof err !== 'object' || err === null) return undefined;
  583. const candidate = err as { statusCode?: unknown; name?: unknown };
  584. if (candidate.name !== 'APICallError') return undefined;
  585. if (typeof candidate.statusCode === 'number') return candidate.statusCode;
  586. return undefined;
  587. }
  588. function extractErrorCode(err: unknown): string | undefined {
  589. if (typeof err !== 'object' || err === null) return undefined;
  590. const candidate = err as { code?: unknown };
  591. return typeof candidate.code === 'string' ? candidate.code : undefined;
  592. }
  593. function extractErrorMessage(err: unknown): string | undefined {
  594. if (err instanceof Error) return err.message;
  595. if (typeof err !== 'object' || err === null) return undefined;
  596. const candidate = err as { message?: unknown };
  597. return typeof candidate.message === 'string' ? candidate.message : undefined;
  598. }
  599. // ────────────────────────────────────────────────────────────────────────────
  600. // LLM error → shared session-status status_code (cloud-runtime wire normalize)
  601. // ────────────────────────────────────────────────────────────────────────────
  602. //
  603. // Complements classifyLLMError's bounded metric labels above: this produces a runtime numeric
  604. // status_code for the wire (BusEvent.errorCode / ProtocolError.code), enabling the frontend's
  605. // typed error messages and status branches.
  606. // Codes 42212 / 50110 / 50150 enter UI ChatStatus.RunOutOfCredit;
  607. // 50111 is short-term request rate limiting and triggers output retry; 50151 displays high cluster load.
  608. //
  609. // These codes are shared wire constants across runtimes. Do not import them back from a host package,
  610. // which would couple cloud-runtime/local-runtime to the local host implementation again.
  611. export const LLM_ERROR_STATUS_CODES = {
  612. /** USAGE_LIMIT_EXCEEDED — quota exhausted / usage limit reached. */
  613. USAGE_LIMIT_EXCEEDED: 42212,
  614. /** LLM_CREDITS_EXHAUSTED — provider reports depleted balance / HTTP 402. */
  615. LLM_CREDITS_EXHAUSTED: 50110,
  616. /** daemon LLM_RATE_LIMITED — HTTP 429 */
  617. LLM_RATE_LIMITED: 50111,
  618. /** daemon LLM_AUTH_ERROR — HTTP 401/403 */
  619. LLM_AUTH_ERROR: 50112,
  620. /** daemon LLM_UPSTREAM_ERROR — generic 4xx/5xx fallback */
  621. LLM_UPSTREAM_ERROR: 50113,
  622. /** daemon LLM_MIGRATION_ERROR — OP migration path failed */
  623. LLM_MIGRATION_ERROR: 50114,
  624. /** daemon LLM_TPM_RATE_LIMITED — provider TPM/RPM short-term throttling */
  625. LLM_TPM_RATE_LIMITED: 50150,
  626. /** LLM_CLUSTER_OVERLOADED — HTTP 529 */
  627. LLM_CLUSTER_OVERLOADED: 50151,
  628. } as const;
  629. export type LLMErrorStatusCode =
  630. (typeof LLM_ERROR_STATUS_CODES)[keyof typeof LLM_ERROR_STATUS_CODES];
  631. // Backward-compatible name for UI typed-match imports.
  632. export const LLM_ERROR_CODES = LLM_ERROR_STATUS_CODES;
  633. export const LLM_TPM_RATE_LIMIT_MESSAGE_CODES = [2045, 2046, 2047, 1039, 1041] as const;
  634. const LLM_TPM_RATE_LIMIT_MESSAGE_CODE_RE = /\b(?:2045|2046|2047|1039|1041)\b/u;
  635. export function isLLMTpmRateLimitMessage(message: string | undefined): boolean {
  636. return message !== undefined && LLM_TPM_RATE_LIMIT_MESSAGE_CODE_RE.test(message);
  637. }
  638. /**
  639. * Map upstream MiniMax / OpenAI-style provider status_code to daemon ErrorCode. Values share the
  640. * source of daemon local-proxy-handler.ts::UPSTREAM_CODE_MAP.
  641. */
  642. export const UPSTREAM_STATUS_CODE_MAP: Record<number, LLMErrorStatusCode> = {
  643. // MiniMax internal status: insufficient balance → 50110.
  644. 1400010161: LLM_ERROR_CODES.LLM_CREDITS_EXHAUSTED,
  645. // MiniMax internal status: usage limit exceeded → 42212.
  646. 2056: LLM_ERROR_CODES.USAGE_LIMIT_EXCEEDED,
  647. // Token Plan limit reached with automatic credit consumption disabled → 42212.
  648. 2067: LLM_ERROR_CODES.USAGE_LIMIT_EXCEEDED,
  649. };
  650. /**
  651. * Extract `{ status_code, errorCode, code, message }` signals from unknown raw values, supporting
  652. * nested envelopes such as `{error: {responseBody: '{"status_code":...}'}}` from Vercel AI SDK /
  653. * DOMException wrappers.
  654. *
  655. * Recursively unwrap three levels through err.responseBody (JSON string) → err.error (nested
  656. * object) → err.data → err.status.
  657. */
  658. export function tryExtractFromPayload(raw: unknown): {
  659. statusCode?: number;
  660. errorCode?: number;
  661. message?: string;
  662. } {
  663. if (typeof raw !== 'object' || raw === null) return {};
  664. const obj = raw as Record<string, unknown>;
  665. const out: { statusCode?: number; errorCode?: number; message?: string } = {};
  666. // ── pass 1: nested envelopes first ──────────────────────────────────────
  667. // Business-level codes (inner upstream `status_code`) MUST take priority
  668. // over transport-level codes (outer HTTP `statusCode`). AI SDK
  669. // APICallError wraps upstream payload as `{statusCode: 500,
  670. // responseBody: '{"status_code": 1400010161, ...}'}` — the inner 1400010161
  671. // is the real cause (MiniMax credit exhausted → 50110), the outer 500 is
  672. // just HTTP transport. We collect nested signals FIRST, then let outer
  673. // fields fill in only what nested didn't provide.
  674. let nested: { statusCode?: number; errorCode?: number; message?: string } = {};
  675. if (typeof obj.responseBody === 'string') {
  676. try {
  677. const inner = JSON.parse(obj.responseBody) as Record<string, unknown>;
  678. const innerExtract = tryExtractFromPayload(inner);
  679. nested = { ...innerExtract };
  680. } catch {
  681. // ignore parse fail
  682. }
  683. }
  684. if (typeof obj.error === 'object' && obj.error !== null) {
  685. const innerExtract = tryExtractFromPayload(obj.error);
  686. nested.statusCode ??= innerExtract.statusCode;
  687. nested.errorCode ??= innerExtract.errorCode;
  688. nested.message ??= innerExtract.message;
  689. }
  690. if (typeof obj.data === 'object' && obj.data !== null) {
  691. const innerExtract = tryExtractFromPayload(obj.data);
  692. nested.statusCode ??= innerExtract.statusCode;
  693. nested.errorCode ??= innerExtract.errorCode;
  694. nested.message ??= innerExtract.message;
  695. }
  696. // `obj.cause` (Error chain root cause via `new Error('...', { cause: orig })`)
  697. // — some SDK wrappers (Vercel AI / Vercel) re-throw the original
  698. // provider Error as `.cause` while putting their own format string in
  699. // `.message`. Recurse so the original typed signal isn't lost.
  700. if (typeof obj.cause === 'object' && obj.cause !== null) {
  701. const innerExtract = tryExtractFromPayload(obj.cause);
  702. nested.statusCode ??= innerExtract.statusCode;
  703. nested.errorCode ??= innerExtract.errorCode;
  704. nested.message ??= innerExtract.message;
  705. }
  706. out.statusCode = nested.statusCode;
  707. out.errorCode = nested.errorCode;
  708. out.message = nested.message;
  709. // ── pass 2: outer fields fill blanks ────────────────────────────────────
  710. if (out.statusCode === undefined && typeof obj.status_code === 'number') {
  711. out.statusCode = obj.status_code;
  712. }
  713. if (out.statusCode === undefined && typeof obj.statusCode === 'number') {
  714. out.statusCode = obj.statusCode;
  715. }
  716. // Messages-compatible SDK `APIError` uses `.status` (number); other SDKs
  717. // use `.statusCode`. Pick whichever appears.
  718. if (out.statusCode === undefined && typeof obj.status === 'number') {
  719. out.statusCode = obj.status;
  720. }
  721. if (out.errorCode === undefined && typeof obj.errorCode === 'number') {
  722. out.errorCode = obj.errorCode;
  723. }
  724. if (out.errorCode === undefined && typeof obj.code === 'number') {
  725. out.errorCode = obj.code;
  726. }
  727. if (!out.message && typeof obj.message === 'string') out.message = obj.message;
  728. if (!out.message && typeof obj.status_message === 'string') out.message = obj.status_message;
  729. if (!out.message && typeof obj.status_msg === 'string') out.message = obj.status_msg;
  730. if (!out.message && typeof obj.error === 'string') out.message = obj.error;
  731. // ── pass 3: message string fallback ──────────────────────────────────────
  732. // Some SDKs throw APIError whose toString() is
  733. // `[Error] <status> <json-body>`, Vercel / Vercel AI re-wrappers, etc.)
  734. // collapse the typed fields into a plain text `message` string before
  735. // throwing. Try to recover the signal from that string when typed fields
  736. // didn't already cover it.
  737. if (typeof obj.message === 'string') {
  738. const fromMsg = extractFromMessageString(obj.message);
  739. out.statusCode ??= fromMsg.statusCode;
  740. out.errorCode ??= fromMsg.errorCode;
  741. // Inner JSON payload may also carry a richer message (e.g. provider
  742. // `error.message: "invalid api key"`); prefer it over the noisy raw
  743. // outer string when available.
  744. if (fromMsg.message) out.message = fromMsg.message;
  745. }
  746. return out;
  747. }
  748. // extractFromMessageString — best-effort parse of a raw error-message
  749. // string for an HTTP status prefix and an embedded JSON body.
  750. //
  751. // Handles shapes seen in real cloud-runtime logs:
  752. //
  753. // `[Error] 401 {"type":"error","error":{"type":"authentication_error",
  754. // "message":"invalid api key"},
  755. // "request_id":"..."}` (Messages-compatible providers)
  756. // `Provider API error (429): rate limited`
  757. // `OpenAI 401: invalid api key`
  758. // `500 Internal Server Error - {"status_code":1400010161,...}`
  759. //
  760. // Returns `{ statusCode?, message? }`:
  761. // - statusCode: first 3-digit HTTP-shaped number in [400, 599] found in
  762. // the prefix segment (before the first `{`). Stops at 599 so random
  763. // numeric content in JSON body doesn't trigger false positives.
  764. // - message: the most specific human-readable message found in the
  765. // embedded JSON (`error.message` → `message` → `error` as string).
  766. function extractFromMessageString(s: string): {
  767. statusCode?: number;
  768. errorCode?: number;
  769. message?: string;
  770. } {
  771. const out: { statusCode?: number; errorCode?: number; message?: string } = {};
  772. if (!s) return out;
  773. // 1. Find the embedded JSON body (first `{` ... last `}`).
  774. const firstBrace = s.indexOf('{');
  775. const lastBrace = s.lastIndexOf('}');
  776. const prefix = firstBrace > 0 ? s.slice(0, firstBrace) : s;
  777. if (firstBrace >= 0 && lastBrace > firstBrace) {
  778. const jsonSlice = s.slice(firstBrace, lastBrace + 1);
  779. try {
  780. const parsed = JSON.parse(jsonSlice) as unknown;
  781. const innerExtract = tryExtractFromPayload(parsed);
  782. if (innerExtract.statusCode !== undefined) out.statusCode = innerExtract.statusCode;
  783. if (innerExtract.errorCode !== undefined) out.errorCode = innerExtract.errorCode;
  784. if (innerExtract.message) out.message = innerExtract.message;
  785. } catch {
  786. // ignore — not JSON
  787. }
  788. }
  789. // 2. If no statusCode from JSON body, grab first 4xx/5xx number in prefix.
  790. if (out.statusCode === undefined) {
  791. const m = prefix.match(/\b([45]\d{2})\b/);
  792. if (m) {
  793. const n = Number(m[1]);
  794. if (Number.isFinite(n) && n >= 400 && n <= 599) {
  795. out.statusCode = n;
  796. }
  797. }
  798. }
  799. return out;
  800. }
  801. /**
  802. * HTTP status → daemon ErrorCode fallback when no typed errorCode or upstream status_code matches.
  803. */
  804. export function mapUpstreamHttpError(httpStatus: number): LLMErrorStatusCode | undefined {
  805. if (httpStatus === 402) return LLM_ERROR_CODES.LLM_CREDITS_EXHAUSTED;
  806. if (httpStatus === 429) return LLM_ERROR_CODES.LLM_RATE_LIMITED;
  807. if (httpStatus === 529) return LLM_ERROR_CODES.LLM_CLUSTER_OVERLOADED;
  808. if (httpStatus === 401 || httpStatus === 403) return LLM_ERROR_CODES.LLM_AUTH_ERROR;
  809. if (httpStatus >= 400) return LLM_ERROR_CODES.LLM_UPSTREAM_ERROR;
  810. return undefined;
  811. }
  812. /**
  813. * Normalize a raw LLM call error into session-status status_code + sanitized message.
  814. *
  815. * Priority:
  816. * 1. Explicit payload errorCode / code (status_code enum).
  817. * 2. Upstream payload status_code matching UPSTREAM_STATUS_CODE_MAP (MiniMax 1400010161 / 2056 /
  818. * 2067).
  819. * 3. Message-only quota/credits signal, e.g. "usage limit exceeded (2056)".
  820. * 4. HTTP 429 + TPM provider message code → LLM_TPM_RATE_LIMITED(50150).
  821. * 5. LLM HTTP timeout signal → LLM_UPSTREAM_ERROR(50113).
  822. * 6. LLM transport network signal → LLM_UPSTREAM_ERROR(50113).
  823. * 7. HTTP status in payload / err.statusCode → mapUpstreamHttpError.
  824. *
  825. * Return null if unrecognized; callers fall back to ProtocolErrorCode.INTERNAL_ERROR.
  826. *
  827. * Prefer sanitized payload text (string_message / message / error text) for message; fall back to
  828. * err.message.
  829. */
  830. export function classifyLLMErrorToCode(
  831. err: unknown,
  832. ): { status_code: LLMErrorStatusCode; message: string } | null {
  833. // Accept plain strings (some callers — notably pi-turn-runner capturing
  834. // `agent.state.errorMessage`) have already collapsed the typed error
  835. // shape into a single line. Wrap into `{message: str}` so the existing
  836. // `pass 3` string-fallback inside `tryExtractFromPayload` (status prefix
  837. // + embedded JSON parse) still fires.
  838. const normalized = typeof err === 'string' ? { message: err } : err;
  839. const extracted = tryExtractFromPayload(normalized);
  840. // 1. typed errorCode
  841. if (extracted.errorCode !== undefined) {
  842. const allowed = new Set<number>(Object.values(LLM_ERROR_CODES));
  843. if (allowed.has(extracted.errorCode)) {
  844. return {
  845. status_code: extracted.errorCode as LLMErrorStatusCode,
  846. message: extracted.message ?? fallbackMessage(err),
  847. };
  848. }
  849. }
  850. // 2. Match upstream status_code.
  851. if (extracted.statusCode !== undefined && UPSTREAM_STATUS_CODE_MAP[extracted.statusCode]) {
  852. return {
  853. status_code: UPSTREAM_STATUS_CODE_MAP[extracted.statusCode]!,
  854. message: extracted.message ?? fallbackMessage(err),
  855. };
  856. }
  857. // 3. Message-only quota fallback. Some SDK/proxy wrappers collapse the
  858. // upstream body into plain text while keeping only a generic HTTP 500 outside.
  859. // Treat the business signal in the text as stronger than the transport status.
  860. const messageOnly = classifyQuotaSignalFromMessage(extracted.message ?? fallbackMessage(err));
  861. if (messageOnly) return messageOnly;
  862. const codeMessage = extracted.message ?? fallbackMessage(err);
  863. const transportCode = extractErrorCode(err);
  864. const httpStatus =
  865. extracted.statusCode ??
  866. (typeof (err as { statusCode?: unknown })?.statusCode === 'number'
  867. ? (err as { statusCode: number }).statusCode
  868. : undefined);
  869. // 4. Provider TPM/rate-window fallback. These 429s are short-term request
  870. // throttles, not quota exhaustion, so they get their own product code.
  871. if (httpStatus === 429 && isLLMTpmRateLimitMessage(codeMessage)) {
  872. return {
  873. status_code: LLM_ERROR_CODES.LLM_TPM_RATE_LIMITED,
  874. message: codeMessage,
  875. };
  876. }
  877. // 5. Structured business HTTP statuses remain stronger than transport text.
  878. // A misleading wrapper message such as "timed out" must not turn auth,
  879. // quota, rate-limit, not-found, or the explicit 529 overload response into
  880. // a generic transient capacity error. 5xx statuses are intentionally left
  881. // for the transport checks below because a 5xx wrapper may represent a
  882. // connection failure with no usable upstream response.
  883. if (httpStatus !== undefined && (httpStatus < 500 || httpStatus === 529)) {
  884. const mapped = mapUpstreamHttpError(httpStatus);
  885. if (mapped !== undefined) {
  886. return { status_code: mapped, message: extracted.message ?? fallbackMessage(err) };
  887. }
  888. }
  889. // 6. LLM HTTP timeout fallback. A transport deadline does not prove that
  890. // the provider returned an explicit cluster-overload response.
  891. const timeoutMessage = codeMessage;
  892. if (isLLMHttpTimeoutSignal(err, timeoutMessage)) {
  893. return {
  894. status_code: LLM_ERROR_CODES.LLM_UPSTREAM_ERROR,
  895. message: timeoutMessage,
  896. };
  897. }
  898. // 7. Remaining HTTP status fallback (normally generic 5xx).
  899. if (httpStatus !== undefined) {
  900. const mapped = mapUpstreamHttpError(httpStatus);
  901. if (mapped !== undefined) {
  902. return { status_code: mapped, message: extracted.message ?? fallbackMessage(err) };
  903. }
  904. }
  905. // 8. LLM transport network fallback. No dedicated daemon wire code exists for
  906. // network, so use the generic upstream code while preserving the raw detail.
  907. const networkMessage = codeMessage;
  908. if (isLLMTransportNetworkSignal(networkMessage) || isLLMTransportNetworkCode(transportCode)) {
  909. return {
  910. status_code: LLM_ERROR_CODES.LLM_UPSTREAM_ERROR,
  911. message: networkMessage,
  912. };
  913. }
  914. return null;
  915. }
  916. function isLLMHttpTimeoutSignal(err: unknown, message: string): boolean {
  917. if (
  918. /\b(timed?\s*out|timeout|ETIMEDOUT|ESOCKETTIMEDOUT|ECONNABORTED|UND_ERR_(?:CONNECT|HEADERS|BODY)_TIMEOUT)\b/i.test(
  919. message,
  920. )
  921. ) {
  922. return true;
  923. }
  924. if (typeof err !== 'object' || err === null) return false;
  925. const candidate = err as { name?: unknown; code?: unknown };
  926. return (
  927. (typeof candidate.name === 'string' &&
  928. /\b(?:TimeoutError|ConnectTimeoutError|HeadersTimeoutError|BodyTimeoutError)\b/i.test(
  929. candidate.name,
  930. )) ||
  931. (typeof candidate.code === 'string' && isLLMTransportTimeoutCode(candidate.code))
  932. );
  933. }
  934. function isLLMTransportTimeoutCode(code: string): boolean {
  935. return /\b(?:ETIMEDOUT|ESOCKETTIMEDOUT|ECONNABORTED|ERR_(?:CONNECTION_)?TIMED_OUT|UND_ERR_(?:CONNECT|HEADERS|BODY)_TIMEOUT)\b/u.test(
  936. code,
  937. );
  938. }
  939. function isLLMTransportTimeoutSignal(message: string): boolean {
  940. return TRANSIENT_TIMEOUT_MESSAGE_RE.test(message) || CHROMIUM_TIMEOUT_MESSAGE_RE.test(message);
  941. }
  942. function isLLMTransportNetworkSignal(message: string): boolean {
  943. return (
  944. CONNECTION_ERROR_MESSAGE_RE.test(message) ||
  945. CHROMIUM_NETWORK_MESSAGE_RE.test(message) ||
  946. SAFE_TRANSPORT_NETWORK_MESSAGE_RE.test(message)
  947. );
  948. }
  949. function isLLMTransportNetworkCode(code: string | undefined): boolean {
  950. return code !== undefined && SAFE_NETWORK_CODES.has(code) && !isLLMTransportTimeoutCode(code);
  951. }
  952. function classifyQuotaSignalFromMessage(
  953. message: string,
  954. ): { status_code: LLMErrorStatusCode; message: string } | null {
  955. if (
  956. /\b(?:1400010161|1008)\b/u.test(message) ||
  957. /credits?\s+exhausted/i.test(message) ||
  958. /insufficient\s+balance/i.test(message)
  959. ) {
  960. return { status_code: LLM_ERROR_CODES.LLM_CREDITS_EXHAUSTED, message };
  961. }
  962. if (
  963. LLM_USAGE_LIMIT_UPSTREAM_STATUS_CODE_RE.test(message) ||
  964. /usage\s+limit\s+exceeded/i.test(message) ||
  965. /package\s+quota\s+has\s+reached(?:\s+its)?\s+limit/i.test(message)
  966. ) {
  967. return { status_code: LLM_ERROR_CODES.USAGE_LIMIT_EXCEEDED, message };
  968. }
  969. if (/\bhibernation\b/i.test(message)) {
  970. return { status_code: LLM_ERROR_CODES.LLM_CREDITS_EXHAUSTED, message };
  971. }
  972. if (/requests?\s+(?:are\s+)?too\s+frequent/i.test(message)) {
  973. return { status_code: LLM_ERROR_CODES.LLM_RATE_LIMITED, message };
  974. }
  975. return null;
  976. }
  977. function fallbackMessage(err: unknown): string {
  978. if (err instanceof Error) return err.message;
  979. if (typeof err === 'string') return err;
  980. return 'LLM call failed';
  981. }