@bastani/atomic-ai 0.10.2-alpha.1 → 0.10.3-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +34 -2
  2. package/dist/api/anthropic-messages.d.ts.map +1 -1
  3. package/dist/api/anthropic-messages.js +92 -16
  4. package/dist/api/anthropic-messages.js.map +1 -1
  5. package/dist/api/azure-openai-responses.d.ts.map +1 -1
  6. package/dist/api/azure-openai-responses.js +3 -1
  7. package/dist/api/azure-openai-responses.js.map +1 -1
  8. package/dist/api/bedrock-converse-stream.d.ts.map +1 -1
  9. package/dist/api/bedrock-converse-stream.js +60 -9
  10. package/dist/api/bedrock-converse-stream.js.map +1 -1
  11. package/dist/api/google-generative-ai.d.ts.map +1 -1
  12. package/dist/api/google-generative-ai.js +3 -1
  13. package/dist/api/google-generative-ai.js.map +1 -1
  14. package/dist/api/google-vertex.d.ts.map +1 -1
  15. package/dist/api/google-vertex.js +3 -1
  16. package/dist/api/google-vertex.js.map +1 -1
  17. package/dist/api/mistral-conversations.d.ts.map +1 -1
  18. package/dist/api/mistral-conversations.js +3 -1
  19. package/dist/api/mistral-conversations.js.map +1 -1
  20. package/dist/api/openai-codex-responses.d.ts.map +1 -1
  21. package/dist/api/openai-codex-responses.js +41 -8
  22. package/dist/api/openai-codex-responses.js.map +1 -1
  23. package/dist/api/openai-completions.d.ts.map +1 -1
  24. package/dist/api/openai-completions.js +78 -14
  25. package/dist/api/openai-completions.js.map +1 -1
  26. package/dist/api/openai-responses.d.ts.map +1 -1
  27. package/dist/api/openai-responses.js +3 -1
  28. package/dist/api/openai-responses.js.map +1 -1
  29. package/dist/api/pi-messages.d.ts.map +1 -1
  30. package/dist/api/pi-messages.js +3 -1
  31. package/dist/api/pi-messages.js.map +1 -1
  32. package/dist/api/simple-options.d.ts +12 -0
  33. package/dist/api/simple-options.d.ts.map +1 -1
  34. package/dist/api/simple-options.js +52 -3
  35. package/dist/api/simple-options.js.map +1 -1
  36. package/dist/api/strict-tool-limits.d.ts +15 -6
  37. package/dist/api/strict-tool-limits.d.ts.map +1 -1
  38. package/dist/api/strict-tool-limits.js +21 -7
  39. package/dist/api/strict-tool-limits.js.map +1 -1
  40. package/dist/index.d.ts +2 -1
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +2 -1
  43. package/dist/index.js.map +1 -1
  44. package/dist/providers/data/.manifest.json +1 -1
  45. package/dist/providers/data/openrouter.json +1 -1
  46. package/dist/providers/data/vercel-ai-gateway.json +1 -1
  47. package/dist/types.d.ts +6 -0
  48. package/dist/types.d.ts.map +1 -1
  49. package/dist/types.js.map +1 -1
  50. package/dist/utils/estimate.d.ts +1 -0
  51. package/dist/utils/estimate.d.ts.map +1 -1
  52. package/dist/utils/estimate.js +1 -1
  53. package/dist/utils/estimate.js.map +1 -1
  54. package/dist/utils/provider-retry.d.ts.map +1 -1
  55. package/dist/utils/provider-retry.js +4 -0
  56. package/dist/utils/provider-retry.js.map +1 -1
  57. package/dist/utils/retry.d.ts +2 -1
  58. package/dist/utils/retry.d.ts.map +1 -1
  59. package/dist/utils/retry.js +6 -1
  60. package/dist/utils/retry.js.map +1 -1
  61. package/dist/utils/tls-certificate.d.ts +75 -0
  62. package/dist/utils/tls-certificate.d.ts.map +1 -0
  63. package/dist/utils/tls-certificate.js +343 -0
  64. package/dist/utils/tls-certificate.js.map +1 -0
  65. package/dist/utils/transcript.d.ts +8 -1
  66. package/dist/utils/transcript.d.ts.map +1 -1
  67. package/dist/utils/transcript.js +82 -7
  68. package/dist/utils/transcript.js.map +1 -1
  69. package/dist/utils/version.d.ts +1 -1
  70. package/dist/utils/version.js +1 -1
  71. package/dist/utils/version.js.map +1 -1
  72. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CA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;IAC9D,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY;QAAE,OAAO,KAAK,CAAC;IAC1E,MAAM,YAAY,GAAG,qBAAqB,CAAC,OAAO,CAAC,CAAC;IACpD,IAAI,YAAY,KAAK,SAAS;QAAE,OAAO,YAAY,CAAC,SAAS,CAAC;IAC9D,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAC1C,IAAI,0CAA0C,CAAC,IAAI,CAAC,YAAY,CAAC;QAAE,OAAO,KAAK,CAAC;IAChF,OAAO,gCAAgC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["import { getGitHubCopilotError } from \"../providers/github-copilot-errors.ts\";\nimport type { AssistantMessage, RetryDeadline } from \"../types.ts\";\nimport { DEFAULT_MAX_RETRY_DELAY_MS } from \"./provider-retry.ts\";\nimport { retryDeadlineReached } from \"./retry-sleep.ts\";\n\nfunction buildProviderErrorPattern(patterns: readonly string[]): RegExp {\n\treturn new RegExp(patterns.join(\"|\"), \"i\");\n}\n\nconst NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN = buildProviderErrorPattern([\n\t// OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's\n\t// Zen API. These are subscription/account limits, not transient throttles.\n\t\"GoUsageLimitError\",\n\t\"FreeUsageLimitError\",\n\n\t// OpenCode Go subscription-limit text asks users to enable available-balance\n\t// usage after rolling/weekly/monthly limits are reached.\n\t\"Monthly usage limit reached\",\n\t\"available balance\",\n\n\t// Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's\n\t// quota/billing error code; the other strings cover common gateway wording.\n\t\"insufficient_quota\",\n\t\"out of budget\",\n\t\"quota exceeded\",\n\t\"billing\",\n\t\"subscription_sharing_usage_limit_exceeded\",\n\t// Sign in with ChatGPT on a ChatGPT Business plan: a usage limit set by the\n\t// workspace admin. Only the admin can raise it.\n\t\"subscription_sharing_workplace_individual_usage_limit_exceeded\",\n\n\t// Zhipu/Z.ai (open.bigmodel.cn) error code 1308: the plan's usage limit is\n\t// reached, sent as HTTP 429. It resets after hours, not seconds (#11537).\n\t'\"code\"\\\\s*:\\\\s*\"?1308(?![0-9])',\n]);\n\nconst RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// Generic provider load, HTTP status, and server-side transient failures.\n\t\"overloaded\",\n\t\"server_busy\",\n\t\"servers are currently busy\",\n\t\"currently experiencing high demand\",\n\t\"model is at capacity\",\n\t\"rate.?limit\",\n\t\"too many requests\",\n\t// Status codes must not be part of a longer word or number, e.g. a request id or byte count (#11057).\n\t// 521-523 are Cloudflare origin errors (#3623); 529 is an overload response.\n\t\"(?<![a-z0-9])(?:429|500|502|503|504|52[0-4]|529)(?![a-z0-9])\",\n\t// Also matches \"The service is temporarily unavailable\" (#10965).\n\t\"service.?(?:is.?)?(?:temporarily.?)?unavailable\",\n\t\"server.?error\",\n\t\"internal.?error\",\n\n\t// Wrapper/provider text for transient upstream failures, including OpenRouter\n\t// \"Provider returned error\" responses (#2264).\n\t\"provider.?returned.?(?:an.?)?error\",\n\t\"exceeded request buffer limit while retrying upstream\",\n\t\"unable to forward upstream\",\n\t\"upstream.?request.?failed\",\n\t\"upstream_stream_read_error\",\n\t\"stream was interrupted\",\n\t\"http/?2 stream failed\",\n\n\t// Network, proxy, and fetch transport failures. This includes OpenAI Codex\n\t// raw-fetch failures such as \"upstream connect\", \"connection refused\", and\n\t// \"reset before headers\" (#733), plus OpenRouter connection drops (#3317).\n\t\"network.?error\",\n\t\"connection.?error\",\n\t\"connection.?refused\",\n\t\"connection.?lost\",\n\t\"connection.?closed\",\n\t\"(?<![a-z0-9_])(?:ECONNRESET|ECONNABORTED|ECONNREFUSED|ETIMEDOUT|EPIPE)(?![a-z0-9_])\",\n\t\"connection reset by peer\",\n\t\"connection.?reset\",\n\t\"other side closed\",\n\t\"fetch failed\",\n\t\"request to \\\\S+ failed, reason:\",\n\t\"getaddrinfo\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"upstream.?connect\",\n\t\"reset before headers\",\n\t\"socket hang up\",\n\t\"socket connection was closed\",\n\t\"timed? out\",\n\t\"timeout\",\n\t\"terminated\",\n\n\t// WebSocket transports can report close/error text instead of HTTP/fetch text.\n\t\"websocket.?closed\",\n\t\"websocket.?error\",\n\n\t// Response-body decompression failures. Node/Bun zlib rejects a body whose\n\t// Content-Encoding lied or whose compressed bytes were corrupted, and the\n\t// fetch/WebSocket layer wraps it with a \"Library error:\" prefix. GitHub\n\t// Copilot on the default `transport: \"auto\"` reports this as\n\t// \"Library error: zlib error: incorrect header check\" (#2553). The transfer\n\t// is already unusable, and a fresh attempt normally succeeds, so treat every\n\t// variant as a transient transport failure rather than a deterministic error.\n\t\"zlib\",\n\t\"incorrect header check\",\n\t\"decompress\",\n\t\"library error\",\n\n\t// Idle-stream deadline enforced below the HTTP layer by `withStreamDeadline`\n\t// so a stream that never settles cannot hang an attempt forever (#2553).\n\t\"stream deadline exceeded\",\n\n\t// Premature stream endings from SDKs and transports. Anthropic can throw\n\t// \"stream ended without ...\" and \"Anthropic stream ended before message_stop\"\n\t// (#4433); Bedrock/Smithy can throw an HTTP/2 no-response error (#3594).\n\t\"ended without\",\n\t\"stream ended before message_stop\",\n\t\"stream ended before a terminal response event\",\n\t\"http2 request did not get a response\",\n\t// Codex CLI mid-stream disconnect, relayed by proxies that wrap the Codex CLI,\n\t// e.g. \"stream disconnected before completion: stream closed before response.completed\" (#11057).\n\t\"stream disconnected before completion\",\n\t// Magpie gateway relaying a dropped upstream Anthropic stream, e.g.\n\t// \"Claude Code's stream from Anthropic was cut short after the reply had begun\" (#11879).\n\t\"cut short after the reply had begun\",\n\t\"pending stream has been canceled\",\n\n\t// Provider-requested retry delay cap failures should flow through the outer\n\t// retry policy so callers can surface/abort the backoff (#1123).\n\t\"retry delay\",\n\n\t// Explicit retry guidance emitted mid-stream by OpenAI Responses and Bedrock\n\t// stream exceptions (#6019).\n\t\"you can retry your request\",\n\t\"try your request again\",\n\t\"please retry your request\",\n\n\t// gRPC based providers (e.g. NVIDIA NIM)\n\t\"ResourceExhausted\",\n\t\"subscription_sharing_usage_unavailable\",\n\t\"subscription_sharing_user_unavailable\",\n]);\n\n/**\n * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).\n * Each delay is capped by `maxAgentDelayMs` (60 seconds by default).\n * Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`) in coding-agent; kept\n * here so the classifier and the policy-driven retry loop live together and stay reusable\n * by the SDK and other callers.\n */\nexport interface RetryPolicy {\n\tenabled: boolean;\n\t/** Max retry attempts (0 = no retries). The initial call never counts as a retry. */\n\tmaxRetries: number;\n\t/** Base delay in ms. Per-attempt delay is `baseDelayMs * 2^(attempt-1)` before jitter. */\n\tbaseDelayMs: number;\n\t/** Cap for agent-level retry delays in ms. Defaults to 60 seconds. */\n\tmaxAgentDelayMs?: number;\n\t/**\n\t * Cap for a server retry hint (`Retry-After-Ms`, `Retry-After`, a body `retry_after`).\n\t * Defaults to 60 seconds; 0 caps the hint by `maxAgentDelayMs` instead.\n\t */\n\tmaxRetryDelayMs?: number;\n}\n\nexport const DEFAULT_MAX_AGENT_RETRY_DELAY_MS = 60_000;\n\nexport function retryDelayMs(policy: Pick<RetryPolicy, \"baseDelayMs\" | \"maxAgentDelayMs\">, attempt: number): number {\n\tconst delay = policy.baseDelayMs * 2 ** Math.max(0, attempt - 1);\n\tconst safeDelay = Number.isSafeInteger(delay) ? delay : Number.MAX_SAFE_INTEGER;\n\treturn Math.min(safeDelay, policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS);\n}\n\ntype RetryFailure = Pick<AssistantMessage, \"stopReason\" | \"errorMessage\" | \"retryAfterMs\" | \"diagnostics\">;\n\n/**\n * Wait before retry `attempt` (1-indexed): the server retry hint when the failure\n * carries one, capped by `maxRetryDelayMs`, otherwise the exponential backoff.\n */\nexport function failureRetryDelayMs(\n\tpolicy: Pick<RetryPolicy, \"baseDelayMs\" | \"maxAgentDelayMs\" | \"maxRetryDelayMs\">,\n\tattempt: number,\n\tfailure: Pick<AssistantMessage, \"retryAfterMs\">,\n): number {\n\tconst hintMs = failure.retryAfterMs;\n\tif (hintMs === undefined || !Number.isFinite(hintMs) || hintMs <= 0) return retryDelayMs(policy, attempt);\n\tconst maxRetryDelayMs = policy.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;\n\tconst capMs = maxRetryDelayMs || (policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS);\n\treturn Math.min(hintMs, capMs);\n}\n\n/**\n * Delay before retry `attempt` (1-indexed) of a failed assistant call, or `undefined`\n * when it is not retryable or `maxRetries` is spent.\n */\nexport function assistantRetryDelayMs(policy: RetryPolicy, attempt: number, message: RetryFailure): number | undefined {\n\tif (!policy.enabled || attempt > policy.maxRetries || !isRetryableAssistantError(message)) return undefined;\n\treturn failureRetryDelayMs(policy, attempt, message);\n}\n\n/** Optional callbacks emitted by {@link retryAssistantCall} around each retry. */\nexport interface RetryCallbacks {\n\t/** Emitted before the backoff sleep of each retry attempt (1-indexed). */\n\tonRetryScheduled?: (\n\t\tattempt: number,\n\t\tmaxAttempts: number,\n\t\tdelayMs: number,\n\t\terrorMessage: string,\n\t) => void | Promise<void>;\n\t/** Emitted after the backoff sleep, immediately before the retried call starts. */\n\tonRetryAttemptStart?: () => void | Promise<void>;\n\t/** Emitted once when the loop ends: success if a later call completed normally. */\n\tonRetryFinished?: (success: boolean, attempt: number, finalError?: string) => void | Promise<void>;\n}\n\nexport interface RetryCallOptions extends RetryCallbacks {\n\t/** Do not start a retry at or after this performance.now() timestamp. Does not cancel a running call. */\n\tretryDeadline?: RetryDeadline;\n}\n\nclass RetrySleepAbortError extends Error {\n\tconstructor() {\n\t\tsuper(\"Aborted\");\n\t}\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new RetrySleepAbortError());\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\treject(new RetrySleepAbortError());\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\n/**\n * Run a single assistant-producing call with bounded retry on transient errors.\n *\n * Behavior:\n * - A successful response is returned immediately. Aborts are terminal and never\n * retried, but reported as unsuccessful if they happen after a retry was scheduled.\n * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`\n * too, so callers do not need to care when cancellation happened.\n * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/\n * billing exhaustion) is returned immediately so deterministic errors fail fast.\n * - Otherwise retries up to `maxRetries` times, waiting for the server retry hint or\n * the exponential backoff (see {@link assistantRetryDelayMs}), emitting\n * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before\n * the retried call starts, and `onRetryFinished` once at the end (whether the loop\n * ends in success, exhausted retries, or an aborted backoff).\n *\n * When `policy` is undefined or disabled, the first response is returned unchanged\n * (equivalent to calling `produce()` directly).\n */\nexport async function retryAssistantCall(\n\tproduce: () => Promise<AssistantMessage>,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallOptions,\n): Promise<AssistantMessage> {\n\tconst maxAttempts = policy?.enabled ? policy.maxRetries : 0;\n\n\tlet attempt = 0;\n\tlet lastRetry: { attempt: number; errorMessage: string } | undefined;\n\tfor (;;) {\n\t\tconst response = await produce();\n\n\t\t// Abort: terminal but not successful. Never retry an aborted message.\n\t\tif (response.stopReason === \"aborted\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Success: non-error, non-abort responses return as-is.\n\t\tif (response.stopReason !== \"error\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Non-retryable, or budget exhausted: return the final error message.\n\t\tconst delayMs = policy ? assistantRetryDelayMs(policy, attempt + 1, response) : undefined;\n\t\tif (delayMs === undefined) {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt, response.errorMessage);\n\t\t\treturn response;\n\t\t}\n\n\t\tattempt++;\n\t\tlastRetry = { attempt, errorMessage: response.errorMessage || \"Unknown error\" };\n\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t// Normalize aborts during retry backoff to the same AssistantMessage shape as\n\t\t// provider stream aborts, so callers do not need to care when cancellation happened.\n\t\ttry {\n\t\t\tawait sleep(delayMs, signal);\n\t\t} catch (error) {\n\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\tif (error instanceof RetrySleepAbortError) {\n\t\t\t\treturn { ...response, stopReason: \"aborted\", errorMessage: undefined };\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tif (!retryDeadlineReached(callbacks?.retryDeadline)) {\n\t\t\tawait callbacks?.onRetryAttemptStart?.();\n\t\t\t// The callback can itself wait past the deadline.\n\t\t\tif (!retryDeadlineReached(callbacks?.retryDeadline)) continue;\n\t\t}\n\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\treturn { ...response, stopReason: \"aborted\", errorMessage: undefined };\n\t}\n}\n\n/**\n * Classifies whether a failed assistant message looks like a transient provider\n * or transport error, so callers can decide if the last assistant turn should be\n * restarted.\n *\n * A GitHub Copilot failure carries its typed error, whose `retryable` decides.\n *\n * This does not implement retry policy. Callers should first handle context\n * overflow separately, then apply their own retry budget, backoff, and reporting\n * before restarting the assistant turn.\n */\nexport function isRetryableAssistantError(message: RetryFailure): boolean {\n\tif (message.stopReason !== \"error\" || !message.errorMessage) return false;\n\tconst copilotError = getGitHubCopilotError(message);\n\tif (copilotError !== undefined) return copilotError.retryable;\n\tconst errorMessage = message.errorMessage;\n\tif (NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage)) return false;\n\treturn RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage);\n}\n"]}
