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,117 @@
1
+ export const FLYWHEEL_SCHEMA_VERSION = 2;
2
+ export const FLYWHEEL_TIERS = ['lite', 'plus', 'pro', 'ultra'];
3
+ export function isTier(value) {
4
+ return typeof value === 'string' && FLYWHEEL_TIERS.includes(value);
5
+ }
6
+ export function num(value, fallback = 0) {
7
+ return typeof value === 'number' && Number.isFinite(value) ? value : fallback;
8
+ }
9
+ export function str(value, fallback = '') {
10
+ return typeof value === 'string' ? value : fallback;
11
+ }
12
+ /**
13
+ * The label a record carries when no operator override is in place: the tier
14
+ * that actually SERVED the request, never the tier the router asked for.
15
+ *
16
+ * Single source of truth for that rule — the collector writes it at capture
17
+ * time and the dataset re-derives it whenever an override is removed, so
18
+ * "clear label" always lands back on the observed value rather than on a
19
+ * stale human label.
20
+ */
21
+ export function deriveDefaultLabel(params) {
22
+ const tier = isTier(params.tierUsed) ? params.tierUsed : null;
23
+ return {
24
+ tier,
25
+ source: params.fallbackOccurred ? 'runtime_fallback' : 'observed_execution',
26
+ confidence: params.fallbackOccurred ? 0.9 : 0.5,
27
+ overridden: tier !== null && params.targetTier !== params.tierUsed,
28
+ isNegativeForLite: params.fallbackOccurred,
29
+ };
30
+ }
31
+ /**
32
+ * Bench/test traffic detector.
33
+ *
34
+ * The flywheel is opt-in (default off) and forced off under `bun test`
35
+ * (NODE_ENV=test), but if collection is ever on, `bun test` would append its
36
+ * fixtures to the production dataset. These three signals are the
37
+ * unmistakable fingerprints the test-suite leaves behind (see
38
+ * backend/tests/flywheel.test.ts and the tier-pool tests); they are checked
39
+ * narrowly so real traffic is never swept up with them.
40
+ */
41
+ export function detectSynthetic(id, modelUsed, fallbackReason) {
42
+ if (/^mock/i.test(id) || /^mock/i.test(modelUsed))
43
+ return true;
44
+ if (modelUsed === 'always-downgrade')
45
+ return true;
46
+ if (fallbackReason && /mandatory_key_that_fails_on/i.test(fallbackReason))
47
+ return true;
48
+ return false;
49
+ }
50
+ /**
51
+ * Disk rows are external input: accept the params object only property by
52
+ * property, dropping values that are not primitives. Absent/invalid →
53
+ * undefined, so rows without the field parse unchanged.
54
+ */
55
+ function optReasonParams(value) {
56
+ if (!value || typeof value !== 'object' || Array.isArray(value))
57
+ return undefined;
58
+ const out = {};
59
+ for (const [k, v] of Object.entries(value)) {
60
+ if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean')
61
+ out[k] = v;
62
+ }
63
+ return out;
64
+ }
65
+ /**
66
+ * Parse one dataset line into the current shape. Never throws on malformed
67
+ * input: a line that cannot be parsed is a logging concern, not a reason to
68
+ * break the console. There is no v1 reader (0.0.1 — no dataset outside this
69
+ * install ever existed): a pre-v2 line returns null and the caller counts it
70
+ * as malformed.
71
+ */
72
+ export function migrateRecord(raw) {
73
+ if (!raw || typeof raw !== 'object')
74
+ return null;
75
+ if (raw.v !== FLYWHEEL_SCHEMA_VERSION || raw.input === undefined)
76
+ return null;
77
+ const exec = raw.execution || {};
78
+ const label = raw.label || {};
79
+ return {
80
+ v: FLYWHEEL_SCHEMA_VERSION,
81
+ id: str(raw.id, `anon_${Date.now()}`),
82
+ timestamp: str(raw.timestamp, new Date().toISOString()),
83
+ input: {
84
+ userPrompt: str(raw.input.userPrompt),
85
+ featureVector: Array.isArray(raw.input.featureVector) ? raw.input.featureVector.map((n) => num(n)) : null,
86
+ featureNames: Array.isArray(raw.input.featureNames) ? raw.input.featureNames.map((s) => str(s)) : [],
87
+ tokenCount: num(raw.input.tokenCount),
88
+ turnCount: num(raw.input.turnCount),
89
+ },
90
+ decision: {
91
+ targetTier: isTier(raw.decision?.targetTier) ? raw.decision.targetTier : 'plus',
92
+ confidence: num(raw.decision?.confidence),
93
+ layerUsed: ['layer0', 'layer1', 'layer2'].includes(raw.decision?.layerUsed) ? raw.decision.layerUsed : 'layer0',
94
+ reason: str(raw.decision?.reason),
95
+ reasonCode: str(raw.decision?.reasonCode) || undefined,
96
+ reasonParams: optReasonParams(raw.decision?.reasonParams),
97
+ },
98
+ execution: {
99
+ tierUsed: isTier(exec.tierUsed) ? exec.tierUsed : isTier(raw.decision?.targetTier) ? raw.decision.targetTier : 'plus',
100
+ modelUsed: str(exec.modelUsed),
101
+ fallbackOccurred: exec.fallbackOccurred === true,
102
+ fallbackReason: str(exec.fallbackReason) || undefined,
103
+ latencyMs: num(exec.latencyMs),
104
+ isSynthetic: exec.isSynthetic === true || detectSynthetic(str(raw.id), str(exec.modelUsed), exec.fallbackReason),
105
+ },
106
+ label: {
107
+ tier: isTier(label.tier) ? label.tier : null,
108
+ source: ['human', 'runtime_fallback', 'observed_execution', 'unlabeled'].includes(label.source)
109
+ ? label.source
110
+ : 'unlabeled',
111
+ confidence: num(label.confidence),
112
+ overridden: label.overridden === true,
113
+ isNegativeForLite: label.isNegativeForLite === true,
114
+ updatedAt: str(label.updatedAt) || undefined,
115
+ },
116
+ };
117
+ }
@@ -0,0 +1,84 @@
1
+ import { FlywheelDataset } from './dataset.js';
2
+ import { TierLevel } from '../types/router.js';
3
+ export type TrainingStatus = 'idle' | 'training' | 'success' | 'failed';
4
+ export interface TrainingReport {
5
+ trainedSamples: number;
6
+ skipped: Record<string, number>;
7
+ classDistribution: Record<string, number>;
8
+ finalLoss: number;
9
+ accuracy: number;
10
+ epochs: number;
11
+ lr: number;
12
+ l2: number;
13
+ balanced: boolean;
14
+ durationMs: number;
15
+ modelPath: string;
16
+ }
17
+ export interface TrainingState {
18
+ status: TrainingStatus;
19
+ lastStartedAt: string | null;
20
+ lastTrainedAt: string | null;
21
+ lastDurationMs: number | null;
22
+ lastResult: TrainingReport | null;
23
+ error: string | null;
24
+ }
25
+ export interface TrainOptions {
26
+ epochs?: number;
27
+ lr?: number;
28
+ l2?: number;
29
+ maxSamples?: number;
30
+ /** Resample minority tiers up to the majority count so `ultra` is learnable. */
31
+ balanceClasses?: boolean;
32
+ includeSynthetic?: boolean;
33
+ minLabelSource?: 'human' | 'runtime_fallback' | 'observed_execution';
34
+ }
35
+ export interface ModelInfo {
36
+ modelPath: string;
37
+ exists: boolean;
38
+ isBaseModel: boolean;
39
+ sampleCount: number;
40
+ lastTrainedAt: string | null;
41
+ featureDimensions: number;
42
+ classes: TierLevel[];
43
+ /** Whether the router's confidence gate actually consumes trained weights
44
+ * (classifier.localModel.enabled in the orchestrator's config snapshot).
45
+ * Training with this false updates the weights but changes NO routing. */
46
+ routingConsumesModel: boolean;
47
+ /** Path of the automatic pre-training backup (previous weights), if any. */
48
+ previousModelPath: string;
49
+ previousModelExists: boolean;
50
+ }
51
+ export declare class FlywheelTrainer {
52
+ private dataset;
53
+ private modelPath;
54
+ /** Deployment-level sample budget (`flywheel.maxSamples`); a request body may override per run. */
55
+ private defaultMaxSamples;
56
+ /** Whether the router gate is open for trained weights (mirrors classifier.localModel.enabled). */
57
+ private routingEnabled;
58
+ private state;
59
+ constructor(dataset: FlywheelDataset, modelPath?: string, defaultMaxSamples?: number, routingEnabled?: boolean);
60
+ private get previousModelPath();
61
+ getState(): TrainingState;
62
+ /** True while a run is in flight — the console disables its button on this. */
63
+ isTraining(): boolean;
64
+ /** Current on-disk model metadata, for the console header. */
65
+ modelInfo(): ModelInfo;
66
+ /**
67
+ * Restore the automatic pre-training backup (the weights this model had
68
+ * before the last successful run) and hot-reload them into this process.
69
+ * Returns false when no backup exists — the caller maps that to 404.
70
+ */
71
+ rollback(): boolean;
72
+ /**
73
+ * Kick off a training run. Returns 409-equivalent state when one is already
74
+ * in flight — the guard lives here, not only in the UI, so a second tab or a
75
+ * direct API call cannot double-schedule a run.
76
+ */
77
+ train(options?: TrainOptions): Promise<{
78
+ started: boolean;
79
+ state: TrainingState;
80
+ report?: TrainingReport;
81
+ error?: string;
82
+ }>;
83
+ private runSync;
84
+ }
@@ -0,0 +1,198 @@
1
+ /**
2
+ * The training stage of the learning flywheel — retraining the Layer 1
3
+ * micro-classifier from what the collector gathered and the console labelled.
4
+ *
5
+ * The optimizer itself already existed (`Layer1Classifier.train` — softmax
6
+ * cross-entropy with L2). What was missing is the stage that closes the loop:
7
+ * dataset → eligible samples → train → persist to
8
+ * `models/layer1-classifier.json` → hot-swap the in-memory weights, so the next
9
+ * request routes on a better Layer 1 and the flywheel collects better samples.
10
+ *
11
+ * `Layer1Classifier.train` is a synchronous CPU loop and blocks the event loop
12
+ * while it runs. Measured on the dev machine (8 features, 4 classes, 150
13
+ * epochs): 265 ms @ 5k samples, 640 ms @ 20k — a single sub-second stall, which
14
+ * is why the hard ceiling exists and why no worker thread was added yet. If the
15
+ * ceiling ever rises, move the loop into a worker first.
16
+ */
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+ import { Layer1Classifier, DEFAULT_BASE_MODEL } from '../router/layer1-classifier.js';
20
+ import { getEnvRootDir } from '../config/env.js';
21
+ /** Hard ceiling on the synchronous training loop's work. */
22
+ const HARD_SAMPLE_CEILING = 20000;
23
+ export class FlywheelTrainer {
24
+ dataset;
25
+ modelPath;
26
+ /** Deployment-level sample budget (`flywheel.maxSamples`); a request body may override per run. */
27
+ defaultMaxSamples;
28
+ /** Whether the router gate is open for trained weights (mirrors classifier.localModel.enabled). */
29
+ routingEnabled;
30
+ state = {
31
+ status: 'idle',
32
+ lastStartedAt: null,
33
+ lastTrainedAt: null,
34
+ lastDurationMs: null,
35
+ lastResult: null,
36
+ error: null,
37
+ };
38
+ constructor(dataset, modelPath, defaultMaxSamples, routingEnabled) {
39
+ this.dataset = dataset;
40
+ // Trained weights live inside the environment: <home>/envs/<env>/models/
41
+ // layer1-classifier.json, so every book-set keeps its own model.
42
+ this.modelPath = modelPath || path.resolve(getEnvRootDir(), 'models/layer1-classifier.json');
43
+ this.defaultMaxSamples = defaultMaxSamples;
44
+ this.routingEnabled = routingEnabled === true;
45
+ }
46
+ get previousModelPath() {
47
+ return `${this.modelPath}.previous`;
48
+ }
49
+ getState() {
50
+ return { ...this.state };
51
+ }
52
+ /** True while a run is in flight — the console disables its button on this. */
53
+ isTraining() {
54
+ return this.state.status === 'training';
55
+ }
56
+ /** Current on-disk model metadata, for the console header. */
57
+ modelInfo() {
58
+ let weights = null;
59
+ try {
60
+ weights = JSON.parse(fs.readFileSync(this.modelPath, 'utf8'));
61
+ }
62
+ catch {
63
+ weights = null;
64
+ }
65
+ const model = weights || DEFAULT_BASE_MODEL;
66
+ return {
67
+ modelPath: this.modelPath,
68
+ exists: weights !== null,
69
+ isBaseModel: model.isBaseModel !== false,
70
+ sampleCount: model.sampleCount || 0,
71
+ lastTrainedAt: model.lastTrainedAt || this.state.lastTrainedAt,
72
+ featureDimensions: model.featureDimensions || DEFAULT_BASE_MODEL.featureDimensions,
73
+ classes: model.classes || DEFAULT_BASE_MODEL.classes,
74
+ routingConsumesModel: this.routingEnabled,
75
+ previousModelPath: this.previousModelPath,
76
+ previousModelExists: fs.existsSync(this.previousModelPath),
77
+ };
78
+ }
79
+ /**
80
+ * Restore the automatic pre-training backup (the weights this model had
81
+ * before the last successful run) and hot-reload them into this process.
82
+ * Returns false when no backup exists — the caller maps that to 404.
83
+ */
84
+ rollback() {
85
+ if (!fs.existsSync(this.previousModelPath))
86
+ return false;
87
+ fs.copyFileSync(this.previousModelPath, this.modelPath);
88
+ // Reload the in-memory weights too: within a single gateway process the
89
+ // static classifier is the live routing brain, not the file.
90
+ Layer1Classifier.reload(this.modelPath);
91
+ this.state = { ...this.state, lastResult: null, error: null };
92
+ return true;
93
+ }
94
+ /**
95
+ * Kick off a training run. Returns 409-equivalent state when one is already
96
+ * in flight — the guard lives here, not only in the UI, so a second tab or a
97
+ * direct API call cannot double-schedule a run.
98
+ */
99
+ async train(options = {}) {
100
+ if (this.isTraining()) {
101
+ return { started: false, state: this.getState(), error: 'A training run is already in progress.' };
102
+ }
103
+ this.state = { ...this.state, status: 'training', lastStartedAt: new Date().toISOString(), error: null };
104
+ // Yield once so the HTTP response that triggered this leaves the event loop
105
+ // before the synchronous training loop takes it over.
106
+ await new Promise((resolve) => setImmediate(resolve));
107
+ const startedAt = Date.now();
108
+ try {
109
+ const report = this.runSync(options);
110
+ this.state = {
111
+ ...this.state,
112
+ status: 'success',
113
+ lastTrainedAt: new Date().toISOString(),
114
+ lastDurationMs: Date.now() - startedAt,
115
+ lastResult: report,
116
+ error: null,
117
+ };
118
+ return { started: true, state: this.getState(), report };
119
+ }
120
+ catch (err) {
121
+ this.state = {
122
+ ...this.state,
123
+ status: 'failed',
124
+ lastDurationMs: Date.now() - startedAt,
125
+ error: err?.message || String(err),
126
+ };
127
+ return { started: true, state: this.getState(), error: this.state.error || 'Training failed.' };
128
+ }
129
+ }
130
+ runSync(options) {
131
+ const { samples, featureDimensions, skipped } = this.dataset.trainingSamples({
132
+ includeSynthetic: options.includeSynthetic,
133
+ minSource: options.minLabelSource,
134
+ });
135
+ if (samples.length === 0) {
136
+ throw new Error('No trainable samples. The dataset has no labelled rows with a feature vector.');
137
+ }
138
+ if (featureDimensions !== DEFAULT_BASE_MODEL.featureDimensions) {
139
+ throw new Error(`Feature dimension mismatch: dataset has ${featureDimensions}, the model expects ${DEFAULT_BASE_MODEL.featureDimensions}.`);
140
+ }
141
+ // Balance by default: routing data is inherently class-skewed (the router
142
+ // loves `plus`), and an unbalanced run mostly learns the prior. Callers
143
+ // that genuinely want raw distribution can opt out explicitly.
144
+ const balanced = options.balanceClasses !== false;
145
+ let trainSamples = samples;
146
+ if (balanced) {
147
+ const byTier = {};
148
+ for (const s of samples)
149
+ (byTier[s.targetTier] ||= []).push(s);
150
+ const maxCount = Math.max(...Object.values(byTier).map((g) => g.length));
151
+ trainSamples = [];
152
+ for (const group of Object.values(byTier)) {
153
+ for (let i = 0; i < maxCount; i++) {
154
+ trainSamples.push(group[i % group.length]);
155
+ }
156
+ }
157
+ }
158
+ const maxSamples = Math.min(options.maxSamples ?? this.defaultMaxSamples ?? HARD_SAMPLE_CEILING, HARD_SAMPLE_CEILING);
159
+ if (trainSamples.length > maxSamples) {
160
+ // Deterministic stride sample — keeps the class mix instead of taking a
161
+ // prefix, which would drop every minority class.
162
+ const stride = trainSamples.length / maxSamples;
163
+ const thinned = [];
164
+ for (let i = 0; i < maxSamples; i++)
165
+ thinned.push(trainSamples[Math.floor(i * stride)]);
166
+ trainSamples = thinned;
167
+ }
168
+ const epochs = options.epochs ?? 150;
169
+ const lr = options.lr ?? 0.1;
170
+ const l2 = options.l2 ?? 0.005;
171
+ const startedAt = Date.now();
172
+ // Snapshot the current weights before overwriting them: the only way back
173
+ // from a bad run is the file this gateway served until a moment ago.
174
+ if (fs.existsSync(this.modelPath)) {
175
+ fs.copyFileSync(this.modelPath, this.previousModelPath);
176
+ }
177
+ const result = Layer1Classifier.train(trainSamples, { epochs, lr, l2 });
178
+ // `train()` already swapped the in-memory weights; persist them so the next
179
+ // gateway boot loads the trained model instead of the base scaffold.
180
+ Layer1Classifier.saveModel(Layer1Classifier.getLoadedModel(), this.modelPath);
181
+ const classDistribution = {};
182
+ for (const s of trainSamples)
183
+ classDistribution[s.targetTier] = (classDistribution[s.targetTier] || 0) + 1;
184
+ return {
185
+ trainedSamples: result.trainedSamples,
186
+ skipped,
187
+ classDistribution,
188
+ finalLoss: result.finalLoss,
189
+ accuracy: result.accuracy,
190
+ epochs,
191
+ lr,
192
+ l2,
193
+ balanced,
194
+ durationMs: Date.now() - startedAt,
195
+ modelPath: this.modelPath,
196
+ };
197
+ }
198
+ }
@@ -3,5 +3,6 @@ import { defineHost } from './declarative.js';
3
3
  import { UNIVERSAL_SKILLS, xdgConfig } from './skills-paths.js';
