@cydm/pie 4.10.2 → 4.12.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 (38) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +2 -2
  2. package/dist/builtin/extensions/cron/index.js +1 -1
  3. package/dist/builtin/extensions/im-forward/index.js +9128 -7189
  4. package/dist/builtin/extensions/mcp-adapter/index.js +1 -1
  5. package/dist/builtin/extensions/memory/index.js +171 -66
  6. package/dist/builtin/extensions/pie-ipc/index.js +1 -1
  7. package/dist/builtin/extensions/pie-proc/index.js +542 -52
  8. package/dist/builtin/extensions/plan-mode/index.js +2 -2
  9. package/dist/builtin/extensions/subagent/README.md +1 -1
  10. package/dist/builtin/extensions/subagent/index.js +3 -3
  11. package/dist/builtin/extensions/todo/index.js +2 -2
  12. package/dist/chunks/{auth-storage-C3FZMT7J.js → auth-storage-IJEJ2TGE.js} +1 -1
  13. package/dist/chunks/chunk-26ILLZKQ.js +400 -0
  14. package/dist/chunks/{chunk-KWK7KTSZ.js → chunk-322WLBDY.js} +1 -1
  15. package/dist/chunks/{chunk-OU33ROFD.js → chunk-3GG342QY.js} +78 -78
  16. package/dist/chunks/{chunk-BB7ETSJK.js → chunk-6U6UGM4C.js} +119 -3
  17. package/dist/chunks/{chunk-ZPJ3BNQB.js → chunk-BSITHT43.js} +1 -0
  18. package/dist/chunks/{chunk-IZKHSUNQ.js → chunk-CAPBTMLI.js} +18 -1
  19. package/dist/chunks/{chunk-FC5AN5QP.js → chunk-IZ4DYCJ7.js} +268 -107
  20. package/dist/chunks/{chunk-HK3FHIAH.js → chunk-KW46ND3S.js} +1999 -767
  21. package/dist/chunks/{chunk-SW2E33UL.js → chunk-LMDWWT43.js} +123 -4
  22. package/dist/chunks/chunk-OGGL6LUN.js +331 -0
  23. package/dist/chunks/{chunk-BTUMBUDU.js → chunk-QSXBPTOA.js} +1 -1
  24. package/dist/chunks/{chunk-5QMS6RQC.js → chunk-SXBX2P5R.js} +160 -5
  25. package/dist/chunks/{chunk-7LICWWUE.js → chunk-W37NAT3N.js} +2 -2
  26. package/dist/chunks/chunk-WTBLV6F5.js +476 -0
  27. package/dist/chunks/{host-image-fallback-3TEMOQM5.js → host-image-fallback-NXY36VO2.js} +1 -1
  28. package/dist/chunks/{manager-cli-BXI4UFTJ.js → manager-cli-B6GIYTI7.js} +35 -13
  29. package/dist/chunks/{manager-upgrade-XPFXKO7A.js → manager-upgrade-WHER3WTJ.js} +284 -109
  30. package/dist/chunks/memory-git-C3S276QJ.js +19 -0
  31. package/dist/chunks/{model-registry-QKJ3YVDS.js → model-registry-QNEPISBJ.js} +11 -3
  32. package/dist/chunks/{read-file-understanding-N2ZZQLTZ.js → read-file-understanding-ZCBNCQHG.js} +3 -3
  33. package/dist/chunks/{src-F5N6O2HR.js → src-7CU7OTQS.js} +36 -36
  34. package/dist/chunks/{src-3PSR2AAX.js → src-7MZZJVOG.js} +1 -1
  35. package/dist/cli.js +750 -516
  36. package/package.json +2 -2
  37. package/dist/chunks/chunk-6WKBQZWM.js +0 -19
  38. package/dist/chunks/chunk-XMTRKMBG.js +0 -386
@@ -20,6 +20,49 @@ import * as fs from "fs";
20
20
  import * as path from "path";
21
21
  import { createHash, createHmac, randomBytes } from "node:crypto";
22
22
 
23
+ // src/core/model-registry-baseline.ts
24
+ function cloneModelsMap(models) {
25
+ return new Map([...models].map(([provider, inner]) => [provider, new Map(inner)]));
26
+ }
27
+ function captureRegistryBaseline(state) {
28
+ return {
29
+ models: cloneModelsMap(state.models),
30
+ order: state.modelOrder.slice(),
31
+ ext: state.usingExternalProviders,
32
+ remCat: new Map(state.remoteCatalogByProvider),
33
+ remEnv: new Map(state.remoteCredentialEnvByProvider),
34
+ auth: state.authStorage.snapshotProviderConfig()
35
+ };
36
+ }
37
+ function deepMergePlainRecords(base, patch) {
38
+ const isPlain = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
39
+ const result = isPlain(base) ? { ...base } : {};
40
+ if (!isPlain(patch)) return result;
41
+ for (const [key, value] of Object.entries(patch)) {
42
+ const current = result[key];
43
+ result[key] = isPlain(current) && isPlain(value) ? deepMergePlainRecords(current, value) : value;
44
+ }
45
+ return result;
46
+ }
47
+ function restoreRegistryBaseline(baseline, target) {
48
+ target.models = cloneModelsMap(baseline.models);
49
+ target.modelOrder = baseline.order.slice();
50
+ target.usingExternalProviders = baseline.ext;
51
+ target.remoteCatalogByProvider = new Map(baseline.remCat);
52
+ target.remoteCredentialEnvByProvider = new Map(baseline.remEnv);
53
+ target.authStorage.restoreModelsConfigOnly(baseline.auth);
54
+ target.authStorage.clearRuntimeEnvVars();
55
+ target.clearExtensionOAuth();
56
+ }
57
+ function reconcileOAuthBindings(prevUrls, prevHandlers, activeUrls, activeHandlers, epochs, authStorage) {
58
+ for (const p of /* @__PURE__ */ new Set([...prevUrls.keys(), ...activeUrls.keys()])) {
59
+ if (activeUrls.get(p) !== prevUrls.get(p) || activeHandlers.get(p) !== prevHandlers.get(p)) {
60
+ epochs.set(p, (epochs.get(p) ?? 0) + 1);
61
+ if (prevUrls.has(p) && activeUrls.get(p) !== prevUrls.get(p)) authStorage.maskOAuthForProvider(p);
62
+ }
63
+ }
64
+ }
65
+
23
66
  // src/core/thinking-capability-validation.ts
