opencode-model-router 1.5.0 → 1.7.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.
@@ -1,4 +1,11 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
1
+ import {
2
+ existsSync,
3
+ mkdirSync,
4
+ readFileSync,
5
+ realpathSync,
6
+ renameSync,
7
+ writeFileSync,
8
+ } from "node:fs";
2
9
  import { homedir } from "node:os";
3
10
  import { dirname, join } from "node:path";
4
11
  import { fileURLToPath } from "node:url";
@@ -24,9 +31,51 @@ export interface ReasoningConfig {
24
31
  summary?: "auto" | "always" | "never";
25
32
  }
26
33
 
34
+ /**
35
+ * Provider-agnostic reasoning effort for a tier.
36
+ *
37
+ * `xhigh` and `max` exist because Anthropic's adaptive models accept them;
38
+ * OpenAI's `reasoning_effort` stops at `high`, so the registration path
39
+ * downgrades those two with a warning (see `src/router/agent-options.ts`).
40
+ */
41
+ export const EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"] as const;
42
+
43
+ export type EffortLevel = (typeof EFFORT_LEVELS)[number];
44
+
45
+ /**
46
+ * Wording style of the default system prompt handed to a tier agent.
47
+ *
48
+ * `prescriptive` uses the enumerated `tierPrompts` from tiers.json; `goal-oriented`
49
+ * uses the goal + constraints defaults in `src/router/prompts.ts`; `auto` (the
50
+ * default when unset) picks goal-oriented for strong models and prescriptive for
51
+ * the rest.
52
+ */
53
+ export const PROMPT_STYLES = ["prescriptive", "goal-oriented", "auto"] as const;
54
+
55
+ export type PromptStyle = (typeof PROMPT_STYLES)[number];
56
+
57
+ /**
58
+ * Shared model-generation pattern lists, matched case-insensitively as substrings
59
+ * of a tier's model ID.
60
+ */
61
+ export interface ModelGenerationsConfig {
62
+ claude5x?: string[];
63
+ strong?: string[];
64
+ }
65
+
66
+ export const DEFAULT_CLAUDE5X_PATTERNS = ["claude-fable-5", "claude-mythos-5"];
67
+ // NOTE: strong is a superset of claude5x by construction — editing DEFAULT_CLAUDE5X_PATTERNS also widens strong. Deliberate: every Claude 5.x model is a strong model.
68
+ export const DEFAULT_STRONG_MODEL_PATTERNS = [...DEFAULT_CLAUDE5X_PATTERNS, "opus-4-8"];
69
+
27
70
  export interface TierConfig {
28
71
  model: string;
29
72
  variant?: string;
73
+ /**
74
+ * Provider-agnostic effort. Loses to an explicit `thinking` budget on
75
+ * Anthropic and to an explicit `reasoning.effort` on OpenAI. When unset, no
76
+ * effort key is registered at all.
77
+ */
78
+ effort?: EffortLevel;
30
79
  thinking?: ThinkingConfig;
31
80
  reasoning?: ReasoningConfig;
32
81
  costRatio?: number;
@@ -35,6 +84,11 @@ export interface TierConfig {
35
84
  description?: string;
36
85
  steps?: number;
37
86
  prompt?: string;
87
+ /**
88
+ * Wording style of the default prompt for this tier. Ignored when `prompt` is
89
+ * set — an explicit per-tier prompt always wins. Defaults to `auto`.
90
+ */
91
+ promptStyle?: PromptStyle;
38
92
  /** Optional use-case hints shown in `/tiers`. */
39
93
  whenToUse?: string[];
40
94
  }
@@ -57,7 +111,13 @@ export interface EnforcementConfig {
57
111
  envGate?: string;
58
112
  perTier?: Record<string, "off" | "advisory" | "enforced">;
59
113
  guard?: { readDraftCap?: number; sameOpRetryCap?: number; blockSelfScript?: boolean; deliverableFirst?: boolean; budget?: number; blockScriptWrites?: boolean };
60
- verify?: { require?: "never" | "whenDoDPresent" | "always"; requireExplicitDoD?: boolean; preferDeterministic?: boolean; graderPolicy?: "atLeastProducerTier"; graderTemperature?: number; minGraderTier?: string };
114
+ verify?: { require?: "never" | "whenDoDPresent" | "always"; requireExplicitDoD?: boolean; preferDeterministic?: boolean; graderPolicy?: "atLeastProducerTier"; graderTemperature?: number; minGraderTier?: string | null;
115
+ /** Ceiling for one producer `session.prompt` turn, in ms. Default 600000. */
116
+ delegateTimeoutMs?: number;
117
+ /** Ceiling for one grader `session.prompt` turn, in ms. Default 60000. */
118
+ graderTimeoutMs?: number;
119
+ /** Ceiling for the whole acceptance gate, in ms. Default 90000. */
120
+ gateBudgetMs?: number };
61
121
  escalate?: { floorTier?: string | null; ladder?: string[]; maxAttemptsPerTier?: number; maxTotalAttempts?: number; costCeiling?: { base?: string; multiple?: number } };
62
122
  proportional?: { trivialBypass?: boolean; trivialClassifier?: string };
63
123
  }
@@ -73,6 +133,14 @@ export interface RouterConfig {
73
133
  modes?: Record<string, ModeConfig>;
74
134
  /** Global default prompts per tier name. A preset-level tier.prompt overrides this. */
75
135
  tierPrompts?: Record<string, string>;
136
+ /**
137
+ * Optional user overrides for the goal-oriented tier prompts. The defaults ship
138
+ * in code (`src/router/prompts.ts`); an entry here replaces the built-in for
139
+ * that tier name.
140
+ */
141
+ tierPromptsGoalOriented?: Record<string, string>;
142
+ /** Shared model-generation pattern lists; see {@link ModelGenerationsConfig}. */
143
+ modelGenerations?: ModelGenerationsConfig;
76
144
  /** Read-only tool-call caps per tier, enforced at runtime via tool.execute.after banner injection. */
77
145
  tierCaps?: Record<string, number>;
78
146
  enforcement?: EnforcementConfig;
@@ -84,6 +152,18 @@ export interface RouterConfig {
84
152
  * "Now I'll add X" phrasing.
85
153
  */
86
154
  antiNarration?: boolean;
155
+ /**
156
+ * Opt-in map of pre-existing agent name → tier name, e.g.
157
+ * `{ "ContextScout": "fast" }`. Listed agents are repointed at the active
158
+ * preset's model for that tier, so they follow `/preset` instead of pinning
159
+ * a model id in their own definition. Absent or empty ⇒ feature is off and
160
+ * no agent is touched.
161
+ *
162
+ * Keys are opencode agent names — the frontmatter `name:` field when a
163
+ * markdown agent declares one, otherwise its path-derived name. List only
164
+ * subagents; a primary agent is the orchestrator.
165
+ */
166
+ subagentTiers?: Record<string, string>;
87
167
  /** Experimental, opt-in features. Off by default. */
88
168
  experimental?: { verifiedDelegateTool?: boolean };
89
169
  }
@@ -176,8 +256,22 @@ const MAX_WALK_DEPTH = 16;
176
256
  * Returns the resolved path, or undefined when no file applies.
177
257
  */
178
258
  export function findProjectOverride(): string | undefined {
179
- let dir = process.cwd();
180
- const home = homedir();
259
+ // Both sides of the $HOME comparison below have to be resolved the same way.
260
+ // process.cwd() returns a realpath, while homedir() returns $HOME verbatim, so
261
+ // on any system where $HOME contains a symlinked component (macOS temp dirs,
262
+ // containers, some NFS homes) a raw string compare never matches and the home
263
+ // boundary silently stops applying. Fail soft: an unresolvable path is used
264
+ // as-is, which is no worse than not comparing at all.
265
+ const resolve = (p: string): string => {
266
+ try {
267
+ return realpathSync(p);
268
+ } catch {
269
+ return p;
270
+ }
271
+ };
272
+
273
+ let dir = resolve(process.cwd());
274
+ const home = resolve(homedir());
181
275
  let depth = 0;
182
276
 
183
277
  for (;;) {
@@ -228,21 +322,17 @@ export function resolvePresetName(
228
322
  );
229
323
  }
230
324
 
231
- export function validateConfig(raw: unknown): RouterConfig {
232
- if (typeof raw !== "object" || raw === null) {
233
- throw new Error("tiers.json: expected a JSON object at root");
234
- }
235
-
236
- const obj = raw as Record<string, unknown>;
325
+ /** True for a non-null, non-array object literal. */
326
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
327
+ return typeof v === "object" && v !== null && !Array.isArray(v);
328
+ }
237
329
 
238
- if (typeof obj.activePreset !== "string" || !obj.activePreset) {
239
- throw new Error("tiers.json: 'activePreset' must be a non-empty string");
240
- }
241
- if (
242
- typeof obj.presets !== "object" ||
243
- obj.presets === null ||
244
- Array.isArray(obj.presets)
245
- ) {
330
+ /**
331
+ * Shape of every preset and every tier within it. Returns the presets map so
332
+ * the caller can hand it to validateActivePreset without re-narrowing.
333
+ */
334
+ function validatePresets(obj: Record<string, unknown>): Record<string, unknown> {
335
+ if (!isPlainObject(obj.presets)) {
246
336
  throw new Error("tiers.json: 'presets' must be a non-null object");
247
337
  }
248
338
 
@@ -281,9 +371,38 @@ export function validateConfig(raw: unknown): RouterConfig {
281
371
  `tiers.json: '${presetName}.${tierName}.whenToUse' must be an array`,
282
372
  );
283
373
  }
374
+ // A typo'd effort would otherwise load clean and be silently dropped at
375
+ // registration time, leaving a tier running at the provider default with
376
+ // only a warning nobody reads.
377
+ if (
378
+ t.effort !== undefined &&
379
+ !EFFORT_LEVELS.some((level) => level === t.effort)
380
+ ) {
381
+ throw new Error(
382
+ `tiers.json: preset '${presetName}' tier '${tierName}': effort must be one of ${EFFORT_LEVELS.join(", ")}`,
383
+ );
384
+ }
385
+ // Same reasoning as effort: a typo'd style would otherwise load clean and
386
+ // silently fall back to the prescriptive prompt with nothing said.
387
+ if (
388
+ t.promptStyle !== undefined &&
389
+ !PROMPT_STYLES.some((style) => style === t.promptStyle)
390
+ ) {
391
+ throw new Error(
392
+ `tiers.json: preset '${presetName}' tier '${tierName}': promptStyle must be one of ${PROMPT_STYLES.join("|")}`,
393
+ );
394
+ }
284
395
  }
285
396
  }
286
397
 
398
+ return presets;
399
+ }
400
+
401
+ /** `activePreset` names a preset that exists. */
402
+ function validateActivePreset(
403
+ obj: Record<string, unknown>,
404
+ presets: Record<string, unknown>,
405
+ ): void {
287
406
  // `activePreset` has to name a preset that actually exists. It is the key most
288
407
  // likely to be typo'd in a hand-edited override file, and without this the bad
289
408
  // name loads clean and routing quietly runs on whatever the state file or the
@@ -301,7 +420,10 @@ export function validateConfig(raw: unknown): RouterConfig {
301
420
  `tiers.json: 'activePreset' is '${activePresetName}', which is not a defined preset (defined: ${presetNames.join(", ")})`,
302
421
  );
303
422
  }
423
+ }
304
424
 
