@ashx-j/lunr 0.1.1 → 0.1.2

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.
Files changed (35) hide show
  1. package/dist/catalog/models.json +1 -1
  2. package/dist/catalog/providers/opencode-go.json +1 -1
  3. package/dist/catalog/providers/openrouter.json +1 -1
  4. package/dist/catalog/providers/qwen-token-plan-cn.json +1 -1
  5. package/dist/catalog/providers/qwen-token-plan.json +1 -1
  6. package/dist/catalog/publication.json +3 -3
  7. package/dist/core/catalog-merge.d.ts.map +1 -1
  8. package/dist/core/catalog-merge.js +7 -1
  9. package/dist/core/catalog-merge.js.map +1 -1
  10. package/dist/core/grok-cli-auth.d.ts +32 -0
  11. package/dist/core/grok-cli-auth.d.ts.map +1 -0
  12. package/dist/core/grok-cli-auth.js +218 -0
  13. package/dist/core/grok-cli-auth.js.map +1 -0
  14. package/dist/core/model-runtime.d.ts +9 -0
  15. package/dist/core/model-runtime.d.ts.map +1 -1
  16. package/dist/core/model-runtime.js +22 -3
  17. package/dist/core/model-runtime.js.map +1 -1
  18. package/dist/core/usage-adapters/xai.d.ts.map +1 -1
  19. package/dist/core/usage-adapters/xai.js +4 -0
  20. package/dist/core/usage-adapters/xai.js.map +1 -1
  21. package/dist/core/usage-service.d.ts +11 -1
  22. package/dist/core/usage-service.d.ts.map +1 -1
  23. package/dist/core/usage-service.js +45 -9
  24. package/dist/core/usage-service.js.map +1 -1
  25. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  26. package/dist/modes/interactive/interactive-mode.js +28 -3
  27. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  28. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  29. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  30. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  31. package/examples/extensions/gondolin/package-lock.json +2 -2
  32. package/examples/extensions/gondolin/package.json +1 -1
  33. package/examples/extensions/with-deps/package-lock.json +2 -2
  34. package/examples/extensions/with-deps/package.json +1 -1
  35. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"model-runtime.d.ts","sourceRoot":"","sources":["../../src/core/model-runtime.ts"],"names":[],"mappings":"AACA,OAAO,EACN,KAAK,GAAG,EAER,KAAK,gBAAgB,EACrB,KAAK,2BAA2B,EAChC,KAAK,SAAS,EACd,KAAK,eAAe,EACpB,KAAK,UAAU,EACf,KAAK,QAAQ,EACb,KAAK,OAAO,EACZ,KAAK,UAAU,EACf,KAAK,cAAc,EACnB,KAAK,eAAe,EAGpB,KAAK,KAAK,EACV,KAAK,MAAM,EACX,KAAK,sBAAsB,EAE3B,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,KAAK,yBAAyB,EAC9B,KAAK,WAAW,EAGhB,KAAK,QAAQ,EAIb,MAAM,uBAAuB,CAAC;AAK/B,OAAO,EAGN,KAAK,mBAAmB,EAGxB,KAAK,iBAAiB,EACtB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAEN,KAAK,yBAAyB,EAI9B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,KAAK,UAAU,EACf,KAAK,0BAA0B,EAG/B,KAAK,mBAAmB,EAIxB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,KAAK,cAAc,EAAqD,MAAM,kBAAkB,CAAC;AAU1G,MAAM,WAAW,yBAAyB;IACzC,4DAA4D;IAC5D,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,oFAAoF;IACpF,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,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IAAI,CAAC,GACpC,OAAO,CAAC,gBAAgB,CAAC,CAE3B;IAED,YAAY,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,yBAAyB,GAAG,2BAA2B,CAKlH;IAED,cAAc,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,yBAAyB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAElH;IAEK,KAAK,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,eAAe,GAAG,OAAO,CAAC,UAAU,CAAC,CAIjG;IAEK,MAAM,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAQ9C;IAEK,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC,CAKlC;IAEK,OAAO,CAAC,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAwC/E;IAED,qBAAqB,IAAI,oBAAoB,CAE5C;IAED,iBAAiB,CAAC,IAAI,EAAE,SAAS,cAAc,EAAE,GAAG,IAAI,CAIvD;YAEa,sBAAsB;YAwBtB,mBAAmB;YAmBnB,mBAAmB;YAkGnB,oBAAoB;IAWlC,gBAAgB,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAmCtE;IAED,kBAAkB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAK3C;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 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 \"@ashx-j/lunr-ai\";\nimport * as builtinProviderCatalog from \"@ashx-j/lunr-ai/providers/all\";\nimport { getAgentDir } from \"../config.ts\";\nimport { AuthStorage as DefaultAuthStorage } from \"./auth-storage.ts\";\nimport { CatalogOverlaySource, knownModelKeys, withCatalogOverlay } from \"./catalog-merge.ts\";\nimport {\n\tbuildLiveOverlay,\n\tfetchLiveProviderModels,\n\ttype IncompleteLiveModel,\n\tisLiveListProvider,\n\tLIVE_LIST_PROVIDER_IDS,\n\ttype LiveCatalogResult,\n} from \"./live-catalog.ts\";\nimport { ModelConfig } from \"./model-config.ts\";\nimport { FileModelsStore, InMemoryCodingAgentModelsStore } from \"./models-store.ts\";\nimport {\n\tloadOfficialCatalog,\n\ttype OfficialCatalogLoadResult,\n\tofficialCatalogCachePath,\n\tofficialEntryToModel,\n\tofficialModelKeys,\n} from \"./official-catalog.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 { RuntimeCredentials } from \"./runtime-credentials.ts\";\nimport { SubscriptionManager } from \"./subscriptions.ts\";\nimport { type UserModelEntry, UserModelsStore, userEntryToModel, userModelsPath } from \"./user-models.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\tallowModelNetwork?: boolean;\n\t/** Applied by callers of `refresh()`, not by `create()` (startup is cache-only). */\n\tmodelRefreshTimeoutMs?: number;\n\t/** Unused. Kept so older callers compiling against this options bag still typecheck. */\n\tcatalogBaseUrl?: string;\n\t/** lunr: subscription-key pool. Defaults to subscriptions.json next to authPath (in-memory for custom stores). */\n\tsubscriptions?: SubscriptionManager;\n}\n\nexport interface CatalogRefreshResult extends ModelsRefreshResult {\n\tofficial?: OfficialCatalogLoadResult & { evictedUserRows: number };\n\tlive: LiveCatalogResult[];\n\tincomplete: IncompleteLiveModel[];\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\t/** lunr: per-provider subscription-key pools; rotation mirrors the active key into the credential store. */\n\treadonly subscriptionManager: SubscriptionManager;\n\tprivate readonly defaultBuiltins: ReadonlyMap<string, Provider>;\n\tprivate readonly builtins = 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 allowModelNetwork: 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\tprivate readonly modelsStore: ModelsStore;\n\tprivate readonly overlay = new CatalogOverlaySource();\n\tprivate readonly userModels: UserModelsStore;\n\tprivate readonly officialCachePath: string | undefined;\n\tprivate lastCatalogRefresh: CatalogRefreshResult = { aborted: false, errors: new Map(), live: [], incomplete: [] };\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\tallowModelNetwork: boolean,\n\t\tsubscriptionManager: SubscriptionManager,\n\t\tcatalogDir: string | undefined,\n\t) {\n\t\tthis.credentials = credentials;\n\t\tthis.config = config;\n\t\tthis.modelsPath = modelsPath;\n\t\tthis.modelsStore = modelsStore;\n\t\tthis.allowModelNetwork = allowModelNetwork;\n\t\tthis.subscriptionManager = subscriptionManager;\n\t\tthis.userModels = new UserModelsStore(catalogDir ? userModelsPath(catalogDir) : undefined);\n\t\tthis.officialCachePath = catalogDir ? officialCatalogCachePath(catalogDir) : undefined;\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\t// lunr: keep the underlying store — the SubscriptionManager mirrors rotated\n\t\t// keys into it directly, NOT through the RuntimeCredentials overlay (a runtime\n\t\t// --api-key override would shadow the mirror there).\n\t\tconst baseStore = options.credentials ?? DefaultAuthStorage.create(options.authPath);\n\t\tconst credentials = new RuntimeCredentials(baseStore);\n\t\t// Pool persistence: subscriptions.json next to auth.json. A custom credential\n\t\t// store without an authPath (tests, SDK embeddings) gets a process-local pool\n\t\t// so nothing leaks into the real agent dir.\n\t\tconst subscriptionManager =\n\t\t\toptions.subscriptions ??\n\t\t\t(options.credentials && !options.authPath\n\t\t\t\t? SubscriptionManager.inMemory(baseStore)\n\t\t\t\t: SubscriptionManager.create(\n\t\t\t\t\t\tbaseStore,\n\t\t\t\t\t\toptions.authPath ? join(dirname(options.authPath), \"subscriptions.json\") : undefined,\n\t\t\t\t\t));\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 providers = builtinProviderCatalog.builtinProviders();\n\t\tconst catalogDir = modelsPath ? dirname(modelsPath) : options.authPath ? dirname(options.authPath) : undefined;\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 ?? process.env.PI_OFFLINE === undefined,\n\t\t\tsubscriptionManager,\n\t\t\tcatalogDir,\n\t\t);\n\t\truntime.configureRadiusProviders();\n\t\truntime.rebuildProviders();\n\t\t// lunr: create() must not wait on GitHub / provider /v1/models / a dead NIC.\n\t\t// Disk cache + baked-in + bundled official overlay are enough to start;\n\t\t// /refresh and the model picker still do a live refresh.\n\t\tawait runtime.refresh({ allowNetwork: false });\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([...this.builtins.keys(), ...this.config.getProviderIds(), ...this.extensionProviders.keys()]);\n\t}\n\n\tprivate recomposeProvider(providerId: string): void {\n\t\tconst base = 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 models.json/extension overlays: keep builtin auth/stream exact, then apply catalog layers.\n\t\t\tthis.models.setProvider(this.withLocalCatalog(base));\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.models.setProvider(this.withLocalCatalog(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(this.withLocalCatalog(base));\n\t\t\telse this.models.deleteProvider(providerId);\n\t\t}\n\t}\n\n\tprivate withLocalCatalog(provider: Provider): Provider {\n\t\treturn isLiveListProvider(provider.id) ? withCatalogOverlay(provider, this.overlay) : provider;\n\t}\n\n\tprivate bakedInModels(providerId: string): Model<Api>[] {\n\t\treturn [...(this.defaultBuiltins.get(providerId)?.getModels() ?? [])];\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 listStoredProviderIds(): Promise<Set<string>> {\n\t\tconst credentials = await this.credentials.list();\n\t\treturn new Set(credentials.map((entry) => entry.providerId));\n\t}\n\n\t/** `/model` lists stored creds + models.json/extension keys, never ambient envApiKeyAuth. */\n\tprivate configuredProviderIds(storedProviders: ReadonlySet<string>): Set<string> {\n\t\tconst configured = new Set(storedProviders);\n\t\tfor (const provider of this.models.getProviders()) {\n\t\t\tif (\n\t\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(provider.id), this.extensionProviders.get(provider.id))\n\t\t\t\t\t?.configured\n\t\t\t) {\n\t\t\t\tconfigured.add(provider.id);\n\t\t\t}\n\t\t}\n\t\treturn configured;\n\t}\n\n\tprivate userModelsForStoredProviders(storedProviders: ReadonlySet<string>): Model<Api>[] {\n\t\treturn this.userModels\n\t\t\t.list()\n\t\t\t.filter((row) => storedProviders.has(row.provider))\n\t\t\t.map(userEntryToModel);\n\t}\n\n\tprivate async runAvailabilityRefresh(): Promise<void> {\n\t\tconst providers = this.models.getProviders();\n\t\tconst [available, checks, storedProviders] = 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.listStoredProviderIds(),\n\t\t]);\n\t\tconst auth = new Map(checks);\n\t\tconst configuredProviders = this.configuredProviderIds(storedProviders);\n\t\tthis.snapshot = {\n\t\t\tall: [...this.models.getModels()],\n\t\t\tavailable: available.filter((model) => configuredProviders.has(model.provider)),\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders,\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 [...this.extensionProviders.keys()];\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\t/** lunr: whether a runtime --api-key override is active for the provider (it shadows auth.json). */\n\thasRuntimeApiKey(providerId: string): boolean {\n\t\treturn this.credentials.hasRuntimeApiKey(providerId);\n\t}\n\n\tasync setRuntimeApiKey(providerId: string, apiKey: string): 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({ allowNetwork: this.allowModelNetwork });\n\t}\n\n\tasync removeRuntimeApiKey(providerId: string): Promise<void> {\n\t\tthis.credentials.removeRuntimeApiKey(providerId);\n\t\tawait this.refresh({ allowNetwork: this.allowModelNetwork });\n\t}\n\n\t/** lunr: whether network model-catalog fetches are allowed (offline mode disables them). */\n\tisNetworkAllowed(): boolean {\n\t\treturn this.allowModelNetwork;\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.allowModelNetwork });\n\t\treturn credential;\n\t}\n\n\tasync logout(providerId: string): Promise<void> {\n\t\tawait this.models.logout(providerId);\n\t\tawait this.modelsStore.delete(providerId);\n\t\tthis.userModels.evictProvider(providerId);\n\t\tthis.overlay.setLive(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.allowModelNetwork });\n\t}\n\n\tasync reloadConfig(): Promise<void> {\n\t\tthis.config = await ModelConfig.load(this.modelsPath);\n\t\tthis.configureRadiusProviders();\n\t\tthis.rebuildProviders();\n\t\tawait this.refresh({ allowNetwork: this.allowModelNetwork });\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<CatalogRefreshResult> {\n\t\tconst refreshOptions = {\n\t\t\t...options,\n\t\t\tallowNetwork: options.allowNetwork ?? this.allowModelNetwork,\n\t\t};\n\t\tconst official = await this.refreshOfficialCatalog(refreshOptions.allowNetwork, refreshOptions.signal);\n\t\tconst live = refreshOptions.allowNetwork\n\t\t\t? await this.refreshLiveCatalogs(\n\t\t\t\t\tofficial ? officialModelKeys(official.catalog) : new Set(),\n\t\t\t\t\trefreshOptions.signal,\n\t\t\t\t)\n\t\t\t: await this.restoreLiveCatalogs();\n\n\t\t// Radius / local-provider / extension refreshModels hooks. Live-list\n\t\t// providers have no refreshModels, so this does not hit pi.dev.\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\tfor (const entry of live) {\n\t\t\tif (entry.status === \"error\" || entry.status === \"timeout\") {\n\t\t\t\terrors.set(entry.providerId, new Error(entry.error ?? entry.status));\n\t\t\t}\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\tconst catalogResult: CatalogRefreshResult = {\n\t\t\taborted: result.aborted,\n\t\t\terrors,\n\t\t\tofficial,\n\t\t\tlive,\n\t\t\tincomplete: live.flatMap((entry) => entry.incomplete),\n\t\t};\n\t\tthis.lastCatalogRefresh = catalogResult;\n\t\treturn catalogResult;\n\t}\n\n\tgetLastCatalogRefresh(): CatalogRefreshResult {\n\t\treturn this.lastCatalogRefresh;\n\t}\n\n\tpersistUserModels(rows: readonly UserModelEntry[]): void {\n\t\tthis.userModels.upsert(rows);\n\t\tthis.overlay.setUser(this.userModelsForStoredProviders(this.snapshot.storedProviders));\n\t\tthis.updateModelSnapshot();\n\t}\n\n\tprivate async refreshOfficialCatalog(\n\t\tallowNetwork: boolean,\n\t\tsignal?: AbortSignal,\n\t): Promise<(OfficialCatalogLoadResult & { evictedUserRows: number }) | undefined> {\n\t\tconst storedProviders = await this.listStoredProviderIds();\n\t\tconst loaded = await loadOfficialCatalog({\n\t\t\tallowNetwork,\n\t\t\tcachePath: this.officialCachePath,\n\t\t\tsignal,\n\t\t\tproviderIds: [...storedProviders],\n\t\t});\n\t\tconst evicted = this.userModels.evictOfficial(officialModelKeys(loaded.catalog));\n\t\tconst templateByProvider = new Map<string, Model<Api> | undefined>();\n\t\tconst officialModels = loaded.catalog.models.map((entry) => {\n\t\t\tif (!templateByProvider.has(entry.provider)) {\n\t\t\t\ttemplateByProvider.set(entry.provider, this.bakedInModels(entry.provider)[0]);\n\t\t\t}\n\t\t\treturn officialEntryToModel(entry, templateByProvider.get(entry.provider));\n\t\t});\n\t\tthis.overlay.setOfficial(officialModels);\n\t\tthis.overlay.setUser(this.userModelsForStoredProviders(storedProviders));\n\t\treturn { ...loaded, evictedUserRows: evicted.length };\n\t}\n\n\tprivate async restoreLiveCatalogs(): Promise<LiveCatalogResult[]> {\n\t\tconst storedProviders = await this.listStoredProviderIds();\n\t\tconst results: LiveCatalogResult[] = [];\n\t\tfor (const providerId of LIVE_LIST_PROVIDER_IDS) {\n\t\t\tconst stored = storedProviders.has(providerId) ? await this.modelsStore.read(providerId) : undefined;\n\t\t\tif (stored?.models) this.overlay.setLive(providerId, stored.models);\n\t\t\telse this.overlay.setLive(providerId, []);\n\t\t\tresults.push({\n\t\t\t\tproviderId,\n\t\t\t\tstatus: \"skipped\",\n\t\t\t\tdiscoveries: [],\n\t\t\t\tadded: 0,\n\t\t\t\ttotal: stored?.models.length ?? 0,\n\t\t\t\tincomplete: [],\n\t\t\t});\n\t\t}\n\t\treturn results;\n\t}\n\n\tprivate async refreshLiveCatalogs(officialKeys: Set<string>, signal?: AbortSignal): Promise<LiveCatalogResult[]> {\n\t\tconst storedProviders = await this.listStoredProviderIds();\n\t\tconst known = knownModelKeys(\n\t\t\tLIVE_LIST_PROVIDER_IDS.flatMap((id) => this.bakedInModels(id)),\n\t\t\tofficialKeys,\n\t\t\tthis.userModels.keys(),\n\t\t);\n\n\t\tconst results = await Promise.all(\n\t\t\tLIVE_LIST_PROVIDER_IDS.map(async (providerId) => {\n\t\t\t\tif (!storedProviders.has(providerId)) {\n\t\t\t\t\tthis.overlay.setLive(providerId, []);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"skipped\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tconst stored = await this.modelsStore.read(providerId);\n\t\t\t\tif (stored?.models) this.overlay.setLive(providerId, stored.models);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"skipped\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: stored?.models.length ?? 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t\terror: \"aborted\",\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tconst bakedIn = this.bakedInModels(providerId);\n\t\t\t\tconst provider = this.models.getProvider(providerId) ?? this.defaultBuiltins.get(providerId);\n\t\t\t\tconst baseUrl = provider?.baseUrl ?? bakedIn[0]?.baseUrl;\n\t\t\t\tif (!baseUrl) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"skipped\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tlet credential: Credential | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tcredential = await this.refreshCredentialFor(providerId);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: stored?.models.length ?? 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (!credential) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"skipped\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: stored?.models.length ?? 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tconst result = await fetchLiveProviderModels({\n\t\t\t\t\tproviderId,\n\t\t\t\t\tbaseUrl,\n\t\t\t\t\tbakedIn,\n\t\t\t\t\tcredential,\n\t\t\t\t\tknownKeys: known,\n\t\t\t\t\tsignal,\n\t\t\t\t});\n\t\t\t\tif (result.status === \"ok\") {\n\t\t\t\t\tconst overlayModels = buildLiveOverlay(bakedIn, result.discoveries);\n\t\t\t\t\tthis.overlay.setLive(providerId, overlayModels);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.modelsStore.write(providerId, { models: overlayModels, checkedAt: Date.now() });\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Store write is best-effort.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}),\n\t\t);\n\t\treturn results;\n\t}\n\n\tprivate async refreshCredentialFor(providerId: string): Promise<Credential | undefined> {\n\t\tconst stored = await this.credentials.read(providerId);\n\t\t// Same lock + persist path as chat. Returning stored OAuth here skips\n\t\t// refresh and sends expired SuperGrok tokens to GET /models (HTTP 403).\n\t\tconst resolved = await this.getAuth(providerId);\n\t\tif (resolved?.auth.apiKey) return { type: \"api_key\", key: resolved.auth.apiKey, env: resolved.env };\n\t\tif (stored?.type === \"oauth\" && stored.access) return stored;\n\t\tif (stored?.type === \"api_key\" && stored.key) return stored;\n\t\treturn undefined;\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\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.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n}\n"]}