1
+ {"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAE9E,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAEhE,SAAS,yBAAyB,CAAC,QAA2B;IAC7D,OAAO,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,0CAA0C,GAAG,yBAAyB,CAAC;IAC5E,8EAA8E;IAC9E,2EAA2E;IAC3E,mBAAmB;IACnB,qBAAqB;IAErB,6EAA6E;IAC7E,yDAAyD;IACzD,6BAA6B;IAC7B,mBAAmB;IAEnB,4EAA4E;IAC5E,4EAA4E;IAC5E,oBAAoB;IACpB,eAAe;IACf,gBAAgB;IAChB,SAAS;IACT,2CAA2C;IAC3C,4EAA4E;IAC5E,gDAAgD;IAChD,gEAAgE;IAEhE,2EAA2E;IAC3E,0EAA0E;IAC1E,gCAAgC;CAChC,CAAC,CAAC;AAEH,MAAM,gCAAgC,GAAG,yBAAyB,CAAC;IAClE,0EAA0E;IAC1E,YAAY;IACZ,aAAa;IACb,4BAA4B;IAC5B,oCAAoC;IACpC,sBAAsB;IACtB,aAAa;IACb,mBAAmB;IACnB,sGAAsG;IACtG,6EAA6E;IAC7E,8DAA8D;IAC9D,kEAAkE;IAClE,iDAA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BAAmB,EAAE,EAAE,CAAC;YACzC,kDAAkD;YAClD,IAAI,CAAC,oBAAoB,CAAC,SAAS,EAAE,aAAa,CAAC;gBAAE,SAAS;QAC/D,CAAC;QACD,MAAM,SAAS,EAAE,eAAe,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,SAAS,CAAC,YAAY,CAAC,CAAC;QAC3E,OAAO,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,SAAS,EAAE,CAAC;IACxE,CAAC;AACF,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAqB;IAC9D,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY;QAAE,OAAO,KAAK,CAAC;IAC1E,oFAAoF;IACpF,IAAI,wBAAwB,CAAC,OAAO,CAAC,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC;IAClE,MAAM,YAAY,GAAG,qBAAqB,CAAC,OAAO,CAAC,CAAC;IACpD,IAAI,YAAY,KAAK,SAAS;QAAE,OAAO,YAAY,CAAC,SAAS,CAAC;IAC9D,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAC1C,IAAI,0CAA0C,CAAC,IAAI,CAAC,YAAY,CAAC;QAAE,OAAO,KAAK,CAAC;IAChF,OAAO,gCAAgC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["import { getGitHubCopilotError } from \"../providers/github-copilot-errors.ts\";\nimport type { AssistantMessage, RetryDeadline } from \"../types.ts\";\nimport { DEFAULT_MAX_RETRY_DELAY_MS } from \"./provider-retry.ts\";\nimport { retryDeadlineReached } from \"./retry-sleep.ts\";\nimport { getTlsCertificateRefusal } from \"./tls-certificate.ts\";\n\nfunction buildProviderErrorPattern(patterns: readonly string[]): RegExp {\n\treturn new RegExp(patterns.join(\"|\"), \"i\");\n}\n\nconst NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN = buildProviderErrorPattern([\n\t// OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's\n\t// Zen API. These are subscription/account limits, not transient throttles.\n\t\"GoUsageLimitError\",\n\t\"FreeUsageLimitError\",\n\n\t// OpenCode Go subscription-limit text asks users to enable available-balance\n\t// usage after rolling/weekly/monthly limits are reached.\n\t\"Monthly usage limit reached\",\n\t\"available balance\",\n\n\t// Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's\n\t// quota/billing error code; the other strings cover common gateway wording.\n\t\"insufficient_quota\",\n\t\"out of budget\",\n\t\"quota exceeded\",\n\t\"billing\",\n\t\"subscription_sharing_usage_limit_exceeded\",\n\t// Sign in with ChatGPT on a ChatGPT Business plan: a usage limit set by the\n\t// workspace admin. Only the admin can raise it.\n\t\"subscription_sharing_workplace_individual_usage_limit_exceeded\",\n\n\t// Zhipu/Z.ai (open.bigmodel.cn) error code 1308: the plan's usage limit is\n\t// reached, sent as HTTP 429. It resets after hours, not seconds (#11537).\n\t'\"code\"\\\\s*:\\\\s*\"?1308(?![0-9])',\n]);\n\nconst RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// Generic provider load, HTTP status, and server-side transient failures.\n\t\"overloaded\",\n\t\"server_busy\",\n\t\"servers are currently busy\",\n\t\"currently experiencing high demand\",\n\t\"model is at capacity\",\n\t\"rate.?limit\",\n\t\"too many requests\",\n\t// Status codes must not be part of a longer word or number, e.g. a request id or byte count (#11057).\n\t// 521-523 are Cloudflare origin errors (#3623); 529 is an overload response.\n\t\"(?<![a-z0-9])(?:429|500|502|503|504|52[0-4]|529)(?![a-z0-9])\",\n\t// Also matches \"The service is temporarily unavailable\" (#10965).\n\t\"service.?(?:is.?)?(?:temporarily.?)?unavailable\",\n\t\"server.?error\",\n\t\"internal.?error\",\n\n\t// Wrapper/provider text for transient upstream failures, including OpenRouter\n\t// \"Provider returned error\" responses (#2264).\n\t\"provider.?returned.?(?:an.?)?error\",\n\t\"exceeded request buffer limit while retrying upstream\",\n\t\"unable to forward upstream\",\n\t\"upstream.?request.?failed\",\n\t\"upstream_stream_read_error\",\n\t\"stream was interrupted\",\n\t\"http/?2 stream failed\",\n\n\t// Network, proxy, and fetch transport failures. This includes OpenAI Codex\n\t// raw-fetch failures such as \"upstream connect\", \"connection refused\", and\n\t// \"reset before headers\" (#733), plus OpenRouter connection drops (#3317).\n\t\"network.?error\",\n\t\"connection.?error\",\n\t\"connection.?refused\",\n\t\"connection.?lost\",\n\t\"connection.?closed\",\n\t\"(?<![a-z0-9_])(?:ECONNRESET|ECONNABORTED|ECONNREFUSED|ETIMEDOUT|EPIPE)(?![a-z0-9_])\",\n\t\"connection reset by peer\",\n\t\"connection.?reset\",\n\t\"other side closed\",\n\t\"fetch failed\",\n\t\"request to \\\\S+ failed, reason:\",\n\t\"getaddrinfo\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"upstream.?connect\",\n\t\"reset before headers\",\n\t\"socket hang up\",\n\t\"socket connection was closed\",\n\t\"timed? out\",\n\t\"timeout\",\n\t\"terminated\",\n\n\t// WebSocket transports can report close/error text instead of HTTP/fetch text.\n\t\"websocket.?closed\",\n\t\"websocket.?error\",\n\n\t// Response-body decompression failures. Node/Bun zlib rejects a body whose\n\t// Content-Encoding lied or whose compressed bytes were corrupted, and the\n\t// fetch/WebSocket layer wraps it with a \"Library error:\" prefix. GitHub\n\t// Copilot on the default `transport: \"auto\"` reports this as\n\t// \"Library error: zlib error: incorrect header check\" (#2553). The transfer\n\t// is already unusable, and a fresh attempt normally succeeds, so treat every\n\t// variant as a transient transport failure rather than a deterministic error.\n\t\"zlib\",\n\t\"incorrect header check\",\n\t\"decompress\",\n\t\"library error\",\n\n\t// Idle-stream deadline enforced below the HTTP layer by `withStreamDeadline`\n\t// so a stream that never settles cannot hang an attempt forever (#2553).\n\t\"stream deadline exceeded\",\n\n\t// Premature stream endings from SDKs and transports. Anthropic can throw\n\t// \"stream ended without ...\" and \"Anthropic stream ended before message_stop\"\n\t// (#4433); Bedrock/Smithy can throw an HTTP/2 no-response error (#3594).\n\t\"ended without\",\n\t\"stream ended before message_stop\",\n\t\"stream ended before a terminal response event\",\n\t\"http2 request did not get a response\",\n\t// Codex CLI mid-stream disconnect, relayed by proxies that wrap the Codex CLI,\n\t// e.g. \"stream disconnected before completion: stream closed before response.completed\" (#11057).\n\t\"stream disconnected before completion\",\n\t// Magpie gateway relaying a dropped upstream Anthropic stream, e.g.\n\t// \"Claude Code's stream from Anthropic was cut short after the reply had begun\" (#11879).\n\t\"cut short after the reply had begun\",\n\t\"pending stream has been canceled\",\n\n\t// Provider-requested retry delay cap failures should flow through the outer\n\t// retry policy so callers can surface/abort the backoff (#1123).\n\t\"retry delay\",\n\n\t// Explicit retry guidance emitted mid-stream by OpenAI Responses and Bedrock\n\t// stream exceptions (#6019).\n\t\"you can retry your request\",\n\t\"try your request again\",\n\t\"please retry your request\",\n\n\t// gRPC based providers (e.g. NVIDIA NIM)\n\t\"ResourceExhausted\",\n\t\"subscription_sharing_usage_unavailable\",\n\t\"subscription_sharing_user_unavailable\",\n]);\n\n/**\n * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).\n * Each delay is capped by `maxAgentDelayMs` (60 seconds by default).\n * Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`) in coding-agent; kept\n * here so the classifier and the policy-driven retry loop live together and stay reusable\n * by the SDK and other callers.\n */\nexport interface RetryPolicy {\n\tenabled: boolean;\n\t/** Max retry attempts (0 = no retries). The initial call never counts as a retry. */\n\tmaxRetries: number;\n\t/** Base delay in ms. Per-attempt delay is `baseDelayMs * 2^(attempt-1)` before jitter. */\n\tbaseDelayMs: number;\n\t/** Cap for agent-level retry delays in ms. Defaults to 60 seconds. */\n\tmaxAgentDelayMs?: number;\n\t/**\n\t * Cap for a server retry hint (`Retry-After-Ms`, `Retry-After`, a body `retry_after`).\n\t * Defaults to 60 seconds; 0 caps the hint by `maxAgentDelayMs` instead.\n\t */\n\tmaxRetryDelayMs?: number;\n}\n\nexport const DEFAULT_MAX_AGENT_RETRY_DELAY_MS = 60_000;\n\nexport function retryDelayMs(policy: Pick<RetryPolicy, \"baseDelayMs\" | \"maxAgentDelayMs\">, attempt: number): number {\n\tconst delay = policy.baseDelayMs * 2 ** Math.max(0, attempt - 1);\n\tconst safeDelay = Number.isSafeInteger(delay) ? delay : Number.MAX_SAFE_INTEGER;\n\treturn Math.min(safeDelay, policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS);\n}\n\ntype RetryFailure = Pick<AssistantMessage, \"stopReason\" | \"errorMessage\" | \"retryAfterMs\" | \"diagnostics\">;\n\n/**\n * Wait before retry `attempt` (1-indexed): the server retry hint when the failure\n * carries one, capped by `maxRetryDelayMs`, otherwise the exponential backoff.\n */\nexport function failureRetryDelayMs(\n\tpolicy: Pick<RetryPolicy, \"baseDelayMs\" | \"maxAgentDelayMs\" | \"maxRetryDelayMs\">,\n\tattempt: number,\n\tfailure: Pick<AssistantMessage, \"retryAfterMs\">,\n): number {\n\tconst hintMs = failure.retryAfterMs;\n\tif (hintMs === undefined || !Number.isFinite(hintMs) || hintMs <= 0) return retryDelayMs(policy, attempt);\n\tconst maxRetryDelayMs = policy.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;\n\tconst capMs = maxRetryDelayMs || (policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS);\n\treturn Math.min(hintMs, capMs);\n}\n\n/**\n * Delay before retry `attempt` (1-indexed) of a failed assistant call, or `undefined`\n * when it is not retryable or `maxRetries` is spent.\n */\nexport function assistantRetryDelayMs(policy: RetryPolicy, attempt: number, message: RetryFailure): number | undefined {\n\tif (!policy.enabled || attempt > policy.maxRetries || !isRetryableAssistantError(message)) return undefined;\n\treturn failureRetryDelayMs(policy, attempt, message);\n}\n\n/** Optional callbacks emitted by {@link retryAssistantCall} around each retry. */\nexport interface RetryCallbacks {\n\t/** Emitted before the backoff sleep of each retry attempt (1-indexed). */\n\tonRetryScheduled?: (\n\t\tattempt: number,\n\t\tmaxAttempts: number,\n\t\tdelayMs: number,\n\t\terrorMessage: string,\n\t) => void | Promise<void>;\n\t/** Emitted after the backoff sleep, immediately before the retried call starts. */\n\tonRetryAttemptStart?: () => void | Promise<void>;\n\t/** Emitted once when the loop ends: success if a later call completed normally. */\n\tonRetryFinished?: (success: boolean, attempt: number, finalError?: string) => void | Promise<void>;\n}\n\nexport interface RetryCallOptions extends RetryCallbacks {\n\t/** Do not start a retry at or after this performance.now() timestamp. Does not cancel a running call. */\n\tretryDeadline?: RetryDeadline;\n}\n\nclass RetrySleepAbortError extends Error {\n\tconstructor() {\n\t\tsuper(\"Aborted\");\n\t}\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new RetrySleepAbortError());\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\treject(new RetrySleepAbortError());\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\n/**\n * Run a single assistant-producing call with bounded retry on transient errors.\n *\n * Behavior:\n * - A successful response is returned immediately. Aborts are terminal and never\n * retried, but reported as unsuccessful if they happen after a retry was scheduled.\n * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage`\n * too, so callers do not need to care when cancellation happened.\n * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/\n * billing exhaustion) is returned immediately so deterministic errors fail fast.\n * - Otherwise retries up to `maxRetries` times, waiting for the server retry hint or\n * the exponential backoff (see {@link assistantRetryDelayMs}), emitting\n * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before\n * the retried call starts, and `onRetryFinished` once at the end (whether the loop\n * ends in success, exhausted retries, or an aborted backoff).\n *\n * When `policy` is undefined or disabled, the first response is returned unchanged\n * (equivalent to calling `produce()` directly).\n */\nexport async function retryAssistantCall(\n\tproduce: () => Promise<AssistantMessage>,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallOptions,\n): Promise<AssistantMessage> {\n\tconst maxAttempts = policy?.enabled ? policy.maxRetries : 0;\n\n\tlet attempt = 0;\n\tlet lastRetry: { attempt: number; errorMessage: string } | undefined;\n\tfor (;;) {\n\t\tconst response = await produce();\n\n\t\t// Abort: terminal but not successful. Never retry an aborted message.\n\t\tif (response.stopReason === \"aborted\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Success: non-error, non-abort responses return as-is.\n\t\tif (response.stopReason !== \"error\") {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn response;\n\t\t}\n\n\t\t// Non-retryable, or budget exhausted: return the final error message.\n\t\tconst delayMs = policy ? assistantRetryDelayMs(policy, attempt + 1, response) : undefined;\n\t\tif (delayMs === undefined) {\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt, response.errorMessage);\n\t\t\treturn response;\n\t\t}\n\n\t\tattempt++;\n\t\tlastRetry = { attempt, errorMessage: response.errorMessage || \"Unknown error\" };\n\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t// Normalize aborts during retry backoff to the same AssistantMessage shape as\n\t\t// provider stream aborts, so callers do not need to care when cancellation happened.\n\t\ttry {\n\t\t\tawait sleep(delayMs, signal);\n\t\t} catch (error) {\n\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\tif (error instanceof RetrySleepAbortError) {\n\t\t\t\treturn { ...response, stopReason: \"aborted\", errorMessage: undefined };\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tif (!retryDeadlineReached(callbacks?.retryDeadline)) {\n\t\t\tawait callbacks?.onRetryAttemptStart?.();\n\t\t\t// The callback can itself wait past the deadline.\n\t\t\tif (!retryDeadlineReached(callbacks?.retryDeadline)) continue;\n\t\t}\n\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\treturn { ...response, stopReason: \"aborted\", errorMessage: undefined };\n\t}\n}\n\n/**\n * Classifies whether a failed assistant message looks like a transient provider\n * or transport error, so callers can decide if the last assistant turn should be\n * restarted.\n *\n * A GitHub Copilot failure carries its typed error, whose `retryable` decides. A request refused for its TLS\n * certificate (a `provider_tls_certificate_refused` diagnostic) is never retried.\n *\n * This does not implement retry policy. Callers should first handle context\n * overflow separately, then apply their own retry budget, backoff, and reporting\n * before restarting the assistant turn.\n */\nexport function isRetryableAssistantError(message: RetryFailure): boolean {\n\tif (message.stopReason !== \"error\" || !message.errorMessage) return false;\n\t// The certificate the endpoint showed is refused again by the next attempt (#6114).\n\tif (getTlsCertificateRefusal(message) !== undefined) return false;\n\tconst copilotError = getGitHubCopilotError(message);\n\tif (copilotError !== undefined) return copilotError.retryable;\n\tconst errorMessage = message.errorMessage;\n\tif (NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage)) return false;\n\treturn RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage);\n}\n"]}
@@ -0,0 +1,75 @@
1
+ import type { AssistantMessage } from "../types.ts";
2
+ /**
3
+ * A request that failed because TLS verification refused the certificate the endpoint (or a proxy on the way) showed
4
+ * (#6114). The certificate does not change between attempts, so such a request is sent once: no retry would succeed.
5
+ */
6
+ /**
7
+ * The codes of a certificate TLS verification refused: the host name check's code and Node's documented X509 codes,
8
+ * which Bun reports too, except `OUT_OF_MEM`, which says nothing about the certificate. The PostgreSQL adapter refuses
9
+ * a certificate with the same list (`packages/storage-postgres/proxy.js`).
10
+ */
11
+ export declare const TLS_VERIFICATION_CODES: ReadonlySet<string>;
12
+ /**
13
+ * Node and Bun report a verification result outside their table as `UNSPECIFIED`, with OpenSSL's reason for it, such as
14
+ * "key usage does not include certificate signing" for a root that may not sign certificates. These are those reasons
15
+ * that describe the certificate, lowercase, from OpenSSL 3 and BoringSSL. `UNSPECIFIED` with any other message, such as
16
+ * OpenSSL's own failures ("unspecified certificate verification error", "issuer certificate lookup error") or an error
17
+ * that did not come from TLS at all, is not a refused certificate. The PostgreSQL adapter holds the same list.
18
+ */
19
+ export declare const UNSPECIFIED_CERTIFICATE_REASONS: readonly string[];
20
+ /** Whether TLS verification refused a certificate with `code`, whose runtime message is `reason`. */
21
+ export declare function isRefusedCertificate(code: string, reason: string): boolean;
22
+ /**
23
+ * A certificate TLS verification refused: its code, the runtime's reason for it ("" when it names none), and the host
24
+ * the request's connection was for, when known.
25
+ */
26
+ export interface TlsCertificateRefusal {
27
+ readonly code: string;
28
+ readonly reason: string;
29
+ readonly host?: string;
30
+ }
31
+ /** The diagnostic a failed assistant message carries for a refused certificate, so retries decide on it. */
32
+ export declare const TLS_CERTIFICATE_REFUSED_DIAGNOSTIC = "provider_tls_certificate_refused";
33
+ /**
34
+ * Whether `error` is itself what the runtime's TLS reports for a certificate it refused: a certificate code with the
35
+ * runtime's own reason for it. Says nothing about which connection it was; see `findTlsCertificateRefusal`.
36
+ */
37
+ export declare function isTlsVerificationError(error: unknown): boolean;
38
+ /**
39
+ * What a request's own connection to `url` failed with, before any response, as the request should throw it (#6114):
40
+ * when the runtime's TLS refused a certificate, a new error made for this rejection alone, with `error` as its cause and
41
+ * its message, which `findTlsCertificateRefusal` reads as a refused certificate for `url`'s host; otherwise `error`
42
+ * itself. A hook, a callback or another request that fails the same way never goes through here.
43
+ */
44
+ export declare function transportFailure(error: unknown, url: string | URL | undefined): unknown;
45
+ /**
46
+ * `fetch` (the global one when undefined, read at each call), whose rejections are the request's own transport failures
47
+ * for their URL (see `transportFailure`). Responses, and the errors of reading them, are untouched.
48
+ */
49
+ export declare function transportFetch(fetch: typeof globalThis.fetch | undefined): typeof globalThis.fetch;
50
+ /**
51
+ * The refused certificate a failed request's error carries: a rejection of the request's own transport (see
52
+ * `transportFailure`), wrapped or not by an SDK (`Connection error.`), whose cause chain carries a certificate code
53
+ * with the runtime's own reason for it (Node's fetch: `fetch failed` over the TLS error; Bun's fetch: the code on its
54
+ * own error). Undefined for any other failure: a response or any link from one, a body or stream event that relays a
55
+ * code, a hook's or callback's failure, another request's.
56
+ */
57
+ export declare function findTlsCertificateRefusal(error: unknown): TlsCertificateRefusal | undefined;
58
+ /**
59
+ * What to tell the user about a refused certificate: the host the connection was for, when known, the code and the
60
+ * runtime's reason, and how to have it accepted.
61
+ */
62
+ export declare function describeTlsCertificateRefusal(refusal: TlsCertificateRefusal): string;
63
+ /**
64
+ * When `error` is a refused certificate on the request's own connection: names it in `output`'s message and records it
65
+ * as a `provider_tls_certificate_refused` diagnostic, so no retry sends the request again. Returns whether it was one.
66
+ */
67
+ export declare function recordTlsCertificateRefusal(output: AssistantMessage, error: unknown): boolean;
68
+ /**
69
+ * The refused certificate a failed assistant message records; undefined when it records none. Accepts a message read
70
+ * back from JSON, whose diagnostics are validated here.
71
+ */
72
+ export declare function getTlsCertificateRefusal(message: {
73
+ readonly diagnostics?: unknown;
74
+ } | undefined): TlsCertificateRefusal | undefined;
75
+ //# sourceMappingURL=tls-certificate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tls-certificate.d.ts","sourceRoot":"","sources":["../../src/utils/tls-certificate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAGpD;;;GAGG;AAEH;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,EAAE,WAAW,CAAC,MAAM,CA6BrD,CAAC;AAEH;;;;;;GAMG;AACH,eAAO,MAAM,+BAA+B,EAAE,SAAS,MAAM,EAiE5D,CAAC;AAEF,qGAAqG;AACrG,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAK1E;AAED;;;GAGG;AACH,MAAM,WAAW,qBAAqB;IACrC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,4GAA4G;AAC5G,eAAO,MAAM,kCAAkC,qCAAqC,CAAC;AAuDrF;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAK9D;AAsDD;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,GAAG,GAAG,GAAG,SAAS,GAAG,OAAO,CAOvF;AAOD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,UAAU,CAAC,KAAK,GAAG,SAAS,GAAG,OAAO,UAAU,CAAC,KAAK,CAWlG;AAED;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,OAAO,GAAG,qBAAqB,GAAG,SAAS,CAuB3F;AAID;;;GAGG;AACH,wBAAgB,6BAA6B,CAAC,OAAO,EAAE,qBAAqB,GAAG,MAAM,CAOpF;AAED;;;GAGG;AACH,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,gBAAgB,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAW7F;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CACvC,OAAO,EAAE;IAAE,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,SAAS,GACrD,qBAAqB,GAAG,SAAS,CAWnC"}
@@ -0,0 +1,343 @@
1
+ import { appendAssistantMessageDiagnostic } from "./diagnostics.js";
2
+ /**
3
+ * A request that failed because TLS verification refused the certificate the endpoint (or a proxy on the way) showed
4
+ * (#6114). The certificate does not change between attempts, so such a request is sent once: no retry would succeed.
5
+ */
6
+ /**
7
+ * The codes of a certificate TLS verification refused: the host name check's code and Node's documented X509 codes,
8
+ * which Bun reports too, except `OUT_OF_MEM`, which says nothing about the certificate. The PostgreSQL adapter refuses
9
+ * a certificate with the same list (`packages/storage-postgres/proxy.js`).
10
+ */
11
+ export const TLS_VERIFICATION_CODES = new Set([
12
+ "ERR_TLS_CERT_ALTNAME_INVALID",
13
+ "UNABLE_TO_GET_ISSUER_CERT",
14
+ "UNABLE_TO_GET_CRL",
15
+ "UNABLE_TO_DECRYPT_CERT_SIGNATURE",
16
+ "UNABLE_TO_DECRYPT_CRL_SIGNATURE",
17
+ "UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY",
18
+ "CERT_SIGNATURE_FAILURE",
19
+ "CRL_SIGNATURE_FAILURE",
20
+ "CERT_NOT_YET_VALID",
21
+ "CERT_HAS_EXPIRED",
22
+ "CRL_NOT_YET_VALID",
23
+ "CRL_HAS_EXPIRED",
24
+ "ERROR_IN_CERT_NOT_BEFORE_FIELD",
25
+ "ERROR_IN_CERT_NOT_AFTER_FIELD",
26
+ "ERROR_IN_CRL_LAST_UPDATE_FIELD",
27
+ "ERROR_IN_CRL_NEXT_UPDATE_FIELD",
28
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
29
+ "SELF_SIGNED_CERT_IN_CHAIN",
30
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
31
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
32
+ "CERT_CHAIN_TOO_LONG",
33
+ "CERT_REVOKED",
34
+ "INVALID_CA",
35
+ "PATH_LENGTH_EXCEEDED",
36
+ "INVALID_PURPOSE",
37
+ "CERT_UNTRUSTED",
38
+ "CERT_REJECTED",
39
+ "HOSTNAME_MISMATCH",
40
+ ]);
41
+ /**
42
+ * Node and Bun report a verification result outside their table as `UNSPECIFIED`, with OpenSSL's reason for it, such as
43
+ * "key usage does not include certificate signing" for a root that may not sign certificates. These are those reasons
44
+ * that describe the certificate, lowercase, from OpenSSL 3 and BoringSSL. `UNSPECIFIED` with any other message, such as
45
+ * OpenSSL's own failures ("unspecified certificate verification error", "issuer certificate lookup error") or an error
46
+ * that did not come from TLS at all, is not a refused certificate. The PostgreSQL adapter holds the same list.
47
+ */
48
+ export const UNSPECIFIED_CERTIFICATE_REASONS = [
49
+ "authority and issuer serial number mismatch",
50
+ "authority and subject key identifier mismatch",
51
+ "authority key identifier marked critical",
52
+ "basic constraints of ca cert not marked critical",
53
+ "ca cert does not include key usage extension",
54
+ "ca certificate key too weak",
55
+ "ca signature digest algorithm too weak",
56
+ "cannot find certificate signature algorithm",
57
+ "cert info signature and signature algorithm mismatch",
58
+ "certificate public key has explicit ecc parameters",
59
+ "certificate transparency required, but no valid scts found",
60
+ "crl path validation error",
61
+ "different crl scope",
62
+ "ee certificate key too weak",
63
+ "email address mismatch",
64
+ "empty subject alternative name extension",
65
+ "excluded subtree violation",
66
+ "invalid non-ca certificate (has ca markings)",
67
+ "invalid or inconsistent certificate extension",
68
+ "invalid or inconsistent certificate policy extension",
69
+ "ip address mismatch",
70
+ "issuer certificate doesn't have a public key",
71
+ "issuer has name constraints but leaf has no sans",
72
+ "issuer name empty",
73
+ "key usage does not include certificate signing",
74
+ "key usage does not include crl signing",
75
+ "key usage does not include digital signature",
76
+ "key usage keycertsign invalid for non-ca cert",
77
+ "missing authority key identifier",
78
+ "missing subject key identifier",
79
+ "name constraints minimum and maximum not supported",
80
+ "no explicit policy",
81
+ "no matching dane tlsa records",
82
+ "ocsp unknown cert",
83
+ "ocsp verification failed",
84
+ "ocsp verification needed",
85
+ "path length given without key usage keycertsign",
86
+ "path length invalid for non-ca cert",
87
+ "path loop",
88
+ "permitted subtree violation",
89
+ "proxy certificates not allowed, please set the appropriate flag",
90
+ "proxy path length constraint exceeded",
91
+ "proxy subject name violation",
92
+ "raw public key untrusted, no trusted keys configured",
93
+ "rfc 3779 resource not subset of parent's resources",
94
+ "subject empty and subject alt name extension not critical",
95
+ "subject issuer mismatch",
96
+ "subject key identifier marked critical",
97
+ "subject name empty",
98
+ "subject signature algorithm and issuer public key algorithm mismatch",
99
+ "suite b: cannot sign p-384 with p-256",
100
+ "suite b: certificate version invalid",
101
+ "suite b: curve not allowed for this los",
102
+ "suite b: invalid ecc curve",
103
+ "suite b: invalid public key algorithm",
104
+ "suite b: invalid signature algorithm",
105
+ "unable to get crl issuer certificate",
106
+ "unhandled critical crl extension",
107
+ "unhandled critical extension",
108
+ "unsupported extension feature",
109
+ "unsupported name constraint type",
110
+ "unsupported or invalid name constraint syntax",
111
+ "unsupported or invalid name syntax",
112
+ "using cert extension requires at least x509v3",
113
+ ];
114
+ /** Whether TLS verification refused a certificate with `code`, whose runtime message is `reason`. */
115
+ export function isRefusedCertificate(code, reason) {
116
+ if (TLS_VERIFICATION_CODES.has(code))
117
+ return true;
118
+ if (code !== "UNSPECIFIED")
119
+ return false;
120
+ const text = reason.toLowerCase();
121
+ return UNSPECIFIED_CERTIFICATE_REASONS.some((known) => text.startsWith(known));
122
+ }
123
+ /** The diagnostic a failed assistant message carries for a refused certificate, so retries decide on it. */
124
+ export const TLS_CERTIFICATE_REFUSED_DIAGNOSTIC = "provider_tls_certificate_refused";
125
+ const MAX_CAUSE_DEPTH = 5;
126
+ /**
127
+ * The runtime's own reasons for each code TLS verification refuses a certificate with, lowercase: OpenSSL 3's and
128
+ * BoringSSL's, and Node.js's and Bun's for a certificate that does not name the host. A runtime may add to them, as
129
+ * Node.js 24 adds a hint to some, so each is a prefix.
130
+ */
131
+ const VERIFICATION_REASONS = {
132
+ ERR_TLS_CERT_ALTNAME_INVALID: ["hostname/ip does not match certificate's altnames"],
133
+ UNABLE_TO_GET_ISSUER_CERT: ["unable to get issuer certificate"],
134
+ UNABLE_TO_GET_CRL: ["unable to get certificate crl"],
135
+ UNABLE_TO_DECRYPT_CERT_SIGNATURE: ["unable to decrypt certificate's signature"],
136
+ UNABLE_TO_DECRYPT_CRL_SIGNATURE: ["unable to decrypt crl's signature"],
137
+ UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: ["unable to decode issuer public key"],
138
+ CERT_SIGNATURE_FAILURE: ["certificate signature failure"],
139
+ CRL_SIGNATURE_FAILURE: ["crl signature failure"],
140
+ CERT_NOT_YET_VALID: ["certificate is not yet valid"],
141
+ CERT_HAS_EXPIRED: ["certificate has expired"],
142
+ CRL_NOT_YET_VALID: ["crl is not yet valid"],
143
+ CRL_HAS_EXPIRED: ["crl has expired"],
144
+ ERROR_IN_CERT_NOT_BEFORE_FIELD: ["format error in certificate's notbefore field"],
145
+ ERROR_IN_CERT_NOT_AFTER_FIELD: ["format error in certificate's notafter field"],
146
+ ERROR_IN_CRL_LAST_UPDATE_FIELD: ["format error in crl's lastupdate field"],
147
+ ERROR_IN_CRL_NEXT_UPDATE_FIELD: ["format error in crl's nextupdate field"],
148
+ DEPTH_ZERO_SELF_SIGNED_CERT: ["self-signed certificate", "self signed certificate"],
149
+ SELF_SIGNED_CERT_IN_CHAIN: [
150
+ "self-signed certificate in certificate chain",
151
+ "self signed certificate in certificate chain",
152
+ ],
153
+ UNABLE_TO_GET_ISSUER_CERT_LOCALLY: ["unable to get local issuer certificate"],
154
+ UNABLE_TO_VERIFY_LEAF_SIGNATURE: ["unable to verify the first certificate"],
155
+ CERT_CHAIN_TOO_LONG: ["certificate chain too long"],
156
+ CERT_REVOKED: ["certificate revoked"],
157
+ INVALID_CA: ["invalid ca certificate"],
158
+ PATH_LENGTH_EXCEEDED: ["path length constraint exceeded"],
159
+ INVALID_PURPOSE: ["unsuitable certificate purpose", "unsupported certificate purpose"],
160
+ CERT_UNTRUSTED: ["certificate not trusted"],
161
+ CERT_REJECTED: ["certificate rejected"],
162
+ HOSTNAME_MISMATCH: ["hostname mismatch"],
163
+ UNSPECIFIED: UNSPECIFIED_CERTIFICATE_REASONS,
164
+ };
165
+ /**
166
+ * Whether `message` is the runtime's own text for a certificate it refused with `code`, as Node's and Bun's TLS give
167
+ * it, or Bun's fetch (`<code> fetching "<url>"`), rather than a provider's: a gateway can relay an upstream's
168
+ * certificate code in its own words, which says nothing about the certificate this request was shown.
169
+ */
170
+ function isVerificationMessage(code, message) {
171
+ const text = message.toLowerCase();
172
+ if (text.startsWith(`${code.toLowerCase()} fetching `))
173
+ return true;
174
+ return (VERIFICATION_REASONS[code] ?? []).some((reason) => text.startsWith(reason));
175
+ }
176
+ /**
177
+ * Whether `error` is itself what the runtime's TLS reports for a certificate it refused: a certificate code with the
178
+ * runtime's own reason for it. Says nothing about which connection it was; see `findTlsCertificateRefusal`.
179
+ */
180
+ export function isTlsVerificationError(error) {
181
+ if (typeof error !== "object" || error === null)
182
+ return false;
183
+ const { code, message } = error;
184
+ const text = typeof message === "string" ? message.trim() : "";
185
+ return typeof code === "string" && isRefusedCertificate(code, text) && isVerificationMessage(code, text);
186
+ }
187
+ /**
188
+ * Whether `value` came from a response: an HTTP status as SDK errors carry it, including pi-messages' recorded one, or
189
+ * the response headers an SDK error for an error event inside a successful response keeps.
190
+ */
191
+ function isResponseError(value) {
192
+ const fields = value;
193
+ return (typeof fields.status === "number" ||
194
+ typeof fields.statusCode === "number" ||
195
+ (typeof fields.headers === "object" && fields.headers !== null) ||
196
+ typeof fields.$metadata?.httpStatusCode === "number" ||
197
+ typeof fields.$response?.statusCode === "number" ||
198
+ typeof fields.diagnosticDetails?.status === "number");
199
+ }
200
+ /**
201
+ * The errors a request's own transport (its fetch, WebSocket or HTTP handler) was refused a certificate with, each a
202
+ * wrapper made for that one rejection, with the host it was for. Errors the transport rejected with are never marked
203
+ * themselves: a fetch may share one error object between requests, and a hook may throw it again.
204
+ */
205
+ const transportRefusals = new WeakMap();
206
+ /** The `host[:port]` of `url`, without credentials, path or query; undefined when it is not a URL. */
207
+ function hostOf(url) {
208
+ if (url === undefined || (typeof url === "string" && url.trim() === ""))
209
+ return undefined;
210
+ try {
211
+ return new URL(url).host || undefined;
212
+ }
213
+ catch {
214
+ return undefined;
215
+ }
216
+ }
217
+ /** Whether `error`'s cause chain carries the runtime's TLS verification error, and nothing from a response. */
218
+ function carriesVerificationError(error) {
219
+ let found = false;
220
+ let current = error;
221
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH && typeof current === "object" && current !== null; depth++) {
222
+ if (isResponseError(current))
223
+ return false;
224
+ found ||= isTlsVerificationError(current);
225
+ current = current.cause;
226
+ }
227
+ return found;
228
+ }
229
+ /**
230
+ * What a request's own connection to `url` failed with, before any response, as the request should throw it (#6114):
231
+ * when the runtime's TLS refused a certificate, a new error made for this rejection alone, with `error` as its cause and
232
+ * its message, which `findTlsCertificateRefusal` reads as a refused certificate for `url`'s host; otherwise `error`
233
+ * itself. A hook, a callback or another request that fails the same way never goes through here.
234
+ */
235
+ export function transportFailure(error, url) {
236
+ const host = hostOf(url);
237
+ if (host === undefined || !carriesVerificationError(error))
238
+ return error;
239
+ const message = error instanceof Error ? error.message : String(error);
240
+ const refusal = error instanceof TypeError ? new TypeError(message, { cause: error }) : new Error(message, { cause: error });
241
+ transportRefusals.set(refusal, host);
242
+ return refusal;
243
+ }
244
+ /** The URL a fetch call asks for. */
245
+ function requestUrl(input) {
246
+ return typeof input === "string" || input instanceof URL ? input : input.url;
247
+ }
248
+ /**
249
+ * `fetch` (the global one when undefined, read at each call), whose rejections are the request's own transport failures
250
+ * for their URL (see `transportFailure`). Responses, and the errors of reading them, are untouched.
251
+ */
252
+ export function transportFetch(fetch) {
253
+ return Object.assign(async (input, init) => {
254
+ try {
255
+ return await (fetch ?? globalThis.fetch)(input, init);
256
+ }
257
+ catch (error) {
258
+ throw transportFailure(error, requestUrl(input));
259
+ }
260
+ }, fetch ?? globalThis.fetch);
261
+ }
262
+ /**
263
+ * The refused certificate a failed request's error carries: a rejection of the request's own transport (see
264
+ * `transportFailure`), wrapped or not by an SDK (`Connection error.`), whose cause chain carries a certificate code
265
+ * with the runtime's own reason for it (Node's fetch: `fetch failed` over the TLS error; Bun's fetch: the code on its
266
+ * own error). Undefined for any other failure: a response or any link from one, a body or stream event that relays a
267
+ * code, a hook's or callback's failure, another request's.
268
+ */
269
+ export function findTlsCertificateRefusal(error) {
270
+ let host;
271
+ let refusal;
272
+ let current = error;
273
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH && typeof current === "object" && current !== null; depth++) {
274
+ // Any link from a response, above or below the code, means the request got an answer.
275
+ if (isResponseError(current))
276
+ return undefined;
277
+ if (current instanceof Error)
278
+ host ??= transportRefusals.get(current);
279
+ const { code, message } = current;
280
+ const text = typeof message === "string" ? message.trim() : "";
281
+ if (host !== undefined &&
282
+ refusal === undefined &&
283
+ typeof code === "string" &&
284
+ isRefusedCertificate(code, text) &&
285
+ isVerificationMessage(code, text)) {
286
+ // Bun's fetch names the code and the URL instead of a reason; the URL can carry credentials.
287
+ refusal = { code, reason: text.startsWith(code) || text.includes("://") ? "" : text, host };
288
+ }
289
+ current = current.cause;
290
+ }
291
+ return refusal;
292
+ }
293
+ const NAME_MISMATCH_CODES = new Set(["ERR_TLS_CERT_ALTNAME_INVALID", "HOSTNAME_MISMATCH"]);
294
+ /**
295
+ * What to tell the user about a refused certificate: the host the connection was for, when known, the code and the
296
+ * runtime's reason, and how to have it accepted.
297
+ */
298
+ export function describeTlsCertificateRefusal(refusal) {
299
+ const what = refusal.reason === "" ? refusal.code : `${refusal.code}: ${refusal.reason}`;
300
+ const fix = NAME_MISMATCH_CODES.has(refusal.code)
301
+ ? "Use a base URL whose host name the certificate names"
302
+ : "If the endpoint, or a proxy on the way to it, uses a certificate from a private or corporate CA, set NODE_EXTRA_CA_CERTS to a PEM file with that CA and restart";
303
+ const whose = refusal.host === undefined ? "" : ` for ${refusal.host}`;
304
+ return `The TLS certificate${whose} was not accepted (${what}). ${fix}. The request is not retried`;
305
+ }
306
+ /**
307
+ * When `error` is a refused certificate on the request's own connection: names it in `output`'s message and records it
308
+ * as a `provider_tls_certificate_refused` diagnostic, so no retry sends the request again. Returns whether it was one.
309
+ */
310
+ export function recordTlsCertificateRefusal(output, error) {
311
+ if (output.stopReason !== "error")
312
+ return false;
313
+ const refusal = findTlsCertificateRefusal(error);
314
+ if (refusal === undefined)
315
+ return false;
316
+ output.errorMessage = describeTlsCertificateRefusal(refusal);
317
+ appendAssistantMessageDiagnostic(output, {
318
+ type: TLS_CERTIFICATE_REFUSED_DIAGNOSTIC,
319
+ timestamp: Date.now(),
320
+ details: { code: refusal.code, reason: refusal.reason },
321
+ });
322
+ return true;
323
+ }
324
+ /**
325
+ * The refused certificate a failed assistant message records; undefined when it records none. Accepts a message read
326
+ * back from JSON, whose diagnostics are validated here.
327
+ */
328
+ export function getTlsCertificateRefusal(message) {
329
+ const diagnostics = message?.diagnostics;
330
+ if (!Array.isArray(diagnostics))
331
+ return undefined;
332
+ for (const diagnostic of diagnostics) {
333
+ if (diagnostic?.type !== TLS_CERTIFICATE_REFUSED_DIAGNOSTIC)
334
+ continue;
335
+ const code = diagnostic.details?.code;
336
+ const recorded = diagnostic.details?.reason;
337
+ const reason = typeof recorded === "string" ? recorded : "";
338
+ if (typeof code === "string" && isRefusedCertificate(code, reason))
339
+ return { code, reason };
340
+ }
341
+ return undefined;
342
+ }
343
+ //# sourceMappingURL=tls-certificate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tls-certificate.js","sourceRoot":"","sources":["../../src/utils/tls-certificate.ts"],"names":[],"mappings":"AACA,OAAO,EAAmC,gCAAgC,EAAE,MAAM,kBAAkB,CAAC;AAErG;;;GAGG;AAEH;;;;GAIG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAwB,IAAI,GAAG,CAAC;IAClE,8BAA8B;IAC9B,2BAA2B;IAC3B,mBAAmB;IACnB,kCAAkC;IAClC,iCAAiC;IACjC,oCAAoC;IACpC,wBAAwB;IACxB,uBAAuB;IACvB,oBAAoB;IACpB,kBAAkB;IAClB,mBAAmB;IACnB,iBAAiB;IACjB,gCAAgC;IAChC,+BAA+B;IAC/B,gCAAgC;IAChC,gCAAgC;IAChC,6BAA6B;IAC7B,2BAA2B;IAC3B,mCAAmC;IACnC,iCAAiC;IACjC,qBAAqB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,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE;KACvD,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,wBAAwB,CACvC,OAAuD;IAEvD,MAAM,WAAW,GAAG,OAAO,EAAE,WAAW,CAAC;IACzC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,WAAW,CAAC;QAAE,OAAO,SAAS,CAAC;IAClD,KAAK,MAAM,UAAU,IAAI,WAAsE,EAAE,CAAC;QACjG,IAAI,UAAU,EAAE,IAAI,KAAK,kCAAkC;YAAE,SAAS;QACtE,MAAM,IAAI,GAAG,UAAU,CAAC,OAAO,EAAE,IAAI,CAAC;QACtC,MAAM,QAAQ,GAAG,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC;QAC5C,MAAM,MAAM,GAAG,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC;QAC5D,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,oBAAoB,CAAC,IAAI,EAAE,MAAM,CAAC;YAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;IAC7F,CAAC;IACD,OAAO,SAAS,CAAC;AAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"../types.ts\";\nimport { type AssistantMessageDiagnostic, appendAssistantMessageDiagnostic } from \"./diagnostics.ts\";\n\n/**\n * A request that failed because TLS verification refused the certificate the endpoint (or a proxy on the way) showed\n * (#6114). The certificate does not change between attempts, so such a request is sent once: no retry would succeed.\n */\n\n/**\n * The codes of a certificate TLS verification refused: the host name check's code and Node's documented X509 codes,\n * which Bun reports too, except `OUT_OF_MEM`, which says nothing about the certificate. The PostgreSQL adapter refuses\n * a certificate with the same list (`packages/storage-postgres/proxy.js`).\n */\nexport const TLS_VERIFICATION_CODES: ReadonlySet<string> = new Set([\n\t\"ERR_TLS_CERT_ALTNAME_INVALID\",\n\t\"UNABLE_TO_GET_ISSUER_CERT\",\n\t\"UNABLE_TO_GET_CRL\",\n\t\"UNABLE_TO_DECRYPT_CERT_SIGNATURE\",\n\t\"UNABLE_TO_DECRYPT_CRL_SIGNATURE\",\n\t\"UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY\",\n\t\"CERT_SIGNATURE_FAILURE\",\n\t\"CRL_SIGNATURE_FAILURE\",\n\t\"CERT_NOT_YET_VALID\",\n\t\"CERT_HAS_EXPIRED\",\n\t\"CRL_NOT_YET_VALID\",\n\t\"CRL_HAS_EXPIRED\",\n\t\"ERROR_IN_CERT_NOT_BEFORE_FIELD\",\n\t\"ERROR_IN_CERT_NOT_AFTER_FIELD\",\n\t\"ERROR_IN_CRL_LAST_UPDATE_FIELD\",\n\t\"ERROR_IN_CRL_NEXT_UPDATE_FIELD\",\n\t\"DEPTH_ZERO_SELF_SIGNED_CERT\",\n\t\"SELF_SIGNED_CERT_IN_CHAIN\",\n\t\"UNABLE_TO_GET_ISSUER_CERT_LOCALLY\",\n\t\"UNABLE_TO_VERIFY_LEAF_SIGNATURE\",\n\t\"CERT_CHAIN_TOO_LONG\",\n\t\"CERT_REVOKED\",\n\t\"INVALID_CA\",\n\t\"PATH_LENGTH_EXCEEDED\",\n\t\"INVALID_PURPOSE\",\n\t\"CERT_UNTRUSTED\",\n\t\"CERT_REJECTED\",\n\t\"HOSTNAME_MISMATCH\",\n]);\n\n/**\n * Node and Bun report a verification result outside their table as `UNSPECIFIED`, with OpenSSL's reason for it, such as\n * \"key usage does not include certificate signing\" for a root that may not sign certificates. These are those reasons\n * that describe the certificate, lowercase, from OpenSSL 3 and BoringSSL. `UNSPECIFIED` with any other message, such as\n * OpenSSL's own failures (\"unspecified certificate verification error\", \"issuer certificate lookup error\") or an error\n * that did not come from TLS at all, is not a refused certificate. The PostgreSQL adapter holds the same list.\n */\nexport const UNSPECIFIED_CERTIFICATE_REASONS: readonly string[] = [\n\t\"authority and issuer serial number mismatch\",\n\t\"authority and subject key identifier mismatch\",\n\t\"authority key identifier marked critical\",\n\t\"basic constraints of ca cert not marked critical\",\n\t\"ca cert does not include key usage extension\",\n\t\"ca certificate key too weak\",\n\t\"ca signature digest algorithm too weak\",\n\t\"cannot find certificate signature algorithm\",\n\t\"cert info signature and signature algorithm mismatch\",\n\t\"certificate public key has explicit ecc parameters\",\n\t\"certificate transparency required, but no valid scts found\",\n\t\"crl path validation error\",\n\t\"different crl scope\",\n\t\"ee certificate key too weak\",\n\t\"email address mismatch\",\n\t\"empty subject alternative name extension\",\n\t\"excluded subtree violation\",\n\t\"invalid non-ca certificate (has ca markings)\",\n\t\"invalid or inconsistent certificate extension\",\n\t\"invalid or inconsistent certificate policy extension\",\n\t\"ip address mismatch\",\n\t\"issuer certificate doesn't have a public key\",\n\t\"issuer has name constraints but leaf has no sans\",\n\t\"issuer name empty\",\n\t\"key usage does not include certificate signing\",\n\t\"key usage does not include crl signing\",\n\t\"key usage does not include digital signature\",\n\t\"key usage keycertsign invalid for non-ca cert\",\n\t\"missing authority key identifier\",\n\t\"missing subject key identifier\",\n\t\"name constraints minimum and maximum not supported\",\n\t\"no explicit policy\",\n\t\"no matching dane tlsa records\",\n\t\"ocsp unknown cert\",\n\t\"ocsp verification failed\",\n\t\"ocsp verification needed\",\n\t\"path length given without key usage keycertsign\",\n\t\"path length invalid for non-ca cert\",\n\t\"path loop\",\n\t\"permitted subtree violation\",\n\t\"proxy certificates not allowed, please set the appropriate flag\",\n\t\"proxy path length constraint exceeded\",\n\t\"proxy subject name violation\",\n\t\"raw public key untrusted, no trusted keys configured\",\n\t\"rfc 3779 resource not subset of parent's resources\",\n\t\"subject empty and subject alt name extension not critical\",\n\t\"subject issuer mismatch\",\n\t\"subject key identifier marked critical\",\n\t\"subject name empty\",\n\t\"subject signature algorithm and issuer public key algorithm mismatch\",\n\t\"suite b: cannot sign p-384 with p-256\",\n\t\"suite b: certificate version invalid\",\n\t\"suite b: curve not allowed for this los\",\n\t\"suite b: invalid ecc curve\",\n\t\"suite b: invalid public key algorithm\",\n\t\"suite b: invalid signature algorithm\",\n\t\"unable to get crl issuer certificate\",\n\t\"unhandled critical crl extension\",\n\t\"unhandled critical extension\",\n\t\"unsupported extension feature\",\n\t\"unsupported name constraint type\",\n\t\"unsupported or invalid name constraint syntax\",\n\t\"unsupported or invalid name syntax\",\n\t\"using cert extension requires at least x509v3\",\n];\n\n/** Whether TLS verification refused a certificate with `code`, whose runtime message is `reason`. */\nexport function isRefusedCertificate(code: string, reason: string): boolean {\n\tif (TLS_VERIFICATION_CODES.has(code)) return true;\n\tif (code !== \"UNSPECIFIED\") return false;\n\tconst text = reason.toLowerCase();\n\treturn UNSPECIFIED_CERTIFICATE_REASONS.some((known) => text.startsWith(known));\n}\n\n/**\n * A certificate TLS verification refused: its code, the runtime's reason for it (\"\" when it names none), and the host\n * the request's connection was for, when known.\n */\nexport interface TlsCertificateRefusal {\n\treadonly code: string;\n\treadonly reason: string;\n\treadonly host?: string;\n}\n\n/** The diagnostic a failed assistant message carries for a refused certificate, so retries decide on it. */\nexport const TLS_CERTIFICATE_REFUSED_DIAGNOSTIC = \"provider_tls_certificate_refused\";\n\nconst MAX_CAUSE_DEPTH = 5;\n\n/**\n * The runtime's own reasons for each code TLS verification refuses a certificate with, lowercase: OpenSSL 3's and\n * BoringSSL's, and Node.js's and Bun's for a certificate that does not name the host. A runtime may add to them, as\n * Node.js 24 adds a hint to some, so each is a prefix.\n */\nconst VERIFICATION_REASONS: Readonly<Record<string, readonly string[]>> = {\n\tERR_TLS_CERT_ALTNAME_INVALID: [\"hostname/ip does not match certificate's altnames\"],\n\tUNABLE_TO_GET_ISSUER_CERT: [\"unable to get issuer certificate\"],\n\tUNABLE_TO_GET_CRL: [\"unable to get certificate crl\"],\n\tUNABLE_TO_DECRYPT_CERT_SIGNATURE: [\"unable to decrypt certificate's signature\"],\n\tUNABLE_TO_DECRYPT_CRL_SIGNATURE: [\"unable to decrypt crl's signature\"],\n\tUNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: [\"unable to decode issuer public key\"],\n\tCERT_SIGNATURE_FAILURE: [\"certificate signature failure\"],\n\tCRL_SIGNATURE_FAILURE: [\"crl signature failure\"],\n\tCERT_NOT_YET_VALID: [\"certificate is not yet valid\"],\n\tCERT_HAS_EXPIRED: [\"certificate has expired\"],\n\tCRL_NOT_YET_VALID: [\"crl is not yet valid\"],\n\tCRL_HAS_EXPIRED: [\"crl has expired\"],\n\tERROR_IN_CERT_NOT_BEFORE_FIELD: [\"format error in certificate's notbefore field\"],\n\tERROR_IN_CERT_NOT_AFTER_FIELD: [\"format error in certificate's notafter field\"],\n\tERROR_IN_CRL_LAST_UPDATE_FIELD: [\"format error in crl's lastupdate field\"],\n\tERROR_IN_CRL_NEXT_UPDATE_FIELD: [\"format error in crl's nextupdate field\"],\n\tDEPTH_ZERO_SELF_SIGNED_CERT: [\"self-signed certificate\", \"self signed certificate\"],\n\tSELF_SIGNED_CERT_IN_CHAIN: [\n\t\t\"self-signed certificate in certificate chain\",\n\t\t\"self signed certificate in certificate chain\",\n\t],\n\tUNABLE_TO_GET_ISSUER_CERT_LOCALLY: [\"unable to get local issuer certificate\"],\n\tUNABLE_TO_VERIFY_LEAF_SIGNATURE: [\"unable to verify the first certificate\"],\n\tCERT_CHAIN_TOO_LONG: [\"certificate chain too long\"],\n\tCERT_REVOKED: [\"certificate revoked\"],\n\tINVALID_CA: [\"invalid ca certificate\"],\n\tPATH_LENGTH_EXCEEDED: [\"path length constraint exceeded\"],\n\tINVALID_PURPOSE: [\"unsuitable certificate purpose\", \"unsupported certificate purpose\"],\n\tCERT_UNTRUSTED: [\"certificate not trusted\"],\n\tCERT_REJECTED: [\"certificate rejected\"],\n\tHOSTNAME_MISMATCH: [\"hostname mismatch\"],\n\tUNSPECIFIED: UNSPECIFIED_CERTIFICATE_REASONS,\n};\n\n/**\n * Whether `message` is the runtime's own text for a certificate it refused with `code`, as Node's and Bun's TLS give\n * it, or Bun's fetch (`<code> fetching \"<url>\"`), rather than a provider's: a gateway can relay an upstream's\n * certificate code in its own words, which says nothing about the certificate this request was shown.\n */\nfunction isVerificationMessage(code: string, message: string): boolean {\n\tconst text = message.toLowerCase();\n\tif (text.startsWith(`${code.toLowerCase()} fetching `)) return true;\n\treturn (VERIFICATION_REASONS[code] ?? []).some((reason) => text.startsWith(reason));\n}\n\n/**\n * Whether `error` is itself what the runtime's TLS reports for a certificate it refused: a certificate code with the\n * runtime's own reason for it. Says nothing about which connection it was; see `findTlsCertificateRefusal`.\n */\nexport function isTlsVerificationError(error: unknown): boolean {\n\tif (typeof error !== \"object\" || error === null) return false;\n\tconst { code, message } = error as { code?: unknown; message?: unknown };\n\tconst text = typeof message === \"string\" ? message.trim() : \"\";\n\treturn typeof code === \"string\" && isRefusedCertificate(code, text) && isVerificationMessage(code, text);\n}\n\n/**\n * Whether `value` came from a response: an HTTP status as SDK errors carry it, including pi-messages' recorded one, or\n * the response headers an SDK error for an error event inside a successful response keeps.\n */\nfunction isResponseError(value: object): boolean {\n\tconst fields = value as {\n\t\tstatus?: unknown;\n\t\tstatusCode?: unknown;\n\t\theaders?: unknown;\n\t\t$metadata?: { httpStatusCode?: unknown };\n\t\t$response?: { statusCode?: unknown };\n\t\tdiagnosticDetails?: { status?: unknown };\n\t};\n\treturn (\n\t\ttypeof fields.status === \"number\" ||\n\t\ttypeof fields.statusCode === \"number\" ||\n\t\t(typeof fields.headers === \"object\" && fields.headers !== null) ||\n\t\ttypeof fields.$metadata?.httpStatusCode === \"number\" ||\n\t\ttypeof fields.$response?.statusCode === \"number\" ||\n\t\ttypeof fields.diagnosticDetails?.status === \"number\"\n\t);\n}\n\n/**\n * The errors a request's own transport (its fetch, WebSocket or HTTP handler) was refused a certificate with, each a\n * wrapper made for that one rejection, with the host it was for. Errors the transport rejected with are never marked\n * themselves: a fetch may share one error object between requests, and a hook may throw it again.\n */\nconst transportRefusals = new WeakMap<Error, string>();\n\n/** The `host[:port]` of `url`, without credentials, path or query; undefined when it is not a URL. */\nfunction hostOf(url: string | URL | undefined): string | undefined {\n\tif (url === undefined || (typeof url === \"string\" && url.trim() === \"\")) return undefined;\n\ttry {\n\t\treturn new URL(url).host || undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Whether `error`'s cause chain carries the runtime's TLS verification error, and nothing from a response. */\nfunction carriesVerificationError(error: unknown): boolean {\n\tlet found = false;\n\tlet current = error;\n\tfor (let depth = 0; depth < MAX_CAUSE_DEPTH && typeof current === \"object\" && current !== null; depth++) {\n\t\tif (isResponseError(current)) return false;\n\t\tfound ||= isTlsVerificationError(current);\n\t\tcurrent = (current as { cause?: unknown }).cause;\n\t}\n\treturn found;\n}\n\n/**\n * What a request's own connection to `url` failed with, before any response, as the request should throw it (#6114):\n * when the runtime's TLS refused a certificate, a new error made for this rejection alone, with `error` as its cause and\n * its message, which `findTlsCertificateRefusal` reads as a refused certificate for `url`'s host; otherwise `error`\n * itself. A hook, a callback or another request that fails the same way never goes through here.\n */\nexport function transportFailure(error: unknown, url: string | URL | undefined): unknown {\n\tconst host = hostOf(url);\n\tif (host === undefined || !carriesVerificationError(error)) return error;\n\tconst message = error instanceof Error ? error.message : String(error);\n\tconst refusal = error instanceof TypeError ? new TypeError(message, { cause: error }) : new Error(message, { cause: error });\n\ttransportRefusals.set(refusal, host);\n\treturn refusal;\n}\n\n/** The URL a fetch call asks for. */\nfunction requestUrl(input: Parameters<typeof globalThis.fetch>[0]): string | URL {\n\treturn typeof input === \"string\" || input instanceof URL ? input : input.url;\n}\n\n/**\n * `fetch` (the global one when undefined, read at each call), whose rejections are the request's own transport failures\n * for their URL (see `transportFailure`). Responses, and the errors of reading them, are untouched.\n */\nexport function transportFetch(fetch: typeof globalThis.fetch | undefined): typeof globalThis.fetch {\n\treturn Object.assign(\n\t\tasync (input: Parameters<typeof globalThis.fetch>[0], init?: RequestInit) => {\n\t\t\ttry {\n\t\t\t\treturn await (fetch ?? globalThis.fetch)(input, init);\n\t\t\t} catch (error) {\n\t\t\t\tthrow transportFailure(error, requestUrl(input));\n\t\t\t}\n\t\t},\n\t\tfetch ?? globalThis.fetch,\n\t);\n}\n\n/**\n * The refused certificate a failed request's error carries: a rejection of the request's own transport (see\n * `transportFailure`), wrapped or not by an SDK (`Connection error.`), whose cause chain carries a certificate code\n * with the runtime's own reason for it (Node's fetch: `fetch failed` over the TLS error; Bun's fetch: the code on its\n * own error). Undefined for any other failure: a response or any link from one, a body or stream event that relays a\n * code, a hook's or callback's failure, another request's.\n */\nexport function findTlsCertificateRefusal(error: unknown): TlsCertificateRefusal | undefined {\n\tlet host: string | undefined;\n\tlet refusal: TlsCertificateRefusal | undefined;\n\tlet current = error;\n\tfor (let depth = 0; depth < MAX_CAUSE_DEPTH && typeof current === \"object\" && current !== null; depth++) {\n\t\t// Any link from a response, above or below the code, means the request got an answer.\n\t\tif (isResponseError(current)) return undefined;\n\t\tif (current instanceof Error) host ??= transportRefusals.get(current);\n\t\tconst { code, message } = current as { code?: unknown; message?: unknown };\n\t\tconst text = typeof message === \"string\" ? message.trim() : \"\";\n\t\tif (\n\t\t\thost !== undefined &&\n\t\t\trefusal === undefined &&\n\t\t\ttypeof code === \"string\" &&\n\t\t\tisRefusedCertificate(code, text) &&\n\t\t\tisVerificationMessage(code, text)\n\t\t) {\n\t\t\t// Bun's fetch names the code and the URL instead of a reason; the URL can carry credentials.\n\t\t\trefusal = { code, reason: text.startsWith(code) || text.includes(\"://\") ? \"\" : text, host };\n\t\t}\n\t\tcurrent = (current as { cause?: unknown }).cause;\n\t}\n\treturn refusal;\n}\n\nconst NAME_MISMATCH_CODES: ReadonlySet<string> = new Set([\"ERR_TLS_CERT_ALTNAME_INVALID\", \"HOSTNAME_MISMATCH\"]);\n\n/**\n * What to tell the user about a refused certificate: the host the connection was for, when known, the code and the\n * runtime's reason, and how to have it accepted.\n */\nexport function describeTlsCertificateRefusal(refusal: TlsCertificateRefusal): string {\n\tconst what = refusal.reason === \"\" ? refusal.code : `${refusal.code}: ${refusal.reason}`;\n\tconst fix = NAME_MISMATCH_CODES.has(refusal.code)\n\t\t? \"Use a base URL whose host name the certificate names\"\n\t\t: \"If the endpoint, or a proxy on the way to it, uses a certificate from a private or corporate CA, set NODE_EXTRA_CA_CERTS to a PEM file with that CA and restart\";\n\tconst whose = refusal.host === undefined ? \"\" : ` for ${refusal.host}`;\n\treturn `The TLS certificate${whose} was not accepted (${what}). ${fix}. The request is not retried`;\n}\n\n/**\n * When `error` is a refused certificate on the request's own connection: names it in `output`'s message and records it\n * as a `provider_tls_certificate_refused` diagnostic, so no retry sends the request again. Returns whether it was one.\n */\nexport function recordTlsCertificateRefusal(output: AssistantMessage, error: unknown): boolean {\n\tif (output.stopReason !== \"error\") return false;\n\tconst refusal = findTlsCertificateRefusal(error);\n\tif (refusal === undefined) return false;\n\toutput.errorMessage = describeTlsCertificateRefusal(refusal);\n\tappendAssistantMessageDiagnostic(output, {\n\t\ttype: TLS_CERTIFICATE_REFUSED_DIAGNOSTIC,\n\t\ttimestamp: Date.now(),\n\t\tdetails: { code: refusal.code, reason: refusal.reason },\n\t});\n\treturn true;\n}\n\n/**\n * The refused certificate a failed assistant message records; undefined when it records none. Accepts a message read\n * back from JSON, whose diagnostics are validated here.\n */\nexport function getTlsCertificateRefusal(\n\tmessage: { readonly diagnostics?: unknown } | undefined,\n): TlsCertificateRefusal | undefined {\n\tconst diagnostics = message?.diagnostics;\n\tif (!Array.isArray(diagnostics)) return undefined;\n\tfor (const diagnostic of diagnostics as readonly (Partial<AssistantMessageDiagnostic> | null)[]) {\n\t\tif (diagnostic?.type !== TLS_CERTIFICATE_REFUSED_DIAGNOSTIC) continue;\n\t\tconst code = diagnostic.details?.code;\n\t\tconst recorded = diagnostic.details?.reason;\n\t\tconst reason = typeof recorded === \"string\" ? recorded : \"\";\n\t\tif (typeof code === \"string\" && isRefusedCertificate(code, reason)) return { code, reason };\n\t}\n\treturn undefined;\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import type { JsonSchema } from "@bastani/atomic-schema";
1
2
  import type { Context, Message, SystemMessage, Tool, ToolReference, TranscriptContext } from "../types.ts";