425
+ /** Top-level keys that are required, or optional with a fixed type. */
426
+ function validateCoreKeys(obj: Record<string, unknown>): void {
305
427
  if (!Array.isArray(obj.rules)) {
306
428
  throw new Error("tiers.json: 'rules' must be an array of strings");
307
429
  }
@@ -311,14 +433,12 @@ export function validateConfig(raw: unknown): RouterConfig {
311
433
  if (obj.antiNarration !== undefined && typeof obj.antiNarration !== "boolean") {
312
434
  throw new Error("tiers.json: 'antiNarration' must be a boolean");
313
435
  }
436
+ }
314
437
 
438
+ function validateModes(obj: Record<string, unknown>): void {
315
439
  // Validate modes if present
316
440
  if (obj.modes !== undefined) {
317
- if (
318
- typeof obj.modes !== "object" ||
319
- obj.modes === null ||
320
- Array.isArray(obj.modes)
321
- ) {
441
+ if (!isPlainObject(obj.modes)) {
322
442
  throw new Error("tiers.json: 'modes' must be an object");
323
443
  }
324
444
  const modes = obj.modes as Record<string, unknown>;
@@ -339,14 +459,12 @@ export function validateConfig(raw: unknown): RouterConfig {
339
459
  }
340
460
  }
341
461
  }
462
+ }
342
463
 
464
+ function validateTierCaps(obj: Record<string, unknown>): void {
343
465
  // Validate tierCaps if present
344
466
  if (obj.tierCaps !== undefined) {
345
- if (
346
- typeof obj.tierCaps !== "object" ||
347
- obj.tierCaps === null ||
348
- Array.isArray(obj.tierCaps)
349
- ) {
467
+ if (!isPlainObject(obj.tierCaps)) {
350
468
  throw new Error("tiers.json: 'tierCaps' must be an object");
351
469
  }
352
470
  const tc = obj.tierCaps as Record<string, unknown>;
@@ -358,14 +476,12 @@ export function validateConfig(raw: unknown): RouterConfig {
358
476
  }
359
477
  }
360
478
  }
479
+ }
361
480
 
481
+ function validateTierPrompts(obj: Record<string, unknown>): void {
362
482
  // Validate tierPrompts if present
363
483
  if (obj.tierPrompts !== undefined) {
364
- if (
365
- typeof obj.tierPrompts !== "object" ||
366
- obj.tierPrompts === null ||
367
- Array.isArray(obj.tierPrompts)
368
- ) {
484
+ if (!isPlainObject(obj.tierPrompts)) {
369
485
  throw new Error("tiers.json: 'tierPrompts' must be an object");
370
486
  }
371
487
  const tp = obj.tierPrompts as Record<string, unknown>;
@@ -377,14 +493,66 @@ export function validateConfig(raw: unknown): RouterConfig {
377
493
  }
378
494
  }
379
495
  }
496
+ }
497
+
498
+ function validateTierPromptsGoalOriented(obj: Record<string, unknown>): void {
499
+ // Validate tierPromptsGoalOriented if present
500
+ if (obj.tierPromptsGoalOriented !== undefined) {
501
+ if (!isPlainObject(obj.tierPromptsGoalOriented)) {
502
+ throw new Error("tiers.json: 'tierPromptsGoalOriented' must be an object");
503
+ }
504
+ const tp = obj.tierPromptsGoalOriented as Record<string, unknown>;
505
+ for (const [tierName, prompt] of Object.entries(tp)) {
506
+ if (typeof prompt !== "string") {
507
+ throw new Error(
508
+ `tiers.json: tierPromptsGoalOriented.'${tierName}' must be a string`,
509
+ );
510
+ }
511
+ }
512
+ }
513
+ }
514
+
515
+ function validateModelGenerations(obj: Record<string, unknown>): void {
516
+ // Validate modelGenerations if present. Element-level non-strings are tolerated
517
+ // and filtered at match time rather than rejected here, so one bad entry in an
518
+ // override file cannot drop the whole layer.
519
+ if (obj.modelGenerations !== undefined) {
520
+ if (!isPlainObject(obj.modelGenerations)) {
521
+ throw new Error("tiers.json: modelGenerations must be an object");
522
+ }
523
+ const modelGenerations = obj.modelGenerations as Record<string, unknown>;
524
+ for (const key of ["claude5x", "strong"] as const) {
525
+ if (
526
+ modelGenerations[key] !== undefined &&
527
+ !Array.isArray(modelGenerations[key])
528
+ ) {
529
+ throw new Error(`tiers.json: modelGenerations.${key} must be an array`);
530
+ }
531
+ }
532
+ }
533
+ }
534
+
535
+ function validateSubagentTiers(obj: Record<string, unknown>): void {
536
+ if (obj.subagentTiers === undefined) return;
537
+ if (!isPlainObject(obj.subagentTiers)) {
538
+ throw new Error("tiers.json: 'subagentTiers' must be an object");
539
+ }
540
+ for (const [agentName, tierName] of Object.entries(obj.subagentTiers)) {
541
+ if (typeof tierName !== "string" || tierName === "") {
542
+ throw new Error(
543
+ `tiers.json: subagentTiers.'${agentName}' must be a non-empty tier name`,
544
+ );
545
+ }
546
+ }
547
+ // Deliberately not checking that the tier exists: a map may name a tier that
548
+ // only some presets define, and switching preset must never brick startup.
549
+ // Unknown tiers are skipped at resolve time (see resolveSubagentOverrides).
550
+ }
380
551
 
552
+ function validateTaskPatterns(obj: Record<string, unknown>): void {
381
553
  // Validate taskPatterns if present
382
554
  if (obj.taskPatterns !== undefined) {
383
- if (
384
- typeof obj.taskPatterns !== "object" ||
385
- obj.taskPatterns === null ||
386
- Array.isArray(obj.taskPatterns)
387
- ) {
555
+ if (!isPlainObject(obj.taskPatterns)) {
388
556
  throw new Error("tiers.json: 'taskPatterns' must be an object");
389
557
  }
390
558
  const tp = obj.taskPatterns as Record<string, unknown>;
@@ -396,14 +564,12 @@ export function validateConfig(raw: unknown): RouterConfig {
396
564
  }
397
565
  }
398
566
  }
567
+ }
399
568
 
569
+ function validateEnforcement(obj: Record<string, unknown>): void {
400
570
  // Validate enforcement if present (optional — absent means no enforcement)
401
571
  if (obj.enforcement !== undefined) {
402
- if (
403
- typeof obj.enforcement !== "object" ||
404
- obj.enforcement === null ||
405
- Array.isArray(obj.enforcement)
406
- ) {
572
+ if (!isPlainObject(obj.enforcement)) {
407
573
  throw new Error("tiers.json: enforcement must be an object");
408
574
  }
409
575
  const enforcement = obj.enforcement as Record<string, unknown>;
@@ -414,6 +580,13 @@ export function validateConfig(raw: unknown): RouterConfig {
414
580
  );
415
581
  }
416
582
  }
583
+ if (enforcement.envGate !== undefined) {
584
+ if (typeof enforcement.envGate !== "string" || !enforcement.envGate) {
585
+ throw new Error(
586
+ "tiers.json: enforcement.envGate must be a non-empty string",
587
+ );
588
+ }
589
+ }
417
590
  if (
418
591
  enforcement.verify !== undefined &&
419
592
  typeof enforcement.verify === "object" &&
@@ -428,6 +601,53 @@ export function validateConfig(raw: unknown): RouterConfig {
428
601
  'tiers.json: enforcement.verify.graderPolicy must be "atLeastProducerTier"',
429
602
  );
430
603
  }
604
+ // `null` is the shipped default and means "no floor" — same as absent.
605
+ if (
606
+ verify.minGraderTier !== undefined &&
607
+ verify.minGraderTier !== null &&
608
+ typeof verify.minGraderTier !== "string"
609
+ ) {
610
+ throw new Error(
611
+ "tiers.json: enforcement.verify.minGraderTier must be a string or null",
612
+ );
613
+ }
614
+ if (verify.graderTemperature !== undefined) {
615
+ if (
616
+ typeof verify.graderTemperature !== "number" ||
617
+ !Number.isFinite(verify.graderTemperature) ||
618
+ verify.graderTemperature < 0
619
+ ) {
620
+ throw new Error(
621
+ "tiers.json: enforcement.verify.graderTemperature must be a number >= 0",
622
+ );
623
+ }
624
+ }
625
+ // Time-box ceilings. `>= 1` and not `>= 0`: a 0 or negative budget is
626
+ // almost always meant as "no timeout", and silently reading it as an
627
+ // immediately-expiring one would make every delegation fail. Reject it
628
+ // at the config boundary and say so, rather than guessing.
629
+ for (const key of [
630
+ "delegateTimeoutMs",
631
+ "graderTimeoutMs",
632
+ "gateBudgetMs",
633
+ ] as const) {
634
+ const value = verify[key];
635
+ if (value !== undefined) {
636
+ if (!Number.isInteger(value) || (value as number) < 1) {
637
+ throw new Error(
638
+ `tiers.json: enforcement.verify.${key} must be an integer >= 1 (milliseconds)`,
639
+ );
640
+ }
641
+ }
642
+ }
643
+ if (
644
+ verify.requireExplicitDoD !== undefined &&
645
+ typeof verify.requireExplicitDoD !== "boolean"
646
+ ) {
647
+ throw new Error(
648
+ "tiers.json: enforcement.verify.requireExplicitDoD must be a boolean",
649
+ );
650
+ }
431
651
  }
432
652
  if (
433
653
  enforcement.escalate !== undefined &&
@@ -521,16 +741,86 @@ export function validateConfig(raw: unknown): RouterConfig {
521
741
  !Number.isFinite(guard.budget) ||
522
742
  guard.budget < 1
523
743
  ) {
524
- throw new Error("enforcement.guard.budget must be a number >= 1");
744
+ throw new Error("tiers.json: enforcement.guard.budget must be a number >= 1");
525
745
  }
526
746
  }
527
747
  if (guard.blockScriptWrites !== undefined) {
528
748
  if (typeof guard.blockScriptWrites !== "boolean") {
529
- throw new Error("enforcement.guard.blockScriptWrites must be a boolean");
749
+ throw new Error(
750
+ "tiers.json: enforcement.guard.blockScriptWrites must be a boolean",
751
+ );
752
+ }
753
+ }
754
+ for (const key of ["readDraftCap", "sameOpRetryCap"] as const) {
755
+ if (guard[key] !== undefined) {
756
+ if (
757
+ typeof guard[key] !== "number" ||
758
+ !Number.isInteger(guard[key]) ||
759
+ (guard[key] as number) < 0
760
+ ) {
761
+ throw new Error(
762
+ `tiers.json: enforcement.guard.${key} must be an integer >= 0`,
763
+ );
764
+ }
530
765
  }
531
766
  }
767
+ for (const key of ["blockSelfScript", "deliverableFirst"] as const) {
768
+ if (guard[key] !== undefined && typeof guard[key] !== "boolean") {
769
+ throw new Error(
770
+ `tiers.json: enforcement.guard.${key} must be a boolean`,
771
+ );
772
+ }
773
+ }
774
+ }
775
+ if (
776
+ enforcement.proportional !== undefined &&
777
+ typeof enforcement.proportional === "object" &&
778
+ enforcement.proportional !== null
779
+ ) {
780
+ const proportional = enforcement.proportional as Record<string, unknown>;
781
+ if (
782
+ proportional.trivialBypass !== undefined &&
783
+ typeof proportional.trivialBypass !== "boolean"
784
+ ) {
785
+ throw new Error(
786
+ "tiers.json: enforcement.proportional.trivialBypass must be a boolean",
787
+ );
788
+ }
532
789
  }