4
4
  /** Amp — own XDG skills directory (does not read `.agents`); no MCP or extension landing. */
5
5
  export const ampAdapter = defineHost('amp', {
6
+ presence: { command: 'amp', dir: path.join(xdgConfig(), 'agents') },
6
7
  skills: { global: path.join(xdgConfig(), 'agents', 'skills'), project: UNIVERSAL_SKILLS.project },
7
8
  });
@@ -3,5 +3,6 @@ import { defineHost } from './declarative.js';
3
3
  import { home } from './skills-paths.js';
4
4
  /** Claude Code — its own skills directory; no VERIFIED MCP or extension landing (§D2/§D8). */
5
5
  export const claudeAdapter = defineHost('claude', {
6
+ presence: { command: 'claude', dir: path.join(home(), '.claude') },
6
7
  skills: { global: path.join(home(), '.claude', 'skills'), project: path.join('.claude', 'skills') },
7
8
  });
@@ -1,6 +1,8 @@
1
+ import path from 'node:path';
1
2
  import { defineHost } from './declarative.js';
2
- import { UNIVERSAL_SKILLS } from './skills-paths.js';
3
+ import { home, UNIVERSAL_SKILLS } from './skills-paths.js';
3
4
  /** Cline — reads the shared cross-agent skills directory; no MCP or extension landing. */