1
+ {"version":3,"file":"model-runtime.d.ts","sourceRoot":"","sources":["../../src/core/model-runtime.ts"],"names":[],"mappings":"AACA,OAAO,EACN,KAAK,GAAG,EAER,KAAK,gBAAgB,EACrB,KAAK,2BAA2B,EAChC,KAAK,SAAS,EACd,KAAK,eAAe,EACpB,KAAK,UAAU,EACf,KAAK,QAAQ,EACb,KAAK,OAAO,EACZ,KAAK,UAAU,EACf,KAAK,cAAc,EACnB,KAAK,eAAe,EAGpB,KAAK,KAAK,EACV,KAAK,MAAM,EACX,KAAK,sBAAsB,EAE3B,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,KAAK,yBAAyB,EAC9B,KAAK,WAAW,EAGhB,KAAK,QAAQ,EAIb,MAAM,uBAAuB,CAAC;AAM/B,OAAO,EAGN,KAAK,mBAAmB,EAGxB,KAAK,iBAAiB,EACtB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAEN,KAAK,yBAAyB,EAI9B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,KAAK,UAAU,EACf,KAAK,0BAA0B,EAG/B,KAAK,mBAAmB,EAIxB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAEzD,OAAO,EAAE,KAAK,cAAc,EAAqD,MA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E5C;IAED,iBAAiB,CAAC,IAAI,EAAE,SAAS,cAAc,EAAE,GAAG,IAAI,CAIvD;YAEa,sBAAsB;YAwBtB,mBAAmB;YAmBnB,mBAAmB;YAkGnB,oBAAoB;IAWlC,gBAAgB,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAmCtE;IAED,kBAAkB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAK3C;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 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 \"@ashx-j/lunr-ai\";\nimport * as builtinProviderCatalog from \"@ashx-j/lunr-ai/providers/all\";\nimport { getAgentDir } from \"../config.ts\";\nimport { AuthStorage as DefaultAuthStorage } from \"./auth-storage.ts\";\nimport { CatalogOverlaySource, knownModelKeys, withCatalogOverlay } from \"./catalog-merge.ts\";\nimport { readGrokCliXaiOAuth, wrapXaiGrokCliCredentials } from \"./grok-cli-auth.ts\";\nimport {\n\tbuildLiveOverlay,\n\tfetchLiveProviderModels,\n\ttype IncompleteLiveModel,\n\tisLiveListProvider,\n\tLIVE_LIST_PROVIDER_IDS,\n\ttype LiveCatalogResult,\n} from \"./live-catalog.ts\";\nimport { ModelConfig } from \"./model-config.ts\";\nimport { FileModelsStore, InMemoryCodingAgentModelsStore } from \"./models-store.ts\";\nimport {\n\tloadOfficialCatalog,\n\ttype OfficialCatalogLoadResult,\n\tofficialCatalogCachePath,\n\tofficialEntryToModel,\n\tofficialModelKeys,\n} from \"./official-catalog.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 { RuntimeCredentials } from \"./runtime-credentials.ts\";\nimport { SubscriptionManager } from \"./subscriptions.ts\";\nimport { clearPlanUsageCache } from \"./usage-service.ts\";\nimport { type UserModelEntry, UserModelsStore, userEntryToModel, userModelsPath } from \"./user-models.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\tallowModelNetwork?: boolean;\n\t/** Applied by callers of `refresh()`, not by `create()` (startup is cache-only). */\n\tmodelRefreshTimeoutMs?: number;\n\t/** Unused. Kept so older callers compiling against this options bag still typecheck. */\n\tcatalogBaseUrl?: string;\n\t/** lunr: subscription-key pool. Defaults to subscriptions.json next to authPath (in-memory for custom stores). */\n\tsubscriptions?: SubscriptionManager;\n\t/**\n\t * Grok CLI home (`~/.grok`) used as a SuperGrok OAuth fallback.\n\t * `null` disables the fallback. Custom `credentials` default to disabled\n\t * unless this is an explicit path.\n\t */\n\tgrokHome?: string | null;\n}\n\nexport interface CatalogRefreshResult extends ModelsRefreshResult {\n\tofficial?: OfficialCatalogLoadResult & { evictedUserRows: number };\n\tlive: LiveCatalogResult[];\n\tincomplete: IncompleteLiveModel[];\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\t/** lunr: per-provider subscription-key pools; rotation mirrors the active key into the credential store. */\n\treadonly subscriptionManager: SubscriptionManager;\n\tprivate readonly defaultBuiltins: ReadonlyMap<string, Provider>;\n\tprivate readonly builtins = 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 allowModelNetwork: 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\tprivate readonly modelsStore: ModelsStore;\n\tprivate readonly overlay = new CatalogOverlaySource();\n\tprivate readonly userModels: UserModelsStore;\n\tprivate readonly officialCachePath: string | undefined;\n\tprivate lastCatalogRefresh: CatalogRefreshResult = { aborted: false, errors: new Map(), live: [], incomplete: [] };\n\tprivate readonly grokHome: 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\tallowModelNetwork: boolean,\n\t\tsubscriptionManager: SubscriptionManager,\n\t\tcatalogDir: string | undefined,\n\t\tgrokHome: string | undefined,\n\t) {\n\t\tthis.credentials = credentials;\n\t\tthis.config = config;\n\t\tthis.modelsPath = modelsPath;\n\t\tthis.modelsStore = modelsStore;\n\t\tthis.allowModelNetwork = allowModelNetwork;\n\t\tthis.subscriptionManager = subscriptionManager;\n\t\tthis.userModels = new UserModelsStore(catalogDir ? userModelsPath(catalogDir) : undefined);\n\t\tthis.officialCachePath = catalogDir ? officialCatalogCachePath(catalogDir) : undefined;\n\t\tthis.grokHome = grokHome;\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\t// lunr: keep the underlying store — the SubscriptionManager mirrors rotated\n\t\t// keys into it directly, NOT through the RuntimeCredentials overlay (a runtime\n\t\t// --api-key override would shadow the mirror there).\n\t\tconst rawStore = options.credentials ?? DefaultAuthStorage.create(options.authPath);\n\t\tconst grokHomeDisabled =\n\t\t\toptions.grokHome === null || (options.grokHome === undefined && options.credentials !== undefined);\n\t\tconst grokHome = grokHomeDisabled ? undefined : (options.grokHome ?? undefined);\n\t\tconst baseStore = grokHomeDisabled ? rawStore : wrapXaiGrokCliCredentials(rawStore, { grokHome });\n\t\tconst credentials = new RuntimeCredentials(baseStore);\n\t\t// Pool persistence: subscriptions.json next to auth.json. A custom credential\n\t\t// store without an authPath (tests, SDK embeddings) gets a process-local pool\n\t\t// so nothing leaks into the real agent dir.\n\t\tconst subscriptionManager =\n\t\t\toptions.subscriptions ??\n\t\t\t(options.credentials && !options.authPath\n\t\t\t\t? SubscriptionManager.inMemory(baseStore)\n\t\t\t\t: SubscriptionManager.create(\n\t\t\t\t\t\tbaseStore,\n\t\t\t\t\t\toptions.authPath ? join(dirname(options.authPath), \"subscriptions.json\") : undefined,\n\t\t\t\t\t));\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 providers = builtinProviderCatalog.builtinProviders();\n\t\tconst catalogDir = modelsPath ? dirname(modelsPath) : options.authPath ? dirname(options.authPath) : undefined;\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 ?? process.env.PI_OFFLINE === undefined,\n\t\t\tsubscriptionManager,\n\t\t\tcatalogDir,\n\t\t\tgrokHome,\n\t\t);\n\t\truntime.configureRadiusProviders();\n\t\truntime.rebuildProviders();\n\t\t// lunr: create() must not wait on GitHub / provider /v1/models / a dead NIC.\n\t\t// Disk cache + baked-in + bundled official overlay are enough to start;\n\t\t// /refresh and the model picker still do a live refresh.\n\t\tawait runtime.refresh({ allowNetwork: false });\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([...this.builtins.keys(), ...this.config.getProviderIds(), ...this.extensionProviders.keys()]);\n\t}\n\n\tprivate recomposeProvider(providerId: string): void {\n\t\tconst base = 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 models.json/extension overlays: keep builtin auth/stream exact, then apply catalog layers.\n\t\t\tthis.models.setProvider(this.withLocalCatalog(base));\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.models.setProvider(this.withLocalCatalog(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(this.withLocalCatalog(base));\n\t\t\telse this.models.deleteProvider(providerId);\n\t\t}\n\t}\n\n\tprivate withLocalCatalog(provider: Provider): Provider {\n\t\treturn isLiveListProvider(provider.id) ? withCatalogOverlay(provider, this.overlay) : provider;\n\t}\n\n\tprivate bakedInModels(providerId: string): Model<Api>[] {\n\t\treturn [...(this.defaultBuiltins.get(providerId)?.getModels() ?? [])];\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 listStoredProviderIds(): Promise<Set<string>> {\n\t\tconst credentials = await this.credentials.list();\n\t\treturn new Set(credentials.map((entry) => entry.providerId));\n\t}\n\n\t/** `/model` lists stored creds + models.json/extension keys, never ambient envApiKeyAuth. */\n\tprivate configuredProviderIds(storedProviders: ReadonlySet<string>): Set<string> {\n\t\tconst configured = new Set(storedProviders);\n\t\tfor (const provider of this.models.getProviders()) {\n\t\t\tif (\n\t\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(provider.id), this.extensionProviders.get(provider.id))\n\t\t\t\t\t?.configured\n\t\t\t) {\n\t\t\t\tconfigured.add(provider.id);\n\t\t\t}\n\t\t}\n\t\treturn configured;\n\t}\n\n\tprivate userModelsForStoredProviders(storedProviders: ReadonlySet<string>): Model<Api>[] {\n\t\treturn this.userModels\n\t\t\t.list()\n\t\t\t.filter((row) => storedProviders.has(row.provider))\n\t\t\t.map(userEntryToModel);\n\t}\n\n\tprivate async runAvailabilityRefresh(): Promise<void> {\n\t\tconst providers = this.models.getProviders();\n\t\tconst [available, checks, storedProviders] = 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.listStoredProviderIds(),\n\t\t]);\n\t\tconst auth = new Map(checks);\n\t\tconst configuredProviders = this.configuredProviderIds(storedProviders);\n\t\tthis.snapshot = {\n\t\t\tall: [...this.models.getModels()],\n\t\t\tavailable: available.filter((model) => configuredProviders.has(model.provider)),\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders,\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 [...this.extensionProviders.keys()];\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\t/** lunr: whether a runtime --api-key override is active for the provider (it shadows auth.json). */\n\thasRuntimeApiKey(providerId: string): boolean {\n\t\treturn this.credentials.hasRuntimeApiKey(providerId);\n\t}\n\n\tasync setRuntimeApiKey(providerId: string, apiKey: string): 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({ allowNetwork: this.allowModelNetwork });\n\t}\n\n\tasync removeRuntimeApiKey(providerId: string): Promise<void> {\n\t\tthis.credentials.removeRuntimeApiKey(providerId);\n\t\tawait this.refresh({ allowNetwork: this.allowModelNetwork });\n\t}\n\n\t/** lunr: whether network model-catalog fetches are allowed (offline mode disables them). */\n\tisNetworkAllowed(): boolean {\n\t\treturn this.allowModelNetwork;\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\tclearPlanUsageCache();\n\t\tawait this.refresh({ allowNetwork: this.allowModelNetwork });\n\t\treturn credential;\n\t}\n\n\tasync logout(providerId: string): Promise<void> {\n\t\tawait this.models.logout(providerId);\n\t\tawait this.modelsStore.delete(providerId);\n\t\tthis.userModels.evictProvider(providerId);\n\t\tthis.overlay.setLive(providerId, []);\n\t\t// Reset credential-dependent compatibility projections before the unconfigured provider is skipped by refresh.\n\t\tthis.recomposeProvider(providerId);\n\t\tclearPlanUsageCache();\n\t\tawait this.refresh({ allowNetwork: this.allowModelNetwork });\n\t}\n\n\t/** Copy a live Grok CLI SuperGrok session into lunR `auth.json`. */\n\tasync importGrokCliXaiAuth(): Promise<Credential | undefined> {\n\t\tconst grok = readGrokCliXaiOAuth({ grokHome: this.grokHome });\n\t\tif (!grok) return undefined;\n\t\tconst stored = await this.credentials.modify(\"xai\", async () => grok);\n\t\tclearPlanUsageCache();\n\t\tawait this.refresh({ allowNetwork: this.allowModelNetwork });\n\t\treturn stored;\n\t}\n\n\tasync reloadConfig(): Promise<void> {\n\t\tthis.config = await ModelConfig.load(this.modelsPath);\n\t\tthis.configureRadiusProviders();\n\t\tthis.rebuildProviders();\n\t\tawait this.refresh({ allowNetwork: this.allowModelNetwork });\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<CatalogRefreshResult> {\n\t\tconst refreshOptions = {\n\t\t\t...options,\n\t\t\tallowNetwork: options.allowNetwork ?? this.allowModelNetwork,\n\t\t};\n\t\tconst official = await this.refreshOfficialCatalog(refreshOptions.allowNetwork, refreshOptions.signal);\n\t\tconst live = refreshOptions.allowNetwork\n\t\t\t? await this.refreshLiveCatalogs(\n\t\t\t\t\tofficial ? officialModelKeys(official.catalog) : new Set(),\n\t\t\t\t\trefreshOptions.signal,\n\t\t\t\t)\n\t\t\t: await this.restoreLiveCatalogs();\n\n\t\t// Radius / local-provider / extension refreshModels hooks. Live-list\n\t\t// providers have no refreshModels, so this does not hit pi.dev.\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\tfor (const entry of live) {\n\t\t\tif (entry.status === \"error\" || entry.status === \"timeout\") {\n\t\t\t\terrors.set(entry.providerId, new Error(entry.error ?? entry.status));\n\t\t\t}\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\tconst catalogResult: CatalogRefreshResult = {\n\t\t\taborted: result.aborted,\n\t\t\terrors,\n\t\t\tofficial,\n\t\t\tlive,\n\t\t\tincomplete: live.flatMap((entry) => entry.incomplete),\n\t\t};\n\t\tthis.lastCatalogRefresh = catalogResult;\n\t\treturn catalogResult;\n\t}\n\n\tgetLastCatalogRefresh(): CatalogRefreshResult {\n\t\treturn this.lastCatalogRefresh;\n\t}\n\n\tpersistUserModels(rows: readonly UserModelEntry[]): void {\n\t\tthis.userModels.upsert(rows);\n\t\tthis.overlay.setUser(this.userModelsForStoredProviders(this.snapshot.storedProviders));\n\t\tthis.updateModelSnapshot();\n\t}\n\n\tprivate async refreshOfficialCatalog(\n\t\tallowNetwork: boolean,\n\t\tsignal?: AbortSignal,\n\t): Promise<(OfficialCatalogLoadResult & { evictedUserRows: number }) | undefined> {\n\t\tconst storedProviders = await this.listStoredProviderIds();\n\t\tconst loaded = await loadOfficialCatalog({\n\t\t\tallowNetwork,\n\t\t\tcachePath: this.officialCachePath,\n\t\t\tsignal,\n\t\t\tproviderIds: [...storedProviders],\n\t\t});\n\t\tconst evicted = this.userModels.evictOfficial(officialModelKeys(loaded.catalog));\n\t\tconst templateByProvider = new Map<string, Model<Api> | undefined>();\n\t\tconst officialModels = loaded.catalog.models.map((entry) => {\n\t\t\tif (!templateByProvider.has(entry.provider)) {\n\t\t\t\ttemplateByProvider.set(entry.provider, this.bakedInModels(entry.provider)[0]);\n\t\t\t}\n\t\t\treturn officialEntryToModel(entry, templateByProvider.get(entry.provider));\n\t\t});\n\t\tthis.overlay.setOfficial(officialModels);\n\t\tthis.overlay.setUser(this.userModelsForStoredProviders(storedProviders));\n\t\treturn { ...loaded, evictedUserRows: evicted.length };\n\t}\n\n\tprivate async restoreLiveCatalogs(): Promise<LiveCatalogResult[]> {\n\t\tconst storedProviders = await this.listStoredProviderIds();\n\t\tconst results: LiveCatalogResult[] = [];\n\t\tfor (const providerId of LIVE_LIST_PROVIDER_IDS) {\n\t\t\tconst stored = storedProviders.has(providerId) ? await this.modelsStore.read(providerId) : undefined;\n\t\t\tif (stored?.models) this.overlay.setLive(providerId, stored.models);\n\t\t\telse this.overlay.setLive(providerId, []);\n\t\t\tresults.push({\n\t\t\t\tproviderId,\n\t\t\t\tstatus: \"skipped\",\n\t\t\t\tdiscoveries: [],\n\t\t\t\tadded: 0,\n\t\t\t\ttotal: stored?.models.length ?? 0,\n\t\t\t\tincomplete: [],\n\t\t\t});\n\t\t}\n\t\treturn results;\n\t}\n\n\tprivate async refreshLiveCatalogs(officialKeys: Set<string>, signal?: AbortSignal): Promise<LiveCatalogResult[]> {\n\t\tconst storedProviders = await this.listStoredProviderIds();\n\t\tconst known = knownModelKeys(\n\t\t\tLIVE_LIST_PROVIDER_IDS.flatMap((id) => this.bakedInModels(id)),\n\t\t\tofficialKeys,\n\t\t\tthis.userModels.keys(),\n\t\t);\n\n\t\tconst results = await Promise.all(\n\t\t\tLIVE_LIST_PROVIDER_IDS.map(async (providerId) => {\n\t\t\t\tif (!storedProviders.has(providerId)) {\n\t\t\t\t\tthis.overlay.setLive(providerId, []);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"skipped\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tconst stored = await this.modelsStore.read(providerId);\n\t\t\t\tif (stored?.models) this.overlay.setLive(providerId, stored.models);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"skipped\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: stored?.models.length ?? 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t\terror: \"aborted\",\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tconst bakedIn = this.bakedInModels(providerId);\n\t\t\t\tconst provider = this.models.getProvider(providerId) ?? this.defaultBuiltins.get(providerId);\n\t\t\t\tconst baseUrl = provider?.baseUrl ?? bakedIn[0]?.baseUrl;\n\t\t\t\tif (!baseUrl) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"skipped\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tlet credential: Credential | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tcredential = await this.refreshCredentialFor(providerId);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: stored?.models.length ?? 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (!credential) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"skipped\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: stored?.models.length ?? 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tconst result = await fetchLiveProviderModels({\n\t\t\t\t\tproviderId,\n\t\t\t\t\tbaseUrl,\n\t\t\t\t\tbakedIn,\n\t\t\t\t\tcredential,\n\t\t\t\t\tknownKeys: known,\n\t\t\t\t\tsignal,\n\t\t\t\t});\n\t\t\t\tif (result.status === \"ok\") {\n\t\t\t\t\tconst overlayModels = buildLiveOverlay(bakedIn, result.discoveries);\n\t\t\t\t\tthis.overlay.setLive(providerId, overlayModels);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.modelsStore.write(providerId, { models: overlayModels, checkedAt: Date.now() });\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Store write is best-effort.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}),\n\t\t);\n\t\treturn results;\n\t}\n\n\tprivate async refreshCredentialFor(providerId: string): Promise<Credential | undefined> {\n\t\tconst stored = await this.credentials.read(providerId);\n\t\t// Same lock + persist path as chat. Returning stored OAuth here skips\n\t\t// refresh and sends expired SuperGrok tokens to GET /models (HTTP 403).\n\t\tconst resolved = await this.getAuth(providerId);\n\t\tif (resolved?.auth.apiKey) return { type: \"api_key\", key: resolved.auth.apiKey, env: resolved.env };\n\t\tif (stored?.type === \"oauth\" && stored.access) return stored;\n\t\tif (stored?.type === \"api_key\" && stored.key) return stored;\n\t\treturn undefined;\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\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.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n}\n"]}
@@ -4,6 +4,7 @@ import * as builtinProviderCatalog from "@ashx-j/lunr-ai/providers/all";
4
4
  import { getAgentDir } from "../config.js";
