@cydm/pie 4.13.1 → 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 (27) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +2 -2
  2. package/dist/builtin/extensions/im-forward/index.js +8092 -8098
  3. package/dist/builtin/extensions/mcp-adapter/index.js +86 -81
  4. package/dist/builtin/extensions/memory/index.js +28 -5
  5. package/dist/builtin/extensions/pie-ipc/index.js +13 -18
  6. package/dist/builtin/extensions/pie-proc/index.js +61 -55
  7. package/dist/builtin/extensions/plan-mode/index.js +2 -2
  8. package/dist/builtin/extensions/subagent/index.js +3 -3
  9. package/dist/builtin/extensions/todo/index.js +2 -2
  10. package/dist/chunks/{chunk-6Z54UHXM.js → chunk-BOQIGMGQ.js} +20 -15
  11. package/dist/chunks/{chunk-XPJHZRTN.js → chunk-EZZTMDWZ.js} +712 -378
  12. package/dist/chunks/{chunk-HSMO2BEA.js → chunk-FD3KBPDR.js} +23 -18
  13. package/dist/chunks/{chunk-3F2CSVNH.js → chunk-IK2FR2YF.js} +2 -1
  14. package/dist/chunks/{chunk-CCPNHS6B.js → chunk-JJH77AUU.js} +1578 -1566
  15. package/dist/chunks/{chunk-DT22BBZL.js → chunk-JKO42HZW.js} +1 -1
  16. package/dist/chunks/{chunk-UCVPNLCO.js → chunk-KGWKRO7Z.js} +1 -1
  17. package/dist/chunks/{chunk-NHWWRE3T.js → chunk-UYDS75SI.js} +725 -718
  18. package/dist/chunks/{host-image-fallback-LGWYQMLA.js → host-image-fallback-LPHB5CTL.js} +1 -1
  19. package/dist/chunks/{manager-cli-OTIMAWO6.js → manager-cli-ZV36YNPJ.js} +187 -173
  20. package/dist/chunks/{memory-git-7SRO5KLB.js → memory-git-ZJN6SPIU.js} +3 -3
  21. package/dist/chunks/{model-registry-IWOOAMLZ.js → model-registry-GLBIUOJR.js} +1 -1
  22. package/dist/chunks/{read-file-understanding-3TYWVOLX.js → read-file-understanding-DFJPTTSB.js} +3 -3
  23. package/dist/chunks/{src-WA2O2O2V.js → src-KZ7YID3I.js} +1 -1
  24. package/dist/chunks/{src-D2ICRXWW.js → src-LEXKDSFV.js} +22 -4
  25. package/dist/cli.js +2859 -2741
  26. package/package.json +1 -1
  27. package/dist/chunks/{chunk-3GG342QY.js → chunk-TYCKSYUF.js} +19 -19
@@ -16,9 +16,9 @@ import {
16
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,75 +478,7 @@ function validateGameUseConfig(value) {
410
478
  validateEndpoint(record.visualDecision, "models.json gameUse.visualDecision");
411
479
  }
412
480
 
413
- // src/core/model-class-config.ts
414
- var MODEL_CLASS_NAMES = ["light", "balanced", "strong"];
415
- var TOOL_MODEL_NAMES = [
416
- "web_search",
417
- "read_file.image",
418
- "read_file.video",
419
- "read_file.audio",
420
- "read_file.document"
421
- ];
422
- function isPlainRecord2(value) {
423
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
424
- }
425
- function assertOnlyKeys(value, allowed, label) {
426
- const allowedSet = new Set(allowed);
427
- for (const key of Object.keys(value)) {
428
- if (!allowedSet.has(key)) {
429
- throw new Error(`${label} contains unsupported field "${key}"`);
430
- }
431
- }
432
- }
433
- function assertOptionalString(value, label) {
434
- if (value !== void 0 && (typeof value !== "string" || !value)) {
435
- throw new Error(`${label} must be a non-empty string`);
436
- }
437
- }
438
- function validateRouteObject(route, label) {
439
- if (!isPlainRecord2(route)) {
440
- throw new Error(`${label} must be an object`);
441
- }
442
- assertOnlyKeys(route, ["provider", "modelId"], label);
443
- assertOptionalString(route.provider, `${label}.provider`);
444
- assertOptionalString(route.modelId, `${label}.modelId`);
445
- }
446
- function normalizeModelClassRoutes(entry) {
447
- if (!entry) return [];
448
- return Array.isArray(entry) ? entry : [entry];
449
- }
450
- function validateDefaultsModelClasses(routes) {
451
- if (routes === void 0) return;
452
- if (!isPlainRecord2(routes)) {
453
- throw new Error("models.json defaults.modelClasses must be an object");
454
- }
455
- assertOnlyKeys(routes, MODEL_CLASS_NAMES, "models.json defaults.modelClasses");
456
- for (const [routeName, route] of Object.entries(routes)) {
457
- const label = `models.json defaults.modelClasses.${routeName}`;
458
- if (Array.isArray(route)) {
459
- if (route.length === 0) {
460
- throw new Error(`${label} must not be an empty array`);
461
- }
462
- for (let i = 0; i < route.length; i++) {
463
- validateRouteObject(route[i], `${label}[${i}]`);
464
- }
465
- } else {
466
- validateRouteObject(route, label);
467
- }
468
- }
469
- }
470
- function validateDefaultsToolModels(routes) {
471
- if (routes === void 0) return;
472
- if (!isPlainRecord2(routes)) {
473
- throw new Error("models.json defaults.toolModels must be an object");
474
- }
475
- assertOnlyKeys(routes, TOOL_MODEL_NAMES, "models.json defaults.toolModels");
476
- for (const [routeName, route] of Object.entries(routes)) {
477
- validateRouteObject(route, `models.json defaults.toolModels.${routeName}`);
478
- }
479
- }
480
-
481
- // src/core/model-registry.ts
481
+ // src/core/model-registry-config.ts
482
482
  var MODEL_OVERRIDE_KEYS = [
483
483
  "name",
484
484
  "reasoning",
@@ -517,29 +517,7 @@ function validateExtensionProviderConfig(provider, config) {
517
517
  validateFileCapabilities(model.fileCapabilities, `registerProvider("${provider}") model "${model.id}" fileCapabilities`);
518
518
  }
519
519
  }
520
- var REMOTE_CATALOG_CACHE_VERSION = 4;
521
520
  var SUPPORTED_REMOTE_APIS = /* @__PURE__ */ new Set(["openai-completions", "anthropic-messages", "openai-responses"]);
522
- var MAX_REMOTE_CATALOG_BYTES = 2 * 1024 * 1024;
523
- var OAUTH_RESTORE_LEEWAY_MS = 6e4;
524
- var OAUTH_REFRESH_TIMEOUT_MS = 3e4;
525
- function withTimeout(promise, ms, timeoutMessage) {
526
- return new Promise((resolve2, reject) => {
527
- const timer = setTimeout(() => reject(new Error(timeoutMessage)), ms);
528
- Promise.resolve(promise).then(
529
- (value) => {
530
- clearTimeout(timer);
531
- resolve2(value);
532
- },
533
- (error) => {
534
- clearTimeout(timer);
535
- reject(error);
536
- }
537
- );
538
- });
539
- }
540
- var REMOTE_REFRESH_LOCK_WAIT_MS = 6e4;
541
- var REMOTE_REFRESH_LOCK_WRITE_GRACE_MS = 1e3;
542
- var remoteRefreshTails = /* @__PURE__ */ new Map();
543
521
  var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
544
522
  "connection",
545
523
  "keep-alive",
@@ -552,463 +530,128 @@ var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
552
530
  "host",
553
531
  "content-length"
554
532
  ]);