4
5
  export const clineAdapter = defineHost('cline', {
6
+ presence: { command: 'code', dir: path.join(home(), '.cline') },
5
7
  skills: { global: UNIVERSAL_SKILLS.global, project: UNIVERSAL_SKILLS.project, readsUniversal: true },
6
8
  });
@@ -1,6 +1,8 @@
1
+ import path from 'node:path';
1
2
  import { defineHost } from './declarative.js';
2
- import { UNIVERSAL_SKILLS } from './skills-paths.js';
3
+ import { home, UNIVERSAL_SKILLS } from './skills-paths.js';
3
4
  /** Codex — reads the shared cross-agent skills directory; no MCP or extension landing. */
4
5
  export const codexAdapter = defineHost('codex', {
6
+ presence: { command: 'codex', dir: path.join(home(), '.codex') },
5
7
  skills: { global: UNIVERSAL_SKILLS.global, project: UNIVERSAL_SKILLS.project, readsUniversal: true },
6
8
  });
@@ -6,5 +6,6 @@ import { home, UNIVERSAL_SKILLS } from './skills-paths.js';
6
6
  * editor's own marketplace, so no extension landing is declared until ADR-0015 §D8 verifies one.
7
7
  */
8
8
  export const cursorAdapter = defineHost('cursor', {
9
+ presence: { command: 'cursor', dir: path.join(home(), '.cursor') },
9
10
  skills: { global: path.join(home(), '.cursor', 'skills'), project: UNIVERSAL_SKILLS.project, readsUniversal: true },
10
11
  });
