omnicell-router 0.1.0 → 0.2.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 (212) hide show
  1. package/RELEASING.md +238 -238
  2. package/RELEASING.zh-CN.md +230 -230
  3. package/backend/dist/capture/recorder.js +2 -1
  4. package/backend/dist/cli/clients/base.js +8 -16
  5. package/backend/dist/cli/clients/dsh.js +8 -16
  6. package/backend/dist/cli/clients/pi.js +16 -9
  7. package/backend/dist/cli/types.d.ts +5 -0
  8. package/backend/dist/config/env.js +2 -1
  9. package/backend/dist/config/index.js +2 -0
  10. package/backend/dist/config/types.d.ts +23 -0
  11. package/backend/dist/harness/adapters/amp.d.ts +2 -0
  12. package/backend/dist/harness/adapters/amp.js +7 -0
  13. package/backend/dist/harness/adapters/claude.d.ts +2 -0
  14. package/backend/dist/harness/adapters/claude.js +7 -0
  15. package/backend/dist/harness/adapters/cline.d.ts +2 -0
  16. package/backend/dist/harness/adapters/cline.js +6 -0
  17. package/backend/dist/harness/adapters/codex.d.ts +2 -0
  18. package/backend/dist/harness/adapters/codex.js +6 -0
  19. package/backend/dist/harness/adapters/cursor.d.ts +5 -0
  20. package/backend/dist/harness/adapters/cursor.js +10 -0
  21. package/backend/dist/harness/adapters/declarative.d.ts +62 -0
  22. package/backend/dist/harness/adapters/declarative.js +202 -0
  23. package/backend/dist/harness/adapters/dsh.d.ts +5 -0
  24. package/backend/dist/harness/adapters/dsh.js +6 -0
  25. package/backend/dist/harness/adapters/gemini-cli.d.ts +2 -0
  26. package/backend/dist/harness/adapters/gemini-cli.js +7 -0
  27. package/backend/dist/harness/adapters/github-copilot.d.ts +5 -0
  28. package/backend/dist/harness/adapters/github-copilot.js +10 -0
  29. package/backend/dist/harness/adapters/index.d.ts +44 -0
  30. package/backend/dist/harness/adapters/index.js +99 -0
  31. package/backend/dist/harness/adapters/opencode.d.ts +2 -0
  32. package/backend/dist/harness/adapters/opencode.js +55 -0
  33. package/backend/dist/harness/adapters/pi.d.ts +1 -0
  34. package/backend/dist/harness/adapters/pi.js +22 -0
  35. package/backend/dist/harness/adapters/skills-paths.d.ts +15 -0
  36. package/backend/dist/harness/adapters/skills-paths.js +17 -0
  37. package/backend/dist/harness/adapters/types.d.ts +174 -0
  38. package/backend/dist/harness/adapters/types.js +12 -0
  39. package/backend/dist/harness/adapters/universal.d.ts +6 -0
  40. package/backend/dist/harness/adapters/universal.js +10 -0
  41. package/backend/dist/harness/adapters/windsurf.d.ts +2 -0
  42. package/backend/dist/harness/adapters/windsurf.js +10 -0
  43. package/backend/dist/harness/adapters/zed.d.ts +2 -0
  44. package/backend/dist/harness/adapters/zed.js +6 -0
  45. package/backend/dist/harness/awesome-opencode.d.ts +40 -0
  46. package/backend/dist/harness/awesome-opencode.js +75 -0
  47. package/backend/dist/harness/browse.d.ts +202 -0
  48. package/backend/dist/harness/browse.js +1214 -0
  49. package/backend/dist/harness/catalog-npm.d.ts +59 -0
  50. package/backend/dist/harness/catalog-npm.js +145 -0
  51. package/backend/dist/harness/clawhub.d.ts +212 -0
  52. package/backend/dist/harness/clawhub.js +426 -0
  53. package/backend/dist/harness/config-file.d.ts +29 -0
  54. package/backend/dist/harness/config-file.js +35 -0
  55. package/backend/dist/harness/detail.d.ts +74 -0
  56. package/backend/dist/harness/detail.js +330 -0
  57. package/backend/dist/harness/discover.d.ts +118 -0
  58. package/backend/dist/harness/discover.js +507 -0
  59. package/backend/dist/harness/drift.d.ts +21 -0
  60. package/backend/dist/harness/drift.js +25 -0
  61. package/backend/dist/harness/hash.d.ts +10 -0
  62. package/backend/dist/harness/hash.js +63 -0
  63. package/backend/dist/harness/hosts.d.ts +18 -0
  64. package/backend/dist/harness/hosts.js +15 -0
  65. package/backend/dist/harness/install.d.ts +88 -0
  66. package/backend/dist/harness/install.js +301 -0
  67. package/backend/dist/harness/inventory.d.ts +10 -0
  68. package/backend/dist/harness/inventory.js +198 -0
  69. package/backend/dist/harness/ledger.d.ts +39 -0
  70. package/backend/dist/harness/ledger.js +83 -0
  71. package/backend/dist/harness/maintenance.d.ts +115 -0
  72. package/backend/dist/harness/maintenance.js +603 -0
  73. package/backend/dist/harness/manifest.d.ts +31 -0
  74. package/backend/dist/harness/manifest.js +234 -0
  75. package/backend/dist/harness/net.d.ts +86 -0
  76. package/backend/dist/harness/net.js +113 -0
  77. package/backend/dist/harness/opencode-cafe.d.ts +40 -0
  78. package/backend/dist/harness/opencode-cafe.js +85 -0
  79. package/backend/dist/harness/opencode-ecosystem.d.ts +34 -0
  80. package/backend/dist/harness/opencode-ecosystem.js +246 -0
  81. package/backend/dist/harness/pi-dev.d.ts +81 -0
  82. package/backend/dist/harness/pi-dev.js +187 -0
  83. package/backend/dist/harness/probe.d.ts +33 -0
  84. package/backend/dist/harness/probe.js +85 -0
  85. package/backend/dist/harness/registry.d.ts +2 -0
  86. package/backend/dist/harness/registry.js +26 -0
  87. package/backend/dist/harness/scopes.d.ts +21 -0
  88. package/backend/dist/harness/scopes.js +22 -0
  89. package/backend/dist/harness/skill-md.d.ts +18 -0
  90. package/backend/dist/harness/skill-md.js +71 -0
  91. package/backend/dist/harness/skills-sh.d.ts +109 -0
  92. package/backend/dist/harness/skills-sh.js +178 -0
  93. package/backend/dist/harness/smithery.d.ts +64 -0
  94. package/backend/dist/harness/smithery.js +146 -0
  95. package/backend/dist/harness/sources/awesome-opencode.d.ts +11 -0
  96. package/backend/dist/harness/sources/awesome-opencode.js +39 -0
  97. package/backend/dist/harness/sources/clawhub.d.ts +2 -0
  98. package/backend/dist/harness/sources/clawhub.js +83 -0
  99. package/backend/dist/harness/sources/github.d.ts +9 -0
  100. package/backend/dist/harness/sources/github.js +202 -0
  101. package/backend/dist/harness/sources/mcp-official.d.ts +2 -0
  102. package/backend/dist/harness/sources/mcp-official.js +110 -0
  103. package/backend/dist/harness/sources/npm.d.ts +2 -0
  104. package/backend/dist/harness/sources/npm.js +152 -0
  105. package/backend/dist/harness/sources/opencode-cafe.d.ts +11 -0
  106. package/backend/dist/harness/sources/opencode-cafe.js +41 -0
  107. package/backend/dist/harness/sources/smithery.d.ts +2 -0
  108. package/backend/dist/harness/sources/smithery.js +81 -0
  109. package/backend/dist/harness/spi.d.ts +98 -0
  110. package/backend/dist/harness/spi.js +8 -0
  111. package/backend/dist/harness/stars.d.ts +70 -0
  112. package/backend/dist/harness/stars.js +202 -0
  113. package/backend/dist/harness/translation.d.ts +142 -0
  114. package/backend/dist/harness/translation.js +567 -0
  115. package/backend/dist/harness/tree.d.ts +13 -0
  116. package/backend/dist/harness/tree.js +19 -0
  117. package/backend/dist/harness/types.d.ts +286 -0
  118. package/backend/dist/harness/types.js +8 -0
  119. package/backend/dist/harness/writers/extension.d.ts +116 -0
  120. package/backend/dist/harness/writers/extension.js +219 -0
  121. package/backend/dist/harness/writers/mcp.d.ts +72 -0
  122. package/backend/dist/harness/writers/mcp.js +195 -0
  123. package/backend/dist/harness/writers/skill.d.ts +60 -0
  124. package/backend/dist/harness/writers/skill.js +146 -0
  125. package/backend/dist/opencode/agents.d.ts +5 -0
  126. package/backend/dist/opencode/agents.js +10 -1
  127. package/backend/dist/opencode/catalog/cache.js +2 -1
  128. package/backend/dist/opencode/catalog/logos.js +2 -1
  129. package/backend/dist/opencode/catalog/ocr-store.js +2 -1
  130. package/backend/dist/opencode/catalog/overrides-store.js +2 -1
  131. package/backend/dist/opencode/credentials/factory.js +10 -27
  132. package/backend/dist/opencode/credentials/ocr-store.js +2 -1
  133. package/backend/dist/opencode/provider-defs.js +2 -1
  134. package/backend/dist/opencode/user-config.js +8 -16
  135. package/backend/dist/providers/registry.d.ts +15 -4
  136. package/backend/dist/providers/registry.js +29 -5
  137. package/backend/dist/providers/virtual-meta.d.ts +13 -0
  138. package/backend/dist/providers/virtual-meta.js +18 -0
  139. package/backend/dist/quota/store.js +2 -1
  140. package/backend/dist/resilience/breaker-state.js +2 -1
  141. package/backend/dist/resilience/credential-state.js +2 -1
  142. package/backend/dist/routes/console.js +137 -15
  143. package/backend/dist/routes/harness.d.ts +2 -0
  144. package/backend/dist/routes/harness.js +622 -0
  145. package/backend/dist/server.js +4 -0
  146. package/backend/dist/session/session-manager.js +2 -1
  147. package/backend/dist/surfaces/systemone-probe.d.ts +25 -0
  148. package/backend/dist/surfaces/systemone-probe.js +74 -0
  149. package/backend/dist/utils/atomic-write.d.ts +12 -0
  150. package/backend/dist/utils/atomic-write.js +29 -0
  151. package/bin/ocr.js +2 -2
  152. package/frontend/dist/assets/{index-DEo2iAT7.css → index-1o7qI-KJ.css} +1 -1
  153. package/frontend/dist/assets/index-DvXKvNxl.js +962 -0
  154. package/frontend/dist/index.html +2 -2
  155. package/package.json +87 -87
  156. package/backend/dist/budget/budget-manager.d.ts +0 -25
  157. package/backend/dist/budget/budget-manager.js +0 -54
  158. package/backend/dist/config/governance-limits.d.ts +0 -68
  159. package/backend/dist/config/governance-limits.js +0 -261
  160. package/backend/dist/flywheel/collector.d.ts +0 -74
  161. package/backend/dist/flywheel/collector.js +0 -235
  162. package/backend/dist/flywheel/dataset.d.ts +0 -130
  163. package/backend/dist/flywheel/dataset.js +0 -638
  164. package/backend/dist/flywheel/decision-capture.d.ts +0 -68
  165. package/backend/dist/flywheel/decision-capture.js +0 -85
  166. package/backend/dist/flywheel/prune.d.ts +0 -133
  167. package/backend/dist/flywheel/prune.js +0 -495
  168. package/backend/dist/flywheel/schema.d.ts +0 -108
  169. package/backend/dist/flywheel/schema.js +0 -117
  170. package/backend/dist/flywheel/trainer.d.ts +0 -84
  171. package/backend/dist/flywheel/trainer.js +0 -198
  172. package/backend/dist/opencode/catalog/custom-store.d.ts +0 -50
  173. package/backend/dist/opencode/catalog/custom-store.js +0 -144
  174. package/backend/dist/opencode/credentials/push.d.ts +0 -38
  175. package/backend/dist/opencode/credentials/push.js +0 -116
  176. package/backend/dist/opencode/credentials/reconcile.d.ts +0 -49
  177. package/backend/dist/opencode/credentials/reconcile.js +0 -216
  178. package/backend/dist/opencode/sync.d.ts +0 -29
  179. package/backend/dist/opencode/sync.js +0 -186
  180. package/backend/dist/pipeline/account-selection.d.ts +0 -101
  181. package/backend/dist/pipeline/account-selection.js +0 -112
  182. package/backend/dist/providers/systemone.d.ts +0 -29
  183. package/backend/dist/providers/systemone.js +0 -170
  184. package/backend/dist/ratelimit/duration.d.ts +0 -24
  185. package/backend/dist/ratelimit/duration.js +0 -43
  186. package/backend/dist/ratelimit/governance-runtime.d.ts +0 -121
  187. package/backend/dist/ratelimit/governance-runtime.js +0 -183
  188. package/backend/dist/ratelimit/index.d.ts +0 -4
  189. package/backend/dist/ratelimit/index.js +0 -4
  190. package/backend/dist/ratelimit/limiter.d.ts +0 -157
  191. package/backend/dist/ratelimit/limiter.js +0 -244
  192. package/backend/dist/ratelimit/sliding-window-counter.d.ts +0 -63
  193. package/backend/dist/ratelimit/sliding-window-counter.js +0 -103
  194. package/backend/dist/ratelimit/subject.d.ts +0 -26
  195. package/backend/dist/ratelimit/subject.js +0 -28
  196. package/backend/dist/resilience/account-state.d.ts +0 -84
  197. package/backend/dist/resilience/account-state.js +0 -228
  198. package/backend/dist/router/layer1-classifier.d.ts +0 -111
  199. package/backend/dist/router/layer1-classifier.js +0 -467
  200. package/backend/dist/router/layer2-judge.d.ts +0 -111
  201. package/backend/dist/router/layer2-judge.js +0 -373
  202. package/backend/dist/router/retry-escalation.d.ts +0 -89
  203. package/backend/dist/router/retry-escalation.js +0 -99
  204. package/backend/dist/routes/flywheel.d.ts +0 -3
  205. package/backend/dist/routes/flywheel.js +0 -268
  206. package/backend/dist/routes/systemone.d.ts +0 -3
  207. package/backend/dist/routes/systemone.js +0 -90
  208. package/backend/dist/surfaces/governance-envelope.d.ts +0 -34
  209. package/backend/dist/surfaces/governance-envelope.js +0 -47
  210. package/backend/dist/utils/token-estimator.d.ts +0 -7
  211. package/backend/dist/utils/token-estimator.js +0 -20
  212. package/frontend/dist/assets/index-nwgWkmU1.js +0 -840
