@oh-my-pi/pi-catalog 15.10.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/dist/types/build.d.ts +3 -0
  3. package/dist/types/compat/anthropic.d.ts +11 -0
  4. package/dist/types/compat/apply.d.ts +7 -0
  5. package/dist/types/compat/openai.d.ts +21 -0
  6. package/dist/types/discovery/antigravity.d.ts +61 -0
  7. package/dist/types/discovery/codex.d.ts +38 -0
  8. package/dist/types/discovery/cursor-gen/agent_pb.d.ts +13022 -0
  9. package/dist/types/discovery/cursor.d.ts +23 -0
  10. package/dist/types/discovery/gemini.d.ts +25 -0
  11. package/dist/types/discovery/index.d.ts +4 -0
  12. package/dist/types/discovery/openai-compatible.d.ts +72 -0
  13. package/dist/types/effort.d.ts +9 -0
  14. package/dist/types/fireworks-model-id.d.ts +10 -0
  15. package/dist/types/hosts.d.ts +128 -0
  16. package/dist/types/identity/bundled.d.ts +6 -0
  17. package/dist/types/identity/classify.d.ts +45 -0
  18. package/dist/types/identity/equivalence.d.ts +46 -0
  19. package/dist/types/identity/family.d.ts +45 -0
  20. package/dist/types/identity/id.d.ts +12 -0
  21. package/dist/types/identity/index.d.ts +9 -0
  22. package/dist/types/identity/markers.d.ts +4 -0
  23. package/dist/types/identity/priority.d.ts +1 -0
  24. package/dist/types/identity/reference.d.ts +22 -0
  25. package/dist/types/identity/selection.d.ts +20 -0
  26. package/dist/types/index.d.ts +15 -0
  27. package/dist/types/model-cache.d.ts +17 -0
  28. package/dist/types/model-manager.d.ts +64 -0
  29. package/dist/types/model-thinking.d.ts +67 -0
  30. package/dist/types/models.d.ts +12 -0
  31. package/dist/types/provider-models/bundled-references.d.ts +11 -0
  32. package/dist/types/provider-models/descriptor-types.d.ts +74 -0
  33. package/dist/types/provider-models/descriptors.d.ts +384 -0
  34. package/dist/types/provider-models/discovery-constants.d.ts +11 -0
  35. package/dist/types/provider-models/google.d.ts +27 -0
  36. package/dist/types/provider-models/index.d.ts +6 -0
  37. package/dist/types/provider-models/ollama.d.ts +9 -0
  38. package/dist/types/provider-models/openai-compat.d.ts +385 -0
  39. package/dist/types/provider-models/special.d.ts +16 -0
  40. package/dist/types/types.d.ts +405 -0
  41. package/dist/types/utils.d.ts +5 -0
  42. package/dist/types/wire/codex.d.ts +26 -0
  43. package/dist/types/wire/gemini-headers.d.ts +18 -0
  44. package/dist/types/wire/github-copilot.d.ts +18 -0
  45. package/package.json +100 -0
  46. package/src/build.ts +40 -0
  47. package/src/compat/anthropic.ts +67 -0
  48. package/src/compat/apply.ts +15 -0
  49. package/src/compat/openai.ts +365 -0
  50. package/src/discovery/antigravity.ts +261 -0
  51. package/src/discovery/codex.ts +371 -0
  52. package/src/discovery/cursor-gen/agent_pb.ts +15274 -0
  53. package/src/discovery/cursor.ts +307 -0
  54. package/src/discovery/gemini.ts +249 -0
  55. package/src/discovery/index.ts +4 -0
  56. package/src/discovery/openai-compatible.ts +224 -0
  57. package/src/effort.ts +16 -0
  58. package/src/fireworks-model-id.ts +30 -0
  59. package/src/hosts.ts +114 -0
  60. package/src/identity/bundled.ts +38 -0
  61. package/src/identity/classify.ts +141 -0
  62. package/src/identity/equivalence.ts +870 -0
  63. package/src/identity/family.ts +88 -0
  64. package/src/identity/id.ts +81 -0
  65. package/src/identity/index.ts +9 -0
  66. package/src/identity/markers.ts +49 -0
  67. package/src/identity/priority.ts +56 -0
  68. package/src/identity/reference.ts +134 -0
  69. package/src/identity/selection.ts +65 -0
  70. package/src/index.ts +15 -0
  71. package/src/model-cache.ts +132 -0
  72. package/src/model-manager.ts +472 -0
  73. package/src/model-thinking.ts +407 -0
  74. package/src/models.json +75308 -0
  75. package/src/models.json.d.ts +9 -0
  76. package/src/models.ts +64 -0
  77. package/src/provider-models/bundled-references.ts +54 -0
  78. package/src/provider-models/descriptor-types.ts +79 -0
  79. package/src/provider-models/descriptors.ts +456 -0
  80. package/src/provider-models/discovery-constants.ts +11 -0
  81. package/src/provider-models/google.ts +105 -0
  82. package/src/provider-models/index.ts +6 -0
  83. package/src/provider-models/ollama.ts +154 -0
  84. package/src/provider-models/openai-compat.ts +3106 -0
  85. package/src/provider-models/special.ts +67 -0
  86. package/src/types.ts +470 -0
  87. package/src/utils.ts +27 -0
  88. package/src/wire/codex.ts +43 -0
  89. package/src/wire/gemini-headers.ts +41 -0
  90. package/src/wire/github-copilot.ts +72 -0
