Repository navigation
Expand file tree
/
Copy pathmodels.ts
More file actions
267 lines (242 loc) · 8.12 KB
/
Copy pathmodels.ts
File metadata and controls
267 lines (242 loc) · 8.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
import { readFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
import { xdgCache, xdgData } from "xdg-basedir";
const FETCH_TIMEOUT_MS = 10_000;
const CACHE_PATH = join(
xdgCache ?? join(homedir(), ".cache"),
"opencode",
"models.json",
);
const AUTH_PATH = join(
xdgData ?? join(homedir(), ".local", "share"),
"opencode",
"auth.json",
);
const MODELS_DEV_URL = "https://models.dev/api.json";
const DEFAULT_HUB_BASE = "https://hub.coreinfra.ai";
const HUB_URL = `${process.env.COREINFRA_HUB_BASE_URL ?? DEFAULT_HUB_BASE}/hub/api/prices`;
const OPENAI_BASE = `${process.env.COREINFRA_HUB_BASE_URL ?? DEFAULT_HUB_BASE}/openai/api/v1`;
const ANTHROPIC_BASE = `${process.env.COREINFRA_HUB_BASE_URL ?? DEFAULT_HUB_BASE}/anthropic/api/v1`;
const ANTHROPIC_BETA_HEADER =
"interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14";
const DEFAULT_LIMIT = { context: 200000, output: 64000 };
const DEFAULT_CAPS = {
attachment: true,
reasoning: true,
temperature: true,
tool_call: true,
};
const DEFAULT_COST = {
input: 0,
output: 0,
cache_read: 0,
cache_write: 0,
};
type Protocol = "openai" | "anthropic";
// Providers we explicitly know how to route. Models from any provider not
// listed here are skipped. Adding a provider is a one-line change here. The
// `npm` package selects the wire API: `@ai-sdk/openai` targets OpenAI's
// Responses API (`/responses`), while `@ai-sdk/openai-compatible` targets the
// Chat Completions API (`/chat/completions`).
const PROVIDERS = new Map<string, { protocol: Protocol; npm: string }>([
["openai", { protocol: "openai", npm: "@ai-sdk/openai" }],
["anthropic", { protocol: "anthropic", npm: "@ai-sdk/anthropic" }],
// DeepSeek must use Chat Completions, not the Anthropic protocol: the
// Anthropic message format drops reasoning blocks that carry no signature,
// and DeepSeek never issues one. A reasoning-only assistant turn then lowers
// to `content: []` and the API rejects the whole request with "all messages
// must have non-empty content", while `reasoning_content` never survives the
// round-trip that DeepSeek's thinking mode requires.
["deepseek", { protocol: "openai", npm: "@ai-sdk/openai-compatible" }],
["zai", { protocol: "openai", npm: "@ai-sdk/openai-compatible" }],
["moonshotai", { protocol: "openai", npm: "@ai-sdk/openai-compatible" }],
]);
type ModelDevEntry = {
id?: string;
name?: string;
limit?: { context?: number; output?: number };
attachment?: boolean;
reasoning?: boolean;
temperature?: boolean;
tool_call?: boolean;
interleaved?: boolean | { field: string };
modalities?: { input?: string[]; output?: string[] };
cost?: {
input?: number;
output?: number;
cache_read?: number;
cache_write?: number;
};
};
type ModelsDevData = {
[provider: string]: {
models?: {
[modelId: string]: ModelDevEntry;
};
};
};
type HubResponse = {
providers: {
[provider: string]: {
models?: {
[model: string]: { display_name: string };
};
};
};
};
type ConfigModel = {
id: string;
name: string;
provider: {
api: string;
npm: string;
};
attachment: boolean;
reasoning: boolean;
temperature: boolean;
tool_call: boolean;
modalities: {
input: string[];
output: string[];
};
cost: {
input: number;
output: number;
cache_read: number;
cache_write: number;
};
limit: {
context: number;
output: number;
};
interleaved: boolean | { field: string };
headers: Record<string, string>;
};
function buildLookupMap(modelsDevData: ModelsDevData) {
const byFullId = new Map<string, ModelDevEntry>();
for (const [provider, providerData] of Object.entries(modelsDevData)) {
if (!PROVIDERS.has(provider) || !providerData?.models) continue;
for (const [modelId, entry] of Object.entries(providerData.models)) {
byFullId.set(`${provider}/${modelId}`, entry);
}
}
return byFullId;
}
function resolveEntry(
provider: string,
modelId: string,
byFullId: Map<string, ModelDevEntry>,
): ModelDevEntry | null {
const entry = byFullId.get(`${provider}/${modelId}`);
return entry ?? null;
}
function extractCost(entry?: ModelDevEntry | null) {
return {
input: entry?.cost?.input ?? DEFAULT_COST.input,
output: entry?.cost?.output ?? DEFAULT_COST.output,
cache_read: entry?.cost?.cache_read ?? DEFAULT_COST.cache_read,
cache_write: entry?.cost?.cache_write ?? DEFAULT_COST.cache_write,
};
}
export async function fetchModelsDevData(): Promise<ModelsDevData> {
try {
const raw = await readFile(CACHE_PATH, "utf-8");
return JSON.parse(raw) as ModelsDevData;
} catch {
const res = await fetch(MODELS_DEV_URL, {
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!res.ok) {
throw new Error(
`Failed to fetch models.dev: ${res.status} ${res.statusText}`,
);
}
return res.json() as Promise<ModelsDevData>;
}
}
type AuthStore = { [provider: string]: { type?: string; key?: string } };
// The config hook runs before OpenCode consults our auth.loader, so the key
// has to be resolved independently: first from the environment, then from the
// auth store OpenCode writes for `opencode auth login`. Every failure on the
// store path (missing file, bad JSON, no usable entry) means "no key".
async function resolveHubApiKey(): Promise<string | undefined> {
const fromEnv = process.env.COREINFRA_API_KEY?.trim();
if (fromEnv) return fromEnv;
try {
const raw = await readFile(AUTH_PATH, "utf-8");
const store = JSON.parse(raw) as AuthStore;
const entry = store["coreinfra"];
const key = entry?.type === "api" ? entry.key?.trim() : undefined;
if (key) return key;
} catch {
// best-effort: anything wrong here just means no key
}
return undefined;
}
export async function fetchHubModels(): Promise<HubResponse> {
const apiKey = await resolveHubApiKey();
const res = await fetch(HUB_URL, {
headers: apiKey ? { "X-CoreInfra-Api-Key": apiKey } : undefined,
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!res.ok) {
throw new Error(
`Failed to fetch CoreInfra prices: ${res.status} ${res.statusText}`,
);
}
return res.json() as Promise<HubResponse>;
}
export function buildConfigModels(
modelsDevData: ModelsDevData,
hubData: HubResponse,
): { models: Record<string, ConfigModel>; warnings: string[] } {
const byFullId = buildLookupMap(modelsDevData);
const models: Record<string, ConfigModel> = {};
const warnings: string[] = [];
for (const [provider, providerData] of Object.entries(hubData.providers)) {
const known = PROVIDERS.get(provider);
if (!known || !providerData?.models) continue;
const anthropic = known.protocol === "anthropic";
for (const [modelId, hubModel] of Object.entries(providerData.models)) {
const entry = resolveEntry(provider, modelId, byFullId);
if (!entry) {
warnings.push(
`${provider}/${modelId} not found in models.dev — using defaults`,
);
}
models[modelId] = {
id: modelId,
name: entry?.name ?? hubModel.display_name,
provider: {
api: anthropic ? ANTHROPIC_BASE : OPENAI_BASE,
npm: known.npm,
},
attachment: entry?.attachment ?? DEFAULT_CAPS.attachment,
reasoning: entry?.reasoning ?? DEFAULT_CAPS.reasoning,
temperature: entry?.temperature ?? DEFAULT_CAPS.temperature,
tool_call: entry?.tool_call ?? DEFAULT_CAPS.tool_call,
modalities: {
input: entry?.modalities?.input ?? [
"text",
"image",
"audio",
"video",
"pdf",
],
output: entry?.modalities?.output ?? ["text"],
},
cost: extractCost(entry),
limit: {
context: entry?.limit?.context ?? DEFAULT_LIMIT.context,
output: entry?.limit?.output ?? DEFAULT_LIMIT.output,
},
interleaved:
entry?.interleaved ??
(anthropic ? { field: "reasoning_content" } : true),
headers: anthropic ? { "anthropic-beta": ANTHROPIC_BETA_HEADER } : {},
};
}
}
return { models, warnings };
}