555
- function canonicalRemote(remote) {
556
- const url = new URL(remote.url);
557
- return { id: remote.id, url: url.href, apiKeyEnv: remote.apiKeyEnv };
558
- }
559
- function remoteIdentityDigest(remote) {
560
- return createHash("sha256").update(JSON.stringify({ version: REMOTE_CATALOG_CACHE_VERSION, ...canonicalRemote(remote) })).digest("hex");
561
- }
562
- function remoteCacheDirectory(modelsPath) {
563
- return path.join(path.dirname(modelsPath), "cache", "remote-catalogs");
564
- }
565
- function safeRemoteCacheDirectory(modelsPath, create) {
566
- const configDirectory = path.dirname(modelsPath);
567
- if (!fs.existsSync(configDirectory)) {
568
- if (!create) return void 0;
569
- fs.mkdirSync(configDirectory, { recursive: true, mode: 448 });
570
- }
571
- const configRoot = fs.realpathSync(configDirectory);
572
- const cacheRoot = path.join(configDirectory, "cache");
573
- const directory = remoteCacheDirectory(modelsPath);
574
- for (const candidate of [cacheRoot, directory]) {
575
- if (!fs.existsSync(candidate)) {
576
- if (!create) return void 0;
577
- fs.mkdirSync(candidate, { mode: 448 });
578
- }
579
- const stat = fs.lstatSync(candidate);
580
- if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error(`remote catalog cache path must be a real directory: ${candidate}`);
581
- const canonical = fs.realpathSync(candidate);
582
- const relative2 = path.relative(configRoot, canonical);
583
- if (relative2 === ".." || relative2.startsWith(`..${path.sep}`) || path.isAbsolute(relative2)) {
584
- throw new Error(`remote catalog cache path escapes the config directory: ${candidate}`);
585
- }
586
- try {
587
- fs.chmodSync(candidate, 448);
588
- } catch {
589
- }
590
- }
591
- return directory;
592
- }
593
- function remoteRefreshLockPath(modelsPath) {
594
- return path.join(remoteCacheDirectory(modelsPath), ".refresh.lock");
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;
595
537
  }
596
- function processIsAlive(pid) {
597
- if (!Number.isSafeInteger(pid) || pid <= 0) return false;
598
- try {
599
- process.kill(pid, 0);
600
- return true;
601
- } catch (error) {
602
- return error.code === "EPERM";
603
- }
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}`);
604
542
  }
605
- function remoteRefreshLockIsStale(lockPath) {
606
- const stat = fs.lstatSync(lockPath);
607
- if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`remote catalog refresh lock must be a regular file: ${lockPath}`);
608
- let owner;
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;
609
550
  try {
610
- owner = JSON.parse(fs.readFileSync(lockPath, "utf8"));
551
+ url = new URL(value.url);
611
552
  } catch {
553
+ throw new Error(`${label}.url must be an absolute URL`);
612
554
  }
613
- const age = Date.now() - stat.mtimeMs;
614
- const validOwner = owner?.version === 1 && Number.isSafeInteger(owner.pid) && typeof owner.token === "string" && typeof owner.createdAt === "number";
615
- if (validOwner && processIsAlive(Number(owner.pid))) return false;
616
- return validOwner || age > REMOTE_REFRESH_LOCK_WRITE_GRACE_MS;
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 };
617
561
  }
618
- function sameFileIdentity(left, right, leftPath, rightPath) {
619
- if (left.dev !== right.dev || left.ino !== right.ino) return false;
620
- if (left.ino !== 0) return true;
621
- return left.size === right.size && fs.readFileSync(leftPath).equals(fs.readFileSync(rightPath));
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);
571
+ }
572
+ return catalogs;
622
573
  }
623
- function reclaimStaleRemoteRefreshLock(lockPath) {
624
- if (!remoteRefreshLockIsStale(lockPath)) return false;
625
- const claimPath = `${lockPath}.reclaim-${process.pid}-${randomBytes(8).toString("hex")}`;
626
- try {
627
- fs.linkSync(lockPath, claimPath);
628
- const claimed = fs.lstatSync(claimPath);
629
- const current = fs.lstatSync(lockPath);
630
- if (claimed.isSymbolicLink() || !claimed.isFile() || current.isSymbolicLink() || !current.isFile() || !sameFileIdentity(claimed, current, claimPath, lockPath)) return false;
631
- if (!remoteRefreshLockIsStale(claimPath)) return false;
632
- fs.unlinkSync(lockPath);
633
- return true;
634
- } catch (error) {
635
- if (["ENOENT", "EEXIST"].includes(error.code ?? "")) return false;
636
- throw error;
637
- } finally {
638
- try {
639
- fs.unlinkSync(claimPath);
640
- } catch {
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);
641
587
  }
642
588
  }
643
- }
644
- async function acquireRemoteRefreshLock(modelsPath) {
645
- const directory = safeRemoteCacheDirectory(modelsPath, true);
646
- const lockPath = remoteRefreshLockPath(modelsPath);
647
- const deadline = Date.now() + REMOTE_REFRESH_LOCK_WAIT_MS;
648
- while (true) {
649
- const token = randomBytes(16).toString("hex");
650
- try {
651
- const fd = fs.openSync(lockPath, "wx", 384);
652
- try {
653
- fs.writeFileSync(fd, `${JSON.stringify({ version: 1, pid: process.pid, token, createdAt: Date.now() })}
654
- `);
655
- } finally {
656
- fs.closeSync(fd);
657
- }
658
- return () => {
659
- try {
660
- const stat = fs.lstatSync(lockPath);
661
- if (stat.isSymbolicLink() || !stat.isFile()) return;
662
- const current = JSON.parse(fs.readFileSync(lockPath, "utf8"));
663
- if (current.token === token) fs.unlinkSync(lockPath);
664
- } catch {
665
- }
666
- };
667
- } catch (error) {
668
- if (error.code !== "EEXIST") throw error;
669
- try {
670
- if (reclaimStaleRemoteRefreshLock(lockPath)) continue;
671
- } catch (lockError) {
672
- if (lockError.code === "ENOENT") continue;
673
- throw lockError;
674
- }
675
- if (Date.now() >= deadline) throw new Error(`timed out waiting for remote catalog refresh lock: ${lockPath}`);
676
- await new Promise((resolve2) => setTimeout(resolve2, 25));
677
- }
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);
678
599
  }
679
600
  }
680
- function readSafeRemoteCacheFile(directory, filepath) {
681
- const stat = fs.lstatSync(filepath);
682
- if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`remote catalog cache entry must be a regular file: ${filepath}`);
683
- const canonicalDirectory = fs.realpathSync(directory);
684
- const canonicalFile = fs.realpathSync(filepath);
685
- const relative2 = path.relative(canonicalDirectory, canonicalFile);
686
- if (!relative2 || relative2 === ".." || relative2.startsWith(`..${path.sep}`) || path.isAbsolute(relative2)) {
687
- throw new Error(`remote catalog cache entry escapes its cache directory: ${filepath}`);
688
- }
689
- return fs.readFileSync(filepath);
601
+ function assertOptionalString2(value, label) {
602
+ if (value !== void 0 && (typeof value !== "string" || !value)) throw new Error(`${label} must be a non-empty string`);
690
603
  }
691
- function credentialNamespaceKey(modelsPath, create) {
692
- const directory = safeRemoteCacheDirectory(modelsPath, create);
693
- if (!directory) return void 0;
694
- const keyPath = path.join(directory, ".credential-namespace-key");
695
- if (!fs.existsSync(keyPath) && !create) return void 0;
696
- if (create && !fs.existsSync(keyPath)) {
697
- try {
698
- fs.writeFileSync(keyPath, randomBytes(32), { flag: "wx", mode: 384 });
699
- } catch (error) {
700
- if (!isPlainRecord3(error) || error.code !== "EEXIST") throw error;
701
- }
702
- }
703
- const key = readSafeRemoteCacheFile(directory, keyPath);
704
- if (key.byteLength !== 32) throw new Error("remote catalog credential namespace key is invalid");
705
- try {
706
- fs.chmodSync(keyPath, 384);
707
- } catch {
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`);
708
607
  }
