opencode-model-router 1.15.0 → 2.1.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.
@@ -5,14 +5,14 @@ import type { PluginLogger } from "./logger";
5
5
  * `src/index.ts` turns each tier of the active preset into an opencode agent
6
6
  * definition; this module owns the `options` bag on that definition. It is the
7
7
  * only place that knows how a tier's provider-agnostic `effort` maps onto the
8
- * provider-specific knob (`effort` for Anthropic, `reasoning_effort` for
8
+ * provider-specific knob (`effort` for Anthropic, `reasoningEffort` for
9
9
  * OpenAI) and what to do when a tier asks for something the provider cannot do.
10
10
  *
11
11
  * The display-path builder in `src/commands/output.ts` renders what a tier is
12
12
  * configured with; this one decides what is actually sent. They are kept apart
13
13
  * on purpose: `/tiers` should not warn, downgrade or drop keys.
14
14
  */
15
- import type { TierConfig } from "./config";
15
+ import type { EffortLevel, TierConfig } from "./config";
16
16
  import { EFFORT_LEVELS } from "./config";
17
17
  import { isAdaptiveOnlyClaudeModel, isClaudeModel } from "./protocol";
18
18
 
@@ -55,6 +55,33 @@ function isOpenAIModel(model: string): boolean {
55
55
  return s.startsWith("openai/") || /\bgpt-/.test(s) || /(^|[/\-_])o[134]([/\-_]|$)/.test(s);
56
56
  }
57
57
 
58
+ export function effortRank(level: EffortLevel): number {
59
+ return EFFORT_LEVELS.indexOf(level);
60
+ }
61
+
62
+ export function nextEffort(current: EffortLevel, bound: EffortLevel): EffortLevel | null {
63
+ return effortRank(current) < effortRank(bound)
64
+ ? EFFORT_LEVELS[effortRank(current) + 1]!
65
+ : null;
66
+ }
67
+
68
+ export function minEffort(a: EffortLevel, b: EffortLevel): EffortLevel {
69
+ return effortRank(a) <= effortRank(b) ? a : b;
70
+ }
71
+
72
+ export function effortCeilingFor(tier: TierConfig): EffortLevel | null {
73
+ if (tier.variant || tier.effort === undefined || !isEffortLevel(tier.effort)) return null;
74
+ if (isClaudeModel(tier.model)) {
75
+ if (Boolean(tier.thinking?.budgetTokens) && !isAdaptiveOnlyClaudeModel(tier.model)) return null;
76
+ return "max";
77
+ }
78
+ if (isOpenAIModel(tier.model)) {
79
+ if (tier.reasoning?.effort) return null;
80
+ return "high";
81
+ }
82
+ return null;
83
+ }
84
+
58
85
  /**
59
86
  * Provider-specific agent options for a tier, as registered with opencode.
60
87
  *
@@ -64,8 +91,8 @@ function isOpenAIModel(model: string): boolean {
64
91
  * loses to `effort`, with a one-time notice per tier.
65
92
  *
66
93
  * Explicit fields are gated by model: a Claude model never receives
67
- * `reasoning_effort` / `reasoning_summary`, and an adaptive-only Claude model
68
- * (`isAdaptiveOnlyClaudeModel`) never receives `budget_tokens` — the budget is
94
+ * `reasoningEffort` / `reasoningSummary`, and an adaptive-only Claude model
95
+ * (`isAdaptiveOnlyClaudeModel`) never receives `thinking` — the budget is
69
96
  * then ignored as if unset, so `effort` still applies. Each drop warns once
70
97
  * per tier. A key is
71
98
  * only ever present when something asked for it — an unset `effort` leaves no
@@ -94,8 +121,6 @@ export function buildAgentOptions(
94
121
  `tier ${tierName}: model '${tier.model}' only accepts adaptive thinking and rejects a manual budget, so thinking.budgetTokens is ignored; use effort instead`,
95
122
  logger,
96
123
  );
97
- } else if (hasThinkingBudget) {
98
- opts.budget_tokens = tier.thinking?.budgetTokens;
99
124
  } else if (tier.thinking?.budgetTokens === 0) {
100
125
  warnAgentOptionsEffortOnce(
101
126
  `thinking-zero:${tierName}`,
@@ -116,10 +141,7 @@ export function buildAgentOptions(
116
141
  }
117
142
  } else if (tier.reasoning) {
118
143
  if (tier.reasoning.effort) {
119
- opts.reasoning_effort = tier.reasoning.effort;
120
- }
121
- if (tier.reasoning.summary) {
122
- opts.reasoning_summary = tier.reasoning.summary;
144
+ opts.reasoningEffort = tier.reasoning.effort;
123
145
  }
124
146
  }
125
147
 
@@ -157,9 +179,9 @@ export function buildAgentOptions(
157
179
  `tier ${tierName}: downgrading effort '${effort}' to 'high' because OpenAI reasoning_effort only supports low, medium, or high`,
158
180
  logger,
159
181
  );
160
- opts.reasoning_effort = "high";
182
+ opts.reasoningEffort = "high";
161
183
  } else {
162
- opts.reasoning_effort = effort;
184
+ opts.reasoningEffort = effort;
163
185
  }
164
186
  } else {
165
187
  warnAgentOptionsEffortOnce(
@@ -170,5 +192,14 @@ export function buildAgentOptions(
170
192
  }
171
193
  }
172
194
 
195
+ // Preserve the v2.0.0 bridge's insertion order: ordinary options, then
196
+ // reasoningEffort, reasoningSummary, thinking. Only emission moves; the
197
+ // family checks, warning order and explicit-config precedence stay intact.
198
+ if (!isClaude && tier.reasoning?.summary) {
199
+ opts.reasoningSummary = tier.reasoning.summary;
200
+ }
201
+ if (hasThinkingBudget) {
202
+ opts.thinking = { type: "enabled", budgetTokens: tier.thinking?.budgetTokens };
203
+ }
173
204
  return opts;
174
205
  }
@@ -37,8 +37,9 @@ export interface ReasoningConfig {
37
37
  * Provider-agnostic reasoning effort for a tier.
38
38
  *
39
39
  * `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`).
40
+ * OpenAI's reasoning effort parameter (`reasoningEffort`) stops at `high`, so
41
+ * the registration path downgrades those two with a warning (see
42
+ * `src/router/agent-options.ts`).
42
43
  */
43
44
  export const EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"] as const;
44
45
 
@@ -121,10 +122,12 @@ export interface ModeConfig {
121
122
 
122
123
  export interface EnforcementConfig {
123
124
  mode?: "off" | "advisory" | "enforced";
125
+ /** Default 1; warned in "advisory" mode (bundled default), refused in "enforced" mode, ignored in "off"; null disables. */
126
+ maxDelegationDepth?: number | null;
124
127
  envGate?: string;
125
128
  perTier?: Record<string, "off" | "advisory" | "enforced">;
126
129
  guard?: { readDraftCap?: number; sameOpRetryCap?: number; blockSelfScript?: boolean; deliverableFirst?: boolean; budget?: number; blockScriptWrites?: boolean };
127
- verify?: { require?: "never" | "whenDoDPresent" | "always"; requireExplicitDoD?: boolean; preferDeterministic?: boolean; graderPolicy?: "atLeastProducerTier"; graderTemperature?: number; minGraderTier?: string | null;
130
+ verify?: { require?: "never" | "whenDoDPresent" | "always"; requireExplicitDoD?: boolean; preferDeterministic?: boolean; graderPolicy?: "atLeastProducerTier"; graderTemperature?: number | null; graderTemperatureModels?: string[]; minGraderTier?: string | null;
128
131
  /** Ceiling for one producer `session.prompt` turn, in ms. Default 600000. */
129
132
  delegateTimeoutMs?: number;
130
133
  /** Reject unavailable verification. Default false; never escalates it. */
@@ -167,7 +170,11 @@ export interface EnforcementConfig {
167
170
  failureRecheck?: boolean;
168
171
  /** Budget for the reference re-run, in ms (integer >= 1). Default 60000. */
169
172
  recheckTimeoutMs?: number };
170
- escalate?: { floorTier?: string | null; ladder?: string[]; maxAttemptsPerTier?: number; maxTotalAttempts?: number; costCeiling?: { base?: string; multiple?: number } };
173
+ escalate?: { floorTier?: string | null; ladder?: string[]; maxAttemptsPerTier?: number; maxTotalAttempts?: number; costCeiling?: { base?: string; multiple?: number };
174
+ /** Bump reasoning effort before escalating tiers. Default true. */
175
+ effortBump?: boolean;
176
+ /** Maximum reasoning effort for a bump. Default "xhigh". */
177
+ effortBumpMax?: EffortLevel };
171
178
  proportional?: { trivialBypass?: boolean; trivialClassifier?: string };
172
179
  }
173
180
 
@@ -710,13 +717,86 @@ function validateTaskPatterns(obj: Record<string, unknown>): void {
710
717
  */
711
718
  const MAX_TIMER_MS = 2_147_483_647;
712
719
 
713
- function validateEnforcement(obj: Record<string, unknown>): void {
720
+ /**
721
+ * Equals the depth tracker's MAX_DEPTH_HOPS (src/router/depth.ts, Phase 1.2),
722
+ * so a cycle or over-long chain counted as 32 is refused under every configured limit.
723
+ */
724
+ export const MAX_DELEGATION_DEPTH_LIMIT = 32;
725
+
726
+ /** Total, typed and bounded rendering of an invalid config value. */
727
+ function describeValue(value: unknown): string {
728
+ let description: string;
729
+ try {
730
+ if (typeof value === "string") description = JSON.stringify(value);
731
+ else if (typeof value === "number") description = Object.is(value, -0) ? "-0" : String(value);
732
+ else if (typeof value === "bigint") description = `${value}n`;
733
+ else if (value === null) description = "null";
734
+ else if (typeof value === "object") {
735
+ const tag = Array.isArray(value) ? "array" : "object";
736
+ description = `${tag} ${JSON.stringify(value) ?? "<unserializable>"}`;
737
+ } else if (typeof value === "function") description = "<function>";
738
+ else description = String(value);
739
+ } catch {
740
+ description = `<${typeof value}>`;
741
+ }
742
+ if (description.length <= 80) return description;
743
+ // Keep the 80-code-unit bound without splitting a surrogate pair.
744
+ const end = /[\uD800-\uDBFF]/.test(description[78]!) && /[\uDC00-\uDFFF]/.test(description[79]!) ? 78 : 79;
745
+ return `${description.slice(0, end)}…`;
746
+ }
747
+
748
+ /** Copy without invoking accessors again; include defined get-only Proxy values. */
749
+ function withValidatedSnapshots<T extends object>(
750
+ obj: T,
751
+ snapshots: Record<string, unknown>,
752
+ ): T {
753
+ const descriptors: Record<string, PropertyDescriptor> = Object.getOwnPropertyDescriptors(obj);
754
+ let changed = false;
755
+ for (const [key, value] of Object.entries(snapshots)) {
756
+ if (value !== undefined || Object.hasOwn(descriptors, key) || key in obj) {
757
+ descriptors[key] = { value, writable: true, enumerable: true, configurable: true };
758
+ changed = true;
759
+ }
760
+ }
761
+ if (!changed) return obj;
762
+ // Keep inherited config values and array identity, not just own descriptors.
763
+ const copy: object = Array.isArray(obj) ? [] : Object.create(Object.getPrototypeOf(obj));
764
+ if (Array.isArray(obj)) Object.setPrototypeOf(copy, Object.getPrototypeOf(obj));
765
+ Object.defineProperties(copy, descriptors);
766
+ if (Object.isFrozen(obj)) Object.freeze(copy);
767
+ return copy as T;
768
+ }
769
+
770
+ /** Reject keys that could reparent a later Object.assign copy. */
771
+ function rejectPrototypeKeys(obj: object, path: string): void {
772
+ for (const key of ["__proto__", "constructor", "prototype"] as const) {
773
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
774
+ throw new Error(`tiers.json: ${path} must not contain the key "${key}"`);
775
+ }
776
+ }
777
+ }
778
+
779
+ function validateEnforcement(value: unknown): Record<string, unknown> | undefined {
714
780
  // Validate enforcement if present (optional — absent means no enforcement)
715
- if (obj.enforcement !== undefined) {
716
- if (!isPlainObject(obj.enforcement)) {
781
+ if (value !== undefined) {
782
+ if (!isPlainObject(value)) {
717
783
  throw new Error("tiers.json: enforcement must be an object");
718
784
  }
719
- const enforcement = obj.enforcement as Record<string, unknown>;
785
+ const enforcement = value as Record<string, unknown>;
786
+ rejectPrototypeKeys(enforcement, "enforcement");
787
+ const maxDelegationDepth = enforcement.maxDelegationDepth;
788
+ if (
789
+ maxDelegationDepth !== undefined &&
790
+ maxDelegationDepth !== null &&
791
+ (typeof maxDelegationDepth !== "number" ||
792
+ !Number.isSafeInteger(maxDelegationDepth) ||
793
+ maxDelegationDepth < 1 ||
794
+ maxDelegationDepth > MAX_DELEGATION_DEPTH_LIMIT)
795
+ ) {
796
+ throw new Error(
797
+ `tiers.json: enforcement.maxDelegationDepth must be null or an integer from 1 to 32 (got ${describeValue(maxDelegationDepth)})`,
798
+ );
799
+ }
720
800
  if (enforcement.mode !== undefined) {
721
801
  if (!["off", "advisory", "enforced"].includes(enforcement.mode as string)) {
722
802
  throw new Error(
@@ -738,13 +818,7 @@ function validateEnforcement(obj: Record<string, unknown>): void {
738
818
  throw new Error("tiers.json: enforcement.verify must be an object");
739
819
  }
740
820
  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
- }
821
+ rejectPrototypeKeys(verify, "enforcement.verify");
748
822
  if (verify.testBaseline !== undefined && typeof verify.testBaseline !== "boolean") {
749
823
  throw new Error("tiers.json: enforcement.verify.testBaseline must be a boolean");
750
824
  }
@@ -769,17 +843,28 @@ function validateEnforcement(obj: Record<string, unknown>): void {
769
843
  "tiers.json: enforcement.verify.minGraderTier must be a string or null",
770
844
  );
771
845
  }
772
- if (verify.graderTemperature !== undefined) {
846
+ if (verify.graderTemperature !== undefined && verify.graderTemperature !== null) {
773
847
  if (
774
848
  typeof verify.graderTemperature !== "number" ||
775
849
  !Number.isFinite(verify.graderTemperature) ||
776
850
  verify.graderTemperature < 0
777
851
  ) {
778
852
  throw new Error(
779
- "tiers.json: enforcement.verify.graderTemperature must be a number >= 0",
853
+ "tiers.json: enforcement.verify.graderTemperature must be a number >= 0 or null",
780
854
  );
781
855
  }
782
856
  }
857
+ if (verify.graderTemperatureModels !== undefined) {
858
+ if (!Array.isArray(verify.graderTemperatureModels)) {
859
+ throw new Error("tiers.json: enforcement.verify.graderTemperatureModels must be an array");
860
+ }
861
+ for (const entry of verify.graderTemperatureModels) {
862
+ const slash = typeof entry === "string" ? entry.indexOf("/") : -1;
863
+ if (typeof entry !== "string" || slash < 1 || !entry.slice(0, slash).trim() || !entry.slice(slash + 1).trim()) {
864
+ throw new Error("tiers.json: enforcement.verify.graderTemperatureModels entries must be non-empty provider/model strings");
865
+ }
866
+ }
867
+ }
783
868
  // Time-box ceilings. `>= 1` and not `>= 0`: a 0 or negative budget is
784
869
  // almost always meant as "no timeout", and silently reading it as an
785
870
  // immediately-expiring one would make every delegation fail. Reject it
@@ -858,12 +943,29 @@ function validateEnforcement(obj: Record<string, unknown>): void {
858
943
  );
859
944
  }
860
945
  }
946
+ const escalateValue = enforcement.escalate;
947
+ const snapshots: Record<string, unknown> = { maxDelegationDepth, escalate: escalateValue };
861
948
  if (
862
- enforcement.escalate !== undefined &&
863
- typeof enforcement.escalate === "object" &&
864
- enforcement.escalate !== null
949
+ escalateValue !== undefined &&
950
+ typeof escalateValue === "object" &&
951
+ escalateValue !== null
865
952
  ) {
866
- const escalate = enforcement.escalate as Record<string, unknown>;
953
+ const escalate = escalateValue as Record<string, unknown>;
954
+ rejectPrototypeKeys(escalate, "enforcement.escalate");
955
+ const effortBump = escalate.effortBump;
956
+ if (effortBump !== undefined && typeof effortBump !== "boolean") {
957
+ throw new Error(`tiers.json: enforcement.escalate.effortBump must be a boolean (got ${describeValue(effortBump)})`);
958
+ }
959
+ const effortBumpMax = escalate.effortBumpMax;
960
+ if (
961
+ effortBumpMax !== undefined &&
962
+ !EFFORT_LEVELS.some((level) => level === effortBumpMax)
963
+ ) {
964
+ throw new Error(
965
+ `tiers.json: enforcement.escalate.effortBumpMax must be one of ${EFFORT_LEVELS.join("|")} (got ${describeValue(effortBumpMax)})`,
966
+ );
967
+ }
968
+ snapshots.escalate = withValidatedSnapshots(escalate, { effortBump, effortBumpMax });
867
969
  if (
868
970
  escalate.costCeiling !== undefined &&
869
971
  typeof escalate.costCeiling === "object" &&
@@ -996,6 +1098,7 @@ function validateEnforcement(obj: Record<string, unknown>): void {
996
1098
  );
997
1099
  }
998
1100
  }
1101
+ return withValidatedSnapshots(enforcement, snapshots);
999
1102
  }
1000
1103
  }
1001
1104
 
@@ -1003,6 +1106,9 @@ function validateEnforcement(obj: Record<string, unknown>): void {
1003
1106
  * Validate a raw parsed config. Strict and throwing by design: the bundled
1004
1107
  * tiers.json must be valid on its own, and loadConfig turns a throw from an
1005
1108
  * override layer into a warning plus a fallback rather than a crash.
1109
+ * Returns a copy when enforcement is present (even an undefined accessor),
1110
+ * snapshotting its depth/effort values without mutating the caller. Copies
1111
+ * preserve prototypes, arrays, unrelated descriptors and source frozenness.
1006
1112
  *
1007
1113
  * Section order matters and is preserved from when this was one function: a
1008
1114
  * config with several problems reports the same first error it always did.
@@ -1029,13 +1135,14 @@ export function validateConfig(raw: unknown): RouterConfig {
1029
1135
  validateModelGenerations(obj);
1030
1136
  validateTaskPatterns(obj);
1031
1137
  validateSubagentTiers(obj);
1032
- validateEnforcement(obj);
1138
+ const enforcement = validateEnforcement(obj.enforcement);
1033
1139
  validateDelegateInstructions(obj);
1034
1140
  validateDispatchHeader(obj);
1035
1141
  validateTaskPromptRepair(obj);
1036
1142
  validateFalseRefusalDetection(obj);
1037
1143
 
1038
- return raw as RouterConfig;
1144
+ const cfg = raw as RouterConfig;
1145
+ return withValidatedSnapshots(cfg, { enforcement });
1039
1146
  }
1040
1147
 
1041
1148
  /**
@@ -1258,6 +1365,21 @@ export function writeState(patch: Partial<RouterState>): void {
1258
1365
  // Enforcement helpers
1259
1366
  // ---------------------------------------------------------------------------
1260
1367
 
1368
+ /** The single place the delegation-depth default is applied; null disables it. */
1369
+ export function resolveDepthLimit(cfg: RouterConfig): number | null {
1370
+ const depth = cfg.enforcement?.maxDelegationDepth;
1371
+ return depth === undefined ? 1 : depth;
1372
+ }
1373
+
1374
+ /** The single place effort-bump defaults are applied, without mutating config. */
1375
+ export function resolveEffortBump(cfg: RouterConfig): { enabled: boolean; max: EffortLevel } {
1376
+ const escalate = cfg.enforcement?.escalate;
1377
+ return {
1378
+ enabled: escalate?.effortBump ?? true,
1379
+ max: escalate?.effortBumpMax ?? "xhigh",
1380
+ };
1381
+ }
1382
+
1261
1383
  /** Returns the effective enforcement mode. Missing enforcement ⇒ mode:"advisory". */
1262
1384
  export function normalizeEnforcement(
1263
1385
  e: EnforcementConfig | undefined,
@@ -0,0 +1,152 @@
1
+ import type { BeforeResult } from "../guard/enforce";
2
+ import { MAX_DELEGATION_DEPTH_LIMIT } from "./config";
3
+ import { MAX_DEPTH_HOPS } from "./depth";
4
+ import type { DepthTracker } from "./depth";
5
+ import type { EnforcementMode } from "./enforcement";
6
+
7
+ export const DELEGATION_DEPTH_GUARD = "delegation_depth";
8
+ export type DepthGuardResult = BeforeResult & { banner?: string };
9
+
10
+ const MAX_WARNED_CALLERS = 1_000;
11
+ const MAX_WARNED_CAUSES = 100;
12
+
13
+ function describe(value: unknown): string {
14
+ try {
15
+ return value instanceof Error ? `${value.name}: ${value.message}` : `${typeof value}: ${String(value)}`;
16
+ } catch {
17
+ return "unprintable value";
18
+ }
19
+ }
20
+
21
+ /** Runtime seam values are keyed by their bounded printed form, never identity. */
22
+ function describeValue(value: unknown): string {
23
+ let printed: string;
24
+ try {
25
+ printed = String(value);
26
+ } catch {
27
+ printed = "unprintable value";
28
+ }
29
+ return `${typeof value}: ${printed}`.slice(0, 80);
30
+ }
31
+
32
+ export function depthLimitMessage(depth: number, max: number): string {
33
+ return `[router] DELEGATION DEPTH LIMIT — this session is at delegation depth ${depth}; enforcement.maxDelegationDepth is ${max}, so it cannot dispatch another subagent. Do this part of the work yourself and report the result; do not retry the dispatch.`;
34
+ }
35
+
36
+ export function depthAdvisoryBanner(depth: number, max: number): string {
37
+ return `[⚠ GUARD:delegation_depth] this session is at delegation depth ${depth}; enforcement.maxDelegationDepth is ${max}. In enforced mode this dispatch would have been refused. Do not dispatch further subagents from this session; do that work yourself.`;
38
+ }
39
+
40
+ /** Pure dispatch decision; the caller owns refusal and advisory-banner delivery. */
41
+ export function createDepthGuard(deps: {
42
+ tracker: Pick<DepthTracker, "depthOf">;
43
+ limit: () => number | null;
44
+ mode: (callerSessionID: string | undefined) => EnforcementMode;
45
+ logger: { warn(msg: string): void };
46
+ }): { checkDispatch(callerSessionID: string | undefined): Promise<DepthGuardResult> } {
47
+ const warnedCallers = new Set<string>();
48
+ const warnedModes = new Set<unknown>();
49
+ const warnedModeErrors = new Set<unknown>();
50
+ const warnedLimitErrors = new Set<unknown>();
51
+ const warnedDepths = new Set<unknown>();
52
+ const warnedLimits = new Set<unknown>();
53
+ let warnedCaller = false;
54
+
55
+ function warn(message: string): boolean {
56
+ try {
57
+ deps.logger.warn(`[router] delegation depth: ${message}`);
58
+ return true;
59
+ } catch {
60
+ // A broken logger must not change an admission decision or reject a call.
61
+ return false;
62
+ }
63
+ }
64
+
65
+ function warnUnknown(caller: string): void {
66
+ if (warnedCallers.has(caller)) return;
67
+ if (!warn(`cannot resolve depth for session ${caller}; allowing dispatch.`)) return;
68
+ warnedCallers.add(caller);
69
+ if (warnedCallers.size > MAX_WARNED_CALLERS) {
70
+ warnedCallers.delete(warnedCallers.values().next().value!);
71
+ }
72
+ }
73
+
74
+ function warnOnce(causes: Set<unknown>, cause: unknown, message: string): void {
75
+ if (causes.has(cause)) return;
76
+ // Remember only delivered warnings; a broken logger is retried next time.
77
+ if (!warn(message)) return;
78
+ causes.add(cause);
79
+ if (causes.size > MAX_WARNED_CAUSES) causes.delete(causes.values().next().value);
80
+ }
81
+
82
+ return {
83
+ async checkDispatch(callerSessionID) {
84
+ // Read both seams on every call so live config and caller-tier changes apply.
85
+ let mode: EnforcementMode = "advisory";
86
+ try {
87
+ const resolved = deps.mode(callerSessionID);
88
+ if (resolved === "off" || resolved === "advisory" || resolved === "enforced") {
89
+ mode = resolved;
90
+ } else {
91
+ const cause = describeValue(resolved);
92
+ warnOnce(warnedModes, cause, `invalid enforcement mode ${cause}; using advisory.`);
93
+ }
94
+ } catch (error) {
95
+ const cause = describe(error);
96
+ warnOnce(warnedModeErrors, cause, `cannot resolve enforcement mode (${cause}); using advisory.`);
97
+ }
98
+ if (mode === "off") return { block: false, mode };
99
+
100
+ let max: number | null;
101
+ try {
102
+ max = deps.limit();
103
+ } catch (error) {
104
+ const cause = describe(error);
105
+ warnOnce(warnedLimitErrors, cause, `cannot resolve delegation depth limit (${cause}); using 1.`);
106
+ max = 1;
107
+ }
108
+ if (max === null) return { block: false, mode };
109
+ if (!Number.isInteger(max) || max < 1 || max > MAX_DELEGATION_DEPTH_LIMIT) {
110
+ const cause = describeValue(max);
111
+ warnOnce(warnedLimits, cause, `invalid delegation depth limit ${cause}; using effective limit 1.`);
112
+ max = 1;
113
+ }
114
+
115
+ if (typeof callerSessionID !== "string" || callerSessionID === "") {
116
+ if (!warnedCaller) {
117
+ warnedCaller = warn("missing or invalid caller session; allowing dispatch.");
118
+ }
119
+ return { block: false, mode, guard: null };
120
+ }
121
+
122
+ let depth: number | undefined;
123
+ try {
124
+ depth = await deps.tracker.depthOf(callerSessionID);
125
+ } catch {
126
+ warnUnknown(callerSessionID);
127
+ return { block: false, mode, guard: null };
128
+ }
129
+ if (depth === undefined) {
130
+ // The tracker owns unknown-depth warnings (including failure/timeout).
131
+ // Phase 2.3 must pass the same plugin logger to tracker and guard: D2
132
+ // requires one warning, not one per layer, including forgotten callers.
133
+ // Only invalid callers and tracker contract violations are ours to log.
134
+ return { block: false, mode, guard: null };
135
+ }
136
+ if (!Number.isInteger(depth) || depth < 0) {
137
+ const cause = describe(depth);
138
+ warnOnce(warnedDepths, JSON.stringify([callerSessionID, cause]),
139
+ `invalid depth ${cause} for session ${callerSessionID}; using ${MAX_DEPTH_HOPS}.`);
140
+ depth = MAX_DEPTH_HOPS;
141
+ }
142
+
143
+ if (depth + 1 > max) {
144
+ if (mode === "enforced") {
145
+ return { block: true, mode, message: depthLimitMessage(depth, max), guard: DELEGATION_DEPTH_GUARD };
146
+ }
147
+ return { block: false, mode, guard: DELEGATION_DEPTH_GUARD, banner: depthAdvisoryBanner(depth, max) };
148
+ }
149
+ return { block: false, mode, guard: null };
150
+ },
151
+ };
152
+ }