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,GAAG,SAAS,EAC5C,SAAS,EAAE,mBAAmB,GAC5B,IAAI,CAKN;AAED,uFAAuF;AACvF,wBAAgB,oBAAoB,CACnC,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,QAAQ,GAAG,SAAS,EAC1B,WAAW,EAAE,WAAW,EACxB,SAAS,EAAE,mBAAmB,GAAG,SAAS,GACxC,QAAQ,CAkFV;AAED,wBAAgB,6BAA6B,CAC5C,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,MAAM,EAAE,kBAAkB,GAAG,SAAS,EACtC,SAAS,EAAE,mBAAmB,GAAG,SAAS,EAC1C,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAC1B,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAMpC;AAED,MAAM,WAAW,0BAA0B;IAC1C,OAAO,CAAC,EAAE,eAAe,CAAC;IAC1B,UAAU,EAAE,OAAO,CAAC;CACpB;AAED,wBAAgB,iCAAiC,CAChD,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,MAAM,EAAE,kBAAkB,GAAG,SAAS,EACtC,SAAS,EAAE,mBAAmB,GAAG,SAAS,GACxC,0BAA0B,CAS5B;AAED,wBAAgB,2BAA2B,CAC1C,MAAM,EAAE,kBAAkB,GAAG,SAAS,EACtC,SAAS,EAAE,mBAAmB,GAAG,SAAS,GACxC,UAAU,GAAG,SAAS,CAWxB","sourcesContent":["import {\n\ttype Api,\n\ttype ApiKeyAuth,\n\ttype AssistantMessageEventStream,\n\ttype AuthContext,\n\ttype AuthInteraction,\n\ttype AuthResult,\n\ttype Context,\n\ttype Credential,\n\tlazyStream,\n\ttype Model,\n\ttype ModelAuth,\n\ttype OAuthAuth,\n\ttype OAuthCredentials,\n\ttype OAuthLoginCallbacks,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype RefreshModelsContext,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@earendil-works/pi-ai\";\nimport { getApiProvider } from \"@earendil-works/pi-ai/compat\";\nimport type { ModelConfig, ModelsJsonModel, ModelsJsonModelOverride, ModelsJsonProvider } from \"./model-config.ts\";\nimport {\n\tclearConfigValueCache,\n\tgetConfigValueEnvVarNames,\n\tisCommandConfigValue,\n\tisConfigValueConfigured,\n\tresolveConfigValueOrThrow,\n\tresolveHeadersOrThrow,\n} from \"./resolve-config-value.ts\";\n\nexport interface ExtensionOAuthConfig {\n\tname: string;\n\t/** @deprecated Retained for extension source compatibility; ignored by canonical auth flows. */\n\tusesCallbackServer?: boolean;\n\tlogin(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials>;\n\trefreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials>;\n\tgetApiKey(credentials: OAuthCredentials): string;\n\tmodifyModels?(models: Model<Api>[], credentials: OAuthCredentials): Model<Api>[];\n}\n\n/** Input type for the extension registerProvider API. */\nexport interface ProviderConfigInput {\n\tname?: string;\n\tbaseUrl?: string;\n\tapiKey?: string;\n\tapi?: Api;\n\tstreamSimple?: (model: Model<Api>, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;\n\theaders?: Record<string, string>;\n\tauthHeader?: boolean;\n\toauth?: ExtensionOAuthConfig;\n\tmodels?: Array<{\n\t\tid: string;\n\t\tname: string;\n\t\tapi?: Api;\n\t\tbaseUrl?: string;\n\t\treasoning: boolean;\n\t\tthinkingLevelMap?: Model<Api>[\"thinkingLevelMap\"];\n\t\tinput: (\"text\" | \"image\")[];\n\t\tcost: Model<Api>[\"cost\"];\n\t\tcontextWindow: number;\n\t\tmaxTokens: number;\n\t\theaders?: Record<string, string>;\n\t\tcompat?: Model<Api>[\"compat\"];\n\t}>;\n\trefreshModels?(context: RefreshModelsContext): Promise<NonNullable<ProviderConfigInput[\"models\"]>>;\n}\n\nexport type AuthStatus = {\n\tconfigured: boolean;\n\tsource?: \"stored\" | \"runtime\" | \"environment\" | \"fallback\" | \"models_json_key\" | \"models_json_command\";\n\tlabel?: string;\n};\n\nexport const clearApiKeyCache = clearConfigValueCache;\n\nfunction mergeCompat(\n\tbase: Model<Api>[\"compat\"],\n\toverride: Model<Api>[\"compat\"] | ModelsJsonModelOverride[\"compat\"],\n): Model<Api>[\"compat\"] {\n\tif (!override) return base;\n\tconst merged = { ...base, ...override } as NonNullable<Model<Api>[\"compat\"]>;\n\tconst baseNested = base as Record<string, unknown> | undefined;\n\tconst overrideNested = override as Record<string, unknown>;\n\tconst mergedNested = merged as Record<string, unknown>;\n\tfor (const key of [\"openRouterRouting\", \"vercelGatewayRouting\", \"chatTemplateKwargs\"] as const) {\n\t\tconst baseValue = baseNested?.[key];\n\t\tconst overrideValue = overrideNested[key];\n\t\tif (\n\t\t\t(typeof baseValue === \"object\" && baseValue !== null) ||\n\t\t\t(typeof overrideValue === \"object\" && overrideValue !== null)\n\t\t) {\n\t\t\tmergedNested[key] = { ...(baseValue as object | undefined), ...(overrideValue as object | undefined) };\n\t\t}\n\t}\n\treturn merged;\n}\n\nfunction applyModelOverride(model: Model<Api>, override: ModelsJsonModelOverride): Model<Api> {\n\treturn {\n\t\t...model,\n\t\tname: override.name ?? model.name,\n\t\treasoning: override.reasoning ?? model.reasoning,\n\t\tthinkingLevelMap: override.thinkingLevelMap\n\t\t\t? { ...model.thinkingLevelMap, ...override.thinkingLevelMap }\n\t\t\t: model.thinkingLevelMap,\n\t\tinput: (override.input as (\"text\" | \"image\")[] | undefined) ?? model.input,\n\t\tcost: override.cost\n\t\t\t? {\n\t\t\t\t\tinput: override.cost.input ?? model.cost.input,\n\t\t\t\t\toutput: override.cost.output ?? model.cost.output,\n\t\t\t\t\tcacheRead: override.cost.cacheRead ?? model.cost.cacheRead,\n\t\t\t\t\tcacheWrite: override.cost.cacheWrite ?? model.cost.cacheWrite,\n\t\t\t\t\ttiers: override.cost.tiers ?? model.cost.tiers,\n\t\t\t\t}\n\t\t\t: model.cost,\n\t\tcontextWindow: override.contextWindow ?? model.contextWindow,\n\t\tmaxTokens: override.maxTokens ?? model.maxTokens,\n\t\tcompat: mergeCompat(model.compat, override.compat),\n\t};\n}\n\nfunction modelFromJson(\n\tproviderId: string,\n\tdefinition: ModelsJsonModel,\n\tproviderConfig: ModelsJsonProvider,\n\tdefaults: Model<Api> | undefined,\n): Model<Api> {\n\tconst api = definition.api ?? providerConfig.api ?? defaults?.api;\n\tif (!api) {\n\t\tthrow new Error(\n\t\t\t`Provider ${providerId}, model ${definition.id}: no \"api\" specified. Set at provider or model level.`,\n\t\t);\n\t}\n\tconst baseUrl = definition.baseUrl ?? providerConfig.baseUrl ?? defaults?.baseUrl;\n\tif (!baseUrl) throw new Error(`Provider ${providerId}: \"baseUrl\" is required when defining custom models.`);\n\tif (definition.contextWindow !== undefined && definition.contextWindow <= 0) {\n\t\tthrow new Error(`Provider ${providerId}, model ${definition.id}: invalid contextWindow`);\n\t}\n\tif (definition.maxTokens !== undefined && definition.maxTokens <= 0) {\n\t\tthrow new Error(`Provider ${providerId}, model ${definition.id}: invalid maxTokens`);\n\t}\n\treturn {\n\t\tid: definition.id,\n\t\tname: definition.name ?? definition.id,\n\t\tapi: api as Api,\n\t\tprovider: providerId,\n\t\tbaseUrl,\n\t\treasoning: definition.reasoning ?? false,\n\t\tthinkingLevelMap: definition.thinkingLevelMap,\n\t\tinput: (definition.input ?? [\"text\"]) as (\"text\" | \"image\")[],\n\t\tcost: definition.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow: definition.contextWindow ?? 128000,\n\t\tmaxTokens: definition.maxTokens ?? 16384,\n\t\theaders: undefined,\n\t\tcompat: mergeCompat(providerConfig.compat, definition.compat),\n\t};\n}\n\nfunction applyModelsJson(\n\tproviderId: string,\n\tbaseModels: readonly Model<Api>[],\n\tconfig: ModelsJsonProvider | undefined,\n): Model<Api>[] {\n\tif (!config) return [...baseModels];\n\tif (config.oauth && !config.baseUrl) {\n\t\tthrow new Error(`Provider ${providerId}: \"baseUrl\" is required when \"oauth\" is set.`);\n\t}\n\tconst hasOverrides = config.modelOverrides && Object.keys(config.modelOverrides).length > 0;\n\tif (\n\t\t!config.models?.length &&\n\t\t!config.baseUrl &&\n\t\t!config.headers &&\n\t\t!config.compat &&\n\t\t!hasOverrides &&\n\t\t!config.apiKey &&\n\t\t!config.oauth &&\n\t\tconfig.authHeader === undefined\n\t) {\n\t\tthrow new Error(\n\t\t\t`Provider ${providerId}: must specify \"baseUrl\", \"headers\", \"compat\", \"modelOverrides\", or \"models\".`,\n\t\t);\n\t}\n\n\tconst models: Model<Api>[] = baseModels.map((model) => ({\n\t\t...model,\n\t\tbaseUrl: config.oauth === \"radius\" ? model.baseUrl : (config.baseUrl ?? model.baseUrl),\n\t\tcompat: mergeCompat(model.compat, config.compat),\n\t}));\n\tfor (const definition of config.models ?? []) {\n\t\tconst existingIndex = models.findIndex((model) => model.id === definition.id);\n\t\tconst defaults = existingIndex >= 0 ? models[existingIndex] : models[0];\n\t\tconst model = modelFromJson(providerId, definition, config, defaults);\n\t\tif (existingIndex >= 0) models[existingIndex] = model;\n\t\telse models.push(model);\n\t}\n\treturn models;\n}\n\nfunction applyExtension(\n\tproviderId: string,\n\tmodels: readonly Model<Api>[],\n\tconfig: ProviderConfigInput | undefined,\n): Model<Api>[] {\n\tif (!config) return [...models];\n\tif (!config.models) {\n\t\treturn config.baseUrl ? models.map((model) => ({ ...model, baseUrl: config.baseUrl! })) : [...models];\n\t}\n\treturn config.models.map((definition) => {\n\t\tconst defaults = models.find((model) => model.id === definition.id) ?? models[0];\n\t\tconst api = definition.api ?? config.api ?? defaults?.api;\n\t\tif (!api) {\n\t\t\tthrow new Error(\n\t\t\t\t`Provider ${providerId}, model ${definition.id}: no \"api\" specified. Set at provider or model level.`,\n\t\t\t);\n\t\t}\n\t\tconst baseUrl = definition.baseUrl ?? config.baseUrl ?? defaults?.baseUrl;\n\t\tif (!baseUrl) throw new Error(`Provider ${providerId}: \"baseUrl\" is required when defining custom models.`);\n\t\treturn {\n\t\t\t...definition,\n\t\t\tapi,\n\t\t\tprovider: providerId,\n\t\t\tbaseUrl,\n\t\t\theaders: undefined,\n\t\t};\n\t});\n}\n\nfunction adaptOAuth(config: ExtensionOAuthConfig): OAuthAuth {\n\treturn {\n\t\tname: config.name,\n\t\tlogin: async (callbacks) => {\n\t\t\tconst credential = await config.login({\n\t\t\t\tonAuth: (info) => callbacks.notify({ type: \"auth_url\", ...info }),\n\t\t\t\tonDeviceCode: (info) => callbacks.notify({ type: \"device_code\", ...info }),\n\t\t\t\tonPrompt: (prompt) => callbacks.prompt({ type: \"text\", ...prompt }),\n\t\t\t\tonProgress: (message) => callbacks.notify({ type: \"progress\", message }),\n\t\t\t\tonManualCodeInput: () => callbacks.prompt({ type: \"manual_code\", message: \"Paste the authorization code\" }),\n\t\t\t\tonSelect: (prompt) => callbacks.prompt({ type: \"select\", ...prompt }),\n\t\t\t\tsignal: callbacks.signal,\n\t\t\t});\n\t\t\treturn { ...credential, type: \"oauth\" };\n\t\t},\n\t\trefresh: async (credential) => ({ ...(await config.refreshToken(credential)), type: \"oauth\" }),\n\t\ttoAuth: async (credential) => ({ apiKey: config.getApiKey(credential) }),\n\t};\n}\n\nfunction withConfiguredAuth(\n\tauth: ModelAuth,\n\theaders: Record<string, string> | undefined,\n\tauthHeader: boolean,\n): ModelAuth {\n\tlet mergedHeaders: ProviderHeaders | undefined =\n\t\tauth.headers || headers ? { ...auth.headers, ...headers } : undefined;\n\tif (authHeader) {\n\t\tif (!auth.apiKey) throw new Error(\"authHeader requires a resolved API key\");\n\t\tmergedHeaders = { ...mergedHeaders, Authorization: `Bearer ${auth.apiKey}` };\n\t}\n\treturn { ...auth, headers: mergedHeaders };\n}\n\nfunction configuredApiKey(\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): string | undefined {\n\treturn extension?.apiKey ?? config?.apiKey;\n}\n\nfunction configuredHeaders(\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): Record<string, string> | undefined {\n\tif (!config?.headers && !extension?.headers) return undefined;\n\treturn { ...config?.headers, ...extension?.headers };\n}\n\nasync function configContextEnv(\n\tvalues: readonly string[],\n\tctx: AuthContext,\n\texplicit?: Record<string, string>,\n): Promise<Record<string, string> | undefined> {\n\tconst env = { ...explicit };\n\tfor (const name of new Set(values.flatMap(getConfigValueEnvVarNames))) {\n\t\tif (env[name] !== undefined) continue;\n\t\tconst value = await ctx.env(name);\n\t\tif (value !== undefined) env[name] = value;\n\t}\n\treturn Object.keys(env).length > 0 ? env : undefined;\n}\n\nfunction composeApiKeyAuth(\n\tproviderId: string,\n\tbase: Provider | undefined,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): ApiKeyAuth | undefined {\n\tconst inherited = base?.auth.apiKey;\n\tconst rawKey = configuredApiKey(config, extension);\n\tconst oauth = extension?.oauth ?? base?.auth.oauth;\n\t// OAuth-only providers get no fabricated API-key login method.\n\tif (!inherited && rawKey === undefined && oauth) return undefined;\n\tconst rawHeaders = configuredHeaders(config, extension);\n\tconst authHeader = extension?.authHeader ?? config?.authHeader ?? false;\n\treturn {\n\t\tname: inherited?.name ?? \"API key\",\n\t\tlogin:\n\t\t\tinherited?.login ??\n\t\t\t(async (interaction: AuthInteraction) => ({\n\t\t\t\ttype: \"api_key\",\n\t\t\t\tkey: await interaction.prompt({ type: \"secret\", message: \"Enter API key\" }),\n\t\t\t})),\n\t\tcheck: async (input) => {\n\t\t\tif (input.credential) {\n\t\t\t\tif (inherited?.check) return inherited.check(input);\n\t\t\t\tif (input.credential.key) return { type: \"api_key\", source: \"stored credential\" };\n\t\t\t\tconst resolved = await inherited?.resolve(input);\n\t\t\t\treturn resolved ? { type: \"api_key\", source: resolved.source } : undefined;\n\t\t\t}\n\t\t\tif (rawKey !== undefined) {\n\t\t\t\tif (isCommandConfigValue(rawKey)) return { type: \"api_key\", source: \"configured API key\" };\n\t\t\t\tconst envNames = getConfigValueEnvVarNames(rawKey);\n\t\t\t\tfor (const name of envNames) {\n\t\t\t\t\tif ((await input.ctx.env(name)) === undefined) return undefined;\n\t\t\t\t}\n\t\t\t\treturn { type: \"api_key\", source: \"configured API key\" };\n\t\t\t}\n\t\t\tif (inherited?.check) return inherited.check(input);\n\t\t\tconst resolved = await inherited?.resolve(input);\n\t\t\treturn resolved ? { type: \"api_key\", source: resolved.source } : undefined;\n\t\t},\n\t\tresolve: async (input) => {\n\t\t\tlet result: AuthResult | undefined;\n\t\t\tif (input.credential) {\n\t\t\t\tresult = inherited\n\t\t\t\t\t? await inherited.resolve(input)\n\t\t\t\t\t: input.credential.key\n\t\t\t\t\t\t? { auth: { apiKey: input.credential.key }, env: input.credential.env, source: \"stored credential\" }\n\t\t\t\t\t\t: undefined;\n\t\t\t} else if (rawKey !== undefined) {\n\t\t\t\tconst env = await configContextEnv([rawKey], input.ctx);\n\t\t\t\tconst key = resolveConfigValueOrThrow(rawKey, `API key for provider \"${providerId}\"`, env);\n\t\t\t\tresult = inherited\n\t\t\t\t\t? await inherited.resolve({ ...input, credential: { type: \"api_key\", key } })\n\t\t\t\t\t: { auth: { apiKey: key }, source: \"configured API key\" };\n\t\t\t} else {\n\t\t\t\tresult = await inherited?.resolve(input);\n\t\t\t}\n\t\t\tif (!result) return undefined;\n\t\t\tconst explicitEnv = { ...(input.credential?.env ?? {}), ...(result.env ?? {}) };\n\t\t\tconst headerEnv = await configContextEnv(Object.values(rawHeaders ?? {}), input.ctx, explicitEnv);\n\t\t\tconst headers = resolveHeadersOrThrow(rawHeaders, `provider \"${providerId}\"`, headerEnv);\n\t\t\treturn { ...result, auth: withConfiguredAuth(result.auth, headers, authHeader) };\n\t\t},\n\t};\n}\n\nfunction composeOAuthAuth(\n\tproviderId: string,\n\tbase: Provider | undefined,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): OAuthAuth | undefined {\n\tconst oauth = extension?.oauth ? adaptOAuth(extension.oauth) : base?.auth.oauth;\n\tif (!oauth) return undefined;\n\tconst rawHeaders = configuredHeaders(config, extension);\n\tconst authHeader = extension?.authHeader ?? config?.authHeader ?? false;\n\treturn {\n\t\t...oauth,\n\t\ttoAuth: async (credential) => {\n\t\t\tconst auth = await oauth.toAuth(credential);\n\t\t\tconst env = credential.env;\n\t\t\tconst headers = resolveHeadersOrThrow(\n\t\t\t\trawHeaders,\n\t\t\t\t`provider \"${providerId}\"`,\n\t\t\t\ttypeof env === \"object\" && env !== null ? (env as Record<string, string>) : undefined,\n\t\t\t);\n\t\t\treturn withConfiguredAuth(auth, headers, authHeader);\n\t\t},\n\t};\n}\n\nfunction rawModelHeaders(\n\tmodel: Model<Api>,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): Record<string, string> | undefined {\n\tconst definition = config?.models?.find((entry) => entry.id === model.id);\n\tconst extensionModel = extension?.models?.find((entry) => entry.id === model.id);\n\tconst headers = {\n\t\t...config?.modelOverrides?.[model.id]?.headers,\n\t\t...definition?.headers,\n\t\t...extensionModel?.headers,\n\t};\n\treturn Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nexport function validateExtensionProvider(\n\tproviderId: string,\n\tbase: Provider | undefined,\n\tmodelsConfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput,\n): void {\n\tif (extension.streamSimple && !extension.api) {\n\t\tthrow new Error(`Provider ${providerId}: \"api\" is required when registering streamSimple.`);\n\t}\n\tapplyExtension(providerId, applyModelsJson(providerId, base?.getModels() ?? [], modelsConfig), extension);\n}\n\n/** Compose built-in, models.json, and extension layers without reading credentials. */\nexport function composeModelProvider(\n\tproviderId: string,\n\tbase: Provider | undefined,\n\tmodelConfig: ModelConfig,\n\textension: ProviderConfigInput | undefined,\n): Provider {\n\tconst config = modelConfig.getProvider(providerId);\n\tlet extensionOAuthCredential: OAuthCredentials | undefined;\n\tlet refreshedExtensionModels: ProviderConfigInput[\"models\"];\n\tconst currentExtension = (): ProviderConfigInput | undefined =>\n\t\textension && refreshedExtensionModels ? { ...extension, models: refreshedExtensionModels } : extension;\n\t// models.json modelOverrides are the topmost user-config layer: they apply once,\n\t// after custom-model upserts, extension model replacement, and legacy OAuth projection.\n\tconst getModels = () => {\n\t\tlet models = applyExtension(\n\t\t\tproviderId,\n\t\t\tapplyModelsJson(providerId, base?.getModels() ?? [], config),\n\t\t\tcurrentExtension(),\n\t\t);\n\t\tif (extensionOAuthCredential && extension?.oauth?.modifyModels) {\n\t\t\tmodels = extension.oauth.modifyModels(models, extensionOAuthCredential);\n\t\t}\n\t\treturn models.map((model) => {\n\t\t\tconst override = config?.modelOverrides?.[model.id];\n\t\t\treturn override ? applyModelOverride(model, override) : model;\n\t\t});\n\t};\n\t// Validate eagerly so registration/reload reports structural errors immediately.\n\tgetModels();\n\tconst apiKey = composeApiKeyAuth(providerId, base, config, extension);\n\tconst oauth = composeOAuthAuth(providerId, base, config, extension);\n\tif (!apiKey && !oauth) throw new Error(`Provider ${providerId}: no authentication method configured.`);\n\n\tconst supportsBaseApi = (model: Model<Api>) => base?.getModels().some((entry) => entry.api === model.api) ?? false;\n\tconst streamWith = (\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: StreamOptions | undefined,\n\t\tsimple: boolean,\n\t): AssistantMessageEventStream =>\n\t\tlazyStream(model, async () => {\n\t\t\tif (extension?.streamSimple && model.api === extension.api) {\n\t\t\t\treturn extension.streamSimple(model, context, options as SimpleStreamOptions);\n\t\t\t}\n\t\t\tif (base && supportsBaseApi(model)) {\n\t\t\t\treturn simple\n\t\t\t\t\t? base.streamSimple(model, context, options as SimpleStreamOptions)\n\t\t\t\t\t: base.stream(model, context, options);\n\t\t\t}\n\t\t\tconst api = getApiProvider(model.api);\n\t\t\tif (!api) throw new Error(`No API provider registered for api: ${model.api}`);\n\t\t\treturn simple\n\t\t\t\t? api.streamSimple(model, context, options as SimpleStreamOptions)\n\t\t\t\t: api.stream(model, context, options);\n\t\t});\n\n\treturn {\n\t\tid: providerId,\n\t\tname: extension?.name ?? config?.name ?? base?.name ?? extension?.oauth?.name ?? providerId,\n\t\tbaseUrl: extension?.baseUrl ?? config?.baseUrl ?? base?.baseUrl,\n\t\theaders: base?.headers,\n\t\tauth: { ...(apiKey ? { apiKey } : {}), ...(oauth ? { oauth } : {}) },\n\t\tgetModels,\n\t\trefreshModels:\n\t\t\tbase?.refreshModels || extension?.refreshModels || extension?.oauth?.modifyModels\n\t\t\t\t? async (context) => {\n\t\t\t\t\t\tawait base?.refreshModels?.(context);\n\t\t\t\t\t\tif (extension?.refreshModels) {\n\t\t\t\t\t\t\tconst refreshed = await extension.refreshModels(context);\n\t\t\t\t\t\t\tif (!context.signal?.aborted) {\n\t\t\t\t\t\t\t\t// Validate before publishing the new synchronous list.\n\t\t\t\t\t\t\t\tapplyExtension(providerId, applyModelsJson(providerId, base?.getModels() ?? [], config), {\n\t\t\t\t\t\t\t\t\t...extension,\n\t\t\t\t\t\t\t\t\tmodels: refreshed,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\trefreshedExtensionModels = refreshed;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\textensionOAuthCredential = context.credential?.type === \"oauth\" ? context.credential : undefined;\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\tfilterModels: base?.filterModels\n\t\t\t? (models, credential: Credential | undefined) => base.filterModels!(models, credential)\n\t\t\t: undefined,\n\t\tstream: (model, context, options) => streamWith(model, context, options, false),\n\t\tstreamSimple: (model, context, options) => streamWith(model, context, options, true),\n\t};\n}\n\nexport function resolveConfiguredModelHeaders(\n\tmodel: Model<Api>,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n\tenv?: Record<string, string>,\n): Record<string, string> | undefined {\n\treturn resolveHeadersOrThrow(\n\t\trawModelHeaders(model, config, extension),\n\t\t`model \"${model.provider}/${model.id}\"`,\n\t\tenv,\n\t);\n}\n\nexport interface CompatibilityRequestConfig {\n\theaders?: ProviderHeaders;\n\tauthHeader: boolean;\n}\n\nexport function resolveCompatibilityRequestConfig(\n\tmodel: Model<Api>,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): CompatibilityRequestConfig {\n\tconst configured = resolveHeadersOrThrow(\n\t\t{ ...configuredHeaders(config, extension), ...rawModelHeaders(model, config, extension) },\n\t\t`model \"${model.provider}/${model.id}\"`,\n\t);\n\treturn {\n\t\theaders: model.headers || configured ? { ...model.headers, ...configured } : undefined,\n\t\tauthHeader: extension?.authHeader ?? config?.authHeader ?? false,\n\t};\n}\n\nexport function configuredRequestAuthStatus(\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): AuthStatus | undefined {\n\tconst value = configuredApiKey(config, extension);\n\tif (value === undefined) return undefined;\n\tif (isCommandConfigValue(value)) return { configured: true, source: \"models_json_command\" };\n\tconst names = getConfigValueEnvVarNames(value);\n\tif (names.length > 0) {\n\t\treturn isConfigValueConfigured(value)\n\t\t\t? { configured: true, source: \"environment\", label: names.join(\", \") }\n\t\t\t: { configured: false };\n\t}\n\treturn { configured: true, source: extension?.apiKey !== undefined ? \"fallback\" : \"models_json_key\" };\n}\n"]}