709
- return key;
710
- }
711
- function credentialFingerprint(modelsPath, remote, credential, create = false) {
712
- const key = credentialNamespaceKey(modelsPath, create);
713
- if (!key) return void 0;
714
- return createHmac("sha256", key).update(remoteIdentityDigest(remote)).update("\0").update(credential).digest("hex");
715
608
  }
716
- function remoteCachePath(modelsPath, remote, fingerprint) {
717
- return path.join(remoteCacheDirectory(modelsPath), `${remoteIdentityDigest(remote)}-${fingerprint}.json`);
609
+ function assertOptionalBoolean(value, label) {
610
+ if (value !== void 0 && typeof value !== "boolean") throw new Error(`${label} must be a boolean`);
718
611
  }
719
- function pruneLegacyRemoteCatalogCaches(modelsPath) {
720
- const directory = safeRemoteCacheDirectory(modelsPath, false);
721
- if (!directory) return;
722
- for (const name of fs.readdirSync(directory)) {
723
- if (!name.endsWith(".json")) continue;
724
- const filepath = path.join(directory, name);
725
- try {
726
- const value = JSON.parse(readSafeRemoteCacheFile(directory, filepath).toString("utf8"));
727
- if (value.version === REMOTE_CATALOG_CACHE_VERSION) continue;
728
- } catch {
729
- let stat;
730
- try {
731
- stat = fs.lstatSync(filepath);
732
- } catch {
733
- continue;
734
- }
735
- if (stat.isSymbolicLink() || !stat.isFile()) continue;
736
- }
737
- try {
738
- fs.unlinkSync(filepath);
739
- } catch {
740
- }
741
- }
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`);
742
618
  }
743
- function scrubActiveSecretsFromRemoteCaches(modelsPath, activeSecrets) {
744
- if (activeSecrets.length === 0) return;
745
- const directory = safeRemoteCacheDirectory(modelsPath, false);
746
- if (!directory) return;
747
- const handle = fs.opendirSync(directory);
748
- try {
749
- let scanned = 0;
750
- while (true) {
751
- const entry = handle.readSync();
752
- if (!entry) break;
753
- if (++scanned > 1e4) throw new Error("remote catalog cache directory exceeds the hygiene scan limit");
754
- const isCache = entry.name.endsWith(".json");
755
- const isOrphanedTemporary = /^\..+\.json\.\d+\.[0-9a-f]+\.tmp$/.test(entry.name);
756
- if (!entry.isFile() || !isCache && !isOrphanedTemporary) continue;
757
- const filepath = path.join(directory, entry.name);
758
- try {
759
- const raw = readSafeRemoteCacheFile(directory, filepath).toString("utf8");
760
- assertNoSecretSubstrings(raw, activeSecrets, "remote catalog cache");
761
- } catch {
762
- try {
763
- const stat = fs.lstatSync(filepath);
764
- if (!stat.isSymbolicLink() && stat.isFile()) fs.unlinkSync(filepath);
765
- } catch {
766
- }
767
- }
768
- }
769
- } finally {
770
- handle.closeSync();
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`);
771
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`);
772
629
  }
773
- function payloadDigest(payload) {
774
- return createHash("sha256").update(JSON.stringify(payload)).digest("hex");
775
- }
776
- function assertNoSecretSubstrings(value, secrets, label) {
777
- const active = [...new Set(secrets.filter((secret) => secret.length > 0))];
778
- if (active.length === 0) return;
779
- const seen = /* @__PURE__ */ new Set();
780
- const visit = (candidate) => {
781
- if (typeof candidate === "string") {
782
- if (active.some((secret) => candidate.includes(secret))) throw new Error(`${label} reflects an active credential`);
783
- return;
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`);
784
642
  }