@@ -4,6 +4,7 @@ import { PROVIDER_ID_RULE, isValidProviderId, readJsonc } from './user-config.js
4
4
  import { resolveDefaultPaths, resolveOpencodeConfigPath } from './credentials/paths.js';
5
5
  import { detectClientFlavor } from './credentials/paths.js';
6
6
  import { providerDefAdapter } from './provider-def-adapters.js';
7
+ import { renameWithRetry } from '../utils/atomic-write.js';
7
8
  /** Bump when the import learns a new source or a new shape conversion. */
8
9
  export const PROVIDER_DEFS_IMPORT_VERSION = 2;
9
10
  export function getProviderDefsPath(paths = resolveDefaultPaths()) {
@@ -57,7 +58,7 @@ export function writeProviderDefs(providers, paths = resolveDefaultPaths()) {
57
58
  const next = { version: 1, updated: Date.now(), providers };
58
59
  const tmp = `${file}.tmp.${process.pid}.${Date.now()}`;
59
60
  fs.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, 'utf8');
60
- fs.renameSync(tmp, file);
61
+ renameWithRetry(tmp, file);
61
62
  defsMutationHook?.(); // defs changed → the sync engine's debounced auto-write converges clients
62
63
  }
63
64
  /** Boot seam: the sync engine registers its auto-write debounce here (null = detached). */
