opencode-model-router 1.1.16 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -0
- package/package.json +12 -2
- package/src/escalate/ladder.ts +201 -0
- package/src/guard/enforce.ts +135 -0
- package/src/guard/fingerprint.ts +16 -0
- package/src/guard/guards.ts +343 -0
- package/src/guard/narration.ts +34 -0
- package/src/guard/scrub.ts +26 -0
- package/src/guard/store.ts +39 -0
- package/src/index.ts +620 -749
- package/src/router/config.ts +480 -0
- package/src/router/enforcement.ts +53 -0
- package/src/router/protocol.ts +306 -0
- package/src/router/sessions.ts +268 -0
- package/src/telemetry/trajectory.ts +180 -0
- package/src/verify/checker.ts +224 -0
- package/src/verify/deterministic.ts +319 -0
- package/src/verify/dispatch.ts +162 -0
- package/src/verify/dod.ts +274 -0
- package/src/verify/gate.ts +166 -0
- package/src/verify/types.ts +49 -0
- package/tiers.json +9 -9
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
// ---------------------------------------------------------------------------
|
|
7
|
+
// Types
|
|
8
|
+
// ---------------------------------------------------------------------------
|
|
9
|
+
|
|
10
|
+
export interface ThinkingConfig {
|
|
11
|
+
budgetTokens?: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface ReasoningConfig {
|
|
15
|
+
effort?: "low" | "medium" | "high";
|
|
16
|
+
summary?: "auto" | "always" | "never";
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface TierConfig {
|
|
20
|
+
model: string;
|
|
21
|
+
variant?: string;
|
|
22
|
+
thinking?: ThinkingConfig;
|
|
23
|
+
reasoning?: ReasoningConfig;
|
|
24
|
+
costRatio?: number;
|
|
25
|
+
color?: string;
|
|
26
|
+
description: string;
|
|
27
|
+
steps?: number;
|
|
28
|
+
prompt?: string;
|
|
29
|
+
whenToUse: string[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type Preset = Record<string, TierConfig>;
|
|
33
|
+
|
|
34
|
+
export interface FallbackConfig {
|
|
35
|
+
global?: Record<string, string[]>;
|
|
36
|
+
presets?: Record<string, Record<string, string[]>>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface ModeConfig {
|
|
40
|
+
defaultTier: string;
|
|
41
|
+
description: string;
|
|
42
|
+
overrideRules?: string[];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface EnforcementConfig {
|
|
46
|
+
mode?: "off" | "advisory" | "enforced";
|
|
47
|
+
envGate?: string;
|
|
48
|
+
perTier?: Record<string, "off" | "advisory" | "enforced">;
|
|
49
|
+
guard?: { readDraftCap?: number; sameOpRetryCap?: number; blockSelfScript?: boolean; deliverableFirst?: boolean; budget?: number; blockScriptWrites?: boolean };
|
|
50
|
+
verify?: { require?: "never" | "whenDoDPresent" | "always"; requireExplicitDoD?: boolean; preferDeterministic?: boolean; graderPolicy?: "atLeastProducerTier"; graderTemperature?: number; minGraderTier?: string };
|
|
51
|
+
escalate?: { floorTier?: string | null; ladder?: string[]; maxAttemptsPerTier?: number; maxTotalAttempts?: number; costCeiling?: { base?: string; multiple?: number } };
|
|
52
|
+
proportional?: { trivialBypass?: boolean; trivialClassifier?: string };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface RouterConfig {
|
|
56
|
+
activePreset: string;
|
|
57
|
+
activeMode?: string;
|
|
58
|
+
presets: Record<string, Preset>;
|
|
59
|
+
rules: string[];
|
|
60
|
+
defaultTier: string;
|
|
61
|
+
fallback?: FallbackConfig;
|
|
62
|
+
taskPatterns?: Record<string, string[]>;
|
|
63
|
+
modes?: Record<string, ModeConfig>;
|
|
64
|
+
/** Global default prompts per tier name. A preset-level tier.prompt overrides this. */
|
|
65
|
+
tierPrompts?: Record<string, string>;
|
|
66
|
+
/** Read-only tool-call caps per tier, enforced at runtime via tool.execute.after banner injection. */
|
|
67
|
+
tierCaps?: Record<string, number>;
|
|
68
|
+
enforcement?: EnforcementConfig;
|
|
69
|
+
/** Experimental, opt-in features. Off by default. */
|
|
70
|
+
experimental?: { verifiedDelegateTool?: boolean };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface RouterState {
|
|
74
|
+
activePreset?: string;
|
|
75
|
+
activeMode?: string;
|
|
76
|
+
enforcementMode?: "off" | "advisory" | "enforced";
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ---------------------------------------------------------------------------
|
|
80
|
+
// Config loader with caching
|
|
81
|
+
// ---------------------------------------------------------------------------
|
|
82
|
+
|
|
83
|
+
let _cachedConfig: RouterConfig | null = null;
|
|
84
|
+
let _configDirty = true;
|
|
85
|
+
|
|
86
|
+
/** Mark config cache as stale so it is re-read on next access. */
|
|
87
|
+
export function invalidateConfigCache(): void {
|
|
88
|
+
_configDirty = true;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function getPluginRoot(): string {
|
|
92
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
93
|
+
return join(__dirname, "../.."); // src/router/ -> plugin root
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function configPath(): string {
|
|
97
|
+
return join(getPluginRoot(), "tiers.json");
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function statePath(): string {
|
|
101
|
+
return join(
|
|
102
|
+
homedir(),
|
|
103
|
+
".config",
|
|
104
|
+
"opencode",
|
|
105
|
+
"opencode-model-router.state.json",
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function resolvePresetName(
|
|
110
|
+
cfg: RouterConfig,
|
|
111
|
+
requestedPreset: string,
|
|
112
|
+
): string | undefined {
|
|
113
|
+
if (cfg.presets[requestedPreset]) {
|
|
114
|
+
return requestedPreset;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const normalized = requestedPreset.trim().toLowerCase();
|
|
118
|
+
if (!normalized) {
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return Object.keys(cfg.presets).find(
|
|
123
|
+
(name) => name.toLowerCase() === normalized,
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function validateConfig(raw: unknown): RouterConfig {
|
|
128
|
+
if (typeof raw !== "object" || raw === null) {
|
|
129
|
+
throw new Error("tiers.json: expected a JSON object at root");
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const obj = raw as Record<string, unknown>;
|
|
133
|
+
|
|
134
|
+
if (typeof obj.activePreset !== "string" || !obj.activePreset) {
|
|
135
|
+
throw new Error("tiers.json: 'activePreset' must be a non-empty string");
|
|
136
|
+
}
|
|
137
|
+
if (
|
|
138
|
+
typeof obj.presets !== "object" ||
|
|
139
|
+
obj.presets === null ||
|
|
140
|
+
Array.isArray(obj.presets)
|
|
141
|
+
) {
|
|
142
|
+
throw new Error("tiers.json: 'presets' must be a non-null object");
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const presets = obj.presets as Record<string, unknown>;
|
|
146
|
+
for (const [presetName, preset] of Object.entries(presets)) {
|
|
147
|
+
if (
|
|
148
|
+
typeof preset !== "object" ||
|
|
149
|
+
preset === null ||
|
|
150
|
+
Array.isArray(preset)
|
|
151
|
+
) {
|
|
152
|
+
throw new Error(`tiers.json: preset '${presetName}' must be an object`);
|
|
153
|
+
}
|
|
154
|
+
const tiers = preset as Record<string, unknown>;
|
|
155
|
+
for (const [tierName, tier] of Object.entries(tiers)) {
|
|
156
|
+
if (typeof tier !== "object" || tier === null) {
|
|
157
|
+
throw new Error(
|
|
158
|
+
`tiers.json: tier '${presetName}.${tierName}' must be an object`,
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
const t = tier as Record<string, unknown>;
|
|
162
|
+
if (typeof t.model !== "string" || !t.model) {
|
|
163
|
+
throw new Error(
|
|
164
|
+
`tiers.json: '${presetName}.${tierName}.model' must be a non-empty string`,
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
if (typeof t.description !== "string") {
|
|
168
|
+
throw new Error(
|
|
169
|
+
`tiers.json: '${presetName}.${tierName}.description' must be a string`,
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
if (!Array.isArray(t.whenToUse)) {
|
|
173
|
+
throw new Error(
|
|
174
|
+
`tiers.json: '${presetName}.${tierName}.whenToUse' must be an array`,
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (!Array.isArray(obj.rules)) {
|
|
181
|
+
throw new Error("tiers.json: 'rules' must be an array of strings");
|
|
182
|
+
}
|
|
183
|
+
if (typeof obj.defaultTier !== "string") {
|
|
184
|
+
throw new Error("tiers.json: 'defaultTier' must be a string");
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Validate modes if present
|
|
188
|
+
if (obj.modes !== undefined) {
|
|
189
|
+
if (
|
|
190
|
+
typeof obj.modes !== "object" ||
|
|
191
|
+
obj.modes === null ||
|
|
192
|
+
Array.isArray(obj.modes)
|
|
193
|
+
) {
|
|
194
|
+
throw new Error("tiers.json: 'modes' must be an object");
|
|
195
|
+
}
|
|
196
|
+
const modes = obj.modes as Record<string, unknown>;
|
|
197
|
+
for (const [modeName, mode] of Object.entries(modes)) {
|
|
198
|
+
if (typeof mode !== "object" || mode === null) {
|
|
199
|
+
throw new Error(`tiers.json: mode '${modeName}' must be an object`);
|
|
200
|
+
}
|
|
201
|
+
const m = mode as Record<string, unknown>;
|
|
202
|
+
if (typeof m.defaultTier !== "string") {
|
|
203
|
+
throw new Error(
|
|
204
|
+
`tiers.json: mode '${modeName}.defaultTier' must be a string`,
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
if (typeof m.description !== "string") {
|
|
208
|
+
throw new Error(
|
|
209
|
+
`tiers.json: mode '${modeName}.description' must be a string`,
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Validate tierCaps if present
|
|
216
|
+
if (obj.tierCaps !== undefined) {
|
|
217
|
+
if (
|
|
218
|
+
typeof obj.tierCaps !== "object" ||
|
|
219
|
+
obj.tierCaps === null ||
|
|
220
|
+
Array.isArray(obj.tierCaps)
|
|
221
|
+
) {
|
|
222
|
+
throw new Error("tiers.json: 'tierCaps' must be an object");
|
|
223
|
+
}
|
|
224
|
+
const tc = obj.tierCaps as Record<string, unknown>;
|
|
225
|
+
for (const [tierName, cap] of Object.entries(tc)) {
|
|
226
|
+
if (typeof cap !== "number" || !Number.isFinite(cap) || cap < 1) {
|
|
227
|
+
throw new Error(
|
|
228
|
+
`tiers.json: tierCaps.'${tierName}' must be a positive integer`,
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// Validate tierPrompts if present
|
|
235
|
+
if (obj.tierPrompts !== undefined) {
|
|
236
|
+
if (
|
|
237
|
+
typeof obj.tierPrompts !== "object" ||
|
|
238
|
+
obj.tierPrompts === null ||
|
|
239
|
+
Array.isArray(obj.tierPrompts)
|
|
240
|
+
) {
|
|
241
|
+
throw new Error("tiers.json: 'tierPrompts' must be an object");
|
|
242
|
+
}
|
|
243
|
+
const tp = obj.tierPrompts as Record<string, unknown>;
|
|
244
|
+
for (const [tierName, prompt] of Object.entries(tp)) {
|
|
245
|
+
if (typeof prompt !== "string") {
|
|
246
|
+
throw new Error(
|
|
247
|
+
`tiers.json: tierPrompts.'${tierName}' must be a string`,
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// Validate taskPatterns if present
|
|
254
|
+
if (obj.taskPatterns !== undefined) {
|
|
255
|
+
if (
|
|
256
|
+
typeof obj.taskPatterns !== "object" ||
|
|
257
|
+
obj.taskPatterns === null ||
|
|
258
|
+
Array.isArray(obj.taskPatterns)
|
|
259
|
+
) {
|
|
260
|
+
throw new Error("tiers.json: 'taskPatterns' must be an object");
|
|
261
|
+
}
|
|
262
|
+
const tp = obj.taskPatterns as Record<string, unknown>;
|
|
263
|
+
for (const [tierName, patterns] of Object.entries(tp)) {
|
|
264
|
+
if (!Array.isArray(patterns)) {
|
|
265
|
+
throw new Error(
|
|
266
|
+
`tiers.json: taskPatterns.'${tierName}' must be an array of strings`,
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// Validate enforcement if present (optional — absent means no enforcement)
|
|
273
|
+
if (obj.enforcement !== undefined) {
|
|
274
|
+
if (
|
|
275
|
+
typeof obj.enforcement !== "object" ||
|
|
276
|
+
obj.enforcement === null ||
|
|
277
|
+
Array.isArray(obj.enforcement)
|
|
278
|
+
) {
|
|
279
|
+
throw new Error("tiers.json: enforcement must be an object");
|
|
280
|
+
}
|
|
281
|
+
const enforcement = obj.enforcement as Record<string, unknown>;
|
|
282
|
+
if (enforcement.mode !== undefined) {
|
|
283
|
+
if (!["off", "advisory", "enforced"].includes(enforcement.mode as string)) {
|
|
284
|
+
throw new Error(
|
|
285
|
+
"tiers.json: enforcement.mode must be one of off|advisory|enforced",
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
if (
|
|
290
|
+
enforcement.verify !== undefined &&
|
|
291
|
+
typeof enforcement.verify === "object" &&
|
|
292
|
+
enforcement.verify !== null
|
|
293
|
+
) {
|
|
294
|
+
const verify = enforcement.verify as Record<string, unknown>;
|
|
295
|
+
if (
|
|
296
|
+
verify.graderPolicy !== undefined &&
|
|
297
|
+
verify.graderPolicy !== "atLeastProducerTier"
|
|
298
|
+
) {
|
|
299
|
+
throw new Error(
|
|
300
|
+
'tiers.json: enforcement.verify.graderPolicy must be "atLeastProducerTier"',
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
if (
|
|
305
|
+
enforcement.escalate !== undefined &&
|
|
306
|
+
typeof enforcement.escalate === "object" &&
|
|
307
|
+
enforcement.escalate !== null
|
|
308
|
+
) {
|
|
309
|
+
const escalate = enforcement.escalate as Record<string, unknown>;
|
|
310
|
+
if (
|
|
311
|
+
escalate.costCeiling !== undefined &&
|
|
312
|
+
typeof escalate.costCeiling === "object" &&
|
|
313
|
+
escalate.costCeiling !== null
|
|
314
|
+
) {
|
|
315
|
+
const costCeiling = escalate.costCeiling as Record<string, unknown>;
|
|
316
|
+
if (costCeiling.multiple !== undefined) {
|
|
317
|
+
if (
|
|
318
|
+
typeof costCeiling.multiple !== "number" ||
|
|
319
|
+
costCeiling.multiple <= 0
|
|
320
|
+
) {
|
|
321
|
+
throw new Error(
|
|
322
|
+
"tiers.json: enforcement.escalate.costCeiling.multiple must be a number > 0",
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
if (escalate.ladder !== undefined) {
|
|
328
|
+
if (
|
|
329
|
+
!Array.isArray(escalate.ladder) ||
|
|
330
|
+
!escalate.ladder.every((s: unknown) => typeof s === "string")
|
|
331
|
+
) {
|
|
332
|
+
throw new Error(
|
|
333
|
+
"tiers.json: enforcement.escalate.ladder must be an array of strings",
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
if (escalate.maxAttemptsPerTier !== undefined) {
|
|
338
|
+
if (
|
|
339
|
+
typeof escalate.maxAttemptsPerTier !== "number" ||
|
|
340
|
+
!Number.isInteger(escalate.maxAttemptsPerTier) ||
|
|
341
|
+
escalate.maxAttemptsPerTier < 0
|
|
342
|
+
) {
|
|
343
|
+
throw new Error(
|
|
344
|
+
"tiers.json: enforcement.escalate.maxAttemptsPerTier must be an integer >= 0",
|
|
345
|
+
);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
if (escalate.maxTotalAttempts !== undefined) {
|
|
349
|
+
if (
|
|
350
|
+
typeof escalate.maxTotalAttempts !== "number" ||
|
|
351
|
+
!Number.isInteger(escalate.maxTotalAttempts) ||
|
|
352
|
+
escalate.maxTotalAttempts < 1
|
|
353
|
+
) {
|
|
354
|
+
throw new Error(
|
|
355
|
+
"tiers.json: enforcement.escalate.maxTotalAttempts must be an integer >= 1",
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
if (
|
|
360
|
+
escalate.floorTier !== undefined &&
|
|
361
|
+
escalate.floorTier !== null &&
|
|
362
|
+
typeof escalate.floorTier !== "string"
|
|
363
|
+
) {
|
|
364
|
+
throw new Error(
|
|
365
|
+
"tiers.json: enforcement.escalate.floorTier must be a string or null",
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
if (
|
|
370
|
+
enforcement.perTier !== undefined &&
|
|
371
|
+
typeof enforcement.perTier === "object" &&
|
|
372
|
+
enforcement.perTier !== null &&
|
|
373
|
+
!Array.isArray(enforcement.perTier)
|
|
374
|
+
) {
|
|
375
|
+
const perTier = enforcement.perTier as Record<string, unknown>;
|
|
376
|
+
for (const [tierName, tierMode] of Object.entries(perTier)) {
|
|
377
|
+
if (!["off", "advisory", "enforced"].includes(tierMode as string)) {
|
|
378
|
+
throw new Error(
|
|
379
|
+
`tiers.json: enforcement.perTier.${tierName} must be one of off|advisory|enforced`,
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
if (
|
|
385
|
+
enforcement.guard !== undefined &&
|
|
386
|
+
typeof enforcement.guard === "object" &&
|
|
387
|
+
enforcement.guard !== null
|
|
388
|
+
) {
|
|
389
|
+
const guard = enforcement.guard as Record<string, unknown>;
|
|
390
|
+
if (guard.budget !== undefined) {
|
|
391
|
+
if (
|
|
392
|
+
typeof guard.budget !== "number" ||
|
|
393
|
+
!Number.isFinite(guard.budget) ||
|
|
394
|
+
guard.budget < 1
|
|
395
|
+
) {
|
|
396
|
+
throw new Error("enforcement.guard.budget must be a number >= 1");
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
if (guard.blockScriptWrites !== undefined) {
|
|
400
|
+
if (typeof guard.blockScriptWrites !== "boolean") {
|
|
401
|
+
throw new Error("enforcement.guard.blockScriptWrites must be a boolean");
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
return raw as RouterConfig;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
export function loadConfig(): RouterConfig {
|
|
411
|
+
if (_cachedConfig && !_configDirty) {
|
|
412
|
+
return _cachedConfig;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
const raw = JSON.parse(readFileSync(configPath(), "utf-8"));
|
|
416
|
+
const cfg = validateConfig(raw);
|
|
417
|
+
|
|
418
|
+
try {
|
|
419
|
+
if (existsSync(statePath())) {
|
|
420
|
+
const state = JSON.parse(
|
|
421
|
+
readFileSync(statePath(), "utf-8"),
|
|
422
|
+
) as RouterState;
|
|
423
|
+
if (state.activePreset) {
|
|
424
|
+
const resolved = resolvePresetName(cfg, state.activePreset);
|
|
425
|
+
if (resolved) {
|
|
426
|
+
cfg.activePreset = resolved;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
if (state.activeMode && cfg.modes?.[state.activeMode]) {
|
|
430
|
+
cfg.activeMode = state.activeMode;
|
|
431
|
+
}
|
|
432
|
+
if (state.enforcementMode) {
|
|
433
|
+
cfg.enforcement = { ...(cfg.enforcement ?? {}), mode: state.enforcementMode };
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
} catch {
|
|
437
|
+
// Ignore state read errors and keep tiers.json defaults
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
_cachedConfig = cfg;
|
|
441
|
+
_configDirty = false;
|
|
442
|
+
return cfg;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// ---------------------------------------------------------------------------
|
|
446
|
+
// State persistence helpers
|
|
447
|
+
// ---------------------------------------------------------------------------
|
|
448
|
+
|
|
449
|
+
/** Read current persisted state (or empty object on failure). */
|
|
450
|
+
export function readState(): RouterState {
|
|
451
|
+
try {
|
|
452
|
+
if (existsSync(statePath())) {
|
|
453
|
+
return JSON.parse(readFileSync(statePath(), "utf-8")) as RouterState;
|
|
454
|
+
}
|
|
455
|
+
} catch {
|
|
456
|
+
// ignore
|
|
457
|
+
}
|
|
458
|
+
return {};
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** Write state to disk atomically (merges with existing keys). */
|
|
462
|
+
export function writeState(patch: Partial<RouterState>): void {
|
|
463
|
+
const state = { ...readState(), ...patch };
|
|
464
|
+
const p = statePath();
|
|
465
|
+
mkdirSync(dirname(p), { recursive: true });
|
|
466
|
+
const tmp = `${p}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
467
|
+
writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", "utf-8");
|
|
468
|
+
renameSync(tmp, p);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// ---------------------------------------------------------------------------
|
|
472
|
+
// Enforcement helpers
|
|
473
|
+
// ---------------------------------------------------------------------------
|
|
474
|
+
|
|
475
|
+
/** Returns the effective enforcement mode. Missing enforcement ⇒ mode:"advisory". */
|
|
476
|
+
export function normalizeEnforcement(
|
|
477
|
+
e: EnforcementConfig | undefined,
|
|
478
|
+
): { mode: "off" | "advisory" | "enforced" } {
|
|
479
|
+
return { mode: e?.mode ?? "advisory" };
|
|
480
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// Enforcement-mode resolver — pure module, no fs/network/SDK/process.env
|
|
3
|
+
// ---------------------------------------------------------------------------
|
|
4
|
+
|
|
5
|
+
import type { RouterConfig } from "./config";
|
|
6
|
+
|
|
7
|
+
export type EnforcementMode = "off" | "advisory" | "enforced";
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_ENV_GATE = "MODEL_ROUTER_ENFORCE";
|
|
10
|
+
|
|
11
|
+
export function resolveEnforcementMode(args: {
|
|
12
|
+
config: RouterConfig | undefined;
|
|
13
|
+
tier?: string;
|
|
14
|
+
env?: Record<string, string | undefined>;
|
|
15
|
+
}): { mode: EnforcementMode; warning?: string } {
|
|
16
|
+
const enf = args.config?.enforcement;
|
|
17
|
+
const gateName = enf?.envGate ?? DEFAULT_ENV_GATE;
|
|
18
|
+
const raw = args.env?.[gateName];
|
|
19
|
+
|
|
20
|
+
// Env gate overrides — highest priority
|
|
21
|
+
if (raw === "1") {
|
|
22
|
+
return { mode: "enforced" };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (raw === "0") {
|
|
26
|
+
return { mode: "off" };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Unrecognized (non-empty, non-undefined) env value → fall through + warn
|
|
30
|
+
let warning: string | undefined;
|
|
31
|
+
if (raw !== undefined && raw !== "") {
|
|
32
|
+
warning = `${gateName}="${raw}" is not "1" or "0"; ignoring env gate and using config.`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Config resolution
|
|
36
|
+
const base: EnforcementMode = enf?.mode ?? "advisory";
|
|
37
|
+
let mode: EnforcementMode;
|
|
38
|
+
|
|
39
|
+
if (
|
|
40
|
+
args.tier !== undefined &&
|
|
41
|
+
enf?.perTier?.[args.tier] !== undefined
|
|
42
|
+
) {
|
|
43
|
+
mode = enf.perTier[args.tier]!;
|
|
44
|
+
} else {
|
|
45
|
+
mode = base;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (warning !== undefined) {
|
|
49
|
+
return { mode, warning };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return { mode };
|
|
53
|
+
}
|