785
- if (!candidate || typeof candidate !== "object" || seen.has(candidate)) return;
786
- seen.add(candidate);
787
- if (Array.isArray(candidate)) {
788
- for (const item of candidate) visit(item);
789
- return;
643
+ if (Array.isArray(capability.formats) && new Set(capability.formats).size !== capability.formats.length) {
644
+ throw new Error(`${label}.${kind}.formats contains duplicates`);
790
645
  }
791
- for (const [key, item] of Object.entries(candidate)) {
792
- visit(key);
793
- visit(item);
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`);
649
+ }
794
650
  }
795
- };
796
- visit(value);
797
- const serialized = JSON.stringify(value);
798
- if (active.some((secret) => serialized.includes(secret))) throw new Error(`${label} reflects an active credential`);
799
- }
800
- function safeRemoteText(value, secrets) {
801
- let message = String(value);
802
- const active = [...new Set(secrets.filter(Boolean))];
803
- const replacement = active.some((secret) => "[REDACTED]".includes(secret)) ? "" : "[REDACTED]";
804
- for (const secret of active) message = message.split(secret).join(replacement);
805
- message = message.slice(0, 1024);
806
- if (!active.some((secret) => message.includes(secret))) return message;
807
- return "";
808
- }
809
- function safeRemoteError(error, secrets) {
810
- return safeRemoteText(error instanceof Error ? `${error.name}: ${error.message}` : String(error), secrets);
811
- }
812
- function warnRemoteCatalog(message, secrets) {
813
- console.warn(safeRemoteText(message, secrets));
814
- }
815
- function configuredRemoteCredentialValues(config) {
816
- let remotes;
817
- try {
818
- remotes = validatedRemoteCatalogs(config.remoteCatalogs);
819
- } catch {
820
- return [];
821
651
  }
822
- return [...new Set(remotes.map((remote) => process.env[remote.apiKeyEnv]).filter((secret) => typeof secret === "string" && secret.length > 0))];
823
652
  }
824
- function sameRemoteIdentity(left, right) {
825
- if (!left || typeof left !== "object" || Array.isArray(left)) return false;
826
- const value = left;
827
- const expected = canonicalRemote(right);
828
- return value.id === expected.id && value.url === expected.url && value.apiKeyEnv === expected.apiKeyEnv;
829
- }
830
- function readRemoteCache(modelsPath, remote, fingerprint, activeSecrets) {
831
- try {
832
- const directory = safeRemoteCacheDirectory(modelsPath, false);
833
- if (!directory) return void 0;
834
- const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
835
- if (fs.existsSync(tombstone)) return void 0;
836
- const value = JSON.parse(readSafeRemoteCacheFile(directory, remoteCachePath(modelsPath, remote, fingerprint)).toString("utf8"));
837
- 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;
838
- assertNoSecretSubstrings({ etag: value.etag, payload: value.payload }, activeSecrets, "remote catalog cache");
839
- const payload = sanitizeRemotePayload(value.payload, canonicalRemote(remote), new URL(remote.url), true);
840
- if (payloadDigest(payload) !== value.payloadSha256) return void 0;
841
- return { ...value, payload };
842
- } catch {
843
- removeRemoteCache(modelsPath, remote, fingerprint);
844
- return void 0;
845
- }
846
- }
847
- function remoteCacheTombstonePath(modelsPath, remote, fingerprint) {
848
- return `${remoteCachePath(modelsPath, remote, fingerprint)}.revoked`;
849
- }
850
- function removeRemoteCache(modelsPath, remote, fingerprint) {
851
- try {
852
- const directory = safeRemoteCacheDirectory(modelsPath, false);
853
- if (!directory) return;
854
- const filepath = remoteCachePath(modelsPath, remote, fingerprint);
855
- if (fs.existsSync(filepath)) {
856
- const stat = fs.lstatSync(filepath);
857
- if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`remote catalog cache entry is not a regular file: ${filepath}`);
858
- fs.unlinkSync(filepath);
859
- }
860
- const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
861
- if (fs.existsSync(tombstone)) fs.unlinkSync(tombstone);
862
- return;
863
- } catch (error) {
864
- const directory = safeRemoteCacheDirectory(modelsPath, true);
865
- if (!directory) throw error;
866
- const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
867
- try {
868
- fs.writeFileSync(tombstone, `${JSON.stringify({ version: 1, revoked: true })}
869
- `, { flag: "wx", mode: 384 });
870
- } catch (tombstoneError) {
871
- if (!fs.existsSync(tombstone)) throw tombstoneError;
872
- }
873
- }
874
- }
875
- function validateRemoteEndpoint(baseUrl, catalogUrl, label) {
876
- let endpoint;
877
- try {
878
- endpoint = new URL(baseUrl);
879
- } catch {
880
- throw new Error(`${label} baseUrl must be an absolute URL`);
881
- }
882
- if (endpoint.protocol !== "https:" && endpoint.hostname !== "127.0.0.1" && endpoint.hostname !== "localhost") {
883
- throw new Error(`${label} baseUrl must use HTTPS`);
884
- }
885
- if (endpoint.username || endpoint.password) throw new Error(`${label} baseUrl must not contain credentials`);
886
- if (endpoint.hash) throw new Error(`${label} baseUrl must not contain a fragment`);
887
- if (endpoint.search) throw new Error(`${label} baseUrl must not contain query parameters`);
888
- if (endpoint.origin !== catalogUrl.origin) throw new Error(`${label} baseUrl must use the authenticated catalog origin`);
889
- }
890
- function isPlainRecord3(value) {
891
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
892
- const prototype = Object.getPrototypeOf(value);
893
- return prototype === Object.prototype || prototype === null;
894
- }
895
- function assertOnlyKeys2(value, allowed, label) {
896
- const allowedSet = new Set(allowed);
897
- const unexpected = Object.keys(value).find((key) => !allowedSet.has(key));
898
- if (unexpected) throw new Error(`${label} contains unsupported field ${unexpected}`);
899
- }
900
- function validateRemoteCatalogConfig(value, label) {
901
- if (!isPlainRecord3(value)) throw new Error(`${label} must be an object`);
902
- assertOnlyKeys2(value, ["id", "url", "apiKeyEnv"], label);
903
- 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`);
904
- if (typeof value.url !== "string" || !value.url) throw new Error(`${label}.url must be a URL`);
905
- 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`);
906
- let url;
907
- try {
908
- url = new URL(value.url);
909
- } catch {
910
- throw new Error(`${label}.url must be an absolute URL`);
911
- }
912
- const localTestHost = url.hostname === "127.0.0.1" || url.hostname === "localhost";
913
- if (url.protocol !== "https:" && !localTestHost) throw new Error(`${label}.url must use HTTPS`);
914
- if (url.username || url.password) throw new Error(`${label}.url must not contain credentials`);
915
- if (url.hash) throw new Error(`${label}.url must not contain a fragment`);
916
- if (url.search) throw new Error(`${label}.url must not contain query parameters`);
917
- return canonicalRemote({ id: value.id, url: url.href, apiKeyEnv: value.apiKeyEnv });
918
- }
919
- function validatedRemoteCatalogs(value) {
920
- if (value === void 0) return [];
921
- if (!Array.isArray(value)) throw new Error("models.json remoteCatalogs must be an array");
922
- if (value.length === 0) throw new Error("models.json remoteCatalogs must be a non-empty array");
923
- const catalogs = value.map((item, index) => validateRemoteCatalogConfig(item, `models.json remoteCatalogs[${index}]`));
924
- const ids = /* @__PURE__ */ new Set();
925
- for (const catalog of catalogs) {
926
- if (ids.has(catalog.id)) throw new Error(`models.json remoteCatalogs contains duplicate id ${catalog.id}`);
927
- ids.add(catalog.id);
928
- }
929
- return catalogs;
930
- }
931
- function validateModelsDocumentShape(value) {
932
- if (!isPlainRecord3(value)) throw new Error("models.json must be an object");
933
- assertOnlyKeys2(value, ["$schema", "profiles", "remoteCatalogs", "defaults", "modelOverrides", "voice", "gameUse"], "models.json");
934
- if (value.$schema !== void 0 && (typeof value.$schema !== "string" || !value.$schema)) throw new Error("models.json $schema must be a non-empty string");
935
- const hasProfiles = Object.prototype.hasOwnProperty.call(value, "profiles");
936
- const hasRemoteCatalogs = Object.prototype.hasOwnProperty.call(value, "remoteCatalogs");
937
- if (!hasProfiles && !hasRemoteCatalogs) throw new Error("models.json must define profiles or remoteCatalogs");
938
- validatedRemoteCatalogs(value.remoteCatalogs);
939
- if (hasProfiles) {
940
- if (!isPlainRecord3(value.profiles) || Object.keys(value.profiles).length === 0) throw new Error("models.json profiles must be a non-empty object");
941
- for (const [profileId, profile] of Object.entries(value.profiles)) {
942
- if (!profileId || profileId !== profileId.trim() || /\s/.test(profileId)) throw new Error(`models.json profile id is invalid: ${profileId}`);
943
- validateProfileConfig(profileId, profile);
944
- }
945
- }
946
- validateModelOverrides(value.modelOverrides);
947
- validateVoiceConfig(value.voice);
948
- validateGameUseConfig(value.gameUse);
949
- if (value.defaults !== void 0) {
950
- if (!isPlainRecord3(value.defaults)) throw new Error("models.json defaults must be an object");
951
- assertOnlyKeys2(value.defaults, ["provider", "modelId", "modelClasses", "toolModels"], "models.json defaults");
952
- assertOptionalString2(value.defaults.provider, "models.json defaults.provider");
953
- assertOptionalString2(value.defaults.modelId, "models.json defaults.modelId");
954
- validateDefaultsModelClasses(value.defaults.modelClasses);
955
- validateDefaultsToolModels(value.defaults.toolModels);
956
- }
957
- }
958
- function assertOptionalString2(value, label) {
959
- if (value !== void 0 && (typeof value !== "string" || !value)) throw new Error(`${label} must be a non-empty string`);
960
- }
961
- function assertOptionalEnvName(value, label) {
962
- if (value !== void 0 && (typeof value !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value))) {
963
- throw new Error(`${label} must be an environment variable name`);
964
- }
965
- }
966
- function assertOptionalBoolean(value, label) {
967
- if (value !== void 0 && typeof value !== "boolean") throw new Error(`${label} must be a boolean`);
968
- }
969
- function validateCacheCapability(value, label) {
970
- if (value === void 0) return;
971
- if (!isPlainRecord3(value) || !["none", "session_store", "prompt_cache", "usage_only"].includes(String(value.mode)) || typeof value.supported !== "boolean") throw new Error(`${label} is invalid`);
972
- assertOnlyKeys2(value, ["mode", "supported", "supportsUsageMetrics", "description"], label);
973
- assertOptionalBoolean(value.supportsUsageMetrics, `${label}.supportsUsageMetrics`);
974
- assertOptionalString2(value.description, `${label}.description`);
975
- }
976
- function validateWebSearchCapability(value, label) {
977
- if (value === void 0) return;
978
- if (!isPlainRecord3(value) || !["anthropic_server_tool", "chat_completions_web_search", "openai_responses"].includes(String(value.type))) {
979
- throw new Error(`${label} is invalid`);
980
- }
981
- assertOnlyKeys2(value, ["type", "forceToolChoice", "searchEngine", "count", "contentSize"], label);
982
- assertOptionalBoolean(value.forceToolChoice, `${label}.forceToolChoice`);
983
- assertOptionalString2(value.searchEngine, `${label}.searchEngine`);
984
- if (value.count !== void 0 && (!Number.isInteger(value.count) || Number(value.count) < 1)) throw new Error(`${label}.count is invalid`);
985
- if (value.contentSize !== void 0 && !["low", "medium", "high"].includes(String(value.contentSize))) throw new Error(`${label}.contentSize is invalid`);
986
- }
987
- function validateFileCapabilities(value, label) {
988
- if (value === void 0) return;
989
- if (!isPlainRecord3(value)) throw new Error(`${label} is invalid`);
990
- for (const [kind, capability] of Object.entries(value)) {
991
- if (!["image", "video", "audio", "document"].includes(kind)) throw new Error(`${label}.${kind} is unsupported`);
992
- if (typeof capability === "boolean") continue;
993
- if (!isPlainRecord3(capability)) throw new Error(`${label}.${kind} is invalid`);
994
- assertOnlyKeys2(capability, ["supported", "formats", "maxFileSizeMb", "maxDurationSeconds", "nativeInline"], `${label}.${kind}`);
995
- assertOptionalBoolean(capability.supported, `${label}.${kind}.supported`);
996
- assertOptionalBoolean(capability.nativeInline, `${label}.${kind}.nativeInline`);
997
- if (capability.formats !== void 0 && (!Array.isArray(capability.formats) || capability.formats.some((item) => typeof item !== "string" || !item))) {
998
- throw new Error(`${label}.${kind}.formats is invalid`);
999
- }
1000
- if (Array.isArray(capability.formats) && new Set(capability.formats).size !== capability.formats.length) {
1001
- throw new Error(`${label}.${kind}.formats contains duplicates`);
1002
- }
1003
- for (const field of ["maxFileSizeMb", "maxDurationSeconds"]) {
1004
- if (capability[field] !== void 0 && (typeof capability[field] !== "number" || !Number.isFinite(capability[field]) || capability[field] <= 0)) {
1005
- throw new Error(`${label}.${kind}.${field} is invalid`);
1006
- }
1007
- }
1008
- }
1009
- }
1010
- function validateTransport(value, label) {
1011
- if (value !== void 0 && value !== "sse" && value !== "websocket" && value !== "auto") throw new Error(`${label}.transport is invalid`);
653
+ function validateTransport(value, label) {
654
+ if (value !== void 0 && value !== "sse" && value !== "websocket" && value !== "auto") throw new Error(`${label}.transport is invalid`);
1012
655
  }
1013
656
  function validateCompat(value, label) {
1014
657
  if (value === void 0) return;
@@ -1102,31 +745,547 @@ function validateRemoteModel(profileId, model) {
1102
745
  if (!Number.isSafeInteger(model.contextWindow) || Number(model.contextWindow) <= 0 || !Number.isSafeInteger(model.maxTokens) || Number(model.maxTokens) <= 0 || Number(model.maxTokens) > Number(model.contextWindow)) {
1103
746
  throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid token limits`);