@@ -3,6 +3,7 @@ import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { applyEdits, modify, parse, } from 'jsonc-parser';
5
5
  import { isOpencodeV2Package } from '../providers/wire.js';
6
+ import { renameWithRetry } from '../utils/atomic-write.js';
6
7
  import { readProviderDefsFile, writeProviderDefs } from './provider-defs.js';
7
8
  import { resolveDefaultPaths, resolveOpencodeConfigPath } from './credentials/paths.js';
8
9
  /**
@@ -60,25 +61,16 @@ function atomicWrite(filePath, content) {
60
61
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
61
62
  const tmpPath = `${filePath}.tmp.${process.pid}.${Date.now()}`;
62
63
  fs.writeFileSync(tmpPath, content, 'utf8');
63
- let lastError;
64
- for (let attempt = 0; attempt < 5; attempt++) {
64
+ try {
65
+ renameWithRetry(tmpPath, filePath);
66
+ }
67
+ catch (e) {
65
68
  try {
66
- fs.renameSync(tmpPath, filePath);
67
- return;
68
- }
69
- catch (e) {
70
- lastError = e;
71
- if (attempt < 4) {
72
- const until = Date.now() + (attempt + 1) * 10;
73
- while (Date.now() < until) { }
74
- }
69
+ fs.unlinkSync(tmpPath);
75
70
  }
71
+ catch { }
72
+ throw e;
76
73
  }
77
- try {
78
- fs.unlinkSync(tmpPath);
79
- }
80
- catch { }
81
- throw lastError;
82
74
  }
83
75
  function backupOnce(filePath, suffix) {
84
76
  if (!fs.existsSync(filePath))
@@ -22,6 +22,10 @@ export declare class ProviderRegistry {
22
22
  private rrCursor;
23
23
  private combos;
24
24
  private comboRrCursor;
25
+ /** Fingerprint of the combo section last applied by applyCombos — lets the
26
+ * lazy hand-edit safety net skip no-op replays instead of resetting
27
+ * round-robin cursors and re-logging skip warnings every TTL window. */
28
+ private combosFingerprint;
25
29
  /** Raw configs for every configured provider (all types) — lets the
26
30
  * /v1/systemone route reach provider baseUrl/apiKey (this map is the
27
31
  * credential/config source for chat providers registered outside the
@@ -166,7 +170,7 @@ export declare class ProviderRegistry {
166
170
  * pool resolution instead of waiting for a gateway restart. Model UNIVERSE
167
171
  * (providers/credentials/wire) stays a boot snapshot.
168
172
  */
