omnicell-router 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/backend/dist/budget/budget-manager.d.ts +25 -0
  2. package/backend/dist/budget/budget-manager.js +54 -0
  3. package/backend/dist/cli/clients/index.js +2 -0
  4. package/backend/dist/cli/clients/omp.d.ts +53 -0
  5. package/backend/dist/cli/clients/omp.js +664 -0
  6. package/backend/dist/cli/clients/pi.js +79 -32
  7. package/backend/dist/cli/index.js +2 -2
  8. package/backend/dist/cli/types.d.ts +1 -1
  9. package/backend/dist/config/governance-limits.d.ts +68 -0
  10. package/backend/dist/config/governance-limits.js +261 -0
  11. package/backend/dist/config/index.js +1 -1
  12. package/backend/dist/config/types.d.ts +15 -5
  13. package/backend/dist/flywheel/collector.d.ts +74 -0
  14. package/backend/dist/flywheel/collector.js +235 -0
  15. package/backend/dist/flywheel/dataset.d.ts +130 -0
  16. package/backend/dist/flywheel/dataset.js +638 -0
  17. package/backend/dist/flywheel/decision-capture.d.ts +68 -0
  18. package/backend/dist/flywheel/decision-capture.js +85 -0
  19. package/backend/dist/flywheel/prune.d.ts +133 -0
  20. package/backend/dist/flywheel/prune.js +495 -0
  21. package/backend/dist/flywheel/schema.d.ts +108 -0
  22. package/backend/dist/flywheel/schema.js +117 -0
  23. package/backend/dist/flywheel/trainer.d.ts +84 -0
  24. package/backend/dist/flywheel/trainer.js +198 -0
  25. package/backend/dist/harness/adapters/amp.js +1 -0
  26. package/backend/dist/harness/adapters/claude.js +1 -0
  27. package/backend/dist/harness/adapters/cline.js +3 -1
  28. package/backend/dist/harness/adapters/codex.js +3 -1
  29. package/backend/dist/harness/adapters/cursor.js +1 -0
  30. package/backend/dist/harness/adapters/declarative.d.ts +3 -1
  31. package/backend/dist/harness/adapters/declarative.js +15 -1
  32. package/backend/dist/harness/adapters/dsh.js +1 -1
  33. package/backend/dist/harness/adapters/gemini-cli.js +1 -0
  34. package/backend/dist/harness/adapters/github-copilot.js +1 -0
  35. package/backend/dist/harness/adapters/index.d.ts +11 -3
  36. package/backend/dist/harness/adapters/index.js +48 -1
  37. package/backend/dist/harness/adapters/omp.d.ts +11 -0
  38. package/backend/dist/harness/adapters/omp.js +22 -0
  39. package/backend/dist/harness/adapters/opencode.js +1 -0
  40. package/backend/dist/harness/adapters/pi.js +2 -1
  41. package/backend/dist/harness/adapters/types.d.ts +19 -4
  42. package/backend/dist/harness/adapters/windsurf.js +1 -0
  43. package/backend/dist/harness/adapters/zed.js +3 -1
  44. package/backend/dist/harness/hosts.js +1 -0
  45. package/backend/dist/harness/translation.js +12 -4
  46. package/backend/dist/harness/types.d.ts +2 -2
  47. package/backend/dist/harness/writers/skill.d.ts +1 -1
  48. package/backend/dist/opencode/agents.d.ts +7 -0
  49. package/backend/dist/opencode/agents.js +22 -3
  50. package/backend/dist/opencode/catalog/custom-store.d.ts +50 -0
  51. package/backend/dist/opencode/catalog/custom-store.js +144 -0
  52. package/backend/dist/opencode/credentials/push.d.ts +38 -0
  53. package/backend/dist/opencode/credentials/push.js +116 -0
  54. package/backend/dist/opencode/credentials/reconcile.d.ts +49 -0
  55. package/backend/dist/opencode/credentials/reconcile.js +216 -0
  56. package/backend/dist/opencode/sync.d.ts +29 -0
  57. package/backend/dist/opencode/sync.js +186 -0
  58. package/backend/dist/pipeline/account-selection.d.ts +101 -0
  59. package/backend/dist/pipeline/account-selection.js +112 -0
  60. package/backend/dist/pipeline/orchestrator.js +34 -3
  61. package/backend/dist/providers/systemone.d.ts +29 -0
  62. package/backend/dist/providers/systemone.js +170 -0
  63. package/backend/dist/ratelimit/duration.d.ts +24 -0
  64. package/backend/dist/ratelimit/duration.js +43 -0
  65. package/backend/dist/ratelimit/governance-runtime.d.ts +121 -0
  66. package/backend/dist/ratelimit/governance-runtime.js +183 -0
  67. package/backend/dist/ratelimit/index.d.ts +4 -0
  68. package/backend/dist/ratelimit/index.js +4 -0
  69. package/backend/dist/ratelimit/limiter.d.ts +157 -0
  70. package/backend/dist/ratelimit/limiter.js +244 -0
  71. package/backend/dist/ratelimit/sliding-window-counter.d.ts +63 -0
  72. package/backend/dist/ratelimit/sliding-window-counter.js +103 -0
  73. package/backend/dist/ratelimit/subject.d.ts +26 -0
  74. package/backend/dist/ratelimit/subject.js +28 -0
  75. package/backend/dist/resilience/account-state.d.ts +84 -0
  76. package/backend/dist/resilience/account-state.js +228 -0
  77. package/backend/dist/router/layer1-classifier.d.ts +111 -0
  78. package/backend/dist/router/layer1-classifier.js +467 -0
  79. package/backend/dist/router/layer2-judge.d.ts +111 -0
  80. package/backend/dist/router/layer2-judge.js +373 -0
  81. package/backend/dist/router/retry-escalation.d.ts +89 -0
  82. package/backend/dist/router/retry-escalation.js +99 -0
  83. package/backend/dist/routes/flywheel.d.ts +3 -0
  84. package/backend/dist/routes/flywheel.js +268 -0
  85. package/backend/dist/routes/harness.js +4 -1
  86. package/backend/dist/routes/systemone.d.ts +3 -0
  87. package/backend/dist/routes/systemone.js +90 -0
  88. package/backend/dist/server.d.ts +0 -15
  89. package/backend/dist/server.js +40 -43
  90. package/backend/dist/session/session-manager.d.ts +15 -0
  91. package/backend/dist/session/session-manager.js +17 -0
  92. package/backend/dist/session/session-row.d.ts +78 -0
  93. package/backend/dist/session/session-row.js +52 -0
  94. package/backend/dist/surfaces/governance-envelope.d.ts +34 -0
  95. package/backend/dist/surfaces/governance-envelope.js +47 -0
  96. package/backend/dist/utils/token-estimator.d.ts +7 -0
  97. package/backend/dist/utils/token-estimator.js +20 -0
  98. package/bin/ocr.js +2 -2
  99. package/frontend/dist/assets/{index-DvXKvNxl.js → index-B7GKsUyU.js} +264 -244
  100. package/frontend/dist/assets/{index-1o7qI-KJ.css → index-DLKLOkQJ.css} +1 -1
  101. package/frontend/dist/index.html +2 -2
  102. package/package.json +1 -1
