omnicell-router 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/RELEASING.md +238 -238
  2. package/RELEASING.zh-CN.md +230 -230
  3. package/backend/dist/capture/recorder.js +2 -1
  4. package/backend/dist/cli/clients/base.js +8 -16
  5. package/backend/dist/cli/clients/dsh.js +8 -16
  6. package/backend/dist/cli/clients/pi.js +16 -9
  7. package/backend/dist/cli/types.d.ts +5 -0
  8. package/backend/dist/config/env.js +2 -1
  9. package/backend/dist/config/index.js +2 -0
  10. package/backend/dist/config/types.d.ts +23 -0
  11. package/backend/dist/harness/adapters/amp.d.ts +2 -0
  12. package/backend/dist/harness/adapters/amp.js +7 -0
  13. package/backend/dist/harness/adapters/claude.d.ts +2 -0
  14. package/backend/dist/harness/adapters/claude.js +7 -0
  15. package/backend/dist/harness/adapters/cline.d.ts +2 -0
  16. package/backend/dist/harness/adapters/cline.js +6 -0
  17. package/backend/dist/harness/adapters/codex.d.ts +2 -0
  18. package/backend/dist/harness/adapters/codex.js +6 -0
  19. package/backend/dist/harness/adapters/cursor.d.ts +5 -0
  20. package/backend/dist/harness/adapters/cursor.js +10 -0
  21. package/backend/dist/harness/adapters/declarative.d.ts +62 -0
  22. package/backend/dist/harness/adapters/declarative.js +202 -0
  23. package/backend/dist/harness/adapters/dsh.d.ts +5 -0
  24. package/backend/dist/harness/adapters/dsh.js +6 -0
  25. package/backend/dist/harness/adapters/gemini-cli.d.ts +2 -0
  26. package/backend/dist/harness/adapters/gemini-cli.js +7 -0
  27. package/backend/dist/harness/adapters/github-copilot.d.ts +5 -0
  28. package/backend/dist/harness/adapters/github-copilot.js +10 -0
  29. package/backend/dist/harness/adapters/index.d.ts +44 -0
  30. package/backend/dist/harness/adapters/index.js +99 -0
  31. package/backend/dist/harness/adapters/opencode.d.ts +2 -0
  32. package/backend/dist/harness/adapters/opencode.js +55 -0
  33. package/backend/dist/harness/adapters/pi.d.ts +1 -0
  34. package/backend/dist/harness/adapters/pi.js +22 -0
  35. package/backend/dist/harness/adapters/skills-paths.d.ts +15 -0
  36. package/backend/dist/harness/adapters/skills-paths.js +17 -0
  37. package/backend/dist/harness/adapters/types.d.ts +174 -0
  38. package/backend/dist/harness/adapters/types.js +12 -0
  39. package/backend/dist/harness/adapters/universal.d.ts +6 -0
  40. package/backend/dist/harness/adapters/universal.js +10 -0
  41. package/backend/dist/harness/adapters/windsurf.d.ts +2 -0
  42. package/backend/dist/harness/adapters/windsurf.js +10 -0
  43. package/backend/dist/harness/adapters/zed.d.ts +2 -0
  44. package/backend/dist/harness/adapters/zed.js +6 -0
  45. package/backend/dist/harness/awesome-opencode.d.ts +40 -0
  46. package/backend/dist/harness/awesome-opencode.js +75 -0
  47. package/backend/dist/harness/browse.d.ts +202 -0
  48. package/backend/dist/harness/browse.js +1214 -0
  49. package/backend/dist/harness/catalog-npm.d.ts +59 -0
  50. package/backend/dist/harness/catalog-npm.js +145 -0
  51. package/backend/dist/harness/clawhub.d.ts +212 -0
  52. package/backend/dist/harness/clawhub.js +426 -0
  53. package/backend/dist/harness/config-file.d.ts +29 -0
  54. package/backend/dist/harness/config-file.js +35 -0
  55. package/backend/dist/harness/detail.d.ts +74 -0
  56. package/backend/dist/harness/detail.js +330 -0
  57. package/backend/dist/harness/discover.d.ts +118 -0
  58. package/backend/dist/harness/discover.js +507 -0
  59. package/backend/dist/harness/drift.d.ts +21 -0
  60. package/backend/dist/harness/drift.js +25 -0
  61. package/backend/dist/harness/hash.d.ts +10 -0
  62. package/backend/dist/harness/hash.js +63 -0
  63. package/backend/dist/harness/hosts.d.ts +18 -0
  64. package/backend/dist/harness/hosts.js +15 -0
  65. package/backend/dist/harness/install.d.ts +88 -0
  66. package/backend/dist/harness/install.js +301 -0
  67. package/backend/dist/harness/inventory.d.ts +10 -0
  68. package/backend/dist/harness/inventory.js +198 -0
  69. package/backend/dist/harness/ledger.d.ts +39 -0
  70. package/backend/dist/harness/ledger.js +83 -0
  71. package/backend/dist/harness/maintenance.d.ts +115 -0
  72. package/backend/dist/harness/maintenance.js +603 -0
  73. package/backend/dist/harness/manifest.d.ts +31 -0
  74. package/backend/dist/harness/manifest.js +234 -0
  75. package/backend/dist/harness/net.d.ts +86 -0
  76. package/backend/dist/harness/net.js +113 -0
  77. package/backend/dist/harness/opencode-cafe.d.ts +40 -0
  78. package/backend/dist/harness/opencode-cafe.js +85 -0
  79. package/backend/dist/harness/opencode-ecosystem.d.ts +34 -0
  80. package/backend/dist/harness/opencode-ecosystem.js +246 -0
  81. package/backend/dist/harness/pi-dev.d.ts +81 -0
  82. package/backend/dist/harness/pi-dev.js +187 -0
  83. package/backend/dist/harness/probe.d.ts +33 -0
  84. package/backend/dist/harness/probe.js +85 -0
  85. package/backend/dist/harness/registry.d.ts +2 -0
  86. package/backend/dist/harness/registry.js +26 -0
  87. package/backend/dist/harness/scopes.d.ts +21 -0
  88. package/backend/dist/harness/scopes.js +22 -0
  89. package/backend/dist/harness/skill-md.d.ts +18 -0
  90. package/backend/dist/harness/skill-md.js +71 -0
  91. package/backend/dist/harness/skills-sh.d.ts +109 -0
  92. package/backend/dist/harness/skills-sh.js +178 -0
  93. package/backend/dist/harness/smithery.d.ts +64 -0
  94. package/backend/dist/harness/smithery.js +146 -0
  95. package/backend/dist/harness/sources/awesome-opencode.d.ts +11 -0
  96. package/backend/dist/harness/sources/awesome-opencode.js +39 -0
  97. package/backend/dist/harness/sources/clawhub.d.ts +2 -0
  98. package/backend/dist/harness/sources/clawhub.js +83 -0
  99. package/backend/dist/harness/sources/github.d.ts +9 -0
  100. package/backend/dist/harness/sources/github.js +202 -0
  101. package/backend/dist/harness/sources/mcp-official.d.ts +2 -0
  102. package/backend/dist/harness/sources/mcp-official.js +110 -0
  103. package/backend/dist/harness/sources/npm.d.ts +2 -0
  104. package/backend/dist/harness/sources/npm.js +152 -0
  105. package/backend/dist/harness/sources/opencode-cafe.d.ts +11 -0
  106. package/backend/dist/harness/sources/opencode-cafe.js +41 -0
  107. package/backend/dist/harness/sources/smithery.d.ts +2 -0
  108. package/backend/dist/harness/sources/smithery.js +81 -0
  109. package/backend/dist/harness/spi.d.ts +98 -0
  110. package/backend/dist/harness/spi.js +8 -0
  111. package/backend/dist/harness/stars.d.ts +70 -0
  112. package/backend/dist/harness/stars.js +202 -0
  113. package/backend/dist/harness/translation.d.ts +142 -0
  114. package/backend/dist/harness/translation.js +567 -0
  115. package/backend/dist/harness/tree.d.ts +13 -0
  116. package/backend/dist/harness/tree.js +19 -0
  117. package/backend/dist/harness/types.d.ts +286 -0
  118. package/backend/dist/harness/types.js +8 -0
  119. package/backend/dist/harness/writers/extension.d.ts +116 -0
  120. package/backend/dist/harness/writers/extension.js +219 -0
  121. package/backend/dist/harness/writers/mcp.d.ts +72 -0
  122. package/backend/dist/harness/writers/mcp.js +195 -0
  123. package/backend/dist/harness/writers/skill.d.ts +60 -0
  124. package/backend/dist/harness/writers/skill.js +146 -0
  125. package/backend/dist/opencode/agents.d.ts +5 -0
  126. package/backend/dist/opencode/agents.js +10 -1
  127. package/backend/dist/opencode/catalog/cache.js +2 -1
  128. package/backend/dist/opencode/catalog/logos.js +2 -1
  129. package/backend/dist/opencode/catalog/ocr-store.js +2 -1
  130. package/backend/dist/opencode/catalog/overrides-store.js +2 -1
  131. package/backend/dist/opencode/credentials/factory.js +10 -27
  132. package/backend/dist/opencode/credentials/ocr-store.js +2 -1
  133. package/backend/dist/opencode/provider-defs.js +2 -1
  134. package/backend/dist/opencode/user-config.js +8 -16
  135. package/backend/dist/providers/registry.d.ts +15 -4
  136. package/backend/dist/providers/registry.js +29 -5
  137. package/backend/dist/providers/virtual-meta.d.ts +13 -0
  138. package/backend/dist/providers/virtual-meta.js +18 -0
  139. package/backend/dist/quota/store.js +2 -1
  140. package/backend/dist/resilience/breaker-state.js +2 -1
  141. package/backend/dist/resilience/credential-state.js +2 -1
  142. package/backend/dist/routes/console.js +137 -15
  143. package/backend/dist/routes/harness.d.ts +2 -0
  144. package/backend/dist/routes/harness.js +622 -0
  145. package/backend/dist/server.js +4 -0
  146. package/backend/dist/session/session-manager.js +2 -1
  147. package/backend/dist/surfaces/systemone-probe.d.ts +25 -0
  148. package/backend/dist/surfaces/systemone-probe.js +74 -0
  149. package/backend/dist/utils/atomic-write.d.ts +12 -0
  150. package/backend/dist/utils/atomic-write.js +29 -0
  151. package/bin/ocr.js +2 -2
  152. package/frontend/dist/assets/{index-DEo2iAT7.css → index-1o7qI-KJ.css} +1 -1
  153. package/frontend/dist/assets/index-DvXKvNxl.js +962 -0
  154. package/frontend/dist/index.html +2 -2
  155. package/package.json +87 -87
  156. package/backend/dist/budget/budget-manager.d.ts +0 -25
  157. package/backend/dist/budget/budget-manager.js +0 -54
  158. package/backend/dist/config/governance-limits.d.ts +0 -68
  159. package/backend/dist/config/governance-limits.js +0 -261
  160. package/backend/dist/flywheel/collector.d.ts +0 -74
  161. package/backend/dist/flywheel/collector.js +0 -235
  162. package/backend/dist/flywheel/dataset.d.ts +0 -130
  163. package/backend/dist/flywheel/dataset.js +0 -638
  164. package/backend/dist/flywheel/decision-capture.d.ts +0 -68
  165. package/backend/dist/flywheel/decision-capture.js +0 -85
  166. package/backend/dist/flywheel/prune.d.ts +0 -133
  167. package/backend/dist/flywheel/prune.js +0 -495
  168. package/backend/dist/flywheel/schema.d.ts +0 -108
  169. package/backend/dist/flywheel/schema.js +0 -117
  170. package/backend/dist/flywheel/trainer.d.ts +0 -84
  171. package/backend/dist/flywheel/trainer.js +0 -198
  172. package/backend/dist/opencode/catalog/custom-store.d.ts +0 -50
  173. package/backend/dist/opencode/catalog/custom-store.js +0 -144
  174. package/backend/dist/opencode/credentials/push.d.ts +0 -38
  175. package/backend/dist/opencode/credentials/push.js +0 -116
  176. package/backend/dist/opencode/credentials/reconcile.d.ts +0 -49
  177. package/backend/dist/opencode/credentials/reconcile.js +0 -216
  178. package/backend/dist/opencode/sync.d.ts +0 -29
  179. package/backend/dist/opencode/sync.js +0 -186
  180. package/backend/dist/pipeline/account-selection.d.ts +0 -101
  181. package/backend/dist/pipeline/account-selection.js +0 -112
  182. package/backend/dist/providers/systemone.d.ts +0 -29
  183. package/backend/dist/providers/systemone.js +0 -170
  184. package/backend/dist/ratelimit/duration.d.ts +0 -24
  185. package/backend/dist/ratelimit/duration.js +0 -43
  186. package/backend/dist/ratelimit/governance-runtime.d.ts +0 -121
  187. package/backend/dist/ratelimit/governance-runtime.js +0 -183
  188. package/backend/dist/ratelimit/index.d.ts +0 -4
  189. package/backend/dist/ratelimit/index.js +0 -4
  190. package/backend/dist/ratelimit/limiter.d.ts +0 -157
  191. package/backend/dist/ratelimit/limiter.js +0 -244
  192. package/backend/dist/ratelimit/sliding-window-counter.d.ts +0 -63
  193. package/backend/dist/ratelimit/sliding-window-counter.js +0 -103
  194. package/backend/dist/ratelimit/subject.d.ts +0 -26
  195. package/backend/dist/ratelimit/subject.js +0 -28
  196. package/backend/dist/resilience/account-state.d.ts +0 -84
  197. package/backend/dist/resilience/account-state.js +0 -228
  198. package/backend/dist/router/layer1-classifier.d.ts +0 -111
  199. package/backend/dist/router/layer1-classifier.js +0 -467
  200. package/backend/dist/router/layer2-judge.d.ts +0 -111
  201. package/backend/dist/router/layer2-judge.js +0 -373
  202. package/backend/dist/router/retry-escalation.d.ts +0 -89
  203. package/backend/dist/router/retry-escalation.js +0 -99
  204. package/backend/dist/routes/flywheel.d.ts +0 -3
  205. package/backend/dist/routes/flywheel.js +0 -268
  206. package/backend/dist/routes/systemone.d.ts +0 -3
  207. package/backend/dist/routes/systemone.js +0 -90
  208. package/backend/dist/surfaces/governance-envelope.d.ts +0 -34
  209. package/backend/dist/surfaces/governance-envelope.js +0 -47
  210. package/backend/dist/utils/token-estimator.d.ts +0 -7
  211. package/backend/dist/utils/token-estimator.js +0 -20
  212. package/frontend/dist/assets/index-nwgWkmU1.js +0 -840
