@draht/ai 2026.10.4-3 → 2026.10.8-1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -17
- package/dist/models.d.ts +1 -1
- package/dist/models.js +1 -1
- package/dist/models.js.map +1 -1
- package/dist/utils/oauth-page.js +1 -1
- package/dist/utils/oauth-page.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -83,7 +83,7 @@ TypeBox exports are re-exported from `@draht/ai`: `Type`, `Static`, and `TSchema
|
|
|
83
83
|
import { Type, getModel, stream, complete, Context, Tool, StringEnum } from '@draht/ai';
|
|
84
84
|
|
|
85
85
|
// Fully typed with auto-complete support for both providers and models
|
|
86
|
-
const model = getModel('openai', 'gpt-
|
|
86
|
+
const model = getModel('openai', 'gpt-6-luna');
|
|
87
87
|
|
|
88
88
|
// Define tools with TypeBox schemas for type safety and validation
|
|
89
89
|
const tools: Tool[] = [{
|
|
@@ -388,7 +388,7 @@ Models with vision capabilities can process images. You can check if a model sup
|
|
|
388
388
|
import { readFileSync } from 'fs';
|
|
389
389
|
import { getModel, complete } from '@draht/ai';
|
|
390
390
|
|
|
391
|
-
const model = getModel('openai', 'gpt-
|
|
391
|
+
const model = getModel('openai', 'gpt-6-luna');
|
|
392
392
|
|
|
393
393
|
// Check if model supports images
|
|
394
394
|
if (model.input.includes('image')) {
|
|
@@ -426,10 +426,10 @@ Many models support thinking/reasoning capabilities where they can show their in
|
|
|
426
426
|
import { getModel, streamSimple, completeSimple } from '@draht/ai';
|
|
427
427
|
|
|
428
428
|
// Many models across providers support thinking/reasoning
|
|
429
|
-
const model = getModel('anthropic', 'claude-sonnet-
|
|
429
|
+
const model = getModel('anthropic', 'claude-sonnet-5');
|
|
430
430
|
// or getModel('openai', 'gpt-5-mini');
|
|
431
431
|
// or getModel('google', 'gemini-2.5-flash');
|
|
432
|
-
// or getModel('xai', 'grok-
|
|
432
|
+
// or getModel('xai', 'grok-4.7');
|
|
433
433
|
// or getModel('groq', 'openai/gpt-oss-20b');
|
|
434
434
|
// or getModel('cerebras', 'gpt-oss-120b');
|
|
435
435
|
// or getModel('openrouter', 'z-ai/glm-4.5v');
|
|
@@ -470,11 +470,11 @@ await complete(openaiModel, context, {
|
|
|
470
470
|
reasoningSummary: 'detailed' // OpenAI Responses API only
|
|
471
471
|
});
|
|
472
472
|
|
|
473
|
-
// Anthropic Thinking (Claude Sonnet
|
|
474
|
-
const anthropicModel = getModel('anthropic', 'claude-sonnet-
|
|
473
|
+
// Anthropic Thinking (Claude Sonnet 5)
|
|
474
|
+
const anthropicModel = getModel('anthropic', 'claude-sonnet-5');
|
|
475
475
|
await complete(anthropicModel, context, {
|
|
476
476
|
thinkingEnabled: true,
|
|
477
|
-
|
|
477
|
+
effort: 'medium' // Adaptive thinking models ignore thinkingBudgetTokens
|
|
478
478
|
});
|
|
479
479
|
|
|
480
480
|
// Google Gemini Thinking
|
|
@@ -552,7 +552,7 @@ The abort signal allows you to cancel in-progress requests. Aborted requests hav
|
|
|
552
552
|
```typescript
|
|
553
553
|
import { getModel, stream } from '@draht/ai';
|
|
554
554
|
|
|
555
|
-
const model = getModel('openai', 'gpt-
|
|
555
|
+
const model = getModel('openai', 'gpt-6-luna');
|
|
556
556
|
const controller = new AbortController();
|
|
557
557
|
|
|
558
558
|
// Abort after 2 seconds
|
|
@@ -751,7 +751,7 @@ for (const model of anthropicModels) {
|
|
|
751
751
|
}
|
|
752
752
|
|
|
753
753
|
// Get a specific model (both provider and model ID are auto-completed in IDEs)
|
|
754
|
-
const model = getModel('openai', 'gpt-
|
|
754
|
+
const model = getModel('openai', 'gpt-6-luna');
|
|
755
755
|
console.log(`Using ${model.name} via ${model.api} API`);
|
|
756
756
|
```
|
|
757
757
|
|
|
@@ -879,11 +879,11 @@ Models are typed by their API, which keeps the model metadata accurate. Provider
|
|
|
879
879
|
import { streamAnthropic, type AnthropicOptions } from '@draht/ai';
|
|
880
880
|
|
|
881
881
|
// TypeScript knows this is an Anthropic model
|
|
882
|
-
const claude = getModel('anthropic', 'claude-sonnet-
|
|
882
|
+
const claude = getModel('anthropic', 'claude-sonnet-5');
|
|
883
883
|
|
|
884
884
|
const options: AnthropicOptions = {
|
|
885
885
|
thinkingEnabled: true,
|
|
886
|
-
|
|
886
|
+
effort: 'medium'
|
|
887
887
|
};
|
|
888
888
|
|
|
889
889
|
await streamAnthropic(claude, context, options);
|
|
@@ -908,7 +908,7 @@ When messages from one provider are sent to a different provider, the library au
|
|
|
908
908
|
import { getModel, complete, Context } from '@draht/ai';
|
|
909
909
|
|
|
910
910
|
// Start with Claude
|
|
911
|
-
const claude = getModel('anthropic', 'claude-sonnet-
|
|
911
|
+
const claude = getModel('anthropic', 'claude-sonnet-5');
|
|
912
912
|
const context: Context = {
|
|
913
913
|
messages: []
|
|
914
914
|
};
|
|
@@ -960,7 +960,7 @@ const context: Context = {
|
|
|
960
960
|
]
|
|
961
961
|
};
|
|
962
962
|
|
|
963
|
-
const model = getModel('openai', 'gpt-
|
|
963
|
+
const model = getModel('openai', 'gpt-6-luna');
|
|
964
964
|
const response = await complete(model, context);
|
|
965
965
|
context.messages.push(response);
|
|
966
966
|
|
|
@@ -976,7 +976,7 @@ const restored: Context = JSON.parse(localStorage.getItem('conversation')!);
|
|
|
976
976
|
restored.messages.push({ role: 'user', content: 'Tell me more about its type system' });
|
|
977
977
|
|
|
978
978
|
// Continue with any model
|
|
979
|
-
const newModel = getModel('anthropic', 'claude-
|
|
979
|
+
const newModel = getModel('anthropic', 'claude-haiku-4-5');
|
|
980
980
|
const continuation = await complete(newModel, restored);
|
|
981
981
|
```
|
|
982
982
|
|
|
@@ -990,7 +990,7 @@ The library supports browser environments. You must pass the API key explicitly
|
|
|
990
990
|
import { getModel, complete } from '@draht/ai';
|
|
991
991
|
|
|
992
992
|
// API key must be passed explicitly in browser
|
|
993
|
-
const model = getModel('anthropic', 'claude-
|
|
993
|
+
const model = getModel('anthropic', 'claude-haiku-4-5');
|
|
994
994
|
|
|
995
995
|
const response = await complete(model, {
|
|
996
996
|
messages: [{ role: 'user', content: 'Hello!' }]
|
|
@@ -1035,7 +1035,7 @@ When set, the library automatically uses these keys:
|
|
|
1035
1035
|
|
|
1036
1036
|
```typescript
|
|
1037
1037
|
// Uses OPENAI_API_KEY from environment
|
|
1038
|
-
const model = getModel('openai', 'gpt-
|
|
1038
|
+
const model = getModel('openai', 'gpt-6-luna');
|
|
1039
1039
|
const response = await complete(model, context);
|
|
1040
1040
|
|
|
1041
1041
|
// Or override with explicit key
|
|
@@ -1205,7 +1205,7 @@ auth['github-copilot'] = { type: 'oauth', ...result.newCredentials };
|
|
|
1205
1205
|
writeFileSync('auth.json', JSON.stringify(auth, null, 2));
|
|
1206
1206
|
|
|
1207
1207
|
// Use the API key
|
|
1208
|
-
const model = getModel('github-copilot', 'gpt-
|
|
1208
|
+
const model = getModel('github-copilot', 'gpt-6.1-sol');
|
|
1209
1209
|
const response = await complete(model, {
|
|
1210
1210
|
messages: [{ role: 'user', content: 'Hello!' }]
|
|
1211
1211
|
}, { apiKey: result.apiKey });
|
package/dist/models.d.ts
CHANGED
|
@@ -249,7 +249,7 @@ export declare function createProvider<TApi extends Api = Api>(input: CreateProv
|
|
|
249
249
|
* Runtime-checked narrowing for dynamically looked-up models:
|
|
250
250
|
*
|
|
251
251
|
* ```ts
|
|
252
|
-
* const model = models.getModel("anthropic", "claude-opus-
|
|
252
|
+
* const model = models.getModel("anthropic", "claude-opus-5-5");
|
|
253
253
|
* if (model && hasApi(model, "anthropic-messages")) {
|
|
254
254
|
* // model: Model<"anthropic-messages">, stream options fully typed
|
|
255
255
|
* }
|
package/dist/models.js
CHANGED
|
@@ -646,7 +646,7 @@ export function createProvider(input) {
|
|
|
646
646
|
* Runtime-checked narrowing for dynamically looked-up models:
|
|
647
647
|
*
|
|
648
648
|
* ```ts
|
|
649
|
-
* const model = models.getModel("anthropic", "claude-opus-
|
|
649
|
+
* const model = models.getModel("anthropic", "claude-opus-5-5");
|
|
650
650
|
* if (model && hasApi(model, "anthropic-messages")) {
|
|
651
651
|
* // model: Model<"anthropic-messages">, stream options fully typed
|
|
652
652
|
* }
|
package/dist/models.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"models.js","sourceRoot":"","sources":["../src/models.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,0BAA0B,IAAI,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACrF,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EAAgC,WAAW,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAanG,OAAO,EAAE,mBAAmB,EAA2C,MAAM,mBAAmB,CAAC;AAmCjG,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,EACN,eAAe,EACf,qBAAqB,EACrB,gBAAgB,EAChB,qBAAqB,EACrB,YAAY,EACZ,gBAAgB,EAChB,WAAW,GACX,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD,OAAO,EAAE,WAAW,EAAwB,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAqDxE,MAAM,iBAAiB,GAA4B,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC;AAEjG,0FAA0F;AAC1F,SAAS,iBAAiB,CAAC,KAAe;IACzC,OAAO,MAAM,CAAC,MAAM,CAAC,iBAAiB,EAAE,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC;AAC9D,CAAC;AAED,iEAAiE;AACjE,SAAS,mBAAmB,CAAC,KAAuB;IACnD,OAAO,EAAE,GAAG,KAAK,EAAE,MAAM,EAAE,KAAK,CAA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,CAAmB,KAAkB;IAC/D,OAAO,CACN,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC;QAC7B,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC;QAC7B,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC;QAC7B,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC,CAC7B,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,CAA8B,EAAE,CAA8B;IAC5F,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC;QAAE,OAAO,KAAK,CAAC;IAC3B,OAAO,YAAY,CAAC,CAAC,CAAC,KAAK,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,QAAQ,KAAK,CAAC,CAAC,QAAQ,CAAC;AAC1F,CAAC","sourcesContent":["import { lazyStream } from \"./api/lazy.ts\";\nimport { defaultProviderAuthContext as defaultAuthContext } from \"./auth/context.ts\";\nimport { InMemoryCredentialStore } from \"./auth/credential-store.ts\";\nimport { type AuthResolutionOverrides, ModelsError, resolveProviderAuth } from \"./auth/resolve.ts\";\nimport type {\n\tAuthCheck,\n\tAuthContext,\n\tAuthInteraction,\n\tAuthOperationOptions,\n\tAuthResult,\n\tAuthType,\n\tCredential,\n\tCredentialStore,\n\tLoginOptions,\n\tProviderAuth,\n} from \"./auth/types.ts\";\nimport { InMemoryModelsStore, type ModelsStore, type ModelsStoreEntry } from \"./models-store.ts\";\nimport type {\n\tAnyModel,\n\tApi,\n\tApiStreamOptions,\n\tAssistantImages,\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tClassifierApi,\n\tClassifierContext,\n\tClassifierModel,\n\tClassifierOptions,\n\tClassifierResult,\n\tContext,\n\tDeferredCancelOptions,\n\tDeferredFetchOptions,\n\tDeferredHandle,\n\tImageApi,\n\tImageModel,\n\tImagesContext,\n\tImagesOptions,\n\tModel,\n\tModelCostRates,\n\tModelThinkingLevel,\n\tModelType,\n\tModelTypeMap,\n\tProviderClassifier,\n\tProviderHeaders,\n\tProviderImages,\n\tProviderRequestOptions,\n\tProviderStreams,\n\tSimpleStreamOptions,\n\tTranscriptContext,\n\tUsage,\n} from \"./types.ts\";\nimport { operationSignal, raceWithAbortSignal } from \"./utils/abort.ts\";\nimport {\n\tassertChatModel,\n\tassertClassifierModel,\n\tassertImageModel,\n\tclassifierErrorResult,\n\tgetModelType,\n\timageErrorResult,\n\tisModelType,\n} from \"./utils/model-operations.ts\";\nimport { normalizeContext } from \"./utils/transcript.ts\";\n\nexport { ModelsError, type ModelsErrorCode } from \"./auth/resolve.ts\";\nexport { getModelType, isModelType } from \"./utils/model-operations.ts\";\n\nexport interface ModelsPublication {\n\t/** Provider-selected persisted catalog. Omit to leave storage unchanged; null deletes it. */\n\tpersist?: ModelsStoreEntry | null;\n\t/** Optional synchronous update of provider-private in-memory catalog state. */\n\tupdate?: () => void;\n}\n\nexport interface RefreshModelsContext {\n\t/** Effective configured credential. OAuth credentials are refreshed before network access. */\n\tcredential?: Credential;\n\t/** Immutable provider-scoped catalog snapshot captured before this refresh phase. */\n\tstored?: Readonly<ModelsStoreEntry>;\n\t/**\n\t * Generation-checked publication. Persistence policy remains provider-owned;\n\t * the update runs synchronously only after the selected persistence mutation.\n\t */\n\tpublish(publication: ModelsPublication): Promise<boolean>;\n\t/** False during offline/cache-only initialization. */\n\tallowNetwork: boolean;\n\t/** Bypass provider freshness checks and fetch immediately when network access is allowed. */\n\tforce?: boolean;\n\t/** Always present, including when the public refresh caller omits its optional signal. */\n\tsignal: AbortSignal;\n}\n\nexport interface ModelsRefreshOptions {\n\tallowNetwork?: boolean;\n\t/** Restrict refresh to these provider IDs. Unknown and static providers are ignored. */\n\tproviders?: readonly string[];\n\t/** Bypass provider freshness checks and fetch immediately when network access is allowed. */\n\tforce?: boolean;\n\tsignal?: AbortSignal;\n}\n\nexport interface ModelsRefreshResult {\n\taborted: boolean;\n\terrors: ReadonlyMap<string, Error>;\n}\n\nexport interface ModelsRequestTransforms {\n\t/** Transform fully assembled model/auth/request headers before provider dispatch. */\n\ttransformHeaders?: (headers: ProviderHeaders) => ProviderHeaders | Promise<ProviderHeaders>;\n}\n\nexport type ModelsApiStreamOptions<TApi extends Api> = ApiStreamOptions<TApi> & ModelsRequestTransforms;\nexport type ModelsSimpleStreamOptions = SimpleStreamOptions & ModelsRequestTransforms;\nexport type ModelsDeferredFetchOptions = DeferredFetchOptions & ModelsRequestTransforms;\nexport type ModelsDeferredCancelOptions = DeferredCancelOptions & ModelsRequestTransforms;\nexport type ModelsImagesOptions = ImagesOptions & ModelsRequestTransforms;\nexport type ModelsClassifierOptions = ClassifierOptions & ModelsRequestTransforms;\n\nconst KNOWN_MODEL_TYPES: Record<ModelType, true> = { chat: true, image: true, classifier: true };\n\n/** Models from stores and remote sources may have types that only newer versions know. */\nfunction hasKnownModelType(model: AnyModel): boolean {\n\treturn Object.hasOwn(KNOWN_MODEL_TYPES, getModelType(model));\n}\n\n/** Drops stored models whose type this version does not know. */\nfunction withKnownModelTypes(entry: ModelsStoreEntry): ModelsStoreEntry {\n\treturn { ...entry, models: entry.models.filter(hasKnownModelType) };\n}\n\n/** Any model a provider with chat APIs `TApi` can list. */\ntype ProviderModel<TApi extends Api> = Model<TApi> | ImageModel<ImageApi> | ClassifierModel<ClassifierApi>;\n\n/**\n * A provider is the concrete runtime unit. It owns id/name/base metadata,\n * auth methods, model listing, and the operations its models support\n * (streaming, image generation, classification).\n *\n * `TApi` lets concrete provider factories declare which chat APIs their models\n * use (e.g. `openaiProvider(): Provider<\"openai-responses\" | \"openai-completions\">`),\n * giving typed chat model lists to direct factory users. Other model types use\n * their operation-specific API unions. Inside a `Models` collection providers\n * are held as `Provider<Api>`.\n */\nexport interface Provider<TApi extends Api = Api> {\n\treadonly id: string;\n\treadonly name: string;\n\n\treadonly baseUrl?: string;\n\treadonly headers?: ProviderHeaders;\n\n\t/**\n\t * Required: at least one of `apiKey`/`oauth`. Every provider has auth\n\t * semantics — even providers with only ambient credentials (env vars, AWS\n\t * profiles, ADC files) and keyless local servers provide `apiKey` auth\n\t * whose `resolve()` reports whether the provider is configured.\n\t * `Models.getAuth()` returns undefined when the provider is unconfigured.\n\t */\n\treadonly auth: ProviderAuth;\n\n\t/**\n\t * Current known chat models, sync. Static providers return their catalog;\n\t * dynamic providers return the list as of the last `refreshModels()` (empty\n\t * before the first). Must not throw; `Models` treats a throwing\n\t * implementation as having no models.\n\t */\n\tgetModels(): readonly Model<TApi>[];\n\n\t/**\n\t * Current known models of every type, sync, with the same contract as\n\t * `getModels()`. Providers with only chat models may omit it; `Models` then\n\t * uses `getModels()`. Model ids are unique within each type; one upstream\n\t * model may have separate entries for different operations.\n\t */\n\tgetAllModels?(): readonly ProviderModel<TApi>[];\n\n\t/**\n\t * Dynamic providers only: restore `context.stored` and optionally fetch a newer list using\n\t * the effective credential. Implementations retain their previous list on failure, publish\n\t * persistence and synchronous state changes through `context.publish()`, and honor the\n\t * shared abort signal for blocking work.\n\t */\n\trefreshModels?(context: RefreshModelsContext): Promise<void>;\n\n\t/**\n\t * Optional provider policy for credential-specific model availability.\n\t * `getModels()` remains the complete synchronous chat catalog; `Models.getAvailable()`\n\t * applies this filter after confirming that provider auth is configured.\n\t */\n\tfilterModels?(models: readonly Model<TApi>[], credential: Credential | undefined): readonly Model<TApi>[];\n\n\t/**\n\t * Optional credential-specific availability policy across every model type.\n\t * Without it, `Models.getAllAvailable()` applies `filterModels` to chat models\n\t * and keeps every other model.\n\t */\n\tfilterAllModels?(\n\t\tmodels: readonly ProviderModel<TApi>[],\n\t\tcredential: Credential | undefined,\n\t): readonly ProviderModel<TApi>[];\n\n\t/** Stream a normalized transcript. `Models` normalizes the caller's `Context` before dispatching here. */\n\tstream<T extends TApi>(\n\t\tmodel: Model<T>,\n\t\tcontext: TranscriptContext,\n\t\toptions?: ApiStreamOptions<T>,\n\t): AssistantMessageEventStream;\n\n\tstreamSimple(\n\t\tmodel: Model<TApi>,\n\t\tcontext: TranscriptContext,\n\t\toptions?: SimpleStreamOptions,\n\t): AssistantMessageEventStream;\n\tfetchDeferred?(\n\t\tmodel: Model<TApi>,\n\t\thandle: DeferredHandle,\n\t\toptions?: DeferredFetchOptions,\n\t): AssistantMessageEventStream;\n\tcancelDeferred?(model: Model<TApi>, handle: DeferredHandle, options?: DeferredCancelOptions): Promise<void>;\n\n\t/** Present when the provider supports dedicated image models. Never rejects. */\n\tgenerateImages?(\n\t\tmodel: ImageModel<ImageApi>,\n\t\tcontext: ImagesContext,\n\t\toptions?: ImagesOptions,\n\t): Promise<AssistantImages>;\n\n\t/** Present when the provider supports structured classifier models. Never rejects. */\n\tclassify?(\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ClassifierOptions,\n\t): Promise<ClassifierResult>;\n}\n\n/**\n * Runtime collection of providers plus auth application and request\n * convenience. Providers own request behavior; `Models` resolves auth and\n * delegates each request to the provider that owns the model.\n *\n * Read accessors come in three flavors: the unqualified ones (`getModels`,\n * `getModel`, `getAvailable`) return chat models, the `*OfType` accessors\n * return one model type, and `getAllModels`/`getAllAvailable` return every type.\n */\nexport interface Models {\n\tgetProviders(): readonly Provider[];\n\tgetProvider(id: string): Provider | undefined;\n\n\t/**\n\t * Sync read of last-known chat models from one provider or all providers.\n\t * Best-effort: a provider whose `getModels()` throws yields no models.\n\t */\n\tgetModels(provider?: string): readonly Model<Api>[];\n\n\t/**\n\t * Sync runtime chat model lookup against last-known lists. Dynamic model lists\n\t * are typed as `Model<Api>`; narrow with the `hasApi()` type guard.\n\t */\n\tgetModel(provider: string, id: string): Model<Api> | undefined;\n\n\t/** Sync read of last-known models of one type from one provider or all providers. */\n\tgetModelsOfType<TType extends ModelType>(type: TType, provider?: string): readonly ModelTypeMap[TType][];\n\n\t/** Sync runtime lookup of a model of one type against last-known lists. */\n\tgetModelOfType<TType extends ModelType>(type: TType, provider: string, id: string): ModelTypeMap[TType] | undefined;\n\n\t/** Sync read of last-known models of every type from one provider or all providers. */\n\tgetAllModels(provider?: string): readonly AnyModel[];\n\n\t/**\n\t * Refresh selected configured dynamic providers concurrently (all when `providers` is omitted).\n\t * Provider errors and cancellation are returned without rejecting; static, unknown, and\n\t * unconfigured providers are skipped.\n\t */\n\trefresh(options?: ModelsRefreshOptions): Promise<ModelsRefreshResult>;\n\n\t/** Check whether a provider has complete auth configuration without refreshing OAuth. */\n\tcheckAuth(providerId: string, options?: AuthOperationOptions): Promise<AuthCheck | undefined>;\n\n\t/** Return chat models whose providers have complete auth configuration. */\n\tgetAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly Model<Api>[]>;\n\n\t/** Return models of one type whose providers have complete auth configuration. */\n\tgetAvailableOfType<TType extends ModelType>(\n\t\ttype: TType,\n\t\tproviderId?: string,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<readonly ModelTypeMap[TType][]>;\n\n\t/** Return models of every type whose providers have complete auth configuration. */\n\tgetAllAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly AnyModel[]>;\n\n\t/**\n\t * Resolve provider-scoped auth by provider id, or provider auth plus static\n\t * model headers when passed a model. Includes a source label for status UI.\n\t * Resolves `undefined` when the provider is unknown or unconfigured.\n\t * Rejects with `ModelsError`: code \"oauth\" when a token refresh fails (the\n\t * stored credential is preserved for retry; re-login fixes it), code \"auth\"\n\t * when api-key resolution or the credential store fails. Request paths\n\t * surface rejections as stream errors.\n\t */\n\tgetAuth(providerId: string, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: AnyModel, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;\n\n\t/** Run a provider-owned login flow and persist its returned credential. */\n\tlogin(providerId: string, type: AuthType, interaction: AuthInteraction, options?: LoginOptions): Promise<Credential>;\n\n\t/** Remove the stored credential for a provider. */\n\tlogout(providerId: string, options?: AuthOperationOptions): Promise<void>;\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream;\n\n\tcomplete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage>;\n\n\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream;\n\tcompleteSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage>;\n\tstreamDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): AssistantMessageEventStream;\n\tfetchDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): Promise<AssistantMessage>;\n\tcancelDeferred(model: Model<Api>, handle: DeferredHandle, options?: ModelsDeferredCancelOptions): Promise<void>;\n\n\t/**\n\t * Generate images through the owning provider with auth resolved like\n\t * `stream()`. Never rejects: unknown providers, unconfigured auth, and\n\t * providers without `generateImages` return an error `AssistantImages`.\n\t */\n\tgenerateImages(\n\t\tmodel: ImageModel<ImageApi>,\n\t\tcontext: ImagesContext,\n\t\toptions?: ModelsImagesOptions,\n\t): Promise<AssistantImages>;\n\n\t/** Classify structured state through the owning provider. Never rejects. */\n\tclassify(\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ModelsClassifierOptions,\n\t): Promise<ClassifierResult>;\n}\n\nexport interface MutableModels extends Models {\n\t/** Upsert/replace by provider.id. Provider ids are unique. */\n\tsetProvider(provider: Provider): void;\n\tdeleteProvider(id: string): void;\n\tclearProviders(): void;\n}\n\nexport interface CreateModelsOptions {\n\tcredentials?: CredentialStore;\n\tmodelsStore?: ModelsStore;\n\tauthContext?: AuthContext;\n}\n\nfunction mergeHeaders(\n\tbase: ProviderHeaders | undefined,\n\toverride: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!base && !override) return undefined;\n\tconst merged = { ...base };\n\tfor (const [name, value] of Object.entries(override ?? {})) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tfor (const existingName of Object.keys(merged)) {\n\t\t\tif (existingName.toLowerCase() === lowerName) delete merged[existingName];\n\t\t}\n\t\tmerged[name] = value;\n\t}\n\treturn merged;\n}\n\nclass ModelsImpl implements MutableModels {\n\tprivate providers = new Map<string, Provider>();\n\tprivate credentials: CredentialStore;\n\tprivate modelsStore: ModelsStore;\n\tprivate authContext: AuthContext;\n\tprivate refreshGenerations = new Map<string, number>();\n\tprivate refreshControllers = new Map<string, AbortController>();\n\tprivate publicationChains = new Map<string, Promise<unknown>>();\n\n\tconstructor(options?: CreateModelsOptions) {\n\t\tthis.credentials = options?.credentials ?? new InMemoryCredentialStore();\n\t\tthis.modelsStore = options?.modelsStore ?? new InMemoryModelsStore();\n\t\tthis.authContext = options?.authContext ?? defaultAuthContext();\n\t}\n\n\tsetProvider(provider: Provider): void {\n\t\tthis.supersedeProviderRefresh(provider.id);\n\t\tthis.providers.set(provider.id, provider);\n\t}\n\n\tdeleteProvider(id: string): void {\n\t\tthis.supersedeProviderRefresh(id);\n\t\tthis.providers.delete(id);\n\t}\n\n\tclearProviders(): void {\n\t\tfor (const id of new Set([...this.providers.keys(), ...this.refreshControllers.keys()])) {\n\t\t\tthis.supersedeProviderRefresh(id);\n\t\t}\n\t\tthis.providers.clear();\n\t}\n\n\tgetProviders(): readonly Provider[] {\n\t\treturn Array.from(this.providers.values());\n\t}\n\n\tgetProvider(id: string): Provider | undefined {\n\t\treturn this.providers.get(id);\n\t}\n\n\tgetModels(provider?: string): readonly Model<Api>[] {\n\t\tif (provider !== undefined) {\n\t\t\tconst entry = this.providers.get(provider);\n\t\t\tif (!entry) return [];\n\t\t\ttry {\n\t\t\t\treturn entry.getModels();\n\t\t\t} catch {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t}\n\n\t\tconst models: Model<Api>[] = [];\n\t\tfor (const entry of this.providers.values()) {\n\t\t\ttry {\n\t\t\t\tmodels.push(...entry.getModels());\n\t\t\t} catch {\n\t\t\t\t// Best-effort: ill-behaved providers yield no models.\n\t\t\t}\n\t\t}\n\t\treturn models;\n\t}\n\n\tgetAllModels(provider?: string): readonly AnyModel[] {\n\t\tif (provider !== undefined) {\n\t\t\tconst entry = this.providers.get(provider);\n\t\t\tif (!entry) return [];\n\t\t\ttry {\n\t\t\t\treturn entry.getAllModels?.() ?? entry.getModels();\n\t\t\t} catch {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t}\n\n\t\tconst models: AnyModel[] = [];\n\t\tfor (const entry of this.providers.values()) {\n\t\t\ttry {\n\t\t\t\tmodels.push(...(entry.getAllModels?.() ?? entry.getModels()));\n\t\t\t} catch {\n\t\t\t\t// Best-effort: ill-behaved providers yield no models.\n\t\t\t}\n\t\t}\n\t\treturn models;\n\t}\n\n\tgetModelsOfType<TType extends ModelType>(type: TType, provider?: string): readonly ModelTypeMap[TType][] {\n\t\treturn this.getAllModels(provider).filter((model): model is ModelTypeMap[TType] => isModelType(model, type));\n\t}\n\n\tgetModel(provider: string, id: string): Model<Api> | undefined {\n\t\treturn this.getModels(provider).find((model) => model.id === id);\n\t}\n\n\tgetModelOfType<TType extends ModelType>(type: TType, provider: string, id: string): ModelTypeMap[TType] | undefined {\n\t\treturn this.getModelsOfType(type, provider).find((model) => model.id === id);\n\t}\n\n\tprivate supersedeProviderRefresh(providerId: string): number {\n\t\tconst generation = (this.refreshGenerations.get(providerId) ?? 0) + 1;\n\t\tthis.refreshGenerations.set(providerId, generation);\n\t\tconst previous = this.refreshControllers.get(providerId);\n\t\tif (previous) {\n\t\t\tthis.refreshControllers.delete(providerId);\n\t\t\tprevious.abort();\n\t\t}\n\t\treturn generation;\n\t}\n\n\tprivate beginProviderRefresh(providerId: string): { generation: number; controller: AbortController } {\n\t\tconst generation = this.supersedeProviderRefresh(providerId);\n\t\tconst controller = new AbortController();\n\t\tthis.refreshControllers.set(providerId, controller);\n\t\treturn { generation, controller };\n\t}\n\n\tprivate publishProviderModels(\n\t\tproviderId: string,\n\t\tgeneration: number,\n\t\tsignal: AbortSignal,\n\t\tpublication: ModelsPublication,\n\t): Promise<boolean> {\n\t\tconst previous = this.publicationChains.get(providerId) ?? Promise.resolve();\n\t\tconst queued = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\tif (signal.aborted || this.refreshGenerations.get(providerId) !== generation) return false;\n\n\t\t\tif (publication.persist === null) {\n\t\t\t\tawait this.modelsStore.delete(providerId, { signal });\n\t\t\t} else if (publication.persist !== undefined) {\n\t\t\t\tawait this.modelsStore.write(providerId, structuredClone(publication.persist), { signal });\n\t\t\t}\n\n\t\t\tif (signal.aborted || this.refreshGenerations.get(providerId) !== generation) return false;\n\t\t\tpublication.update?.();\n\t\t\treturn true;\n\t\t})();\n\t\tconst tail = queued.catch(() => {});\n\t\tthis.publicationChains.set(providerId, tail);\n\t\tvoid tail.then(() => {\n\t\t\tif (this.publicationChains.get(providerId) === tail) this.publicationChains.delete(providerId);\n\t\t});\n\t\treturn raceWithAbortSignal(queued, signal);\n\t}\n\n\tprivate async runProviderRefreshPhase(\n\t\tprovider: Provider & Required<Pick<Provider, \"refreshModels\">>,\n\t\tcredential: Credential | undefined,\n\t\tallowNetwork: boolean,\n\t\tforce: boolean | undefined,\n\t\tgeneration: number,\n\t\tsignal: AbortSignal,\n\t): Promise<void> {\n\t\tconst stored = await this.modelsStore.read(provider.id, { signal });\n\t\tawait provider.refreshModels({\n\t\t\tcredential,\n\t\t\tstored: stored ? withKnownModelTypes(structuredClone(stored)) : undefined,\n\t\t\tpublish: (publication) => this.publishProviderModels(provider.id, generation, signal, publication),\n\t\t\tallowNetwork,\n\t\t\tforce: allowNetwork ? force : undefined,\n\t\t\tsignal,\n\t\t});\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<ModelsRefreshResult> {\n\t\tconst allowNetwork = options.allowNetwork ?? true;\n\t\tconst callerSignal = operationSignal(options.signal);\n\t\tconst errors = new Map<string, Error>();\n\t\tif (callerSignal.aborted) return { aborted: true, errors };\n\t\tconst selected = options.providers ? new Set(options.providers) : undefined;\n\t\tconst refreshable = Array.from(this.providers.values()).filter(\n\t\t\t(provider): provider is Provider & Required<Pick<Provider, \"refreshModels\">> =>\n\t\t\t\tprovider.refreshModels !== undefined && (!selected || selected.has(provider.id)),\n\t\t);\n\n\t\tconst refresh = Promise.all(\n\t\t\trefreshable.map(async (provider) => {\n\t\t\t\tconst { generation, controller } = this.beginProviderRefresh(provider.id);\n\t\t\t\tconst signal = AbortSignal.any([callerSignal, controller.signal]);\n\t\t\t\tconst operation = (async () => {\n\t\t\t\t\tlet storedCredential: Credential | undefined;\n\t\t\t\t\tlet credentialError: unknown;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tstoredCredential = await this.readCredential(provider.id, signal);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tcredentialError = error;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Restore cached provider state before auth resolution or network access.\n\t\t\t\t\tawait this.runProviderRefreshPhase(provider, storedCredential, false, undefined, generation, signal);\n\t\t\t\t\tif (credentialError !== undefined) throw credentialError;\n\t\t\t\t\tif (!allowNetwork || signal.aborted) return;\n\n\t\t\t\t\tconst credential = await this.resolveRefreshCredential(provider, storedCredential, signal);\n\t\t\t\t\tif (!credential) return;\n\t\t\t\t\tawait this.runProviderRefreshPhase(provider, credential, true, options.force, generation, signal);\n\t\t\t\t})();\n\n\t\t\t\ttry {\n\t\t\t\t\tawait raceWithAbortSignal(operation, signal);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!signal.aborted) {\n\t\t\t\t\t\terrors.set(\n\t\t\t\t\t\t\tprovider.id,\n\t\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t\t? error\n\t\t\t\t\t\t\t\t: new ModelsError(\"model_source\", `Model refresh failed for ${provider.id}`, { cause: error }),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tif (this.refreshControllers.get(provider.id) === controller) {\n\t\t\t\t\t\tthis.refreshControllers.delete(provider.id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\n\t\ttry {\n\t\t\tawait raceWithAbortSignal(refresh, callerSignal);\n\t\t} catch (error) {\n\t\t\tif (!callerSignal.aborted) throw error;\n\t\t}\n\n\t\treturn { aborted: callerSignal.aborted, errors: new Map(errors) };\n\t}\n\n\tprivate async resolveRefreshCredential(\n\t\tprovider: Provider,\n\t\tstored: Credential | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<Credential | undefined> {\n\t\tif (stored?.type === \"oauth\") {\n\t\t\tconst oauth = provider.auth.oauth;\n\t\t\tif (!oauth) return undefined;\n\t\t\tif (Date.now() < stored.expires) return stored;\n\t\t\tif (signal.aborted) return undefined;\n\t\t\tconst post = await this.credentials.modify(\n\t\t\t\tprovider.id,\n\t\t\t\tasync (current) => {\n\t\t\t\t\tif (current?.type !== \"oauth\" || Date.now() < current.expires) return undefined;\n\t\t\t\t\treturn oauth.refresh(current, signal);\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t\treturn post?.type === \"oauth\" ? post : undefined;\n\t\t}\n\n\t\tconst apiKey = provider.auth.apiKey;\n\t\tif (!apiKey) return undefined;\n\t\tconst credential = stored?.type === \"api_key\" ? stored : undefined;\n\t\tconst result = await apiKey.resolve({ ctx: this.authContext, credential, signal });\n\t\tif (!result) return undefined;\n\t\treturn { type: \"api_key\", key: result.auth.apiKey, env: result.env };\n\t}\n\n\tprivate async readCredential(providerId: string, signal: AbortSignal): Promise<Credential | undefined> {\n\t\ttry {\n\t\t\treturn await this.credentials.read(providerId, { signal });\n\t\t} catch (error) {\n\t\t\tthrow new ModelsError(\"auth\", `Credential store read failed for ${providerId}`, { cause: error });\n\t\t}\n\t}\n\n\tprivate async checkProviderAuth(\n\t\tprovider: Provider,\n\t\tcredential: Credential | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<AuthCheck | undefined> {\n\t\tif (credential?.type === \"oauth\") {\n\t\t\treturn provider.auth.oauth ? { source: \"OAuth\", type: \"oauth\" } : undefined;\n\t\t}\n\t\tconst apiKey = provider.auth.apiKey;\n\t\tif (!apiKey) return undefined;\n\t\tif (apiKey.check) {\n\t\t\ttry {\n\t\t\t\treturn await apiKey.check({\n\t\t\t\t\tctx: this.authContext,\n\t\t\t\t\tcredential: credential?.type === \"api_key\" ? credential : undefined,\n\t\t\t\t\tsignal,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow new ModelsError(\"auth\", `API key auth check failed for provider ${provider.id}`, { cause: error });\n\t\t\t}\n\t\t}\n\n\t\tconst resolution = await resolveProviderAuth(provider, this.credentials, this.authContext, { signal });\n\t\treturn resolution ? { source: resolution.source, type: \"api_key\" } : undefined;\n\t}\n\n\tcheckAuth(providerId: string, options?: AuthOperationOptions): Promise<AuthCheck | undefined> {\n\t\tconst signal = operationSignal(options?.signal);\n\t\tconst check = (async () => {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst provider = this.providers.get(providerId);\n\t\t\tif (!provider) return undefined;\n\t\t\treturn this.checkProviderAuth(provider, await this.readCredential(providerId, signal), signal);\n\t\t})();\n\t\treturn raceWithAbortSignal(check, signal);\n\t}\n\n\tprivate async getAuthenticatedProviders(providerId: string | undefined, signal: AbortSignal) {\n\t\tsignal.throwIfAborted();\n\t\tconst providers = providerId\n\t\t\t? [this.providers.get(providerId)].filter((entry) => entry !== undefined)\n\t\t\t: this.getProviders();\n\t\tconst checks = await Promise.all(\n\t\t\tproviders.map(async (provider) => {\n\t\t\t\tconst credential = await this.readCredential(provider.id, signal);\n\t\t\t\treturn { provider, credential, auth: await this.checkProviderAuth(provider, credential, signal) };\n\t\t\t}),\n\t\t);\n\t\treturn checks.filter((entry) => entry.auth !== undefined);\n\t}\n\n\tgetAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly Model<Api>[]> {\n\t\tconst signal = operationSignal(options?.signal);\n\t\tconst available = (async () => {\n\t\t\tconst providers = await this.getAuthenticatedProviders(providerId, signal);\n\t\t\treturn providers.flatMap(({ provider, credential }) => {\n\t\t\t\tconst models = provider.getModels();\n\t\t\t\treturn provider.filterModels?.(models, credential) ?? models;\n\t\t\t});\n\t\t})();\n\t\treturn raceWithAbortSignal(available, signal);\n\t}\n\n\tasync getAvailableOfType<TType extends ModelType>(\n\t\ttype: TType,\n\t\tproviderId?: string,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<readonly ModelTypeMap[TType][]> {\n\t\treturn (await this.getAllAvailable(providerId, options)).filter((model): model is ModelTypeMap[TType] =>\n\t\t\tisModelType(model, type),\n\t\t);\n\t}\n\n\tgetAllAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly AnyModel[]> {\n\t\tconst signal = operationSignal(options?.signal);\n\t\tconst available = (async () => {\n\t\t\tconst providers = await this.getAuthenticatedProviders(providerId, signal);\n\t\t\treturn providers.flatMap(({ provider, credential }) => {\n\t\t\t\tconst models = provider.getAllModels?.() ?? provider.getModels();\n\t\t\t\tif (provider.filterAllModels) return provider.filterAllModels(models, credential);\n\t\t\t\tif (!provider.filterModels) return models;\n\t\t\t\tconst availableChatIds = new Set(\n\t\t\t\t\tprovider.filterModels(provider.getModels(), credential).map((model) => model.id),\n\t\t\t\t);\n\t\t\t\treturn models.filter((model) => !isModelType(model, \"chat\") || availableChatIds.has(model.id));\n\t\t\t});\n\t\t})();\n\t\treturn raceWithAbortSignal(available, signal);\n\t}\n\n\tgetAuth(providerId: string, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: AnyModel, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;\n\tasync getAuth(\n\t\tproviderOrModel: string | AnyModel,\n\t\toverrides?: AuthResolutionOverrides,\n\t): Promise<AuthResult | undefined> {\n\t\tconst signal = operationSignal(overrides?.signal);\n\t\tconst providerId = typeof providerOrModel === \"string\" ? providerOrModel : providerOrModel.provider;\n\t\tconst provider = this.providers.get(providerId);\n\t\tif (!provider) return undefined;\n\t\tconst result = await resolveProviderAuth(provider, this.credentials, this.authContext, { ...overrides, signal });\n\t\tif (!result || typeof providerOrModel === \"string\" || !providerOrModel.headers) return result;\n\t\treturn {\n\t\t\t...result,\n\t\t\tauth: {\n\t\t\t\t...result.auth,\n\t\t\t\theaders: mergeHeaders(result.auth.headers, providerOrModel.headers),\n\t\t\t},\n\t\t};\n\t}\n\n\tasync login(\n\t\tproviderId: string,\n\t\ttype: AuthType,\n\t\tinteraction: AuthInteraction,\n\t\toptions?: LoginOptions,\n\t): Promise<Credential> {\n\t\tconst signal = operationSignal(interaction.signal);\n\t\tsignal.throwIfAborted();\n\t\tconst provider = this.providers.get(providerId);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${providerId}`);\n\t\tconst method = type === \"oauth\" ? provider.auth.oauth : provider.auth.apiKey;\n\t\tif (!method?.login) {\n\t\t\tthrow new ModelsError(\"auth\", `${provider.name} does not support ${type} login`);\n\t\t}\n\t\tconst loginOperation: Promise<Credential> = method.login({ ...interaction, signal }, options);\n\t\tconst credential = await raceWithAbortSignal(loginOperation, signal);\n\t\tlet mutationStarted = false;\n\t\tlet markMutationStarted: (() => void) | undefined;\n\t\tconst started = new Promise<void>((resolve) => {\n\t\t\tmarkMutationStarted = resolve;\n\t\t});\n\t\tconst mutation = this.credentials.modify(\n\t\t\tproviderId,\n\t\t\tasync () => {\n\t\t\t\tmutationStarted = true;\n\t\t\t\tmarkMutationStarted?.();\n\t\t\t\treturn credential;\n\t\t\t},\n\t\t\t{ signal },\n\t\t);\n\t\tvoid mutation.catch(() => {});\n\t\ttry {\n\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\tconst onAbort = () => {\n\t\t\t\t\tif (!mutationStarted) reject(signal.reason);\n\t\t\t\t};\n\t\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\tvoid Promise.race([started, mutation]).then(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t},\n\t\t\t\t\t(error: unknown) => {\n\t\t\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t});\n\t\t\tawait mutation;\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow new ModelsError(\"auth\", `Credential store modify failed for ${providerId}`, { cause: error });\n\t\t}\n\t\treturn credential;\n\t}\n\n\tasync logout(providerId: string, options?: AuthOperationOptions): Promise<void> {\n\t\tconst signal = operationSignal(options?.signal);\n\t\tsignal.throwIfAborted();\n\t\ttry {\n\t\t\tawait this.credentials.delete(providerId, { signal });\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow new ModelsError(\"auth\", `Credential store delete failed for ${providerId}`, { cause: error });\n\t\t}\n\t}\n\n\tprivate requireProvider(model: AnyModel): Provider {\n\t\tconst provider = this.providers.get(model.provider);\n\t\tif (!provider) {\n\t\t\tthrow new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\t}\n\t\treturn provider;\n\t}\n\n\tprivate requireChatProvider(model: Model<Api>): Provider {\n\t\tassertChatModel(model);\n\t\treturn this.requireProvider(model);\n\t}\n\n\tprivate async applyAuth<\n\t\tTModel extends AnyModel,\n\t\tTOptions extends ProviderRequestOptions<TModel> & ModelsRequestTransforms,\n\t>(\n\t\tmodel: TModel,\n\t\toptions: TOptions | undefined,\n\t): Promise<{\n\t\trequestModel: TModel;\n\t\trequestOptions: Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions<TModel>;\n\t}> {\n\t\tthis.requireProvider(model);\n\t\tconst resolution = await this.getAuth(model, {\n\t\t\tapiKey: options?.apiKey,\n\t\t\tenv: options?.env,\n\t\t\tsignal: options?.signal,\n\t\t});\n\t\tif (!resolution) {\n\t\t\tthrow new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\t\t}\n\t\tconst auth = resolution.auth;\n\n\t\t// Explicit request options win per-field; the Models-only transform runs last.\n\t\tconst apiKey = options?.apiKey ?? auth.apiKey;\n\t\tlet headers = mergeHeaders(auth.headers, options?.headers);\n\t\tif (options?.transformHeaders) headers = await options.transformHeaders(headers ?? {});\n\t\tconst env = resolution.env || options?.env ? { ...(resolution.env ?? {}), ...(options?.env ?? {}) } : undefined;\n\t\tconst requestModel: TModel = auth.baseUrl ? { ...model, baseUrl: auth.baseUrl } : model;\n\t\tconst { transformHeaders: _transformHeaders, ...providerOptions } = options ?? {};\n\t\tconst requestOptions = { ...providerOptions, apiKey, headers, env } as Omit<TOptions, \"transformHeaders\"> &\n\t\t\tProviderRequestOptions<TModel>;\n\n\t\treturn { requestModel, requestOptions };\n\t}\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream {\n\t\tconst transcript = normalizeContext(context);\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst provider = this.requireChatProvider(model);\n\t\t\tconst { requestModel, requestOptions } = await this.applyAuth(\n\t\t\t\tmodel,\n\t\t\t\toptions as ModelsApiStreamOptions<Api> | undefined,\n\t\t\t);\n\t\t\treturn provider.stream(requestModel, transcript, requestOptions as ApiStreamOptions<TApi>);\n\t\t});\n\t}\n\n\tasync complete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage> {\n\t\treturn this.stream(model, context, options).result();\n\t}\n\n\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream {\n\t\tconst transcript = normalizeContext(context);\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst provider = this.requireChatProvider(model);\n\t\t\tconst { requestModel, requestOptions } = await this.applyAuth(model, options);\n\t\t\treturn provider.streamSimple(requestModel, transcript, requestOptions as SimpleStreamOptions);\n\t\t});\n\t}\n\n\tasync completeSimple(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions?: ModelsSimpleStreamOptions,\n\t): Promise<AssistantMessage> {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n\n\tstreamDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst provider = this.requireChatProvider(model);\n\t\t\tif (!provider.fetchDeferred) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t\t}\n\t\t\tconst { requestModel, requestOptions } = await this.applyAuth(model, options);\n\t\t\treturn provider.fetchDeferred(requestModel, handle, requestOptions as DeferredFetchOptions);\n\t\t});\n\t}\n\n\tasync fetchDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): Promise<AssistantMessage> {\n\t\treturn this.streamDeferred(model, handle, options).result();\n\t}\n\n\tasync cancelDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredCancelOptions,\n\t): Promise<void> {\n\t\tconst provider = this.requireChatProvider(model);\n\t\tif (!provider.cancelDeferred) {\n\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t}\n\t\tconst { requestModel, requestOptions } = await this.applyAuth(model, options);\n\t\tawait provider.cancelDeferred(requestModel, handle, requestOptions);\n\t}\n\n\tasync generateImages(\n\t\tmodel: ImageModel<ImageApi>,\n\t\tcontext: ImagesContext,\n\t\toptions?: ModelsImagesOptions,\n\t): Promise<AssistantImages> {\n\t\ttry {\n\t\t\tassertImageModel(model);\n\t\t\tconst provider = this.requireProvider(model);\n\t\t\tif (!provider.generateImages) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support image generation`);\n\t\t\t}\n\t\t\tconst { requestModel, requestOptions } = await this.applyAuth(model, options);\n\t\t\treturn await provider.generateImages(requestModel, context, requestOptions);\n\t\t} catch (error) {\n\t\t\treturn imageErrorResult(model, error, options?.signal?.aborted);\n\t\t}\n\t}\n\n\tasync classify(\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ModelsClassifierOptions,\n\t): Promise<ClassifierResult> {\n\t\ttry {\n\t\t\tassertClassifierModel(model);\n\t\t\tconst provider = this.requireProvider(model);\n\t\t\tif (!provider.classify) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support classification`);\n\t\t\t}\n\t\t\tconst { requestModel, requestOptions } = await this.applyAuth(model, options);\n\t\t\treturn await provider.classify(requestModel, context, requestOptions);\n\t\t} catch (error) {\n\t\t\treturn classifierErrorResult(model, error, options?.signal?.aborted);\n\t\t}\n\t}\n}\n\nexport function createModels(options?: CreateModelsOptions): MutableModels {\n\treturn new ModelsImpl(options);\n}\n\nexport interface CreateProviderOptions<TApi extends Api = Api> {\n\tid: string;\n\t/** Display name. Default: `id`. */\n\tname?: string;\n\tbaseUrl?: string;\n\theaders?: ProviderHeaders;\n\t/** Required — every provider has auth semantics, even ambient/keyless ones. */\n\tauth: ProviderAuth;\n\t/**\n\t * Static baseline models of every type (empty for purely dynamic providers).\n\t * Models without `type` are chat models.\n\t */\n\tmodels: readonly ProviderModel<TApi>[];\n\t/**\n\t * Fetch a dynamic model overlay of every type. createProvider restores and\n\t * publishes it transactionally and drops models of unknown types.\n\t */\n\tfetchModels?: (context: RefreshModelsContext) => Promise<readonly ProviderModel<TApi>[]>;\n\t/** Credential-specific chat model availability. See `Provider.filterModels`. */\n\tfilterModels?: (models: readonly Model<TApi>[], credential: Credential | undefined) => readonly Model<TApi>[];\n\t/** Credential-specific availability across every model type. See `Provider.filterAllModels`. */\n\tfilterAllModels?: (\n\t\tmodels: readonly ProviderModel<TApi>[],\n\t\tcredential: Credential | undefined,\n\t) => readonly ProviderModel<TApi>[];\n\t/**\n\t * Chat implementation: a single one for all chat models, or a map keyed by\n\t * `model.api` for mixed-API providers. Optional when `images` or\n\t * `classifiers` is given.\n\t */\n\tapi?: ProviderStreams | Partial<Record<TApi, ProviderStreams>>;\n\t/** Image-generation implementations keyed by `model.api`. */\n\timages?: Partial<Record<ImageApi, ProviderImages>>;\n\t/** Classifier implementations keyed by `model.api`. */\n\tclassifiers?: Partial<Record<ClassifierApi, ProviderClassifier>>;\n}\n\n/**\n * Builds a provider from parts. Built-in provider factories and models.json\n * custom providers both go through this. A single `api` streams all chat\n * models; an `api` map dispatches on `model.api`, and a model whose api has\n * no entry produces a stream error. One-shot operation maps dispatch on\n * `model.api` the same way. At least one concrete implementation across\n * `api`/`images`/`classifiers` is required; empty maps are rejected.\n */\nexport function createProvider<TApi extends Api = Api>(input: CreateProviderOptions<TApi>): Provider<TApi> {\n\tconst single =\n\t\tinput.api && typeof (input.api as ProviderStreams).stream === \"function\"\n\t\t\t? (input.api as ProviderStreams)\n\t\t\t: undefined;\n\tconst byApi = single || !input.api ? undefined : (input.api as Partial<Record<string, ProviderStreams>>);\n\tconst images = input.images as Partial<Record<string, ProviderImages>> | undefined;\n\tconst classifiers = input.classifiers as Partial<Record<string, ProviderClassifier>> | undefined;\n\tconst streams = single ? [single] : Object.values(byApi ?? {}).filter((entry) => entry !== undefined);\n\tconst imageImplementations = Object.values(images ?? {}).filter((entry) => entry !== undefined);\n\tconst classifierImplementations = Object.values(classifiers ?? {}).filter((entry) => entry !== undefined);\n\tif (streams.length === 0 && imageImplementations.length === 0 && classifierImplementations.length === 0) {\n\t\tthrow new Error(`Provider ${input.id}: at least one of \"api\", \"images\", or \"classifiers\" is required.`);\n\t}\n\n\tconst baselineModels = input.models;\n\tlet dynamicModels: readonly ProviderModel<TApi>[] = [];\n\tconst fetchModels = input.fetchModels;\n\tconst currentModels = (): readonly ProviderModel<TApi>[] => {\n\t\tconst merged = [...baselineModels];\n\t\tfor (const model of dynamicModels) {\n\t\t\tconst index = merged.findIndex(\n\t\t\t\t(entry) => getModelType(entry) === getModelType(model) && entry.id === model.id,\n\t\t\t);\n\t\t\tif (index >= 0) merged[index] = model;\n\t\t\telse merged.push(model);\n\t\t}\n\t\treturn merged;\n\t};\n\tconst apiFor = (model: Model<Api>): ProviderStreams | undefined => single ?? byApi?.[model.api];\n\n\tconst dispatch = (\n\t\tmodel: Model<Api>,\n\t\trun: (streams: ProviderStreams) => AssistantMessageEventStream,\n\t): AssistantMessageEventStream => {\n\t\tconst streams = apiFor(model);\n\t\tif (!streams) {\n\t\t\treturn lazyStream(model, async () => {\n\t\t\t\tthrow new ModelsError(\"stream\", `Provider ${input.id} has no API implementation for \"${model.api}\"`);\n\t\t\t});\n\t\t}\n\t\treturn run(streams);\n\t};\n\n\tconst provider: Provider<TApi> = {\n\t\tid: input.id,\n\t\tname: input.name ?? input.id,\n\t\tbaseUrl: input.baseUrl,\n\t\theaders: input.headers,\n\t\tauth: input.auth,\n\t\tgetModels: () => currentModels().filter((model): model is Model<TApi> => isModelType(model, \"chat\")),\n\t\tgetAllModels: currentModels,\n\t\trefreshModels: fetchModels\n\t\t\t? async (context) => {\n\t\t\t\t\tif (context.stored) {\n\t\t\t\t\t\tconst restored = context.stored.models\n\t\t\t\t\t\t\t.filter((model) => model.provider === input.id)\n\t\t\t\t\t\t\t.map((model) => model as ProviderModel<TApi>);\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!(await context.publish({\n\t\t\t\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\t\t\t\tdynamicModels = restored;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}))\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\t\t\t\t\tconst fetched = await fetchModels(context);\n\t\t\t\t\tif (context.signal.aborted) return;\n\t\t\t\t\tconst refreshed = fetched.filter(hasKnownModelType);\n\t\t\t\t\tawait context.publish({\n\t\t\t\t\t\tpersist: { models: refreshed, checkedAt: Date.now() },\n\t\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\t\tdynamicModels = refreshed;\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t: undefined,\n\t\tfilterModels: input.filterModels,\n\t\tfilterAllModels: input.filterAllModels,\n\t\tstream: (model, context, options) => dispatch(model, (streams) => streams.stream(model, context, options)),\n\t\tstreamSimple: (model, context, options) =>\n\t\t\tdispatch(model, (streams) => streams.streamSimple(model, context, options)),\n\t};\n\n\tif (streams.some((entry) => entry.fetchDeferred !== undefined)) {\n\t\tprovider.fetchDeferred = (model, handle, options) =>\n\t\t\tlazyStream(model, async () => {\n\t\t\t\tconst implementation = apiFor(model);\n\t\t\t\tif (!implementation?.fetchDeferred) {\n\t\t\t\t\tthrow new ModelsError(\n\t\t\t\t\t\t\"provider\",\n\t\t\t\t\t\t`Provider ${input.id} does not support deferred responses for \"${model.api}\"`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn implementation.fetchDeferred(model, handle, options);\n\t\t\t});\n\t}\n\tif (streams.some((entry) => entry.cancelDeferred !== undefined)) {\n\t\tprovider.cancelDeferred = async (model, handle, options) => {\n\t\t\tconst implementation = apiFor(model);\n\t\t\tif (!implementation?.cancelDeferred) {\n\t\t\t\tthrow new ModelsError(\n\t\t\t\t\t\"provider\",\n\t\t\t\t\t`Provider ${input.id} cannot cancel deferred responses for \"${model.api}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait implementation.cancelDeferred(model, handle, options);\n\t\t};\n\t}\n\tif (images && imageImplementations.length > 0) {\n\t\tprovider.generateImages = async (model, context, options) => {\n\t\t\tconst implementation = images[model.api];\n\t\t\tif (!implementation) {\n\t\t\t\treturn imageErrorResult(\n\t\t\t\t\tmodel,\n\t\t\t\t\tnew ModelsError(\n\t\t\t\t\t\t\"provider\",\n\t\t\t\t\t\t`Provider ${input.id} has no image generation implementation for \"${model.api}\"`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn implementation.generateImages(model, context, options);\n\t\t};\n\t}\n\tif (classifiers && classifierImplementations.length > 0) {\n\t\tprovider.classify = async (model, context, options) => {\n\t\t\tconst implementation = classifiers[model.api];\n\t\t\tif (!implementation) {\n\t\t\t\treturn classifierErrorResult(\n\t\t\t\t\tmodel,\n\t\t\t\t\tnew ModelsError(\"provider\", `Provider ${input.id} has no classifier implementation for \"${model.api}\"`),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn implementation.classify(model, context, options);\n\t\t};\n\t}\n\n\treturn provider;\n}\n\n/**\n * Runtime-checked narrowing for dynamically looked-up models:\n *\n * ```ts\n * const model = models.getModel(\"anthropic\", \"claude-opus-4-7\");\n * if (model && hasApi(model, \"anthropic-messages\")) {\n * // model: Model<\"anthropic-messages\">, stream options fully typed\n * }\n * ```\n *\n * Non-chat models never match, even when their api id equals `api`.\n */\nexport function hasApi<TApi extends Api>(model: AnyModel, api: TApi): model is Model<TApi> {\n\treturn isModelType(model, \"chat\") && model.api === api;\n}\n\nexport function calculateCost(model: AnyModel, usage: Usage): Usage[\"cost\"] {\n\tconst inputTokens = usage.input + usage.cacheRead + usage.cacheWrite;\n\tlet rates: ModelCostRates = model.cost;\n\tlet matchedThreshold = -1;\n\tfor (const tier of model.cost.tiers ?? []) {\n\t\tif (inputTokens > tier.inputTokensAbove && tier.inputTokensAbove > matchedThreshold) {\n\t\t\trates = tier;\n\t\t\tmatchedThreshold = tier.inputTokensAbove;\n\t\t}\n\t}\n\n\t// Anthropic charges 2x base input for 1h cache writes.\n\tconst longWrite = usage.cacheWrite1h ?? 0;\n\tconst shortWrite = usage.cacheWrite - longWrite;\n\tusage.cost.input = (rates.input / 1000000) * usage.input;\n\tusage.cost.output = (rates.output / 1000000) * usage.output;\n\tusage.cost.cacheRead = (rates.cacheRead / 1000000) * usage.cacheRead;\n\tusage.cost.cacheWrite = (rates.cacheWrite * shortWrite + rates.input * 2 * longWrite) / 1000000;\n\tusage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n\treturn usage.cost;\n}\n\nconst EXTENDED_THINKING_LEVELS: ModelThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n\nexport function getSupportedThinkingLevels<TApi extends Api>(model: Model<TApi>): ModelThinkingLevel[] {\n\tif (!model.reasoning) return [\"off\"];\n\n\treturn EXTENDED_THINKING_LEVELS.filter((level) => {\n\t\tconst mapped = model.thinkingLevelMap?.[level];\n\t\tif (mapped === null) return false;\n\t\tif (level === \"xhigh\" || level === \"max\") return mapped !== undefined;\n\t\treturn true;\n\t});\n}\n\nexport function clampThinkingLevel<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tlevel: ModelThinkingLevel,\n): ModelThinkingLevel {\n\tconst availableLevels = getSupportedThinkingLevels(model);\n\tif (availableLevels.includes(level)) return level;\n\n\tconst requestedIndex = EXTENDED_THINKING_LEVELS.indexOf(level);\n\tif (requestedIndex === -1) return availableLevels[0] ?? \"off\";\n\n\tfor (let i = requestedIndex; i < EXTENDED_THINKING_LEVELS.length; i++) {\n\t\tconst candidate = EXTENDED_THINKING_LEVELS[i];\n\t\tif (availableLevels.includes(candidate)) return candidate;\n\t}\n\tfor (let i = requestedIndex - 1; i >= 0; i--) {\n\t\tconst candidate = EXTENDED_THINKING_LEVELS[i];\n\t\tif (availableLevels.includes(candidate)) return candidate;\n\t}\n\treturn availableLevels[0] ?? \"off\";\n}\n\n/**\n * Check if a model supports xhigh thinking level.\n */\nexport function supportsXhigh<TApi extends Api>(model: Model<TApi>): boolean {\n\tif (model.id.includes(\"gpt-5.2\") || model.id.includes(\"gpt-5.3\") || model.id.includes(\"gpt-5.4\")) {\n\t\treturn true;\n\t}\n\tif (\n\t\tmodel.id.includes(\"opus-4-6\") ||\n\t\tmodel.id.includes(\"opus-4.6\") ||\n\t\tmodel.id.includes(\"opus-4-7\") ||\n\t\tmodel.id.includes(\"opus-4.7\") ||\n\t\tmodel.id.includes(\"sonnet-4-6\") ||\n\t\tmodel.id.includes(\"sonnet-4.6\") ||\n\t\tmodel.id.includes(\"haiku-4-5\") ||\n\t\tmodel.id.includes(\"haiku-4.5\")\n\t) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n/**\n * Check if a model supports the max thinking level.\n * Currently Anthropic Opus 4.6 and Opus 4.7 only.\n */\nexport function supportsMax<TApi extends Api>(model: Model<TApi>): boolean {\n\treturn (\n\t\tmodel.id.includes(\"opus-4-6\") ||\n\t\tmodel.id.includes(\"opus-4.6\") ||\n\t\tmodel.id.includes(\"opus-4-7\") ||\n\t\tmodel.id.includes(\"opus-4.7\")\n\t);\n}\n\n/**\n * Check if two models are equal by comparing their type, id, and provider.\n * Returns false if either model is null or undefined.\n */\nexport function modelsAreEqual(a: AnyModel | null | undefined, b: AnyModel | null | undefined): boolean {\n\tif (!a || !b) return false;\n\treturn getModelType(a) === getModelType(b) && a.id === b.id && a.provider === b.provider;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"models.js","sourceRoot":"","sources":["../src/models.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,0BAA0B,IAAI,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACrF,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EAAgC,WAAW,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAanG,OAAO,EAAE,mBAAmB,EA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IAAI,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,QAAQ,KAAK,CAAC,CAAC,QAAQ,CAAC;AAC1F,CAAC","sourcesContent":["import { lazyStream } from \"./api/lazy.ts\";\nimport { defaultProviderAuthContext as defaultAuthContext } from \"./auth/context.ts\";\nimport { InMemoryCredentialStore } from \"./auth/credential-store.ts\";\nimport { type AuthResolutionOverrides, ModelsError, resolveProviderAuth } from \"./auth/resolve.ts\";\nimport type {\n\tAuthCheck,\n\tAuthContext,\n\tAuthInteraction,\n\tAuthOperationOptions,\n\tAuthResult,\n\tAuthType,\n\tCredential,\n\tCredentialStore,\n\tLoginOptions,\n\tProviderAuth,\n} from \"./auth/types.ts\";\nimport { InMemoryModelsStore, type ModelsStore, type ModelsStoreEntry } from \"./models-store.ts\";\nimport type {\n\tAnyModel,\n\tApi,\n\tApiStreamOptions,\n\tAssistantImages,\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tClassifierApi,\n\tClassifierContext,\n\tClassifierModel,\n\tClassifierOptions,\n\tClassifierResult,\n\tContext,\n\tDeferredCancelOptions,\n\tDeferredFetchOptions,\n\tDeferredHandle,\n\tImageApi,\n\tImageModel,\n\tImagesContext,\n\tImagesOptions,\n\tModel,\n\tModelCostRates,\n\tModelThinkingLevel,\n\tModelType,\n\tModelTypeMap,\n\tProviderClassifier,\n\tProviderHeaders,\n\tProviderImages,\n\tProviderRequestOptions,\n\tProviderStreams,\n\tSimpleStreamOptions,\n\tTranscriptContext,\n\tUsage,\n} from \"./types.ts\";\nimport { operationSignal, raceWithAbortSignal } from \"./utils/abort.ts\";\nimport {\n\tassertChatModel,\n\tassertClassifierModel,\n\tassertImageModel,\n\tclassifierErrorResult,\n\tgetModelType,\n\timageErrorResult,\n\tisModelType,\n} from \"./utils/model-operations.ts\";\nimport { normalizeContext } from \"./utils/transcript.ts\";\n\nexport { ModelsError, type ModelsErrorCode } from \"./auth/resolve.ts\";\nexport { getModelType, isModelType } from \"./utils/model-operations.ts\";\n\nexport interface ModelsPublication {\n\t/** Provider-selected persisted catalog. Omit to leave storage unchanged; null deletes it. */\n\tpersist?: ModelsStoreEntry | null;\n\t/** Optional synchronous update of provider-private in-memory catalog state. */\n\tupdate?: () => void;\n}\n\nexport interface RefreshModelsContext {\n\t/** Effective configured credential. OAuth credentials are refreshed before network access. */\n\tcredential?: Credential;\n\t/** Immutable provider-scoped catalog snapshot captured before this refresh phase. */\n\tstored?: Readonly<ModelsStoreEntry>;\n\t/**\n\t * Generation-checked publication. Persistence policy remains provider-owned;\n\t * the update runs synchronously only after the selected persistence mutation.\n\t */\n\tpublish(publication: ModelsPublication): Promise<boolean>;\n\t/** False during offline/cache-only initialization. */\n\tallowNetwork: boolean;\n\t/** Bypass provider freshness checks and fetch immediately when network access is allowed. */\n\tforce?: boolean;\n\t/** Always present, including when the public refresh caller omits its optional signal. */\n\tsignal: AbortSignal;\n}\n\nexport interface ModelsRefreshOptions {\n\tallowNetwork?: boolean;\n\t/** Restrict refresh to these provider IDs. Unknown and static providers are ignored. */\n\tproviders?: readonly string[];\n\t/** Bypass provider freshness checks and fetch immediately when network access is allowed. */\n\tforce?: boolean;\n\tsignal?: AbortSignal;\n}\n\nexport interface ModelsRefreshResult {\n\taborted: boolean;\n\terrors: ReadonlyMap<string, Error>;\n}\n\nexport interface ModelsRequestTransforms {\n\t/** Transform fully assembled model/auth/request headers before provider dispatch. */\n\ttransformHeaders?: (headers: ProviderHeaders) => ProviderHeaders | Promise<ProviderHeaders>;\n}\n\nexport type ModelsApiStreamOptions<TApi extends Api> = ApiStreamOptions<TApi> & ModelsRequestTransforms;\nexport type ModelsSimpleStreamOptions = SimpleStreamOptions & ModelsRequestTransforms;\nexport type ModelsDeferredFetchOptions = DeferredFetchOptions & ModelsRequestTransforms;\nexport type ModelsDeferredCancelOptions = DeferredCancelOptions & ModelsRequestTransforms;\nexport type ModelsImagesOptions = ImagesOptions & ModelsRequestTransforms;\nexport type ModelsClassifierOptions = ClassifierOptions & ModelsRequestTransforms;\n\nconst KNOWN_MODEL_TYPES: Record<ModelType, true> = { chat: true, image: true, classifier: true };\n\n/** Models from stores and remote sources may have types that only newer versions know. */\nfunction hasKnownModelType(model: AnyModel): boolean {\n\treturn Object.hasOwn(KNOWN_MODEL_TYPES, getModelType(model));\n}\n\n/** Drops stored models whose type this version does not know. */\nfunction withKnownModelTypes(entry: ModelsStoreEntry): ModelsStoreEntry {\n\treturn { ...entry, models: entry.models.filter(hasKnownModelType) };\n}\n\n/** Any model a provider with chat APIs `TApi` can list. */\ntype ProviderModel<TApi extends Api> = Model<TApi> | ImageModel<ImageApi> | ClassifierModel<ClassifierApi>;\n\n/**\n * A provider is the concrete runtime unit. It owns id/name/base metadata,\n * auth methods, model listing, and the operations its models support\n * (streaming, image generation, classification).\n *\n * `TApi` lets concrete provider factories declare which chat APIs their models\n * use (e.g. `openaiProvider(): Provider<\"openai-responses\" | \"openai-completions\">`),\n * giving typed chat model lists to direct factory users. Other model types use\n * their operation-specific API unions. Inside a `Models` collection providers\n * are held as `Provider<Api>`.\n */\nexport interface Provider<TApi extends Api = Api> {\n\treadonly id: string;\n\treadonly name: string;\n\n\treadonly baseUrl?: string;\n\treadonly headers?: ProviderHeaders;\n\n\t/**\n\t * Required: at least one of `apiKey`/`oauth`. Every provider has auth\n\t * semantics — even providers with only ambient credentials (env vars, AWS\n\t * profiles, ADC files) and keyless local servers provide `apiKey` auth\n\t * whose `resolve()` reports whether the provider is configured.\n\t * `Models.getAuth()` returns undefined when the provider is unconfigured.\n\t */\n\treadonly auth: ProviderAuth;\n\n\t/**\n\t * Current known chat models, sync. Static providers return their catalog;\n\t * dynamic providers return the list as of the last `refreshModels()` (empty\n\t * before the first). Must not throw; `Models` treats a throwing\n\t * implementation as having no models.\n\t */\n\tgetModels(): readonly Model<TApi>[];\n\n\t/**\n\t * Current known models of every type, sync, with the same contract as\n\t * `getModels()`. Providers with only chat models may omit it; `Models` then\n\t * uses `getModels()`. Model ids are unique within each type; one upstream\n\t * model may have separate entries for different operations.\n\t */\n\tgetAllModels?(): readonly ProviderModel<TApi>[];\n\n\t/**\n\t * Dynamic providers only: restore `context.stored` and optionally fetch a newer list using\n\t * the effective credential. Implementations retain their previous list on failure, publish\n\t * persistence and synchronous state changes through `context.publish()`, and honor the\n\t * shared abort signal for blocking work.\n\t */\n\trefreshModels?(context: RefreshModelsContext): Promise<void>;\n\n\t/**\n\t * Optional provider policy for credential-specific model availability.\n\t * `getModels()` remains the complete synchronous chat catalog; `Models.getAvailable()`\n\t * applies this filter after confirming that provider auth is configured.\n\t */\n\tfilterModels?(models: readonly Model<TApi>[], credential: Credential | undefined): readonly Model<TApi>[];\n\n\t/**\n\t * Optional credential-specific availability policy across every model type.\n\t * Without it, `Models.getAllAvailable()` applies `filterModels` to chat models\n\t * and keeps every other model.\n\t */\n\tfilterAllModels?(\n\t\tmodels: readonly ProviderModel<TApi>[],\n\t\tcredential: Credential | undefined,\n\t): readonly ProviderModel<TApi>[];\n\n\t/** Stream a normalized transcript. `Models` normalizes the caller's `Context` before dispatching here. */\n\tstream<T extends TApi>(\n\t\tmodel: Model<T>,\n\t\tcontext: TranscriptContext,\n\t\toptions?: ApiStreamOptions<T>,\n\t): AssistantMessageEventStream;\n\n\tstreamSimple(\n\t\tmodel: Model<TApi>,\n\t\tcontext: TranscriptContext,\n\t\toptions?: SimpleStreamOptions,\n\t): AssistantMessageEventStream;\n\tfetchDeferred?(\n\t\tmodel: Model<TApi>,\n\t\thandle: DeferredHandle,\n\t\toptions?: DeferredFetchOptions,\n\t): AssistantMessageEventStream;\n\tcancelDeferred?(model: Model<TApi>, handle: DeferredHandle, options?: DeferredCancelOptions): Promise<void>;\n\n\t/** Present when the provider supports dedicated image models. Never rejects. */\n\tgenerateImages?(\n\t\tmodel: ImageModel<ImageApi>,\n\t\tcontext: ImagesContext,\n\t\toptions?: ImagesOptions,\n\t): Promise<AssistantImages>;\n\n\t/** Present when the provider supports structured classifier models. Never rejects. */\n\tclassify?(\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ClassifierOptions,\n\t): Promise<ClassifierResult>;\n}\n\n/**\n * Runtime collection of providers plus auth application and request\n * convenience. Providers own request behavior; `Models` resolves auth and\n * delegates each request to the provider that owns the model.\n *\n * Read accessors come in three flavors: the unqualified ones (`getModels`,\n * `getModel`, `getAvailable`) return chat models, the `*OfType` accessors\n * return one model type, and `getAllModels`/`getAllAvailable` return every type.\n */\nexport interface Models {\n\tgetProviders(): readonly Provider[];\n\tgetProvider(id: string): Provider | undefined;\n\n\t/**\n\t * Sync read of last-known chat models from one provider or all providers.\n\t * Best-effort: a provider whose `getModels()` throws yields no models.\n\t */\n\tgetModels(provider?: string): readonly Model<Api>[];\n\n\t/**\n\t * Sync runtime chat model lookup against last-known lists. Dynamic model lists\n\t * are typed as `Model<Api>`; narrow with the `hasApi()` type guard.\n\t */\n\tgetModel(provider: string, id: string): Model<Api> | undefined;\n\n\t/** Sync read of last-known models of one type from one provider or all providers. */\n\tgetModelsOfType<TType extends ModelType>(type: TType, provider?: string): readonly ModelTypeMap[TType][];\n\n\t/** Sync runtime lookup of a model of one type against last-known lists. */\n\tgetModelOfType<TType extends ModelType>(type: TType, provider: string, id: string): ModelTypeMap[TType] | undefined;\n\n\t/** Sync read of last-known models of every type from one provider or all providers. */\n\tgetAllModels(provider?: string): readonly AnyModel[];\n\n\t/**\n\t * Refresh selected configured dynamic providers concurrently (all when `providers` is omitted).\n\t * Provider errors and cancellation are returned without rejecting; static, unknown, and\n\t * unconfigured providers are skipped.\n\t */\n\trefresh(options?: ModelsRefreshOptions): Promise<ModelsRefreshResult>;\n\n\t/** Check whether a provider has complete auth configuration without refreshing OAuth. */\n\tcheckAuth(providerId: string, options?: AuthOperationOptions): Promise<AuthCheck | undefined>;\n\n\t/** Return chat models whose providers have complete auth configuration. */\n\tgetAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly Model<Api>[]>;\n\n\t/** Return models of one type whose providers have complete auth configuration. */\n\tgetAvailableOfType<TType extends ModelType>(\n\t\ttype: TType,\n\t\tproviderId?: string,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<readonly ModelTypeMap[TType][]>;\n\n\t/** Return models of every type whose providers have complete auth configuration. */\n\tgetAllAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly AnyModel[]>;\n\n\t/**\n\t * Resolve provider-scoped auth by provider id, or provider auth plus static\n\t * model headers when passed a model. Includes a source label for status UI.\n\t * Resolves `undefined` when the provider is unknown or unconfigured.\n\t * Rejects with `ModelsError`: code \"oauth\" when a token refresh fails (the\n\t * stored credential is preserved for retry; re-login fixes it), code \"auth\"\n\t * when api-key resolution or the credential store fails. Request paths\n\t * surface rejections as stream errors.\n\t */\n\tgetAuth(providerId: string, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: AnyModel, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;\n\n\t/** Run a provider-owned login flow and persist its returned credential. */\n\tlogin(providerId: string, type: AuthType, interaction: AuthInteraction, options?: LoginOptions): Promise<Credential>;\n\n\t/** Remove the stored credential for a provider. */\n\tlogout(providerId: string, options?: AuthOperationOptions): Promise<void>;\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream;\n\n\tcomplete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage>;\n\n\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream;\n\tcompleteSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage>;\n\tstreamDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): AssistantMessageEventStream;\n\tfetchDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): Promise<AssistantMessage>;\n\tcancelDeferred(model: Model<Api>, handle: DeferredHandle, options?: ModelsDeferredCancelOptions): Promise<void>;\n\n\t/**\n\t * Generate images through the owning provider with auth resolved like\n\t * `stream()`. Never rejects: unknown providers, unconfigured auth, and\n\t * providers without `generateImages` return an error `AssistantImages`.\n\t */\n\tgenerateImages(\n\t\tmodel: ImageModel<ImageApi>,\n\t\tcontext: ImagesContext,\n\t\toptions?: ModelsImagesOptions,\n\t): Promise<AssistantImages>;\n\n\t/** Classify structured state through the owning provider. Never rejects. */\n\tclassify(\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ModelsClassifierOptions,\n\t): Promise<ClassifierResult>;\n}\n\nexport interface MutableModels extends Models {\n\t/** Upsert/replace by provider.id. Provider ids are unique. */\n\tsetProvider(provider: Provider): void;\n\tdeleteProvider(id: string): void;\n\tclearProviders(): void;\n}\n\nexport interface CreateModelsOptions {\n\tcredentials?: CredentialStore;\n\tmodelsStore?: ModelsStore;\n\tauthContext?: AuthContext;\n}\n\nfunction mergeHeaders(\n\tbase: ProviderHeaders | undefined,\n\toverride: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!base && !override) return undefined;\n\tconst merged = { ...base };\n\tfor (const [name, value] of Object.entries(override ?? {})) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tfor (const existingName of Object.keys(merged)) {\n\t\t\tif (existingName.toLowerCase() === lowerName) delete merged[existingName];\n\t\t}\n\t\tmerged[name] = value;\n\t}\n\treturn merged;\n}\n\nclass ModelsImpl implements MutableModels {\n\tprivate providers = new Map<string, Provider>();\n\tprivate credentials: CredentialStore;\n\tprivate modelsStore: ModelsStore;\n\tprivate authContext: AuthContext;\n\tprivate refreshGenerations = new Map<string, number>();\n\tprivate refreshControllers = new Map<string, AbortController>();\n\tprivate publicationChains = new Map<string, Promise<unknown>>();\n\n\tconstructor(options?: CreateModelsOptions) {\n\t\tthis.credentials = options?.credentials ?? new InMemoryCredentialStore();\n\t\tthis.modelsStore = options?.modelsStore ?? new InMemoryModelsStore();\n\t\tthis.authContext = options?.authContext ?? defaultAuthContext();\n\t}\n\n\tsetProvider(provider: Provider): void {\n\t\tthis.supersedeProviderRefresh(provider.id);\n\t\tthis.providers.set(provider.id, provider);\n\t}\n\n\tdeleteProvider(id: string): void {\n\t\tthis.supersedeProviderRefresh(id);\n\t\tthis.providers.delete(id);\n\t}\n\n\tclearProviders(): void {\n\t\tfor (const id of new Set([...this.providers.keys(), ...this.refreshControllers.keys()])) {\n\t\t\tthis.supersedeProviderRefresh(id);\n\t\t}\n\t\tthis.providers.clear();\n\t}\n\n\tgetProviders(): readonly Provider[] {\n\t\treturn Array.from(this.providers.values());\n\t}\n\n\tgetProvider(id: string): Provider | undefined {\n\t\treturn this.providers.get(id);\n\t}\n\n\tgetModels(provider?: string): readonly Model<Api>[] {\n\t\tif (provider !== undefined) {\n\t\t\tconst entry = this.providers.get(provider);\n\t\t\tif (!entry) return [];\n\t\t\ttry {\n\t\t\t\treturn entry.getModels();\n\t\t\t} catch {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t}\n\n\t\tconst models: Model<Api>[] = [];\n\t\tfor (const entry of this.providers.values()) {\n\t\t\ttry {\n\t\t\t\tmodels.push(...entry.getModels());\n\t\t\t} catch {\n\t\t\t\t// Best-effort: ill-behaved providers yield no models.\n\t\t\t}\n\t\t}\n\t\treturn models;\n\t}\n\n\tgetAllModels(provider?: string): readonly AnyModel[] {\n\t\tif (provider !== undefined) {\n\t\t\tconst entry = this.providers.get(provider);\n\t\t\tif (!entry) return [];\n\t\t\ttry {\n\t\t\t\treturn entry.getAllModels?.() ?? entry.getModels();\n\t\t\t} catch {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t}\n\n\t\tconst models: AnyModel[] = [];\n\t\tfor (const entry of this.providers.values()) {\n\t\t\ttry {\n\t\t\t\tmodels.push(...(entry.getAllModels?.() ?? entry.getModels()));\n\t\t\t} catch {\n\t\t\t\t// Best-effort: ill-behaved providers yield no models.\n\t\t\t}\n\t\t}\n\t\treturn models;\n\t}\n\n\tgetModelsOfType<TType extends ModelType>(type: TType, provider?: string): readonly ModelTypeMap[TType][] {\n\t\treturn this.getAllModels(provider).filter((model): model is ModelTypeMap[TType] => isModelType(model, type));\n\t}\n\n\tgetModel(provider: string, id: string): Model<Api> | undefined {\n\t\treturn this.getModels(provider).find((model) => model.id === id);\n\t}\n\n\tgetModelOfType<TType extends ModelType>(type: TType, provider: string, id: string): ModelTypeMap[TType] | undefined {\n\t\treturn this.getModelsOfType(type, provider).find((model) => model.id === id);\n\t}\n\n\tprivate supersedeProviderRefresh(providerId: string): number {\n\t\tconst generation = (this.refreshGenerations.get(providerId) ?? 0) + 1;\n\t\tthis.refreshGenerations.set(providerId, generation);\n\t\tconst previous = this.refreshControllers.get(providerId);\n\t\tif (previous) {\n\t\t\tthis.refreshControllers.delete(providerId);\n\t\t\tprevious.abort();\n\t\t}\n\t\treturn generation;\n\t}\n\n\tprivate beginProviderRefresh(providerId: string): { generation: number; controller: AbortController } {\n\t\tconst generation = this.supersedeProviderRefresh(providerId);\n\t\tconst controller = new AbortController();\n\t\tthis.refreshControllers.set(providerId, controller);\n\t\treturn { generation, controller };\n\t}\n\n\tprivate publishProviderModels(\n\t\tproviderId: string,\n\t\tgeneration: number,\n\t\tsignal: AbortSignal,\n\t\tpublication: ModelsPublication,\n\t): Promise<boolean> {\n\t\tconst previous = this.publicationChains.get(providerId) ?? Promise.resolve();\n\t\tconst queued = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\tif (signal.aborted || this.refreshGenerations.get(providerId) !== generation) return false;\n\n\t\t\tif (publication.persist === null) {\n\t\t\t\tawait this.modelsStore.delete(providerId, { signal });\n\t\t\t} else if (publication.persist !== undefined) {\n\t\t\t\tawait this.modelsStore.write(providerId, structuredClone(publication.persist), { signal });\n\t\t\t}\n\n\t\t\tif (signal.aborted || this.refreshGenerations.get(providerId) !== generation) return false;\n\t\t\tpublication.update?.();\n\t\t\treturn true;\n\t\t})();\n\t\tconst tail = queued.catch(() => {});\n\t\tthis.publicationChains.set(providerId, tail);\n\t\tvoid tail.then(() => {\n\t\t\tif (this.publicationChains.get(providerId) === tail) this.publicationChains.delete(providerId);\n\t\t});\n\t\treturn raceWithAbortSignal(queued, signal);\n\t}\n\n\tprivate async runProviderRefreshPhase(\n\t\tprovider: Provider & Required<Pick<Provider, \"refreshModels\">>,\n\t\tcredential: Credential | undefined,\n\t\tallowNetwork: boolean,\n\t\tforce: boolean | undefined,\n\t\tgeneration: number,\n\t\tsignal: AbortSignal,\n\t): Promise<void> {\n\t\tconst stored = await this.modelsStore.read(provider.id, { signal });\n\t\tawait provider.refreshModels({\n\t\t\tcredential,\n\t\t\tstored: stored ? withKnownModelTypes(structuredClone(stored)) : undefined,\n\t\t\tpublish: (publication) => this.publishProviderModels(provider.id, generation, signal, publication),\n\t\t\tallowNetwork,\n\t\t\tforce: allowNetwork ? force : undefined,\n\t\t\tsignal,\n\t\t});\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<ModelsRefreshResult> {\n\t\tconst allowNetwork = options.allowNetwork ?? true;\n\t\tconst callerSignal = operationSignal(options.signal);\n\t\tconst errors = new Map<string, Error>();\n\t\tif (callerSignal.aborted) return { aborted: true, errors };\n\t\tconst selected = options.providers ? new Set(options.providers) : undefined;\n\t\tconst refreshable = Array.from(this.providers.values()).filter(\n\t\t\t(provider): provider is Provider & Required<Pick<Provider, \"refreshModels\">> =>\n\t\t\t\tprovider.refreshModels !== undefined && (!selected || selected.has(provider.id)),\n\t\t);\n\n\t\tconst refresh = Promise.all(\n\t\t\trefreshable.map(async (provider) => {\n\t\t\t\tconst { generation, controller } = this.beginProviderRefresh(provider.id);\n\t\t\t\tconst signal = AbortSignal.any([callerSignal, controller.signal]);\n\t\t\t\tconst operation = (async () => {\n\t\t\t\t\tlet storedCredential: Credential | undefined;\n\t\t\t\t\tlet credentialError: unknown;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tstoredCredential = await this.readCredential(provider.id, signal);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tcredentialError = error;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Restore cached provider state before auth resolution or network access.\n\t\t\t\t\tawait this.runProviderRefreshPhase(provider, storedCredential, false, undefined, generation, signal);\n\t\t\t\t\tif (credentialError !== undefined) throw credentialError;\n\t\t\t\t\tif (!allowNetwork || signal.aborted) return;\n\n\t\t\t\t\tconst credential = await this.resolveRefreshCredential(provider, storedCredential, signal);\n\t\t\t\t\tif (!credential) return;\n\t\t\t\t\tawait this.runProviderRefreshPhase(provider, credential, true, options.force, generation, signal);\n\t\t\t\t})();\n\n\t\t\t\ttry {\n\t\t\t\t\tawait raceWithAbortSignal(operation, signal);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!signal.aborted) {\n\t\t\t\t\t\terrors.set(\n\t\t\t\t\t\t\tprovider.id,\n\t\t\t\t\t\t\terror instanceof Error\n\t\t\t\t\t\t\t\t? error\n\t\t\t\t\t\t\t\t: new ModelsError(\"model_source\", `Model refresh failed for ${provider.id}`, { cause: error }),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tif (this.refreshControllers.get(provider.id) === controller) {\n\t\t\t\t\t\tthis.refreshControllers.delete(provider.id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\n\t\ttry {\n\t\t\tawait raceWithAbortSignal(refresh, callerSignal);\n\t\t} catch (error) {\n\t\t\tif (!callerSignal.aborted) throw error;\n\t\t}\n\n\t\treturn { aborted: callerSignal.aborted, errors: new Map(errors) };\n\t}\n\n\tprivate async resolveRefreshCredential(\n\t\tprovider: Provider,\n\t\tstored: Credential | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<Credential | undefined> {\n\t\tif (stored?.type === \"oauth\") {\n\t\t\tconst oauth = provider.auth.oauth;\n\t\t\tif (!oauth) return undefined;\n\t\t\tif (Date.now() < stored.expires) return stored;\n\t\t\tif (signal.aborted) return undefined;\n\t\t\tconst post = await this.credentials.modify(\n\t\t\t\tprovider.id,\n\t\t\t\tasync (current) => {\n\t\t\t\t\tif (current?.type !== \"oauth\" || Date.now() < current.expires) return undefined;\n\t\t\t\t\treturn oauth.refresh(current, signal);\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t\treturn post?.type === \"oauth\" ? post : undefined;\n\t\t}\n\n\t\tconst apiKey = provider.auth.apiKey;\n\t\tif (!apiKey) return undefined;\n\t\tconst credential = stored?.type === \"api_key\" ? stored : undefined;\n\t\tconst result = await apiKey.resolve({ ctx: this.authContext, credential, signal });\n\t\tif (!result) return undefined;\n\t\treturn { type: \"api_key\", key: result.auth.apiKey, env: result.env };\n\t}\n\n\tprivate async readCredential(providerId: string, signal: AbortSignal): Promise<Credential | undefined> {\n\t\ttry {\n\t\t\treturn await this.credentials.read(providerId, { signal });\n\t\t} catch (error) {\n\t\t\tthrow new ModelsError(\"auth\", `Credential store read failed for ${providerId}`, { cause: error });\n\t\t}\n\t}\n\n\tprivate async checkProviderAuth(\n\t\tprovider: Provider,\n\t\tcredential: Credential | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<AuthCheck | undefined> {\n\t\tif (credential?.type === \"oauth\") {\n\t\t\treturn provider.auth.oauth ? { source: \"OAuth\", type: \"oauth\" } : undefined;\n\t\t}\n\t\tconst apiKey = provider.auth.apiKey;\n\t\tif (!apiKey) return undefined;\n\t\tif (apiKey.check) {\n\t\t\ttry {\n\t\t\t\treturn await apiKey.check({\n\t\t\t\t\tctx: this.authContext,\n\t\t\t\t\tcredential: credential?.type === \"api_key\" ? credential : undefined,\n\t\t\t\t\tsignal,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow new ModelsError(\"auth\", `API key auth check failed for provider ${provider.id}`, { cause: error });\n\t\t\t}\n\t\t}\n\n\t\tconst resolution = await resolveProviderAuth(provider, this.credentials, this.authContext, { signal });\n\t\treturn resolution ? { source: resolution.source, type: \"api_key\" } : undefined;\n\t}\n\n\tcheckAuth(providerId: string, options?: AuthOperationOptions): Promise<AuthCheck | undefined> {\n\t\tconst signal = operationSignal(options?.signal);\n\t\tconst check = (async () => {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst provider = this.providers.get(providerId);\n\t\t\tif (!provider) return undefined;\n\t\t\treturn this.checkProviderAuth(provider, await this.readCredential(providerId, signal), signal);\n\t\t})();\n\t\treturn raceWithAbortSignal(check, signal);\n\t}\n\n\tprivate async getAuthenticatedProviders(providerId: string | undefined, signal: AbortSignal) {\n\t\tsignal.throwIfAborted();\n\t\tconst providers = providerId\n\t\t\t? [this.providers.get(providerId)].filter((entry) => entry !== undefined)\n\t\t\t: this.getProviders();\n\t\tconst checks = await Promise.all(\n\t\t\tproviders.map(async (provider) => {\n\t\t\t\tconst credential = await this.readCredential(provider.id, signal);\n\t\t\t\treturn { provider, credential, auth: await this.checkProviderAuth(provider, credential, signal) };\n\t\t\t}),\n\t\t);\n\t\treturn checks.filter((entry) => entry.auth !== undefined);\n\t}\n\n\tgetAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly Model<Api>[]> {\n\t\tconst signal = operationSignal(options?.signal);\n\t\tconst available = (async () => {\n\t\t\tconst providers = await this.getAuthenticatedProviders(providerId, signal);\n\t\t\treturn providers.flatMap(({ provider, credential }) => {\n\t\t\t\tconst models = provider.getModels();\n\t\t\t\treturn provider.filterModels?.(models, credential) ?? models;\n\t\t\t});\n\t\t})();\n\t\treturn raceWithAbortSignal(available, signal);\n\t}\n\n\tasync getAvailableOfType<TType extends ModelType>(\n\t\ttype: TType,\n\t\tproviderId?: string,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<readonly ModelTypeMap[TType][]> {\n\t\treturn (await this.getAllAvailable(providerId, options)).filter((model): model is ModelTypeMap[TType] =>\n\t\t\tisModelType(model, type),\n\t\t);\n\t}\n\n\tgetAllAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly AnyModel[]> {\n\t\tconst signal = operationSignal(options?.signal);\n\t\tconst available = (async () => {\n\t\t\tconst providers = await this.getAuthenticatedProviders(providerId, signal);\n\t\t\treturn providers.flatMap(({ provider, credential }) => {\n\t\t\t\tconst models = provider.getAllModels?.() ?? provider.getModels();\n\t\t\t\tif (provider.filterAllModels) return provider.filterAllModels(models, credential);\n\t\t\t\tif (!provider.filterModels) return models;\n\t\t\t\tconst availableChatIds = new Set(\n\t\t\t\t\tprovider.filterModels(provider.getModels(), credential).map((model) => model.id),\n\t\t\t\t);\n\t\t\t\treturn models.filter((model) => !isModelType(model, \"chat\") || availableChatIds.has(model.id));\n\t\t\t});\n\t\t})();\n\t\treturn raceWithAbortSignal(available, signal);\n\t}\n\n\tgetAuth(providerId: string, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: AnyModel, overrides?: AuthResolutionOverrides): Promise<AuthResult | undefined>;\n\tasync getAuth(\n\t\tproviderOrModel: string | AnyModel,\n\t\toverrides?: AuthResolutionOverrides,\n\t): Promise<AuthResult | undefined> {\n\t\tconst signal = operationSignal(overrides?.signal);\n\t\tconst providerId = typeof providerOrModel === \"string\" ? providerOrModel : providerOrModel.provider;\n\t\tconst provider = this.providers.get(providerId);\n\t\tif (!provider) return undefined;\n\t\tconst result = await resolveProviderAuth(provider, this.credentials, this.authContext, { ...overrides, signal });\n\t\tif (!result || typeof providerOrModel === \"string\" || !providerOrModel.headers) return result;\n\t\treturn {\n\t\t\t...result,\n\t\t\tauth: {\n\t\t\t\t...result.auth,\n\t\t\t\theaders: mergeHeaders(result.auth.headers, providerOrModel.headers),\n\t\t\t},\n\t\t};\n\t}\n\n\tasync login(\n\t\tproviderId: string,\n\t\ttype: AuthType,\n\t\tinteraction: AuthInteraction,\n\t\toptions?: LoginOptions,\n\t): Promise<Credential> {\n\t\tconst signal = operationSignal(interaction.signal);\n\t\tsignal.throwIfAborted();\n\t\tconst provider = this.providers.get(providerId);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${providerId}`);\n\t\tconst method = type === \"oauth\" ? provider.auth.oauth : provider.auth.apiKey;\n\t\tif (!method?.login) {\n\t\t\tthrow new ModelsError(\"auth\", `${provider.name} does not support ${type} login`);\n\t\t}\n\t\tconst loginOperation: Promise<Credential> = method.login({ ...interaction, signal }, options);\n\t\tconst credential = await raceWithAbortSignal(loginOperation, signal);\n\t\tlet mutationStarted = false;\n\t\tlet markMutationStarted: (() => void) | undefined;\n\t\tconst started = new Promise<void>((resolve) => {\n\t\t\tmarkMutationStarted = resolve;\n\t\t});\n\t\tconst mutation = this.credentials.modify(\n\t\t\tproviderId,\n\t\t\tasync () => {\n\t\t\t\tmutationStarted = true;\n\t\t\t\tmarkMutationStarted?.();\n\t\t\t\treturn credential;\n\t\t\t},\n\t\t\t{ signal },\n\t\t);\n\t\tvoid mutation.catch(() => {});\n\t\ttry {\n\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\tconst onAbort = () => {\n\t\t\t\t\tif (!mutationStarted) reject(signal.reason);\n\t\t\t\t};\n\t\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\tvoid Promise.race([started, mutation]).then(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t},\n\t\t\t\t\t(error: unknown) => {\n\t\t\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t});\n\t\t\tawait mutation;\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow new ModelsError(\"auth\", `Credential store modify failed for ${providerId}`, { cause: error });\n\t\t}\n\t\treturn credential;\n\t}\n\n\tasync logout(providerId: string, options?: AuthOperationOptions): Promise<void> {\n\t\tconst signal = operationSignal(options?.signal);\n\t\tsignal.throwIfAborted();\n\t\ttry {\n\t\t\tawait this.credentials.delete(providerId, { signal });\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow new ModelsError(\"auth\", `Credential store delete failed for ${providerId}`, { cause: error });\n\t\t}\n\t}\n\n\tprivate requireProvider(model: AnyModel): Provider {\n\t\tconst provider = this.providers.get(model.provider);\n\t\tif (!provider) {\n\t\t\tthrow new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\t}\n\t\treturn provider;\n\t}\n\n\tprivate requireChatProvider(model: Model<Api>): Provider {\n\t\tassertChatModel(model);\n\t\treturn this.requireProvider(model);\n\t}\n\n\tprivate async applyAuth<\n\t\tTModel extends AnyModel,\n\t\tTOptions extends ProviderRequestOptions<TModel> & ModelsRequestTransforms,\n\t>(\n\t\tmodel: TModel,\n\t\toptions: TOptions | undefined,\n\t): Promise<{\n\t\trequestModel: TModel;\n\t\trequestOptions: Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions<TModel>;\n\t}> {\n\t\tthis.requireProvider(model);\n\t\tconst resolution = await this.getAuth(model, {\n\t\t\tapiKey: options?.apiKey,\n\t\t\tenv: options?.env,\n\t\t\tsignal: options?.signal,\n\t\t});\n\t\tif (!resolution) {\n\t\t\tthrow new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\t\t}\n\t\tconst auth = resolution.auth;\n\n\t\t// Explicit request options win per-field; the Models-only transform runs last.\n\t\tconst apiKey = options?.apiKey ?? auth.apiKey;\n\t\tlet headers = mergeHeaders(auth.headers, options?.headers);\n\t\tif (options?.transformHeaders) headers = await options.transformHeaders(headers ?? {});\n\t\tconst env = resolution.env || options?.env ? { ...(resolution.env ?? {}), ...(options?.env ?? {}) } : undefined;\n\t\tconst requestModel: TModel = auth.baseUrl ? { ...model, baseUrl: auth.baseUrl } : model;\n\t\tconst { transformHeaders: _transformHeaders, ...providerOptions } = options ?? {};\n\t\tconst requestOptions = { ...providerOptions, apiKey, headers, env } as Omit<TOptions, \"transformHeaders\"> &\n\t\t\tProviderRequestOptions<TModel>;\n\n\t\treturn { requestModel, requestOptions };\n\t}\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream {\n\t\tconst transcript = normalizeContext(context);\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst provider = this.requireChatProvider(model);\n\t\t\tconst { requestModel, requestOptions } = await this.applyAuth(\n\t\t\t\tmodel,\n\t\t\t\toptions as ModelsApiStreamOptions<Api> | undefined,\n\t\t\t);\n\t\t\treturn provider.stream(requestModel, transcript, requestOptions as ApiStreamOptions<TApi>);\n\t\t});\n\t}\n\n\tasync complete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage> {\n\t\treturn this.stream(model, context, options).result();\n\t}\n\n\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream {\n\t\tconst transcript = normalizeContext(context);\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst provider = this.requireChatProvider(model);\n\t\t\tconst { requestModel, requestOptions } = await this.applyAuth(model, options);\n\t\t\treturn provider.streamSimple(requestModel, transcript, requestOptions as SimpleStreamOptions);\n\t\t});\n\t}\n\n\tasync completeSimple(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions?: ModelsSimpleStreamOptions,\n\t): Promise<AssistantMessage> {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n\n\tstreamDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst provider = this.requireChatProvider(model);\n\t\t\tif (!provider.fetchDeferred) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t\t}\n\t\t\tconst { requestModel, requestOptions } = await this.applyAuth(model, options);\n\t\t\treturn provider.fetchDeferred(requestModel, handle, requestOptions as DeferredFetchOptions);\n\t\t});\n\t}\n\n\tasync fetchDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): Promise<AssistantMessage> {\n\t\treturn this.streamDeferred(model, handle, options).result();\n\t}\n\n\tasync cancelDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredCancelOptions,\n\t): Promise<void> {\n\t\tconst provider = this.requireChatProvider(model);\n\t\tif (!provider.cancelDeferred) {\n\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t}\n\t\tconst { requestModel, requestOptions } = await this.applyAuth(model, options);\n\t\tawait provider.cancelDeferred(requestModel, handle, requestOptions);\n\t}\n\n\tasync generateImages(\n\t\tmodel: ImageModel<ImageApi>,\n\t\tcontext: ImagesContext,\n\t\toptions?: ModelsImagesOptions,\n\t): Promise<AssistantImages> {\n\t\ttry {\n\t\t\tassertImageModel(model);\n\t\t\tconst provider = this.requireProvider(model);\n\t\t\tif (!provider.generateImages) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support image generation`);\n\t\t\t}\n\t\t\tconst { requestModel, requestOptions } = await this.applyAuth(model, options);\n\t\t\treturn await provider.generateImages(requestModel, context, requestOptions);\n\t\t} catch (error) {\n\t\t\treturn imageErrorResult(model, error, options?.signal?.aborted);\n\t\t}\n\t}\n\n\tasync classify(\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ModelsClassifierOptions,\n\t): Promise<ClassifierResult> {\n\t\ttry {\n\t\t\tassertClassifierModel(model);\n\t\t\tconst provider = this.requireProvider(model);\n\t\t\tif (!provider.classify) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support classification`);\n\t\t\t}\n\t\t\tconst { requestModel, requestOptions } = await this.applyAuth(model, options);\n\t\t\treturn await provider.classify(requestModel, context, requestOptions);\n\t\t} catch (error) {\n\t\t\treturn classifierErrorResult(model, error, options?.signal?.aborted);\n\t\t}\n\t}\n}\n\nexport function createModels(options?: CreateModelsOptions): MutableModels {\n\treturn new ModelsImpl(options);\n}\n\nexport interface CreateProviderOptions<TApi extends Api = Api> {\n\tid: string;\n\t/** Display name. Default: `id`. */\n\tname?: string;\n\tbaseUrl?: string;\n\theaders?: ProviderHeaders;\n\t/** Required — every provider has auth semantics, even ambient/keyless ones. */\n\tauth: ProviderAuth;\n\t/**\n\t * Static baseline models of every type (empty for purely dynamic providers).\n\t * Models without `type` are chat models.\n\t */\n\tmodels: readonly ProviderModel<TApi>[];\n\t/**\n\t * Fetch a dynamic model overlay of every type. createProvider restores and\n\t * publishes it transactionally and drops models of unknown types.\n\t */\n\tfetchModels?: (context: RefreshModelsContext) => Promise<readonly ProviderModel<TApi>[]>;\n\t/** Credential-specific chat model availability. See `Provider.filterModels`. */\n\tfilterModels?: (models: readonly Model<TApi>[], credential: Credential | undefined) => readonly Model<TApi>[];\n\t/** Credential-specific availability across every model type. See `Provider.filterAllModels`. */\n\tfilterAllModels?: (\n\t\tmodels: readonly ProviderModel<TApi>[],\n\t\tcredential: Credential | undefined,\n\t) => readonly ProviderModel<TApi>[];\n\t/**\n\t * Chat implementation: a single one for all chat models, or a map keyed by\n\t * `model.api` for mixed-API providers. Optional when `images` or\n\t * `classifiers` is given.\n\t */\n\tapi?: ProviderStreams | Partial<Record<TApi, ProviderStreams>>;\n\t/** Image-generation implementations keyed by `model.api`. */\n\timages?: Partial<Record<ImageApi, ProviderImages>>;\n\t/** Classifier implementations keyed by `model.api`. */\n\tclassifiers?: Partial<Record<ClassifierApi, ProviderClassifier>>;\n}\n\n/**\n * Builds a provider from parts. Built-in provider factories and models.json\n * custom providers both go through this. A single `api` streams all chat\n * models; an `api` map dispatches on `model.api`, and a model whose api has\n * no entry produces a stream error. One-shot operation maps dispatch on\n * `model.api` the same way. At least one concrete implementation across\n * `api`/`images`/`classifiers` is required; empty maps are rejected.\n */\nexport function createProvider<TApi extends Api = Api>(input: CreateProviderOptions<TApi>): Provider<TApi> {\n\tconst single =\n\t\tinput.api && typeof (input.api as ProviderStreams).stream === \"function\"\n\t\t\t? (input.api as ProviderStreams)\n\t\t\t: undefined;\n\tconst byApi = single || !input.api ? undefined : (input.api as Partial<Record<string, ProviderStreams>>);\n\tconst images = input.images as Partial<Record<string, ProviderImages>> | undefined;\n\tconst classifiers = input.classifiers as Partial<Record<string, ProviderClassifier>> | undefined;\n\tconst streams = single ? [single] : Object.values(byApi ?? {}).filter((entry) => entry !== undefined);\n\tconst imageImplementations = Object.values(images ?? {}).filter((entry) => entry !== undefined);\n\tconst classifierImplementations = Object.values(classifiers ?? {}).filter((entry) => entry !== undefined);\n\tif (streams.length === 0 && imageImplementations.length === 0 && classifierImplementations.length === 0) {\n\t\tthrow new Error(`Provider ${input.id}: at least one of \"api\", \"images\", or \"classifiers\" is required.`);\n\t}\n\n\tconst baselineModels = input.models;\n\tlet dynamicModels: readonly ProviderModel<TApi>[] = [];\n\tconst fetchModels = input.fetchModels;\n\tconst currentModels = (): readonly ProviderModel<TApi>[] => {\n\t\tconst merged = [...baselineModels];\n\t\tfor (const model of dynamicModels) {\n\t\t\tconst index = merged.findIndex(\n\t\t\t\t(entry) => getModelType(entry) === getModelType(model) && entry.id === model.id,\n\t\t\t);\n\t\t\tif (index >= 0) merged[index] = model;\n\t\t\telse merged.push(model);\n\t\t}\n\t\treturn merged;\n\t};\n\tconst apiFor = (model: Model<Api>): ProviderStreams | undefined => single ?? byApi?.[model.api];\n\n\tconst dispatch = (\n\t\tmodel: Model<Api>,\n\t\trun: (streams: ProviderStreams) => AssistantMessageEventStream,\n\t): AssistantMessageEventStream => {\n\t\tconst streams = apiFor(model);\n\t\tif (!streams) {\n\t\t\treturn lazyStream(model, async () => {\n\t\t\t\tthrow new ModelsError(\"stream\", `Provider ${input.id} has no API implementation for \"${model.api}\"`);\n\t\t\t});\n\t\t}\n\t\treturn run(streams);\n\t};\n\n\tconst provider: Provider<TApi> = {\n\t\tid: input.id,\n\t\tname: input.name ?? input.id,\n\t\tbaseUrl: input.baseUrl,\n\t\theaders: input.headers,\n\t\tauth: input.auth,\n\t\tgetModels: () => currentModels().filter((model): model is Model<TApi> => isModelType(model, \"chat\")),\n\t\tgetAllModels: currentModels,\n\t\trefreshModels: fetchModels\n\t\t\t? async (context) => {\n\t\t\t\t\tif (context.stored) {\n\t\t\t\t\t\tconst restored = context.stored.models\n\t\t\t\t\t\t\t.filter((model) => model.provider === input.id)\n\t\t\t\t\t\t\t.map((model) => model as ProviderModel<TApi>);\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!(await context.publish({\n\t\t\t\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\t\t\t\tdynamicModels = restored;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}))\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\t\t\t\t\tconst fetched = await fetchModels(context);\n\t\t\t\t\tif (context.signal.aborted) return;\n\t\t\t\t\tconst refreshed = fetched.filter(hasKnownModelType);\n\t\t\t\t\tawait context.publish({\n\t\t\t\t\t\tpersist: { models: refreshed, checkedAt: Date.now() },\n\t\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\t\tdynamicModels = refreshed;\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t: undefined,\n\t\tfilterModels: input.filterModels,\n\t\tfilterAllModels: input.filterAllModels,\n\t\tstream: (model, context, options) => dispatch(model, (streams) => streams.stream(model, context, options)),\n\t\tstreamSimple: (model, context, options) =>\n\t\t\tdispatch(model, (streams) => streams.streamSimple(model, context, options)),\n\t};\n\n\tif (streams.some((entry) => entry.fetchDeferred !== undefined)) {\n\t\tprovider.fetchDeferred = (model, handle, options) =>\n\t\t\tlazyStream(model, async () => {\n\t\t\t\tconst implementation = apiFor(model);\n\t\t\t\tif (!implementation?.fetchDeferred) {\n\t\t\t\t\tthrow new ModelsError(\n\t\t\t\t\t\t\"provider\",\n\t\t\t\t\t\t`Provider ${input.id} does not support deferred responses for \"${model.api}\"`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn implementation.fetchDeferred(model, handle, options);\n\t\t\t});\n\t}\n\tif (streams.some((entry) => entry.cancelDeferred !== undefined)) {\n\t\tprovider.cancelDeferred = async (model, handle, options) => {\n\t\t\tconst implementation = apiFor(model);\n\t\t\tif (!implementation?.cancelDeferred) {\n\t\t\t\tthrow new ModelsError(\n\t\t\t\t\t\"provider\",\n\t\t\t\t\t`Provider ${input.id} cannot cancel deferred responses for \"${model.api}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait implementation.cancelDeferred(model, handle, options);\n\t\t};\n\t}\n\tif (images && imageImplementations.length > 0) {\n\t\tprovider.generateImages = async (model, context, options) => {\n\t\t\tconst implementation = images[model.api];\n\t\t\tif (!implementation) {\n\t\t\t\treturn imageErrorResult(\n\t\t\t\t\tmodel,\n\t\t\t\t\tnew ModelsError(\n\t\t\t\t\t\t\"provider\",\n\t\t\t\t\t\t`Provider ${input.id} has no image generation implementation for \"${model.api}\"`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn implementation.generateImages(model, context, options);\n\t\t};\n\t}\n\tif (classifiers && classifierImplementations.length > 0) {\n\t\tprovider.classify = async (model, context, options) => {\n\t\t\tconst implementation = classifiers[model.api];\n\t\t\tif (!implementation) {\n\t\t\t\treturn classifierErrorResult(\n\t\t\t\t\tmodel,\n\t\t\t\t\tnew ModelsError(\"provider\", `Provider ${input.id} has no classifier implementation for \"${model.api}\"`),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn implementation.classify(model, context, options);\n\t\t};\n\t}\n\n\treturn provider;\n}\n\n/**\n * Runtime-checked narrowing for dynamically looked-up models:\n *\n * ```ts\n * const model = models.getModel(\"anthropic\", \"claude-opus-5-5\");\n * if (model && hasApi(model, \"anthropic-messages\")) {\n * // model: Model<\"anthropic-messages\">, stream options fully typed\n * }\n * ```\n *\n * Non-chat models never match, even when their api id equals `api`.\n */\nexport function hasApi<TApi extends Api>(model: AnyModel, api: TApi): model is Model<TApi> {\n\treturn isModelType(model, \"chat\") && model.api === api;\n}\n\nexport function calculateCost(model: AnyModel, usage: Usage): Usage[\"cost\"] {\n\tconst inputTokens = usage.input + usage.cacheRead + usage.cacheWrite;\n\tlet rates: ModelCostRates = model.cost;\n\tlet matchedThreshold = -1;\n\tfor (const tier of model.cost.tiers ?? []) {\n\t\tif (inputTokens > tier.inputTokensAbove && tier.inputTokensAbove > matchedThreshold) {\n\t\t\trates = tier;\n\t\t\tmatchedThreshold = tier.inputTokensAbove;\n\t\t}\n\t}\n\n\t// Anthropic charges 2x base input for 1h cache writes.\n\tconst longWrite = usage.cacheWrite1h ?? 0;\n\tconst shortWrite = usage.cacheWrite - longWrite;\n\tusage.cost.input = (rates.input / 1000000) * usage.input;\n\tusage.cost.output = (rates.output / 1000000) * usage.output;\n\tusage.cost.cacheRead = (rates.cacheRead / 1000000) * usage.cacheRead;\n\tusage.cost.cacheWrite = (rates.cacheWrite * shortWrite + rates.input * 2 * longWrite) / 1000000;\n\tusage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n\treturn usage.cost;\n}\n\nconst EXTENDED_THINKING_LEVELS: ModelThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n\nexport function getSupportedThinkingLevels<TApi extends Api>(model: Model<TApi>): ModelThinkingLevel[] {\n\tif (!model.reasoning) return [\"off\"];\n\n\treturn EXTENDED_THINKING_LEVELS.filter((level) => {\n\t\tconst mapped = model.thinkingLevelMap?.[level];\n\t\tif (mapped === null) return false;\n\t\tif (level === \"xhigh\" || level === \"max\") return mapped !== undefined;\n\t\treturn true;\n\t});\n}\n\nexport function clampThinkingLevel<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tlevel: ModelThinkingLevel,\n): ModelThinkingLevel {\n\tconst availableLevels = getSupportedThinkingLevels(model);\n\tif (availableLevels.includes(level)) return level;\n\n\tconst requestedIndex = EXTENDED_THINKING_LEVELS.indexOf(level);\n\tif (requestedIndex === -1) return availableLevels[0] ?? \"off\";\n\n\tfor (let i = requestedIndex; i < EXTENDED_THINKING_LEVELS.length; i++) {\n\t\tconst candidate = EXTENDED_THINKING_LEVELS[i];\n\t\tif (availableLevels.includes(candidate)) return candidate;\n\t}\n\tfor (let i = requestedIndex - 1; i >= 0; i--) {\n\t\tconst candidate = EXTENDED_THINKING_LEVELS[i];\n\t\tif (availableLevels.includes(candidate)) return candidate;\n\t}\n\treturn availableLevels[0] ?? \"off\";\n}\n\n/**\n * Check if a model supports xhigh thinking level.\n */\nexport function supportsXhigh<TApi extends Api>(model: Model<TApi>): boolean {\n\tif (model.id.includes(\"gpt-5.2\") || model.id.includes(\"gpt-5.3\") || model.id.includes(\"gpt-5.4\")) {\n\t\treturn true;\n\t}\n\tif (\n\t\tmodel.id.includes(\"opus-4-6\") ||\n\t\tmodel.id.includes(\"opus-4.6\") ||\n\t\tmodel.id.includes(\"opus-4-7\") ||\n\t\tmodel.id.includes(\"opus-4.7\") ||\n\t\tmodel.id.includes(\"sonnet-4-6\") ||\n\t\tmodel.id.includes(\"sonnet-4.6\") ||\n\t\tmodel.id.includes(\"haiku-4-5\") ||\n\t\tmodel.id.includes(\"haiku-4.5\")\n\t) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n/**\n * Check if a model supports the max thinking level.\n * Currently Anthropic Opus 4.6 and Opus 4.7 only.\n */\nexport function supportsMax<TApi extends Api>(model: Model<TApi>): boolean {\n\treturn (\n\t\tmodel.id.includes(\"opus-4-6\") ||\n\t\tmodel.id.includes(\"opus-4.6\") ||\n\t\tmodel.id.includes(\"opus-4-7\") ||\n\t\tmodel.id.includes(\"opus-4.7\")\n\t);\n}\n\n/**\n * Check if two models are equal by comparing their type, id, and provider.\n * Returns false if either model is null or undefined.\n */\nexport function modelsAreEqual(a: AnyModel | null | undefined, b: AnyModel | null | undefined): boolean {\n\tif (!a || !b) return false;\n\treturn getModelType(a) === getModelType(b) && a.id === b.id && a.provider === b.provider;\n}\n"]}
|
package/dist/utils/oauth-page.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const LOGO_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="
|
|
1
|
+
const LOGO_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="120 108 296 296" aria-hidden="true"><g fill="none" stroke="#fff" stroke-width="8" stroke-linejoin="round"><circle cx="157" cy="141" r="10"/><path d="M167 141 H283 A95 115.5 0 0 1 283 372 H219 Q205 372 205 358 V202 Q205 190 217 190 H270 A58 67.5 0 0 1 270 325 H171 Q157 325 157 311 V151"/></g></svg>`;
|
|
2
2
|
function escapeHtml(value) {
|
|
3
3
|
return value
|
|
4
4
|
.replaceAll("&", "&")
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-page.js","sourceRoot":"","sources":["../../src/utils/oauth-page.ts"],"names":[],"mappings":"AAAA,MAAM,QAAQ,GAAG,
|
|
1
|
+
{"version":3,"file":"oauth-page.js","sourceRoot":"","sources":["../../src/utils/oauth-page.ts"],"names":[],"mappings":"AAAA,MAAM,QAAQ,GAAG,6VAA6V,CAAC;AAE/W,SAAS,UAAU,CAAC,KAAa;IAChC,OAAO,KAAK;SACV,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC;SACxB,UAAU,CAAC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8\" stroke-linejoin=\"round\"><circle cx=\"157\" cy=\"141\" r=\"10\"/><path d=\"M167 141 H283 A95 115.5 0 0 1 283 372 H219 Q205 372 205 358 V202 Q205 190 217 190 H270 A58 67.5 0 0 1 270 325 H171 Q157 325 157 311 V151\"/></g></svg>`;\n\nfunction escapeHtml(value: string): string {\n\treturn value\n\t\t.replaceAll(\"&\", \"&\")\n\t\t.replaceAll(\"<\", \"<\")\n\t\t.replaceAll(\">\", \">\")\n\t\t.replaceAll('\"', \""\")\n\t\t.replaceAll(\"'\", \"'\");\n}\n\nfunction renderPage(options: { title: string; heading: string; message: string; details?: string }): string {\n\tconst title = escapeHtml(options.title);\n\tconst heading = escapeHtml(options.heading);\n\tconst message = escapeHtml(options.message);\n\tconst details = options.details ? escapeHtml(options.details) : undefined;\n\n\treturn `<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>${title}</title>\n <style>\n :root {\n --text: #fafafa;\n --text-dim: #a1a1aa;\n --page-bg: #09090b;\n --font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, \"Noto Sans\", sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\", \"Noto Color Emoji\";\n --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace;\n }\n * { box-sizing: border-box; }\n html { color-scheme: dark; }\n body {\n margin: 0;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n background: var(--page-bg);\n color: var(--text);\n font-family: var(--font-sans);\n text-align: center;\n }\n main {\n width: 100%;\n max-width: 560px;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n }\n .logo {\n width: 72px;\n height: 72px;\n display: block;\n margin-bottom: 24px;\n }\n h1 {\n margin: 0 0 10px;\n font-size: 28px;\n line-height: 1.15;\n font-weight: 650;\n color: var(--text);\n }\n p {\n margin: 0;\n line-height: 1.7;\n color: var(--text-dim);\n font-size: 15px;\n }\n .details {\n margin-top: 16px;\n font-family: var(--font-mono);\n font-size: 13px;\n color: var(--text-dim);\n white-space: pre-wrap;\n word-break: break-word;\n }\n </style>\n</head>\n<body>\n <main>\n <div class=\"logo\">${LOGO_SVG}</div>\n <h1>${heading}</h1>\n <p>${message}</p>\n ${details ? `<div class=\"details\">${details}</div>` : \"\"}\n </main>\n</body>\n</html>`;\n}\n\nexport function oauthSuccessHtml(message: string): string {\n\treturn renderPage({\n\t\ttitle: \"Authentication successful\",\n\t\theading: \"Authentication successful\",\n\t\tmessage,\n\t});\n}\n\nexport function oauthErrorHtml(message: string, details?: string): string {\n\treturn renderPage({\n\t\ttitle: \"Authentication failed\",\n\t\theading: \"Authentication failed\",\n\t\tmessage,\n\t\tdetails,\n\t});\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@draht/ai",
|
|
3
|
-
"version": "2026.10.
|
|
3
|
+
"version": "2026.10.8-1",
|
|
4
4
|
"description": "Unified LLM API with automatic model discovery and provider configuration",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
"dependencies": {
|
|
65
65
|
"@anthropic-ai/sdk": "^0.124.0",
|
|
66
66
|
"@aws-sdk/client-bedrock-runtime": "^3.1127.0",
|
|
67
|
-
"@draht/telemetry": "2026.10.
|
|
67
|
+
"@draht/telemetry": "2026.10.8-1",
|
|
68
68
|
"@google/genai": "^2.21.0",
|
|
69
69
|
"chalk": "^5.6.2",
|
|
70
70
|
"http-proxy-agent": "7.0.2",
|