533
790
  }
791
+ }
792
+
793
+ /**
794
+ * Validate a raw parsed config. Strict and throwing by design: the bundled
795
+ * tiers.json must be valid on its own, and loadConfig turns a throw from an
796
+ * override layer into a warning plus a fallback rather than a crash.
797
+ *
798
+ * Section order matters and is preserved from when this was one function: a
799
+ * config with several problems reports the same first error it always did.
800
+ */
801
+ export function validateConfig(raw: unknown): RouterConfig {
802
+ if (typeof raw !== "object" || raw === null) {
803
+ throw new Error("tiers.json: expected a JSON object at root");
804
+ }
805
+
806
+
807
+ const obj = raw as Record<string, unknown>;
808
+
809
+ if (typeof obj.activePreset !== "string" || !obj.activePreset) {
810
+ throw new Error("tiers.json: 'activePreset' must be a non-empty string");
811
+ }
812
+
813
+ const presets = validatePresets(obj);
814
+ validateActivePreset(obj, presets);
815
+ validateCoreKeys(obj);
816
+ validateModes(obj);
817
+ validateTierCaps(obj);
818
+ validateTierPrompts(obj);
819
+ validateTierPromptsGoalOriented(obj);
820
+ validateModelGenerations(obj);
821
+ validateTaskPatterns(obj);
822
+ validateSubagentTiers(obj);
823
+ validateEnforcement(obj);
534
824
 
535
825
  return raw as RouterConfig;
536
826
  }
