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.
- package/RELEASING.md +238 -238
- package/RELEASING.zh-CN.md +230 -230
- package/backend/dist/capture/recorder.js +2 -1
- package/backend/dist/cli/clients/base.js +8 -16
- package/backend/dist/cli/clients/dsh.js +8 -16
- package/backend/dist/cli/clients/pi.js +16 -9
- package/backend/dist/cli/types.d.ts +5 -0
- package/backend/dist/config/env.js +2 -1
- package/backend/dist/config/index.js +2 -0
- package/backend/dist/config/types.d.ts +23 -0
- package/backend/dist/harness/adapters/amp.d.ts +2 -0
- package/backend/dist/harness/adapters/amp.js +7 -0
- package/backend/dist/harness/adapters/claude.d.ts +2 -0
- package/backend/dist/harness/adapters/claude.js +7 -0
- package/backend/dist/harness/adapters/cline.d.ts +2 -0
- package/backend/dist/harness/adapters/cline.js +6 -0
- package/backend/dist/harness/adapters/codex.d.ts +2 -0
- package/backend/dist/harness/adapters/codex.js +6 -0
- package/backend/dist/harness/adapters/cursor.d.ts +5 -0
- package/backend/dist/harness/adapters/cursor.js +10 -0
- package/backend/dist/harness/adapters/declarative.d.ts +62 -0
- package/backend/dist/harness/adapters/declarative.js +202 -0
- package/backend/dist/harness/adapters/dsh.d.ts +5 -0
- package/backend/dist/harness/adapters/dsh.js +6 -0
- package/backend/dist/harness/adapters/gemini-cli.d.ts +2 -0
- package/backend/dist/harness/adapters/gemini-cli.js +7 -0
- package/backend/dist/harness/adapters/github-copilot.d.ts +5 -0
- package/backend/dist/harness/adapters/github-copilot.js +10 -0
- package/backend/dist/harness/adapters/index.d.ts +44 -0
- package/backend/dist/harness/adapters/index.js +99 -0
- package/backend/dist/harness/adapters/opencode.d.ts +2 -0
- package/backend/dist/harness/adapters/opencode.js +55 -0
- package/backend/dist/harness/adapters/pi.d.ts +1 -0
- package/backend/dist/harness/adapters/pi.js +22 -0
- package/backend/dist/harness/adapters/skills-paths.d.ts +15 -0
- package/backend/dist/harness/adapters/skills-paths.js +17 -0
- package/backend/dist/harness/adapters/types.d.ts +174 -0
- package/backend/dist/harness/adapters/types.js +12 -0
- package/backend/dist/harness/adapters/universal.d.ts +6 -0
- package/backend/dist/harness/adapters/universal.js +10 -0
- package/backend/dist/harness/adapters/windsurf.d.ts +2 -0
- package/backend/dist/harness/adapters/windsurf.js +10 -0
- package/backend/dist/harness/adapters/zed.d.ts +2 -0
- package/backend/dist/harness/adapters/zed.js +6 -0
- package/backend/dist/harness/awesome-opencode.d.ts +40 -0
- package/backend/dist/harness/awesome-opencode.js +75 -0
- package/backend/dist/harness/browse.d.ts +202 -0
- package/backend/dist/harness/browse.js +1214 -0
- package/backend/dist/harness/catalog-npm.d.ts +59 -0
- package/backend/dist/harness/catalog-npm.js +145 -0
- package/backend/dist/harness/clawhub.d.ts +212 -0
- package/backend/dist/harness/clawhub.js +426 -0
- package/backend/dist/harness/config-file.d.ts +29 -0
- package/backend/dist/harness/config-file.js +35 -0
- package/backend/dist/harness/detail.d.ts +74 -0
- package/backend/dist/harness/detail.js +330 -0
- package/backend/dist/harness/discover.d.ts +118 -0
- package/backend/dist/harness/discover.js +507 -0
- package/backend/dist/harness/drift.d.ts +21 -0
- package/backend/dist/harness/drift.js +25 -0
- package/backend/dist/harness/hash.d.ts +10 -0
- package/backend/dist/harness/hash.js +63 -0
- package/backend/dist/harness/hosts.d.ts +18 -0
- package/backend/dist/harness/hosts.js +15 -0
- package/backend/dist/harness/install.d.ts +88 -0
- package/backend/dist/harness/install.js +301 -0
- package/backend/dist/harness/inventory.d.ts +10 -0
- package/backend/dist/harness/inventory.js +198 -0
- package/backend/dist/harness/ledger.d.ts +39 -0
- package/backend/dist/harness/ledger.js +83 -0
- package/backend/dist/harness/maintenance.d.ts +115 -0
- package/backend/dist/harness/maintenance.js +603 -0
- package/backend/dist/harness/manifest.d.ts +31 -0
- package/backend/dist/harness/manifest.js +234 -0
- package/backend/dist/harness/net.d.ts +86 -0
- package/backend/dist/harness/net.js +113 -0
- package/backend/dist/harness/opencode-cafe.d.ts +40 -0
- package/backend/dist/harness/opencode-cafe.js +85 -0
- package/backend/dist/harness/opencode-ecosystem.d.ts +34 -0
- package/backend/dist/harness/opencode-ecosystem.js +246 -0
- package/backend/dist/harness/pi-dev.d.ts +81 -0
- package/backend/dist/harness/pi-dev.js +187 -0
- package/backend/dist/harness/probe.d.ts +33 -0
- package/backend/dist/harness/probe.js +85 -0
- package/backend/dist/harness/registry.d.ts +2 -0
- package/backend/dist/harness/registry.js +26 -0
- package/backend/dist/harness/scopes.d.ts +21 -0
- package/backend/dist/harness/scopes.js +22 -0
- package/backend/dist/harness/skill-md.d.ts +18 -0
- package/backend/dist/harness/skill-md.js +71 -0
- package/backend/dist/harness/skills-sh.d.ts +109 -0
- package/backend/dist/harness/skills-sh.js +178 -0
- package/backend/dist/harness/smithery.d.ts +64 -0
- package/backend/dist/harness/smithery.js +146 -0
- package/backend/dist/harness/sources/awesome-opencode.d.ts +11 -0
- package/backend/dist/harness/sources/awesome-opencode.js +39 -0
- package/backend/dist/harness/sources/clawhub.d.ts +2 -0
- package/backend/dist/harness/sources/clawhub.js +83 -0
- package/backend/dist/harness/sources/github.d.ts +9 -0
- package/backend/dist/harness/sources/github.js +202 -0
- package/backend/dist/harness/sources/mcp-official.d.ts +2 -0
- package/backend/dist/harness/sources/mcp-official.js +110 -0
- package/backend/dist/harness/sources/npm.d.ts +2 -0
- package/backend/dist/harness/sources/npm.js +152 -0
- package/backend/dist/harness/sources/opencode-cafe.d.ts +11 -0
- package/backend/dist/harness/sources/opencode-cafe.js +41 -0
- package/backend/dist/harness/sources/smithery.d.ts +2 -0
- package/backend/dist/harness/sources/smithery.js +81 -0
- package/backend/dist/harness/spi.d.ts +98 -0
- package/backend/dist/harness/spi.js +8 -0
- package/backend/dist/harness/stars.d.ts +70 -0
- package/backend/dist/harness/stars.js +202 -0
- package/backend/dist/harness/translation.d.ts +142 -0
- package/backend/dist/harness/translation.js +567 -0
- package/backend/dist/harness/tree.d.ts +13 -0
- package/backend/dist/harness/tree.js +19 -0
- package/backend/dist/harness/types.d.ts +286 -0
- package/backend/dist/harness/types.js +8 -0
- package/backend/dist/harness/writers/extension.d.ts +116 -0
- package/backend/dist/harness/writers/extension.js +219 -0
- package/backend/dist/harness/writers/mcp.d.ts +72 -0
- package/backend/dist/harness/writers/mcp.js +195 -0
- package/backend/dist/harness/writers/skill.d.ts +60 -0
- package/backend/dist/harness/writers/skill.js +146 -0
- package/backend/dist/opencode/agents.d.ts +5 -0
- package/backend/dist/opencode/agents.js +10 -1
- package/backend/dist/opencode/catalog/cache.js +2 -1
- package/backend/dist/opencode/catalog/logos.js +2 -1
- package/backend/dist/opencode/catalog/ocr-store.js +2 -1
- package/backend/dist/opencode/catalog/overrides-store.js +2 -1
- package/backend/dist/opencode/credentials/factory.js +10 -27
- package/backend/dist/opencode/credentials/ocr-store.js +2 -1
- package/backend/dist/opencode/provider-defs.js +2 -1
- package/backend/dist/opencode/user-config.js +8 -16
- package/backend/dist/providers/registry.d.ts +15 -4
- package/backend/dist/providers/registry.js +29 -5
- package/backend/dist/providers/virtual-meta.d.ts +13 -0
- package/backend/dist/providers/virtual-meta.js +18 -0
- package/backend/dist/quota/store.js +2 -1
- package/backend/dist/resilience/breaker-state.js +2 -1
- package/backend/dist/resilience/credential-state.js +2 -1
- package/backend/dist/routes/console.js +137 -15
- package/backend/dist/routes/harness.d.ts +2 -0
- package/backend/dist/routes/harness.js +622 -0
- package/backend/dist/server.js +4 -0
- package/backend/dist/session/session-manager.js +2 -1
- package/backend/dist/surfaces/systemone-probe.d.ts +25 -0
- package/backend/dist/surfaces/systemone-probe.js +74 -0
- package/backend/dist/utils/atomic-write.d.ts +12 -0
- package/backend/dist/utils/atomic-write.js +29 -0
- package/bin/ocr.js +2 -2
- package/frontend/dist/assets/{index-DEo2iAT7.css → index-1o7qI-KJ.css} +1 -1
- package/frontend/dist/assets/index-DvXKvNxl.js +962 -0
- package/frontend/dist/index.html +2 -2
- package/package.json +87 -87
- package/backend/dist/budget/budget-manager.d.ts +0 -25
- package/backend/dist/budget/budget-manager.js +0 -54
- package/backend/dist/config/governance-limits.d.ts +0 -68
- package/backend/dist/config/governance-limits.js +0 -261
- package/backend/dist/flywheel/collector.d.ts +0 -74
- package/backend/dist/flywheel/collector.js +0 -235
- package/backend/dist/flywheel/dataset.d.ts +0 -130
- package/backend/dist/flywheel/dataset.js +0 -638
- package/backend/dist/flywheel/decision-capture.d.ts +0 -68
- package/backend/dist/flywheel/decision-capture.js +0 -85
- package/backend/dist/flywheel/prune.d.ts +0 -133
- package/backend/dist/flywheel/prune.js +0 -495
- package/backend/dist/flywheel/schema.d.ts +0 -108
- package/backend/dist/flywheel/schema.js +0 -117
- package/backend/dist/flywheel/trainer.d.ts +0 -84
- package/backend/dist/flywheel/trainer.js +0 -198
- package/backend/dist/opencode/catalog/custom-store.d.ts +0 -50
- package/backend/dist/opencode/catalog/custom-store.js +0 -144
- package/backend/dist/opencode/credentials/push.d.ts +0 -38
- package/backend/dist/opencode/credentials/push.js +0 -116
- package/backend/dist/opencode/credentials/reconcile.d.ts +0 -49
- package/backend/dist/opencode/credentials/reconcile.js +0 -216
- package/backend/dist/opencode/sync.d.ts +0 -29
- package/backend/dist/opencode/sync.js +0 -186
- package/backend/dist/pipeline/account-selection.d.ts +0 -101
- package/backend/dist/pipeline/account-selection.js +0 -112
- package/backend/dist/providers/systemone.d.ts +0 -29
- package/backend/dist/providers/systemone.js +0 -170
- package/backend/dist/ratelimit/duration.d.ts +0 -24
- package/backend/dist/ratelimit/duration.js +0 -43
- package/backend/dist/ratelimit/governance-runtime.d.ts +0 -121
- package/backend/dist/ratelimit/governance-runtime.js +0 -183
- package/backend/dist/ratelimit/index.d.ts +0 -4
- package/backend/dist/ratelimit/index.js +0 -4
- package/backend/dist/ratelimit/limiter.d.ts +0 -157
- package/backend/dist/ratelimit/limiter.js +0 -244
- package/backend/dist/ratelimit/sliding-window-counter.d.ts +0 -63
- package/backend/dist/ratelimit/sliding-window-counter.js +0 -103
- package/backend/dist/ratelimit/subject.d.ts +0 -26
- package/backend/dist/ratelimit/subject.js +0 -28
- package/backend/dist/resilience/account-state.d.ts +0 -84
- package/backend/dist/resilience/account-state.js +0 -228
- package/backend/dist/router/layer1-classifier.d.ts +0 -111
- package/backend/dist/router/layer1-classifier.js +0 -467
- package/backend/dist/router/layer2-judge.d.ts +0 -111
- package/backend/dist/router/layer2-judge.js +0 -373
- package/backend/dist/router/retry-escalation.d.ts +0 -89
- package/backend/dist/router/retry-escalation.js +0 -99
- package/backend/dist/routes/flywheel.d.ts +0 -3
- package/backend/dist/routes/flywheel.js +0 -268
- package/backend/dist/routes/systemone.d.ts +0 -3
- package/backend/dist/routes/systemone.js +0 -90
- package/backend/dist/surfaces/governance-envelope.d.ts +0 -34
- package/backend/dist/surfaces/governance-envelope.js +0 -47
- package/backend/dist/utils/token-estimator.d.ts +0 -7
- package/backend/dist/utils/token-estimator.js +0 -20
- package/frontend/dist/assets/index-nwgWkmU1.js +0 -840
|
@@ -1,268 +0,0 @@
|
|
|
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,90 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import type { Verdict } from '../ratelimit/index.js';
|
|
2
|
-
import type { ProtocolSurface } from './types.js';
|
|
3
|
-
/**
|
|
4
|
-
* Wire shapes for inbound governance denials (design §8: the 429 + Retry-After
|
|
5
|
-
* and 402 bodies are protocol-compatible on ALL FOUR inference surfaces).
|
|
6
|
-
* The status mapping is the ENFORCE policy half (design §3): `costUsd` denial
|
|
7
|
-
* → 402 contract refusal (NEVER 429 — a budget is not a throttle, retrying
|
|
8
|
-
* will not help), any other denial → 429 + Retry-After.
|
|
9
|
-
*
|
|
10
|
-
* These bodies deliberately do NOT route through each surface's `errorBody`:
|
|
11
|
-
* that helper is the legacy parse-400/execution-catch envelope with its own
|
|
12
|
-
* status→type mapping (invalid_request_error / api_error), and "preserved,
|
|
13
|
-
* not fixed" applies to what it already answers — governance refusals are NEW
|
|
14
|
-
* behavior, so they carry the provider-real rate/budget types directly:
|
|
15
|
-
* chat / responses / systemone → OpenAI style {error:{message,type,code}}
|
|
16
|
-
* anthropic → Anthropic style {type:'error',error:{type,message}}
|
|
17
|
-
* Key insertion order mirrors each surface's existing error emitter (wire-byte
|
|
18
|
-
* consistency with the surfaces/ family).
|
|
19
|
-
*/
|
|
20
|
-
/** The engine's denial arm — the envelope helper's input (Verdict narrowed). */
|
|
21
|
-
export type GovernanceDenial = Extract<Verdict, {
|
|
22
|
-
allowed: false;
|
|
23
|
-
}>;
|
|
24
|
-
export type GovernanceRejection = {
|
|
25
|
-
status: number;
|
|
26
|
-
body: unknown;
|
|
27
|
-
headers: Record<string, string>;
|
|
28
|
-
};
|
|
29
|
-
/**
|
|
30
|
-
* Render one denial verdict into the caller's protocol dialect. The message
|
|
31
|
-
* carries the rule id verbatim (§5 reason culture: operator maps the refusal
|
|
32
|
-
* straight back to the YAML `limits:` line — zero translation).
|
|
33
|
-
*/
|
|
34
|
-
export declare function governanceRejection(surface: ProtocolSurface, denial: GovernanceDenial, keyName: string): GovernanceRejection;
|
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Render one denial verdict into the caller's protocol dialect. The message
|
|
3
|
-
* carries the rule id verbatim (§5 reason culture: operator maps the refusal
|
|
4
|
-
* straight back to the YAML `limits:` line — zero translation).
|
|
5
|
-
*/
|
|
6
|
-
export function governanceRejection(surface, denial, keyName) {
|
|
7
|
-
const isCost = denial.limitedBy === 'costUsd';
|
|
8
|
-
const retryAfterSec = Math.max(1, Math.ceil(denial.retryAfterMs / 1000));
|
|
9
|
-
// Retry-After rides the 429 only: a sliding-window budget has a next-open
|
|
10
|
-
// moment, but it is NOT a retry contract (top-up / renegotiation is the
|
|
11
|
-
// recovery), so answering 402 with "retry in Ns" would teach clients to
|
|
12
|
-
// hammer — design §1: over-limit rejects, no queueing.
|
|
13
|
-
const headers = isCost ? {} : { 'retry-after': String(retryAfterSec) };
|
|
14
|
-
const message = isCost
|
|
15
|
-
? `Budget exhausted for API key '${keyName}' (rule ${denial.rule}). This is a contract refusal, not a throttle: retrying will not help — the window recovers as recorded spend ages out, or the gateway operator raises the limit.`
|
|
16
|
-
: `Rate limit exceeded for API key '${keyName}' (rule ${denial.rule}). Retry after ${retryAfterSec}s.`;
|
|
17
|
-
if (surface.wire === 'anthropic') {
|
|
18
|
-
// Anthropic's own vocabulary: 429 rate_limit_error / 402 billing_error.
|
|
19
|
-
// 'insufficient_quota' is NOT an Anthropic error type — emitting it here
|
|
20
|
-
// would break SDK type-parsing on the /v1/messages wire. The error object
|
|
21
|
-
// is {type, message} with no code slot (mirrors surfaces/anthropic.ts).
|
|
22
|
-
return {
|
|
23
|
-
status: isCost ? 402 : 429,
|
|
24
|
-
body: {
|
|
25
|
-
type: 'error',
|
|
26
|
-
error: {
|
|
27
|
-
type: isCost ? 'billing_error' : 'rate_limit_error',
|
|
28
|
-
message,
|
|
29
|
-
},
|
|
30
|
-
},
|
|
31
|
-
headers,
|
|
32
|
-
};
|
|
33
|
-
}
|
|
34
|
-
// OpenAI-compatible family (chat / responses / systemone): message/type/code,
|
|
35
|
-
// insertion order matching surfaces/chat.ts chatErrorBody.
|
|
36
|
-
return {
|
|
37
|
-
status: isCost ? 402 : 429,
|
|
38
|
-
body: {
|
|
39
|
-
error: {
|
|
40
|
-
message,
|
|
41
|
-
type: isCost ? 'insufficient_quota' : 'rate_limit_error',
|
|
42
|
-
code: isCost ? 'insufficient_quota' : 'rate_limit_exceeded',
|
|
43
|
-
},
|
|
44
|
-
},
|
|
45
|
-
headers,
|
|
46
|
-
};
|
|
47
|
-
}
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Fast, language-neutral token estimator:
|
|
3
|
-
* ~1.5 chars per token for CJK scripts, ~4 chars per token for Latin, Cyrillic, Greek, Arabic, etc.
|
|
4
|
-
*/
|
|
5
|
-
export class TokenEstimator {
|
|
6
|
-
static estimate(text) {
|
|
7
|
-
let cjkCount = 0;
|
|
8
|
-
let otherCount = 0;
|
|
9
|
-
for (let i = 0; i < text.length; i++) {
|
|
10
|
-
const code = text.charCodeAt(i);
|
|
11
|
-
if (code >= 0x4e00 && code <= 0x9fff) {
|
|
12
|
-
cjkCount++;
|
|
13
|
-
}
|
|
14
|
-
else {
|
|
15
|
-
otherCount++;
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
return Math.ceil(cjkCount / 1.5 + otherCount / 4);
|
|
19
|
-
}
|
|
20
|
-
}
|