@code-yeongyu/senpi-ai 2026.9.12 → 2026.9.13
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.
- package/README.md +39 -4
- package/dist/api/anthropic-messages.d.ts.map +1 -1
- package/dist/api/anthropic-messages.js +8 -1
- package/dist/api/anthropic-messages.js.map +1 -1
- package/dist/api/cloudflare-ai-binding.d.ts +77 -0
- package/dist/api/cloudflare-ai-binding.d.ts.map +1 -0
- package/dist/api/cloudflare-ai-binding.js +72 -0
- package/dist/api/cloudflare-ai-binding.js.map +1 -0
- package/dist/api/cursor-agent/measure.d.ts +11 -0
- package/dist/api/cursor-agent/measure.d.ts.map +1 -1
- package/dist/api/cursor-agent/measure.js +18 -0
- package/dist/api/cursor-agent/measure.js.map +1 -1
- package/dist/api/cursor-agent.d.ts +1 -1
- package/dist/api/cursor-agent.d.ts.map +1 -1
- package/dist/api/cursor-agent.js +5 -1
- package/dist/api/cursor-agent.js.map +1 -1
- package/dist/api/mistral-conversations.js +4 -1
- package/dist/api/mistral-conversations.js.map +1 -1
- package/dist/api/openai-codex-responses.d.ts.map +1 -1
- package/dist/api/openai-codex-responses.js +6 -3
- package/dist/api/openai-codex-responses.js.map +1 -1
- package/dist/api/openai-responses-shared.d.ts.map +1 -1
- package/dist/api/openai-responses-shared.js +4 -1
- package/dist/api/openai-responses-shared.js.map +1 -1
- package/dist/api/openai-responses.d.ts.map +1 -1
- package/dist/api/openai-responses.js +13 -3
- package/dist/api/openai-responses.js.map +1 -1
- package/dist/cursor/context-limit-store.d.ts +32 -0
- package/dist/cursor/context-limit-store.d.ts.map +1 -0
- package/dist/cursor/context-limit-store.js +62 -0
- package/dist/cursor/context-limit-store.js.map +1 -0
- package/dist/cursor/store-migration.d.ts.map +1 -1
- package/dist/cursor/store-migration.js +2 -1
- package/dist/cursor/store-migration.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/models.d.ts +1 -0
- package/dist/models.d.ts.map +1 -1
- package/dist/models.js +5 -2
- package/dist/models.js.map +1 -1
- package/dist/openai-responses-compat.d.ts +1 -1
- package/dist/openai-responses-compat.d.ts.map +1 -1
- package/dist/openai-responses-compat.js.map +1 -1
- package/dist/providers/cloudflare-ai-gateway.d.ts.map +1 -1
- package/dist/providers/cloudflare-ai-gateway.js +4 -0
- package/dist/providers/cloudflare-ai-gateway.js.map +1 -1
- package/dist/providers/cursor.d.ts.map +1 -1
- package/dist/providers/cursor.js +2 -1
- package/dist/providers/cursor.js.map +1 -1
- package/dist/providers/data/.manifest.json +1 -1
- package/dist/providers/data/azure-openai-responses.json +1 -1
- package/dist/providers/data/baseten.json +1 -1
- package/dist/providers/data/deepseek.json +1 -1
- package/dist/providers/data/fireworks.json +1 -1
- package/dist/providers/data/github-copilot.json +1 -1
- package/dist/providers/data/openai-codex.json +1 -1
- package/dist/providers/data/openrouter.json +1 -1
- package/dist/providers/data/qwen-token-plan-cn.json +1 -1
- package/dist/providers/data/qwen-token-plan-individual.json +1 -1
- package/dist/providers/data/qwen-token-plan.json +1 -1
- package/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/providers/data/xai.json +1 -1
- package/dist/providers/faux.js +5 -5
- package/dist/providers/faux.js.map +1 -1
- package/dist/providers/opencode-go.d.ts.map +1 -1
- package/dist/providers/opencode-go.js +4 -3
- package/dist/providers/opencode-go.js.map +1 -1
- package/dist/providers/opencode-headers.d.ts +4 -0
- package/dist/providers/opencode-headers.d.ts.map +1 -0
- package/dist/providers/opencode-headers.js +22 -0
- package/dist/providers/opencode-headers.js.map +1 -0
- package/dist/providers/opencode.d.ts.map +1 -1
- package/dist/providers/opencode.js +5 -4
- package/dist/providers/opencode.js.map +1 -1
- package/dist/types.d.ts +16 -6
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/assistant-message-frame.d.ts +77 -0
- package/dist/utils/assistant-message-frame.d.ts.map +1 -0
- package/dist/utils/assistant-message-frame.js +427 -0
- package/dist/utils/assistant-message-frame.js.map +1 -0
- package/dist/utils/cursor-context-limit.d.ts +12 -0
- package/dist/utils/cursor-context-limit.d.ts.map +1 -0
- package/dist/utils/cursor-context-limit.js +93 -0
- package/dist/utils/cursor-context-limit.js.map +1 -0
- package/dist/utils/event-stream.d.ts.map +1 -1
- package/dist/utils/event-stream.js +25 -5
- package/dist/utils/event-stream.js.map +1 -1
- package/dist/utils/prompt-cache-ttl.d.ts +1 -1
- package/dist/utils/prompt-cache-ttl.d.ts.map +1 -1
- package/dist/utils/prompt-cache-ttl.js +5 -1
- package/dist/utils/prompt-cache-ttl.js.map +1 -1
- package/dist/utils/retry-profile/types.d.ts +10 -1
- package/dist/utils/retry-profile/types.d.ts.map +1 -1
- package/dist/utils/retry-profile/types.js.map +1 -1
- package/dist/utils/retry.d.ts +13 -2
- package/dist/utils/retry.d.ts.map +1 -1
- package/dist/utils/retry.js +18 -7
- package/dist/utils/retry.js.map +1 -1
- package/dist/utils/uuid.d.ts +2 -2
- package/dist/utils/uuid.d.ts.map +1 -1
- package/dist/utils/uuid.js +36 -31
- package/dist/utils/uuid.js.map +1 -1
- package/package.json +6 -6
- package/dist/api/cloudflare-gateway-binding.d.ts +0 -69
- package/dist/api/cloudflare-gateway-binding.d.ts.map +0 -1
- package/dist/api/cloudflare-gateway-binding.js +0 -159
- package/dist/api/cloudflare-gateway-binding.js.map +0 -1
package/dist/utils/retry.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAEA,SAAS,yBAAyB,CAAC,QAA2B;IAC7D,OAAO,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,oCAAoC,GAAG,yBAAyB,CAAC;IACtE,8EAA8E;I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AAI,EAAE,CAAC,CAAC;AAClF,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,uBAAuB,CAAC,YAAoB;IAC3D,OAAO,oBAAoB,CAAC,YAAY,CAAC,KAAK,WAAW,CAAC;AAC3D,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,oBAAoB,CAAC,YAAoB;IACxD,IAAI,CAAC,YAAY;QAAE,OAAO,SAAS,CAAC;IACpC,IAAI,oCAAoC,CAAC,IAAI,CAAC,YAAY,CAAC;QAAE,OAAO,eAAe,CAAC;IACpF,IAAI,gCAAgC,CAAC,IAAI,CAAC,YAAY,CAAC;QAAE,OAAO,WAAW,CAAC;IAC5E,OAAO,SAAS,CAAC;AAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"../types.ts\";\n\nfunction buildProviderErrorPattern(patterns: readonly string[]): RegExp {\n\treturn new RegExp(patterns.join(\"|\"), \"i\");\n}\n\nconst NON_RETRYABLE_PROVIDER_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\n\t// Anthropic Console credit exhaustion: a 429 rate_limit_error whose details\n\t// carry error_code credits_required (\"Usage credits are required for this\n\t// model.\"). The account is dead until the user buys credits or raises the\n\t// spend limit, so same-model retries can never recover it.\n\t\"credits_required\",\n\t\"credits are required\",\n\n\t// Request-shape rejections: the provider refused the payload we built, not the\n\t// work it describes. Gateways wrap these in whatever status they like — the\n\t// observed Apitopia/Kimi case arrives as `500 server_error: Invalid request:\n\t// tools.function.parameters.type is required and must be \"object\"` — so the\n\t// status text alone would classify a permanent failure as transient. The same\n\t// bytes are rejected on every attempt and on every fallback model, so retrying\n\t// can only burn the turn. Anchored on the `tools[...]`/`functions[...]` request\n\t// path so unrelated prose mentioning tools stays retryable.\n\t\"invalid request: tools\\\\.\",\n\t\"invalid request: functions\\\\.\",\n\t\"tools\\\\.[^ ]*function\\\\.parameters\",\n\t\"tools\\\\.\\\\d+\\\\.function\\\\.parameters\",\n\t\"invalid tool schema\",\n]);\n\nconst RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// Local credential/auth sidecar lock exhaustion is infrastructure contention,\n\t// not a provider failure and must stay on the transient retry path.\n\t\"Credential store is busy: lock\",\n\t// Generic provider load, HTTP status, and server-side transient failures.\n\t\"overloaded\",\n\t\"rate.?limit\",\n\t\"too many requests\",\n\t\"429\",\n\t\"500\",\n\t\"502\",\n\t\"503\",\n\t\"504\",\n\t// Cloudflare 522 (Connection timed out): origin stopped responding; transient\n\t// like the other 5xx gateway statuses, surfaced as \"Error: error code: 522\".\n\t\"522\",\n\t\"524\",\n\t\"service.?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.?error\",\n\t\"exceeded request buffer limit while retrying upstream\",\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\"other side closed\",\n\t\"fetch failed\",\n\t\"getaddrinfo\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"upstream.?connect\",\n\t\"upstream.?unavailable\",\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// 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\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// Gateway/proxy-side rejection of the whole model request, e.g. \"Error: The\n\t// model request was rejected. Check the request and try again.\" (observed in a\n\t// live session, 2026-08-11). Coupling the rejection sentence to its explicit\n\t// retry instruction keeps unrelated permission, request-shape, and content-\n\t// policy rejections terminal while the bounded retry policy absorbs this\n\t// transient wrapper wording.\n\t\"the model request was rejected\\\\.\\\\s*check the request and try again\\\\.?\",\n\n\t// Anthropic server-tool pairing rejections, e.g. \"`web_search` tool use with id\n\t// `srvtoolu_...` was found without a corresponding `web_search_tool_result`\n\t// block\". A turn closed before its deferred server tool could answer leaves\n\t// the unpairable half in history, and replaying it 400s every later request.\n\t// The Anthropic request builder repairs the replayed history, so a retry sends\n\t// a valid payload; keeping the class retryable is what lets retry and the model\n\t// fallback chain unwedge such a session instead of dead-ending it. The trailing\n\t// backtick keeps the pattern on Anthropic's pairing-error template.\n\t\"was found without a corresponding `\",\n\n\t// gRPC based providers (e.g. NVIDIA NIM)\n\t\"ResourceExhausted\",\n\n\t// Claude Agent SDK session.json lock contention. A second stream/resume\n\t// hits proper-lockfile while the previous subprocess still holds the file.\n\t// Same-process retry recovers; hopping providers cannot release that lock.\n\t\"Lock file is already being held\",\n]);\n\n/**\n * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).\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/** Injectable source used for Codex-style +/-10% backoff jitter. */\n\trandom?: () => number;\n}\n\nexport function retryDelayMs(baseDelayMs: number, attempt: number, random: () => number = Math.random): number {\n\tconst scheduledDelayMs = baseDelayMs * 2 ** (attempt - 1);\n\tconst sample = Math.min(1, Math.max(0, random()));\n\treturn Math.round(scheduledDelayMs * (0.9 + sample * 0.2));\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\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 producer that signals failure by THROWING, with the same bounded\n * backoff, abort, and callback semantics as {@link retryAssistantCall}.\n *\n * `retryAssistantCall` is value-based: its producer reports failure by resolving\n * an `AssistantMessage` with `stopReason: \"error\"`. Callers that instead reject\n * (compaction summarization, and any other request pipeline that throws) need\n * the identical retry policy without reshaping their failures into assistant\n * messages first, so both live here and share one implementation of the delay,\n * abort, and callback contract.\n *\n * Behavior:\n * - A resolved value is returned immediately.\n * - A throw that `isRetryable` rejects is rethrown at once: deterministic\n * failures never spend a retry.\n * - Otherwise the call is retried up to `policy.maxRetries` times with the same\n * exponential backoff (`baseDelayMs * 2^(attempt-1)`), rethrowing the final\n * error when the budget is exhausted.\n * - An abort during the backoff sleep stops the loop and rethrows; unlike the\n * assistant-message path there is no aborted value to normalize to.\n *\n * When `policy` is undefined or disabled the producer runs exactly once and its\n * error propagates unchanged.\n */\nexport async function retryTransientCall<T>(\n\tproduce: () => Promise<T>,\n\tisRetryable: (error: unknown) => boolean,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallbacks,\n): Promise<T> {\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\ttry {\n\t\t\tconst value = await produce();\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn value;\n\t\t} catch (error) {\n\t\t\tif (error instanceof RetrySleepAbortError) throw error;\n\t\t\tif (attempt >= maxAttempts || !isRetryable(error)) {\n\t\t\t\tif (lastRetry) {\n\t\t\t\t\tawait callbacks?.onRetryFinished?.(false, lastRetry.attempt, errorMessageOf(error));\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tattempt++;\n\t\t\tlastRetry = { attempt, errorMessage: errorMessageOf(error) };\n\t\t\tconst delayMs = retryDelayMs(policy!.baseDelayMs, attempt, policy!.random);\n\t\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t\ttry {\n\t\t\t\tawait sleep(delayMs, signal);\n\t\t\t} catch (sleepError) {\n\t\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\t\tthrow sleepError instanceof RetrySleepAbortError ? error : sleepError;\n\t\t\t}\n\t\t\tawait callbacks?.onRetryAttemptStart?.();\n\t\t}\n\t}\n}\n\nfunction errorMessageOf(error: unknown): string {\n\tif (error instanceof Error) return error.message || \"Unknown error\";\n\treturn String(error) || \"Unknown error\";\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 with exponential backoff, 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?: RetryCallbacks,\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\tif (attempt >= maxAttempts || !isRetryableAssistantError(response)) {\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\tconst delayMs = retryDelayMs(policy!.baseDelayMs, attempt, policy!.random);\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\tawait callbacks?.onRetryAttemptStart?.();\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 * 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: AssistantMessage): boolean {\n\tif (\n\t\tmessage.stopReason !== \"error\" ||\n\t\tmessage.stopDetails?.type === \"refusal\" ||\n\t\tmessage.stopDetails?.type === \"sensitive\" ||\n\t\t!message.errorMessage\n\t) {\n\t\treturn false;\n\t}\n\treturn isRetryableErrorMessage(message.errorMessage);\n}\n\n/**\n * Matches the agent-loop stream watchdog failures (\"Idle timeout waiting for\n * provider stream after <n>ms\" and \"Provider stream start timed out after\n * <n>ms\"). These anchored shapes distinguish provider-stream stalls from\n * unrelated extension, command, or MCP timeout diagnostics.\n */\nconst PROVIDER_STREAM_STALL_ERROR_PATTERN =\n\t/^(?:Idle timeout waiting for provider stream after \\d+ms|Provider stream start timed out after \\d+ms(?: \\([^)]*\\))?)$/i;\nconst PROVIDER_TRANSPORT_TIMEOUT_ERROR_PATTERN = /^Request timed out\\.?$/i;\n\nexport function isProviderStreamStallError(message: AssistantMessage): boolean {\n\treturn message.stopReason === \"error\" && PROVIDER_STREAM_STALL_ERROR_PATTERN.test(message.errorMessage ?? \"\");\n}\n\n/**\n * Classifies timeout failures that originate from the provider stream or its\n * transport. Transport timeouts may arrive as `aborted`; stream watchdog\n * failures are ordinary error responses.\n */\nexport function isProviderTimeoutError(message: AssistantMessage): boolean {\n\tif (message.abortSource === \"provider\") return true;\n\tif (isProviderStreamStallError(message)) return true;\n\tif (message.stopReason !== \"error\" && message.stopReason !== \"aborted\") return false;\n\treturn PROVIDER_TRANSPORT_TIMEOUT_ERROR_PATTERN.test(message.errorMessage ?? \"\");\n}\n\n/**\n * Classifies a raw error-message string with the same transient-vs-terminal\n * rules as {@link isRetryableAssistantError}, for callers that hold a thrown\n * `Error` instead of an `AssistantMessage` (e.g. compaction summarization\n * failures that must decide between degrading and surfacing loudly).\n */\nexport function isRetryableErrorMessage(errorMessage: string): boolean {\n\treturn classifyErrorMessage(errorMessage) === \"retryable\";\n}\n\n/**\n * Tri-state form of {@link isRetryableErrorMessage}. The regexes only carry\n * three outcomes — a non-retryable match, a retryable match, or no match at\n * all — and callers that hold structured failure facts (status codes, provider\n * error codes) need to distinguish \"the regexes say terminal\" from \"the\n * regexes say nothing\" so they can consult the structured facts only in the\n * latter case. Non-retryable still outranks retryable, exactly as before.\n */\nexport function classifyErrorMessage(errorMessage: string): \"non-retryable\" | \"retryable\" | \"unknown\" {\n\tif (!errorMessage) return \"unknown\";\n\tif (NON_RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage)) return \"non-retryable\";\n\tif (RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage)) return \"retryable\";\n\treturn \"unknown\";\n}\n"]}
|
|
1
|
+
{"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAEA,SAAS,yBAAyB,CAAC,QAA2B;IAC7D,OAAO,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,oCAAoC,GAAG,yBAAyB,CAAC;IACtE,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;IAET,4EAA4E;IAC5E,0EAA0E;IAC1E,0EAA0E;IAC1E,2DAA2D;IAC3D,kBAAkB;IAClB,sBAAsB;IAEtB,+EAA+E;IAC/E,4EAA4E;IAC5E,6EAA6E;IAC7E,4EAA4E;IAC5E,8EAA8E;IAC9E,+EAA+E;IAC/E,gFAAgF;IAChF,4DAA4D;IAC5D,2BAA2B;IAC3B,+BAA+B;IAC/B,oCAAoC;IACpC,sCAAsC;IACtC,qBAAqB;CACrB,CAAC,CAAC;AAEH,MAAM,gCAAgC,GAAG,yBAAyB,CAAC;IAClE,8EAA8E;IAC9E,oEAAoE;IACpE,gCAAgC;IAChC,0EAA0E;IAC1E,YAAY;IACZ,aAAa;IACb,mBAAmB;IACnB,KAAK;IACL,KAAK;IACL,KA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AAO,eAAe,CAAC;IACpF,IAAI,gCAAgC,CAAC,IAAI,CAAC,YAAY,CAAC;QAAE,OAAO,WAAW,CAAC;IAC5E,OAAO,SAAS,CAAC;AAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"../types.ts\";\n\nfunction buildProviderErrorPattern(patterns: readonly string[]): RegExp {\n\treturn new RegExp(patterns.join(\"|\"), \"i\");\n}\n\nconst NON_RETRYABLE_PROVIDER_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\n\t// Anthropic Console credit exhaustion: a 429 rate_limit_error whose details\n\t// carry error_code credits_required (\"Usage credits are required for this\n\t// model.\"). The account is dead until the user buys credits or raises the\n\t// spend limit, so same-model retries can never recover it.\n\t\"credits_required\",\n\t\"credits are required\",\n\n\t// Request-shape rejections: the provider refused the payload we built, not the\n\t// work it describes. Gateways wrap these in whatever status they like — the\n\t// observed Apitopia/Kimi case arrives as `500 server_error: Invalid request:\n\t// tools.function.parameters.type is required and must be \"object\"` — so the\n\t// status text alone would classify a permanent failure as transient. The same\n\t// bytes are rejected on every attempt and on every fallback model, so retrying\n\t// can only burn the turn. Anchored on the `tools[...]`/`functions[...]` request\n\t// path so unrelated prose mentioning tools stays retryable.\n\t\"invalid request: tools\\\\.\",\n\t\"invalid request: functions\\\\.\",\n\t\"tools\\\\.[^ ]*function\\\\.parameters\",\n\t\"tools\\\\.\\\\d+\\\\.function\\\\.parameters\",\n\t\"invalid tool schema\",\n]);\n\nconst RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([\n\t// Local credential/auth sidecar lock exhaustion is infrastructure contention,\n\t// not a provider failure and must stay on the transient retry path.\n\t\"Credential store is busy: lock\",\n\t// Generic provider load, HTTP status, and server-side transient failures.\n\t\"overloaded\",\n\t\"rate.?limit\",\n\t\"too many requests\",\n\t\"429\",\n\t\"500\",\n\t\"502\",\n\t\"503\",\n\t\"504\",\n\t// Cloudflare 522 (Connection timed out): origin stopped responding; transient\n\t// like the other 5xx gateway statuses, surfaced as \"Error: error code: 522\".\n\t\"522\",\n\t\"524\",\n\t\"service.?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.?error\",\n\t\"exceeded request buffer limit while retrying upstream\",\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\"other side closed\",\n\t\"fetch failed\",\n\t\"getaddrinfo\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\",\n\t\"upstream.?connect\",\n\t\"upstream.?unavailable\",\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// 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\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// Gateway/proxy-side rejection of the whole model request, e.g. \"Error: The\n\t// model request was rejected. Check the request and try again.\" (observed in a\n\t// live session, 2026-08-11). Coupling the rejection sentence to its explicit\n\t// retry instruction keeps unrelated permission, request-shape, and content-\n\t// policy rejections terminal while the bounded retry policy absorbs this\n\t// transient wrapper wording.\n\t\"the model request was rejected\\\\.\\\\s*check the request and try again\\\\.?\",\n\n\t// Anthropic server-tool pairing rejections, e.g. \"`web_search` tool use with id\n\t// `srvtoolu_...` was found without a corresponding `web_search_tool_result`\n\t// block\". A turn closed before its deferred server tool could answer leaves\n\t// the unpairable half in history, and replaying it 400s every later request.\n\t// The Anthropic request builder repairs the replayed history, so a retry sends\n\t// a valid payload; keeping the class retryable is what lets retry and the model\n\t// fallback chain unwedge such a session instead of dead-ending it. The trailing\n\t// backtick keeps the pattern on Anthropic's pairing-error template.\n\t\"was found without a corresponding `\",\n\n\t// gRPC based providers (e.g. NVIDIA NIM)\n\t\"ResourceExhausted\",\n\n\t// Claude Agent SDK session.json lock contention. A second stream/resume\n\t// hits proper-lockfile while the previous subprocess still holds the file.\n\t// Same-process retry recovers; hopping providers cannot release that lock.\n\t\"Lock file is already being held\",\n]);\n\n/**\n * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`).\n * `maxAgentDelayMs` caps each computed delay and defaults to 60 seconds.\n * Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`, `maxAgentDelayMs`) 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/** Optional cap for agent-level retry delays in ms. Defaults to 60 seconds. */\n\tmaxAgentDelayMs?: number;\n\t/** Injectable source used for Codex-style +/-10% backoff jitter. */\n\trandom?: () => number;\n}\n\nexport const DEFAULT_MAX_AGENT_RETRY_DELAY_MS = 60_000;\n\n/**\n * Per-attempt backoff: `baseDelayMs * 2^(attempt-1)`, jittered by +/-10% through the\n * injectable `random` source, then clamped to `maxAgentDelayMs` (60s by default). The\n * jitter runs before the clamp so a capped delay stays exactly at the cap instead of\n * scattering above it, and the safe-integer guard keeps a large `attempt` from producing\n * `Infinity` before the clamp.\n */\nexport function retryDelayMs(\n\tpolicy: Pick<RetryPolicy, \"baseDelayMs\" | \"maxAgentDelayMs\" | \"random\">,\n\tattempt: number,\n): number {\n\tconst scheduledDelayMs = policy.baseDelayMs * 2 ** Math.max(0, attempt - 1);\n\tconst sample = Math.min(1, Math.max(0, (policy.random ?? Math.random)()));\n\tconst jitteredDelayMs = Math.round(scheduledDelayMs * (0.9 + sample * 0.2));\n\tconst safeDelay = Number.isSafeInteger(jitteredDelayMs) ? jitteredDelayMs : Number.MAX_SAFE_INTEGER;\n\treturn Math.min(safeDelay, policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS);\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\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 producer that signals failure by THROWING, with the same bounded\n * backoff, abort, and callback semantics as {@link retryAssistantCall}.\n *\n * `retryAssistantCall` is value-based: its producer reports failure by resolving\n * an `AssistantMessage` with `stopReason: \"error\"`. Callers that instead reject\n * (compaction summarization, and any other request pipeline that throws) need\n * the identical retry policy without reshaping their failures into assistant\n * messages first, so both live here and share one implementation of the delay,\n * abort, and callback contract.\n *\n * Behavior:\n * - A resolved value is returned immediately.\n * - A throw that `isRetryable` rejects is rethrown at once: deterministic\n * failures never spend a retry.\n * - Otherwise the call is retried up to `policy.maxRetries` times with the same\n * exponential backoff (`baseDelayMs * 2^(attempt-1)`), rethrowing the final\n * error when the budget is exhausted.\n * - An abort during the backoff sleep stops the loop and rethrows; unlike the\n * assistant-message path there is no aborted value to normalize to.\n *\n * When `policy` is undefined or disabled the producer runs exactly once and its\n * error propagates unchanged.\n */\nexport async function retryTransientCall<T>(\n\tproduce: () => Promise<T>,\n\tisRetryable: (error: unknown) => boolean,\n\tpolicy: RetryPolicy | undefined,\n\tsignal: AbortSignal | undefined,\n\tcallbacks?: RetryCallbacks,\n): Promise<T> {\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\ttry {\n\t\t\tconst value = await produce();\n\t\t\tif (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt);\n\t\t\treturn value;\n\t\t} catch (error) {\n\t\t\tif (error instanceof RetrySleepAbortError) throw error;\n\t\t\tif (attempt >= maxAttempts || !isRetryable(error)) {\n\t\t\t\tif (lastRetry) {\n\t\t\t\t\tawait callbacks?.onRetryFinished?.(false, lastRetry.attempt, errorMessageOf(error));\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tattempt++;\n\t\t\tlastRetry = { attempt, errorMessage: errorMessageOf(error) };\n\t\t\tconst delayMs = retryDelayMs(policy!, attempt);\n\t\t\tawait callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage);\n\n\t\t\ttry {\n\t\t\t\tawait sleep(delayMs, signal);\n\t\t\t} catch (sleepError) {\n\t\t\t\tawait callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage);\n\t\t\t\tthrow sleepError instanceof RetrySleepAbortError ? error : sleepError;\n\t\t\t}\n\t\t\tawait callbacks?.onRetryAttemptStart?.();\n\t\t}\n\t}\n}\n\nfunction errorMessageOf(error: unknown): string {\n\tif (error instanceof Error) return error.message || \"Unknown error\";\n\treturn String(error) || \"Unknown error\";\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 with exponential backoff, 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?: RetryCallbacks,\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\tif (attempt >= maxAttempts || !isRetryableAssistantError(response)) {\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\tconst delayMs = retryDelayMs(policy!, attempt);\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\tconst { errorMessage: _errorMessage, ...rest } = response;\n\t\t\t\treturn { ...rest, stopReason: \"aborted\" };\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tawait callbacks?.onRetryAttemptStart?.();\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 * 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: AssistantMessage): boolean {\n\tif (\n\t\tmessage.stopReason !== \"error\" ||\n\t\tmessage.stopDetails?.type === \"refusal\" ||\n\t\tmessage.stopDetails?.type === \"sensitive\" ||\n\t\t!message.errorMessage\n\t) {\n\t\treturn false;\n\t}\n\treturn isRetryableErrorMessage(message.errorMessage);\n}\n\n/**\n * Matches the agent-loop stream watchdog failures (\"Idle timeout waiting for\n * provider stream after <n>ms\" and \"Provider stream start timed out after\n * <n>ms\"). These anchored shapes distinguish provider-stream stalls from\n * unrelated extension, command, or MCP timeout diagnostics.\n */\nconst PROVIDER_STREAM_STALL_ERROR_PATTERN =\n\t/^(?:Idle timeout waiting for provider stream after \\d+ms|Provider stream start timed out after \\d+ms(?: \\([^)]*\\))?)$/i;\nconst PROVIDER_TRANSPORT_TIMEOUT_ERROR_PATTERN = /^Request timed out\\.?$/i;\n\nexport function isProviderStreamStallError(message: AssistantMessage): boolean {\n\treturn message.stopReason === \"error\" && PROVIDER_STREAM_STALL_ERROR_PATTERN.test(message.errorMessage ?? \"\");\n}\n\n/**\n * Classifies timeout failures that originate from the provider stream or its\n * transport. Transport timeouts may arrive as `aborted`; stream watchdog\n * failures are ordinary error responses.\n */\nexport function isProviderTimeoutError(message: AssistantMessage): boolean {\n\tif (message.abortSource === \"provider\") return true;\n\tif (isProviderStreamStallError(message)) return true;\n\tif (message.stopReason !== \"error\" && message.stopReason !== \"aborted\") return false;\n\treturn PROVIDER_TRANSPORT_TIMEOUT_ERROR_PATTERN.test(message.errorMessage ?? \"\");\n}\n\n/**\n * Classifies a raw error-message string with the same transient-vs-terminal\n * rules as {@link isRetryableAssistantError}, for callers that hold a thrown\n * `Error` instead of an `AssistantMessage` (e.g. compaction summarization\n * failures that must decide between degrading and surfacing loudly).\n */\nexport function isRetryableErrorMessage(errorMessage: string): boolean {\n\treturn classifyErrorMessage(errorMessage) === \"retryable\";\n}\n\n/**\n * Tri-state form of {@link isRetryableErrorMessage}. The regexes only carry\n * three outcomes — a non-retryable match, a retryable match, or no match at\n * all — and callers that hold structured failure facts (status codes, provider\n * error codes) need to distinguish \"the regexes say terminal\" from \"the\n * regexes say nothing\" so they can consult the structured facts only in the\n * latter case. Non-retryable still outranks retryable, exactly as before.\n */\nexport function classifyErrorMessage(errorMessage: string): \"non-retryable\" | \"retryable\" | \"unknown\" {\n\tif (!errorMessage) return \"unknown\";\n\tif (NON_RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage)) return \"non-retryable\";\n\tif (RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage)) return \"retryable\";\n\treturn \"unknown\";\n}\n"]}
|
package/dist/utils/uuid.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
/** Generate a time-ordered UUIDv7. */
|
|
2
|
-
export declare function uuidv7(): string;
|
|
1
|
+
/** Generate a time-ordered UUIDv7. A supplied timestamp is preserved for follower ids. */
|
|
2
|
+
export declare function uuidv7(timestampMs?: number): string;
|
|
3
3
|
//# sourceMappingURL=uuid.d.ts.map
|
package/dist/utils/uuid.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uuid.d.ts","sourceRoot":"","sources":["../../src/utils/uuid.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"uuid.d.ts","sourceRoot":"","sources":["../../src/utils/uuid.ts"],"names":[],"mappings":"AAiBA,0FAA0F;AAC1F,wBAAgB,MAAM,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,MAAM,CAoCnD"}
|
package/dist/utils/uuid.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
const MAX_UUID_V7_TIMESTAMP = 0xffffffffffff;
|
|
2
|
+
const MAX_SEQUENCE = (1n << 41n) - 1n;
|
|
3
|
+
let lastOrdinaryTimestamp = -1;
|
|
4
|
+
let sequence;
|
|
3
5
|
function fillRandomBytes(bytes) {
|
|
4
6
|
const crypto = globalThis.crypto;
|
|
5
7
|
if (crypto?.getRandomValues) {
|
|
@@ -10,41 +12,44 @@ function fillRandomBytes(bytes) {
|
|
|
10
12
|
bytes[i] = Math.floor(Math.random() * 256);
|
|
11
13
|
}
|
|
12
14
|
}
|
|
13
|
-
/** Generate a time-ordered UUIDv7. */
|
|
14
|
-
export function uuidv7() {
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
15
|
+
/** Generate a time-ordered UUIDv7. A supplied timestamp is preserved for follower ids. */
|
|
16
|
+
export function uuidv7(timestampMs) {
|
|
17
|
+
const requestedTimestamp = timestampMs ?? Date.now();
|
|
18
|
+
if (!Number.isInteger(requestedTimestamp) || requestedTimestamp < 0 || requestedTimestamp > MAX_UUID_V7_TIMESTAMP) {
|
|
19
|
+
throw new RangeError(`UUIDv7 timestamp must be an integer between 0 and ${MAX_UUID_V7_TIMESTAMP}`);
|
|
20
|
+
}
|
|
21
|
+
const effectiveTimestamp = timestampMs === undefined ? Math.max(requestedTimestamp, lastOrdinaryTimestamp) : timestampMs;
|
|
22
|
+
if (timestampMs === undefined)
|
|
23
|
+
lastOrdinaryTimestamp = effectiveTimestamp;
|
|
24
|
+
const bytes = new Uint8Array(16);
|
|
25
|
+
fillRandomBytes(bytes);
|
|
26
|
+
if (sequence === undefined) {
|
|
27
|
+
sequence =
|
|
28
|
+
(BigInt(bytes[1]) << 32n) |
|
|
29
|
+
(BigInt(bytes[2]) << 24n) |
|
|
30
|
+
(BigInt(bytes[3]) << 16n) |
|
|
31
|
+
(BigInt(bytes[4]) << 8n) |
|
|
32
|
+
BigInt(bytes[5]);
|
|
21
33
|
}
|
|
22
34
|
else {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
35
|
+
if (sequence === MAX_SEQUENCE)
|
|
36
|
+
throw new RangeError("UUIDv7 generator sequence exhausted");
|
|
37
|
+
sequence++;
|
|
26
38
|
}
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
bytes[
|
|
32
|
-
bytes[
|
|
33
|
-
bytes[
|
|
34
|
-
bytes[
|
|
35
|
-
bytes[
|
|
36
|
-
bytes[
|
|
37
|
-
bytes[9] = (sequence >>> 6) & 0xff;
|
|
38
|
-
bytes[10] = ((sequence & 0x3f) << 2) | (random[10] & 0x03);
|
|
39
|
-
bytes[11] = random[11];
|
|
40
|
-
bytes[12] = random[12];
|
|
41
|
-
bytes[13] = random[13];
|
|
42
|
-
bytes[14] = random[14];
|
|
43
|
-
bytes[15] = random[15];
|
|
39
|
+
const timestamp = BigInt(effectiveTimestamp);
|
|
40
|
+
for (let index = 5; index >= 0; index--) {
|
|
41
|
+
bytes[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 0xff;
|
|
42
|
+
}
|
|
43
|
+
bytes[6] = 0x70 | Number((sequence >> 37n) & 0x0fn);
|
|
44
|
+
bytes[7] = Number((sequence >> 29n) & 0xffn);
|
|
45
|
+
bytes[8] = 0x80 | Number((sequence >> 23n) & 0x3fn);
|
|
46
|
+
bytes[9] = Number((sequence >> 15n) & 0xffn);
|
|
47
|
+
bytes[10] = Number((sequence >> 7n) & 0xffn);
|
|
48
|
+
bytes[11] = Number((sequence & 0x7fn) << 1n) | (bytes[11] & 0x01);
|
|
44
49
|
return formatUuid(bytes);
|
|
45
50
|
}
|
|
46
51
|
function formatUuid(bytes) {
|
|
47
52
|
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
|
|
48
|
-
return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10
|
|
53
|
+
return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
|
|
49
54
|
}
|
|
50
55
|
//# sourceMappingURL=uuid.js.map
|
package/dist/utils/uuid.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uuid.js","sourceRoot":"","sources":["../../src/utils/uuid.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"uuid.js","sourceRoot":"","sources":["../../src/utils/uuid.ts"],"names":[],"mappings":"AAAA,MAAM,qBAAqB,GAAG,cAAc,CAAC;AAC7C,MAAM,YAAY,GAAG,CAAC,EAAE,IAAI,GAAG,CAAC,GAAG,EAAE,CAAC;AAEtC,IAAI,qBAAqB,GAAG,CAAC,CAAC,CAAC;AAC/B,IAAI,QAA4B,CAAC;AAEjC,SAAS,eAAe,CAAC,KAA8B;IACtD,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC;IACjC,IAAI,MAAM,EAAE,eAAe,EAAE,CAAC;QAC7B,MAAM,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;QAC9B,OAAO;IACR,CAAC;IACD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACvC,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,GAAG,CAAC,CAAC;IAC5C,CAAC;AACF,CAAC;AAED,0FAA0F;AAC1F,MAAM,UAAU,MAAM,CAAC,WAAoB;IAC1C,MAAM,kBAAkB,GAAG,WAAW,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;IACrD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,kBAAkB,CAAC,IAAI,kBAAkB,GAAG,CAAC,IAAI,kBAAkB,GAAG,qBAAqB,EAAE,CAAC;QACn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CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,CAAC;AACrJ,CAAC","sourcesContent":["const MAX_UUID_V7_TIMESTAMP = 0xffffffffffff;\nconst MAX_SEQUENCE = (1n << 41n) - 1n;\n\nlet lastOrdinaryTimestamp = -1;\nlet sequence: bigint | undefined;\n\nfunction fillRandomBytes(bytes: Uint8Array<ArrayBuffer>): void {\n\tconst crypto = globalThis.crypto;\n\tif (crypto?.getRandomValues) {\n\t\tcrypto.getRandomValues(bytes);\n\t\treturn;\n\t}\n\tfor (let i = 0; i < bytes.length; i++) {\n\t\tbytes[i] = Math.floor(Math.random() * 256);\n\t}\n}\n\n/** Generate a time-ordered UUIDv7. A supplied timestamp is preserved for follower ids. */\nexport function uuidv7(timestampMs?: number): string {\n\tconst requestedTimestamp = timestampMs ?? Date.now();\n\tif (!Number.isInteger(requestedTimestamp) || requestedTimestamp < 0 || requestedTimestamp > MAX_UUID_V7_TIMESTAMP) {\n\t\tthrow new RangeError(`UUIDv7 timestamp must be an integer between 0 and ${MAX_UUID_V7_TIMESTAMP}`);\n\t}\n\n\tconst effectiveTimestamp =\n\t\ttimestampMs === undefined ? Math.max(requestedTimestamp, lastOrdinaryTimestamp) : timestampMs;\n\tif (timestampMs === undefined) lastOrdinaryTimestamp = effectiveTimestamp;\n\n\tconst bytes: Uint8Array<ArrayBuffer> = new Uint8Array(16);\n\tfillRandomBytes(bytes);\n\tif (sequence === undefined) {\n\t\tsequence =\n\t\t\t(BigInt(bytes[1]) << 32n) |\n\t\t\t(BigInt(bytes[2]) << 24n) |\n\t\t\t(BigInt(bytes[3]) << 16n) |\n\t\t\t(BigInt(bytes[4]) << 8n) |\n\t\t\tBigInt(bytes[5]);\n\t} else {\n\t\tif (sequence === MAX_SEQUENCE) throw new RangeError(\"UUIDv7 generator sequence exhausted\");\n\t\tsequence++;\n\t}\n\n\tconst timestamp = BigInt(effectiveTimestamp);\n\tfor (let index = 5; index >= 0; index--) {\n\t\tbytes[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 0xff;\n\t}\n\tbytes[6] = 0x70 | Number((sequence >> 37n) & 0x0fn);\n\tbytes[7] = Number((sequence >> 29n) & 0xffn);\n\tbytes[8] = 0x80 | Number((sequence >> 23n) & 0x3fn);\n\tbytes[9] = Number((sequence >> 15n) & 0xffn);\n\tbytes[10] = Number((sequence >> 7n) & 0xffn);\n\tbytes[11] = Number((sequence & 0x7fn) << 1n) | (bytes[11] & 0x01);\n\n\treturn formatUuid(bytes);\n}\n\nfunction formatUuid(bytes: Uint8Array<ArrayBuffer>): string {\n\tconst hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\"));\n\treturn `${hex.slice(0, 4).join(\"\")}-${hex.slice(4, 6).join(\"\")}-${hex.slice(6, 8).join(\"\")}-${hex.slice(8, 10).join(\"\")}-${hex.slice(10).join(\"\")}`;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@code-yeongyu/senpi-ai",
|
|
3
|
-
"version": "2026.9.
|
|
3
|
+
"version": "2026.9.13",
|
|
4
4
|
"description": "Unified LLM API with automatic model discovery and provider configuration",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -75,15 +75,15 @@
|
|
|
75
75
|
},
|
|
76
76
|
"dependencies": {
|
|
77
77
|
"@anthropic-ai/sdk": "0.123.0",
|
|
78
|
-
"@aws-sdk/client-bedrock-runtime": "3.
|
|
79
|
-
"@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.9.
|
|
80
|
-
"@google/genai": "2.
|
|
81
|
-
"@smithy/node-http-handler": "4.
|
|
78
|
+
"@aws-sdk/client-bedrock-runtime": "3.1127.0",
|
|
79
|
+
"@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.9.13",
|
|
80
|
+
"@google/genai": "2.21.0",
|
|
81
|
+
"@smithy/node-http-handler": "4.12.1",
|
|
82
82
|
"http-proxy-agent": "9.1.0",
|
|
83
83
|
"https-proxy-agent": "9.1.0",
|
|
84
84
|
"openai": "6.26.0",
|
|
85
85
|
"partial-json": "0.1.7",
|
|
86
|
-
"typebox": "1.3.
|
|
86
|
+
"typebox": "1.3.27",
|
|
87
87
|
"@bufbuild/protobuf": "2.14.0",
|
|
88
88
|
"@smithy/types": "4.17.2",
|
|
89
89
|
"yaml": "2.9.0"
|
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* AI Gateway transport over the Workers AI binding.
|
|
3
|
-
*
|
|
4
|
-
* pi's Cloudflare AI Gateway support speaks HTTPS
|
|
5
|
-
* (`gateway.ai.cloudflare.com/v1/{account}/{gateway}/{provider}/...`, see `api/cloudflare.ts`),
|
|
6
|
-
* which needs a Cloudflare API token even when the caller is a Worker in the gateway's own
|
|
7
|
-
* account.
|
|
8
|
-
*
|
|
9
|
-
* In order to solve for this problem, `createGatewayBindingFetch` returns a {@link FetchFunction}
|
|
10
|
-
* that translates requests under a gateway HTTPS prefix into calls to the Workers AI binding's
|
|
11
|
-
* universal endpoint, `env.AI.gateway(id).run({provider, endpoint, headers, query})`.
|
|
12
|
-
* Binding calls are pre-authenticated in-account and return the provider's native wire format as a
|
|
13
|
-
* regular (streaming) `Response`, so API implementations behave identically over either
|
|
14
|
-
* transport.
|
|
15
|
-
*
|
|
16
|
-
* The result is the transport for one gateway-bound client, not a general-purpose fetch:
|
|
17
|
-
* requests it cannot serve — URLs outside the prefix, or in-prefix requests the universal
|
|
18
|
-
* endpoint cannot express (non-POST, non-JSON body) — reject with a descriptive error.
|
|
19
|
-
* Transport selection is the caller's job, per client: route such traffic over HTTPS with
|
|
20
|
-
* real gateway auth instead of through this shim.
|
|
21
|
-
*/
|
|
22
|
-
import type { FetchFunction } from "../types.ts";
|
|
23
|
-
/**
|
|
24
|
-
* Structural type for the Workers AI binding's gateway surface (`env.AI`), so this
|
|
25
|
-
* module does not depend on `@cloudflare/workers-types`. Any real `Ai` binding satisfies it.
|
|
26
|
-
*/
|
|
27
|
-
export interface AiGatewayBinding {
|
|
28
|
-
gateway(id: string): AiGatewayBindingGateway;
|
|
29
|
-
}
|
|
30
|
-
export interface AiGatewayBindingGateway {
|
|
31
|
-
run(data: AiGatewayUniversalRequestLike, options?: {
|
|
32
|
-
signal?: AbortSignal;
|
|
33
|
-
}): Promise<Response>;
|
|
34
|
-
}
|
|
35
|
-
/** One universal-endpoint request entry, as accepted by `AiGateway.run()`. */
|
|
36
|
-
export interface AiGatewayUniversalRequestLike {
|
|
37
|
-
provider: string;
|
|
38
|
-
endpoint: string;
|
|
39
|
-
headers: Record<string, string>;
|
|
40
|
-
query: unknown;
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
* Placeholder value for auth headers on binding-routed requests. API implementations
|
|
44
|
-
* require an API key or a recognized auth header (`authorization`, `x-api-key`,
|
|
45
|
-
* `cf-aig-authorization`) before dispatch; binding calls are pre-authenticated, so pass
|
|
46
|
-
* `cf-aig-authorization: Bearer ${CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL}` to satisfy
|
|
47
|
-
* the check. The shim strips `cf-aig-authorization` before calling the binding. Pair it with
|
|
48
|
-
* `Authorization: null` / `x-api-key: null` so the SDKs' placeholder auth headers never reach
|
|
49
|
-
* the gateway, which would treat a request-supplied auth header as a BYOK provider key that
|
|
50
|
-
* overrides its stored keys — the same as it would over HTTPS.
|
|
51
|
-
*/
|
|
52
|
-
export declare const CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL = "cloudflare-gateway-binding";
|
|
53
|
-
export interface GatewayBindingFetchOptions {
|
|
54
|
-
/** The Workers AI binding (e.g. `env.AI`). */
|
|
55
|
-
binding: AiGatewayBinding;
|
|
56
|
-
/**
|
|
57
|
-
* Gateway HTTPS prefix every request must fall under, without a trailing slash:
|
|
58
|
-
* `https://gateway.ai.cloudflare.com/v1/{accountId}/{gatewayName}`.
|
|
59
|
-
*/
|
|
60
|
-
baseUrl: string;
|
|
61
|
-
/** Gateway name passed to `binding.gateway()`. Must match the `baseUrl` gateway. */
|
|
62
|
-
gateway: string;
|
|
63
|
-
}
|
|
64
|
-
/**
|
|
65
|
-
* Create a `fetch` that routes AI Gateway requests through the Workers AI binding.
|
|
66
|
-
* See the module docs for behavior and composition notes.
|
|
67
|
-
*/
|
|
68
|
-
export declare function createGatewayBindingFetch(options: GatewayBindingFetchOptions): FetchFunction;
|
|
69
|
-
//# sourceMappingURL=cloudflare-gateway-binding.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cloudflare-gateway-binding.d.ts","sourceRoot":"","sources":["../../src/api/cloudflare-gateway-binding.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEjD;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAChC,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,uBAAuB,CAAC;CAC7C;AAED,MAAM,WAAW,uBAAuB;IACvC,GAAG,CAAC,IAAI,EAAE,6BAA6B,EAAE,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CAChG;AAED,8EAA8E;AAC9E,MAAM,WAAW,6BAA6B;IAC7C,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,KAAK,EAAE,OAAO,CAAC;CACf;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,wCAAwC,+BAA+B,CAAC;AAErF,MAAM,WAAW,0BAA0B;IAC1C,8CAA8C;IAC9C,OAAO,EAAE,gBAAgB,CAAC;IAC1B;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB,oFAAoF;IACpF,OAAO,EAAE,MAAM,CAAC;CAChB;AAQD;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,0BAA0B,GAAG,aAAa,CAgE5F"}
|
|
@@ -1,159 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* AI Gateway transport over the Workers AI binding.
|
|
3
|
-
*
|
|
4
|
-
* pi's Cloudflare AI Gateway support speaks HTTPS
|
|
5
|
-
* (`gateway.ai.cloudflare.com/v1/{account}/{gateway}/{provider}/...`, see `api/cloudflare.ts`),
|
|
6
|
-
* which needs a Cloudflare API token even when the caller is a Worker in the gateway's own
|
|
7
|
-
* account.
|
|
8
|
-
*
|
|
9
|
-
* In order to solve for this problem, `createGatewayBindingFetch` returns a {@link FetchFunction}
|
|
10
|
-
* that translates requests under a gateway HTTPS prefix into calls to the Workers AI binding's
|
|
11
|
-
* universal endpoint, `env.AI.gateway(id).run({provider, endpoint, headers, query})`.
|
|
12
|
-
* Binding calls are pre-authenticated in-account and return the provider's native wire format as a
|
|
13
|
-
* regular (streaming) `Response`, so API implementations behave identically over either
|
|
14
|
-
* transport.
|
|
15
|
-
*
|
|
16
|
-
* The result is the transport for one gateway-bound client, not a general-purpose fetch:
|
|
17
|
-
* requests it cannot serve — URLs outside the prefix, or in-prefix requests the universal
|
|
18
|
-
* endpoint cannot express (non-POST, non-JSON body) — reject with a descriptive error.
|
|
19
|
-
* Transport selection is the caller's job, per client: route such traffic over HTTPS with
|
|
20
|
-
* real gateway auth instead of through this shim.
|
|
21
|
-
*/
|
|
22
|
-
/**
|
|
23
|
-
* Placeholder value for auth headers on binding-routed requests. API implementations
|
|
24
|
-
* require an API key or a recognized auth header (`authorization`, `x-api-key`,
|
|
25
|
-
* `cf-aig-authorization`) before dispatch; binding calls are pre-authenticated, so pass
|
|
26
|
-
* `cf-aig-authorization: Bearer ${CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL}` to satisfy
|
|
27
|
-
* the check. The shim strips `cf-aig-authorization` before calling the binding. Pair it with
|
|
28
|
-
* `Authorization: null` / `x-api-key: null` so the SDKs' placeholder auth headers never reach
|
|
29
|
-
* the gateway, which would treat a request-supplied auth header as a BYOK provider key that
|
|
30
|
-
* overrides its stored keys — the same as it would over HTTPS.
|
|
31
|
-
*/
|
|
32
|
-
export const CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL = "cloudflare-gateway-binding";
|
|
33
|
-
// Never forwarded to the binding: hop-by-hop/derived headers, and gateway auth
|
|
34
|
-
// (binding calls are pre-authenticated; the sentinel must not reach the wire).
|
|
35
|
-
const STRIP_HEADERS = new Set(["content-length", "host", "cf-aig-authorization"]);
|
|
36
|
-
/**
|
|
37
|
-
* Create a `fetch` that routes AI Gateway requests through the Workers AI binding.
|
|
38
|
-
* See the module docs for behavior and composition notes.
|
|
39
|
-
*/
|
|
40
|
-
export function createGatewayBindingFetch(options) {
|
|
41
|
-
const { binding, gateway } = options;
|
|
42
|
-
// Prefix matching runs on URL-normalized components (origin + pathname), not raw strings:
|
|
43
|
-
// dot segments resolve away and fragments drop, matching what real fetch would put on the
|
|
44
|
-
// wire, so a lexical variant can't split provider/endpoint differently than HTTPS would.
|
|
45
|
-
const base = new URL(options.baseUrl);
|
|
46
|
-
const basePath = base.pathname.endsWith("/") ? base.pathname : `${base.pathname}/`;
|
|
47
|
-
return async (input, init) => {
|
|
48
|
-
const request = input instanceof Request ? input : undefined;
|
|
49
|
-
const url = request ? request.url : input.toString();
|
|
50
|
-
const method = (init?.method ?? request?.method ?? "GET").toUpperCase();
|
|
51
|
-
let parsed;
|
|
52
|
-
try {
|
|
53
|
-
parsed = new URL(url);
|
|
54
|
-
}
|
|
55
|
-
catch {
|
|
56
|
-
parsed = undefined;
|
|
57
|
-
}
|
|
58
|
-
// Out-of-prefix URLs are a configuration bug, not passthrough traffic: silently
|
|
59
|
-
// forwarding would ship the auth sentinel to whatever host the URL names.
|
|
60
|
-
if (parsed === undefined || parsed.origin !== base.origin || !parsed.pathname.startsWith(basePath)) {
|
|
61
|
-
throw new Error(`createGatewayBindingFetch: ${method} ${url} is outside the configured gateway ` +
|
|
62
|
-
`prefix (${base.origin}${basePath}); this fetch only serves its gateway-bound client`);
|
|
63
|
-
}
|
|
64
|
-
// In-prefix requests the universal endpoint cannot express always reject: forwarding
|
|
65
|
-
// them over HTTPS would send the sentinel to the gateway and fail with a misleading
|
|
66
|
-
// auth error instead of naming the real problem. Callers that need such endpoints
|
|
67
|
-
// route them over HTTPS with real gateway auth themselves.
|
|
68
|
-
const unexpressible = (reason) => {
|
|
69
|
-
throw new Error(`createGatewayBindingFetch: cannot express ${method} ${url} as a universal ` +
|
|
70
|
-
`gateway request (${reason}); route it over HTTPS with gateway auth instead`);
|
|
71
|
-
};
|
|
72
|
-
if (method !== "POST")
|
|
73
|
-
return unexpressible("only POST is supported");
|
|
74
|
-
const rest = parsed.pathname.slice(basePath.length);
|
|
75
|
-
const slash = rest.indexOf("/");
|
|
76
|
-
if (slash <= 0) {
|
|
77
|
-
return unexpressible("missing provider/endpoint path");
|
|
78
|
-
}
|
|
79
|
-
const provider = rest.slice(0, slash);
|
|
80
|
-
// Keep the query string on the endpoint — it's part of what HTTPS would have sent.
|
|
81
|
-
const endpoint = rest.slice(slash + 1) + parsed.search;
|
|
82
|
-
const bodyText = await readBodyText(request, init);
|
|
83
|
-
let query;
|
|
84
|
-
try {
|
|
85
|
-
query = bodyText === undefined ? undefined : JSON.parse(bodyText);
|
|
86
|
-
}
|
|
87
|
-
catch {
|
|
88
|
-
return unexpressible("non-JSON body");
|
|
89
|
-
}
|
|
90
|
-
if (query === undefined) {
|
|
91
|
-
return unexpressible("missing body");
|
|
92
|
-
}
|
|
93
|
-
const headers = collectHeaders(request, init);
|
|
94
|
-
// Per the fetch spec an explicit `signal: null` in init clears a Request input's signal.
|
|
95
|
-
const signal = init?.signal ?? (init && "signal" in init && init.signal === null ? undefined : request?.signal);
|
|
96
|
-
return binding.gateway(gateway).run({ provider, endpoint, headers, query }, signal ? { signal } : {});
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
async function readBodyText(request, init) {
|
|
100
|
-
const body = init?.body;
|
|
101
|
-
if (body === undefined || body === null) {
|
|
102
|
-
// Per the fetch spec an explicit `body: null` in init clears a Request input's body.
|
|
103
|
-
if (init && "body" in init && body === null)
|
|
104
|
-
return undefined;
|
|
105
|
-
if (request && request.body !== null)
|
|
106
|
-
return request.clone().text();
|
|
107
|
-
return undefined;
|
|
108
|
-
}
|
|
109
|
-
if (typeof body === "string")
|
|
110
|
-
return body;
|
|
111
|
-
if (body instanceof Uint8Array)
|
|
112
|
-
return new TextDecoder().decode(body);
|
|
113
|
-
if (body instanceof ArrayBuffer)
|
|
114
|
-
return new TextDecoder().decode(new Uint8Array(body));
|
|
115
|
-
// URLSearchParams, FormData, Blob, ReadableStream in init: read via a Request wrapper.
|
|
116
|
-
// Consuming a one-shot stream here is fine — unexpressible requests reject rather than
|
|
117
|
-
// replay, so nothing downstream needs the body again.
|
|
118
|
-
return new Request("http://body.local", {
|
|
119
|
-
method: "POST",
|
|
120
|
-
body,
|
|
121
|
-
// The fetch spec requires `duplex: "half"` to construct a Request with a stream body
|
|
122
|
-
// (Node's undici enforces it; it is ignored for the replayable body types). TypeScript's
|
|
123
|
-
// RequestInit does not declare the field yet, hence the cast.
|
|
124
|
-
duplex: "half",
|
|
125
|
-
}).text();
|
|
126
|
-
}
|
|
127
|
-
// Entry header names are lowercased so case-variant duplicates collapse and stripping is
|
|
128
|
-
// uniform. Per the fetch spec, `init.headers` replaces a Request input's headers entirely.
|
|
129
|
-
function collectHeaders(request, init) {
|
|
130
|
-
const result = {};
|
|
131
|
-
const add = (key, value) => {
|
|
132
|
-
const name = key.toLowerCase();
|
|
133
|
-
if (!STRIP_HEADERS.has(name))
|
|
134
|
-
result[name] = value;
|
|
135
|
-
};
|
|
136
|
-
const headers = init?.headers;
|
|
137
|
-
if (headers === undefined) {
|
|
138
|
-
if (request) {
|
|
139
|
-
for (const [key, value] of request.headers)
|
|
140
|
-
add(key, value);
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
else if (headers instanceof Headers) {
|
|
144
|
-
for (const [key, value] of headers)
|
|
145
|
-
add(key, value);
|
|
146
|
-
}
|
|
147
|
-
else if (Array.isArray(headers)) {
|
|
148
|
-
for (const [key, value] of headers)
|
|
149
|
-
add(key, value);
|
|
150
|
-
}
|
|
151
|
-
else {
|
|
152
|
-
for (const [key, value] of Object.entries(headers)) {
|
|
153
|
-
if (value !== undefined)
|
|
154
|
-
add(key, String(value));
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
return result;
|
|
158
|
-
}
|
|
159
|
-
//# sourceMappingURL=cloudflare-gateway-binding.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cloudflare-gateway-binding.js","sourceRoot":"","sources":["../../src/api/cloudflare-gateway-binding.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAwBH;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,wCAAwC,GAAG,4BAA4B,CAAC;AAcrF,+EAA+E;AAC/E,+EAA+E;AAC/E,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,CAAC,gBAAgB,EAAE,MAAM,EAAE,sBAAsB,CAAC,CAAC,CAAC;AAIlF;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAmC;IAC5E,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IACrC,0FAA0F;IAC1F,0FAA0F;IAC1F,yFAAyF;IACzF,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IACtC,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAA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C;IAC1C,MAAM,GAAG,GAAG,CAAC,GAAW,EAAE,KAAa,EAAE,EAAE;QAC1C,MAAM,IAAI,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;QAC/B,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC;YAAE,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;IACpD,CAAC,CAAC;IACF,MAAM,OAAO,GAAG,IAAI,EAAE,OAAO,CAAC;IAC9B,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC3B,IAAI,OAAO,EAAE,CAAC;YACb,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,OAAO,CAAC,OAAO;gBAAE,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC7D,CAAC;IACF,CAAC;SAAM,IAAI,OAAO,YAAY,OAAO,EAAE,CAAC;QACvC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,OAAO;YAAE,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACrD,CAAC;SAAM,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACnC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,OAAO;YAAE,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACrD,CAAC;SAAM,CAAC;QACP,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;YACpD,IAAI,KAAK,KAAK,SAAS;gBAAE,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QAClD,CAAC;IACF,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["/**\n * AI Gateway transport over the Workers AI binding.\n *\n * pi's Cloudflare AI Gateway support speaks HTTPS\n * (`gateway.ai.cloudflare.com/v1/{account}/{gateway}/{provider}/...`, see `api/cloudflare.ts`),\n * which needs a Cloudflare API token even when the caller is a Worker in the gateway's own\n * account.\n *\n * In order to solve for this problem, `createGatewayBindingFetch` returns a {@link FetchFunction}\n * that translates requests under a gateway HTTPS prefix into calls to the Workers AI binding's\n * universal endpoint, `env.AI.gateway(id).run({provider, endpoint, headers, query})`.\n * Binding calls are pre-authenticated in-account and return the provider's native wire format as a\n * regular (streaming) `Response`, so API implementations behave identically over either\n * transport.\n *\n * The result is the transport for one gateway-bound client, not a general-purpose fetch:\n * requests it cannot serve — URLs outside the prefix, or in-prefix requests the universal\n * endpoint cannot express (non-POST, non-JSON body) — reject with a descriptive error.\n * Transport selection is the caller's job, per client: route such traffic over HTTPS with\n * real gateway auth instead of through this shim.\n */\n\nimport type { FetchFunction } from \"../types.ts\";\n\n/**\n * Structural type for the Workers AI binding's gateway surface (`env.AI`), so this\n * module does not depend on `@cloudflare/workers-types`. Any real `Ai` binding satisfies it.\n */\nexport interface AiGatewayBinding {\n\tgateway(id: string): AiGatewayBindingGateway;\n}\n\nexport interface AiGatewayBindingGateway {\n\trun(data: AiGatewayUniversalRequestLike, options?: { signal?: AbortSignal }): Promise<Response>;\n}\n\n/** One universal-endpoint request entry, as accepted by `AiGateway.run()`. */\nexport interface AiGatewayUniversalRequestLike {\n\tprovider: string;\n\tendpoint: string;\n\theaders: Record<string, string>;\n\tquery: unknown;\n}\n\n/**\n * Placeholder value for auth headers on binding-routed requests. API implementations\n * require an API key or a recognized auth header (`authorization`, `x-api-key`,\n * `cf-aig-authorization`) before dispatch; binding calls are pre-authenticated, so pass\n * `cf-aig-authorization: Bearer ${CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL}` to satisfy\n * the check. The shim strips `cf-aig-authorization` before calling the binding. Pair it with\n * `Authorization: null` / `x-api-key: null` so the SDKs' placeholder auth headers never reach\n * the gateway, which would treat a request-supplied auth header as a BYOK provider key that\n * overrides its stored keys — the same as it would over HTTPS.\n */\nexport const CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL = \"cloudflare-gateway-binding\";\n\nexport interface GatewayBindingFetchOptions {\n\t/** The Workers AI binding (e.g. `env.AI`). */\n\tbinding: AiGatewayBinding;\n\t/**\n\t * Gateway HTTPS prefix every request must fall under, without a trailing slash:\n\t * `https://gateway.ai.cloudflare.com/v1/{accountId}/{gatewayName}`.\n\t */\n\tbaseUrl: string;\n\t/** Gateway name passed to `binding.gateway()`. Must match the `baseUrl` gateway. */\n\tgateway: string;\n}\n\n// Never forwarded to the binding: hop-by-hop/derived headers, and gateway auth\n// (binding calls are pre-authenticated; the sentinel must not reach the wire).\nconst STRIP_HEADERS = new Set([\"content-length\", \"host\", \"cf-aig-authorization\"]);\n\ntype FetchInput = Parameters<FetchFunction>[0];\n\n/**\n * Create a `fetch` that routes AI Gateway requests through the Workers AI binding.\n * See the module docs for behavior and composition notes.\n */\nexport function createGatewayBindingFetch(options: GatewayBindingFetchOptions): FetchFunction {\n\tconst { binding, gateway } = options;\n\t// Prefix matching runs on URL-normalized components (origin + pathname), not raw strings:\n\t// dot segments resolve away and fragments drop, matching what real fetch would put on the\n\t// wire, so a lexical variant can't split provider/endpoint differently than HTTPS would.\n\tconst base = new URL(options.baseUrl);\n\tconst basePath = base.pathname.endsWith(\"/\") ? base.pathname : `${base.pathname}/`;\n\n\treturn async (input: FetchInput, init?: RequestInit): Promise<Response> => {\n\t\tconst request = input instanceof Request ? input : undefined;\n\t\tconst url = request ? request.url : input.toString();\n\t\tconst method = (init?.method ?? request?.method ?? \"GET\").toUpperCase();\n\t\tlet parsed: URL | undefined;\n\t\ttry {\n\t\t\tparsed = new URL(url);\n\t\t} catch {\n\t\t\tparsed = undefined;\n\t\t}\n\t\t// Out-of-prefix URLs are a configuration bug, not passthrough traffic: silently\n\t\t// forwarding would ship the auth sentinel to whatever host the URL names.\n\t\tif (parsed === undefined || parsed.origin !== base.origin || !parsed.pathname.startsWith(basePath)) {\n\t\t\tthrow new Error(\n\t\t\t\t`createGatewayBindingFetch: ${method} ${url} is outside the configured gateway ` +\n\t\t\t\t\t`prefix (${base.origin}${basePath}); this fetch only serves its gateway-bound client`,\n\t\t\t);\n\t\t}\n\n\t\t// In-prefix requests the universal endpoint cannot express always reject: forwarding\n\t\t// them over HTTPS would send the sentinel to the gateway and fail with a misleading\n\t\t// auth error instead of naming the real problem. Callers that need such endpoints\n\t\t// route them over HTTPS with real gateway auth themselves.\n\t\tconst unexpressible = (reason: string): never => {\n\t\t\tthrow new Error(\n\t\t\t\t`createGatewayBindingFetch: cannot express ${method} ${url} as a universal ` +\n\t\t\t\t\t`gateway request (${reason}); route it over HTTPS with gateway auth instead`,\n\t\t\t);\n\t\t};\n\t\tif (method !== \"POST\") return unexpressible(\"only POST is supported\");\n\n\t\tconst rest = parsed.pathname.slice(basePath.length);\n\t\tconst slash = rest.indexOf(\"/\");\n\t\tif (slash <= 0) {\n\t\t\treturn unexpressible(\"missing provider/endpoint path\");\n\t\t}\n\t\tconst provider = rest.slice(0, slash);\n\t\t// Keep the query string on the endpoint — it's part of what HTTPS would have sent.\n\t\tconst endpoint = rest.slice(slash + 1) + parsed.search;\n\n\t\tconst bodyText = await readBodyText(request, init);\n\t\tlet query: unknown;\n\t\ttry {\n\t\t\tquery = bodyText === undefined ? undefined : JSON.parse(bodyText);\n\t\t} catch {\n\t\t\treturn unexpressible(\"non-JSON body\");\n\t\t}\n\t\tif (query === undefined) {\n\t\t\treturn unexpressible(\"missing body\");\n\t\t}\n\n\t\tconst headers = collectHeaders(request, init);\n\t\t// Per the fetch spec an explicit `signal: null` in init clears a Request input's signal.\n\t\tconst signal = init?.signal ?? (init && \"signal\" in init && init.signal === null ? undefined : request?.signal);\n\t\treturn binding.gateway(gateway).run({ provider, endpoint, headers, query }, signal ? { signal } : {});\n\t};\n}\n\nasync function readBodyText(request: Request | undefined, init?: RequestInit): Promise<string | undefined> {\n\tconst body = init?.body;\n\tif (body === undefined || body === null) {\n\t\t// Per the fetch spec an explicit `body: null` in init clears a Request input's body.\n\t\tif (init && \"body\" in init && body === null) return undefined;\n\t\tif (request && request.body !== null) return request.clone().text();\n\t\treturn undefined;\n\t}\n\tif (typeof body === \"string\") return body;\n\tif (body instanceof Uint8Array) return new TextDecoder().decode(body);\n\tif (body instanceof ArrayBuffer) return new TextDecoder().decode(new Uint8Array(body));\n\t// URLSearchParams, FormData, Blob, ReadableStream in init: read via a Request wrapper.\n\t// Consuming a one-shot stream here is fine — unexpressible requests reject rather than\n\t// replay, so nothing downstream needs the body again.\n\treturn new Request(\"http://body.local\", {\n\t\tmethod: \"POST\",\n\t\tbody,\n\t\t// The fetch spec requires `duplex: \"half\"` to construct a Request with a stream body\n\t\t// (Node's undici enforces it; it is ignored for the replayable body types). TypeScript's\n\t\t// RequestInit does not declare the field yet, hence the cast.\n\t\tduplex: \"half\",\n\t} as RequestInit).text();\n}\n\n// Entry header names are lowercased so case-variant duplicates collapse and stripping is\n// uniform. Per the fetch spec, `init.headers` replaces a Request input's headers entirely.\nfunction collectHeaders(request: Request | undefined, init?: RequestInit): Record<string, string> {\n\tconst result: Record<string, string> = {};\n\tconst add = (key: string, value: string) => {\n\t\tconst name = key.toLowerCase();\n\t\tif (!STRIP_HEADERS.has(name)) result[name] = value;\n\t};\n\tconst headers = init?.headers;\n\tif (headers === undefined) {\n\t\tif (request) {\n\t\t\tfor (const [key, value] of request.headers) add(key, value);\n\t\t}\n\t} else if (headers instanceof Headers) {\n\t\tfor (const [key, value] of headers) add(key, value);\n\t} else if (Array.isArray(headers)) {\n\t\tfor (const [key, value] of headers) add(key, value);\n\t} else {\n\t\tfor (const [key, value] of Object.entries(headers)) {\n\t\t\tif (value !== undefined) add(key, String(value));\n\t\t}\n\t}\n\treturn result;\n}\n"]}
|