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essageEventStream,\n\ttype AuthCheck,\n\ttype AuthInteraction,\n\ttype AuthResult,\n\ttype AuthType,\n\ttype Context,\n\ttype Credential,\n\ttype CredentialInfo,\n\ttype CredentialStore,\n\tcreateModels,\n\tlazyStream,\n\ttype Model,\n\ttype Models,\n\ttype ModelsApiStreamOptions,\n\tModelsError,\n\ttype ModelsRefreshOptions,\n\ttype ModelsRefreshResult,\n\ttype ModelsSimpleStreamOptions,\n\ttype ModelsStore,\n\ttype ModelsStreamTransforms,\n\ttype MutableModels,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@earendil-works/pi-ai\";\nimport * as builtinProviderCatalog from \"@earendil-works/pi-ai/providers/all\";\nimport { getAgentDir, getBundledDefaultsDir } from \"../config.ts\";\nimport { AuthStorage as DefaultAuthStorage } from \"./auth-storage.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 { withRemoteCatalog } from \"./remote-catalog-provider.ts\";\nimport { RuntimeCredentials } from \"./runtime-credentials.ts\";\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}\n\nexport interface ModelRuntimeAuthOverrides {\n\tapiKey?: string;\n\tenv?: Record<string, string>;\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\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 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 availabilityRefresh: Promise<void> | undefined;\n\tprivate availabilityError: string | undefined;\n\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) {\n\t\tthis.credentials = credentials;\n\t\tthis.config = config;\n\t\tthis.modelsPath = modelsPath;\n\t\tthis.modelNetworkEnabled = modelNetworkEnabled;\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.loadMerged([\n\t\t\tjoin(getBundledDefaultsDir(), \"models.json\"),\n\t\t\t...(modelsPath ? [modelsPath] : []),\n\t\t]);\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.id === \"radius\"\n\t\t\t\t\t? provider\n\t\t\t\t\t: withRemoteCatalog(\n\t\t\t\t\t\t\tprovider,\n\t\t\t\t\t\t\toptions.catalogBaseUrl,\n\t\t\t\t\t\t\tbuiltinProviderCatalog.getBuiltinModelDataUrl(\n\t\t\t\t\t\t\t\tprovider.id as builtinProviderCatalog.BuiltinProvider,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\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\tprocess.env.PI_OFFLINE === undefined,\n\t\t);\n\t\truntime.configureRadiusProviders();\n\t\truntime.rebuildProviders();\n\t\tconst refreshFromNetwork = runtime.modelNetworkEnabled && options.allowModelNetwork === true;\n\t\tconst controller = refreshFromNetwork ? new AbortController() : undefined;\n\t\tconst timeout = controller\n\t\t\t? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs ?? 15_000)\n\t\t\t: undefined;\n\t\ttry {\n\t\t\tawait runtime.refresh({ allowNetwork: refreshFromNetwork, signal: controller?.signal });\n\t\t} finally {\n\t\t\tif (timeout) clearTimeout(timeout);\n\t\t}\n\t\treturn runtime;\n\t}\n\n\tprivate configureRadiusProviders(): void {\n\t\tthis.builtins.clear();\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tfor (const providerId of this.config.getProviderIds()) {\n\t\t\tconst config = this.config.getProvider(providerId);\n\t\t\tif (config?.oauth !== \"radius\" || !config.baseUrl) continue;\n\t\t\tthis.builtins.set(\n\t\t\t\tproviderId,\n\t\t\t\tbuiltinProviderCatalog.radiusProvider({\n\t\t\t\t\tid: providerId,\n\t\t\t\t\tname: config.name ?? providerId,\n\t\t\t\t\tgateway: config.baseUrl.replace(/\\/v1\\/?$/u, \"\"),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\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\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(): Promise<void> {\n\t\tconst providers = this.models.getProviders();\n\t\tconst [available, checks, credentials] = await Promise.all([\n\t\t\tthis.models.getAvailable(),\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),\n\t\t\t\t\t],\n\t\t\t\t),\n\t\t\t),\n\t\t\tthis.credentials.list(),\n\t\t]);\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.availabilityError = undefined;\n\t}\n\n\tprivate queueAvailabilityRefresh(after: Promise<void> | undefined): Promise<void> {\n\t\tconst refresh = (after ?? Promise.resolve()).catch(() => {}).then(() => this.runAvailabilityRefresh());\n\t\tconst recorded = refresh.catch((error) => {\n\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\tthrow error;\n\t\t});\n\t\tconst tracked = recorded.finally(() => {\n\t\t\tif (this.availabilityRefresh === tracked) this.availabilityRefresh = undefined;\n\t\t});\n\t\tthis.availabilityRefresh = tracked;\n\t\treturn tracked;\n\t}\n\n\t/** Coalesce concurrent readers onto the pending refresh. */\n\tprivate refreshAvailability(): Promise<void> {\n\t\treturn this.availabilityRefresh ?? this.queueAvailabilityRefresh(undefined);\n\t}\n\n\t/** Mutations must not observe an in-flight refresh started before them. */\n\tprivate forceRefreshAvailability(): Promise<void> {\n\t\treturn this.queueAvailabilityRefresh(this.availabilityRefresh);\n\t}\n\n\tgetProviders(): readonly Provider[] {\n\t\treturn this.models.getProviders();\n\t}\n\n\tgetProvider(providerId: string): Provider | undefined {\n\t\treturn this.models.getProvider(providerId);\n\t}\n\n\tgetModels(providerId?: string): readonly Model<Api>[] {\n\t\treturn this.models.getModels(providerId);\n\t}\n\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): Promise<AuthCheck | undefined> {\n\t\treturn this.models.checkAuth(providerId);\n\t}\n\n\tasync getAvailable(providerId?: string): Promise<readonly Model<Api>[]> {\n\t\tif (providerId) {\n\t\t\tif (this.availabilityRefresh) {\n\t\t\t\tawait this.availabilityRefresh;\n\t\t\t\treturn this.snapshot.available.filter((model) => model.provider === providerId);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn await this.models.getAvailable(providerId);\n\t\t\t} catch (error) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tawait this.refreshAvailability();\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetAvailableSnapshot(): readonly Model<Api>[] {\n\t\treturn this.snapshot.available;\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>): 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);\n\t}\n\n\tisUsingOAuth(providerId: string): boolean {\n\t\treturn this.snapshot.auth.get(providerId)?.type === \"oauth\";\n\t}\n\n\thasConfiguredAuth(providerId: string): boolean {\n\t\treturn this.snapshot.configuredProviders.has(providerId);\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\tasync setRuntimeApiKey(\n\t\tproviderId: string,\n\t\tapiKey: string,\n\t\trefreshOptions: ModelsRefreshOptions = {},\n\t): Promise<void> {\n\t\tthis.credentials.setRuntimeApiKey(providerId, apiKey);\n\t\tconst auth = new Map(this.snapshot.auth).set(providerId, { type: \"api_key\", source: \"runtime API key\" });\n\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\tconst storedProviders = new Set(this.snapshot.storedProviders).add(providerId);\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tauth,\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders,\n\t\t\tavailable: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),\n\t\t};\n\t\tawait this.refresh(refreshOptions);\n\t}\n\n\tasync removeRuntimeApiKey(providerId: string): Promise<void> {\n\t\tthis.credentials.removeRuntimeApiKey(providerId);\n\t\tawait this.refresh({ allowNetwork: this.modelNetworkEnabled });\n\t}\n\n\tlistCredentials(): Promise<readonly CredentialInfo[]> {\n\t\treturn this.credentials.list();\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(\n\t\tmodel: Model<Api>,\n\t\toptions: (StreamOptions & ModelsStreamTransforms) | undefined,\n\t): Promise<{ provider: Provider; model: Model<Api>; options: StreamOptions }> {\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, { apiKey: options?.apiKey, env: options?.env });\n\t\tif (!resolution) throw new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\n\t\tconst { transformHeaders, ...providerOptions } = options ?? {};\n\t\tlet headers = mergeHeaders(resolution.auth.headers, providerOptions.headers);\n\t\tif (transformHeaders) headers = await transformHeaders(headers ?? {});\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\treturn {\n\t\t\tprovider,\n\t\t\tmodel: resolution.auth.baseUrl ? { ...model, baseUrl: resolution.auth.baseUrl } : model,\n\t\t\toptions: {\n\t\t\t\t...providerOptions,\n\t\t\t\tapiKey: providerOptions.apiKey ?? resolution.auth.apiKey,\n\t\t\t\theaders,\n\t\t\t\tenv,\n\t\t\t},\n\t\t};\n\t}\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(\n\t\t\t\tmodel,\n\t\t\t\toptions as (StreamOptions & ModelsStreamTransforms) | undefined,\n\t\t\t);\n\t\t\treturn prepared.provider.stream(\n\t\t\t\tprepared.model as Model<TApi>,\n\t\t\t\tcontext,\n\t\t\t\tprepared.options as ApiStreamOptions<TApi>,\n\t\t\t);\n\t\t});\n\t}\n\n\tcomplete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage> {\n\t\treturn this.stream(model, context, options).result();\n\t}\n\n\tstreamSimple(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\treturn prepared.provider.streamSimple(prepared.model, context, prepared.options as SimpleStreamOptions);\n\t\t});\n\t}\n\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 login(providerId: string, type: AuthType, interaction: AuthInteraction): Promise<Credential> {\n\t\tconst credential = await this.models.login(providerId, type, interaction);\n\t\tawait this.refresh({ allowNetwork: this.modelNetworkEnabled });\n\t\treturn credential;\n\t}\n\n\tasync logout(providerId: string): Promise<void> {\n\t\tawait this.models.logout(providerId);\n\t\t// Reset credential-dependent compatibility projections before the unconfigured provider is skipped by refresh.\n\t\tthis.recomposeProvider(providerId);\n\t\tawait this.refresh({ allowNetwork: this.modelNetworkEnabled });\n\t}\n\n\tgetCredentialStore(): CredentialStore {\n\t\treturn this.credentials.getStore();\n\t}\n\n\tasync reloadConfig(): Promise<void> {\n\t\tthis.credentials.reload();\n\t\tthis.config = await ModelConfig.loadMerged([\n\t\t\tjoin(getBundledDefaultsDir(), \"models.json\"),\n\t\t\t...(this.modelsPath ? [this.modelsPath] : []),\n\t\t]);\n\t\tthis.configureRadiusProviders();\n\t\tthis.rebuildProviders();\n\t\tawait this.refresh({ allowNetwork: this.modelNetworkEnabled });\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<ModelsRefreshResult> {\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\tthis.updateModelSnapshot();\n\t\ttry {\n\t\t\tawait this.forceRefreshAvailability();\n\t\t} catch {\n\t\t\t// Availability errors are recorded by forceRefreshAvailability; refreshed models remain usable.\n\t\t}\n\t\treturn result;\n\t}\n\n\tregisterNativeProvider(provider: Provider): void {\n\t\tif (!provider.id.trim()) throw new Error(\"Provider id must not be empty.\");\n\t\tthis.extensionProviders.delete(provider.id);\n\t\tthis.nativeExtensionProviders.set(provider.id, provider);\n\t\tthis.recomposeProvider(provider.id);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tregisterProvider(providerId: string, config: ProviderConfigInput): void {\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\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\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\tvoid this.refresh({ allowNetwork: false });\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.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n}\n"]}