5
5
  import { AuthStorage as DefaultAuthStorage } from "./auth-storage.js";
6
6
  import { CatalogOverlaySource, knownModelKeys, withCatalogOverlay } from "./catalog-merge.js";
7
+ import { readGrokCliXaiOAuth, wrapXaiGrokCliCredentials } from "./grok-cli-auth.js";
7
8
  import { buildLiveOverlay, fetchLiveProviderModels, isLiveListProvider, LIVE_LIST_PROVIDER_IDS, } from "./live-catalog.js";
8
9
  import { ModelConfig } from "./model-config.js";
9
10
  import { FileModelsStore, InMemoryCodingAgentModelsStore } from "./models-store.js";
@@ -11,6 +12,7 @@ import { loadOfficialCatalog, officialCatalogCachePath, officialEntryToModel, of
11
12
  import { composeModelProvider, configuredRequestAuthStatus, resolveCompatibilityRequestConfig, resolveConfiguredModelHeaders, validateExtensionProvider, } from "./provider-composer.js";
12
13
  import { RuntimeCredentials } from "./runtime-credentials.js";
13
14
  import { SubscriptionManager } from "./subscriptions.js";
15
+ import { clearPlanUsageCache } from "./usage-service.js";
14
16
  import { UserModelsStore, userEntryToModel, userModelsPath } from "./user-models.js";
15
17
  function mergeHeaders(base, override) {
16
18
  if (!base && !override)
@@ -53,7 +55,8 @@ export class ModelRuntime {
53
55
  userModels;
54
56
  officialCachePath;
55
57
  lastCatalogRefresh = { aborted: false, errors: new Map(), live: [], incomplete: [] };
56
- constructor(credentials, config, modelsPath, modelsStore, providers, allowModelNetwork, subscriptionManager, catalogDir) {
58
+ grokHome;
59
+ constructor(credentials, config, modelsPath, modelsStore, providers, allowModelNetwork, subscriptionManager, catalogDir, grokHome) {
57
60
  this.credentials = credentials;
58
61
  this.config = config;
59
62
  this.modelsPath = modelsPath;
@@ -62,6 +65,7 @@ export class ModelRuntime {
62
65
  this.subscriptionManager = subscriptionManager;
63
66
  this.userModels = new UserModelsStore(catalogDir ? userModelsPath(catalogDir) : undefined);
64
67
  this.officialCachePath = catalogDir ? officialCatalogCachePath(catalogDir) : undefined;
68
+ this.grokHome = grokHome;
65
69
  this.defaultBuiltins = new Map(providers.map((provider) => [provider.id, provider]));
66
70
  for (const [providerId, provider] of this.defaultBuiltins)
67
71
  this.builtins.set(providerId, provider);
@@ -72,7 +76,10 @@ export class ModelRuntime {
72
76
  // lunr: keep the underlying store — the SubscriptionManager mirrors rotated
73
77
  // keys into it directly, NOT through the RuntimeCredentials overlay (a runtime
74
78
  // --api-key override would shadow the mirror there).
75
- const baseStore = options.credentials ?? DefaultAuthStorage.create(options.authPath);
79
+ const rawStore = options.credentials ?? DefaultAuthStorage.create(options.authPath);
80
+ const grokHomeDisabled = options.grokHome === null || (options.grokHome === undefined && options.credentials !== undefined);
81
+ const grokHome = grokHomeDisabled ? undefined : (options.grokHome ?? undefined);
82
+ const baseStore = grokHomeDisabled ? rawStore : wrapXaiGrokCliCredentials(rawStore, { grokHome });
76
83
  const credentials = new RuntimeCredentials(baseStore);
77
84
  // Pool persistence: subscriptions.json next to auth.json. A custom credential
78
85
  // store without an authPath (tests, SDK embeddings) gets a process-local pool
@@ -89,7 +96,7 @@ export class ModelRuntime {
89
96
  : new InMemoryCodingAgentModelsStore());
90
97
  const providers = builtinProviderCatalog.builtinProviders();
91
98
  const catalogDir = modelsPath ? dirname(modelsPath) : options.authPath ? dirname(options.authPath) : undefined;
92
- const runtime = new ModelRuntime(credentials, config, modelsPath, modelsStore, providers, options.allowModelNetwork ?? process.env.PI_OFFLINE === undefined, subscriptionManager, catalogDir);
99
+ const runtime = new ModelRuntime(credentials, config, modelsPath, modelsStore, providers, options.allowModelNetwork ?? process.env.PI_OFFLINE === undefined, subscriptionManager, catalogDir, grokHome);
93
100
  runtime.configureRadiusProviders();
94
101
  runtime.rebuildProviders();
95
102
  // lunr: create() must not wait on GitHub / provider /v1/models / a dead NIC.
@@ -389,6 +396,7 @@ export class ModelRuntime {
389
396
  }
390
397
  async login(providerId, type, interaction) {
391
398
  const credential = await this.models.login(providerId, type, interaction);
399
+ clearPlanUsageCache();
392
400
  await this.refresh({ allowNetwork: this.allowModelNetwork });
393
401
  return credential;
394
402
  }
@@ -399,8 +407,19 @@ export class ModelRuntime {
399
407
  this.overlay.setLive(providerId, []);
400
408
  // Reset credential-dependent compatibility projections before the unconfigured provider is skipped by refresh.
401
409
  this.recomposeProvider(providerId);
410
+ clearPlanUsageCache();
402
411
  await this.refresh({ allowNetwork: this.allowModelNetwork });
403
412
  }
413
+ /** Copy a live Grok CLI SuperGrok session into lunR `auth.json`. */
414
+ async importGrokCliXaiAuth() {
415
+ const grok = readGrokCliXaiOAuth({ grokHome: this.grokHome });
416
+ if (!grok)
417
+ return undefined;
418
+ const stored = await this.credentials.modify("xai", async () => grok);
419
+ clearPlanUsageCache();
420
+ await this.refresh({ allowNetwork: this.allowModelNetwork });
421
+ return stored;
422
+ }
404
423
  async reloadConfig() {
405
424
  this.config = await ModelConfig.load(this.modelsPath);
406
425
  this.configureRadiusProviders();
@@ -1 +1 @@
1
- {"version":3,"file":"model-runtime.js","sourceRoot":"","sources":["../../src/core/model-runtime.ts"],"names":[],"mappings":"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C;IAAA,CAC3C;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 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 \"@ashx-j/lunr-ai\";\nimport * as builtinProviderCatalog from \"@ashx-j/lunr-ai/providers/all\";\nimport { getAgentDir } from \"../config.ts\";\nimport { AuthStorage as DefaultAuthStorage } from \"./auth-storage.ts\";\nimport { CatalogOverlaySource, knownModelKeys, withCatalogOverlay } from \"./catalog-merge.ts\";\nimport {\n\tbuildLiveOverlay,\n\tfetchLiveProviderModels,\n\ttype IncompleteLiveModel,\n\tisLiveListProvider,\n\tLIVE_LIST_PROVIDER_IDS,\n\ttype LiveCatalogResult,\n} from \"./live-catalog.ts\";\nimport { ModelConfig } from \"./model-config.ts\";\nimport { FileModelsStore, InMemoryCodingAgentModelsStore } from \"./models-store.ts\";\nimport {\n\tloadOfficialCatalog,\n\ttype OfficialCatalogLoadResult,\n\tofficialCatalogCachePath,\n\tofficialEntryToModel,\n\tofficialModelKeys,\n} from \"./official-catalog.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 { RuntimeCredentials } from \"./runtime-credentials.ts\";\nimport { SubscriptionManager } from \"./subscriptions.ts\";\nimport { type UserModelEntry, UserModelsStore, userEntryToModel, userModelsPath } from \"./user-models.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\tallowModelNetwork?: boolean;\n\t/** Applied by callers of `refresh()`, not by `create()` (startup is cache-only). */\n\tmodelRefreshTimeoutMs?: number;\n\t/** Unused. Kept so older callers compiling against this options bag still typecheck. */\n\tcatalogBaseUrl?: string;\n\t/** lunr: subscription-key pool. Defaults to subscriptions.json next to authPath (in-memory for custom stores). */\n\tsubscriptions?: SubscriptionManager;\n}\n\nexport interface CatalogRefreshResult extends ModelsRefreshResult {\n\tofficial?: OfficialCatalogLoadResult & { evictedUserRows: number };\n\tlive: LiveCatalogResult[];\n\tincomplete: IncompleteLiveModel[];\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\t/** lunr: per-provider subscription-key pools; rotation mirrors the active key into the credential store. */\n\treadonly subscriptionManager: SubscriptionManager;\n\tprivate readonly defaultBuiltins: ReadonlyMap<string, Provider>;\n\tprivate readonly builtins = 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 allowModelNetwork: 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\tprivate readonly modelsStore: ModelsStore;\n\tprivate readonly overlay = new CatalogOverlaySource();\n\tprivate readonly userModels: UserModelsStore;\n\tprivate readonly officialCachePath: string | undefined;\n\tprivate lastCatalogRefresh: CatalogRefreshResult = { aborted: false, errors: new Map(), live: [], incomplete: [] };\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\tallowModelNetwork: boolean,\n\t\tsubscriptionManager: SubscriptionManager,\n\t\tcatalogDir: string | undefined,\n\t) {\n\t\tthis.credentials = credentials;\n\t\tthis.config = config;\n\t\tthis.modelsPath = modelsPath;\n\t\tthis.modelsStore = modelsStore;\n\t\tthis.allowModelNetwork = allowModelNetwork;\n\t\tthis.subscriptionManager = subscriptionManager;\n\t\tthis.userModels = new UserModelsStore(catalogDir ? userModelsPath(catalogDir) : undefined);\n\t\tthis.officialCachePath = catalogDir ? officialCatalogCachePath(catalogDir) : undefined;\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\t// lunr: keep the underlying store — the SubscriptionManager mirrors rotated\n\t\t// keys into it directly, NOT through the RuntimeCredentials overlay (a runtime\n\t\t// --api-key override would shadow the mirror there).\n\t\tconst baseStore = options.credentials ?? DefaultAuthStorage.create(options.authPath);\n\t\tconst credentials = new RuntimeCredentials(baseStore);\n\t\t// Pool persistence: subscriptions.json next to auth.json. A custom credential\n\t\t// store without an authPath (tests, SDK embeddings) gets a process-local pool\n\t\t// so nothing leaks into the real agent dir.\n\t\tconst subscriptionManager =\n\t\t\toptions.subscriptions ??\n\t\t\t(options.credentials && !options.authPath\n\t\t\t\t? SubscriptionManager.inMemory(baseStore)\n\t\t\t\t: SubscriptionManager.create(\n\t\t\t\t\t\tbaseStore,\n\t\t\t\t\t\toptions.authPath ? join(dirname(options.authPath), \"subscriptions.json\") : undefined,\n\t\t\t\t\t));\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 providers = builtinProviderCatalog.builtinProviders();\n\t\tconst catalogDir = modelsPath ? dirname(modelsPath) : options.authPath ? dirname(options.authPath) : undefined;\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 ?? process.env.PI_OFFLINE === undefined,\n\t\t\tsubscriptionManager,\n\t\t\tcatalogDir,\n\t\t);\n\t\truntime.configureRadiusProviders();\n\t\truntime.rebuildProviders();\n\t\t// lunr: create() must not wait on GitHub / provider /v1/models / a dead NIC.\n\t\t// Disk cache + baked-in + bundled official overlay are enough to start;\n\t\t// /refresh and the model picker still do a live refresh.\n\t\tawait runtime.refresh({ allowNetwork: false });\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([...this.builtins.keys(), ...this.config.getProviderIds(), ...this.extensionProviders.keys()]);\n\t}\n\n\tprivate recomposeProvider(providerId: string): void {\n\t\tconst base = 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 models.json/extension overlays: keep builtin auth/stream exact, then apply catalog layers.\n\t\t\tthis.models.setProvider(this.withLocalCatalog(base));\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.models.setProvider(this.withLocalCatalog(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(this.withLocalCatalog(base));\n\t\t\telse this.models.deleteProvider(providerId);\n\t\t}\n\t}\n\n\tprivate withLocalCatalog(provider: Provider): Provider {\n\t\treturn isLiveListProvider(provider.id) ? withCatalogOverlay(provider, this.overlay) : provider;\n\t}\n\n\tprivate bakedInModels(providerId: string): Model<Api>[] {\n\t\treturn [...(this.defaultBuiltins.get(providerId)?.getModels() ?? [])];\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 listStoredProviderIds(): Promise<Set<string>> {\n\t\tconst credentials = await this.credentials.list();\n\t\treturn new Set(credentials.map((entry) => entry.providerId));\n\t}\n\n\t/** `/model` lists stored creds + models.json/extension keys, never ambient envApiKeyAuth. */\n\tprivate configuredProviderIds(storedProviders: ReadonlySet<string>): Set<string> {\n\t\tconst configured = new Set(storedProviders);\n\t\tfor (const provider of this.models.getProviders()) {\n\t\t\tif (\n\t\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(provider.id), this.extensionProviders.get(provider.id))\n\t\t\t\t\t?.configured\n\t\t\t) {\n\t\t\t\tconfigured.add(provider.id);\n\t\t\t}\n\t\t}\n\t\treturn configured;\n\t}\n\n\tprivate userModelsForStoredProviders(storedProviders: ReadonlySet<string>): Model<Api>[] {\n\t\treturn this.userModels\n\t\t\t.list()\n\t\t\t.filter((row) => storedProviders.has(row.provider))\n\t\t\t.map(userEntryToModel);\n\t}\n\n\tprivate async runAvailabilityRefresh(): Promise<void> {\n\t\tconst providers = this.models.getProviders();\n\t\tconst [available, checks, storedProviders] = 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.listStoredProviderIds(),\n\t\t]);\n\t\tconst auth = new Map(checks);\n\t\tconst configuredProviders = this.configuredProviderIds(storedProviders);\n\t\tthis.snapshot = {\n\t\t\tall: [...this.models.getModels()],\n\t\t\tavailable: available.filter((model) => configuredProviders.has(model.provider)),\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders,\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 [...this.extensionProviders.keys()];\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\t/** lunr: whether a runtime --api-key override is active for the provider (it shadows auth.json). */\n\thasRuntimeApiKey(providerId: string): boolean {\n\t\treturn this.credentials.hasRuntimeApiKey(providerId);\n\t}\n\n\tasync setRuntimeApiKey(providerId: string, apiKey: string): 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({ allowNetwork: this.allowModelNetwork });\n\t}\n\n\tasync removeRuntimeApiKey(providerId: string): Promise<void> {\n\t\tthis.credentials.removeRuntimeApiKey(providerId);\n\t\tawait this.refresh({ allowNetwork: this.allowModelNetwork });\n\t}\n\n\t/** lunr: whether network model-catalog fetches are allowed (offline mode disables them). */\n\tisNetworkAllowed(): boolean {\n\t\treturn this.allowModelNetwork;\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.allowModelNetwork });\n\t\treturn credential;\n\t}\n\n\tasync logout(providerId: string): Promise<void> {\n\t\tawait this.models.logout(providerId);\n\t\tawait this.modelsStore.delete(providerId);\n\t\tthis.userModels.evictProvider(providerId);\n\t\tthis.overlay.setLive(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.allowModelNetwork });\n\t}\n\n\tasync reloadConfig(): Promise<void> {\n\t\tthis.config = await ModelConfig.load(this.modelsPath);\n\t\tthis.configureRadiusProviders();\n\t\tthis.rebuildProviders();\n\t\tawait this.refresh({ allowNetwork: this.allowModelNetwork });\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<CatalogRefreshResult> {\n\t\tconst refreshOptions = {\n\t\t\t...options,\n\t\t\tallowNetwork: options.allowNetwork ?? this.allowModelNetwork,\n\t\t};\n\t\tconst official = await this.refreshOfficialCatalog(refreshOptions.allowNetwork, refreshOptions.signal);\n\t\tconst live = refreshOptions.allowNetwork\n\t\t\t? await this.refreshLiveCatalogs(\n\t\t\t\t\tofficial ? officialModelKeys(official.catalog) : new Set(),\n\t\t\t\t\trefreshOptions.signal,\n\t\t\t\t)\n\t\t\t: await this.restoreLiveCatalogs();\n\n\t\t// Radius / local-provider / extension refreshModels hooks. Live-list\n\t\t// providers have no refreshModels, so this does not hit pi.dev.\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\tfor (const entry of live) {\n\t\t\tif (entry.status === \"error\" || entry.status === \"timeout\") {\n\t\t\t\terrors.set(entry.providerId, new Error(entry.error ?? entry.status));\n\t\t\t}\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\tconst catalogResult: CatalogRefreshResult = {\n\t\t\taborted: result.aborted,\n\t\t\terrors,\n\t\t\tofficial,\n\t\t\tlive,\n\t\t\tincomplete: live.flatMap((entry) => entry.incomplete),\n\t\t};\n\t\tthis.lastCatalogRefresh = catalogResult;\n\t\treturn catalogResult;\n\t}\n\n\tgetLastCatalogRefresh(): CatalogRefreshResult {\n\t\treturn this.lastCatalogRefresh;\n\t}\n\n\tpersistUserModels(rows: readonly UserModelEntry[]): void {\n\t\tthis.userModels.upsert(rows);\n\t\tthis.overlay.setUser(this.userModelsForStoredProviders(this.snapshot.storedProviders));\n\t\tthis.updateModelSnapshot();\n\t}\n\n\tprivate async refreshOfficialCatalog(\n\t\tallowNetwork: boolean,\n\t\tsignal?: AbortSignal,\n\t): Promise<(OfficialCatalogLoadResult & { evictedUserRows: number }) | undefined> {\n\t\tconst storedProviders = await this.listStoredProviderIds();\n\t\tconst loaded = await loadOfficialCatalog({\n\t\t\tallowNetwork,\n\t\t\tcachePath: this.officialCachePath,\n\t\t\tsignal,\n\t\t\tproviderIds: [...storedProviders],\n\t\t});\n\t\tconst evicted = this.userModels.evictOfficial(officialModelKeys(loaded.catalog));\n\t\tconst templateByProvider = new Map<string, Model<Api> | undefined>();\n\t\tconst officialModels = loaded.catalog.models.map((entry) => {\n\t\t\tif (!templateByProvider.has(entry.provider)) {\n\t\t\t\ttemplateByProvider.set(entry.provider, this.bakedInModels(entry.provider)[0]);\n\t\t\t}\n\t\t\treturn officialEntryToModel(entry, templateByProvider.get(entry.provider));\n\t\t});\n\t\tthis.overlay.setOfficial(officialModels);\n\t\tthis.overlay.setUser(this.userModelsForStoredProviders(storedProviders));\n\t\treturn { ...loaded, evictedUserRows: evicted.length };\n\t}\n\n\tprivate async restoreLiveCatalogs(): Promise<LiveCatalogResult[]> {\n\t\tconst storedProviders = await this.listStoredProviderIds();\n\t\tconst results: LiveCatalogResult[] = [];\n\t\tfor (const providerId of LIVE_LIST_PROVIDER_IDS) {\n\t\t\tconst stored = storedProviders.has(providerId) ? await this.modelsStore.read(providerId) : undefined;\n\t\t\tif (stored?.models) this.overlay.setLive(providerId, stored.models);\n\t\t\telse this.overlay.setLive(providerId, []);\n\t\t\tresults.push({\n\t\t\t\tproviderId,\n\t\t\t\tstatus: \"skipped\",\n\t\t\t\tdiscoveries: [],\n\t\t\t\tadded: 0,\n\t\t\t\ttotal: stored?.models.length ?? 0,\n\t\t\t\tincomplete: [],\n\t\t\t});\n\t\t}\n\t\treturn results;\n\t}\n\n\tprivate async refreshLiveCatalogs(officialKeys: Set<string>, signal?: AbortSignal): Promise<LiveCatalogResult[]> {\n\t\tconst storedProviders = await this.listStoredProviderIds();\n\t\tconst known = knownModelKeys(\n\t\t\tLIVE_LIST_PROVIDER_IDS.flatMap((id) => this.bakedInModels(id)),\n\t\t\tofficialKeys,\n\t\t\tthis.userModels.keys(),\n\t\t);\n\n\t\tconst results = await Promise.all(\n\t\t\tLIVE_LIST_PROVIDER_IDS.map(async (providerId) => {\n\t\t\t\tif (!storedProviders.has(providerId)) {\n\t\t\t\t\tthis.overlay.setLive(providerId, []);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"skipped\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tconst stored = await this.modelsStore.read(providerId);\n\t\t\t\tif (stored?.models) this.overlay.setLive(providerId, stored.models);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"skipped\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: stored?.models.length ?? 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t\terror: \"aborted\",\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tconst bakedIn = this.bakedInModels(providerId);\n\t\t\t\tconst provider = this.models.getProvider(providerId) ?? this.defaultBuiltins.get(providerId);\n\t\t\t\tconst baseUrl = provider?.baseUrl ?? bakedIn[0]?.baseUrl;\n\t\t\t\tif (!baseUrl) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"skipped\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tlet credential: Credential | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tcredential = await this.refreshCredentialFor(providerId);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: stored?.models.length ?? 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (!credential) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"skipped\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: stored?.models.length ?? 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tconst result = await fetchLiveProviderModels({\n\t\t\t\t\tproviderId,\n\t\t\t\t\tbaseUrl,\n\t\t\t\t\tbakedIn,\n\t\t\t\t\tcredential,\n\t\t\t\t\tknownKeys: known,\n\t\t\t\t\tsignal,\n\t\t\t\t});\n\t\t\t\tif (result.status === \"ok\") {\n\t\t\t\t\tconst overlayModels = buildLiveOverlay(bakedIn, result.discoveries);\n\t\t\t\t\tthis.overlay.setLive(providerId, overlayModels);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.modelsStore.write(providerId, { models: overlayModels, checkedAt: Date.now() });\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Store write is best-effort.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}),\n\t\t);\n\t\treturn results;\n\t}\n\n\tprivate async refreshCredentialFor(providerId: string): Promise<Credential | undefined> {\n\t\tconst stored = await this.credentials.read(providerId);\n\t\t// Same lock + persist path as chat. Returning stored OAuth here skips\n\t\t// refresh and sends expired SuperGrok tokens to GET /models (HTTP 403).\n\t\tconst resolved = await this.getAuth(providerId);\n\t\tif (resolved?.auth.apiKey) return { type: \"api_key\", key: resolved.auth.apiKey, env: resolved.env };\n\t\tif (stored?.type === \"oauth\" && stored.access) return stored;\n\t\tif (stored?.type === \"api_key\" && stored.key) return stored;\n\t\treturn undefined;\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\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.recomposeProvider(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,EAaN,YAAY,EACZ,UAAU,EAIV,WAAW,GAWX,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,sBAAsB,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,IAAI,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAC9F,OAAO,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AACpF,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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,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAAA,CAC3C;IAED,kBAAkB,CAAC,UAAkB,EAAQ;QAC5C,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC3C,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC;QACnC,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC3B,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAAA,CAC3C;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 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 \"@ashx-j/lunr-ai\";\nimport * as builtinProviderCatalog from \"@ashx-j/lunr-ai/providers/all\";\nimport { getAgentDir } from \"../config.ts\";\nimport { AuthStorage as DefaultAuthStorage } from \"./auth-storage.ts\";\nimport { CatalogOverlaySource, knownModelKeys, withCatalogOverlay } from \"./catalog-merge.ts\";\nimport { readGrokCliXaiOAuth, wrapXaiGrokCliCredentials } from \"./grok-cli-auth.ts\";\nimport {\n\tbuildLiveOverlay,\n\tfetchLiveProviderModels,\n\ttype IncompleteLiveModel,\n\tisLiveListProvider,\n\tLIVE_LIST_PROVIDER_IDS,\n\ttype LiveCatalogResult,\n} from \"./live-catalog.ts\";\nimport { ModelConfig } from \"./model-config.ts\";\nimport { FileModelsStore, InMemoryCodingAgentModelsStore } from \"./models-store.ts\";\nimport {\n\tloadOfficialCatalog,\n\ttype OfficialCatalogLoadResult,\n\tofficialCatalogCachePath,\n\tofficialEntryToModel,\n\tofficialModelKeys,\n} from \"./official-catalog.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 { RuntimeCredentials } from \"./runtime-credentials.ts\";\nimport { SubscriptionManager } from \"./subscriptions.ts\";\nimport { clearPlanUsageCache } from \"./usage-service.ts\";\nimport { type UserModelEntry, UserModelsStore, userEntryToModel, userModelsPath } from \"./user-models.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\tallowModelNetwork?: boolean;\n\t/** Applied by callers of `refresh()`, not by `create()` (startup is cache-only). */\n\tmodelRefreshTimeoutMs?: number;\n\t/** Unused. Kept so older callers compiling against this options bag still typecheck. */\n\tcatalogBaseUrl?: string;\n\t/** lunr: subscription-key pool. Defaults to subscriptions.json next to authPath (in-memory for custom stores). */\n\tsubscriptions?: SubscriptionManager;\n\t/**\n\t * Grok CLI home (`~/.grok`) used as a SuperGrok OAuth fallback.\n\t * `null` disables the fallback. Custom `credentials` default to disabled\n\t * unless this is an explicit path.\n\t */\n\tgrokHome?: string | null;\n}\n\nexport interface CatalogRefreshResult extends ModelsRefreshResult {\n\tofficial?: OfficialCatalogLoadResult & { evictedUserRows: number };\n\tlive: LiveCatalogResult[];\n\tincomplete: IncompleteLiveModel[];\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\t/** lunr: per-provider subscription-key pools; rotation mirrors the active key into the credential store. */\n\treadonly subscriptionManager: SubscriptionManager;\n\tprivate readonly defaultBuiltins: ReadonlyMap<string, Provider>;\n\tprivate readonly builtins = 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 allowModelNetwork: 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\tprivate readonly modelsStore: ModelsStore;\n\tprivate readonly overlay = new CatalogOverlaySource();\n\tprivate readonly userModels: UserModelsStore;\n\tprivate readonly officialCachePath: string | undefined;\n\tprivate lastCatalogRefresh: CatalogRefreshResult = { aborted: false, errors: new Map(), live: [], incomplete: [] };\n\tprivate readonly grokHome: 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\tallowModelNetwork: boolean,\n\t\tsubscriptionManager: SubscriptionManager,\n\t\tcatalogDir: string | undefined,\n\t\tgrokHome: string | undefined,\n\t) {\n\t\tthis.credentials = credentials;\n\t\tthis.config = config;\n\t\tthis.modelsPath = modelsPath;\n\t\tthis.modelsStore = modelsStore;\n\t\tthis.allowModelNetwork = allowModelNetwork;\n\t\tthis.subscriptionManager = subscriptionManager;\n\t\tthis.userModels = new UserModelsStore(catalogDir ? userModelsPath(catalogDir) : undefined);\n\t\tthis.officialCachePath = catalogDir ? officialCatalogCachePath(catalogDir) : undefined;\n\t\tthis.grokHome = grokHome;\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\t// lunr: keep the underlying store — the SubscriptionManager mirrors rotated\n\t\t// keys into it directly, NOT through the RuntimeCredentials overlay (a runtime\n\t\t// --api-key override would shadow the mirror there).\n\t\tconst rawStore = options.credentials ?? DefaultAuthStorage.create(options.authPath);\n\t\tconst grokHomeDisabled =\n\t\t\toptions.grokHome === null || (options.grokHome === undefined && options.credentials !== undefined);\n\t\tconst grokHome = grokHomeDisabled ? undefined : (options.grokHome ?? undefined);\n\t\tconst baseStore = grokHomeDisabled ? rawStore : wrapXaiGrokCliCredentials(rawStore, { grokHome });\n\t\tconst credentials = new RuntimeCredentials(baseStore);\n\t\t// Pool persistence: subscriptions.json next to auth.json. A custom credential\n\t\t// store without an authPath (tests, SDK embeddings) gets a process-local pool\n\t\t// so nothing leaks into the real agent dir.\n\t\tconst subscriptionManager =\n\t\t\toptions.subscriptions ??\n\t\t\t(options.credentials && !options.authPath\n\t\t\t\t? SubscriptionManager.inMemory(baseStore)\n\t\t\t\t: SubscriptionManager.create(\n\t\t\t\t\t\tbaseStore,\n\t\t\t\t\t\toptions.authPath ? join(dirname(options.authPath), \"subscriptions.json\") : undefined,\n\t\t\t\t\t));\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 providers = builtinProviderCatalog.builtinProviders();\n\t\tconst catalogDir = modelsPath ? dirname(modelsPath) : options.authPath ? dirname(options.authPath) : undefined;\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 ?? process.env.PI_OFFLINE === undefined,\n\t\t\tsubscriptionManager,\n\t\t\tcatalogDir,\n\t\t\tgrokHome,\n\t\t);\n\t\truntime.configureRadiusProviders();\n\t\truntime.rebuildProviders();\n\t\t// lunr: create() must not wait on GitHub / provider /v1/models / a dead NIC.\n\t\t// Disk cache + baked-in + bundled official overlay are enough to start;\n\t\t// /refresh and the model picker still do a live refresh.\n\t\tawait runtime.refresh({ allowNetwork: false });\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([...this.builtins.keys(), ...this.config.getProviderIds(), ...this.extensionProviders.keys()]);\n\t}\n\n\tprivate recomposeProvider(providerId: string): void {\n\t\tconst base = 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 models.json/extension overlays: keep builtin auth/stream exact, then apply catalog layers.\n\t\t\tthis.models.setProvider(this.withLocalCatalog(base));\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.models.setProvider(this.withLocalCatalog(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(this.withLocalCatalog(base));\n\t\t\telse this.models.deleteProvider(providerId);\n\t\t}\n\t}\n\n\tprivate withLocalCatalog(provider: Provider): Provider {\n\t\treturn isLiveListProvider(provider.id) ? withCatalogOverlay(provider, this.overlay) : provider;\n\t}\n\n\tprivate bakedInModels(providerId: string): Model<Api>[] {\n\t\treturn [...(this.defaultBuiltins.get(providerId)?.getModels() ?? [])];\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 listStoredProviderIds(): Promise<Set<string>> {\n\t\tconst credentials = await this.credentials.list();\n\t\treturn new Set(credentials.map((entry) => entry.providerId));\n\t}\n\n\t/** `/model` lists stored creds + models.json/extension keys, never ambient envApiKeyAuth. */\n\tprivate configuredProviderIds(storedProviders: ReadonlySet<string>): Set<string> {\n\t\tconst configured = new Set(storedProviders);\n\t\tfor (const provider of this.models.getProviders()) {\n\t\t\tif (\n\t\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(provider.id), this.extensionProviders.get(provider.id))\n\t\t\t\t\t?.configured\n\t\t\t) {\n\t\t\t\tconfigured.add(provider.id);\n\t\t\t}\n\t\t}\n\t\treturn configured;\n\t}\n\n\tprivate userModelsForStoredProviders(storedProviders: ReadonlySet<string>): Model<Api>[] {\n\t\treturn this.userModels\n\t\t\t.list()\n\t\t\t.filter((row) => storedProviders.has(row.provider))\n\t\t\t.map(userEntryToModel);\n\t}\n\n\tprivate async runAvailabilityRefresh(): Promise<void> {\n\t\tconst providers = this.models.getProviders();\n\t\tconst [available, checks, storedProviders] = 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.listStoredProviderIds(),\n\t\t]);\n\t\tconst auth = new Map(checks);\n\t\tconst configuredProviders = this.configuredProviderIds(storedProviders);\n\t\tthis.snapshot = {\n\t\t\tall: [...this.models.getModels()],\n\t\t\tavailable: available.filter((model) => configuredProviders.has(model.provider)),\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders,\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 [...this.extensionProviders.keys()];\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\t/** lunr: whether a runtime --api-key override is active for the provider (it shadows auth.json). */\n\thasRuntimeApiKey(providerId: string): boolean {\n\t\treturn this.credentials.hasRuntimeApiKey(providerId);\n\t}\n\n\tasync setRuntimeApiKey(providerId: string, apiKey: string): 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({ allowNetwork: this.allowModelNetwork });\n\t}\n\n\tasync removeRuntimeApiKey(providerId: string): Promise<void> {\n\t\tthis.credentials.removeRuntimeApiKey(providerId);\n\t\tawait this.refresh({ allowNetwork: this.allowModelNetwork });\n\t}\n\n\t/** lunr: whether network model-catalog fetches are allowed (offline mode disables them). */\n\tisNetworkAllowed(): boolean {\n\t\treturn this.allowModelNetwork;\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\tclearPlanUsageCache();\n\t\tawait this.refresh({ allowNetwork: this.allowModelNetwork });\n\t\treturn credential;\n\t}\n\n\tasync logout(providerId: string): Promise<void> {\n\t\tawait this.models.logout(providerId);\n\t\tawait this.modelsStore.delete(providerId);\n\t\tthis.userModels.evictProvider(providerId);\n\t\tthis.overlay.setLive(providerId, []);\n\t\t// Reset credential-dependent compatibility projections before the unconfigured provider is skipped by refresh.\n\t\tthis.recomposeProvider(providerId);\n\t\tclearPlanUsageCache();\n\t\tawait this.refresh({ allowNetwork: this.allowModelNetwork });\n\t}\n\n\t/** Copy a live Grok CLI SuperGrok session into lunR `auth.json`. */\n\tasync importGrokCliXaiAuth(): Promise<Credential | undefined> {\n\t\tconst grok = readGrokCliXaiOAuth({ grokHome: this.grokHome });\n\t\tif (!grok) return undefined;\n\t\tconst stored = await this.credentials.modify(\"xai\", async () => grok);\n\t\tclearPlanUsageCache();\n\t\tawait this.refresh({ allowNetwork: this.allowModelNetwork });\n\t\treturn stored;\n\t}\n\n\tasync reloadConfig(): Promise<void> {\n\t\tthis.config = await ModelConfig.load(this.modelsPath);\n\t\tthis.configureRadiusProviders();\n\t\tthis.rebuildProviders();\n\t\tawait this.refresh({ allowNetwork: this.allowModelNetwork });\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<CatalogRefreshResult> {\n\t\tconst refreshOptions = {\n\t\t\t...options,\n\t\t\tallowNetwork: options.allowNetwork ?? this.allowModelNetwork,\n\t\t};\n\t\tconst official = await this.refreshOfficialCatalog(refreshOptions.allowNetwork, refreshOptions.signal);\n\t\tconst live = refreshOptions.allowNetwork\n\t\t\t? await this.refreshLiveCatalogs(\n\t\t\t\t\tofficial ? officialModelKeys(official.catalog) : new Set(),\n\t\t\t\t\trefreshOptions.signal,\n\t\t\t\t)\n\t\t\t: await this.restoreLiveCatalogs();\n\n\t\t// Radius / local-provider / extension refreshModels hooks. Live-list\n\t\t// providers have no refreshModels, so this does not hit pi.dev.\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\tfor (const entry of live) {\n\t\t\tif (entry.status === \"error\" || entry.status === \"timeout\") {\n\t\t\t\terrors.set(entry.providerId, new Error(entry.error ?? entry.status));\n\t\t\t}\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\tconst catalogResult: CatalogRefreshResult = {\n\t\t\taborted: result.aborted,\n\t\t\terrors,\n\t\t\tofficial,\n\t\t\tlive,\n\t\t\tincomplete: live.flatMap((entry) => entry.incomplete),\n\t\t};\n\t\tthis.lastCatalogRefresh = catalogResult;\n\t\treturn catalogResult;\n\t}\n\n\tgetLastCatalogRefresh(): CatalogRefreshResult {\n\t\treturn this.lastCatalogRefresh;\n\t}\n\n\tpersistUserModels(rows: readonly UserModelEntry[]): void {\n\t\tthis.userModels.upsert(rows);\n\t\tthis.overlay.setUser(this.userModelsForStoredProviders(this.snapshot.storedProviders));\n\t\tthis.updateModelSnapshot();\n\t}\n\n\tprivate async refreshOfficialCatalog(\n\t\tallowNetwork: boolean,\n\t\tsignal?: AbortSignal,\n\t): Promise<(OfficialCatalogLoadResult & { evictedUserRows: number }) | undefined> {\n\t\tconst storedProviders = await this.listStoredProviderIds();\n\t\tconst loaded = await loadOfficialCatalog({\n\t\t\tallowNetwork,\n\t\t\tcachePath: this.officialCachePath,\n\t\t\tsignal,\n\t\t\tproviderIds: [...storedProviders],\n\t\t});\n\t\tconst evicted = this.userModels.evictOfficial(officialModelKeys(loaded.catalog));\n\t\tconst templateByProvider = new Map<string, Model<Api> | undefined>();\n\t\tconst officialModels = loaded.catalog.models.map((entry) => {\n\t\t\tif (!templateByProvider.has(entry.provider)) {\n\t\t\t\ttemplateByProvider.set(entry.provider, this.bakedInModels(entry.provider)[0]);\n\t\t\t}\n\t\t\treturn officialEntryToModel(entry, templateByProvider.get(entry.provider));\n\t\t});\n\t\tthis.overlay.setOfficial(officialModels);\n\t\tthis.overlay.setUser(this.userModelsForStoredProviders(storedProviders));\n\t\treturn { ...loaded, evictedUserRows: evicted.length };\n\t}\n\n\tprivate async restoreLiveCatalogs(): Promise<LiveCatalogResult[]> {\n\t\tconst storedProviders = await this.listStoredProviderIds();\n\t\tconst results: LiveCatalogResult[] = [];\n\t\tfor (const providerId of LIVE_LIST_PROVIDER_IDS) {\n\t\t\tconst stored = storedProviders.has(providerId) ? await this.modelsStore.read(providerId) : undefined;\n\t\t\tif (stored?.models) this.overlay.setLive(providerId, stored.models);\n\t\t\telse this.overlay.setLive(providerId, []);\n\t\t\tresults.push({\n\t\t\t\tproviderId,\n\t\t\t\tstatus: \"skipped\",\n\t\t\t\tdiscoveries: [],\n\t\t\t\tadded: 0,\n\t\t\t\ttotal: stored?.models.length ?? 0,\n\t\t\t\tincomplete: [],\n\t\t\t});\n\t\t}\n\t\treturn results;\n\t}\n\n\tprivate async refreshLiveCatalogs(officialKeys: Set<string>, signal?: AbortSignal): Promise<LiveCatalogResult[]> {\n\t\tconst storedProviders = await this.listStoredProviderIds();\n\t\tconst known = knownModelKeys(\n\t\t\tLIVE_LIST_PROVIDER_IDS.flatMap((id) => this.bakedInModels(id)),\n\t\t\tofficialKeys,\n\t\t\tthis.userModels.keys(),\n\t\t);\n\n\t\tconst results = await Promise.all(\n\t\t\tLIVE_LIST_PROVIDER_IDS.map(async (providerId) => {\n\t\t\t\tif (!storedProviders.has(providerId)) {\n\t\t\t\t\tthis.overlay.setLive(providerId, []);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"skipped\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tconst stored = await this.modelsStore.read(providerId);\n\t\t\t\tif (stored?.models) this.overlay.setLive(providerId, stored.models);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"skipped\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: stored?.models.length ?? 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t\terror: \"aborted\",\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tconst bakedIn = this.bakedInModels(providerId);\n\t\t\t\tconst provider = this.models.getProvider(providerId) ?? this.defaultBuiltins.get(providerId);\n\t\t\t\tconst baseUrl = provider?.baseUrl ?? bakedIn[0]?.baseUrl;\n\t\t\t\tif (!baseUrl) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"skipped\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tlet credential: Credential | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tcredential = await this.refreshCredentialFor(providerId);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: stored?.models.length ?? 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (!credential) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\tstatus: \"skipped\" as const,\n\t\t\t\t\t\tdiscoveries: [],\n\t\t\t\t\t\tadded: 0,\n\t\t\t\t\t\ttotal: stored?.models.length ?? 0,\n\t\t\t\t\t\tincomplete: [],\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tconst result = await fetchLiveProviderModels({\n\t\t\t\t\tproviderId,\n\t\t\t\t\tbaseUrl,\n\t\t\t\t\tbakedIn,\n\t\t\t\t\tcredential,\n\t\t\t\t\tknownKeys: known,\n\t\t\t\t\tsignal,\n\t\t\t\t});\n\t\t\t\tif (result.status === \"ok\") {\n\t\t\t\t\tconst overlayModels = buildLiveOverlay(bakedIn, result.discoveries);\n\t\t\t\t\tthis.overlay.setLive(providerId, overlayModels);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.modelsStore.write(providerId, { models: overlayModels, checkedAt: Date.now() });\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Store write is best-effort.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}),\n\t\t);\n\t\treturn results;\n\t}\n\n\tprivate async refreshCredentialFor(providerId: string): Promise<Credential | undefined> {\n\t\tconst stored = await this.credentials.read(providerId);\n\t\t// Same lock + persist path as chat. Returning stored OAuth here skips\n\t\t// refresh and sends expired SuperGrok tokens to GET /models (HTTP 403).\n\t\tconst resolved = await this.getAuth(providerId);\n\t\tif (resolved?.auth.apiKey) return { type: \"api_key\", key: resolved.auth.apiKey, env: resolved.env };\n\t\tif (stored?.type === \"oauth\" && stored.access) return stored;\n\t\tif (stored?.type === \"api_key\" && stored.key) return stored;\n\t\treturn undefined;\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\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.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"xai.d.ts","sourceRoot":"","sources":["../../../src/core/usage-adapters/xai.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,KAAK,EAAE,SAAS,EAAmB,MAAM,qBAAqB,CAAC;AA+BtE,wBAAsB,iBAAiB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC,CAsC7F","sourcesContent":["/**\n * xAI Grok (SuperGrok / X Premium) weekly plan usage.\n *\n * `GET https://cli-chat-proxy.grok.com/v1/billing?format=credits` with the\n * OAuth access token (Grok CLI identity header required). Official Grok\n * Build `/usage` and grok.com Settings → Usage read the same weekly pool:\n * config.creditUsagePercent + config.currentPeriod.end\n *\n * Extra Usage Credits (`onDemandCap` > 0) are a secondary window only.\n * `monthlyLimit` / `includedUsed` / `billingPeriodEnd` are the old monthly\n * Extra Usage envelope — never treated as the subscription plan.\n *\n * Pay-as-you-go API keys have no quota endpoint. OAuth-only; any failure\n * or shape mismatch resolves to `undefined` (caller hides the plan section).\n * First-party undocumented protocol — re-smoke against a real OAuth token\n * after xAI changes the billing payload.\n */\n\nimport type { ModelRuntime } from \"../model-runtime.ts\";\nimport type { PlanUsage, PlanUsageWindow } from \"../usage-service.ts\";\nimport {\n\tasObject,\n\tasString,\n\tclampPercent,\n\tfetchWithTimeout,\n\ttoEpochMs,\n\tunwrapVal,\n\tusedPercentFromUsed,\n} from \"./shared.ts\";\n\nconst XAI_PROVIDER_ID = \"xai\";\nconst XAI_BILLING_URL = \"https://cli-chat-proxy.grok.com/v1/billing?format=credits\";\n\nfunction currentPeriod(config: Record<string, unknown>): Record<string, unknown> | undefined {\n\treturn asObject(config.currentPeriod) ?? asObject(config.current_period);\n}\n\nfunction weeklyWindow(config: Record<string, unknown>): PlanUsageWindow | undefined {\n\tconst period = currentPeriod(config);\n\tconst raw = unwrapVal(config.creditUsagePercent ?? config.credit_usage_percent);\n\t// Omitted proto3 percent + a live currentPeriod means 0% used (CodexBar).\n\tif (raw === undefined && !period) return undefined;\n\tconst usedPercent = raw === undefined ? 0 : clampPercent(raw);\n\treturn {\n\t\tlabel: \"Weekly\",\n\t\tusedPercent,\n\t\tresetsAt: toEpochMs(period?.end),\n\t};\n}\n\nexport async function fetchXaiPlanUsage(runtime: ModelRuntime): Promise<PlanUsage | undefined> {\n\tif (!runtime.isUsingOAuth(XAI_PROVIDER_ID)) return undefined;\n\n\tconst resolution = await runtime.getAuth(XAI_PROVIDER_ID);\n\tconst accessToken = resolution?.auth.apiKey;\n\tif (!accessToken) return undefined;\n\n\tconst response = await fetchWithTimeout(XAI_BILLING_URL, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${accessToken}`,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"x-xai-token-auth\": \"xai-grok-cli\",\n\t\t},\n\t});\n\tif (!response.ok) return undefined;\n\tconst payload = asObject(await response.json());\n\tif (!payload) return undefined;\n\tconst config = asObject(payload.config) ?? payload;\n\n\tconst windows: PlanUsageWindow[] = [];\n\tconst weekly = weeklyWindow(config);\n\tif (weekly) windows.push(weekly);\n\n\tconst onDemandCap = unwrapVal(config.onDemandCap);\n\tif (onDemandCap !== undefined && onDemandCap > 0) {\n\t\tconst usedPercent = usedPercentFromUsed(onDemandCap, unwrapVal(config.onDemandUsed) ?? 0);\n\t\tif (usedPercent !== undefined) {\n\t\t\twindows.push({\n\t\t\t\tlabel: \"Extra\",\n\t\t\t\tusedPercent,\n\t\t\t\tresetsAt: weekly?.resetsAt,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (windows.length === 0) return undefined;\n\tconst planLabel = asString(config.subscriptionTier) ?? asString(config.subscription_tier);\n\treturn { provider: XAI_PROVIDER_ID, planLabel, windows };\n}\n"]}
1
+ {"version":3,"file":"xai.d.ts","sourceRoot":"","sources":["../../../src/core/usage-adapters/xai.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,KAAK,EAAE,SAAS,EAAmB,MAAM,qBAAqB,CAAC;AA+BtE,wBAAsB,iBAAiB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC,CAyC7F","sourcesContent":["/**\n * xAI Grok (SuperGrok / X Premium) weekly plan usage.\n *\n * `GET https://cli-chat-proxy.grok.com/v1/billing?format=credits` with the\n * OAuth access token (Grok CLI identity header required). Official Grok\n * Build `/usage` and grok.com Settings → Usage read the same weekly pool:\n * config.creditUsagePercent + config.currentPeriod.end\n *\n * Extra Usage Credits (`onDemandCap` > 0) are a secondary window only.\n * `monthlyLimit` / `includedUsed` / `billingPeriodEnd` are the old monthly\n * Extra Usage envelope — never treated as the subscription plan.\n *\n * Pay-as-you-go API keys have no quota endpoint. OAuth-only; any failure\n * or shape mismatch resolves to `undefined` (caller hides the plan section).\n * First-party undocumented protocol — re-smoke against a real OAuth token\n * after xAI changes the billing payload.\n */\n\nimport { ModelsError } from \"@ashx-j/lunr-ai\";\nimport type { ModelRuntime } from \"../model-runtime.ts\";\nimport type { PlanUsage, PlanUsageWindow } from \"../usage-service.ts\";\nimport {\n\tasObject,\n\tasString,\n\tclampPercent,\n\tfetchWithTimeout,\n\ttoEpochMs,\n\tunwrapVal,\n\tusedPercentFromUsed,\n} from \"./shared.ts\";\n\nconst XAI_PROVIDER_ID = \"xai\";\nconst XAI_BILLING_URL = \"https://cli-chat-proxy.grok.com/v1/billing?format=credits\";\n\nfunction currentPeriod(config: Record<string, unknown>): Record<string, unknown> | undefined {\n\treturn asObject(config.currentPeriod) ?? asObject(config.current_period);\n}\n\nfunction weeklyWindow(config: Record<string, unknown>): PlanUsageWindow | undefined {\n\tconst period = currentPeriod(config);\n\tconst raw = unwrapVal(config.creditUsagePercent ?? config.credit_usage_percent);\n\t// Omitted proto3 percent + a live currentPeriod means 0% used (CodexBar).\n\tif (raw === undefined && !period) return undefined;\n\tconst usedPercent = raw === undefined ? 0 : clampPercent(raw);\n\treturn {\n\t\tlabel: \"Weekly\",\n\t\tusedPercent,\n\t\tresetsAt: toEpochMs(period?.end),\n\t};\n}\n\nexport async function fetchXaiPlanUsage(runtime: ModelRuntime): Promise<PlanUsage | undefined> {\n\tif (!runtime.isUsingOAuth(XAI_PROVIDER_ID)) return undefined;\n\n\tconst resolution = await runtime.getAuth(XAI_PROVIDER_ID);\n\tconst accessToken = resolution?.auth.apiKey;\n\tif (!accessToken) return undefined;\n\n\tconst response = await fetchWithTimeout(XAI_BILLING_URL, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${accessToken}`,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"x-xai-token-auth\": \"xai-grok-cli\",\n\t\t},\n\t});\n\tif (response.status === 401 || response.status === 403) {\n\t\tthrow new ModelsError(\"oauth\", `xAI billing rejected the session (HTTP ${response.status})`);\n\t}\n\tif (!response.ok) return undefined;\n\tconst payload = asObject(await response.json());\n\tif (!payload) return undefined;\n\tconst config = asObject(payload.config) ?? payload;\n\n\tconst windows: PlanUsageWindow[] = [];\n\tconst weekly = weeklyWindow(config);\n\tif (weekly) windows.push(weekly);\n\n\tconst onDemandCap = unwrapVal(config.onDemandCap);\n\tif (onDemandCap !== undefined && onDemandCap > 0) {\n\t\tconst usedPercent = usedPercentFromUsed(onDemandCap, unwrapVal(config.onDemandUsed) ?? 0);\n\t\tif (usedPercent !== undefined) {\n\t\t\twindows.push({\n\t\t\t\tlabel: \"Extra\",\n\t\t\t\tusedPercent,\n\t\t\t\tresetsAt: weekly?.resetsAt,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (windows.length === 0) return undefined;\n\tconst planLabel = asString(config.subscriptionTier) ?? asString(config.subscription_tier);\n\treturn { provider: XAI_PROVIDER_ID, planLabel, windows };\n}\n"]}
@@ -15,6 +15,7 @@
15
15
  * First-party undocumented protocol — re-smoke against a real OAuth token
16
16
  * after xAI changes the billing payload.
17
17
  */
18
+ import { ModelsError } from "@ashx-j/lunr-ai";
18
19
  import { asObject, asString, clampPercent, fetchWithTimeout, toEpochMs, unwrapVal, usedPercentFromUsed, } from "./shared.js";
19
20
  const XAI_PROVIDER_ID = "xai";
20
21
  const XAI_BILLING_URL = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
@@ -48,6 +49,9 @@ export async function fetchXaiPlanUsage(runtime) {
48
49
  "x-xai-token-auth": "xai-grok-cli",
49
50
  },
50
51
  });
52
+ if (response.status === 401 || response.status === 403) {
53
+ throw new ModelsError("oauth", `xAI billing rejected the session (HTTP ${response.status})`);
54
+ }
51
55
  if (!response.ok)
52
56
  return undefined;
53
57
  const payload = asObject(await response.json());