@@ -0,0 +1,268 @@
1
+ import { FlywheelDataset } from '../flywheel/dataset.js';
2
+ import { FlywheelTrainer } from '../flywheel/trainer.js';
3
+ import { deleteRecordsById, pruneDataset, resetDataset } from '../flywheel/prune.js';
4
+ import { FLYWHEEL_TIERS, isTier } from '../flywheel/schema.js';
5
+ import { getEnvRootDir } from '../config/env.js';
6
+ import { loadConfig, saveConfig } from '../config/index.js';
7
+ import path from 'node:path';
8
+ /**
9
+ * Flywheel console API — dataset inspection, operator relabelling, manual
10
+ * Layer 1 training and the dataset lifecycle operations (prune / batch
11
+ * delete / reset).
12
+ *
13
+ * The dataset is append-only under normal operation; the destructive POSTs
14
+ * below discard whole records through the shared rewrite engine
15
+ * (`flywheel/prune.ts`) under its documented backup policy (design doc D3),
16
+ * never by mutating history in place — corrections remain overlay-only via
17
+ * `setLabel`. Every successful rewrite calls `dataset.invalidate()` so the
18
+ * read side re-indexes before responding. The training guard lives in
19
+ * FlywheelTrainer (one run at a time) and is mirrored by a 409 here, so a
20
+ * second console tab cannot schedule a duplicate run — or a rewrite that
21
+ * races one. Auth: inherits the /api/admin webAuth gate unchanged.
22
+ */
23
+ const VALID_SOURCES = ['human', 'runtime_fallback', 'observed_execution', 'unlabeled'];
24
+ /** Batch-delete cap per call (§3.2): a re-click after partial failure is safe, a giant POST is not. */
25
+ const MAX_DELETE_IDS = 1000;
26
+ /** Lifecycle POST bodies are optional JSON objects; absent = endpoint defaults. */
27
+ function asObjectBody(body) {
28
+ if (body === undefined || body === null)
29
+ return {};
30
+ if (typeof body !== 'object' || Array.isArray(body))
31
+ return null;
32
+ return body;
33
+ }
34
+ export function registerFlywheelRoutes(app, orchestrator) {
35
+ const datasetPath = orchestrator.getFlywheel().getDatasetPath();
36
+ const dataset = new FlywheelDataset(datasetPath);
37
+ const modelPath = orchestrator.getClassifierConfig()?.localModel?.modelPath ||
38
+ path.resolve(getEnvRootDir(), 'models/layer1-classifier.json');
39
+ const trainer = new FlywheelTrainer(dataset, modelPath, orchestrator.getFlywheelConfig()?.maxSamples,
40
+ // Whether the router's confidence gate consumes trained weights. Mirrors
41
+ // the orchestrator's config snapshot: editing config.yaml alone does not
42
+ // flip this until a gateway restart, and the console must say so.
43
+ orchestrator.getClassifierConfig()?.localModel?.enabled === true);
44
+ // A pre-existing multi-hundred-MB dataset takes one cold pass to index; walk
45
+ // it down in slices so the first console visit doesn't pay for it all at once.
46
+ dataset.warmup();
47
+ app.get('/api/admin/flywheel/stats', async () => {
48
+ return {
49
+ ...dataset.summary(),
50
+ process: orchestrator.getFlywheel().getStats(),
51
+ tiers: FLYWHEEL_TIERS,
52
+ // Live collection gate — the page renders its toggle from this.
53
+ collectionEnabled: orchestrator.getFlywheel().isEnabled(),
54
+ // Additive block (§3.4): effective retention knobs + last sweep outcome.
55
+ retention: orchestrator.getFlywheel().getRetentionState(),
56
+ };
57
+ });
58
+ // Collection gate toggle — persists through saveConfig so every writer
59
+ // (console toggle, config editor, raw YAML) shares one hot-apply routine;
60
+ // the flip takes effect immediately, no restart. datasetPath and the
61
+ // retention knobs stay restart-scoped (collector construction).
62
+ app.post('/api/admin/flywheel/enabled', async (req, reply) => {
63
+ const body = asObjectBody(req.body);
64
+ if (!body)
65
+ return reply.status(400).send({ error: 'Body must be a JSON object' });
66
+ if (typeof body.enabled !== 'boolean') {
67
+ return reply.status(400).send({ error: '"enabled" must be a boolean' });
68
+ }
69
+ // Base the payload on the DISK-current section: saveConfig is a top-level
70
+ // shallow merge, so spreading the boot snapshot here would silently roll
71
+ // back datasetPath/knob edits an operator made via the raw YAML editor
72
+ // after boot. Re-read-before-spread, same pattern as the catalog routes.
73
+ const current = loadConfig().flywheel ?? {};
74
+ const outcome = saveConfig({
75
+ flywheel: { ...current, enabled: body.enabled },
76
+ });
77
+ if (!outcome.success)
78
+ return reply.status(500).send({ error: outcome.error });
79
+ return { ok: true, collectionEnabled: orchestrator.getFlywheel().isEnabled() };
80
+ });
81
+ app.get('/api/admin/flywheel/samples', async (req) => {
82
+ const q = req.query;
83
+ const tierParam = typeof q.tier === 'string' ? q.tier : undefined;
84
+ const tier = isTier(tierParam)
85
+ ? tierParam
86
+ : tierParam === 'none'
87
+ ? 'none'
88
+ : 'any';
89
+ const sourceParam = typeof q.source === 'string' ? q.source : undefined;
90
+ const source = VALID_SOURCES.includes(sourceParam)
91
+ ? sourceParam
92
+ : 'any';
93
+ const result = dataset.query({
94
+ limit: q.limit !== undefined ? Number(q.limit) : undefined,
95
+ offset: q.offset !== undefined ? Number(q.offset) : undefined,
96
+ tier,
97
+ source,
98
+ includeSynthetic: q.includeSynthetic === 'true' || q.includeSynthetic === true,
99
+ trainableOnly: q.trainableOnly === 'true' || q.trainableOnly === true,
100
+ search: typeof q.search === 'string' && q.search.trim() ? q.search.trim() : undefined,
101
+ });
102
+ return { ...result, tiers: FLYWHEEL_TIERS };
103
+ });
104
+ // Operator relabelling. `{ "tier": "pro" }` sets a human label,
105
+ // `{ "tier": null }` clears it back to the observed label.
106
+ app.patch('/api/admin/flywheel/samples/:id', async (req, reply) => {
107
+ const { id } = req.params;
108
+ const body = (req.body || {});
109
+ if (!(body.tier === null || isTier(body.tier))) {
110
+ return reply.status(400).send({ error: `tier must be null or one of: ${FLYWHEEL_TIERS.join(', ')}` });
111
+ }
112
+ if (trainer.isTraining()) {
113
+ return reply.status(409).send({ error: 'A training run is in progress; relabelling is paused.' });
114
+ }
115
+ try {
116
+ const label = dataset.setLabel(id, body.tier === null ? null : body.tier);
117
+ if (!label)
118
+ return reply.status(404).send({ error: `Unknown sample id: ${id}` });
119
+ return { ok: true, label };
120
+ }
121
+ catch (err) {
122
+ return reply.status(400).send({ error: err?.message || String(err) });
123
+ }
124
+ });
125
+ app.delete('/api/admin/flywheel/labels', async () => {
126
+ const cleared = dataset.clearOverrides();
127
+ return { ok: true, cleared };
128
+ });
129
+ // ---- dataset lifecycle: prune / batch delete / reset (§3, frozen contract) ----
130
+ // All three share: JSON-object body (absent = defaults), 409 while training,
131
+ // engine-side atomic tmp+rename rewrites, dataset.invalidate() after a real
132
+ // rewrite, and labels-overlay orphan purge inside the engine (D9).
133
+ // Dry-run default like the CLI: preview performs zero writes; apply rewrites
134
+ // with a full `.bak-<ts>` backup, rotation keeps the newest 3.
135
+ app.post('/api/admin/flywheel/prune', async (req, reply) => {
136
+ const body = asObjectBody(req.body);
137
+ if (!body)
138
+ return reply.status(400).send({ error: 'Body must be a JSON object' });
139
+ const boolField = ['apply', 'dropSynthetic', 'dropDuplicates'].find((k) => body[k] !== undefined && typeof body[k] !== 'boolean');
140
+ if (boolField)
141
+ return reply.status(400).send({ error: `"${boolField}" must be a boolean` });
142
+ if (trainer.isTraining()) {
143
+ return reply.status(409).send({ error: 'A training run is in progress; pruning is paused.' });
144
+ }
145
+ const opts = {
146
+ dropSynthetic: body.dropSynthetic !== false,
147
+ dropDuplicates: body.dropDuplicates !== false,
148
+ };
149
+ try {
150
+ const outcome = pruneDataset(datasetPath, opts, body.apply === true);
151
+ if (!outcome)
152
+ return reply.status(404).send({ error: `No dataset file at ${datasetPath}` });
153
+ if (outcome.applied)
154
+ dataset.invalidate();
155
+ return {
156
+ ok: true,
157
+ applied: outcome.applied,
158
+ total: outcome.total,
159
+ kept: outcome.kept,
160
+ dropped: outcome.dropped,
161
+ removedLabels: outcome.removedLabels,
162
+ backupPath: outcome.backupPath,
163
+ };
164
+ }
165
+ catch (err) {
166
+ return reply.status(400).send({ error: err?.message || String(err) });
167
+ }
168
+ });
169
+ // Partial-success + idempotent (§3.2): unknown ids are reported, never an
170
+ // error; a re-click after a partial failure is safe. Removed lines land
171
+ // verbatim in the `.deleted.jsonl` sidecar (D3).
172
+ app.post('/api/admin/flywheel/samples/delete', async (req, reply) => {
173
+ const body = asObjectBody(req.body);
174
+ if (!body)
175
+ return reply.status(400).send({ error: 'Body must be a JSON object' });
176
+ const ids = body.ids;
177
+ if (!Array.isArray(ids) ||
178
+ ids.length === 0 ||
179
+ ids.length > MAX_DELETE_IDS ||
180
+ ids.some((id) => typeof id !== 'string' || id === '')) {
181
+ return reply.status(400).send({ error: `ids must be an array of 1-${MAX_DELETE_IDS} non-empty strings` });
182
+ }
183
+ if (trainer.isTraining()) {
184
+ return reply.status(409).send({ error: 'A training run is in progress; deletion is paused.' });
185
+ }
186
+ try {
187
+ const outcome = deleteRecordsById(datasetPath, ids);
188
+ if (outcome.rewrote)
189
+ dataset.invalidate();
190
+ return {
191
+ ok: true,
192
+ deleted: outcome.deleted,
193
+ notFound: outcome.notFound,
194
+ removedLabels: outcome.removedLabels,
195
+ sidecarPath: outcome.sidecarPath,
196
+ };
197
+ }
198
+ catch (err) {
199
+ return reply.status(400).send({ error: err?.message || String(err) });
200
+ }
201
+ });
202
+ // Typed confirmation guards RESET only (D6) — the engine clears the dataset
203
+ // AND the labels overlay (both archived) and NEVER touches the trained model
204
+ // files; `modelUntouched: true` is a contract promise, not just a fact (D8).
205
+ app.post('/api/admin/flywheel/reset', async (req, reply) => {
206
+ const body = asObjectBody(req.body);
207
+ if (!body)
208
+ return reply.status(400).send({ error: 'Body must be a JSON object' });
209
+ if (body.confirm !== 'RESET') {
210
+ return reply
211
+ .status(400)
212
+ .send({ error: 'Body must include { "confirm": "RESET" } (exact, case-sensitive).' });
213
+ }
214
+ if (trainer.isTraining()) {
215
+ return reply.status(409).send({ error: 'A training run is in progress; reset is paused.' });
216
+ }
217
+ try {
218
+ const outcome = resetDataset(datasetPath);
219
+ if (outcome.datasetRewrote || outcome.labelsBackupPath)
220
+ dataset.invalidate();
221
+ return {
222
+ ok: true,
223
+ removedRecords: outcome.removedRecords,
224
+ removedLabels: outcome.removedLabels,
225
+ backupPath: outcome.backupPath,
226
+ labelsBackupPath: outcome.labelsBackupPath,
227
+ modelUntouched: true,
228
+ };
229
+ }
230
+ catch (err) {
231
+ return reply.status(400).send({ error: err?.message || String(err) });
232
+ }
233
+ });
234
+ app.get('/api/admin/flywheel/training', async () => {
235
+ return { ...trainer.getState(), model: trainer.modelInfo() };
236
+ });
237
+ // Restore the weights this model had before the last training run.
238
+ app.post('/api/admin/flywheel/model/rollback', async (_req, reply) => {
239
+ if (trainer.isTraining()) {
240
+ return reply.status(409).send({ error: 'A training run is in progress; rollback is paused.' });
241
+ }
242
+ if (!trainer.rollback()) {
243
+ return reply.status(404).send({ error: 'No pre-training backup exists — nothing to roll back to.' });
244
+ }
245
+ return { ok: true, model: trainer.modelInfo() };
246
+ });
247
+ app.post('/api/admin/flywheel/training', async (req, reply) => {
248
+ if (trainer.isTraining()) {
249
+ return reply.status(409).send({ error: 'A training run is already in progress.', state: trainer.getState() });
250
+ }
251
+ const body = (req.body || {});
252
+ const outcome = await trainer.train({
253
+ epochs: typeof body.epochs === 'number' ? body.epochs : undefined,
254
+ lr: typeof body.lr === 'number' ? body.lr : undefined,
255
+ l2: typeof body.l2 === 'number' ? body.l2 : undefined,
256
+ maxSamples: typeof body.maxSamples === 'number' ? body.maxSamples : undefined,
257
+ balanceClasses: body.balanceClasses === true,
258
+ includeSynthetic: body.includeSynthetic === true,
259
+ minLabelSource: body.minLabelSource === 'human' || body.minLabelSource === 'runtime_fallback'
260
+ ? body.minLabelSource
261
+ : undefined,
262
+ });
263
+ if (outcome.error) {
264
+ return reply.status(400).send({ error: outcome.error, state: outcome.state });
265
+ }
266
+ return outcome;
267
+ });
268
+ }
@@ -1,5 +1,5 @@
1
1
  import { HOSTS } from '../harness/hosts.js';
