@cydm/pie 4.13.0 → 4.14.0

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 (33) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +4 -4
  2. package/dist/builtin/extensions/im-forward/index.js +8099 -8101
  3. package/dist/builtin/extensions/mcp-adapter/index.js +86 -81
  4. package/dist/builtin/extensions/memory/index.js +30 -7
  5. package/dist/builtin/extensions/pie-ipc/index.js +13 -18
  6. package/dist/builtin/extensions/pie-proc/index.js +69 -60
  7. package/dist/builtin/extensions/plan-mode/index.js +4 -4
  8. package/dist/builtin/extensions/subagent/index.js +6 -5
  9. package/dist/builtin/extensions/todo/index.js +4 -4
  10. package/dist/chunks/{chunk-BQWHLYYZ.js → chunk-26KRUYZH.js} +1 -1
  11. package/dist/chunks/{chunk-5MCIBDAM.js → chunk-BOQIGMGQ.js} +38 -93
  12. package/dist/chunks/{chunk-AKC7NMP4.js → chunk-EZZTMDWZ.js} +887 -391
  13. package/dist/chunks/{chunk-5PCLBIOO.js → chunk-FD3KBPDR.js} +110 -75
  14. package/dist/chunks/{chunk-NOSNHMA2.js → chunk-IK2FR2YF.js} +2 -1
  15. package/dist/chunks/{chunk-SXBX2P5R.js → chunk-JJH77AUU.js} +1709 -1577
  16. package/dist/chunks/{chunk-OGGL6LUN.js → chunk-JKO42HZW.js} +1 -1
  17. package/dist/chunks/{chunk-3CJLYX5J.js → chunk-KGWKRO7Z.js} +2 -2
  18. package/dist/chunks/{chunk-G2K4GY6N.js → chunk-MCR4JYI6.js} +103 -12
  19. package/dist/chunks/{chunk-IZ4DYCJ7.js → chunk-UYDS75SI.js} +810 -726
  20. package/dist/chunks/{host-image-fallback-MZK633DK.js → host-image-fallback-LPHB5CTL.js} +1 -1
  21. package/dist/chunks/{manager-cli-OTIMAWO6.js → manager-cli-ZV36YNPJ.js} +187 -173
  22. package/dist/chunks/{memory-git-Q3UBYOJ4.js → memory-git-ZJN6SPIU.js} +5 -5
  23. package/dist/chunks/{model-registry-QNEPISBJ.js → model-registry-GLBIUOJR.js} +2 -2
  24. package/dist/chunks/{read-file-understanding-KCJMSOS7.js → read-file-understanding-DFJPTTSB.js} +5 -5
  25. package/dist/chunks/{src-TIDKYA5F.js → src-76Q33OY5.js} +1 -1
  26. package/dist/chunks/{src-D5GN4Q5O.js → src-ALHMJZ5R.js} +2 -2
  27. package/dist/chunks/{src-7MZZJVOG.js → src-KZ7YID3I.js} +11 -3
  28. package/dist/chunks/{src-QI47K3W3.js → src-LEXKDSFV.js} +24 -6
  29. package/dist/chunks/{test-stream-JAJHK44G.js → test-stream-OVGDTXOY.js} +1 -1
  30. package/dist/cli.js +12910 -12631
  31. package/models.schema.json +12 -3
  32. package/package.json +1 -1
  33. package/dist/chunks/{chunk-3GG342QY.js → chunk-TYCKSYUF.js} +19 -19
@@ -13,12 +13,12 @@ import {
13
13
  modelSupportsToolPurpose,
14
14
  requiredCapabilityForToolPurpose,
15
15
  sortToolModelCandidatesByCapability
16
- } from "./chunk-G2K4GY6N.js";
16
+ } from "./chunk-MCR4JYI6.js";
17
17
 
18
18
  // src/core/model-registry.ts
19
- import * as fs from "fs";
20
- import * as path from "path";
21
- import { createHash, createHmac, randomBytes } from "node:crypto";
19
+ import * as fs2 from "fs";
20
+ import * as path2 from "path";
21
+ import { randomBytes as randomBytes2 } from "node:crypto";
22
22
 
23
23
  // src/core/model-registry-baseline.ts
24
24
  function cloneModelsMap(models) {
@@ -244,6 +244,74 @@ function mergeThinkingCapability(base, override, api, label = "thinking") {
244
244
  return merged;
245
245
  }
246
246
 
247
+ // src/core/model-class-config.ts
248
+ var MODEL_CLASS_NAMES = ["light", "balanced", "strong"];
249
+ var TOOL_MODEL_NAMES = [
250
+ "web_search",
251
+ "read_file.image",
252
+ "read_file.video",
253
+ "read_file.audio",
254
+ "read_file.document"
255
+ ];
256
+ function isPlainRecord2(value) {
257
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
258
+ }
259
+ function assertOnlyKeys(value, allowed, label) {
260
+ const allowedSet = new Set(allowed);
261
+ for (const key of Object.keys(value)) {
262
+ if (!allowedSet.has(key)) {
263
+ throw new Error(`${label} contains unsupported field "${key}"`);
264
+ }
265
+ }
266
+ }
267
+ function assertOptionalString(value, label) {
268
+ if (value !== void 0 && (typeof value !== "string" || !value)) {
269
+ throw new Error(`${label} must be a non-empty string`);
270
+ }
271
+ }
272
+ function validateRouteObject(route, label) {
273
+ if (!isPlainRecord2(route)) {
274
+ throw new Error(`${label} must be an object`);
275
+ }
276
+ assertOnlyKeys(route, ["provider", "modelId"], label);
277
+ assertOptionalString(route.provider, `${label}.provider`);
278
+ assertOptionalString(route.modelId, `${label}.modelId`);
279
+ }
280
+ function normalizeModelClassRoutes(entry) {
281
+ if (!entry) return [];
282
+ return Array.isArray(entry) ? entry : [entry];
283
+ }
284
+ function validateDefaultsModelClasses(routes) {
285
+ if (routes === void 0) return;
286
+ if (!isPlainRecord2(routes)) {
287
+ throw new Error("models.json defaults.modelClasses must be an object");
288
+ }
289
+ assertOnlyKeys(routes, MODEL_CLASS_NAMES, "models.json defaults.modelClasses");
290
+ for (const [routeName, route] of Object.entries(routes)) {
291
+ const label = `models.json defaults.modelClasses.${routeName}`;
292
+ if (Array.isArray(route)) {
293
+ if (route.length === 0) {
294
+ throw new Error(`${label} must not be an empty array`);
295
+ }
296
+ for (let i = 0; i < route.length; i++) {
297
+ validateRouteObject(route[i], `${label}[${i}]`);
298
+ }
299
+ } else {
300
+ validateRouteObject(route, label);
301
+ }
302
+ }
303
+ }
304
+ function validateDefaultsToolModels(routes) {
305
+ if (routes === void 0) return;
306
+ if (!isPlainRecord2(routes)) {
307
+ throw new Error("models.json defaults.toolModels must be an object");
308
+ }
309
+ assertOnlyKeys(routes, TOOL_MODEL_NAMES, "models.json defaults.toolModels");
310
+ for (const [routeName, route] of Object.entries(routes)) {
311
+ validateRouteObject(route, `models.json defaults.toolModels.${routeName}`);
312
+ }
313
+ }
314
+
247
315
  // src/core/voice-config-validation.ts
248
316
  var VOICE_CONFIG_KEYS = [
249
317
  "apiBaseUrl",
@@ -410,7 +478,7 @@ function validateGameUseConfig(value) {
410
478
  validateEndpoint(record.visualDecision, "models.json gameUse.visualDecision");
411
479
  }
412
480
 
413
- // src/core/model-registry.ts
481
+ // src/core/model-registry-config.ts
414
482
  var MODEL_OVERRIDE_KEYS = [
415
483
  "name",
416
484
  "reasoning",
@@ -449,29 +517,7 @@ function validateExtensionProviderConfig(provider, config) {
449
517
  validateFileCapabilities(model.fileCapabilities, `registerProvider("${provider}") model "${model.id}" fileCapabilities`);
450
518
  }
451
519
  }
452
- var REMOTE_CATALOG_CACHE_VERSION = 4;
453
520
  var SUPPORTED_REMOTE_APIS = /* @__PURE__ */ new Set(["openai-completions", "anthropic-messages", "openai-responses"]);
454
- var MAX_REMOTE_CATALOG_BYTES = 2 * 1024 * 1024;
455
- var OAUTH_RESTORE_LEEWAY_MS = 6e4;
456
- var OAUTH_REFRESH_TIMEOUT_MS = 3e4;
457
- function withTimeout(promise, ms, timeoutMessage) {
458
- return new Promise((resolve2, reject) => {
459
- const timer = setTimeout(() => reject(new Error(timeoutMessage)), ms);
460
- Promise.resolve(promise).then(
461
- (value) => {
462
- clearTimeout(timer);
463
- resolve2(value);
464
- },
465
- (error) => {
466
- clearTimeout(timer);
467
- reject(error);
468
- }
469
- );
470
- });
471
- }
472
- var REMOTE_REFRESH_LOCK_WAIT_MS = 6e4;
473
- var REMOTE_REFRESH_LOCK_WRITE_GRACE_MS = 1e3;
474
- var remoteRefreshTails = /* @__PURE__ */ new Map();
475
521
  var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
476
522
  "connection",
477
523
  "keep-alive",
@@ -484,603 +530,774 @@ var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
484
530
  "host",
485
531
  "content-length"
486
532
  ]);
