@code-yeongyu/senpi 2026.8.28 → 2026.8.29
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 +74 -0
- package/dist/cli/args.d.ts +2 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +4 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +2 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +5 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +1 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts +1 -0
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +3 -0
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/credential-accounts.d.ts.map +1 -1
- package/dist/core/credential-accounts.js +22 -12
- package/dist/core/credential-accounts.js.map +1 -1
- package/dist/core/credential-pool/classify.d.ts +6 -1
- package/dist/core/credential-pool/classify.d.ts.map +1 -1
- package/dist/core/credential-pool/classify.js +22 -5
- package/dist/core/credential-pool/classify.js.map +1 -1
- package/dist/core/credential-pool/failover.d.ts +8 -0
- package/dist/core/credential-pool/failover.d.ts.map +1 -1
- package/dist/core/credential-pool/failover.js +24 -6
- package/dist/core/credential-pool/failover.js.map +1 -1
- package/dist/core/credential-pool/rotation-stream.d.ts +13 -2
- package/dist/core/credential-pool/rotation-stream.d.ts.map +1 -1
- package/dist/core/credential-pool/rotation-stream.js +97 -10
- package/dist/core/credential-pool/rotation-stream.js.map +1 -1
- package/dist/core/extensions/builtin/goal/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/index.js +7 -0
- package/dist/core/extensions/builtin/goal/index.js.map +1 -1
- package/dist/core/extensions/builtin/service-tier.d.ts.map +1 -1
- package/dist/core/extensions/builtin/service-tier.js +13 -0
- package/dist/core/extensions/builtin/service-tier.js.map +1 -1
- package/dist/core/extensions/builtin/terminal/extension.d.ts.map +1 -1
- package/dist/core/extensions/builtin/terminal/extension.js +4 -2
- package/dist/core/extensions/builtin/terminal/extension.js.map +1 -1
- package/dist/core/model-config-schema.d.ts +4 -4
- package/dist/core/model-runtime.d.ts +2 -0
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +74 -37
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/retry-fallback/chains.d.ts +23 -1
- package/dist/core/retry-fallback/chains.d.ts.map +1 -1
- package/dist/core/retry-fallback/chains.js +59 -3
- package/dist/core/retry-fallback/chains.js.map +1 -1
- package/dist/core/retry-fallback/controller.d.ts.map +1 -1
- package/dist/core/retry-fallback/controller.js +9 -2
- package/dist/core/retry-fallback/controller.js.map +1 -1
- package/dist/core/retry-fallback/settings.d.ts.map +1 -1
- package/dist/core/retry-fallback/settings.js +9 -0
- package/dist/core/retry-fallback/settings.js.map +1 -1
- package/dist/core/retry-fallback/validate.js +1 -1
- package/dist/core/retry-fallback/validate.js.map +1 -1
- package/dist/core/sdk.js +1 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts +9 -0
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +31 -0
- package/dist/core/session-manager.js.map +1 -1
- package/dist/main.d.ts +7 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +10 -1
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/favorite-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/favorite-models-selector.js +2 -2
- package/dist/modes/interactive/components/favorite-models-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-host-runtime.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-host-runtime.js +323 -33
- package/dist/modes/interactive/interactive-host-runtime.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +276 -237
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/connection-handler.d.ts.map +1 -1
- package/dist/modes/rpc/connection-handler.js +133 -24
- package/dist/modes/rpc/connection-handler.js.map +1 -1
- package/dist/modes/rpc/multi-session-host.js +14 -4
- package/dist/modes/rpc/multi-session-host.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +82 -13
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +85 -28
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts +3 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +3 -1
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +162 -2
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/modes/rpc/session-command-router.d.ts +22 -0
- package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
- package/dist/modes/rpc/session-command-router.js +147 -16
- package/dist/modes/rpc/session-command-router.js.map +1 -1
- package/dist/modes/rpc/session-event-writer.d.ts +2 -0
- package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
- package/dist/modes/rpc/session-event-writer.js +4 -0
- package/dist/modes/rpc/session-event-writer.js.map +1 -1
- package/dist/modes/rpc/session-registry.d.ts +7 -0
- package/dist/modes/rpc/session-registry.d.ts.map +1 -1
- package/dist/modes/rpc/session-registry.js +9 -0
- package/dist/modes/rpc/session-registry.js.map +1 -1
- package/docs/rpc.md +37 -0
- package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +24 -0
- package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
- package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +6 -3
- package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/baseten.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/node_modules/@earendil-works/pi-pty/package.json +1 -1
- package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-runtime.js","sourceRoot":"","sources":["../../src/core/model-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAcN,YAAY,EAIZ,gBAAgB,EAChB,UAAU,EAMV,WAAW,EAYX,eAAe,EACf,2BAA2B,GAC3B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,sBAAsB,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,c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D,IAAI,YAAY,IAAI,OAAO,EAAE,OAAO,KAAK,KAAK,EAAE,CAAC;YAChD,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,GAAG,EAAE,EAAE,CAAC,CAAC;QAC/D,CAAC;QACD,OAAO,IAAI,CAAC,wBAAwB,EAAE,CAAC;IACxC,CAAC;IAED,kBAAkB,CAAC,UAAkB;QACpC,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC3C,IAAI,CAAC,wBAAwB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QACjD,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC;QACnC,IAAI,CAAC,WAAW,CAAC,uBAAuB,CAAC,UAAU,CAAC,CAAC;QACrD,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC3B,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAC5C,CAAC;CACD","sourcesContent":["import { dirname, join } from \"node:path\";\nimport {\n\ttype Api,\n\ttype ApiStreamOptions,\n\ttype AssistantMessage,\n\ttype AssistantMessageEventStream,\n\ttype AuthCheck,\n\ttype AuthInteraction,\n\ttype AuthOperationOptions,\n\ttype AuthResult,\n\ttype AuthType,\n\ttype Context,\n\ttype Credential,\n\ttype CredentialInfo,\n\ttype CredentialStore,\n\tcreateModels,\n\ttype DeferredCancelOptions,\n\ttype DeferredFetchOptions,\n\ttype DeferredHandle,\n\tgetApiKeyEnvVars,\n\tlazyStream,\n\ttype Model,\n\ttype Models,\n\ttype ModelsApiStreamOptions,\n\ttype ModelsDeferredCancelOptions,\n\ttype ModelsDeferredFetchOptions,\n\tModelsError,\n\ttype ModelsRefreshOptions,\n\ttype ModelsRefreshResult,\n\ttype ModelsRequestTransforms,\n\ttype ModelsSimpleStreamOptions,\n\ttype ModelsStore,\n\ttype MutableModels,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype ProviderRequestOptions,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n\tsetWireIdentity,\n\twrapStreamWithModelRecovery,\n} from \"@earendil-works/pi-ai\";\nimport * as builtinProviderCatalog from \"@earendil-works/pi-ai/providers/all\";\nimport { APP_NAME, BRAND, getAgentDir } from \"../config.ts\";\nimport { operationSignal, raceWithAbortSignal } from \"../utils/abort.ts\";\nimport { AuthStorage as DefaultAuthStorage } from \"./auth-storage.ts\";\nimport { envValue } from \"./brand.ts\";\nimport type { RotationSources } from \"./credential-pool/rotation-stream.ts\";\nimport { ModelConfig } from \"./model-config.ts\";\nimport { FileModelsStore, InMemoryCodingAgentModelsStore } from \"./models-store.ts\";\nimport {\n\ttype AuthStatus,\n\ttype CompatibilityRequestConfig,\n\tcomposeModelProvider,\n\tconfiguredRequestAuthStatus,\n\ttype ProviderConfigInput,\n\tresolveCompatibilityRequestConfig,\n\tresolveConfiguredModelHeaders,\n\tvalidateExtensionProvider,\n} from \"./provider-composer.ts\";\nimport { remoteCatalogServesProvider, withRemoteCatalog } from \"./remote-catalog-provider.ts\";\nimport { RuntimeCredentials } from \"./runtime-credentials.ts\";\n\n// The product's identity must ride outgoing requests. This lives here because the AI package\n// is already part of this module's graph; the CLI bootstrap deliberately does not import it.\nsetWireIdentity(BRAND?.userAgent ?? APP_NAME);\n\ninterface ModelRuntimeSnapshot {\n\tall: readonly Model<Api>[];\n\tavailable: readonly Model<Api>[];\n\tconfiguredProviders: ReadonlySet<string>;\n\tstoredProviders: ReadonlySet<string>;\n\tauth: ReadonlyMap<string, AuthCheck | undefined>;\n}\n\nexport interface CreateModelRuntimeOptions {\n\t/** Credential storage. Defaults to the file at authPath. */\n\tcredentials?: CredentialStore;\n\tauthPath?: string;\n\tmodelsPath?: string | null;\n\tmodelsStore?: ModelsStore;\n\tmodelsStorePath?: string;\n\t/** Allow create() to refresh model catalogs over the network. Defaults to false. */\n\tallowModelNetwork?: boolean;\n\t/** Timeout for the create-time network model refresh. */\n\tmodelRefreshTimeoutMs?: number;\n\tcatalogBaseUrl?: string;\n\t/** Optional caller cancellation for initial cache restoration and availability checks. */\n\tsignal?: AbortSignal;\n\t/** Skip initial catalog and availability refresh. Static models remain available. */\n\trefreshOnCreate?: boolean;\n}\n\nexport interface ModelRuntimeAuthOverrides extends AuthOperationOptions {\n\tapiKey?: string;\n\tenv?: Record<string, string>;\n\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n\t/** Resolve against one named slot of a pooled credential instead of the flat projection. */\n\tslotName?: string;\n}\n\n/**\n * Stream options plus the coding-agent-only affinity key. It is declared here\n * rather than widening the engine's `StreamOptions`: a stable key (the session\n * id) keeps one conversation on one credential slot, and its absence simply\n * distributes requests instead of concentrating them.\n */\nexport type CredentialRotationStreamOptions = StreamOptions & ModelsRequestTransforms & { affinityKey?: string };\n\n/**\n * Cheap pre-check answering \"could this provider hold more than one credential\n * at all?\" without loading the credential pool. A stored entry pools only\n * through `accounts`; env slots participate only when nothing is stored, and a\n * lone primary variable is still a single credential.\n */\nfunction mightHoldEnvCredentialPool(providerId: string, env: (name: string) => string | undefined): boolean {\n\tconst envVars = getApiKeyEnvVars(providerId);\n\tconst primary = envVars?.find((name) => name.endsWith(\"_API_KEY\")) ?? envVars?.[0];\n\tif (primary === undefined) return false;\n\tlet found = env(primary) ? 1 : 0;\n\tfor (let index = 2; index <= 16 && found < 2; index++) {\n\t\tif (env(`${primary}_${index}`)) found++;\n\t}\n\treturn found > 1;\n}\n\nfunction mightHoldCredentialPool(\n\tproviderId: string,\n\tcredential: Credential | undefined,\n\tenv: (name: string) => string | undefined,\n): boolean {\n\tif (credential) {\n\t\tconst accounts = Object.entries(credential).find(([key]) => key === \"accounts\")?.[1];\n\t\treturn Array.isArray(accounts) && accounts.length > 1;\n\t}\n\treturn mightHoldEnvCredentialPool(providerId, env);\n}\n\nexport type CredentialSynchronizationOperation = \"login\" | \"logout\" | \"setRuntimeApiKey\" | \"removeRuntimeApiKey\";\n\n/** Credentials changed successfully, but the local model/auth snapshot could not be synchronized. */\nexport class CredentialSynchronizationError extends Error {\n\treadonly providerId: string;\n\treadonly operation: CredentialSynchronizationOperation;\n\treadonly credential: Credential | undefined;\n\n\tconstructor(\n\t\tproviderId: string,\n\t\toperation: CredentialSynchronizationOperation,\n\t\tcredential: Credential | undefined,\n\t\toptions: ErrorOptions,\n\t) {\n\t\tsuper(`Credential ${operation} committed for ${providerId}, but local synchronization failed`, options);\n\t\tthis.name = \"CredentialSynchronizationError\";\n\t\tthis.providerId = providerId;\n\t\tthis.operation = operation;\n\t\tthis.credential = credential;\n\t}\n}\n\nfunction 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\nfunction withPayloadRequestMetadata(options: StreamOptions, model: Model<Api>): StreamOptions {\n\tif (!options.onPayload) return options;\n\tconst onPayload = options.onPayload;\n\treturn {\n\t\t...options,\n\t\tonPayload: async (payload, providerModel) =>\n\t\t\tawait onPayload(payload, providerModel, { model, headers: options.headers ?? {} }),\n\t};\n}\n\n/** Configured pi-ai Models collection used by coding-agent and SDK consumers. */\nexport class ModelRuntime implements Models {\n\tprivate readonly models: MutableModels;\n\tprivate readonly credentials: RuntimeCredentials;\n\tprivate readonly defaultBuiltins: ReadonlyMap<string, Provider>;\n\tprivate readonly builtins = new Map<string, Provider>();\n\tprivate readonly nativeExtensionProviders = new Map<string, Provider>();\n\tprivate readonly extensionProviders = new Map<string, ProviderConfigInput>();\n\tprivate readonly compositionErrors = new Map<string, string>();\n\tprivate readonly modelsPath: string | undefined;\n\tprivate readonly modelNetworkEnabled: boolean;\n\tprivate readonly modelRefreshTimeoutMs: number;\n\tprivate config: ModelConfig;\n\tprivate snapshot: ModelRuntimeSnapshot = {\n\t\tall: [],\n\t\tavailable: [],\n\t\tconfiguredProviders: new Set(),\n\t\tstoredProviders: new Set(),\n\t\tauth: new Map(),\n\t};\n\tprivate availabilityInitialized = false;\n\tprivate availabilityRefreshSeq = 0;\n\tprivate availabilityErrorSeq = 0;\n\tprivate readonly providerAvailabilitySeq = new Map<string, number>();\n\tprivate availabilityError: string | undefined;\n\tprivate readonly credentialOperations = new Map<string, Promise<unknown>>();\n\t/**\n\t * The credential pool is loaded lazily and only for a provider that actually\n\t * has more than one slot. Importing it eagerly would pull the pool's schema\n\t * validator - and its module-level global registry - into every consumer of\n\t * ModelRuntime, which the import-graph guard forbids.\n\t */\n\tprivate credentialPoolModules:\n\t\t| Promise<{\n\t\t\t\trotation: typeof import(\"./credential-pool/rotation-stream.ts\");\n\t\t\t\trepository: InstanceType<typeof import(\"./credential-pool/state-store.ts\").CredentialSlotRepository>;\n\t\t }>\n\t\t| undefined;\n\tprivate constructor(\n\t\tcredentials: RuntimeCredentials,\n\t\tconfig: ModelConfig,\n\t\tmodelsPath: string | undefined,\n\t\tmodelsStore: ModelsStore,\n\t\tproviders: readonly Provider[],\n\t\tmodelNetworkEnabled: boolean,\n\t\tmodelRefreshTimeoutMs: number,\n\t) {\n\t\tthis.credentials = credentials;\n\t\tthis.config = config;\n\t\tthis.modelsPath = modelsPath;\n\t\tthis.modelNetworkEnabled = modelNetworkEnabled;\n\t\tthis.modelRefreshTimeoutMs = modelRefreshTimeoutMs;\n\t\tthis.defaultBuiltins = new Map(providers.map((provider) => [provider.id, provider]));\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tthis.models = createModels({ credentials, modelsStore });\n\t\tthis.rebuildProviders();\n\t}\n\n\tstatic async create(options: CreateModelRuntimeOptions = {}): Promise<ModelRuntime> {\n\t\tconst credentials = new RuntimeCredentials(options.credentials ?? DefaultAuthStorage.create(options.authPath));\n\t\tconst modelsPath =\n\t\t\toptions.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), \"models.json\"));\n\t\tconst config = await ModelConfig.load(modelsPath);\n\t\tconst modelsStore =\n\t\t\toptions.modelsStore ??\n\t\t\t(modelsPath\n\t\t\t\t? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), \"models-store.json\"))\n\t\t\t\t: new InMemoryCodingAgentModelsStore());\n\t\tconst builtinModelDataGeneratedAt = builtinProviderCatalog.getBuiltinModelDataGeneratedAt();\n\t\tconst providers = builtinProviderCatalog\n\t\t\t.builtinProviders()\n\t\t\t.map((provider) =>\n\t\t\t\tprovider.refreshModels || !remoteCatalogServesProvider(provider.id, options.catalogBaseUrl)\n\t\t\t\t\t? provider\n\t\t\t\t\t: withRemoteCatalog(provider, options.catalogBaseUrl, builtinModelDataGeneratedAt),\n\t\t\t);\n\t\tconst runtime = new ModelRuntime(\n\t\t\tcredentials,\n\t\t\tconfig,\n\t\t\tmodelsPath,\n\t\t\tmodelsStore,\n\t\t\tproviders,\n\t\t\tenvValue(\"OFFLINE\") === undefined && options.allowModelNetwork === true,\n\t\t\toptions.modelRefreshTimeoutMs ?? 15_000,\n\t\t);\n\t\truntime.rebuildProviders();\n\t\tconst refreshFromNetwork = runtime.modelNetworkEnabled && options.allowModelNetwork === true;\n\t\tconst controller =\n\t\t\trefreshFromNetwork && options.modelRefreshTimeoutMs !== undefined ? new AbortController() : undefined;\n\t\tconst timeout = controller ? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs) : undefined;\n\t\tconst signal = controller\n\t\t\t? options.signal\n\t\t\t\t? AbortSignal.any([options.signal, controller.signal])\n\t\t\t\t: controller.signal\n\t\t\t: options.signal;\n\t\ttry {\n\t\t\tif (options.refreshOnCreate !== false) {\n\t\t\t\tawait runtime.refresh({ allowNetwork: refreshFromNetwork, signal });\n\t\t\t}\n\t\t} finally {\n\t\t\tif (timeout) clearTimeout(timeout);\n\t\t}\n\t\treturn runtime;\n\t}\n\n\t/** Synchronous compatibility constructor for legacy ModelRegistry callers. */\n\tstatic createSync(options: CreateModelRuntimeOptions = {}): ModelRuntime {\n\t\tconst credentials = new RuntimeCredentials(options.credentials ?? DefaultAuthStorage.create(options.authPath));\n\t\tconst modelsPath =\n\t\t\toptions.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), \"models.json\"));\n\t\tconst config = ModelConfig.loadSync(modelsPath);\n\t\tconst modelsStore =\n\t\t\toptions.modelsStore ??\n\t\t\t(modelsPath\n\t\t\t\t? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), \"models-store.json\"))\n\t\t\t\t: new InMemoryCodingAgentModelsStore());\n\t\tconst providers = builtinProviderCatalog\n\t\t\t.builtinProviders()\n\t\t\t.map((provider) =>\n\t\t\t\tprovider.refreshModels || !remoteCatalogServesProvider(provider.id, options.catalogBaseUrl)\n\t\t\t\t\t? provider\n\t\t\t\t\t: withRemoteCatalog(provider, options.catalogBaseUrl),\n\t\t\t);\n\t\tconst runtime = new ModelRuntime(\n\t\t\tcredentials,\n\t\t\tconfig,\n\t\t\tmodelsPath,\n\t\t\tmodelsStore,\n\t\t\tproviders,\n\t\t\toptions.allowModelNetwork ?? false,\n\t\t\toptions.modelRefreshTimeoutMs ?? 15_000,\n\t\t);\n\t\truntime.rebuildProviders();\n\t\treturn runtime;\n\t}\n\n\tprivate providerIds(): Set<string> {\n\t\treturn new Set([\n\t\t\t...this.builtins.keys(),\n\t\t\t...this.nativeExtensionProviders.keys(),\n\t\t\t...this.config.getProviderIds(),\n\t\t\t...this.extensionProviders.keys(),\n\t\t]);\n\t}\n\n\tprivate recomposeProvider(providerId: string): void {\n\t\tif (this.config.isProviderDisabled(providerId)) {\n\t\t\tthis.models.deleteProvider(providerId);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\tconst base = this.nativeExtensionProviders.get(providerId) ?? this.builtins.get(providerId);\n\t\tconst extension = this.extensionProviders.get(providerId);\n\t\tif (!base && !this.config.getProvider(providerId) && !extension) {\n\t\t\tthis.models.deleteProvider(providerId);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\tif (base && !this.config.getProvider(providerId) && !extension) {\n\t\t\t// No overlays: use the builtin untouched so its auth/login/stream behavior is exact.\n\t\t\tthis.models.setProvider(base);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.models.setProvider(composeModelProvider(providerId, base, this.config, extension));\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t} catch (error) {\n\t\t\tthis.compositionErrors.set(providerId, error instanceof Error ? error.message : String(error));\n\t\t\tif (base) this.models.setProvider(base);\n\t\t\telse this.models.deleteProvider(providerId);\n\t\t}\n\t}\n\n\tprivate rebuildProviders(): void {\n\t\tthis.models.clearProviders();\n\t\tthis.compositionErrors.clear();\n\t\tfor (const providerId of this.providerIds()) this.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t}\n\n\tprivate updateModelSnapshot(): void {\n\t\tconst all = [...this.models.getModels()];\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tall,\n\t\t\tavailable: all.filter((model) => this.snapshot.configuredProviders.has(model.provider)),\n\t\t};\n\t}\n\n\tprivate async runAvailabilityRefresh(seq: number, errorSeq: number, signal: AbortSignal): Promise<void> {\n\t\tconst providers = this.models.getProviders();\n\t\tconst [available, checks, credentials] = await Promise.all([\n\t\t\tthis.models.getAvailable(undefined, { signal }),\n\t\t\tPromise.all(\n\t\t\t\tproviders.map(\n\t\t\t\t\tasync (provider): Promise<[string, AuthCheck | undefined]> => [\n\t\t\t\t\t\tprovider.id,\n\t\t\t\t\t\tawait this.models.checkAuth(provider.id, { signal }),\n\t\t\t\t\t],\n\t\t\t\t),\n\t\t\t),\n\t\t\tthis.credentials.list({ signal }),\n\t\t]);\n\t\tif (seq !== this.availabilityRefreshSeq) return;\n\t\tconst auth = new Map(checks);\n\t\tconst configuredProviders = new Set(\n\t\t\tchecks\n\t\t\t\t.filter((entry): entry is [string, AuthCheck] => entry[1] !== undefined)\n\t\t\t\t.map(([providerId]) => providerId),\n\t\t);\n\t\tthis.snapshot = {\n\t\t\tall: [...this.models.getModels()],\n\t\t\tavailable: [...available],\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders: new Set(credentials.map((entry) => entry.providerId)),\n\t\t\tauth,\n\t\t};\n\t\tthis.availabilityInitialized = true;\n\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t}\n\n\tprivate queueAvailabilityRefresh(signal?: AbortSignal): Promise<void> {\n\t\tconst seq = ++this.availabilityRefreshSeq;\n\t\tfor (const [providerId, providerSeq] of this.providerAvailabilitySeq) {\n\t\t\tthis.providerAvailabilitySeq.set(providerId, providerSeq + 1);\n\t\t}\n\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\tconst effectiveSignal = operationSignal(signal);\n\t\treturn this.runAvailabilityRefresh(seq, errorSeq, effectiveSignal).catch((error) => {\n\t\t\tif (errorSeq === this.availabilityErrorSeq && !effectiveSignal.aborted) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t});\n\t}\n\n\tprivate async refreshProviderAvailability(providerId: string, signal: AbortSignal): Promise<void> {\n\t\t// Invalidate any full availability pass that started before this credential change.\n\t\t++this.availabilityRefreshSeq;\n\t\tconst providerSeq = (this.providerAvailabilitySeq.get(providerId) ?? 0) + 1;\n\t\tthis.providerAvailabilitySeq.set(providerId, providerSeq);\n\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\ttry {\n\t\t\tconst [available, auth, credential] = await Promise.all([\n\t\t\t\tthis.models.getAvailable(providerId, { signal }),\n\t\t\t\tthis.models.checkAuth(providerId, { signal }),\n\t\t\t\tthis.credentials.read(providerId, { signal }),\n\t\t\t]);\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (this.providerAvailabilitySeq.get(providerId) !== providerSeq) return;\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders);\n\t\t\tconst storedProviders = new Set(this.snapshot.storedProviders);\n\t\t\tconst authByProvider = new Map(this.snapshot.auth);\n\t\t\tif (auth) {\n\t\t\t\tconfiguredProviders.add(providerId);\n\t\t\t\tauthByProvider.set(providerId, auth);\n\t\t\t} else {\n\t\t\t\tconfiguredProviders.delete(providerId);\n\t\t\t\tauthByProvider.delete(providerId);\n\t\t\t}\n\t\t\tif (credential) storedProviders.add(providerId);\n\t\t\telse storedProviders.delete(providerId);\n\t\t\tconst all = [...this.models.getModels()];\n\t\t\tconst availableById = new Map(\n\t\t\t\t[...this.snapshot.available.filter((model) => model.provider !== providerId), ...available].map((model) => [\n\t\t\t\t\t`${model.provider}\\0${model.id}`,\n\t\t\t\t\tmodel,\n\t\t\t\t]),\n\t\t\t);\n\t\t\tthis.snapshot = {\n\t\t\t\tall,\n\t\t\t\tavailable: all.flatMap((model) => availableById.get(`${model.provider}\\0${model.id}`) ?? []),\n\t\t\t\tconfiguredProviders,\n\t\t\t\tstoredProviders,\n\t\t\t\tauth: authByProvider,\n\t\t\t};\n\t\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tthis.providerAvailabilitySeq.get(providerId) === providerSeq &&\n\t\t\t\terrorSeq === this.availabilityErrorSeq &&\n\t\t\t\t!signal.aborted\n\t\t\t) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tgetProviders(): readonly Provider[] {\n\t\treturn this.models.getProviders();\n\t}\n\tgetProvider(providerId: string): Provider | undefined {\n\t\treturn this.models.getProvider(providerId);\n\t}\n\tgetModels(providerId?: string): readonly Model<Api>[] {\n\t\treturn this.models.getModels(providerId);\n\t}\n\tgetModel(providerId: string, modelId: string): Model<Api> | undefined {\n\t\treturn this.models.getModel(providerId, modelId);\n\t}\n\n\tasync checkAuth(providerId: string, options?: AuthOperationOptions): Promise<AuthCheck | undefined> {\n\t\treturn this.models.checkAuth(providerId, options);\n\t}\n\n\tasync getAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly Model<Api>[]> {\n\t\tif (providerId) {\n\t\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\t\ttry {\n\t\t\t\tconst available = await this.models.getAvailable(providerId, options);\n\t\t\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t\t\t\treturn available;\n\t\t\t} catch (error) {\n\t\t\t\tif (errorSeq === this.availabilityErrorSeq && !options?.signal?.aborted) {\n\t\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tawait this.queueAvailabilityRefresh(options?.signal);\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetAvailableSnapshot(): readonly Model<Api>[] {\n\t\treturn this.snapshot.available;\n\t}\n\n\t/** True only when the most recent availability refresh completed without error. */\n\thasFreshAvailabilitySnapshot(): boolean {\n\t\treturn this.availabilityInitialized && this.availabilityError === undefined;\n\t}\n\n\thasAvailabilitySnapshot(): boolean {\n\t\treturn this.availabilityInitialized;\n\t}\n\n\tgetError(): string | undefined {\n\t\tconst errors: string[] = [];\n\t\tconst configError = this.config.getError();\n\t\tif (configError) errors.push(configError);\n\t\tfor (const [providerId, error] of this.compositionErrors) {\n\t\t\terrors.push(`Provider \"${providerId}\": ${error}`);\n\t\t}\n\t\tif (this.availabilityError) errors.push(`Availability refresh: ${this.availabilityError}`);\n\t\treturn errors.length > 0 ? errors.join(\"\\n\\n\") : undefined;\n\t}\n\n\tgetRegisteredProviderConfig(providerId: string): ProviderConfigInput | undefined {\n\t\treturn this.extensionProviders.get(providerId);\n\t}\n\n\tgetRegisteredProviderIds(): readonly string[] {\n\t\treturn [...new Set([...this.extensionProviders.keys(), ...this.nativeExtensionProviders.keys()])];\n\t}\n\n\tgetRegisteredNativeProvider(providerId: string): Provider | undefined {\n\t\treturn this.nativeExtensionProviders.get(providerId);\n\t}\n\n\t/** @internal Compatibility fallback for ModelRegistry when provider auth is unconfigured. */\n\tgetCompatibilityRequestConfig(model: Model<Api>, env?: Record<string, string>): CompatibilityRequestConfig {\n\t\treturn resolveCompatibilityRequestConfig(\n\t\t\tmodel,\n\t\t\tthis.config.getProvider(model.provider),\n\t\t\tthis.extensionProviders.get(model.provider),\n\t\t\tenv,\n\t\t);\n\t}\n\n\tisUsingOAuth(providerId: string): boolean {\n\t\treturn this.snapshot.auth.get(providerId)?.type === \"oauth\";\n\t}\n\n\tisUsingSubscription(providerId: string): boolean {\n\t\treturn this.isUsingOAuth(providerId) && this.models.getProvider(providerId)?.auth.oauth?.isSubscription === true;\n\t}\n\n\thasConfiguredAuth(providerId: string): boolean {\n\t\treturn this.snapshot.configuredProviders.has(providerId);\n\t}\n\n\t/**\n\t * Deterministic fallback-expansion gate declared by the provider's own\n\t * registration. Only a definitive `false` excludes; providers without the\n\t * hook, and hooks that throw, stay eligible so expansion never shrinks on\n\t * uncertainty.\n\t */\n\tisFallbackEligible(providerId: string): boolean {\n\t\tconst hook = this.extensionProviders.get(providerId)?.fallbackEligible;\n\t\tif (typeof hook !== \"function\") return true;\n\t\ttry {\n\t\t\treturn hook() !== false;\n\t\t} catch {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tgetAuth(providerId: string, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: Model<Api>, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tasync getAuth(\n\t\tproviderOrModel: string | Model<Api>,\n\t\toverrides: ModelRuntimeAuthOverrides = {},\n\t): Promise<AuthResult | undefined> {\n\t\tif (typeof providerOrModel === \"string\") return this.models.getAuth(providerOrModel, overrides);\n\t\tconst resolution = await this.models.getAuth(providerOrModel, overrides);\n\t\tif (!resolution) return undefined;\n\t\tconst configuredHeaders = resolveConfiguredModelHeaders(\n\t\t\tproviderOrModel,\n\t\t\tthis.config.getProvider(providerOrModel.provider),\n\t\t\tthis.extensionProviders.get(providerOrModel.provider),\n\t\t\t{ ...(resolution.env ?? {}), ...(overrides.env ?? {}) },\n\t\t);\n\t\treturn {\n\t\t\t...resolution,\n\t\t\tauth: {\n\t\t\t\t...resolution.auth,\n\t\t\t\theaders: mergeHeaders(resolution.auth.headers, configuredHeaders),\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate enqueueCredentialOperation<T>(providerId: string, signal: AbortSignal, task: () => Promise<T>): Promise<T> {\n\t\tconst previous = this.credentialOperations.get(providerId) ?? Promise.resolve();\n\t\tlet markStarted: (() => void) | undefined;\n\t\tconst started = new Promise<void>((resolve) => {\n\t\t\tmarkStarted = resolve;\n\t\t});\n\t\tconst operation = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\tsignal.throwIfAborted();\n\t\t\tmarkStarted?.();\n\t\t\treturn task();\n\t\t})();\n\t\tconst tail = operation.catch(() => {});\n\t\tthis.credentialOperations.set(providerId, tail);\n\t\tvoid tail.then(() => {\n\t\t\tif (this.credentialOperations.get(providerId) === tail) this.credentialOperations.delete(providerId);\n\t\t});\n\t\treturn raceWithAbortSignal(started, signal).then(() => operation);\n\t}\n\n\tprivate async synchronizeCredentialState(\n\t\tproviderId: string,\n\t\toperation: CredentialSynchronizationOperation,\n\t\tcredential: Credential | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthis.recomposeProvider(providerId);\n\t\t\tconst compositionError = this.compositionErrors.get(providerId);\n\t\t\tif (compositionError) throw new Error(compositionError);\n\t\t\tconst result = await this.models.refresh({ allowNetwork: false, providers: [providerId], signal });\n\t\t\tif (result.aborted) signal.throwIfAborted();\n\t\t\tconst refreshError = result.errors.get(providerId);\n\t\t\tif (refreshError) throw refreshError;\n\t\t\tthis.updateModelSnapshot();\n\t\t\tawait this.refreshProviderAvailability(providerId, signal);\n\t\t} catch (cause) {\n\t\t\tthrow new CredentialSynchronizationError(providerId, operation, credential, { cause });\n\t\t}\n\t}\n\n\tsetRuntimeApiKey(providerId: string, apiKey: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tthis.credentials.setRuntimeApiKey(providerId, apiKey);\n\t\t\tawait this.synchronizeCredentialState(\n\t\t\t\tproviderId,\n\t\t\t\t\"setRuntimeApiKey\",\n\t\t\t\t{ type: \"api_key\", key: apiKey },\n\t\t\t\tsignal,\n\t\t\t);\n\t\t});\n\t}\n\n\tremoveRuntimeApiKey(providerId: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tthis.credentials.removeRuntimeApiKey(providerId);\n\t\t\tawait this.synchronizeCredentialState(providerId, \"removeRuntimeApiKey\", undefined, signal);\n\t\t});\n\t}\n\n\tlistCredentials(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\treturn this.credentials.list(options);\n\t}\n\n\tgetProviderAuthStatus(providerId: string): AuthStatus {\n\t\tif (this.credentials.hasRuntimeApiKey(providerId)) return { configured: true, source: \"runtime\" };\n\t\tif (this.snapshot.storedProviders.has(providerId)) return { configured: true, source: \"stored\" };\n\t\tconst configured = configuredRequestAuthStatus(\n\t\t\tthis.config.getProvider(providerId),\n\t\t\tthis.extensionProviders.get(providerId),\n\t\t);\n\t\tif (configured) return configured;\n\t\tconst check = this.snapshot.auth.get(providerId);\n\t\treturn check ? { configured: true, source: \"environment\", label: check.source } : { configured: false };\n\t}\n\n\tprivate async prepareRequest<TOptions extends ProviderRequestOptions & ModelsRequestTransforms>(\n\t\tmodel: Model<Api>,\n\t\toptions: TOptions | undefined,\n\t\tslotAuth?: { apiKey?: string; slotName?: string },\n\t): Promise<{\n\t\tprovider: Provider;\n\t\tmodel: Model<Api>;\n\t\toptions: Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions;\n\t}> {\n\t\tconst provider = this.models.getProvider(model.provider);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\tconst resolution = await this.getAuth(model, {\n\t\t\tapiKey: slotAuth?.apiKey ?? options?.apiKey,\n\t\t\tenv: options?.env,\n\t\t\tsignal: options?.signal,\n\t\t\t...(slotAuth?.slotName === undefined ? {} : { slotName: slotAuth.slotName }),\n\t\t});\n\t\tif (!resolution) throw new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\n\t\tconst { transformHeaders, ...rawProviderOptions } = options ?? {};\n\t\tconst providerOptions = rawProviderOptions as Omit<TOptions, \"transformHeaders\"> &\n\t\t\tProviderRequestOptions & { extraBody?: Record<string, unknown> };\n\t\tlet headers = mergeHeaders(resolution.auth.headers, providerOptions.headers);\n\t\tif (transformHeaders) headers = await transformHeaders(headers ?? {});\n\t\tconst compatibility = this.getCompatibilityRequestConfig(model, resolution.env);\n\t\tconst extraBody =\n\t\t\tcompatibility.extraBody || providerOptions.extraBody\n\t\t\t\t? { ...compatibility.extraBody, ...providerOptions.extraBody }\n\t\t\t\t: undefined;\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 upstreamModelId = compatibility.upstreamModelId;\n\t\tconst requestModel =\n\t\t\tresolution.auth.baseUrl || upstreamModelId\n\t\t\t\t? {\n\t\t\t\t\t\t...model,\n\t\t\t\t\t\t...(upstreamModelId ? { id: upstreamModelId } : {}),\n\t\t\t\t\t\t...(resolution.auth.baseUrl ? { baseUrl: resolution.auth.baseUrl } : {}),\n\t\t\t\t\t}\n\t\t\t\t: model;\n\t\treturn {\n\t\t\tprovider,\n\t\t\tmodel: requestModel,\n\t\t\toptions: {\n\t\t\t\t...providerOptions,\n\t\t\t\tapiKey: slotAuth?.apiKey ?? providerOptions.apiKey ?? resolution.auth.apiKey,\n\t\t\t\theaders,\n\t\t\t\textraBody,\n\t\t\t\tenv,\n\t\t\t} as Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions,\n\t\t};\n\t}\n\n\t/**\n\t * Rotation engages only for a provider that actually holds more than one\n\t * credential slot and only when nothing pins the request to one credential\n\t * (a runtime key or an explicit per-request apiKey). Every single-credential\n\t * user therefore keeps byte-identical request behavior.\n\t */\n\tprivate loadCredentialPool(): NonNullable<typeof this.credentialPoolModules> {\n\t\tthis.credentialPoolModules ??= (async () => {\n\t\t\tconst [rotation, stateStore] = await Promise.all([\n\t\t\t\timport(\"./credential-pool/rotation-stream.ts\"),\n\t\t\t\timport(\"./credential-pool/state-store.ts\"),\n\t\t\t]);\n\t\t\treturn { rotation, repository: new stateStore.CredentialSlotRepository() };\n\t\t})();\n\t\treturn this.credentialPoolModules;\n\t}\n\n\t/**\n\t * Fully synchronous admission check. A provider that cannot possibly hold a\n\t * pool must not even reach the async rotation path: awaiting an async method\n\t * costs a microtask hop, which would reorder an ordinary request's provider\n\t * call relative to the untouched `streamSimple` path.\n\t */\n\tprivate couldRotateCredentials(model: Model<Api>, options: CredentialRotationStreamOptions | undefined): boolean {\n\t\tif (options?.apiKey !== undefined) return false;\n\t\tif (this.credentials.hasRuntimeApiKey(model.provider)) return false;\n\t\tif (this.config.getProvider(model.provider)?.credentials?.rotation === false) return false;\n\t\tconst env = (name: string) => options?.env?.[name] ?? process.env[name];\n\t\tif (this.snapshot.storedProviders.has(model.provider)) return true;\n\t\treturn mightHoldEnvCredentialPool(model.provider, env);\n\t}\n\n\tprivate async credentialRotationSources(\n\t\tmodel: Model<Api>,\n\t\toptions: CredentialRotationStreamOptions | undefined,\n\t): Promise<RotationSources | undefined> {\n\t\tconst env = (name: string) => options?.env?.[name] ?? process.env[name];\n\t\tconst credential = await this.credentials.read(model.provider, { signal: options?.signal });\n\t\tif (!mightHoldCredentialPool(model.provider, credential, env)) return undefined;\n\t\tconst pool = await this.loadCredentialPool();\n\t\tconst sources: RotationSources = {\n\t\t\tproviderId: model.provider,\n\t\t\tcredential,\n\t\t\tenv,\n\t\t\trepository: pool.repository,\n\t\t};\n\t\tconst slots = await pool.rotation.listRotationSlots(sources);\n\t\treturn slots.length > 1 ? sources : undefined;\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\treturn lazyStream(model, async () => {\n\t\t\tconst streamOptions = options as CredentialRotationStreamOptions | undefined;\n\t\t\tconst sources = this.couldRotateCredentials(model, streamOptions)\n\t\t\t\t? await this.credentialRotationSources(model, streamOptions)\n\t\t\t\t: undefined;\n\t\t\tif (sources) {\n\t\t\t\tconst { rotation } = await this.loadCredentialPool();\n\t\t\t\treturn rotation.streamWithCredentialRotation({\n\t\t\t\t\tsources,\n\t\t\t\t\t...(streamOptions?.affinityKey === undefined ? {} : { affinityKey: streamOptions.affinityKey }),\n\t\t\t\t\trunAttempt: async (slot) => {\n\t\t\t\t\t\tconst prepared = await this.prepareRequest(\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tstreamOptions,\n\t\t\t\t\t\t\tslot.lane === \"env\"\n\t\t\t\t\t\t\t\t? { ...(slot.envKey === undefined ? {} : { apiKey: slot.envKey }) }\n\t\t\t\t\t\t\t\t: { slotName: slot.name },\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst attempt = prepared.provider.stream(\n\t\t\t\t\t\t\tprepared.model as Model<TApi>,\n\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\twithPayloadRequestMetadata(prepared.options, prepared.model) as ApiStreamOptions<TApi>,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn wrapStreamWithModelRecovery(attempt, model, context.tools ?? []);\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst prepared = await this.prepareRequest(model, streamOptions);\n\t\t\tconst inner = prepared.provider.stream(\n\t\t\t\tprepared.model as Model<TApi>,\n\t\t\t\tcontext,\n\t\t\t\twithPayloadRequestMetadata(prepared.options, prepared.model) as ApiStreamOptions<TApi>,\n\t\t\t);\n\t\t\treturn wrapStreamWithModelRecovery(inner, model, context.tools ?? []);\n\t\t});\n\t}\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\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\tconst inner = prepared.provider.streamSimple(\n\t\t\t\tprepared.model,\n\t\t\t\tcontext,\n\t\t\t\twithPayloadRequestMetadata(prepared.options, prepared.model) as SimpleStreamOptions,\n\t\t\t);\n\t\t\treturn wrapStreamWithModelRecovery(inner, model, context.tools ?? []);\n\t\t});\n\t}\n\tcompleteSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage> {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n\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\tlogin(providerId: string, type: AuthType, interaction: AuthInteraction): Promise<Credential> {\n\t\tconst signal = operationSignal(interaction.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tconst credential = await this.models.login(providerId, type, { ...interaction, signal });\n\t\t\tawait this.synchronizeCredentialState(providerId, \"login\", credential, signal);\n\t\t\treturn credential;\n\t\t});\n\t}\n\n\tlogout(providerId: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tawait this.models.logout(providerId, { signal });\n\t\t\tawait this.synchronizeCredentialState(providerId, \"logout\", undefined, signal);\n\t\t});\n\t}\n\n\tasync reloadConfig(): Promise<void> {\n\t\tawait this.refresh({ allowNetwork: this.modelNetworkEnabled });\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<ModelsRefreshResult> {\n\t\tthis.config = await ModelConfig.load(this.modelsPath);\n\t\tif (options.providers) {\n\t\t\tfor (const providerId of new Set(options.providers)) this.recomposeProvider(providerId);\n\t\t\tthis.updateModelSnapshot();\n\t\t} else {\n\t\t\tthis.rebuildProviders();\n\t\t}\n\t\tconst refreshOptions = {\n\t\t\t...options,\n\t\t\tallowNetwork: options.allowNetwork ?? this.modelNetworkEnabled,\n\t\t};\n\t\t// Published pi-ai builds before ModelsStore returned void and accepted a provider ID.\n\t\t// The fallback keeps source-mode CLI tests working without rebuilding workspace dependencies.\n\t\tconst result = ((await this.models.refresh(refreshOptions)) as ModelsRefreshResult | undefined) ?? {\n\t\t\taborted: refreshOptions.signal?.aborted ?? false,\n\t\t\terrors: new Map(),\n\t\t};\n\t\tconst errors = new Map(result.errors);\n\t\tthis.updateModelSnapshot();\n\t\tif (options.providers) {\n\t\t\tawait Promise.all(\n\t\t\t\t[...new Set(options.providers)].map(async (providerId) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.refreshProviderAvailability(providerId, operationSignal(options.signal));\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!options.signal?.aborted) {\n\t\t\t\t\t\t\terrors.set(providerId, error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tawait this.queueAvailabilityRefresh(options.signal);\n\t\t\t} catch {\n\t\t\t\t// Availability errors are recorded by the latest pass; refreshed models remain usable.\n\t\t\t}\n\t\t}\n\t\treturn { aborted: result.aborted || (options.signal?.aborted ?? false), errors };\n\t}\n\n\t/**\n\t * Providers registered after startup missed the create() refresh. Load their catalogs\n\t * under the runtime network policy, bounded like startup, so newly registered models are\n\t * usable without a manual refresh. Offline policy restores from the store only and never\n\t * touches the network.\n\t */\n\tprivate shouldSkipRegistrationRefresh(providerId: string): boolean {\n\t\treturn (\n\t\t\tthis.hasFreshAvailabilitySnapshot() &&\n\t\t\t(this.nativeExtensionProviders.has(providerId) || this.extensionProviders.has(providerId))\n\t\t);\n\t}\n\n\tprivate refreshAfterRegistration(): Promise<ModelsRefreshResult> {\n\t\tif (!this.modelNetworkEnabled) return this.refresh({ allowNetwork: false });\n\t\tconst controller = new AbortController();\n\t\tconst timeout = setTimeout(() => controller.abort(), this.modelRefreshTimeoutMs);\n\t\treturn this.refresh({ allowNetwork: true, signal: controller.signal }).finally(() => clearTimeout(timeout));\n\t}\n\n\tregisterNativeProvider(provider: Provider, options?: { refresh?: boolean }): Promise<ModelsRefreshResult> {\n\t\tif (!provider.id.trim()) throw new Error(\"Provider id must not be empty.\");\n\t\tconst alreadyFresh = this.shouldSkipRegistrationRefresh(provider.id);\n\t\tthis.extensionProviders.delete(provider.id);\n\t\tthis.nativeExtensionProviders.set(provider.id, provider);\n\t\tthis.recomposeProvider(provider.id);\n\t\tconst composedOAuth = this.models.getProvider(provider.id)?.auth.oauth;\n\t\tif (composedOAuth) this.credentials.registerOAuthProvider(provider.id, composedOAuth);\n\t\telse this.credentials.unregisterOAuthProvider(provider.id);\n\t\tthis.updateModelSnapshot();\n\t\tif (alreadyFresh || options?.refresh === false) {\n\t\t\treturn Promise.resolve({ aborted: false, errors: new Map() });\n\t\t}\n\t\treturn this.refreshAfterRegistration();\n\t}\n\n\tregisterProvider(\n\t\tproviderId: string,\n\t\tconfig: ProviderConfigInput,\n\t\toptions?: { refresh?: boolean },\n\t): Promise<ModelsRefreshResult> {\n\t\t// Validate the incoming registration on its own, like the legacy registry:\n\t\t// a broken re-registration must throw without touching the stored config.\n\t\tvalidateExtensionProvider(providerId, this.builtins.get(providerId), this.config.getProvider(providerId), config);\n\t\tconst alreadyFresh = this.shouldSkipRegistrationRefresh(providerId);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\t// Re-registration merges defined values over the previous registration and\n\t\t// preserves undefined ones, matching the legacy ModelRegistry contract.\n\t\tconst previous = this.extensionProviders.get(providerId);\n\t\tconst effective: ProviderConfigInput = { ...previous };\n\t\tfor (const [key, value] of Object.entries(config)) {\n\t\t\tif (value !== undefined) (effective as Record<string, unknown>)[key] = value;\n\t\t}\n\t\tthis.extensionProviders.set(providerId, effective);\n\t\tthis.recomposeProvider(providerId);\n\t\tconst composedOAuth = this.models.getProvider(providerId)?.auth.oauth;\n\t\tif (composedOAuth) this.credentials.registerOAuthProvider(providerId, composedOAuth);\n\t\telse this.credentials.unregisterOAuthProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tif (\n\t\t\tthis.snapshot.storedProviders.has(providerId) ||\n\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(providerId), effective)?.configured\n\t\t) {\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\t\tconst auth = new Map(this.snapshot.auth);\n\t\t\t// Provisional entry until the async refresh lands; never clobber a real check result.\n\t\t\tif (!auth.get(providerId)) {\n\t\t\t\tauth.set(providerId, {\n\t\t\t\t\ttype: effective.oauth && !effective.apiKey ? \"oauth\" : \"api_key\",\n\t\t\t\t\tsource: \"configured provider\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tthis.snapshot = {\n\t\t\t\t...this.snapshot,\n\t\t\t\tauth,\n\t\t\t\tconfiguredProviders,\n\t\t\t\tavailable: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),\n\t\t\t};\n\t\t}\n\t\tif (alreadyFresh || options?.refresh === false) {\n\t\t\treturn Promise.resolve({ aborted: false, errors: new Map() });\n\t\t}\n\t\treturn this.refreshAfterRegistration();\n\t}\n\n\tunregisterProvider(providerId: string): void {\n\t\tthis.extensionProviders.delete(providerId);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.credentials.unregisterOAuthProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"model-runtime.js","sourceRoot":"","sources":["../../src/core/model-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAcN,YAAY,EAIZ,UAAU,EAMV,WAAW,EAYX,eAAe,EACf,2BAA2B,GAC3B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,sBAAsB,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,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C,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS;oBAChE,MAAM,EAAE,qBAAqB;iBAC7B,CAAC,CAAC;YACJ,CAAC;YACD,IAAI,CAAC,QAAQ,GAAG;gBACf,GAAG,IAAI,CAAC,QAAQ;gBAChB,IAAI;gBACJ,mBAAmB;gBACnB,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,mBAAmB,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;aACvF,CAAC;QACH,CAAC;QACD,IAAI,YAAY,IAAI,OAAO,EAAE,OAAO,KAAK,KAAK,EAAE,CAAC;YAChD,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,GAAG,EAAE,EAAE,CAAC,CAAC;QAC/D,CAAC;QACD,OAAO,IAAI,CAAC,wBAAwB,EAAE,CAAC;IACxC,CAAC;IAED,kBAAkB,CAAC,UAAkB;QACpC,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC3C,IAAI,CAAC,wBAAwB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QACjD,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC;QACnC,IAAI,CAAC,WAAW,CAAC,uBAAuB,CAAC,UAAU,CAAC,CAAC;QACrD,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC3B,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAC5C,CAAC;CACD","sourcesContent":["import { dirname, join } from \"node:path\";\nimport {\n\ttype Api,\n\ttype ApiStreamOptions,\n\ttype AssistantMessage,\n\ttype AssistantMessageEventStream,\n\ttype AuthCheck,\n\ttype AuthInteraction,\n\ttype AuthOperationOptions,\n\ttype AuthResult,\n\ttype AuthType,\n\ttype Context,\n\ttype Credential,\n\ttype CredentialInfo,\n\ttype CredentialStore,\n\tcreateModels,\n\ttype DeferredCancelOptions,\n\ttype DeferredFetchOptions,\n\ttype DeferredHandle,\n\tlazyStream,\n\ttype Model,\n\ttype Models,\n\ttype ModelsApiStreamOptions,\n\ttype ModelsDeferredCancelOptions,\n\ttype ModelsDeferredFetchOptions,\n\tModelsError,\n\ttype ModelsRefreshOptions,\n\ttype ModelsRefreshResult,\n\ttype ModelsRequestTransforms,\n\ttype ModelsSimpleStreamOptions,\n\ttype ModelsStore,\n\ttype MutableModels,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype ProviderRequestOptions,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n\tsetWireIdentity,\n\twrapStreamWithModelRecovery,\n} from \"@earendil-works/pi-ai\";\nimport * as builtinProviderCatalog from \"@earendil-works/pi-ai/providers/all\";\nimport { APP_NAME, BRAND, getAgentDir } from \"../config.ts\";\nimport { operationSignal, raceWithAbortSignal } from \"../utils/abort.ts\";\nimport { AuthStorage as DefaultAuthStorage } from \"./auth-storage.ts\";\nimport { envValue } from \"./brand.ts\";\nimport { discoverEnvSlots } from \"./credential-pool/env-slots.ts\";\nimport type { RotationSources } from \"./credential-pool/rotation-stream.ts\";\nimport { ModelConfig } from \"./model-config.ts\";\nimport { FileModelsStore, InMemoryCodingAgentModelsStore } from \"./models-store.ts\";\nimport {\n\ttype AuthStatus,\n\ttype CompatibilityRequestConfig,\n\tcomposeModelProvider,\n\tconfiguredRequestAuthStatus,\n\ttype ProviderConfigInput,\n\tresolveCompatibilityRequestConfig,\n\tresolveConfiguredModelHeaders,\n\tvalidateExtensionProvider,\n} from \"./provider-composer.ts\";\nimport { remoteCatalogServesProvider, withRemoteCatalog } from \"./remote-catalog-provider.ts\";\nimport { RuntimeCredentials } from \"./runtime-credentials.ts\";\n\n// The product's identity must ride outgoing requests. This lives here because the AI package\n// is already part of this module's graph; the CLI bootstrap deliberately does not import it.\nsetWireIdentity(BRAND?.userAgent ?? APP_NAME);\n\ninterface ModelRuntimeSnapshot {\n\tall: readonly Model<Api>[];\n\tavailable: readonly Model<Api>[];\n\tconfiguredProviders: ReadonlySet<string>;\n\tstoredProviders: ReadonlySet<string>;\n\tauth: ReadonlyMap<string, AuthCheck | undefined>;\n}\n\nexport interface CreateModelRuntimeOptions {\n\t/** Credential storage. Defaults to the file at authPath. */\n\tcredentials?: CredentialStore;\n\tauthPath?: string;\n\tagentDir?: string;\n\tmodelsPath?: string | null;\n\tmodelsStore?: ModelsStore;\n\tmodelsStorePath?: string;\n\t/** Allow create() to refresh model catalogs over the network. Defaults to false. */\n\tallowModelNetwork?: boolean;\n\t/** Timeout for the create-time network model refresh. */\n\tmodelRefreshTimeoutMs?: number;\n\tcatalogBaseUrl?: string;\n\t/** Optional caller cancellation for initial cache restoration and availability checks. */\n\tsignal?: AbortSignal;\n\t/** Skip initial catalog and availability refresh. Static models remain available. */\n\trefreshOnCreate?: boolean;\n}\n\nexport interface ModelRuntimeAuthOverrides extends AuthOperationOptions {\n\tapiKey?: string;\n\tenv?: Record<string, string>;\n\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n\t/** Resolve against one named slot of a pooled credential instead of the flat projection. */\n\tslotName?: string;\n}\n\n/**\n * Stream options plus the coding-agent-only affinity key. It is declared here\n * rather than widening the engine's `StreamOptions`: a stable key (the session\n * id) keeps one conversation on one credential slot, and its absence simply\n * distributes requests instead of concentrating them.\n */\nexport type CredentialRotationStreamOptions = StreamOptions & ModelsRequestTransforms & { affinityKey?: string };\n\nfunction mightHoldCredentialPool(\n\tproviderId: string,\n\tcredential: Credential | undefined,\n\tenv: (name: string) => string | undefined,\n\tpolicySlots?: Record<string, { env?: string; value?: string }>,\n): boolean {\n\tif (credential) {\n\t\tconst accounts = Object.entries(credential).find(([key]) => key === \"accounts\")?.[1];\n\t\treturn (Array.isArray(accounts) && accounts.length > 1) || Object.keys(policySlots ?? {}).length > 0;\n\t}\n\treturn discoverEnvSlots(providerId, env).length + Object.keys(policySlots ?? {}).length > 1;\n}\n\nexport type CredentialSynchronizationOperation = \"login\" | \"logout\" | \"setRuntimeApiKey\" | \"removeRuntimeApiKey\";\n\n/** Credentials changed successfully, but the local model/auth snapshot could not be synchronized. */\nexport class CredentialSynchronizationError extends Error {\n\treadonly providerId: string;\n\treadonly operation: CredentialSynchronizationOperation;\n\treadonly credential: Credential | undefined;\n\n\tconstructor(\n\t\tproviderId: string,\n\t\toperation: CredentialSynchronizationOperation,\n\t\tcredential: Credential | undefined,\n\t\toptions: ErrorOptions,\n\t) {\n\t\tsuper(`Credential ${operation} committed for ${providerId}, but local synchronization failed`, options);\n\t\tthis.name = \"CredentialSynchronizationError\";\n\t\tthis.providerId = providerId;\n\t\tthis.operation = operation;\n\t\tthis.credential = credential;\n\t}\n}\n\nfunction 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\nfunction withPayloadRequestMetadata(options: StreamOptions, model: Model<Api>): StreamOptions {\n\tif (!options.onPayload) return options;\n\tconst onPayload = options.onPayload;\n\treturn {\n\t\t...options,\n\t\tonPayload: async (payload, providerModel) =>\n\t\t\tawait onPayload(payload, providerModel, {\n\t\t\t\tmodel,\n\t\t\t\theaders: options.headers ?? {},\n\t\t\t}),\n\t};\n}\n\n/** Configured pi-ai Models collection used by coding-agent and SDK consumers. */\nexport class ModelRuntime implements Models {\n\tprivate readonly models: MutableModels;\n\tprivate readonly credentials: RuntimeCredentials;\n\tprivate readonly defaultBuiltins: ReadonlyMap<string, Provider>;\n\tprivate readonly builtins = new Map<string, Provider>();\n\tprivate readonly nativeExtensionProviders = new Map<string, Provider>();\n\tprivate readonly extensionProviders = new Map<string, ProviderConfigInput>();\n\tprivate readonly compositionErrors = new Map<string, string>();\n\tprivate readonly modelsPath: string | undefined;\n\tprivate readonly modelNetworkEnabled: boolean;\n\tprivate readonly modelRefreshTimeoutMs: number;\n\tprivate config: ModelConfig;\n\tprivate snapshot: ModelRuntimeSnapshot = {\n\t\tall: [],\n\t\tavailable: [],\n\t\tconfiguredProviders: new Set(),\n\t\tstoredProviders: new Set(),\n\t\tauth: new Map(),\n\t};\n\tprivate availabilityInitialized = false;\n\tprivate availabilityRefreshSeq = 0;\n\tprivate availabilityErrorSeq = 0;\n\tprivate readonly providerAvailabilitySeq = new Map<string, number>();\n\tprivate availabilityError: string | undefined;\n\tprivate readonly credentialOperations = new Map<string, Promise<unknown>>();\n\t/**\n\t * The credential pool is loaded lazily and only for a provider that actually\n\t * has more than one slot. Importing it eagerly would pull the pool's schema\n\t * validator - and its module-level global registry - into every consumer of\n\t * ModelRuntime, which the import-graph guard forbids.\n\t */\n\tprivate readonly poolStatePath: string | undefined;\n\tprivate credentialPoolModules:\n\t\t| Promise<{\n\t\t\t\trotation: typeof import(\"./credential-pool/rotation-stream.ts\");\n\t\t\t\trepository: InstanceType<typeof import(\"./credential-pool/state-store.ts\").CredentialSlotRepository>;\n\t\t }>\n\t\t| undefined;\n\tprivate constructor(\n\t\tcredentials: RuntimeCredentials,\n\t\tconfig: ModelConfig,\n\t\tmodelsPath: string | undefined,\n\t\tmodelsStore: ModelsStore,\n\t\tproviders: readonly Provider[],\n\t\tmodelNetworkEnabled: boolean,\n\t\tmodelRefreshTimeoutMs: number,\n\t\tpoolStatePath?: string,\n\t) {\n\t\tthis.credentials = credentials;\n\t\tthis.poolStatePath = poolStatePath;\n\t\tthis.config = config;\n\t\tthis.modelsPath = modelsPath;\n\t\tthis.modelNetworkEnabled = modelNetworkEnabled;\n\t\tthis.modelRefreshTimeoutMs = modelRefreshTimeoutMs;\n\t\tthis.defaultBuiltins = new Map(providers.map((provider) => [provider.id, provider]));\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tthis.models = createModels({ credentials, modelsStore });\n\t\tthis.rebuildProviders();\n\t}\n\n\tstatic async create(options: CreateModelRuntimeOptions = {}): Promise<ModelRuntime> {\n\t\tconst credentials = new RuntimeCredentials(options.credentials ?? DefaultAuthStorage.create(options.authPath));\n\t\tconst modelsPath =\n\t\t\toptions.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), \"models.json\"));\n\t\tconst config = await ModelConfig.load(modelsPath);\n\t\tconst modelsStore =\n\t\t\toptions.modelsStore ??\n\t\t\t(modelsPath\n\t\t\t\t? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), \"models-store.json\"))\n\t\t\t\t: new InMemoryCodingAgentModelsStore());\n\t\tconst builtinModelDataGeneratedAt = builtinProviderCatalog.getBuiltinModelDataGeneratedAt();\n\t\tconst providers = builtinProviderCatalog\n\t\t\t.builtinProviders()\n\t\t\t.map((provider) =>\n\t\t\t\tprovider.refreshModels || !remoteCatalogServesProvider(provider.id, options.catalogBaseUrl)\n\t\t\t\t\t? provider\n\t\t\t\t\t: withRemoteCatalog(provider, options.catalogBaseUrl, builtinModelDataGeneratedAt),\n\t\t\t);\n\t\tconst runtime = new ModelRuntime(\n\t\t\tcredentials,\n\t\t\tconfig,\n\t\t\tmodelsPath,\n\t\t\tmodelsStore,\n\t\t\tproviders,\n\t\t\tenvValue(\"OFFLINE\") === undefined && options.allowModelNetwork === true,\n\t\t\toptions.modelRefreshTimeoutMs ?? 15_000,\n\t\t\toptions.agentDir\n\t\t\t\t? join(options.agentDir, \"credential-pool-state.json\")\n\t\t\t\t: options.authPath\n\t\t\t\t\t? join(dirname(options.authPath), \"credential-pool-state.json\")\n\t\t\t\t\t: undefined,\n\t\t);\n\t\truntime.rebuildProviders();\n\t\tconst refreshFromNetwork = runtime.modelNetworkEnabled && options.allowModelNetwork === true;\n\t\tconst controller =\n\t\t\trefreshFromNetwork && options.modelRefreshTimeoutMs !== undefined ? new AbortController() : undefined;\n\t\tconst timeout = controller ? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs) : undefined;\n\t\tconst signal = controller\n\t\t\t? options.signal\n\t\t\t\t? AbortSignal.any([options.signal, controller.signal])\n\t\t\t\t: controller.signal\n\t\t\t: options.signal;\n\t\ttry {\n\t\t\tif (options.refreshOnCreate !== false) {\n\t\t\t\tawait runtime.refresh({ allowNetwork: refreshFromNetwork, signal });\n\t\t\t}\n\t\t} finally {\n\t\t\tif (timeout) clearTimeout(timeout);\n\t\t}\n\t\treturn runtime;\n\t}\n\n\t/** Synchronous compatibility constructor for legacy ModelRegistry callers. */\n\tstatic createSync(options: CreateModelRuntimeOptions = {}): ModelRuntime {\n\t\tconst credentials = new RuntimeCredentials(options.credentials ?? DefaultAuthStorage.create(options.authPath));\n\t\tconst modelsPath =\n\t\t\toptions.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), \"models.json\"));\n\t\tconst config = ModelConfig.loadSync(modelsPath);\n\t\tconst modelsStore =\n\t\t\toptions.modelsStore ??\n\t\t\t(modelsPath\n\t\t\t\t? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), \"models-store.json\"))\n\t\t\t\t: new InMemoryCodingAgentModelsStore());\n\t\tconst providers = builtinProviderCatalog\n\t\t\t.builtinProviders()\n\t\t\t.map((provider) =>\n\t\t\t\tprovider.refreshModels || !remoteCatalogServesProvider(provider.id, options.catalogBaseUrl)\n\t\t\t\t\t? provider\n\t\t\t\t\t: withRemoteCatalog(provider, options.catalogBaseUrl),\n\t\t\t);\n\t\tconst runtime = new ModelRuntime(\n\t\t\tcredentials,\n\t\t\tconfig,\n\t\t\tmodelsPath,\n\t\t\tmodelsStore,\n\t\t\tproviders,\n\t\t\toptions.allowModelNetwork ?? false,\n\t\t\toptions.modelRefreshTimeoutMs ?? 15_000,\n\t\t\toptions.agentDir\n\t\t\t\t? join(options.agentDir, \"credential-pool-state.json\")\n\t\t\t\t: options.authPath\n\t\t\t\t\t? join(dirname(options.authPath), \"credential-pool-state.json\")\n\t\t\t\t\t: undefined,\n\t\t);\n\t\truntime.rebuildProviders();\n\t\treturn runtime;\n\t}\n\n\tprivate providerIds(): Set<string> {\n\t\treturn new Set([\n\t\t\t...this.builtins.keys(),\n\t\t\t...this.nativeExtensionProviders.keys(),\n\t\t\t...this.config.getProviderIds(),\n\t\t\t...this.extensionProviders.keys(),\n\t\t]);\n\t}\n\n\tprivate recomposeProvider(providerId: string): void {\n\t\tif (this.config.isProviderDisabled(providerId)) {\n\t\t\tthis.models.deleteProvider(providerId);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\tconst base = this.nativeExtensionProviders.get(providerId) ?? this.builtins.get(providerId);\n\t\tconst extension = this.extensionProviders.get(providerId);\n\t\tif (!base && !this.config.getProvider(providerId) && !extension) {\n\t\t\tthis.models.deleteProvider(providerId);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\tif (base && !this.config.getProvider(providerId) && !extension) {\n\t\t\t// No overlays: use the builtin untouched so its auth/login/stream behavior is exact.\n\t\t\tthis.models.setProvider(base);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.models.setProvider(composeModelProvider(providerId, base, this.config, extension));\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t} catch (error) {\n\t\t\tthis.compositionErrors.set(providerId, error instanceof Error ? error.message : String(error));\n\t\t\tif (base) this.models.setProvider(base);\n\t\t\telse this.models.deleteProvider(providerId);\n\t\t}\n\t}\n\n\tprivate rebuildProviders(): void {\n\t\tthis.models.clearProviders();\n\t\tthis.compositionErrors.clear();\n\t\tfor (const providerId of this.providerIds()) this.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t}\n\n\tprivate updateModelSnapshot(): void {\n\t\tconst all = [...this.models.getModels()];\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tall,\n\t\t\tavailable: all.filter((model) => this.snapshot.configuredProviders.has(model.provider)),\n\t\t};\n\t}\n\n\tprivate async runAvailabilityRefresh(seq: number, errorSeq: number, signal: AbortSignal): Promise<void> {\n\t\tconst providers = this.models.getProviders();\n\t\tconst [available, checks, credentials] = await Promise.all([\n\t\t\tthis.models.getAvailable(undefined, { signal }),\n\t\t\tPromise.all(\n\t\t\t\tproviders.map(\n\t\t\t\t\tasync (provider): Promise<[string, AuthCheck | undefined]> => [\n\t\t\t\t\t\tprovider.id,\n\t\t\t\t\t\tawait this.models.checkAuth(provider.id, { signal }),\n\t\t\t\t\t],\n\t\t\t\t),\n\t\t\t),\n\t\t\tthis.credentials.list({ signal }),\n\t\t]);\n\t\tif (seq !== this.availabilityRefreshSeq) return;\n\t\tconst auth = new Map(checks);\n\t\tconst configuredProviders = new Set(\n\t\t\tchecks\n\t\t\t\t.filter((entry): entry is [string, AuthCheck] => entry[1] !== undefined)\n\t\t\t\t.map(([providerId]) => providerId),\n\t\t);\n\t\tthis.snapshot = {\n\t\t\tall: [...this.models.getModels()],\n\t\t\tavailable: [...available],\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders: new Set(credentials.map((entry) => entry.providerId)),\n\t\t\tauth,\n\t\t};\n\t\tthis.availabilityInitialized = true;\n\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t}\n\n\tprivate queueAvailabilityRefresh(signal?: AbortSignal): Promise<void> {\n\t\tconst seq = ++this.availabilityRefreshSeq;\n\t\tfor (const [providerId, providerSeq] of this.providerAvailabilitySeq) {\n\t\t\tthis.providerAvailabilitySeq.set(providerId, providerSeq + 1);\n\t\t}\n\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\tconst effectiveSignal = operationSignal(signal);\n\t\treturn this.runAvailabilityRefresh(seq, errorSeq, effectiveSignal).catch((error) => {\n\t\t\tif (errorSeq === this.availabilityErrorSeq && !effectiveSignal.aborted) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t});\n\t}\n\n\tprivate async refreshProviderAvailability(providerId: string, signal: AbortSignal): Promise<void> {\n\t\t// Invalidate any full availability pass that started before this credential change.\n\t\t++this.availabilityRefreshSeq;\n\t\tconst providerSeq = (this.providerAvailabilitySeq.get(providerId) ?? 0) + 1;\n\t\tthis.providerAvailabilitySeq.set(providerId, providerSeq);\n\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\ttry {\n\t\t\tconst [available, auth, credential] = await Promise.all([\n\t\t\t\tthis.models.getAvailable(providerId, { signal }),\n\t\t\t\tthis.models.checkAuth(providerId, { signal }),\n\t\t\t\tthis.credentials.read(providerId, { signal }),\n\t\t\t]);\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (this.providerAvailabilitySeq.get(providerId) !== providerSeq) return;\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders);\n\t\t\tconst storedProviders = new Set(this.snapshot.storedProviders);\n\t\t\tconst authByProvider = new Map(this.snapshot.auth);\n\t\t\tif (auth) {\n\t\t\t\tconfiguredProviders.add(providerId);\n\t\t\t\tauthByProvider.set(providerId, auth);\n\t\t\t} else {\n\t\t\t\tconfiguredProviders.delete(providerId);\n\t\t\t\tauthByProvider.delete(providerId);\n\t\t\t}\n\t\t\tif (credential) storedProviders.add(providerId);\n\t\t\telse storedProviders.delete(providerId);\n\t\t\tconst all = [...this.models.getModels()];\n\t\t\tconst availableById = new Map(\n\t\t\t\t[...this.snapshot.available.filter((model) => model.provider !== providerId), ...available].map((model) => [\n\t\t\t\t\t`${model.provider}\\0${model.id}`,\n\t\t\t\t\tmodel,\n\t\t\t\t]),\n\t\t\t);\n\t\t\tthis.snapshot = {\n\t\t\t\tall,\n\t\t\t\tavailable: all.flatMap((model) => availableById.get(`${model.provider}\\0${model.id}`) ?? []),\n\t\t\t\tconfiguredProviders,\n\t\t\t\tstoredProviders,\n\t\t\t\tauth: authByProvider,\n\t\t\t};\n\t\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tthis.providerAvailabilitySeq.get(providerId) === providerSeq &&\n\t\t\t\terrorSeq === this.availabilityErrorSeq &&\n\t\t\t\t!signal.aborted\n\t\t\t) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tgetProviders(): readonly Provider[] {\n\t\treturn this.models.getProviders();\n\t}\n\tgetProvider(providerId: string): Provider | undefined {\n\t\treturn this.models.getProvider(providerId);\n\t}\n\tgetModels(providerId?: string): readonly Model<Api>[] {\n\t\treturn this.models.getModels(providerId);\n\t}\n\tgetModel(providerId: string, modelId: string): Model<Api> | undefined {\n\t\treturn this.models.getModel(providerId, modelId);\n\t}\n\n\tasync checkAuth(providerId: string, options?: AuthOperationOptions): Promise<AuthCheck | undefined> {\n\t\treturn this.models.checkAuth(providerId, options);\n\t}\n\n\tasync getAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly Model<Api>[]> {\n\t\tif (providerId) {\n\t\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\t\ttry {\n\t\t\t\tconst available = await this.models.getAvailable(providerId, options);\n\t\t\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t\t\t\treturn available;\n\t\t\t} catch (error) {\n\t\t\t\tif (errorSeq === this.availabilityErrorSeq && !options?.signal?.aborted) {\n\t\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tawait this.queueAvailabilityRefresh(options?.signal);\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetAvailableSnapshot(): readonly Model<Api>[] {\n\t\treturn this.snapshot.available;\n\t}\n\n\t/** True only when the most recent availability refresh completed without error. */\n\thasFreshAvailabilitySnapshot(): boolean {\n\t\treturn this.availabilityInitialized && this.availabilityError === undefined;\n\t}\n\n\thasAvailabilitySnapshot(): boolean {\n\t\treturn this.availabilityInitialized;\n\t}\n\n\tgetError(): string | undefined {\n\t\tconst errors: string[] = [];\n\t\tconst configError = this.config.getError();\n\t\tif (configError) errors.push(configError);\n\t\tfor (const [providerId, error] of this.compositionErrors) {\n\t\t\terrors.push(`Provider \"${providerId}\": ${error}`);\n\t\t}\n\t\tif (this.availabilityError) errors.push(`Availability refresh: ${this.availabilityError}`);\n\t\treturn errors.length > 0 ? errors.join(\"\\n\\n\") : undefined;\n\t}\n\n\tgetRegisteredProviderConfig(providerId: string): ProviderConfigInput | undefined {\n\t\treturn this.extensionProviders.get(providerId);\n\t}\n\n\tgetRegisteredProviderIds(): readonly string[] {\n\t\treturn [...new Set([...this.extensionProviders.keys(), ...this.nativeExtensionProviders.keys()])];\n\t}\n\n\tgetRegisteredNativeProvider(providerId: string): Provider | undefined {\n\t\treturn this.nativeExtensionProviders.get(providerId);\n\t}\n\n\t/** @internal Compatibility fallback for ModelRegistry when provider auth is unconfigured. */\n\tgetCompatibilityRequestConfig(model: Model<Api>, env?: Record<string, string>): CompatibilityRequestConfig {\n\t\treturn resolveCompatibilityRequestConfig(\n\t\t\tmodel,\n\t\t\tthis.config.getProvider(model.provider),\n\t\t\tthis.extensionProviders.get(model.provider),\n\t\t\tenv,\n\t\t);\n\t}\n\n\tisUsingOAuth(providerId: string): boolean {\n\t\treturn this.snapshot.auth.get(providerId)?.type === \"oauth\";\n\t}\n\n\tisUsingSubscription(providerId: string): boolean {\n\t\treturn this.isUsingOAuth(providerId) && this.models.getProvider(providerId)?.auth.oauth?.isSubscription === true;\n\t}\n\n\thasConfiguredAuth(providerId: string): boolean {\n\t\treturn this.snapshot.configuredProviders.has(providerId);\n\t}\n\n\t/**\n\t * Deterministic fallback-expansion gate declared by the provider's own\n\t * registration. Only a definitive `false` excludes; providers without the\n\t * hook, and hooks that throw, stay eligible so expansion never shrinks on\n\t * uncertainty.\n\t */\n\tisFallbackEligible(providerId: string): boolean {\n\t\tconst hook = this.extensionProviders.get(providerId)?.fallbackEligible;\n\t\tif (typeof hook !== \"function\") return true;\n\t\ttry {\n\t\t\treturn hook() !== false;\n\t\t} catch {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tgetAuth(providerId: string, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: Model<Api>, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tasync getAuth(\n\t\tproviderOrModel: string | Model<Api>,\n\t\toverrides: ModelRuntimeAuthOverrides = {},\n\t): Promise<AuthResult | undefined> {\n\t\tif (typeof providerOrModel === \"string\") return this.models.getAuth(providerOrModel, overrides);\n\t\tconst resolution = await this.models.getAuth(providerOrModel, overrides);\n\t\tif (!resolution) return undefined;\n\t\tconst configuredHeaders = resolveConfiguredModelHeaders(\n\t\t\tproviderOrModel,\n\t\t\tthis.config.getProvider(providerOrModel.provider),\n\t\t\tthis.extensionProviders.get(providerOrModel.provider),\n\t\t\t{ ...(resolution.env ?? {}), ...(overrides.env ?? {}) },\n\t\t);\n\t\treturn {\n\t\t\t...resolution,\n\t\t\tauth: {\n\t\t\t\t...resolution.auth,\n\t\t\t\theaders: mergeHeaders(resolution.auth.headers, configuredHeaders),\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate enqueueCredentialOperation<T>(providerId: string, signal: AbortSignal, task: () => Promise<T>): Promise<T> {\n\t\tconst previous = this.credentialOperations.get(providerId) ?? Promise.resolve();\n\t\tlet markStarted: (() => void) | undefined;\n\t\tconst started = new Promise<void>((resolve) => {\n\t\t\tmarkStarted = resolve;\n\t\t});\n\t\tconst operation = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\tsignal.throwIfAborted();\n\t\t\tmarkStarted?.();\n\t\t\treturn task();\n\t\t})();\n\t\tconst tail = operation.catch(() => {});\n\t\tthis.credentialOperations.set(providerId, tail);\n\t\tvoid tail.then(() => {\n\t\t\tif (this.credentialOperations.get(providerId) === tail) this.credentialOperations.delete(providerId);\n\t\t});\n\t\treturn raceWithAbortSignal(started, signal).then(() => operation);\n\t}\n\n\tprivate async synchronizeCredentialState(\n\t\tproviderId: string,\n\t\toperation: CredentialSynchronizationOperation,\n\t\tcredential: Credential | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthis.recomposeProvider(providerId);\n\t\t\tconst compositionError = this.compositionErrors.get(providerId);\n\t\t\tif (compositionError) throw new Error(compositionError);\n\t\t\tconst result = await this.models.refresh({\n\t\t\t\tallowNetwork: false,\n\t\t\t\tproviders: [providerId],\n\t\t\t\tsignal,\n\t\t\t});\n\t\t\tif (result.aborted) signal.throwIfAborted();\n\t\t\tconst refreshError = result.errors.get(providerId);\n\t\t\tif (refreshError) throw refreshError;\n\t\t\tthis.updateModelSnapshot();\n\t\t\tawait this.refreshProviderAvailability(providerId, signal);\n\t\t} catch (cause) {\n\t\t\tthrow new CredentialSynchronizationError(providerId, operation, credential, { cause });\n\t\t}\n\t}\n\n\tsetRuntimeApiKey(providerId: string, apiKey: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tthis.credentials.setRuntimeApiKey(providerId, apiKey);\n\t\t\tawait this.synchronizeCredentialState(\n\t\t\t\tproviderId,\n\t\t\t\t\"setRuntimeApiKey\",\n\t\t\t\t{ type: \"api_key\", key: apiKey },\n\t\t\t\tsignal,\n\t\t\t);\n\t\t});\n\t}\n\n\tremoveRuntimeApiKey(providerId: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tthis.credentials.removeRuntimeApiKey(providerId);\n\t\t\tawait this.synchronizeCredentialState(providerId, \"removeRuntimeApiKey\", undefined, signal);\n\t\t});\n\t}\n\n\tlistCredentials(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\treturn this.credentials.list(options);\n\t}\n\n\tgetProviderAuthStatus(providerId: string): AuthStatus {\n\t\tif (this.credentials.hasRuntimeApiKey(providerId)) return { configured: true, source: \"runtime\" };\n\t\tif (this.snapshot.storedProviders.has(providerId)) return { configured: true, source: \"stored\" };\n\t\tconst configured = configuredRequestAuthStatus(\n\t\t\tthis.config.getProvider(providerId),\n\t\t\tthis.extensionProviders.get(providerId),\n\t\t);\n\t\tif (configured) return configured;\n\t\tconst check = this.snapshot.auth.get(providerId);\n\t\treturn check ? { configured: true, source: \"environment\", label: check.source } : { configured: false };\n\t}\n\n\tprivate async prepareRequest<TOptions extends ProviderRequestOptions & ModelsRequestTransforms>(\n\t\tmodel: Model<Api>,\n\t\toptions: TOptions | undefined,\n\t\tslotAuth?: { apiKey?: string; slotName?: string },\n\t): Promise<{\n\t\tprovider: Provider;\n\t\tmodel: Model<Api>;\n\t\toptions: Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions;\n\t}> {\n\t\tconst provider = this.models.getProvider(model.provider);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\tconst resolution = await this.getAuth(model, {\n\t\t\tapiKey: slotAuth?.apiKey ?? options?.apiKey,\n\t\t\tenv: options?.env,\n\t\t\tsignal: options?.signal,\n\t\t\t...(slotAuth?.slotName === undefined ? {} : { slotName: slotAuth.slotName }),\n\t\t});\n\t\tif (!resolution) throw new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\n\t\tconst { transformHeaders, ...rawProviderOptions } = options ?? {};\n\t\tconst providerOptions = rawProviderOptions as Omit<TOptions, \"transformHeaders\"> &\n\t\t\tProviderRequestOptions & { extraBody?: Record<string, unknown> };\n\t\tlet headers = mergeHeaders(resolution.auth.headers, providerOptions.headers);\n\t\tif (transformHeaders) headers = await transformHeaders(headers ?? {});\n\t\tconst compatibility = this.getCompatibilityRequestConfig(model, resolution.env);\n\t\tconst extraBody =\n\t\t\tcompatibility.extraBody || providerOptions.extraBody\n\t\t\t\t? { ...compatibility.extraBody, ...providerOptions.extraBody }\n\t\t\t\t: undefined;\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 upstreamModelId = compatibility.upstreamModelId;\n\t\tconst requestModel =\n\t\t\tresolution.auth.baseUrl || upstreamModelId\n\t\t\t\t? {\n\t\t\t\t\t\t...model,\n\t\t\t\t\t\t...(upstreamModelId ? { id: upstreamModelId } : {}),\n\t\t\t\t\t\t...(resolution.auth.baseUrl ? { baseUrl: resolution.auth.baseUrl } : {}),\n\t\t\t\t\t}\n\t\t\t\t: model;\n\t\treturn {\n\t\t\tprovider,\n\t\t\tmodel: requestModel,\n\t\t\toptions: {\n\t\t\t\t...providerOptions,\n\t\t\t\tapiKey: slotAuth?.apiKey ?? providerOptions.apiKey ?? resolution.auth.apiKey,\n\t\t\t\theaders,\n\t\t\t\textraBody,\n\t\t\t\tenv,\n\t\t\t} as Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions,\n\t\t};\n\t}\n\n\t/**\n\t * Rotation engages only for a provider that actually holds more than one\n\t * credential slot and only when nothing pins the request to one credential\n\t * (a runtime key or an explicit per-request apiKey). Every single-credential\n\t * user therefore keeps byte-identical request behavior.\n\t */\n\tprivate loadCredentialPool(): NonNullable<typeof this.credentialPoolModules> {\n\t\tthis.credentialPoolModules ??= (async () => {\n\t\t\tconst [rotation, stateStore] = await Promise.all([\n\t\t\t\timport(\"./credential-pool/rotation-stream.ts\"),\n\t\t\t\timport(\"./credential-pool/state-store.ts\"),\n\t\t\t]);\n\t\t\treturn {\n\t\t\t\trotation,\n\t\t\t\trepository: new stateStore.CredentialSlotRepository(this.poolStatePath),\n\t\t\t};\n\t\t})();\n\t\treturn this.credentialPoolModules;\n\t}\n\n\t/**\n\t * Fully synchronous admission check. A provider that cannot possibly hold a\n\t * pool must not even reach the async rotation path: awaiting an async method\n\t * costs a microtask hop, which would reorder an ordinary request's provider\n\t * call relative to the untouched `streamSimple` path.\n\t */\n\tprivate couldRotateCredentials(model: Model<Api>, options: CredentialRotationStreamOptions | undefined): boolean {\n\t\tif (options?.apiKey !== undefined) return false;\n\t\tif (this.credentials.hasRuntimeApiKey(model.provider)) return false;\n\t\tif (this.config.getProvider(model.provider)?.credentials?.rotation === false) return false;\n\t\tconst env = (name: string) => options?.env?.[name] ?? process.env[name];\n\t\tif (this.snapshot.storedProviders.has(model.provider)) return true;\n\t\tconst policySlots = this.config.getProvider(model.provider)?.credentials?.slots;\n\t\treturn discoverEnvSlots(model.provider, env).length + Object.keys(policySlots ?? {}).length > 1;\n\t}\n\n\tprivate async credentialRotationSources(\n\t\tmodel: Model<Api>,\n\t\toptions: CredentialRotationStreamOptions | undefined,\n\t): Promise<RotationSources | undefined> {\n\t\tconst env = (name: string) => options?.env?.[name] ?? process.env[name];\n\t\tconst credential = await this.credentials.read(model.provider, {\n\t\t\tsignal: options?.signal,\n\t\t});\n\t\tconst policy = this.config.getProvider(model.provider)?.credentials;\n\t\tif (!mightHoldCredentialPool(model.provider, credential, env, policy?.slots)) return undefined;\n\t\tconst pool = await this.loadCredentialPool();\n\t\tconst sources: RotationSources = {\n\t\t\tproviderId: model.provider,\n\t\t\tcredential,\n\t\t\tenv,\n\t\t\trepository: pool.repository,\n\t\t\tpolicy,\n\t\t};\n\t\tconst slots = await pool.rotation.listRotationSlots(sources, { acquireLeases: false });\n\t\treturn slots.length > 1 ? sources : undefined;\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\treturn lazyStream(model, async () => {\n\t\t\tconst streamOptions = options as CredentialRotationStreamOptions | undefined;\n\t\t\tconst sources = this.couldRotateCredentials(model, streamOptions)\n\t\t\t\t? await this.credentialRotationSources(model, streamOptions)\n\t\t\t\t: undefined;\n\t\t\tif (sources) {\n\t\t\t\tconst { rotation } = await this.loadCredentialPool();\n\t\t\t\treturn rotation.streamWithCredentialRotation({\n\t\t\t\t\tsources,\n\t\t\t\t\t...(streamOptions?.affinityKey !== undefined\n\t\t\t\t\t\t? { affinityKey: streamOptions.affinityKey }\n\t\t\t\t\t\t: streamOptions?.sessionId !== undefined\n\t\t\t\t\t\t\t? { affinityKey: streamOptions.sessionId }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\trunAttempt: async (slot) => {\n\t\t\t\t\t\tconst prepared = await this.prepareRequest(\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tstreamOptions,\n\t\t\t\t\t\t\tslot.lane === \"env\"\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t...(slot.envKey === undefined ? {} : { apiKey: slot.envKey }),\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: { slotName: slot.name },\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst attempt = prepared.provider.stream(\n\t\t\t\t\t\t\tprepared.model as Model<TApi>,\n\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\twithPayloadRequestMetadata(prepared.options, prepared.model) as ApiStreamOptions<TApi>,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn wrapStreamWithModelRecovery(attempt, model, context.tools ?? []);\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst prepared = await this.prepareRequest(model, streamOptions);\n\t\t\tconst inner = prepared.provider.stream(\n\t\t\t\tprepared.model as Model<TApi>,\n\t\t\t\tcontext,\n\t\t\t\twithPayloadRequestMetadata(prepared.options, prepared.model) as ApiStreamOptions<TApi>,\n\t\t\t);\n\t\t\treturn wrapStreamWithModelRecovery(inner, model, context.tools ?? []);\n\t\t});\n\t}\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\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst streamOptions = options as CredentialRotationStreamOptions | undefined;\n\t\t\tconst sources = this.couldRotateCredentials(model, streamOptions)\n\t\t\t\t? await this.credentialRotationSources(model, streamOptions)\n\t\t\t\t: undefined;\n\t\t\tif (sources) {\n\t\t\t\tconst { rotation } = await this.loadCredentialPool();\n\t\t\t\treturn rotation.streamWithCredentialRotation({\n\t\t\t\t\tsources,\n\t\t\t\t\t...(streamOptions?.sessionId === undefined ? {} : { affinityKey: streamOptions.sessionId }),\n\t\t\t\t\trunAttempt: async (slot) => {\n\t\t\t\t\t\tconst prepared = await this.prepareRequest(\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tstreamOptions,\n\t\t\t\t\t\t\tslot.lane === \"env\" ? { apiKey: slot.envKey } : { slotName: slot.name },\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn wrapStreamWithModelRecovery(\n\t\t\t\t\t\t\tprepared.provider.streamSimple(\n\t\t\t\t\t\t\t\tprepared.model,\n\t\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\t\twithPayloadRequestMetadata(prepared.options, prepared.model) as SimpleStreamOptions,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tcontext.tools ?? [],\n\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\tconst inner = prepared.provider.streamSimple(\n\t\t\t\tprepared.model,\n\t\t\t\tcontext,\n\t\t\t\twithPayloadRequestMetadata(prepared.options, prepared.model) as SimpleStreamOptions,\n\t\t\t);\n\t\t\treturn wrapStreamWithModelRecovery(inner, model, context.tools ?? []);\n\t\t});\n\t}\n\tcompleteSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage> {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n\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\tlogin(providerId: string, type: AuthType, interaction: AuthInteraction): Promise<Credential> {\n\t\tconst signal = operationSignal(interaction.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tconst credential = await this.models.login(providerId, type, {\n\t\t\t\t...interaction,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t\tawait this.synchronizeCredentialState(providerId, \"login\", credential, signal);\n\t\t\treturn credential;\n\t\t});\n\t}\n\n\tlogout(providerId: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tawait this.models.logout(providerId, { signal });\n\t\t\tawait this.synchronizeCredentialState(providerId, \"logout\", undefined, signal);\n\t\t});\n\t}\n\n\tasync reloadConfig(): Promise<void> {\n\t\tawait this.refresh({ allowNetwork: this.modelNetworkEnabled });\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<ModelsRefreshResult> {\n\t\tthis.config = await ModelConfig.load(this.modelsPath);\n\t\tif (options.providers) {\n\t\t\tfor (const providerId of new Set(options.providers)) this.recomposeProvider(providerId);\n\t\t\tthis.updateModelSnapshot();\n\t\t} else {\n\t\t\tthis.rebuildProviders();\n\t\t}\n\t\tconst refreshOptions = {\n\t\t\t...options,\n\t\t\tallowNetwork: options.allowNetwork ?? this.modelNetworkEnabled,\n\t\t};\n\t\t// Published pi-ai builds before ModelsStore returned void and accepted a provider ID.\n\t\t// The fallback keeps source-mode CLI tests working without rebuilding workspace dependencies.\n\t\tconst result = ((await this.models.refresh(refreshOptions)) as ModelsRefreshResult | undefined) ?? {\n\t\t\taborted: refreshOptions.signal?.aborted ?? false,\n\t\t\terrors: new Map(),\n\t\t};\n\t\tconst errors = new Map(result.errors);\n\t\tthis.updateModelSnapshot();\n\t\tif (options.providers) {\n\t\t\tawait Promise.all(\n\t\t\t\t[...new Set(options.providers)].map(async (providerId) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.refreshProviderAvailability(providerId, operationSignal(options.signal));\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!options.signal?.aborted) {\n\t\t\t\t\t\t\terrors.set(providerId, error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tawait this.queueAvailabilityRefresh(options.signal);\n\t\t\t} catch {\n\t\t\t\t// Availability errors are recorded by the latest pass; refreshed models remain usable.\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\taborted: result.aborted || (options.signal?.aborted ?? false),\n\t\t\terrors,\n\t\t};\n\t}\n\n\t/**\n\t * Providers registered after startup missed the create() refresh. Load their catalogs\n\t * under the runtime network policy, bounded like startup, so newly registered models are\n\t * usable without a manual refresh. Offline policy restores from the store only and never\n\t * touches the network.\n\t */\n\tprivate shouldSkipRegistrationRefresh(providerId: string): boolean {\n\t\treturn (\n\t\t\tthis.hasFreshAvailabilitySnapshot() &&\n\t\t\t(this.nativeExtensionProviders.has(providerId) || this.extensionProviders.has(providerId))\n\t\t);\n\t}\n\n\tprivate refreshAfterRegistration(): Promise<ModelsRefreshResult> {\n\t\tif (!this.modelNetworkEnabled) return this.refresh({ allowNetwork: false });\n\t\tconst controller = new AbortController();\n\t\tconst timeout = setTimeout(() => controller.abort(), this.modelRefreshTimeoutMs);\n\t\treturn this.refresh({\n\t\t\tallowNetwork: true,\n\t\t\tsignal: controller.signal,\n\t\t}).finally(() => clearTimeout(timeout));\n\t}\n\n\tregisterNativeProvider(provider: Provider, options?: { refresh?: boolean }): Promise<ModelsRefreshResult> {\n\t\tif (!provider.id.trim()) throw new Error(\"Provider id must not be empty.\");\n\t\tconst alreadyFresh = this.shouldSkipRegistrationRefresh(provider.id);\n\t\tthis.extensionProviders.delete(provider.id);\n\t\tthis.nativeExtensionProviders.set(provider.id, provider);\n\t\tthis.recomposeProvider(provider.id);\n\t\tconst composedOAuth = this.models.getProvider(provider.id)?.auth.oauth;\n\t\tif (composedOAuth) this.credentials.registerOAuthProvider(provider.id, composedOAuth);\n\t\telse this.credentials.unregisterOAuthProvider(provider.id);\n\t\tthis.updateModelSnapshot();\n\t\tif (alreadyFresh || options?.refresh === false) {\n\t\t\treturn Promise.resolve({ aborted: false, errors: new Map() });\n\t\t}\n\t\treturn this.refreshAfterRegistration();\n\t}\n\n\tregisterProvider(\n\t\tproviderId: string,\n\t\tconfig: ProviderConfigInput,\n\t\toptions?: { refresh?: boolean },\n\t): Promise<ModelsRefreshResult> {\n\t\t// Validate the incoming registration on its own, like the legacy registry:\n\t\t// a broken re-registration must throw without touching the stored config.\n\t\tvalidateExtensionProvider(providerId, this.builtins.get(providerId), this.config.getProvider(providerId), config);\n\t\tconst alreadyFresh = this.shouldSkipRegistrationRefresh(providerId);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\t// Re-registration merges defined values over the previous registration and\n\t\t// preserves undefined ones, matching the legacy ModelRegistry contract.\n\t\tconst previous = this.extensionProviders.get(providerId);\n\t\tconst effective: ProviderConfigInput = { ...previous };\n\t\tfor (const [key, value] of Object.entries(config)) {\n\t\t\tif (value !== undefined) (effective as Record<string, unknown>)[key] = value;\n\t\t}\n\t\tthis.extensionProviders.set(providerId, effective);\n\t\tthis.recomposeProvider(providerId);\n\t\tconst composedOAuth = this.models.getProvider(providerId)?.auth.oauth;\n\t\tif (composedOAuth) this.credentials.registerOAuthProvider(providerId, composedOAuth);\n\t\telse this.credentials.unregisterOAuthProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tif (\n\t\t\tthis.snapshot.storedProviders.has(providerId) ||\n\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(providerId), effective)?.configured\n\t\t) {\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\t\tconst auth = new Map(this.snapshot.auth);\n\t\t\t// Provisional entry until the async refresh lands; never clobber a real check result.\n\t\t\tif (!auth.get(providerId)) {\n\t\t\t\tauth.set(providerId, {\n\t\t\t\t\ttype: effective.oauth && !effective.apiKey ? \"oauth\" : \"api_key\",\n\t\t\t\t\tsource: \"configured provider\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tthis.snapshot = {\n\t\t\t\t...this.snapshot,\n\t\t\t\tauth,\n\t\t\t\tconfiguredProviders,\n\t\t\t\tavailable: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),\n\t\t\t};\n\t\t}\n\t\tif (alreadyFresh || options?.refresh === false) {\n\t\t\treturn Promise.resolve({ aborted: false, errors: new Map() });\n\t\t}\n\t\treturn this.refreshAfterRegistration();\n\t}\n\n\tunregisterProvider(providerId: string): void {\n\t\tthis.extensionProviders.delete(providerId);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.credentials.unregisterOAuthProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n}\n"]}
|
|
@@ -32,8 +32,30 @@ export declare function baseSelector(selector: Pick<FallbackSelector, "provider"
|
|
|
32
32
|
* Provider-qualified keys and entries keep exact semantics, and an explicit key
|
|
33
33
|
* always overrides the expansion it collides with.
|
|
34
34
|
*/
|
|
35
|
+
/**
|
|
36
|
+
* Chain key matched when no exact or base key resolves for the current model.
|
|
37
|
+
* Exists so a model without its own configured chain still has an escape lane:
|
|
38
|
+
* without it, a hard-failing upstream wedges the session terminal even though
|
|
39
|
+
* healthy fallback targets exist (desktop thread 487d7c29, 2026-08-28: nine
|
|
40
|
+
* consecutive upstream 500s, zero fallback attempts, terminal error).
|
|
41
|
+
* Users disable it with the `"*": []` tombstone.
|
|
42
|
+
*/
|
|
43
|
+
export declare const WILDCARD_CHAIN_KEY = "*";
|
|
44
|
+
/**
|
|
45
|
+
* Whether the user explicitly switched fallback OFF for this model with the
|
|
46
|
+
* documented `[]` tombstone (exact key, base key, or a bare family key that
|
|
47
|
+
* covers it). The shipped wildcard lane must never resurrect fallback against
|
|
48
|
+
* that instruction, so the wildcard gate consults this first.
|
|
49
|
+
*
|
|
50
|
+
* Bare-family matching is deliberately conservative: an ambiguous match
|
|
51
|
+
* suppresses the wildcard rather than overriding an explicit opt-out, because a
|
|
52
|
+
* surprising extra fallback hop is worse than a missing convenience lane.
|
|
53
|
+
*/
|
|
54
|
+
export declare function hasExplicitFallbackOptOut(chains: FallbackChains, currentModel: Model<Api>, currentThinking: ThinkingLevel | undefined): boolean;
|
|
35
55
|
export declare function canonicalizeFallbackChains(chains: FallbackChains, lookup: FallbackModelLookup): FallbackChains;
|
|
36
|
-
export declare function resolveChainKey(currentModel: Model<Api>, currentThinking: ThinkingLevel | undefined, chains: FallbackChains
|
|
56
|
+
export declare function resolveChainKey(currentModel: Model<Api>, currentThinking: ThinkingLevel | undefined, chains: FallbackChains, options?: {
|
|
57
|
+
allowWildcard?: boolean;
|
|
58
|
+
}): string | undefined;
|
|
37
59
|
/**
|
|
38
60
|
* Returns entries after the current fallback. A primary or unknown selector starts
|
|
39
61
|
* from the beginning, which also makes re-entry after stale runtime state safe.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chains.d.ts","sourceRoot":"","sources":["../../../src/core/retry-fallback/chains.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"chains.d.ts","sourceRoot":"","sources":["../../../src/core/retry-fallback/chains.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAWxD,MAAM,WAAW,gBAAgB;IAChC,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,EAAE,EAAE,MAAM,CAAC;IACX,aAAa,CAAC,EAAE,aAAa,CAAC;CAC9B;AAED,MAAM,MAAM,cAAc,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC,CAAC;AAEzE,MAAM,MAAM,mBAAmB,GAC5B,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,GACrB;IACA,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;IACvB,YAAY,CAAC,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC;IAC1C,iBAAiB,CAAC,CAAC,KAAK,EAAE,KA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,GAAG,MAAM,GACxC,SAAS,MAAM,EAAE,CAQnB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { isValidThinkingLevel } from "../../cli/args.js";
|
|
2
2
|
import { findExactModelReferenceMatch, parseModelPattern } from "../model-resolver.js";
|
|
3
|
-
import { MAX_PROVIDERS_PER_FAMILY, parseBareSelector, rankFamilyModels } from "./expansion.js";
|
|
3
|
+
import { MAX_PROVIDERS_PER_FAMILY, matchesFamily, parseBareSelector, rankFamilyModels, } from "./expansion.js";
|
|
4
4
|
function availableModels(lookup) {
|
|
5
5
|
return "getAll" in lookup ? lookup.getAll() : [...lookup];
|
|
6
6
|
}
|
|
@@ -91,6 +91,43 @@ export function baseSelector(selector) {
|
|
|
91
91
|
* Provider-qualified keys and entries keep exact semantics, and an explicit key
|
|
92
92
|
* always overrides the expansion it collides with.
|
|
93
93
|
*/
|
|
94
|
+
/**
|
|
95
|
+
* Chain key matched when no exact or base key resolves for the current model.
|
|
96
|
+
* Exists so a model without its own configured chain still has an escape lane:
|
|
97
|
+
* without it, a hard-failing upstream wedges the session terminal even though
|
|
98
|
+
* healthy fallback targets exist (desktop thread 487d7c29, 2026-08-28: nine
|
|
99
|
+
* consecutive upstream 500s, zero fallback attempts, terminal error).
|
|
100
|
+
* Users disable it with the `"*": []` tombstone.
|
|
101
|
+
*/
|
|
102
|
+
export const WILDCARD_CHAIN_KEY = "*";
|
|
103
|
+
/**
|
|
104
|
+
* Whether the user explicitly switched fallback OFF for this model with the
|
|
105
|
+
* documented `[]` tombstone (exact key, base key, or a bare family key that
|
|
106
|
+
* covers it). The shipped wildcard lane must never resurrect fallback against
|
|
107
|
+
* that instruction, so the wildcard gate consults this first.
|
|
108
|
+
*
|
|
109
|
+
* Bare-family matching is deliberately conservative: an ambiguous match
|
|
110
|
+
* suppresses the wildcard rather than overriding an explicit opt-out, because a
|
|
111
|
+
* surprising extra fallback hop is worse than a missing convenience lane.
|
|
112
|
+
*/
|
|
113
|
+
export function hasExplicitFallbackOptOut(chains, currentModel, currentThinking) {
|
|
114
|
+
const base = formatSelector(currentModel).toLowerCase();
|
|
115
|
+
const exact = currentThinking ? `${base}:${currentThinking}`.toLowerCase() : base;
|
|
116
|
+
for (const [key, entries] of Object.entries(chains)) {
|
|
117
|
+
if (!Array.isArray(entries) || !isChainTombstone(entries))
|
|
118
|
+
continue;
|
|
119
|
+
if (key === WILDCARD_CHAIN_KEY)
|
|
120
|
+
continue;
|
|
121
|
+
const normalizedKey = key.trim().toLowerCase();
|
|
122
|
+
const keyBase = normalizedBase(normalizedKey);
|
|
123
|
+
if (keyBase === base || normalizedKey === exact)
|
|
124
|
+
return true;
|
|
125
|
+
// Bare family key (no provider prefix): treat an id match as covering.
|
|
126
|
+
if (!normalizedKey.includes("/") && matchesFamily(currentModel, keyBase))
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
94
131
|
export function canonicalizeFallbackChains(chains, lookup) {
|
|
95
132
|
const models = availableModels(lookup);
|
|
96
133
|
const tiers = authTiers(lookup);
|
|
@@ -149,14 +186,33 @@ export function canonicalizeFallbackChains(chains, lookup) {
|
|
|
149
186
|
if (tombstones.has(normalizedBase(key)))
|
|
150
187
|
delete canonical[key];
|
|
151
188
|
}
|
|
189
|
+
// The wildcard key is not a model selector, so both loops above skip it.
|
|
190
|
+
// Its entries expand exactly like any other chain; a `[]` tombstone removes
|
|
191
|
+
// the lane entirely. Self-selection of the failing model is prevented at
|
|
192
|
+
// candidate time (nextCandidate's "self" skip), not here, because the
|
|
193
|
+
// wildcard has no key selector to filter against.
|
|
194
|
+
const wildcardEntries = chains[WILDCARD_CHAIN_KEY];
|
|
195
|
+
if (Array.isArray(wildcardEntries) && !isChainTombstone(wildcardEntries)) {
|
|
196
|
+
const canonicalEntries = expandEntries(wildcardEntries, WILDCARD_CHAIN_KEY);
|
|
197
|
+
if (canonicalEntries.length > 0)
|
|
198
|
+
canonical[WILDCARD_CHAIN_KEY] = canonicalEntries;
|
|
199
|
+
}
|
|
152
200
|
return canonical;
|
|
153
201
|
}
|
|
154
|
-
export function resolveChainKey(currentModel, currentThinking, chains) {
|
|
202
|
+
export function resolveChainKey(currentModel, currentThinking, chains, options) {
|
|
155
203
|
const base = formatSelector(currentModel);
|
|
156
204
|
const exact = currentThinking ? `${base}:${currentThinking}` : base;
|
|
157
205
|
if (Object.hasOwn(chains, exact))
|
|
158
206
|
return exact;
|
|
159
|
-
|
|
207
|
+
if (Object.hasOwn(chains, base))
|
|
208
|
+
return base;
|
|
209
|
+
// The wildcard is opt-in per call site: it is a last resort for a model with
|
|
210
|
+
// no chain of its own, and it must never hijack a session already walking a
|
|
211
|
+
// configured chain (the last rung of that chain usually has no key either).
|
|
212
|
+
// nextCandidate consults the active episode's chainKey before asking for it.
|
|
213
|
+
if (!options?.allowWildcard)
|
|
214
|
+
return undefined;
|
|
215
|
+
return Object.hasOwn(chains, WILDCARD_CHAIN_KEY) ? WILDCARD_CHAIN_KEY : undefined;
|
|
160
216
|
}
|
|
161
217
|
function formatParsedSelector(selector) {
|
|
162
218
|
const base = baseSelector(selector);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chains.js","sourceRoot":"","sources":["../../../src/core/retry-fallback/chains.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,4BAA4B,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACvF,OAAO,EAA0B,wBAAwB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAoBvH,SAAS,eAAe,CAAC,MAA2B;IACnD,OAAO,QAAQ,IAAI,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC;AAC3D,CAAC;AAED;;;GAGG;AACH,SAAS,SAAS,CAAC,MAA2B;IAC7C,IAAI,KAAK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AAK,CAAC,KAAK,IAAI,CAAC,CAAC;IACpF,OAAO,SAAS,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,KAAK,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC;AAC5E,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, Model } from \"@earendil-works/pi-ai\";\nimport { isValidThinkingLevel } from \"../../cli/args.ts\";\nimport { findExactModelReferenceMatch, parseModelPattern } from \"../model-resolver.ts\";\nimport { type FallbackAuthTiers, MAX_PROVIDERS_PER_FAMILY, parseBareSelector, rankFamilyModels } from \"./expansion.ts\";\n\nexport interface FallbackSelector {\n\traw: string;\n\tprovider: string;\n\tid: string;\n\tthinkingLevel?: ThinkingLevel;\n}\n\nexport type FallbackChains = Readonly<Record<string, readonly string[]>>;\n\nexport type FallbackModelLookup =\n\t| readonly Model<Api>[]\n\t| {\n\t\t\tgetAll(): Model<Api>[];\n\t\t\tisUsingOAuth?(model: Model<Api>): boolean;\n\t\t\thasConfiguredAuth?(model: Model<Api>): boolean;\n\t\t\tisFallbackEligible?(model: Model<Api>): boolean;\n\t };\n\nfunction availableModels(lookup: FallbackModelLookup): Model<Api>[] {\n\treturn \"getAll\" in lookup ? lookup.getAll() : [...lookup];\n}\n\n/**\n * Auth tier is optional so array lookups and older callers keep working; without\n * it every provider lands in the non-OAuth tier and the precedence table decides.\n */\nfunction authTiers(lookup: FallbackModelLookup): FallbackAuthTiers {\n\tif (Array.isArray(lookup)) return { isUsingOAuth: () => false };\n\tconst registry = lookup as {\n\t\tisUsingOAuth?(model: Model<Api>): boolean;\n\t\thasConfiguredAuth?(model: Model<Api>): boolean;\n\t\tisFallbackEligible?(model: Model<Api>): boolean;\n\t};\n\treturn {\n\t\tisUsingOAuth: (model) => registry.isUsingOAuth?.(model) === true,\n\t\thasConfiguredAuth:\n\t\t\ttypeof registry.hasConfiguredAuth === \"function\"\n\t\t\t\t? (model) => registry.hasConfiguredAuth?.(model) === true\n\t\t\t\t: undefined,\n\t\tisFallbackEligible:\n\t\t\ttypeof registry.isFallbackEligible === \"function\"\n\t\t\t\t? (model) => registry.isFallbackEligible?.(model) !== false\n\t\t\t\t: undefined,\n\t};\n}\n\n/** An empty entry list is the documented opt-out; it survives as a tombstone. */\nexport function isChainTombstone(entries: readonly string[] | undefined): boolean {\n\treturn Array.isArray(entries) && entries.length === 0;\n}\n\nfunction selectorReference(raw: string): { reference: string; thinkingLevel?: ThinkingLevel } | undefined {\n\tconst trimmed = raw.trim();\n\tif (!trimmed.includes(\"/\") || trimmed.includes(\"*\")) return undefined;\n\n\tconst lastColon = trimmed.lastIndexOf(\":\");\n\tif (lastColon === -1) return { reference: trimmed };\n\n\tconst prefix = trimmed.slice(0, lastColon);\n\tconst suffix = trimmed.slice(lastColon + 1).toLowerCase();\n\tif (!isValidThinkingLevel(suffix)) return { reference: trimmed };\n\treturn { reference: prefix, thinkingLevel: suffix };\n}\n\n/**\n * Resolves only complete provider/model selectors. The full input is resolved first\n * so colons belonging to a model id remain part of that id; aliases then resolve\n * against the model-id portion while retaining the explicitly selected provider.\n */\nexport function parseFallbackSelector(raw: string, lookup: FallbackModelLookup): FallbackSelector | undefined {\n\tconst models = availableModels(lookup);\n\tconst trimmed = raw.trim();\n\tconst parsedReference = selectorReference(trimmed);\n\tif (!parsedReference) return undefined;\n\n\tconst fullMatch = findExactModelReferenceMatch(trimmed, models);\n\tif (fullMatch) {\n\t\treturn { raw: trimmed, provider: fullMatch.provider, id: fullMatch.id };\n\t}\n\n\tconst slashIndex = parsedReference.reference.indexOf(\"/\");\n\tconst provider = parsedReference.reference.slice(0, slashIndex).trim();\n\tconst modelPattern = parsedReference.reference.slice(slashIndex + 1).trim();\n\tif (!provider || !modelPattern) return undefined;\n\n\t// The provider is explicit, so resolve the id pattern inside that provider only.\n\t// A global lookup lets foreign ids containing the pattern (e.g. Bedrock's\n\t// \"us.anthropic.claude-opus-5\") win over the requested provider's exact id.\n\tconst providerModels = models.filter((model) => model.provider.toLowerCase() === provider.toLowerCase());\n\tconst parsed = parseModelPattern(\n\t\tparsedReference.thinkingLevel ? `${modelPattern}:${parsedReference.thinkingLevel}` : modelPattern,\n\t\tproviderModels,\n\t\t{ allowInvalidThinkingLevelFallback: false },\n\t);\n\tif (!parsed.model || parsed.warning) return undefined;\n\tif (parsedReference.thinkingLevel && !parsed.thinkingLevel) return undefined;\n\n\treturn {\n\t\traw: trimmed,\n\t\tprovider: parsed.model.provider,\n\t\tid: parsed.model.id,\n\t\tthinkingLevel: parsed.thinkingLevel,\n\t};\n}\n\nexport function formatSelector(model: Model<Api>, thinkingLevel?: ThinkingLevel): string {\n\tconst base = `${model.provider}/${model.id}`;\n\treturn thinkingLevel ? `${base}:${thinkingLevel}` : base;\n}\n\nexport function baseSelector(selector: Pick<FallbackSelector, \"provider\" | \"id\">): string {\n\treturn `${selector.provider}/${selector.id}`;\n}\n\n/**\n * Converts validated configuration to canonical selector strings for runtime lookup.\n *\n * A bare key (no provider prefix) is a model-family policy: it expands to one\n * canonical key per provider serving that family, so a chain shipped for\n * `claude-fable-5` applies no matter which provider the user attached it through.\n * Provider-qualified keys and entries keep exact semantics, and an explicit key\n * always overrides the expansion it collides with.\n */\nexport function canonicalizeFallbackChains(chains: FallbackChains, lookup: FallbackModelLookup): FallbackChains {\n\tconst models = availableModels(lookup);\n\tconst tiers = authTiers(lookup);\n\tconst canonical: Record<string, readonly string[]> = {};\n\tconst explicitKeys = new Set<string>();\n\tconst tombstones = new Set<string>();\n\n\tconst expandEntries = (entries: readonly string[], keySelector: string): string[] =>\n\t\tentries.flatMap((entry) => {\n\t\t\tconst bare = parseBareSelector(entry);\n\t\t\tif (bare) {\n\t\t\t\treturn rankFamilyModels(models, bare.family, tiers, { limit: MAX_PROVIDERS_PER_FAMILY })\n\t\t\t\t\t.map((model) =>\n\t\t\t\t\t\tbare.thinkingLevel ? `${formatSelector(model)}:${bare.thinkingLevel}` : formatSelector(model),\n\t\t\t\t\t)\n\t\t\t\t\t.filter((selector) => normalizedBase(selector) !== normalizedBase(keySelector));\n\t\t\t}\n\t\t\tconst parsedEntry = parseFallbackSelector(entry, models);\n\t\t\treturn parsedEntry ? [formatParsedSelector(parsedEntry)] : [];\n\t\t});\n\n\t// Bare keys expand first so a same-named explicit key can overwrite them.\n\tfor (const [key, entries] of Object.entries(chains)) {\n\t\tconst bareKey = parseBareSelector(key);\n\t\tif (!bareKey || !Array.isArray(entries)) continue;\n\t\tif (isChainTombstone(entries)) {\n\t\t\tfor (const model of rankFamilyModels(models, bareKey.family, tiers)) {\n\t\t\t\ttombstones.add(formatSelector(model).toLowerCase());\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const model of rankFamilyModels(models, bareKey.family, tiers)) {\n\t\t\tconst keySelector = bareKey.thinkingLevel\n\t\t\t\t? `${formatSelector(model)}:${bareKey.thinkingLevel}`\n\t\t\t\t: formatSelector(model);\n\t\t\tconst canonicalEntries = expandEntries(entries, keySelector);\n\t\t\tif (canonicalEntries.length > 0) canonical[keySelector] = canonicalEntries;\n\t\t}\n\t}\n\n\tfor (const [key, entries] of Object.entries(chains)) {\n\t\tif (parseBareSelector(key)) continue;\n\t\tconst parsedKey = parseFallbackSelector(key, models);\n\t\tif (!parsedKey || !Array.isArray(entries)) continue;\n\t\tconst keySelector = formatParsedSelector(parsedKey);\n\t\tif (isChainTombstone(entries)) {\n\t\t\ttombstones.add(normalizedBase(keySelector));\n\t\t\tcontinue;\n\t\t}\n\t\texplicitKeys.add(keySelector.toLowerCase());\n\t\tconst canonicalEntries = expandEntries(entries, keySelector);\n\t\tif (canonicalEntries.length > 0) canonical[keySelector] = canonicalEntries;\n\t}\n\n\tfor (const key of Object.keys(canonical)) {\n\t\tif (explicitKeys.has(key.toLowerCase())) continue;\n\t\tif (tombstones.has(normalizedBase(key))) delete canonical[key];\n\t}\n\n\treturn canonical;\n}\n\nexport function resolveChainKey(\n\tcurrentModel: Model<Api>,\n\tcurrentThinking: ThinkingLevel | undefined,\n\tchains: FallbackChains,\n): string | undefined {\n\tconst base = formatSelector(currentModel);\n\tconst exact = currentThinking ? `${base}:${currentThinking}` : base;\n\tif (Object.hasOwn(chains, exact)) return exact;\n\treturn Object.hasOwn(chains, base) ? base : undefined;\n}\n\nfunction formatParsedSelector(selector: FallbackSelector): string {\n\tconst base = baseSelector(selector);\n\treturn selector.thinkingLevel ? `${base}:${selector.thinkingLevel}` : base;\n}\n\nfunction normalizedBase(selector: FallbackSelector | string): string {\n\tif (typeof selector !== \"string\") return baseSelector(selector).toLowerCase();\n\n\tconst normalized = selector.trim().toLowerCase();\n\tconst lastColon = normalized.lastIndexOf(\":\");\n\tif (lastColon === -1 || !isValidThinkingLevel(normalized.slice(lastColon + 1))) return normalized;\n\treturn normalized.slice(0, lastColon);\n}\n\nfunction normalizedExact(selector: FallbackSelector | string): string {\n\treturn typeof selector === \"string\" ? selector.trim().toLowerCase() : formatParsedSelector(selector).toLowerCase();\n}\n\n/**\n * Returns entries after the current fallback. A primary or unknown selector starts\n * from the beginning, which also makes re-entry after stale runtime state safe.\n */\nexport function candidatesAfter(\n\tchainEntries: readonly string[],\n\tcurrentSelector: FallbackSelector | string,\n): readonly string[] {\n\tconst exact = normalizedExact(currentSelector);\n\tconst exactIndex = chainEntries.findIndex((entry) => entry.toLowerCase() === exact);\n\tif (exactIndex !== -1) return chainEntries.slice(exactIndex + 1);\n\n\tconst base = normalizedBase(currentSelector);\n\tconst baseIndex = chainEntries.findIndex((entry) => normalizedBase(entry) === base);\n\treturn baseIndex === -1 ? chainEntries : chainEntries.slice(baseIndex + 1);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"chains.js","sourceRoot":"","sources":["../../../src/core/retry-fallback/chains.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,4BAA4B,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC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AACvC,CAAC;AAED,SAAS,eAAe,CAAC,QAAmC;IAC3D,OAAO,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,oBAAoB,CAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,CAAC;AACpH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,eAAe,CAC9B,YAA+B,EAC/B,eAA0C;IAE1C,MAAM,KAAK,GAAG,eAAe,CAAC,eAAe,CAAC,CAAC;IAC/C,MAAM,UAAU,GAAG,YAAY,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,EAAE,KAAK,KAAK,CAAC,CAAC;IACpF,IAAI,UAAU,KAAK,CAAC,CAAC;QAAE,OAAO,YAAY,CAAC,KAAK,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC;IAEjE,MAAM,IAAI,GAAG,cAAc,CAAC,eAAe,CAAC,CAAC;IAC7C,MAAM,SAAS,GAAG,YAAY,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,cAAc,CAAC,KAAK,CAAC,KAAK,IAAI,CAAC,CAAC;IACpF,OAAO,SAAS,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,KAAK,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC;AAC5E,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, Model } from \"@earendil-works/pi-ai\";\nimport { isValidThinkingLevel } from \"../../cli/args.ts\";\nimport { findExactModelReferenceMatch, parseModelPattern } from \"../model-resolver.ts\";\nimport {\n\ttype FallbackAuthTiers,\n\tMAX_PROVIDERS_PER_FAMILY,\n\tmatchesFamily,\n\tparseBareSelector,\n\trankFamilyModels,\n} from \"./expansion.ts\";\n\nexport interface FallbackSelector {\n\traw: string;\n\tprovider: string;\n\tid: string;\n\tthinkingLevel?: ThinkingLevel;\n}\n\nexport type FallbackChains = Readonly<Record<string, readonly string[]>>;\n\nexport type FallbackModelLookup =\n\t| readonly Model<Api>[]\n\t| {\n\t\t\tgetAll(): Model<Api>[];\n\t\t\tisUsingOAuth?(model: Model<Api>): boolean;\n\t\t\thasConfiguredAuth?(model: Model<Api>): boolean;\n\t\t\tisFallbackEligible?(model: Model<Api>): boolean;\n\t };\n\nfunction availableModels(lookup: FallbackModelLookup): Model<Api>[] {\n\treturn \"getAll\" in lookup ? lookup.getAll() : [...lookup];\n}\n\n/**\n * Auth tier is optional so array lookups and older callers keep working; without\n * it every provider lands in the non-OAuth tier and the precedence table decides.\n */\nfunction authTiers(lookup: FallbackModelLookup): FallbackAuthTiers {\n\tif (Array.isArray(lookup)) return { isUsingOAuth: () => false };\n\tconst registry = lookup as {\n\t\tisUsingOAuth?(model: Model<Api>): boolean;\n\t\thasConfiguredAuth?(model: Model<Api>): boolean;\n\t\tisFallbackEligible?(model: Model<Api>): boolean;\n\t};\n\treturn {\n\t\tisUsingOAuth: (model) => registry.isUsingOAuth?.(model) === true,\n\t\thasConfiguredAuth:\n\t\t\ttypeof registry.hasConfiguredAuth === \"function\"\n\t\t\t\t? (model) => registry.hasConfiguredAuth?.(model) === true\n\t\t\t\t: undefined,\n\t\tisFallbackEligible:\n\t\t\ttypeof registry.isFallbackEligible === \"function\"\n\t\t\t\t? (model) => registry.isFallbackEligible?.(model) !== false\n\t\t\t\t: undefined,\n\t};\n}\n\n/** An empty entry list is the documented opt-out; it survives as a tombstone. */\nexport function isChainTombstone(entries: readonly string[] | undefined): boolean {\n\treturn Array.isArray(entries) && entries.length === 0;\n}\n\nfunction selectorReference(raw: string): { reference: string; thinkingLevel?: ThinkingLevel } | undefined {\n\tconst trimmed = raw.trim();\n\tif (!trimmed.includes(\"/\") || trimmed.includes(\"*\")) return undefined;\n\n\tconst lastColon = trimmed.lastIndexOf(\":\");\n\tif (lastColon === -1) return { reference: trimmed };\n\n\tconst prefix = trimmed.slice(0, lastColon);\n\tconst suffix = trimmed.slice(lastColon + 1).toLowerCase();\n\tif (!isValidThinkingLevel(suffix)) return { reference: trimmed };\n\treturn { reference: prefix, thinkingLevel: suffix };\n}\n\n/**\n * Resolves only complete provider/model selectors. The full input is resolved first\n * so colons belonging to a model id remain part of that id; aliases then resolve\n * against the model-id portion while retaining the explicitly selected provider.\n */\nexport function parseFallbackSelector(raw: string, lookup: FallbackModelLookup): FallbackSelector | undefined {\n\tconst models = availableModels(lookup);\n\tconst trimmed = raw.trim();\n\tconst parsedReference = selectorReference(trimmed);\n\tif (!parsedReference) return undefined;\n\n\tconst fullMatch = findExactModelReferenceMatch(trimmed, models);\n\tif (fullMatch) {\n\t\treturn { raw: trimmed, provider: fullMatch.provider, id: fullMatch.id };\n\t}\n\n\tconst slashIndex = parsedReference.reference.indexOf(\"/\");\n\tconst provider = parsedReference.reference.slice(0, slashIndex).trim();\n\tconst modelPattern = parsedReference.reference.slice(slashIndex + 1).trim();\n\tif (!provider || !modelPattern) return undefined;\n\n\t// The provider is explicit, so resolve the id pattern inside that provider only.\n\t// A global lookup lets foreign ids containing the pattern (e.g. Bedrock's\n\t// \"us.anthropic.claude-opus-5\") win over the requested provider's exact id.\n\tconst providerModels = models.filter((model) => model.provider.toLowerCase() === provider.toLowerCase());\n\tconst parsed = parseModelPattern(\n\t\tparsedReference.thinkingLevel ? `${modelPattern}:${parsedReference.thinkingLevel}` : modelPattern,\n\t\tproviderModels,\n\t\t{ allowInvalidThinkingLevelFallback: false },\n\t);\n\tif (!parsed.model || parsed.warning) return undefined;\n\tif (parsedReference.thinkingLevel && !parsed.thinkingLevel) return undefined;\n\n\treturn {\n\t\traw: trimmed,\n\t\tprovider: parsed.model.provider,\n\t\tid: parsed.model.id,\n\t\tthinkingLevel: parsed.thinkingLevel,\n\t};\n}\n\nexport function formatSelector(model: Model<Api>, thinkingLevel?: ThinkingLevel): string {\n\tconst base = `${model.provider}/${model.id}`;\n\treturn thinkingLevel ? `${base}:${thinkingLevel}` : base;\n}\n\nexport function baseSelector(selector: Pick<FallbackSelector, \"provider\" | \"id\">): string {\n\treturn `${selector.provider}/${selector.id}`;\n}\n\n/**\n * Converts validated configuration to canonical selector strings for runtime lookup.\n *\n * A bare key (no provider prefix) is a model-family policy: it expands to one\n * canonical key per provider serving that family, so a chain shipped for\n * `claude-fable-5` applies no matter which provider the user attached it through.\n * Provider-qualified keys and entries keep exact semantics, and an explicit key\n * always overrides the expansion it collides with.\n */\n/**\n * Chain key matched when no exact or base key resolves for the current model.\n * Exists so a model without its own configured chain still has an escape lane:\n * without it, a hard-failing upstream wedges the session terminal even though\n * healthy fallback targets exist (desktop thread 487d7c29, 2026-08-28: nine\n * consecutive upstream 500s, zero fallback attempts, terminal error).\n * Users disable it with the `\"*\": []` tombstone.\n */\nexport const WILDCARD_CHAIN_KEY = \"*\";\n\n/**\n * Whether the user explicitly switched fallback OFF for this model with the\n * documented `[]` tombstone (exact key, base key, or a bare family key that\n * covers it). The shipped wildcard lane must never resurrect fallback against\n * that instruction, so the wildcard gate consults this first.\n *\n * Bare-family matching is deliberately conservative: an ambiguous match\n * suppresses the wildcard rather than overriding an explicit opt-out, because a\n * surprising extra fallback hop is worse than a missing convenience lane.\n */\nexport function hasExplicitFallbackOptOut(\n\tchains: FallbackChains,\n\tcurrentModel: Model<Api>,\n\tcurrentThinking: ThinkingLevel | undefined,\n): boolean {\n\tconst base = formatSelector(currentModel).toLowerCase();\n\tconst exact = currentThinking ? `${base}:${currentThinking}`.toLowerCase() : base;\n\tfor (const [key, entries] of Object.entries(chains)) {\n\t\tif (!Array.isArray(entries) || !isChainTombstone(entries)) continue;\n\t\tif (key === WILDCARD_CHAIN_KEY) continue;\n\t\tconst normalizedKey = key.trim().toLowerCase();\n\t\tconst keyBase = normalizedBase(normalizedKey);\n\t\tif (keyBase === base || normalizedKey === exact) return true;\n\t\t// Bare family key (no provider prefix): treat an id match as covering.\n\t\tif (!normalizedKey.includes(\"/\") && matchesFamily(currentModel, keyBase)) return true;\n\t}\n\treturn false;\n}\n\nexport function canonicalizeFallbackChains(chains: FallbackChains, lookup: FallbackModelLookup): FallbackChains {\n\tconst models = availableModels(lookup);\n\tconst tiers = authTiers(lookup);\n\tconst canonical: Record<string, readonly string[]> = {};\n\tconst explicitKeys = new Set<string>();\n\tconst tombstones = new Set<string>();\n\n\tconst expandEntries = (entries: readonly string[], keySelector: string): string[] =>\n\t\tentries.flatMap((entry) => {\n\t\t\tconst bare = parseBareSelector(entry);\n\t\t\tif (bare) {\n\t\t\t\treturn rankFamilyModels(models, bare.family, tiers, { limit: MAX_PROVIDERS_PER_FAMILY })\n\t\t\t\t\t.map((model) =>\n\t\t\t\t\t\tbare.thinkingLevel ? `${formatSelector(model)}:${bare.thinkingLevel}` : formatSelector(model),\n\t\t\t\t\t)\n\t\t\t\t\t.filter((selector) => normalizedBase(selector) !== normalizedBase(keySelector));\n\t\t\t}\n\t\t\tconst parsedEntry = parseFallbackSelector(entry, models);\n\t\t\treturn parsedEntry ? [formatParsedSelector(parsedEntry)] : [];\n\t\t});\n\n\t// Bare keys expand first so a same-named explicit key can overwrite them.\n\tfor (const [key, entries] of Object.entries(chains)) {\n\t\tconst bareKey = parseBareSelector(key);\n\t\tif (!bareKey || !Array.isArray(entries)) continue;\n\t\tif (isChainTombstone(entries)) {\n\t\t\tfor (const model of rankFamilyModels(models, bareKey.family, tiers)) {\n\t\t\t\ttombstones.add(formatSelector(model).toLowerCase());\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const model of rankFamilyModels(models, bareKey.family, tiers)) {\n\t\t\tconst keySelector = bareKey.thinkingLevel\n\t\t\t\t? `${formatSelector(model)}:${bareKey.thinkingLevel}`\n\t\t\t\t: formatSelector(model);\n\t\t\tconst canonicalEntries = expandEntries(entries, keySelector);\n\t\t\tif (canonicalEntries.length > 0) canonical[keySelector] = canonicalEntries;\n\t\t}\n\t}\n\n\tfor (const [key, entries] of Object.entries(chains)) {\n\t\tif (parseBareSelector(key)) continue;\n\t\tconst parsedKey = parseFallbackSelector(key, models);\n\t\tif (!parsedKey || !Array.isArray(entries)) continue;\n\t\tconst keySelector = formatParsedSelector(parsedKey);\n\t\tif (isChainTombstone(entries)) {\n\t\t\ttombstones.add(normalizedBase(keySelector));\n\t\t\tcontinue;\n\t\t}\n\t\texplicitKeys.add(keySelector.toLowerCase());\n\t\tconst canonicalEntries = expandEntries(entries, keySelector);\n\t\tif (canonicalEntries.length > 0) canonical[keySelector] = canonicalEntries;\n\t}\n\n\tfor (const key of Object.keys(canonical)) {\n\t\tif (explicitKeys.has(key.toLowerCase())) continue;\n\t\tif (tombstones.has(normalizedBase(key))) delete canonical[key];\n\t}\n\n\t// The wildcard key is not a model selector, so both loops above skip it.\n\t// Its entries expand exactly like any other chain; a `[]` tombstone removes\n\t// the lane entirely. Self-selection of the failing model is prevented at\n\t// candidate time (nextCandidate's \"self\" skip), not here, because the\n\t// wildcard has no key selector to filter against.\n\tconst wildcardEntries = chains[WILDCARD_CHAIN_KEY];\n\tif (Array.isArray(wildcardEntries) && !isChainTombstone(wildcardEntries)) {\n\t\tconst canonicalEntries = expandEntries(wildcardEntries, WILDCARD_CHAIN_KEY);\n\t\tif (canonicalEntries.length > 0) canonical[WILDCARD_CHAIN_KEY] = canonicalEntries;\n\t}\n\n\treturn canonical;\n}\n\nexport function resolveChainKey(\n\tcurrentModel: Model<Api>,\n\tcurrentThinking: ThinkingLevel | undefined,\n\tchains: FallbackChains,\n\toptions?: { allowWildcard?: boolean },\n): string | undefined {\n\tconst base = formatSelector(currentModel);\n\tconst exact = currentThinking ? `${base}:${currentThinking}` : base;\n\tif (Object.hasOwn(chains, exact)) return exact;\n\tif (Object.hasOwn(chains, base)) return base;\n\t// The wildcard is opt-in per call site: it is a last resort for a model with\n\t// no chain of its own, and it must never hijack a session already walking a\n\t// configured chain (the last rung of that chain usually has no key either).\n\t// nextCandidate consults the active episode's chainKey before asking for it.\n\tif (!options?.allowWildcard) return undefined;\n\treturn Object.hasOwn(chains, WILDCARD_CHAIN_KEY) ? WILDCARD_CHAIN_KEY : undefined;\n}\n\nfunction formatParsedSelector(selector: FallbackSelector): string {\n\tconst base = baseSelector(selector);\n\treturn selector.thinkingLevel ? `${base}:${selector.thinkingLevel}` : base;\n}\n\nfunction normalizedBase(selector: FallbackSelector | string): string {\n\tif (typeof selector !== \"string\") return baseSelector(selector).toLowerCase();\n\n\tconst normalized = selector.trim().toLowerCase();\n\tconst lastColon = normalized.lastIndexOf(\":\");\n\tif (lastColon === -1 || !isValidThinkingLevel(normalized.slice(lastColon + 1))) return normalized;\n\treturn normalized.slice(0, lastColon);\n}\n\nfunction normalizedExact(selector: FallbackSelector | string): string {\n\treturn typeof selector === \"string\" ? selector.trim().toLowerCase() : formatParsedSelector(selector).toLowerCase();\n}\n\n/**\n * Returns entries after the current fallback. A primary or unknown selector starts\n * from the beginning, which also makes re-entry after stale runtime state safe.\n */\nexport function candidatesAfter(\n\tchainEntries: readonly string[],\n\tcurrentSelector: FallbackSelector | string,\n): readonly string[] {\n\tconst exact = normalizedExact(currentSelector);\n\tconst exactIndex = chainEntries.findIndex((entry) => entry.toLowerCase() === exact);\n\tif (exactIndex !== -1) return chainEntries.slice(exactIndex + 1);\n\n\tconst base = normalizedBase(currentSelector);\n\tconst baseIndex = chainEntries.findIndex((entry) => normalizedBase(entry) === base);\n\treturn baseIndex === -1 ? chainEntries : chainEntries.slice(baseIndex + 1);\n}\n"]}
|