@@ -542,9 +832,6 @@ export function validateConfig(raw: unknown): RouterConfig {
542
832
  * override are skipped so they never blow away a base value.
543
833
  */
544
834
  export function deepMerge(base: unknown, override: unknown): unknown {
545
- const isPlainObject = (v: unknown): v is Record<string, unknown> =>
546
- typeof v === "object" && v !== null && !Array.isArray(v);
547
-
548
835
  if (!isPlainObject(base) || !isPlainObject(override)) {
549
836
  return override;
550
837
  }
@@ -0,0 +1,35 @@
1
+ export const DEFAULT_IDLE_TTL_MS = 60 * 60_000;
2
+ export const IDLE_SWEEP_THROTTLE_MS = 5 * 60_000;
3
+
4
+ export type SweepFn = () => void;
5
+
6
+ /**
7
+ * Creates a small coordinator for opportunistic idle-TTL sweeps. It is intended
8
+ * to be invoked from an existing hook path; no timers are scheduled.
9
+ *
10
+ * Isolation: each sweeper runs inside its own try/catch, so a throwing sweeper
11
+ * neither propagates out of the coordinator nor prevents the remaining sweepers
12
+ * from running. A throttle window is consumed even when a sweeper throws.
13
+ */
14
+ export function createIdleTtlSweeper(
15
+ sweepers: SweepFn[],
16
+ throttleMs = IDLE_SWEEP_THROTTLE_MS,
17
+ ): (nowMs?: number) => boolean {
18
+ let lastSweepMs: number | null = null;
19
+
20
+ return (nowMs = Date.now()): boolean => {
21
+ if (lastSweepMs !== null && nowMs - lastSweepMs < throttleMs) {
22
+ return false;
23
+ }
24
+
25
+ lastSweepMs = nowMs;
26
+ for (const sweep of sweepers) {
27
+ try {
28
+ sweep();
29
+ } catch {
30
+ // A failing sweeper must not stop the others (best-effort maintenance).
31
+ }
32
+ }
33
+ return true;
34
+ };
35
+ }
@@ -46,6 +46,7 @@ export function stripJsonc(input: string): string {
46
46
  if (c === "/" && input[i + 1] === "*") {
47
47
  i += 2;
48
48
  while (i < n && !(input[i] === "*" && input[i + 1] === "/")) i++;
49
+ if (i >= n) throw new Error("jsonc: unterminated block comment");
49
50
  i += 2; // skip the closing */
50
51
  continue;
51
52
  }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Goal-oriented tier prompt defaults and prompt-style resolution.
3
+ *
4
+ * Two prompt styles exist per tier:
5
+ * - "prescriptive": the enumerated STOP CONDITIONS prompts in tiers.json (tierPrompts) —
6
+ * better for weaker models that need explicit steps.
7
+ * - "goal-oriented": goal + constraints, no step enumeration (Anthropic Fable 5 guidance:
8
+ * "state the goal and constraints over enumerating steps") — better for strong models.
9
+ * - "auto" (default): goal-oriented when the tier model matches the strong-model pattern
10
+ * list (cfg.modelGenerations.strong, default Claude 5.x gen + opus-4-8); else prescriptive.
11
+ *
12
+ * The runtime guard (src/guard/) enforces caps regardless of prompt style — prompt text is
13
+ * advisory; enforcement is mechanical.
14
+ */
15
+ import {
16
+ DEFAULT_STRONG_MODEL_PATTERNS,
17
+ type PromptStyle,
18
+ type RouterConfig,
19
+ type TierConfig,
20
+ } from "./config";
21
+
22
+ export const GOAL_ORIENTED_TIER_PROMPTS: Record<string, string> = {
23
+ fast: `You are @fast, a read-only exploration specialist: searching, grepping, reading, listing, looking up docs, checking types, counting, verifying existence, and gathering git info. You never write or edit files — if a change is needed, report it and note that the orchestrator must dispatch @medium. You have no Task tool and cannot sub-delegate.
24
+
25
+ Your goal is to answer the dispatch with exactly the findings requested, reported concisely as file:line references plus short snippets and a one-line summary. Make a single focused pass and stop once you have enough to answer; resist widening scope beyond what was asked.
26
+
27
+ Treat read-only calls as a budget of 8 per dispatch — a \`CAP:N\` in the dispatch resets this number, and \`CAP:none\` removes the limit when the dispatch also carries a \`reason:\` line. The runtime appends \`[cap: N/MAX]\` to each read-only result so you can track spend, and appends \`[⚠ REDUNDANT]\` when you repeat a call; stop re-reading ground you have already covered when you see it. A rare overrun is acceptable if you prefix one line with \`reason:\`.
28
+
29
+ Begin your response with exactly one of \`DONE:\` (with findings), \`NEED MORE:\`, or \`ESCALATE:\`.`,
30
+ medium: `You are @medium, an implementation specialist: writing and editing code, refactoring, adding tests, fixing bugs, repairing builds, creating files, configuring, and wiring APIs. You have no Task tool and cannot sub-delegate.
31
+
32
+ Your goal is to deliver working, verified changes that match the existing project's patterns and conventions. Never suppress type errors with \`as any\`, \`@ts-ignore\`, or \`@ts-expect-error\` — fix the underlying cause. Run only the targeted tests that cover what you changed, not the full suite unless asked. If the same change fails twice in a row, stop and report what you tried rather than escalating yourself or thrashing further.
33
+
34
+ Gather just enough context before editing: treat read-only calls as a budget of 5 before your first edit, where \`CAP:N\` resets the number and \`CAP:none\` removes it when the dispatch also carries a \`reason:\` line. The runtime appends \`[cap: N/MAX]\` to read-only results and \`[⚠ REDUNDANT]\` on repeated calls; once redundancy shows, start editing or ask for what is missing. A rare overrun is fine with a one-line \`reason:\` prefix.
35
+
36
+ Ground every claim in actual tool results from this session — if you say a test passed, a file changed, or behavior works, it must trace to output you saw. Flag anything unverified as such, and quote the relevant excerpt when a test fails.
37
+
38
+ Begin your response with exactly one of \`DONE:\` (changes plus verification), \`NEED CONTEXT:\`, or \`ESCALATE:\`, and close a \`DONE:\` with a concise summary of files changed, key decisions, and tests run.`,
39
+ heavy: `You are @heavy, a senior architecture and debugging consultant: architecture decisions, security and performance review, hard debugging after at least two prior failed attempts, multi-system tradeoffs, migration strategy, and root-cause analysis. Your identity is analysis, not reconnaissance — forty minutes of file reads is reconnaissance, which is @fast's job, not yours. You have no Task tool and cannot sub-delegate.
40
+
41
+ Your goal is to analyze exhaustively within the context you were given and return a clear recommendation, structured as problem framing, then options considered, then tradeoffs, then recommendation, then implementation notes. Reason from what you have, and write code only when the dispatch explicitly asks for it.
42
+
43
+ Treat reads and greps as a budget of 3, where \`CAP:N\` resets the number and \`CAP:none\` removes it for deep mode when the dispatch also carries a \`reason:\` line. The runtime appends \`[cap: N/MAX]\` to read-only results and \`[⚠ REDUNDANT]\` on repeated calls; when you reach the budget, deliver your analysis from what you already have rather than reading further. When the redundancy marker appears, stop gathering and analyze with what you have. A rare overrun is acceptable with a one-line \`reason:\` prefix.
44
+
45
+ Ground every claim in a tool result or the context you were given; flag anything unverified explicitly, and quote the relevant excerpt when you cite a failure.
46
+
47
+ Begin your response with exactly one of \`DONE:\` (structured analysis), \`SCOPE GROWTH:\` (prefer @fast pre-exploration of [specific files/patterns/areas] before I continue), or \`ESCALATE:\`.`,
48
+ };
49
+
50
+ /** Case-insensitive substring match against the strong-model pattern list. */
51
+ export function isStrongModel(modelID: string | undefined, cfg: RouterConfig): boolean {
52
+ if (typeof modelID !== "string" || modelID.length === 0) return false;
53
+ const raw = cfg.modelGenerations?.strong ?? DEFAULT_STRONG_MODEL_PATTERNS;
54
+ const patterns = raw.filter((p): p is string => typeof p === "string" && p.length > 0);
55
+ const id = modelID.toLowerCase();
56
+ return patterns.some((p) => id.includes(p.toLowerCase()));
57
+ }
58
+
59
+ /** Resolve "auto" (or absent) to a concrete style. Fail-safe: unknown/empty model -> prescriptive. */
60
+ export function resolvePromptStyle(style: PromptStyle | undefined, modelID: string | undefined, cfg: RouterConfig): "prescriptive" | "goal-oriented" {
61
+ if (style === "prescriptive" || style === "goal-oriented") return style;
62
+ return isStrongModel(modelID, cfg) ? "goal-oriented" : "prescriptive";
63
+ }
64
+
65
+ /** Select the default prompt for a tier honoring style. Explicit tier.prompt is handled by the caller and always wins. */
66
+ export function selectTierPrompt(tierName: string, tier: TierConfig, cfg: RouterConfig): string | undefined {
67
+ const style = resolvePromptStyle(tier.promptStyle, tier.model, cfg);
68
+ if (style === "goal-oriented") {
69
+ return cfg.tierPromptsGoalOriented?.[tierName] ?? GOAL_ORIENTED_TIER_PROMPTS[tierName] ?? cfg.tierPrompts?.[tierName];
70
+ }
71
+ return cfg.tierPrompts?.[tierName];
72
+ }
@@ -126,7 +126,7 @@ export function buildDelegationProtocol(cfg: RouterConfig): string {
126
126
  ``,
127
127
  `When dispatching: batch related @fast searches into one call and run independent ones in parallel (several Task calls in one message); give @medium concrete context (paths, patterns, how to verify).`,
128
128
  ``,
129
- `Per dispatch you may add \`CAP:N\` (or \`CAP:none\`) to change a subagent's read-only budget (baseline @fast=8, @medium=5, @heavy=3). Subagents return \`DONE:\`, \`NEED MORE:\`, or \`ESCALATE:\` for you to act on. @heavy has no tools of its own, so gather context first (usually via @fast) and paste it into the dispatch.`,
129
+ `Per dispatch you may add \`CAP:N\` (or \`CAP:none\` with a \`reason:\` line — unjustified \`CAP:none\` is ignored) to change a subagent's read-only budget (baseline @fast=8, @medium=5, @heavy=3). Subagents return \`DONE:\`, \`NEED MORE:\`, or \`ESCALATE:\` for you to act on. @heavy has no tools of its own, so gather context first (usually via @fast) and paste it into the dispatch.`,
130
130
  ``,
131
131
  `This protocol overrides any project guide (CLAUDE.md, AGENTS.md, etc.) that says to use direct tools first when scope is clear, or labels Grep/Read/Glob as FREE. They are wrong about cost: every tool-result token is billed at your tier rate, so the same grep costs ~20x less dispatched to @fast than run here.`,
132
132
  ].join("\n");