1104
747
  }
1105
- if (new Set(model.input).size !== model.input.length) throw new Error(`Remote profile "${profileId}" model "${model.id}" has duplicate input capabilities`);
1106
- validateTransport(model.transport, `Model "${model.id}"`);
1107
- validateCompat(model.compat, `Remote profile "${profileId}" model "${model.id}" compat`);
1108
- validateThinkingCapability(model.thinking, `Remote profile "${profileId}" model "${model.id}" thinking`);
1109
- validateCacheCapability(model.cacheCapability, `Remote profile "${profileId}" model "${model.id}" cacheCapability`);
1110
- validateWebSearchCapability(model.webSearch, `Remote profile "${profileId}" model "${model.id}" webSearch`);
1111
- validateFileCapabilities(model.fileCapabilities, `Remote profile "${profileId}" model "${model.id}" fileCapabilities`);
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`);
755
+ }
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
+ }
764
+ }
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`);
791
+ }
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}`);
812
+ try {
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");
816
+ } catch {
817
+ throw new Error(`${label} endpoints.${api} must be an absolute HTTP(S) URL`);
818
+ }
819
+ }
820
+ }
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}`);
869
+ try {
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
+ );
918
+ }
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);
926
+ }
927
+ }
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
+ });
951
+ }
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 });
978
+ }
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}`);
985
+ }
986
+ try {
987
+ fs.chmodSync(candidate, 448);
988
+ } catch {
989
+ }
990
+ }
991
+ return directory;
992
+ }
993
+ function remoteRefreshLockPath(modelsPath) {
994
+ return path.join(remoteCacheDirectory(modelsPath), ".refresh.lock");
995
+ }
996
+ function processIsAlive(pid) {
997
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
998
+ try {
999
+ process.kill(pid, 0);
1000
+ return true;
1001
+ } catch (error) {
1002
+ return error.code === "EPERM";
1003
+ }
1004
+ }
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;
1009
+ try {
1010
+ owner = JSON.parse(fs.readFileSync(lockPath, "utf8"));
1011
+ } catch {
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;
1017
+ }
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));
1022
+ }
1023
+ function reclaimStaleRemoteRefreshLock(lockPath) {
1024
+ if (!remoteRefreshLockIsStale(lockPath)) return false;
1025
+ const claimPath = `${lockPath}.reclaim-${process.pid}-${randomBytes(8).toString("hex")}`;
1026
+ try {
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;
1034
+ } catch (error) {
1035
+ if (["ENOENT", "EEXIST"].includes(error.code ?? "")) return false;
1036
+ throw error;
1037
+ } finally {
1038
+ try {
1039
+ fs.unlinkSync(claimPath);
1040
+ } catch {
1041
+ }
1042
+ }
1043
+ }
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
+ }
1078
+ }
1079
+ }
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);
1090
+ }
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");
1105
+ try {
1106
+ fs.chmodSync(keyPath, 384);
1107
+ } catch {
1108
+ }
1109
+ return key;
1110
+ }
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");
1115
+ }
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;
1134
+ }
1135
+ if (stat.isSymbolicLink() || !stat.isFile()) continue;
1136
+ }
1137
+ try {
1138
+ fs.unlinkSync(filepath);
1139
+ } catch {
1140
+ }
1141
+ }
1142
+ }
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();
1171
+ }
1172
+ }
1173
+ function payloadDigest(payload) {
1174
+ return createHash("sha256").update(JSON.stringify(payload)).digest("hex");
1175
+ }
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;
1184
+ }
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;
1190
+ }
1191
+ for (const [key, item] of Object.entries(candidate)) {
1192
+ visit(key);
1193
+ visit(item);
1194
+ }
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`);
1199
+ }
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 "";
1208
+ }
1209
+ function safeRemoteError(error, secrets) {
1210
+ return safeRemoteText(error instanceof Error ? `${error.name}: ${error.message}` : String(error), secrets);
1211
+ }
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 [];
1221
+ }
1222
+ return [...new Set(remotes.map((remote) => process.env[remote.apiKeyEnv]).filter((secret) => typeof secret === "string" && secret.length > 0))];
1112
1223
  }