@@ -0,0 +1,3106 @@
1
+ import {
2
+ fetchOpenAICompatibleModels,
3
+ type OpenAICompatibleModelMapperContext,
4
+ type OpenAICompatibleModelRecord,
5
+ } from "../discovery/openai-compatible";
6
+ import { Effort } from "../effort";
7
+ import { toFireworksPublicModelId } from "../fireworks-model-id";
8
+ import type { ModelManagerOptions } from "../model-manager";
9
+ import { getBundledModels } from "../models";
10
+ import type { Api, FetchImpl, Model, ModelSpec, Provider, ThinkingConfig } from "../types";
11
+ import { isAnthropicOAuthToken, isRecord, toBoolean, toNumber, toPositiveNumber } from "../utils";
12
+ import { getGitHubCopilotBaseUrl, OPENCODE_HEADERS, parseGitHubCopilotApiKey } from "../wire/github-copilot";
13
+ import { createBundledReferenceMap, createReferenceResolver, toModelSpec } from "./bundled-references";
14
+ import { UNK_CONTEXT_WINDOW, UNK_MAX_TOKENS } from "./discovery-constants";
15
+
16
+ const MODELS_DEV_URL = "https://models.dev/api.json";
17
+ const ANTHROPIC_BASE_URL = "https://api.anthropic.com/v1";
18
+ const ANTHROPIC_OAUTH_BETA =
19
+ "claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,redact-thinking-2026-02-12,context-management-2025-06-27,prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,advanced-tool-use-2025-11-20,effort-2025-11-24,extended-cache-ttl-2025-04-11";
20
+
21
+ export interface ModelsDevModel {
22
+ id?: string;
23
+ name?: string;
24
+ tool_call?: boolean;
25
+ reasoning?: boolean;
26
+ limit?: {
27
+ context?: number;
28
+ output?: number;
29
+ };
30
+ cost?: {
31
+ input?: number;
32
+ output?: number;
33
+ cache_read?: number;
34
+ cache_write?: number;
35
+ };
36
+ modalities?: {
37
+ input?: string[];
38
+ };
39
+ status?: string;
40
+ provider?: { npm?: string };
41
+ }
42
+
43
+ function toModelName(value: unknown, fallback: string): string {
44
+ if (typeof value !== "string") {
45
+ return fallback;
46
+ }
47
+ const trimmed = value.trim();
48
+ return trimmed.length > 0 ? trimmed : fallback;
49
+ }
50
+
51
+ function toInputCapabilities(value: unknown): ("text" | "image")[] {
52
+ if (!Array.isArray(value)) {
53
+ return ["text"];
54
+ }
55
+ const supportsImage = value.some(item => item === "image");
56
+ return supportsImage ? ["text", "image"] : ["text"];
57
+ }
58
+
59
+ async function fetchModelsDevPayload(fetchImpl: FetchImpl = fetch): Promise<unknown> {
60
+ const response = await fetchImpl(MODELS_DEV_URL, {
61
+ method: "GET",
62
+ headers: { Accept: "application/json" },
63
+ });
64
+ if (!response.ok) {
65
+ throw new Error(`models.dev fetch failed: ${response.status}`);
66
+ }
67
+ return response.json();
68
+ }
69
+
70
+ function mapAnthropicModelsDev(payload: unknown, baseUrl: string): ModelSpec<"anthropic-messages">[] {
71
+ if (!isRecord(payload)) {
72
+ return [];
73
+ }
74
+ const anthropicPayload = payload.anthropic;
75
+ if (!isRecord(anthropicPayload)) {
76
+ return [];
77
+ }
78
+ const modelsValue = anthropicPayload.models;
79
+ if (!isRecord(modelsValue)) {
80
+ return [];
81
+ }
82
+
83
+ const models: ModelSpec<"anthropic-messages">[] = [];
84
+ for (const [modelId, rawModel] of Object.entries(modelsValue)) {
85
+ if (!isRecord(rawModel)) {
86
+ continue;
87
+ }
88
+ const model = rawModel as ModelsDevModel;
89
+ if (model.tool_call !== true) {
90
+ continue;
91
+ }
92
+ models.push({
93
+ id: modelId,
94
+ name: toModelName(model.name, modelId),
95
+ api: "anthropic-messages",
96
+ provider: "anthropic",
97
+ baseUrl,
98
+ reasoning: model.reasoning === true,
99
+ input: toInputCapabilities(model.modalities?.input),
100
+ cost: {
101
+ input: toNumber(model.cost?.input) ?? 0,
102
+ output: toNumber(model.cost?.output) ?? 0,
103
+ cacheRead: toNumber(model.cost?.cache_read) ?? 0,
104
+ cacheWrite: toNumber(model.cost?.cache_write) ?? 0,
105
+ },
106
+ contextWindow: toPositiveNumber(model.limit?.context, UNK_CONTEXT_WINDOW),
107
+ maxTokens: toPositiveNumber(model.limit?.output, UNK_MAX_TOKENS),
108
+ });
109
+ }
110
+
111
+ models.sort((left, right) => left.id.localeCompare(right.id));
112
+ return models;
113
+ }
114
+
115
+ function buildAnthropicDiscoveryHeaders(apiKey: string): Record<string, string> {
116
+ const oauthToken = isAnthropicOAuthToken(apiKey);
117
+ const headers: Record<string, string> = {
118
+ "anthropic-version": "2023-06-01",
119
+ "anthropic-dangerous-direct-browser-access": "true",
120
+ "anthropic-beta": ANTHROPIC_OAUTH_BETA,
121
+ };
122
+ if (oauthToken) {
123
+ headers.Authorization = `Bearer ${apiKey}`;
124
+ } else {
125
+ headers["x-api-key"] = apiKey;
126
+ }
127
+ return headers;
128
+ }
129
+
130
+ function buildAnthropicReferenceMap(
131
+ modelsDevModels: readonly ModelSpec<"anthropic-messages">[],
132
+ ): Map<string, ModelSpec<"anthropic-messages">> {
133
+ const merged = new Map<string, ModelSpec<"anthropic-messages">>();
134
+ for (const model of modelsDevModels) {
135
+ merged.set(model.id, model);
136
+ }
137
+ // Anthropic /v1/models does not carry token limits, so bundled metadata stays canonical
138
+ // for known models while models.dev only fills gaps for newly discovered ids.
139
+ const bundledModels = getBundledModels("anthropic").filter(
140
+ (model): model is Model<"anthropic-messages"> => model.api === "anthropic-messages",
141
+ );
142
+ for (const model of bundledModels) {
143
+ merged.set(model.id, toModelSpec(model));
144
+ }
145
+ return merged;
146
+ }
147
+
148
+ /**
149
+ * Curated Anthropic models that are live or limited-availability on the
150
+ * first-party `/v1/models` endpoint but that models.dev has not catalogued yet.
151
+ * Seeded into model generation so the bundled catalog is never gated on
152
+ * models.dev's update cadence; deduped behind upstream catalog / models.dev
153
+ * entries once those appear. Token limits and pricing are pinned
154
+ * authoritatively in `applyAnthropicCatalogPolicy`, and `thinking` is re-baked
155
+ * by the generator's policy pass (scripts/generated-policies.ts).
156
+ */
157
+ export const ANTHROPIC_CURATED_FALLBACK_MODELS: readonly ModelSpec<"anthropic-messages">[] = [
158
+ {
159
+ id: "claude-fable-5",
160
+ name: "Claude Fable 5",
161
+ api: "anthropic-messages",
162
+ provider: "anthropic",
163
+ baseUrl: "https://api.anthropic.com",
164
+ reasoning: true,
165
+ input: ["text", "image"],
166
+ cost: { input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5 },
167
+ contextWindow: 1_000_000,
168
+ maxTokens: 128_000,
169
+ },
170
+ {
171
+ id: "claude-mythos-5",
172
+ name: "Claude Mythos 5",
173
+ api: "anthropic-messages",
174
+ provider: "anthropic",
175
+ baseUrl: "https://api.anthropic.com",
176
+ reasoning: true,
177
+ input: ["text", "image"],
178
+ cost: { input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5 },
179
+ contextWindow: 1_000_000,
180
+ maxTokens: 128_000,
181
+ },
182
+ ];
183
+
184
+ function mapWithBundledReference<TApi extends Api>(
185
+ entry: OpenAICompatibleModelRecord,
186
+ defaults: ModelSpec<TApi>,
187
+ reference: ModelSpec<TApi> | undefined,
188
+ ): ModelSpec<TApi> {
189
+ const name = toModelName(entry.name, reference?.name ?? defaults.name);
190
+ if (!reference) {
191
+ return {
192
+ ...defaults,
193
+ name,
194
+ };
195
+ }
196
+ return {
197
+ ...reference,
198
+ id: defaults.id,
199
+ name,
200
+ baseUrl: defaults.baseUrl,
201
+ contextWindow: toPositiveNumber(entry.context_length, reference.contextWindow),
202
+ maxTokens: toPositiveNumber(entry.max_completion_tokens, reference.maxTokens),
203
+ };
204
+ }
205
+
206
+ function normalizeAnthropicBaseUrl(baseUrl: string | undefined, fallback: string): string {
207
+ const value = baseUrl?.trim();
208
+ if (!value) {
209
+ return fallback;
210
+ }
211
+ return value.endsWith("/") ? value.slice(0, -1) : value;
212
+ }
213
+
214
+ function toAnthropicDiscoveryBaseUrl(baseUrl: string): string {
215
+ return baseUrl.endsWith("/v1") ? baseUrl : `${baseUrl}/v1`;
216
+ }
217
+
218
+ function normalizeOllamaBaseUrl(baseUrl?: string): string {
219
+ const value = baseUrl?.trim();
220
+ if (!value) {
221
+ return "http://127.0.0.1:11434/v1";
222
+ }
223
+ const trimmed = value.endsWith("/") ? value.slice(0, -1) : value;
224
+ return trimmed.endsWith("/v1") ? trimmed : `${trimmed}/v1`;
225
+ }
226
+
227
+ function toOllamaNativeBaseUrl(baseUrl: string): string {
228
+ return baseUrl.endsWith("/v1") ? baseUrl.slice(0, -3) : baseUrl;
229
+ }
230
+
231
+ async function fetchOllamaNativeModels(
232
+ baseUrl: string,
233
+ resolveMetadata: (modelId: string) => Promise<OllamaResolvedMetadata>,
234
+ fetchImpl: FetchImpl = fetch,
235
+ ): Promise<ModelSpec<"openai-responses">[] | null> {
236
+ const nativeBaseUrl = toOllamaNativeBaseUrl(baseUrl);
237
+ let response: Response;
238
+ try {
239
+ response = await fetchImpl(`${nativeBaseUrl}/api/tags`, {
240
+ method: "GET",
241
+ headers: { Accept: "application/json" },
242
+ });
243
+ } catch {
244
+ return null;
245
+ }
246
+ if (!response.ok) {
247
+ return null;
248
+ }
249
+ const payload = (await response.json()) as { models?: Array<{ name?: string; model?: string }> };
250
+ const entries = payload.models ?? [];
251
+ const resolved = await Promise.all(
252
+ entries.map(async (entry): Promise<ModelSpec<"openai-responses"> | null> => {
253
+ const id = entry.model ?? entry.name;
254
+ if (!id) return null;
255
+ const metadata = await resolveMetadata(id);
256
+ return {
257
+ id,
258
+ name: entry.name ?? id,
259
+ api: "openai-responses",
260
+ provider: "ollama",
261
+ baseUrl,
262
+ reasoning: metadata.reasoning ?? false,
263
+ thinking: metadata.thinking,
264
+ input: metadata.input ?? ["text"],
265
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
266
+ contextWindow: metadata.contextWindow,
267
+ maxTokens: metadata.maxTokens,
268
+ };
269
+ }),
270
+ );
271
+ const models: ModelSpec<"openai-responses">[] = resolved.filter(
272
+ (m): m is ModelSpec<"openai-responses"> => m !== null,
273
+ );
274
+ return models.sort((left, right) => left.id.localeCompare(right.id));
275
+ }
276
+
277
+ /**
278
+ * Fallback context window for Ollama models when `/api/show` is unavailable
279
+ * or omits a `model_info.<arch>.context_length` field. Matches the size
280
+ * Ollama's cloud catalog reports for stock models.
281
+ */
282
+ const OLLAMA_FALLBACK_CONTEXT_WINDOW = 128_000;
283
+ /** Cap max output tokens at a value that matches OMP's other openai-responses defaults. */
284
+ const OLLAMA_DEFAULT_MAX_TOKENS = 8192;
285
+ /**
286
+ * Ollama's OpenAI-compatible `reasoning.effort` only accepts
287
+ * `high|medium|low|max|none`; passing OMP's `minimal`/`xhigh` levels verbatim
288
+ * makes the server reject the turn with HTTP 400 `invalid reasoning value`.
289
+ * Map the two unsupported levels onto the closest accepted ones (`low`/`max`).
290
+ */
291
+ const OLLAMA_REASONING_EFFORT_MAP = { minimal: "low", xhigh: "max" } as const;
292
+
293
+ /** Stamp the Ollama reasoning-effort map onto a reasoning-capable model. */
294
+ function applyOllamaReasoningCompat(model: ModelSpec<"openai-responses">): void {
295
+ if (!model.reasoning) return;
296
+ model.compat = {
297
+ ...model.compat,
298
+ reasoningEffortMap: { ...OLLAMA_REASONING_EFFORT_MAP, ...model.compat?.reasoningEffortMap },
299
+ };
300
+ }
301
+
302
+ interface OllamaResolvedMetadata {
303
+ contextWindow: number;
304
+ maxTokens: number;
305
+ capabilities?: string[];
306
+ reasoning?: boolean;
307
+ thinking?: ThinkingConfig;
308
+ input?: ("text" | "image")[];
309
+ }
310
+
311
+ interface OllamaShowMetadata {
312
+ contextWindow?: number;
313
+ maxTokens?: number;
314
+ capabilities?: string[];
315
+ reasoning?: boolean;
316
+ thinking?: ThinkingConfig;
317
+ input?: ("text" | "image")[];
318
+ }
319
+
320
+ function getOllamaContextWindow(modelInfo: Record<string, unknown> | undefined): number | undefined {
321
+ if (!modelInfo) {
322
+ return undefined;
323
+ }
324
+ for (const [key, value] of Object.entries(modelInfo)) {
325
+ if (typeof value !== "number" || value <= 0) {
326
+ continue;
327
+ }
328
+ if (key.endsWith(".context_length") || key.endsWith(".num_ctx") || key.endsWith(".context_window")) {
329
+ return value;
330
+ }
331
+ }
332
+ }
333
+
334
+ function getOllamaCapabilities(value: unknown): string[] | undefined {
335
+ if (!Array.isArray(value)) {
336
+ return undefined;
337
+ }
338
+ return value.filter((item): item is string => typeof item === "string");
339
+ }
340
+
341
+ function getOllamaThinkingConfig(capabilities: string[] | undefined): ThinkingConfig | undefined {
342
+ if (!capabilities?.includes("thinking")) {
343
+ return undefined;
344
+ }
345
+ return { mode: "effort", efforts: [Effort.Minimal, Effort.Low, Effort.Medium, Effort.High] };
346
+ }
347
+
348
+ /**
349
+ * Query Ollama's `/api/show` endpoint for a single model and pull native
350
+ * context and capability metadata from the response. Returns `undefined` when
351
+ * the endpoint is unavailable so callers can layer their own fallback.
352
+ */
353
+ async function fetchOllamaShowMetadata(
354
+ nativeBaseUrl: string,
355
+ modelId: string,
356
+ fetchImpl: FetchImpl = fetch,
357
+ ): Promise<OllamaShowMetadata | undefined> {
358
+ try {
359
+ const response = await fetchImpl(`${nativeBaseUrl}/api/show`, {
360
+ method: "POST",
361
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
362
+ body: JSON.stringify({ model: modelId }),
363
+ });
364
+ if (!response.ok) {
365
+ return undefined;
366
+ }
367
+ const payload = (await response.json()) as { capabilities?: unknown; model_info?: Record<string, unknown> };
368
+ const capabilities = getOllamaCapabilities(payload.capabilities);
369
+ const contextWindow = getOllamaContextWindow(payload.model_info);
370
+ return {
371
+ contextWindow,
372
+ maxTokens: contextWindow ? OLLAMA_DEFAULT_MAX_TOKENS : undefined,
373
+ capabilities,
374
+ reasoning: capabilities ? capabilities.includes("thinking") : undefined,
375
+ thinking: getOllamaThinkingConfig(capabilities),
376
+ input: capabilities
377
+ ? capabilities.includes("vision")
378
+ ? (["text", "image"] as Array<"text" | "image">)
379
+ : (["text"] as Array<"text">)
380
+ : undefined,
381
+ };
382
+ } catch {
383
+ // fall through; caller decides on the fallback
384
+ }
385
+ return undefined;
386
+ }
387
+
388
+ /**
389
+ * Build a resolver that fetches `/api/show` metadata per model id and caches
390
+ * the result in-memory for the lifetime of the manager. Successful lookups are
391
+ * cached so repeated `fetchDynamicModels` calls do not refetch; failed
392
+ * lookups stay uncached so a later refresh can recover.
393
+ */
394
+ function createOllamaMetadataResolver(
395
+ nativeBaseUrl: string,
396
+ fetchImpl?: FetchImpl,
397
+ ): (modelId: string) => Promise<OllamaResolvedMetadata> {
398
+ const cache = new Map<string, Promise<OllamaResolvedMetadata>>();
399
+ return modelId => {
400
+ const cached = cache.get(modelId);
401
+ if (cached) return cached;
402
+ const pending = (async () => {
403
+ const metadata = await fetchOllamaShowMetadata(nativeBaseUrl, modelId, fetchImpl);
404
+ if (!metadata) {
405
+ cache.delete(modelId);
406
+ return { contextWindow: OLLAMA_FALLBACK_CONTEXT_WINDOW, maxTokens: OLLAMA_DEFAULT_MAX_TOKENS };
407
+ }
408
+ return {
409
+ ...metadata,
410
+ contextWindow: metadata.contextWindow ?? OLLAMA_FALLBACK_CONTEXT_WINDOW,
411
+ maxTokens: metadata.maxTokens ?? OLLAMA_DEFAULT_MAX_TOKENS,
412
+ };
413
+ })();
414
+ cache.set(modelId, pending);
415
+ void pending.catch(() => cache.delete(modelId));
416
+ return pending;
417
+ };
418
+ }
419
+
420
+ const OPENAI_NON_RESPONSES_PREFIXES = [
421
+ "text-embedding",
422
+ "whisper-",
423
+ "tts-",
424
+ "omni-moderation",
425
+ "omni-transcribe",
426
+ "omni-speech",
427
+ "gpt-image-",
428
+ "gpt-realtime",
429
+ ] as const;
430
+
431
+ function isLikelyOpenAIResponsesModelId(id: string, references: Map<string, ModelSpec<"openai-responses">>): boolean {
432
+ const trimmed = id.trim();
433
+ if (!trimmed) {
434
+ return false;
435
+ }
436
+ if (references.has(trimmed)) {
437
+ return true;
438
+ }
439
+ const normalized = trimmed.toLowerCase();
440
+ if (OPENAI_NON_RESPONSES_PREFIXES.some(prefix => normalized.startsWith(prefix))) {
441
+ return false;
442
+ }
443
+ if (normalized.includes("embedding")) {
444
+ return false;
445
+ }
446
+ return (
447
+ normalized.startsWith("gpt-") ||
448
+ normalized.startsWith("o1") ||
449
+ normalized.startsWith("o3") ||
450
+ normalized.startsWith("o4") ||
451
+ normalized.startsWith("chatgpt")
452
+ );
453
+ }
454
+
455
+ const NANO_GPT_NON_TEXT_MODEL_TOKENS = [
456
+ "embedding",
457
+ "image",
458
+ "vision",
459
+ "audio",
460
+ "speech",
461
+ "transcribe",
462
+ "moderation",
463
+ "realtime",
464
+ "whisper",
465
+ "tts",
466
+ ] as const;
467
+
468
+ /** Regex matching NanoGPT `:thinking` suffixed model IDs (with or without a level). */
469
+ const NANO_GPT_THINKING_SUFFIX_RE = /:thinking(:[^:]+)?$/;
470
+
471
+ function isLikelyNanoGptTextModelId(id: string): boolean {
472
+ const normalized = id.trim().toLowerCase();
473
+ if (!normalized) {
474
+ return false;
475
+ }
476
+ if (NANO_GPT_THINKING_SUFFIX_RE.test(normalized)) {
477
+ return false;
478
+ }
479
+ return !NANO_GPT_NON_TEXT_MODEL_TOKENS.some(token => normalized.includes(token));
480
+ }
481
+
482
+ type SimpleProviderConfig = { apiKey?: string; baseUrl?: string; fetch?: FetchImpl };
483
+
484
+ export function createSimpleOpenAICompletionsOptions(
485
+ providerId: Parameters<typeof getBundledModels>[0],
486
+ defaultBaseUrl: string,
487
+ config?: SimpleProviderConfig,
488
+ ): ModelManagerOptions<"openai-completions"> {
489
+ const apiKey = config?.apiKey;
490
+ const baseUrl = config?.baseUrl ?? defaultBaseUrl;
491
+ const references = createBundledReferenceMap<"openai-completions">(providerId);
492
+ return {
493
+ providerId,
494
+ ...(apiKey && {
495
+ fetchDynamicModels: () =>
496
+ fetchOpenAICompatibleModels({
497
+ api: "openai-completions",
498
+ provider: providerId,
499
+ baseUrl,
500
+ apiKey,
501
+ mapModel: (entry, defaults) => {
502
+ const reference = references.get(defaults.id);
503
+ return mapWithBundledReference(entry, defaults, reference);
504
+ },
505
+ fetch: config?.fetch,
506
+ }),
507
+ }),
508
+ };
509
+ }
510
+
511
+ function createSimpleOpenAIResponsesOptions(
512
+ providerId: Parameters<typeof getBundledModels>[0],
513
+ defaultBaseUrl: string,
514
+ config?: SimpleProviderConfig,
515
+ ): ModelManagerOptions<"openai-responses"> {
516
+ const apiKey = config?.apiKey;
517
+ const baseUrl = config?.baseUrl ?? defaultBaseUrl;
518
+ const references = createBundledReferenceMap<"openai-responses">(providerId);
519
+ return {
520
+ providerId,
521
+ ...(apiKey && {
522
+ fetchDynamicModels: () =>
523
+ fetchOpenAICompatibleModels({
524
+ api: "openai-responses",
525
+ provider: providerId,
526
+ baseUrl,
527
+ apiKey,
528
+ mapModel: (entry, defaults) => {
529
+ const reference = references.get(defaults.id);
530
+ return mapWithBundledReference(entry, defaults, reference);
531
+ },
532
+ fetch: config?.fetch,
533
+ }),
534
+ }),
535
+ };
536
+ }
537
+
538
+ function createSimpleAnthropicProviderOptions(
539
+ providerId: Parameters<typeof getBundledModels>[0],
540
+ defaultBaseUrlFallback: string,
541
+ config?: SimpleProviderConfig,
542
+ ): ModelManagerOptions<"anthropic-messages"> {
543
+ const apiKey = config?.apiKey;
544
+ const baseUrl = normalizeAnthropicBaseUrl(config?.baseUrl, defaultBaseUrlFallback);
545
+ const discoveryBaseUrl = toAnthropicDiscoveryBaseUrl(baseUrl);
546
+ const references = createBundledReferenceMap<"anthropic-messages">(providerId);
547
+ return {
548
+ providerId,
549
+ ...(apiKey && {
550
+ fetchDynamicModels: () =>
551
+ fetchOpenAICompatibleModels({
552
+ api: "anthropic-messages",
553
+ provider: providerId,
554
+ baseUrl: discoveryBaseUrl,
555
+ headers: buildAnthropicDiscoveryHeaders(apiKey),
556
+ mapModel: (entry, defaults) => {
557
+ const reference = references.get(defaults.id);
558
+ const model = mapWithBundledReference(entry, defaults, reference);
559
+ return {
560
+ ...model,
561
+ name: toModelName(entry.display_name, model.name),
562
+ baseUrl,
563
+ };
564
+ },
565
+ fetch: config?.fetch,
566
+ }),
567
+ }),
568
+ };
569
+ }
570
+
571
+ // ---------------------------------------------------------------------------
572
+ // 1. OpenAI
573
+ // ---------------------------------------------------------------------------
574
+
575
+ export interface OpenAIModelManagerConfig {
576
+ apiKey?: string;
577
+ baseUrl?: string;
578
+ fetch?: FetchImpl;
579
+ }
580
+
581
+ export function openaiModelManagerOptions(config?: OpenAIModelManagerConfig): ModelManagerOptions<"openai-responses"> {
582
+ const apiKey = config?.apiKey;
583
+ const baseUrl = config?.baseUrl ?? "https://api.openai.com/v1";
584
+ const references = createBundledReferenceMap<"openai-responses">("openai");
585
+ return {
586
+ providerId: "openai",
587
+ ...(apiKey && {
588
+ fetchDynamicModels: () =>
589
+ fetchOpenAICompatibleModels({
590
+ api: "openai-responses",
591
+ provider: "openai",
592
+ baseUrl,
593
+ apiKey,
594
+ filterModel: (_entry, model) => isLikelyOpenAIResponsesModelId(model.id, references),
595
+ mapModel: (entry, defaults) => {
596
+ const reference = references.get(defaults.id);
597
+ return mapWithBundledReference(entry, defaults, reference);
598
+ },
599
+ fetch: config?.fetch,
600
+ }),
601
+ }),
602
+ };
603
+ }
604
+
605
+ // ---------------------------------------------------------------------------
606
+ // 2. Groq
607
+ // ---------------------------------------------------------------------------
608
+
609
+ export interface GroqModelManagerConfig {
610
+ apiKey?: string;
611
+ baseUrl?: string;
612
+ fetch?: FetchImpl;
613
+ }
614
+
615
+ export function groqModelManagerOptions(config?: GroqModelManagerConfig): ModelManagerOptions<"openai-completions"> {
616
+ return createSimpleOpenAICompletionsOptions("groq", "https://api.groq.com/openai/v1", config);
617
+ }
618
+
619
+ // ---------------------------------------------------------------------------
620
+ // 3. Cerebras
621
+ // ---------------------------------------------------------------------------
622
+
623
+ export interface CerebrasModelManagerConfig {
624
+ apiKey?: string;
625
+ baseUrl?: string;
626
+ fetch?: FetchImpl;
627
+ }
628
+
629
+ export function cerebrasModelManagerOptions(
630
+ config?: CerebrasModelManagerConfig,
631
+ ): ModelManagerOptions<"openai-completions"> {
632
+ return createSimpleOpenAICompletionsOptions("cerebras", "https://api.cerebras.ai/v1", config);
633
+ }
634
+
635
+ // ---------------------------------------------------------------------------
636
+ // 4. Hugging Face
637
+ // ---------------------------------------------------------------------------
638
+
639
+ export interface HuggingfaceModelManagerConfig {
640
+ apiKey?: string;
641
+ baseUrl?: string;
642
+ fetch?: FetchImpl;
643
+ }
644
+
645
+ export function huggingfaceModelManagerOptions(
646
+ config?: HuggingfaceModelManagerConfig,
647
+ ): ModelManagerOptions<"openai-completions"> {
648
+ return createSimpleOpenAICompletionsOptions("huggingface", "https://router.huggingface.co/v1", config);
649
+ }
650
+
651
+ // ---------------------------------------------------------------------------
652
+ // 5. NVIDIA
653
+ // ---------------------------------------------------------------------------
654
+
655
+ export interface NvidiaModelManagerConfig {
656
+ apiKey?: string;
657
+ baseUrl?: string;
658
+ fetch?: FetchImpl;
659
+ }
660
+
661
+ export function nvidiaModelManagerOptions(
662
+ config?: NvidiaModelManagerConfig,
663
+ ): ModelManagerOptions<"openai-completions"> {
664
+ return createSimpleOpenAICompletionsOptions("nvidia", "https://integrate.api.nvidia.com/v1", config);
665
+ }
666
+
667
+ // ---------------------------------------------------------------------------
668
+ // 6. xAI
669
+ // ---------------------------------------------------------------------------
670
+
671
+ export interface XaiModelManagerConfig {
672
+ apiKey?: string;
673
+ baseUrl?: string;
674
+ fetch?: FetchImpl;
675
+ }
676
+
677
+ export function xaiModelManagerOptions(config?: XaiModelManagerConfig): ModelManagerOptions<"openai-completions"> {
678
+ return createSimpleOpenAICompletionsOptions("xai", "https://api.x.ai/v1", config);
679
+ }
680
+
681
+ export interface XaiOAuthModelManagerConfig {
682
+ apiKey?: string;
683
+ baseUrl?: string;
684
+ fetch?: FetchImpl;
685
+ }
686
+
687
+ interface XAICuratedModel {
688
+ id: string;
689
+ contextWindow: number;
690
+ name?: string;
691
+ /** Whether the model reasons natively. Defaults to true for Grok-4.x family. */
692
+ reasoning?: boolean;
693
+ /**
694
+ * Whether xAI accepts the `reasoning.effort` wire param for this model.
695
+ * Default true. When false: picker hides the effort dial (via
696
+ * getSupportedEfforts in model-thinking.ts) AND wire-side already omits
697
+ * the param via GROK_EFFORT_CAPABLE_PREFIXES in providers/xai-responses.ts.
698
+ * Must agree with that allowlist; two truths kept in sync by curated-catalog
699
+ * author convention until a follow-up Op: compress unifies them.
700
+ */
701
+ supportsReasoningEffort?: boolean;
702
+ /**
703
+ * Input modalities this model accepts. Defaults to `["text"]` when absent.
704
+ * Vision-capable Grok models MUST list `"image"` here so the curated layer
705
+ * overrides `fetchOpenAICompatibleModels`' default of `["text"]` (which
706
+ * otherwise strips image capability on every online refresh).
707
+ */
708
+ input?: ("text" | "image")[];
709
+ }
710
+
711
+ // Source of truth for the xai-oauth chat picker. Top of list = headline.
712
+ // Context windows from hermes-agent/agent/model_metadata.py:205-220
713
+ // ("Values sourced from models.dev (2026-04)"). grok-build is xAI's
714
+ // coding-fine-tuned chat model; 512K context per user spec (2026-05-17).
715
+ //
716
+ // supportsReasoningEffort=false entries reason natively but reject the wire
717
+ // `reasoning.effort` param (api.x.ai returns HTTP 400). Mirrors the HTTP-side
718
+ // GROK_EFFORT_CAPABLE_PREFIXES allowlist in providers/xai-responses.ts. The
719
+ // curated flag is the picker-visible truth; the HTTP allowlist is the wire
720
+ // truth. omitReasoningEffort in xai-responses.ts already prevents 400s; this
721
+ // fixes the picker UX wart of advertising an inert dial.
722
+ export const XAI_OAUTH_CURATED_MODELS: readonly XAICuratedModel[] = [
723
+ // grok-build is text-only per the bundled catalog; omit `input` for the default.
724
+ { id: "grok-build", contextWindow: 512_000, name: "Grok Build", supportsReasoningEffort: false },
725
+ { id: "grok-4.3", contextWindow: 1_000_000, name: "Grok 4.3", input: ["text", "image"] },
726
+ // grok-4.20-multi-agent-0309 is text-only per the bundled catalog; omit `input` for the default.
727
+ { id: "grok-4.20-multi-agent-0309", contextWindow: 2_000_000, name: "Grok 4.20 (Multi-Agent)" },
728
+ {
729
+ id: "grok-4.20-0309-reasoning",
730
+ contextWindow: 2_000_000,
731
+ name: "Grok 4.20 (Reasoning)",
732
+ supportsReasoningEffort: false,
733
+ input: ["text", "image"],
734
+ },
735
+ {
736
+ id: "grok-4.20-0309-non-reasoning",
737
+ contextWindow: 2_000_000,
738
+ name: "Grok 4.20 (Non-Reasoning)",
739
+ reasoning: false,
740
+ input: ["text", "image"],
741
+ },
742
+ ] as const;
743
+
744
+ // xAI /v1/models returns chat, image, voice, and STT entries. Tool surfaces
745
+ // route through dedicated tools (generate_image, tts) with their own model
746
+ // strings; the chat picker MUST exclude these prefixes or selecting them 400s.
747
+ const XAI_NON_CHAT_PREFIXES = ["grok-imagine-", "grok-stt-", "grok-voice-"] as const;
748
+
749
+ // Hermes-agent parity: only the `minimal -> low` clamp is applied (see
750
+ // hermes-agent/agent/transports/codex.py:92 `_effort_clamp = {"minimal":
751
+ // "low"}`). Hermes sends `xhigh` to xAI verbatim and we match that contract
752
+ // — let xAI decide if the level is valid for the specific Grok model.
753
+ // applyResponsesReasoningParams runs this through `model.compat.reasoningEffortMap`
754
+ // at request time, downstream of the omitReasoningEffort gate in xai-responses.ts.
755
+ const XAI_REASONING_EFFORT_MAP = { minimal: "low" } as const;
756
+
757
+ // Single source of truth for curated → Model fan-in. Used by the static-seed
758
+ // and the dynamic overlay/inject paths (applyXAIOAuthCuration) so curated
759
+ // reasoning/effort flags survive an online refresh (xAI's /v1/models lacks
760
+ // reasoning metadata and fetchOpenAICompatibleModels defaults reasoning to
761
+ // false). Caller supplies a `base` Model (either a freshly synthesised seed
762
+ // or a dynamic-fetched entry); the helper layers curated fields on top.
763
+ // The `minimal -> low` effort clamp (XAI_REASONING_EFFORT_MAP) is always
764
+ // merged in so dynamic-fetched models — which arrive without curated
765
+ // compat keys — still get the clamp applyResponsesReasoningParams expects.
766
+ function mergeCuratedIntoModel(
767
+ base: ModelSpec<"openai-responses">,
768
+ curated: XAICuratedModel,
769
+ ): ModelSpec<"openai-responses"> {
770
+ const effort = curated.supportsReasoningEffort;
771
+ const compat = {
772
+ ...(base.compat ?? {}),
773
+ reasoningEffortMap: { ...XAI_REASONING_EFFORT_MAP, ...(base.compat?.reasoningEffortMap ?? {}) },
774
+ ...(effort === undefined ? {} : { supportsReasoningEffort: effort }),
775
+ };
776
+ return {
777
+ ...base,
778
+ contextWindow: curated.contextWindow,
779
+ name: curated.name ?? base.name,
780
+ reasoning: curated.reasoning ?? true,
781
+ input: curated.input ?? base.input,
782
+ compat,
783
+ };
784
+ }
785
+
786
+ /**
787
+ * Overlay/inject curated xai-oauth metadata onto dynamic-fetch results so
788
+ * a successful `online refresh` doesn't regress vision capability, context
789
+ * window, reasoning flags, or the effort-dial allowlist.
790
+ *
791
+ * Three passes:
792
+ * 1. Filter `XAI_NON_CHAT_PREFIXES` (picker pollution defense for tool
793
+ * surfaces routed through dedicated tools — generate_image, tts).
794
+ * 2. Overlay curated metadata onto dynamic-fetch matches. xAI's /v1/models
795
+ * does not return context_window or reasoning metadata, so without
796
+ * this overlay the runtime falls back to the bundled-reference default
797
+ * (effectively 128k context) and `reasoning: false` (suppressing the
798
+ * effort dial and stripping thinking metadata downstream).
799
+ * 3. Inject curated entries missing from the dynamic fetch. Clones the
800
+ * first surviving entry as a template so required Model fields (api,
801
+ * provider, baseUrl, cost, etc.) inherit sane defaults. If `filtered`
802
+ * is empty (offline / no auth) injection is skipped — the descriptor's
803
+ * defaultModel covers the fallback.
804
+ *
805
+ * Order: curated models first in declaration order; then dynamic remainder
806
+ * in original order.
807
+ */
808
+ function applyXAIOAuthCuration(dynamic: readonly ModelSpec<"openai-responses">[]): ModelSpec<"openai-responses">[] {
809
+ const filtered = dynamic.filter(e => !XAI_NON_CHAT_PREFIXES.some(p => e.id.startsWith(p)));
810
+
811
+ const byId = new Map<string, ModelSpec<"openai-responses">>(filtered.map(e => [e.id, e]));
812
+ for (const curated of XAI_OAUTH_CURATED_MODELS) {
813
+ const existing = byId.get(curated.id);
814
+ if (existing) {
815
+ byId.set(curated.id, mergeCuratedIntoModel(existing, curated));
816
+ }
817
+ }
818
+
819
+ const template = filtered[0];
820
+ if (template) {
821
+ for (const curated of XAI_OAUTH_CURATED_MODELS) {
822
+ if (!byId.has(curated.id)) {
823
+ // Reset id/name on the template before merging so the helper's
824
+ // `curated.name ?? base.name` clause falls back to curated.id
825
+ // (the inject contract), not to the unrelated template's label.
826
+ const base: ModelSpec<"openai-responses"> = { ...template, id: curated.id, name: curated.id };
827
+ byId.set(curated.id, mergeCuratedIntoModel(base, curated));
828
+ }
829
+ }
830
+ }
831
+
832
+ const curatedIds = new Set(XAI_OAUTH_CURATED_MODELS.map(c => c.id));
833
+ const curatedFirst = XAI_OAUTH_CURATED_MODELS.map(c => byId.get(c.id)).filter(
834
+ (e): e is ModelSpec<"openai-responses"> => e !== undefined,
835
+ );
836
+ const rest = filtered.filter(e => !curatedIds.has(e.id));
837
+ return [...curatedFirst, ...rest];
838
+ }
839
+
840
+ /**
841
+ * Render `XAI_OAUTH_CURATED_MODELS` as full `ModelSpec<"openai-responses">` entries.
842
+ *
843
+ * Single source of truth for the curated to Model fan-in, consumed by both
844
+ * - {@link xaiOAuthModelManagerOptions} (runtime static seed handed to the model
845
+ * manager so the picker is populated on a fresh login), and
846
+ * - `packages/ai/scripts/generate-models.ts` (bundles the same entries into
847
+ * `models.json`, so the synchronous `ModelRegistry.#loadModels()` boot path
848
+ * sees `xai-oauth` without waiting for a refresh — fixes the boot-time
849
+ * default-model reset when `modelRoles.default = "xai-oauth/<id>"`).
850
+ *
851
+ * `reasoning` defaults to `true` for the Grok-4.x family; the explicit
852
+ * `grok-4.20-0309-non-reasoning` entry opts out via `XAICuratedModel.reasoning`.
853
+ * `maxTokens` uses `UNK_MAX_TOKENS` so id-keyed overlays from a successful
854
+ * dynamic fetch merge cleanly. Mirrors
855
+ * `hermes-agent/hermes_cli/models.py:_XAI_STATIC_FALLBACK`.
856
+ */
857
+ export function buildXaiOAuthStaticSeed(baseUrl?: string): ModelSpec<"openai-responses">[] {
858
+ const resolvedBaseUrl = baseUrl ?? "https://api.x.ai/v1";
859
+ return XAI_OAUTH_CURATED_MODELS.map(curated => {
860
+ // Synthesise a bare base then layer curated metadata via the same helper
861
+ // the dynamic overlay/inject paths use. `name: curated.id` is a sentinel
862
+ // the helper rewrites to `curated.name ?? base.name`, so curated.name
863
+ // wins when set.
864
+ const base: ModelSpec<"openai-responses"> = {
865
+ id: curated.id,
866
+ name: curated.id,
867
+ api: "openai-responses",
868
+ provider: "xai-oauth",
869
+ baseUrl: resolvedBaseUrl,
870
+ reasoning: true,
871
+ input: ["text"],
872
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
873
+ contextWindow: curated.contextWindow,
874
+ maxTokens: UNK_MAX_TOKENS,
875
+ compat: { reasoningEffortMap: XAI_REASONING_EFFORT_MAP },
876
+ };
877
+ return mergeCuratedIntoModel(base, curated);
878
+ });
879
+ }
880
+
881
+ export function xaiOAuthModelManagerOptions(
882
+ config?: XaiOAuthModelManagerConfig,
883
+ ): ModelManagerOptions<"openai-responses"> {
884
+ const defaultBaseUrl = "https://api.x.ai/v1";
885
+ const resolvedBaseUrl = config?.baseUrl ?? defaultBaseUrl;
886
+ const base = createSimpleOpenAIResponsesOptions(
887
+ "xai-oauth" as Parameters<typeof getBundledModels>[0],
888
+ defaultBaseUrl,
889
+ config,
890
+ );
891
+ // Static seed handed to the runtime model manager so the picker populates on
892
+ // a fresh login even before `fetchDynamicModels` fires (it is gated on
893
+ // `config.apiKey` at construction time, and OAuth tokens resolve later via
894
+ // AuthStorage). `generate-models.ts` calls the same builder so `models.json`
895
+ // carries these entries too — making the synchronous `#loadModels()` boot
896
+ // path honor `modelRoles.default = "xai-oauth/<id>"` without `await refresh()`.
897
+ const staticModels = buildXaiOAuthStaticSeed(resolvedBaseUrl);
898
+ if (!base.fetchDynamicModels) {
899
+ return { ...base, staticModels };
900
+ }
901
+ // Wrap fetchDynamicModels so an `online refresh` against xAI's /v1/models
902
+ // runs through applyXAIOAuthCuration — preserves curated context windows,
903
+ // vision modality, reasoning flags, and filters tool-only model ids
904
+ // (grok-imagine-*, grok-stt-*, grok-voice-*) from the chat picker.
905
+ const inner = base.fetchDynamicModels;
906
+ return {
907
+ ...base,
908
+ staticModels,
909
+ fetchDynamicModels: async () => {
910
+ const dynamic = await inner();
911
+ return dynamic == null ? dynamic : applyXAIOAuthCuration(dynamic);
912
+ },
913
+ };
914
+ }
915
+
916
+ // ---------------------------------------------------------------------------
917
+ // 6.4 AIML API
918
+ // ---------------------------------------------------------------------------
919
+
920
+ const AIML_API_NON_CHAT_MODEL_ID_PATTERN =
921
+ /(?:^|[/:._-])(?:audio|embed|embedding|embeddings|i2i|i2v|image|speech|t2i|t2v|tts|video)(?:$|[/:._-])/i;
922
+
923
+ const AIML_API_NON_CHAT_MODEL_ID_SUBSTRINGS = ["dall-e", "dalle", "flux", "imagen", "sora", "veo", "whisper"] as const;
924
+
925
+ export function isLikelyAimlApiChatModelId(id: string): boolean {
926
+ const normalized = id.trim().toLowerCase();
927
+ if (!normalized) return false;
928
+ return (
929
+ !AIML_API_NON_CHAT_MODEL_ID_PATTERN.test(normalized) &&
930
+ !AIML_API_NON_CHAT_MODEL_ID_SUBSTRINGS.some(token => normalized.includes(token))
931
+ );
932
+ }
933
+
934
+ export interface AimlApiModelManagerConfig {
935
+ apiKey?: string;
936
+ baseUrl?: string;
937
+ fetch?: FetchImpl;
938
+ }
939
+
940
+ export function aimlApiModelManagerOptions(
941
+ config?: AimlApiModelManagerConfig,
942
+ ): ModelManagerOptions<"openai-completions"> {
943
+ const apiKey = config?.apiKey;
944
+ const baseUrl = config?.baseUrl ?? "https://api.aimlapi.com/v1";
945
+ const references = createBundledReferenceMap<"openai-completions">("aimlapi");
946
+ return {
947
+ providerId: "aimlapi",
948
+ dynamicModelsAuthoritative: true,
949
+ ...(apiKey && {
950
+ fetchDynamicModels: () =>
951
+ fetchOpenAICompatibleModels({
952
+ api: "openai-completions",
953
+ provider: "aimlapi",
954
+ baseUrl,
955
+ apiKey,
956
+ filterModel: (_entry, model) => isLikelyAimlApiChatModelId(model.id),
957
+ mapModel: (entry, defaults) => {
958
+ const reference = references.get(defaults.id);
959
+ return mapWithBundledReference(entry, defaults, reference);
960
+ },
961
+ fetch: config?.fetch,
962
+ }),
963
+ }),
964
+ };
965
+ }
966
+
967
+ // ---------------------------------------------------------------------------
968
+ // 6.5 DeepSeek
969
+ // ---------------------------------------------------------------------------
970
+
971
+ export interface DeepSeekModelManagerConfig {
972
+ apiKey?: string;
973
+ baseUrl?: string;
974
+ fetch?: FetchImpl;
975
+ }
976
+
977
+ export function deepseekModelManagerOptions(
978
+ config?: DeepSeekModelManagerConfig,
979
+ ): ModelManagerOptions<"openai-completions"> {
980
+ return createSimpleOpenAICompletionsOptions("deepseek", "https://api.deepseek.com", config);
981
+ }
982
+ // ---------------------------------------------------------------------------
983
+ // 6.7 Zhipu Coding Plan
984
+ // ---------------------------------------------------------------------------
985
+
986
+ export interface ZhipuCodingPlanModelManagerConfig {
987
+ apiKey?: string;
988
+ baseUrl?: string;
989
+ fetch?: FetchImpl;
990
+ }
991
+
992
+ export function zhipuCodingPlanModelManagerOptions(
993
+ config?: ZhipuCodingPlanModelManagerConfig,
994
+ ): ModelManagerOptions<"openai-completions"> {
995
+ const apiKey = config?.apiKey;
996
+ const baseUrl = config?.baseUrl ?? "https://open.bigmodel.cn/api/coding/paas/v4";
997
+ return {
998
+ providerId: "zhipu-coding-plan",
999
+ ...(apiKey && {
1000
+ fetchDynamicModels: () =>
1001
+ fetchOpenAICompatibleModels({
1002
+ api: "openai-completions",
1003
+ provider: "zhipu-coding-plan",
1004
+ baseUrl,
1005
+ apiKey,
1006
+ mapModel: (
1007
+ _entry: OpenAICompatibleModelRecord,
1008
+ defaults: ModelSpec<"openai-completions">,
1009
+ _context: OpenAICompatibleModelMapperContext<"openai-completions">,
1010
+ ): ModelSpec<"openai-completions"> => {
1011
+ const id = defaults.id;
1012
+ return {
1013
+ ...defaults,
1014
+ reasoning: ZHIPU_REASONING_MODELS[id] === true || id.includes("thinking"),
1015
+ input: ZHIPU_VISION_PATTERN.test(id) ? (["text", "image"] as const) : ["text"],
1016
+ compat: {
1017
+ thinkingFormat: "zai",
1018
+ reasoningContentField: "reasoning_content",
1019
+ supportsDeveloperRole: false,
1020
+ },
1021
+ };
1022
+ },
1023
+ fetch: config?.fetch,
1024
+ }),
1025
+ }),
1026
+ };
1027
+ }
1028
+
1029
+ // Reasoning-capable GLM models on the BigModel coding-plan SKU. Keep this
1030
+ // explicit rather than regex-matching `glm-[45]\.\d` so newly-added integers
1031
+ // like `glm-5` / `glm-5-turbo` are covered and unrelated future SKUs (e.g.
1032
+ // `glm-5-preview`) do not silently flip into thinking mode.
1033
+ const ZHIPU_REASONING_MODELS: Readonly<Record<string, true>> = {
1034
+ "glm-4.5": true,
1035
+ "glm-4.5-air": true,
1036
+ "glm-4.6": true,
1037
+ "glm-4.7": true,
1038
+ "glm-5": true,
1039
+ "glm-5-turbo": true,
1040
+ "glm-5.1": true,
1041
+ };
1042
+
1043
+ // Vision-capable GLM models follow the `glm-<N>[.<N>]v[-<variant>]` shape
1044
+ // (e.g. `glm-4v`, `glm-4.5v`, `glm-4v-plus`). The previous `id.includes("v")`
1045
+ // check matched anything with a `v` — including the non-vision `glm-5-preview`.
1046
+ const ZHIPU_VISION_PATTERN = /^glm-[45](?:\.\d+)?v(?:-|$)/;
1047
+
1048
+ // ---------------------------------------------------------------------------
1049
+ // 7.5 Fireworks
1050
+ // ---------------------------------------------------------------------------
1051
+
1052
+ /**
1053
+ * Fireworks-published cap for the Kimi K2 family. Fireworks' `/v1/models`
1054
+ * envelope generically reports `max_completion_tokens: 65536` for every Kimi
1055
+ * deployment, but Kimi K2 (instruct / thinking / turbo) on Fireworks is
1056
+ * documented to ship long reasoning traces that should be bounded — capping
1057
+ * at 32,768 prevents handing callers a budget the router cannot honor.
1058
+ * See https://github.com/can1357/oh-my-pi/issues/1849.
1059
+ */
1060
+ export const FIREWORKS_KIMI_MAX_TOKENS = 32_768;
1061
+
1062
+ /**
1063
+ * Returns true for any Kimi K2.x public model id served by Fireworks-backed
1064
+ * providers (`fireworks` direct, `firepass` router). Matches both the public
1065
+ * catalog id (`kimi-k2.5`, `kimi-k2.6`, `kimi-k2.6-turbo`) and the canonical
1066
+ * Fireworks wire id (`accounts/fireworks/{models,routers}/kimi-k2…`).
1067
+ */
1068
+ export function isFireworksKimiK2ModelId(modelId: string): boolean {
1069
+ const trimmed = modelId.toLowerCase();
1070
+ if (trimmed.startsWith("kimi-k2")) return true;
1071
+ return /\/kimi-k2(?:p\d+)?(?:[._-]|$)/.test(trimmed);
1072
+ }
1073
+
1074
+ /**
1075
+ * Clamp the Kimi K2 family's `maxTokens` to {@link FIREWORKS_KIMI_MAX_TOKENS}
1076
+ * on Fireworks-backed providers, leaving every other model untouched.
1077
+ */
1078
+ export function clampFireworksKimiMaxTokens(modelId: string, candidate: number): number {
1079
+ return isFireworksKimiK2ModelId(modelId) ? Math.min(candidate, FIREWORKS_KIMI_MAX_TOKENS) : candidate;
1080
+ }
1081
+
1082
+ /**
1083
+ * Fireworks DeepSeek V4 accepts effort via `reasoning_effort` but rejects the
1084
+ * DeepSeek-native binary `thinking` toggle when both are present.
1085
+ */
1086
+ export function stripFireworksDeepSeekThinkingToggle(
1087
+ model: ModelSpec<"openai-completions">,
1088
+ publicModelId: string,
1089
+ ): ModelSpec<"openai-completions"> {
1090
+ if (!publicModelId.startsWith("deepseek-v4")) return model;
1091
+ const compat = model.compat;
1092
+ if (!compat?.extraBody || !("thinking" in compat.extraBody)) return model;
1093
+
1094
+ const extraBody = { ...compat.extraBody };
1095
+ delete extraBody.thinking;
1096
+ if (Object.keys(extraBody).length > 0) {
1097
+ return { ...model, compat: { ...compat, extraBody } };
1098
+ }
1099
+
1100
+ const nextCompat = { ...compat };
1101
+ delete nextCompat.extraBody;
1102
+ return { ...model, compat: nextCompat };
1103
+ }
1104
+
1105
+ export interface FireworksModelManagerConfig {
1106
+ apiKey?: string;
1107
+ baseUrl?: string;
1108
+ fetch?: FetchImpl;
1109
+ }
1110
+
1111
+ function toFireworksModelName(entry: OpenAICompatibleModelRecord, fallback: string): string {
1112
+ const name = toModelName(entry.name, "");
1113
+ if (name) return name;
1114
+ const id = typeof entry.id === "string" ? entry.id : fallback;
1115
+ const shortName = id.split("/").at(-1) ?? fallback;
1116
+ if (fallback !== id && fallback !== shortName) return fallback;
1117
+ return shortName
1118
+ .split("-")
1119
+ .filter(Boolean)
1120
+ .map(part => part.charAt(0).toUpperCase() + part.slice(1))
1121
+ .join(" ");
1122
+ }
1123
+
1124
+ function createModelsDevReferenceMap<TApi extends Api>(
1125
+ models: readonly ModelSpec<Api>[],
1126
+ ): Map<string, ModelSpec<TApi>> {
1127
+ const references = new Map<string, ModelSpec<TApi>>();
1128
+ for (const model of models) {
1129
+ const candidate = model as ModelSpec<TApi>;
1130
+ const existing = references.get(candidate.id);
1131
+ if (!existing) {
1132
+ references.set(candidate.id, candidate);
1133
+ continue;
1134
+ }
1135
+ if (candidate.contextWindow > existing.contextWindow) {
1136
+ references.set(candidate.id, candidate);
1137
+ continue;
1138
+ }
1139
+ if (candidate.contextWindow === existing.contextWindow && candidate.maxTokens > existing.maxTokens) {
1140
+ references.set(candidate.id, candidate);
1141
+ }
1142
+ }
1143
+ return references;
1144
+ }
1145
+
1146
+ async function loadModelsDevReferences<TApi extends Api>(fetchImpl?: FetchImpl): Promise<Map<string, ModelSpec<TApi>>> {
1147
+ try {
1148
+ const payload = await fetchModelsDevPayload(fetchImpl);
1149
+ return createModelsDevReferenceMap<TApi>(
1150
+ mapModelsDevToModels(payload as Record<string, unknown>, MODELS_DEV_PROVIDER_DESCRIPTORS),
1151
+ );
1152
+ } catch {
1153
+ return new Map<string, ModelSpec<TApi>>();
1154
+ }
1155
+ }
1156
+ export function fireworksModelManagerOptions(
1157
+ config?: FireworksModelManagerConfig,
1158
+ ): ModelManagerOptions<"openai-completions"> {
1159
+ const apiKey = config?.apiKey;
1160
+ const baseUrl = config?.baseUrl ?? "https://api.fireworks.ai/inference/v1";
1161
+ const bundledReferences = createReferenceResolver(createBundledReferenceMap<"openai-completions">("fireworks"));
1162
+ return {
1163
+ providerId: "fireworks",
1164
+ ...(apiKey && {
1165
+ fetchDynamicModels: async () => {
1166
+ const modelsDevReferences = await loadModelsDevReferences<"openai-completions">(config?.fetch);
1167
+ return fetchOpenAICompatibleModels({
1168
+ api: "openai-completions",
1169
+ provider: "fireworks",
1170
+ baseUrl,
1171
+ apiKey,
1172
+ filterModel: entry =>
1173
+ toBoolean(entry.supports_chat) === true && toBoolean(entry.supports_tools) === true,
1174
+ mapModel: (entry, defaults) => {
1175
+ const publicModelId = toFireworksPublicModelId(defaults.id);
1176
+ const reference = modelsDevReferences.get(publicModelId) ?? bundledReferences(publicModelId);
1177
+ const model = stripFireworksDeepSeekThinkingToggle(
1178
+ mapWithBundledReference(entry, defaults, reference),
1179
+ publicModelId,
1180
+ );
1181
+ return {
1182
+ ...model,
1183
+ id: publicModelId,
1184
+ api: "openai-completions",
1185
+ provider: "fireworks",
1186
+ baseUrl,
1187
+ name: toFireworksModelName(entry, model.name),
1188
+ input: toBoolean(entry.supports_image_input) === true ? ["text", "image"] : ["text"],
1189
+ contextWindow: toPositiveNumber(entry.context_length, model.contextWindow),
1190
+ maxTokens: clampFireworksKimiMaxTokens(
1191
+ publicModelId,
1192
+ toPositiveNumber(entry.max_completion_tokens, model.maxTokens),
1193
+ ),
1194
+ };
1195
+ },
1196
+ fetch: config?.fetch,
1197
+ });
1198
+ },
1199
+ }),
1200
+ };
1201
+ }
1202
+
1203
+ // ---------------------------------------------------------------------------
1204
+ // 7.6 Fire Pass (Fireworks Kimi K2.6 Turbo subscription)
1205
+ // ---------------------------------------------------------------------------
1206
+
1207
+ export interface FirepassModelManagerConfig {
1208
+ apiKey?: string;
1209
+ baseUrl?: string;
1210
+ fetch?: FetchImpl;
1211
+ }
1212
+
1213
+ /**
1214
+ * Fire Pass is a Fireworks subscription product that exposes a single router
1215
+ * model (Kimi K2.6 Turbo) under `accounts/fireworks/routers/kimi-k2p6-turbo`.
1216
+ * The dedicated `fpk_…` keys do not authorize `/v1/models`, so this manager
1217
+ * never performs dynamic discovery — the bundled catalog entry is canonical.
1218
+ * See https://docs.fireworks.ai/firepass.
1219
+ */
1220
+ export function firepassModelManagerOptions(
1221
+ _config?: FirepassModelManagerConfig,
1222
+ ): ModelManagerOptions<"openai-completions"> {
1223
+ return {
1224
+ providerId: "firepass",
1225
+ };
1226
+ }
1227
+
1228
+ // ---------------------------------------------------------------------------
1229
+ // 7.7 Wafer (Pass + Serverless)
1230
+ // ---------------------------------------------------------------------------
1231
+
1232
+ export interface WaferModelManagerConfig {
1233
+ apiKey?: string;
1234
+ baseUrl?: string;
1235
+ fetch?: FetchImpl;
1236
+ }
1237
+
1238
+ const WAFER_DEFAULT_BASE_URL = "https://pass.wafer.ai/v1";
1239
+ const WAFER_MAX_TOKENS_CAP = 65536;
1240
+
1241
+ /**
1242
+ * Shared mapper for Wafer's `/v1/models` records.
1243
+ *
1244
+ * Wafer wraps each entry with a `wafer` envelope describing tier, capabilities,
1245
+ * and cents-per-million pricing. The mapper folds that metadata into the
1246
+ * canonical `ModelSpec<"openai-completions">` shape and applies zai-family thinking
1247
+ * compat when the entry advertises reasoning support (GLM-family on the Pass
1248
+ * SKU). Cents-per-million → dollars-per-million via /100.
1249
+ */
1250
+ interface WaferRecord {
1251
+ context_length?: unknown;
1252
+ tier?: unknown;
1253
+ provider?: unknown;
1254
+ capabilities?: { vision?: unknown; reasoning?: unknown; tools?: unknown };
1255
+ pricing?: {
1256
+ input_cents_per_million?: unknown;
1257
+ output_cents_per_million?: unknown;
1258
+ cache_read_cents_per_million?: unknown;
1259
+ };
1260
+ display_name?: unknown;
1261
+ }
1262
+
1263
+ function readWaferRecord(entry: OpenAICompatibleModelRecord): WaferRecord | undefined {
1264
+ const raw = (entry as { wafer?: unknown }).wafer;
1265
+ return raw && typeof raw === "object" ? (raw as WaferRecord) : undefined;
1266
+ }
1267
+
1268
+ function mapWaferModel(
1269
+ providerId: "wafer-pass" | "wafer-serverless",
1270
+ baseUrl: string,
1271
+ entry: OpenAICompatibleModelRecord,
1272
+ defaults: ModelSpec<"openai-completions">,
1273
+ ): ModelSpec<"openai-completions"> {
1274
+ const wafer = readWaferRecord(entry);
1275
+ const capabilities = wafer?.capabilities ?? {};
1276
+ const reasoning = capabilities.reasoning === true;
1277
+ const vision = capabilities.vision === true;
1278
+ const contextWindow = toPositiveNumber(
1279
+ wafer?.context_length,
1280
+ toPositiveNumber((entry as { max_model_len?: unknown }).max_model_len, defaults.contextWindow),
1281
+ );
1282
+ const maxTokens = Math.min(contextWindow, WAFER_MAX_TOKENS_CAP);
1283
+ const pricing = wafer?.pricing ?? {};
1284
+ // Wafer's `/v1/models` exposes pricing through `*_cents_per_million` fields,
1285
+ // but the values are an internal wholesale unit, not literal cents — across
1286
+ // every published Serverless model on wafer.ai the user-facing rate equals
1287
+ // `cents × 125 / 10000` (i.e. wholesale × 1.25 / 100; GLM-5.1's `120` →
1288
+ // $1.50/M, Kimi-K2.6's `88` → $1.10/M, etc.). The multiply-first form keeps
1289
+ // the result a finite dyadic for every observed value.
1290
+ // For the Pass SKU the per-token rate is bundled in the flat-rate
1291
+ // subscription, so we follow the convention shared with
1292
+ // `kimi-code`/`firepass`/`alibaba-coding-plan` and seed every Pass model with
1293
+ // `cost: 0` regardless of what the upstream envelope says.
1294
+ const isPassSku = providerId === "wafer-pass";
1295
+ const cost = isPassSku
1296
+ ? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
1297
+ : {
1298
+ input: (toPositiveNumber(pricing.input_cents_per_million, 0) * 125) / 10000,
1299
+ output: (toPositiveNumber(pricing.output_cents_per_million, 0) * 125) / 10000,
1300
+ cacheRead: (toPositiveNumber(pricing.cache_read_cents_per_million, 0) * 125) / 10000,
1301
+ cacheWrite: 0,
1302
+ };
1303
+ const name = toModelName(wafer?.display_name, defaults.name);
1304
+ const base: ModelSpec<"openai-completions"> = {
1305
+ ...defaults,
1306
+ id: defaults.id,
1307
+ name,
1308
+ api: "openai-completions",
1309
+ provider: providerId,
1310
+ baseUrl,
1311
+ reasoning,
1312
+ input: vision ? (["text", "image"] as const) : ["text"],
1313
+ cost,
1314
+ contextWindow,
1315
+ maxTokens,
1316
+ };
1317
+ if (reasoning) {
1318
+ // Wafer's `wafer.provider` envelope tells us which upstream backend serves
1319
+ // the model. Each upstream accepts a different thinking-control parameter
1320
+ // on the wire — Wafer passes the body through, so we must mirror the
1321
+ // upstream's native shape:
1322
+ // - zai (GLM) and moonshotai (Kimi) → `thinking: { type: "enabled" | "disabled" }`
1323
+ // - qwen (Alibaba) → top-level `enable_thinking: boolean`
1324
+ // - deepseek → `reasoning_effort` (DeepSeek effort map; the model always
1325
+ // reasons when invoked, replay of `reasoning_content` is required on
1326
+ // tool-call turns — both handled by `detectOpenAICompat` from the id).
1327
+ // For unknown upstreams we omit `thinkingFormat` and let the per-id
1328
+ // detection in `detectOpenAICompat` pick a safe default.
1329
+ const upstream = typeof wafer?.provider === "string" ? wafer.provider : undefined;
1330
+ const thinkingFormat: "zai" | "qwen" | undefined =
1331
+ upstream === "zai" || upstream === "moonshotai" ? "zai" : upstream === "qwen" ? "qwen" : undefined;
1332
+ return {
1333
+ ...base,
1334
+ compat: {
1335
+ ...(thinkingFormat ? { thinkingFormat } : {}),
1336
+ reasoningContentField: "reasoning_content",
1337
+ supportsDeveloperRole: false,
1338
+ },
1339
+ };
1340
+ }
1341
+ return {
1342
+ ...base,
1343
+ compat: { supportsDeveloperRole: false },
1344
+ };
1345
+ }
1346
+
1347
+ function createWaferOptions(
1348
+ providerId: "wafer-pass" | "wafer-serverless",
1349
+ config: WaferModelManagerConfig | undefined,
1350
+ ): ModelManagerOptions<"openai-completions"> {
1351
+ const apiKey = config?.apiKey;
1352
+ const baseUrl = config?.baseUrl ?? WAFER_DEFAULT_BASE_URL;
1353
+ const passOnly = providerId === "wafer-pass";
1354
+ return {
1355
+ providerId,
1356
+ ...(apiKey && {
1357
+ fetchDynamicModels: () =>
1358
+ fetchOpenAICompatibleModels({
1359
+ api: "openai-completions",
1360
+ provider: providerId,
1361
+ baseUrl,
1362
+ apiKey,
1363
+ filterModel: entry => {
1364
+ if (!passOnly) return true;
1365
+ const wafer = readWaferRecord(entry);
1366
+ return wafer?.tier === "pass_included";
1367
+ },
1368
+ mapModel: (entry, defaults) => mapWaferModel(providerId, baseUrl, entry, defaults),
1369
+ fetch: config?.fetch,
1370
+ }),
1371
+ }),
1372
+ };
1373
+ }
1374
+
1375
+ export function waferPassModelManagerOptions(
1376
+ config?: WaferModelManagerConfig,
1377
+ ): ModelManagerOptions<"openai-completions"> {
1378
+ return createWaferOptions("wafer-pass", config);
1379
+ }
1380
+
1381
+ export function waferServerlessModelManagerOptions(
1382
+ config?: WaferModelManagerConfig,
1383
+ ): ModelManagerOptions<"openai-completions"> {
1384
+ return createWaferOptions("wafer-serverless", config);
1385
+ }
1386
+
1387
+ // ---------------------------------------------------------------------------
1388
+ // 7. Mistral
1389
+ // ---------------------------------------------------------------------------
1390
+
1391
+ export interface MistralModelManagerConfig {
1392
+ apiKey?: string;
1393
+ baseUrl?: string;
1394
+ fetch?: FetchImpl;
1395
+ }
1396
+
1397
+ export function mistralModelManagerOptions(
1398
+ config?: MistralModelManagerConfig,
1399
+ ): ModelManagerOptions<"openai-completions"> {
1400
+ return createSimpleOpenAICompletionsOptions("mistral", "https://api.mistral.ai/v1", config);
1401
+ }
1402
+
1403
+ // ---------------------------------------------------------------------------
1404
+ // 8. OpenCode
1405
+ // ---------------------------------------------------------------------------
1406
+
1407
+ export interface OpenCodeModelManagerConfig {
1408
+ apiKey?: string;
1409
+ baseUrl?: string;
1410
+ fetch?: FetchImpl;
1411
+ }
1412
+
1413
+ function normalizeOpenCodeBasePath(baseUrl: string | undefined, fallbackBasePath: string): string {
1414
+ const value = normalizeAnthropicBaseUrl(baseUrl, fallbackBasePath);
1415
+ return value.endsWith("/v1") ? value.slice(0, -3) : value;
1416
+ }
1417
+
1418
+ function openCodeBaseUrlForApi(api: Api, basePath: string): string {
1419
+ return api === "anthropic-messages" ? basePath : `${basePath}/v1`;
1420
+ }
1421
+
1422
+ function openCodeModelManagerOptions(
1423
+ providerId: "opencode-go" | "opencode-zen",
1424
+ defaultBasePath: string,
1425
+ config?: OpenCodeModelManagerConfig,
1426
+ ): ModelManagerOptions<Api> {
1427
+ const apiKey = config?.apiKey;
1428
+ const basePath = normalizeOpenCodeBasePath(config?.baseUrl, defaultBasePath);
1429
+ const discoveryBaseUrl = openCodeBaseUrlForApi("openai-completions", basePath);
1430
+ const references = createBundledReferenceMap<Api>(providerId);
1431
+ return {
1432
+ providerId,
1433
+ ...(apiKey && {
1434
+ fetchDynamicModels: () =>
1435
+ fetchOpenAICompatibleModels<Api>({
1436
+ api: "openai-completions",
1437
+ provider: providerId,
1438
+ baseUrl: discoveryBaseUrl,
1439
+ apiKey,
1440
+ mapModel: (entry, defaults) => {
1441
+ const reference = references.get(defaults.id);
1442
+ const name = toModelName(entry.name, reference?.name ?? defaults.name);
1443
+ if (!reference) {
1444
+ return {
1445
+ ...defaults,
1446
+ name,
1447
+ };
1448
+ }
1449
+ return {
1450
+ ...reference,
1451
+ id: defaults.id,
1452
+ name,
1453
+ baseUrl: openCodeBaseUrlForApi(reference.api, basePath),
1454
+ contextWindow: toPositiveNumber(entry.context_length, reference.contextWindow),
1455
+ maxTokens: toPositiveNumber(entry.max_completion_tokens, reference.maxTokens),
1456
+ };
1457
+ },
1458
+ fetch: config?.fetch,
1459
+ }),
1460
+ }),
1461
+ };
1462
+ }
1463
+
1464
+ export function opencodeZenModelManagerOptions(config?: OpenCodeModelManagerConfig): ModelManagerOptions<Api> {
1465
+ return openCodeModelManagerOptions("opencode-zen", "https://opencode.ai/zen", config);
1466
+ }
1467
+
1468
+ export function opencodeGoModelManagerOptions(config?: OpenCodeModelManagerConfig): ModelManagerOptions<Api> {
1469
+ return openCodeModelManagerOptions("opencode-go", "https://opencode.ai/zen/go", config);
1470
+ }
1471
+
1472
+ // ---------------------------------------------------------------------------
1473
+ // 9. Ollama
1474
+ // ---------------------------------------------------------------------------
1475
+
1476
+ export interface OllamaModelManagerConfig {
1477
+ apiKey?: string;
1478
+ baseUrl?: string;
1479
+ fetch?: FetchImpl;
1480
+ }
1481
+
1482
+ export function ollamaModelManagerOptions(config?: OllamaModelManagerConfig): ModelManagerOptions<"openai-responses"> {
1483
+ const apiKey = config?.apiKey;
1484
+ const baseUrl = normalizeOllamaBaseUrl(config?.baseUrl);
1485
+ const nativeBaseUrl = toOllamaNativeBaseUrl(baseUrl);
1486
+ const references = createBundledReferenceMap<"openai-responses">("ollama" as Parameters<typeof getBundledModels>[0]);
1487
+ const resolveMetadata = createOllamaMetadataResolver(nativeBaseUrl, config?.fetch);
1488
+ return {
1489
+ providerId: "ollama",
1490
+ fetchDynamicModels: async () => {
1491
+ const openAiCompatible = await fetchOpenAICompatibleModels({
1492
+ api: "openai-responses",
1493
+ provider: "ollama",
1494
+ baseUrl,
1495
+ apiKey,
1496
+ mapModel: (entry, defaults) => {
1497
+ const reference = references.get(defaults.id);
1498
+ if (!reference) {
1499
+ return {
1500
+ ...defaults,
1501
+ name: toModelName(entry.name, defaults.name),
1502
+ contextWindow: OLLAMA_FALLBACK_CONTEXT_WINDOW,
1503
+ maxTokens: OLLAMA_DEFAULT_MAX_TOKENS,
1504
+ };
1505
+ }
1506
+ return mapWithBundledReference(entry, defaults, reference);
1507
+ },
1508
+ fetch: config?.fetch,
1509
+ });
1510
+ if (openAiCompatible && openAiCompatible.length > 0) {
1511
+ await Promise.all(
1512
+ openAiCompatible.map(async model => {
1513
+ const metadata = await resolveMetadata(model.id);
1514
+ model.contextWindow = metadata.contextWindow;
1515
+ if (metadata.reasoning !== undefined) {
1516
+ model.reasoning = metadata.reasoning;
1517
+ model.thinking = metadata.thinking;
1518
+ }
1519
+ if (metadata.input) {
1520
+ model.input = metadata.input;
1521
+ }
1522
+ applyOllamaReasoningCompat(model);
1523
+ }),
1524
+ );
1525
+ return openAiCompatible;
1526
+ }
1527
+ const nativeFallback = await fetchOllamaNativeModels(baseUrl, resolveMetadata, config?.fetch);
1528
+ if (nativeFallback && nativeFallback.length > 0) {
1529
+ for (const model of nativeFallback) applyOllamaReasoningCompat(model);
1530
+ return nativeFallback;
1531
+ }
1532
+ return openAiCompatible;
1533
+ },
1534
+ };
1535
+ }
1536
+
1537
+ // ---------------------------------------------------------------------------
1538
+ // 10. OpenRouter
1539
+ // ---------------------------------------------------------------------------
1540
+
1541
+ export interface OpenRouterModelManagerConfig {
1542
+ apiKey?: string;
1543
+ baseUrl?: string;
1544
+ fetch?: FetchImpl;
1545
+ }
1546
+
1547
+ export function openrouterModelManagerOptions(
1548
+ config?: OpenRouterModelManagerConfig,
1549
+ ): ModelManagerOptions<"openai-completions"> {
1550
+ const apiKey = config?.apiKey;
1551
+ const baseUrl = config?.baseUrl ?? "https://openrouter.ai/api/v1";
1552
+ return {
1553
+ providerId: "openrouter",
1554
+ fetchDynamicModels: () =>
1555
+ fetchOpenAICompatibleModels({
1556
+ api: "openai-completions",
1557
+ provider: "openrouter",
1558
+ baseUrl,
1559
+ apiKey,
1560
+ filterModel: (entry: OpenAICompatibleModelRecord) => {
1561
+ const params = entry.supported_parameters;
1562
+ return Array.isArray(params) && params.includes("tools");
1563
+ },
1564
+ mapModel: (
1565
+ entry: OpenAICompatibleModelRecord,
1566
+ defaults: ModelSpec<"openai-completions">,
1567
+ _context: OpenAICompatibleModelMapperContext<"openai-completions">,
1568
+ ): ModelSpec<"openai-completions"> => {
1569
+ const pricing = entry.pricing as Record<string, unknown> | undefined;
1570
+ const params = Array.isArray(entry.supported_parameters) ? (entry.supported_parameters as string[]) : [];
1571
+ const modality = String((entry.architecture as Record<string, unknown> | undefined)?.modality ?? "");
1572
+ const topProvider = entry.top_provider as Record<string, unknown> | undefined;
1573
+
1574
+ const supportsToolChoice = params.includes("tool_choice");
1575
+
1576
+ return {
1577
+ ...defaults,
1578
+ reasoning: params.includes("reasoning"),
1579
+ input: modality.includes("image") ? ["text", "image"] : ["text"],
1580
+ cost: {
1581
+ input: parseFloat(String(pricing?.prompt ?? "0")) * 1_000_000,
1582
+ output: parseFloat(String(pricing?.completion ?? "0")) * 1_000_000,
1583
+ cacheRead: parseFloat(String(pricing?.input_cache_read ?? "0")) * 1_000_000,
1584
+ cacheWrite: parseFloat(String(pricing?.input_cache_write ?? "0")) * 1_000_000,
1585
+ },
1586
+ contextWindow:
1587
+ typeof entry.context_length === "number" ? entry.context_length : defaults.contextWindow,
1588
+ maxTokens:
1589
+ typeof topProvider?.max_completion_tokens === "number"
1590
+ ? topProvider.max_completion_tokens
1591
+ : defaults.maxTokens,
1592
+ ...(!supportsToolChoice && {
1593
+ compat: { supportsToolChoice: false },
1594
+ }),
1595
+ };
1596
+ },
1597
+ fetch: config?.fetch,
1598
+ }),
1599
+ };
1600
+ }
1601
+
1602
+ const ZENMUX_OPENAI_BASE_URL = "https://zenmux.ai/api/v1";
1603
+ const ZENMUX_ANTHROPIC_BASE_URL = "https://zenmux.ai/api/anthropic";
1604
+
1605
+ function normalizeZenMuxOpenAiBaseUrl(baseUrl?: string): string {
1606
+ const value = baseUrl?.trim();
1607
+ if (!value) {
1608
+ return ZENMUX_OPENAI_BASE_URL;
1609
+ }
1610
+ return value.endsWith("/") ? value.slice(0, -1) : value;
1611
+ }
1612
+
1613
+ function toZenMuxAnthropicBaseUrl(openAiBaseUrl: string): string {
1614
+ try {
1615
+ const parsed = new URL(openAiBaseUrl);
1616
+ const trimmedPath = parsed.pathname.replace(/\/+$/g, "");
1617
+ parsed.pathname = trimmedPath.endsWith("/api/v1")
1618
+ ? `${trimmedPath.slice(0, -"/api/v1".length)}/api/anthropic`
1619
+ : "/api/anthropic";
1620
+ return `${parsed.protocol}//${parsed.host}${parsed.pathname}`;
1621
+ } catch {
1622
+ return ZENMUX_ANTHROPIC_BASE_URL;
1623
+ }
1624
+ }
1625
+
1626
+ function isZenMuxAnthropicModel(entry: OpenAICompatibleModelRecord, modelId: string): boolean {
1627
+ if (typeof entry.owned_by === "string" && entry.owned_by.toLowerCase() === "anthropic") {
1628
+ return true;
1629
+ }
1630
+ return modelId.toLowerCase().startsWith("anthropic/");
1631
+ }
1632
+
1633
+ function getZenMuxPricingValue(pricings: Record<string, unknown> | undefined, key: string): number {
1634
+ const bucket = pricings?.[key];
1635
+ if (!Array.isArray(bucket)) {
1636
+ return 0;
1637
+ }
1638
+ for (const item of bucket) {
1639
+ if (!isRecord(item)) {
1640
+ continue;
1641
+ }
1642
+ const value = toNumber(item.value);
1643
+ if (value !== undefined) {
1644
+ return value;
1645
+ }
1646
+ }
1647
+ return 0;
1648
+ }
1649
+
1650
+ function getZenMuxCacheWritePrice(pricings: Record<string, unknown> | undefined): number {
1651
+ const oneHour = getZenMuxPricingValue(pricings, "input_cache_write_1_h");
1652
+ if (oneHour > 0) {
1653
+ return oneHour;
1654
+ }
1655
+ const fiveMinute = getZenMuxPricingValue(pricings, "input_cache_write_5_min");
1656
+ if (fiveMinute > 0) {
1657
+ return fiveMinute;
1658
+ }
1659
+ return getZenMuxPricingValue(pricings, "input_cache_write");
1660
+ }
1661
+
1662
+ // ---------------------------------------------------------------------------
1663
+ // 10.5 ZenMux
1664
+ // ---------------------------------------------------------------------------
1665
+
1666
+ export interface ZenMuxModelManagerConfig {
1667
+ apiKey?: string;
1668
+ baseUrl?: string;
1669
+ fetch?: FetchImpl;
1670
+ }
1671
+
1672
+ export function zenmuxModelManagerOptions(config?: ZenMuxModelManagerConfig): ModelManagerOptions<Api> {
1673
+ const apiKey = config?.apiKey;
1674
+ const openAiBaseUrl = normalizeZenMuxOpenAiBaseUrl(config?.baseUrl);
1675
+ const anthropicBaseUrl = toZenMuxAnthropicBaseUrl(openAiBaseUrl);
1676
+ return {
1677
+ providerId: "zenmux",
1678
+ ...(apiKey && {
1679
+ fetchDynamicModels: () =>
1680
+ fetchOpenAICompatibleModels<Api>({
1681
+ api: "openai-completions",
1682
+ provider: "zenmux",
1683
+ baseUrl: openAiBaseUrl,
1684
+ apiKey,
1685
+ mapModel: (entry, defaults) => {
1686
+ const pricings = isRecord(entry.pricings) ? entry.pricings : undefined;
1687
+ const capabilities = isRecord(entry.capabilities) ? entry.capabilities : undefined;
1688
+ const isAnthropicModel = isZenMuxAnthropicModel(entry, defaults.id);
1689
+ return {
1690
+ ...defaults,
1691
+ name: toModelName(entry.display_name, defaults.name),
1692
+ api: isAnthropicModel ? "anthropic-messages" : "openai-completions",
1693
+ baseUrl: isAnthropicModel ? anthropicBaseUrl : openAiBaseUrl,
1694
+ reasoning: capabilities?.reasoning === true || defaults.reasoning,
1695
+ input: toInputCapabilities(entry.input_modalities),
1696
+ cost: {
1697
+ input: getZenMuxPricingValue(pricings, "prompt"),
1698
+ output: getZenMuxPricingValue(pricings, "completion"),
1699
+ cacheRead: getZenMuxPricingValue(pricings, "input_cache_read"),
1700
+ cacheWrite: getZenMuxCacheWritePrice(pricings),
1701
+ },
1702
+ contextWindow: toPositiveNumber(entry.context_length, defaults.contextWindow),
1703
+ maxTokens: toPositiveNumber(entry.max_completion_tokens, defaults.maxTokens),
1704
+ };
1705
+ },
1706
+ fetch: config?.fetch,
1707
+ }),
1708
+ }),
1709
+ };
1710
+ }
1711
+
1712
+ // ---------------------------------------------------------------------------
1713
+ // 10.6 Kilo Gateway
1714
+ // ---------------------------------------------------------------------------
1715
+
1716
+ export interface KiloModelManagerConfig {
1717
+ apiKey?: string;
1718
+ baseUrl?: string;
1719
+ fetch?: FetchImpl;
1720
+ }
1721
+
1722
+ export function kiloModelManagerOptions(config?: KiloModelManagerConfig): ModelManagerOptions<"openai-completions"> {
1723
+ const apiKey = config?.apiKey;
1724
+ const baseUrl = config?.baseUrl ?? "https://api.kilo.ai/api/gateway";
1725
+ return {
1726
+ providerId: "kilo",
1727
+ fetchDynamicModels: () =>
1728
+ fetchOpenAICompatibleModels({
1729
+ api: "openai-completions",
1730
+ provider: "kilo",
1731
+ baseUrl,
1732
+ apiKey,
1733
+ fetch: config?.fetch,
1734
+ }),
1735
+ };
1736
+ }
1737
+
1738
+ // ---------------------------------------------------------------------------
1739
+ // Alibaba Coding Plan
1740
+ // ---------------------------------------------------------------------------
1741
+
1742
+ export interface AlibabaCodingPlanModelManagerConfig {
1743
+ apiKey?: string;
1744
+ baseUrl?: string;
1745
+ fetch?: FetchImpl;
1746
+ }
1747
+
1748
+ export function alibabaCodingPlanModelManagerOptions(
1749
+ config?: AlibabaCodingPlanModelManagerConfig,
1750
+ ): ModelManagerOptions<"openai-completions"> {
1751
+ const apiKey = config?.apiKey;
1752
+ const baseUrl = config?.baseUrl ?? "https://coding-intl.dashscope.aliyuncs.com/v1";
1753
+ const references = createBundledReferenceMap<"openai-completions">("alibaba-coding-plan");
1754
+ return {
1755
+ providerId: "alibaba-coding-plan",
1756
+ fetchDynamicModels: () =>
1757
+ fetchOpenAICompatibleModels({
1758
+ api: "openai-completions",
1759
+ provider: "alibaba-coding-plan",
1760
+ baseUrl,
1761
+ apiKey,
1762
+ mapModel: (entry, defaults) => {
1763
+ const reference = references.get(defaults.id);
1764
+ return mapWithBundledReference(entry, defaults, reference);
1765
+ },
1766
+ fetch: config?.fetch,
1767
+ }),
1768
+ };
1769
+ }
1770
+
1771
+ // ---------------------------------------------------------------------------
1772
+ // 11. Vercel AI Gateway
1773
+ // ---------------------------------------------------------------------------
1774
+
1775
+ export interface VercelAiGatewayModelManagerConfig {
1776
+ apiKey?: string;
1777
+ baseUrl?: string;
1778
+ fetch?: FetchImpl;
1779
+ }
1780
+
1781
+ function normalizeVercelAiGatewayBaseUrls(rawBaseUrl: string | undefined): { baseUrl: string; catalogBaseUrl: string } {
1782
+ const baseUrl = (rawBaseUrl === undefined ? "https://ai-gateway.vercel.sh" : rawBaseUrl.trim()).replace(/\/+$/, "");
1783
+ const catalogBaseUrl = baseUrl === "" || baseUrl.endsWith("/v1") ? baseUrl : `${baseUrl}/v1`;
1784
+
1785
+ return {
1786
+ baseUrl: baseUrl.endsWith("/v1") ? baseUrl.slice(0, -3) : baseUrl,
1787
+ catalogBaseUrl,
1788
+ };
1789
+ }
1790
+
1791
+ export function vercelAiGatewayModelManagerOptions(
1792
+ config?: VercelAiGatewayModelManagerConfig,
1793
+ ): ModelManagerOptions<"anthropic-messages"> {
1794
+ const apiKey = config?.apiKey;
1795
+ const { baseUrl, catalogBaseUrl } = normalizeVercelAiGatewayBaseUrls(config?.baseUrl);
1796
+ return {
1797
+ providerId: "vercel-ai-gateway",
1798
+ fetchDynamicModels: () =>
1799
+ fetchOpenAICompatibleModels({
1800
+ api: "anthropic-messages",
1801
+ provider: "vercel-ai-gateway",
1802
+ baseUrl: catalogBaseUrl,
1803
+ apiKey,
1804
+ filterModel: (entry: OpenAICompatibleModelRecord) => {
1805
+ const tags = entry.tags;
1806
+ return Array.isArray(tags) && tags.includes("tool-use");
1807
+ },
1808
+ mapModel: (
1809
+ entry: OpenAICompatibleModelRecord,
1810
+ defaults: ModelSpec<"anthropic-messages">,
1811
+ _context: OpenAICompatibleModelMapperContext<"anthropic-messages">,
1812
+ ): ModelSpec<"anthropic-messages"> => {
1813
+ const pricing = entry.pricing as Record<string, unknown> | undefined;
1814
+ const tags = Array.isArray(entry.tags) ? (entry.tags as string[]) : [];
1815
+
1816
+ return {
1817
+ ...defaults,
1818
+ baseUrl,
1819
+ reasoning: tags.includes("reasoning"),
1820
+ input: tags.includes("vision") ? ["text", "image"] : ["text"],
1821
+ cost: {
1822
+ input: (toNumber(pricing?.input) ?? 0) * 1_000_000,
1823
+ output: (toNumber(pricing?.output) ?? 0) * 1_000_000,
1824
+ cacheRead: (toNumber(pricing?.input_cache_read) ?? 0) * 1_000_000,
1825
+ cacheWrite: (toNumber(pricing?.input_cache_write) ?? 0) * 1_000_000,
1826
+ },
1827
+ contextWindow:
1828
+ typeof entry.context_window === "number" ? entry.context_window : defaults.contextWindow,
1829
+ maxTokens: typeof entry.max_tokens === "number" ? entry.max_tokens : defaults.maxTokens,
1830
+ };
1831
+ },
1832
+ fetch: config?.fetch,
1833
+ }),
1834
+ };
1835
+ }
1836
+
1837
+ // ---------------------------------------------------------------------------
1838
+ // 12. Kimi Code
1839
+ // ---------------------------------------------------------------------------
1840
+
1841
+ export interface KimiCodeModelManagerConfig {
1842
+ apiKey?: string;
1843
+ baseUrl?: string;
1844
+ fetch?: FetchImpl;
1845
+ }
1846
+
1847
+ export function kimiCodeModelManagerOptions(
1848
+ config?: KimiCodeModelManagerConfig,
1849
+ ): ModelManagerOptions<"openai-completions"> {
1850
+ const apiKey = config?.apiKey;
1851
+ const baseUrl = config?.baseUrl ?? "https://api.kimi.com/coding/v1";
1852
+ return {
1853
+ providerId: "kimi-code",
1854
+ ...(apiKey && {
1855
+ fetchDynamicModels: () =>
1856
+ fetchOpenAICompatibleModels({
1857
+ api: "openai-completions",
1858
+ provider: "kimi-code",
1859
+ baseUrl,
1860
+ apiKey,
1861
+ headers: {
1862
+ "User-Agent": "KimiCLI/1.0",
1863
+ "X-Msh-Platform": "kimi_cli",
1864
+ },
1865
+ mapModel: (
1866
+ entry: OpenAICompatibleModelRecord,
1867
+ defaults: ModelSpec<"openai-completions">,
1868
+ _context: OpenAICompatibleModelMapperContext<"openai-completions">,
1869
+ ): ModelSpec<"openai-completions"> => {
1870
+ const id = defaults.id;
1871
+ return {
1872
+ ...defaults,
1873
+ name: typeof entry.display_name === "string" ? entry.display_name : defaults.name,
1874
+ reasoning: entry.supports_reasoning === true || id.includes("thinking"),
1875
+ input: entry.supports_image_in === true || id.includes("k2.5") ? ["text", "image"] : ["text"],
1876
+ contextWindow: typeof entry.context_length === "number" ? entry.context_length : 262144,
1877
+ maxTokens: 32000,
1878
+ compat: {
1879
+ thinkingFormat: "zai",
1880
+ reasoningContentField: "reasoning_content",
1881
+ supportsDeveloperRole: false,
1882
+ },
1883
+ };
1884
+ },
1885
+ fetch: config?.fetch,
1886
+ }),
1887
+ }),
1888
+ };
1889
+ }
1890
+
1891
+ // ---------------------------------------------------------------------------
1892
+ // 12.5. LM Studio
1893
+ // ---------------------------------------------------------------------------
1894
+
1895
+ export interface LmStudioModelManagerConfig {
1896
+ apiKey?: string;
1897
+ baseUrl?: string;
1898
+ fetch?: FetchImpl;
1899
+ }
1900
+
1901
+ export function lmStudioModelManagerOptions(
1902
+ config?: LmStudioModelManagerConfig,
1903
+ ): ModelManagerOptions<"openai-completions"> {
1904
+ const apiKey = config?.apiKey;
1905
+ const baseUrl = config?.baseUrl ?? Bun.env.LM_STUDIO_BASE_URL ?? "http://127.0.0.1:1234/v1";
1906
+ const references = createBundledReferenceMap<"openai-completions">("lm-studio" as any);
1907
+ return {
1908
+ providerId: "lm-studio",
1909
+ fetchDynamicModels: () =>
1910
+ fetchOpenAICompatibleModels({
1911
+ api: "openai-completions",
1912
+ provider: "lm-studio",
1913
+ baseUrl,
1914
+ apiKey,
1915
+ mapModel: (entry, defaults) => {
1916
+ const reference = references.get(defaults.id);
1917
+ return mapWithBundledReference(entry, defaults, reference);
1918
+ },
1919
+ fetch: config?.fetch,
1920
+ }),
1921
+ };
1922
+ }
1923
+
1924
+ // ---------------------------------------------------------------------------
1925
+ // 13. Synthetic
1926
+ // ---------------------------------------------------------------------------
1927
+
1928
+ export interface SyntheticModelManagerConfig {
1929
+ apiKey?: string;
1930
+ baseUrl?: string;
1931
+ fetch?: FetchImpl;
1932
+ }
1933
+
1934
+ export function syntheticModelManagerOptions(
1935
+ config?: SyntheticModelManagerConfig,
1936
+ ): ModelManagerOptions<"openai-completions"> {
1937
+ const apiKey = config?.apiKey;
1938
+ const baseUrl = config?.baseUrl ?? "https://api.synthetic.new/openai/v1";
1939
+ const references = new Map(
1940
+ (getBundledModels("synthetic") as Model<"openai-completions">[]).map(model => [model.id, toModelSpec(model)]),
1941
+ );
1942
+ return {
1943
+ providerId: "synthetic",
1944
+ dynamicModelsAuthoritative: true,
1945
+ ...(apiKey && {
1946
+ fetchDynamicModels: () =>
1947
+ fetchOpenAICompatibleModels({
1948
+ api: "openai-completions",
1949
+ provider: "synthetic",
1950
+ baseUrl,
1951
+ apiKey,
1952
+ mapModel: (
1953
+ entry: OpenAICompatibleModelRecord,
1954
+ defaults: ModelSpec<"openai-completions">,
1955
+ _context: OpenAICompatibleModelMapperContext<"openai-completions">,
1956
+ ): ModelSpec<"openai-completions"> => {
1957
+ const reference = references.get(defaults.id);
1958
+ const referenceSupportsImage = reference?.input.includes("image") ?? false;
1959
+ return {
1960
+ ...(reference ? { ...reference, id: defaults.id, baseUrl } : defaults),
1961
+ name: toModelName(entry.name, reference?.name ?? defaults.name),
1962
+ reasoning: entry.supports_reasoning === true || (reference?.reasoning ?? false),
1963
+ input: entry.supports_vision === true || referenceSupportsImage ? ["text", "image"] : ["text"],
1964
+ contextWindow: toPositiveNumber(
1965
+ entry.context_length,
1966
+ reference?.contextWindow ?? defaults.contextWindow,
1967
+ ),
1968
+ maxTokens: toPositiveNumber(entry.max_tokens, reference?.maxTokens ?? 8192),
1969
+ };
1970
+ },
1971
+ fetch: config?.fetch,
1972
+ }),
1973
+ }),
1974
+ };
1975
+ }
1976
+
1977
+ // ---------------------------------------------------------------------------
1978
+ // 14. Venice
1979
+ // ---------------------------------------------------------------------------
1980
+
1981
+ export interface VeniceModelManagerConfig {
1982
+ apiKey?: string;
1983
+ baseUrl?: string;
1984
+ fetch?: FetchImpl;
1985
+ }
1986
+
1987
+ export function veniceModelManagerOptions(
1988
+ config?: VeniceModelManagerConfig,
1989
+ ): ModelManagerOptions<"openai-completions"> {
1990
+ const apiKey = config?.apiKey;
1991
+ const baseUrl = config?.baseUrl ?? "https://api.venice.ai/api/v1";
1992
+ const references = createBundledReferenceMap<"openai-completions">("venice");
1993
+ return {
1994
+ providerId: "venice",
1995
+ fetchDynamicModels: () =>
1996
+ fetchOpenAICompatibleModels({
1997
+ api: "openai-completions",
1998
+ provider: "venice",
1999
+ baseUrl,
2000
+ apiKey,
2001
+ mapModel: (entry, defaults) => {
2002
+ const reference = references.get(defaults.id);
2003
+ const model = mapWithBundledReference(entry, defaults, reference);
2004
+ return {
2005
+ ...model,
2006
+ compat: { ...model.compat, supportsUsageInStreaming: false },
2007
+ };
2008
+ },
2009
+ fetch: config?.fetch,
2010
+ }),
2011
+ };
2012
+ }
2013
+
2014
+ // ---------------------------------------------------------------------------
2015
+ // 15. Together
2016
+ // ---------------------------------------------------------------------------
2017
+
2018
+ export interface TogetherModelManagerConfig {
2019
+ apiKey?: string;
2020
+ baseUrl?: string;
2021
+ fetch?: FetchImpl;
2022
+ }
2023
+
2024
+ export function togetherModelManagerOptions(
2025
+ config?: TogetherModelManagerConfig,
2026
+ ): ModelManagerOptions<"openai-completions"> {
2027
+ return createSimpleOpenAICompletionsOptions("together", "https://api.together.xyz/v1", config);
2028
+ }
2029
+
2030
+ // ---------------------------------------------------------------------------
2031
+ // 16. Moonshot
2032
+ // ---------------------------------------------------------------------------
2033
+
2034
+ export interface MoonshotModelManagerConfig {
2035
+ apiKey?: string;
2036
+ baseUrl?: string;
2037
+ fetch?: FetchImpl;
2038
+ }
2039
+
2040
+ export function moonshotModelManagerOptions(
2041
+ config?: MoonshotModelManagerConfig,
2042
+ ): ModelManagerOptions<"openai-completions"> {
2043
+ const apiKey = config?.apiKey;
2044
+ const baseUrl = config?.baseUrl ?? "https://api.moonshot.ai/v1";
2045
+ const references = createBundledReferenceMap<"openai-completions">("moonshot");
2046
+ return {
2047
+ providerId: "moonshot",
2048
+ ...(apiKey && {
2049
+ fetchDynamicModels: () =>
2050
+ fetchOpenAICompatibleModels({
2051
+ api: "openai-completions",
2052
+ provider: "moonshot",
2053
+ baseUrl,
2054
+ apiKey,
2055
+ mapModel: (entry, defaults) => {
2056
+ const reference = references.get(defaults.id);
2057
+ const model = mapWithBundledReference(entry, defaults, reference);
2058
+ const id = model.id.toLowerCase();
2059
+ // Moonshot's K2.x family (K2.5, K2.6, kimi-k2-thinking, …) is reasoning-capable
2060
+ // and vision-capable on the native API. Without these flags the openai-completions
2061
+ // path skips the z.ai-format `thinking` block, and Moonshot K2.6 stalls on first
2062
+ // turn because its endpoint expects an explicit `thinking: {type}` (#2113). Match
2063
+ // the bundled K2.5 metadata for every K2.x id we discover.
2064
+ const isKimiK2Reasoning = id.includes("thinking") || /(^|\/)kimi-k2(?:\.\d+)?(?:[-:]|$)/.test(id);
2065
+ const isVision =
2066
+ id.includes("vision") || id.includes("vl") || /(^|\/)kimi-k2(?:\.\d+)?(?:[-:]|$)/.test(id);
2067
+ return {
2068
+ ...model,
2069
+ reasoning: isKimiK2Reasoning || model.reasoning,
2070
+ input: isVision ? ["text", "image"] : model.input,
2071
+ thinking:
2072
+ model.thinking ??
2073
+ (isKimiK2Reasoning
2074
+ ? { mode: "effort", efforts: [Effort.Minimal, Effort.Low, Effort.Medium, Effort.High] }
2075
+ : undefined),
2076
+ };
2077
+ },
2078
+ fetch: config?.fetch,
2079
+ }),
2080
+ }),
2081
+ };
2082
+ }
2083
+
2084
+ // ---------------------------------------------------------------------------
2085
+ // 17. Qwen Portal
2086
+ // ---------------------------------------------------------------------------
2087
+
2088
+ export interface QwenPortalModelManagerConfig {
2089
+ apiKey?: string;
2090
+ baseUrl?: string;
2091
+ fetch?: FetchImpl;
2092
+ }
2093
+
2094
+ export function qwenPortalModelManagerOptions(
2095
+ config?: QwenPortalModelManagerConfig,
2096
+ ): ModelManagerOptions<"openai-completions"> {
2097
+ return createSimpleOpenAICompletionsOptions("qwen-portal", "https://portal.qwen.ai/v1", config);
2098
+ }
2099
+
2100
+ // ---------------------------------------------------------------------------
2101
+ // 18. Qianfan
2102
+ // ---------------------------------------------------------------------------
2103
+
2104
+ export interface QianfanModelManagerConfig {
2105
+ apiKey?: string;
2106
+ baseUrl?: string;
2107
+ fetch?: FetchImpl;
2108
+ }
2109
+
2110
+ export function qianfanModelManagerOptions(
2111
+ config?: QianfanModelManagerConfig,
2112
+ ): ModelManagerOptions<"openai-completions"> {
2113
+ return createSimpleOpenAICompletionsOptions("qianfan", "https://qianfan.baidubce.com/v2", config);
2114
+ }
2115
+
2116
+ // ---------------------------------------------------------------------------
2117
+ // 19. Cloudflare AI Gateway
2118
+ // ---------------------------------------------------------------------------
2119
+
2120
+ export interface CloudflareAiGatewayModelManagerConfig {
2121
+ apiKey?: string;
2122
+ baseUrl?: string;
2123
+ fetch?: FetchImpl;
2124
+ }
2125
+
2126
+ export function cloudflareAiGatewayModelManagerOptions(
2127
+ config?: CloudflareAiGatewayModelManagerConfig,
2128
+ ): ModelManagerOptions<"anthropic-messages"> {
2129
+ return createSimpleAnthropicProviderOptions(
2130
+ "cloudflare-ai-gateway",
2131
+ "https://gateway.ai.cloudflare.com/v1/<account>/<gateway>/anthropic",
2132
+ config,
2133
+ );
2134
+ }
2135
+
2136
+ // ---------------------------------------------------------------------------
2137
+ // 20. Xiaomi
2138
+ // ---------------------------------------------------------------------------
2139
+
2140
+ /** Region codes for Xiaomi Token Plan clusters exposed as separate login providers. */
2141
+ export type XiaomiTokenPlanRegion = "sgp" | "ams" | "cn";
2142
+
2143
+ /** Configures Xiaomi standard or regional Token Plan OpenAI-compatible model discovery. */
2144
+ export interface XiaomiModelManagerConfig {
2145
+ apiKey?: string;
2146
+ baseUrl?: string;
2147
+ fetch?: FetchImpl;
2148
+ providerId?: Provider;
2149
+ tokenPlanRegion?: XiaomiTokenPlanRegion;
2150
+ }
2151
+
2152
+ const XIAOMI_TOKEN_PLAN_BASE_URLS: Record<XiaomiTokenPlanRegion, string> = {
2153
+ sgp: "https://token-plan-sgp.xiaomimimo.com/v1",
2154
+ ams: "https://token-plan-ams.xiaomimimo.com/v1",
2155
+ cn: "https://token-plan-cn.xiaomimimo.com/v1",
2156
+ };
2157
+
2158
+ const XIAOMI_TOKEN_PLAN_FALLBACK_BASE_URLS = [
2159
+ XIAOMI_TOKEN_PLAN_BASE_URLS.sgp,
2160
+ XIAOMI_TOKEN_PLAN_BASE_URLS.ams,
2161
+ XIAOMI_TOKEN_PLAN_BASE_URLS.cn,
2162
+ ];
2163
+
2164
+ /** Builds a Xiaomi model manager, preserving Token Plan region provider ids during discovery. */
2165
+ export function xiaomiModelManagerOptions(
2166
+ config?: XiaomiModelManagerConfig,
2167
+ ): ModelManagerOptions<"openai-completions"> {
2168
+ const apiKey = config?.apiKey;
2169
+ const providerId = config?.providerId ?? "xiaomi";
2170
+ const tokenPlanBaseUrls = config?.tokenPlanRegion
2171
+ ? [XIAOMI_TOKEN_PLAN_BASE_URLS[config.tokenPlanRegion]]
2172
+ : XIAOMI_TOKEN_PLAN_FALLBACK_BASE_URLS;
2173
+ const XIAOMI_STANDARD_BASE_URL = "https://api.xiaomimimo.com/v1";
2174
+ const isTokenPlanProvider = config?.tokenPlanRegion !== undefined || providerId.startsWith("xiaomi-token-plan-");
2175
+ const isTokenPlanKey = isTokenPlanProvider || apiKey?.startsWith("tp-");
2176
+ // Token-plan keys always use a TP cluster; config?.baseUrl (from catalog)
2177
+ // would incorrectly pin to the standard endpoint (api.xiaomimimo.com).
2178
+ const baseUrl = isTokenPlanKey ? tokenPlanBaseUrls[0] : (config?.baseUrl ?? XIAOMI_STANDARD_BASE_URL);
2179
+ const references = createBundledReferenceMap<"openai-completions">("xiaomi");
2180
+ const fetchModels = (url: string) =>
2181
+ fetchOpenAICompatibleModels({
2182
+ api: "openai-completions",
2183
+ provider: providerId,
2184
+ baseUrl: url,
2185
+ apiKey,
2186
+ filterModel: (_entry, model) => !model.id.includes("-tts"),
2187
+ mapModel: (entry, defaults) => {
2188
+ const reference = references.get(defaults.id);
2189
+ const model = mapWithBundledReference(entry, defaults, reference);
2190
+ return {
2191
+ ...model,
2192
+ api: "openai-completions",
2193
+ provider: providerId,
2194
+ baseUrl: defaults.baseUrl,
2195
+ name: toModelName(entry.display_name, model.name),
2196
+ };
2197
+ },
2198
+ fetch: config?.fetch,
2199
+ });
2200
+ return {
2201
+ providerId,
2202
+ ...(apiKey && {
2203
+ fetchDynamicModels: async () => {
2204
+ if (!isTokenPlanKey) {
2205
+ return fetchModels(baseUrl);
2206
+ }
2207
+ for (const url of tokenPlanBaseUrls) {
2208
+ const result = await fetchModels(url);
2209
+ if (result) return result;
2210
+ }
2211
+ return null;
2212
+ },
2213
+ }),
2214
+ };
2215
+ }
2216
+ // ---------------------------------------------------------------------------
2217
+ // 21. LiteLLM
2218
+ // ---------------------------------------------------------------------------
2219
+
2220
+ export interface LiteLLMModelManagerConfig {
2221
+ apiKey?: string;
2222
+ baseUrl?: string;
2223
+ fetch?: FetchImpl;
2224
+ }
2225
+
2226
+ export function litellmModelManagerOptions(
2227
+ config?: LiteLLMModelManagerConfig,
2228
+ ): ModelManagerOptions<"openai-completions"> {
2229
+ const apiKey = config?.apiKey;
2230
+ const baseUrl = config?.baseUrl ?? "http://localhost:4000/v1";
2231
+ return {
2232
+ providerId: "litellm",
2233
+ // litellm is a local-only proxy whose /v1/models returns bare ids with no
2234
+ // metadata, and it is never bundled in models.json (that would leak the
2235
+ // machine's localhost catalog). It proxies known upstream models, so we
2236
+ // enrich discovered ids against models.dev — the same reference source the
2237
+ // gateway providers (fireworks et al.) use — instead of a bundled map.
2238
+ fetchDynamicModels: async () => {
2239
+ const modelsDevReferences = await loadModelsDevReferences<"openai-completions">(config?.fetch);
2240
+ return fetchOpenAICompatibleModels({
2241
+ api: "openai-completions",
2242
+ provider: "litellm",
2243
+ baseUrl,
2244
+ apiKey,
2245
+ mapModel: (entry, defaults) =>
2246
+ mapWithBundledReference(entry, defaults, modelsDevReferences.get(defaults.id)),
2247
+ fetch: config?.fetch,
2248
+ });
2249
+ },
2250
+ };
2251
+ }
2252
+
2253
+ // ---------------------------------------------------------------------------
2254
+ // 22. vLLM
2255
+ // ---------------------------------------------------------------------------
2256
+
2257
+ export interface VllmModelManagerConfig {
2258
+ apiKey?: string;
2259
+ baseUrl?: string;
2260
+ fetch?: FetchImpl;
2261
+ }
2262
+
2263
+ export function vllmModelManagerOptions(config?: VllmModelManagerConfig): ModelManagerOptions<"openai-completions"> {
2264
+ const apiKey = config?.apiKey;
2265
+ const baseUrl = config?.baseUrl ?? "http://127.0.0.1:8000/v1";
2266
+ const references = createBundledReferenceMap<"openai-completions">("vllm" as Parameters<typeof getBundledModels>[0]);
2267
+ return {
2268
+ providerId: "vllm",
2269
+ fetchDynamicModels: () =>
2270
+ fetchOpenAICompatibleModels({
2271
+ api: "openai-completions",
2272
+ provider: "vllm",
2273
+ baseUrl,
2274
+ apiKey,
2275
+ mapModel: (entry, defaults) => {
2276
+ const model = mapWithBundledReference(entry, defaults, references.get(defaults.id));
2277
+ return {
2278
+ ...model,
2279
+ contextWindow: toPositiveNumber(entry.max_model_len, model.contextWindow),
2280
+ };
2281
+ },
2282
+ fetch: config?.fetch,
2283
+ }),
2284
+ };
2285
+ }
2286
+
2287
+ // ---------------------------------------------------------------------------
2288
+ // 23. NanoGPT
2289
+ // ---------------------------------------------------------------------------
2290
+
2291
+ export interface NanoGptModelManagerConfig {
2292
+ apiKey?: string;
2293
+ baseUrl?: string;
2294
+ fetch?: FetchImpl;
2295
+ }
2296
+
2297
+ export function nanoGptModelManagerOptions(
2298
+ config?: NanoGptModelManagerConfig,
2299
+ ): ModelManagerOptions<"openai-completions"> {
2300
+ const apiKey = config?.apiKey;
2301
+ const baseUrl = config?.baseUrl ?? "https://nano-gpt.com/api/v1";
2302
+ const resolveReference = createReferenceResolver(
2303
+ createBundledReferenceMap<"openai-completions">("nanogpt" as Parameters<typeof getBundledModels>[0]),
2304
+ );
2305
+ return {
2306
+ providerId: "nanogpt",
2307
+ ...(apiKey && {
2308
+ fetchDynamicModels: async () => {
2309
+ // Track base IDs that have :thinking variants so we can mark them reasoning-capable.
2310
+ const thinkingBaseIds = new Set<string>();
2311
+ const models = await fetchOpenAICompatibleModels({
2312
+ api: "openai-completions",
2313
+ provider: "nanogpt",
2314
+ baseUrl,
2315
+ apiKey,
2316
+ mapModel: (entry, defaults) => {
2317
+ const reference = resolveReference(defaults.id);
2318
+ const mapped = mapWithBundledReference(entry, defaults, reference);
2319
+ return { ...mapped, api: "openai-completions", provider: "nanogpt" };
2320
+ },
2321
+ filterModel: (_entry, model) => {
2322
+ const match = NANO_GPT_THINKING_SUFFIX_RE.exec(model.id);
2323
+ if (match) {
2324
+ thinkingBaseIds.add(model.id.slice(0, match.index));
2325
+ return false;
2326
+ }
2327
+ return isLikelyNanoGptTextModelId(model.id);
2328
+ },
2329
+ fetch: config?.fetch,
2330
+ });
2331
+ if (!models) return null;
2332
+ // Mark base models as reasoning-capable when a :thinking variant existed.
2333
+ for (const model of models) {
2334
+ if (!model.reasoning && thinkingBaseIds.has(model.id)) {
2335
+ (model as { reasoning: boolean }).reasoning = true;
2336
+ }
2337
+ }
2338
+ return models;
2339
+ },
2340
+ }),
2341
+ };
2342
+ }
2343
+
2344
+ // ---------------------------------------------------------------------------
2345
+ // 24. GitHub Copilot
2346
+ // ---------------------------------------------------------------------------
2347
+
2348
+ export interface GithubCopilotModelManagerConfig {
2349
+ apiKey?: string;
2350
+ baseUrl?: string;
2351
+ fetch?: FetchImpl;
2352
+ }
2353
+
2354
+ const COPILOT_ANTHROPIC_MODEL_PATTERN = /^claude-(haiku|sonnet|opus)-4([.-]|$)/;
2355
+ const isCopilotResponsesModelId = (modelId: string): boolean =>
2356
+ modelId.startsWith("gpt-5") || modelId.startsWith("oswe");
2357
+
2358
+ function inferCopilotApi(modelId: string): Api {
2359
+ if (COPILOT_ANTHROPIC_MODEL_PATTERN.test(modelId)) {
2360
+ return "anthropic-messages";
2361
+ }
2362
+ if (isCopilotResponsesModelId(modelId)) {
2363
+ return "openai-responses";
2364
+ }
2365
+ return "openai-completions";
2366
+ }
2367
+
2368
+ function extractCopilotLimits(entry: OpenAICompatibleModelRecord): {
2369
+ maxPromptTokens?: number;
2370
+ maxContextWindowTokens?: number;
2371
+ maxOutputTokens?: number;
2372
+ maxNonStreamingOutputTokens?: number;
2373
+ } {
2374
+ if (!isRecord(entry.capabilities)) {
2375
+ return {};
2376
+ }
2377
+ const limitsValue = entry.capabilities.limits;
2378
+ if (!isRecord(limitsValue)) {
2379
+ return {};
2380
+ }
2381
+ return {
2382
+ maxPromptTokens: toNumber(limitsValue.max_prompt_tokens),
2383
+ maxContextWindowTokens: toNumber(limitsValue.max_context_window_tokens),
2384
+ maxOutputTokens: toNumber(limitsValue.max_output_tokens),
2385
+ maxNonStreamingOutputTokens: toNumber(limitsValue.max_non_streaming_output_tokens),
2386
+ };
2387
+ }
2388
+
2389
+ export function githubCopilotModelManagerOptions(config?: GithubCopilotModelManagerConfig): ModelManagerOptions<Api> {
2390
+ const rawApiKey = config?.apiKey;
2391
+ const configuredBaseUrl = config?.baseUrl ?? "https://api.githubcopilot.com";
2392
+ const parsedApiKey = rawApiKey ? parseGitHubCopilotApiKey(rawApiKey) : undefined;
2393
+ const apiKey = parsedApiKey?.accessToken;
2394
+ const baseUrl =
2395
+ parsedApiKey?.enterpriseUrl && configuredBaseUrl.includes("githubcopilot.com")
2396
+ ? getGitHubCopilotBaseUrl(parsedApiKey.enterpriseUrl)
2397
+ : configuredBaseUrl;
2398
+ const providerRefs = createBundledReferenceMap<Api>("github-copilot");
2399
+ const resolveReference = createReferenceResolver(providerRefs);
2400
+ return {
2401
+ providerId: "github-copilot",
2402
+ ...(apiKey && {
2403
+ fetchDynamicModels: () =>
2404
+ fetchOpenAICompatibleModels<Api>({
2405
+ api: "openai-completions",
2406
+ provider: "github-copilot",
2407
+ baseUrl,
2408
+ apiKey,
2409
+ headers: OPENCODE_HEADERS,
2410
+ mapModel: (
2411
+ entry: OpenAICompatibleModelRecord,
2412
+ defaults: ModelSpec<Api>,
2413
+ _context: OpenAICompatibleModelMapperContext<Api>,
2414
+ ): ModelSpec<Api> => {
2415
+ const reference = resolveReference(defaults.id);
2416
+ const copilotLimits = extractCopilotLimits(entry);
2417
+ // Copilot exposes token limits under capabilities.limits.*.
2418
+ // max_context_window_tokens is the model's total usable window;
2419
+ // max_prompt_tokens is Copilot's prompt/summarization budget and
2420
+ // must only be a fallback when total-window fields are absent.
2421
+ const contextWindow = toPositiveNumber(
2422
+ copilotLimits.maxContextWindowTokens,
2423
+ toPositiveNumber(
2424
+ entry.context_length,
2425
+ toPositiveNumber(
2426
+ copilotLimits.maxPromptTokens,
2427
+ reference?.contextWindow ?? defaults.contextWindow,
2428
+ ),
2429
+ ),
2430
+ );
2431
+ const maxTokens = toPositiveNumber(
2432
+ copilotLimits.maxOutputTokens,
2433
+ toPositiveNumber(
2434
+ entry.max_completion_tokens,
2435
+ toPositiveNumber(
2436
+ copilotLimits.maxNonStreamingOutputTokens,
2437
+ reference?.maxTokens ?? defaults.maxTokens,
2438
+ ),
2439
+ ),
2440
+ );
2441
+ const name =
2442
+ typeof entry.name === "string" && entry.name.trim().length > 0
2443
+ ? entry.name
2444
+ : (reference?.name ?? defaults.name);
2445
+ const api = inferCopilotApi(defaults.id);
2446
+ if (reference) {
2447
+ return {
2448
+ ...reference,
2449
+ api,
2450
+ provider: "github-copilot",
2451
+ baseUrl,
2452
+ name,
2453
+ contextWindow,
2454
+ maxTokens,
2455
+ headers: { ...OPENCODE_HEADERS, ...(providerRefs.get(defaults.id)?.headers ?? {}) },
2456
+ ...(api === "openai-completions"
2457
+ ? {
2458
+ compat: {
2459
+ supportsStore: false,
2460
+ supportsDeveloperRole: false,
2461
+ supportsReasoningEffort: false,
2462
+ },
2463
+ }
2464
+ : {}),
2465
+ };
2466
+ }
2467
+ return {
2468
+ ...defaults,
2469
+ api,
2470
+ baseUrl,
2471
+ name,
2472
+ contextWindow,
2473
+ maxTokens,
2474
+ headers: { ...OPENCODE_HEADERS },
2475
+ ...(api === "openai-completions"
2476
+ ? {
2477
+ compat: {
2478
+ supportsStore: false,
2479
+ supportsDeveloperRole: false,
2480
+ supportsReasoningEffort: false,
2481
+ },
2482
+ }
2483
+ : {}),
2484
+ };
2485
+ },
2486
+ fetch: config?.fetch,
2487
+ }),
2488
+ }),
2489
+ };
2490
+ }
2491
+
2492
+ // ---------------------------------------------------------------------------
2493
+ // 24. Anthropic
2494
+ // ---------------------------------------------------------------------------
2495
+
2496
+ export interface AnthropicModelManagerConfig {
2497
+ apiKey?: string;
2498
+ baseUrl?: string;
2499
+ fetch?: FetchImpl;
2500
+ }
2501
+
2502
+ export function anthropicModelManagerOptions(
2503
+ config?: AnthropicModelManagerConfig,
2504
+ ): ModelManagerOptions<"anthropic-messages"> {
2505
+ const apiKey = config?.apiKey;
2506
+ const baseUrl = config?.baseUrl ?? ANTHROPIC_BASE_URL;
2507
+ return {
2508
+ providerId: "anthropic",
2509
+ modelsDev: {
2510
+ fetch: () => fetchModelsDevPayload(config?.fetch),
2511
+ map: payload => mapAnthropicModelsDev(payload, baseUrl),
2512
+ },
2513
+ ...(apiKey && {
2514
+ fetchDynamicModels: async () => {
2515
+ const modelsDevModels = await fetchModelsDevPayload(config?.fetch)
2516
+ .then(payload => mapAnthropicModelsDev(payload, baseUrl))
2517
+ .catch(() => []);
2518
+ const references = buildAnthropicReferenceMap(modelsDevModels);
2519
+ return (
2520
+ fetchOpenAICompatibleModels({
2521
+ api: "anthropic-messages",
2522
+ provider: "anthropic",
2523
+ baseUrl,
2524
+ headers: buildAnthropicDiscoveryHeaders(apiKey),
2525
+ mapModel: (
2526
+ entry: OpenAICompatibleModelRecord,
2527
+ defaults: ModelSpec<"anthropic-messages">,
2528
+ _context: OpenAICompatibleModelMapperContext<"anthropic-messages">,
2529
+ ): ModelSpec<"anthropic-messages"> => {
2530
+ const discoveredName = typeof entry.display_name === "string" ? entry.display_name : defaults.name;
2531
+ const reference = references.get(defaults.id);
2532
+ if (!reference) {
2533
+ return {
2534
+ ...defaults,
2535
+ name: discoveredName,
2536
+ };
2537
+ }
2538
+ return {
2539
+ ...reference,
2540
+ id: defaults.id,
2541
+ name: discoveredName,
2542
+ api: "anthropic-messages",
2543
+ provider: "anthropic",
2544
+ baseUrl,
2545
+ };
2546
+ },
2547
+ fetch: config?.fetch,
2548
+ }) ?? null
2549
+ );
2550
+ },
2551
+ }),
2552
+ };
2553
+ }
2554
+
2555
+ // ---------------------------------------------------------------------------
2556
+ // Models.dev provider descriptors for generate-models.ts
2557
+ // ---------------------------------------------------------------------------
2558
+
2559
+ export { UNK_CONTEXT_WINDOW, UNK_MAX_TOKENS } from "./discovery-constants";
2560
+
2561
+ /** Describes how to map models.dev API data for a single provider. */
2562
+ export interface ModelsDevProviderDescriptor {
2563
+ /** Key in the models.dev API response JSON (e.g., "anthropic", "amazon-bedrock") */
2564
+ modelsDevKey: string;
2565
+ /** Provider ID in our system */
2566
+ providerId: string;
2567
+ /** Default API type for this provider's models */
2568
+ api: Api;
2569
+ /** Default base URL */
2570
+ baseUrl: string;
2571
+ /** Default context window fallback (default: UNKNNOWN_CONTEXT_WINDOW) */
2572
+ defaultContextWindow?: number;
2573
+ /** Default max tokens fallback (default: UNKNNOWN_MAX_TOKENS) */
2574
+ defaultMaxTokens?: number;
2575
+ /** Optional compat overrides applied to every model from this provider */
2576
+ compat?: ModelSpec<Api>["compat"];
2577
+ /** Optional static headers applied to every model */
2578
+ headers?: Record<string, string>;
2579
+ /**
2580
+ * Optional filter: return false to skip a model.
2581
+ * Called with (modelId, rawModel). Default: skip if tool_call !== true.
2582
+ */
2583
+ filterModel?: (modelId: string, model: ModelsDevModel) => boolean;
2584
+ /**
2585
+ * Optional transform: modify the mapped model before it's added.
2586
+ * Can return null to skip the model, or an array to emit multiple models.
2587
+ */
2588
+ transformModel?: (
2589
+ model: ModelSpec<Api>,
2590
+ modelId: string,
2591
+ raw: ModelsDevModel,
2592
+ ) => ModelSpec<Api> | ModelSpec<Api>[] | null;
2593
+ /**
2594
+ * Optional: override the API type per-model.
2595
+ * Called with (modelId, raw). Return the API type to use.
2596
+ * If not provided, uses the `api` field.
2597
+ */
2598
+ resolveApi?: (modelId: string, raw: ModelsDevModel) => { api: Api; baseUrl: string } | null;
2599
+ }
2600
+
2601
+ /** Generic mapper that converts models.dev data using provider descriptors. */
2602
+ export function mapModelsDevToModels(
2603
+ data: Record<string, unknown>,
2604
+ descriptors: readonly ModelsDevProviderDescriptor[],
2605
+ ): ModelSpec<Api>[] {
2606
+ const models: ModelSpec<Api>[] = [];
2607
+ for (const desc of descriptors) {
2608
+ const providerData = (data as Record<string, Record<string, unknown>>)[desc.modelsDevKey];
2609
+ if (!isRecord(providerData) || !isRecord(providerData.models)) continue;
2610
+
2611
+ for (const [modelId, rawModel] of Object.entries(providerData.models)) {
2612
+ if (!isRecord(rawModel)) continue;
2613
+ const m = rawModel as ModelsDevModel;
2614
+
2615
+ // Default filter: tool_call must be true
2616
+ if (desc.filterModel) {
2617
+ if (!desc.filterModel(modelId, m)) continue;
2618
+ } else {
2619
+ if (m.tool_call !== true) continue;
2620
+ }
2621
+
2622
+ // Resolve API and baseUrl (may be per-model for providers like OpenCode)
2623
+ const resolved = desc.resolveApi?.(modelId, m) ?? { api: desc.api, baseUrl: desc.baseUrl };
2624
+ if (!resolved) continue;
2625
+
2626
+ const mapped: ModelSpec<Api> = {
2627
+ id: modelId,
2628
+ name: toModelName(m.name, modelId),
2629
+ api: resolved.api,
2630
+ provider: desc.providerId as ModelSpec<Api>["provider"],
2631
+ baseUrl: resolved.baseUrl,
2632
+ reasoning: m.reasoning === true,
2633
+ input: toInputCapabilities(m.modalities?.input),
2634
+ cost: {
2635
+ input: toNumber(m.cost?.input) ?? 0,
2636
+ output: toNumber(m.cost?.output) ?? 0,
2637
+ cacheRead: toNumber(m.cost?.cache_read) ?? 0,
2638
+ cacheWrite: toNumber(m.cost?.cache_write) ?? 0,
2639
+ },
2640
+ contextWindow: toPositiveNumber(m.limit?.context, desc.defaultContextWindow ?? UNK_CONTEXT_WINDOW),
2641
+ maxTokens: toPositiveNumber(m.limit?.output, desc.defaultMaxTokens ?? UNK_MAX_TOKENS),
2642
+ ...(desc.compat && { compat: desc.compat }),
2643
+ ...(desc.headers && { headers: { ...desc.headers } }),
2644
+ };
2645
+
2646
+ // Apply per-model transform
2647
+ if (desc.transformModel) {
2648
+ const result = desc.transformModel(mapped, modelId, m);
2649
+ if (result === null) continue;
2650
+ if (Array.isArray(result)) {
2651
+ models.push(...result);
2652
+ } else {
2653
+ models.push(result);
2654
+ }
2655
+ } else {
2656
+ models.push(mapped);
2657
+ }
2658
+ }
2659
+ }
2660
+ return models;
2661
+ }
2662
+
2663
+ // Bedrock cross-region prefix helpers
2664
+ const BEDROCK_GLOBAL_PREFIXES = [
2665
+ "anthropic.claude-fable-5",
2666
+ "anthropic.claude-mythos-5",
2667
+ "anthropic.claude-haiku-4-5",
2668
+ "anthropic.claude-sonnet-4",
2669
+ "anthropic.claude-opus-4-5",
2670
+ "amazon.nova-2-lite",
2671
+ "cohere.embed-v4",
2672
+ "twelvelabs.pegasus-1-2",
2673
+ ];
2674
+
2675
+ const BEDROCK_US_PREFIXES = [
2676
+ "amazon.nova-lite",
2677
+ "amazon.nova-micro",
2678
+ "amazon.nova-premier",
2679
+ "amazon.nova-pro",
2680
+ "anthropic.claude-3-7-sonnet",
2681
+ "anthropic.claude-opus-4-1",
2682
+ "anthropic.claude-opus-4-20250514",
2683
+ "deepseek.r1",
2684
+ "meta.llama3-2",
2685
+ "meta.llama3-3",
2686
+ "meta.llama4",
2687
+ ];
2688
+
2689
+ function bedrockCrossRegionId(id: string): string {
2690
+ if (BEDROCK_GLOBAL_PREFIXES.some(p => id.startsWith(p))) return `global.${id}`;
2691
+ if (BEDROCK_US_PREFIXES.some(p => id.startsWith(p))) return `us.${id}`;
2692
+ return id;
2693
+ }
2694
+
2695
+ interface ApiResolutionRule {
2696
+ matches: (modelId: string, raw: ModelsDevModel) => boolean;
2697
+ resolved: { api: Api; baseUrl: string };
2698
+ }
2699
+
2700
+ function resolveApiByRules(
2701
+ modelId: string,
2702
+ raw: ModelsDevModel,
2703
+ rules: readonly ApiResolutionRule[],
2704
+ fallback: { api: Api; baseUrl: string },
2705
+ ): { api: Api; baseUrl: string } {
2706
+ for (const rule of rules) {
2707
+ if (rule.matches(modelId, raw)) return rule.resolved;
2708
+ }
2709
+ return fallback;
2710
+ }
2711
+
2712
+ function createOpenCodeApiResolution(
2713
+ basePath: string,
2714
+ idOverrides: Readonly<Record<string, Api>> = {},
2715
+ ): {
2716
+ defaultResolution: { api: Api; baseUrl: string };
2717
+ rules: ApiResolutionRule[];
2718
+ } {
2719
+ const completionsBaseUrl = `${basePath}/v1`;
2720
+ // Per-API base URLs on the OpenCode-style endpoint:
2721
+ // - openai-completions / openai-responses / google-generative-ai → /v1
2722
+ // - anthropic-messages → bare basePath (the Anthropic client appends /v1/messages)
2723
+ const baseUrlForApi = (api: Api): string => (api === "anthropic-messages" ? basePath : completionsBaseUrl);
2724
+ const overrideRules: ApiResolutionRule[] = Object.entries(idOverrides).map(([id, api]) => ({
2725
+ matches: modelId => modelId === id,
2726
+ resolved: { api, baseUrl: baseUrlForApi(api) },
2727
+ }));
2728
+ return {
2729
+ defaultResolution: { api: "openai-completions", baseUrl: completionsBaseUrl },
2730
+ rules: [
2731
+ // Per-id overrides take precedence over npm-based heuristics so we can
2732
+ // correct upstream metadata mismatches (see OPENCODE_GO_API_RESOLUTION).
2733
+ ...overrideRules,
2734
+ {
2735
+ matches: (_modelId, raw) => raw.provider?.npm === "@ai-sdk/openai",
2736
+ resolved: { api: "openai-responses", baseUrl: completionsBaseUrl },
2737
+ },
2738
+ {
2739
+ matches: (_modelId, raw) => raw.provider?.npm === "@ai-sdk/anthropic",
2740
+ resolved: { api: "anthropic-messages", baseUrl: basePath },
2741
+ },
2742
+ {
2743
+ matches: (_modelId, raw) => raw.provider?.npm === "@ai-sdk/google",
2744
+ resolved: { api: "google-generative-ai", baseUrl: completionsBaseUrl },
2745
+ },
2746
+ ],
2747
+ };
2748
+ }
2749
+
2750
+ // OpenCode Zen: models.dev declares minimax-m3-free (and forward-compat
2751
+ // minimax-m3) with `provider.npm = "@ai-sdk/anthropic"`, but the Zen gateway
2752
+ // only serves them at https://opencode.ai/zen/v1/chat/completions (verified
2753
+ // against the live /v1/models response — minimax-m3-free is listed there, and
2754
+ // the gateway has no /v1/messages route for it). Without this override the
2755
+ // resolver POSTs anthropic-shaped requests to /v1/messages and the UI surfaces
2756
+ // raw <invoke>/<|minimax|>/<tool_call> markup (#1617).
2757
+ const OPENCODE_ZEN_API_RESOLUTION = createOpenCodeApiResolution("https://opencode.ai/zen", {
2758
+ "minimax-m3": "openai-completions",
2759
+ "minimax-m3-free": "openai-completions",
2760
+ });
2761
+ // OpenCode Go: models.dev declares minimax-m2.7 / qwen3.5-plus / qwen3.6-plus
2762
+ // (and now also minimax-m3) with `provider.npm = "@ai-sdk/anthropic"`, but
2763
+ // the OpenCode Go gateway only serves them at
2764
+ // `https://opencode.ai/zen/go/v1/chat/completions` (verified against
2765
+ // https://opencode.ai/zen/go/v1/models and the upstream endpoint table at
2766
+ // https://opencode.ai/docs/go/#endpoints — minimax-m2.5 works the same way
2767
+ // and lacks an `npm` field on models.dev so it already falls through to the
2768
+ // openai-completions default). Without this override the resolver would POST
2769
+ // anthropic-style requests to /v1/messages and the gateway would return its
2770
+ // `Page Not Found` HTML (issue #887 for the qwen/m2.7 entries; minimax-m3
2771
+ // and minimax-m3-free added under #1617 for the same root cause).
2772
+ const OPENCODE_GO_API_RESOLUTION = createOpenCodeApiResolution("https://opencode.ai/zen/go", {
2773
+ "minimax-m2.7": "openai-completions",
2774
+ "minimax-m3": "openai-completions",
2775
+ "minimax-m3-free": "openai-completions",
2776
+ "qwen3.5-plus": "openai-completions",
2777
+ "qwen3.6-plus": "openai-completions",
2778
+ });
2779
+
2780
+ const COPILOT_BASE_URL = "https://api.githubcopilot.com";
2781
+
2782
+ const COPILOT_DEFAULT_RESOLUTION = {
2783
+ api: "openai-completions",
2784
+ baseUrl: COPILOT_BASE_URL,
2785
+ } as const satisfies { api: Api; baseUrl: string };
2786
+
2787
+ const COPILOT_API_RESOLUTION_RULES: readonly ApiResolutionRule[] = [
2788
+ {
2789
+ matches: modelId => COPILOT_ANTHROPIC_MODEL_PATTERN.test(modelId),
2790
+ resolved: { api: "anthropic-messages", baseUrl: COPILOT_BASE_URL },
2791
+ },
2792
+ {
2793
+ matches: isCopilotResponsesModelId,
2794
+ resolved: { api: "openai-responses", baseUrl: COPILOT_BASE_URL },
2795
+ },
2796
+ ];
2797
+
2798
+ function simpleModelsDevDescriptor(
2799
+ modelsDevKey: string,
2800
+ providerId: string,
2801
+ api: Api,
2802
+ baseUrl: string,
2803
+ options: Omit<ModelsDevProviderDescriptor, "modelsDevKey" | "providerId" | "api" | "baseUrl"> = {},
2804
+ ): ModelsDevProviderDescriptor {
2805
+ return {
2806
+ modelsDevKey,
2807
+ providerId,
2808
+ api,
2809
+ baseUrl,
2810
+ ...options,
2811
+ };
2812
+ }
2813
+
2814
+ function openAiCompletionsDescriptor(
2815
+ modelsDevKey: string,
2816
+ providerId: string,
2817
+ baseUrl: string,
2818
+ options: Omit<ModelsDevProviderDescriptor, "modelsDevKey" | "providerId" | "api" | "baseUrl"> = {},
2819
+ ): ModelsDevProviderDescriptor {
2820
+ return simpleModelsDevDescriptor(modelsDevKey, providerId, "openai-completions", baseUrl, options);
2821
+ }
2822
+
2823
+ function anthropicMessagesDescriptor(
2824
+ modelsDevKey: string,
2825
+ providerId: string,
2826
+ baseUrl: string,
2827
+ options: Omit<ModelsDevProviderDescriptor, "modelsDevKey" | "providerId" | "api" | "baseUrl"> = {},
2828
+ ): ModelsDevProviderDescriptor {
2829
+ return simpleModelsDevDescriptor(modelsDevKey, providerId, "anthropic-messages", baseUrl, options);
2830
+ }
2831
+
2832
+ const GOOGLE_VERTEX_BASE_URL = "https://{location}-aiplatform.googleapis.com";
2833
+ const GOOGLE_VERTEX_OPENAI_BASE_URL =
2834
+ "https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/openapi";
2835
+ const GOOGLE_VERTEX_ANTHROPIC_BASE_URL =
2836
+ "https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/publishers/anthropic/models/{model}:streamRawPredict";
2837
+
2838
+ function resolveGoogleVertexApi(modelId: string, raw: ModelsDevModel): { api: Api; baseUrl: string } {
2839
+ if (raw.provider?.npm === "@ai-sdk/google-vertex/anthropic") {
2840
+ return {
2841
+ api: "anthropic-messages",
2842
+ baseUrl: GOOGLE_VERTEX_ANTHROPIC_BASE_URL.replace("{model}", modelId),
2843
+ };
2844
+ }
2845
+ if (modelId.includes("/") || raw.provider?.npm === "@ai-sdk/openai-compatible") {
2846
+ return { api: "openai-completions", baseUrl: GOOGLE_VERTEX_OPENAI_BASE_URL };
2847
+ }
2848
+ return { api: "google-vertex", baseUrl: GOOGLE_VERTEX_BASE_URL };
2849
+ }
2850
+
2851
+ const MODELS_DEV_PROVIDER_DESCRIPTORS_BEDROCK: readonly ModelsDevProviderDescriptor[] = [
2852
+ // --- Amazon Bedrock ---
2853
+ {
2854
+ modelsDevKey: "amazon-bedrock",
2855
+ providerId: "amazon-bedrock",
2856
+ api: "bedrock-converse-stream",
2857
+ baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
2858
+ filterModel: (id, m) => {
2859
+ if (m.tool_call !== true) return false;
2860
+ if (id.startsWith("ai21.jamba")) return false;
2861
+ if (id.startsWith("amazon.titan-text-express") || id.startsWith("mistral.mistral-7b-instruct-v0"))
2862
+ return false;
2863
+ return true;
2864
+ },
2865
+ transformModel: (model, modelId, m) => {
2866
+ const crossRegionId = bedrockCrossRegionId(modelId);
2867
+ const bedrockModel: ModelSpec<Api> = {
2868
+ ...model,
2869
+ id: crossRegionId,
2870
+ name: toModelName(m.name, crossRegionId),
2871
+ };
2872
+ // Also emit EU variants for Claude models
2873
+ if (modelId.startsWith("anthropic.claude-")) {
2874
+ return [
2875
+ bedrockModel,
2876
+ {
2877
+ ...bedrockModel,
2878
+ id: `eu.${modelId}`,
2879
+ name: `${toModelName(m.name, modelId)} (EU)`,
2880
+ },
2881
+ ];
2882
+ }
2883
+ return bedrockModel;
2884
+ },
2885
+ },
2886
+ ];
2887
+
2888
+ const MODELS_DEV_PROVIDER_DESCRIPTORS_CORE: readonly ModelsDevProviderDescriptor[] = [
2889
+ // --- Anthropic ---
2890
+ anthropicMessagesDescriptor("anthropic", "anthropic", "https://api.anthropic.com", {
2891
+ filterModel: (id, m) => {
2892
+ if (m.tool_call !== true) return false;
2893
+ if (
2894
+ id.startsWith("claude-3-5-haiku") ||
2895
+ id.startsWith("claude-3-7-sonnet") ||
2896
+ id === "claude-3-opus-20240229" ||
2897
+ id === "claude-3-sonnet-20240229"
2898
+ )
2899
+ return false;
2900
+ return true;
2901
+ },
2902
+ }),
2903
+ // --- Google ---
2904
+ simpleModelsDevDescriptor(
2905
+ "google",
2906
+ "google",
2907
+ "google-generative-ai",
2908
+ "https://generativelanguage.googleapis.com/v1beta",
2909
+ ),
2910
+ // --- OpenAI ---
2911
+ simpleModelsDevDescriptor("openai", "openai", "openai-responses", "https://api.openai.com/v1"),
2912
+ // --- Groq ---
2913
+ openAiCompletionsDescriptor("groq", "groq", "https://api.groq.com/openai/v1"),
2914
+ // --- Cerebras ---
2915
+ openAiCompletionsDescriptor("cerebras", "cerebras", "https://api.cerebras.ai/v1"),
2916
+ // --- Together ---
2917
+ openAiCompletionsDescriptor("together", "together", "https://api.together.xyz/v1"),
2918
+ // --- NVIDIA ---
2919
+ openAiCompletionsDescriptor("nvidia", "nvidia", "https://integrate.api.nvidia.com/v1", {
2920
+ defaultContextWindow: 131072,
2921
+ }),
2922
+ // --- xAI ---
2923
+ openAiCompletionsDescriptor("xai", "xai", "https://api.x.ai/v1"),
2924
+ // --- DeepSeek ---
2925
+ openAiCompletionsDescriptor("deepseek", "deepseek", "https://api.deepseek.com", {
2926
+ // Only ship the v4 family as built-ins; older deepseek-chat / deepseek-reasoner
2927
+ // ids are kept off the catalog until the issue thread asks for them.
2928
+ filterModel: (id, m) => m.tool_call === true && id.startsWith("deepseek-v4"),
2929
+ compat: {
2930
+ // DeepSeek V4 only accepts `high`/`max`; map lower OMP levels upward so
2931
+ // subagent "minimal" turns stay in documented thinking mode instead of
2932
+ // sending unsupported effort strings.
2933
+ supportsDeveloperRole: false,
2934
+ supportsReasoningEffort: true,
2935
+ reasoningEffortMap: { minimal: "high", low: "high", medium: "high", high: "high", xhigh: "max" },
2936
+ maxTokensField: "max_tokens",
2937
+ // DeepSeek V4 thinking mode rejects the `tool_choice` control parameter.
2938
+ // Tool calls still work without it; the API defaults to auto when tools exist.
2939
+ supportsToolChoice: false,
2940
+ // DeepSeek V4's OpenAI format docs enable thinking with both the toggle and
2941
+ // reasoning_effort. Keep the toggle explicit for built-in models.
2942
+ extraBody: { thinking: { type: "enabled" } },
2943
+ // DeepSeek emits chain-of-thought via `reasoning_content` and requires it
2944
+ // to round-trip on assistant tool-call messages so the model can resume
2945
+ // from prior thinking (interleaved.field=reasoning_content on models.dev,
2946
+ // matches the kimi/openrouter handling already in detectCompat).
2947
+ reasoningContentField: "reasoning_content",
2948
+ requiresReasoningContentForToolCalls: true,
2949
+ requiresAssistantContentForToolCalls: true,
2950
+ },
2951
+ }),
2952
+ ];
2953
+
2954
+ const MODELS_DEV_PROVIDER_DESCRIPTORS_CODING_PLANS: readonly ModelsDevProviderDescriptor[] = [
2955
+ // --- zAI ---
2956
+ anthropicMessagesDescriptor("zai-coding-plan", "zai", "https://api.z.ai/api/anthropic"),
2957
+ // --- Xiaomi ---
2958
+ openAiCompletionsDescriptor("xiaomi", "xiaomi", "https://api.xiaomimimo.com/v1", {
2959
+ defaultContextWindow: 262144,
2960
+ defaultMaxTokens: 8192,
2961
+ compat: {
2962
+ supportsStore: false,
2963
+ thinkingFormat: "zai",
2964
+ reasoningContentField: "reasoning_content",
2965
+ requiresReasoningContentForToolCalls: true,
2966
+ allowsSyntheticReasoningContentForToolCalls: false,
2967
+ },
2968
+ }),
2969
+ // --- MiniMax Coding Plan ---
2970
+ openAiCompletionsDescriptor("minimax-coding-plan", "minimax-code", "https://api.minimax.io/v1", {
2971
+ compat: {
2972
+ supportsStore: false,
2973
+ supportsDeveloperRole: false,
2974
+ supportsReasoningEffort: false,
2975
+ reasoningContentField: "reasoning_content",
2976
+ },
2977
+ }),
2978
+ openAiCompletionsDescriptor("minimax-cn-coding-plan", "minimax-code-cn", "https://api.minimaxi.com/v1", {
2979
+ compat: {
2980
+ supportsStore: false,
2981
+ supportsDeveloperRole: false,
2982
+ supportsReasoningEffort: false,
2983
+ reasoningContentField: "reasoning_content",
2984
+ },
2985
+ }),
2986
+ // --- Alibaba Coding Plan ---
2987
+ openAiCompletionsDescriptor(
2988
+ "alibaba-coding-plan",
2989
+ "alibaba-coding-plan",
2990
+ "https://coding-intl.dashscope.aliyuncs.com/v1",
2991
+ {
2992
+ compat: {
2993
+ supportsDeveloperRole: false,
2994
+ },
2995
+ },
2996
+ ),
2997
+ // --- Zhipu Coding Plan ---
2998
+ openAiCompletionsDescriptor(
2999
+ "zhipu-coding-plan",
3000
+ "zhipu-coding-plan",
3001
+ "https://open.bigmodel.cn/api/coding/paas/v4",
3002
+ {
3003
+ compat: {
3004
+ thinkingFormat: "zai",
3005
+ reasoningContentField: "reasoning_content",
3006
+ supportsDeveloperRole: false,
3007
+ },
3008
+ },
3009
+ ),
3010
+ ];
3011
+
3012
+ const filterActiveToolCallModels = (_id: string, m: ModelsDevModel): boolean => {
3013
+ if (m.tool_call !== true) return false;
3014
+ if (m.status === "deprecated") return false;
3015
+ return true;
3016
+ };
3017
+
3018
+ const MODELS_DEV_PROVIDER_DESCRIPTORS_GOOGLE_VERTEX: readonly ModelsDevProviderDescriptor[] = [
3019
+ simpleModelsDevDescriptor("google-vertex", "google-vertex", "google-vertex", GOOGLE_VERTEX_BASE_URL, {
3020
+ filterModel: filterActiveToolCallModels,
3021
+ resolveApi: resolveGoogleVertexApi,
3022
+ }),
3023
+ ];
3024
+
3025
+ const MODELS_DEV_PROVIDER_DESCRIPTORS_SPECIALIZED: readonly ModelsDevProviderDescriptor[] = [
3026
+ // --- Cloudflare AI Gateway ---
3027
+ anthropicMessagesDescriptor(
3028
+ "cloudflare-ai-gateway",
3029
+ "cloudflare-ai-gateway",
3030
+ "https://gateway.ai.cloudflare.com/v1/<account>/<gateway>/anthropic",
3031
+ ),
3032
+ // --- Mistral ---
3033
+ openAiCompletionsDescriptor("mistral", "mistral", "https://api.mistral.ai/v1"),
3034
+ // --- OpenCode Zen ---
3035
+ openAiCompletionsDescriptor("opencode", "opencode-zen", "https://opencode.ai/zen/v1", {
3036
+ filterModel: filterActiveToolCallModels,
3037
+ resolveApi: (modelId, raw) =>
3038
+ resolveApiByRules(
3039
+ modelId,
3040
+ raw,
3041
+ OPENCODE_ZEN_API_RESOLUTION.rules,
3042
+ OPENCODE_ZEN_API_RESOLUTION.defaultResolution,
3043
+ ),
3044
+ }),
3045
+ // --- OpenCode Go ---
3046
+ openAiCompletionsDescriptor("opencode-go", "opencode-go", "https://opencode.ai/zen/go/v1", {
3047
+ filterModel: filterActiveToolCallModels,
3048
+ resolveApi: (modelId, raw) =>
3049
+ resolveApiByRules(
3050
+ modelId,
3051
+ raw,
3052
+ OPENCODE_GO_API_RESOLUTION.rules,
3053
+ OPENCODE_GO_API_RESOLUTION.defaultResolution,
3054
+ ),
3055
+ }),
3056
+ // --- GitHub Copilot ---
3057
+ openAiCompletionsDescriptor("github-copilot", "github-copilot", COPILOT_BASE_URL, {
3058
+ defaultContextWindow: 128000,
3059
+ defaultMaxTokens: 8192,
3060
+ headers: { ...OPENCODE_HEADERS },
3061
+ filterModel: filterActiveToolCallModels,
3062
+ resolveApi: (modelId, raw) =>
3063
+ resolveApiByRules(modelId, raw, COPILOT_API_RESOLUTION_RULES, COPILOT_DEFAULT_RESOLUTION),
3064
+ transformModel: model => {
3065
+ // compat only applies to openai-completions models
3066
+ if (model.api === "openai-completions") {
3067
+ return {
3068
+ ...model,
3069
+ compat: {
3070
+ supportsStore: false,
3071
+ supportsDeveloperRole: false,
3072
+ supportsReasoningEffort: false,
3073
+ },
3074
+ };
3075
+ }
3076
+ return model;
3077
+ },
3078
+ }),
3079
+ // --- MiniMax (Anthropic) ---
3080
+ anthropicMessagesDescriptor("minimax", "minimax", "https://api.minimax.io/anthropic"),
3081
+ anthropicMessagesDescriptor("minimax-cn", "minimax-cn", "https://api.minimaxi.com/anthropic"),
3082
+ // --- Qwen Portal ---
3083
+ openAiCompletionsDescriptor("qwen-portal", "qwen-portal", "https://portal.qwen.ai/v1", {
3084
+ defaultContextWindow: 128000,
3085
+ defaultMaxTokens: 8192,
3086
+ }),
3087
+
3088
+ // --- ZenMux ---
3089
+ openAiCompletionsDescriptor("zenmux", "zenmux", ZENMUX_OPENAI_BASE_URL, {
3090
+ filterModel: filterActiveToolCallModels,
3091
+ resolveApi: modelId => {
3092
+ if (modelId.startsWith("anthropic/")) {
3093
+ return { api: "anthropic-messages" as const, baseUrl: ZENMUX_ANTHROPIC_BASE_URL };
3094
+ }
3095
+ return { api: "openai-completions" as const, baseUrl: ZENMUX_OPENAI_BASE_URL };
3096
+ },
3097
+ }),
3098
+ ];
3099
+ /** All provider descriptors for models.dev data mapping in generate-models.ts. */
3100
+ export const MODELS_DEV_PROVIDER_DESCRIPTORS: readonly ModelsDevProviderDescriptor[] = [
3101
+ ...MODELS_DEV_PROVIDER_DESCRIPTORS_BEDROCK,
3102
+ ...MODELS_DEV_PROVIDER_DESCRIPTORS_GOOGLE_VERTEX,
3103
+ ...MODELS_DEV_PROVIDER_DESCRIPTORS_CORE,
3104
+ ...MODELS_DEV_PROVIDER_DESCRIPTORS_CODING_PLANS,
3105
+ ...MODELS_DEV_PROVIDER_DESCRIPTORS_SPECIALIZED,
3106
+ ];