opencode-model-router 2.0.0 → 2.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.
@@ -4,10 +4,11 @@ import {
4
4
  readFileSync,
5
5
  realpathSync,
6
6
  renameSync,
7
+ statSync,
7
8
  writeFileSync,
8
9
  } from "node:fs";
9
10
  import { availableParallelism, homedir } from "node:os";
10
- import { dirname, join } from "node:path";
11
+ import { dirname, join, resolve as resolvePath } from "node:path";
11
12
  import { fileURLToPath } from "node:url";
12
13
  import { parseJsonc } from "./jsonc";
13
14
  import type { DelegateInstructionsPolicy } from "./instructions";
@@ -37,8 +38,9 @@ export interface ReasoningConfig {
37
38
  * Provider-agnostic reasoning effort for a tier.
38
39
  *
39
40
  * `xhigh` and `max` exist because Anthropic's adaptive models accept them;
40
- * OpenAI's `reasoning_effort` stops at `high`, so the registration path
41
- * downgrades those two with a warning (see `src/router/agent-options.ts`).
41
+ * OpenAI's reasoning effort parameter (`reasoningEffort`) stops at `high`, so
42
+ * the registration path downgrades those two with a warning (see
43
+ * `src/router/agent-options.ts`).
42
44
  */
43
45
  export const EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"] as const;
44
46
 
@@ -121,6 +123,8 @@ export interface ModeConfig {
121
123
 
122
124
  export interface EnforcementConfig {
123
125
  mode?: "off" | "advisory" | "enforced";
126
+ /** Default 1; warned in "advisory" mode (bundled default), refused in "enforced" mode, ignored in "off"; null disables. */
127
+ maxDelegationDepth?: number | null;
124
128
  envGate?: string;
125
129
  perTier?: Record<string, "off" | "advisory" | "enforced">;
126
130
  guard?: { readDraftCap?: number; sameOpRetryCap?: number; blockSelfScript?: boolean; deliverableFirst?: boolean; budget?: number; blockScriptWrites?: boolean };
@@ -167,7 +171,11 @@ export interface EnforcementConfig {
167
171
  failureRecheck?: boolean;
168
172
  /** Budget for the reference re-run, in ms (integer >= 1). Default 60000. */
169
173
  recheckTimeoutMs?: number };
170
- escalate?: { floorTier?: string | null; ladder?: string[]; maxAttemptsPerTier?: number; maxTotalAttempts?: number; costCeiling?: { base?: string; multiple?: number } };
174
+ escalate?: { floorTier?: string | null; ladder?: string[]; maxAttemptsPerTier?: number; maxTotalAttempts?: number; costCeiling?: { base?: string; multiple?: number };
175
+ /** Bump reasoning effort before escalating tiers. Default true. */
176
+ effortBump?: boolean;
177
+ /** Maximum reasoning effort for a bump. Default "xhigh". */
178
+ effortBumpMax?: EffortLevel };
171
179
  proportional?: { trivialBypass?: boolean; trivialClassifier?: string };
172
180
  }
173
181
 
@@ -257,12 +265,82 @@ export interface RouterState {
257
265
  // Config loader with caching
258
266
  // ---------------------------------------------------------------------------
259
267
 
260
- let _cachedConfig: RouterConfig | null = null;
261
- let _configDirty = true;
268
+ /**
269
+ * Cache state for one project directory. Hosts such as OpenCode v2 run one
270
+ * plugin instance per project directory inside a single process, so the cache
271
+ * cannot be a single module-level slot: each directory has its own project
272
+ * override file and therefore its own config, fingerprint and last-good state.
273
+ */
274
+ interface ConfigCacheEntry {
275
+ config: RouterConfig | null;
276
+ dirty: boolean;
277
+ fingerprint: string;
278
+ /** Source locations (paths only, no mtimes) that produced `config`. */
279
+ sourceKey: string;
280
+ /** Sources that were already failing when `config` was built (tolerated). */
281
+ tolerated: Set<string>;
282
+ /** Last hot-reload failure (null when the most recent rebuild succeeded). */
283
+ reloadError: string | null;
284
+ /** Fingerprint a reload-failure warning was last emitted for (warn once each). */
285
+ warnedFingerprint: string | null;
286
+ }
287
+
288
+ /** Keyed by {@link normalizeProjectDir}. */
289
+ const _configCaches = new Map<string, ConfigCacheEntry>();
290
+
291
+ function getCacheEntry(key: string): ConfigCacheEntry {
292
+ let entry = _configCaches.get(key);
293
+ if (!entry) {
294
+ entry = {
295
+ config: null,
296
+ dirty: true,
297
+ fingerprint: "",
298
+ sourceKey: "",
299
+ tolerated: new Set<string>(),
300
+ reloadError: null,
301
+ warnedFingerprint: null,
302
+ };
303
+ _configCaches.set(key, entry);
304
+ }
305
+ return entry;
306
+ }
307
+
308
+ /**
309
+ * `realpathSync` that fails soft: an unresolvable path is used as-is, which is
310
+ * no worse than not resolving at all.
311
+ */
312
+ function realpathOrSelf(p: string): string {
313
+ try {
314
+ return realpathSync(p);
315
+ } catch {
316
+ return p;
317
+ }
318
+ }
319
+
320
+ /**
321
+ * Canonical form of a project directory: absolute and symlink-resolved, so the
322
+ * same directory reached through different spellings shares one cache entry
323
+ * and compares equal to the (resolved) home directory. A missing or empty `dir`
324
+ * means "the process working directory at call time".
325
+ */
326
+ function normalizeProjectDir(dir?: string): string {
327
+ return realpathOrSelf(dir ? resolvePath(dir) : process.cwd());
328
+ }
329
+
330
+ /**
331
+ * Why the last config rebuild failed for `dir` (default: the working
332
+ * directory), or null when it succeeded. When a source (tiers.json, an
333
+ * overrides file, or the state file) becomes invalid after a successful load,
334
+ * loadConfig() keeps serving the last valid config and records the reason here
335
+ * instead of throwing or silently dropping layers.
336
+ */
337
+ export function getConfigReloadError(dir?: string): string | null {
338
+ return _configCaches.get(normalizeProjectDir(dir))?.reloadError ?? null;
339
+ }
262
340
 
263
- /** Mark config cache as stale so it is re-read on next access. */
341
+ /** Mark every directory's config cache as stale so it is re-read on next access. */
264
342
  export function invalidateConfigCache(): void {
265
- _configDirty = true;
343
+ for (const entry of _configCaches.values()) entry.dirty = true;
266
344
  }
267
345
 
268
346
  function getPluginRoot(): string {
@@ -286,17 +364,17 @@ export function overridePath(): string {
286
364
 
287
365
  /**
288
366
  * Default location of the project-local overrides file
289
- * (`.opencode/opencode-model-router.overrides.jsonc` in the current working
290
- * directory). This is the path to *create* the file at; the actual lookup walks
291
- * upward — see {@link findProjectOverride}. Used for display when no project
292
- * file is found.
367
+ * (`.opencode/opencode-model-router.overrides.jsonc` in the project directory,
368
+ * or in the current working directory when `dir` is omitted). This is the path
369
+ * to *create* the file at; the actual lookup walks upward — see
370
+ * {@link findProjectOverride}. Used for display when no project file is found.
293
371
  *
294
372
  * The project file is deep-merged *after* (and therefore wins over) the global
295
373
  * overrides file, so a team can commit a shared file that unifies routing for
296
374
  * the project on top of each member's personal global file.
297
375
  */
298
- export function localOverridePath(): string {
299
- return join(process.cwd(), ".opencode", OVERRIDE_FILENAME);
376
+ export function localOverridePath(dir?: string): string {
377
+ return join(dir ? resolvePath(dir) : process.cwd(), ".opencode", OVERRIDE_FILENAME);
300
378
  }
301
379
 
302
380
  /**
@@ -316,10 +394,54 @@ const REPO_MARKERS = [".git", ".hg", ".svn"] as const;
316
394
  */
317
395
  const MAX_WALK_DEPTH = 16;
318
396
 
397
+ /** errno code of a thrown fs error, or "UNKNOWN" when it carries none. */
398
+ function errnoCode(err: unknown): string {
399
+ const code = (err as NodeJS.ErrnoException | undefined)?.code;
400
+ return typeof code === "string" ? code : "UNKNOWN";
401
+ }
402
+
403
+ /**
404
+ * ENOENT (nothing there) and ENOTDIR (a path component is a file) both mean the
405
+ * path is gone. Every other errno (EACCES, EIO, ELOOP, …) means "cannot tell",
406
+ * which is NOT the same as "removed".
407
+ */
408
+ function isGoneError(err: unknown): boolean {
409
+ const code = errnoCode(err);
410
+ return code === "ENOENT" || code === "ENOTDIR";
411
+ }
412
+
413
+ /** A stat that failed for a reason other than the path being gone. */
414
+ interface StatFailure {
415
+ code: string;
416
+ message: string;
417
+ }
418
+
319
419
  /**
320
- * Locate the project-local overrides file by walking upward from the current
321
- * working directory, so the project config is found even when opencode is
322
- * launched from a subdirectory.
420
+ * Outcome of looking at a config source: it is there, it is definitely gone, or
421
+ * it could not be inspected. Unlike `existsSync` — which folds every error into
422
+ * `false` — this keeps "removed" and "unreachable" apart, so a transient I/O
423
+ * error or a directory that lost search permission is never mistaken for the
424
+ * user deleting the file.
425
+ */
426
+ type StatKind = "present" | "missing" | StatFailure;
427
+
428
+ function statKind(p: string): StatKind {
429
+ try {
430
+ statSync(p);
431
+ return "present";
432
+ } catch (err) {
433
+ if (isGoneError(err)) return "missing";
434
+ return { code: errnoCode(err), message: (err as Error).message };
435
+ }
436
+ }
437
+
438
+ /**
439
+ * Locate the project-local overrides file by walking upward from `dir` (the
440
+ * host-provided project directory), so the project config is found even when
441
+ * opencode is launched from a subdirectory. When `dir` is omitted the walk
442
+ * starts at the process working directory; hosts that change the working
443
+ * directory away from the project (OpenCode v2 server mode chdirs to $HOME)
444
+ * must pass the project directory explicitly.
323
445
  *
324
446
  * The walk stops at the first of these, whichever comes first:
325
447
  * - an ancestor containing a repo marker (`.git`, `.hg`, `.svn`), after
@@ -333,28 +455,34 @@ const MAX_WALK_DEPTH = 16;
333
455
  * tree with no repo marker anywhere would otherwise be walked all the way to the
334
456
  * filesystem root, silently adopting an unrelated ancestor's override file.
335
457
  * Returns the resolved path, or undefined when no file applies.
458
+ *
459
+ * Only ENOENT/ENOTDIR count as "no file here". A candidate that cannot be
460
+ * inspected for any other reason (EACCES on a parent directory, a transient
461
+ * I/O error) is still returned and ends the walk — the nearest override wins,
462
+ * so it must not be skipped in favour of an ancestor's file — and the later
463
+ * read reports it as a failure instead of the source silently vanishing. A
464
+ * repo marker that cannot be inspected is likewise treated as present, so the
465
+ * walk never climbs past a project root it merely failed to stat.
336
466
  */
337
- export function findProjectOverride(): string | undefined {
467
+ export function findProjectOverride(dir?: string): string | undefined {
468
+ return walkForProjectOverride(normalizeProjectDir(dir));
469
+ }
470
+
471
+ /** `startDir` must already be normalized (see {@link normalizeProjectDir}). */
472
+ function walkForProjectOverride(startDir: string): string | undefined {
338
473
  // Both sides of the $HOME comparison below have to be resolved the same way.
339
474
  // process.cwd() returns a realpath, while homedir() returns $HOME verbatim, so
340
475
  // on any system where $HOME contains a symlinked component (macOS temp dirs,
341
476
  // containers, some NFS homes) a raw string compare never matches and the home
342
- // boundary silently stops applying. Fail soft: an unresolvable path is used
343
- // as-is, which is no worse than not comparing at all.
344
- const resolve = (p: string): string => {
345
- try {
346
- return realpathSync(p);
347
- } catch {
348
- return p;
349
- }
350
- };
351
-
352
- let dir = resolve(process.cwd());
353
- const home = resolve(homedir());
477
+ // boundary silently stops applying. A host-provided project directory gets
478
+ // the same treatment (normalizeProjectDir). Fail soft: an unresolvable path
479
+ // is used as-is, which is no worse than not comparing at all.
480
+ let dir = startDir;
481
+ const home = realpathOrSelf(homedir());
354
482
  let depth = 0;
355
483
 
356
484
  for (;;) {
357
- const hasMarker = REPO_MARKERS.some((m) => existsSync(join(dir, m)));
485
+ const hasMarker = REPO_MARKERS.some((m) => statKind(join(dir, m)) !== "missing");
358
486
 
359
487
  // $HOME is not a project directory. Only look inside it when it is itself a
360
488
  // repo root (a dotfiles repo), otherwise `~/.opencode/…` would be picked up
@@ -362,7 +490,7 @@ export function findProjectOverride(): string | undefined {
362
490
  if (dir === home && !hasMarker) return undefined;
363
491
 
364
492
  const candidate = join(dir, ".opencode", OVERRIDE_FILENAME);
365
- if (existsSync(candidate)) return candidate;
493
+ if (statKind(candidate) !== "missing") return candidate;
366
494
 
367
495
  if (hasMarker) return undefined; // reached the project root, no file
368
496
  if (dir === home) return undefined; // home was a repo root; never go above it
@@ -710,13 +838,86 @@ function validateTaskPatterns(obj: Record<string, unknown>): void {
710
838
  */
711
839
  const MAX_TIMER_MS = 2_147_483_647;
712
840
 
713
- function validateEnforcement(obj: Record<string, unknown>): void {
841
+ /**
842
+ * Equals the depth tracker's MAX_DEPTH_HOPS (src/router/depth.ts, Phase 1.2),
843
+ * so a cycle or over-long chain counted as 32 is refused under every configured limit.
844
+ */
845
+ export const MAX_DELEGATION_DEPTH_LIMIT = 32;
846
+
847
+ /** Total, typed and bounded rendering of an invalid config value. */
848
+ function describeValue(value: unknown): string {
849
+ let description: string;
850
+ try {
851
+ if (typeof value === "string") description = JSON.stringify(value);
852
+ else if (typeof value === "number") description = Object.is(value, -0) ? "-0" : String(value);
853
+ else if (typeof value === "bigint") description = `${value}n`;
854
+ else if (value === null) description = "null";
855
+ else if (typeof value === "object") {
856
+ const tag = Array.isArray(value) ? "array" : "object";
857
+ description = `${tag} ${JSON.stringify(value) ?? "<unserializable>"}`;
858
+ } else if (typeof value === "function") description = "<function>";
859
+ else description = String(value);
860
+ } catch {
861
+ description = `<${typeof value}>`;
862
+ }
863
+ if (description.length <= 80) return description;
864
+ // Keep the 80-code-unit bound without splitting a surrogate pair.
865
+ const end = /[\uD800-\uDBFF]/.test(description[78]!) && /[\uDC00-\uDFFF]/.test(description[79]!) ? 78 : 79;
866
+ return `${description.slice(0, end)}…`;
867
+ }
868
+
869
+ /** Copy without invoking accessors again; include defined get-only Proxy values. */
870
+ function withValidatedSnapshots<T extends object>(
871
+ obj: T,
872
+ snapshots: Record<string, unknown>,
873
+ ): T {
874
+ const descriptors: Record<string, PropertyDescriptor> = Object.getOwnPropertyDescriptors(obj);
875
+ let changed = false;
876
+ for (const [key, value] of Object.entries(snapshots)) {
877
+ if (value !== undefined || Object.hasOwn(descriptors, key) || key in obj) {
878
+ descriptors[key] = { value, writable: true, enumerable: true, configurable: true };
879
+ changed = true;
880
+ }
881
+ }
882
+ if (!changed) return obj;
883
+ // Keep inherited config values and array identity, not just own descriptors.
884
+ const copy: object = Array.isArray(obj) ? [] : Object.create(Object.getPrototypeOf(obj));
885
+ if (Array.isArray(obj)) Object.setPrototypeOf(copy, Object.getPrototypeOf(obj));
886
+ Object.defineProperties(copy, descriptors);
887
+ if (Object.isFrozen(obj)) Object.freeze(copy);
888
+ return copy as T;
889
+ }
890
+
891
+ /** Reject keys that could reparent a later Object.assign copy. */
892
+ function rejectPrototypeKeys(obj: object, path: string): void {
893
+ for (const key of ["__proto__", "constructor", "prototype"] as const) {
894
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
895
+ throw new Error(`tiers.json: ${path} must not contain the key "${key}"`);
896
+ }
897
+ }
898
+ }
899
+
900
+ function validateEnforcement(value: unknown): Record<string, unknown> | undefined {
714
901
  // Validate enforcement if present (optional — absent means no enforcement)
715
- if (obj.enforcement !== undefined) {
716
- if (!isPlainObject(obj.enforcement)) {
902
+ if (value !== undefined) {
903
+ if (!isPlainObject(value)) {
717
904
  throw new Error("tiers.json: enforcement must be an object");
718
905
  }
719
- const enforcement = obj.enforcement as Record<string, unknown>;
906
+ const enforcement = value as Record<string, unknown>;
907
+ rejectPrototypeKeys(enforcement, "enforcement");
908
+ const maxDelegationDepth = enforcement.maxDelegationDepth;
909
+ if (
910
+ maxDelegationDepth !== undefined &&
911
+ maxDelegationDepth !== null &&
912
+ (typeof maxDelegationDepth !== "number" ||
913
+ !Number.isSafeInteger(maxDelegationDepth) ||
914
+ maxDelegationDepth < 1 ||
915
+ maxDelegationDepth > MAX_DELEGATION_DEPTH_LIMIT)
916
+ ) {
917
+ throw new Error(
918
+ `tiers.json: enforcement.maxDelegationDepth must be null or an integer from 1 to 32 (got ${describeValue(maxDelegationDepth)})`,
919
+ );
920
+ }
720
921
  if (enforcement.mode !== undefined) {
721
922
  if (!["off", "advisory", "enforced"].includes(enforcement.mode as string)) {
722
923
  throw new Error(
@@ -738,13 +939,7 @@ function validateEnforcement(obj: Record<string, unknown>): void {
738
939
  throw new Error("tiers.json: enforcement.verify must be an object");
739
940
  }
740
941
  const verify = enforcement.verify as Record<string, unknown>;
741
- // An own `__proto__`/`constructor`/`prototype` key is never read, but a
742
- // later `Object.assign` copy would reparent through it; reject it here.
743
- for (const key of ["__proto__", "constructor", "prototype"] as const) {
744
- if (Object.prototype.hasOwnProperty.call(verify, key)) {
745
- throw new Error(`tiers.json: enforcement.verify must not contain the key "${key}"`);
746
- }
747
- }
942
+ rejectPrototypeKeys(verify, "enforcement.verify");
748
943
  if (verify.testBaseline !== undefined && typeof verify.testBaseline !== "boolean") {
749
944
  throw new Error("tiers.json: enforcement.verify.testBaseline must be a boolean");
750
945
  }
@@ -869,12 +1064,29 @@ function validateEnforcement(obj: Record<string, unknown>): void {
869
1064
  );
870
1065
  }
871
1066
  }
1067
+ const escalateValue = enforcement.escalate;
1068
+ const snapshots: Record<string, unknown> = { maxDelegationDepth, escalate: escalateValue };
872
1069
  if (
873
- enforcement.escalate !== undefined &&
874
- typeof enforcement.escalate === "object" &&
875
- enforcement.escalate !== null
1070
+ escalateValue !== undefined &&
1071
+ typeof escalateValue === "object" &&
1072
+ escalateValue !== null
876
1073
  ) {
877
- const escalate = enforcement.escalate as Record<string, unknown>;
1074
+ const escalate = escalateValue as Record<string, unknown>;
1075
+ rejectPrototypeKeys(escalate, "enforcement.escalate");
1076
+ const effortBump = escalate.effortBump;
1077
+ if (effortBump !== undefined && typeof effortBump !== "boolean") {
1078
+ throw new Error(`tiers.json: enforcement.escalate.effortBump must be a boolean (got ${describeValue(effortBump)})`);
1079
+ }
1080
+ const effortBumpMax = escalate.effortBumpMax;
1081
+ if (
1082
+ effortBumpMax !== undefined &&
1083
+ !EFFORT_LEVELS.some((level) => level === effortBumpMax)
1084
+ ) {
1085
+ throw new Error(
1086
+ `tiers.json: enforcement.escalate.effortBumpMax must be one of ${EFFORT_LEVELS.join("|")} (got ${describeValue(effortBumpMax)})`,
1087
+ );
1088
+ }
1089
+ snapshots.escalate = withValidatedSnapshots(escalate, { effortBump, effortBumpMax });
878
1090
  if (
879
1091
  escalate.costCeiling !== undefined &&
880
1092
  typeof escalate.costCeiling === "object" &&
@@ -1007,6 +1219,7 @@ function validateEnforcement(obj: Record<string, unknown>): void {
1007
1219
  );
1008
1220
  }
1009
1221
  }
1222
+ return withValidatedSnapshots(enforcement, snapshots);
1010
1223
  }
1011
1224
  }
1012
1225
 
@@ -1014,6 +1227,9 @@ function validateEnforcement(obj: Record<string, unknown>): void {
1014
1227
  * Validate a raw parsed config. Strict and throwing by design: the bundled
1015
1228
  * tiers.json must be valid on its own, and loadConfig turns a throw from an
1016
1229
  * override layer into a warning plus a fallback rather than a crash.
1230
+ * Returns a copy when enforcement is present (even an undefined accessor),
1231
+ * snapshotting its depth/effort values without mutating the caller. Copies
1232
+ * preserve prototypes, arrays, unrelated descriptors and source frozenness.
1017
1233
  *
1018
1234
  * Section order matters and is preserved from when this was one function: a
1019
1235
  * config with several problems reports the same first error it always did.
@@ -1040,13 +1256,14 @@ export function validateConfig(raw: unknown): RouterConfig {
1040
1256
  validateModelGenerations(obj);
1041
1257
  validateTaskPatterns(obj);
1042
1258
  validateSubagentTiers(obj);
1043
- validateEnforcement(obj);
1259
+ const enforcement = validateEnforcement(obj.enforcement);
1044
1260
  validateDelegateInstructions(obj);
1045
1261
  validateDispatchHeader(obj);
1046
1262
  validateTaskPromptRepair(obj);
1047
1263
  validateFalseRefusalDetection(obj);
1048
1264
 
1049
- return raw as RouterConfig;
1265
+ const cfg = raw as RouterConfig;
1266
+ return withValidatedSnapshots(cfg, { enforcement });
1050
1267
  }
1051
1268
 
1052
1269
  /**
@@ -1083,38 +1300,58 @@ export function deepMerge(base: unknown, override: unknown): unknown {
1083
1300
  * overrides file can never brick opencode startup — but the user still gets a
1084
1301
  * visible reason why their override was ignored.
1085
1302
  */
1086
- function readOverridesAt(op: string): Record<string, unknown> | undefined {
1303
+ function readOverridesAt(
1304
+ op: string,
1305
+ failures?: SourceFailure[],
1306
+ ): Record<string, unknown> | undefined {
1307
+ // Only ENOENT/ENOTDIR mean the file is absent. Any other stat error (EACCES on
1308
+ // a parent directory, a transient I/O error) is a failure, never a removal —
1309
+ // otherwise a reload would swap the last valid config for lower-priority
1310
+ // defaults.
1311
+ const kind = statKind(op);
1312
+ if (kind === "missing") return undefined;
1313
+
1087
1314
  let text: string;
1088
1315
  try {
1089
- if (!existsSync(op)) return undefined;
1316
+ if (kind !== "present") throw new Error(kind.message);
1090
1317
  text = readFileSync(op, "utf-8");
1091
1318
  } catch (err) {
1092
1319
  // The file is there but unreadable (permissions, a dangling symlink, a
1093
1320
  // race with a delete). Every other failure below says so; staying silent
1094
1321
  // here makes an unreadable override look exactly like an absent one.
1095
- console.warn(
1096
- `[model-router] ignoring ${op}: cannot read it — ${(err as Error).message}`,
1097
- );
1322
+ const reason = `cannot read it — ${(err as Error).message}`;
1323
+ console.warn(`[model-router] ignoring ${op}: ${reason}`);
1324
+ failures?.push({ source: op, message: `${op}: ${reason}` });
1098
1325
  return undefined;
1099
1326
  }
1100
1327
 
1101
1328
  try {
1102
1329
  const parsed = parseJsonc(text) as unknown;
1103
1330
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1104
- console.warn(
1105
- `[model-router] ignoring ${op}: expected a JSON object at root`,
1106
- );
1331
+ const reason = "expected a JSON object at root";
1332
+ console.warn(`[model-router] ignoring ${op}: ${reason}`);
1333
+ failures?.push({ source: op, message: `${op}: ${reason}` });
1107
1334
  return undefined;
1108
1335
  }
1109
1336
  return parsed as Record<string, unknown>;
1110
1337
  } catch (err) {
1111
- console.warn(
1112
- `[model-router] ignoring ${op}: invalid JSONC — ${(err as Error).message}`,
1113
- );
1338
+ const reason = `invalid JSONC — ${(err as Error).message}`;
1339
+ console.warn(`[model-router] ignoring ${op}: ${reason}`);
1340
+ failures?.push({ source: op, message: `${op}: ${reason}` });
1114
1341
  return undefined;
1115
1342
  }
1116
1343
  }
1117
1344
 
1345
+ /**
1346
+ * A source that exists on disk but could not be used while building the
1347
+ * config. `source` is a stable key (a file path, or the joined layer paths for
1348
+ * a combined-merge failure); `message` is the user-facing reason.
1349
+ */
1350
+ interface SourceFailure {
1351
+ source: string;
1352
+ message: string;
1353
+ }
1354
+
1118
1355
  /**
1119
1356
  * The ordered override layers (lowest priority first): global, then
1120
1357
  * project-local. Each present, well-formed file becomes a layer that is
@@ -1125,13 +1362,14 @@ export interface OverrideLayer {
1125
1362
  data: Record<string, unknown>;
1126
1363
  }
1127
1364
 
1128
- function collectOverrideLayers(): OverrideLayer[] {
1365
+ function collectOverrideLayers(dir: string, failures?: SourceFailure[]): OverrideLayer[] {
1129
1366
  const layers: OverrideLayer[] = [];
1130
- // Lowest priority first: global, then project-local (found by upward search).
1131
- const paths = [overridePath(), findProjectOverride()];
1367
+ // Lowest priority first: global, then project-local (found by upward search
1368
+ // from the project directory).
1369
+ const paths = [overridePath(), walkForProjectOverride(dir)];
1132
1370
  for (const p of paths) {
1133
1371
  if (!p) continue;
1134
- const data = readOverridesAt(p);
1372
+ const data = readOverridesAt(p, failures);
1135
1373
  if (data) layers.push({ path: p, data });
1136
1374
  }
1137
1375
  return layers;
@@ -1165,13 +1403,132 @@ function applyTierDefaults(cfg: RouterConfig): void {
1165
1403
  }
1166
1404
  }
1167
1405
 
1168
- export function loadConfig(): RouterConfig {
1169
- if (_cachedConfig && !_configDirty) {
1170
- return _cachedConfig;
1406
+ /**
1407
+ * Every file location that feeds loadConfig() for the (normalized) project
1408
+ * directory `dir` (undefined = none applicable).
1409
+ */
1410
+ function sourcePaths(dir: string): Array<string | undefined> {
1411
+ return [configPath(), overridePath(), walkForProjectOverride(dir), statePath()];
1412
+ }
1413
+
1414
+ /**
1415
+ * mtime/ctime/size fingerprint of every file that feeds loadConfig(). ctime is
1416
+ * included because restoring access to a previously unreadable file (chmod)
1417
+ * changes ctime but not mtime/size, and that must trigger a retry. Only
1418
+ * ENOENT/ENOTDIR map to `missing` (removal); any other stat error maps to
1419
+ * `error:<code>`, a distinct marker, so losing access to a file is never
1420
+ * fingerprinted — or reloaded — as if it had been deleted.
1421
+ */
1422
+ function sourceFingerprint(paths: Array<string | undefined>): string {
1423
+ return paths
1424
+ .map((p) => {
1425
+ if (!p) return "none";
1426
+ try {
1427
+ const st = statSync(p);
1428
+ return `${p}:${st.mtimeMs}:${st.ctimeMs}:${st.size}`;
1429
+ } catch (err) {
1430
+ return isGoneError(err) ? `${p}:missing` : `${p}:error:${errnoCode(err)}`;
1431
+ }
1432
+ })
1433
+ .join("|");
1434
+ }
1435
+
1436
+ /**
1437
+ * Load the effective config for the project directory `dir` (the host-provided
1438
+ * project dir; defaults to the process working directory). Each directory has
1439
+ * its own cache entry, so several project instances sharing one process never
1440
+ * see or overwrite each other's config.
1441
+ */
1442
+ export function loadConfig(dir?: string): RouterConfig {
1443
+ const projectDir = normalizeProjectDir(dir);
1444
+ const entry = getCacheEntry(projectDir);
1445
+ const paths = sourcePaths(projectDir);
1446
+ const fingerprint = sourceFingerprint(paths);
1447
+ if (entry.config && !entry.dirty && fingerprint === entry.fingerprint) {
1448
+ return entry.config;
1171
1449
  }
1172
1450
 
1451
+ // A previous config is only a valid fallback when it was built for the same
1452
+ // project identity: HOME + the normalized project dir (the cache key) + the
1453
+ // state path. Deliberately NOT the resolved override file paths: a project
1454
+ // override created after startup must not turn a broken file into a
1455
+ // tolerated "first load".
1456
+ const sourceKey = [homedir(), projectDir, statePath()].join("|");
1457
+ const previous =
1458
+ entry.config !== null && sourceKey === entry.sourceKey ? entry.config : null;
1459
+
1460
+ const failures: SourceFailure[] = [];
1461
+ let cfg: RouterConfig;
1462
+ try {
1463
+ cfg = buildConfig(projectDir, failures);
1464
+ } catch (err) {
1465
+ // First load: unchanged behaviour — throw. Reload: keep the last good one.
1466
+ if (!previous) throw err;
1467
+ return keepLastValidConfig(
1468
+ entry,
1469
+ previous,
1470
+ fingerprint,
1471
+ `${configPath()}: ${(err as Error).message}`,
1472
+ );
1473
+ }
1474
+
1475
+ if (previous) {
1476
+ // Sources that were already failing when `previous` was built are an
1477
+ // accepted state (e.g. a broken override at startup); only a source that
1478
+ // newly broke counts as a failed reload.
1479
+ const regressions = failures.filter((f) => !entry.tolerated.has(f.source));
1480
+ if (regressions.length > 0) {
1481
+ return keepLastValidConfig(
1482
+ entry,
1483
+ previous,
1484
+ fingerprint,
1485
+ regressions.map((f) => f.message).join("\n"),
1486
+ );
1487
+ }
1488
+ }
1489
+
1490
+ entry.config = cfg;
1491
+ entry.fingerprint = fingerprint;
1492
+ entry.sourceKey = sourceKey;
1493
+ entry.tolerated = new Set(failures.map((f) => f.source));
1494
+ entry.dirty = false;
1495
+ entry.reloadError = null;
1496
+ entry.warnedFingerprint = null;
1497
+ return cfg;
1498
+ }
1499
+
1500
+ /**
1501
+ * Reload failed: keep serving `previous` (same object reference), remember the
1502
+ * fingerprint so we do not retry on every message until a file changes (or
1503
+ * invalidateConfigCache() is called), record the reason, and warn once per
1504
+ * failed fingerprint. All state lives on the directory's own cache `entry`.
1505
+ */
1506
+ function keepLastValidConfig(
1507
+ entry: ConfigCacheEntry,
1508
+ previous: RouterConfig,
1509
+ fingerprint: string,
1510
+ message: string,
1511
+ ): RouterConfig {
1512
+ entry.fingerprint = fingerprint;
1513
+ entry.dirty = false;
1514
+ entry.reloadError = message;
1515
+ if (entry.warnedFingerprint !== fingerprint) {
1516
+ entry.warnedFingerprint = fingerprint;
1517
+ console.warn(
1518
+ `[model-router] config reload failed — keeping last valid config: ${message}`,
1519
+ );
1520
+ }
1521
+ return previous;
1522
+ }
1523
+
1524
+ /**
1525
+ * Build a fresh config from tiers.json + override layers + persisted state.
1526
+ * Throws only when tiers.json itself is unreadable/invalid. Override and state
1527
+ * problems are warned about, skipped, and appended to `failures`.
1528
+ */
1529
+ function buildConfig(dir: string, failures: SourceFailure[]): RouterConfig {
1173
1530
  const base = JSON.parse(readFileSync(configPath(), "utf-8"));
1174
- const layers = collectOverrideLayers();
1531
+ const layers = collectOverrideLayers(dir, failures);
1175
1532
 
1176
1533
  // Bundled config must be valid on its own — throw otherwise (unchanged
1177
1534
  // behaviour). Override layers are then applied on top.
@@ -1191,6 +1548,11 @@ export function loadConfig(): RouterConfig {
1191
1548
  console.warn(
1192
1549
  `[model-router] combined overrides are invalid (${(err as Error).message}); dropping conflicting layer(s)`,
1193
1550
  );
1551
+ const layerPaths = layers.map((l) => l.path).join(" + ");
1552
+ failures.push({
1553
+ source: layerPaths,
1554
+ message: `${layerPaths}: combined overrides are invalid — ${(err as Error).message}`,
1555
+ });
1194
1556
  for (let i = layers.length - 1; i >= 0; i--) {
1195
1557
  try {
1196
1558
  cfg = validateConfig(merge([layers[i]!]));
@@ -1204,6 +1566,10 @@ export function loadConfig(): RouterConfig {
1204
1566
  console.warn(
1205
1567
  `[model-router] ignoring ${layers[i]!.path}: ${(singleErr as Error).message}`,
1206
1568
  );
1569
+ failures.push({
1570
+ source: layers[i]!.path,
1571
+ message: `${layers[i]!.path}: ${(singleErr as Error).message}`,
1572
+ });
1207
1573
  cfg = validateConfig(base);
1208
1574
  }
1209
1575
  }
@@ -1211,7 +1577,12 @@ export function loadConfig(): RouterConfig {
1211
1577
  }
1212
1578
 
1213
1579
  try {
1214
- if (existsSync(statePath())) {
1580
+ const stateKind = statKind(statePath());
1581
+ if (stateKind !== "missing") {
1582
+ // Present-but-uninspectable (EACCES, EIO, …) is a failure, not an absent
1583
+ // state file: reverting the persisted preset on a transient error would
1584
+ // be silent data loss.
1585
+ if (stateKind !== "present") throw new Error(`cannot read it — ${stateKind.message}`);
1215
1586
  const state = JSON.parse(
1216
1587
  readFileSync(statePath(), "utf-8"),
1217
1588
  ) as RouterState;
@@ -1228,14 +1599,17 @@ export function loadConfig(): RouterConfig {
1228
1599
  cfg.enforcement = { ...(cfg.enforcement ?? {}), mode: state.enforcementMode };
1229
1600
  }
1230
1601
  }
1231
- } catch {
1232
- // Ignore state read errors and keep tiers.json defaults
1602
+ } catch (err) {
1603
+ // State read errors never block startup: keep tiers.json defaults. They are
1604
+ // recorded so a state file that breaks on a later reload is reported (and
1605
+ // the last valid config kept) rather than silently reverting the preset.
1606
+ failures.push({
1607
+ source: statePath(),
1608
+ message: `${statePath()}: ${(err as Error).message}`,
1609
+ });
1233
1610
  }
1234
1611
 
1235
1612
  applyTierDefaults(cfg);
1236
-
1237
- _cachedConfig = cfg;
1238
- _configDirty = false;
1239
1613
  return cfg;
1240
1614
  }
1241
1615
 
@@ -1269,6 +1643,21 @@ export function writeState(patch: Partial<RouterState>): void {
1269
1643
  // Enforcement helpers
1270
1644
  // ---------------------------------------------------------------------------
1271
1645
 
1646
+ /** The single place the delegation-depth default is applied; null disables it. */
1647
+ export function resolveDepthLimit(cfg: RouterConfig): number | null {
1648
+ const depth = cfg.enforcement?.maxDelegationDepth;
1649
+ return depth === undefined ? 1 : depth;
1650
+ }
1651
+
1652
+ /** The single place effort-bump defaults are applied, without mutating config. */
1653
+ export function resolveEffortBump(cfg: RouterConfig): { enabled: boolean; max: EffortLevel } {
1654
+ const escalate = cfg.enforcement?.escalate;
1655
+ return {
1656
+ enabled: escalate?.effortBump ?? true,
1657
+ max: escalate?.effortBumpMax ?? "xhigh",
1658
+ };
1659
+ }
1660
+
1272
1661
  /** Returns the effective enforcement mode. Missing enforcement ⇒ mode:"advisory". */
1273
1662
  export function normalizeEnforcement(
1274
1663
  e: EnforcementConfig | undefined,