24
67
  var THINKING_MODES = /* @__PURE__ */ new Set(["none", "effort", "adaptive", "budget"]);
25
68
  var DISABLE_WIRES = /* @__PURE__ */ new Set(["omit", "none", "disabled"]);
@@ -1193,15 +1236,6 @@ function loadResolvedModelsConfig(modelsPath) {
1193
1236
  }
1194
1237
  return { config: { ...raw, profiles }, remoteCatalogs: catalogs.sort((a, b) => a.id.localeCompare(b.id)) };
1195
1238
  }
1196
- function deepMergePlainRecords(base, patch) {
1197
- const result = isPlainRecord2(base) ? { ...base } : {};
1198
- if (!isPlainRecord2(patch)) return result;
1199
- for (const [key, value] of Object.entries(patch)) {
1200
- const current = result[key];
1201
- result[key] = isPlainRecord2(current) && isPlainRecord2(value) ? deepMergePlainRecords(current, value) : value;
1202
- }
1203
- return result;
1204
- }
1205
1239
  function validateModelOverrides(value) {
1206
1240
  if (value === void 0) return;
1207
1241
  if (!isPlainRecord2(value)) throw new Error("models.json modelOverrides must be an object");
@@ -1365,11 +1399,18 @@ var ModelRegistry = class {
1365
1399
  modelOrder = [];
1366
1400
  modelOverrides = {};
1367
1401
  extensionOAuthProviders = /* @__PURE__ */ new Map();
1402
+ runtimeRegistrations = [];
1403
+ runtimeReloadEpoch = 0;
1368
1404
  usingExternalProviders = false;
1369
1405
  localProfileIds = /* @__PURE__ */ new Set();
1370
1406
  remoteCredentialEnvByProvider = /* @__PURE__ */ new Map();
1371
1407
  remoteCatalogByProvider = /* @__PURE__ */ new Map();
1372
1408
  remoteCredentialFingerprintByCatalog = /* @__PURE__ */ new Map();
1409
+ routeReplacedProviders = /* @__PURE__ */ new Set();
1410
+ runtimeProviderUrls = /* @__PURE__ */ new Map();
1411
+ activeOAuthUrls = /* @__PURE__ */ new Map();
1412
+ oauthProviderEpoch = /* @__PURE__ */ new Map();
1413
+ baseSnapshot;
1373
1414
  constructor(authStorage, modelsPath = path.join(getConfigDir(), "models.json")) {
1374
1415
  this.authStorage = authStorage;
1375
1416
  this.modelsPath = modelsPath;
@@ -1388,6 +1429,7 @@ var ModelRegistry = class {
1388
1429
  providerModels.set(model.id, model);
1389
1430
  }
1390
1431
  load() {
1432
+ const prevAuth = this.authStorage.snapshotProviderConfig();
1391
1433
  this.loadError = void 0;
1392
1434
  this.models.clear();
1393
1435
  this.modelOrder = [];
@@ -1405,6 +1447,8 @@ var ModelRegistry = class {
1405
1447
  return;
1406
1448
  }
1407
1449
  if (!fs.existsSync(this.modelsPath)) {
1450
+ this.authStorage.replaceModelsConfigCredentials(/* @__PURE__ */ new Map(), /* @__PURE__ */ new Map());
1451
+ this.captureBaseline();
1408
1452
  return;
1409
1453
  }
1410
1454
  try {
@@ -1427,18 +1471,13 @@ var ModelRegistry = class {
1427
1471
  toolModels: raw.defaults.toolModels
1428
1472
  } : void 0;
1429
1473
  this.usingExternalProviders = hasConfiguredProviders;
1474
+ const stagedApiKeys = /* @__PURE__ */ new Map();
1475
+ const stagedEnvVars = /* @__PURE__ */ new Map();
1430
1476
  for (const [configuredProvider, providerConfig] of configuredProviders) {
1431
1477
  const provider = configuredProvider;
1432
1478
  validateProfileConfig(provider, providerConfig);
1433
- if (providerConfig.apiKey) {
1434
- this.authStorage.setProviderApiKey(provider, providerConfig.apiKey);
1435
- }
1436
- if (providerConfig.apiKeyEnv) {
1437
- this.authStorage.setProviderEnvVar(
1438
- provider,
1439
- providerConfig.apiKeyEnv
1440
- );
1441
- }
1479
+ if (providerConfig.apiKey) stagedApiKeys.set(provider, providerConfig.apiKey);
1480
+ if (providerConfig.apiKeyEnv) stagedEnvVars.set(provider, providerConfig.apiKeyEnv);
1442
1481
  const existing = this.models.get(provider);
1443
1482
  if (existing && (providerConfig.baseUrl || providerConfig.api || providerConfig.headers || providerConfig.transport)) {
1444
1483
  for (const model of existing.values()) {
@@ -1499,14 +1538,42 @@ var ModelRegistry = class {
1499
1538
  return existing !== void 0 && existing !== owner;
1500
1539
  })) continue;
1501
1540
  for (const [provider, profile] of candidates) {
1502
- this.registerRemoteProfile(provider, profile, identity.apiKeyEnv, owner);
1541
+ this.registerRemoteProfile(provider, profile, identity.apiKeyEnv, owner, stagedEnvVars);
1503
1542
  }
1504
1543
  }
1544
+ this.authStorage.replaceModelsConfigCredentials(stagedApiKeys, stagedEnvVars);
1545
+ const nextBase = captureRegistryBaseline({ models: this.models, modelOrder: this.modelOrder, usingExternalProviders: this.usingExternalProviders, remoteCatalogByProvider: this.remoteCatalogByProvider, remoteCredentialEnvByProvider: this.remoteCredentialEnvByProvider, authStorage: this.authStorage });
1505
1546
  this.applyModelOverrides();
1547
+ this.baseSnapshot = nextBase;
1506
1548
  } catch (error) {
1549
+ this.authStorage.restoreProviderConfig(prevAuth);
1507
1550
  this.loadError = error instanceof Error ? error.message : String(error);
1508
1551
  }
1509
1552
  }
1553
+ captureBaseline() {
1554
+ this.baseSnapshot = captureRegistryBaseline({ models: this.models, modelOrder: this.modelOrder, usingExternalProviders: this.usingExternalProviders, remoteCatalogByProvider: this.remoteCatalogByProvider, remoteCredentialEnvByProvider: this.remoteCredentialEnvByProvider, authStorage: this.authStorage });
1555
+ }
1556
+ restoreBaselineRaw() {
1557
+ if (!this.baseSnapshot) return;
1558
+ const box = { models: this.models, modelOrder: this.modelOrder, usingExternalProviders: this.usingExternalProviders, remoteCatalogByProvider: this.remoteCatalogByProvider, remoteCredentialEnvByProvider: this.remoteCredentialEnvByProvider, authStorage: this.authStorage, clearExtensionOAuth: () => {
1559
+ this.extensionOAuthProviders.clear();
1560
+ this.activeOAuthUrls.clear();
1561
+ this.routeReplacedProviders.clear();
1562
+ this.runtimeProviderUrls.clear();
1563
+ } };
1564
+ restoreRegistryBaseline(this.baseSnapshot, box);
1565
+ this.models = box.models;
1566
+ this.modelOrder = box.modelOrder;
1567
+ this.usingExternalProviders = box.usingExternalProviders;
1568
+ this.remoteCatalogByProvider = box.remoteCatalogByProvider;
1569
+ this.remoteCredentialEnvByProvider = box.remoteCredentialEnvByProvider;
1570
+ }
1571
+ rebuildFromBaseline(prevUrls = new Map(this.activeOAuthUrls), prevHandlers = new Map(this.extensionOAuthProviders)) {
1572
+ this.restoreBaselineRaw();
1573
+ for (const reg of this.runtimeRegistrations) this.applyRuntimeRegistration(reg.provider, reg.config);
1574
+ reconcileOAuthBindings(prevUrls, prevHandlers, this.activeOAuthUrls, this.extensionOAuthProviders, this.oauthProviderEpoch, this.authStorage);
1575
+ this.applyModelOverrides();
1576
+ }
1510
1577
  /**
1511
1578
  * Re-apply models.json modelOverrides after any (re)materialization pass
1512
1579
  * (initial load, remote catalog refresh). Overrides patch descriptive
@@ -1529,7 +1596,7 @@ var ModelRegistry = class {
1529
1596
  if (override.contextWindow !== void 0) patched.contextWindow = override.contextWindow;
1530
1597
  if (override.maxTokens !== void 0) patched.maxTokens = override.maxTokens;
1531
1598
  if (override.cost !== void 0) patched.cost = { ...existing.cost, ...override.cost };
1532
- if (override.headers !== void 0) patched.headers = { ...existing.headers, ...override.headers };
1599
+ if (override.headers !== void 0 && !this.routeReplacedProviders.has(provider)) patched.headers = { ...existing.headers, ...override.headers };
1533
1600
  if (override.transport !== void 0) patched.transport = override.transport;
1534
1601
  if (override.compat !== void 0) patched.compat = deepMergePlainRecords(existing.compat, override.compat);
1535
1602
  if (override.cacheCapability !== void 0) patched.cacheCapability = { ...existing.cacheCapability, ...override.cacheCapability };
@@ -1538,7 +1605,7 @@ var ModelRegistry = class {
1538
1605
  this.upsert(patched);
1539
1606
  }
1540
1607
  }
1541
- registerRemoteProfile(provider, providerConfig, credentialEnv, catalogId) {
1608
+ registerRemoteProfile(provider, providerConfig, credentialEnv, catalogId, stagedEnvVars) {
1542
1609
  if (this.localProfileIds.has(provider)) return;
1543
1610
  const existingCatalog = this.remoteCatalogByProvider.get(provider);
1544
1611
  if (existingCatalog && existingCatalog !== catalogId) {
@@ -1547,7 +1614,8 @@ var ModelRegistry = class {
1547
1614
  validateProfileConfig(provider, providerConfig);
1548
1615
  this.remoteCatalogByProvider.set(provider, catalogId);
1549
1616
  this.remoteCredentialEnvByProvider.set(provider, credentialEnv);
1550
- this.authStorage.setProviderEnvVar(provider, credentialEnv);
1617
+ if (stagedEnvVars) stagedEnvVars.set(provider, credentialEnv);
1618
+ else this.authStorage.setConfigProviderEnvVar(provider, credentialEnv);
1551
1619
  for (const customModel of providerConfig.models || []) {
1552
1620
  this.upsert({
1553
1621
  id: customModel.id,
@@ -1580,12 +1648,16 @@ var ModelRegistry = class {
1580
1648
  this.modelOrder = this.modelOrder.filter((key) => !key.startsWith(`${provider}/`));
1581
1649
  this.remoteCatalogByProvider.delete(provider);
1582
1650
  this.remoteCredentialEnvByProvider.delete(provider);
1651
+ this.authStorage.clearConfigProviderEnvVar(provider);
1583
1652
  }
1584
1653
  removeRemoteCatalogProfiles(catalogId) {
1585
- for (const [provider, owner] of [...this.remoteCatalogByProvider]) {
1586
- if (owner === catalogId) this.removeRemoteProvider(provider, catalogId);
1587
- }
1654
+ const prevUrls = new Map(this.activeOAuthUrls);
1655
+ const prevHandlers = new Map(this.extensionOAuthProviders);
1656
+ this.restoreBaselineRaw();
1657
+ for (const [provider, owner] of [...this.remoteCatalogByProvider]) if (owner === catalogId) this.removeRemoteProvider(provider, catalogId);
1588
1658
  this.usingExternalProviders = this.localProfileIds.size > 0 || this.remoteCatalogByProvider.size > 0;
1659
+ this.captureBaseline();
1660
+ this.rebuildFromBaseline(prevUrls, prevHandlers);
1589
1661
  }
1590
1662
  replaceRemoteCatalogProfiles(catalogId, payload, credentialEnv) {
1591
1663
  const candidates = Object.entries(payload.profiles || {}).filter(([provider]) => !this.localProfileIds.has(provider));
@@ -1594,11 +1666,14 @@ var ModelRegistry = class {
1594
1666
  if (owner && owner !== catalogId) throw new Error(`remote profile "${provider}" is already owned by another catalog identity`);
1595
1667
  validateProfileConfig(provider, profile);
1596
1668
  }
1597
- this.removeRemoteCatalogProfiles(catalogId);
1598
- for (const [provider, profile] of candidates) {
1599
- this.registerRemoteProfile(provider, profile, credentialEnv, catalogId);
1600
- }
1601
- this.applyModelOverrides();
1669
+ const prevUrls = new Map(this.activeOAuthUrls);
1670
+ const prevHandlers = new Map(this.extensionOAuthProviders);
1671
+ this.restoreBaselineRaw();
1672
+ for (const [provider, owner] of [...this.remoteCatalogByProvider]) if (owner === catalogId) this.removeRemoteProvider(provider, catalogId);
1673
+ for (const [provider, profile] of candidates) this.registerRemoteProfile(provider, profile, credentialEnv, catalogId);
1674
+ this.usingExternalProviders = this.localProfileIds.size > 0 || this.remoteCatalogByProvider.size > 0;
1675
+ this.captureBaseline();
1676
+ this.rebuildFromBaseline(prevUrls, prevHandlers);
1602
1677
  }
1603
1678
  writeRemoteCache(remote, fingerprint, value) {
1604
1679
  const directory = safeRemoteCacheDirectory(this.modelsPath, true);
@@ -1827,11 +1902,10 @@ var ModelRegistry = class {
1827
1902
  };
1828
1903
  const explicit = this.resolveConfiguredRoute(purpose, this.configDefaults?.toolModels?.[purpose]);
1829
1904
  add(explicit);
1830
- if (currentModel && modelSupportsToolPurpose(currentModel, purpose)) {
1831
- const apiKey = this.getApiKey(currentModel);
1832
- if (apiKey) {
1833
- add({ purpose, requiredCapability, routeSource: "current_model", model: currentModel, apiKey });
1834
- }
1905
+ const liveCurrent = currentModel ? this.find(currentModel.provider, currentModel.id) : void 0;
1906
+ if (liveCurrent && modelSupportsToolPurpose(liveCurrent, purpose)) {
1907
+ const apiKey = this.getApiKey(liveCurrent);
1908
+ if (apiKey) add({ purpose, requiredCapability, routeSource: "current_model", model: liveCurrent, apiKey });
1835
1909
  }
1836
1910
  const modelClassCandidates = [];
1837
1911
  for (const modelClass of MODEL_CLASS_FALLBACK_ORDER) {
@@ -1940,9 +2014,7 @@ var ModelRegistry = class {
1940
2014
  }
1941
2015
  getAll() {
1942
2016
  const all = [];
1943
- for (const providerModels of this.models.values()) {
1944
- all.push(...providerModels.values());
1945
- }
2017
+ for (const providerModels of this.models.values()) all.push(...providerModels.values());
1946
2018
  return all.sort((a, b) => `${a.provider}/${a.id}`.localeCompare(`${b.provider}/${b.id}`));
1947
2019
  }
1948
2020
  getAllInConfigOrder() {
@@ -1972,48 +2044,47 @@ var ModelRegistry = class {
1972
2044
  return this.getAll().map((model) => `${model.provider}/${model.id}`);
1973
2045
  }
1974
2046
  getApiKey(model) {
2047
+ const current = this.find(model.provider, model.id);
2048
+ if (!current || current.baseUrl !== model.baseUrl) return void 0;
1975
2049
  const remoteEnv = this.remoteCredentialEnvByProvider.get(model.provider);
1976
2050
  if (remoteEnv) return typeof process !== "undefined" ? process.env?.[remoteEnv] : void 0;
1977
- return this.authStorage.getApiKey(model.provider, model.apiKeyEnv);
2051
+ const oauthEndpoint = this.authStorage.getOAuthCredentials(model.provider)?.endpoint;
2052
+ const skipOAuth = this.localProfileIds.has(model.provider) && !this.extensionOAuthProviders.has(model.provider) || oauthEndpoint !== current.baseUrl;
2053
+ return this.authStorage.getApiKey(model.provider, current.apiKeyEnv, { skipOAuth });
1978
2054
  }
1979
2055
  getApiKeyForProvider(provider) {
1980
2056
  const remoteEnv = this.remoteCredentialEnvByProvider.get(provider);
1981
2057
  if (remoteEnv) return typeof process !== "undefined" ? process.env?.[remoteEnv] : void 0;
1982
- return this.authStorage.getApiKey(provider);
2058
+ const oauthEndpoint = this.authStorage.getOAuthCredentials(provider)?.endpoint;
2059
+ const activeUrl = this.activeOAuthUrls.get(provider) ?? [...this.models.get(provider)?.values() ?? []][0]?.baseUrl;
2060
+ const skipOAuth = this.localProfileIds.has(provider) && !this.extensionOAuthProviders.has(provider) || !activeUrl || oauthEndpoint !== activeUrl;
2061
+ return this.authStorage.getApiKey(provider, void 0, { skipOAuth });
1983
2062
  }
1984
- /**
1985
- * Register a provider at runtime (extension API). Not persisted to
1986
- * models.json: runtime registrations live for the process unless the
1987
- * extension registers them again. Returns an unregister handle that
1988
- * restores the provider's previous state (models, order, env binding).
1989
- *
1990
- * When the provider already exists (local profile or remote catalog),
1991
- * models are merged by id: registered models upsert over existing entries
1992
- * with the same id; existing entries not named in `config.models` survive.
1993
- * baseUrl/api/headers patch every model of that provider (existing and
1994
- * new) when provided.
1995
- */
1996
- registerProvider(provider, config) {
1997
- validateExtensionProviderConfig(provider, config);
1998
- const previousModels = this.models.get(provider) ? new Map(this.models.get(provider)) : void 0;
1999
- const previousOrder = [...this.modelOrder];
2000
- const previousEnvVar = this.authStorage.getProviderEnvVar(provider);
2001
- if (config.apiKey) {
2002
- this.authStorage.setRuntimeApiKey(provider, config.apiKey);
2063
+ applyRuntimeRegistration(provider, config) {
2064
+ const wasRemote = this.remoteCatalogByProvider.has(provider);
2065
+ const existing = this.models.get(provider);
2066
+ const prevRtUrl = this.runtimeProviderUrls.get(provider);
2067
+ const routeChanged = wasRemote || prevRtUrl !== void 0 && prevRtUrl !== config.baseUrl || Boolean(existing?.size && [...existing.values()].some((m) => m.baseUrl !== config.baseUrl));
2068
+ this.runtimeProviderUrls.set(provider, config.baseUrl);
2069
+ if (routeChanged) {
2070
+ this.routeReplacedProviders.add(provider);
2071
+ if (!config.oauth) {
2072
+ this.extensionOAuthProviders.delete(provider);
2073
+ this.activeOAuthUrls.delete(provider);
2074
+ }
2003
2075
  }
2004
- if (config.apiKeyEnv) {
2005
- this.authStorage.setProviderEnvVar(provider, config.apiKeyEnv);
2076
+ if (wasRemote) {
2077
+ this.remoteCredentialEnvByProvider.delete(provider);
2078
+ this.authStorage.clearConfigProviderEnvVar(provider);
2006
2079
  }
2007
- const existing = this.models.get(provider);
2008
- if (existing && (config.baseUrl || config.api || config.headers || config.transport)) {
2080
+ if (config.apiKey) this.authStorage.setRuntimeCredentialOverride(provider, { kind: "literal", key: config.apiKey });
2081
+ else if (config.apiKeyEnv) this.authStorage.setRuntimeCredentialOverride(provider, { kind: "env", envVar: config.apiKeyEnv });
2082
+ else if (config.oauth) this.authStorage.setRuntimeCredentialOverride(provider, { kind: "oauth" });
2083
+ else if (routeChanged) this.authStorage.setRuntimeCredentialOverride(provider, { kind: "none" });
2084
+ if (existing && (routeChanged || config.baseUrl || config.api || config.headers || config.transport || config.apiKeyEnv)) {
2009
2085
  for (const model of existing.values()) {
2010
- this.upsert({
2011
- ...model,
2012
- baseUrl: config.baseUrl || model.baseUrl,
2013
- api: config.api || model.api,
2014
- transport: config.transport ?? model.transport,
2015
- headers: config.headers ? { ...model.headers, ...config.headers } : model.headers
2016
- });
2086
+ const nextHeaders = routeChanged ? config.headers ? { ...config.headers } : void 0 : config.headers ? { ...model.headers, ...config.headers } : model.headers;
2087
+ this.upsert({ ...model, baseUrl: config.baseUrl || model.baseUrl, api: config.api || model.api, transport: config.transport ?? model.transport, apiKeyEnv: routeChanged ? config.apiKeyEnv : config.apiKeyEnv || model.apiKeyEnv, headers: nextHeaders });
2017
2088
  }
2018
2089
  }
2019
2090
  for (const customModel of config.models ?? []) {
@@ -2021,6 +2092,7 @@ var ModelRegistry = class {
2021
2092
  const resolvedApi = config.api || baseModel?.api || "openai-completions";
2022
2093
  const resolvedThinking = cloneThinkingCapability(customModel.thinking ?? baseModel?.thinking);
2023
2094
  validateThinkingCapabilityForApi(resolvedThinking, resolvedApi, `registerProvider("${provider}") model "${customModel.id}" thinking`);
2095
+ const customHeaders = routeChanged ? config.headers || customModel.headers ? { ...config.headers, ...customModel.headers } : void 0 : config.headers ? { ...baseModel?.headers, ...config.headers, ...customModel.headers } : customModel.headers || baseModel?.headers;
2024
2096
  this.upsert({
2025
2097
  id: customModel.id,
2026
2098
  name: customModel.name || baseModel?.name || customModel.id,
@@ -2033,9 +2105,9 @@ var ModelRegistry = class {
2033
2105
  cost: customModel.cost || baseModel?.cost || { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
2034
2106
  contextWindow: customModel.contextWindow || baseModel?.contextWindow || 128e3,
2035
2107
  maxTokens: customModel.maxTokens || baseModel?.maxTokens || 8192,
2036
- apiKeyEnv: config.apiKeyEnv || baseModel?.apiKeyEnv,
2108
+ apiKeyEnv: config.apiKeyEnv || (routeChanged ? void 0 : baseModel?.apiKeyEnv),
2037
2109
  displayName: customModel.displayName || baseModel?.displayName || provider,
2038
- headers: config.headers ? { ...baseModel?.headers, ...config.headers, ...customModel.headers } : customModel.headers || baseModel?.headers,
2110
+ headers: customHeaders,
2039
2111
  transport: customModel.transport ?? config.transport ?? baseModel?.transport,
2040
2112
  compat: customModel.compat || baseModel?.compat,
2041
2113
  cacheCapability: customModel.cacheCapability || baseModel?.cacheCapability,
@@ -2043,61 +2115,145 @@ var ModelRegistry = class {
2043
2115
  fileCapabilities: customModel.fileCapabilities || baseModel?.fileCapabilities
2044
2116
  });
2045
2117
  }
2046
- this.applyModelOverrides();
2047
2118
  this.usingExternalProviders = true;
2048
- const registeredOAuth = config.oauth;
2049
- if (registeredOAuth) this.extensionOAuthProviders.set(provider, registeredOAuth);
2119
+ if (config.oauth) {
2120
+ this.extensionOAuthProviders.set(provider, config.oauth);
2121
+ this.activeOAuthUrls.set(provider, config.baseUrl);
2122
+ }
2123
+ }
2124
+ /** Register a runtime provider (extension API; merged by id with existing providers) and return an unregister handle. */
2125
+ registerProvider(provider, config) {
2126
+ validateExtensionProviderConfig(provider, config);
2127
+ if (!this.baseSnapshot) this.captureBaseline();
2128
+ const regId = Symbol(provider);
2129
+ const prevRegs = [...this.runtimeRegistrations];
2130
+ const prevAuth = this.authStorage.snapshotProviderConfig();
2131
+ this.runtimeRegistrations.push({ id: regId, provider, config });
2132
+ try {
2133
+ this.rebuildFromBaseline();
2134
+ } catch (error) {
2135
+ this.runtimeRegistrations = prevRegs;
2136
+ this.authStorage.restoreProviderConfig(prevAuth);
2137
+ this.rebuildFromBaseline();
2138
+ throw error;
2139
+ }
2140
+ let disposed = false;
2050
2141
  return () => {
2051
- if (previousModels) this.models.set(provider, previousModels);
2052
- else this.models.delete(provider);
2053
- this.modelOrder = previousOrder;
2054
- this.authStorage.setRuntimeApiKey(provider, void 0);
2055
- this.authStorage.setProviderEnvVar(provider, previousEnvVar);
2056
- if (registeredOAuth) this.extensionOAuthProviders.delete(provider);
2057
- this.applyModelOverrides();
2142
+ if (disposed) return;
2143
+ disposed = true;
2144
+ this.runtimeRegistrations = this.runtimeRegistrations.filter((r) => r.id !== regId);
2145
+ try {
2146
+ this.rebuildFromBaseline();
2147
+ } catch {
2148
+ this.rebuildBestEffort();
2149
+ }
2058
2150
  };
2059
2151
  }
2152
+ rebuildBestEffort() {
2153
+ const prevUrls = new Map(this.activeOAuthUrls);
2154
+ const prevHandlers = new Map(this.extensionOAuthProviders);
2155
+ this.restoreBaselineRaw();
2156
+ const surviving = [];
2157
+ for (const reg of this.runtimeRegistrations) {
2158
+ const snap = captureRegistryBaseline({ models: this.models, modelOrder: this.modelOrder, usingExternalProviders: this.usingExternalProviders, remoteCatalogByProvider: this.remoteCatalogByProvider, remoteCredentialEnvByProvider: this.remoteCredentialEnvByProvider, authStorage: this.authStorage });
2159
+ const snapRtUrls = new Map(this.runtimeProviderUrls);
2160
+ const snapReplaced = new Set(this.routeReplacedProviders);
2161
+ try {
2162
+ this.applyRuntimeRegistration(reg.provider, reg.config);
2163
+ surviving.push(reg);
2164
+ } catch {
2165
+ this.models = snap.models;
2166
+ this.modelOrder = snap.order;
2167
+ this.usingExternalProviders = snap.ext;
2168
+ this.remoteCatalogByProvider = snap.remCat;
2169
+ this.remoteCredentialEnvByProvider = snap.remEnv;
2170
+ this.authStorage.restoreProviderConfig(snap.auth);
2171
+ this.runtimeProviderUrls = snapRtUrls;
2172
+ this.routeReplacedProviders = snapReplaced;
2173
+ }
2174
+ }
2175
+ reconcileOAuthBindings(prevUrls, prevHandlers, this.activeOAuthUrls, this.extensionOAuthProviders, this.oauthProviderEpoch, this.authStorage);
2176
+ this.runtimeRegistrations = surviving;
2177
+ try {
2178
+ this.applyModelOverrides();
2179
+ } catch {
2180
+ }
2181
+ }
2060
2182
  /** OAuth flow declared by an extension-registered provider, if any. */
2061
2183
  getExtensionOAuth(provider) {
2062
2184
  return this.extensionOAuthProviders.get(provider);
2063
2185
  }
2064
- /**
2065
- * Restore persisted OAuth credentials now that extensions have registered
2066
- * their providers: refresh expired tokens when the extension declares
2067
- * refreshToken, and drop the runtime binding when a token cannot be
2068
- * recovered (getApiKey then reports the provider as unauthenticated).
2069
- * Never throws; returns per-provider outcomes for the host to surface.
2070
- */
2186
+ getExtensionOAuthBinding(provider) {
2187
+ const oauth = this.extensionOAuthProviders.get(provider);
2188
+ const baseUrl = this.activeOAuthUrls.get(provider);
2189
+ return oauth && baseUrl ? { oauth, baseUrl, epoch: this.oauthProviderEpoch.get(provider) ?? 0, authVersion: this.authStorage.getOAuthVersion(provider) } : void 0;
2190
+ }
2191
+ commitExtensionOAuthCredentials(provider, binding, credentials) {
2192
+ if (this.extensionOAuthProviders.get(provider) !== binding.oauth || this.activeOAuthUrls.get(provider) !== binding.baseUrl || (this.oauthProviderEpoch.get(provider) ?? 0) !== binding.epoch || this.authStorage.getOAuthVersion(provider) !== binding.authVersion) return false;
2193
+ if (credentials) {
2194
+ this.authStorage.setOAuthCredentials(provider, { ...credentials, endpoint: binding.baseUrl });
2195
+ this.authStorage.setRuntimeApiKey(provider, credentials.access);
2196
+ } else this.authStorage.setRuntimeApiKey(provider, void 0);
2197
+ return true;
2198
+ }
2199
+ /** Reload models.json + cached remote catalogs, replaying active runtime provider registrations. */
2200
+ reloadFromDisk() {
2201
+ const prevModels = cloneModelsMap(this.models);
2202
+ const prevAuth = this.authStorage.snapshotProviderConfig();
2203
+ const prevOAuth = new Map(this.extensionOAuthProviders);
2204
+ const prevBase = this.baseSnapshot;
2205
+ const prevOAuthUrls = new Map(this.activeOAuthUrls);
2206
+ const prevReplaced = new Set(this.routeReplacedProviders);
2207
+ const prevRtUrls = new Map(this.runtimeProviderUrls);
2208
+ const prevEpochs = new Map(this.oauthProviderEpoch);
2209
+ const prev = [this.modelOrder.slice(), { ...this.modelOverrides }, this.configDefaults, this.usingExternalProviders, new Set(this.localProfileIds), new Map(this.remoteCredentialEnvByProvider), new Map(this.remoteCatalogByProvider), new Map(this.remoteCredentialFingerprintByCatalog), this.loadError];
2210
+ const rollback = () => {
2211
+ this.models = prevModels;
2212
+ this.authStorage.restoreProviderConfig(prevAuth);
2213
+ this.extensionOAuthProviders = prevOAuth;
2214
+ this.baseSnapshot = prevBase;
2215
+ this.activeOAuthUrls = prevOAuthUrls;
2216
+ this.routeReplacedProviders = prevReplaced;
2217
+ this.runtimeProviderUrls = prevRtUrls;
2218
+ this.oauthProviderEpoch = prevEpochs;
2219
+ [this.modelOrder, this.modelOverrides, this.configDefaults, this.usingExternalProviders, this.localProfileIds, this.remoteCredentialEnvByProvider, this.remoteCatalogByProvider, this.remoteCredentialFingerprintByCatalog, this.loadError] = prev;
2220
+ return false;
2221
+ };
2222
+ this.load();
2223
+ if (this.loadError) return rollback();
2224
+ try {
2225
+ this.rebuildFromBaseline();
2226
+ } catch {
2227
+ return rollback();
2228
+ }
2229
+ this.runtimeReloadEpoch++;
2230
+ return true;
2231
+ }
2071
2232
  async restorePersistedOAuth() {
2072
2233
  const authStorage = this.authStorage;
2073
2234
  const results = [];
2074
2235
  for (const provider of authStorage.getOAuthProviderNames()) {
2236
+ if (authStorage.isOAuthMasked(provider)) continue;
2075
2237
  const credentials = authStorage.getOAuthCredentials(provider);
2076
- if (!credentials?.access) continue;
2077
- const expired = credentials.expires !== void 0 && credentials.expires <= Date.now() + OAUTH_RESTORE_LEEWAY_MS;
2078
- if (!expired) continue;
2079
- const oauth = this.extensionOAuthProviders.get(provider);
2080
- if (!oauth?.refreshToken || !credentials.refresh) {
2238
+ if (!credentials?.access || credentials.expires !== void 0 && credentials.expires > Date.now() + OAUTH_RESTORE_LEEWAY_MS) continue;
2239
+ const binding = this.getExtensionOAuthBinding(provider);
2240
+ if (!binding || credentials.endpoint !== binding.baseUrl) {
2241
+ authStorage.setRuntimeApiKey(provider, void 0);
2242
+ results.push({ provider, action: "not-refreshable", detail: "credentials missing or mismatched endpoint binding; re-login required" });
2243
+ continue;
2244
+ }
2245
+ const oauth = binding.oauth;
2246
+ if (!oauth.refreshToken || !credentials.refresh) {
2081
2247
  authStorage.setRuntimeApiKey(provider, void 0);
2082
2248
  results.push({ provider, action: "not-refreshable", detail: "token expired and no refresh flow" });
2083
2249
  continue;
2084
2250
  }
2085
2251
  try {
2086
- const next = await withTimeout(
2087
- oauth.refreshToken({
2088
- access: credentials.access,
2089
- refresh: credentials.refresh,
2090
- expires: credentials.expires
2091
- }),
2092
- OAUTH_REFRESH_TIMEOUT_MS,
2093
- `${provider} refreshToken timed out after ${OAUTH_REFRESH_TIMEOUT_MS}ms`
2094
- );
2095
- const merged = { ...credentials, ...next };
2096
- authStorage.setOAuthCredentials(provider, merged);
2097
- authStorage.setRuntimeApiKey(provider, merged.access);
2252
+ const next = await withTimeout(oauth.refreshToken({ access: credentials.access, refresh: credentials.refresh, expires: credentials.expires }), OAUTH_REFRESH_TIMEOUT_MS, `${provider} refreshToken timed out after ${OAUTH_REFRESH_TIMEOUT_MS}ms`);
2253
+ if (!this.commitExtensionOAuthCredentials(provider, binding, { ...credentials, ...next })) continue;
2098
2254
  results.push({ provider, action: "refreshed" });
2099
2255
  } catch (error) {
2100
- authStorage.setRuntimeApiKey(provider, void 0);
2256
+ if (!this.commitExtensionOAuthCredentials(provider, binding, void 0)) continue;
2101
2257
  results.push({ provider, action: "refresh-failed", detail: error instanceof Error ? error.message : String(error) });
2102
2258
  }
2103
2259
  }
@@ -2110,8 +2266,13 @@ var ModelRegistry = class {
2110
2266
  };
2111
2267
 
2112
2268
  export {
2269
+ mergeThinkingCapability,
2113
2270
  assertNoSecretSubstrings,
2114
2271
  configuredRemoteCredentialValues,
2272
+ validatedRemoteCatalogs,
2273
+ validateModelsDocumentShape,
2115
2274
  loadResolvedModelsConfig,
2275
+ resolveProfileRoute,
2276
+ validateProfileConfig,
2116
2277
  ModelRegistry
2117
2278
  };