1113
- function assertHeadersShape(headers, label) {
1114
- if (headers === void 0) return;
1115
- if (!isPlainRecord3(headers)) throw new Error(`${label} headers must be an object`);
1116
- for (const [name, value] of Object.entries(headers)) {
1117
- if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) throw new Error(`${label} header name ${name || "(empty)"} is invalid`);
1118
- if (typeof value !== "string") throw new Error(`${label} header ${name} must be a string`);
1119
- 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;
1120
1245
  }
1121
1246
  }
1122
- function assertRemoteHeadersSafe(headers, label) {
1123
- assertHeadersShape(headers, label);
1124
- for (const name of Object.keys(headers || {})) {
1125
- if (/(?:authorization|cookie|api[-_]?key|token|secret|credential)/i.test(name)) {
1126
- 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);
1127
1259
  }
1128
- 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`);
1281
+ }
1282
+ if (endpoint.protocol !== "https:" && endpoint.hostname !== "127.0.0.1" && endpoint.hostname !== "localhost") {
1283
+ throw new Error(`${label} baseUrl must use HTTPS`);
1129
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`);
1130
1289
  }
1131
1290
  function sanitizeRemotePayload(decoded, remote, catalogUrl, allowLocallyInjectedCredential = false) {
1132
1291
  if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) throw new Error("catalog response must be an object");
@@ -1294,160 +1453,8 @@ function loadResolvedModelsConfig(modelsPath) {
1294
1453
  }
1295
1454
  return { config: { ...raw, profiles }, remoteCatalogs: catalogs.sort((a, b) => a.id.localeCompare(b.id)) };
1296
1455
  }