169
- /** Hot-path guard: replay member lists + refresh policies at most every 2 seconds. */
173
+ /** Hot-path guard: replay member lists + the combo map + policies at most every 2 seconds. */
170
174
  private maybeRefreshTierMatch;
171
175
  /** Latest committed `tiers` config (snapshot; updated by applyTierConfigNow / maybeRefreshTierMatch). */
172
176
  getTierPolicies(): TiersConfig;
@@ -186,8 +190,8 @@ export declare class ProviderRegistry {
186
190
  /**
187
191
  * COMMIT path — the only one that rewrites live pool membership. Called on
188
192
  * every config-save event (console routes) so edits take effect immediately;
189
- * the lazy maybeRefreshTierMatch replay remains only as the out-of-band
190
- * (hand-edited YAML) safety net.
193
+ * the lazy maybeRefreshTierMatch replay (tiers AND combos) remains only as
194
+ * the out-of-band (hand-edited YAML) safety net.
191
195
  */
192
196
  applyTierConfigNow(): void;
193
197
  /** Replays the member lists over every reclassifiable model and stores
@@ -286,7 +290,14 @@ export declare class ProviderRegistry {
286
290
  base: ModelRegistration;
287
291
  variant: ModelVariant;
288
292
  }[];
289
- /** (Re)register combo definitions — used at boot and for hot-apply on console config saves. */
293
+ /**
294
+ * (Re)register combo definitions — used at boot, for hot-apply on console
295
+ * config saves, and by the lazy maybeRefreshTierMatch safety net. A section
296
+ * byte-identical to the last applied one is a no-op (keeps round-robin
297
+ * cursors, avoids repeat skip warnings): skip outcomes depend only on the
298
+ * section plus the monotonically grown model map, and every read path
299
+ * re-checks model shadowing live, so skipping loses nothing.
300
+ */
290
301
  applyCombos(combos?: ComboConfig[]): void;
291
302
  isCombo(modelId: string): boolean;
292
303
  getCombos(): ComboConfig[];
@@ -58,6 +58,10 @@ export class ProviderRegistry {
58
58
  rrCursor = new Map();
59
59
  combos = new Map();
60
60
  comboRrCursor = new Map();
61
+ /** Fingerprint of the combo section last applied by applyCombos — lets the
62
+ * lazy hand-edit safety net skip no-op replays instead of resetting
63
+ * round-robin cursors and re-logging skip warnings every TTL window. */
64
+ combosFingerprint = '';
61
65
  /** Raw configs for every configured provider (all types) — lets the
62
66
  * /v1/systemone route reach provider baseUrl/apiKey (this map is the
63
67
  * credential/config source for chat providers registered outside the
@@ -436,7 +440,7 @@ export class ProviderRegistry {
436
440
  * pool resolution instead of waiting for a gateway restart. Model UNIVERSE
437
441
  * (providers/credentials/wire) stays a boot snapshot.
438
442
  */
439
- /** Hot-path guard: replay member lists + refresh policies at most every 2 seconds. */
443
+ /** Hot-path guard: replay member lists + the combo map + policies at most every 2 seconds. */
440
444
  maybeRefreshTierMatch() {
441
445
  if (!this.autoRefreshTierMatch)
442
446
  return;
@@ -445,7 +449,16 @@ export class ProviderRegistry {
445
449
  return;
446
450
  this.lastMatchRefreshAt = now;
447
451
  try {
448
- const tiers = loadConfig().tiers || {};
452
+ const fresh = loadConfig();
453
+ // Combos share the hand-edited-YAML safety net: a combo write that
454
+ // bypasses the console save paths (hand edit, direct saveConfig
455
+ // callers) must not stay invisible to routing until the next save
456
+ // event. Applied BEFORE the tier replay — combo-ref expansion reads
457
+ // the combo map. Mock mode excepted: hermetic registries never couple
458
+ // to disk. applyCombos self-skips on an unchanged section.
459
+ if (!this.mockMode)
460
+ this.applyCombos(fresh.combos);
461
+ const tiers = fresh.tiers || {};
449
462
  this.tierPolicies = tiers; // the global denylist lives here too
450
463
  this.reclassifyTiers(this.expandedMemberRules(tiers).tiers);
451
464
  }
@@ -482,8 +495,8 @@ export class ProviderRegistry {
482
495
  /**
483
496
  * COMMIT path — the only one that rewrites live pool membership. Called on
484
497
  * every config-save event (console routes) so edits take effect immediately;
485
- * the lazy maybeRefreshTierMatch replay remains only as the out-of-band
486
- * (hand-edited YAML) safety net.
498
+ * the lazy maybeRefreshTierMatch replay (tiers AND combos) remains only as
499
+ * the out-of-band (hand-edited YAML) safety net.
487
500
  */
488
501
  applyTierConfigNow() {
489
502
  if (this.mockMode)
@@ -764,8 +777,19 @@ export class ProviderRegistry {
764
777
  return out;
765
778
  }
766
779
  // ─── Custom model combos ────────────────────────────────────────────────
767
- /** (Re)register combo definitions — used at boot and for hot-apply on console config saves. */
780
+ /**
781
+ * (Re)register combo definitions — used at boot, for hot-apply on console
782
+ * config saves, and by the lazy maybeRefreshTierMatch safety net. A section
783
+ * byte-identical to the last applied one is a no-op (keeps round-robin
784
+ * cursors, avoids repeat skip warnings): skip outcomes depend only on the
785
+ * section plus the monotonically grown model map, and every read path
786
+ * re-checks model shadowing live, so skipping loses nothing.
787
+ */
768
788
  applyCombos(combos) {
789
+ const fingerprint = JSON.stringify(combos ?? null);
790
+ if (fingerprint === this.combosFingerprint)
791
+ return;
792
+ this.combosFingerprint = fingerprint;
769
793
  this.combos.clear();
770
794
  this.comboRrCursor.clear();
771
795
  for (const combo of combos || []) {
@@ -53,6 +53,19 @@ export declare function modelsDevBlock(cat: CatalogModel): Record<string, unknow
53
53
  export declare function virtualModelsDevBlock(env: VirtualEnvelope): Record<string, unknown>;
54
54
  /** The tier ladder in escalation order — `auto` spans all of it. */
55
55
  export declare const TIER_LADDER: readonly TierLevel[];
56
+ /**
57
+ * What each tier is FOR — a FUNCTION label, deliberately not a price or
58
+ * capability ranking. The distinction matters: an ordering ("lite < plus <
59
+ * pro < ultra, cheapest → broadest") makes every console decision land on the
60
+ * top rung, because "best" is then unambiguous. A function label instead lets
61
+ * a decider match a role's WORK to a tier.
62
+ *
63
+ * The wording mirrors the gateway's own pi-subagent default mapping
64
+ * (cli/clients/pi.ts PI_SUBAGENT_TIERS), which is the one place these rungs
65
+ * were already given meaning. It is an operator-facing convention, not a
66
+ * routing rule: routing itself only knows pool membership.
67
+ */
68
+ export declare const TIER_PURPOSE: Record<TierLevel, string>;
56
69
  /** Minimal registry seam so callers can pass the live singleton (or a stub). */
57
70
  export type CatalogList = () => Promise<CatalogProviderRecord[]>;
58
71
  /**
@@ -40,6 +40,24 @@ export function virtualModelsDevBlock(env) {
40
40
  }
41
41
  /** The tier ladder in escalation order — `auto` spans all of it. */
42
42
  export const TIER_LADDER = ['lite', 'plus', 'pro', 'ultra'];
43
+ /**
44
+ * What each tier is FOR — a FUNCTION label, deliberately not a price or
45
+ * capability ranking. The distinction matters: an ordering ("lite < plus <
46
+ * pro < ultra, cheapest → broadest") makes every console decision land on the
47
+ * top rung, because "best" is then unambiguous. A function label instead lets
48
+ * a decider match a role's WORK to a tier.
49
+ *
50
+ * The wording mirrors the gateway's own pi-subagent default mapping
51
+ * (cli/clients/pi.ts PI_SUBAGENT_TIERS), which is the one place these rungs
52
+ * were already given meaning. It is an operator-facing convention, not a
53
+ * routing rule: routing itself only knows pool membership.
54
+ */
55
+ export const TIER_PURPOSE = {
56
+ lite: 'recon & web research — breadth over depth, cheap single-shot work',
57
+ plus: 'verification & delegation — check someone else\'s output, hand work out',
58
+ pro: 'implementation & review — write code, review code',
59
+ ultra: 'the oracle second opinion — the hardest judgment calls',
60
+ };
43
61
  /** Common math: safe-min limits, intersection image, leader pricing/name. */
44
62
  function envelopeOf(memberCats, leaderCat, leaderPricing, fallbackCount) {
45
63
  const contexts = memberCats.map((c) => c.limit?.context).filter((n) => typeof n === 'number' && n > 0);
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { resolveDefaultPaths, quotaSnapshotsFile, } from '../opencode/credentials/paths.js';
4
+ import { renameWithRetry } from '../utils/atomic-write.js';
4
5
  /**
5
6
  * The (provider × keyHashPrefix) quota snapshot store.
6
7
  *
@@ -224,7 +225,7 @@ export class QuotaSnapshotStore {
224
225
  };
225
226
  const tmp = `${file}.tmp-${process.pid}`;
226
227
  fs.writeFileSync(tmp, JSON.stringify(payload, null, 2), { mode: 0o600 });
227
- fs.renameSync(tmp, file);
228
+ renameWithRetry(tmp, file);
228
229
  }
229
230
  catch (err) {
230
231
  console.warn(`[quota] snapshot save failed: ${err?.message ?? err}`);
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { peekEnvName } from '../config/env.js';
4
+ import { renameWithRetry } from '../utils/atomic-write.js';
4
5
  import { breakerStateFile, resolveDefaultPaths, } from '../opencode/credentials/paths.js';
5
6
  import { ERROR_CATEGORIES, BREAKER_REASON_CODES, } from './types.js';
6
7
  /**
@@ -225,7 +226,7 @@ export class BreakerStateStore {
225
226
  catch {
226
227
  // best effort — Windows chmod semantics differ
227
228
  }
228
- fs.renameSync(tmpPath, this.filePath);
229
+ renameWithRetry(tmpPath, this.filePath);
229
230
  }
230
231
  catch (e) {
231
232
  // The gateway keeps running on in-memory breakers; only persistence
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { resolveDefaultPaths, suspectCredentialsFile, } from '../opencode/credentials/paths.js';
4
+ import { renameWithRetry } from '../utils/atomic-write.js';
4
5
  /**
5
6
  * The SUSPECT credential flag store.
6
7
  *
@@ -173,7 +174,7 @@ export class CredentialStateStore {
173
174
  catch {
174
175
  // best effort — Windows chmod semantics differ
175
176
  }
176
- fs.renameSync(tmpPath, this.filePath);
177
+ renameWithRetry(tmpPath, this.filePath);
177
178
  // The new file is durable — only now may the legacy name go away. A failed
178
179
  // unlink leaves the flag set; the next persist retries the cleanup.
179
180
  if (this.legacyCleanupFile) {
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { getAllClientStatuses, refreshClientProfileBindings, setupClient, teardownClient } from '../cli/clients/index.js';
4
4
  import { MEMBER_TIER_ORDER } from '../providers/member-match.js';
5
+ import { TIER_PURPOSE } from '../providers/virtual-meta.js';
5
6
  import { globMatchAny } from '../utils/glob.js';
6
7
  import { getRawConfig, loadConfig, saveConfig, saveRawConfig, getRuntimeConfigRef } from '../config/index.js';
7
8
  import { getEnvPaths, resolveEnvName } from '../config/env.js';
@@ -1112,6 +1113,94 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
1112
1113
  };
1113
1114
  app.post('/api/admin/client/:client/setup', handleSetup);
1114
1115
  app.post('/api/admin/client/:client/teardown', handleTeardown);
1116
+ /**
1117
+ * Resolve a console decider PICK to the PHYSICAL model that answers it.
1118
+ * Deliberately the SAME cascade the /v1/systemone surface applies (ADR-0008),
1119
+ * so a name means one thing console-wide: a registered id, or a combo (its
1120
+ * leader member answers — the same leader pick the routing path uses), is
1121
+ * used as-is; a bare tier alias projects onto the chain head of its healthy
1122
+ * DECISION-SURFACE pool (the read that keeps systemone-wire models in view);
1123
+ * bare `auto` means `systemone.defaultModel`. Undefined = nothing routable
1124
+ * behind the name (unknown id, combo without members, empty/all-unhealthy
1125
+ * pool, unset default) — callers must refuse, never silently fall back.
1126
+ */
1127
+ const resolveDecider = (raw) => {
1128
+ const direct = registry.getModel(raw);
1129
+ if (direct)
1130
+ return direct;
1131
+ if (registry.isCombo(raw)) {
1132
+ const members = registry.resolveCombo(raw);
1133
+ return members.length > 0 ? registry.pickComboLeader(raw, members) : undefined;
1134
+ }
1135
+ if (raw === 'auto') {
1136
+ const fallback = (loadConfig().systemone?.defaultModel || '').trim();
1137
+ return fallback ? registry.getModel(fallback) : undefined;
1138
+ }
1139
+ if (MEMBER_TIER_ORDER.includes(raw)) {
1140
+ return registry.getCandidateModelsForTier(raw, true, { decisionSurface: true })[0];
1141
+ }
1142
+ return undefined;
1143
+ };
1144
+ /**
1145
+ * One-line, model-readable description of a candidate — `criteria` values are
1146
+ * the ONLY per-option context the decision prompt carries (the whole
1147
+ * questions document is serialized verbatim by convert.ts
1148
+ * buildDecisionChatRequest). Registry data is the objective half (tier
1149
+ * membership, price, reasoning support, wire); the frontend-supplied note
1150
+ * carries what the registry cannot know (a profile slot link). Virtual ids
1151
+ * resolve to no entity and are described by what they MEAN, since "assign
1152
+ * `lite`" is a legitimate pick. Deliberately NO tier ladder here: writing
1153
+ * "ultra = broadest" made every role land on `ultra`.
1154
+ */
1155
+ const describeCandidate = (rawId, note) => {
1156
+ const m = registry.getModel(rawId);
1157
+ let body;
1158
+ if (m) {
1159
+ const tiers = registry.tiersOf(m);
1160
+ const parts = [
1161
+ `registered model; tiers=${tiers.length > 0 ? tiers.join('|') : 'none'}`,
1162
+ `price $${m.pricing?.input ?? 0}/$${m.pricing?.output ?? 0} per 1M tokens in/out`,
1163
+ ];
1164
+ if (m.wire === 'systemone') {
1165
+ parts.push('wire=systemone — decision protocol ONLY, cannot serve chat, never assign it to a chat role');
1166
+ }
1167
+ else if (m.wire) {
1168
+ parts.push(`wire=${m.wire}`);
1169
+ }
1170
+ const efforts = m.supportedReasoningEfforts;
1171
+ if (efforts && efforts.length > 0)
1172
+ parts.push(`reasoning=${efforts.join('|')}`);
1173
+ else if (m.supportsReasoningEffort)
1174
+ parts.push('reasoning=yes');
1175
+ body = parts.join('; ');
1176
+ }
1177
+ else if (registry.resolveVariantRef(rawId)) {
1178
+ // Variant sibling id (`<baseId>-<variantId>`): not a registry entry of its
1179
+ // own — the base model plus a pinned reasoning level (orchestrator
1180
+ // resolves it the same way). Calling it unregistered would steer the
1181
+ // decider away from a perfectly legal pick.
1182
+ const { base, variant } = registry.resolveVariantRef(rawId);
1183
+ const tiers = registry.tiersOf(base);
1184
+ body =
1185
+ `variant of ${base.id} (pins reasoning_effort '${variant.reasoningEffort}'); ` +
1186
+ `tiers=${tiers.length > 0 ? tiers.join('|') : 'none'}; ` +
1187
+ `price $${base.pricing?.input ?? 0}/$${base.pricing?.output ?? 0} per 1M tokens in/out; ` +
1188
+ `wire=${base.wire ?? 'unknown'}`;
1189
+ }
1190
+ else if (registry.isCombo(rawId)) {
1191
+ body = `combo; members=${registry.resolveCombo(rawId).length} (the router picks a healthy member per request)`;
1192
+ }
1193
+ else if (rawId === 'auto') {
1194
+ body = 'virtual alias auto; cross-tier auto-routing — the router picks per tier policy, not a fixed model';
1195
+ }
1196
+ else if (MEMBER_TIER_ORDER.includes(rawId)) {
1197
+ body = `virtual alias '${rawId}'; ${TIER_PURPOSE[rawId]}; the router picks a healthy member of that tier pool`;
1198
+ }
1199
+ else {
1200
+ body = 'NOT registered and not routable — do not pick';
1201
+ }
1202
+ return note ? `${body} · ${note}` : body;
1203
+ };
1115
1204
  /**
1116
1205
  * Smart slot assignment (console "smart assign" button): ONE System One
1117
1206
  * decision call against a caller-chosen decider model — per-target 'choice'
@@ -1141,35 +1230,39 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
1141
1230
  return reply.status(400).send({ success: false, message: 'targets must not be empty' });
1142
1231
  if (candidates.length === 0)
1143
1232
  return reply.status(400).send({ success: false, message: 'candidates must not be empty' });
1144
- // Resolve the decider to a PHYSICAL model: a combo id runs through its
1145
- // leader member (the same leader pick the routing path uses).
1146
- let model = registry.getModel(decider);
1147
- if (!model && registry.isCombo(decider)) {
1148
- const members = registry.resolveCombo(decider);
1149
- if (members.length === 0) {
1150
- return reply.status(400).send({ success: false, message: `Decider combo '${decider}' has no registered members` });
1151
- }
1152
- model = registry.pickComboLeader(decider, members);
1153
- }
1233
+ // Resolve the pick to a PHYSICAL model through the SAME cascade the
1234
+ // /v1/systemone surface applies (see resolveDecider): physical id / combo
1235
+ // leader / tier-alias pool head / `auto` → systemone.defaultModel.
1236
+ const model = resolveDecider(decider);
1154
1237
  if (!model) {
1155
- return reply.status(400).send({ success: false, message: `Decider model '${decider}' is not routable by the gateway` });
1238
+ return reply.status(400).send({
1239
+ success: false,
1240
+ message: `Decider '${decider}' does not resolve to a routable model (unknown id, empty tier pool, or unset systemone.defaultModel)`,
1241
+ });
1156
1242
  }
1157
1243
  const state = {
1158
- task: 'Assign each role/slot the MOST suitable candidate id.',
1244
+ // Tier PURPOSE (what each rung is for), never a ranking: a ladder reads
1245
+ // as "ultra is the most/broadest" and then every role lands on it.
1246
+ tierPurpose: TIER_PURPOSE,
1247
+ task: 'Assign each role/slot the MOST suitable candidate id. Every candidate is described with its objective profile (tier membership, price per 1M tokens, reasoning support, wire); use that — never guess from the model name alone.',
1159
1248
  roles: targets.map((t) => ({
1160
1249
  key: t.key,
1161
1250
  name: t.label || t.key,
1251
+ // `purpose` = the client's OWN role description when it declares one
1252
+ // (opencode agent frontmatter / pi agent file / live service roster).
1253
+ // Absent means unknown — never synthesized server-side: role sets are
1254
+ // discovered per client and change with the installed package.
1162
1255
  ...(t.role ? { purpose: t.role } : {}),
1163
1256
  ...(t.current ? { current: t.current } : {}),
1164
1257
  })),
1165
1258
  };
1166
- const rubric = 'Pick exactly one candidate id per question. Weigh the role purpose (capability needs, cost, latency) against each candidate.';
1259
+ const rubric = 'Pick exactly one candidate id per question. Match the role\'s WORK to the tier whose PURPOSE describes it (see tierPurpose), then weigh that candidate\'s described profile (capability needs, cost, latency). Do not default every role to one "best" model — the four tiers exist to separate that work. A candidate marked unable to serve chat is never a valid answer.';
1167
1260
  const questions = {};
1168
1261
  for (const t of targets) {
1169
1262
  questions[t.key] = {
1170
1263
  type: 'choice',
1171
1264
  instructions: rubric,
1172
- criteria: Object.fromEntries(candidates.map((c) => [c.id, c.note || c.id])),
1265
+ criteria: Object.fromEntries(candidates.map((c) => [c.id, describeCandidate(c.id, c.note)])),
1173
1266
  };
1174
1267
  }
1175
1268
  const params = req.params;
@@ -1196,14 +1289,25 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
1196
1289
  finally {
1197
1290
  clearTimeout(deadline);
1198
1291
  }
1292
+ // Diagnosability: "the decider picked badly" is unactionable without the
1293
+ // INPUT it saw and the CHOICES it made. `state` is small (roles + task);
1294
+ // `criteriaSample` shows one rendered candidate description verbatim and
1295
+ // `criteriaChars` the total prompt weight; `answers` collapses each answer
1296
+ // to its chosen id, so a diff against expectations is one line per role.
1297
+ // The full questions document stays out of the log.
1199
1298
  req.log.info({
1200
1299
  client: params.client,
1201
1300
  decider,
1301
+ resolved: model.id,
1202
1302
  resolvedWire: model.wire,
1203
1303
  upstreamKind,
1204
1304
  ms: Date.now() - startedAt,
1205
1305
  targets: targets.length,
1206
1306
  candidates: candidates.length,
1307
+ criteriaChars: JSON.stringify(questions).length,
1308
+ criteriaSample: candidates[0] ? describeCandidate(candidates[0].id, candidates[0].note) : '',
1309
+ state,
1310
+ answers: Object.fromEntries(Object.entries((response?.answers || {})).map(([k, v]) => [k, v?.choice])),
1207
1311
  usage: response?.usage,
1208
1312
  }, 'smart-assign: decider answered');
1209
1313
  const allowed = new Set(candidates.map((c) => c.id));
@@ -1222,7 +1326,25 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
1222
1326
  message: `Decider returned invalid/missing assignments for: ${invalid.join(', ')}`,
1223
1327
  });
1224
1328
  }
1225
- return { status: 'ok', assignments };
1329
+ return { status: 'ok', resolved: model.id, assignments };
1330
+ });
1331
+ /**
1332
+ * Resolve a decider name WITHOUT spending anything: the console shows
1333
+ * "→ <physical model>" next to the pick, so `lite` (a pool projection) and
1334
+ * `auto` (the System One default) are never blind choices about who answers.
1335
+ * Same resolver as the smart-assign call itself — one implementation.
1336
+ */
1337
+ app.get('/api/admin/decider/resolve', async (req, reply) => {
1338
+ const raw = String(req.query?.model || '').trim();
1339
+ if (!raw)
1340
+ return reply.status(400).send({ success: false, message: 'model is required' });
1341
+ const model = resolveDecider(raw);
1342
+ if (!model) {
1343
+ return reply
1344
+ .status(404)
1345
+ .send({ success: false, message: `Decider '${raw}' does not resolve to a routable model` });
1346
+ }
1347
+ return { success: true, model: raw, resolved: model.id };
1226
1348
  });
1227
1349
  // 4a. OpenCode agent inventory (model-profile binding UI): live v2 service
1228
1350
  // roster (`GET /api/agent`, plugins included) with the file scan
@@ -0,0 +1,2 @@
1
+ import type { FastifyInstance } from 'fastify';
2
+ export declare function registerHarnessRoutes(app: FastifyInstance): void;