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B,CAgBpB;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,IAAI,SAAS,GAAG,EAC9C,CAAC,EAAE,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,SAAS,EACjC,CAAC,EAAE,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,SAAS,GAC/B,OAAO,CAGT","sourcesContent":["import { lazyStream } from \"./api/lazy.ts\";\nimport { defaultProviderAuthContext as defaultAuthContext } from \"./auth/context.ts\";\nimport { InMemoryCredentialStore } from \"./auth/credential-store.ts\";\nimport { type AuthResolutionOverrides, ModelsError, resolveProviderAuth } from \"./auth/resolve.ts\";\nimport type {\n\tAuthCheck,\n\tAuthContext,\n\tAuthInteraction,\n\tAuthResult,\n\tAuthType,\n\tCredential,\n\tCredentialStore,\n\tProviderAuth,\n} from \"./auth/types.ts\";\nimport { InMemoryModelsStore, type ModelsStore, type ProviderModelsStore } from \"./models-store.ts\";\nimport type {\n\tApi,\n\tApiStreamOptions,\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tContext,\n\tModel,\n\tModelCostRates,\n\tModelThinkingLevel,\n\tProviderHeaders,\n\tProviderStreams,\n\tSimpleStreamOptions,\n\tStreamOptions,\n\tUsage,\n} from \"./types.ts\";\n\nexport { ModelsError, type ModelsErrorCode } from \"./auth/resolve.ts\";\n\nexport interface RefreshModelsContext {\n\t/** Effective configured credential. OAuth credentials are refreshed before network access. */\n\tcredential?: Credential;\n\t/** Persistent model storage scoped to this provider ID. */\n\tstore: ProviderModelsStore;\n\t/** False during offline/cache-only initialization. */\n\tallowNetwork: boolean;\n\t/** Bypass provider freshness checks and fetch immediately when network access is allowed. */\n\tforce?: boolean;\n\tsignal?: AbortSignal;\n}\n\nexport interface ModelsRefreshOptions {\n\tallowNetwork?: boolean;\n\t/** Bypass provider freshness checks and fetch immediately when network access is allowed. */\n\tforce?: boolean;\n\tsignal?: AbortSignal;\n}\n\nexport interface ModelsRefreshResult {\n\taborted: boolean;\n\terrors: ReadonlyMap<string, Error>;\n}\n\nexport interface ModelsStreamTransforms {\n\t/** Transform fully assembled model/auth/request headers before provider dispatch. */\n\ttransformHeaders?: (headers: ProviderHeaders) => ProviderHeaders | Promise<ProviderHeaders>;\n}\n\nexport type ModelsApiStreamOptions<TApi extends Api> = ApiStreamOptions<TApi> & ModelsStreamTransforms;\nexport type ModelsSimpleStreamOptions = SimpleStreamOptions & ModelsStreamTransforms;\n\n/**\n * A provider is the concrete runtime unit. It owns id/name/base metadata,\n * auth methods, model listing, and stream behavior.\n *\n * `TApi` lets concrete provider factories declare which APIs their models\n * use (e.g. `openaiProvider(): Provider<\"openai-responses\" | \"openai-completions\">`),\n * giving typed model lists to direct factory users. Inside a `Models`\n * collection providers are held as `Provider<Api>`.\n */\nexport interface Provider<TApi extends Api = Api> {\n\treadonly id: string;\n\treadonly name: string;\n\n\treadonly baseUrl?: string;\n\treadonly headers?: ProviderHeaders;\n\n\t/**\n\t * Required: at least one of `apiKey`/`oauth`. Every provider has auth\n\t * semantics — even providers with only ambient credentials (env vars, AWS\n\t * profiles, ADC files) and keyless local servers provide `apiKey` auth\n\t * whose `resolve()` reports whether the provider is configured.\n\t * `Models.getAuth()` returns undefined when the provider is unconfigured.\n\t */\n\treadonly auth: ProviderAuth;\n\n\t/**\n\t * Current known models, sync. Static providers return their catalog;\n\t * dynamic providers return the list as of the last `refreshModels()`\n\t * (empty before the first). Must not throw; `Models` treats a throwing\n\t * implementation as having no models.\n\t */\n\tgetModels(): readonly Model<TApi>[];\n\n\t/**\n\t * Dynamic providers only: restore the provider-scoped stored catalog and optionally fetch\n\t * a newer list using the effective credential. Implementations must retain their previous\n\t * list on failure and honor the shared abort signal for network requests.\n\t */\n\trefreshModels?(context: RefreshModelsContext): Promise<void>;\n\n\t/**\n\t * Optional provider policy for credential-specific model availability.\n\t * `getModels()` remains the complete synchronous catalog; `Models.getAvailable()`\n\t * applies this filter after confirming that provider auth is configured.\n\t */\n\tfilterModels?(models: readonly Model<TApi>[], credential: Credential | undefined): readonly Model<TApi>[];\n\n\tstream<T extends TApi>(\n\t\tmodel: Model<T>,\n\t\tcontext: Context,\n\t\toptions?: ApiStreamOptions<T>,\n\t): AssistantMessageEventStream;\n\n\tstreamSimple(model: Model<TApi>, context: Context, options?: SimpleStreamOptions): AssistantMessageEventStream;\n}\n\n/**\n * Runtime collection of providers plus auth application and stream\n * convenience. Providers own stream behavior; `Models` resolves auth and\n * delegates each request to the provider that owns the model.\n */\nexport interface Models {\n\tgetProviders(): readonly Provider[];\n\tgetProvider(id: string): Provider | undefined;\n\n\t/**\n\t * Sync read of last-known models from one provider or all providers.\n\t * Best-effort: a provider whose `getModels()` throws yields no models.\n\t */\n\tgetModels(provider?: string): readonly Model<Api>[];\n\n\t/**\n\t * Sync runtime model lookup against last-known lists. Dynamic model lists\n\t * are typed as `Model<Api>`; narrow with the `hasApi()` type guard.\n\t */\n\tgetModel(provider: string, id: string): Model<Api> | undefined;\n\n\t/**\n\t * Refresh every configured dynamic provider concurrently. Provider errors and cancellation\n\t * are returned without rejecting; static and unconfigured providers are skipped.\n\t */\n\trefresh(options?: ModelsRefreshOptions): Promise<ModelsRefreshResult>;\n\n\t/** Check whether a provider has complete auth configuration without refreshing OAuth. */\n\tcheckAuth(providerId: string): Promise<AuthCheck | undefined>;\n\n\t/** Return models whose providers have complete auth configuration. */\n\tgetAvailable(providerId?: string): Promise<readonly Model<Api>[]>;\n\n\t/**\n\t * Resolve provider-scoped auth by provider id, or provider auth plus static\n\t * model headers when passed a model. Includes a source label for status UI.\n\t * Resolves `undefined` when the provider is unknown or unconfigured.\n\t * Rejects with `ModelsError`: code \"oauth\" when a token refresh fails (the\n\t * stored credential is preserved for retry; re-login fixes it), code \"auth\"\n\t * when api-key resolution or the credential store fails. Request paths\n\t * surface rejections as stream errors.\n\t */\n\tgetAuth(providerId: string, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: Model<Api>, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;\n\n\t/** Run a provider-owned login flow and persist its returned credential. */\n\tlogin(providerId: string, type: AuthType, interaction: AuthInteraction): Promise<Credential>;\n\n\t/** Remove the stored credential for a provider. */\n\tlogout(providerId: string): Promise<void>;\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream;\n\n\tcomplete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage>;\n\n\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream;\n\tcompleteSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage>;\n}\n\nexport interface MutableModels extends Models {\n\t/** Upsert/replace by provider.id. Provider ids are unique. */\n\tsetProvider(provider: Provider): void;\n\tdeleteProvider(id: string): void;\n\tclearProviders(): void;\n}\n\nexport interface CreateModelsOptions {\n\tcredentials?: CredentialStore;\n\tmodelsStore?: ModelsStore;\n\tauthContext?: AuthContext;\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\nclass ModelsImpl implements MutableModels {\n\tprivate providers = new Map<string, Provider>();\n\tprivate credentials: CredentialStore;\n\tprivate modelsStore: ModelsStore;\n\tprivate authContext: AuthContext;\n\n\tconstructor(options?: CreateModelsOptions) {\n\t\tthis.credentials = options?.credentials ?? new InMemoryCredentialStore();\n\t\tthis.modelsStore = options?.modelsStore ?? new InMemoryModelsStore();\n\t\tthis.authContext = options?.authContext ?? defaultAuthContext();\n\t}\n\n\tsetProvider(provider: Provider): void {\n\t\tthis.providers.set(provider.id, provider);\n\t}\n\n\tdeleteProvider(id: string): void {\n\t\tthis.providers.delete(id);\n\t}\n\n\tclearProviders(): void {\n\t\tthis.providers.clear();\n\t}\n\n\tgetProviders(): readonly Provider[] {\n\t\treturn Array.from(this.providers.values());\n\t}\n\n\tgetProvider(id: string): Provider | undefined {\n\t\treturn this.providers.get(id);\n\t}\n\n\tgetModels(provider?: string): readonly Model<Api>[] {\n\t\tif (provider !== undefined) {\n\t\t\tconst entry = this.providers.get(provider);\n\t\t\tif (!entry) return [];\n\t\t\ttry {\n\t\t\t\treturn entry.getModels();\n\t\t\t} catch {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t}\n\n\t\tconst models: Model<Api>[] = [];\n\t\tfor (const entry of this.providers.values()) {\n\t\t\ttry {\n\t\t\t\tmodels.push(...entry.getModels());\n\t\t\t} catch {\n\t\t\t\t// Best-effort: ill-behaved providers yield no models.\n\t\t\t}\n\t\t}\n\t\treturn models;\n\t}\n\n\tgetModel(provider: string, id: string): Model<Api> | undefined {\n\t\treturn this.getModels(provider).find((model) => model.id === id);\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<ModelsRefreshResult> {\n\t\tconst allowNetwork = options.allowNetwork ?? true;\n\t\tconst errors = new Map<string, Error>();\n\t\tconst refreshable = Array.from(this.providers.values()).filter(\n\t\t\t(provider): provider is Provider & Required<Pick<Provider, \"refreshModels\">> =>\n\t\t\t\tprovider.refreshModels !== undefined,\n\t\t);\n\n\t\tawait Promise.all(\n\t\t\trefreshable.map(async (provider) => {\n\t\t\t\tif (options.signal?.aborted) return;\n\t\t\t\tconst store: ProviderModelsStore = {\n\t\t\t\t\tread: () => this.modelsStore.read(provider.id),\n\t\t\t\t\twrite: (entry) => this.modelsStore.write(provider.id, entry),\n\t\t\t\t\tdelete: () => this.modelsStore.delete(provider.id),\n\t\t\t\t};\n\t\t\t\tlet stored: Credential | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tstored = await this.readCredential(provider.id);\n\t\t\t\t\tconst credential = await this.resolveRefreshCredential(provider, stored, allowNetwork, options.signal);\n\t\t\t\t\tif (!credential) return;\n\t\t\t\t\tawait provider.refreshModels({\n\t\t\t\t\t\tcredential,\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\tallowNetwork,\n\t\t\t\t\t\tforce: options.force,\n\t\t\t\t\t\tsignal: options.signal,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!options.signal?.aborted) {\n\t\t\t\t\t\terrors.set(\n\t\t\t\t\t\t\tprovider.id,\n\t\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t\t? error\n\t\t\t\t\t\t\t\t: new ModelsError(\"model_source\", `Model refresh failed for ${provider.id}`, { cause: error }),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait provider.refreshModels({\n\t\t\t\t\t\t\tcredential: stored,\n\t\t\t\t\t\t\tstore,\n\t\t\t\t\t\t\tallowNetwork: false,\n\t\t\t\t\t\t\tsignal: options.signal,\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Preserve the original auth/network error; cache restoration is best-effort here.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\n\t\treturn { aborted: options.signal?.aborted ?? false, errors };\n\t}\n\n\tprivate async resolveRefreshCredential(\n\t\tprovider: Provider,\n\t\tstored: Credential | undefined,\n\t\tallowNetwork: boolean,\n\t\tsignal?: AbortSignal,\n\t): Promise<Credential | undefined> {\n\t\tif (stored?.type === \"oauth\") {\n\t\t\tconst oauth = provider.auth.oauth;\n\t\t\tif (!oauth) return undefined;\n\t\t\tif (!allowNetwork || Date.now() < stored.expires) return stored;\n\t\t\tif (signal?.aborted) return undefined;\n\t\t\tconst post = await this.credentials.modify(provider.id, async (current) => {\n\t\t\t\tif (current?.type !== \"oauth\" || Date.now() < current.expires) return undefined;\n\t\t\t\treturn oauth.refresh(current, signal);\n\t\t\t});\n\t\t\treturn post?.type === \"oauth\" ? post : undefined;\n\t\t}\n\n\t\tconst apiKey = provider.auth.apiKey;\n\t\tif (!apiKey) return undefined;\n\t\tconst credential = stored?.type === \"api_key\" ? stored : undefined;\n\t\tconst result = await apiKey.resolve({ ctx: this.authContext, credential });\n\t\tif (!result) return undefined;\n\t\treturn { type: \"api_key\", key: result.auth.apiKey, env: result.env };\n\t}\n\n\tprivate async readCredential(providerId: string): Promise<Credential | undefined> {\n\t\ttry {\n\t\t\treturn await this.credentials.read(providerId);\n\t\t} catch (error) {\n\t\t\tthrow new ModelsError(\"auth\", `Credential store read failed for ${providerId}`, { cause: error });\n\t\t}\n\t}\n\n\tprivate async checkProviderAuth(\n\t\tprovider: Provider,\n\t\tcredential: Credential | undefined,\n\t): Promise<AuthCheck | undefined> {\n\t\tif (credential?.type === \"oauth\") {\n\t\t\treturn provider.auth.oauth ? { source: \"OAuth\", type: \"oauth\" } : undefined;\n\t\t}\n\t\tconst apiKey = provider.auth.apiKey;\n\t\tif (!apiKey) return undefined;\n\t\tif (apiKey.check) {\n\t\t\ttry {\n\t\t\t\treturn await apiKey.check({\n\t\t\t\t\tctx: this.authContext,\n\t\t\t\t\tcredential: credential?.type === \"api_key\" ? credential : undefined,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow new ModelsError(\"auth\", `API key auth check failed for provider ${provider.id}`, { cause: error });\n\t\t\t}\n\t\t}\n\n\t\tconst resolution = await resolveProviderAuth(provider, this.credentials, this.authContext);\n\t\treturn resolution ? { source: resolution.source, type: \"api_key\" } : undefined;\n\t}\n\n\tasync checkAuth(providerId: string): Promise<AuthCheck | undefined> {\n\t\tconst provider = this.providers.get(providerId);\n\t\tif (!provider) return undefined;\n\t\treturn this.checkProviderAuth(provider, await this.readCredential(providerId));\n\t}\n\n\tasync getAvailable(providerId?: string): Promise<readonly Model<Api>[]> {\n\t\tconst providers = providerId\n\t\t\t? [this.providers.get(providerId)].filter((entry) => entry !== undefined)\n\t\t\t: this.getProviders();\n\t\tconst checks = await Promise.all(\n\t\t\tproviders.map(async (provider) => {\n\t\t\t\tconst credential = await this.readCredential(provider.id);\n\t\t\t\treturn { provider, credential, auth: await this.checkProviderAuth(provider, credential) };\n\t\t\t}),\n\t\t);\n\t\treturn checks.flatMap(({ provider, credential, auth }) => {\n\t\t\tif (!auth) return [];\n\t\t\tconst models = provider.getModels();\n\t\t\treturn provider.filterModels?.(models, credential) ?? models;\n\t\t});\n\t}\n\n\tgetAuth(providerId: string, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: Model<Api>, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;\n\tasync getAuth(\n\t\tproviderOrModel: string | Model<Api>,\n\t\toverrides?: AuthResolutionOverrides,\n\t): Promise<AuthResult | undefined> {\n\t\tconst providerId = typeof providerOrModel === \"string\" ? providerOrModel : providerOrModel.provider;\n\t\tconst provider = this.providers.get(providerId);\n\t\tif (!provider) return undefined;\n\t\tconst result = await resolveProviderAuth(provider, this.credentials, this.authContext, overrides);\n\t\tif (!result || typeof providerOrModel === \"string\" || !providerOrModel.headers) return result;\n\t\treturn {\n\t\t\t...result,\n\t\t\tauth: {\n\t\t\t\t...result.auth,\n\t\t\t\theaders: mergeHeaders(result.auth.headers, providerOrModel.headers),\n\t\t\t},\n\t\t};\n\t}\n\n\tasync login(providerId: string, type: AuthType, interaction: AuthInteraction): Promise<Credential> {\n\t\tconst provider = this.providers.get(providerId);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${providerId}`);\n\t\tconst method = type === \"oauth\" ? provider.auth.oauth : provider.auth.apiKey;\n\t\tif (!method?.login) {\n\t\t\tthrow new ModelsError(\"auth\", `${provider.name} does not support ${type} login`);\n\t\t}\n\t\tconst credential = await method.login(interaction);\n\t\ttry {\n\t\t\tawait this.credentials.modify(providerId, async () => credential);\n\t\t} catch (error) {\n\t\t\tthrow new ModelsError(\"auth\", `Credential store modify failed for ${providerId}`, { cause: error });\n\t\t}\n\t\treturn credential;\n\t}\n\n\tasync logout(providerId: string): Promise<void> {\n\t\ttry {\n\t\t\tawait this.credentials.delete(providerId);\n\t\t} catch (error) {\n\t\t\tthrow new ModelsError(\"auth\", `Credential store delete failed for ${providerId}`, { cause: error });\n\t\t}\n\t}\n\n\tprivate requireProvider(model: Model<Api>): Provider {\n\t\tconst provider = this.providers.get(model.provider);\n\t\tif (!provider) {\n\t\t\tthrow new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\t}\n\t\treturn provider;\n\t}\n\n\tprivate async applyAuth<TOptions extends StreamOptions & ModelsStreamTransforms>(\n\t\tmodel: Model<Api>,\n\t\toptions: TOptions | undefined,\n\t): Promise<{ requestModel: Model<Api>; requestOptions: StreamOptions | undefined }> {\n\t\tthis.requireProvider(model);\n\t\tconst resolution = await this.getAuth(model, {\n\t\t\tapiKey: options?.apiKey,\n\t\t\tenv: options?.env,\n\t\t});\n\t\tif (!resolution) {\n\t\t\tthrow new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\t\t}\n\t\tconst auth = resolution.auth;\n\n\t\t// Explicit request options win per-field; the Models-only transform runs last.\n\t\tconst apiKey = options?.apiKey ?? auth.apiKey;\n\t\tlet headers = mergeHeaders(auth.headers, options?.headers);\n\t\tif (options?.transformHeaders) headers = await options.transformHeaders(headers ?? {});\n\t\tconst env = resolution.env || options?.env ? { ...(resolution.env ?? {}), ...(options?.env ?? {}) } : undefined;\n\t\tconst requestModel = auth.baseUrl ? { ...model, baseUrl: auth.baseUrl } : model;\n\t\tconst { transformHeaders: _transformHeaders, ...providerOptions } = options ?? {};\n\t\tconst requestOptions = { ...providerOptions, apiKey, headers, env } as StreamOptions;\n\n\t\treturn { requestModel, requestOptions };\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 provider = this.requireProvider(model);\n\t\t\tconst { requestModel, requestOptions } = await this.applyAuth(\n\t\t\t\tmodel,\n\t\t\t\toptions as ModelsApiStreamOptions<Api> | undefined,\n\t\t\t);\n\t\t\treturn provider.stream(requestModel as Model<TApi>, context, requestOptions as ApiStreamOptions<TApi>);\n\t\t});\n\t}\n\n\tasync complete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage> {\n\t\treturn this.stream(model, context, options).result();\n\t}\n\n\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst provider = this.requireProvider(model);\n\t\t\tconst { requestModel, requestOptions } = await this.applyAuth(model, options);\n\t\t\treturn provider.streamSimple(requestModel, context, requestOptions as SimpleStreamOptions);\n\t\t});\n\t}\n\n\tasync completeSimple(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions?: ModelsSimpleStreamOptions,\n\t): Promise<AssistantMessage> {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n}\n\nexport function createModels(options?: CreateModelsOptions): MutableModels {\n\treturn new ModelsImpl(options);\n}\n\nexport interface CreateProviderOptions<TApi extends Api = Api> {\n\tid: string;\n\t/** Display name. Default: `id`. */\n\tname?: string;\n\tbaseUrl?: string;\n\theaders?: ProviderHeaders;\n\t/** Required — every provider has auth semantics, even ambient/keyless ones. */\n\tauth: ProviderAuth;\n\t/** Static baseline model list (empty for purely dynamic providers). */\n\tmodels: readonly Model<TApi>[];\n\t/** Fetch a dynamic model overlay. createProvider restores/persists it through ModelsStore. */\n\tfetchModels?: (context: RefreshModelsContext) => Promise<readonly Model<TApi>[]>;\n\tfilterModels?: (models: readonly Model<TApi>[], credential: Credential | undefined) => readonly Model<TApi>[];\n\t/** Single implementation, or map keyed by `model.api` for mixed-API providers. */\n\tapi: ProviderStreams | Partial<Record<TApi, ProviderStreams>>;\n}\n\n/**\n * Builds a provider from parts. Built-in provider factories and models.json\n * custom providers both go through this. A single `api` streams all models;\n * an `api` map dispatches on `model.api`, and a model whose api has no entry\n * produces a stream error.\n */\nexport function createProvider<TApi extends Api = Api>(input: CreateProviderOptions<TApi>): Provider<TApi> {\n\tconst baselineModels = input.models;\n\tlet dynamicModels: readonly Model<TApi>[] = [];\n\tlet inflightRefresh: Promise<void> | undefined;\n\tconst fetchModels = input.fetchModels;\n\tconst currentModels = (): readonly Model<TApi>[] => {\n\t\tconst merged = [...baselineModels];\n\t\tfor (const model of dynamicModels) {\n\t\t\tconst index = merged.findIndex((entry) => entry.id === model.id);\n\t\t\tif (index >= 0) merged[index] = model;\n\t\t\telse merged.push(model);\n\t\t}\n\t\treturn merged;\n\t};\n\tconst single =\n\t\ttypeof (input.api as ProviderStreams).stream === \"function\" ? (input.api as ProviderStreams) : undefined;\n\tconst byApi = single ? undefined : (input.api as Partial<Record<string, ProviderStreams>>);\n\n\tconst apiFor = (model: Model<Api>): ProviderStreams | undefined => single ?? byApi?.[model.api];\n\n\tconst dispatch = (\n\t\tmodel: Model<Api>,\n\t\trun: (streams: ProviderStreams) => AssistantMessageEventStream,\n\t): AssistantMessageEventStream => {\n\t\tconst streams = apiFor(model);\n\t\tif (!streams) {\n\t\t\treturn lazyStream(model, async () => {\n\t\t\t\tthrow new ModelsError(\"stream\", `Provider ${input.id} has no API implementation for \"${model.api}\"`);\n\t\t\t});\n\t\t}\n\t\treturn run(streams);\n\t};\n\n\treturn {\n\t\tid: input.id,\n\t\tname: input.name ?? input.id,\n\t\tbaseUrl: input.baseUrl,\n\t\theaders: input.headers,\n\t\tauth: input.auth,\n\t\tgetModels: currentModels,\n\t\trefreshModels: fetchModels\n\t\t\t? (context) => {\n\t\t\t\t\tinflightRefresh ??= (async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst stored = await context.store.read();\n\t\t\t\t\t\t\tif (stored) {\n\t\t\t\t\t\t\t\tdynamicModels = stored.models\n\t\t\t\t\t\t\t\t\t.filter((model) => model.provider === input.id)\n\t\t\t\t\t\t\t\t\t.map((model) => model as Model<TApi>);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!context.allowNetwork || context.signal?.aborted) return;\n\t\t\t\t\t\t\tconst refreshed = await fetchModels(context);\n\t\t\t\t\t\t\tif (context.signal?.aborted) return;\n\t\t\t\t\t\t\tdynamicModels = refreshed;\n\t\t\t\t\t\t\tawait context.store.write({ models: refreshed, checkedAt: Date.now() });\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tinflightRefresh = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t\treturn inflightRefresh;\n\t\t\t\t}\n\t\t\t: undefined,\n\t\tfilterModels: input.filterModels,\n\t\tstream: (model, context, options) => dispatch(model, (streams) => streams.stream(model, context, options)),\n\t\tstreamSimple: (model, context, options) =>\n\t\t\tdispatch(model, (streams) => streams.streamSimple(model, context, options)),\n\t};\n}\n\n/**\n * Runtime-checked narrowing for dynamically looked-up models:\n *\n * ```ts\n * const model = models.getModel(\"anthropic\", \"claude-opus-4-7\");\n * if (model && hasApi(model, \"anthropic-messages\")) {\n *   // model: Model<\"anthropic-messages\">, stream options fully typed\n * }\n * ```\n */\nexport function hasApi<TApi extends Api>(model: Model<Api>, api: TApi): model is Model<TApi> {\n\treturn model.api === api;\n}\n\nexport function calculateCost<TApi extends Api>(model: Model<TApi>, usage: Usage): Usage[\"cost\"] {\n\tconst inputTokens = usage.input + usage.cacheRead + usage.cacheWrite;\n\tlet rates: ModelCostRates = model.cost;\n\tlet matchedThreshold = -1;\n\tfor (const tier of model.cost.tiers ?? []) {\n\t\tif (inputTokens > tier.inputTokensAbove && tier.inputTokensAbove > matchedThreshold) {\n\t\t\trates = tier;\n\t\t\tmatchedThreshold = tier.inputTokensAbove;\n\t\t}\n\t}\n\n\t// Anthropic charges 2x base input for 1h cache writes.\n\tconst longWrite = usage.cacheWrite1h ?? 0;\n\tconst shortWrite = usage.cacheWrite - longWrite;\n\tusage.cost.input = (rates.input / 1000000) * usage.input;\n\tusage.cost.output = (rates.output / 1000000) * usage.output;\n\tusage.cost.cacheRead = (rates.cacheRead / 1000000) * usage.cacheRead;\n\tusage.cost.cacheWrite = (rates.cacheWrite * shortWrite + rates.input * 2 * longWrite) / 1000000;\n\tusage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n\treturn usage.cost;\n}\n\nconst EXTENDED_THINKING_LEVELS: ModelThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n\nexport function getSupportedThinkingLevels<TApi extends Api>(model: Model<TApi>): ModelThinkingLevel[] {\n\tif (!model.reasoning) return [\"off\"];\n\n\treturn EXTENDED_THINKING_LEVELS.filter((level) => {\n\t\tconst mapped = model.thinkingLevelMap?.[level];\n\t\tif (mapped === null) return false;\n\t\tif (level === \"xhigh\" || level === \"max\") return mapped !== undefined;\n\t\treturn true;\n\t});\n}\n\nexport function clampThinkingLevel<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tlevel: ModelThinkingLevel,\n): ModelThinkingLevel {\n\tconst availableLevels = getSupportedThinkingLevels(model);\n\tif (availableLevels.includes(level)) return level;\n\n\tconst requestedIndex = EXTENDED_THINKING_LEVELS.indexOf(level);\n\tif (requestedIndex === -1) return availableLevels[0] ?? \"off\";\n\n\tfor (let i = requestedIndex; i < EXTENDED_THINKING_LEVELS.length; i++) {\n\t\tconst candidate = EXTENDED_THINKING_LEVELS[i];\n\t\tif (availableLevels.includes(candidate)) return candidate;\n\t}\n\tfor (let i = requestedIndex - 1; i >= 0; i--) {\n\t\tconst candidate = EXTENDED_THINKING_LEVELS[i];\n\t\tif (availableLevels.includes(candidate)) return candidate;\n\t}\n\treturn availableLevels[0] ?? \"off\";\n}\n\n/**\n * Check if two models are equal by comparing both their id and provider.\n * Returns false if either model is null or undefined.\n */\nexport function modelsAreEqual<TApi extends Api>(\n\ta: Model<TApi> | null | undefined,\n\tb: Model<TApi> | null | undefined,\n): boolean {\n\tif (!a || !b) return false;\n\treturn a.id === b.id && a.provider === b.provider;\n}\n"]}