1297
- function validateModelOverrides(value) {
1298
- if (value === void 0) return;
1299
- if (!isPlainRecord3(value)) throw new Error("models.json modelOverrides must be an object");
1300
- for (const [key, override] of Object.entries(value)) {
1301
- if (!/^[^\s/]+\/[^\s/]+$/.test(key)) throw new Error(`models.json modelOverrides key must be "provider/modelId": ${key}`);
1302
- if (!isPlainRecord3(override)) throw new Error(`models.json modelOverrides["${key}"] must be an object`);
1303
- assertOnlyKeys2(override, [...MODEL_OVERRIDE_KEYS], `models.json modelOverrides["${key}"]`);
1304
- 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`);
1305
- 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`);
1306
- if (override.reasoning !== void 0 && typeof override.reasoning !== "boolean") throw new Error(`models.json modelOverrides["${key}"].reasoning must be a boolean`);
1307
- 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`);
1308
- if (override.contextWindow !== void 0 && (!Number.isInteger(override.contextWindow) || Number(override.contextWindow) < 1)) throw new Error(`models.json modelOverrides["${key}"].contextWindow is invalid`);
1309
- if (override.maxTokens !== void 0 && (!Number.isInteger(override.maxTokens) || Number(override.maxTokens) < 1)) throw new Error(`models.json modelOverrides["${key}"].maxTokens is invalid`);
1310
- if (override.cost !== void 0) {
1311
- if (!isPlainRecord3(override.cost)) throw new Error(`models.json modelOverrides["${key}"].cost must be an object`);
1312
- for (const field of ["input", "output", "cacheRead", "cacheWrite", "cacheWriteLong"]) {
1313
- 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`);
1314
- }
1315
- }
1316
- if (override.headers !== void 0) {
1317
- if (!isPlainRecord3(override.headers)) throw new Error(`models.json modelOverrides["${key}"].headers must be an object`);
1318
- for (const [headerName, headerValue] of Object.entries(override.headers)) {
1319
- if (typeof headerValue !== "string") throw new Error(`models.json modelOverrides["${key}"].headers.${headerName} must be a string`);
1320
- }
1321
- }
1322
- validateTransport(override.transport, `Model override "${key}"`);
1323
- validateCompat(override.compat, `models.json modelOverrides["${key}"].compat`);
1324
- validateThinkingCapability(override.thinking, `models.json modelOverrides["${key}"].thinking`);
1325
- validateCacheCapability(override.cacheCapability, `models.json modelOverrides["${key}"].cacheCapability`);
1326
- validateWebSearchCapability(override.webSearch, `models.json modelOverrides["${key}"].webSearch`);
1327
- validateFileCapabilities(override.fileCapabilities, `models.json modelOverrides["${key}"].fileCapabilities`);
1328
- }
1329
- }
1330
- function validateProfileEndpoints(profile, label) {
1331
- if (profile.endpoints === void 0) return;
1332
- if (!isPlainRecord3(profile.endpoints)) throw new Error(`${label} endpoints must be an object`);
1333
- for (const [api, value] of Object.entries(profile.endpoints)) {
1334
- if (!SUPPORTED_REMOTE_APIS.has(api)) throw new Error(`${label} endpoints has unsupported api ${api}`);
1335
- try {
1336
- if (typeof value !== "string") throw new Error("invalid URL");
1337
- const endpoint = new URL(value);
1338
- if (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") throw new Error("unsupported protocol");
1339
- } catch {
1340
- throw new Error(`${label} endpoints.${api} must be an absolute HTTP(S) URL`);
1341
- }
1342
- }
1343
- }
1344
- function resolveProfileRoute(profile, model) {
1345
- const api = model.api ?? profile.api;
1346
- if (!SUPPORTED_REMOTE_APIS.has(api)) throw new Error(`Model "${model.id}" has unsupported api ${api}`);
1347
- const endpoint = profile.endpoints?.[api];
1348
- if (model.api !== void 0 && endpoint === void 0 && api !== profile.api) {
1349
- throw new Error(`Model "${model.id}" api ${api} requires profile endpoints.${api} (otherwise api must equal profile api)`);
1350
- }
1351
- return { api, baseUrl: endpoint ?? profile.baseUrl };
1352
- }
1353
- function validateProfileConfig(profileId, profileConfig) {
1354
- if (!isPlainRecord3(profileConfig)) throw new Error(`Profile "${profileId}" must be an object.`);
1355
- assertOnlyKeys2(profileConfig, [
1356
- "baseUrl",
1357
- "endpoints",
1358
- "api",
1359
- "apiKey",
1360
- "apiKeyEnv",
1361
- "headers",
1362
- "displayName",
1363
- "filePlatform",
1364
- "attachmentPlatform",
1365
- "transport",
1366
- "compat",
1367
- "cacheCapability",
1368
- "thinking",
1369
- "webSearch",
1370
- "fileCapabilities",
1371
- "models"
1372
- ], `Profile "${profileId}"`);
1373
- const missing = [];
1374
- if (!profileConfig.api) missing.push("api");
1375
- if (!profileConfig.baseUrl) missing.push("baseUrl");
1376
- if (!Array.isArray(profileConfig.models) || profileConfig.models.length === 0) missing.push("models");
1377
- const hasProfileKeySource = Boolean(profileConfig.apiKey || profileConfig.apiKeyEnv);
1378
- const hasModelKeySource = Boolean(
1379
- (profileConfig.models || []).some((model) => Boolean(model.apiKeyEnv))
1380
- );
1381
- if (!hasProfileKeySource && !hasModelKeySource) missing.push("apiKey or apiKeyEnv");
1382
- if (missing.length > 0) {
1383
- throw new Error(
1384
- `Profile "${profileId}" is missing required field${missing.length > 1 ? "s" : ""}: ${missing.join(", ")}.`
1385
- );
1386
- }
1387
- for (const field of ["baseUrl", "api", "apiKey", "displayName", "filePlatform", "attachmentPlatform"]) {
1388
- assertOptionalString2(profileConfig[field], `Profile "${profileId}" ${field}`);
1389
- }
1390
- assertOptionalEnvName(profileConfig.apiKeyEnv, `Profile "${profileId}" apiKeyEnv`);
1391
- if (!SUPPORTED_REMOTE_APIS.has(profileConfig.api)) throw new Error(`Profile "${profileId}" has unsupported api ${profileConfig.api}`);
1392
- try {
1393
- const endpoint = new URL(profileConfig.baseUrl);
1394
- if (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") throw new Error("unsupported protocol");
1395
- } catch {
1396
- throw new Error(`Profile "${profileId}" baseUrl must be an absolute HTTP(S) URL`);
1397
- }
1398
- validateProfileEndpoints(profileConfig, `Profile "${profileId}"`);
1399
- assertHeadersShape(profileConfig.headers, `Profile "${profileId}"`);
1400
- validateTransport(profileConfig.transport, `Profile "${profileId}"`);
1401
- validateCompat(profileConfig.compat, `Profile "${profileId}" compat`);
1402
- validateCacheCapability(profileConfig.cacheCapability, `Profile "${profileId}" cacheCapability`);
1403
- validateWebSearchCapability(profileConfig.webSearch, `Profile "${profileId}" webSearch`);
1404
- validateFileCapabilities(profileConfig.fileCapabilities, `Profile "${profileId}" fileCapabilities`);
1405
- validateThinkingCapability(profileConfig.thinking, `Profile "${profileId}" thinking`);
1406
- const seenModelIds = /* @__PURE__ */ new Set();
1407
- for (const [index, modelConfig] of (profileConfig.models || []).entries()) {
1408
- if (!isPlainRecord3(modelConfig)) throw new Error(`Profile "${profileId}" model #${index} must be an object.`);
1409
- assertOnlyKeys2(modelConfig, [
1410
- "id",
1411
- "api",
1412
- "name",
1413
- "reasoning",
1414
- "thinking",
1415
- "input",
1416
- "cost",
1417
- "contextWindow",
1418
- "maxTokens",
1419
- "transport",
1420
- "compat",
1421
- "cacheCapability",
1422
- "webSearch",
1423
- "fileCapabilities",
1424
- "headers",
1425
- "apiKeyEnv",
1426
- "displayName",
1427
- "filePlatform",
1428
- "attachmentPlatform"
1429
- ], `Profile "${profileId}" model #${index}`);
1430
- const modelMissing = [];
1431
- if (!modelConfig.id) modelMissing.push("id");
1432
- if (!Array.isArray(modelConfig.input) || modelConfig.input.length === 0) modelMissing.push("input");
1433
- if (!modelConfig.cost) modelMissing.push("cost");
1434
- if (!modelConfig.contextWindow) modelMissing.push("contextWindow");
1435
- if (!modelConfig.maxTokens) modelMissing.push("maxTokens");
1436
- if (modelMissing.length > 0) {
1437
- const label = modelConfig.id || `#${index}`;
1438
- throw new Error(
1439
- `Profile "${profileId}" model "${label}" is missing required field${modelMissing.length > 1 ? "s" : ""}: ${modelMissing.join(", ")}.`
1440
- );
1441
- }
1442
- validateRemoteModel(profileId, modelConfig);
1443
- const route = resolveProfileRoute(profileConfig, modelConfig);
1444
- validateThinkingCapabilityForApi(modelConfig.thinking ?? profileConfig.thinking, route.api, `Profile "${profileId}" model "${modelConfig.id}" thinking`);
1445
- assertHeadersShape(modelConfig.headers, `Profile "${profileId}" model "${modelConfig.id}"`);
1446
- assertOptionalEnvName(modelConfig.apiKeyEnv, `Profile "${profileId}" model "${modelConfig.id}" apiKeyEnv`);
1447
- if (seenModelIds.has(modelConfig.id)) throw new Error(`Profile "${profileId}" contains duplicate model "${modelConfig.id}".`);
1448
- seenModelIds.add(modelConfig.id);
1449
- }
1450
- }
1456
+
1457
+ // src/core/model-registry.ts
1451
1458
  var ModelRegistry = class {
1452
1459
  models = /* @__PURE__ */ new Map();
1453
1460
  loadError;
@@ -1469,7 +1476,7 @@ var ModelRegistry = class {
1469
1476
  activeOAuthUrls = /* @__PURE__ */ new Map();
1470
1477
  oauthProviderEpoch = /* @__PURE__ */ new Map();
1471
1478
  baseSnapshot;
1472
- constructor(authStorage, modelsPath = path.join(getConfigDir(), "models.json")) {
1479
+ constructor(authStorage, modelsPath = path2.join(getConfigDir(), "models.json")) {
1473
1480
  this.authStorage = authStorage;
1474
1481
  this.modelsPath = modelsPath;
1475
1482
  this.load();
@@ -1504,13 +1511,13 @@ var ModelRegistry = class {
1504
1511
  this.loadError = error instanceof Error ? error.message : String(error);
1505
1512
  return;
1506
1513
  }
1507
- if (!fs.existsSync(this.modelsPath)) {
1514
+ if (!fs2.existsSync(this.modelsPath)) {
1508
1515
  this.authStorage.replaceModelsConfigCredentials(/* @__PURE__ */ new Map(), /* @__PURE__ */ new Map());
1509
1516
  this.captureBaseline();
1510
1517
  return;
1511
1518
  }
1512
1519
  try {
1513
- const raw = JSON.parse(fs.readFileSync(this.modelsPath, "utf-8"));
1520
+ const raw = JSON.parse(fs2.readFileSync(this.modelsPath, "utf-8"));
1514
1521
  if (raw && typeof raw === "object" && "providers" in raw) {
1515
1522
  throw new Error('Legacy models.json format is no longer supported. Use top-level "profiles".');
1516
1523
  }
@@ -1736,23 +1743,23 @@ var ModelRegistry = class {
1736
1743
  writeRemoteCache(remote, fingerprint, value) {
1737
1744
  const directory = safeRemoteCacheDirectory(this.modelsPath, true);
1738
1745
  const target = remoteCachePath(this.modelsPath, remote, fingerprint);
1739
- if (fs.existsSync(target)) {
1740
- const stat = fs.lstatSync(target);
1746
+ if (fs2.existsSync(target)) {
1747
+ const stat = fs2.lstatSync(target);
1741
1748
  if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`remote catalog cache entry must be a regular file: ${target}`);
1742
1749
  }
1743
- 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`);
1744
1751
  try {
1745
- fs.writeFileSync(temporary, `${JSON.stringify(value)}
1752
+ fs2.writeFileSync(temporary, `${JSON.stringify(value)}
1746
1753
  `, { flag: "wx", mode: 384 });
1747
- fs.renameSync(temporary, target);
1754
+ fs2.renameSync(temporary, target);
1748
1755
  const tombstone = remoteCacheTombstonePath(this.modelsPath, remote, fingerprint);
1749
- if (fs.existsSync(tombstone)) fs.unlinkSync(tombstone);
1756
+ if (fs2.existsSync(tombstone)) fs2.unlinkSync(tombstone);
1750
1757
  } finally {
1751
- if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
1758
+ if (fs2.existsSync(temporary)) fs2.unlinkSync(temporary);
1752
1759
  }
1753
1760
  }
1754
1761
  refreshRemoteCatalogs() {
1755
- const queueKey = path.resolve(this.modelsPath);
1762
+ const queueKey = path2.resolve(this.modelsPath);
1756
1763
  const previous = remoteRefreshTails.get(queueKey) ?? Promise.resolve();
1757
1764
  const refresh = previous.then(() => this.performRemoteCatalogRefresh());
1758
1765
  const tail = refresh.catch(() => void 0);
@@ -1777,14 +1784,14 @@ var ModelRegistry = class {
1777
1784
  this.loadError = error instanceof Error ? error.message : String(error);
1778
1785
  return;
1779
1786
  }
1780
- if (!fs.existsSync(this.modelsPath)) {
1787
+ if (!fs2.existsSync(this.modelsPath)) {
1781
1788
  for (const owner of new Set(this.remoteCatalogByProvider.values())) this.removeRemoteCatalogProfiles(owner);
1782
1789
  this.remoteCredentialFingerprintByCatalog.clear();
1783
1790
  return;
1784
1791
  }
1785
1792
  let config;
1786
1793
  try {
1787
- const decoded = JSON.parse(fs.readFileSync(this.modelsPath, "utf8"));
1794
+ const decoded = JSON.parse(fs2.readFileSync(this.modelsPath, "utf8"));
1788
1795
  validateModelsDocumentShape(decoded);
1789
1796
  config = decoded;
1790
1797
  } catch {
@@ -2344,12 +2351,12 @@ var ModelRegistry = class {
2344
2351
 
2345
2352
  export {
2346
2353
  mergeThinkingCapability,
2347
- assertNoSecretSubstrings,
2348
- configuredRemoteCredentialValues,
2349
2354
  validatedRemoteCatalogs,
2350
2355
  validateModelsDocumentShape,
2351
- loadResolvedModelsConfig,
2352
2356
  resolveProfileRoute,
2353
2357
  validateProfileConfig,
2358
+ assertNoSecretSubstrings,
2359
+ configuredRemoteCredentialValues,
2360
+ loadResolvedModelsConfig,
2354
2361
  ModelRegistry
2355
2362
  };