@bastani/atomic 0.9.45 → 0.9.46-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.
- package/CHANGELOG.md +34 -0
- package/dist/builtin/intercom/CHANGELOG.md +11 -0
- package/dist/builtin/intercom/broker/broker.ts +124 -10
- package/dist/builtin/intercom/broker/client.ts +177 -25
- package/dist/builtin/intercom/broker/multinode-router.ts +228 -27
- package/dist/builtin/intercom/broker/multinode-state-store.ts +10 -0
- package/dist/builtin/intercom/broker/recipient-receipts.ts +38 -4
- package/dist/builtin/intercom/broker/send-handler.ts +9 -2
- package/dist/builtin/intercom/broker/sql-outbox-store.ts +29 -4
- package/dist/builtin/intercom/group.ts +25 -0
- package/dist/builtin/intercom/index.bundle.mjs +177 -35
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/intercom/retry-policy.ts +7 -0
- package/dist/builtin/intercom/types.ts +21 -0
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +10 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +150 -54
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +39 -0
- package/dist/builtin/workflows/builtin/{chunk-6901nsd6.js → chunk-6jpwc09k.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-vwx023ge.js → chunk-qhm35ntx.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-jvna28mq.js → chunk-zhyqnf5g.js} +331 -68
- package/dist/builtin/workflows/builtin/goal.js +2 -2
- package/dist/builtin/workflows/builtin/index.js +3 -3
- package/dist/builtin/workflows/builtin/ralph.js +2 -2
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/skills/prompt-engineer/SKILL.md +1 -0
- package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6.md +2 -2
- package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6_1_sol.md +2 -2
- package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6_1_terra.md +77 -0
- package/dist/builtin/workflows/src/authoring.d.ts +1 -1
- package/dist/builtin/workflows/src/durable/journal/internal.d.ts +2 -0
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +7076 -3386
- package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +11075 -7261
- package/dist/builtin/workflows/src/index.js +6768 -3605
- package/dist/builtin/workflows/src/local-worker-entry.mjs +11075 -7261
- package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +19 -0
- package/dist/core/agent-session-boundaries.d.ts.map +1 -1
- package/dist/core/agent-session-boundaries.js +1 -0
- package/dist/core/agent-session-boundaries.js.map +1 -1
- package/dist/core/agent-session-events.d.ts.map +1 -1
- package/dist/core/agent-session-events.js +2 -1
- package/dist/core/agent-session-events.js.map +1 -1
- package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
- package/dist/core/agent-session-extension-bindings.js +15 -2
- package/dist/core/agent-session-extension-bindings.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +3 -2
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts +4 -2
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +13 -8
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/agent-session-recovery.d.ts.map +1 -1
- package/dist/core/agent-session-recovery.js +92 -1
- package/dist/core/agent-session-recovery.js.map +1 -1
- package/dist/core/agent-session-transfer.d.ts.map +1 -1
- package/dist/core/agent-session-transfer.js +5 -0
- package/dist/core/agent-session-transfer.js.map +1 -1
- package/dist/core/agent-session.d.ts +2 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +2 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/copilot-errors.d.ts +6 -0
- package/dist/core/copilot-errors.d.ts.map +1 -0
- package/dist/core/copilot-errors.js +17 -0
- package/dist/core/copilot-errors.js.map +1 -0
- package/dist/core/execution-model-router.d.ts.map +1 -1
- package/dist/core/execution-model-router.js +12 -2
- package/dist/core/execution-model-router.js.map +1 -1
- package/dist/core/extensions/context-types.d.ts +7 -0
- package/dist/core/extensions/context-types.d.ts.map +1 -1
- package/dist/core/extensions/context-types.js.map +1 -1
- package/dist/core/extensions/runner-context.d.ts.map +1 -1
- package/dist/core/extensions/runner-context.js +6 -0
- package/dist/core/extensions/runner-context.js.map +1 -1
- package/dist/core/extensions/workflow-activity-hub.d.ts +4 -0
- package/dist/core/extensions/workflow-activity-hub.d.ts.map +1 -1
- package/dist/core/extensions/workflow-activity-hub.js +26 -5
- package/dist/core/extensions/workflow-activity-hub.js.map +1 -1
- package/dist/core/extensions/workflow-events.d.ts +5 -0
- package/dist/core/extensions/workflow-events.d.ts.map +1 -1
- package/dist/core/extensions/workflow-events.js.map +1 -1
- package/dist/core/messages.d.ts +5 -0
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +1 -1
- package/dist/core/messages.js.map +1 -1
- package/dist/core/model-fallback-failures.d.ts +1 -1
- package/dist/core/model-fallback-failures.d.ts.map +1 -1
- package/dist/core/model-fallback-failures.js +37 -3
- package/dist/core/model-fallback-failures.js.map +1 -1
- package/dist/core/model-runtime-streaming.js +2 -2
- package/dist/core/model-runtime-streaming.js.map +1 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +19 -11
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/provider-rate-limits.d.ts +55 -6
- package/dist/core/provider-rate-limits.d.ts.map +1 -1
- package/dist/core/provider-rate-limits.js +182 -29
- package/dist/core/provider-rate-limits.js.map +1 -1
- package/dist/core/provider-request-admission.d.ts.map +1 -1
- package/dist/core/provider-request-admission.js +42 -18
- package/dist/core/provider-request-admission.js.map +1 -1
- package/dist/core/storage/node-sqlite.d.ts.map +1 -1
- package/dist/core/storage/node-sqlite.js +176 -19
- package/dist/core/storage/node-sqlite.js.map +1 -1
- package/dist/core/storage/provider.d.ts +4 -2
- package/dist/core/storage/provider.d.ts.map +1 -1
- package/dist/core/storage/provider.js +94 -5
- package/dist/core/storage/provider.js.map +1 -1
- package/dist/core/structured-output/index.d.ts.map +1 -1
- package/dist/core/structured-output/index.js +15 -8
- package/dist/core/structured-output/index.js.map +1 -1
- package/dist/core/structured-output/provider-failure.d.ts +17 -0
- package/dist/core/structured-output/provider-failure.d.ts.map +1 -0
- package/dist/core/structured-output/provider-failure.js +28 -0
- package/dist/core/structured-output/provider-failure.js.map +1 -0
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +13 -7
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/shell-task-render.d.ts +1 -0
- package/dist/core/tools/shell-task-render.d.ts.map +1 -1
- package/dist/core/tools/shell-task-render.js +7 -2
- package/dist/core/tools/shell-task-render.js.map +1 -1
- package/dist/extensions/tool-search/tool.d.ts +5 -0
- package/dist/extensions/tool-search/tool.d.ts.map +1 -1
- package/dist/extensions/tool-search/tool.js +38 -5
- package/dist/extensions/tool-search/tool.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-actions.js +3 -2
- package/dist/modes/interactive/components/chat-session-host-actions.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +42 -14
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/interactive-extension-context.js +2 -1
- package/dist/modes/interactive/interactive-extension-context.js.map +1 -1
- package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-startup.js +5 -6
- package/dist/modes/interactive/interactive-startup.js.map +1 -1
- package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client-process.js +8 -1
- package/dist/modes/rpc/rpc-client-process.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +7 -1
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/utils/ansi.d.ts +2 -0
- package/dist/utils/ansi.d.ts.map +1 -1
- package/dist/utils/ansi.js +5 -0
- package/dist/utils/ansi.js.map +1 -1
- package/docs/codemode.md +1 -1
- package/docs/intercom/reference.md +3 -3
- package/docs/models/evals.md +31 -12
- package/docs/models/reference.md +23 -51
- package/docs/models.md +3 -4
- package/docs/providers.md +5 -15
- package/docs/settings.md +1 -1
- package/docs/storage.md +2 -2
- package/docs/tools.md +1 -1
- package/docs/workflows/api-reference.md +20 -1
- package/docs/workflows/operations.md +17 -4
- package/npm-shrinkwrap.json +64 -44
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-fallback-failures.js","sourceRoot":"","sources":["../../src/core/model-fallback-failures.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAE3E,MAAM,gCAAgC,GAAsB;IAC3D,eAAe;IACf,wBAAwB;IACxB,SAAS;IACT,QAAQ;IACR,oBAAoB;IACpB,UAAU;IACV,SAAS;IACT,gCAAgC;IAChC,kBAAkB;IAClB,YAAY;IACZ,gBAAgB;IAChB,sBAAsB;IACtB,sCAAsC;IACtC,+CAA+C;IAC/C,YAAY;IACZ,gBAAgB;IAChB,aAAa;IACb,4BAA4B;IAC5B,wBAAwB;IACxB,UAAU;IACV,QAAQ;IACR,cAAc;IACd,YAAY;IACZ,YAAY;IACZ,SAAS;IACT,uBAAuB;IACvB,WAAW;IACX,UAAU;IACV,cAAc;IACd,aAAa;IACb,aAAa;IACb,4BAA4B;IAC5B,gBAAgB;IAChB,kBAAkB;IAClB,oBAAoB;IACpB,mBAAmB;IACnB,oBAAoB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IAAI,KAAK,SAAS;QACzB,MAAM,CAAC,IAAI,KAAK,SAAS;QACzB,CAAC,gCAAgC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAEjF,OAAO,KAAK,CAAC;IACd,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/**\n * Shared model/provider failure classification.\n *\n * Workflows, subagents, and the main chat all need the same decision about\n * whether a provider failure may spend another model candidate. Keep this\n * module free of AgentSession and workflow imports so the published SDK can\n * expose it to the raw-TypeScript companion packages without a cycle.\n */\n\nimport { isExtensionStartupFailure } from \"./extension-startup-failure.ts\";\n\nconst RETRYABLE_MODEL_FAILURE_PATTERNS: readonly RegExp[] = [\n\t/rate\\s*limit/i,\n\t/too\\s*many\\s*requests/i,\n\t/\\b429\\b/,\n\t/quota/i,\n\t/usage[\\s_-]*limit/i,\n\t/billing/i,\n\t/credit/i,\n\t/auth(?:entication|orization)?/i,\n\t/unauthori[sz]ed/i,\n\t/\\b40[13]\\b/,\n\t/api[_\\s-]*key/i,\n\t/token[_\\s-]*expired/i,\n\t/token[_\\s-]*(?:revoked|invalidated)/i,\n\t/invalidated[_\\s-]+(?:oauth|auth)[_\\s-]+token/i,\n\t/forbidden/i,\n\t/invalid\\s*key/i,\n\t/overloaded/i,\n\t/temporarily\\s*unavailable/i,\n\t/service\\s*unavailable/i,\n\t/network/i,\n\t/fetch/i,\n\t/getaddrinfo/i,\n\t/ENOTFOUND/i,\n\t/EAI_AGAIN/i,\n\t/socket/i,\n\t/connection\\s*refused/i,\n\t/upstream/i,\n\t/timeout/i,\n\t/timed\\s*out/i,\n\t/\\b50[0-4]\\b/,\n\t/\\b52[0-4]\\b/,\n\t/provider.?returned.?error/i,\n\t/server.?error/i,\n\t/internal.?error/i,\n\t/connection.?error/i,\n\t/connection.?lost/i,\n\t/connection.?reset/i,\n\t/ECONNRESET/i,\n\t/other side closed/i,\n\t/websocket.?closed/i,\n\t/websocket.?error/i,\n\t/reset before headers/i,\n\t/socket hang up/i,\n\t/ended without/i,\n\t/stream ended before message_stop/i,\n\t/stream ended before a terminal response event/i,\n\t/http2 request did not get a response/i,\n\t/pending stream has been canceled/i,\n\t/retry delay/i,\n\t/finish.?reason:?\\s*error/i,\n\t/terminated/i,\n\t/you can retry your request/i,\n\t/try your request again/i,\n\t/please retry your request/i,\n\t// gRPC based providers (e.g. NVIDIA NIM); upstream pi-ai retries this too.\n\t/ResourceExhausted/i,\n];\n\nconst NON_RETRYABLE_FAILURE_PATTERNS: readonly RegExp[] = [\n\t/command failed/i,\n\t/tests? failed/i,\n\t/shell/i,\n\t/missing file/i,\n\t/no such file/i,\n\t/cancel/i,\n\t/abort/i,\n\t/interrupted/i,\n];\n\nconst CANCELLED_FAILURE_PATTERNS: readonly RegExp[] = [/cancel/i, /abort/i, /interrupted/i];\n\nconst TRANSPORT_CANCELLATION_FAILURE_PATTERNS: readonly RegExp[] = [\n\t/getaddrinfo|ENOTFOUND|EAI_AGAIN/i,\n\t/pending stream has been canceled/i,\n];\n\nexport type ModelFallbackFailureKind =\n\t| \"auth_on_candidate_provider\"\n\t| \"rate_limit\"\n\t| \"provider_unavailable\"\n\t| \"network_timeout\"\n\t| \"transport_error\"\n\t| \"model_unavailable\"\n\t| \"request_incompatible\"\n\t| \"cancelled\"\n\t| \"task_failure\"\n\t| \"unknown\";\n\nexport type ModelFallbackFailureSource =\n\t| \"assistant_message\"\n\t| \"diagnostic\"\n\t| \"throw\"\n\t| \"structured\"\n\t| \"string_fallback\";\n\nexport interface ModelFallbackFailureSignal {\n\treadonly kind: ModelFallbackFailureKind;\n\treadonly message: string;\n\treadonly source: ModelFallbackFailureSource;\n\treadonly stopReason?: string;\n\treadonly status?: number;\n\treadonly code?: string | number;\n\treadonly name?: string;\n}\n\nconst FALLBACKABLE_FAILURE_KINDS: ReadonlySet<ModelFallbackFailureKind> = new Set([\n\t\"auth_on_candidate_provider\",\n\t\"rate_limit\",\n\t\"provider_unavailable\",\n\t\"network_timeout\",\n\t\"transport_error\",\n\t\"model_unavailable\",\n\t\"request_incompatible\",\n]);\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn value !== null && typeof value === \"object\" ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction field(value: unknown, key: string): unknown {\n\treturn asRecord(value)?.[key];\n}\n\nfunction stringField(value: unknown, key: string): string | undefined {\n\tconst raw = field(value, key);\n\treturn typeof raw === \"string\" && raw.trim().length > 0 ? raw : undefined;\n}\n\nfunction errorName(value: unknown): string | undefined {\n\treturn value instanceof Error ? value.name : stringField(value, \"name\");\n}\n\nfunction directMessageFrom(value: unknown): string | undefined {\n\treturn stringField(value, \"errorMessage\") ?? stringField(value, \"message\") ?? stringField(value, \"statusText\");\n}\n\nfunction integerFrom(value: unknown): number | undefined {\n\tif (typeof value === \"number\" && Number.isInteger(value)) return value;\n\tif (typeof value !== \"string\" || value.trim().length === 0) return undefined;\n\tconst parsed = Number(value.trim());\n\treturn Number.isInteger(parsed) ? parsed : undefined;\n}\n\nfunction statusFrom(value: unknown): number | undefined {\n\treturn (\n\t\tintegerFrom(field(value, \"status\")) ??\n\t\tintegerFrom(field(value, \"statusCode\")) ??\n\t\tintegerFrom(field(value, \"httpStatus\"))\n\t);\n}\n\nfunction codeFrom(value: unknown): string | number | undefined {\n\tconst rawCode = field(value, \"code\");\n\treturn typeof rawCode === \"string\" || typeof rawCode === \"number\" ? rawCode : undefined;\n}\n\nfunction stopReasonFrom(value: unknown): string | undefined {\n\treturn stringField(value, \"stopReason\");\n}\n\nfunction finishReasonFrom(value: unknown): string | undefined {\n\treturn stringField(value, \"finish_reason\") ?? stringField(value, \"finishReason\");\n}\n\nfunction causeOf(value: unknown): unknown {\n\treturn value instanceof Error ? value.cause : field(value, \"cause\");\n}\n\nfunction diagnosticErrors(value: unknown): readonly unknown[] {\n\tconst diagnostics = field(value, \"diagnostics\");\n\tif (!Array.isArray(diagnostics)) return [];\n\tconst errors: unknown[] = [];\n\tfor (const diagnostic of diagnostics) {\n\t\tconst diagnosticType = stringField(diagnostic, \"type\");\n\t\tconst diagnosticError = field(diagnostic, \"error\");\n\t\terrors.push(\n\t\t\tnormalizeCode(diagnosticType) === \"provider_transport_failure\" ? diagnostic : (diagnosticError ?? diagnostic),\n\t\t);\n\t}\n\treturn errors;\n}\n\nfunction normalizeCode(value: string | number | undefined): string | undefined {\n\tif (value === undefined) return undefined;\n\tconst raw = String(value).trim().toLowerCase();\n\tif (!raw) return undefined;\n\tlet normalized = \"\";\n\tlet needsSeparator = false;\n\tfor (const char of raw) {\n\t\tconst code = char.charCodeAt(0);\n\t\tconst isLowerAlpha = code >= 97 && code <= 122;\n\t\tconst isDigit = code >= 48 && code <= 57;\n\t\tif (isLowerAlpha || isDigit) {\n\t\t\tnormalized += char;\n\t\t\tneedsSeparator = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (needsSeparator && normalized[normalized.length - 1] !== \"_\") normalized += \"_\";\n\t}\n\tif (normalized.endsWith(\"_\")) normalized = normalized.slice(0, -1);\n\treturn normalized.length > 0 ? normalized : undefined;\n}\n\nfunction messageLooksLikeModelUnavailable(message: string): boolean {\n\tconst lower = message.toLowerCase();\n\treturn (\n\t\tlower.includes(\"model\") &&\n\t\t(lower.includes(\"unavailable\") ||\n\t\t\tlower.includes(\"disabled\") ||\n\t\t\tlower.includes(\"not found\") ||\n\t\t\tlower.includes(\"unknown\"))\n\t);\n}\n\nfunction kindFromStatus(status: number | undefined): ModelFallbackFailureKind | undefined {\n\tswitch (status) {\n\t\tcase 400:\n\t\tcase 413:\n\t\tcase 422:\n\t\t\treturn \"request_incompatible\";\n\t\tcase 401:\n\t\tcase 403:\n\t\t\treturn \"auth_on_candidate_provider\";\n\t\tcase 408:\n\t\t\treturn \"network_timeout\";\n\t\tcase 404:\n\t\t\treturn \"model_unavailable\";\n\t\tcase 429:\n\t\t\treturn \"rate_limit\";\n\t\tdefault:\n\t\t\tif (status !== undefined && status >= 500 && status <= 599) return \"provider_unavailable\";\n\t\t\treturn undefined;\n\t}\n}\n\nfunction refusalKindFromCode(code: string | number | undefined): ModelFallbackFailureKind | undefined {\n\tconst normalizedCode = normalizeCode(code);\n\tif (normalizedCode === undefined) return undefined;\n\tif (normalizedCode.includes(\"content_filter\") || normalizedCode.includes(\"contentfilter\")) return \"task_failure\";\n\tif (normalizedCode.includes(\"safety\") || normalizedCode.includes(\"policy\")) return \"task_failure\";\n\tswitch (normalizedCode) {\n\t\tcase \"blocked\":\n\t\tcase \"blocked_by_provider\":\n\t\tcase \"blocked_by_safety\":\n\t\tcase \"blocked_by_policy\":\n\t\tcase \"provider_refusal\":\n\t\tcase \"refusal\":\n\t\tcase \"tool_refusal\":\n\t\tcase \"tool_call_refusal\":\n\t\tcase \"tool_use_refusal\":\n\t\t\treturn \"task_failure\";\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nconst REQUEST_INCOMPATIBLE_CODES: ReadonlySet<string> = new Set([\n\t\"invalid_request\",\n\t\"invalid_request_error\",\n\t\"bad_request\",\n\t\"context_length_exceeded\",\n\t\"request_too_large\",\n\t\"too_large\",\n\t\"request_entity_too_large\",\n\t\"max_tokens\",\n\t\"max_context_length\",\n\t\"context_window_exceeded\",\n]);\n\nfunction requestIncompatibleKindFromCode(code: string | number | undefined): ModelFallbackFailureKind | undefined {\n\tconst normalized = normalizeCode(code);\n\treturn normalized !== undefined && REQUEST_INCOMPATIBLE_CODES.has(normalized) ? \"request_incompatible\" : undefined;\n}\n\nfunction kindFromCode(code: string | number | undefined): ModelFallbackFailureKind | undefined {\n\tconst normalizedCode = normalizeCode(code);\n\tif (normalizedCode === undefined) return undefined;\n\tconst refusalKind = refusalKindFromCode(code);\n\tif (refusalKind !== undefined) return refusalKind;\n\tconst httpStatusKind = kindFromStatus(integerFrom(code));\n\tif (httpStatusKind !== undefined) return httpStatusKind;\n\tconst requestIncompatibleKind = requestIncompatibleKindFromCode(code);\n\tif (requestIncompatibleKind !== undefined) return requestIncompatibleKind;\n\n\tswitch (normalizedCode) {\n\t\tcase \"auth\":\n\t\tcase \"auth_required\":\n\t\tcase \"authentication_required\":\n\t\tcase \"unauthorized\":\n\t\tcase \"forbidden\":\n\t\tcase \"invalid_api_key\":\n\t\tcase \"missing_api_key\":\n\t\tcase \"invalid_key\":\n\t\tcase \"token_expired\":\n\t\tcase \"token_revoked\":\n\t\tcase \"token_invalidated\":\n\t\tcase \"oauth_token_invalidated\":\n\t\t\treturn \"auth_on_candidate_provider\";\n\t\tcase \"etimedout\":\n\t\tcase \"econnreset\":\n\t\tcase \"econnrefused\":\n\t\tcase \"enotfound\":\n\t\tcase \"eai_again\":\n\t\tcase \"fetch_failed\":\n\t\tcase \"network_error\":\n\t\tcase \"timeout\":\n\t\tcase \"timeout_error\":\n\t\tcase \"und_err_connect_timeout\":\n\t\t\treturn \"network_timeout\";\n\t\tcase \"rate_limit\":\n\t\tcase \"rate_limit_exceeded\":\n\t\tcase \"too_many_requests\":\n\t\tcase \"quota_exceeded\":\n\t\tcase \"insufficient_quota\":\n\t\tcase \"usage_limit\":\n\t\tcase \"usage_limit_reached\":\n\t\tcase \"usage_limit_exceeded\":\n\t\t\treturn \"rate_limit\";\n\t\tcase \"aborterror\":\n\t\tcase \"aborted\":\n\t\tcase \"cancelled\":\n\t\tcase \"canceled\":\n\t\t\treturn \"cancelled\";\n\t\tcase \"model_not_found\":\n\t\tcase \"model_unavailable\":\n\t\tcase \"model_disabled\":\n\t\tcase \"unknown_model\":\n\t\t\treturn \"model_unavailable\";\n\t\tcase \"provider_error\":\n\t\tcase \"api_error\":\n\t\tcase \"service_unavailable\":\n\t\tcase \"temporarily_unavailable\":\n\t\tcase \"overloaded\":\n\t\t\treturn \"provider_unavailable\";\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nconst REQUEST_INCOMPATIBLE_FAILURE_PATTERNS: readonly RegExp[] = [\n\t/\\bcontext[_\\s-]?length(?:[_\\s-]?exceeded)?\\b/i,\n\t/\\bcontext[_\\s-]?window(?:[_\\s-]?exceeded)?\\b/i,\n\t/\\bmax[_\\s-]?context\\b/i,\n\t/\\bmax[_\\s-]?tokens?\\b/i,\n\t/\\brequest(?:[_\\s-]?entity)?[_\\s-]?too[_\\s-]?large\\b/i,\n\t/\\btoo[_\\s-]?large\\b/i,\n\t/\\b(?:unsupported|unknown|invalid)\\s+(?:tool|parameter|function)\\b/i,\n\t/\\b(?:tool|parameter|function)\\s+(?:not\\s+(?:supported|found|allowed)|unknown|invalid)\\b/i,\n\t/\\binvalid[_\\s-]?request(?:[_\\s-]?error)?\\b/i,\n\t/\\bbad[_\\s-]?request\\b/i,\n];\n\nconst PROVIDER_REFUSAL_FAILURE_PATTERNS: readonly RegExp[] = [\n\t/\\bthe\\s+model\\s+refused\\s+to\\s+complete\\s+the\\s+request\\b/i,\n\t/\\bfinish[_\\s-]?reason\\b[^\\n]*\\bcontent[_\\s-]?filter\\b/i,\n\t/\\bcontent[_\\s-]?filter(?:ed|ing)?\\b/i,\n\t/\\b(?:safety|policy)\\b[^\\n]*\\b(?:refus(?:e|al|ed|es|ing)?|block(?:ed|ing)?|filter(?:ed|ing)?|violat(?:e|ion|ed|ing)?|disallow(?:ed|ing)?|reject(?:ed|ion|ing)?)\\b/i,\n\t/\\b(?:refus(?:e|al|ed|es|ing)?|block(?:ed|ing)?|filter(?:ed|ing)?|violat(?:e|ion|ed|ing)?|disallow(?:ed|ing)?|reject(?:ed|ion|ing)?)\\b[^\\n]*\\b(?:safety|policy)\\b/i,\n\t/\\btool[_\\s-]?(?:call|use)?[_\\s-]?refus(?:e|al|ed|es|ing)?\\b/i,\n\t/\\btool(?:\\s+call|\\s+use)?\\b[^\\n]*\\brefus(?:e|al|ed|es|ing)?\\b/i,\n\t/\\brefus(?:e|al|ed|es|ing)?\\b[^\\n]*\\btool(?:\\s+call|\\s+use)?\\b/i,\n\t/\\bprovider[_\\s-]?refus(?:e|al|ed|es|ing)?\\b/i,\n\t/\\bprovider\\b[^\\n]*\\brefus(?:e|al|ed|es|ing)?\\b[^\\n]*\\b(?:prompt|request|content|policy|safety)\\b/i,\n];\n\nconst TRANSPORT_OUTAGE_FAILURE_PATTERNS: readonly RegExp[] = [\n\t/^connection\\s+error\\.?$/i,\n\t/^fetch\\s+failed\\.?$/i,\n\t// Response-body decompression failures reported by Node/Bun zlib, optionally\n\t// behind the fetch/WebSocket layer's \"Library error:\" wrapper. GitHub Copilot\n\t// on the default `transport: \"auto\"` surfaces this as\n\t// \"Library error: zlib error: incorrect header check\" (#2553). These are\n\t// unanchored because the wrapper text varies by runtime and transport. `zlib`\n\t// has no trailing word boundary on purpose: Bun 1.4.0, the shipped runtime\n\t// when verified, throws `ZlibError fetching \"...\"` as one word.\n\t/\\bzlib/i,\n\t/\\bincorrect\\s+header\\s+check\\b/i,\n\t/\\bdecompress(?:ion|ing|ed)?\\b/i,\n\t/^library\\s+error\\b/i,\n\t// Idle-stream deadline enforced below the HTTP layer by pi-ai's\n\t// `withStreamDeadline`, so a stalled stream fails over instead of hanging.\n\t/\\bstream\\s+deadline\\s+exceeded\\b/i,\n];\n\nfunction transportOutageKindFromMessage(message: string): ModelFallbackFailureKind | undefined {\n\treturn TRANSPORT_OUTAGE_FAILURE_PATTERNS.some((pattern) => pattern.test(message.trim()))\n\t\t? \"transport_error\"\n\t\t: undefined;\n}\n\nfunction refusalKindFromMessage(message: string): ModelFallbackFailureKind | undefined {\n\tif (TRANSPORT_CANCELLATION_FAILURE_PATTERNS.some((pattern) => pattern.test(message))) return \"network_timeout\";\n\tif (CANCELLED_FAILURE_PATTERNS.some((pattern) => pattern.test(message))) return \"cancelled\";\n\tif (NON_RETRYABLE_FAILURE_PATTERNS.some((pattern) => pattern.test(message))) return \"task_failure\";\n\tif (PROVIDER_REFUSAL_FAILURE_PATTERNS.some((pattern) => pattern.test(message))) return \"task_failure\";\n\treturn undefined;\n}\n\nfunction fallbackKindFromMessage(message: string, name: string | undefined): ModelFallbackFailureKind | undefined {\n\tconst refusalKind = refusalKindFromMessage(message);\n\tif (refusalKind !== undefined) return refusalKind;\n\tconst transportOutageKind = transportOutageKindFromMessage(message);\n\tif (transportOutageKind !== undefined) return transportOutageKind;\n\tif (REQUEST_INCOMPATIBLE_FAILURE_PATTERNS.some((pattern) => pattern.test(message))) return \"request_incompatible\";\n\tconst nameKind = kindFromCode(name);\n\tif (nameKind !== undefined) return nameKind;\n\tconst hasRetryablePattern =\n\t\tRETRYABLE_MODEL_FAILURE_PATTERNS.some((pattern) => pattern.test(message)) ||\n\t\tmessageLooksLikeModelUnavailable(message);\n\tif (!hasRetryablePattern) return undefined;\n\tif (/rate\\s*limit|too\\s*many\\s*requests|\\b429\\b|quota|usage[\\s_-]*limit|billing|credit/i.test(message))\n\t\treturn \"rate_limit\";\n\tif (\n\t\t/auth|unauthori[sz]ed|\\b40[13]\\b|api[_\\s-]*key|token[_\\s-]*(?:expired|revoked|invalidated|rejected)|forbidden|invalid[_\\s-]*key/i.test(\n\t\t\tmessage,\n\t\t)\n\t)\n\t\treturn \"auth_on_candidate_provider\";\n\tif (messageLooksLikeModelUnavailable(message)) return \"model_unavailable\";\n\tif (/network|fetch|socket|connection\\s*refused|getaddrinfo|ENOTFOUND|EAI_AGAIN|timeout|timed\\s*out/i.test(message))\n\t\treturn \"network_timeout\";\n\treturn \"provider_unavailable\";\n}\n\nfunction signalSource(value: unknown, fallback: ModelFallbackFailureSource | undefined): ModelFallbackFailureSource {\n\tif (fallback !== undefined) return fallback;\n\tif (stopReasonFrom(value) !== undefined || diagnosticErrors(value).length > 0) return \"assistant_message\";\n\tif (value instanceof Error) return \"throw\";\n\treturn \"structured\";\n}\n\nfunction makeSignal(\n\tkind: ModelFallbackFailureKind,\n\tvalue: unknown,\n\tsource: ModelFallbackFailureSource | undefined,\n): ModelFallbackFailureSignal {\n\tconst status = statusFrom(value);\n\tconst code = codeFrom(value);\n\tconst name = errorName(value);\n\tconst stopReason = stopReasonFrom(value);\n\treturn {\n\t\tkind,\n\t\tmessage: errorMessage(value),\n\t\tsource: signalSource(value, source),\n\t\t...(stopReason !== undefined ? { stopReason } : {}),\n\t\t...(status !== undefined ? { status } : {}),\n\t\t...(code !== undefined ? { code } : {}),\n\t\t...(name !== undefined ? { name } : {}),\n\t};\n}\n\nfunction fallbackSignalFromDirectMessage(\n\tvalue: unknown,\n\tsource: ModelFallbackFailureSource | undefined,\n): ModelFallbackFailureSignal | undefined {\n\tconst message = directMessageFrom(value);\n\tif (message === undefined) return undefined;\n\tconst kind = fallbackKindFromMessage(message, errorName(value));\n\treturn kind === undefined ? undefined : makeSignal(kind, value, source);\n}\n\nfunction fallbackSignalFromMessage(\n\tvalue: unknown,\n\tsource: ModelFallbackFailureSource | undefined,\n): ModelFallbackFailureSignal | undefined {\n\tconst message = errorMessage(value);\n\tif (!message.trim()) return undefined;\n\tconst kind = fallbackKindFromMessage(message, errorName(value));\n\treturn kind === undefined ? undefined : makeSignal(kind, value, source);\n}\n\nfunction classifyAssistantRefusalSignal(\n\tvalue: unknown,\n\tsource: ModelFallbackFailureSource | undefined,\n): ModelFallbackFailureSignal | undefined {\n\tconst codeRefusalKind =\n\t\trefusalKindFromCode(codeFrom(value)) ??\n\t\trefusalKindFromCode(errorName(value)) ??\n\t\trefusalKindFromCode(finishReasonFrom(value));\n\tif (codeRefusalKind !== undefined) return makeSignal(codeRefusalKind, value, source);\n\n\tconst messageRefusalKind = refusalKindFromMessage(directMessageFrom(value) ?? \"\");\n\treturn messageRefusalKind === undefined ? undefined : makeSignal(messageRefusalKind, value, source);\n}\n\nfunction isRefusalSignal(signal: ModelFallbackFailureSignal): boolean {\n\treturn signal.kind === \"cancelled\" || signal.kind === \"task_failure\";\n}\n\nfunction nestedSignalPriority(signal: ModelFallbackFailureSignal): number {\n\tswitch (signal.kind) {\n\t\tcase \"cancelled\":\n\t\tcase \"task_failure\":\n\t\t\treturn 100;\n\t\tcase \"auth_on_candidate_provider\":\n\t\t\treturn 90;\n\t\tcase \"request_incompatible\":\n\t\t\treturn 85;\n\t\tcase \"model_unavailable\":\n\t\t\treturn 80;\n\t\tcase \"rate_limit\":\n\t\t\treturn 70;\n\t\tcase \"provider_unavailable\":\n\t\t\treturn 60;\n\t\tcase \"network_timeout\":\n\t\t\treturn 50;\n\t\tcase \"transport_error\":\n\t\t\treturn 82;\n\t\tcase \"unknown\":\n\t\t\treturn 0;\n\t}\n}\nfunction structuredSignal(\n\tvalue: unknown,\n\tseen: Set<unknown>,\n\tsource?: ModelFallbackFailureSource,\n): ModelFallbackFailureSignal | undefined {\n\tif (value === undefined || value === null || seen.has(value)) return undefined;\n\tif (typeof value === \"object\") seen.add(value);\n\n\tconst stopReason = stopReasonFrom(value)?.toLowerCase();\n\tconst diagnosticType = stringField(value, \"type\");\n\tconst providerTransportSignal =\n\t\tdiagnosticType !== undefined && normalizeCode(diagnosticType) === \"provider_transport_failure\"\n\t\t\t? makeSignal(\"transport_error\", value, source)\n\t\t\t: undefined;\n\tif (stopReason === \"aborted\") return makeSignal(\"cancelled\", value, source);\n\n\t// Defer direct refusal/cancellation signals until nested diagnostics and\n\t// causes have been inspected. A transport wrapper can carry a cancellation\n\t// or provider refusal that must win over the wrapper's transport label.\n\tconst directRefusalSignal = classifyAssistantRefusalSignal(value, source);\n\tconst codeKind = kindFromCode(codeFrom(value));\n\tconst nameKind = kindFromCode(errorName(value));\n\tconst directCancellationSignal =\n\t\tcodeKind === \"cancelled\" || nameKind === \"cancelled\" ? makeSignal(\"cancelled\", value, source) : undefined;\n\n\tlet bestNestedFallbackSignal: ModelFallbackFailureSignal | undefined;\n\tconst nestedSeen = new Set(seen);\n\tconst nestedValues: readonly { value: unknown; source?: ModelFallbackFailureSource }[] = [\n\t\t...diagnosticErrors(value).map((diagnosticError) => ({ value: diagnosticError, source: \"diagnostic\" as const })),\n\t\t...(field(value, \"error\") === undefined ? [] : [{ value: field(value, \"error\"), source }]),\n\t];\n\tfor (const nested of nestedValues) {\n\t\tconst nestedSignal =\n\t\t\tstructuredSignal(nested.value, nestedSeen, nested.source) ??\n\t\t\tfallbackSignalFromMessage(nested.value, nested.source);\n\t\tif (nestedSignal === undefined) continue;\n\t\tif (isRefusalSignal(nestedSignal)) return nestedSignal;\n\t\tif (\n\t\t\tbestNestedFallbackSignal === undefined ||\n\t\t\tnestedSignalPriority(nestedSignal) > nestedSignalPriority(bestNestedFallbackSignal)\n\t\t) {\n\t\t\tbestNestedFallbackSignal = nestedSignal;\n\t\t}\n\t}\n\tconst cause = causeOf(value);\n\tconst causeSignal = structuredSignal(cause, nestedSeen, source) ?? fallbackSignalFromMessage(cause, source);\n\tif (causeSignal !== undefined) {\n\t\tif (isRefusalSignal(causeSignal)) return causeSignal;\n\t\tif (\n\t\t\tbestNestedFallbackSignal === undefined ||\n\t\t\tnestedSignalPriority(causeSignal) > nestedSignalPriority(bestNestedFallbackSignal)\n\t\t) {\n\t\t\tbestNestedFallbackSignal = causeSignal;\n\t\t}\n\t}\n\n\tconst directSignals = [\n\t\tdirectRefusalSignal,\n\t\tdirectCancellationSignal,\n\t\tproviderTransportSignal,\n\t\tfallbackSignalFromDirectMessage(value, source),\n\t\tkindFromStatus(statusFrom(value)) === undefined\n\t\t\t? undefined\n\t\t\t: makeSignal(kindFromStatus(statusFrom(value))!, value, source),\n\t\tkindFromCode(codeFrom(value)) === undefined\n\t\t\t? undefined\n\t\t\t: makeSignal(kindFromCode(codeFrom(value))!, value, source),\n\t\tkindFromCode(errorName(value)) === undefined\n\t\t\t? undefined\n\t\t\t: makeSignal(kindFromCode(errorName(value))!, value, source),\n\t].filter((signal): signal is ModelFallbackFailureSignal => signal !== undefined);\n\tfor (const directSignal of directSignals) {\n\t\tif (isRefusalSignal(directSignal)) return directSignal;\n\t\tif (\n\t\t\tbestNestedFallbackSignal === undefined ||\n\t\t\tnestedSignalPriority(directSignal) > nestedSignalPriority(bestNestedFallbackSignal)\n\t\t) {\n\t\t\tbestNestedFallbackSignal = directSignal;\n\t\t}\n\t}\n\n\tif (bestNestedFallbackSignal !== undefined) return bestNestedFallbackSignal;\n\tif (stopReason === \"error\") return makeSignal(\"provider_unavailable\", value, source);\n\treturn undefined;\n}\n\nfunction messageFromUnknown(value: unknown, seen: Set<unknown>): string | undefined {\n\tif (value === undefined || value === null || seen.has(value)) return undefined;\n\tif (typeof value === \"string\") return value.trim().length > 0 ? value : undefined;\n\tif (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") return String(value);\n\tif (typeof value === \"symbol\" || typeof value === \"function\") return undefined;\n\tseen.add(value);\n\n\tif (value instanceof Error && value.message.trim().length > 0) return value.message;\n\tconst directMessage = directMessageFrom(value);\n\tif (directMessage !== undefined) return directMessage;\n\tfor (const diagnosticError of diagnosticErrors(value)) {\n\t\tconst diagnosticMessage = messageFromUnknown(diagnosticError, seen);\n\t\tif (diagnosticMessage !== undefined) return diagnosticMessage;\n\t}\n\tconst causeMessage = messageFromUnknown(causeOf(value), seen);\n\tif (causeMessage !== undefined) return causeMessage;\n\tconst finishReason = finishReasonFrom(value);\n\tif (finishReason !== undefined) return `Model request finished with finish_reason:${finishReason}`;\n\tconst stopReason = stopReasonFrom(value);\n\tif (stopReason !== undefined) return `Assistant message ended with stopReason:${stopReason}`;\n\tconst status = statusFrom(value);\n\tif (status !== undefined) return `Model request failed with status ${status}`;\n\tconst code = codeFrom(value);\n\tif (code !== undefined) return `Model request failed with code ${String(code)}`;\n\treturn undefined;\n}\n\nexport function errorMessage(error: unknown): string {\n\tconst structuredMessage = messageFromUnknown(error, new Set());\n\tif (structuredMessage !== undefined) return structuredMessage;\n\tconst rendered = String(error);\n\treturn rendered === \"[object Object]\" ? \"Model request failed\" : rendered;\n}\n\n/** Alias used by the subagent package's older public helper name. */\nexport const modelFailureMessage = errorMessage;\n\nexport function normalizeModelFailureSignal(error: unknown): ModelFallbackFailureSignal {\n\t// Extension startup is not a model request. Its message names extension paths\n\t// and their own errors, which must not read as a provider failure.\n\tif (isExtensionStartupFailure(error)) {\n\t\tconst name = errorName(error);\n\t\treturn {\n\t\t\tkind: \"unknown\",\n\t\t\tmessage: errorMessage(error),\n\t\t\tsource: \"string_fallback\",\n\t\t\t...(name !== undefined ? { name } : {}),\n\t\t};\n\t}\n\tconst structured = structuredSignal(error, new Set());\n\tif (structured !== undefined) return structured;\n\tconst message = errorMessage(error);\n\tconst name = errorName(error);\n\tconst fallbackKind = message.trim().length > 0 ? fallbackKindFromMessage(message, name) : undefined;\n\treturn {\n\t\tkind: fallbackKind ?? \"unknown\",\n\t\tmessage,\n\t\tsource: \"string_fallback\",\n\t\t...(name !== undefined ? { name } : {}),\n\t};\n}\n\n/** Whether a task-failure signal is a provider safety/refusal response. */\nexport function isSafetyRefusalFailure(error: unknown): boolean {\n\tconst signal = normalizeModelFailureSignal(error);\n\tif (signal.kind !== \"task_failure\") return false;\n\tconst text = `${signal.message}\\n${signal.code ?? \"\"}\\n${signal.name ?? \"\"}`;\n\treturn PROVIDER_REFUSAL_FAILURE_PATTERNS.some((pattern) => pattern.test(text));\n}\n\n/** True when this failure may spend a configured model fallback candidate. */\nexport function isRetryableModelFailure(error: unknown): boolean {\n\tif (error === undefined) return false;\n\treturn FALLBACKABLE_FAILURE_KINDS.has(normalizeModelFailureSignal(error).kind);\n}\n\nconst SAME_MODEL_RETRYABLE_FAILURE_KINDS: ReadonlySet<ModelFallbackFailureKind> = new Set([\n\t\"rate_limit\",\n\t\"provider_unavailable\",\n\t\"network_timeout\",\n\t\"transport_error\",\n]);\n\n/** True when the same model may be requested again before fallback advances. */\nexport function isRetryableSameModelFailure(error: unknown): boolean {\n\tif (!isRetryableModelFailure(error)) return false;\n\tconst signal = normalizeModelFailureSignal(error);\n\tif (!SAME_MODEL_RETRYABLE_FAILURE_KINDS.has(signal.kind)) return false;\n\tif (\n\t\tsignal.kind === \"provider_unavailable\" &&\n\t\tsignal.source === \"assistant_message\" &&\n\t\tsignal.status === undefined &&\n\t\tsignal.code === undefined &&\n\t\tsignal.name === undefined &&\n\t\t!RETRYABLE_MODEL_FAILURE_PATTERNS.some((pattern) => pattern.test(signal.message))\n\t)\n\t\treturn false;\n\treturn true;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"model-fallback-failures.js","sourceRoot":"","sources":["../../src/core/model-fallback-failures.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAE3E,MAAM,gCAAgC,GAAsB;IAC3D,eAAe;IACf,wBAAwB;IACxB,wBAAwB;IACxB,SAAS;IACT,QAAQ;IACR,oBAAoB;IACpB,UAAU;IACV,SAAS;IACT,gCAAgC;IAChC,kBAAkB;IAClB,YAAY;IACZ,gBAAgB;IAChB,sBAAsB;IACtB,sCAAsC;IACtC,+CAA+C;IAC/C,YAAY;IACZ,gBAAgB;IAChB,aAAa;IACb,4BAA4B;IAC5B,wBAAwB;IACxB,UAAU;IACV,QAAQ;IACR,cAAc;IACd,YAAY;IACZ,YAAY;IACZ,SAAS;IACT,uBAAuB;IACvB,WAAW;IACX,UAAU;IACV,cAAc;IACd,aAAa;IACb,aAAa;IACb,SAAS;IACT,4BAA4B;IAC5B,gBAAgB;IAChB,kBAAkB;IAClB,oBAAoB;IACpB,mBAAmB;IACnB,oBAAoB;IACpB,aAAa;IACb,oBAAoB;IACpB,oBAAoB;IACpB,mBAAmB;IACnB,uBAAuB;IACvB,iBAAiB;IACjB,gBAAgB;IAChB,mCAAmC;IACnC,gDAAgD;IAChD,uCAAuC;IACvC,mCAAmC;IACnC,cAAc;IACd,2BAA2B;IAC3B,aAAa;IACb,6BAA6B;IAC7B,yBAAyB;IACzB,4BAA4B;IAC5B,2EAA2E;IAC3E,oBAAoB;CACpB,CAAC;AAEF,MAAM,8BAA8B,GAAsB;IACzD,iBAAiB;IACjB,gBAAgB;IAChB,QAAQ;IACR,eAAe;IACf,eAAe;IACf,SAAS;IACT,QAAQ;IACR,cAAc;CACd,CAAC;AAEF,MAAM,0BAA0B,GAAsB,CAAC,SAAS,EAAE,QAAQ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C;IACzF,YAAY;IACZ,sBAAsB;IACtB,iBAAiB;IACjB,iBAAiB;CACjB,CAAC,CAAC;AAEH,gFAAgF;AAChF,MAAM,UAAU,2BAA2B,CAAC,KAAc;IACzD,IAAI,CAAC,uBAAuB,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAClD,MAAM,MAAM,GAAG,2BAA2B,CAAC,KAAK,CAAC,CAAC;IAClD,IAAI,CAAC,kCAAkC,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC;QAAE,OAAO,KAAK,CAAC;IACvE,IACC,MAAM,CAAC,IAAI,KAAK,sBAAsB;QACtC,MAAM,CAAC,MAAM,KAAK,mBAAmB;QACrC,MAAM,CAAC,MAAM,KAAK,SAAS;QAC3B,MAAM,CAAC,IAAI,KAAK,SAAS;QACzB,MAAM,CAAC,IAAI,KAAK,SAAS;QACzB,CAAC,gCAAgC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAEjF,OAAO,KAAK,CAAC;IACd,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/**\n * Shared model/provider failure classification.\n *\n * Workflows, subagents, and the main chat all need the same decision about\n * whether a provider failure may spend another model candidate. Keep this\n * module free of AgentSession and workflow imports so the published SDK can\n * expose it to the raw-TypeScript companion packages without a cycle.\n */\n\nimport { isExtensionStartupFailure } from \"./extension-startup-failure.ts\";\n\nconst RETRYABLE_MODEL_FAILURE_PATTERNS: readonly RegExp[] = [\n\t/rate\\s*limit/i,\n\t/too\\s*many\\s*requests/i,\n\t/\\bthrottl(?:ing|ed)\\b/i,\n\t/\\b429\\b/,\n\t/quota/i,\n\t/usage[\\s_-]*limit/i,\n\t/billing/i,\n\t/credit/i,\n\t/auth(?:entication|orization)?/i,\n\t/unauthori[sz]ed/i,\n\t/\\b40[13]\\b/,\n\t/api[_\\s-]*key/i,\n\t/token[_\\s-]*expired/i,\n\t/token[_\\s-]*(?:revoked|invalidated)/i,\n\t/invalidated[_\\s-]+(?:oauth|auth)[_\\s-]+token/i,\n\t/forbidden/i,\n\t/invalid\\s*key/i,\n\t/overloaded/i,\n\t/temporarily\\s*unavailable/i,\n\t/service\\s*unavailable/i,\n\t/network/i,\n\t/fetch/i,\n\t/getaddrinfo/i,\n\t/ENOTFOUND/i,\n\t/EAI_AGAIN/i,\n\t/socket/i,\n\t/connection\\s*refused/i,\n\t/upstream/i,\n\t/timeout/i,\n\t/timed\\s*out/i,\n\t/\\b50[0-4]\\b/,\n\t/\\b52[0-4]\\b/,\n\t/\\b529\\b/,\n\t/provider.?returned.?error/i,\n\t/server.?error/i,\n\t/internal.?error/i,\n\t/connection.?error/i,\n\t/connection.?lost/i,\n\t/connection.?reset/i,\n\t/ECONNRESET/i,\n\t/other side closed/i,\n\t/websocket.?closed/i,\n\t/websocket.?error/i,\n\t/reset before headers/i,\n\t/socket hang up/i,\n\t/ended without/i,\n\t/stream ended before message_stop/i,\n\t/stream ended before a terminal response event/i,\n\t/http2 request did not get a response/i,\n\t/pending stream has been canceled/i,\n\t/retry delay/i,\n\t/finish.?reason:?\\s*error/i,\n\t/terminated/i,\n\t/you can retry your request/i,\n\t/try your request again/i,\n\t/please retry your request/i,\n\t// gRPC based providers (e.g. NVIDIA NIM); upstream pi-ai retries this too.\n\t/ResourceExhausted/i,\n];\n\nconst NON_RETRYABLE_FAILURE_PATTERNS: readonly RegExp[] = [\n\t/command failed/i,\n\t/tests? failed/i,\n\t/shell/i,\n\t/missing file/i,\n\t/no such file/i,\n\t/cancel/i,\n\t/abort/i,\n\t/interrupted/i,\n];\n\nconst CANCELLED_FAILURE_PATTERNS: readonly RegExp[] = [/cancel/i, /abort/i, /interrupted/i];\n\nconst TRANSPORT_CANCELLATION_FAILURE_PATTERNS: readonly RegExp[] = [\n\t/getaddrinfo|ENOTFOUND|EAI_AGAIN/i,\n\t/pending stream has been canceled/i,\n];\n\nexport type ModelFallbackFailureKind =\n\t| \"auth_on_candidate_provider\"\n\t| \"rate_limit\"\n\t| \"quota_exhausted\"\n\t| \"provider_unavailable\"\n\t| \"network_timeout\"\n\t| \"transport_error\"\n\t| \"model_unavailable\"\n\t| \"request_incompatible\"\n\t| \"cancelled\"\n\t| \"task_failure\"\n\t| \"unknown\";\n\nexport type ModelFallbackFailureSource =\n\t| \"assistant_message\"\n\t| \"diagnostic\"\n\t| \"throw\"\n\t| \"structured\"\n\t| \"string_fallback\";\n\nexport interface ModelFallbackFailureSignal {\n\treadonly kind: ModelFallbackFailureKind;\n\treadonly message: string;\n\treadonly source: ModelFallbackFailureSource;\n\treadonly stopReason?: string;\n\treadonly status?: number;\n\treadonly code?: string | number;\n\treadonly name?: string;\n}\n\nconst FALLBACKABLE_FAILURE_KINDS: ReadonlySet<ModelFallbackFailureKind> = new Set([\n\t\"auth_on_candidate_provider\",\n\t\"rate_limit\",\n\t\"quota_exhausted\",\n\t\"provider_unavailable\",\n\t\"network_timeout\",\n\t\"transport_error\",\n\t\"model_unavailable\",\n\t\"request_incompatible\",\n]);\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn value !== null && typeof value === \"object\" ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction field(value: unknown, key: string): unknown {\n\treturn asRecord(value)?.[key];\n}\n\nfunction stringField(value: unknown, key: string): string | undefined {\n\tconst raw = field(value, key);\n\treturn typeof raw === \"string\" && raw.trim().length > 0 ? raw : undefined;\n}\n\nfunction errorName(value: unknown): string | undefined {\n\treturn value instanceof Error ? value.name : stringField(value, \"name\");\n}\n\nfunction directMessageFrom(value: unknown): string | undefined {\n\treturn stringField(value, \"errorMessage\") ?? stringField(value, \"message\") ?? stringField(value, \"statusText\");\n}\n\nfunction integerFrom(value: unknown): number | undefined {\n\tif (typeof value === \"number\" && Number.isInteger(value)) return value;\n\tif (typeof value !== \"string\" || value.trim().length === 0) return undefined;\n\tconst parsed = Number(value.trim());\n\treturn Number.isInteger(parsed) ? parsed : undefined;\n}\n\nfunction statusFrom(value: unknown): number | undefined {\n\treturn (\n\t\tintegerFrom(field(value, \"status\")) ??\n\t\tintegerFrom(field(value, \"statusCode\")) ??\n\t\tintegerFrom(field(value, \"httpStatus\"))\n\t);\n}\n\nfunction codeFrom(value: unknown): string | number | undefined {\n\tconst rawCode = field(value, \"code\");\n\tif (typeof rawCode === \"string\" || typeof rawCode === \"number\") return rawCode;\n\t// Provider failure diagnostics (`bedrock_response_failure`) keep the modeled error code in `details.errorCode`,\n\t// because the provider's display message replaces the exception name with a readable prefix.\n\tconst detailsCode = field(field(value, \"details\"), \"errorCode\");\n\treturn typeof detailsCode === \"string\" ? detailsCode : undefined;\n}\n\nfunction stopReasonFrom(value: unknown): string | undefined {\n\treturn stringField(value, \"stopReason\");\n}\n\nfunction finishReasonFrom(value: unknown): string | undefined {\n\treturn stringField(value, \"finish_reason\") ?? stringField(value, \"finishReason\");\n}\n\nfunction causeOf(value: unknown): unknown {\n\treturn value instanceof Error ? value.cause : field(value, \"cause\");\n}\n\nfunction diagnosticErrors(value: unknown): readonly unknown[] {\n\tconst diagnostics = field(value, \"diagnostics\");\n\tif (!Array.isArray(diagnostics)) return [];\n\tconst errors: unknown[] = [];\n\tfor (const diagnostic of diagnostics) {\n\t\tconst diagnosticType = stringField(diagnostic, \"type\");\n\t\tconst diagnosticError = field(diagnostic, \"error\");\n\t\terrors.push(\n\t\t\tnormalizeCode(diagnosticType) === \"provider_transport_failure\" ? diagnostic : (diagnosticError ?? diagnostic),\n\t\t);\n\t}\n\treturn errors;\n}\n\nfunction normalizeCode(value: string | number | undefined): string | undefined {\n\tif (value === undefined) return undefined;\n\tconst raw = String(value).trim().toLowerCase();\n\tif (!raw) return undefined;\n\tlet normalized = \"\";\n\tlet needsSeparator = false;\n\tfor (const char of raw) {\n\t\tconst code = char.charCodeAt(0);\n\t\tconst isLowerAlpha = code >= 97 && code <= 122;\n\t\tconst isDigit = code >= 48 && code <= 57;\n\t\tif (isLowerAlpha || isDigit) {\n\t\t\tnormalized += char;\n\t\t\tneedsSeparator = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (needsSeparator && normalized[normalized.length - 1] !== \"_\") normalized += \"_\";\n\t}\n\tif (normalized.endsWith(\"_\")) normalized = normalized.slice(0, -1);\n\treturn normalized.length > 0 ? normalized : undefined;\n}\n\nfunction messageLooksLikeModelUnavailable(message: string): boolean {\n\tconst lower = message.toLowerCase();\n\treturn (\n\t\tlower.includes(\"model\") &&\n\t\t(lower.includes(\"unavailable\") ||\n\t\t\tlower.includes(\"disabled\") ||\n\t\t\tlower.includes(\"not found\") ||\n\t\t\tlower.includes(\"unknown\"))\n\t);\n}\n\n/** GitHub Copilot rejects a model this client integration cannot use with a generic 400 `invalid_request_error`. */\nconst MODEL_UNAVAILABLE_FOR_INTEGRATOR_PATTERN = /model_not_available_for_integrator|not available for integrator/i;\n\nfunction kindFromStatus(status: number | undefined): ModelFallbackFailureKind | undefined {\n\tswitch (status) {\n\t\tcase 400:\n\t\tcase 413:\n\t\tcase 422:\n\t\t\treturn \"request_incompatible\";\n\t\tcase 401:\n\t\tcase 403:\n\t\t\treturn \"auth_on_candidate_provider\";\n\t\tcase 408:\n\t\t\treturn \"network_timeout\";\n\t\tcase 404:\n\t\t\treturn \"model_unavailable\";\n\t\tcase 402:\n\t\t\treturn \"quota_exhausted\";\n\t\tcase 429:\n\t\t\treturn \"rate_limit\";\n\t\tdefault:\n\t\t\tif (status !== undefined && status >= 500 && status <= 599) return \"provider_unavailable\";\n\t\t\treturn undefined;\n\t}\n}\n\nfunction refusalKindFromCode(code: string | number | undefined): ModelFallbackFailureKind | undefined {\n\tconst normalizedCode = normalizeCode(code);\n\tif (normalizedCode === undefined) return undefined;\n\tif (normalizedCode.includes(\"content_filter\") || normalizedCode.includes(\"contentfilter\")) return \"task_failure\";\n\tif (normalizedCode.includes(\"safety\") || normalizedCode.includes(\"policy\")) return \"task_failure\";\n\tswitch (normalizedCode) {\n\t\tcase \"blocked\":\n\t\tcase \"blocked_by_provider\":\n\t\tcase \"blocked_by_safety\":\n\t\tcase \"blocked_by_policy\":\n\t\tcase \"provider_refusal\":\n\t\tcase \"refusal\":\n\t\tcase \"tool_refusal\":\n\t\tcase \"tool_call_refusal\":\n\t\tcase \"tool_use_refusal\":\n\t\t\treturn \"task_failure\";\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nconst REQUEST_INCOMPATIBLE_CODES: ReadonlySet<string> = new Set([\n\t\"invalid_request\",\n\t\"invalid_request_error\",\n\t\"bad_request\",\n\t\"context_length_exceeded\",\n\t\"request_too_large\",\n\t\"too_large\",\n\t\"request_entity_too_large\",\n\t\"max_tokens\",\n\t\"max_context_length\",\n\t\"context_window_exceeded\",\n]);\n\nfunction requestIncompatibleKindFromCode(code: string | number | undefined): ModelFallbackFailureKind | undefined {\n\tconst normalized = normalizeCode(code);\n\treturn normalized !== undefined && REQUEST_INCOMPATIBLE_CODES.has(normalized) ? \"request_incompatible\" : undefined;\n}\n\nfunction kindFromCode(code: string | number | undefined): ModelFallbackFailureKind | undefined {\n\tconst normalizedCode = normalizeCode(code);\n\tif (normalizedCode === undefined) return undefined;\n\tconst refusalKind = refusalKindFromCode(code);\n\tif (refusalKind !== undefined) return refusalKind;\n\tconst httpStatusKind = kindFromStatus(integerFrom(code));\n\tif (httpStatusKind !== undefined) return httpStatusKind;\n\tconst requestIncompatibleKind = requestIncompatibleKindFromCode(code);\n\tif (requestIncompatibleKind !== undefined) return requestIncompatibleKind;\n\n\tswitch (normalizedCode) {\n\t\tcase \"auth\":\n\t\tcase \"auth_required\":\n\t\tcase \"authentication_required\":\n\t\tcase \"unauthorized\":\n\t\tcase \"forbidden\":\n\t\tcase \"invalid_api_key\":\n\t\tcase \"missing_api_key\":\n\t\tcase \"invalid_key\":\n\t\tcase \"token_expired\":\n\t\tcase \"token_revoked\":\n\t\tcase \"token_invalidated\":\n\t\tcase \"oauth_token_invalidated\":\n\t\t\treturn \"auth_on_candidate_provider\";\n\t\tcase \"etimedout\":\n\t\tcase \"econnreset\":\n\t\tcase \"econnrefused\":\n\t\tcase \"enotfound\":\n\t\tcase \"eai_again\":\n\t\tcase \"fetch_failed\":\n\t\tcase \"network_error\":\n\t\tcase \"timeout\":\n\t\tcase \"timeout_error\":\n\t\tcase \"und_err_connect_timeout\":\n\t\t\treturn \"network_timeout\";\n\t\tcase \"rate_limit\":\n\t\tcase \"rate_limit_exceeded\":\n\t\tcase \"too_many_requests\":\n\t\tcase \"throttlingexception\":\n\t\t\treturn \"rate_limit\";\n\t\tcase \"quota_exceeded\":\n\t\tcase \"insufficient_quota\":\n\t\tcase \"usage_limit\":\n\t\tcase \"usage_limit_reached\":\n\t\tcase \"usage_limit_exceeded\":\n\t\tcase \"payment_required\":\n\t\tcase \"servicequotaexceededexception\":\n\t\t\treturn \"quota_exhausted\";\n\t\tcase \"aborterror\":\n\t\tcase \"aborted\":\n\t\tcase \"cancelled\":\n\t\tcase \"canceled\":\n\t\t\treturn \"cancelled\";\n\t\tcase \"model_not_found\":\n\t\tcase \"model_unavailable\":\n\t\tcase \"model_disabled\":\n\t\tcase \"unknown_model\":\n\t\tcase \"model_not_available_for_integrator\":\n\t\t\treturn \"model_unavailable\";\n\t\tcase \"provider_error\":\n\t\tcase \"api_error\":\n\t\tcase \"service_unavailable\":\n\t\tcase \"temporarily_unavailable\":\n\t\tcase \"overloaded\":\n\t\t\treturn \"provider_unavailable\";\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nconst REQUEST_INCOMPATIBLE_FAILURE_PATTERNS: readonly RegExp[] = [\n\t/\\bcontext[_\\s-]?length(?:[_\\s-]?exceeded)?\\b/i,\n\t/\\bcontext[_\\s-]?window(?:[_\\s-]?exceeded)?\\b/i,\n\t/\\bmax[_\\s-]?context\\b/i,\n\t/\\bmax[_\\s-]?tokens?\\b/i,\n\t/\\brequest(?:[_\\s-]?entity)?[_\\s-]?too[_\\s-]?large\\b/i,\n\t/\\btoo[_\\s-]?large\\b/i,\n\t/\\b(?:unsupported|unknown|invalid)\\s+(?:tool|parameter|function)\\b/i,\n\t/\\b(?:tool|parameter|function)\\s+(?:not\\s+(?:supported|found|allowed)|unknown|invalid)\\b/i,\n\t/\\binvalid[_\\s-]?request(?:[_\\s-]?error)?\\b/i,\n\t/\\bbad[_\\s-]?request\\b/i,\n];\n\nconst PROVIDER_REFUSAL_FAILURE_PATTERNS: readonly RegExp[] = [\n\t/\\bthe\\s+model\\s+refused\\s+to\\s+complete\\s+the\\s+request\\b/i,\n\t/\\bfinish[_\\s-]?reason\\b[^\\n]*\\bcontent[_\\s-]?filter\\b/i,\n\t/\\bcontent[_\\s-]?filter(?:ed|ing)?\\b/i,\n\t/\\b(?:safety|policy)\\b[^\\n]*\\b(?:refus(?:e|al|ed|es|ing)?|block(?:ed|ing)?|filter(?:ed|ing)?|violat(?:e|ion|ed|ing)?|disallow(?:ed|ing)?|reject(?:ed|ion|ing)?)\\b/i,\n\t/\\b(?:refus(?:e|al|ed|es|ing)?|block(?:ed|ing)?|filter(?:ed|ing)?|violat(?:e|ion|ed|ing)?|disallow(?:ed|ing)?|reject(?:ed|ion|ing)?)\\b[^\\n]*\\b(?:safety|policy)\\b/i,\n\t/\\btool[_\\s-]?(?:call|use)?[_\\s-]?refus(?:e|al|ed|es|ing)?\\b/i,\n\t/\\btool(?:\\s+call|\\s+use)?\\b[^\\n]*\\brefus(?:e|al|ed|es|ing)?\\b/i,\n\t/\\brefus(?:e|al|ed|es|ing)?\\b[^\\n]*\\btool(?:\\s+call|\\s+use)?\\b/i,\n\t/\\bprovider[_\\s-]?refus(?:e|al|ed|es|ing)?\\b/i,\n\t/\\bprovider\\b[^\\n]*\\brefus(?:e|al|ed|es|ing)?\\b[^\\n]*\\b(?:prompt|request|content|policy|safety)\\b/i,\n];\n\nconst TRANSPORT_OUTAGE_FAILURE_PATTERNS: readonly RegExp[] = [\n\t/^connection\\s+error\\.?$/i,\n\t/^fetch\\s+failed\\.?$/i,\n\t// Response-body decompression failures reported by Node/Bun zlib, optionally\n\t// behind the fetch/WebSocket layer's \"Library error:\" wrapper. GitHub Copilot\n\t// on the default `transport: \"auto\"` surfaces this as\n\t// \"Library error: zlib error: incorrect header check\" (#2553). These are\n\t// unanchored because the wrapper text varies by runtime and transport. `zlib`\n\t// has no trailing word boundary on purpose: Bun 1.4.0, the shipped runtime\n\t// when verified, throws `ZlibError fetching \"...\"` as one word.\n\t/\\bzlib/i,\n\t/\\bincorrect\\s+header\\s+check\\b/i,\n\t/\\bdecompress(?:ion|ing|ed)?\\b/i,\n\t/^library\\s+error\\b/i,\n\t// Idle-stream deadline enforced below the HTTP layer by pi-ai's\n\t// `withStreamDeadline`, so a stalled stream fails over instead of hanging.\n\t/\\bstream\\s+deadline\\s+exceeded\\b/i,\n];\n\n// HTTP 402 and explicit quota exhaustion: the account cannot be served again until its quota resets.\n// Codes that also appear as free-text wording for short limits (\"quota exceeded\", \"usage limit reached\")\n// count only as a JSON `code`/`type` value, as in a raw error body some providers put in the message.\n// A service-quota exception and a per-day quota violation in a JSON error body (`\"quotaId\": \"...PerDay...\"`)\n// also last until the quota resets.\nconst QUOTA_EXHAUSTED_FAILURE_PATTERN =\n\t/(?<![a-z0-9.])402(?![a-z0-9.])|payment[_\\s-]*required|insufficient[_\\s-]*quota|\\bServiceQuotaExceededException\\b|\"quotaId\"\\s*:\\s*\"[^\"]*PerDay|\"(?:code|type|error_code)\"\\s*:\\s*\"(?:quota_exceeded|usage_limit|usage_limit_reached|usage_limit_exceeded)\"/i;\n\nfunction transportOutageKindFromMessage(message: string): ModelFallbackFailureKind | undefined {\n\treturn TRANSPORT_OUTAGE_FAILURE_PATTERNS.some((pattern) => pattern.test(message.trim()))\n\t\t? \"transport_error\"\n\t\t: undefined;\n}\n\nfunction refusalKindFromMessage(message: string): ModelFallbackFailureKind | undefined {\n\tif (TRANSPORT_CANCELLATION_FAILURE_PATTERNS.some((pattern) => pattern.test(message))) return \"network_timeout\";\n\tif (CANCELLED_FAILURE_PATTERNS.some((pattern) => pattern.test(message))) return \"cancelled\";\n\tif (NON_RETRYABLE_FAILURE_PATTERNS.some((pattern) => pattern.test(message))) return \"task_failure\";\n\tif (PROVIDER_REFUSAL_FAILURE_PATTERNS.some((pattern) => pattern.test(message))) return \"task_failure\";\n\treturn undefined;\n}\n\nfunction fallbackKindFromMessage(message: string, name: string | undefined): ModelFallbackFailureKind | undefined {\n\tconst refusalKind = refusalKindFromMessage(message);\n\tif (refusalKind !== undefined) return refusalKind;\n\tconst transportOutageKind = transportOutageKindFromMessage(message);\n\tif (transportOutageKind !== undefined) return transportOutageKind;\n\tif (MODEL_UNAVAILABLE_FOR_INTEGRATOR_PATTERN.test(message)) return \"model_unavailable\";\n\tif (REQUEST_INCOMPATIBLE_FAILURE_PATTERNS.some((pattern) => pattern.test(message))) return \"request_incompatible\";\n\tconst nameKind = kindFromCode(name);\n\tif (nameKind !== undefined) return nameKind;\n\tif (QUOTA_EXHAUSTED_FAILURE_PATTERN.test(message)) return \"quota_exhausted\";\n\tconst hasRetryablePattern =\n\t\tRETRYABLE_MODEL_FAILURE_PATTERNS.some((pattern) => pattern.test(message)) ||\n\t\tmessageLooksLikeModelUnavailable(message);\n\tif (!hasRetryablePattern) return undefined;\n\tif (\n\t\t/rate\\s*limit|too\\s*many\\s*requests|\\bthrottl(?:ing|ed)\\b|\\b429\\b|quota|usage[\\s_-]*limit|billing|credit/i.test(\n\t\t\tmessage,\n\t\t)\n\t)\n\t\treturn \"rate_limit\";\n\tif (\n\t\t/auth|unauthori[sz]ed|\\b40[13]\\b|api[_\\s-]*key|token[_\\s-]*(?:expired|revoked|invalidated|rejected)|forbidden|invalid[_\\s-]*key/i.test(\n\t\t\tmessage,\n\t\t)\n\t)\n\t\treturn \"auth_on_candidate_provider\";\n\tif (messageLooksLikeModelUnavailable(message)) return \"model_unavailable\";\n\tif (/network|fetch|socket|connection\\s*refused|getaddrinfo|ENOTFOUND|EAI_AGAIN|timeout|timed\\s*out/i.test(message))\n\t\treturn \"network_timeout\";\n\treturn \"provider_unavailable\";\n}\n\nfunction signalSource(value: unknown, fallback: ModelFallbackFailureSource | undefined): ModelFallbackFailureSource {\n\tif (fallback !== undefined) return fallback;\n\tif (stopReasonFrom(value) !== undefined || diagnosticErrors(value).length > 0) return \"assistant_message\";\n\tif (value instanceof Error) return \"throw\";\n\treturn \"structured\";\n}\n\nfunction makeSignal(\n\tkind: ModelFallbackFailureKind,\n\tvalue: unknown,\n\tsource: ModelFallbackFailureSource | undefined,\n): ModelFallbackFailureSignal {\n\tconst status = statusFrom(value);\n\tconst code = codeFrom(value);\n\tconst name = errorName(value);\n\tconst stopReason = stopReasonFrom(value);\n\treturn {\n\t\tkind,\n\t\tmessage: errorMessage(value),\n\t\tsource: signalSource(value, source),\n\t\t...(stopReason !== undefined ? { stopReason } : {}),\n\t\t...(status !== undefined ? { status } : {}),\n\t\t...(code !== undefined ? { code } : {}),\n\t\t...(name !== undefined ? { name } : {}),\n\t};\n}\n\nfunction fallbackSignalFromDirectMessage(\n\tvalue: unknown,\n\tsource: ModelFallbackFailureSource | undefined,\n): ModelFallbackFailureSignal | undefined {\n\tconst message = directMessageFrom(value);\n\tif (message === undefined) return undefined;\n\tconst kind = fallbackKindFromMessage(message, errorName(value));\n\treturn kind === undefined ? undefined : makeSignal(kind, value, source);\n}\n\nfunction fallbackSignalFromMessage(\n\tvalue: unknown,\n\tsource: ModelFallbackFailureSource | undefined,\n): ModelFallbackFailureSignal | undefined {\n\tconst message = errorMessage(value);\n\tif (!message.trim()) return undefined;\n\tconst kind = fallbackKindFromMessage(message, errorName(value));\n\treturn kind === undefined ? undefined : makeSignal(kind, value, source);\n}\n\nfunction classifyAssistantRefusalSignal(\n\tvalue: unknown,\n\tsource: ModelFallbackFailureSource | undefined,\n): ModelFallbackFailureSignal | undefined {\n\tconst codeRefusalKind =\n\t\trefusalKindFromCode(codeFrom(value)) ??\n\t\trefusalKindFromCode(errorName(value)) ??\n\t\trefusalKindFromCode(finishReasonFrom(value));\n\tif (codeRefusalKind !== undefined) return makeSignal(codeRefusalKind, value, source);\n\n\tconst messageRefusalKind = refusalKindFromMessage(directMessageFrom(value) ?? \"\");\n\treturn messageRefusalKind === undefined ? undefined : makeSignal(messageRefusalKind, value, source);\n}\n\nfunction isRefusalSignal(signal: ModelFallbackFailureSignal): boolean {\n\treturn signal.kind === \"cancelled\" || signal.kind === \"task_failure\";\n}\n\nfunction nestedSignalPriority(signal: ModelFallbackFailureSignal): number {\n\tswitch (signal.kind) {\n\t\tcase \"cancelled\":\n\t\tcase \"task_failure\":\n\t\t\treturn 100;\n\t\tcase \"auth_on_candidate_provider\":\n\t\t\treturn 90;\n\t\tcase \"request_incompatible\":\n\t\t\treturn 85;\n\t\tcase \"model_unavailable\":\n\t\t\treturn 80;\n\t\tcase \"quota_exhausted\":\n\t\t\treturn 75;\n\t\tcase \"rate_limit\":\n\t\t\treturn 70;\n\t\tcase \"provider_unavailable\":\n\t\t\treturn 60;\n\t\tcase \"network_timeout\":\n\t\t\treturn 50;\n\t\tcase \"transport_error\":\n\t\t\treturn 82;\n\t\tcase \"unknown\":\n\t\t\treturn 0;\n\t}\n}\nfunction structuredSignal(\n\tvalue: unknown,\n\tseen: Set<unknown>,\n\tsource?: ModelFallbackFailureSource,\n): ModelFallbackFailureSignal | undefined {\n\tif (value === undefined || value === null || seen.has(value)) return undefined;\n\tif (typeof value === \"object\") seen.add(value);\n\n\tconst stopReason = stopReasonFrom(value)?.toLowerCase();\n\tconst diagnosticType = stringField(value, \"type\");\n\tconst providerTransportSignal =\n\t\tdiagnosticType !== undefined && normalizeCode(diagnosticType) === \"provider_transport_failure\"\n\t\t\t? makeSignal(\"transport_error\", value, source)\n\t\t\t: undefined;\n\tif (stopReason === \"aborted\") return makeSignal(\"cancelled\", value, source);\n\n\t// Defer direct refusal/cancellation signals until nested diagnostics and\n\t// causes have been inspected. A transport wrapper can carry a cancellation\n\t// or provider refusal that must win over the wrapper's transport label.\n\tconst directRefusalSignal = classifyAssistantRefusalSignal(value, source);\n\tconst codeKind = kindFromCode(codeFrom(value));\n\tconst nameKind = kindFromCode(errorName(value));\n\tconst directCancellationSignal =\n\t\tcodeKind === \"cancelled\" || nameKind === \"cancelled\" ? makeSignal(\"cancelled\", value, source) : undefined;\n\n\tlet bestNestedFallbackSignal: ModelFallbackFailureSignal | undefined;\n\tconst nestedSeen = new Set(seen);\n\tconst nestedValues: readonly { value: unknown; source?: ModelFallbackFailureSource }[] = [\n\t\t...diagnosticErrors(value).map((diagnosticError) => ({ value: diagnosticError, source: \"diagnostic\" as const })),\n\t\t...(field(value, \"error\") === undefined ? [] : [{ value: field(value, \"error\"), source }]),\n\t];\n\tfor (const nested of nestedValues) {\n\t\tconst nestedSignal =\n\t\t\tstructuredSignal(nested.value, nestedSeen, nested.source) ??\n\t\t\tfallbackSignalFromMessage(nested.value, nested.source);\n\t\tif (nestedSignal === undefined) continue;\n\t\tif (isRefusalSignal(nestedSignal)) return nestedSignal;\n\t\tif (\n\t\t\tbestNestedFallbackSignal === undefined ||\n\t\t\tnestedSignalPriority(nestedSignal) > nestedSignalPriority(bestNestedFallbackSignal)\n\t\t) {\n\t\t\tbestNestedFallbackSignal = nestedSignal;\n\t\t}\n\t}\n\tconst cause = causeOf(value);\n\tconst causeSignal = structuredSignal(cause, nestedSeen, source) ?? fallbackSignalFromMessage(cause, source);\n\tif (causeSignal !== undefined) {\n\t\tif (isRefusalSignal(causeSignal)) return causeSignal;\n\t\tif (\n\t\t\tbestNestedFallbackSignal === undefined ||\n\t\t\tnestedSignalPriority(causeSignal) > nestedSignalPriority(bestNestedFallbackSignal)\n\t\t) {\n\t\t\tbestNestedFallbackSignal = causeSignal;\n\t\t}\n\t}\n\n\t// This code names the exact cause, so the generic 400 status and its request-error text must not outrank it.\n\tif (\n\t\tdirectRefusalSignal === undefined &&\n\t\tdirectCancellationSignal === undefined &&\n\t\tnormalizeCode(codeFrom(value)) === \"model_not_available_for_integrator\"\n\t)\n\t\treturn makeSignal(\"model_unavailable\", value, source);\n\n\tconst directSignals = [\n\t\tdirectRefusalSignal,\n\t\tdirectCancellationSignal,\n\t\tproviderTransportSignal,\n\t\tfallbackSignalFromDirectMessage(value, source),\n\t\tkindFromStatus(statusFrom(value)) === undefined\n\t\t\t? undefined\n\t\t\t: makeSignal(kindFromStatus(statusFrom(value))!, value, source),\n\t\tkindFromCode(codeFrom(value)) === undefined\n\t\t\t? undefined\n\t\t\t: makeSignal(kindFromCode(codeFrom(value))!, value, source),\n\t\tkindFromCode(errorName(value)) === undefined\n\t\t\t? undefined\n\t\t\t: makeSignal(kindFromCode(errorName(value))!, value, source),\n\t].filter((signal): signal is ModelFallbackFailureSignal => signal !== undefined);\n\tfor (const directSignal of directSignals) {\n\t\tif (isRefusalSignal(directSignal)) return directSignal;\n\t\tif (\n\t\t\tbestNestedFallbackSignal === undefined ||\n\t\t\tnestedSignalPriority(directSignal) > nestedSignalPriority(bestNestedFallbackSignal)\n\t\t) {\n\t\t\tbestNestedFallbackSignal = directSignal;\n\t\t}\n\t}\n\n\tif (bestNestedFallbackSignal !== undefined) return bestNestedFallbackSignal;\n\tif (stopReason === \"error\") return makeSignal(\"provider_unavailable\", value, source);\n\treturn undefined;\n}\n\nfunction messageFromUnknown(value: unknown, seen: Set<unknown>): string | undefined {\n\tif (value === undefined || value === null || seen.has(value)) return undefined;\n\tif (typeof value === \"string\") return value.trim().length > 0 ? value : undefined;\n\tif (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") return String(value);\n\tif (typeof value === \"symbol\" || typeof value === \"function\") return undefined;\n\tseen.add(value);\n\n\tif (value instanceof Error && value.message.trim().length > 0) return value.message;\n\tconst directMessage = directMessageFrom(value);\n\tif (directMessage !== undefined) return directMessage;\n\tfor (const diagnosticError of diagnosticErrors(value)) {\n\t\tconst diagnosticMessage = messageFromUnknown(diagnosticError, seen);\n\t\tif (diagnosticMessage !== undefined) return diagnosticMessage;\n\t}\n\tconst causeMessage = messageFromUnknown(causeOf(value), seen);\n\tif (causeMessage !== undefined) return causeMessage;\n\tconst finishReason = finishReasonFrom(value);\n\tif (finishReason !== undefined) return `Model request finished with finish_reason:${finishReason}`;\n\tconst stopReason = stopReasonFrom(value);\n\tif (stopReason !== undefined) return `Assistant message ended with stopReason:${stopReason}`;\n\tconst status = statusFrom(value);\n\tif (status !== undefined) return `Model request failed with status ${status}`;\n\tconst code = codeFrom(value);\n\tif (code !== undefined) return `Model request failed with code ${String(code)}`;\n\treturn undefined;\n}\n\nexport function errorMessage(error: unknown): string {\n\tconst structuredMessage = messageFromUnknown(error, new Set());\n\tif (structuredMessage !== undefined) return structuredMessage;\n\tconst rendered = String(error);\n\treturn rendered === \"[object Object]\" ? \"Model request failed\" : rendered;\n}\n\n/** Alias used by the subagent package's older public helper name. */\nexport const modelFailureMessage = errorMessage;\n\nexport function normalizeModelFailureSignal(error: unknown): ModelFallbackFailureSignal {\n\t// Extension startup is not a model request. Its message names extension paths\n\t// and their own errors, which must not read as a provider failure.\n\tif (isExtensionStartupFailure(error)) {\n\t\tconst name = errorName(error);\n\t\treturn {\n\t\t\tkind: \"unknown\",\n\t\t\tmessage: errorMessage(error),\n\t\t\tsource: \"string_fallback\",\n\t\t\t...(name !== undefined ? { name } : {}),\n\t\t};\n\t}\n\tconst structured = structuredSignal(error, new Set());\n\tif (structured !== undefined) return structured;\n\tconst message = errorMessage(error);\n\tconst name = errorName(error);\n\tconst fallbackKind = message.trim().length > 0 ? fallbackKindFromMessage(message, name) : undefined;\n\treturn {\n\t\tkind: fallbackKind ?? \"unknown\",\n\t\tmessage,\n\t\tsource: \"string_fallback\",\n\t\t...(name !== undefined ? { name } : {}),\n\t};\n}\n\n/** Whether a task-failure signal is a provider safety/refusal response. */\nexport function isSafetyRefusalFailure(error: unknown): boolean {\n\tconst signal = normalizeModelFailureSignal(error);\n\tif (signal.kind !== \"task_failure\") return false;\n\tconst text = `${signal.message}\\n${signal.code ?? \"\"}\\n${signal.name ?? \"\"}`;\n\treturn PROVIDER_REFUSAL_FAILURE_PATTERNS.some((pattern) => pattern.test(text));\n}\n\n/** True when this failure may spend a configured model fallback candidate. */\nexport function isRetryableModelFailure(error: unknown): boolean {\n\tif (error === undefined) return false;\n\treturn FALLBACKABLE_FAILURE_KINDS.has(normalizeModelFailureSignal(error).kind);\n}\n\nconst SAME_MODEL_RETRYABLE_FAILURE_KINDS: ReadonlySet<ModelFallbackFailureKind> = new Set([\n\t\"rate_limit\",\n\t\"provider_unavailable\",\n\t\"network_timeout\",\n\t\"transport_error\",\n]);\n\n/** True when the same model may be requested again before fallback advances. */\nexport function isRetryableSameModelFailure(error: unknown): boolean {\n\tif (!isRetryableModelFailure(error)) return false;\n\tconst signal = normalizeModelFailureSignal(error);\n\tif (!SAME_MODEL_RETRYABLE_FAILURE_KINDS.has(signal.kind)) return false;\n\tif (\n\t\tsignal.kind === \"provider_unavailable\" &&\n\t\tsignal.source === \"assistant_message\" &&\n\t\tsignal.status === undefined &&\n\t\tsignal.code === undefined &&\n\t\tsignal.name === undefined &&\n\t\t!RETRYABLE_MODEL_FAILURE_PATTERNS.some((pattern) => pattern.test(signal.message))\n\t)\n\t\treturn false;\n\treturn true;\n}\n"]}
|
|
@@ -159,7 +159,7 @@ export class ModelRuntimeStreaming {
|
|
|
159
159
|
if (event.type === "error")
|
|
160
160
|
admission.observeFailure(event.error);
|
|
161
161
|
if (event.type === "done")
|
|
162
|
-
recordProviderSuccess(prepared.model.provider);
|
|
162
|
+
recordProviderSuccess(prepared.model.provider, prepared.model.id);
|
|
163
163
|
if (event.type === "start") {
|
|
164
164
|
pending.push(event);
|
|
165
165
|
continue;
|
|
@@ -179,7 +179,7 @@ export class ModelRuntimeStreaming {
|
|
|
179
179
|
if (!rejection && !terminal) {
|
|
180
180
|
const result = await source.result();
|
|
181
181
|
if (result.stopReason !== "error" && result.stopReason !== "aborted")
|
|
182
|
-
recordProviderSuccess(prepared.model.provider);
|
|
182
|
+
recordProviderSuccess(prepared.model.provider, prepared.model.id);
|
|
183
183
|
if (result.stopReason === "error")
|
|
184
184
|
admission.observeFailure(result);
|
|
185
185
|
const event = result.stopReason === "error" || result.stopReason === "aborted"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-runtime-streaming.js","sourceRoot":"","sources":["../../src/core/model-runtime-streaming.ts"],"names":[],"mappings":"AAAA,OAAO,EAON,eAAe,EAKf,yBAAyB,EACzB,UAAU,EAKV,WAAW,EAIX,gBAAgB,GAKhB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,yBAAyB,EAAE,gCAAgC,EAAE,MAAM,yBAAyB,CAAC;AACtG,OAAO,EAAE,sCAAsC,EAAE,MAAM,mCAAmC,CAAC;AAE3F,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AAEtE,MAAM,UAAU,YAAY,CAC3B,IAAiC,EACjC,QAAqC;IAErC,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ;QAAE,OAAO,SAAS,CAAC;IACzC,MAAM,MAAM,GAAG,EAAE,GAAG,IAAI,EAAE,CAAC;IAC3B,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,IAAI,EAAE,CAAC,EAAE,CAAC;QAC5D,MAAM,SAAS,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QACrC,KAAK,MAAM,YAAY,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;YAChD,IAAI,YAAY,CAAC,WAAW,EAAE,KAAK,SAAS;gBAAE,OAAO,MAAM,CAAC,YAAY,CAAC,CAAC;QAC3E,CAAC;QACD,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;IACtB,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC;AA0BD,sGAAsG;AACtG,MAAM,O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CAAC","sourcesContent":["import {\n\ttype Api,\n\ttype ApiStreamOptions,\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype AssistantMessageEventStream,\n\ttype AuthResult,\n\tassertChatModel,\n\ttype Context,\n\ttype DeferredCancelOptions,\n\ttype DeferredFetchOptions,\n\ttype DeferredHandle,\n\tgetOpenCodeSessionHeaders,\n\tlazyStream,\n\ttype Model,\n\ttype ModelsApiStreamOptions,\n\ttype ModelsDeferredCancelOptions,\n\ttype ModelsDeferredFetchOptions,\n\tModelsError,\n\ttype ModelsRequestTransforms,\n\ttype ModelsSimpleStreamOptions,\n\ttype MutableModels,\n\tnormalizeContext,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@bastani/pi-ai\";\nimport { normalizeModelProvider } from \"./azure-provider-compat.js\";\nimport { usesChatGptCodexTransport, withChatGptCodexTransportRouting } from \"./fast-model-routing.ts\";\nimport { installCodexFastRouteWebSocketIdentity } from \"./fast-model-routing-transport.ts\";\nimport type { ModelRuntimeAuthOverrides } from \"./model-runtime-types.ts\";\nimport { recordProviderSuccess } from \"./provider-rate-limits.js\";\nimport { admitProviderStream } from \"./provider-request-admission.js\";\n\nexport function mergeHeaders(\n\tbase: ProviderHeaders | undefined,\n\toverride: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!base && !override) return undefined;\n\tconst merged = { ...base };\n\tfor (const [name, value] of Object.entries(override ?? {})) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tfor (const existingName of Object.keys(merged)) {\n\t\t\tif (existingName.toLowerCase() === lowerName) delete merged[existingName];\n\t\t}\n\t\tmerged[name] = value;\n\t}\n\treturn merged;\n}\n\n/** SDK-owned request-auth result so transport preparation does not start a second deadline. */\nexport interface PreparedRequestAuth {\n\treadonly resolution: AuthResult | undefined;\n\treadonly reprepare?: () => Promise<{ model: Model<Api>; options: ModelRuntimeSimpleStreamOptions }>;\n\treadonly streamSimple?: (\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions,\n\t) => AssistantMessageEventStream;\n}\n\nexport type ModelRuntimePreparedStreamOptions = StreamOptions &\n\tModelsRequestTransforms & {\n\t\tpreparedRequestAuth?: PreparedRequestAuth;\n\t};\n\nexport type ModelRuntimeSimpleStreamOptions = ModelsSimpleStreamOptions & {\n\tpreparedRequestAuth?: PreparedRequestAuth;\n};\n\ntype ResolveAuth = (model: Model<Api>, overrides?: ModelRuntimeAuthOverrides) => Promise<AuthResult | undefined>;\n/** Whether an extension owns this model's transport, in which case it owns its serialization too. */\ntype OwnsExtensionTransport = (model: Model<Api>) => boolean;\n\n/** Streaming request preparation split from ModelRuntime solely for Atomic's 500-line source gate. */\nexport class ModelRuntimeStreaming {\n\tprivate readonly models: MutableModels;\n\tprivate readonly resolveAuth: ResolveAuth;\n\tprivate readonly ownsExtensionTransport: OwnsExtensionTransport;\n\tprivate readonly transportModel: (model: Model<Api>) => Model<Api>;\n\tprivate readonly reloadCredentials: () => Promise<void>;\n\tconstructor(\n\t\tmodels: MutableModels,\n\t\tresolveAuth: ResolveAuth,\n\t\townsExtensionTransport: OwnsExtensionTransport,\n\t\ttransportModel: (model: Model<Api>) => Model<Api> = (model) => model,\n\t\treloadCredentials: () => Promise<void> = async () => {},\n\t) {\n\t\tthis.models = models;\n\t\tthis.resolveAuth = resolveAuth;\n\t\tthis.ownsExtensionTransport = ownsExtensionTransport;\n\t\tthis.transportModel = transportModel;\n\t\tthis.reloadCredentials = reloadCredentials;\n\t}\n\n\t/**\n\t * Attach the first-party ChatGPT Codex routing identity to a prepared request.\n\t *\n\t * This must happen *after* `prepareRequest`, not before it. The wrapper works by mutating the\n\t * header object it captures at construction, and `prepareRequest` rebuilds headers through\n\t * `mergeHeaders`, which copies — so a wrapper applied upstream is silently inert. The wrapper\n\t * decides from the final payload whether the request is priority, so a normal model still ends up\n\t * with `originator: pi` and no routing hint.\n\t */\n\tprivate withCodexRouting<TOptions extends StreamOptions>(model: Model<Api>, options: TOptions): TOptions {\n\t\tmodel = this.transportModel(model);\n\t\tif (!usesChatGptCodexTransport(model) || this.ownsExtensionTransport(model)) return options;\n\t\t// The WebSocket handshake builds its headers inside pi-ai and the constructor can be cached, so\n\t\t// the identity is repaired through the global constructor rather than per-request options. CLI\n\t\t// entrypoints install this through the HTTP dispatcher; a pure SDK embedder never does.\n\t\tif (options.transport !== \"sse\") installCodexFastRouteWebSocketIdentity();\n\t\treturn withChatGptCodexTransportRouting(model, options);\n\t}\n\n\tprivate async prepareRequest(\n\t\tmodel: Model<Api>,\n\t\toptions: ModelRuntimePreparedStreamOptions | undefined,\n\t): Promise<{ provider: Provider; model: Model<Api>; options: StreamOptions; authIdentity: string }> {\n\t\tassertChatModel(model);\n\t\tmodel = normalizeModelProvider(model);\n\t\tconst provider = this.models.getProvider(model.provider);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\tconst { transformHeaders, preparedRequestAuth, ...providerOptions } = options ?? {};\n\t\tconst resolution = preparedRequestAuth\n\t\t\t? preparedRequestAuth.resolution\n\t\t\t: await this.resolveAuth(model, {\n\t\t\t\t\tapiKey: options?.apiKey,\n\t\t\t\t\tenv: options?.env,\n\t\t\t\t\tsignal: options?.signal,\n\t\t\t\t});\n\t\toptions?.signal?.throwIfAborted();\n\t\tif (!resolution) throw new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\n\t\tconst requestModel = resolution.auth.baseUrl ? { ...model, baseUrl: resolution.auth.baseUrl } : model;\n\t\t// An SDK-prepared request already carries the session header, which `before_provider_headers`\n\t\t// handlers may have removed, so only other requests add it here.\n\t\tconst sessionHeaders = preparedRequestAuth\n\t\t\t? undefined\n\t\t\t: getOpenCodeSessionHeaders(requestModel, providerOptions.sessionId);\n\t\tlet headers = mergeHeaders(mergeHeaders(sessionHeaders, resolution.auth.headers), providerOptions.headers);\n\t\tif (transformHeaders) headers = await transformHeaders(headers ?? {});\n\t\toptions?.signal?.throwIfAborted();\n\t\tconst env =\n\t\t\tresolution.env || providerOptions.env\n\t\t\t\t? { ...(resolution.env ?? {}), ...(providerOptions.env ?? {}) }\n\t\t\t\t: undefined;\n\t\tconst apiKey = providerOptions.apiKey ?? resolution.auth.apiKey;\n\t\tconst credentialHeaderNames = new Set(\n\t\t\tObject.keys(resolution.auth.headers ?? {}).map((name) => name.toLowerCase()),\n\t\t);\n\t\treturn {\n\t\t\tprovider,\n\t\t\tauthIdentity: JSON.stringify({\n\t\t\t\tapiKey,\n\t\t\t\theaders: Object.entries(headers ?? {})\n\t\t\t\t\t.map(([name, value]) => [name.toLowerCase(), value] as const)\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t([name]) =>\n\t\t\t\t\t\t\tcredentialHeaderNames.has(name) ||\n\t\t\t\t\t\t\t/^(?:authorization|proxy-authorization|x-api-key|api-key|cookie)$/.test(name),\n\t\t\t\t\t)\n\t\t\t\t\t.sort(([left], [right]) => left.localeCompare(right)),\n\t\t\t\tenv: Object.entries(env ?? {}).sort(([left], [right]) => left.localeCompare(right)),\n\t\t\t\tbaseUrl: resolution.auth.baseUrl ?? model.baseUrl,\n\t\t\t}),\n\t\t\tmodel: requestModel,\n\t\t\toptions: {\n\t\t\t\t...providerOptions,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tenv,\n\t\t\t},\n\t\t};\n\t}\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream {\n\t\tconst transcript = normalizeContext(context);\n\t\treturn this.streamWithCredentialRetry(model, options, (prepared) =>\n\t\t\tprepared.provider.stream(\n\t\t\t\tprepared.model as Model<TApi>,\n\t\t\t\ttranscript,\n\t\t\t\tthis.withCodexRouting(prepared.model, prepared.options) as ApiStreamOptions<TApi>,\n\t\t\t),\n\t\t);\n\t}\n\n\tcomplete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage> {\n\t\treturn this.stream(model, context, options).result();\n\t}\n\n\tstreamSimple(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions?: ModelRuntimeSimpleStreamOptions,\n\t): AssistantMessageEventStream {\n\t\tconst transcript = normalizeContext(context);\n\t\tconst dispatch = options?.preparedRequestAuth?.streamSimple;\n\t\treturn this.streamWithCredentialRetry(model, options, (prepared) =>\n\t\t\tdispatch\n\t\t\t\t? dispatch(prepared.model, context, prepared.options as SimpleStreamOptions)\n\t\t\t\t: prepared.provider.streamSimple(\n\t\t\t\t\t\tprepared.model,\n\t\t\t\t\t\ttranscript,\n\t\t\t\t\t\tthis.withCodexRouting(prepared.model, prepared.options) as SimpleStreamOptions,\n\t\t\t\t\t),\n\t\t);\n\t}\n\n\tcompleteSimple(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions?: ModelRuntimeSimpleStreamOptions,\n\t): Promise<AssistantMessage> {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n\n\tprivate streamWithCredentialRetry(\n\t\tmodel: Model<Api>,\n\t\toptions: ModelRuntimePreparedStreamOptions | undefined,\n\t\tinvoke: (prepared: Awaited<ReturnType<ModelRuntimeStreaming[\"prepareRequest\"]>>) => AssistantMessageEventStream,\n\t): AssistantMessageEventStream {\n\t\tconst prepare = () => this.prepareRequest(model, options);\n\t\tconst reprepareCredentials = async (previous: Awaited<ReturnType<typeof prepare>>) => {\n\t\t\tif (options?.signal?.aborted) return undefined;\n\t\t\tawait this.reloadCredentials();\n\t\t\tconst { preparedRequestAuth: previousAuth, ...callerOptions } = options ?? {};\n\t\t\tconst reprepared = previousAuth?.reprepare ? await previousAuth.reprepare() : undefined;\n\t\t\tconst next = reprepared\n\t\t\t\t? await this.prepareRequest(reprepared.model, {\n\t\t\t\t\t\t...callerOptions,\n\t\t\t\t\t\tapiKey: reprepared.options.apiKey,\n\t\t\t\t\t\theaders: reprepared.options.headers,\n\t\t\t\t\t\tenv: reprepared.options.env,\n\t\t\t\t\t\tpreparedRequestAuth: reprepared.options.preparedRequestAuth,\n\t\t\t\t\t})\n\t\t\t\t: await this.prepareRequest(model, callerOptions);\n\t\t\treturn next.authIdentity !== previous.authIdentity ? next : undefined;\n\t\t};\n\t\tconst retry = (previous: Awaited<ReturnType<typeof prepare>>) =>\n\t\t\treprepareCredentials(previous).catch(() => undefined);\n\t\tconst ownsTransport = (requestModel: Model<Api>) => this.ownsExtensionTransport(requestModel);\n\t\tconst iterate = async function* (): AsyncGenerator<AssistantMessageEvent> {\n\t\t\tlet prepared = await prepare();\n\t\t\tfor (let attempt = 0; attempt < 2; attempt++) {\n\t\t\t\tconst pending: AssistantMessageEvent[] = [];\n\t\t\t\tlet deliveredContent = false;\n\t\t\t\tlet rejection: AssistantMessageEvent | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tconst admission = await admitProviderStream(\n\t\t\t\t\t\tprepared.model,\n\t\t\t\t\t\tprepared.options,\n\t\t\t\t\t\townsTransport(prepared.model),\n\t\t\t\t\t);\n\t\t\t\t\tprepared = { ...prepared, options: admission.options };\n\t\t\t\t\toptions?.signal?.throwIfAborted();\n\t\t\t\t\tconst source = admission.run(() => invoke(prepared));\n\t\t\t\t\tlet terminal = false;\n\t\t\t\t\tfor await (const event of source) {\n\t\t\t\t\t\tif (event.type === \"error\") admission.observeFailure(event.error);\n\t\t\t\t\t\tif (event.type === \"done\") recordProviderSuccess(prepared.model.provider);\n\t\t\t\t\t\tif (event.type === \"start\") {\n\t\t\t\t\t\t\tpending.push(event);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tevent.type === \"error\" &&\n\t\t\t\t\t\t\t!deliveredContent &&\n\t\t\t\t\t\t\tattempt === 0 &&\n\t\t\t\t\t\t\tisCredentialRejection(event.error.errorMessage)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\trejection = event;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tyield* pending.splice(0);\n\t\t\t\t\t\tyield event;\n\t\t\t\t\t\tterminal = event.type === \"done\" || event.type === \"error\";\n\t\t\t\t\t\tdeliveredContent = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (!rejection && !terminal) {\n\t\t\t\t\t\tconst result = await source.result();\n\t\t\t\t\t\tif (result.stopReason !== \"error\" && result.stopReason !== \"aborted\")\n\t\t\t\t\t\t\trecordProviderSuccess(prepared.model.provider);\n\t\t\t\t\t\tif (result.stopReason === \"error\") admission.observeFailure(result);\n\t\t\t\t\t\tconst event: AssistantMessageEvent =\n\t\t\t\t\t\t\tresult.stopReason === \"error\" || result.stopReason === \"aborted\"\n\t\t\t\t\t\t\t\t? { type: \"error\", reason: result.stopReason, error: result }\n\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\ttype: \"done\",\n\t\t\t\t\t\t\t\t\t\treason: result.stopReason === \"pending\" ? \"stop\" : result.stopReason,\n\t\t\t\t\t\t\t\t\t\tmessage: result,\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!deliveredContent &&\n\t\t\t\t\t\t\tattempt === 0 &&\n\t\t\t\t\t\t\tresult.stopReason === \"error\" &&\n\t\t\t\t\t\t\tisCredentialRejection(result.errorMessage)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\trejection = event;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tyield* pending;\n\t\t\t\t\t\t\tyield event;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!deliveredContent && options?.signal?.aborted) {\n\t\t\t\t\t\tconst aborted: AssistantMessage = {\n\t\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\t\tapi: prepared.model.api,\n\t\t\t\t\t\t\tprovider: prepared.model.provider,\n\t\t\t\t\t\t\tmodel: prepared.model.id,\n\t\t\t\t\t\t\tcontent: [],\n\t\t\t\t\t\t\tusage: {\n\t\t\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tstopReason: \"aborted\",\n\t\t\t\t\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t};\n\t\t\t\t\t\tyield* pending;\n\t\t\t\t\t\tyield { type: \"error\", reason: \"aborted\", error: aborted };\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tdeliveredContent ||\n\t\t\t\t\t\tattempt !== 0 ||\n\t\t\t\t\t\t!isCredentialRejection(error instanceof Error ? error : String(error))\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\tconst next = await retry(prepared);\n\t\t\t\t\tif (!next) throw error;\n\t\t\t\t\tprepared = next;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!rejection) return;\n\t\t\t\tconst next = await retry(prepared);\n\t\t\t\tif (!next) {\n\t\t\t\t\tyield* pending;\n\t\t\t\t\tyield rejection;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tprepared = next;\n\t\t\t}\n\t\t};\n\t\treturn lazyStream(model, async () => iterate());\n\t}\n\tasync fetchDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): Promise<AssistantMessage> {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\tif (!prepared.provider.fetchDeferred) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t\t}\n\t\t\treturn prepared.provider.fetchDeferred(prepared.model, handle, prepared.options as DeferredFetchOptions);\n\t\t}).result();\n\t}\n\n\tasync cancelDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredCancelOptions,\n\t): Promise<void> {\n\t\tconst prepared = await this.prepareRequest(model, options);\n\t\tif (!prepared.provider.cancelDeferred) {\n\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t}\n\t\tawait prepared.provider.cancelDeferred(prepared.model, handle, prepared.options as DeferredCancelOptions);\n\t}\n}\n\nconst HTTP_401_PATTERN = /^\\W*401\\b|\\b(?:http|status|code|error)\\W{0,3}401\\b|\\(401\\)/i;\nconst CREDENTIAL_REJECTION_PATTERN =\n\t/unauthori[sz]ed|invalid(?:ated)?[_\\s-]*(?:api[_\\s-]*key|(?:access[_\\s-]*|auth[_\\s-]*|oauth[_\\s-]*)?token)|(?:token|api[_\\s-]*key)[_\\s-]*(?:(?:is|has[_\\s-]*been)[_\\s-]*)?(?:invalid|revoked|expired|invalidated)/i;\n\nfunction isCredentialRejection(error: object | string | undefined): boolean {\n\tif (error instanceof Error) {\n\t\tif ((\"status\" in error && error.status === 401) || (\"statusCode\" in error && error.statusCode === 401))\n\t\t\treturn true;\n\t\terror = error.message;\n\t}\n\treturn typeof error === \"string\" && (HTTP_401_PATTERN.test(error) || CREDENTIAL_REJECTION_PATTERN.test(error));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"model-runtime-streaming.js","sourceRoot":"","sources":["../../src/core/model-runtime-streaming.ts"],"names":[],"mappings":"AAAA,OAAO,EAON,eAAe,EAKf,yBAAyB,EACzB,UAAU,EAKV,WAAW,EAIX,gBAAgB,GAKhB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,sBAAsB,EAA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K,CAAC,cAAc,CACnB,KAAiB,EACjB,MAAsB,EACtB,OAAqC;QAErC,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;QAC3D,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,cAAc,EAAE,CAAC;YACvC,MAAM,IAAI,WAAW,CAAC,UAAU,EAAE,YAAY,KAAK,CAAC,QAAQ,sCAAsC,CAAC,CAAC;QACrG,CAAC;QACD,MAAM,QAAQ,CAAC,QAAQ,CAAC,cAAc,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC,OAAgC,CAAC,CAAC;IAC3G,CAAC;CACD;AAED,MAAM,gBAAgB,GAAG,6DAA6D,CAAC;AACvF,MAAM,4BAA4B,GACjC,mNAAmN,CAAC;AAErN,SAAS,qBAAqB,CAAC,KAAkC;IAChE,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;QAC5B,IAAI,CAAC,QAAQ,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,KAAK,GAAG,CAAC,IAAI,CAAC,YAAY,IAAI,KAAK,IAAI,KAAK,CAAC,UAAU,KAAK,GAAG,CAAC;YACrG,OAAO,IAAI,CAAC;QACb,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC;IACvB,CAAC;IACD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,4BAA4B,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;AAChH,CAAC","sourcesContent":["import {\n\ttype Api,\n\ttype ApiStreamOptions,\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype AssistantMessageEventStream,\n\ttype AuthResult,\n\tassertChatModel,\n\ttype Context,\n\ttype DeferredCancelOptions,\n\ttype DeferredFetchOptions,\n\ttype DeferredHandle,\n\tgetOpenCodeSessionHeaders,\n\tlazyStream,\n\ttype Model,\n\ttype ModelsApiStreamOptions,\n\ttype ModelsDeferredCancelOptions,\n\ttype ModelsDeferredFetchOptions,\n\tModelsError,\n\ttype ModelsRequestTransforms,\n\ttype ModelsSimpleStreamOptions,\n\ttype MutableModels,\n\tnormalizeContext,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@bastani/pi-ai\";\nimport { normalizeModelProvider } from \"./azure-provider-compat.js\";\nimport { usesChatGptCodexTransport, withChatGptCodexTransportRouting } from \"./fast-model-routing.ts\";\nimport { installCodexFastRouteWebSocketIdentity } from \"./fast-model-routing-transport.ts\";\nimport type { ModelRuntimeAuthOverrides } from \"./model-runtime-types.ts\";\nimport { recordProviderSuccess } from \"./provider-rate-limits.js\";\nimport { admitProviderStream } from \"./provider-request-admission.js\";\n\nexport function mergeHeaders(\n\tbase: ProviderHeaders | undefined,\n\toverride: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!base && !override) return undefined;\n\tconst merged = { ...base };\n\tfor (const [name, value] of Object.entries(override ?? {})) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tfor (const existingName of Object.keys(merged)) {\n\t\t\tif (existingName.toLowerCase() === lowerName) delete merged[existingName];\n\t\t}\n\t\tmerged[name] = value;\n\t}\n\treturn merged;\n}\n\n/** SDK-owned request-auth result so transport preparation does not start a second deadline. */\nexport interface PreparedRequestAuth {\n\treadonly resolution: AuthResult | undefined;\n\treadonly reprepare?: () => Promise<{ model: Model<Api>; options: ModelRuntimeSimpleStreamOptions }>;\n\treadonly streamSimple?: (\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions,\n\t) => AssistantMessageEventStream;\n}\n\nexport type ModelRuntimePreparedStreamOptions = StreamOptions &\n\tModelsRequestTransforms & {\n\t\tpreparedRequestAuth?: PreparedRequestAuth;\n\t};\n\nexport type ModelRuntimeSimpleStreamOptions = ModelsSimpleStreamOptions & {\n\tpreparedRequestAuth?: PreparedRequestAuth;\n};\n\ntype ResolveAuth = (model: Model<Api>, overrides?: ModelRuntimeAuthOverrides) => Promise<AuthResult | undefined>;\n/** Whether an extension owns this model's transport, in which case it owns its serialization too. */\ntype OwnsExtensionTransport = (model: Model<Api>) => boolean;\n\n/** Streaming request preparation split from ModelRuntime solely for Atomic's 500-line source gate. */\nexport class ModelRuntimeStreaming {\n\tprivate readonly models: MutableModels;\n\tprivate readonly resolveAuth: ResolveAuth;\n\tprivate readonly ownsExtensionTransport: OwnsExtensionTransport;\n\tprivate readonly transportModel: (model: Model<Api>) => Model<Api>;\n\tprivate readonly reloadCredentials: () => Promise<void>;\n\tconstructor(\n\t\tmodels: MutableModels,\n\t\tresolveAuth: ResolveAuth,\n\t\townsExtensionTransport: OwnsExtensionTransport,\n\t\ttransportModel: (model: Model<Api>) => Model<Api> = (model) => model,\n\t\treloadCredentials: () => Promise<void> = async () => {},\n\t) {\n\t\tthis.models = models;\n\t\tthis.resolveAuth = resolveAuth;\n\t\tthis.ownsExtensionTransport = ownsExtensionTransport;\n\t\tthis.transportModel = transportModel;\n\t\tthis.reloadCredentials = reloadCredentials;\n\t}\n\n\t/**\n\t * Attach the first-party ChatGPT Codex routing identity to a prepared request.\n\t *\n\t * This must happen *after* `prepareRequest`, not before it. The wrapper works by mutating the\n\t * header object it captures at construction, and `prepareRequest` rebuilds headers through\n\t * `mergeHeaders`, which copies — so a wrapper applied upstream is silently inert. The wrapper\n\t * decides from the final payload whether the request is priority, so a normal model still ends up\n\t * with `originator: pi` and no routing hint.\n\t */\n\tprivate withCodexRouting<TOptions extends StreamOptions>(model: Model<Api>, options: TOptions): TOptions {\n\t\tmodel = this.transportModel(model);\n\t\tif (!usesChatGptCodexTransport(model) || this.ownsExtensionTransport(model)) return options;\n\t\t// The WebSocket handshake builds its headers inside pi-ai and the constructor can be cached, so\n\t\t// the identity is repaired through the global constructor rather than per-request options. CLI\n\t\t// entrypoints install this through the HTTP dispatcher; a pure SDK embedder never does.\n\t\tif (options.transport !== \"sse\") installCodexFastRouteWebSocketIdentity();\n\t\treturn withChatGptCodexTransportRouting(model, options);\n\t}\n\n\tprivate async prepareRequest(\n\t\tmodel: Model<Api>,\n\t\toptions: ModelRuntimePreparedStreamOptions | undefined,\n\t): Promise<{ provider: Provider; model: Model<Api>; options: StreamOptions; authIdentity: string }> {\n\t\tassertChatModel(model);\n\t\tmodel = normalizeModelProvider(model);\n\t\tconst provider = this.models.getProvider(model.provider);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\tconst { transformHeaders, preparedRequestAuth, ...providerOptions } = options ?? {};\n\t\tconst resolution = preparedRequestAuth\n\t\t\t? preparedRequestAuth.resolution\n\t\t\t: await this.resolveAuth(model, {\n\t\t\t\t\tapiKey: options?.apiKey,\n\t\t\t\t\tenv: options?.env,\n\t\t\t\t\tsignal: options?.signal,\n\t\t\t\t});\n\t\toptions?.signal?.throwIfAborted();\n\t\tif (!resolution) throw new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\n\t\tconst requestModel = resolution.auth.baseUrl ? { ...model, baseUrl: resolution.auth.baseUrl } : model;\n\t\t// An SDK-prepared request already carries the session header, which `before_provider_headers`\n\t\t// handlers may have removed, so only other requests add it here.\n\t\tconst sessionHeaders = preparedRequestAuth\n\t\t\t? undefined\n\t\t\t: getOpenCodeSessionHeaders(requestModel, providerOptions.sessionId);\n\t\tlet headers = mergeHeaders(mergeHeaders(sessionHeaders, resolution.auth.headers), providerOptions.headers);\n\t\tif (transformHeaders) headers = await transformHeaders(headers ?? {});\n\t\toptions?.signal?.throwIfAborted();\n\t\tconst env =\n\t\t\tresolution.env || providerOptions.env\n\t\t\t\t? { ...(resolution.env ?? {}), ...(providerOptions.env ?? {}) }\n\t\t\t\t: undefined;\n\t\tconst apiKey = providerOptions.apiKey ?? resolution.auth.apiKey;\n\t\tconst credentialHeaderNames = new Set(\n\t\t\tObject.keys(resolution.auth.headers ?? {}).map((name) => name.toLowerCase()),\n\t\t);\n\t\treturn {\n\t\t\tprovider,\n\t\t\tauthIdentity: JSON.stringify({\n\t\t\t\tapiKey,\n\t\t\t\theaders: Object.entries(headers ?? {})\n\t\t\t\t\t.map(([name, value]) => [name.toLowerCase(), value] as const)\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t([name]) =>\n\t\t\t\t\t\t\tcredentialHeaderNames.has(name) ||\n\t\t\t\t\t\t\t/^(?:authorization|proxy-authorization|x-api-key|api-key|cookie)$/.test(name),\n\t\t\t\t\t)\n\t\t\t\t\t.sort(([left], [right]) => left.localeCompare(right)),\n\t\t\t\tenv: Object.entries(env ?? {}).sort(([left], [right]) => left.localeCompare(right)),\n\t\t\t\tbaseUrl: resolution.auth.baseUrl ?? model.baseUrl,\n\t\t\t}),\n\t\t\tmodel: requestModel,\n\t\t\toptions: {\n\t\t\t\t...providerOptions,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tenv,\n\t\t\t},\n\t\t};\n\t}\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream {\n\t\tconst transcript = normalizeContext(context);\n\t\treturn this.streamWithCredentialRetry(model, options, (prepared) =>\n\t\t\tprepared.provider.stream(\n\t\t\t\tprepared.model as Model<TApi>,\n\t\t\t\ttranscript,\n\t\t\t\tthis.withCodexRouting(prepared.model, prepared.options) as ApiStreamOptions<TApi>,\n\t\t\t),\n\t\t);\n\t}\n\n\tcomplete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage> {\n\t\treturn this.stream(model, context, options).result();\n\t}\n\n\tstreamSimple(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions?: ModelRuntimeSimpleStreamOptions,\n\t): AssistantMessageEventStream {\n\t\tconst transcript = normalizeContext(context);\n\t\tconst dispatch = options?.preparedRequestAuth?.streamSimple;\n\t\treturn this.streamWithCredentialRetry(model, options, (prepared) =>\n\t\t\tdispatch\n\t\t\t\t? dispatch(prepared.model, context, prepared.options as SimpleStreamOptions)\n\t\t\t\t: prepared.provider.streamSimple(\n\t\t\t\t\t\tprepared.model,\n\t\t\t\t\t\ttranscript,\n\t\t\t\t\t\tthis.withCodexRouting(prepared.model, prepared.options) as SimpleStreamOptions,\n\t\t\t\t\t),\n\t\t);\n\t}\n\n\tcompleteSimple(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions?: ModelRuntimeSimpleStreamOptions,\n\t): Promise<AssistantMessage> {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n\n\tprivate streamWithCredentialRetry(\n\t\tmodel: Model<Api>,\n\t\toptions: ModelRuntimePreparedStreamOptions | undefined,\n\t\tinvoke: (prepared: Awaited<ReturnType<ModelRuntimeStreaming[\"prepareRequest\"]>>) => AssistantMessageEventStream,\n\t): AssistantMessageEventStream {\n\t\tconst prepare = () => this.prepareRequest(model, options);\n\t\tconst reprepareCredentials = async (previous: Awaited<ReturnType<typeof prepare>>) => {\n\t\t\tif (options?.signal?.aborted) return undefined;\n\t\t\tawait this.reloadCredentials();\n\t\t\tconst { preparedRequestAuth: previousAuth, ...callerOptions } = options ?? {};\n\t\t\tconst reprepared = previousAuth?.reprepare ? await previousAuth.reprepare() : undefined;\n\t\t\tconst next = reprepared\n\t\t\t\t? await this.prepareRequest(reprepared.model, {\n\t\t\t\t\t\t...callerOptions,\n\t\t\t\t\t\tapiKey: reprepared.options.apiKey,\n\t\t\t\t\t\theaders: reprepared.options.headers,\n\t\t\t\t\t\tenv: reprepared.options.env,\n\t\t\t\t\t\tpreparedRequestAuth: reprepared.options.preparedRequestAuth,\n\t\t\t\t\t})\n\t\t\t\t: await this.prepareRequest(model, callerOptions);\n\t\t\treturn next.authIdentity !== previous.authIdentity ? next : undefined;\n\t\t};\n\t\tconst retry = (previous: Awaited<ReturnType<typeof prepare>>) =>\n\t\t\treprepareCredentials(previous).catch(() => undefined);\n\t\tconst ownsTransport = (requestModel: Model<Api>) => this.ownsExtensionTransport(requestModel);\n\t\tconst iterate = async function* (): AsyncGenerator<AssistantMessageEvent> {\n\t\t\tlet prepared = await prepare();\n\t\t\tfor (let attempt = 0; attempt < 2; attempt++) {\n\t\t\t\tconst pending: AssistantMessageEvent[] = [];\n\t\t\t\tlet deliveredContent = false;\n\t\t\t\tlet rejection: AssistantMessageEvent | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tconst admission = await admitProviderStream(\n\t\t\t\t\t\tprepared.model,\n\t\t\t\t\t\tprepared.options,\n\t\t\t\t\t\townsTransport(prepared.model),\n\t\t\t\t\t);\n\t\t\t\t\tprepared = { ...prepared, options: admission.options };\n\t\t\t\t\toptions?.signal?.throwIfAborted();\n\t\t\t\t\tconst source = admission.run(() => invoke(prepared));\n\t\t\t\t\tlet terminal = false;\n\t\t\t\t\tfor await (const event of source) {\n\t\t\t\t\t\tif (event.type === \"error\") admission.observeFailure(event.error);\n\t\t\t\t\t\tif (event.type === \"done\") recordProviderSuccess(prepared.model.provider, prepared.model.id);\n\t\t\t\t\t\tif (event.type === \"start\") {\n\t\t\t\t\t\t\tpending.push(event);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tevent.type === \"error\" &&\n\t\t\t\t\t\t\t!deliveredContent &&\n\t\t\t\t\t\t\tattempt === 0 &&\n\t\t\t\t\t\t\tisCredentialRejection(event.error.errorMessage)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\trejection = event;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tyield* pending.splice(0);\n\t\t\t\t\t\tyield event;\n\t\t\t\t\t\tterminal = event.type === \"done\" || event.type === \"error\";\n\t\t\t\t\t\tdeliveredContent = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (!rejection && !terminal) {\n\t\t\t\t\t\tconst result = await source.result();\n\t\t\t\t\t\tif (result.stopReason !== \"error\" && result.stopReason !== \"aborted\")\n\t\t\t\t\t\t\trecordProviderSuccess(prepared.model.provider, prepared.model.id);\n\t\t\t\t\t\tif (result.stopReason === \"error\") admission.observeFailure(result);\n\t\t\t\t\t\tconst event: AssistantMessageEvent =\n\t\t\t\t\t\t\tresult.stopReason === \"error\" || result.stopReason === \"aborted\"\n\t\t\t\t\t\t\t\t? { type: \"error\", reason: result.stopReason, error: result }\n\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\ttype: \"done\",\n\t\t\t\t\t\t\t\t\t\treason: result.stopReason === \"pending\" ? \"stop\" : result.stopReason,\n\t\t\t\t\t\t\t\t\t\tmessage: result,\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!deliveredContent &&\n\t\t\t\t\t\t\tattempt === 0 &&\n\t\t\t\t\t\t\tresult.stopReason === \"error\" &&\n\t\t\t\t\t\t\tisCredentialRejection(result.errorMessage)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\trejection = event;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tyield* pending;\n\t\t\t\t\t\t\tyield event;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!deliveredContent && options?.signal?.aborted) {\n\t\t\t\t\t\tconst aborted: AssistantMessage = {\n\t\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\t\tapi: prepared.model.api,\n\t\t\t\t\t\t\tprovider: prepared.model.provider,\n\t\t\t\t\t\t\tmodel: prepared.model.id,\n\t\t\t\t\t\t\tcontent: [],\n\t\t\t\t\t\t\tusage: {\n\t\t\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tstopReason: \"aborted\",\n\t\t\t\t\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t};\n\t\t\t\t\t\tyield* pending;\n\t\t\t\t\t\tyield { type: \"error\", reason: \"aborted\", error: aborted };\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tdeliveredContent ||\n\t\t\t\t\t\tattempt !== 0 ||\n\t\t\t\t\t\t!isCredentialRejection(error instanceof Error ? error : String(error))\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\tconst next = await retry(prepared);\n\t\t\t\t\tif (!next) throw error;\n\t\t\t\t\tprepared = next;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!rejection) return;\n\t\t\t\tconst next = await retry(prepared);\n\t\t\t\tif (!next) {\n\t\t\t\t\tyield* pending;\n\t\t\t\t\tyield rejection;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tprepared = next;\n\t\t\t}\n\t\t};\n\t\treturn lazyStream(model, async () => iterate());\n\t}\n\tasync fetchDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): Promise<AssistantMessage> {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\tif (!prepared.provider.fetchDeferred) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t\t}\n\t\t\treturn prepared.provider.fetchDeferred(prepared.model, handle, prepared.options as DeferredFetchOptions);\n\t\t}).result();\n\t}\n\n\tasync cancelDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredCancelOptions,\n\t): Promise<void> {\n\t\tconst prepared = await this.prepareRequest(model, options);\n\t\tif (!prepared.provider.cancelDeferred) {\n\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t}\n\t\tawait prepared.provider.cancelDeferred(prepared.model, handle, prepared.options as DeferredCancelOptions);\n\t}\n}\n\nconst HTTP_401_PATTERN = /^\\W*401\\b|\\b(?:http|status|code|error)\\W{0,3}401\\b|\\(401\\)/i;\nconst CREDENTIAL_REJECTION_PATTERN =\n\t/unauthori[sz]ed|invalid(?:ated)?[_\\s-]*(?:api[_\\s-]*key|(?:access[_\\s-]*|auth[_\\s-]*|oauth[_\\s-]*)?token)|(?:token|api[_\\s-]*key)[_\\s-]*(?:(?:is|has[_\\s-]*been)[_\\s-]*)?(?:invalid|revoked|expired|invalidated)/i;\n\nfunction isCredentialRejection(error: object | string | undefined): boolean {\n\tif (error instanceof Error) {\n\t\tif ((\"status\" in error && error.status === 401) || (\"statusCode\" in error && error.statusCode === 401))\n\t\t\treturn true;\n\t\terror = error.message;\n\t}\n\treturn typeof error === \"string\" && (HTTP_401_PATTERN.test(error) || CREDENTIAL_REJECTION_PATTERN.test(error));\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-composer.d.ts","sourceRoot":"","sources":["../../src/core/provider-composer.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,QAAQ,EAUb,KAAK,QAAQ,EACb,KAAK,eAAe,EAIpB,MAAM,gBAAgB,CAAC;AAExB,OAAO,KAAK,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACzE,OAAO,KAAK,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AAkBvF,YAAY,EAAE,UAAU,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AAC7G,OAAO,EAAE,gBAAgB,EAAE,MAA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M,EAAE,kBAAkB,GAAG,SAAS,EACtC,SAAS,EAAE,mBAAmB,GAAG,SAAS,EAC1C,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAC1B,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAMpC;AAED,MAAM,WAAW,0BAA0B;IAC1C,OAAO,CAAC,EAAE,eAAe,CAAC;IAC1B,UAAU,EAAE,OAAO,CAAC;CACpB;AAED,wBAAgB,iCAAiC,CAChD,KAAK,EAAE,QAAQ,EACf,MAAM,EAAE,kBAAkB,GAAG,SAAS,EACtC,SAAS,EAAE,mBAAmB,GAAG,SAAS,GACxC,0BAA0B,CAS5B;AAED,wBAAgB,2BAA2B,CAC1C,MAAM,EAAE,kBAAkB,GAAG,SAAS,EACtC,SAAS,EAAE,mBAAmB,GAAG,SAAS,GACxC,UAAU,GAAG,SAAS,CAWxB"}
|
|
@@ -99,17 +99,25 @@ export function composeModelProvider(providerId, base, modelConfig, extension) {
|
|
|
99
99
|
}
|
|
100
100
|
: undefined,
|
|
101
101
|
filterModels: base?.filterModels
|
|
102
|
-
? (models, credential) =>
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
const
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
102
|
+
? (models, credential) => {
|
|
103
|
+
// Models the user defines in models.json are an explicit choice: the base provider's
|
|
104
|
+
// account filter (such as GitHub Copilot's model list) must not hide them.
|
|
105
|
+
const isConfigured = (model) => config?.models?.some((entry) => entry.id === model.id) === true;
|
|
106
|
+
const filtered = new Map(base.filterModels(models, credential).map((model) => [model.id, model]));
|
|
107
|
+
return models.flatMap((original) => {
|
|
108
|
+
if (isConfigured(original))
|
|
109
|
+
return [original];
|
|
110
|
+
const model = filtered.get(original.id);
|
|
111
|
+
if (model === undefined)
|
|
112
|
+
return [];
|
|
113
|
+
const inheritedContext = model.fastRoute
|
|
114
|
+
? config?.modelOverrides?.[model.fastRoute.baseModelId]?.contextWindow
|
|
115
|
+
: undefined;
|
|
116
|
+
const personalized = inheritedContext === undefined ? model : { ...model, contextWindow: inheritedContext };
|
|
117
|
+
const override = config?.modelOverrides?.[model.id];
|
|
118
|
+
return [override ? applyModelOverride(personalized, override) : personalized];
|
|
119
|
+
});
|
|
120
|
+
}
|
|
113
121
|
: undefined,
|
|
114
122
|
filterAllModels: base?.filterAllModels
|
|
115
123
|
? (models, credential) => base.filterAllModels(models, credential)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-composer.js","sourceRoot":"","sources":["../../src/core/provider-composer.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,qBAAqB,EACrB,gBAAgB,EAChB,WAAW,EACX,UAAU,GAQV,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAGvD,OAAO,EACN,cAAc,EACd,kBAAkB,EAClB,eAAe,EACf,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,eAAe,GACf,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACN,yBAAyB,EACzB,oBAAoB,EACpB,uBAAuB,EACvB,qBAAqB,GACrB,MAAM,2BAA2B,CAAC;AAGnC,OAAO,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AAEnE,SAAS,oBAAoB,CAAC,QAA8B;IAC3D,OAAO,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,YAAY,EAAE,EAAE,IAAI,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAC5E,CAAC;AAED,MAAM,UAAU,yBAAyB,CACxC,UAAkB,EAClB,IAA0B,EAC1B,YAA4C,EAC5C,SAA8B;IAE9B,IAAI,SAAS,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;QACrC,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,IA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,MAAM,EAAE,aAAa,EAAE,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;YACtE,CAAC,CAAC,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;IAC1B,CAAC;IACD,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,iBAAiB,EAAE,CAAC;AACvG,CAAC","sourcesContent":["import {\n\ttype AnyModel,\n\ttype Api,\n\ttype AssistantMessageEventStream,\n\ttype Credential,\n\tclassifierErrorResult,\n\timageErrorResult,\n\tisModelType,\n\tlazyStream,\n\ttype Model,\n\ttype OAuthCredentials,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n\ttype TranscriptContext,\n} from \"@bastani/pi-ai\";\nimport { getApiProvider } from \"@bastani/pi-ai/compat\";\nimport type { ModelConfig, ModelsJsonProvider } from \"./model-config.ts\";\nimport type { AuthStatus, ProviderConfigInput } from \"./provider-composer-internal.ts\";\nimport {\n\tapplyExtension,\n\tapplyModelOverride,\n\tapplyModelsJson,\n\tcomposeApiKeyAuth,\n\tcomposeOAuthAuth,\n\tconfiguredApiKey,\n\tconfiguredHeaders,\n\trawModelHeaders,\n} from \"./provider-composer-internal.ts\";\nimport {\n\tgetConfigValueEnvVarNames,\n\tisCommandConfigValue,\n\tisConfigValueConfigured,\n\tresolveHeadersOrThrow,\n} from \"./resolve-config-value.ts\";\n\nexport type { AuthStatus, ExtensionOAuthConfig, ProviderConfigInput } from \"./provider-composer-internal.ts\";\nexport { clearApiKeyCache } from \"./provider-composer-internal.ts\";\n\nfunction getAllProviderModels(provider: Provider | undefined): readonly AnyModel[] {\n\treturn provider ? (provider.getAllModels?.() ?? provider.getModels()) : [];\n}\n\nexport function validateExtensionProvider(\n\tproviderId: string,\n\tbase: Provider | undefined,\n\tmodelsConfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput,\n): void {\n\tif (extension.aliasOf !== undefined) {\n\t\tif (!providerId.trim() || !extension.aliasOf.trim() || providerId === extension.aliasOf) {\n\t\t\tthrow new Error(\"A provider alias needs distinct, non-empty alias and source IDs.\");\n\t\t}\n\t\tif (Object.keys(extension).some((key) => ![\"aliasOf\", \"name\"].includes(key))) {\n\t\t\tthrow new Error(\"Provider aliases accept only aliasOf and name; configure the source provider instead.\");\n\t\t}\n\t\treturn;\n\t}\n\tif (extension.streamSimple && !extension.api) {\n\t\tthrow new Error(`Provider ${providerId}: \"api\" is required when registering streamSimple.`);\n\t}\n\tapplyExtension(providerId, applyModelsJson(providerId, getAllProviderModels(base), modelsConfig), extension);\n}\n\n/** Compose built-in, models.json, and extension layers without reading credentials. */\nexport function composeModelProvider(\n\tproviderId: string,\n\tbase: Provider | undefined,\n\tmodelConfig: ModelConfig,\n\textension: ProviderConfigInput | undefined,\n): Provider {\n\tconst config = modelConfig.getProvider(providerId);\n\tlet extensionOAuthCredential: OAuthCredentials | undefined;\n\tlet refreshedExtensionModels: ProviderConfigInput[\"models\"];\n\tconst currentExtension = (): ProviderConfigInput | undefined =>\n\t\textension && refreshedExtensionModels ? { ...extension, models: refreshedExtensionModels } : extension;\n\t// models.json modelOverrides are the topmost user-config layer: they apply once,\n\t// after custom-model upserts, extension model replacement, and legacy OAuth projection.\n\tconst getAllModels = (): AnyModel[] => {\n\t\tlet models = applyExtension(\n\t\t\tproviderId,\n\t\t\tapplyModelsJson(providerId, getAllProviderModels(base), config),\n\t\t\tcurrentExtension(),\n\t\t);\n\t\tif (extensionOAuthCredential && extension?.oauth?.modifyModels) {\n\t\t\t// The extension hook is chat-only; other model types pass through untouched.\n\t\t\tmodels = [\n\t\t\t\t...extension.oauth.modifyModels(\n\t\t\t\t\tmodels.filter((model) => isModelType(model, \"chat\")),\n\t\t\t\t\textensionOAuthCredential,\n\t\t\t\t),\n\t\t\t\t...models.filter((model) => !isModelType(model, \"chat\")),\n\t\t\t];\n\t\t}\n\t\treturn models.map((model) => {\n\t\t\tconst override = config?.modelOverrides?.[model.id];\n\t\t\treturn override && isModelType(model, \"chat\") ? applyModelOverride(model, override) : model;\n\t\t});\n\t};\n\t// Validate eagerly so registration/reload reports structural errors immediately.\n\tgetAllModels();\n\tconst apiKey = composeApiKeyAuth(providerId, base, config, extension);\n\tconst oauth = composeOAuthAuth(providerId, base, config, extension);\n\tif (!apiKey && !oauth) throw new Error(`Provider ${providerId}: no authentication method configured.`);\n\n\tconst supportsBaseApi = (model: Model<Api>) => base?.getModels().some((entry) => entry.api === model.api) ?? false;\n\tconst streamWith = (\n\t\tmodel: Model<Api>,\n\t\tcontext: TranscriptContext,\n\t\toptions: StreamOptions | undefined,\n\t\tsimple: boolean,\n\t): AssistantMessageEventStream =>\n\t\tlazyStream(model, async () => {\n\t\t\tif (extension?.streamSimple && model.api === extension.api) {\n\t\t\t\treturn extension.streamSimple(model, context, options as SimpleStreamOptions);\n\t\t\t}\n\t\t\tif (base && supportsBaseApi(model)) {\n\t\t\t\treturn simple\n\t\t\t\t\t? base.streamSimple(model, context, options as SimpleStreamOptions)\n\t\t\t\t\t: base.stream(model, context, options);\n\t\t\t}\n\t\t\tconst api = getApiProvider(model.api);\n\t\t\tif (!api) throw new Error(`No API provider registered for api: ${model.api}`);\n\t\t\treturn simple\n\t\t\t\t? api.streamSimple(model, context, options as SimpleStreamOptions)\n\t\t\t\t: api.stream(model, context, options);\n\t\t});\n\n\tconst provider: Provider = {\n\t\tid: providerId,\n\t\tname: extension?.name ?? config?.name ?? base?.name ?? extension?.oauth?.name ?? providerId,\n\t\tbaseUrl: extension?.baseUrl ?? config?.baseUrl ?? base?.baseUrl,\n\t\theaders: base?.headers,\n\t\tauth: { ...(apiKey ? { apiKey } : {}), ...(oauth ? { oauth } : {}) },\n\t\tgetModels: () => getAllModels().filter((model) => isModelType(model, \"chat\")),\n\t\tgetAllModels,\n\t\trefreshModels:\n\t\t\tbase?.refreshModels || extension?.refreshModels || extension?.oauth?.modifyModels\n\t\t\t\t? async (context) => {\n\t\t\t\t\t\tawait base?.refreshModels?.(context);\n\t\t\t\t\t\tlet refreshed: NonNullable<ProviderConfigInput[\"models\"]> | undefined;\n\t\t\t\t\t\tif (extension?.refreshModels) refreshed = await extension.refreshModels(context);\n\t\t\t\t\t\tif (context.signal.aborted) return;\n\t\t\t\t\t\tconst oauthCredential = context.credential?.type === \"oauth\" ? context.credential : undefined;\n\t\t\t\t\t\tawait context.publish({\n\t\t\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\t\t\tif (refreshed) {\n\t\t\t\t\t\t\t\t\t// Validate before publishing the new synchronous list.\n\t\t\t\t\t\t\t\t\tapplyExtension(providerId, applyModelsJson(providerId, getAllProviderModels(base), config), {\n\t\t\t\t\t\t\t\t\t\t...extension,\n\t\t\t\t\t\t\t\t\t\tmodels: refreshed,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\trefreshedExtensionModels = refreshed;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\textensionOAuthCredential = oauthCredential;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\tfilterModels: base?.filterModels\n\t\t\t? (models, credential: Credential | undefined) =>\n\t\t\t\t\tbase.filterModels!(models, credential).map((model) => {\n\t\t\t\t\t\tconst original = models.find((entry) => entry.id === model.id);\n\t\t\t\t\t\tif (config?.models?.some((entry) => entry.id === model.id)) return original ?? model;\n\t\t\t\t\t\tconst inheritedContext = model.fastRoute\n\t\t\t\t\t\t\t? config?.modelOverrides?.[model.fastRoute.baseModelId]?.contextWindow\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tconst personalized =\n\t\t\t\t\t\t\tinheritedContext === undefined ? model : { ...model, contextWindow: inheritedContext };\n\t\t\t\t\t\tconst override = config?.modelOverrides?.[model.id];\n\t\t\t\t\t\treturn override ? applyModelOverride(personalized, override) : personalized;\n\t\t\t\t\t})\n\t\t\t: undefined,\n\t\tfilterAllModels: base?.filterAllModels\n\t\t\t? (models, credential: Credential | undefined) => base.filterAllModels!(models, credential)\n\t\t\t: undefined,\n\t\tstream: (model, context, options) => streamWith(model, context, options, false),\n\t\tstreamSimple: (model, context, options) => streamWith(model, context, options, true),\n\t};\n\n\tconst fetchDeferred = base?.fetchDeferred;\n\tif (fetchDeferred) {\n\t\tprovider.fetchDeferred = (model, handle, options) => fetchDeferred(model, handle, options);\n\t}\n\tconst cancelDeferred = base?.cancelDeferred;\n\tif (cancelDeferred) {\n\t\tprovider.cancelDeferred = (model, handle, options) => cancelDeferred(model, handle, options);\n\t}\n\tconst extensionImages = extension?.images;\n\tconst generateImages = base?.generateImages;\n\tif (generateImages || Object.keys(extensionImages ?? {}).length > 0) {\n\t\tprovider.generateImages = (model, context, options) => {\n\t\t\tconst implementation = extensionImages?.[model.api];\n\t\t\tif (implementation) return implementation.generateImages(model, context, options);\n\t\t\tif (generateImages) return generateImages(model, context, options);\n\t\t\treturn Promise.resolve(\n\t\t\t\timageErrorResult(model, new Error(`Provider ${providerId} has no image implementation for \"${model.api}\"`)),\n\t\t\t);\n\t\t};\n\t}\n\tconst extensionClassifiers = extension?.classifiers;\n\tconst classify = base?.classify;\n\tif (classify || Object.keys(extensionClassifiers ?? {}).length > 0) {\n\t\tprovider.classify = (model, context, options) => {\n\t\t\tconst implementation = extensionClassifiers?.[model.api];\n\t\t\tif (implementation) return implementation.classify(model, context, options);\n\t\t\tif (classify) return classify(model, context, options);\n\t\t\treturn Promise.resolve(\n\t\t\t\tclassifierErrorResult(\n\t\t\t\t\tmodel,\n\t\t\t\t\tnew Error(`Provider ${providerId} has no classifier implementation for \"${model.api}\"`),\n\t\t\t\t),\n\t\t\t);\n\t\t};\n\t}\n\n\treturn provider;\n}\n\nexport function resolveConfiguredModelHeaders(\n\tmodel: AnyModel,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n\tenv?: Record<string, string>,\n): Record<string, string> | undefined {\n\treturn resolveHeadersOrThrow(\n\t\trawModelHeaders(model, config, extension),\n\t\t`model \"${model.provider}/${model.id}\"`,\n\t\tenv,\n\t);\n}\n\nexport interface CompatibilityRequestConfig {\n\theaders?: ProviderHeaders;\n\tauthHeader: boolean;\n}\n\nexport function resolveCompatibilityRequestConfig(\n\tmodel: AnyModel,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): CompatibilityRequestConfig {\n\tconst configured = resolveHeadersOrThrow(\n\t\t{ ...configuredHeaders(config, extension), ...rawModelHeaders(model, config, extension) },\n\t\t`model \"${model.provider}/${model.id}\"`,\n\t);\n\treturn {\n\t\theaders: model.headers || configured ? { ...model.headers, ...configured } : undefined,\n\t\tauthHeader: extension?.authHeader ?? config?.authHeader ?? false,\n\t};\n}\n\nexport function configuredRequestAuthStatus(\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): AuthStatus | undefined {\n\tconst value = configuredApiKey(config, extension);\n\tif (value === undefined) return undefined;\n\tif (isCommandConfigValue(value)) return { configured: true, source: \"models_json_command\" };\n\tconst names = getConfigValueEnvVarNames(value);\n\tif (names.length > 0) {\n\t\treturn isConfigValueConfigured(value)\n\t\t\t? { configured: true, source: \"environment\", label: names.join(\", \") }\n\t\t\t: { configured: false };\n\t}\n\treturn { configured: true, source: extension?.apiKey !== undefined ? \"fallback\" : \"models_json_key\" };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"provider-composer.js","sourceRoot":"","sources":["../../src/core/provider-composer.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,qBAAqB,EACrB,gBAAgB,EAChB,WAAW,EACX,UAAU,GAQV,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAGvD,OAAO,EACN,cAAc,EACd,kBAAkB,EAClB,eAAe,EACf,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,EACh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el,\n\ttype Api,\n\ttype AssistantMessageEventStream,\n\ttype Credential,\n\tclassifierErrorResult,\n\timageErrorResult,\n\tisModelType,\n\tlazyStream,\n\ttype Model,\n\ttype OAuthCredentials,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n\ttype TranscriptContext,\n} from \"@bastani/pi-ai\";\nimport { getApiProvider } from \"@bastani/pi-ai/compat\";\nimport type { ModelConfig, ModelsJsonProvider } from \"./model-config.ts\";\nimport type { AuthStatus, ProviderConfigInput } from \"./provider-composer-internal.ts\";\nimport {\n\tapplyExtension,\n\tapplyModelOverride,\n\tapplyModelsJson,\n\tcomposeApiKeyAuth,\n\tcomposeOAuthAuth,\n\tconfiguredApiKey,\n\tconfiguredHeaders,\n\trawModelHeaders,\n} from \"./provider-composer-internal.ts\";\nimport {\n\tgetConfigValueEnvVarNames,\n\tisCommandConfigValue,\n\tisConfigValueConfigured,\n\tresolveHeadersOrThrow,\n} from \"./resolve-config-value.ts\";\n\nexport type { AuthStatus, ExtensionOAuthConfig, ProviderConfigInput } from \"./provider-composer-internal.ts\";\nexport { clearApiKeyCache } from \"./provider-composer-internal.ts\";\n\nfunction getAllProviderModels(provider: Provider | undefined): readonly AnyModel[] {\n\treturn provider ? (provider.getAllModels?.() ?? provider.getModels()) : [];\n}\n\nexport function validateExtensionProvider(\n\tproviderId: string,\n\tbase: Provider | undefined,\n\tmodelsConfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput,\n): void {\n\tif (extension.aliasOf !== undefined) {\n\t\tif (!providerId.trim() || !extension.aliasOf.trim() || providerId === extension.aliasOf) {\n\t\t\tthrow new Error(\"A provider alias needs distinct, non-empty alias and source IDs.\");\n\t\t}\n\t\tif (Object.keys(extension).some((key) => ![\"aliasOf\", \"name\"].includes(key))) {\n\t\t\tthrow new Error(\"Provider aliases accept only aliasOf and name; configure the source provider instead.\");\n\t\t}\n\t\treturn;\n\t}\n\tif (extension.streamSimple && !extension.api) {\n\t\tthrow new Error(`Provider ${providerId}: \"api\" is required when registering streamSimple.`);\n\t}\n\tapplyExtension(providerId, applyModelsJson(providerId, getAllProviderModels(base), modelsConfig), extension);\n}\n\n/** Compose built-in, models.json, and extension layers without reading credentials. */\nexport function composeModelProvider(\n\tproviderId: string,\n\tbase: Provider | undefined,\n\tmodelConfig: ModelConfig,\n\textension: ProviderConfigInput | undefined,\n): Provider {\n\tconst config = modelConfig.getProvider(providerId);\n\tlet extensionOAuthCredential: OAuthCredentials | undefined;\n\tlet refreshedExtensionModels: ProviderConfigInput[\"models\"];\n\tconst currentExtension = (): ProviderConfigInput | undefined =>\n\t\textension && refreshedExtensionModels ? { ...extension, models: refreshedExtensionModels } : extension;\n\t// models.json modelOverrides are the topmost user-config layer: they apply once,\n\t// after custom-model upserts, extension model replacement, and legacy OAuth projection.\n\tconst getAllModels = (): AnyModel[] => {\n\t\tlet models = applyExtension(\n\t\t\tproviderId,\n\t\t\tapplyModelsJson(providerId, getAllProviderModels(base), config),\n\t\t\tcurrentExtension(),\n\t\t);\n\t\tif (extensionOAuthCredential && extension?.oauth?.modifyModels) {\n\t\t\t// The extension hook is chat-only; other model types pass through untouched.\n\t\t\tmodels = [\n\t\t\t\t...extension.oauth.modifyModels(\n\t\t\t\t\tmodels.filter((model) => isModelType(model, \"chat\")),\n\t\t\t\t\textensionOAuthCredential,\n\t\t\t\t),\n\t\t\t\t...models.filter((model) => !isModelType(model, \"chat\")),\n\t\t\t];\n\t\t}\n\t\treturn models.map((model) => {\n\t\t\tconst override = config?.modelOverrides?.[model.id];\n\t\t\treturn override && isModelType(model, \"chat\") ? applyModelOverride(model, override) : model;\n\t\t});\n\t};\n\t// Validate eagerly so registration/reload reports structural errors immediately.\n\tgetAllModels();\n\tconst apiKey = composeApiKeyAuth(providerId, base, config, extension);\n\tconst oauth = composeOAuthAuth(providerId, base, config, extension);\n\tif (!apiKey && !oauth) throw new Error(`Provider ${providerId}: no authentication method configured.`);\n\n\tconst supportsBaseApi = (model: Model<Api>) => base?.getModels().some((entry) => entry.api === model.api) ?? false;\n\tconst streamWith = (\n\t\tmodel: Model<Api>,\n\t\tcontext: TranscriptContext,\n\t\toptions: StreamOptions | undefined,\n\t\tsimple: boolean,\n\t): AssistantMessageEventStream =>\n\t\tlazyStream(model, async () => {\n\t\t\tif (extension?.streamSimple && model.api === extension.api) {\n\t\t\t\treturn extension.streamSimple(model, context, options as SimpleStreamOptions);\n\t\t\t}\n\t\t\tif (base && supportsBaseApi(model)) {\n\t\t\t\treturn simple\n\t\t\t\t\t? base.streamSimple(model, context, options as SimpleStreamOptions)\n\t\t\t\t\t: base.stream(model, context, options);\n\t\t\t}\n\t\t\tconst api = getApiProvider(model.api);\n\t\t\tif (!api) throw new Error(`No API provider registered for api: ${model.api}`);\n\t\t\treturn simple\n\t\t\t\t? api.streamSimple(model, context, options as SimpleStreamOptions)\n\t\t\t\t: api.stream(model, context, options);\n\t\t});\n\n\tconst provider: Provider = {\n\t\tid: providerId,\n\t\tname: extension?.name ?? config?.name ?? base?.name ?? extension?.oauth?.name ?? providerId,\n\t\tbaseUrl: extension?.baseUrl ?? config?.baseUrl ?? base?.baseUrl,\n\t\theaders: base?.headers,\n\t\tauth: { ...(apiKey ? { apiKey } : {}), ...(oauth ? { oauth } : {}) },\n\t\tgetModels: () => getAllModels().filter((model) => isModelType(model, \"chat\")),\n\t\tgetAllModels,\n\t\trefreshModels:\n\t\t\tbase?.refreshModels || extension?.refreshModels || extension?.oauth?.modifyModels\n\t\t\t\t? async (context) => {\n\t\t\t\t\t\tawait base?.refreshModels?.(context);\n\t\t\t\t\t\tlet refreshed: NonNullable<ProviderConfigInput[\"models\"]> | undefined;\n\t\t\t\t\t\tif (extension?.refreshModels) refreshed = await extension.refreshModels(context);\n\t\t\t\t\t\tif (context.signal.aborted) return;\n\t\t\t\t\t\tconst oauthCredential = context.credential?.type === \"oauth\" ? context.credential : undefined;\n\t\t\t\t\t\tawait context.publish({\n\t\t\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\t\t\tif (refreshed) {\n\t\t\t\t\t\t\t\t\t// Validate before publishing the new synchronous list.\n\t\t\t\t\t\t\t\t\tapplyExtension(providerId, applyModelsJson(providerId, getAllProviderModels(base), config), {\n\t\t\t\t\t\t\t\t\t\t...extension,\n\t\t\t\t\t\t\t\t\t\tmodels: refreshed,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\trefreshedExtensionModels = refreshed;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\textensionOAuthCredential = oauthCredential;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\tfilterModels: base?.filterModels\n\t\t\t? (models, credential: Credential | undefined) => {\n\t\t\t\t\t// Models the user defines in models.json are an explicit choice: the base provider's\n\t\t\t\t\t// account filter (such as GitHub Copilot's model list) must not hide them.\n\t\t\t\t\tconst isConfigured = (model: Model<Api>) =>\n\t\t\t\t\t\tconfig?.models?.some((entry) => entry.id === model.id) === true;\n\t\t\t\t\tconst filtered = new Map(base.filterModels!(models, credential).map((model) => [model.id, model]));\n\t\t\t\t\treturn models.flatMap((original) => {\n\t\t\t\t\t\tif (isConfigured(original)) return [original];\n\t\t\t\t\t\tconst model = filtered.get(original.id);\n\t\t\t\t\t\tif (model === undefined) return [];\n\t\t\t\t\t\tconst inheritedContext = model.fastRoute\n\t\t\t\t\t\t\t? config?.modelOverrides?.[model.fastRoute.baseModelId]?.contextWindow\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tconst personalized =\n\t\t\t\t\t\t\tinheritedContext === undefined ? model : { ...model, contextWindow: inheritedContext };\n\t\t\t\t\t\tconst override = config?.modelOverrides?.[model.id];\n\t\t\t\t\t\treturn [override ? applyModelOverride(personalized, override) : personalized];\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t: undefined,\n\t\tfilterAllModels: base?.filterAllModels\n\t\t\t? (models, credential: Credential | undefined) => base.filterAllModels!(models, credential)\n\t\t\t: undefined,\n\t\tstream: (model, context, options) => streamWith(model, context, options, false),\n\t\tstreamSimple: (model, context, options) => streamWith(model, context, options, true),\n\t};\n\n\tconst fetchDeferred = base?.fetchDeferred;\n\tif (fetchDeferred) {\n\t\tprovider.fetchDeferred = (model, handle, options) => fetchDeferred(model, handle, options);\n\t}\n\tconst cancelDeferred = base?.cancelDeferred;\n\tif (cancelDeferred) {\n\t\tprovider.cancelDeferred = (model, handle, options) => cancelDeferred(model, handle, options);\n\t}\n\tconst extensionImages = extension?.images;\n\tconst generateImages = base?.generateImages;\n\tif (generateImages || Object.keys(extensionImages ?? {}).length > 0) {\n\t\tprovider.generateImages = (model, context, options) => {\n\t\t\tconst implementation = extensionImages?.[model.api];\n\t\t\tif (implementation) return implementation.generateImages(model, context, options);\n\t\t\tif (generateImages) return generateImages(model, context, options);\n\t\t\treturn Promise.resolve(\n\t\t\t\timageErrorResult(model, new Error(`Provider ${providerId} has no image implementation for \"${model.api}\"`)),\n\t\t\t);\n\t\t};\n\t}\n\tconst extensionClassifiers = extension?.classifiers;\n\tconst classify = base?.classify;\n\tif (classify || Object.keys(extensionClassifiers ?? {}).length > 0) {\n\t\tprovider.classify = (model, context, options) => {\n\t\t\tconst implementation = extensionClassifiers?.[model.api];\n\t\t\tif (implementation) return implementation.classify(model, context, options);\n\t\t\tif (classify) return classify(model, context, options);\n\t\t\treturn Promise.resolve(\n\t\t\t\tclassifierErrorResult(\n\t\t\t\t\tmodel,\n\t\t\t\t\tnew Error(`Provider ${providerId} has no classifier implementation for \"${model.api}\"`),\n\t\t\t\t),\n\t\t\t);\n\t\t};\n\t}\n\n\treturn provider;\n}\n\nexport function resolveConfiguredModelHeaders(\n\tmodel: AnyModel,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n\tenv?: Record<string, string>,\n): Record<string, string> | undefined {\n\treturn resolveHeadersOrThrow(\n\t\trawModelHeaders(model, config, extension),\n\t\t`model \"${model.provider}/${model.id}\"`,\n\t\tenv,\n\t);\n}\n\nexport interface CompatibilityRequestConfig {\n\theaders?: ProviderHeaders;\n\tauthHeader: boolean;\n}\n\nexport function resolveCompatibilityRequestConfig(\n\tmodel: AnyModel,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): CompatibilityRequestConfig {\n\tconst configured = resolveHeadersOrThrow(\n\t\t{ ...configuredHeaders(config, extension), ...rawModelHeaders(model, config, extension) },\n\t\t`model \"${model.provider}/${model.id}\"`,\n\t);\n\treturn {\n\t\theaders: model.headers || configured ? { ...model.headers, ...configured } : undefined,\n\t\tauthHeader: extension?.authHeader ?? config?.authHeader ?? false,\n\t};\n}\n\nexport function configuredRequestAuthStatus(\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): AuthStatus | undefined {\n\tconst value = configuredApiKey(config, extension);\n\tif (value === undefined) return undefined;\n\tif (isCommandConfigValue(value)) return { configured: true, source: \"models_json_command\" };\n\tconst names = getConfigValueEnvVarNames(value);\n\tif (names.length > 0) {\n\t\treturn isConfigValueConfigured(value)\n\t\t\t? { configured: true, source: \"environment\", label: names.join(\", \") }\n\t\t\t: { configured: false };\n\t}\n\treturn { configured: true, source: extension?.apiKey !== undefined ? \"fallback\" : \"models_json_key\" };\n}\n"]}
|