@@ -1,117 +0,0 @@
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
- }
@@ -1,84 +0,0 @@
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
- }
@@ -1,198 +0,0 @@
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
- }
@@ -1,50 +0,0 @@
1
- import type { CatalogModel } from './types.js';
2
- /**
3
- * Custom-pull store (~/.onecast-router/catalog/custom.json).
4
- *
5
- * Models pulled for CREDENTIAL-ONLY providers (auth.json entry without an
6
- * defs-file definition) — they have no defs node to write into, so the
7
- * pulled lists land here and feed the aggregation as the 'custom' source
8
- * (after config defs, entry-creating like the baseline). Merge is add-only:
9
- * a model id already present for a provider is never overwritten.
10
- */
11
- export interface CustomProviderEntry {
12
- name?: string;
13
- npm?: string;
14
- api?: string;
15
- models: CatalogModel[];
16
- }
17
- export interface CustomModelStore {
18
- version: 1;
19
- updated: number;
20
- providers: Record<string, CustomProviderEntry>;
21
- }
22
- export declare function getCustomStorePath(): string;
23
- export declare function readCustomStore(): CustomModelStore | null;
24
- /** Merge (add-only) one provider's pulled models into the store. */
25
- export declare function upsertCustomProviderModels(providerId: string, meta: {
26
- name?: string;
27
- npm?: string;
28
- api?: string;
29
- }, models: CatalogModel[]): number;
30
- export declare function removeCustomProvider(providerId: string): void;
31
- export declare function getCustomProviderModels(providerId: string): CatalogModel[];
32
- export declare function upsertCustomModel(providerId: string, model: CatalogModel): {
33
- success: boolean;
34
- error?: string;
35
- };
36
- /**
37
- * Clear models from a provider's custom-store entry — mirrors clearProviderModels
38
- * semantics (no pattern → all, pattern → glob matches). Fails when the provider
39
- * has no custom-store entry at all (same 404 signal as an unknown jsonc node),
40
- * but succeeds with removed: 0 when the entry exists and nothing matches.
41
- */
42
- export declare function clearCustomModels(providerId: string, pattern?: string): {
43
- success: boolean;
44
- removed?: number;
45
- error?: string;
46
- };
47
- export declare function removeCustomModel(providerId: string, modelId: string): {
48
- success: boolean;
49
- error?: string;
50
- };
@@ -1,144 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { getOcrStorePath } from './ocr-store.js';
4
- import { matchesGlobPattern } from '../user-config.js';
5
- export function getCustomStorePath() {
6
- return path.join(path.dirname(getOcrStorePath()), 'custom.json');
7
- }
8
- export function readCustomStore() {
9
- try {
10
- const file = getCustomStorePath();
11
- if (!fs.existsSync(file))
12
- return null;
13
- const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
14
- if (parsed?.version !== 1 || typeof parsed.providers !== 'object' || parsed.providers === null)
15
- return null;
16
- return parsed;
17
- }
18
- catch {
19
- return null;
20
- }
21
- }
22
- /** Merge (add-only) one provider's pulled models into the store. */
23
- export function upsertCustomProviderModels(providerId, meta, models) {
24
- try {
25
- const file = getCustomStorePath();
26
- const store = readCustomStore() ?? { version: 1, updated: 0, providers: {} };
27
- const entry = store.providers[providerId] ?? { models: [] };
28
- if (meta.name && !entry.name)
29
- entry.name = meta.name;
30
- if (meta.npm && !entry.npm)
31
- entry.npm = meta.npm;
32
- if (meta.api && !entry.api)
33
- entry.api = meta.api;
34
- const byId = new Map(entry.models.map((m) => [m.id, m]));
35
- let added = 0;
36
- for (const m of models) {
37
- if (byId.has(m.id))
38
- continue; // add-only
39
- byId.set(m.id, m);
40
- added++;
41
- }
42
- entry.models = [...byId.values()];
43
- store.providers[providerId] = entry;
44
- store.updated = Date.now();
45
- fs.mkdirSync(path.dirname(file), { recursive: true });
46
- const tmp = `${file}.tmp.${process.pid}.${Date.now()}`;
47
- fs.writeFileSync(tmp, JSON.stringify(store), 'utf8');
48
- fs.renameSync(tmp, file);
49
- return added;
50
- }
51
- catch {
52
- return 0;
53
- }
54
- }
55
- export function removeCustomProvider(providerId) {
56
- try {
57
- const store = readCustomStore();
58
- if (!store?.providers[providerId])
59
- return;
60
- delete store.providers[providerId];
61
- store.updated = Date.now();
62
- const file = getCustomStorePath();
63
- const tmp = `${file}.tmp.${process.pid}.${Date.now()}`;
64
- fs.writeFileSync(tmp, JSON.stringify(store), 'utf8');
65
- fs.renameSync(tmp, file);
66
- }
67
- catch {
68
- // best effort
69
- }
70
- }
71
- export function getCustomProviderModels(providerId) {
72
- return readCustomStore()?.providers[providerId]?.models ?? [];
73
- }
74
- export function upsertCustomModel(providerId, model) {
75
- try {
76
- const file = getCustomStorePath();
77
- const store = readCustomStore() ?? { version: 1, updated: 0, providers: {} };
78
- const entry = store.providers[providerId] ?? { models: [] };
79
- const byId = new Map(entry.models.map((m) => [m.id, m]));
80
- byId.set(model.id, model);
81
- entry.models = [...byId.values()];
82
- store.providers[providerId] = entry;
83
- store.updated = Date.now();
84
- fs.mkdirSync(path.dirname(file), { recursive: true });
85
- const tmp = `${file}.tmp.${process.pid}.${Date.now()}`;
86
- fs.writeFileSync(tmp, JSON.stringify(store), 'utf8');
87
- fs.renameSync(tmp, file);
88
- return { success: true };
89
- }
90
- catch (err) {
91
- return { success: false, error: err?.message };
92
- }
93
- }
94
- /**
95
- * Clear models from a provider's custom-store entry — mirrors clearProviderModels
96
- * semantics (no pattern → all, pattern → glob matches). Fails when the provider
97
- * has no custom-store entry at all (same 404 signal as an unknown jsonc node),
98
- * but succeeds with removed: 0 when the entry exists and nothing matches.
99
- */
100
- export function clearCustomModels(providerId, pattern) {
101
- try {
102
- const store = readCustomStore();
103
- const entry = store?.providers[providerId];
104
- if (!store || !entry) {
105
- return { success: false, error: `Provider '${providerId}' has no models in the custom store` };
106
- }
107
- const trimmed = pattern?.trim();
108
- const keep = trimmed ? entry.models.filter((m) => !matchesGlobPattern(trimmed, m.id)) : [];
109
- const removed = entry.models.length - keep.length;
110
- if (removed === 0)
111
- return { success: true, removed: 0 };
112
- entry.models = keep;
113
- store.updated = Date.now();
114
- const file = getCustomStorePath();
115
- fs.mkdirSync(path.dirname(file), { recursive: true });
116
- const tmp = `${file}.tmp.${process.pid}.${Date.now()}`;
117
- fs.writeFileSync(tmp, JSON.stringify(store), 'utf8');
118
- fs.renameSync(tmp, file);
119
- return { success: true, removed };
120
- }
121
- catch (err) {
122
- return { success: false, error: err?.message };
123
- }
124
- }
125
- export function removeCustomModel(providerId, modelId) {
126
- try {
127
- const store = readCustomStore();
128
- const entry = store?.providers[providerId];
129
- if (!entry || !entry.models.some((m) => m.id === modelId)) {
130
- return { success: false, error: `Model '${modelId}' not found in the custom store` };
131
- }
132
- entry.models = entry.models.filter((m) => m.id !== modelId);
133
- store.providers[providerId] = entry;
134
- store.updated = Date.now();
135
- const file = getCustomStorePath();
136
- const tmp = `${file}.tmp.${process.pid}.${Date.now()}`;
137
- fs.writeFileSync(tmp, JSON.stringify(store), 'utf8');
138
- fs.renameSync(tmp, file);
139
- return { success: true };
140
- }
141
- catch (err) {
142
- return { success: false, error: err?.message };
143
- }
144
- }
@@ -1,38 +0,0 @@
1
- import { CredentialPaths } from './paths.js';
2
- import { CredentialStore } from './types.js';
3
- import { DbOpener } from './opencode-v2-store.js';
4
- import { ReconcileLogSink } from './reconcile.js';
5
- export type PushPrecondition = 'not_ocr_bound' | 'opencode_v2_service_unreachable' | 'opencode_v2_db_unreadable';
6
- export interface PushOutcome {
7
- /** set instead of attempting anything when the endpoint's gate fails. */
8
- precondition?: PushPrecondition;
9
- /** provider ids fully converged (pushed or deduped AND local entry removed). */
10
- pushed: string[];
11
- /**
12
- * Converged (provider, keyHashPrefix) pairs — consumers need the
13
- * key identity per KEY (a push of a new key is a reconnect and lifts
14
- * that account's SUSPECT flag; provider ids alone cannot name the account).
15
- */
16
- pushedKeys: {
17
- provider: string;
18
- keyHashPrefix: string;
19
- }[];
20
- /** per-entry failures; the local copy of each is KEPT (never blind-delete). */
21
- failed: {
22
- provider: string;
23
- reason: string;
24
- }[];
25
- }
26
- export interface PushDeps {
27
- /** the bound store — precondition + local entries + removals. */
28
- store: CredentialStore;
29
- paths?: CredentialPaths;
30
- /** absent = every provider with local entries. */
31
- provider?: string;
32
- env?: Readonly<Record<string, string | undefined>>;
33
- fetchImpl?: typeof fetch;
34
- now?: () => number;
35
- openDatabase?: DbOpener;
36
- log?: ReconcileLogSink;
37
- }
38
- export declare function pushLocalCredentialsToV2(deps: PushDeps): Promise<PushOutcome>;