2
3
  export type { TranscriptContext } from "../types.ts";
3
4
  /**
@@ -72,13 +73,19 @@ export declare function followsToolResults(message: Message): boolean;
72
73
  export declare function resolveRequestTranscript(context: TranscriptContext, supportsMidConvoSystemMessages: boolean | undefined): TranscriptContext;
73
74
  /** Strip executable and display-only fields from a tool before transcript comparison or persistence. */
74
75
  export declare function toToolDeclaration(tool: Tool): Tool;
76
+ /**
77
+ * Whether two JSON Schemas describe the same values, as {@link declarationsEqual} compares tool parameters: object keys
78
+ * in any order, and the names a `required` list holds in any order.
79
+ */
80
+ export declare function jsonSchemasEqual(left: JsonSchema | undefined, right: JsonSchema | undefined): boolean;
75
81
  /**
76
82
  * Whether two tools declare the same interface to the model.
77
83
  *
78
84
  * Both sides go through {@link toToolDeclaration} first: its JSON round-trip drops the
79
85
  * schema metadata keys (TypeBox's non-enumerable kind marks) and `undefined` fields that a structural comparison would see.
80
86
  * Object keys are compared in a canonical order, so a schema rebuilt with its keys in another order, as a server may
81
- * send it after reconnecting, is not a new definition. Array order counts. This avoids a deep-equal dependency in a
87
+ * send it after reconnecting, is not a new definition. A schema's `required` names form a set and may come in any order;
88
+ * other arrays, such as `enum` values or tuple items, keep their order. This avoids a deep-equal dependency in a
82
89
  * browser-safe package.
83
90
  */
84
91
  export declare function declarationsEqual(left: Tool, right: Tool): boolean;