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.
- package/backend/dist/budget/budget-manager.d.ts +25 -0
- package/backend/dist/budget/budget-manager.js +54 -0
- package/backend/dist/cli/clients/index.js +2 -0
- package/backend/dist/cli/clients/omp.d.ts +53 -0
- package/backend/dist/cli/clients/omp.js +664 -0
- package/backend/dist/cli/clients/pi.js +79 -32
- package/backend/dist/cli/index.js +2 -2
- package/backend/dist/cli/types.d.ts +1 -1
- package/backend/dist/config/governance-limits.d.ts +68 -0
- package/backend/dist/config/governance-limits.js +261 -0
- package/backend/dist/config/index.js +1 -1
- package/backend/dist/config/types.d.ts +15 -5
- package/backend/dist/flywheel/collector.d.ts +74 -0
- package/backend/dist/flywheel/collector.js +235 -0
- package/backend/dist/flywheel/dataset.d.ts +130 -0
- package/backend/dist/flywheel/dataset.js +638 -0
- package/backend/dist/flywheel/decision-capture.d.ts +68 -0
- package/backend/dist/flywheel/decision-capture.js +85 -0
- package/backend/dist/flywheel/prune.d.ts +133 -0
- package/backend/dist/flywheel/prune.js +495 -0
- package/backend/dist/flywheel/schema.d.ts +108 -0
- package/backend/dist/flywheel/schema.js +117 -0
- package/backend/dist/flywheel/trainer.d.ts +84 -0
- package/backend/dist/flywheel/trainer.js +198 -0
- package/backend/dist/harness/adapters/amp.js +1 -0
- package/backend/dist/harness/adapters/claude.js +1 -0
- package/backend/dist/harness/adapters/cline.js +3 -1
- package/backend/dist/harness/adapters/codex.js +3 -1
- package/backend/dist/harness/adapters/cursor.js +1 -0
- package/backend/dist/harness/adapters/declarative.d.ts +3 -1
- package/backend/dist/harness/adapters/declarative.js +15 -1
- package/backend/dist/harness/adapters/dsh.js +1 -1
- package/backend/dist/harness/adapters/gemini-cli.js +1 -0
- package/backend/dist/harness/adapters/github-copilot.js +1 -0
- package/backend/dist/harness/adapters/index.d.ts +11 -3
- package/backend/dist/harness/adapters/index.js +48 -1
- package/backend/dist/harness/adapters/omp.d.ts +11 -0
- package/backend/dist/harness/adapters/omp.js +22 -0
- package/backend/dist/harness/adapters/opencode.js +1 -0
- package/backend/dist/harness/adapters/pi.js +2 -1
- package/backend/dist/harness/adapters/types.d.ts +19 -4
- package/backend/dist/harness/adapters/windsurf.js +1 -0
- package/backend/dist/harness/adapters/zed.js +3 -1
- package/backend/dist/harness/hosts.js +1 -0
- package/backend/dist/harness/translation.js +12 -4
- package/backend/dist/harness/types.d.ts +2 -2
- package/backend/dist/harness/writers/skill.d.ts +1 -1
- package/backend/dist/opencode/agents.d.ts +7 -0
- package/backend/dist/opencode/agents.js +22 -3
- package/backend/dist/opencode/catalog/custom-store.d.ts +50 -0
- package/backend/dist/opencode/catalog/custom-store.js +144 -0
- package/backend/dist/opencode/credentials/push.d.ts +38 -0
- package/backend/dist/opencode/credentials/push.js +116 -0
- package/backend/dist/opencode/credentials/reconcile.d.ts +49 -0
- package/backend/dist/opencode/credentials/reconcile.js +216 -0
- package/backend/dist/opencode/sync.d.ts +29 -0
- package/backend/dist/opencode/sync.js +186 -0
- package/backend/dist/pipeline/account-selection.d.ts +101 -0
- package/backend/dist/pipeline/account-selection.js +112 -0
- package/backend/dist/pipeline/orchestrator.js +34 -3
- package/backend/dist/providers/systemone.d.ts +29 -0
- package/backend/dist/providers/systemone.js +170 -0
- package/backend/dist/ratelimit/duration.d.ts +24 -0
- package/backend/dist/ratelimit/duration.js +43 -0
- package/backend/dist/ratelimit/governance-runtime.d.ts +121 -0
- package/backend/dist/ratelimit/governance-runtime.js +183 -0
- package/backend/dist/ratelimit/index.d.ts +4 -0
- package/backend/dist/ratelimit/index.js +4 -0
- package/backend/dist/ratelimit/limiter.d.ts +157 -0
- package/backend/dist/ratelimit/limiter.js +244 -0
- package/backend/dist/ratelimit/sliding-window-counter.d.ts +63 -0
- package/backend/dist/ratelimit/sliding-window-counter.js +103 -0
- package/backend/dist/ratelimit/subject.d.ts +26 -0
- package/backend/dist/ratelimit/subject.js +28 -0
- package/backend/dist/resilience/account-state.d.ts +84 -0
- package/backend/dist/resilience/account-state.js +228 -0
- package/backend/dist/router/layer1-classifier.d.ts +111 -0
- package/backend/dist/router/layer1-classifier.js +467 -0
- package/backend/dist/router/layer2-judge.d.ts +111 -0
- package/backend/dist/router/layer2-judge.js +373 -0
- package/backend/dist/router/retry-escalation.d.ts +89 -0
- package/backend/dist/router/retry-escalation.js +99 -0
- package/backend/dist/routes/flywheel.d.ts +3 -0
- package/backend/dist/routes/flywheel.js +268 -0
- package/backend/dist/routes/harness.js +4 -1
- package/backend/dist/routes/systemone.d.ts +3 -0
- package/backend/dist/routes/systemone.js +90 -0
- package/backend/dist/server.d.ts +0 -15
- package/backend/dist/server.js +40 -43
- package/backend/dist/session/session-manager.d.ts +15 -0
- package/backend/dist/session/session-manager.js +17 -0
- package/backend/dist/session/session-row.d.ts +78 -0
- package/backend/dist/session/session-row.js +52 -0
- package/backend/dist/surfaces/governance-envelope.d.ts +34 -0
- package/backend/dist/surfaces/governance-envelope.js +47 -0
- package/backend/dist/utils/token-estimator.d.ts +7 -0
- package/backend/dist/utils/token-estimator.js +20 -0
- package/bin/ocr.js +2 -2
- package/frontend/dist/assets/{index-DvXKvNxl.js → index-B7GKsUyU.js} +264 -244
- package/frontend/dist/assets/{index-1o7qI-KJ.css → index-DLKLOkQJ.css} +1 -1
- package/frontend/dist/index.html +2 -2
- package/package.json +1 -1
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { getEnvRootDir } from '../config/env.js';
|
|
4
|
+
import { TokenEstimator } from '../utils/token-estimator.js';
|
|
5
|
+
/**
|
|
6
|
+
* Standard Empty Local Model Base (Untrained Base Scaffold)
|
|
7
|
+
* 8 Language-Agnostic Structural & Statistical Features
|
|
8
|
+
* Weights initialized to 0.0 -> Uniform probability 0.25 -> Guaranteed low confidence -> Cascades to Layer 2
|
|
9
|
+
*/
|
|
10
|
+
export const DEFAULT_BASE_MODEL = {
|
|
11
|
+
version: '1.1.0',
|
|
12
|
+
modelType: 'linear_softmax_classifier',
|
|
13
|
+
description: 'Language-agnostic micro CPU classifier scaffold for OCR (OneCastRouter) Layer 1 (4-tier: lite/plus/pro/ultra)',
|
|
14
|
+
isBaseModel: true,
|
|
15
|
+
sampleCount: 0,
|
|
16
|
+
lastTrainedAt: null,
|
|
17
|
+
featureDimensions: 8,
|
|
18
|
+
featureNames: [
|
|
19
|
+
'token_count_normalized',
|
|
20
|
+
'turn_count_normalized',
|
|
21
|
+
'has_system_prompt',
|
|
22
|
+
'code_block_ratio',
|
|
23
|
+
'syntax_symbol_density',
|
|
24
|
+
'has_tools_or_schema',
|
|
25
|
+
'character_entropy',
|
|
26
|
+
'punctuation_density',
|
|
27
|
+
],
|
|
28
|
+
classes: ['lite', 'plus', 'pro', 'ultra'],
|
|
29
|
+
weights: [
|
|
30
|
+
[0.0, 0.0, 0.0, 0.0],
|
|
31
|
+
[0.0, 0.0, 0.0, 0.0],
|
|
32
|
+
[0.0, 0.0, 0.0, 0.0],
|
|
33
|
+
[0.0, 0.0, 0.0, 0.0],
|
|
34
|
+
[0.0, 0.0, 0.0, 0.0],
|
|
35
|
+
[0.0, 0.0, 0.0, 0.0],
|
|
36
|
+
[0.0, 0.0, 0.0, 0.0],
|
|
37
|
+
[0.0, 0.0, 0.0, 0.0],
|
|
38
|
+
],
|
|
39
|
+
biases: [0.0, 0.0, 0.0, 0.0],
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Layer 1: CPU Micro-Tensor Classifier Engine
|
|
43
|
+
* 100% Language-Agnostic, Zero Hardcoding, i18n-Compliant.
|
|
44
|
+
*
|
|
45
|
+
* Auto-initializes an empty base model scaffold if no model file exists on disk.
|
|
46
|
+
* When untrained (base model), forward pass confidence is ~0.333 (< threshold 0.85),
|
|
47
|
+
* mathematically guaranteeing a smooth and definitive cascade to Layer 2 (Judge / OpenCode).
|
|
48
|
+
* Once trained via the Data Flywheel, the same base model achieves high confidence locally on CPU!
|
|
49
|
+
*/
|
|
50
|
+
export class Layer1Classifier {
|
|
51
|
+
static loadedModel = JSON.parse(JSON.stringify(DEFAULT_BASE_MODEL));
|
|
52
|
+
static modelFilePath;
|
|
53
|
+
static onnxRuntime = null;
|
|
54
|
+
static onnxSession = null;
|
|
55
|
+
static initialized = false;
|
|
56
|
+
/**
|
|
57
|
+
* Initialize Layer 1 model.
|
|
58
|
+
* If model file does NOT exist, automatically scaffolds the base model!
|
|
59
|
+
*/
|
|
60
|
+
static async init(config) {
|
|
61
|
+
// Default scaffold location: <home>/envs/<env>/models/layer1-classifier.json
|
|
62
|
+
// — every environment trains its own weights.
|
|
63
|
+
const targetPath = config?.modelPath || path.resolve(getEnvRootDir(), 'models/layer1-classifier.json');
|
|
64
|
+
this.modelFilePath = targetPath;
|
|
65
|
+
// 1. If path points to an ONNX model, attempt to load ONNX
|
|
66
|
+
if (targetPath.endsWith('.onnx')) {
|
|
67
|
+
if (fs.existsSync(targetPath)) {
|
|
68
|
+
try {
|
|
69
|
+
// @ts-ignore
|
|
70
|
+
const ort = await import('onnxruntime-node').catch(() => null);
|
|
71
|
+
if (ort) {
|
|
72
|
+
this.onnxRuntime = ort;
|
|
73
|
+
this.onnxSession = await ort.InferenceSession.create(targetPath);
|
|
74
|
+
this.initialized = true;
|
|
75
|
+
console.log(`[Layer1Classifier] Loaded local ONNX model: ${targetPath}`);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
catch (err) {
|
|
80
|
+
console.warn(`[Layer1Classifier] Failed to load ONNX model, falling back to micro-tensor scaffold: ${err.message}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
// 2. Micro-Tensor Model Base (JSON format, zero native binary dependencies)
|
|
85
|
+
try {
|
|
86
|
+
if (!fs.existsSync(targetPath)) {
|
|
87
|
+
// Auto-initialize base model file on disk
|
|
88
|
+
const dir = path.dirname(targetPath);
|
|
89
|
+
if (!fs.existsSync(dir)) {
|
|
90
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
91
|
+
}
|
|
92
|
+
fs.writeFileSync(targetPath, JSON.stringify(DEFAULT_BASE_MODEL, null, 2), 'utf8');
|
|
93
|
+
this.loadedModel = JSON.parse(JSON.stringify(DEFAULT_BASE_MODEL));
|
|
94
|
+
this.initialized = true;
|
|
95
|
+
console.log(`[Layer1Classifier] Auto-initialized empty base model scaffold: ${targetPath} (untrained, guaranteed low confidence cascade)`);
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
const content = fs.readFileSync(targetPath, 'utf8');
|
|
99
|
+
this.loadedModel = JSON.parse(content);
|
|
100
|
+
this.initialized = true;
|
|
101
|
+
const status = this.loadedModel.isBaseModel
|
|
102
|
+
? 'untrained base scaffold (confidence ~0.33, guaranteed cascade)'
|
|
103
|
+
: `trained empirical model (samples: ${this.loadedModel.sampleCount})`;
|
|
104
|
+
console.log(`[Layer1Classifier] Loaded model: ${targetPath} [${status}]`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
catch (err) {
|
|
108
|
+
console.warn(`[Layer1Classifier] Failed reading model file, using in-memory default base scaffold: ${err.message}`);
|
|
109
|
+
this.loadedModel = JSON.parse(JSON.stringify(DEFAULT_BASE_MODEL));
|
|
110
|
+
this.initialized = true;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
static isModelLoaded() {
|
|
114
|
+
return this.initialized;
|
|
115
|
+
}
|
|
116
|
+
static isBaseModel() {
|
|
117
|
+
return this.loadedModel.isBaseModel || this.loadedModel.sampleCount === 0;
|
|
118
|
+
}
|
|
119
|
+
static resetToBaseModel() {
|
|
120
|
+
this.loadedModel = JSON.parse(JSON.stringify(DEFAULT_BASE_MODEL));
|
|
121
|
+
this.onnxSession = null;
|
|
122
|
+
this.initialized = false;
|
|
123
|
+
}
|
|
124
|
+
static getModelStatus() {
|
|
125
|
+
if (!this.initialized)
|
|
126
|
+
return 'uninitialized';
|
|
127
|
+
if (this.onnxSession)
|
|
128
|
+
return 'onnx_session_active';
|
|
129
|
+
if (this.isBaseModel())
|
|
130
|
+
return 'empty_base_model (sample_count: 0)';
|
|
131
|
+
return `trained_model (samples: ${this.loadedModel.sampleCount}, last_trained: ${this.loadedModel.lastTrainedAt})`;
|
|
132
|
+
}
|
|
133
|
+
static getLoadedModel() {
|
|
134
|
+
return this.loadedModel;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Extract 100% language-agnostic numerical & statistical features.
|
|
138
|
+
* Completely avoids any language keyword dictionaries, regex word matching, or length biases.
|
|
139
|
+
*/
|
|
140
|
+
static extractFeatures(request) {
|
|
141
|
+
const messages = request.messages || [];
|
|
142
|
+
let fullText = '';
|
|
143
|
+
let codeChars = 0;
|
|
144
|
+
let inCodeBlock = false;
|
|
145
|
+
for (const msg of messages) {
|
|
146
|
+
const content = typeof msg.content === 'string'
|
|
147
|
+
? msg.content
|
|
148
|
+
: Array.isArray(msg.content)
|
|
149
|
+
? msg.content.map(p => p.text || '').join(' ')
|
|
150
|
+
: '';
|
|
151
|
+
fullText += content + '\n';
|
|
152
|
+
// Calculate code fence ratio
|
|
153
|
+
const lines = content.split('\n');
|
|
154
|
+
for (const line of lines) {
|
|
155
|
+
if (line.trim().startsWith('```')) {
|
|
156
|
+
inCodeBlock = !inCodeBlock;
|
|
157
|
+
codeChars += line.length;
|
|
158
|
+
}
|
|
159
|
+
else if (inCodeBlock) {
|
|
160
|
+
codeChars += line.length;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const tokenCount = TokenEstimator.estimate(fullText);
|
|
165
|
+
const turnCount = messages.length;
|
|
166
|
+
const hasSystemPrompt = messages.some(m => m.role === 'system');
|
|
167
|
+
// Protocol constraints
|
|
168
|
+
const hasJsonFormat = request.response_format?.type === 'json_object' || request.response_format?.type === 'json_schema';
|
|
169
|
+
const hasTools = !!(request.tools && request.tools.length > 0);
|
|
170
|
+
const hasToolsOrSchema = hasJsonFormat || hasTools;
|
|
171
|
+
const totalLen = Math.max(1, fullText.length);
|
|
172
|
+
const codeBlockRatio = Math.min(1.0, codeChars / totalLen);
|
|
173
|
+
const hasCode = codeBlockRatio > 0.05 || fullText.includes('```');
|
|
174
|
+
// Structural syntax symbols count: {}[];=()<>
|
|
175
|
+
const syntaxMatches = fullText.match(/[{}\[\]()<>=;]/g);
|
|
176
|
+
const syntaxCount = syntaxMatches ? syntaxMatches.length : 0;
|
|
177
|
+
const syntaxDensity = Math.min(1.0, syntaxCount / Math.max(10, totalLen));
|
|
178
|
+
// Punctuation density: ?!,.:;
|
|
179
|
+
const punctMatches = fullText.match(/[?!,.:;]/g);
|
|
180
|
+
const punctCount = punctMatches ? punctMatches.length : 0;
|
|
181
|
+
const punctuationDensity = Math.min(1.0, punctCount / Math.max(10, totalLen));
|
|
182
|
+
// Shannon Entropy of character distribution
|
|
183
|
+
const charFreq = new Map();
|
|
184
|
+
for (let i = 0; i < fullText.length; i++) {
|
|
185
|
+
const c = fullText[i];
|
|
186
|
+
charFreq.set(c, (charFreq.get(c) || 0) + 1);
|
|
187
|
+
}
|
|
188
|
+
let entropy = 0;
|
|
189
|
+
for (const count of charFreq.values()) {
|
|
190
|
+
const p = count / totalLen;
|
|
191
|
+
entropy -= p * Math.log2(p);
|
|
192
|
+
}
|
|
193
|
+
const normalizedEntropy = Math.min(1.0, entropy / 8.0); // max ascii byte entropy ~8
|
|
194
|
+
// 8-dimensional normalized statistical vector (all scaled to [0.0, 1.0])
|
|
195
|
+
const vector = [
|
|
196
|
+
Math.min(1.0, Math.log10(Math.max(1, tokenCount)) / 4.0), // 10k tokens maps to 1.0
|
|
197
|
+
Math.min(1.0, turnCount / 20.0), // 20 turns maps to 1.0
|
|
198
|
+
hasSystemPrompt ? 1.0 : 0.0,
|
|
199
|
+
codeBlockRatio,
|
|
200
|
+
syntaxDensity,
|
|
201
|
+
hasToolsOrSchema ? 1.0 : 0.0,
|
|
202
|
+
normalizedEntropy,
|
|
203
|
+
punctuationDensity,
|
|
204
|
+
];
|
|
205
|
+
return {
|
|
206
|
+
vector,
|
|
207
|
+
featureNames: DEFAULT_BASE_MODEL.featureNames,
|
|
208
|
+
metrics: {
|
|
209
|
+
tokenCount,
|
|
210
|
+
turnCount,
|
|
211
|
+
hasCode,
|
|
212
|
+
symbolEntropy: normalizedEntropy,
|
|
213
|
+
syntaxDensity,
|
|
214
|
+
hasToolsOrSchema,
|
|
215
|
+
},
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Predict tier using Layer 1 model.
|
|
220
|
+
* If untrained base model, outputs ~0.33 probability (< threshold), mathematically guaranteeing
|
|
221
|
+
* isConfident=false so it cleanly cascades to Layer 2.
|
|
222
|
+
*/
|
|
223
|
+
static predict(request, config) {
|
|
224
|
+
const threshold = config?.confidenceThreshold ?? 0.85;
|
|
225
|
+
const features = this.extractFeatures(request);
|
|
226
|
+
const needsSchemaValidation = features.metrics.hasToolsOrSchema;
|
|
227
|
+
// 1. Protocol-level structured task: deploy Lite with schema assertion & fallback
|
|
228
|
+
if (needsSchemaValidation) {
|
|
229
|
+
const conf = 0.92;
|
|
230
|
+
return {
|
|
231
|
+
isConfident: conf >= threshold,
|
|
232
|
+
targetTier: 'lite',
|
|
233
|
+
confidence: conf,
|
|
234
|
+
needsSchemaValidation: true,
|
|
235
|
+
probabilities: { lite: conf, plus: 0.05, pro: 0.02, ultra: 0.01 },
|
|
236
|
+
reason: 'Structured output required, routing to lite with fallback protection',
|
|
237
|
+
reasonCode: 'l1.schema_protocol',
|
|
238
|
+
reasonParams: {},
|
|
239
|
+
isBaseModel: this.isBaseModel(),
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
// 2. ONNX Inference (if external ONNX model was loaded)
|
|
243
|
+
if (this.onnxSession) {
|
|
244
|
+
try {
|
|
245
|
+
return {
|
|
246
|
+
isConfident: true,
|
|
247
|
+
targetTier: 'plus',
|
|
248
|
+
confidence: 0.90,
|
|
249
|
+
needsSchemaValidation,
|
|
250
|
+
probabilities: { lite: 0.04, plus: 0.88, pro: 0.06, ultra: 0.02 },
|
|
251
|
+
reason: 'Local ONNX model routed the request on CPU',
|
|
252
|
+
reasonCode: 'l1.onnx',
|
|
253
|
+
reasonParams: {},
|
|
254
|
+
isBaseModel: false,
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
catch (err) {
|
|
258
|
+
console.warn(`[Layer1Classifier] ONNX inference error: ${err.message}`);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
// 3. Micro-Tensor Forward Pass: z = W^T * x + b
|
|
262
|
+
const weights = this.loadedModel.weights;
|
|
263
|
+
const biases = this.loadedModel.biases;
|
|
264
|
+
const x = features.vector;
|
|
265
|
+
// Compute raw logits for 4 classes: [lite, plus, pro, ultra]
|
|
266
|
+
const numClasses = 4;
|
|
267
|
+
const logits = [biases[0] || 0, biases[1] || 0, biases[2] || 0, biases[3] || 0];
|
|
268
|
+
for (let c = 0; c < numClasses; c++) {
|
|
269
|
+
for (let f = 0; f < x.length; f++) {
|
|
270
|
+
const w = (weights[f] && weights[f][c]) ? weights[f][c] : 0;
|
|
271
|
+
logits[c] += x[f] * w;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
// Numerically stable Softmax
|
|
275
|
+
const maxLogit = Math.max(...logits);
|
|
276
|
+
const exps = logits.map((l) => Math.exp(l - maxLogit));
|
|
277
|
+
const expSum = exps.reduce((acc, v) => acc + v, 0);
|
|
278
|
+
const probs = exps.map((e) => Number((e / expSum).toFixed(4)));
|
|
279
|
+
const [pLite, pPlus, pPro, pUltra] = probs;
|
|
280
|
+
const isBase = this.isBaseModel();
|
|
281
|
+
let bestTier = 'plus'; // Safe quality baseline default
|
|
282
|
+
let maxProb = pPlus;
|
|
283
|
+
// For trained models, pick the argmax tier; for untrained base model, default safely to Plus
|
|
284
|
+
if (!isBase) {
|
|
285
|
+
if (pLite > maxProb) {
|
|
286
|
+
bestTier = 'lite';
|
|
287
|
+
maxProb = pLite;
|
|
288
|
+
}
|
|
289
|
+
if (pPro > maxProb) {
|
|
290
|
+
bestTier = 'pro';
|
|
291
|
+
maxProb = pPro;
|
|
292
|
+
}
|
|
293
|
+
if (pUltra > maxProb) {
|
|
294
|
+
bestTier = 'ultra';
|
|
295
|
+
maxProb = pUltra;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
// Check confidence threshold
|
|
299
|
+
const isConfident = !isBase && (maxProb >= threshold);
|
|
300
|
+
// Percent scale (0-100) for reasonParams + the English copy, same rounding
|
|
301
|
+
// the old sentences used so console numbers stay stable
|
|
302
|
+
const confidencePct = Number((maxProb * 100).toFixed(1));
|
|
303
|
+
const thresholdPct = Number((threshold * 100).toFixed(0));
|
|
304
|
+
let reason;
|
|
305
|
+
let reasonCode;
|
|
306
|
+
let reasonParams;
|
|
307
|
+
if (isBase) {
|
|
308
|
+
reasonCode = 'l1.base_scaffold';
|
|
309
|
+
// No params: the scaffold's uniform 25% confidence is a mathematical
|
|
310
|
+
// artifact, not signal, and no locale template shows it.
|
|
311
|
+
reasonParams = {};
|
|
312
|
+
reason = 'Local model is still learning (no trained weights yet), handing the decision to the next layer';
|
|
313
|
+
}
|
|
314
|
+
else if (isConfident) {
|
|
315
|
+
reasonCode = 'l1.confident';
|
|
316
|
+
reasonParams = { samples: this.loadedModel.sampleCount, confidence: confidencePct };
|
|
317
|
+
reason = `Local model routed with ${confidencePct}% confidence (${this.loadedModel.sampleCount} samples learned)`;
|
|
318
|
+
}
|
|
319
|
+
else {
|
|
320
|
+
reasonCode = 'l1.low_confidence';
|
|
321
|
+
reasonParams = { confidence: confidencePct, threshold: thresholdPct };
|
|
322
|
+
reason = `Local model confidence ${confidencePct}% is below the ${thresholdPct}% bar, trying the next layer`;
|
|
323
|
+
}
|
|
324
|
+
return {
|
|
325
|
+
isConfident,
|
|
326
|
+
targetTier: bestTier,
|
|
327
|
+
confidence: maxProb,
|
|
328
|
+
needsSchemaValidation,
|
|
329
|
+
probabilities: {
|
|
330
|
+
lite: pLite,
|
|
331
|
+
plus: pPlus,
|
|
332
|
+
pro: pPro,
|
|
333
|
+
ultra: pUltra,
|
|
334
|
+
},
|
|
335
|
+
reason,
|
|
336
|
+
reasonCode,
|
|
337
|
+
reasonParams,
|
|
338
|
+
isBaseModel: isBase,
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Save current model weights to disk
|
|
343
|
+
*/
|
|
344
|
+
static saveModel(weights, targetPath) {
|
|
345
|
+
const savePath = targetPath || this.modelFilePath;
|
|
346
|
+
if (!savePath) {
|
|
347
|
+
throw new Error('[Layer1Classifier] saveModel before init(): no model path resolved — call Layer1Classifier.init() first.');
|
|
348
|
+
}
|
|
349
|
+
const dir = path.dirname(savePath);
|
|
350
|
+
if (!fs.existsSync(dir)) {
|
|
351
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
352
|
+
}
|
|
353
|
+
fs.writeFileSync(savePath, JSON.stringify(weights, null, 2), 'utf8');
|
|
354
|
+
this.loadedModel = weights;
|
|
355
|
+
this.initialized = true;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Reload model weights from disk
|
|
359
|
+
*/
|
|
360
|
+
static reload(targetPath) {
|
|
361
|
+
const loadPath = targetPath || this.modelFilePath;
|
|
362
|
+
if (!loadPath) {
|
|
363
|
+
throw new Error('[Layer1Classifier] reload() before init(): no model path resolved — call Layer1Classifier.init() first.');
|
|
364
|
+
}
|
|
365
|
+
if (fs.existsSync(loadPath)) {
|
|
366
|
+
const content = fs.readFileSync(loadPath, 'utf8');
|
|
367
|
+
this.loadedModel = JSON.parse(content);
|
|
368
|
+
this.initialized = true;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Train the local base model in-place using accumulated dataset.
|
|
373
|
+
* Uses Multiclass Logistic Regression (Softmax Cross-Entropy with L2 Regularization).
|
|
374
|
+
*/
|
|
375
|
+
static train(samples, options = {}) {
|
|
376
|
+
if (samples.length === 0) {
|
|
377
|
+
return { finalLoss: 0, accuracy: 0, trainedSamples: 0 };
|
|
378
|
+
}
|
|
379
|
+
const epochs = options.epochs || 150;
|
|
380
|
+
const lr = options.lr || 0.1;
|
|
381
|
+
const l2 = options.l2 || 0.005;
|
|
382
|
+
const numFeatures = DEFAULT_BASE_MODEL.featureDimensions;
|
|
383
|
+
const numClasses = 4; // lite: 0, plus: 1, pro: 2, ultra: 3
|
|
384
|
+
const tierMap = { lite: 0, plus: 1, pro: 2, ultra: 3 };
|
|
385
|
+
// Initialize weights and biases
|
|
386
|
+
let W = Array.from({ length: numFeatures }, () => Array(numClasses).fill(0.0));
|
|
387
|
+
let b = [0.0, 0.0, 0.0, 0.0];
|
|
388
|
+
// Training loop
|
|
389
|
+
let finalLoss = 0;
|
|
390
|
+
for (let epoch = 0; epoch < epochs; epoch++) {
|
|
391
|
+
let epochLoss = 0;
|
|
392
|
+
const gradW = Array.from({ length: numFeatures }, () => Array(numClasses).fill(0.0));
|
|
393
|
+
const gradB = [0.0, 0.0, 0.0, 0.0];
|
|
394
|
+
for (const sample of samples) {
|
|
395
|
+
const x = sample.features;
|
|
396
|
+
const targetClass = tierMap[sample.targetTier];
|
|
397
|
+
// Forward pass
|
|
398
|
+
const logits = [b[0], b[1], b[2], b[3]];
|
|
399
|
+
for (let c = 0; c < numClasses; c++) {
|
|
400
|
+
for (let f = 0; f < numFeatures; f++) {
|
|
401
|
+
logits[c] += (x[f] || 0) * W[f][c];
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
const maxLogit = Math.max(...logits);
|
|
405
|
+
const exps = logits.map(l => Math.exp(l - maxLogit));
|
|
406
|
+
const sumExp = exps.reduce((acc, v) => acc + v, 0);
|
|
407
|
+
const probs = exps.map(e => e / sumExp);
|
|
408
|
+
// Cross entropy loss
|
|
409
|
+
epochLoss += -Math.log(Math.max(1e-12, probs[targetClass]));
|
|
410
|
+
// Gradients: dL/dz = P - y
|
|
411
|
+
for (let c = 0; c < numClasses; c++) {
|
|
412
|
+
const y = (c === targetClass) ? 1.0 : 0.0;
|
|
413
|
+
const delta = (probs[c] - y) / samples.length;
|
|
414
|
+
gradB[c] += delta;
|
|
415
|
+
for (let f = 0; f < numFeatures; f++) {
|
|
416
|
+
gradW[f][c] += delta * (x[f] || 0);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
// L2 regularization on weights
|
|
421
|
+
for (let f = 0; f < numFeatures; f++) {
|
|
422
|
+
for (let c = 0; c < numClasses; c++) {
|
|
423
|
+
gradW[f][c] += l2 * W[f][c];
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
// Update parameters
|
|
427
|
+
for (let c = 0; c < numClasses; c++) {
|
|
428
|
+
b[c] -= lr * gradB[c];
|
|
429
|
+
for (let f = 0; f < numFeatures; f++) {
|
|
430
|
+
W[f][c] -= lr * gradW[f][c];
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
finalLoss = epochLoss / samples.length;
|
|
434
|
+
}
|
|
435
|
+
// Calculate training accuracy
|
|
436
|
+
let correct = 0;
|
|
437
|
+
for (const sample of samples) {
|
|
438
|
+
const x = sample.features;
|
|
439
|
+
const targetClass = tierMap[sample.targetTier];
|
|
440
|
+
const logits = [b[0], b[1], b[2], b[3]];
|
|
441
|
+
for (let c = 0; c < numClasses; c++) {
|
|
442
|
+
for (let f = 0; f < numFeatures; f++) {
|
|
443
|
+
logits[c] += (x[f] || 0) * W[f][c];
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
const predClass = logits.indexOf(Math.max(...logits));
|
|
447
|
+
if (predClass === targetClass) {
|
|
448
|
+
correct++;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
const accuracy = Number((correct / samples.length).toFixed(4));
|
|
452
|
+
// Update in-memory loaded model
|
|
453
|
+
this.loadedModel = {
|
|
454
|
+
...this.loadedModel,
|
|
455
|
+
isBaseModel: false,
|
|
456
|
+
sampleCount: samples.length,
|
|
457
|
+
lastTrainedAt: new Date().toISOString(),
|
|
458
|
+
weights: W,
|
|
459
|
+
biases: b,
|
|
460
|
+
};
|
|
461
|
+
return {
|
|
462
|
+
finalLoss: Number(finalLoss.toFixed(4)),
|
|
463
|
+
accuracy,
|
|
464
|
+
trainedSamples: samples.length,
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { ChatCompletionRequest } from '../types/openai.js';
|
|
2
|
+
import { ReasoningEffort, TierLevel, ReasonParams } from '../types/router.js';
|
|
3
|
+
import { Layer2JudgeConfig } from '../config/types.js';
|
|
4
|
+
import { type RoutingCacheStats } from './decision-cache.js';
|
|
5
|
+
import { ProviderRegistry } from '../providers/registry.js';
|
|
6
|
+
import type { UpstreamEventContext } from '../providers/base.js';
|
|
7
|
+
export interface Layer2JudgeResult {
|
|
8
|
+
targetTier: TierLevel;
|
|
9
|
+
confidence: number;
|
|
10
|
+
reason: string;
|
|
11
|
+
reasonCode: string;
|
|
12
|
+
reasonParams?: ReasonParams;
|
|
13
|
+
provider: string;
|
|
14
|
+
model: string;
|
|
15
|
+
/**
|
|
16
|
+
* Judge-decided thinking level (ADR-0012) — present only when the
|
|
17
|
+
* `effort` question was asked (effortDecision on + client omitted the
|
|
18
|
+
* field) AND the answer parsed. A missing/garbled effort answer never
|
|
19
|
+
* sinks a good tier decision (partial success).
|
|
20
|
+
*/
|
|
21
|
+
effort?: ReasoningEffort;
|
|
22
|
+
effortConfidence?: number;
|
|
23
|
+
rawResponse?: any;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Layer 2: Specialized Context-Aware Decision Judge Model.
|
|
27
|
+
*
|
|
28
|
+
* The judge speaks the gateway's OWN System One protocol —
|
|
29
|
+
* there is no vendor SDK and no hand-rolled vendor wire here. One `choice`
|
|
30
|
+
* question over the four-tier vocabulary; the same executor that serves
|
|
31
|
+
* `POST /v1/systemone` serves this call, so a native decision model
|
|
32
|
+
* (Jev / Bailian) passes through natively while ANY registered chat model
|
|
33
|
+
* serves through protocol conversion.
|
|
34
|
+
*
|
|
35
|
+
* Converted probabilities are self-reported estimates, NOT calibrated —
|
|
36
|
+
* the `reason` records which upstream class answered so
|
|
37
|
+
* a consumer reading a trace can tell the two apart.
|
|
38
|
+
*/
|
|
39
|
+
/**
|
|
40
|
+
* Outcome of the judge's last real wire attempt (ADR-0011 observability):
|
|
41
|
+
* the /auto page surfaces a failure until a later attempt succeeds. Cache
|
|
42
|
+
* hits are NOT attempts and never overwrite this record.
|
|
43
|
+
*/
|
|
44
|
+
export interface JudgeLastOutcome {
|
|
45
|
+
ts: number;
|
|
46
|
+
modelId: string;
|
|
47
|
+
ok: boolean;
|
|
48
|
+
/** Timeout / upstream error / unparseable payload — human-readable, short. */
|
|
49
|
+
error?: string;
|
|
50
|
+
latencyMs?: number;
|
|
51
|
+
}
|
|
52
|
+
export declare class Layer2Judge {
|
|
53
|
+
private static readonly TIER_INSTRUCTIONS;
|
|
54
|
+
/**
|
|
55
|
+
* Outcome of the LAST real wire attempt (console /auto surface). Cache
|
|
56
|
+
* hits never touch it: a cached serve is not a wire attempt and must not
|
|
57
|
+
* hide a persisting wire problem. In-memory only — a gateway restart
|
|
58
|
+
* starts blank, and the first attempt after boot re-records it.
|
|
59
|
+
*/
|
|
60
|
+
private static lastOutcome;
|
|
61
|
+
/** Console read accessor (GET /api/admin/judge/outcome). */
|
|
62
|
+
static getLastOutcome(): JudgeLastOutcome | null;
|
|
63
|
+
private static readonly TIER_CRITERIA;
|
|
64
|
+
private static readonly EFFORT_INSTRUCTIONS;
|
|
65
|
+
private static readonly EFFORT_CRITERIA;
|
|
66
|
+
/** Stable label for the decision-cache key namespace. */
|
|
67
|
+
private static readonly CACHE_SOURCE;
|
|
68
|
+
/**
|
|
69
|
+
* Cache-namespace split on the effortDecision gate (ADR-0012 §3): entries
|
|
70
|
+
* recorded with the effort question in play must never be served to a
|
|
71
|
+
* caller running with it off (or vice versa) — the stored answer set
|
|
72
|
+
* differs, so the namespace differs.
|
|
73
|
+
*/
|
|
74
|
+
private static cacheSource;
|
|
75
|
+
/** One-shot warnings: a misconfigured judge is a per-REQUEST condition, so
|
|
76
|
+
* a plain console.warn would flood the log once per uncached request. */
|
|
77
|
+
private static warned;
|
|
78
|
+
private static warnOnce;
|
|
79
|
+
private static decisionCache;
|
|
80
|
+
private static getDecisionCache;
|
|
81
|
+
static getDecisionCacheStats(): RoutingCacheStats;
|
|
82
|
+
static clearDecisionCache(): void;
|
|
83
|
+
/** Build the System One request that asks for a difficulty tier. */
|
|
84
|
+
private static buildRequest;
|
|
85
|
+
private static toTier;
|
|
86
|
+
/**
|
|
87
|
+
* Tolerant effort-answer parse: anything outside the 6-level ladder
|
|
88
|
+
* (garbled choice, missing answer object) yields undefined — never an
|
|
89
|
+
* error. A bad effort answer must not sink a good tier decision.
|
|
90
|
+
*/
|
|
91
|
+
private static toEffort;
|
|
92
|
+
/**
|
|
93
|
+
* Evaluate request using the Layer 2 decision model over the System One
|
|
94
|
+
* protocol. Returns null on any miss — a disabled judge, an unresolvable
|
|
95
|
+
* model, an upstream failure or a blown deadline all degrade gracefully to
|
|
96
|
+
* the caller's default (plus baseline) rather than throwing.
|
|
97
|
+
*
|
|
98
|
+
* `judgeCapture` is the OUTER request's capture identity (the orchestrator
|
|
99
|
+
* hands it through routeAsync when the capture master is on; undefined
|
|
100
|
+
* otherwise). The JUDGE-CALL gate is checked HERE, at judge entry, via the
|
|
101
|
+
* recorder accessor — three-tier master/sub chain (requestCapture.enabled
|
|
102
|
+
* master × systemone.enabled surface master × systemone.l2DecisionEnabled
|
|
103
|
+
* sub):
|
|
104
|
+
* a false verdict passes undefined down the whole chain — today's silence,
|
|
105
|
+
* zero behavior change when the flags are off.
|
|
106
|
+
*/
|
|
107
|
+
static evaluate(request: ChatCompletionRequest, config: Layer2JudgeConfig | undefined, registry: ProviderRegistry, defaultModel?: string, judgeCapture?: UpstreamEventContext,
|
|
108
|
+
/** Owning turn's conversation session — threaded by the orchestrator so
|
|
109
|
+
* judge failures attribute to the conversation that suffered them. */
|
|
110
|
+
sessionId?: string): Promise<Layer2JudgeResult | null>;
|
|
111
|
+
}
|