487
- function canonicalRemote(remote) {
488
- const url = new URL(remote.url);
489
- return { id: remote.id, url: url.href, apiKeyEnv: remote.apiKeyEnv };
533
+ function isPlainRecord3(value) {
534
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
535
+ const prototype = Object.getPrototypeOf(value);
536
+ return prototype === Object.prototype || prototype === null;
490
537
  }
491
- function remoteIdentityDigest(remote) {
492
- return createHash("sha256").update(JSON.stringify({ version: REMOTE_CATALOG_CACHE_VERSION, ...canonicalRemote(remote) })).digest("hex");
538
+ function assertOnlyKeys2(value, allowed, label) {
539
+ const allowedSet = new Set(allowed);
540
+ const unexpected = Object.keys(value).find((key) => !allowedSet.has(key));
541
+ if (unexpected) throw new Error(`${label} contains unsupported field ${unexpected}`);
493
542
  }
494
- function remoteCacheDirectory(modelsPath) {
495
- return path.join(path.dirname(modelsPath), "cache", "remote-catalogs");
543
+ function validateRemoteCatalogConfig(value, label) {
544
+ if (!isPlainRecord3(value)) throw new Error(`${label} must be an object`);
545
+ assertOnlyKeys2(value, ["id", "url", "apiKeyEnv"], label);
546
+ 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`);
547
+ if (typeof value.url !== "string" || !value.url) throw new Error(`${label}.url must be a URL`);
548
+ 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`);
549
+ let url;
550
+ try {
551
+ url = new URL(value.url);
552
+ } catch {
553
+ throw new Error(`${label}.url must be an absolute URL`);
554
+ }
555
+ const localTestHost = url.hostname === "127.0.0.1" || url.hostname === "localhost";
556
+ if (url.protocol !== "https:" && !localTestHost) throw new Error(`${label}.url must use HTTPS`);
557
+ if (url.username || url.password) throw new Error(`${label}.url must not contain credentials`);
558
+ if (url.hash) throw new Error(`${label}.url must not contain a fragment`);
559
+ if (url.search) throw new Error(`${label}.url must not contain query parameters`);
560
+ return { id: value.id, url: url.href, apiKeyEnv: value.apiKeyEnv };
496
561
  }
497
- function safeRemoteCacheDirectory(modelsPath, create) {
498
- const configDirectory = path.dirname(modelsPath);
499
- if (!fs.existsSync(configDirectory)) {
500
- if (!create) return void 0;
501
- fs.mkdirSync(configDirectory, { recursive: true, mode: 448 });
562
+ function validatedRemoteCatalogs(value) {
563
+ if (value === void 0) return [];
564
+ if (!Array.isArray(value)) throw new Error("models.json remoteCatalogs must be an array");
565
+ if (value.length === 0) throw new Error("models.json remoteCatalogs must be a non-empty array");
566
+ const catalogs = value.map((item, index) => validateRemoteCatalogConfig(item, `models.json remoteCatalogs[${index}]`));
567
+ const ids = /* @__PURE__ */ new Set();
568
+ for (const catalog of catalogs) {
569
+ if (ids.has(catalog.id)) throw new Error(`models.json remoteCatalogs contains duplicate id ${catalog.id}`);
570
+ ids.add(catalog.id);
502
571
  }
503
- const configRoot = fs.realpathSync(configDirectory);
504
- const cacheRoot = path.join(configDirectory, "cache");
505
- const directory = remoteCacheDirectory(modelsPath);
506
- for (const candidate of [cacheRoot, directory]) {
507
- if (!fs.existsSync(candidate)) {
508
- if (!create) return void 0;
509
- fs.mkdirSync(candidate, { mode: 448 });
510
- }
511
- const stat = fs.lstatSync(candidate);
512
- if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error(`remote catalog cache path must be a real directory: ${candidate}`);
513
- const canonical = fs.realpathSync(candidate);
514
- const relative2 = path.relative(configRoot, canonical);
515
- if (relative2 === ".." || relative2.startsWith(`..${path.sep}`) || path.isAbsolute(relative2)) {
516
- throw new Error(`remote catalog cache path escapes the config directory: ${candidate}`);
517
- }
518
- try {
519
- fs.chmodSync(candidate, 448);
520
- } catch {
572
+ return catalogs;
573
+ }
574
+ function validateModelsDocumentShape(value) {
575
+ if (!isPlainRecord3(value)) throw new Error("models.json must be an object");
576
+ assertOnlyKeys2(value, ["$schema", "profiles", "remoteCatalogs", "defaults", "modelOverrides", "voice", "gameUse"], "models.json");
577
+ if (value.$schema !== void 0 && (typeof value.$schema !== "string" || !value.$schema)) throw new Error("models.json $schema must be a non-empty string");
578
+ const hasProfiles = Object.prototype.hasOwnProperty.call(value, "profiles");
579
+ const hasRemoteCatalogs = Object.prototype.hasOwnProperty.call(value, "remoteCatalogs");
580
+ if (!hasProfiles && !hasRemoteCatalogs) throw new Error("models.json must define profiles or remoteCatalogs");
581
+ validatedRemoteCatalogs(value.remoteCatalogs);
582
+ if (hasProfiles) {
583
+ if (!isPlainRecord3(value.profiles) || Object.keys(value.profiles).length === 0) throw new Error("models.json profiles must be a non-empty object");
584
+ for (const [profileId, profile] of Object.entries(value.profiles)) {
585
+ if (!profileId || profileId !== profileId.trim() || /\s/.test(profileId)) throw new Error(`models.json profile id is invalid: ${profileId}`);
586
+ validateProfileConfig(profileId, profile);
521
587
  }
522
588
  }
523
- return directory;
589
+ validateModelOverrides(value.modelOverrides);
590
+ validateVoiceConfig(value.voice);
591
+ validateGameUseConfig(value.gameUse);
592
+ if (value.defaults !== void 0) {
593
+ if (!isPlainRecord3(value.defaults)) throw new Error("models.json defaults must be an object");
594
+ assertOnlyKeys2(value.defaults, ["provider", "modelId", "modelClasses", "toolModels"], "models.json defaults");
595
+ assertOptionalString2(value.defaults.provider, "models.json defaults.provider");
596
+ assertOptionalString2(value.defaults.modelId, "models.json defaults.modelId");
597
+ validateDefaultsModelClasses(value.defaults.modelClasses);
598
+ validateDefaultsToolModels(value.defaults.toolModels);
599
+ }
524
600
  }
525
- function remoteRefreshLockPath(modelsPath) {
526
- return path.join(remoteCacheDirectory(modelsPath), ".refresh.lock");
601
+ function assertOptionalString2(value, label) {
602
+ if (value !== void 0 && (typeof value !== "string" || !value)) throw new Error(`${label} must be a non-empty string`);
527
603
  }
528
- function processIsAlive(pid) {
529
- if (!Number.isSafeInteger(pid) || pid <= 0) return false;
530
- try {
531
- process.kill(pid, 0);
532
- return true;
533
- } catch (error) {
534
- return error.code === "EPERM";
604
+ function assertOptionalEnvName(value, label) {
605
+ if (value !== void 0 && (typeof value !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value))) {
606
+ throw new Error(`${label} must be an environment variable name`);
535
607
  }
536
608
  }
537
- function remoteRefreshLockIsStale(lockPath) {
538
- const stat = fs.lstatSync(lockPath);
539
- if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`remote catalog refresh lock must be a regular file: ${lockPath}`);
540
- let owner;
541
- try {
542
- owner = JSON.parse(fs.readFileSync(lockPath, "utf8"));
543
- } catch {
544
- }
545
- const age = Date.now() - stat.mtimeMs;
546
- const validOwner = owner?.version === 1 && Number.isSafeInteger(owner.pid) && typeof owner.token === "string" && typeof owner.createdAt === "number";
547
- if (validOwner && processIsAlive(Number(owner.pid))) return false;
548
- return validOwner || age > REMOTE_REFRESH_LOCK_WRITE_GRACE_MS;
609
+ function assertOptionalBoolean(value, label) {
610
+ if (value !== void 0 && typeof value !== "boolean") throw new Error(`${label} must be a boolean`);
549
611
  }
550
- function sameFileIdentity(left, right, leftPath, rightPath) {
551
- if (left.dev !== right.dev || left.ino !== right.ino) return false;
552
- if (left.ino !== 0) return true;
553
- return left.size === right.size && fs.readFileSync(leftPath).equals(fs.readFileSync(rightPath));
612
+ function validateCacheCapability(value, label) {
613
+ if (value === void 0) return;
614
+ if (!isPlainRecord3(value) || !["none", "session_store", "prompt_cache", "usage_only"].includes(String(value.mode)) || typeof value.supported !== "boolean") throw new Error(`${label} is invalid`);
615
+ assertOnlyKeys2(value, ["mode", "supported", "supportsUsageMetrics", "description"], label);
616
+ assertOptionalBoolean(value.supportsUsageMetrics, `${label}.supportsUsageMetrics`);
617
+ assertOptionalString2(value.description, `${label}.description`);
554
618
  }
555
- function reclaimStaleRemoteRefreshLock(lockPath) {
556
- if (!remoteRefreshLockIsStale(lockPath)) return false;
557
- const claimPath = `${lockPath}.reclaim-${process.pid}-${randomBytes(8).toString("hex")}`;
558
- try {
559
- fs.linkSync(lockPath, claimPath);
560
- const claimed = fs.lstatSync(claimPath);
561
- const current = fs.lstatSync(lockPath);
562
- if (claimed.isSymbolicLink() || !claimed.isFile() || current.isSymbolicLink() || !current.isFile() || !sameFileIdentity(claimed, current, claimPath, lockPath)) return false;
563
- if (!remoteRefreshLockIsStale(claimPath)) return false;
564
- fs.unlinkSync(lockPath);
565
- return true;
566
- } catch (error) {
567
- if (["ENOENT", "EEXIST"].includes(error.code ?? "")) return false;
568
- throw error;
569
- } finally {
570
- try {
571
- fs.unlinkSync(claimPath);
572
- } catch {
573
- }
619
+ function validateWebSearchCapability(value, label) {
620
+ if (value === void 0) return;
621
+ if (!isPlainRecord3(value) || !["anthropic_server_tool", "chat_completions_web_search", "openai_responses"].includes(String(value.type))) {
622
+ throw new Error(`${label} is invalid`);
574
623
  }
624
+ assertOnlyKeys2(value, ["type", "forceToolChoice", "searchEngine", "count", "contentSize"], label);
625
+ assertOptionalBoolean(value.forceToolChoice, `${label}.forceToolChoice`);
626
+ assertOptionalString2(value.searchEngine, `${label}.searchEngine`);
627
+ if (value.count !== void 0 && (!Number.isInteger(value.count) || Number(value.count) < 1)) throw new Error(`${label}.count is invalid`);
628
+ if (value.contentSize !== void 0 && !["low", "medium", "high"].includes(String(value.contentSize))) throw new Error(`${label}.contentSize is invalid`);
575
629
  }
576
- async function acquireRemoteRefreshLock(modelsPath) {
577
- const directory = safeRemoteCacheDirectory(modelsPath, true);
578
- const lockPath = remoteRefreshLockPath(modelsPath);
579
- const deadline = Date.now() + REMOTE_REFRESH_LOCK_WAIT_MS;
580
- while (true) {
581
- const token = randomBytes(16).toString("hex");
582
- try {
583
- const fd = fs.openSync(lockPath, "wx", 384);
584
- try {
585
- fs.writeFileSync(fd, `${JSON.stringify({ version: 1, pid: process.pid, token, createdAt: Date.now() })}
586
- `);
587
- } finally {
588
- fs.closeSync(fd);
589
- }
590
- return () => {
591
- try {
592
- const stat = fs.lstatSync(lockPath);
593
- if (stat.isSymbolicLink() || !stat.isFile()) return;
594
- const current = JSON.parse(fs.readFileSync(lockPath, "utf8"));
595
- if (current.token === token) fs.unlinkSync(lockPath);
596
- } catch {
597
- }
598
- };
599
- } catch (error) {
600
- if (error.code !== "EEXIST") throw error;
601
- try {
602
- if (reclaimStaleRemoteRefreshLock(lockPath)) continue;
603
- } catch (lockError) {
604
- if (lockError.code === "ENOENT") continue;
605
- throw lockError;
630
+ function validateFileCapabilities(value, label) {
631
+ if (value === void 0) return;
632
+ if (!isPlainRecord3(value)) throw new Error(`${label} is invalid`);
633
+ for (const [kind, capability] of Object.entries(value)) {
634
+ if (!["image", "video", "audio", "document"].includes(kind)) throw new Error(`${label}.${kind} is unsupported`);
635
+ if (typeof capability === "boolean") continue;
636
+ if (!isPlainRecord3(capability)) throw new Error(`${label}.${kind} is invalid`);
637
+ assertOnlyKeys2(capability, ["supported", "formats", "maxFileSizeMb", "maxDurationSeconds", "nativeInline"], `${label}.${kind}`);
638
+ assertOptionalBoolean(capability.supported, `${label}.${kind}.supported`);
639
+ assertOptionalBoolean(capability.nativeInline, `${label}.${kind}.nativeInline`);
640
+ if (capability.formats !== void 0 && (!Array.isArray(capability.formats) || capability.formats.some((item) => typeof item !== "string" || !item))) {
641
+ throw new Error(`${label}.${kind}.formats is invalid`);
642
+ }
643
+ if (Array.isArray(capability.formats) && new Set(capability.formats).size !== capability.formats.length) {
644
+ throw new Error(`${label}.${kind}.formats contains duplicates`);
645
+ }
646
+ for (const field of ["maxFileSizeMb", "maxDurationSeconds"]) {
647
+ if (capability[field] !== void 0 && (typeof capability[field] !== "number" || !Number.isFinite(capability[field]) || capability[field] <= 0)) {
648
+ throw new Error(`${label}.${kind}.${field} is invalid`);
606
649
  }
607
- if (Date.now() >= deadline) throw new Error(`timed out waiting for remote catalog refresh lock: ${lockPath}`);
608
- await new Promise((resolve2) => setTimeout(resolve2, 25));
609
650
  }
610
651
  }
611
652
  }
612
- function readSafeRemoteCacheFile(directory, filepath) {
613
- const stat = fs.lstatSync(filepath);
614
- if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`remote catalog cache entry must be a regular file: ${filepath}`);
615
- const canonicalDirectory = fs.realpathSync(directory);
616
- const canonicalFile = fs.realpathSync(filepath);
617
- const relative2 = path.relative(canonicalDirectory, canonicalFile);
618
- if (!relative2 || relative2 === ".." || relative2.startsWith(`..${path.sep}`) || path.isAbsolute(relative2)) {
619
- throw new Error(`remote catalog cache entry escapes its cache directory: ${filepath}`);
620
- }
621
- return fs.readFileSync(filepath);
653
+ function validateTransport(value, label) {
654
+ if (value !== void 0 && value !== "sse" && value !== "websocket" && value !== "auto") throw new Error(`${label}.transport is invalid`);
622
655
  }
623
- function credentialNamespaceKey(modelsPath, create) {
624
- const directory = safeRemoteCacheDirectory(modelsPath, create);
625
- if (!directory) return void 0;
626
- const keyPath = path.join(directory, ".credential-namespace-key");
627
- if (!fs.existsSync(keyPath) && !create) return void 0;
628
- if (create && !fs.existsSync(keyPath)) {
629
- try {
630
- fs.writeFileSync(keyPath, randomBytes(32), { flag: "wx", mode: 384 });
631
- } catch (error) {
632
- if (!isPlainRecord2(error) || error.code !== "EEXIST") throw error;
633
- }
656
+ function validateCompat(value, label) {
657
+ if (value === void 0) return;
658
+ if (!isPlainRecord3(value)) throw new Error(`${label} is invalid`);
659
+ assertOnlyKeys2(value, [
660
+ "forcedReasoningEffort",
661
+ "store",
662
+ "supportsEncryptedReasoning",
663
+ "responsesContinuation",
664
+ "supportsReasoningSummary",
665
+ "reasoningSummary",
666
+ "timeoutReplay",
667
+ "supportsStore",
668
+ "supportsDeveloperRole",
669
+ "supportsReasoningEffort",
670
+ "supportsUsageInStreaming",
671
+ "maxTokensField",
672
+ "requiresToolResultName",
673
+ "requiresAssistantAfterToolResult",
674
+ "requiresThinkingAsText",
675
+ "supportsStrictMode",
676
+ "streamRequiresDone",
677
+ "streamRequiresFinishReason",
678
+ "cacheCapability"
679
+ ], label);
680
+ if (value.forcedReasoningEffort !== void 0 && value.forcedReasoningEffort !== "none") {
681
+ throw new Error(`${label}.forcedReasoningEffort must be "none"`);
634
682
  }
635
- const key = readSafeRemoteCacheFile(directory, keyPath);
636
- if (key.byteLength !== 32) throw new Error("remote catalog credential namespace key is invalid");
637
- try {
638
- fs.chmodSync(keyPath, 384);
639
- } catch {
683
+ if (value.reasoningSummary !== void 0 && !["auto", "concise", "detailed", "none"].includes(String(value.reasoningSummary))) {
684
+ throw new Error(`${label}.reasoningSummary must be auto | concise | detailed | none`);
640
685
  }
641
- return key;
686
+ for (const field of [
687
+ "store",
688
+ "supportsEncryptedReasoning",
689
+ "responsesContinuation",
690
+ "supportsReasoningSummary",
691
+ "timeoutReplay",
692
+ "supportsStore",
693
+ "supportsDeveloperRole",
694
+ "supportsReasoningEffort",
695
+ "supportsUsageInStreaming",
696
+ "requiresToolResultName",
697
+ "requiresAssistantAfterToolResult",
698
+ "requiresThinkingAsText",
699
+ "supportsStrictMode",
700
+ "streamRequiresDone",
701
+ "streamRequiresFinishReason"
702
+ ]) assertOptionalBoolean(value[field], `${label}.${field}`);
703
+ if (value.maxTokensField !== void 0 && value.maxTokensField !== "max_completion_tokens" && value.maxTokensField !== "max_tokens") {
704
+ throw new Error(`${label}.maxTokensField is invalid`);
705
+ }
706
+ validateCacheCapability(value.cacheCapability, `${label}.cacheCapability`);
642
707
  }
643
- function credentialFingerprint(modelsPath, remote, credential, create = false) {
644
- const key = credentialNamespaceKey(modelsPath, create);
645
- if (!key) return void 0;
646
- return createHmac("sha256", key).update(remoteIdentityDigest(remote)).update("\0").update(credential).digest("hex");
708
+ function validateRemoteModel(profileId, model) {
709
+ if (!isPlainRecord3(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`);
710
+ assertOnlyKeys2(model, [
711
+ "id",
712
+ "api",
713
+ "name",
714
+ "reasoning",
715
+ "thinking",
716
+ "input",
717
+ "cost",
718
+ "contextWindow",
719
+ "maxTokens",
720
+ "transport",
721
+ "compat",
722
+ "cacheCapability",
723
+ "webSearch",
724
+ "fileCapabilities",
725
+ "headers",
726
+ "apiKeyEnv",
727
+ "displayName",
728
+ "filePlatform",
729
+ "attachmentPlatform"
730
+ ], `Remote profile "${profileId}" model "${model.id}"`);
731
+ for (const field of ["name", "displayName", "filePlatform", "attachmentPlatform", "apiKeyEnv"]) {
732
+ assertOptionalString2(model[field], `Remote profile "${profileId}" model "${model.id}" ${field}`);
733
+ }
734
+ if (model.api !== void 0 && !SUPPORTED_REMOTE_APIS.has(model.api)) throw new Error(`Model "${model.id}" has unsupported api ${model.api}`);
735
+ assertOptionalBoolean(model.reasoning, `Remote profile "${profileId}" model "${model.id}" reasoning`);
736
+ if (!Array.isArray(model.input) || model.input.length === 0 || model.input.some((item) => !["text", "image", "audio", "video"].includes(item))) {
737
+ throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid input capabilities`);
738
+ }
739
+ if (!isPlainRecord3(model.cost)) throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid cost values`);
740
+ assertOnlyKeys2(model.cost, ["input", "output", "cacheRead", "cacheWrite", "cacheWriteLong"], `Remote profile "${profileId}" model "${model.id}" cost`);
741
+ const invalidRate = (value) => typeof value !== "number" || !Number.isFinite(value) || value < 0;
742
+ if ([model.cost.input, model.cost.output, model.cost.cacheRead, model.cost.cacheWrite].some(invalidRate) || model.cost.cacheWriteLong !== void 0 && invalidRate(model.cost.cacheWriteLong)) {
743
+ throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid cost values`);
744
+ }
745
+ if (!Number.isSafeInteger(model.contextWindow) || Number(model.contextWindow) <= 0 || !Number.isSafeInteger(model.maxTokens) || Number(model.maxTokens) <= 0 || Number(model.maxTokens) > Number(model.contextWindow)) {
746
+ throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid token limits`);
747
+ }
748
+ if (new Set(model.input).size !== model.input.length) throw new Error(`Remote profile "${profileId}" model "${model.id}" has duplicate input capabilities`);
749
+ validateTransport(model.transport, `Model "${model.id}"`);
750
+ validateCompat(model.compat, `Remote profile "${profileId}" model "${model.id}" compat`);
751
+ validateThinkingCapability(model.thinking, `Remote profile "${profileId}" model "${model.id}" thinking`);
752
+ validateCacheCapability(model.cacheCapability, `Remote profile "${profileId}" model "${model.id}" cacheCapability`);
753
+ validateWebSearchCapability(model.webSearch, `Remote profile "${profileId}" model "${model.id}" webSearch`);
754
+ validateFileCapabilities(model.fileCapabilities, `Remote profile "${profileId}" model "${model.id}" fileCapabilities`);
647
755
  }
648
- function remoteCachePath(modelsPath, remote, fingerprint) {
649
- return path.join(remoteCacheDirectory(modelsPath), `${remoteIdentityDigest(remote)}-${fingerprint}.json`);
756
+ function assertHeadersShape(headers, label) {
757
+ if (headers === void 0) return;
758
+ if (!isPlainRecord3(headers)) throw new Error(`${label} headers must be an object`);
759
+ for (const [name, value] of Object.entries(headers)) {
760
+ if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) throw new Error(`${label} header name ${name || "(empty)"} is invalid`);
761
+ if (typeof value !== "string") throw new Error(`${label} header ${name} must be a string`);
762
+ if (/[\0-\x08\x0A-\x1F\x7F]/.test(value)) throw new Error(`${label} header ${name} contains an invalid control character`);
763
+ }
650
764
  }
651
- function pruneLegacyRemoteCatalogCaches(modelsPath) {
652
- const directory = safeRemoteCacheDirectory(modelsPath, false);
653
- if (!directory) return;
654
- for (const name of fs.readdirSync(directory)) {
655
- if (!name.endsWith(".json")) continue;
656
- const filepath = path.join(directory, name);
657
- try {
658
- const value = JSON.parse(readSafeRemoteCacheFile(directory, filepath).toString("utf8"));
659
- if (value.version === REMOTE_CATALOG_CACHE_VERSION) continue;
660
- } catch {
661
- let stat;
662
- try {
663
- stat = fs.lstatSync(filepath);
664
- } catch {
665
- continue;
765
+ function assertRemoteHeadersSafe(headers, label) {
766
+ assertHeadersShape(headers, label);
767
+ for (const name of Object.keys(headers || {})) {
768
+ if (/(?:authorization|cookie|api[-_]?key|token|secret|credential)/i.test(name)) {
769
+ throw new Error(`${label} must not provide credential-bearing header ${name}`);
770
+ }
771
+ if (HOP_BY_HOP_HEADERS.has(name.toLowerCase())) throw new Error(`${label} must not provide transport header ${name}`);
772
+ }
773
+ }
774
+ function validateModelOverrides(value) {
775
+ if (value === void 0) return;
776
+ if (!isPlainRecord3(value)) throw new Error("models.json modelOverrides must be an object");
777
+ for (const [key, override] of Object.entries(value)) {
778
+ if (!/^[^\s/]+\/[^\s/]+$/.test(key)) throw new Error(`models.json modelOverrides key must be "provider/modelId": ${key}`);
779
+ if (!isPlainRecord3(override)) throw new Error(`models.json modelOverrides["${key}"] must be an object`);
780
+ assertOnlyKeys2(override, [...MODEL_OVERRIDE_KEYS], `models.json modelOverrides["${key}"]`);
781
+ 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`);
782
+ 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`);
783
+ if (override.reasoning !== void 0 && typeof override.reasoning !== "boolean") throw new Error(`models.json modelOverrides["${key}"].reasoning must be a boolean`);
784
+ 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`);
785
+ if (override.contextWindow !== void 0 && (!Number.isInteger(override.contextWindow) || Number(override.contextWindow) < 1)) throw new Error(`models.json modelOverrides["${key}"].contextWindow is invalid`);
786
+ if (override.maxTokens !== void 0 && (!Number.isInteger(override.maxTokens) || Number(override.maxTokens) < 1)) throw new Error(`models.json modelOverrides["${key}"].maxTokens is invalid`);
787
+ if (override.cost !== void 0) {
788
+ if (!isPlainRecord3(override.cost)) throw new Error(`models.json modelOverrides["${key}"].cost must be an object`);
789
+ for (const field of ["input", "output", "cacheRead", "cacheWrite", "cacheWriteLong"]) {
790
+ 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`);
666
791
  }
667
- if (stat.isSymbolicLink() || !stat.isFile()) continue;
668
792
  }
793
+ if (override.headers !== void 0) {
794
+ if (!isPlainRecord3(override.headers)) throw new Error(`models.json modelOverrides["${key}"].headers must be an object`);
795
+ for (const [headerName, headerValue] of Object.entries(override.headers)) {
796
+ if (typeof headerValue !== "string") throw new Error(`models.json modelOverrides["${key}"].headers.${headerName} must be a string`);
797
+ }
798
+ }
799
+ validateTransport(override.transport, `Model override "${key}"`);
800
+ validateCompat(override.compat, `models.json modelOverrides["${key}"].compat`);
801
+ validateThinkingCapability(override.thinking, `models.json modelOverrides["${key}"].thinking`);
802
+ validateCacheCapability(override.cacheCapability, `models.json modelOverrides["${key}"].cacheCapability`);
803
+ validateWebSearchCapability(override.webSearch, `models.json modelOverrides["${key}"].webSearch`);
804
+ validateFileCapabilities(override.fileCapabilities, `models.json modelOverrides["${key}"].fileCapabilities`);
805
+ }
806
+ }
807
+ function validateProfileEndpoints(profile, label) {
808
+ if (profile.endpoints === void 0) return;
809
+ if (!isPlainRecord3(profile.endpoints)) throw new Error(`${label} endpoints must be an object`);
810
+ for (const [api, value] of Object.entries(profile.endpoints)) {
811
+ if (!SUPPORTED_REMOTE_APIS.has(api)) throw new Error(`${label} endpoints has unsupported api ${api}`);
669
812
  try {
670
- fs.unlinkSync(filepath);
813
+ if (typeof value !== "string") throw new Error("invalid URL");
814
+ const endpoint = new URL(value);
815
+ if (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") throw new Error("unsupported protocol");
671
816
  } catch {
817
+ throw new Error(`${label} endpoints.${api} must be an absolute HTTP(S) URL`);
672
818
  }
673
819
  }
674
820
  }
675
- function scrubActiveSecretsFromRemoteCaches(modelsPath, activeSecrets) {
676
- if (activeSecrets.length === 0) return;
677
- const directory = safeRemoteCacheDirectory(modelsPath, false);
678
- if (!directory) return;
679
- const handle = fs.opendirSync(directory);
821
+ function resolveProfileRoute(profile, model) {
822
+ const api = model.api ?? profile.api;
823
+ if (!SUPPORTED_REMOTE_APIS.has(api)) throw new Error(`Model "${model.id}" has unsupported api ${api}`);
824
+ const endpoint = profile.endpoints?.[api];
825
+ if (model.api !== void 0 && endpoint === void 0 && api !== profile.api) {
826
+ throw new Error(`Model "${model.id}" api ${api} requires profile endpoints.${api} (otherwise api must equal profile api)`);
827
+ }
828
+ return { api, baseUrl: endpoint ?? profile.baseUrl };
829
+ }
830
+ function validateProfileConfig(profileId, profileConfig) {
831
+ if (!isPlainRecord3(profileConfig)) throw new Error(`Profile "${profileId}" must be an object.`);
832
+ assertOnlyKeys2(profileConfig, [
833
+ "baseUrl",
834
+ "endpoints",
835
+ "api",
836
+ "apiKey",
837
+ "apiKeyEnv",
838
+ "headers",
839
+ "displayName",
840
+ "filePlatform",
841
+ "attachmentPlatform",
842
+ "transport",
843
+ "compat",
844
+ "cacheCapability",
845
+ "thinking",
846
+ "webSearch",
847
+ "fileCapabilities",
848
+ "models"
849
+ ], `Profile "${profileId}"`);
850
+ const missing = [];
851
+ if (!profileConfig.api) missing.push("api");
852
+ if (!profileConfig.baseUrl) missing.push("baseUrl");
853
+ if (!Array.isArray(profileConfig.models) || profileConfig.models.length === 0) missing.push("models");
854
+ const hasProfileKeySource = Boolean(profileConfig.apiKey || profileConfig.apiKeyEnv);
855
+ const hasModelKeySource = Boolean(
856
+ (profileConfig.models || []).some((model) => Boolean(model.apiKeyEnv))
857
+ );
858
+ if (!hasProfileKeySource && !hasModelKeySource) missing.push("apiKey or apiKeyEnv");
859
+ if (missing.length > 0) {
860
+ throw new Error(
861
+ `Profile "${profileId}" is missing required field${missing.length > 1 ? "s" : ""}: ${missing.join(", ")}.`
862
+ );
863
+ }
864
+ for (const field of ["baseUrl", "api", "apiKey", "displayName", "filePlatform", "attachmentPlatform"]) {
865
+ assertOptionalString2(profileConfig[field], `Profile "${profileId}" ${field}`);
866
+ }
867
+ assertOptionalEnvName(profileConfig.apiKeyEnv, `Profile "${profileId}" apiKeyEnv`);
868
+ if (!SUPPORTED_REMOTE_APIS.has(profileConfig.api)) throw new Error(`Profile "${profileId}" has unsupported api ${profileConfig.api}`);
680
869
  try {
681
- let scanned = 0;
682
- while (true) {
683
- const entry = handle.readSync();
684
- if (!entry) break;
685
- if (++scanned > 1e4) throw new Error("remote catalog cache directory exceeds the hygiene scan limit");
686
- const isCache = entry.name.endsWith(".json");
687
- const isOrphanedTemporary = /^\..+\.json\.\d+\.[0-9a-f]+\.tmp$/.test(entry.name);
688
- if (!entry.isFile() || !isCache && !isOrphanedTemporary) continue;
689
- const filepath = path.join(directory, entry.name);
690
- try {
691
- const raw = readSafeRemoteCacheFile(directory, filepath).toString("utf8");
692
- assertNoSecretSubstrings(raw, activeSecrets, "remote catalog cache");
693
- } catch {
694
- try {
695
- const stat = fs.lstatSync(filepath);
696
- if (!stat.isSymbolicLink() && stat.isFile()) fs.unlinkSync(filepath);
697
- } catch {
698
- }
699
- }
870
+ const endpoint = new URL(profileConfig.baseUrl);
871
+ if (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") throw new Error("unsupported protocol");
872
+ } catch {
873
+ throw new Error(`Profile "${profileId}" baseUrl must be an absolute HTTP(S) URL`);
874
+ }
875
+ validateProfileEndpoints(profileConfig, `Profile "${profileId}"`);
876
+ assertHeadersShape(profileConfig.headers, `Profile "${profileId}"`);
877
+ validateTransport(profileConfig.transport, `Profile "${profileId}"`);
878
+ validateCompat(profileConfig.compat, `Profile "${profileId}" compat`);
879
+ validateCacheCapability(profileConfig.cacheCapability, `Profile "${profileId}" cacheCapability`);
880
+ validateWebSearchCapability(profileConfig.webSearch, `Profile "${profileId}" webSearch`);
881
+ validateFileCapabilities(profileConfig.fileCapabilities, `Profile "${profileId}" fileCapabilities`);
882
+ validateThinkingCapability(profileConfig.thinking, `Profile "${profileId}" thinking`);
883
+ const seenModelIds = /* @__PURE__ */ new Set();
884
+ for (const [index, modelConfig] of (profileConfig.models || []).entries()) {
885
+ if (!isPlainRecord3(modelConfig)) throw new Error(`Profile "${profileId}" model #${index} must be an object.`);
886
+ assertOnlyKeys2(modelConfig, [
887
+ "id",
888
+ "api",
889
+ "name",
890
+ "reasoning",
891
+ "thinking",
892
+ "input",
893
+ "cost",
894
+ "contextWindow",
895
+ "maxTokens",
896
+ "transport",
897
+ "compat",
898
+ "cacheCapability",
899
+ "webSearch",
900
+ "fileCapabilities",
901
+ "headers",
902
+ "apiKeyEnv",
903
+ "displayName",
904
+ "filePlatform",
905
+ "attachmentPlatform"
906
+ ], `Profile "${profileId}" model #${index}`);
907
+ const modelMissing = [];
908
+ if (!modelConfig.id) modelMissing.push("id");
909
+ if (!Array.isArray(modelConfig.input) || modelConfig.input.length === 0) modelMissing.push("input");
910
+ if (!modelConfig.cost) modelMissing.push("cost");
911
+ if (!modelConfig.contextWindow) modelMissing.push("contextWindow");
912
+ if (!modelConfig.maxTokens) modelMissing.push("maxTokens");
913
+ if (modelMissing.length > 0) {
914
+ const label = modelConfig.id || `#${index}`;
915
+ throw new Error(
916
+ `Profile "${profileId}" model "${label}" is missing required field${modelMissing.length > 1 ? "s" : ""}: ${modelMissing.join(", ")}.`
917
+ );
700
918
  }
701
- } finally {
702
- handle.closeSync();
919
+ validateRemoteModel(profileId, modelConfig);
920
+ const route = resolveProfileRoute(profileConfig, modelConfig);
921
+ validateThinkingCapabilityForApi(modelConfig.thinking ?? profileConfig.thinking, route.api, `Profile "${profileId}" model "${modelConfig.id}" thinking`);
922
+ assertHeadersShape(modelConfig.headers, `Profile "${profileId}" model "${modelConfig.id}"`);
923
+ assertOptionalEnvName(modelConfig.apiKeyEnv, `Profile "${profileId}" model "${modelConfig.id}" apiKeyEnv`);
924
+ if (seenModelIds.has(modelConfig.id)) throw new Error(`Profile "${profileId}" contains duplicate model "${modelConfig.id}".`);
925
+ seenModelIds.add(modelConfig.id);
703
926
  }
704
927
  }
705
- function payloadDigest(payload) {
706
- return createHash("sha256").update(JSON.stringify(payload)).digest("hex");
928
+
929
+ // src/core/model-registry-remote.ts
930
+ import * as fs from "fs";
931
+ import * as path from "path";
932
+ import { createHash, createHmac, randomBytes } from "node:crypto";
933
+ var REMOTE_CATALOG_CACHE_VERSION = 4;
934
+ var MAX_REMOTE_CATALOG_BYTES = 2 * 1024 * 1024;
935
+ var OAUTH_RESTORE_LEEWAY_MS = 6e4;
936
+ var OAUTH_REFRESH_TIMEOUT_MS = 3e4;
937
+ function withTimeout(promise, ms, timeoutMessage) {
938
+ return new Promise((resolve2, reject) => {
939
+ const timer = setTimeout(() => reject(new Error(timeoutMessage)), ms);
940
+ Promise.resolve(promise).then(
941
+ (value) => {
942
+ clearTimeout(timer);
943
+ resolve2(value);
944
+ },
945
+ (error) => {
946
+ clearTimeout(timer);
947
+ reject(error);
948
+ }
949
+ );
950
+ });
707
951
  }
708
- function assertNoSecretSubstrings(value, secrets, label) {
709
- const active = [...new Set(secrets.filter((secret) => secret.length > 0))];
710
- if (active.length === 0) return;
711
- const seen = /* @__PURE__ */ new Set();
712
- const visit = (candidate) => {
713
- if (typeof candidate === "string") {
714
- if (active.some((secret) => candidate.includes(secret))) throw new Error(`${label} reflects an active credential`);
715
- return;
952
+ var REMOTE_REFRESH_LOCK_WAIT_MS = 6e4;
953
+ var REMOTE_REFRESH_LOCK_WRITE_GRACE_MS = 1e3;
954
+ var remoteRefreshTails = /* @__PURE__ */ new Map();
955
+ function canonicalRemote(remote) {
956
+ const url = new URL(remote.url);
957
+ return { id: remote.id, url: url.href, apiKeyEnv: remote.apiKeyEnv };
958
+ }
959
+ function remoteIdentityDigest(remote) {
960
+ return createHash("sha256").update(JSON.stringify({ version: REMOTE_CATALOG_CACHE_VERSION, ...canonicalRemote(remote) })).digest("hex");
961
+ }
962
+ function remoteCacheDirectory(modelsPath) {
963
+ return path.join(path.dirname(modelsPath), "cache", "remote-catalogs");
964
+ }
965
+ function safeRemoteCacheDirectory(modelsPath, create) {
966
+ const configDirectory = path.dirname(modelsPath);
967
+ if (!fs.existsSync(configDirectory)) {
968
+ if (!create) return void 0;
969
+ fs.mkdirSync(configDirectory, { recursive: true, mode: 448 });
970
+ }
971
+ const configRoot = fs.realpathSync(configDirectory);
972
+ const cacheRoot = path.join(configDirectory, "cache");
973
+ const directory = remoteCacheDirectory(modelsPath);
974
+ for (const candidate of [cacheRoot, directory]) {
975
+ if (!fs.existsSync(candidate)) {
976
+ if (!create) return void 0;
977
+ fs.mkdirSync(candidate, { mode: 448 });
716
978
  }
717
- if (!candidate || typeof candidate !== "object" || seen.has(candidate)) return;
718
- seen.add(candidate);
719
- if (Array.isArray(candidate)) {
720
- for (const item of candidate) visit(item);
721
- return;
979
+ const stat = fs.lstatSync(candidate);
980
+ if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error(`remote catalog cache path must be a real directory: ${candidate}`);
981
+ const canonical = fs.realpathSync(candidate);
982
+ const relative2 = path.relative(configRoot, canonical);
983
+ if (relative2 === ".." || relative2.startsWith(`..${path.sep}`) || path.isAbsolute(relative2)) {
984
+ throw new Error(`remote catalog cache path escapes the config directory: ${candidate}`);
722
985
  }
723
- for (const [key, item] of Object.entries(candidate)) {
724
- visit(key);
725
- visit(item);
986
+ try {
987
+ fs.chmodSync(candidate, 448);
988
+ } catch {
726
989
  }
727
- };
728
- visit(value);
729
- const serialized = JSON.stringify(value);
730
- if (active.some((secret) => serialized.includes(secret))) throw new Error(`${label} reflects an active credential`);
731
- }
732
- function safeRemoteText(value, secrets) {
733
- let message = String(value);
734
- const active = [...new Set(secrets.filter(Boolean))];
735
- const replacement = active.some((secret) => "[REDACTED]".includes(secret)) ? "" : "[REDACTED]";
736
- for (const secret of active) message = message.split(secret).join(replacement);
737
- message = message.slice(0, 1024);
738
- if (!active.some((secret) => message.includes(secret))) return message;
739
- return "";
740
- }
741
- function safeRemoteError(error, secrets) {
742
- return safeRemoteText(error instanceof Error ? `${error.name}: ${error.message}` : String(error), secrets);
990
+ }
991
+ return directory;
743
992
  }
744
- function warnRemoteCatalog(message, secrets) {
745
- console.warn(safeRemoteText(message, secrets));
993
+ function remoteRefreshLockPath(modelsPath) {
994
+ return path.join(remoteCacheDirectory(modelsPath), ".refresh.lock");
746
995
  }
747
- function configuredRemoteCredentialValues(config) {
748
- let remotes;
996
+ function processIsAlive(pid) {
997
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
749
998
  try {
750
- remotes = validatedRemoteCatalogs(config.remoteCatalogs);
751
- } catch {
752
- return [];
999
+ process.kill(pid, 0);
1000
+ return true;
1001
+ } catch (error) {
1002
+ return error.code === "EPERM";
753
1003
  }
754
- return [...new Set(remotes.map((remote) => process.env[remote.apiKeyEnv]).filter((secret) => typeof secret === "string" && secret.length > 0))];
755
- }
756
- function sameRemoteIdentity(left, right) {
757
- if (!left || typeof left !== "object" || Array.isArray(left)) return false;
758
- const value = left;
759
- const expected = canonicalRemote(right);
760
- return value.id === expected.id && value.url === expected.url && value.apiKeyEnv === expected.apiKeyEnv;
761
1004
  }
762
- function readRemoteCache(modelsPath, remote, fingerprint, activeSecrets) {
1005
+ function remoteRefreshLockIsStale(lockPath) {
1006
+ const stat = fs.lstatSync(lockPath);
1007
+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`remote catalog refresh lock must be a regular file: ${lockPath}`);
1008
+ let owner;
763
1009
  try {
764
- const directory = safeRemoteCacheDirectory(modelsPath, false);
765
- if (!directory) return void 0;
766
- const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
767
- if (fs.existsSync(tombstone)) return void 0;
768
- const value = JSON.parse(readSafeRemoteCacheFile(directory, remoteCachePath(modelsPath, remote, fingerprint)).toString("utf8"));
769
- 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;
770
- assertNoSecretSubstrings({ etag: value.etag, payload: value.payload }, activeSecrets, "remote catalog cache");
771
- const payload = sanitizeRemotePayload(value.payload, canonicalRemote(remote), new URL(remote.url), true);
772
- if (payloadDigest(payload) !== value.payloadSha256) return void 0;
773
- return { ...value, payload };
1010
+ owner = JSON.parse(fs.readFileSync(lockPath, "utf8"));
774
1011
  } catch {
775
- removeRemoteCache(modelsPath, remote, fingerprint);
776
- return void 0;
777
1012
  }
1013
+ const age = Date.now() - stat.mtimeMs;
1014
+ const validOwner = owner?.version === 1 && Number.isSafeInteger(owner.pid) && typeof owner.token === "string" && typeof owner.createdAt === "number";
1015
+ if (validOwner && processIsAlive(Number(owner.pid))) return false;
1016
+ return validOwner || age > REMOTE_REFRESH_LOCK_WRITE_GRACE_MS;
778
1017
  }
779
- function remoteCacheTombstonePath(modelsPath, remote, fingerprint) {
780
- return `${remoteCachePath(modelsPath, remote, fingerprint)}.revoked`;
1018
+ function sameFileIdentity(left, right, leftPath, rightPath) {
1019
+ if (left.dev !== right.dev || left.ino !== right.ino) return false;
1020
+ if (left.ino !== 0) return true;
1021
+ return left.size === right.size && fs.readFileSync(leftPath).equals(fs.readFileSync(rightPath));
781
1022
  }
782
- function removeRemoteCache(modelsPath, remote, fingerprint) {
1023
+ function reclaimStaleRemoteRefreshLock(lockPath) {
1024
+ if (!remoteRefreshLockIsStale(lockPath)) return false;
1025
+ const claimPath = `${lockPath}.reclaim-${process.pid}-${randomBytes(8).toString("hex")}`;
783
1026
  try {
784
- const directory = safeRemoteCacheDirectory(modelsPath, false);
785
- if (!directory) return;
786
- const filepath = remoteCachePath(modelsPath, remote, fingerprint);
787
- if (fs.existsSync(filepath)) {
788
- const stat = fs.lstatSync(filepath);
789
- if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`remote catalog cache entry is not a regular file: ${filepath}`);
790
- fs.unlinkSync(filepath);
791
- }
792
- const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
793
- if (fs.existsSync(tombstone)) fs.unlinkSync(tombstone);
794
- return;
1027
+ fs.linkSync(lockPath, claimPath);
1028
+ const claimed = fs.lstatSync(claimPath);
1029
+ const current = fs.lstatSync(lockPath);
1030
+ if (claimed.isSymbolicLink() || !claimed.isFile() || current.isSymbolicLink() || !current.isFile() || !sameFileIdentity(claimed, current, claimPath, lockPath)) return false;
1031
+ if (!remoteRefreshLockIsStale(claimPath)) return false;
1032
+ fs.unlinkSync(lockPath);
1033
+ return true;
795
1034
  } catch (error) {
796
- const directory = safeRemoteCacheDirectory(modelsPath, true);
797
- if (!directory) throw error;
798
- const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
1035
+ if (["ENOENT", "EEXIST"].includes(error.code ?? "")) return false;
1036
+ throw error;
1037
+ } finally {
799
1038
  try {
800
- fs.writeFileSync(tombstone, `${JSON.stringify({ version: 1, revoked: true })}
801
- `, { flag: "wx", mode: 384 });
802
- } catch (tombstoneError) {
803
- if (!fs.existsSync(tombstone)) throw tombstoneError;
1039
+ fs.unlinkSync(claimPath);
1040
+ } catch {
804
1041
  }
805
1042
  }
806
1043
  }
807
- function validateRemoteEndpoint(baseUrl, catalogUrl, label) {
808
- let endpoint;
809
- try {
810
- endpoint = new URL(baseUrl);
811
- } catch {
812
- throw new Error(`${label} baseUrl must be an absolute URL`);
813
- }
814
- if (endpoint.protocol !== "https:" && endpoint.hostname !== "127.0.0.1" && endpoint.hostname !== "localhost") {
815
- throw new Error(`${label} baseUrl must use HTTPS`);
1044
+ async function acquireRemoteRefreshLock(modelsPath) {
1045
+ const directory = safeRemoteCacheDirectory(modelsPath, true);
1046
+ const lockPath = remoteRefreshLockPath(modelsPath);
1047
+ const deadline = Date.now() + REMOTE_REFRESH_LOCK_WAIT_MS;
1048
+ while (true) {
1049
+ const token = randomBytes(16).toString("hex");
1050
+ try {
1051
+ const fd = fs.openSync(lockPath, "wx", 384);
1052
+ try {
1053
+ fs.writeFileSync(fd, `${JSON.stringify({ version: 1, pid: process.pid, token, createdAt: Date.now() })}
1054
+ `);
1055
+ } finally {
1056
+ fs.closeSync(fd);
1057
+ }
1058
+ return () => {
1059
+ try {
1060
+ const stat = fs.lstatSync(lockPath);
1061
+ if (stat.isSymbolicLink() || !stat.isFile()) return;
1062
+ const current = JSON.parse(fs.readFileSync(lockPath, "utf8"));
1063
+ if (current.token === token) fs.unlinkSync(lockPath);
1064
+ } catch {
1065
+ }
1066
+ };
1067
+ } catch (error) {
1068
+ if (error.code !== "EEXIST") throw error;
1069
+ try {
1070
+ if (reclaimStaleRemoteRefreshLock(lockPath)) continue;
1071
+ } catch (lockError) {
1072
+ if (lockError.code === "ENOENT") continue;
1073
+ throw lockError;
1074
+ }
1075
+ if (Date.now() >= deadline) throw new Error(`timed out waiting for remote catalog refresh lock: ${lockPath}`);
1076
+ await new Promise((resolve2) => setTimeout(resolve2, 25));
1077
+ }
816
1078
  }
817
- if (endpoint.username || endpoint.password) throw new Error(`${label} baseUrl must not contain credentials`);
818
- if (endpoint.hash) throw new Error(`${label} baseUrl must not contain a fragment`);
819
- if (endpoint.search) throw new Error(`${label} baseUrl must not contain query parameters`);
820
- if (endpoint.origin !== catalogUrl.origin) throw new Error(`${label} baseUrl must use the authenticated catalog origin`);
821
1079
  }
822
- function isPlainRecord2(value) {
823
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
824
- const prototype = Object.getPrototypeOf(value);
825
- return prototype === Object.prototype || prototype === null;
826
- }
827
- function assertOnlyKeys(value, allowed, label) {
828
- const allowedSet = new Set(allowed);
829
- const unexpected = Object.keys(value).find((key) => !allowedSet.has(key));
830
- if (unexpected) throw new Error(`${label} contains unsupported field ${unexpected}`);
1080
+ function readSafeRemoteCacheFile(directory, filepath) {
1081
+ const stat = fs.lstatSync(filepath);
1082
+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`remote catalog cache entry must be a regular file: ${filepath}`);
1083
+ const canonicalDirectory = fs.realpathSync(directory);
1084
+ const canonicalFile = fs.realpathSync(filepath);
1085
+ const relative2 = path.relative(canonicalDirectory, canonicalFile);
1086
+ if (!relative2 || relative2 === ".." || relative2.startsWith(`..${path.sep}`) || path.isAbsolute(relative2)) {
1087
+ throw new Error(`remote catalog cache entry escapes its cache directory: ${filepath}`);
1088
+ }
1089
+ return fs.readFileSync(filepath);
831
1090
  }
832
- function validateRemoteCatalogConfig(value, label) {
833
- if (!isPlainRecord2(value)) throw new Error(`${label} must be an object`);
834
- assertOnlyKeys(value, ["id", "url", "apiKeyEnv"], label);
835
- 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`);
836
- if (typeof value.url !== "string" || !value.url) throw new Error(`${label}.url must be a URL`);
837
- 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`);
838
- let url;
1091
+ function credentialNamespaceKey(modelsPath, create) {
1092
+ const directory = safeRemoteCacheDirectory(modelsPath, create);
1093
+ if (!directory) return void 0;
1094
+ const keyPath = path.join(directory, ".credential-namespace-key");
1095
+ if (!fs.existsSync(keyPath) && !create) return void 0;
1096
+ if (create && !fs.existsSync(keyPath)) {
1097
+ try {
1098
+ fs.writeFileSync(keyPath, randomBytes(32), { flag: "wx", mode: 384 });
1099
+ } catch (error) {
1100
+ if (!isPlainRecord3(error) || error.code !== "EEXIST") throw error;
1101
+ }
1102
+ }
1103
+ const key = readSafeRemoteCacheFile(directory, keyPath);
1104
+ if (key.byteLength !== 32) throw new Error("remote catalog credential namespace key is invalid");
839
1105
  try {
840
- url = new URL(value.url);
1106
+ fs.chmodSync(keyPath, 384);
841
1107
  } catch {
842
- throw new Error(`${label}.url must be an absolute URL`);
843
1108
  }
844
- const localTestHost = url.hostname === "127.0.0.1" || url.hostname === "localhost";
845
- if (url.protocol !== "https:" && !localTestHost) throw new Error(`${label}.url must use HTTPS`);
846
- if (url.username || url.password) throw new Error(`${label}.url must not contain credentials`);
847
- if (url.hash) throw new Error(`${label}.url must not contain a fragment`);
848
- if (url.search) throw new Error(`${label}.url must not contain query parameters`);
849
- return canonicalRemote({ id: value.id, url: url.href, apiKeyEnv: value.apiKeyEnv });
1109
+ return key;
850
1110
  }
851
- function validatedRemoteCatalogs(value) {
852
- if (value === void 0) return [];
853
- if (!Array.isArray(value)) throw new Error("models.json remoteCatalogs must be an array");
854
- if (value.length === 0) throw new Error("models.json remoteCatalogs must be a non-empty array");
855
- const catalogs = value.map((item, index) => validateRemoteCatalogConfig(item, `models.json remoteCatalogs[${index}]`));
856
- const ids = /* @__PURE__ */ new Set();
857
- for (const catalog of catalogs) {
858
- if (ids.has(catalog.id)) throw new Error(`models.json remoteCatalogs contains duplicate id ${catalog.id}`);
859
- ids.add(catalog.id);
860
- }
861
- return catalogs;
1111
+ function credentialFingerprint(modelsPath, remote, credential, create = false) {
1112
+ const key = credentialNamespaceKey(modelsPath, create);
1113
+ if (!key) return void 0;
1114
+ return createHmac("sha256", key).update(remoteIdentityDigest(remote)).update("\0").update(credential).digest("hex");
862
1115
  }
863
- function validateModelsDocumentShape(value) {
864
- if (!isPlainRecord2(value)) throw new Error("models.json must be an object");
865
- assertOnlyKeys(value, ["$schema", "profiles", "remoteCatalogs", "defaults", "modelOverrides", "voice", "gameUse"], "models.json");
866
- if (value.$schema !== void 0 && (typeof value.$schema !== "string" || !value.$schema)) throw new Error("models.json $schema must be a non-empty string");
867
- const hasProfiles = Object.prototype.hasOwnProperty.call(value, "profiles");
868
- const hasRemoteCatalogs = Object.prototype.hasOwnProperty.call(value, "remoteCatalogs");
869
- if (!hasProfiles && !hasRemoteCatalogs) throw new Error("models.json must define profiles or remoteCatalogs");
870
- validatedRemoteCatalogs(value.remoteCatalogs);
871
- if (hasProfiles) {
872
- if (!isPlainRecord2(value.profiles) || Object.keys(value.profiles).length === 0) throw new Error("models.json profiles must be a non-empty object");
873
- for (const [profileId, profile] of Object.entries(value.profiles)) {
874
- if (!profileId || profileId !== profileId.trim() || /\s/.test(profileId)) throw new Error(`models.json profile id is invalid: ${profileId}`);
875
- validateProfileConfig(profileId, profile);
876
- }
877
- }
878
- validateModelOverrides(value.modelOverrides);
879
- validateVoiceConfig(value.voice);
880
- validateGameUseConfig(value.gameUse);
881
- if (value.defaults !== void 0) {
882
- if (!isPlainRecord2(value.defaults)) throw new Error("models.json defaults must be an object");
883
- assertOnlyKeys(value.defaults, ["provider", "modelId", "modelClasses", "toolModels"], "models.json defaults");
884
- assertOptionalString(value.defaults.provider, "models.json defaults.provider");
885
- assertOptionalString(value.defaults.modelId, "models.json defaults.modelId");
886
- for (const [field, allowed] of [["modelClasses", ["light", "balanced", "strong"]], ["toolModels", ["web_search", "read_file.image", "read_file.video", "read_file.audio", "read_file.document"]]]) {
887
- const routes = value.defaults[field];
888
- if (routes === void 0) continue;
889
- if (!isPlainRecord2(routes)) throw new Error(`models.json defaults.${field} must be an object`);
890
- assertOnlyKeys(routes, allowed, `models.json defaults.${field}`);
891
- for (const [routeName, route] of Object.entries(routes)) {
892
- if (!isPlainRecord2(route)) throw new Error(`models.json defaults.${field}.${routeName} must be an object`);
893
- assertOnlyKeys(route, ["provider", "modelId"], `models.json defaults.${field}.${routeName}`);
894
- assertOptionalString(route.provider, `models.json defaults.${field}.${routeName}.provider`);
895
- assertOptionalString(route.modelId, `models.json defaults.${field}.${routeName}.modelId`);
1116
+ function remoteCachePath(modelsPath, remote, fingerprint) {
1117
+ return path.join(remoteCacheDirectory(modelsPath), `${remoteIdentityDigest(remote)}-${fingerprint}.json`);
1118
+ }
1119
+ function pruneLegacyRemoteCatalogCaches(modelsPath) {
1120
+ const directory = safeRemoteCacheDirectory(modelsPath, false);
1121
+ if (!directory) return;
1122
+ for (const name of fs.readdirSync(directory)) {
1123
+ if (!name.endsWith(".json")) continue;
1124
+ const filepath = path.join(directory, name);
1125
+ try {
1126
+ const value = JSON.parse(readSafeRemoteCacheFile(directory, filepath).toString("utf8"));
1127
+ if (value.version === REMOTE_CATALOG_CACHE_VERSION) continue;
1128
+ } catch {
1129
+ let stat;
1130
+ try {
1131
+ stat = fs.lstatSync(filepath);
1132
+ } catch {
1133
+ continue;
896
1134
  }
1135
+ if (stat.isSymbolicLink() || !stat.isFile()) continue;
1136
+ }
1137
+ try {
1138
+ fs.unlinkSync(filepath);
1139
+ } catch {
897
1140
  }
898
1141
  }
899
1142
  }
900
- function assertOptionalString(value, label) {
901
- if (value !== void 0 && (typeof value !== "string" || !value)) throw new Error(`${label} must be a non-empty string`);
902
- }
903
- function assertOptionalEnvName(value, label) {
904
- if (value !== void 0 && (typeof value !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value))) {
905
- throw new Error(`${label} must be an environment variable name`);
1143
+ function scrubActiveSecretsFromRemoteCaches(modelsPath, activeSecrets) {
1144
+ if (activeSecrets.length === 0) return;
1145
+ const directory = safeRemoteCacheDirectory(modelsPath, false);
1146
+ if (!directory) return;
1147
+ const handle = fs.opendirSync(directory);
1148
+ try {
1149
+ let scanned = 0;
1150
+ while (true) {
1151
+ const entry = handle.readSync();
1152
+ if (!entry) break;
1153
+ if (++scanned > 1e4) throw new Error("remote catalog cache directory exceeds the hygiene scan limit");
1154
+ const isCache = entry.name.endsWith(".json");
1155
+ const isOrphanedTemporary = /^\..+\.json\.\d+\.[0-9a-f]+\.tmp$/.test(entry.name);
1156
+ if (!entry.isFile() || !isCache && !isOrphanedTemporary) continue;
1157
+ const filepath = path.join(directory, entry.name);
1158
+ try {
1159
+ const raw = readSafeRemoteCacheFile(directory, filepath).toString("utf8");
1160
+ assertNoSecretSubstrings(raw, activeSecrets, "remote catalog cache");
1161
+ } catch {
1162
+ try {
1163
+ const stat = fs.lstatSync(filepath);
1164
+ if (!stat.isSymbolicLink() && stat.isFile()) fs.unlinkSync(filepath);
1165
+ } catch {
1166
+ }
1167
+ }
1168
+ }
1169
+ } finally {
1170
+ handle.closeSync();
906
1171
  }
907
1172
  }
908
- function assertOptionalBoolean(value, label) {
909
- if (value !== void 0 && typeof value !== "boolean") throw new Error(`${label} must be a boolean`);
910
- }
911
- function validateCacheCapability(value, label) {
912
- if (value === void 0) return;
913
- if (!isPlainRecord2(value) || !["none", "session_store", "prompt_cache", "usage_only"].includes(String(value.mode)) || typeof value.supported !== "boolean") throw new Error(`${label} is invalid`);
914
- assertOnlyKeys(value, ["mode", "supported", "supportsUsageMetrics", "description"], label);
915
- assertOptionalBoolean(value.supportsUsageMetrics, `${label}.supportsUsageMetrics`);
916
- assertOptionalString(value.description, `${label}.description`);
917
- }
918
- function validateWebSearchCapability(value, label) {
919
- if (value === void 0) return;
920
- if (!isPlainRecord2(value) || !["anthropic_server_tool", "chat_completions_web_search", "openai_responses"].includes(String(value.type))) {
921
- throw new Error(`${label} is invalid`);
922
- }
923
- assertOnlyKeys(value, ["type", "forceToolChoice", "searchEngine", "count", "contentSize"], label);
924
- assertOptionalBoolean(value.forceToolChoice, `${label}.forceToolChoice`);
925
- assertOptionalString(value.searchEngine, `${label}.searchEngine`);
926
- if (value.count !== void 0 && (!Number.isInteger(value.count) || Number(value.count) < 1)) throw new Error(`${label}.count is invalid`);
927
- if (value.contentSize !== void 0 && !["low", "medium", "high"].includes(String(value.contentSize))) throw new Error(`${label}.contentSize is invalid`);
1173
+ function payloadDigest(payload) {
1174
+ return createHash("sha256").update(JSON.stringify(payload)).digest("hex");
928
1175
  }
929
- function validateFileCapabilities(value, label) {
930
- if (value === void 0) return;
931
- if (!isPlainRecord2(value)) throw new Error(`${label} is invalid`);
932
- for (const [kind, capability] of Object.entries(value)) {
933
- if (!["image", "video", "audio", "document"].includes(kind)) throw new Error(`${label}.${kind} is unsupported`);
934
- if (typeof capability === "boolean") continue;
935
- if (!isPlainRecord2(capability)) throw new Error(`${label}.${kind} is invalid`);
936
- assertOnlyKeys(capability, ["supported", "formats", "maxFileSizeMb", "maxDurationSeconds", "nativeInline"], `${label}.${kind}`);
937
- assertOptionalBoolean(capability.supported, `${label}.${kind}.supported`);
938
- assertOptionalBoolean(capability.nativeInline, `${label}.${kind}.nativeInline`);
939
- if (capability.formats !== void 0 && (!Array.isArray(capability.formats) || capability.formats.some((item) => typeof item !== "string" || !item))) {
940
- throw new Error(`${label}.${kind}.formats is invalid`);
1176
+ function assertNoSecretSubstrings(value, secrets, label) {
1177
+ const active = [...new Set(secrets.filter((secret) => secret.length > 0))];
1178
+ if (active.length === 0) return;
1179
+ const seen = /* @__PURE__ */ new Set();
1180
+ const visit = (candidate) => {
1181
+ if (typeof candidate === "string") {
1182
+ if (active.some((secret) => candidate.includes(secret))) throw new Error(`${label} reflects an active credential`);
1183
+ return;
941
1184
  }
942
- if (Array.isArray(capability.formats) && new Set(capability.formats).size !== capability.formats.length) {
943
- throw new Error(`${label}.${kind}.formats contains duplicates`);
1185
+ if (!candidate || typeof candidate !== "object" || seen.has(candidate)) return;
1186
+ seen.add(candidate);
1187
+ if (Array.isArray(candidate)) {
1188
+ for (const item of candidate) visit(item);
1189
+ return;
944
1190
  }
945
- for (const field of ["maxFileSizeMb", "maxDurationSeconds"]) {
946
- if (capability[field] !== void 0 && (typeof capability[field] !== "number" || !Number.isFinite(capability[field]) || capability[field] <= 0)) {
947
- throw new Error(`${label}.${kind}.${field} is invalid`);
948
- }
1191
+ for (const [key, item] of Object.entries(candidate)) {
1192
+ visit(key);
1193
+ visit(item);
949
1194
  }
950
- }
1195
+ };
1196
+ visit(value);
1197
+ const serialized = JSON.stringify(value);
1198
+ if (active.some((secret) => serialized.includes(secret))) throw new Error(`${label} reflects an active credential`);
951
1199
  }
952
- function validateTransport(value, label) {
953
- if (value !== void 0 && value !== "sse" && value !== "websocket" && value !== "auto") throw new Error(`${label}.transport is invalid`);
1200
+ function safeRemoteText(value, secrets) {
1201
+ let message = String(value);
1202
+ const active = [...new Set(secrets.filter(Boolean))];
1203
+ const replacement = active.some((secret) => "[REDACTED]".includes(secret)) ? "" : "[REDACTED]";
1204
+ for (const secret of active) message = message.split(secret).join(replacement);
1205
+ message = message.slice(0, 1024);
1206
+ if (!active.some((secret) => message.includes(secret))) return message;
1207
+ return "";
954
1208
  }
955
- function validateCompat(value, label) {
956
- if (value === void 0) return;
957
- if (!isPlainRecord2(value)) throw new Error(`${label} is invalid`);
958
- assertOnlyKeys(value, [
959
- "forcedReasoningEffort",
960
- "store",
961
- "supportsEncryptedReasoning",
962
- "responsesContinuation",
963
- "supportsReasoningSummary",
964
- "reasoningSummary",
965
- "timeoutReplay",
966
- "supportsStore",
967
- "supportsDeveloperRole",
968
- "supportsReasoningEffort",
969
- "supportsUsageInStreaming",
970
- "maxTokensField",
971
- "requiresToolResultName",
972
- "requiresAssistantAfterToolResult",
973
- "requiresThinkingAsText",
974
- "supportsStrictMode",
975
- "streamRequiresDone",
976
- "streamRequiresFinishReason",
977
- "cacheCapability"
978
- ], label);
979
- if (value.forcedReasoningEffort !== void 0 && value.forcedReasoningEffort !== "none") {
980
- throw new Error(`${label}.forcedReasoningEffort must be "none"`);
981
- }
982
- if (value.reasoningSummary !== void 0 && !["auto", "concise", "detailed", "none"].includes(String(value.reasoningSummary))) {
983
- throw new Error(`${label}.reasoningSummary must be auto | concise | detailed | none`);
984
- }
985
- for (const field of [
986
- "store",
987
- "supportsEncryptedReasoning",
988
- "responsesContinuation",
989
- "supportsReasoningSummary",
990
- "timeoutReplay",
991
- "supportsStore",
992
- "supportsDeveloperRole",
993
- "supportsReasoningEffort",
994
- "supportsUsageInStreaming",
995
- "requiresToolResultName",
996
- "requiresAssistantAfterToolResult",
997
- "requiresThinkingAsText",
998
- "supportsStrictMode",
999
- "streamRequiresDone",
1000
- "streamRequiresFinishReason"
1001
- ]) assertOptionalBoolean(value[field], `${label}.${field}`);
1002
- if (value.maxTokensField !== void 0 && value.maxTokensField !== "max_completion_tokens" && value.maxTokensField !== "max_tokens") {
1003
- throw new Error(`${label}.maxTokensField is invalid`);
1004
- }
1005
- validateCacheCapability(value.cacheCapability, `${label}.cacheCapability`);
1209
+ function safeRemoteError(error, secrets) {
1210
+ return safeRemoteText(error instanceof Error ? `${error.name}: ${error.message}` : String(error), secrets);
1006
1211
  }
1007
- function validateRemoteModel(profileId, model) {
1008
- if (!isPlainRecord2(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`);
1009
- assertOnlyKeys(model, [
1010
- "id",
1011
- "api",
1012
- "name",
1013
- "reasoning",
1014
- "thinking",
1015
- "input",
1016
- "cost",
1017
- "contextWindow",
1018
- "maxTokens",
1019
- "transport",
1020
- "compat",
1021
- "cacheCapability",
1022
- "webSearch",
1023
- "fileCapabilities",
1024
- "headers",
1025
- "apiKeyEnv",
1026
- "displayName",
1027
- "filePlatform",
1028
- "attachmentPlatform"
1029
- ], `Remote profile "${profileId}" model "${model.id}"`);
1030
- for (const field of ["name", "displayName", "filePlatform", "attachmentPlatform", "apiKeyEnv"]) {
1031
- assertOptionalString(model[field], `Remote profile "${profileId}" model "${model.id}" ${field}`);
1032
- }
1033
- if (model.api !== void 0 && !SUPPORTED_REMOTE_APIS.has(model.api)) throw new Error(`Model "${model.id}" has unsupported api ${model.api}`);
1034
- assertOptionalBoolean(model.reasoning, `Remote profile "${profileId}" model "${model.id}" reasoning`);
1035
- if (!Array.isArray(model.input) || model.input.length === 0 || model.input.some((item) => !["text", "image", "audio", "video"].includes(item))) {
1036
- throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid input capabilities`);
1037
- }
1038
- if (!isPlainRecord2(model.cost)) throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid cost values`);
1039
- assertOnlyKeys(model.cost, ["input", "output", "cacheRead", "cacheWrite", "cacheWriteLong"], `Remote profile "${profileId}" model "${model.id}" cost`);
1040
- const invalidRate = (value) => typeof value !== "number" || !Number.isFinite(value) || value < 0;
1041
- if ([model.cost.input, model.cost.output, model.cost.cacheRead, model.cost.cacheWrite].some(invalidRate) || model.cost.cacheWriteLong !== void 0 && invalidRate(model.cost.cacheWriteLong)) {
1042
- throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid cost values`);
1043
- }
1044
- if (!Number.isSafeInteger(model.contextWindow) || Number(model.contextWindow) <= 0 || !Number.isSafeInteger(model.maxTokens) || Number(model.maxTokens) <= 0 || Number(model.maxTokens) > Number(model.contextWindow)) {
1045
- throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid token limits`);
1212
+ function warnRemoteCatalog(message, secrets) {
1213
+ console.warn(safeRemoteText(message, secrets));
1214
+ }
1215
+ function configuredRemoteCredentialValues(config) {
1216
+ let remotes;
1217
+ try {
1218
+ remotes = validatedRemoteCatalogs(config.remoteCatalogs);
1219
+ } catch {
1220
+ return [];
1046
1221
  }
1047
- if (new Set(model.input).size !== model.input.length) throw new Error(`Remote profile "${profileId}" model "${model.id}" has duplicate input capabilities`);
1048
- validateTransport(model.transport, `Model "${model.id}"`);
1049
- validateCompat(model.compat, `Remote profile "${profileId}" model "${model.id}" compat`);
1050
- validateThinkingCapability(model.thinking, `Remote profile "${profileId}" model "${model.id}" thinking`);
1051
- validateCacheCapability(model.cacheCapability, `Remote profile "${profileId}" model "${model.id}" cacheCapability`);
1052
- validateWebSearchCapability(model.webSearch, `Remote profile "${profileId}" model "${model.id}" webSearch`);
1053
- validateFileCapabilities(model.fileCapabilities, `Remote profile "${profileId}" model "${model.id}" fileCapabilities`);
1222
+ return [...new Set(remotes.map((remote) => process.env[remote.apiKeyEnv]).filter((secret) => typeof secret === "string" && secret.length > 0))];
1054
1223
  }
1055
- function assertHeadersShape(headers, label) {
1056
- if (headers === void 0) return;
1057
- if (!isPlainRecord2(headers)) throw new Error(`${label} headers must be an object`);
1058
- for (const [name, value] of Object.entries(headers)) {
1059
- if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) throw new Error(`${label} header name ${name || "(empty)"} is invalid`);
1060
- if (typeof value !== "string") throw new Error(`${label} header ${name} must be a string`);
1061
- if (/[\0-\x08\x0A-\x1F\x7F]/.test(value)) throw new Error(`${label} header ${name} contains an invalid control character`);
1224
+ function sameRemoteIdentity(left, right) {
1225
+ if (!left || typeof left !== "object" || Array.isArray(left)) return false;
1226
+ const value = left;
1227
+ const expected = canonicalRemote(right);
1228
+ return value.id === expected.id && value.url === expected.url && value.apiKeyEnv === expected.apiKeyEnv;
1229
+ }
1230
+ function readRemoteCache(modelsPath, remote, fingerprint, activeSecrets) {
1231
+ try {
1232
+ const directory = safeRemoteCacheDirectory(modelsPath, false);
1233
+ if (!directory) return void 0;
1234
+ const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
1235
+ if (fs.existsSync(tombstone)) return void 0;
1236
+ const value = JSON.parse(readSafeRemoteCacheFile(directory, remoteCachePath(modelsPath, remote, fingerprint)).toString("utf8"));
1237
+ 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;
1238
+ assertNoSecretSubstrings({ etag: value.etag, payload: value.payload }, activeSecrets, "remote catalog cache");
1239
+ const payload = sanitizeRemotePayload(value.payload, canonicalRemote(remote), new URL(remote.url), true);
1240
+ if (payloadDigest(payload) !== value.payloadSha256) return void 0;
1241
+ return { ...value, payload };
1242
+ } catch {
1243
+ removeRemoteCache(modelsPath, remote, fingerprint);
1244
+ return void 0;
1062
1245
  }
1063
1246
  }
1064
- function assertRemoteHeadersSafe(headers, label) {
1065
- assertHeadersShape(headers, label);
1066
- for (const name of Object.keys(headers || {})) {
1067
- if (/(?:authorization|cookie|api[-_]?key|token|secret|credential)/i.test(name)) {
1068
- throw new Error(`${label} must not provide credential-bearing header ${name}`);
1247
+ function remoteCacheTombstonePath(modelsPath, remote, fingerprint) {
1248
+ return `${remoteCachePath(modelsPath, remote, fingerprint)}.revoked`;
1249
+ }
1250
+ function removeRemoteCache(modelsPath, remote, fingerprint) {
1251
+ try {
1252
+ const directory = safeRemoteCacheDirectory(modelsPath, false);
1253
+ if (!directory) return;
1254
+ const filepath = remoteCachePath(modelsPath, remote, fingerprint);
1255
+ if (fs.existsSync(filepath)) {
1256
+ const stat = fs.lstatSync(filepath);
1257
+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`remote catalog cache entry is not a regular file: ${filepath}`);
1258
+ fs.unlinkSync(filepath);
1069
1259
  }
1070
- if (HOP_BY_HOP_HEADERS.has(name.toLowerCase())) throw new Error(`${label} must not provide transport header ${name}`);
1260
+ const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
1261
+ if (fs.existsSync(tombstone)) fs.unlinkSync(tombstone);
1262
+ return;
1263
+ } catch (error) {
1264
+ const directory = safeRemoteCacheDirectory(modelsPath, true);
1265
+ if (!directory) throw error;
1266
+ const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
1267
+ try {
1268
+ fs.writeFileSync(tombstone, `${JSON.stringify({ version: 1, revoked: true })}
1269
+ `, { flag: "wx", mode: 384 });
1270
+ } catch (tombstoneError) {
1271
+ if (!fs.existsSync(tombstone)) throw tombstoneError;
1272
+ }
1273
+ }
1274
+ }
1275
+ function validateRemoteEndpoint(baseUrl, catalogUrl, label) {
1276
+ let endpoint;
1277
+ try {
1278
+ endpoint = new URL(baseUrl);
1279
+ } catch {
1280
+ throw new Error(`${label} baseUrl must be an absolute URL`);
1071
1281
  }
1282
+ if (endpoint.protocol !== "https:" && endpoint.hostname !== "127.0.0.1" && endpoint.hostname !== "localhost") {
1283
+ throw new Error(`${label} baseUrl must use HTTPS`);
1284
+ }
1285
+ if (endpoint.username || endpoint.password) throw new Error(`${label} baseUrl must not contain credentials`);
1286
+ if (endpoint.hash) throw new Error(`${label} baseUrl must not contain a fragment`);
1287
+ if (endpoint.search) throw new Error(`${label} baseUrl must not contain query parameters`);
1288
+ if (endpoint.origin !== catalogUrl.origin) throw new Error(`${label} baseUrl must use the authenticated catalog origin`);
1072
1289
  }
1073
1290
  function sanitizeRemotePayload(decoded, remote, catalogUrl, allowLocallyInjectedCredential = false) {
1074
1291
  if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) throw new Error("catalog response must be an object");
1075
- assertOnlyKeys(decoded, ["profiles"], "catalog response");
1292
+ assertOnlyKeys2(decoded, ["profiles"], "catalog response");
1076
1293
  const sourceProfiles = decoded.profiles;
1077
1294
  if (!sourceProfiles || typeof sourceProfiles !== "object" || Array.isArray(sourceProfiles)) {
1078
1295
  throw new Error("catalog response profiles must be an object");
1079
1296
  }
1080
1297
  const profiles = /* @__PURE__ */ Object.create(null);
1081
1298
  for (const [provider, source] of Object.entries(sourceProfiles)) {
1082
- if (!provider || provider !== provider.trim() || /\s/.test(provider) || !isPlainRecord2(source)) throw new Error("catalog contains an invalid profile");
1083
- assertOnlyKeys(source, [
1299
+ if (!provider || provider !== provider.trim() || /\s/.test(provider) || !isPlainRecord3(source)) throw new Error("catalog contains an invalid profile");
1300
+ assertOnlyKeys2(source, [
1084
1301
  "baseUrl",
1085
1302
  "endpoints",
1086
1303
  "api",
@@ -1104,7 +1321,7 @@ function sanitizeRemotePayload(decoded, remote, catalogUrl, allowLocallyInjected
1104
1321
  if (!source.api || !SUPPORTED_REMOTE_APIS.has(source.api)) throw new Error(`Remote profile "${provider}" has unsupported api`);
1105
1322
  if (!source.baseUrl) throw new Error(`Remote profile "${provider}" has no baseUrl`);
1106
1323
  for (const field of ["baseUrl", "api", "displayName", "filePlatform", "attachmentPlatform", "apiKeyEnv"]) {
1107
- assertOptionalString(source[field], `Remote profile "${provider}" ${field}`);
1324
+ assertOptionalString2(source[field], `Remote profile "${provider}" ${field}`);
1108
1325
  }
1109
1326
  validateRemoteEndpoint(source.baseUrl, catalogUrl, `Remote profile "${provider}"`);
1110
1327
  validateProfileEndpoints(source, `Remote profile "${provider}"`);
@@ -1121,7 +1338,7 @@ function sanitizeRemotePayload(decoded, remote, catalogUrl, allowLocallyInjected
1121
1338
  validateFileCapabilities(source.fileCapabilities, `Remote profile "${provider}" fileCapabilities`);
1122
1339
  const seen = /* @__PURE__ */ new Set();
1123
1340
  for (const model of source.models) {
1124
- if (isPlainRecord2(model) && Object.prototype.hasOwnProperty.call(model, "apiKeyEnv") && (!allowLocallyInjectedCredential || model.apiKeyEnv !== remote.apiKeyEnv)) {
1341
+ if (isPlainRecord3(model) && Object.prototype.hasOwnProperty.call(model, "apiKeyEnv") && (!allowLocallyInjectedCredential || model.apiKeyEnv !== remote.apiKeyEnv)) {
1125
1342
  throw new Error(`Remote profile "${provider}" model must not declare credential fields`);
1126
1343
  }
1127
1344
  validateRemoteModel(provider, model);
@@ -1236,160 +1453,8 @@ function loadResolvedModelsConfig(modelsPath) {
1236
1453
  }
1237
1454
  return { config: { ...raw, profiles }, remoteCatalogs: catalogs.sort((a, b) => a.id.localeCompare(b.id)) };
1238
1455
  }
1239
- function validateModelOverrides(value) {
1240
- if (value === void 0) return;
1241
- if (!isPlainRecord2(value)) throw new Error("models.json modelOverrides must be an object");
1242
- for (const [key, override] of Object.entries(value)) {
1243
- if (!/^[^\s/]+\/[^\s/]+$/.test(key)) throw new Error(`models.json modelOverrides key must be "provider/modelId": ${key}`);
1244
- if (!isPlainRecord2(override)) throw new Error(`models.json modelOverrides["${key}"] must be an object`);
1245
- assertOnlyKeys(override, [...MODEL_OVERRIDE_KEYS], `models.json modelOverrides["${key}"]`);
1246
- 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`);
1247
- 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`);
1248
- if (override.reasoning !== void 0 && typeof override.reasoning !== "boolean") throw new Error(`models.json modelOverrides["${key}"].reasoning must be a boolean`);
1249
- 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`);
1250
- if (override.contextWindow !== void 0 && (!Number.isInteger(override.contextWindow) || Number(override.contextWindow) < 1)) throw new Error(`models.json modelOverrides["${key}"].contextWindow is invalid`);
1251
- if (override.maxTokens !== void 0 && (!Number.isInteger(override.maxTokens) || Number(override.maxTokens) < 1)) throw new Error(`models.json modelOverrides["${key}"].maxTokens is invalid`);
1252
- if (override.cost !== void 0) {
1253
- if (!isPlainRecord2(override.cost)) throw new Error(`models.json modelOverrides["${key}"].cost must be an object`);
1254
- for (const field of ["input", "output", "cacheRead", "cacheWrite", "cacheWriteLong"]) {
1255
- 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`);
1256
- }
1257
- }
1258
- if (override.headers !== void 0) {
1259
- if (!isPlainRecord2(override.headers)) throw new Error(`models.json modelOverrides["${key}"].headers must be an object`);
1260
- for (const [headerName, headerValue] of Object.entries(override.headers)) {
1261
- if (typeof headerValue !== "string") throw new Error(`models.json modelOverrides["${key}"].headers.${headerName} must be a string`);
1262
- }
1263
- }
1264
- validateTransport(override.transport, `Model override "${key}"`);
1265
- validateCompat(override.compat, `models.json modelOverrides["${key}"].compat`);
1266
- validateThinkingCapability(override.thinking, `models.json modelOverrides["${key}"].thinking`);
1267
- validateCacheCapability(override.cacheCapability, `models.json modelOverrides["${key}"].cacheCapability`);
1268
- validateWebSearchCapability(override.webSearch, `models.json modelOverrides["${key}"].webSearch`);
1269
- validateFileCapabilities(override.fileCapabilities, `models.json modelOverrides["${key}"].fileCapabilities`);
1270
- }
1271
- }
1272
- function validateProfileEndpoints(profile, label) {
1273
- if (profile.endpoints === void 0) return;
1274
- if (!isPlainRecord2(profile.endpoints)) throw new Error(`${label} endpoints must be an object`);
1275
- for (const [api, value] of Object.entries(profile.endpoints)) {
1276
- if (!SUPPORTED_REMOTE_APIS.has(api)) throw new Error(`${label} endpoints has unsupported api ${api}`);
1277
- try {
1278
- if (typeof value !== "string") throw new Error("invalid URL");
1279
- const endpoint = new URL(value);
1280
- if (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") throw new Error("unsupported protocol");
1281
- } catch {
1282
- throw new Error(`${label} endpoints.${api} must be an absolute HTTP(S) URL`);
1283
- }
1284
- }
1285
- }
1286
- function resolveProfileRoute(profile, model) {
1287
- const api = model.api ?? profile.api;
1288
- if (!SUPPORTED_REMOTE_APIS.has(api)) throw new Error(`Model "${model.id}" has unsupported api ${api}`);
1289
- const endpoint = profile.endpoints?.[api];
1290
- if (model.api !== void 0 && endpoint === void 0 && api !== profile.api) {
1291
- throw new Error(`Model "${model.id}" api ${api} requires profile endpoints.${api} (otherwise api must equal profile api)`);
1292
- }
1293
- return { api, baseUrl: endpoint ?? profile.baseUrl };
1294
- }
1295
- function validateProfileConfig(profileId, profileConfig) {
1296
- if (!isPlainRecord2(profileConfig)) throw new Error(`Profile "${profileId}" must be an object.`);
1297
- assertOnlyKeys(profileConfig, [
1298
- "baseUrl",
1299
- "endpoints",
1300
- "api",
1301
- "apiKey",
1302
- "apiKeyEnv",
1303
- "headers",
1304
- "displayName",
1305
- "filePlatform",
1306
- "attachmentPlatform",
1307
- "transport",
1308
- "compat",
1309
- "cacheCapability",
1310
- "thinking",
1311
- "webSearch",
1312
- "fileCapabilities",
1313
- "models"
1314
- ], `Profile "${profileId}"`);
1315
- const missing = [];
1316
- if (!profileConfig.api) missing.push("api");
1317
- if (!profileConfig.baseUrl) missing.push("baseUrl");
1318
- if (!Array.isArray(profileConfig.models) || profileConfig.models.length === 0) missing.push("models");
1319
- const hasProfileKeySource = Boolean(profileConfig.apiKey || profileConfig.apiKeyEnv);
1320
- const hasModelKeySource = Boolean(
1321
- (profileConfig.models || []).some((model) => Boolean(model.apiKeyEnv))
1322
- );
1323
- if (!hasProfileKeySource && !hasModelKeySource) missing.push("apiKey or apiKeyEnv");
1324
- if (missing.length > 0) {
1325
- throw new Error(
1326
- `Profile "${profileId}" is missing required field${missing.length > 1 ? "s" : ""}: ${missing.join(", ")}.`
1327
- );
1328
- }
1329
- for (const field of ["baseUrl", "api", "apiKey", "displayName", "filePlatform", "attachmentPlatform"]) {
1330
- assertOptionalString(profileConfig[field], `Profile "${profileId}" ${field}`);
1331
- }
1332
- assertOptionalEnvName(profileConfig.apiKeyEnv, `Profile "${profileId}" apiKeyEnv`);
1333
- if (!SUPPORTED_REMOTE_APIS.has(profileConfig.api)) throw new Error(`Profile "${profileId}" has unsupported api ${profileConfig.api}`);
1334
- try {
1335
- const endpoint = new URL(profileConfig.baseUrl);
1336
- if (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") throw new Error("unsupported protocol");
1337
- } catch {
1338
- throw new Error(`Profile "${profileId}" baseUrl must be an absolute HTTP(S) URL`);
1339
- }
1340
- validateProfileEndpoints(profileConfig, `Profile "${profileId}"`);
1341
- assertHeadersShape(profileConfig.headers, `Profile "${profileId}"`);
1342
- validateTransport(profileConfig.transport, `Profile "${profileId}"`);
1343
- validateCompat(profileConfig.compat, `Profile "${profileId}" compat`);
1344
- validateCacheCapability(profileConfig.cacheCapability, `Profile "${profileId}" cacheCapability`);
1345
- validateWebSearchCapability(profileConfig.webSearch, `Profile "${profileId}" webSearch`);
1346
- validateFileCapabilities(profileConfig.fileCapabilities, `Profile "${profileId}" fileCapabilities`);
1347
- validateThinkingCapability(profileConfig.thinking, `Profile "${profileId}" thinking`);
1348
- const seenModelIds = /* @__PURE__ */ new Set();
1349
- for (const [index, modelConfig] of (profileConfig.models || []).entries()) {
1350
- if (!isPlainRecord2(modelConfig)) throw new Error(`Profile "${profileId}" model #${index} must be an object.`);
1351
- assertOnlyKeys(modelConfig, [
1352
- "id",
1353
- "api",
1354
- "name",
1355
- "reasoning",
1356
- "thinking",
1357
- "input",
1358
- "cost",
1359
- "contextWindow",
1360
- "maxTokens",
1361
- "transport",
1362
- "compat",
1363
- "cacheCapability",
1364
- "webSearch",
1365
- "fileCapabilities",
1366
- "headers",
1367
- "apiKeyEnv",
1368
- "displayName",
1369
- "filePlatform",
1370
- "attachmentPlatform"
1371
- ], `Profile "${profileId}" model #${index}`);
1372
- const modelMissing = [];
1373
- if (!modelConfig.id) modelMissing.push("id");
1374
- if (!Array.isArray(modelConfig.input) || modelConfig.input.length === 0) modelMissing.push("input");
1375
- if (!modelConfig.cost) modelMissing.push("cost");
1376
- if (!modelConfig.contextWindow) modelMissing.push("contextWindow");
1377
- if (!modelConfig.maxTokens) modelMissing.push("maxTokens");
1378
- if (modelMissing.length > 0) {
1379
- const label = modelConfig.id || `#${index}`;
1380
- throw new Error(
1381
- `Profile "${profileId}" model "${label}" is missing required field${modelMissing.length > 1 ? "s" : ""}: ${modelMissing.join(", ")}.`
1382
- );
1383
- }
1384
- validateRemoteModel(profileId, modelConfig);
1385
- const route = resolveProfileRoute(profileConfig, modelConfig);
1386
- validateThinkingCapabilityForApi(modelConfig.thinking ?? profileConfig.thinking, route.api, `Profile "${profileId}" model "${modelConfig.id}" thinking`);
1387
- assertHeadersShape(modelConfig.headers, `Profile "${profileId}" model "${modelConfig.id}"`);
1388
- assertOptionalEnvName(modelConfig.apiKeyEnv, `Profile "${profileId}" model "${modelConfig.id}" apiKeyEnv`);
1389
- if (seenModelIds.has(modelConfig.id)) throw new Error(`Profile "${profileId}" contains duplicate model "${modelConfig.id}".`);
1390
- seenModelIds.add(modelConfig.id);
1391
- }
1392
- }
1456
+
1457
+ // src/core/model-registry.ts
1393
1458
  var ModelRegistry = class {
1394
1459
  models = /* @__PURE__ */ new Map();
1395
1460
  loadError;
@@ -1411,7 +1476,7 @@ var ModelRegistry = class {
1411
1476
  activeOAuthUrls = /* @__PURE__ */ new Map();
1412
1477
  oauthProviderEpoch = /* @__PURE__ */ new Map();
1413
1478
  baseSnapshot;
1414
- constructor(authStorage, modelsPath = path.join(getConfigDir(), "models.json")) {
1479
+ constructor(authStorage, modelsPath = path2.join(getConfigDir(), "models.json")) {
1415
1480
  this.authStorage = authStorage;
1416
1481
  this.modelsPath = modelsPath;
1417
1482
  this.load();
@@ -1446,13 +1511,13 @@ var ModelRegistry = class {
1446
1511
  this.loadError = error instanceof Error ? error.message : String(error);
1447
1512
  return;
1448
1513
  }
1449
- if (!fs.existsSync(this.modelsPath)) {
1514
+ if (!fs2.existsSync(this.modelsPath)) {
1450
1515
  this.authStorage.replaceModelsConfigCredentials(/* @__PURE__ */ new Map(), /* @__PURE__ */ new Map());
1451
1516
  this.captureBaseline();
1452
1517
  return;
1453
1518
  }
1454
1519
  try {
1455
- const raw = JSON.parse(fs.readFileSync(this.modelsPath, "utf-8"));
1520
+ const raw = JSON.parse(fs2.readFileSync(this.modelsPath, "utf-8"));
1456
1521
  if (raw && typeof raw === "object" && "providers" in raw) {
1457
1522
  throw new Error('Legacy models.json format is no longer supported. Use top-level "profiles".');
1458
1523
  }
@@ -1678,23 +1743,23 @@ var ModelRegistry = class {
1678
1743
  writeRemoteCache(remote, fingerprint, value) {
1679
1744
  const directory = safeRemoteCacheDirectory(this.modelsPath, true);
1680
1745
  const target = remoteCachePath(this.modelsPath, remote, fingerprint);
1681
- if (fs.existsSync(target)) {
1682
- const stat = fs.lstatSync(target);
1746
+ if (fs2.existsSync(target)) {
1747
+ const stat = fs2.lstatSync(target);
1683
1748
  if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`remote catalog cache entry must be a regular file: ${target}`);
1684
1749
  }
1685
- const temporary = path.join(directory, `.${path.basename(target)}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`);
1750
+ const temporary = path2.join(directory, `.${path2.basename(target)}.${process.pid}.${randomBytes2(8).toString("hex")}.tmp`);
1686
1751
  try {
1687
- fs.writeFileSync(temporary, `${JSON.stringify(value)}
1752
+ fs2.writeFileSync(temporary, `${JSON.stringify(value)}
1688
1753
  `, { flag: "wx", mode: 384 });
1689
- fs.renameSync(temporary, target);
1754
+ fs2.renameSync(temporary, target);
1690
1755
  const tombstone = remoteCacheTombstonePath(this.modelsPath, remote, fingerprint);
1691
- if (fs.existsSync(tombstone)) fs.unlinkSync(tombstone);
1756
+ if (fs2.existsSync(tombstone)) fs2.unlinkSync(tombstone);
1692
1757
  } finally {
1693
- if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
1758
+ if (fs2.existsSync(temporary)) fs2.unlinkSync(temporary);
1694
1759
  }
1695
1760
  }
1696
1761
  refreshRemoteCatalogs() {
1697
- const queueKey = path.resolve(this.modelsPath);
1762
+ const queueKey = path2.resolve(this.modelsPath);
1698
1763
  const previous = remoteRefreshTails.get(queueKey) ?? Promise.resolve();
1699
1764
  const refresh = previous.then(() => this.performRemoteCatalogRefresh());
1700
1765
  const tail = refresh.catch(() => void 0);
@@ -1719,14 +1784,14 @@ var ModelRegistry = class {
1719
1784
  this.loadError = error instanceof Error ? error.message : String(error);
1720
1785
  return;
1721
1786
  }
1722
- if (!fs.existsSync(this.modelsPath)) {
1787
+ if (!fs2.existsSync(this.modelsPath)) {
1723
1788
  for (const owner of new Set(this.remoteCatalogByProvider.values())) this.removeRemoteCatalogProfiles(owner);
1724
1789
  this.remoteCredentialFingerprintByCatalog.clear();
1725
1790
  return;
1726
1791
  }
1727
1792
  let config;
1728
1793
  try {
1729
- const decoded = JSON.parse(fs.readFileSync(this.modelsPath, "utf8"));
1794
+ const decoded = JSON.parse(fs2.readFileSync(this.modelsPath, "utf8"));
1730
1795
  validateModelsDocumentShape(decoded);
1731
1796
  config = decoded;
1732
1797
  } catch {
@@ -1909,15 +1974,10 @@ var ModelRegistry = class {
1909
1974
  }
1910
1975
  const modelClassCandidates = [];
1911
1976
  for (const modelClass of MODEL_CLASS_FALLBACK_ORDER) {
1912
- const resolved = this.resolveModelClass(modelClass);
1913
- if (resolved.model && resolved.apiKey && modelSupportsToolPurpose(resolved.model, purpose)) {
1914
- modelClassCandidates.push({
1915
- purpose,
1916
- requiredCapability,
1917
- routeSource: "model_class",
1918
- model: resolved.model,
1919
- apiKey: resolved.apiKey
1920
- });
1977
+ for (const resolved of this.resolveModelClassCandidates(modelClass)) {
1978
+ if (modelSupportsToolPurpose(resolved.model, purpose)) {
1979
+ modelClassCandidates.push({ purpose, requiredCapability, routeSource: "model_class", model: resolved.model, apiKey: resolved.apiKey });
1980
+ }
1921
1981
  }
1922
1982
  }
1923
1983
  for (const decision of sortToolModelCandidatesByCapability(purpose, modelClassCandidates)) add(decision);
@@ -1948,20 +2008,44 @@ var ModelRegistry = class {
1948
2008
  }
1949
2009
  return results;
1950
2010
  }
1951
- resolveModelClass(modelClass) {
1952
- const configured = this.configDefaults?.modelClasses?.[modelClass];
1953
- if (!configured?.provider || !configured?.modelId) {
1954
- return { fallbackReason: `models.json defaults.modelClasses.${modelClass} is not configured` };
1955
- }
1956
- const model = this.find(configured.provider, configured.modelId);
1957
- if (!model) {
1958
- return { fallbackReason: `models.json defaults.modelClasses.${modelClass} points to missing model ${configured.provider}/${configured.modelId}` };
2011
+ resolveModelClassCandidates(modelClass) {
2012
+ const entries = normalizeModelClassRoutes(this.configDefaults?.modelClasses?.[modelClass]);
2013
+ const out = [];
2014
+ const seen = /* @__PURE__ */ new Set();
2015
+ for (const configured of entries) {
2016
+ if (!configured.provider || !configured.modelId) continue;
2017
+ const model = this.find(configured.provider, configured.modelId);
2018
+ if (!model) continue;
2019
+ const apiKey = this.getApiKey(model);
2020
+ if (!apiKey) continue;
2021
+ const key = `${model.provider}/${model.id}`;
2022
+ if (seen.has(key)) continue;
2023
+ seen.add(key);
2024
+ out.push({ model, apiKey });
1959
2025
  }
1960
- const apiKey = this.getApiKey(model);
1961
- if (!apiKey) {
1962
- return { model, fallbackReason: `no API key available for model class ${modelClass} (${configured.provider}/${configured.modelId})` };
2026
+ return out;
2027
+ }
2028
+ resolveModelClass(modelClass) {
2029
+ const entries = normalizeModelClassRoutes(this.configDefaults?.modelClasses?.[modelClass]);
2030
+ const complete = entries.filter((entry) => Boolean(entry.provider && entry.modelId));
2031
+ if (complete.length === 0) return { fallbackReason: `models.json defaults.modelClasses.${modelClass} is not configured` };
2032
+ let firstModel;
2033
+ let firstReason;
2034
+ for (const configured of complete) {
2035
+ const model = this.find(configured.provider, configured.modelId);
2036
+ if (!model) {
2037
+ firstReason ??= `models.json defaults.modelClasses.${modelClass} points to missing model ${configured.provider}/${configured.modelId}`;
2038
+ continue;
2039
+ }
2040
+ const apiKey = this.getApiKey(model);
2041
+ if (!apiKey) {
2042
+ firstModel ??= model;
2043
+ firstReason ??= `no API key available for model class ${modelClass} (${configured.provider}/${configured.modelId})`;
2044
+ continue;
2045
+ }
2046
+ return { model, apiKey };
1963
2047
  }
1964
- return { model, apiKey };
2048
+ return { ...firstModel ? { model: firstModel } : {}, fallbackReason: firstReason };
1965
2049
  }
1966
2050
  /** Resolve an explicit model reference for user-requested overrides.
1967
2051
  * Accepts "provider/model-id" (exact lookup) or a bare model id (only
@@ -2267,12 +2351,12 @@ var ModelRegistry = class {
2267
2351
 
2268
2352
  export {
2269
2353
  mergeThinkingCapability,
2270
- assertNoSecretSubstrings,
2271
- configuredRemoteCredentialValues,
2272
2354
  validatedRemoteCatalogs,
2273
2355
  validateModelsDocumentShape,
2274
- loadResolvedModelsConfig,
2275
2356
  resolveProfileRoute,
2276
2357
  validateProfileConfig,
2358
+ assertNoSecretSubstrings,
2359
+ configuredRemoteCredentialValues,
2360
+ loadResolvedModelsConfig,
2277
2361
  ModelRegistry
2278
2362
  };