2
- import { adapterFor, isExtensionHost, isMcpHost, isSkillsHost, skillOwner, skillRootsFor, } from '../harness/adapters/index.js';
2
+ import { adapterFor, hostDetected, isExtensionHost, isMcpHost, isSkillsHost, skillOwner, skillRootsFor, } from '../harness/adapters/index.js';
3
3
  import { scanInventory } from '../harness/inventory.js';
4
4
  import { claimsPath, manifestPath } from '../harness/manifest.js';
5
5
  import { applyRemove, planRemove } from '../harness/maintenance.js';
@@ -256,6 +256,9 @@ export function registerHarnessRoutes(app) {
256
256
  return {
257
257
  id: host.id,
258
258
  label: host.label,
259
+ /** Present on this machine (executable, config dir, or an existing skills root). The
260
+ * console rail hides undetected hosts — but never one whose rows are already landed. */
261
+ detected: hostDetected(adapterFor(host.id)),
259
262
  hasSkills: isSkillsHost(adapterFor(host.id)),
260
263
  /** MCP-capable host: its adapter implements the MCP landing capability. */
261
264
  hasMcp: isMcpHost(adapterFor(host.id)),
@@ -0,0 +1,3 @@
1
+ import { FastifyInstance } from 'fastify';
2
+ import { PipelineOrchestrator } from '../pipeline/orchestrator.js';
3
+ export declare function registerSystemoneRoutes(app: FastifyInstance, orchestrator: PipelineOrchestrator): void;
@@ -0,0 +1,90 @@
1
+ import { loadConfig } from '../config/index.js';
2
+ import { runSystemoneDecision } from '../protocols/systemone/decide.js';
3
+ import { validateSystemoneRequest } from '../protocols/systemone/convert.js';
4
+ import { makeModelAccessGuard } from '../auth/model-access.js';
5
+ import { UpstreamError } from '../resilience/error-classifier.js';
6
+ /**
7
+ * System One protocol compatibility surface (POST /v1/systemone).
8
+ *
9
+ * A thin HTTP shell over the shared decision executor
10
+ * (protocols/systemone/decide.ts) — the same one the Layer 2 router judge
11
+ * uses. This route owns ONLY the wire concerns: structural validation,
12
+ * model resolution, per-key model access, status mapping and response
13
+ * headers. Upstream dispatch (native passthrough vs chat conversion, the
14
+ * reasoning-effort calibration) lives in the shared executor.
15
+ *
16
+ * Stateless decision surface: the named model is the model served — no tier
17
+ * cascade, session ratchet or combo resolution. Auth and
18
+ * per-key model-access policies apply exactly like the other /v1 surfaces.
19
+ */
20
+ function errorStatus(err) {
21
+ if (Number.isInteger(err?.statusCode) && err.statusCode >= 400 && err.statusCode < 600)
22
+ return err.statusCode;
23
+ if (err instanceof UpstreamError && Number.isInteger(err.status) && err.status >= 400 && err.status < 600) {
24
+ return err.status;
25
+ }
26
+ return 502;
27
+ }
28
+ export function registerSystemoneRoutes(app, orchestrator) {
29
+ app.post('/v1/systemone', async (req, reply) => {
30
+ const verdict = validateSystemoneRequest(req.body);
31
+ if (!verdict.ok) {
32
+ return reply.status(400).send({
33
+ error: { message: verdict.message, type: 'invalid_request_error', code: 'invalid_request_error' },
34
+ });
35
+ }
36
+ const body = verdict.value;
37
+ const registry = orchestrator.getRegistry();
38
+ const rawModel = typeof body.model === 'string' ? body.model.trim() : '';
39
+ const effective = rawModel && rawModel !== 'auto' && rawModel !== 'default'
40
+ ? rawModel
41
+ : (loadConfig().systemone?.defaultModel || '').trim();
42
+ if (!effective) {
43
+ return reply.status(400).send({
44
+ error: {
45
+ message: 'Invalid request: "model" is required (or configure systemone.defaultModel).',
46
+ type: 'invalid_request_error',
47
+ code: 'model_required',
48
+ },
49
+ });
50
+ }
51
+ // Per-key model access gate (403 when the key's policy denies this model).
52
+ // The PHYSICAL model that will actually serve must always be admitted:
53
+ // 'auto'/'default' resolve to `systemone.defaultModel`, so checking only
54
+ // the alias would let a key denied for that model reach it via `auto`.
55
+ // A named alias is additionally checked as itself — mirroring the chat
56
+ // surfaces, where an allow-mode key must name `auto` explicitly.
57
+ const enforceModelAccess = makeModelAccessGuard(registry);
58
+ if (rawModel && rawModel !== effective && !enforceModelAccess(req, reply, rawModel)) {
59
+ return reply;
60
+ }
61
+ if (!enforceModelAccess(req, reply, effective)) {
62
+ return reply;
63
+ }
64
+ const model = registry.getModel(effective);
65
+ if (!model) {
66
+ return reply.status(404).send({
67
+ error: { message: `Model '${effective}' not found.`, type: 'invalid_request_error', code: 'model_not_found' },
68
+ });
69
+ }
70
+ const startedAt = Date.now();
71
+ try {
72
+ const decision = await runSystemoneDecision(registry, body, model);
73
+ reply.header('X-OCR-Model', model.id);
74
+ reply.header('X-OCR-Systemone-Upstream', decision.upstreamKind);
75
+ reply.header('X-OCR-Latency-MS', (Date.now() - startedAt).toString());
76
+ return reply.send(decision.response);
77
+ }
78
+ catch (err) {
79
+ req.log.error(err, 'System One request failed');
80
+ const status = errorStatus(err);
81
+ return reply.status(status).send({
82
+ error: {
83
+ message: err?.message || 'System One upstream failure',
84
+ type: status >= 500 ? 'api_error' : 'invalid_request_error',
85
+ code: err?.systemoneCode || (err instanceof UpstreamError ? 'upstream_error' : 'api_error'),
86
+ },
87
+ });
88
+ }
89
+ });
90
+ }
@@ -3,21 +3,6 @@ import { RouterConfig, ProviderConfig } from './config/types.js';
3
3
  import { PipelineOrchestrator } from './pipeline/orchestrator.js';
4
4
  import { ProviderRegistry } from './providers/registry.js';
5
5
  import { FinOpsTracker } from './metrics/finops-tracker.js';
6
- import { type ExecutionTrace } from './trace/tracker.js';
7
- /**
8
- * How the client addressed a session's turns, derived from persisted traces
9
- * (observability reconstruction — never routing state):
10
- * - 'auto' : every turn named an auto alias (bare auto or a tier-forced
11
- * lite/plus/pro/ultra) — the ratchet owns the tier.
12
- * - 'explicit': every turn named a concrete registered model — the client owns
13
- * the choice, the tier column has no lock to show.
14
- * - 'combo' : every turn went through a combo — the composition IS the
15
- * decision; the executed member's tier is not a session ceiling.
16
- * - 'mixed' : the conversation switched entry modes across turns.
17
- */
18
- export type SessionEntryMode = 'auto' | 'explicit' | 'combo' | 'mixed';
19
- /** Classify a session from its traces (chronological order irrelevant). */
20
- export declare function deriveSessionEntryMode(traces: ExecutionTrace[]): SessionEntryMode;
21
6
  /**
22
7
  * Router-canonical PATH for every gate in the preHandler below. find-my-way
23
8
  * decodeURI's the request target ONCE (path portion only — it splits on the
@@ -19,42 +19,15 @@ import { APP_VERSION } from './version.js';
19
19
  import { setGatewayMetaDeps } from './cli/clients/model-meta.js';
20
20
  import { comboEnvelope, findMemberCatalogRecords, modelsDevBlock, tierAliasEnvelope, virtualModelsDevBlock, } from './providers/virtual-meta.js';
21
21
  import { modelSupportsEfforts } from './types/router.js';
22
+ import { isInternalSessionId } from './session/session-manager.js';
23
+ import { currentModelOf, deriveSessionEntryMode, projectSessionEntity, } from './session/session-row.js';
22
24
  const TIER_RANK = { lite: 1, plus: 2, pro: 3, ultra: 4 };
23
- /** Classify a session from its traces (chronological order irrelevant). */
24
- export function deriveSessionEntryMode(traces) {
25
- // Virtual auto aliases: bare auto plus the four tier-forced aliases
26
- // (lite/plus/pro/ultra). Routing runs these through the ratchet path (the
27
- // tier aliases rewrite force_tier before routing), so a tier-forced session
28
- // owns a tier lock — classifying it as explicit would strip the tier badge.
29
- const AUTO_ALIAS_MODELS = new Set(['auto', 'lite', 'plus', 'pro', 'ultra']);
30
- let sawAuto = false;
31
- let sawExplicit = false;
32
- let sawCombo = false;
33
- for (const t of traces) {
34
- // Combo turns are the only ones carrying this reasonCode (the orchestrator
35
- // sets it on the bypass decision and the trace copies it verbatim).
36
- if (t.routing?.reasonCode === 'combo')
37
- sawCombo = true;
38
- else {
39
- // Routing-name matching trims once while request.model is stored
40
- // verbatim (surface contract) — reconstruct the routing view, not the
41
- // bytes: a padded alias routed as the alias must classify as the alias.
42
- const requested = (t.request?.model ?? '').trim();
43
- if (!requested || AUTO_ALIAS_MODELS.has(requested))
44
- sawAuto = true;
45
- else
46
- sawExplicit = true;
47
- }
48
- }
49
- if (Number(sawAuto) + Number(sawExplicit) + Number(sawCombo) !== 1)
50
- return 'mixed';
51
- return sawCombo ? 'combo' : sawExplicit ? 'explicit' : 'auto';
52
- }
53
25
  /**
54
26
  * Rebuild a console session row from persisted traces alone (seen after a
55
27
  * gateway restart, when the live session-manager state is gone but the trace
56
28
  * store survived). Derived values are observability reconstructions — the
57
- * routing state itself (pin/ratchet) starts fresh by design.
29
+ * routing state itself (pin/ratchet) starts fresh by design, so the row is the
30
+ * execution view (`currentModel`), never a fabricated pin (ADR-0002 §3).
58
31
  */
59
32
  function reconstructSessionFromTraces(traceTracker, id) {
60
33
  const traces = traceTracker.getTracesBySession(id);
@@ -65,10 +38,12 @@ function reconstructSessionFromTraces(traceTracker, id) {
65
38
  const uaList = distinctTraceUserAgents(traces);
66
39
  return {
67
40
  id,
41
+ // The id IS the marker (see isInternalSessionId) — traces key on it, so
42
+ // this survives restarts on the reconstruction path exactly like live.
43
+ internal: isInternalSessionId(id),
68
44
  maxTier,
69
45
  entryMode: deriveSessionEntryMode(traces),
70
- pinnedModel: last?.execution.modelUsed ?? '',
71
- pinnedProvider: last?.execution.provider ?? '',
46
+ ...currentModelOf(traces),
72
47
  createdAt: first?.timestamp ?? 0,
73
48
  lastActiveAt: last?.timestamp ?? 0,
74
49
  turnCount: traces.length,
@@ -962,17 +937,29 @@ providerConfigs = []) {
962
937
  // Per-application selector (same semantics as the capture sessions route):
963
938
  // exact client API-key id OR case-insensitive name substring.
964
939
  const ak = firstStr(query.apiKey).trim();
940
+ // Internal (gateway-loopback) rows: hidden unless the caller asks for
941
+ // them. Filtered BEFORE pagination so `total` stays truthful.
942
+ const hideInternal = firstStr(query.hideInternal) !== '0';
965
943
  const traceTracker = orchestrator.getTraceTracker();
966
- // Live sessions carry the authoritative routing state (pin/ratchet);
967
- // sessions that only exist in the persisted trace store (e.g. after a
968
- // gateway restart) are reconstructed from their traces so console
969
- // history survives. Live wins on id collision.
970
- const live = (orchestrator.getSessionManager()?.getAllSessions() || []).map(s => {
944
+ // Live sessions (entity + traces) and sessions that exist only in the
945
+ // persisted trace store (e.g. after a gateway restart) are reconstructed
946
+ // so console history survives. Live wins on id collision. Both paths
947
+ // project into the same SessionRow contract (session-row.ts), so a row
948
+ // never carries the live routing state (pin/ratchet).
949
+ const live = (orchestrator.getSessionManager()?.getAllSessions() || []).map((s) => {
971
950
  const sessTraces = traceTracker.getTracesBySession(s.id);
972
951
  const keyList = distinctTraceKeys(sessTraces);
973
952
  const uaList = distinctTraceUserAgents(sessTraces);
974
953
  return {
975
- ...s,
954
+ // Whitelisted entity projection (session-row.ts): the entity's
955
+ // pinnedModel/pinnedProvider are routing-internal (ADR-0002) and are
956
+ // deliberately NOT surfaced, so live and trace-reconstructed rows
957
+ // report the same execution view instead of an anchor.
958
+ ...projectSessionEntity(s),
959
+ ...currentModelOf(sessTraces),
960
+ // The id IS the internal marker (reserved `ocr-internal:` prefix) —
961
+ // derived, never stored, so live and trace-reconstructed rows agree.
962
+ internal: isInternalSessionId(s.id),
976
963
  // Application attribution from the session's traces — distinct key set
977
964
  // in write order (first element = display anchor).
978
965
  apiKeys: keyList.length ? keyList : undefined,
@@ -990,17 +977,23 @@ providerConfigs = []) {
990
977
  .filter(id => !liveIds.has(id))
991
978
  .map(id => reconstructSessionFromTraces(traceTracker, id));
992
979
  // Most recently active first — stable ordering for pagination. `q`
993
- // filters (case-insensitive substring) across session id, pinned model,
994
- // first user message and every app name, applied BEFORE pagination.
980
+ // filters (case-insensitive substring) across session id, current model AND
981
+ // its provider (both are rendered in that column), first user message and
982
+ // every app name, applied BEFORE pagination.
995
983
  // `apiKey` (ak) selects by membership in the session's distinct key set.
996
984
  const all = [...live, ...reconstructed]
997
985
  .filter(s => {
986
+ if (hideInternal && s.internal)
987
+ return false;
998
988
  const keys = s.apiKeys ?? [];
999
989
  if (ak && !keys.some(k => k.id === ak || k.name.toLowerCase().includes(ak.toLowerCase())))
1000
990
  return false;
1001
991
  return (!q ||
1002
992
  s.id.toLowerCase().includes(q) ||
1003
- String(s.pinnedModel || '')
993
+ String(s.currentModel || '')
994
+ .toLowerCase()
995
+ .includes(q) ||
996
+ String(s.currentProvider || '')
1004
997
  .toLowerCase()
1005
998
  .includes(q) ||
1006
999
  String(s.firstUserMessage || '')
@@ -1033,7 +1026,11 @@ providerConfigs = []) {
1033
1026
  const traces = orchestrator.getTraceTracker().getTracesBySession(id);
1034
1027
  return {
1035
1028
  object: 'session',
1036
- ...session,
1029
+ // Same two projections as the list rows (ADR-0002 §3): the routing pin
1030
+ // and the client IP stay inside the gateway, and `currentModel` reuses the
1031
+ // list's execution-view derivation so the endpoints cannot disagree.
1032
+ ...projectSessionEntity(session),
1033
+ ...currentModelOf(traces),
1037
1034
  traceCount: traces.length,
1038
1035
  recentTraces: traces.slice(-5),
1039
1036
  };
@@ -1,6 +1,21 @@
1
1
  import { ChatCompletionRequest } from '../types/openai.js';
2
2
  import { RoutingDecision, SessionLookupType, TierLevel, TierModelConfig } from '../types/router.js';
3
3
  import { SessionConfig } from '../config/types.js';
4
+ /**
5
+ * RESERVED session-id namespace for the gateway's OWN loopback calls
6
+ * (console description/README translation, translation-chain probe). The
7
+ * gateway pins a fixed per-purpose id (`ocr-internal:translation`, …) via
8
+ * `router_options.session_id` so internal calls share one session instead of
9
+ * minting a fresh `cold_start` session per call. The marker IS the id, so it
10
+ * survives restarts: persisted traces key on sessionId and the admin
11
+ * sessions endpoint re-derives `internal` from the prefix on BOTH live and
12
+ * reconstructed rows. External clients must not use this prefix — it is a
13
+ * claim of "this row is gateway-internal noise", honored by the admin
14
+ * filter, not an enforced restriction (see ADR-0015).
15
+ */
16
+ export declare const INTERNAL_SESSION_PREFIX = "ocr-internal:";
17
+ /** Gateway-internal loopback session rows are hidden from the console by default. */
18
+ export declare function isInternalSessionId(id: string): boolean;
4
19
  export interface ConversationSession {
5
20
  id: string;
6
21
  maxTier: TierLevel;
@@ -3,6 +3,23 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { TIER_RANK } from '../types/router.js';
5
5
  import { renameWithRetry } from '../utils/atomic-write.js';
6
+ /**
7
+ * RESERVED session-id namespace for the gateway's OWN loopback calls
8
+ * (console description/README translation, translation-chain probe). The
9
+ * gateway pins a fixed per-purpose id (`ocr-internal:translation`, …) via
10
+ * `router_options.session_id` so internal calls share one session instead of
11
+ * minting a fresh `cold_start` session per call. The marker IS the id, so it
12
+ * survives restarts: persisted traces key on sessionId and the admin
13
+ * sessions endpoint re-derives `internal` from the prefix on BOTH live and
14
+ * reconstructed rows. External clients must not use this prefix — it is a
15
+ * claim of "this row is gateway-internal noise", honored by the admin
16
+ * filter, not an enforced restriction (see ADR-0015).
17
+ */
18
+ export const INTERNAL_SESSION_PREFIX = 'ocr-internal:';
19
+ /** Gateway-internal loopback session rows are hidden from the console by default. */
20
+ export function isInternalSessionId(id) {
21
+ return id.startsWith(INTERNAL_SESSION_PREFIX);
22
+ }
6
23
  // Memory/safety bounds — intentionally NOT config-exposed: they tune memory,
7
24
  // not product behavior.
8
25
  const TAIL_WINDOW = 8; // messages per registered tail window