@cydm/pie 2.7.20 → 2.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +18 -0
  2. package/dist/builtin/extensions/ask-user/README.md +117 -0
  3. package/dist/builtin/extensions/ask-user/index.js +4 -3
  4. package/dist/builtin/extensions/cron/index.js +299 -39
  5. package/dist/builtin/extensions/im-forward/README.md +297 -0
  6. package/dist/builtin/extensions/im-forward/index.js +315 -27
  7. package/dist/builtin/extensions/mcp-adapter/README.md +27 -0
  8. package/dist/builtin/extensions/memory/index.js +515 -0
  9. package/dist/builtin/extensions/memory/package.json +19 -0
  10. package/dist/builtin/extensions/pie-ipc/README.md +21 -0
  11. package/dist/builtin/extensions/plan-mode/METHOD.md +70 -0
  12. package/dist/builtin/extensions/plan-mode/index.js +150 -82
  13. package/dist/builtin/extensions/subagent/README.md +315 -0
  14. package/dist/builtin/extensions/subagent/index.js +8 -5
  15. package/dist/builtin/extensions/todo/index.js +4 -3
  16. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +1 -1
  17. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  18. package/dist/builtin/skills/chrome-devtools-axi/{chunk-U75F4DPF.js → chunk-BNSAEVRT.js} +201 -77
  19. package/dist/builtin/skills/chrome-devtools-axi/{cli-4ITIR57L.js → cli-AO2ZTPRM.js} +57 -202
  20. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +6 -1
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +6 -1
  22. package/dist/chunks/auth-storage-3EGM3VTK.js +13 -0
  23. package/dist/chunks/{chunk-X7UO6BA6.js → chunk-3BC5KGDQ.js} +451 -162
  24. package/dist/chunks/chunk-3NHP7HK5.js +298 -0
  25. package/dist/chunks/chunk-6DNYGVZP.js +278 -0
  26. package/dist/chunks/{chunk-TGCI5M6R.js → chunk-GDIYSMTS.js} +22 -142
  27. package/dist/chunks/{chunk-2H2DD22Z.js → chunk-GH4VW2OT.js} +1 -1
  28. package/dist/chunks/chunk-ILUHTKF3.js +149 -0
  29. package/dist/chunks/{chunk-UDCGB3LZ.js → chunk-PK72LVWQ.js} +11841 -16501
  30. package/dist/chunks/chunk-RSL7E4R7.js +9634 -0
  31. package/dist/chunks/chunk-YRR6C43W.js +1740 -0
  32. package/dist/chunks/config-74AUVDLT.js +46 -0
  33. package/dist/chunks/model-registry-LI5THXV4.js +17 -0
  34. package/dist/chunks/src-66XSMIAM.js +134 -0
  35. package/dist/chunks/src-BPSQMSSC.js +431 -0
  36. package/dist/chunks/src-OPPYTPWG.js +285 -0
  37. package/dist/chunks/{src-GX4UBAYF.js → src-YG5M2H44.js} +2 -2
  38. package/dist/chunks/{test-stream-AKIZNFCM.js → test-stream-JBWXKOQA.js} +1 -1
  39. package/dist/cli.js +986 -2292
  40. package/package.json +3 -3