@@ -1,4 +1,4 @@
1
- import type { ExtensionHost, ExtensionSpec, HostAdapter, McpHost, SkillsHost, SkillsSpec } from './types.js';
1
+ import type { ExtensionHost, ExtensionSpec, HostAdapter, HostPresence, McpHost, SkillsHost, SkillsSpec } from './types.js';
2
2
  import type { HarnessHostId } from '../types.js';
3
3
  /**
4
4
  * The generic host implementations — every behaviour a host can have WITHOUT host-specific code
@@ -28,6 +28,7 @@ export declare function writeLanding(candidates: string[]): string;
28
28
  /** What one host declares: the env root plus whichever capabilities it actually has. */
29
29
  export interface HostSpec {
30
30
  configRootEnv?: string;
31
+ presence?: HostPresence;
31
32
  skills?: SkillsSpec;
32
33
  mcp?: {
33
34
  configGlobal: string | string[];
@@ -59,4 +60,5 @@ export declare function defineFullHost(id: HarnessHostId, spec: {
59
60
  mcp: NonNullable<HostSpec['mcp']>;
60
61
  ext: ExtensionSpec;
61
62
  configRootEnv?: string;
63
+ presence?: HostPresence;
62
64
  }): SkillsHost & McpHost & ExtensionHost;
@@ -39,7 +39,20 @@ const SKILL_NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/;
39
39
  function buildSkills(id, spec, configRootEnv) {
40
40
  const roots = (ctx, scope) => {
41
41
  if (scope === 'project') {
42
- return [{ root: path.resolve(ctx.projectRoot, spec.project), origin: 'default', precedence: 0 }];
42
+ const out = [
43
+ { root: path.resolve(ctx.projectRoot, spec.project), origin: 'default', precedence: 0 },
44
+ ];
45
+ // A readsUniversal host with a PRIVATE project root (omp: `.omp/skills`) ALSO loads the
46
+ // cross-agent project tree — referenced from skills-paths, never re-spelled. Hosts whose
47
+ // project root IS the shared tree (cursor, pi, …) already resolve it as their only root.
48
+ if (spec.readsUniversal && spec.project !== UNIVERSAL_SKILLS.project) {
49
+ out.push({
50
+ root: path.resolve(ctx.projectRoot, UNIVERSAL_SKILLS.project),
51
+ origin: 'default',
52
+ precedence: 1,
53
+ });
54
+ }
55
+ return out;
43
56
  }
44
57
  const out = [];
45
58
  const override = configRootEnv ? process.env[configRootEnv]?.trim() : undefined;
@@ -187,6 +200,7 @@ export function defineHost(id, spec = {}) {
187
200
  const base = {
188
201
  id,
189
202
  ...(spec.configRootEnv ? { configRootEnv: spec.configRootEnv } : {}),
203
+ ...(spec.presence ? { presence: spec.presence } : {}),
190
204
  };
191
205
  return Object.assign(base, ...parts);
192
206
  }
@@ -3,4 +3,4 @@ import { defineHost } from './declarative.js';
3
3
  * DSH — relocated by `DSH_HOME`; NO skills location (`skills: null` in the old catalog) and no
4
4
  * verified MCP or extension landing. Identity + env root only, which is the honest surface.
5
5
  */
6
- export const dshAdapter = defineHost('dsh', { configRootEnv: 'DSH_HOME' });
6
+ export const dshAdapter = defineHost('dsh', { configRootEnv: 'DSH_HOME', presence: { command: 'dsh' } });
@@ -3,5 +3,6 @@ import { defineHost } from './declarative.js';
3
3
  import { home, UNIVERSAL_SKILLS } from './skills-paths.js';
4
4
  /** Gemini CLI — own skills directory plus the shared one; no MCP or extension landing. */
5
5
  export const geminiCliAdapter = defineHost('gemini-cli', {
6
+ presence: { command: 'gemini', dir: path.join(home(), '.gemini') },
6
7
  skills: { global: path.join(home(), '.gemini', 'skills'), project: UNIVERSAL_SKILLS.project, readsUniversal: true },
7
8
  });
@@ -6,5 +6,6 @@ import { home, UNIVERSAL_SKILLS } from './skills-paths.js';
6
6
  * landing is verified for this host.
7
7
  */
8
8
  export const githubCopilotAdapter = defineHost('github-copilot', {
9
+ presence: { command: 'code', dir: path.join(home(), '.vscode') },
9
10
  skills: { global: path.join(home(), '.copilot', 'skills'), project: UNIVERSAL_SKILLS.project, readsUniversal: true },
10
11
  });
@@ -1,7 +1,7 @@
1
1
  import type { HarnessHostId, HarnessScope } from '../types.js';
2
- import type { HostAdapter } from './types.js';
2
+ import type { AdapterContext, HostAdapter } from './types.js';
3
3
  export { isExtensionHost, isMcpHost, isSkillsHost } from './types.js';
4
- export type { AdapterContext, ExtensionHost, ExtensionSpec, ExtensionWriteTarget, ExtSource, HostAdapter, McpHost, SkillsHost, SkillsSpec, } from './types.js';
4
+ export type { AdapterContext, ExtensionHost, ExtensionSpec, ExtensionWriteTarget, ExtSource, HostAdapter, HostPresence, McpHost, SkillsHost, SkillsSpec, } from './types.js';
5
5
  /**
6
6
  * The adapter registry — one entry per host in `HOSTS`, SAME ORDER (a test asserts the parity, so a
7
7
  * new host cannot be added to the catalog without an adapter, nor removed unnoticed).
@@ -15,7 +15,7 @@ export declare function adapterFor(id: HarnessHostId | string): HostAdapter | un
15
15
  /**
16
16
  * Every physical skills directory the adapters resolve, deduplicated.
17
17
  *
18
- * One directory is ONE copy: nine hosts share `.agents/skills`, so the FIRST adapter in registry
18
+ * One directory is ONE copy: ten hosts share `.agents/skills`, so the FIRST adapter in registry
19
19
  * order is the owner and every other host is an alias — installation, the inventory scan and the
20
20
  * console all use this rule, otherwise the same directory gets labeled two different ways.
21
21
  */
@@ -42,3 +42,11 @@ export declare function skillOwner(root: string, scope: HarnessScope, projectRoo
42
42
  * look empty for the eight runtimes that read it.
43
43
  */
44
44
  export declare function skillReaders(root: string, scope: HarnessScope, projectRoot?: string): HarnessHostId[];
45
+ /**
46
+ * Is this runtime present on THIS machine? Measured, never configured: the adapter's `presence`
47
+ * markers (executable on PATH, config directory on disk), plus — for a skills host — the existence
48
+ * of any of its global skills roots, so a runtime that left its skills tree behind stays visible
49
+ * and its rows stay manageable. `universal` is always present: it is the bootstrap entry, the
50
+ * place a first install lands when no runtime is installed yet.
51
+ */
52
+ export declare function hostDetected(adapter: HostAdapter, ctx?: AdapterContext): boolean;
@@ -1,3 +1,4 @@
1
+ import fs from 'node:fs';
1
2
  import path from 'node:path';
2
3
  import { ampAdapter } from './amp.js';
3
4
  import { claudeAdapter } from './claude.js';
@@ -5,6 +6,7 @@ import { clineAdapter } from './cline.js';
5
6
  import { codexAdapter } from './codex.js';
6
7
  import { cursorAdapter } from './cursor.js';
7
8
  import { dshAdapter } from './dsh.js';
9
+ import { ompAdapter } from './omp.js';
8
10
  import { geminiCliAdapter } from './gemini-cli.js';
9
11
  import { githubCopilotAdapter } from './github-copilot.js';
10
12
  import { opencodeAdapter } from './opencode.js';
@@ -28,6 +30,7 @@ export const HOST_ADAPTERS = [
28
30
  codexAdapter,
29
31
  piAdapter,
30
32
  dshAdapter,
33
+ ompAdapter,
31
34
  cursorAdapter,
32
35
  githubCopilotAdapter,
33
36
  geminiCliAdapter,
@@ -44,7 +47,7 @@ export function adapterFor(id) {
44
47
  /**
45
48
  * Every physical skills directory the adapters resolve, deduplicated.
46
49
  *
47
- * One directory is ONE copy: nine hosts share `.agents/skills`, so the FIRST adapter in registry
50
+ * One directory is ONE copy: ten hosts share `.agents/skills`, so the FIRST adapter in registry
48
51
  * order is the owner and every other host is an alias — installation, the inventory scan and the
49
52
  * console all use this rule, otherwise the same directory gets labeled two different ways.
50
53
  */
@@ -97,3 +100,47 @@ export function skillReaders(root, scope, projectRoot = process.cwd()) {
97
100
  }
98
101
  return out;
99
102
  }
103
+ /**
104
+ * Is this runtime present on THIS machine? Measured, never configured: the adapter's `presence`
105
+ * markers (executable on PATH, config directory on disk), plus — for a skills host — the existence
106
+ * of any of its global skills roots, so a runtime that left its skills tree behind stays visible
107
+ * and its rows stay manageable. `universal` is always present: it is the bootstrap entry, the
108
+ * place a first install lands when no runtime is installed yet.
109
+ */
110
+ export function hostDetected(adapter, ctx = { projectRoot: process.cwd() }) {
111
+ if (adapter.id === 'universal')
112
+ return true;
113
+ const command = adapter.presence?.command;
114
+ if (command && executableOnPath(command))
115
+ return true;
116
+ const dir = adapter.presence?.dir;
117
+ if (dir && fs.existsSync(dir))
118
+ return true;
119
+ if (isSkillsHost(adapter)) {
120
+ return adapter.skillRoots(ctx, 'global').some((resolved) => fs.existsSync(resolved.root));
121
+ }
122
+ return false;
123
+ }
124
+ /** PATH probe for an extensionless executable name; Windows suffixes are tried when the name has none. */
125
+ function executableOnPath(command) {
126
+ const exts = process.platform === 'win32' && !path.extname(command) ? ['.exe', '.cmd', '.bat', ''] : [''];
127
+ for (const dir of (process.env.PATH ?? '').split(path.delimiter)) {
128
+ if (!dir)
129
+ continue;
130
+ for (const ext of exts) {
131
+ const full = path.join(dir, command + ext);
132
+ try {
133
+ // X_OK degrades to mere existence on Windows, and on POSIX a
134
+ // directory with the execute bit also passes; require a real file.
135
+ if (!fs.statSync(full).isFile())
136
+ continue;
137
+ fs.accessSync(full, fs.constants.X_OK);
138
+ return true;
139
+ }
140
+ catch {
141
+ // not this candidate — keep probing
142
+ }
143
+ }
144
+ }
145
+ return false;
146
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * omp (oh-my-pi) — its own `.omp/skills` directory plus the shared cross-agent tree.
3
+ *
4
+ * The native provider discovers `<config-dir>/skills/<name>/SKILL.md` at user level and
5
+ * `.omp/skills/<name>/SKILL.md` at project level; the config root defaults to `~/.omp` and is
6
+ * relocated by `PI_CONFIG_DIR` (omp runtime docs: environment-variables.md resolution model).
7
+ * The `agents` provider additionally reads the cross-agent `.agents/skills` tree, so the shared
8
+ * directory is REFERENCED from skills-paths, never re-spelled here. No VERIFIED MCP or extension
9
+ * landing is declared for omp.
10
+ */
11
+ export declare const ompAdapter: import("./declarative.js").DefinedHost;
@@ -0,0 +1,22 @@
1
+ import path from 'node:path';
2
+ import { defineHost } from './declarative.js';
3
+ import { home } from './skills-paths.js';
4
+ /**
5
+ * omp (oh-my-pi) — its own `.omp/skills` directory plus the shared cross-agent tree.
6
+ *
7
+ * The native provider discovers `<config-dir>/skills/<name>/SKILL.md` at user level and
8
+ * `.omp/skills/<name>/SKILL.md` at project level; the config root defaults to `~/.omp` and is
9
+ * relocated by `PI_CONFIG_DIR` (omp runtime docs: environment-variables.md resolution model).
10
+ * The `agents` provider additionally reads the cross-agent `.agents/skills` tree, so the shared
11
+ * directory is REFERENCED from skills-paths, never re-spelled here. No VERIFIED MCP or extension
12
+ * landing is declared for omp.
13
+ */
14
+ export const ompAdapter = defineHost('omp', {
15
+ configRootEnv: 'PI_CONFIG_DIR',
16
+ presence: { command: 'omp', dir: path.join(home(), '.omp') },
17
+ skills: {
18
+ global: path.join(home(), '.omp', 'skills'),
19
+ project: path.join('.omp', 'skills'),
20
+ readsUniversal: true,
21
+ },
22
+ });