@@ -0,0 +1,1740 @@
1
+ import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+ import {
3
+ getConfigDir
4
+ } from "./chunk-ILUHTKF3.js";
5
+ import {
6
+ MODEL_CLASS_FALLBACK_ORDER,
7
+ modelSupportsToolPurpose,
8
+ requiredCapabilityForToolPurpose,
9
+ sortToolModelCandidatesByCapability
10
+ } from "./chunk-3BC5KGDQ.js";
11
+
12
+ // src/core/model-registry.ts
13
+ import * as fs from "fs";
14
+ import * as path from "path";
15
+ import { createHash, createHmac, randomBytes } from "node:crypto";
16
+ var MODEL_OVERRIDE_KEYS = [
17
+ "name",
18
+ "reasoning",
19
+ "input",
20
+ "cost",
21
+ "contextWindow",
22
+ "maxTokens",
23
+ "transport",
24
+ "headers",
25
+ "compat",
26
+ "cacheCapability",
27
+ "webSearch",
28
+ "fileCapabilities",
29
+ "displayName"
30
+ ];
31
+ function validateExtensionProviderConfig(provider, config) {
32
+ if (!provider || provider !== provider.trim() || /\s/.test(provider)) throw new Error(`registerProvider: invalid provider id "${provider}"`);
33
+ if (!config || typeof config !== "object") throw new Error("registerProvider: config must be an object");
34
+ if (typeof config.baseUrl !== "string" || !config.baseUrl) throw new Error(`registerProvider("${provider}"): baseUrl is required`);
35
+ try {
36
+ new URL(config.baseUrl);
37
+ } catch {
38
+ throw new Error(`registerProvider("${provider}"): baseUrl must be an absolute URL`);
39
+ }
40
+ assertHeadersShape(config.headers, `registerProvider("${provider}")`);
41
+ validateTransport(config.transport, `registerProvider("${provider}")`);
42
+ for (const model of config.models ?? []) {
43
+ if (!model || typeof model.id !== "string" || !model.id.trim() || /\s/.test(model.id)) throw new Error(`registerProvider("${provider}"): invalid model id`);
44
+ assertHeadersShape(model.headers, `registerProvider("${provider}") model "${model.id}"`);
45
+ validateTransport(model.transport, `Model "${model.id}"`);
46
+ validateCompat(model.compat, `registerProvider("${provider}") model "${model.id}" compat`);
47
+ validateCacheCapability(model.cacheCapability, `registerProvider("${provider}") model "${model.id}" cacheCapability`);
48
+ validateWebSearchCapability(model.webSearch, `registerProvider("${provider}") model "${model.id}" webSearch`);
49
+ validateFileCapabilities(model.fileCapabilities, `registerProvider("${provider}") model "${model.id}" fileCapabilities`);
50
+ }
51
+ }
52
+ var REMOTE_CATALOG_CACHE_VERSION = 4;
53
+ var SUPPORTED_REMOTE_APIS = /* @__PURE__ */ new Set(["openai-completions", "anthropic-messages", "openai-responses"]);
54
+ var MAX_REMOTE_CATALOG_BYTES = 2 * 1024 * 1024;
55
+ var OAUTH_RESTORE_LEEWAY_MS = 6e4;
56
+ var OAUTH_REFRESH_TIMEOUT_MS = 3e4;
57
+ function withTimeout(promise, ms, timeoutMessage) {
58
+ return new Promise((resolve2, reject) => {
59
+ const timer = setTimeout(() => reject(new Error(timeoutMessage)), ms);
60
+ Promise.resolve(promise).then(
61
+ (value) => {
62
+ clearTimeout(timer);
63
+ resolve2(value);
64
+ },
65
+ (error) => {
66
+ clearTimeout(timer);
67
+ reject(error);
68
+ }
69
+ );
70
+ });
71
+ }
72
+ var REMOTE_REFRESH_LOCK_WAIT_MS = 6e4;
73
+ var REMOTE_REFRESH_LOCK_WRITE_GRACE_MS = 1e3;
74
+ var remoteRefreshTails = /* @__PURE__ */ new Map();
75
+ var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
76
+ "connection",
77
+ "keep-alive",
78
+ "proxy-authenticate",
79
+ "proxy-authorization",
80
+ "te",
81
+ "trailer",
82
+ "transfer-encoding",
83
+ "upgrade",
84
+ "host",
85
+ "content-length"
86
+ ]);
87
+ function canonicalRemote(remote) {
88
+ const url = new URL(remote.url);
89
+ return { id: remote.id, url: url.href, apiKeyEnv: remote.apiKeyEnv };
90
+ }
91
+ function remoteIdentityDigest(remote) {
92
+ return createHash("sha256").update(JSON.stringify({ version: REMOTE_CATALOG_CACHE_VERSION, ...canonicalRemote(remote) })).digest("hex");
93
+ }
94
+ function remoteCacheDirectory(modelsPath) {
95
+ return path.join(path.dirname(modelsPath), "cache", "remote-catalogs");
96
+ }
97
+ function safeRemoteCacheDirectory(modelsPath, create) {
98
+ const configDirectory = path.dirname(modelsPath);
99
+ if (!fs.existsSync(configDirectory)) {
100
+ if (!create) return void 0;
101
+ fs.mkdirSync(configDirectory, { recursive: true, mode: 448 });
102
+ }
103
+ const configRoot = fs.realpathSync(configDirectory);
104
+ const cacheRoot = path.join(configDirectory, "cache");
105
+ const directory = remoteCacheDirectory(modelsPath);
106
+ for (const candidate of [cacheRoot, directory]) {
107
+ if (!fs.existsSync(candidate)) {
108
+ if (!create) return void 0;
109
+ fs.mkdirSync(candidate, { mode: 448 });
110
+ }
111
+ const stat = fs.lstatSync(candidate);
112
+ if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error(`remote catalog cache path must be a real directory: ${candidate}`);
113
+ const canonical = fs.realpathSync(candidate);
114
+ const relative2 = path.relative(configRoot, canonical);
115
+ if (relative2 === ".." || relative2.startsWith(`..${path.sep}`) || path.isAbsolute(relative2)) {
116
+ throw new Error(`remote catalog cache path escapes the config directory: ${candidate}`);
117
+ }
118
+ try {
119
+ fs.chmodSync(candidate, 448);
120
+ } catch {
121
+ }
122
+ }
123
+ return directory;
124
+ }
125
+ function remoteRefreshLockPath(modelsPath) {
126
+ return path.join(remoteCacheDirectory(modelsPath), ".refresh.lock");
127
+ }
128
+ function processIsAlive(pid) {
129
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
130
+ try {
131
+ process.kill(pid, 0);
132
+ return true;
133
+ } catch (error) {
134
+ return error.code === "EPERM";
135
+ }
136
+ }
137
+ function remoteRefreshLockIsStale(lockPath) {
138
+ const stat = fs.lstatSync(lockPath);
139
+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`remote catalog refresh lock must be a regular file: ${lockPath}`);
140
+ let owner;
141
+ try {
142
+ owner = JSON.parse(fs.readFileSync(lockPath, "utf8"));
143
+ } catch {
144
+ }
145
+ const age = Date.now() - stat.mtimeMs;
146
+ const validOwner = owner?.version === 1 && Number.isSafeInteger(owner.pid) && typeof owner.token === "string" && typeof owner.createdAt === "number";
147
+ if (validOwner && processIsAlive(Number(owner.pid))) return false;
148
+ return validOwner || age > REMOTE_REFRESH_LOCK_WRITE_GRACE_MS;
149
+ }
150
+ function sameFileIdentity(left, right, leftPath, rightPath) {
151
+ if (left.dev !== right.dev || left.ino !== right.ino) return false;
152
+ if (left.ino !== 0) return true;
153
+ return left.size === right.size && fs.readFileSync(leftPath).equals(fs.readFileSync(rightPath));
154
+ }
155
+ function reclaimStaleRemoteRefreshLock(lockPath) {
156
+ if (!remoteRefreshLockIsStale(lockPath)) return false;
157
+ const claimPath = `${lockPath}.reclaim-${process.pid}-${randomBytes(8).toString("hex")}`;
158
+ try {
159
+ fs.linkSync(lockPath, claimPath);
160
+ const claimed = fs.lstatSync(claimPath);
161
+ const current = fs.lstatSync(lockPath);
162
+ if (claimed.isSymbolicLink() || !claimed.isFile() || current.isSymbolicLink() || !current.isFile() || !sameFileIdentity(claimed, current, claimPath, lockPath)) return false;
163
+ if (!remoteRefreshLockIsStale(claimPath)) return false;
164
+ fs.unlinkSync(lockPath);
165
+ return true;
166
+ } catch (error) {
167
+ if (["ENOENT", "EEXIST"].includes(error.code ?? "")) return false;
168
+ throw error;
169
+ } finally {
170
+ try {
171
+ fs.unlinkSync(claimPath);
172
+ } catch {
173
+ }
174
+ }
175
+ }
176
+ async function acquireRemoteRefreshLock(modelsPath) {
177
+ const directory = safeRemoteCacheDirectory(modelsPath, true);
178
+ const lockPath = remoteRefreshLockPath(modelsPath);
179
+ const deadline = Date.now() + REMOTE_REFRESH_LOCK_WAIT_MS;
180
+ while (true) {
181
+ const token = randomBytes(16).toString("hex");
182
+ try {
183
+ const fd = fs.openSync(lockPath, "wx", 384);
184
+ try {
185
+ fs.writeFileSync(fd, `${JSON.stringify({ version: 1, pid: process.pid, token, createdAt: Date.now() })}
186
+ `);
187
+ } finally {
188
+ fs.closeSync(fd);
189
+ }
190
+ return () => {
191
+ try {
192
+ const stat = fs.lstatSync(lockPath);
193
+ if (stat.isSymbolicLink() || !stat.isFile()) return;
194
+ const current = JSON.parse(fs.readFileSync(lockPath, "utf8"));
195
+ if (current.token === token) fs.unlinkSync(lockPath);
196
+ } catch {
197
+ }
198
+ };
199
+ } catch (error) {
200
+ if (error.code !== "EEXIST") throw error;
201
+ try {
202
+ if (reclaimStaleRemoteRefreshLock(lockPath)) continue;
203
+ } catch (lockError) {
204
+ if (lockError.code === "ENOENT") continue;
205
+ throw lockError;
206
+ }
207
+ if (Date.now() >= deadline) throw new Error(`timed out waiting for remote catalog refresh lock: ${lockPath}`);
208
+ await new Promise((resolve2) => setTimeout(resolve2, 25));
209
+ }
210
+ }
211
+ }
212
+ function readSafeRemoteCacheFile(directory, filepath) {
213
+ const stat = fs.lstatSync(filepath);
214
+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`remote catalog cache entry must be a regular file: ${filepath}`);
215
+ const canonicalDirectory = fs.realpathSync(directory);
216
+ const canonicalFile = fs.realpathSync(filepath);
217
+ const relative2 = path.relative(canonicalDirectory, canonicalFile);
218
+ if (!relative2 || relative2 === ".." || relative2.startsWith(`..${path.sep}`) || path.isAbsolute(relative2)) {
219
+ throw new Error(`remote catalog cache entry escapes its cache directory: ${filepath}`);
220
+ }
221
+ return fs.readFileSync(filepath);
222
+ }
223
+ function credentialNamespaceKey(modelsPath, create) {
224
+ const directory = safeRemoteCacheDirectory(modelsPath, create);
225
+ if (!directory) return void 0;
226
+ const keyPath = path.join(directory, ".credential-namespace-key");
227
+ if (!fs.existsSync(keyPath) && !create) return void 0;
228
+ if (create && !fs.existsSync(keyPath)) {
229
+ try {
230
+ fs.writeFileSync(keyPath, randomBytes(32), { flag: "wx", mode: 384 });
231
+ } catch (error) {
232
+ if (!isPlainRecord(error) || error.code !== "EEXIST") throw error;
233
+ }
234
+ }
235
+ const key = readSafeRemoteCacheFile(directory, keyPath);
236
+ if (key.byteLength !== 32) throw new Error("remote catalog credential namespace key is invalid");
237
+ try {
238
+ fs.chmodSync(keyPath, 384);
239
+ } catch {
240
+ }
241
+ return key;
242
+ }
243
+ function credentialFingerprint(modelsPath, remote, credential, create = false) {
244
+ const key = credentialNamespaceKey(modelsPath, create);
245
+ if (!key) return void 0;
246
+ return createHmac("sha256", key).update(remoteIdentityDigest(remote)).update("\0").update(credential).digest("hex");
247
+ }
248
+ function remoteCachePath(modelsPath, remote, fingerprint) {
249
+ return path.join(remoteCacheDirectory(modelsPath), `${remoteIdentityDigest(remote)}-${fingerprint}.json`);
250
+ }
251
+ function pruneLegacyRemoteCatalogCaches(modelsPath) {
252
+ const directory = safeRemoteCacheDirectory(modelsPath, false);
253
+ if (!directory) return;
254
+ for (const name of fs.readdirSync(directory)) {
255
+ if (!name.endsWith(".json")) continue;
256
+ const filepath = path.join(directory, name);
257
+ try {
258
+ const value = JSON.parse(readSafeRemoteCacheFile(directory, filepath).toString("utf8"));
259
+ if (value.version === REMOTE_CATALOG_CACHE_VERSION) continue;
260
+ } catch {
261
+ let stat;
262
+ try {
263
+ stat = fs.lstatSync(filepath);
264
+ } catch {
265
+ continue;
266
+ }
267
+ if (stat.isSymbolicLink() || !stat.isFile()) continue;
268
+ }
269
+ try {
270
+ fs.unlinkSync(filepath);
271
+ } catch {
272
+ }
273
+ }
274
+ }
275
+ function scrubActiveSecretsFromRemoteCaches(modelsPath, activeSecrets) {
276
+ if (activeSecrets.length === 0) return;
277
+ const directory = safeRemoteCacheDirectory(modelsPath, false);
278
+ if (!directory) return;
279
+ const handle = fs.opendirSync(directory);
280
+ try {
281
+ let scanned = 0;
282
+ while (true) {
283
+ const entry = handle.readSync();
284
+ if (!entry) break;
285
+ if (++scanned > 1e4) throw new Error("remote catalog cache directory exceeds the hygiene scan limit");
286
+ const isCache = entry.name.endsWith(".json");
287
+ const isOrphanedTemporary = /^\..+\.json\.\d+\.[0-9a-f]+\.tmp$/.test(entry.name);
288
+ if (!entry.isFile() || !isCache && !isOrphanedTemporary) continue;
289
+ const filepath = path.join(directory, entry.name);
290
+ try {
291
+ const raw = readSafeRemoteCacheFile(directory, filepath).toString("utf8");
292
+ assertNoSecretSubstrings(raw, activeSecrets, "remote catalog cache");
293
+ } catch {
294
+ try {
295
+ const stat = fs.lstatSync(filepath);
296
+ if (!stat.isSymbolicLink() && stat.isFile()) fs.unlinkSync(filepath);
297
+ } catch {
298
+ }
299
+ }
300
+ }
301
+ } finally {
302
+ handle.closeSync();
303
+ }
304
+ }
305
+ function payloadDigest(payload) {
306
+ return createHash("sha256").update(JSON.stringify(payload)).digest("hex");
307
+ }
308
+ function assertNoSecretSubstrings(value, secrets, label) {
309
+ const active = [...new Set(secrets.filter((secret) => secret.length > 0))];
310
+ if (active.length === 0) return;
311
+ const seen = /* @__PURE__ */ new Set();
312
+ const visit = (candidate) => {
313
+ if (typeof candidate === "string") {
314
+ if (active.some((secret) => candidate.includes(secret))) throw new Error(`${label} reflects an active credential`);
315
+ return;
316
+ }
317
+ if (!candidate || typeof candidate !== "object" || seen.has(candidate)) return;
318
+ seen.add(candidate);
319
+ if (Array.isArray(candidate)) {
320
+ for (const item of candidate) visit(item);
321
+ return;
322
+ }
323
+ for (const [key, item] of Object.entries(candidate)) {
324
+ visit(key);
325
+ visit(item);
326
+ }
327
+ };
328
+ visit(value);
329
+ const serialized = JSON.stringify(value);
330
+ if (active.some((secret) => serialized.includes(secret))) throw new Error(`${label} reflects an active credential`);
331
+ }
332
+ function safeRemoteText(value, secrets) {
333
+ let message = String(value);
334
+ const active = [...new Set(secrets.filter(Boolean))];
335
+ const replacement = active.some((secret) => "[REDACTED]".includes(secret)) ? "" : "[REDACTED]";
336
+ for (const secret of active) message = message.split(secret).join(replacement);
337
+ message = message.slice(0, 1024);
338
+ if (!active.some((secret) => message.includes(secret))) return message;
339
+ return "";
340
+ }
341
+ function safeRemoteError(error, secrets) {
342
+ return safeRemoteText(error instanceof Error ? `${error.name}: ${error.message}` : String(error), secrets);
343
+ }
344
+ function warnRemoteCatalog(message, secrets) {
345
+ console.warn(safeRemoteText(message, secrets));
346
+ }
347
+ function configuredRemoteCredentialValues(config) {
348
+ let remotes;
349
+ try {
350
+ remotes = validatedRemoteCatalogs(config.remoteCatalogs);
351
+ } catch {
352
+ return [];
353
+ }
354
+ return [...new Set(remotes.map((remote) => process.env[remote.apiKeyEnv]).filter((secret) => typeof secret === "string" && secret.length > 0))];
355
+ }
356
+ function sameRemoteIdentity(left, right) {
357
+ if (!left || typeof left !== "object" || Array.isArray(left)) return false;
358
+ const value = left;
359
+ const expected = canonicalRemote(right);
360
+ return value.id === expected.id && value.url === expected.url && value.apiKeyEnv === expected.apiKeyEnv;
361
+ }
362
+ function readRemoteCache(modelsPath, remote, fingerprint, activeSecrets) {
363
+ try {
364
+ const directory = safeRemoteCacheDirectory(modelsPath, false);
365
+ if (!directory) return void 0;
366
+ const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
367
+ if (fs.existsSync(tombstone)) return void 0;
368
+ const value = JSON.parse(readSafeRemoteCacheFile(directory, remoteCachePath(modelsPath, remote, fingerprint)).toString("utf8"));
369
+ if (value.version !== REMOTE_CATALOG_CACHE_VERSION || !sameRemoteIdentity(value.identity, remote) || value.credentialFingerprint !== fingerprint || typeof value.payloadSha256 !== "string" || value.payloadSha256 !== payloadDigest(value.payload)) return void 0;
370
+ assertNoSecretSubstrings({ etag: value.etag, payload: value.payload }, activeSecrets, "remote catalog cache");
371
+ const payload = sanitizeRemotePayload(value.payload, canonicalRemote(remote), new URL(remote.url), true);
372
+ if (payloadDigest(payload) !== value.payloadSha256) return void 0;
373
+ return { ...value, payload };
374
+ } catch {
375
+ removeRemoteCache(modelsPath, remote, fingerprint);
376
+ return void 0;
377
+ }
378
+ }
379
+ function remoteCacheTombstonePath(modelsPath, remote, fingerprint) {
380
+ return `${remoteCachePath(modelsPath, remote, fingerprint)}.revoked`;
381
+ }
382
+ function removeRemoteCache(modelsPath, remote, fingerprint) {
383
+ try {
384
+ const directory = safeRemoteCacheDirectory(modelsPath, false);
385
+ if (!directory) return;
386
+ const filepath = remoteCachePath(modelsPath, remote, fingerprint);
387
+ if (fs.existsSync(filepath)) {
388
+ const stat = fs.lstatSync(filepath);
389
+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`remote catalog cache entry is not a regular file: ${filepath}`);
390
+ fs.unlinkSync(filepath);
391
+ }
392
+ const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
393
+ if (fs.existsSync(tombstone)) fs.unlinkSync(tombstone);
394
+ return;
395
+ } catch (error) {
396
+ const directory = safeRemoteCacheDirectory(modelsPath, true);
397
+ if (!directory) throw error;
398
+ const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
399
+ try {
400
+ fs.writeFileSync(tombstone, `${JSON.stringify({ version: 1, revoked: true })}
401
+ `, { flag: "wx", mode: 384 });
402
+ } catch (tombstoneError) {
403
+ if (!fs.existsSync(tombstone)) throw tombstoneError;
404
+ }
405
+ }
406
+ }
407
+ function validateRemoteEndpoint(baseUrl, catalogUrl, label) {
408
+ let endpoint;
409
+ try {
410
+ endpoint = new URL(baseUrl);
411
+ } catch {
412
+ throw new Error(`${label} baseUrl must be an absolute URL`);
413
+ }
414
+ if (endpoint.protocol !== "https:" && endpoint.hostname !== "127.0.0.1" && endpoint.hostname !== "localhost") {
415
+ throw new Error(`${label} baseUrl must use HTTPS`);
416
+ }
417
+ if (endpoint.username || endpoint.password) throw new Error(`${label} baseUrl must not contain credentials`);
418
+ if (endpoint.hash) throw new Error(`${label} baseUrl must not contain a fragment`);
419
+ if (endpoint.search) throw new Error(`${label} baseUrl must not contain query parameters`);
420
+ if (endpoint.origin !== catalogUrl.origin) throw new Error(`${label} baseUrl must use the authenticated catalog origin`);
421
+ }
422
+ function isPlainRecord(value) {
423
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
424
+ const prototype = Object.getPrototypeOf(value);
425
+ return prototype === Object.prototype || prototype === null;
426
+ }
427
+ function assertOnlyKeys(value, allowed, label) {
428
+ const allowedSet = new Set(allowed);
429
+ const unexpected = Object.keys(value).find((key) => !allowedSet.has(key));
430
+ if (unexpected) throw new Error(`${label} contains unsupported field ${unexpected}`);
431
+ }
432
+ function validateRemoteCatalogConfig(value, label) {
433
+ if (!isPlainRecord(value)) throw new Error(`${label} must be an object`);
434
+ assertOnlyKeys(value, ["id", "url", "apiKeyEnv"], label);
435
+ if (typeof value.id !== "string" || !value.id.trim() || value.id !== value.id.trim() || /\s/.test(value.id)) throw new Error(`${label}.id must be a non-empty identifier without whitespace`);
436
+ if (typeof value.url !== "string" || !value.url) throw new Error(`${label}.url must be a URL`);
437
+ if (typeof value.apiKeyEnv !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value.apiKeyEnv)) throw new Error(`${label}.apiKeyEnv must be an environment variable name`);
438
+ let url;
439
+ try {
440
+ url = new URL(value.url);
441
+ } catch {
442
+ throw new Error(`${label}.url must be an absolute URL`);
443
+ }
444
+ const localTestHost = url.hostname === "127.0.0.1" || url.hostname === "localhost";
445
+ if (url.protocol !== "https:" && !localTestHost) throw new Error(`${label}.url must use HTTPS`);
446
+ if (url.username || url.password) throw new Error(`${label}.url must not contain credentials`);
447
+ if (url.hash) throw new Error(`${label}.url must not contain a fragment`);
448
+ if (url.search) throw new Error(`${label}.url must not contain query parameters`);
449
+ return canonicalRemote({ id: value.id, url: url.href, apiKeyEnv: value.apiKeyEnv });
450
+ }
451
+ function validatedRemoteCatalogs(value) {
452
+ if (value === void 0) return [];
453
+ if (!Array.isArray(value)) throw new Error("models.json remoteCatalogs must be an array");
454
+ if (value.length === 0) throw new Error("models.json remoteCatalogs must be a non-empty array");
455
+ const catalogs = value.map((item, index) => validateRemoteCatalogConfig(item, `models.json remoteCatalogs[${index}]`));
456
+ const ids = /* @__PURE__ */ new Set();
457
+ for (const catalog of catalogs) {
458
+ if (ids.has(catalog.id)) throw new Error(`models.json remoteCatalogs contains duplicate id ${catalog.id}`);
459
+ ids.add(catalog.id);
460
+ }
461
+ return catalogs;
462
+ }
463
+ function validateModelsDocumentShape(value) {
464
+ if (!isPlainRecord(value)) throw new Error("models.json must be an object");
465
+ assertOnlyKeys(value, ["$schema", "profiles", "remoteCatalogs", "defaults", "modelOverrides"], "models.json");
466
+ if (value.$schema !== void 0 && (typeof value.$schema !== "string" || !value.$schema)) throw new Error("models.json $schema must be a non-empty string");
467
+ const hasProfiles = Object.prototype.hasOwnProperty.call(value, "profiles");
468
+ const hasRemoteCatalogs = Object.prototype.hasOwnProperty.call(value, "remoteCatalogs");
469
+ if (!hasProfiles && !hasRemoteCatalogs) throw new Error("models.json must define profiles or remoteCatalogs");
470
+ validatedRemoteCatalogs(value.remoteCatalogs);
471
+ if (hasProfiles) {
472
+ if (!isPlainRecord(value.profiles) || Object.keys(value.profiles).length === 0) throw new Error("models.json profiles must be a non-empty object");
473
+ for (const [profileId, profile] of Object.entries(value.profiles)) {
474
+ if (!profileId || profileId !== profileId.trim() || /\s/.test(profileId)) throw new Error(`models.json profile id is invalid: ${profileId}`);
475
+ validateProfileConfig(profileId, profile);
476
+ }
477
+ }
478
+ validateModelOverrides(value.modelOverrides);
479
+ if (value.defaults !== void 0) {
480
+ if (!isPlainRecord(value.defaults)) throw new Error("models.json defaults must be an object");
481
+ assertOnlyKeys(value.defaults, ["provider", "modelId", "modelClasses", "toolModels"], "models.json defaults");
482
+ assertOptionalString(value.defaults.provider, "models.json defaults.provider");
483
+ assertOptionalString(value.defaults.modelId, "models.json defaults.modelId");
484
+ for (const [field, allowed] of [["modelClasses", ["light", "balanced", "strong"]], ["toolModels", ["web_search", "read_file.image", "read_file.video", "read_file.audio", "read_file.document"]]]) {
485
+ const routes = value.defaults[field];
486
+ if (routes === void 0) continue;
487
+ if (!isPlainRecord(routes)) throw new Error(`models.json defaults.${field} must be an object`);
488
+ assertOnlyKeys(routes, allowed, `models.json defaults.${field}`);
489
+ for (const [routeName, route] of Object.entries(routes)) {
490
+ if (!isPlainRecord(route)) throw new Error(`models.json defaults.${field}.${routeName} must be an object`);
491
+ assertOnlyKeys(route, ["provider", "modelId"], `models.json defaults.${field}.${routeName}`);
492
+ assertOptionalString(route.provider, `models.json defaults.${field}.${routeName}.provider`);
493
+ assertOptionalString(route.modelId, `models.json defaults.${field}.${routeName}.modelId`);
494
+ }
495
+ }
496
+ }
497
+ }
498
+ function assertOptionalString(value, label) {
499
+ if (value !== void 0 && (typeof value !== "string" || !value)) throw new Error(`${label} must be a non-empty string`);
500
+ }
501
+ function assertOptionalEnvName(value, label) {
502
+ if (value !== void 0 && (typeof value !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value))) {
503
+ throw new Error(`${label} must be an environment variable name`);
504
+ }
505
+ }
506
+ function assertOptionalBoolean(value, label) {
507
+ if (value !== void 0 && typeof value !== "boolean") throw new Error(`${label} must be a boolean`);
508
+ }
509
+ function validateCacheCapability(value, label) {
510
+ if (value === void 0) return;
511
+ if (!isPlainRecord(value) || !["none", "session_store", "prompt_cache", "usage_only"].includes(String(value.mode)) || typeof value.supported !== "boolean") throw new Error(`${label} is invalid`);
512
+ assertOnlyKeys(value, ["mode", "supported", "supportsUsageMetrics", "description"], label);
513
+ assertOptionalBoolean(value.supportsUsageMetrics, `${label}.supportsUsageMetrics`);
514
+ assertOptionalString(value.description, `${label}.description`);
515
+ }
516
+ function validateWebSearchCapability(value, label) {
517
+ if (value === void 0) return;
518
+ if (!isPlainRecord(value) || !["anthropic_server_tool", "chat_completions_web_search", "openai_responses"].includes(String(value.type))) {
519
+ throw new Error(`${label} is invalid`);
520
+ }
521
+ assertOnlyKeys(value, ["type", "forceToolChoice", "searchEngine", "count", "contentSize"], label);
522
+ assertOptionalBoolean(value.forceToolChoice, `${label}.forceToolChoice`);
523
+ assertOptionalString(value.searchEngine, `${label}.searchEngine`);
524
+ if (value.count !== void 0 && (!Number.isInteger(value.count) || Number(value.count) < 1)) throw new Error(`${label}.count is invalid`);
525
+ if (value.contentSize !== void 0 && !["low", "medium", "high"].includes(String(value.contentSize))) throw new Error(`${label}.contentSize is invalid`);
526
+ }
527
+ function validateFileCapabilities(value, label) {
528
+ if (value === void 0) return;
529
+ if (!isPlainRecord(value)) throw new Error(`${label} is invalid`);
530
+ for (const [kind, capability] of Object.entries(value)) {
531
+ if (!["image", "video", "audio", "document"].includes(kind)) throw new Error(`${label}.${kind} is unsupported`);
532
+ if (typeof capability === "boolean") continue;
533
+ if (!isPlainRecord(capability)) throw new Error(`${label}.${kind} is invalid`);
534
+ assertOnlyKeys(capability, ["supported", "formats", "maxFileSizeMb", "maxDurationSeconds", "nativeInline"], `${label}.${kind}`);
535
+ assertOptionalBoolean(capability.supported, `${label}.${kind}.supported`);
536
+ assertOptionalBoolean(capability.nativeInline, `${label}.${kind}.nativeInline`);
537
+ if (capability.formats !== void 0 && (!Array.isArray(capability.formats) || capability.formats.some((item) => typeof item !== "string" || !item))) {
538
+ throw new Error(`${label}.${kind}.formats is invalid`);
539
+ }
540
+ if (Array.isArray(capability.formats) && new Set(capability.formats).size !== capability.formats.length) {
541
+ throw new Error(`${label}.${kind}.formats contains duplicates`);
542
+ }
543
+ for (const field of ["maxFileSizeMb", "maxDurationSeconds"]) {
544
+ if (capability[field] !== void 0 && (typeof capability[field] !== "number" || !Number.isFinite(capability[field]) || capability[field] <= 0)) {
545
+ throw new Error(`${label}.${kind}.${field} is invalid`);
546
+ }
547
+ }
548
+ }
549
+ }
550
+ function validateTransport(value, label) {
551
+ if (value !== void 0 && value !== "sse" && value !== "websocket" && value !== "auto") throw new Error(`${label}.transport is invalid`);
552
+ }
553
+ function validateCompat(value, label) {
554
+ if (value === void 0) return;
555
+ if (!isPlainRecord(value)) throw new Error(`${label} is invalid`);
556
+ assertOnlyKeys(value, [
557
+ "forcedReasoningEffort",
558
+ "store",
559
+ "supportsEncryptedReasoning",
560
+ "responsesContinuation",
561
+ "supportsReasoningSummary",
562
+ "reasoningSummary",
563
+ "timeoutReplay",
564
+ "supportsStore",
565
+ "supportsDeveloperRole",
566
+ "supportsReasoningEffort",
567
+ "supportsUsageInStreaming",
568
+ "maxTokensField",
569
+ "requiresToolResultName",
570
+ "requiresAssistantAfterToolResult",
571
+ "requiresThinkingAsText",
572
+ "supportsStrictMode",
573
+ "streamRequiresDone",
574
+ "streamRequiresFinishReason",
575
+ "cacheCapability"
576
+ ], label);
577
+ if (value.forcedReasoningEffort !== void 0 && value.forcedReasoningEffort !== "none") {
578
+ throw new Error(`${label}.forcedReasoningEffort must be "none"`);
579
+ }
580
+ if (value.reasoningSummary !== void 0 && !["auto", "concise", "detailed", "none"].includes(String(value.reasoningSummary))) {
581
+ throw new Error(`${label}.reasoningSummary must be auto | concise | detailed | none`);
582
+ }
583
+ for (const field of [
584
+ "store",
585
+ "supportsEncryptedReasoning",
586
+ "responsesContinuation",
587
+ "supportsReasoningSummary",
588
+ "timeoutReplay",
589
+ "supportsStore",
590
+ "supportsDeveloperRole",
591
+ "supportsReasoningEffort",
592
+ "supportsUsageInStreaming",
593
+ "requiresToolResultName",
594
+ "requiresAssistantAfterToolResult",
595
+ "requiresThinkingAsText",
596
+ "supportsStrictMode",
597
+ "streamRequiresDone",
598
+ "streamRequiresFinishReason"
599
+ ]) assertOptionalBoolean(value[field], `${label}.${field}`);
600
+ if (value.maxTokensField !== void 0 && value.maxTokensField !== "max_completion_tokens" && value.maxTokensField !== "max_tokens") {
601
+ throw new Error(`${label}.maxTokensField is invalid`);
602
+ }
603
+ validateCacheCapability(value.cacheCapability, `${label}.cacheCapability`);
604
+ }
605
+ function validateRemoteModel(profileId, model) {
606
+ if (!isPlainRecord(model) || typeof model.id !== "string" || !model.id.trim() || model.id !== model.id.trim() || /\s/.test(model.id)) throw new Error(`Remote profile "${profileId}" contains an invalid model id`);
607
+ assertOnlyKeys(model, [
608
+ "id",
609
+ "api",
610
+ "name",
611
+ "reasoning",
612
+ "input",
613
+ "cost",
614
+ "contextWindow",
615
+ "maxTokens",
616
+ "transport",
617
+ "compat",
618
+ "cacheCapability",
619
+ "webSearch",
620
+ "fileCapabilities",
621
+ "headers",
622
+ "apiKeyEnv",
623
+ "displayName",
624
+ "filePlatform",
625
+ "attachmentPlatform"
626
+ ], `Remote profile "${profileId}" model "${model.id}"`);
627
+ for (const field of ["name", "displayName", "filePlatform", "attachmentPlatform", "apiKeyEnv"]) {
628
+ assertOptionalString(model[field], `Remote profile "${profileId}" model "${model.id}" ${field}`);
629
+ }
630
+ if (model.api !== void 0 && !SUPPORTED_REMOTE_APIS.has(model.api)) throw new Error(`Model "${model.id}" has unsupported api ${model.api}`);
631
+ assertOptionalBoolean(model.reasoning, `Remote profile "${profileId}" model "${model.id}" reasoning`);
632
+ if (!Array.isArray(model.input) || model.input.length === 0 || model.input.some((item) => !["text", "image", "audio", "video"].includes(item))) {
633
+ throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid input capabilities`);
634
+ }
635
+ if (!isPlainRecord(model.cost)) throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid cost values`);
636
+ assertOnlyKeys(model.cost, ["input", "output", "cacheRead", "cacheWrite", "cacheWriteLong"], `Remote profile "${profileId}" model "${model.id}" cost`);
637
+ const invalidRate = (value) => typeof value !== "number" || !Number.isFinite(value) || value < 0;
638
+ if ([model.cost.input, model.cost.output, model.cost.cacheRead, model.cost.cacheWrite].some(invalidRate) || model.cost.cacheWriteLong !== void 0 && invalidRate(model.cost.cacheWriteLong)) {
639
+ throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid cost values`);
640
+ }
641
+ if (!Number.isSafeInteger(model.contextWindow) || Number(model.contextWindow) <= 0 || !Number.isSafeInteger(model.maxTokens) || Number(model.maxTokens) <= 0 || Number(model.maxTokens) > Number(model.contextWindow)) {
642
+ throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid token limits`);
643
+ }
644
+ if (new Set(model.input).size !== model.input.length) throw new Error(`Remote profile "${profileId}" model "${model.id}" has duplicate input capabilities`);
645
+ validateTransport(model.transport, `Model "${model.id}"`);
646
+ validateCompat(model.compat, `Remote profile "${profileId}" model "${model.id}" compat`);
647
+ validateCacheCapability(model.cacheCapability, `Remote profile "${profileId}" model "${model.id}" cacheCapability`);
648
+ validateWebSearchCapability(model.webSearch, `Remote profile "${profileId}" model "${model.id}" webSearch`);
649
+ validateFileCapabilities(model.fileCapabilities, `Remote profile "${profileId}" model "${model.id}" fileCapabilities`);
650
+ }
651
+ function assertHeadersShape(headers, label) {
652
+ if (headers === void 0) return;
653
+ if (!isPlainRecord(headers)) throw new Error(`${label} headers must be an object`);
654
+ for (const [name, value] of Object.entries(headers)) {
655
+ if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) throw new Error(`${label} header name ${name || "(empty)"} is invalid`);
656
+ if (typeof value !== "string") throw new Error(`${label} header ${name} must be a string`);
657
+ if (/[\0-\x08\x0A-\x1F\x7F]/.test(value)) throw new Error(`${label} header ${name} contains an invalid control character`);
658
+ }
659
+ }
660
+ function assertRemoteHeadersSafe(headers, label) {
661
+ assertHeadersShape(headers, label);
662
+ for (const name of Object.keys(headers || {})) {
663
+ if (/(?:authorization|cookie|api[-_]?key|token|secret|credential)/i.test(name)) {
664
+ throw new Error(`${label} must not provide credential-bearing header ${name}`);
665
+ }
666
+ if (HOP_BY_HOP_HEADERS.has(name.toLowerCase())) throw new Error(`${label} must not provide transport header ${name}`);
667
+ }
668
+ }
669
+ function sanitizeRemotePayload(decoded, remote, catalogUrl, allowLocallyInjectedCredential = false) {
670
+ if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) throw new Error("catalog response must be an object");
671
+ assertOnlyKeys(decoded, ["profiles"], "catalog response");
672
+ const sourceProfiles = decoded.profiles;
673
+ if (!sourceProfiles || typeof sourceProfiles !== "object" || Array.isArray(sourceProfiles)) {
674
+ throw new Error("catalog response profiles must be an object");
675
+ }
676
+ const profiles = /* @__PURE__ */ Object.create(null);
677
+ for (const [provider, source] of Object.entries(sourceProfiles)) {
678
+ if (!provider || provider !== provider.trim() || /\s/.test(provider) || !isPlainRecord(source)) throw new Error("catalog contains an invalid profile");
679
+ assertOnlyKeys(source, [
680
+ "baseUrl",
681
+ "endpoints",
682
+ "api",
683
+ "apiKey",
684
+ "apiKeyEnv",
685
+ "headers",
686
+ "displayName",
687
+ "filePlatform",
688
+ "attachmentPlatform",
689
+ "transport",
690
+ "compat",
691
+ "cacheCapability",
692
+ "webSearch",
693
+ "fileCapabilities",
694
+ "models"
695
+ ], `Remote profile "${provider}"`);
696
+ if (Object.prototype.hasOwnProperty.call(source, "apiKey") || Object.prototype.hasOwnProperty.call(source, "apiKeyEnv") && (!allowLocallyInjectedCredential || source.apiKeyEnv !== remote.apiKeyEnv)) {
697
+ throw new Error(`Remote profile "${provider}" must not declare credential fields`);
698
+ }
699
+ if (!source.api || !SUPPORTED_REMOTE_APIS.has(source.api)) throw new Error(`Remote profile "${provider}" has unsupported api`);
700
+ if (!source.baseUrl) throw new Error(`Remote profile "${provider}" has no baseUrl`);
701
+ for (const field of ["baseUrl", "api", "displayName", "filePlatform", "attachmentPlatform", "apiKeyEnv"]) {
702
+ assertOptionalString(source[field], `Remote profile "${provider}" ${field}`);
703
+ }
704
+ validateRemoteEndpoint(source.baseUrl, catalogUrl, `Remote profile "${provider}"`);
705
+ validateProfileEndpoints(source, `Remote profile "${provider}"`);
706
+ for (const [api, endpoint] of Object.entries(source.endpoints ?? {})) {
707
+ validateRemoteEndpoint(endpoint, catalogUrl, `Remote profile "${provider}" endpoints.${api}`);
708
+ }
709
+ if (!Array.isArray(source.models) || source.models.length === 0) throw new Error(`Remote profile "${provider}" has no models`);
710
+ assertRemoteHeadersSafe(source.headers, `Remote profile "${provider}"`);
711
+ validateTransport(source.transport, `Remote profile "${provider}"`);
712
+ validateCompat(source.compat, `Remote profile "${provider}" compat`);
713
+ validateCacheCapability(source.cacheCapability, `Remote profile "${provider}" cacheCapability`);
714
+ validateWebSearchCapability(source.webSearch, `Remote profile "${provider}" webSearch`);
715
+ validateFileCapabilities(source.fileCapabilities, `Remote profile "${provider}" fileCapabilities`);
716
+ const seen = /* @__PURE__ */ new Set();
717
+ for (const model of source.models) {
718
+ if (isPlainRecord(model) && Object.prototype.hasOwnProperty.call(model, "apiKeyEnv") && (!allowLocallyInjectedCredential || model.apiKeyEnv !== remote.apiKeyEnv)) {
719
+ throw new Error(`Remote profile "${provider}" model must not declare credential fields`);
720
+ }
721
+ validateRemoteModel(provider, model);
722
+ assertRemoteHeadersSafe(model.headers, `Remote profile "${provider}" model "${model.id}"`);
723
+ if (seen.has(model.id)) throw new Error(`Remote profile "${provider}" contains duplicate model "${model.id}"`);
724
+ seen.add(model.id);
725
+ }
726
+ const sanitized = {
727
+ baseUrl: source.baseUrl,
728
+ ...source.endpoints === void 0 ? {} : { endpoints: { ...source.endpoints } },
729
+ api: source.api,
730
+ transport: source.transport,
731
+ apiKeyEnv: remote.apiKeyEnv,
732
+ ...source.headers === void 0 ? {} : { headers: { ...source.headers } },
733
+ ...source.displayName === void 0 ? {} : { displayName: source.displayName },
734
+ ...source.filePlatform === void 0 ? {} : { filePlatform: source.filePlatform },
735
+ ...source.attachmentPlatform === void 0 ? {} : { attachmentPlatform: source.attachmentPlatform },
736
+ ...source.compat === void 0 ? {} : { compat: { ...source.compat } },
737
+ ...source.cacheCapability === void 0 ? {} : { cacheCapability: { ...source.cacheCapability } },
738
+ ...source.webSearch === void 0 ? {} : { webSearch: { ...source.webSearch } },
739
+ ...source.fileCapabilities === void 0 ? {} : { fileCapabilities: { ...source.fileCapabilities } },
740
+ models: source.models.map((model) => ({
741
+ id: model.id,
742
+ ...model.api === void 0 ? {} : { api: model.api },
743
+ ...model.name === void 0 ? {} : { name: model.name },
744
+ ...model.reasoning === void 0 ? {} : { reasoning: model.reasoning },
745
+ input: [...model.input],
746
+ cost: {
747
+ input: model.cost.input,
748
+ output: model.cost.output,
749
+ cacheRead: model.cost.cacheRead,
750
+ cacheWrite: model.cost.cacheWrite,
751
+ ...model.cost.cacheWriteLong === void 0 ? {} : { cacheWriteLong: model.cost.cacheWriteLong }
752
+ },
753
+ contextWindow: model.contextWindow,
754
+ maxTokens: model.maxTokens,
755
+ ...model.transport === void 0 ? {} : { transport: model.transport },
756
+ ...model.compat === void 0 ? {} : { compat: { ...model.compat } },
757
+ ...model.cacheCapability === void 0 ? {} : { cacheCapability: { ...model.cacheCapability } },
758
+ ...model.webSearch === void 0 ? {} : { webSearch: { ...model.webSearch } },
759
+ ...model.fileCapabilities === void 0 ? {} : { fileCapabilities: { ...model.fileCapabilities } },
760
+ ...model.headers === void 0 ? {} : { headers: { ...model.headers } },
761
+ apiKeyEnv: remote.apiKeyEnv,
762
+ ...model.displayName === void 0 ? {} : { displayName: model.displayName },
763
+ ...model.filePlatform === void 0 ? {} : { filePlatform: model.filePlatform },
764
+ ...model.attachmentPlatform === void 0 ? {} : { attachmentPlatform: model.attachmentPlatform }
765
+ }))
766
+ };
767
+ validateProfileConfig(provider, sanitized);
768
+ Object.defineProperty(profiles, provider, { value: sanitized, enumerable: true, configurable: true, writable: true });
769
+ }
770
+ return { profiles };
771
+ }
772
+ async function readResponseTextBounded(response, maxBytes) {
773
+ const reader = response.body?.getReader();
774
+ if (!reader) return "";
775
+ const chunks = [];
776
+ let total = 0;
777
+ try {
778
+ while (true) {
779
+ const { done, value } = await reader.read();
780
+ if (done) break;
781
+ if (!value) continue;
782
+ total += value.byteLength;
783
+ if (total > maxBytes) {
784
+ await reader.cancel("catalog response is too large");
785
+ throw new Error("catalog response is too large");
786
+ }
787
+ chunks.push(value);
788
+ }
789
+ return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString("utf8");
790
+ } finally {
791
+ reader.releaseLock();
792
+ }
793
+ }
794
+ function loadResolvedModelsConfig(modelsPath) {
795
+ const raw = JSON.parse(fs.readFileSync(modelsPath, "utf8"));
796
+ validateModelsDocumentShape(raw);
797
+ const remotes = validatedRemoteCatalogs(raw.remoteCatalogs);
798
+ const activeRemoteSecrets = configuredRemoteCredentialValues(raw);
799
+ scrubActiveSecretsFromRemoteCaches(modelsPath, activeRemoteSecrets);
800
+ const profiles = /* @__PURE__ */ Object.create(null);
801
+ const localProviders = /* @__PURE__ */ new Set();
802
+ for (const [provider, profile] of Object.entries(raw.profiles || {})) {
803
+ Object.defineProperty(profiles, provider, { value: profile, enumerable: true, configurable: true, writable: true });
804
+ localProviders.add(provider);
805
+ }
806
+ const catalogs = [];
807
+ const remoteOwnerByProvider = /* @__PURE__ */ new Map();
808
+ for (const remote of remotes) {
809
+ const credential = process.env[remote.apiKeyEnv];
810
+ if (!credential) continue;
811
+ const fingerprint = credentialFingerprint(modelsPath, remote, credential);
812
+ if (!fingerprint) continue;
813
+ const cache = readRemoteCache(modelsPath, remote, fingerprint, activeRemoteSecrets);
814
+ if (!cache) continue;
815
+ const owner = remoteIdentityDigest(remote);
816
+ const candidates = Object.entries(cache.payload.profiles || {}).filter(([provider]) => !localProviders.has(provider));
817
+ if (candidates.some(([provider]) => {
818
+ const existing = remoteOwnerByProvider.get(provider);
819
+ return existing !== void 0 && existing !== owner;
820
+ })) continue;
821
+ for (const [provider, profile] of candidates) {
822
+ if (!Object.prototype.hasOwnProperty.call(profiles, provider)) {
823
+ Object.defineProperty(profiles, provider, { value: profile, enumerable: true, configurable: true, writable: true });
824
+ }
825
+ remoteOwnerByProvider.set(provider, owner);
826
+ }
827
+ catalogs.push({ ...remote, payloadSha256: cache.payloadSha256 });
828
+ }
829
+ return { config: { ...raw, profiles }, remoteCatalogs: catalogs.sort((a, b) => a.id.localeCompare(b.id)) };
830
+ }
831
+ function deepMergePlainRecords(base, patch) {
832
+ const result = isPlainRecord(base) ? { ...base } : {};
833
+ if (!isPlainRecord(patch)) return result;
834
+ for (const [key, value] of Object.entries(patch)) {
835
+ const current = result[key];
836
+ result[key] = isPlainRecord(current) && isPlainRecord(value) ? deepMergePlainRecords(current, value) : value;
837
+ }
838
+ return result;
839
+ }
840
+ function validateModelOverrides(value) {
841
+ if (value === void 0) return;
842
+ if (!isPlainRecord(value)) throw new Error("models.json modelOverrides must be an object");
843
+ for (const [key, override] of Object.entries(value)) {
844
+ if (!/^[^\s/]+\/[^\s/]+$/.test(key)) throw new Error(`models.json modelOverrides key must be "provider/modelId": ${key}`);
845
+ if (!isPlainRecord(override)) throw new Error(`models.json modelOverrides["${key}"] must be an object`);
846
+ assertOnlyKeys(override, [...MODEL_OVERRIDE_KEYS], `models.json modelOverrides["${key}"]`);
847
+ if (override.name !== void 0 && (typeof override.name !== "string" || !override.name.trim())) throw new Error(`models.json modelOverrides["${key}"].name must be a non-empty string`);
848
+ if (override.displayName !== void 0 && (typeof override.displayName !== "string" || !override.displayName.trim())) throw new Error(`models.json modelOverrides["${key}"].displayName must be a non-empty string`);
849
+ if (override.reasoning !== void 0 && typeof override.reasoning !== "boolean") throw new Error(`models.json modelOverrides["${key}"].reasoning must be a boolean`);
850
+ if (override.input !== void 0 && (!Array.isArray(override.input) || override.input.length === 0 || override.input.some((kind) => !["text", "image", "audio", "video"].includes(String(kind))))) throw new Error(`models.json modelOverrides["${key}"].input is invalid`);
851
+ if (override.contextWindow !== void 0 && (!Number.isInteger(override.contextWindow) || Number(override.contextWindow) < 1)) throw new Error(`models.json modelOverrides["${key}"].contextWindow is invalid`);
852
+ if (override.maxTokens !== void 0 && (!Number.isInteger(override.maxTokens) || Number(override.maxTokens) < 1)) throw new Error(`models.json modelOverrides["${key}"].maxTokens is invalid`);
853
+ if (override.cost !== void 0) {
854
+ if (!isPlainRecord(override.cost)) throw new Error(`models.json modelOverrides["${key}"].cost must be an object`);
855
+ for (const field of ["input", "output", "cacheRead", "cacheWrite", "cacheWriteLong"]) {
856
+ if (override.cost[field] !== void 0 && (typeof override.cost[field] !== "number" || !Number.isFinite(override.cost[field]) || override.cost[field] < 0)) throw new Error(`models.json modelOverrides["${key}"].cost.${field} must be a non-negative finite number`);
857
+ }
858
+ }
859
+ if (override.headers !== void 0) {
860
+ if (!isPlainRecord(override.headers)) throw new Error(`models.json modelOverrides["${key}"].headers must be an object`);
861
+ for (const [headerName, headerValue] of Object.entries(override.headers)) {
862
+ if (typeof headerValue !== "string") throw new Error(`models.json modelOverrides["${key}"].headers.${headerName} must be a string`);
863
+ }
864
+ }
865
+ validateTransport(override.transport, `Model override "${key}"`);
866
+ validateCompat(override.compat, `models.json modelOverrides["${key}"].compat`);
867
+ validateCacheCapability(override.cacheCapability, `models.json modelOverrides["${key}"].cacheCapability`);
868
+ validateWebSearchCapability(override.webSearch, `models.json modelOverrides["${key}"].webSearch`);
869
+ validateFileCapabilities(override.fileCapabilities, `models.json modelOverrides["${key}"].fileCapabilities`);
870
+ }
871
+ }
872
+ function validateProfileEndpoints(profile, label) {
873
+ if (profile.endpoints === void 0) return;
874
+ if (!isPlainRecord(profile.endpoints)) throw new Error(`${label} endpoints must be an object`);
875
+ for (const [api, value] of Object.entries(profile.endpoints)) {
876
+ if (!SUPPORTED_REMOTE_APIS.has(api)) throw new Error(`${label} endpoints has unsupported api ${api}`);
877
+ try {
878
+ if (typeof value !== "string") throw new Error("invalid URL");
879
+ const endpoint = new URL(value);
880
+ if (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") throw new Error("unsupported protocol");
881
+ } catch {
882
+ throw new Error(`${label} endpoints.${api} must be an absolute HTTP(S) URL`);
883
+ }
884
+ }
885
+ }
886
+ function resolveProfileRoute(profile, model) {
887
+ const api = model.api ?? profile.api;
888
+ if (!SUPPORTED_REMOTE_APIS.has(api)) throw new Error(`Model "${model.id}" has unsupported api ${api}`);
889
+ const endpoint = profile.endpoints?.[api];
890
+ if (model.api !== void 0 && endpoint === void 0 && api !== profile.api) {
891
+ throw new Error(`Model "${model.id}" api ${api} requires profile endpoints.${api} (otherwise api must equal profile api)`);
892
+ }
893
+ return { api, baseUrl: endpoint ?? profile.baseUrl };
894
+ }
895
+ function validateProfileConfig(profileId, profileConfig) {
896
+ if (!isPlainRecord(profileConfig)) throw new Error(`Profile "${profileId}" must be an object.`);
897
+ assertOnlyKeys(profileConfig, [
898
+ "baseUrl",
899
+ "endpoints",
900
+ "api",
901
+ "apiKey",
902
+ "apiKeyEnv",
903
+ "headers",
904
+ "displayName",
905
+ "filePlatform",
906
+ "attachmentPlatform",
907
+ "transport",
908
+ "compat",
909
+ "cacheCapability",
910
+ "webSearch",
911
+ "fileCapabilities",
912
+ "models"
913
+ ], `Profile "${profileId}"`);
914
+ const missing = [];
915
+ if (!profileConfig.api) missing.push("api");
916
+ if (!profileConfig.baseUrl) missing.push("baseUrl");
917
+ if (!Array.isArray(profileConfig.models) || profileConfig.models.length === 0) missing.push("models");
918
+ const hasProfileKeySource = Boolean(profileConfig.apiKey || profileConfig.apiKeyEnv);
919
+ const hasModelKeySource = Boolean(
920
+ (profileConfig.models || []).some((model) => Boolean(model.apiKeyEnv))
921
+ );
922
+ if (!hasProfileKeySource && !hasModelKeySource) missing.push("apiKey or apiKeyEnv");
923
+ if (missing.length > 0) {
924
+ throw new Error(
925
+ `Profile "${profileId}" is missing required field${missing.length > 1 ? "s" : ""}: ${missing.join(", ")}.`
926
+ );
927
+ }
928
+ for (const field of ["baseUrl", "api", "apiKey", "displayName", "filePlatform", "attachmentPlatform"]) {
929
+ assertOptionalString(profileConfig[field], `Profile "${profileId}" ${field}`);
930
+ }
931
+ assertOptionalEnvName(profileConfig.apiKeyEnv, `Profile "${profileId}" apiKeyEnv`);
932
+ if (!SUPPORTED_REMOTE_APIS.has(profileConfig.api)) throw new Error(`Profile "${profileId}" has unsupported api ${profileConfig.api}`);
933
+ try {
934
+ const endpoint = new URL(profileConfig.baseUrl);
935
+ if (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") throw new Error("unsupported protocol");
936
+ } catch {
937
+ throw new Error(`Profile "${profileId}" baseUrl must be an absolute HTTP(S) URL`);
938
+ }
939
+ validateProfileEndpoints(profileConfig, `Profile "${profileId}"`);
940
+ assertHeadersShape(profileConfig.headers, `Profile "${profileId}"`);
941
+ validateTransport(profileConfig.transport, `Profile "${profileId}"`);
942
+ validateCompat(profileConfig.compat, `Profile "${profileId}" compat`);
943
+ validateCacheCapability(profileConfig.cacheCapability, `Profile "${profileId}" cacheCapability`);
944
+ validateWebSearchCapability(profileConfig.webSearch, `Profile "${profileId}" webSearch`);
945
+ validateFileCapabilities(profileConfig.fileCapabilities, `Profile "${profileId}" fileCapabilities`);
946
+ const seenModelIds = /* @__PURE__ */ new Set();
947
+ for (const [index, modelConfig] of (profileConfig.models || []).entries()) {
948
+ if (!isPlainRecord(modelConfig)) throw new Error(`Profile "${profileId}" model #${index} must be an object.`);
949
+ assertOnlyKeys(modelConfig, [
950
+ "id",
951
+ "api",
952
+ "name",
953
+ "reasoning",
954
+ "input",
955
+ "cost",
956
+ "contextWindow",
957
+ "maxTokens",
958
+ "transport",
959
+ "compat",
960
+ "cacheCapability",
961
+ "webSearch",
962
+ "fileCapabilities",
963
+ "headers",
964
+ "apiKeyEnv",
965
+ "displayName",
966
+ "filePlatform",
967
+ "attachmentPlatform"
968
+ ], `Profile "${profileId}" model #${index}`);
969
+ const modelMissing = [];
970
+ if (!modelConfig.id) modelMissing.push("id");
971
+ if (!Array.isArray(modelConfig.input) || modelConfig.input.length === 0) modelMissing.push("input");
972
+ if (!modelConfig.cost) modelMissing.push("cost");
973
+ if (!modelConfig.contextWindow) modelMissing.push("contextWindow");
974
+ if (!modelConfig.maxTokens) modelMissing.push("maxTokens");
975
+ if (modelMissing.length > 0) {
976
+ const label = modelConfig.id || `#${index}`;
977
+ throw new Error(
978
+ `Profile "${profileId}" model "${label}" is missing required field${modelMissing.length > 1 ? "s" : ""}: ${modelMissing.join(", ")}.`
979
+ );
980
+ }
981
+ validateRemoteModel(profileId, modelConfig);
982
+ resolveProfileRoute(profileConfig, modelConfig);
983
+ assertHeadersShape(modelConfig.headers, `Profile "${profileId}" model "${modelConfig.id}"`);
984
+ assertOptionalEnvName(modelConfig.apiKeyEnv, `Profile "${profileId}" model "${modelConfig.id}" apiKeyEnv`);
985
+ if (seenModelIds.has(modelConfig.id)) throw new Error(`Profile "${profileId}" contains duplicate model "${modelConfig.id}".`);
986
+ seenModelIds.add(modelConfig.id);
987
+ }
988
+ }
989
+ var ModelRegistry = class {
990
+ models = /* @__PURE__ */ new Map();
991
+ loadError;
992
+ authStorage;
993
+ modelsPath;
994
+ configDefaults;
995
+ modelOrder = [];
996
+ modelOverrides = {};
997
+ extensionOAuthProviders = /* @__PURE__ */ new Map();
998
+ usingExternalProviders = false;
999
+ localProfileIds = /* @__PURE__ */ new Set();
1000
+ remoteCredentialEnvByProvider = /* @__PURE__ */ new Map();
1001
+ remoteCatalogByProvider = /* @__PURE__ */ new Map();
1002
+ remoteCredentialFingerprintByCatalog = /* @__PURE__ */ new Map();
1003
+ constructor(authStorage, modelsPath = path.join(getConfigDir(), "models.json")) {
1004
+ this.authStorage = authStorage;
1005
+ this.modelsPath = modelsPath;
1006
+ this.load();
1007
+ }
1008
+ upsert(model) {
1009
+ let providerModels = this.models.get(model.provider);
1010
+ if (!providerModels) {
1011
+ providerModels = /* @__PURE__ */ new Map();
1012
+ this.models.set(model.provider, providerModels);
1013
+ }
1014
+ const key = `${model.provider}/${model.id}`;
1015
+ if (!providerModels.has(model.id) && !this.modelOrder.includes(key)) {
1016
+ this.modelOrder.push(key);
1017
+ }
1018
+ providerModels.set(model.id, model);
1019
+ }
1020
+ load() {
1021
+ this.loadError = void 0;
1022
+ this.models.clear();
1023
+ this.modelOrder = [];
1024
+ this.modelOverrides = {};
1025
+ this.configDefaults = void 0;
1026
+ this.usingExternalProviders = false;
1027
+ this.localProfileIds.clear();
1028
+ this.remoteCredentialEnvByProvider.clear();
1029
+ this.remoteCatalogByProvider.clear();
1030
+ this.remoteCredentialFingerprintByCatalog.clear();
1031
+ try {
1032
+ pruneLegacyRemoteCatalogCaches(this.modelsPath);
1033
+ } catch (error) {
1034
+ this.loadError = error instanceof Error ? error.message : String(error);
1035
+ return;
1036
+ }
1037
+ if (!fs.existsSync(this.modelsPath)) {
1038
+ return;
1039
+ }
1040
+ try {
1041
+ const raw = JSON.parse(fs.readFileSync(this.modelsPath, "utf-8"));
1042
+ if (raw && typeof raw === "object" && "providers" in raw) {
1043
+ throw new Error('Legacy models.json format is no longer supported. Use top-level "profiles".');
1044
+ }
1045
+ validateModelsDocumentShape(raw);
1046
+ const remotes = validatedRemoteCatalogs(raw.remoteCatalogs);
1047
+ this.modelOverrides = raw.modelOverrides ?? {};
1048
+ const activeRemoteSecrets = configuredRemoteCredentialValues(raw);
1049
+ scrubActiveSecretsFromRemoteCaches(this.modelsPath, activeRemoteSecrets);
1050
+ const configuredProviders = Object.entries(raw.profiles || {});
1051
+ this.localProfileIds = new Set(configuredProviders.map(([provider]) => provider));
1052
+ const hasConfiguredProviders = configuredProviders.length > 0;
1053
+ this.configDefaults = raw.defaults ? {
1054
+ provider: raw.defaults.provider,
1055
+ modelId: raw.defaults.modelId,
1056
+ modelClasses: raw.defaults.modelClasses,
1057
+ toolModels: raw.defaults.toolModels
1058
+ } : void 0;
1059
+ this.usingExternalProviders = hasConfiguredProviders;
1060
+ for (const [configuredProvider, providerConfig] of configuredProviders) {
1061
+ const provider = configuredProvider;
1062
+ validateProfileConfig(provider, providerConfig);
1063
+ if (providerConfig.apiKey) {
1064
+ this.authStorage.setProviderApiKey(provider, providerConfig.apiKey);
1065
+ }
1066
+ if (providerConfig.apiKeyEnv) {
1067
+ this.authStorage.setProviderEnvVar(
1068
+ provider,
1069
+ providerConfig.apiKeyEnv
1070
+ );
1071
+ }
1072
+ const existing = this.models.get(provider);
1073
+ if (existing && (providerConfig.baseUrl || providerConfig.api || providerConfig.headers || providerConfig.transport)) {
1074
+ for (const model of existing.values()) {
1075
+ this.upsert({
1076
+ ...model,
1077
+ baseUrl: providerConfig.baseUrl || model.baseUrl,
1078
+ api: providerConfig.api || model.api,
1079
+ transport: providerConfig.transport ?? model.transport,
1080
+ apiKeyEnv: providerConfig.apiKeyEnv || model.apiKeyEnv,
1081
+ displayName: providerConfig.displayName || model.displayName || provider,
1082
+ filePlatform: providerConfig.filePlatform || model.filePlatform,
1083
+ attachmentPlatform: providerConfig.attachmentPlatform || model.attachmentPlatform,
1084
+ cacheCapability: providerConfig.cacheCapability || model.cacheCapability,
1085
+ webSearch: providerConfig.webSearch || model.webSearch,
1086
+ fileCapabilities: providerConfig.fileCapabilities || model.fileCapabilities,
1087
+ headers: providerConfig.headers ? { ...model.headers, ...providerConfig.headers } : model.headers
1088
+ });
1089
+ }
1090
+ }
1091
+ for (const customModel of providerConfig.models || []) {
1092
+ const baseModel = existing?.get(customModel.id);
1093
+ this.upsert({
1094
+ id: customModel.id,
1095
+ name: customModel.name || baseModel?.name || customModel.id,
1096
+ ...resolveProfileRoute(providerConfig, customModel),
1097
+ provider,
1098
+ reasoning: customModel.reasoning ?? baseModel?.reasoning ?? false,
1099
+ input: customModel.input || baseModel?.input || ["text"],
1100
+ cost: customModel.cost || baseModel?.cost || { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1101
+ contextWindow: customModel.contextWindow || baseModel?.contextWindow || 128e3,
1102
+ maxTokens: customModel.maxTokens || baseModel?.maxTokens || 8192,
1103
+ apiKeyEnv: customModel.apiKeyEnv || providerConfig.apiKeyEnv || baseModel?.apiKeyEnv,
1104
+ displayName: customModel.displayName || providerConfig.displayName || baseModel?.displayName || provider,
1105
+ filePlatform: customModel.filePlatform || providerConfig.filePlatform || baseModel?.filePlatform,
1106
+ attachmentPlatform: customModel.attachmentPlatform || providerConfig.attachmentPlatform || baseModel?.attachmentPlatform,
1107
+ headers: providerConfig.headers ? { ...baseModel?.headers, ...providerConfig.headers, ...customModel.headers } : customModel.headers || baseModel?.headers,
1108
+ transport: customModel.transport ?? providerConfig.transport ?? baseModel?.transport,
1109
+ compat: customModel.compat || providerConfig.compat || baseModel?.compat,
1110
+ cacheCapability: customModel.cacheCapability || providerConfig.cacheCapability || baseModel?.cacheCapability,
1111
+ webSearch: customModel.webSearch || providerConfig.webSearch || baseModel?.webSearch,
1112
+ fileCapabilities: customModel.fileCapabilities || providerConfig.fileCapabilities || baseModel?.fileCapabilities
1113
+ });
1114
+ }
1115
+ }
1116
+ for (const identity of remotes) {
1117
+ const credential = process.env[identity.apiKeyEnv];
1118
+ if (!credential) continue;
1119
+ const fingerprint = credentialFingerprint(this.modelsPath, identity, credential);
1120
+ if (!fingerprint) continue;
1121
+ const cached = readRemoteCache(this.modelsPath, identity, fingerprint, activeRemoteSecrets);
1122
+ if (!cached) continue;
1123
+ const owner = remoteIdentityDigest(identity);
1124
+ this.remoteCredentialFingerprintByCatalog.set(owner, fingerprint);
1125
+ const candidates = Object.entries(cached.payload.profiles || {}).filter(([provider]) => !this.localProfileIds.has(provider));
1126
+ if (candidates.some(([provider]) => {
1127
+ const existing = this.remoteCatalogByProvider.get(provider);
1128
+ return existing !== void 0 && existing !== owner;
1129
+ })) continue;
1130
+ for (const [provider, profile] of candidates) {
1131
+ this.registerRemoteProfile(provider, profile, identity.apiKeyEnv, owner);
1132
+ }
1133
+ }
1134
+ this.applyModelOverrides();
1135
+ } catch (error) {
1136
+ this.loadError = error instanceof Error ? error.message : String(error);
1137
+ }
1138
+ }
1139
+ /**
1140
+ * Re-apply models.json modelOverrides after any (re)materialization pass
1141
+ * (initial load, remote catalog refresh). Overrides patch descriptive
1142
+ * fields only; nested plain objects deep-merge, arrays/scalars replace.
1143
+ */
1144
+ applyModelOverrides() {
1145
+ for (const [key, override] of Object.entries(this.modelOverrides)) {
1146
+ const slash = key.indexOf("/");
1147
+ if (slash <= 0) continue;
1148
+ const provider = key.slice(0, slash);
1149
+ const modelId = key.slice(slash + 1);
1150
+ const existing = this.models.get(provider)?.get(modelId);
1151
+ if (!existing) continue;
1152
+ const patched = { ...existing };
1153
+ if (override.name !== void 0) patched.name = override.name;
1154
+ if (override.displayName !== void 0) patched.displayName = override.displayName;
1155
+ if (override.reasoning !== void 0) patched.reasoning = override.reasoning;
1156
+ if (override.input !== void 0) patched.input = [...override.input];
1157
+ if (override.contextWindow !== void 0) patched.contextWindow = override.contextWindow;
1158
+ if (override.maxTokens !== void 0) patched.maxTokens = override.maxTokens;
1159
+ if (override.cost !== void 0) patched.cost = { ...existing.cost, ...override.cost };
1160
+ if (override.headers !== void 0) patched.headers = { ...existing.headers, ...override.headers };
1161
+ if (override.transport !== void 0) patched.transport = override.transport;
1162
+ if (override.compat !== void 0) patched.compat = deepMergePlainRecords(existing.compat, override.compat);
1163
+ if (override.cacheCapability !== void 0) patched.cacheCapability = { ...existing.cacheCapability, ...override.cacheCapability };
1164
+ if (override.webSearch !== void 0) patched.webSearch = { ...existing.webSearch, ...override.webSearch };
1165
+ if (override.fileCapabilities !== void 0) patched.fileCapabilities = deepMergePlainRecords(existing.fileCapabilities, override.fileCapabilities);
1166
+ this.upsert(patched);
1167
+ }
1168
+ }
1169
+ registerRemoteProfile(provider, providerConfig, credentialEnv, catalogId) {
1170
+ if (this.localProfileIds.has(provider)) return;
1171
+ const existingCatalog = this.remoteCatalogByProvider.get(provider);
1172
+ if (existingCatalog && existingCatalog !== catalogId) {
1173
+ throw new Error(`remote profile "${provider}" is already owned by catalog "${existingCatalog}"`);
1174
+ }
1175
+ validateProfileConfig(provider, providerConfig);
1176
+ this.remoteCatalogByProvider.set(provider, catalogId);
1177
+ this.remoteCredentialEnvByProvider.set(provider, credentialEnv);
1178
+ this.authStorage.setProviderEnvVar(provider, credentialEnv);
1179
+ for (const customModel of providerConfig.models || []) {
1180
+ this.upsert({
1181
+ id: customModel.id,
1182
+ name: customModel.name || customModel.id,
1183
+ ...resolveProfileRoute(providerConfig, customModel),
1184
+ provider,
1185
+ reasoning: customModel.reasoning ?? false,
1186
+ input: customModel.input || ["text"],
1187
+ cost: customModel.cost || { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1188
+ contextWindow: customModel.contextWindow || 128e3,
1189
+ maxTokens: customModel.maxTokens || 8192,
1190
+ apiKeyEnv: credentialEnv,
1191
+ displayName: customModel.displayName || providerConfig.displayName || provider,
1192
+ filePlatform: customModel.filePlatform || providerConfig.filePlatform,
1193
+ attachmentPlatform: customModel.attachmentPlatform || providerConfig.attachmentPlatform,
1194
+ headers: { ...providerConfig.headers, ...customModel.headers },
1195
+ transport: customModel.transport ?? providerConfig.transport,
1196
+ compat: customModel.compat || providerConfig.compat,
1197
+ cacheCapability: customModel.cacheCapability || providerConfig.cacheCapability,
1198
+ webSearch: customModel.webSearch || providerConfig.webSearch,
1199
+ fileCapabilities: customModel.fileCapabilities || providerConfig.fileCapabilities
1200
+ });
1201
+ }
1202
+ this.usingExternalProviders = true;
1203
+ }
1204
+ removeRemoteProvider(provider, catalogId) {
1205
+ if (this.remoteCatalogByProvider.get(provider) !== catalogId) return;
1206
+ this.models.delete(provider);
1207
+ this.modelOrder = this.modelOrder.filter((key) => !key.startsWith(`${provider}/`));
1208
+ this.remoteCatalogByProvider.delete(provider);
1209
+ this.remoteCredentialEnvByProvider.delete(provider);
1210
+ }
1211
+ removeRemoteCatalogProfiles(catalogId) {
1212
+ for (const [provider, owner] of [...this.remoteCatalogByProvider]) {
1213
+ if (owner === catalogId) this.removeRemoteProvider(provider, catalogId);
1214
+ }
1215
+ this.usingExternalProviders = this.localProfileIds.size > 0 || this.remoteCatalogByProvider.size > 0;
1216
+ }
1217
+ replaceRemoteCatalogProfiles(catalogId, payload, credentialEnv) {
1218
+ const candidates = Object.entries(payload.profiles || {}).filter(([provider]) => !this.localProfileIds.has(provider));
1219
+ for (const [provider, profile] of candidates) {
1220
+ const owner = this.remoteCatalogByProvider.get(provider);
1221
+ if (owner && owner !== catalogId) throw new Error(`remote profile "${provider}" is already owned by another catalog identity`);
1222
+ validateProfileConfig(provider, profile);
1223
+ }
1224
+ this.removeRemoteCatalogProfiles(catalogId);
1225
+ for (const [provider, profile] of candidates) {
1226
+ this.registerRemoteProfile(provider, profile, credentialEnv, catalogId);
1227
+ }
1228
+ this.applyModelOverrides();
1229
+ }
1230
+ writeRemoteCache(remote, fingerprint, value) {
1231
+ const directory = safeRemoteCacheDirectory(this.modelsPath, true);
1232
+ const target = remoteCachePath(this.modelsPath, remote, fingerprint);
1233
+ if (fs.existsSync(target)) {
1234
+ const stat = fs.lstatSync(target);
1235
+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`remote catalog cache entry must be a regular file: ${target}`);
1236
+ }
1237
+ const temporary = path.join(directory, `.${path.basename(target)}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`);
1238
+ try {
1239
+ fs.writeFileSync(temporary, `${JSON.stringify(value)}
1240
+ `, { flag: "wx", mode: 384 });
1241
+ fs.renameSync(temporary, target);
1242
+ const tombstone = remoteCacheTombstonePath(this.modelsPath, remote, fingerprint);
1243
+ if (fs.existsSync(tombstone)) fs.unlinkSync(tombstone);
1244
+ } finally {
1245
+ if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
1246
+ }
1247
+ }
1248
+ refreshRemoteCatalogs() {
1249
+ const queueKey = path.resolve(this.modelsPath);
1250
+ const previous = remoteRefreshTails.get(queueKey) ?? Promise.resolve();
1251
+ const refresh = previous.then(() => this.performRemoteCatalogRefresh());
1252
+ const tail = refresh.catch(() => void 0);
1253
+ remoteRefreshTails.set(queueKey, tail);
1254
+ void tail.finally(() => {
1255
+ if (remoteRefreshTails.get(queueKey) === tail) remoteRefreshTails.delete(queueKey);
1256
+ });
1257
+ return refresh;
1258
+ }
1259
+ async performRemoteCatalogRefresh() {
1260
+ const releaseLock = await acquireRemoteRefreshLock(this.modelsPath);
1261
+ try {
1262
+ await this.performRemoteCatalogRefreshLocked();
1263
+ } finally {
1264
+ releaseLock();
1265
+ }
1266
+ }
1267
+ async performRemoteCatalogRefreshLocked() {
1268
+ try {
1269
+ pruneLegacyRemoteCatalogCaches(this.modelsPath);
1270
+ } catch (error) {
1271
+ this.loadError = error instanceof Error ? error.message : String(error);
1272
+ return;
1273
+ }
1274
+ if (!fs.existsSync(this.modelsPath)) {
1275
+ for (const owner of new Set(this.remoteCatalogByProvider.values())) this.removeRemoteCatalogProfiles(owner);
1276
+ this.remoteCredentialFingerprintByCatalog.clear();
1277
+ return;
1278
+ }
1279
+ let config;
1280
+ try {
1281
+ const decoded = JSON.parse(fs.readFileSync(this.modelsPath, "utf8"));
1282
+ validateModelsDocumentShape(decoded);
1283
+ config = decoded;
1284
+ } catch {
1285
+ for (const owner of new Set(this.remoteCatalogByProvider.values())) this.removeRemoteCatalogProfiles(owner);
1286
+ this.remoteCredentialFingerprintByCatalog.clear();
1287
+ return;
1288
+ }
1289
+ this.modelOverrides = config.modelOverrides ?? {};
1290
+ let remotes;
1291
+ try {
1292
+ remotes = validatedRemoteCatalogs(config.remoteCatalogs);
1293
+ } catch (error) {
1294
+ for (const owner of new Set(this.remoteCatalogByProvider.values())) this.removeRemoteCatalogProfiles(owner);
1295
+ this.remoteCredentialFingerprintByCatalog.clear();
1296
+ this.loadError = error instanceof Error ? error.message : String(error);
1297
+ return;
1298
+ }
1299
+ const activeOwners = new Set(remotes.map(remoteIdentityDigest));
1300
+ const activeRemoteSecrets = configuredRemoteCredentialValues(config);
1301
+ scrubActiveSecretsFromRemoteCaches(this.modelsPath, activeRemoteSecrets);
1302
+ for (const owner of new Set(this.remoteCatalogByProvider.values())) {
1303
+ if (!activeOwners.has(owner)) this.removeRemoteCatalogProfiles(owner);
1304
+ }
1305
+ for (const owner of [...this.remoteCredentialFingerprintByCatalog.keys()]) {
1306
+ if (!activeOwners.has(owner)) this.remoteCredentialFingerprintByCatalog.delete(owner);
1307
+ }
1308
+ for (const identity of remotes) {
1309
+ const remote = identity;
1310
+ const url = new URL(identity.url);
1311
+ const catalogOwner = remoteIdentityDigest(identity);
1312
+ const apiKey = process.env[remote.apiKeyEnv];
1313
+ if (!apiKey) {
1314
+ this.removeRemoteCatalogProfiles(catalogOwner);
1315
+ this.remoteCredentialFingerprintByCatalog.delete(catalogOwner);
1316
+ warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" unavailable: environment variable ${remote.apiKeyEnv} is not set`, activeRemoteSecrets);
1317
+ continue;
1318
+ }
1319
+ const fingerprint = credentialFingerprint(this.modelsPath, identity, apiKey, true);
1320
+ const previousFingerprint = this.remoteCredentialFingerprintByCatalog.get(catalogOwner);
1321
+ if (previousFingerprint && previousFingerprint !== fingerprint) {
1322
+ this.removeRemoteCatalogProfiles(catalogOwner);
1323
+ this.remoteCredentialFingerprintByCatalog.delete(catalogOwner);
1324
+ }
1325
+ const cached = readRemoteCache(this.modelsPath, identity, fingerprint, activeRemoteSecrets);
1326
+ let payload = cached?.payload;
1327
+ let response;
1328
+ try {
1329
+ const headers = { Authorization: `Bearer ${apiKey}` };
1330
+ if (cached?.etag) headers["If-None-Match"] = cached.etag;
1331
+ response = await fetch(url, {
1332
+ headers,
1333
+ redirect: "manual",
1334
+ signal: AbortSignal.timeout(3e3)
1335
+ });
1336
+ } catch (error) {
1337
+ if (!payload) {
1338
+ warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" unavailable: ${safeRemoteError(error, activeRemoteSecrets)}`, activeRemoteSecrets);
1339
+ continue;
1340
+ }
1341
+ warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" using cached data after a transient fetch failure: ${safeRemoteError(error, activeRemoteSecrets)}`, activeRemoteSecrets);
1342
+ }
1343
+ if (response) {
1344
+ if (response.status === 304 && payload && cached?.etag && (!response.headers.get("etag") || response.headers.get("etag") === cached.etag)) {
1345
+ } else if (response.ok) {
1346
+ try {
1347
+ const contentLength = Number(response.headers.get("content-length") || 0);
1348
+ if (contentLength > MAX_REMOTE_CATALOG_BYTES) throw new Error("catalog response is too large");
1349
+ const text = await readResponseTextBounded(response, MAX_REMOTE_CATALOG_BYTES);
1350
+ const decoded = JSON.parse(text);
1351
+ const etag = response.headers.get("etag") || void 0;
1352
+ assertNoSecretSubstrings({ etag, payload: decoded }, activeRemoteSecrets, "remote catalog response");
1353
+ payload = sanitizeRemotePayload(decoded, identity, url);
1354
+ const envelope = {
1355
+ version: REMOTE_CATALOG_CACHE_VERSION,
1356
+ identity,
1357
+ credentialFingerprint: fingerprint,
1358
+ etag,
1359
+ payload,
1360
+ payloadSha256: payloadDigest(payload)
1361
+ };
1362
+ this.writeRemoteCache(identity, fingerprint, envelope);
1363
+ } catch (error) {
1364
+ this.removeRemoteCatalogProfiles(catalogOwner);
1365
+ this.remoteCredentialFingerprintByCatalog.delete(catalogOwner);
1366
+ removeRemoteCache(this.modelsPath, identity, fingerprint);
1367
+ warnRemoteCatalog(`[Config] Rejecting invalid remote catalog "${remote.id}": ${safeRemoteError(error, activeRemoteSecrets)}`, activeRemoteSecrets);
1368
+ continue;
1369
+ }
1370
+ } else if (response.status === 408 || response.status === 429 || response.status >= 500) {
1371
+ if (!payload) {
1372
+ warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" unavailable: HTTP ${response.status}`, activeRemoteSecrets);
1373
+ continue;
1374
+ }
1375
+ warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" using cached data after transient HTTP ${response.status}`, activeRemoteSecrets);
1376
+ } else {
1377
+ this.removeRemoteCatalogProfiles(catalogOwner);
1378
+ this.remoteCredentialFingerprintByCatalog.delete(catalogOwner);
1379
+ removeRemoteCache(this.modelsPath, identity, fingerprint);
1380
+ warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" rejected: HTTP ${response.status}`, activeRemoteSecrets);
1381
+ continue;
1382
+ }
1383
+ }
1384
+ if (!payload) continue;
1385
+ try {
1386
+ this.replaceRemoteCatalogProfiles(catalogOwner, payload, identity.apiKeyEnv);
1387
+ this.remoteCredentialFingerprintByCatalog.set(catalogOwner, fingerprint);
1388
+ } catch (error) {
1389
+ this.removeRemoteCatalogProfiles(catalogOwner);
1390
+ this.remoteCredentialFingerprintByCatalog.delete(catalogOwner);
1391
+ removeRemoteCache(this.modelsPath, identity, fingerprint);
1392
+ warnRemoteCatalog(`[Config] Ignoring conflicting remote catalog "${remote.id}": ${safeRemoteError(error, activeRemoteSecrets)}`, activeRemoteSecrets);
1393
+ }
1394
+ }
1395
+ }
1396
+ getConfigDefaults() {
1397
+ return this.configDefaults;
1398
+ }
1399
+ resolveConfiguredRoute(purpose, route) {
1400
+ if (!route?.provider || !route?.modelId) return void 0;
1401
+ const requiredCapability = requiredCapabilityForToolPurpose(purpose);
1402
+ const model = this.find(route.provider, route.modelId);
1403
+ if (!model) {
1404
+ return {
1405
+ purpose,
1406
+ requiredCapability,
1407
+ routeSource: "unavailable",
1408
+ fallbackReason: `models.json defaults.toolModels.${purpose} points to missing model ${route.provider}/${route.modelId}`
1409
+ };
1410
+ }
1411
+ if (!modelSupportsToolPurpose(model, purpose)) {
1412
+ return {
1413
+ purpose,
1414
+ requiredCapability,
1415
+ routeSource: "unavailable",
1416
+ model,
1417
+ fallbackReason: `models.json defaults.toolModels.${purpose} points to ${model.provider}/${model.id}, but it does not declare ${requiredCapability} capability`
1418
+ };
1419
+ }
1420
+ const apiKey = this.getApiKey(model);
1421
+ if (!apiKey) {
1422
+ return {
1423
+ purpose,
1424
+ requiredCapability,
1425
+ routeSource: "unavailable",
1426
+ model,
1427
+ fallbackReason: `no API key available for models.json defaults.toolModels.${purpose} (${model.provider}/${model.id})`
1428
+ };
1429
+ }
1430
+ return { purpose, requiredCapability, routeSource: "explicit", model, apiKey };
1431
+ }
1432
+ resolveToolModel(purpose, currentModel) {
1433
+ return this.resolveToolModelCandidates(purpose, currentModel)[0] ?? {
1434
+ purpose,
1435
+ requiredCapability: requiredCapabilityForToolPurpose(purpose),
1436
+ routeSource: "unavailable",
1437
+ fallbackReason: `No configured model declares ${requiredCapabilityForToolPurpose(purpose)} capability for ${purpose}.`
1438
+ };
1439
+ }
1440
+ resolveToolModelCandidates(purpose, currentModel) {
1441
+ const requiredCapability = requiredCapabilityForToolPurpose(purpose);
1442
+ const candidates = [];
1443
+ const seen = /* @__PURE__ */ new Set();
1444
+ const add = (decision) => {
1445
+ if (!decision) return;
1446
+ if (!decision.model) {
1447
+ if (decision.routeSource === "unavailable") candidates.push(decision);
1448
+ return;
1449
+ }
1450
+ const key = `${decision.model.provider}/${decision.model.id}`;
1451
+ if (seen.has(key)) return;
1452
+ seen.add(key);
1453
+ candidates.push(decision);
1454
+ };
1455
+ const explicit = this.resolveConfiguredRoute(purpose, this.configDefaults?.toolModels?.[purpose]);
1456
+ add(explicit);
1457
+ if (currentModel && modelSupportsToolPurpose(currentModel, purpose)) {
1458
+ const apiKey = this.getApiKey(currentModel);
1459
+ if (apiKey) {
1460
+ add({ purpose, requiredCapability, routeSource: "current_model", model: currentModel, apiKey });
1461
+ }
1462
+ }
1463
+ const modelClassCandidates = [];
1464
+ for (const modelClass of MODEL_CLASS_FALLBACK_ORDER) {
1465
+ const resolved = this.resolveModelClass(modelClass);
1466
+ if (resolved.model && resolved.apiKey && modelSupportsToolPurpose(resolved.model, purpose)) {
1467
+ modelClassCandidates.push({
1468
+ purpose,
1469
+ requiredCapability,
1470
+ routeSource: "model_class",
1471
+ model: resolved.model,
1472
+ apiKey: resolved.apiKey
1473
+ });
1474
+ }
1475
+ }
1476
+ for (const decision of sortToolModelCandidatesByCapability(purpose, modelClassCandidates)) add(decision);
1477
+ const configuredCandidates = [];
1478
+ for (const model of this.getAllInConfigOrder()) {
1479
+ if (!modelSupportsToolPurpose(model, purpose)) continue;
1480
+ const apiKey = this.getApiKey(model);
1481
+ if (!apiKey) continue;
1482
+ configuredCandidates.push({ purpose, requiredCapability, routeSource: "configured_model", model, apiKey });
1483
+ }
1484
+ for (const decision of sortToolModelCandidatesByCapability(purpose, configuredCandidates)) add(decision);
1485
+ if (candidates.some((candidate) => candidate.model)) {
1486
+ return candidates.filter((candidate) => candidate.model);
1487
+ }
1488
+ return candidates.length > 0 ? candidates : [{
1489
+ purpose,
1490
+ requiredCapability,
1491
+ routeSource: "unavailable",
1492
+ fallbackReason: `No configured model declares ${requiredCapability} capability for ${purpose}.`
1493
+ }];
1494
+ }
1495
+ validateExplicitToolModelRoutes() {
1496
+ const routes = this.configDefaults?.toolModels || {};
1497
+ const results = [];
1498
+ for (const purpose of Object.keys(routes)) {
1499
+ const decision = this.resolveConfiguredRoute(purpose, routes[purpose]);
1500
+ if (decision) results.push(decision);
1501
+ }
1502
+ return results;
1503
+ }
1504
+ resolveModelClass(modelClass) {
1505
+ const configured = this.configDefaults?.modelClasses?.[modelClass];
1506
+ if (!configured?.provider || !configured?.modelId) {
1507
+ return { fallbackReason: `models.json defaults.modelClasses.${modelClass} is not configured` };
1508
+ }
1509
+ const model = this.find(configured.provider, configured.modelId);
1510
+ if (!model) {
1511
+ return { fallbackReason: `models.json defaults.modelClasses.${modelClass} points to missing model ${configured.provider}/${configured.modelId}` };
1512
+ }
1513
+ const apiKey = this.getApiKey(model);
1514
+ if (!apiKey) {
1515
+ return { model, fallbackReason: `no API key available for model class ${modelClass} (${configured.provider}/${configured.modelId})` };
1516
+ }
1517
+ return { model, apiKey };
1518
+ }
1519
+ /** Resolve an explicit model reference for user-requested overrides.
1520
+ * Accepts "provider/model-id" (exact lookup) or a bare model id (only
1521
+ * when it matches exactly one configured model). Never guesses across
1522
+ * providers; ambiguity and missing keys are reported as fallback reasons. */
1523
+ resolveModelRef(ref) {
1524
+ const trimmed = ref.trim();
1525
+ if (!trimmed) {
1526
+ return { fallbackReason: "empty model reference" };
1527
+ }
1528
+ const separator = trimmed.indexOf("/");
1529
+ if (separator >= 0) {
1530
+ if (separator === 0 || separator === trimmed.length - 1) {
1531
+ return { fallbackReason: `invalid model reference "${trimmed}"; expected provider/model-id` };
1532
+ }
1533
+ const provider = trimmed.slice(0, separator);
1534
+ const modelId = trimmed.slice(separator + 1);
1535
+ const model2 = this.find(provider, modelId);
1536
+ if (!model2) {
1537
+ return { fallbackReason: `model "${trimmed}" is not configured` };
1538
+ }
1539
+ const apiKey2 = this.getApiKey(model2);
1540
+ if (!apiKey2) {
1541
+ return { model: model2, fallbackReason: `no API key available for model "${trimmed}"` };
1542
+ }
1543
+ return { model: model2, apiKey: apiKey2 };
1544
+ }
1545
+ const matches = this.getAll().filter((model2) => model2.id === trimmed);
1546
+ if (matches.length === 0) {
1547
+ return { fallbackReason: `model "${trimmed}" is not configured; use provider/model-id` };
1548
+ }
1549
+ if (matches.length > 1) {
1550
+ return { fallbackReason: `model "${trimmed}" is ambiguous across providers (${matches.map((model2) => `${model2.provider}/${model2.id}`).join(", ")}); use provider/model-id` };
1551
+ }
1552
+ const model = matches[0];
1553
+ const apiKey = this.getApiKey(model);
1554
+ if (!apiKey) {
1555
+ return { model, fallbackReason: `no API key available for model "${model.provider}/${model.id}"` };
1556
+ }
1557
+ return { model, apiKey };
1558
+ }
1559
+ hasExternalProviderConfig() {
1560
+ return this.usingExternalProviders;
1561
+ }
1562
+ getLoadError() {
1563
+ return this.loadError;
1564
+ }
1565
+ find(provider, modelId) {
1566
+ return this.models.get(provider)?.get(modelId);
1567
+ }
1568
+ getAll() {
1569
+ const all = [];
1570
+ for (const providerModels of this.models.values()) {
1571
+ all.push(...providerModels.values());
1572
+ }
1573
+ return all.sort((a, b) => `${a.provider}/${a.id}`.localeCompare(`${b.provider}/${b.id}`));
1574
+ }
1575
+ getAllInConfigOrder() {
1576
+ const ordered = [];
1577
+ const seen = /* @__PURE__ */ new Set();
1578
+ for (const key of this.modelOrder) {
1579
+ const [provider, ...modelParts] = key.split("/");
1580
+ const modelId = modelParts.join("/");
1581
+ const model = this.find(provider, modelId);
1582
+ if (!model) continue;
1583
+ ordered.push(model);
1584
+ seen.add(key);
1585
+ }
1586
+ for (const model of this.getAll()) {
1587
+ const key = `${model.provider}/${model.id}`;
1588
+ if (!seen.has(key)) ordered.push(model);
1589
+ }
1590
+ return ordered;
1591
+ }
1592
+ getAvailable() {
1593
+ return this.getAll().filter((model) => !!this.getApiKey(model));
1594
+ }
1595
+ getByProvider(provider) {
1596
+ return [...this.models.get(provider)?.values() || []].sort((a, b) => a.id.localeCompare(b.id));
1597
+ }
1598
+ listAvailableModels() {
1599
+ return this.getAll().map((model) => `${model.provider}/${model.id}`);
1600
+ }
1601
+ getApiKey(model) {
1602
+ const remoteEnv = this.remoteCredentialEnvByProvider.get(model.provider);
1603
+ if (remoteEnv) return typeof process !== "undefined" ? process.env?.[remoteEnv] : void 0;
1604
+ return this.authStorage.getApiKey(model.provider, model.apiKeyEnv);
1605
+ }
1606
+ getApiKeyForProvider(provider) {
1607
+ const remoteEnv = this.remoteCredentialEnvByProvider.get(provider);
1608
+ if (remoteEnv) return typeof process !== "undefined" ? process.env?.[remoteEnv] : void 0;
1609
+ return this.authStorage.getApiKey(provider);
1610
+ }
1611
+ /**
1612
+ * Register a provider at runtime (extension API). Not persisted to
1613
+ * models.json: runtime registrations live for the process unless the
1614
+ * extension registers them again. Returns an unregister handle that
1615
+ * restores the provider's previous state (models, order, env binding).
1616
+ *
1617
+ * When the provider already exists (local profile or remote catalog),
1618
+ * models are merged by id: registered models upsert over existing entries
1619
+ * with the same id; existing entries not named in `config.models` survive.
1620
+ * baseUrl/api/headers patch every model of that provider (existing and
1621
+ * new) when provided.
1622
+ */
1623
+ registerProvider(provider, config) {
1624
+ validateExtensionProviderConfig(provider, config);
1625
+ const previousModels = this.models.get(provider) ? new Map(this.models.get(provider)) : void 0;
1626
+ const previousOrder = [...this.modelOrder];
1627
+ const previousEnvVar = this.authStorage.getProviderEnvVar(provider);
1628
+ if (config.apiKey) {
1629
+ this.authStorage.setRuntimeApiKey(provider, config.apiKey);
1630
+ }
1631
+ if (config.apiKeyEnv) {
1632
+ this.authStorage.setProviderEnvVar(provider, config.apiKeyEnv);
1633
+ }
1634
+ const existing = this.models.get(provider);
1635
+ if (existing && (config.baseUrl || config.api || config.headers || config.transport)) {
1636
+ for (const model of existing.values()) {
1637
+ this.upsert({
1638
+ ...model,
1639
+ baseUrl: config.baseUrl || model.baseUrl,
1640
+ api: config.api || model.api,
1641
+ transport: config.transport ?? model.transport,
1642
+ headers: config.headers ? { ...model.headers, ...config.headers } : model.headers
1643
+ });
1644
+ }
1645
+ }
1646
+ for (const customModel of config.models ?? []) {
1647
+ const baseModel = this.models.get(provider)?.get(customModel.id);
1648
+ this.upsert({
1649
+ id: customModel.id,
1650
+ name: customModel.name || baseModel?.name || customModel.id,
1651
+ api: config.api || baseModel?.api || "openai-completions",
1652
+ provider,
1653
+ baseUrl: config.baseUrl || baseModel?.baseUrl || "",
1654
+ reasoning: customModel.reasoning ?? baseModel?.reasoning ?? false,
1655
+ input: customModel.input || baseModel?.input || ["text"],
1656
+ cost: customModel.cost || baseModel?.cost || { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1657
+ contextWindow: customModel.contextWindow || baseModel?.contextWindow || 128e3,
1658
+ maxTokens: customModel.maxTokens || baseModel?.maxTokens || 8192,
1659
+ apiKeyEnv: config.apiKeyEnv || baseModel?.apiKeyEnv,
1660
+ displayName: customModel.displayName || baseModel?.displayName || provider,
1661
+ headers: config.headers ? { ...baseModel?.headers, ...config.headers, ...customModel.headers } : customModel.headers || baseModel?.headers,
1662
+ transport: customModel.transport ?? config.transport ?? baseModel?.transport,
1663
+ compat: customModel.compat || baseModel?.compat,
1664
+ cacheCapability: customModel.cacheCapability || baseModel?.cacheCapability,
1665
+ webSearch: customModel.webSearch || baseModel?.webSearch,
1666
+ fileCapabilities: customModel.fileCapabilities || baseModel?.fileCapabilities
1667
+ });
1668
+ }
1669
+ this.applyModelOverrides();
1670
+ this.usingExternalProviders = true;
1671
+ const registeredOAuth = config.oauth;
1672
+ if (registeredOAuth) this.extensionOAuthProviders.set(provider, registeredOAuth);
1673
+ return () => {
1674
+ if (previousModels) this.models.set(provider, previousModels);
1675
+ else this.models.delete(provider);
1676
+ this.modelOrder = previousOrder;
1677
+ this.authStorage.setRuntimeApiKey(provider, void 0);
1678
+ this.authStorage.setProviderEnvVar(provider, previousEnvVar);
1679
+ if (registeredOAuth) this.extensionOAuthProviders.delete(provider);
1680
+ this.applyModelOverrides();
1681
+ };
1682
+ }
1683
+ /** OAuth flow declared by an extension-registered provider, if any. */
1684
+ getExtensionOAuth(provider) {
1685
+ return this.extensionOAuthProviders.get(provider);
1686
+ }
1687
+ /**
1688
+ * Restore persisted OAuth credentials now that extensions have registered
1689
+ * their providers: refresh expired tokens when the extension declares
1690
+ * refreshToken, and drop the runtime binding when a token cannot be
1691
+ * recovered (getApiKey then reports the provider as unauthenticated).
1692
+ * Never throws; returns per-provider outcomes for the host to surface.
1693
+ */
1694
+ async restorePersistedOAuth() {
1695
+ const authStorage = this.authStorage;
1696
+ const results = [];
1697
+ for (const provider of authStorage.getOAuthProviderNames()) {
1698
+ const credentials = authStorage.getOAuthCredentials(provider);
1699
+ if (!credentials?.access) continue;
1700
+ const expired = credentials.expires !== void 0 && credentials.expires <= Date.now() + OAUTH_RESTORE_LEEWAY_MS;
1701
+ if (!expired) continue;
1702
+ const oauth = this.extensionOAuthProviders.get(provider);
1703
+ if (!oauth?.refreshToken || !credentials.refresh) {
1704
+ authStorage.setRuntimeApiKey(provider, void 0);
1705
+ results.push({ provider, action: "not-refreshable", detail: "token expired and no refresh flow" });
1706
+ continue;
1707
+ }
1708
+ try {
1709
+ const next = await withTimeout(
1710
+ oauth.refreshToken({
1711
+ access: credentials.access,
1712
+ refresh: credentials.refresh,
1713
+ expires: credentials.expires
1714
+ }),
1715
+ OAUTH_REFRESH_TIMEOUT_MS,
1716
+ `${provider} refreshToken timed out after ${OAUTH_REFRESH_TIMEOUT_MS}ms`
1717
+ );
1718
+ const merged = { ...credentials, ...next };
1719
+ authStorage.setOAuthCredentials(provider, merged);
1720
+ authStorage.setRuntimeApiKey(provider, merged.access);
1721
+ results.push({ provider, action: "refreshed" });
1722
+ } catch (error) {
1723
+ authStorage.setRuntimeApiKey(provider, void 0);
1724
+ results.push({ provider, action: "refresh-failed", detail: error instanceof Error ? error.message : String(error) });
1725
+ }
1726
+ }
1727
+ return results;
1728
+ }
1729
+ /** Credential store backing this registry (for OAuth persistence). */
1730
+ getAuthStorage() {
1731
+ return this.authStorage;
1732
+ }
1733
+ };
1734
+
1735
+ export {
1736
+ assertNoSecretSubstrings,
1737
+ configuredRemoteCredentialValues,
1738
+ loadResolvedModelsConfig,
1739
+ ModelRegistry
1740
+ };