opencode-model-router 2.3.0 → 2.4.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.
Files changed (61) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/README.md +56 -10
  3. package/package.json +1 -1
  4. package/src/commands/output.ts +21 -1
  5. package/src/compat/v2-hooks.ts +1322 -18
  6. package/src/escalate/ladder.ts +12 -0
  7. package/src/guard/enforce.ts +186 -22
  8. package/src/guard/guards.ts +132 -6
  9. package/src/guard/store.ts +5 -0
  10. package/src/index.ts +718 -29
  11. package/src/router/config.ts +247 -1
  12. package/src/router/dispatch-header.ts +46 -4
  13. package/src/router/git-tools.ts +1152 -0
  14. package/src/router/guard-profile.ts +100 -0
  15. package/src/router/plugin-agents.ts +433 -0
  16. package/src/router/prompts.ts +26 -1
  17. package/src/router/protocol.ts +133 -0
  18. package/src/router/read-only.ts +149 -0
  19. package/src/router/role-agents.ts +409 -0
  20. package/src/router/roles-config.ts +429 -0
  21. package/src/router/roles.ts +600 -0
  22. package/src/router/run-tools.ts +913 -0
  23. package/src/router/sensitive-paths.ts +101 -0
  24. package/src/router/sessions.ts +92 -0
  25. package/src/router/subagents.ts +28 -1
  26. package/src/routing/advisor/findings.ts +193 -1
  27. package/src/routing/advisor/index.ts +13 -5
  28. package/src/routing/classify/index.ts +23 -5
  29. package/src/routing/classify/route-line.ts +67 -3
  30. package/src/routing/classify/rules.ts +80 -20
  31. package/src/routing/classify/types.ts +34 -4
  32. package/src/routing/commands/stats.ts +3 -0
  33. package/src/routing/engine/kernel.ts +163 -0
  34. package/src/routing/engine/ladders.ts +242 -1
  35. package/src/routing/engine/protocol-line.ts +17 -0
  36. package/src/routing/engine/roles-taxonomy.ts +52 -0
  37. package/src/routing/engine/types.ts +99 -1
  38. package/src/routing/outcomes/beta.ts +10 -4
  39. package/src/routing/outcomes/index.ts +44 -1
  40. package/src/routing/outcomes/ingest.ts +163 -15
  41. package/src/routing/outcomes/persist.ts +23 -1
  42. package/src/routing/outcomes/signals.ts +650 -0
  43. package/src/routing/outcomes/stats.ts +273 -2
  44. package/src/routing/outcomes/store.ts +25 -5
  45. package/src/routing/outcomes/types.ts +145 -6
  46. package/src/routing/roles/authority.ts +495 -0
  47. package/src/routing/roles/binding.ts +543 -0
  48. package/src/routing/roles/policy.ts +416 -0
  49. package/src/routing/roles/work-root.ts +132 -0
  50. package/src/routing/wire/dispatch.ts +1306 -17
  51. package/src/routing/wire/hint.ts +14 -0
  52. package/src/routing/wire/runtime.ts +117 -28
  53. package/src/v2.ts +26 -1
  54. package/src/verify/checker.ts +249 -7
  55. package/src/verify/deterministic.ts +10 -1
  56. package/src/verify/dispatch.ts +63 -6
  57. package/src/verify/dod.ts +127 -10
  58. package/src/verify/gate.ts +75 -7
  59. package/src/verify/types.ts +12 -0
  60. package/src/verify/wiring.ts +55 -10
  61. package/tiers.json +13 -5
@@ -0,0 +1,543 @@
1
+ /**
2
+ * Child-session binding (plan §2.4, §2.5; spikes S2, amendments P-2 and R7; invariants I5, I9).
3
+ *
4
+ * A role dispatch registers a pending entry in `execute.before` (keyed by parent session + callID) with a
5
+ * router-generated nonce ({@link newDispatchNonce}); P2.1 appends {@link nonceTitleSuffix} to the `subagent`
6
+ * description and {@link noncePromptLine} as the LAST line of its prompt. The child session binds lazily, at its
7
+ * first context hook (or permission evaluation), from `session.get(child)`: parentID, agent, title, first
8
+ * message.
9
+ *
10
+ * Decision (one per child, process-wide; R7: no nonce → unknown):
11
+ * - no parentID/agent, or a failed lookup → unknown, not cached (the next hook retries);
12
+ * - markers are read only at their anchors: the title's trailing ` [nonce <n>]` suffix and the prompt's last
13
+ * non-empty line `OMR_NONCE=<n>` (quoted marker syntax anywhere else is plain text). Both present and
14
+ * different → unknown; none → unknown;
15
+ * - the nonce names a live entry of the child's parent and agent that no other child has claimed → exact (the
16
+ * entry is claimed: one dispatch binds at most one child); a retired, unregistered, foreign or claimed nonce →
17
+ * unknown. Two identical parallel dispatches therefore each bind exactly by their own nonce.
18
+ * Every caller sees the decision ∩ its own role max (`maxOf(agent)`, required), then the separation rule (I4:
19
+ * egress dropped when mixed) and the work-root rule (I9: no `router_run` without an absolute work root). An
20
+ * unknown binding is max ∩ local, whatever `policy.grantFor` would give. Never a union. The `intersection` kind
21
+ * stays in the contract but is never produced under R7.
22
+ *
23
+ * Lifetimes: a pending entry lives until `evictCall(parent, callID)` (the parent's call completed,
24
+ * `execute.after`), at most {@link PENDING_TTL_MS} (checked on access) and {@link PENDING_MAX} entries (oldest
25
+ * evicted). Nonces of removed entries stay retired for the TTL and are never reused. A decision is cached per
26
+ * child until `evict(childSessionID)` or `evict(parentSessionID)` (`session.deleted`; deleted sessions are
27
+ * tombstoned for the TTL, so an in-flight lookup never stores a binding to them), LRU-bounded by
28
+ * {@link BOUND_MAX}; a resume returns the cached binding with its widened grant.
29
+ *
30
+ * Residual (accepted): a child that lost both own markers but whose anchors carry a live, unclaimed sibling's nonce binds to it (unguessable UUID).
31
+ *
32
+ * State lives on `globalThis` under a versioned `Symbol.for` key, so every copy of this module in the process
33
+ * (two plugin instances) shares one registry and one decision per child; a foreign value there is replaced.
34
+ */
35
+
36
+ import { randomUUID } from "node:crypto";
37
+ import { isAbsolute } from "node:path";
38
+ import type { AuthorityAction } from "../../router/roles";
39
+ import { GRANT_NOTES, type DispatchGrant } from "./policy";
40
+
41
+ export interface PendingDispatch {
42
+ parentSessionID: string;
43
+ callID: string;
44
+ agent: string;
45
+ description: string;
46
+ /** Router-generated per-dispatch nonce ({@link newDispatchNonce}): 16–128 of `A-Z a-z 0-9 _ -`, else refused. */
47
+ nonce: string;
48
+ grant: DispatchGrant;
49
+ /** Call budget of the dispatch: finite and > 0, otherwise the entry is refused. */
50
+ budget: number;
51
+ decisionID: string | null;
52
+ registeredAt: number;
53
+ }
54
+
55
+ export type SessionLookup = (
56
+ id: string,
57
+ ) => Promise<{ parentID?: string; agent?: string; title?: string; firstText?: string } | undefined>;
58
+
59
+ export interface Binding {
60
+ childSessionID: string;
61
+ /** `intersection` is part of the contract but never produced under R7 (ambiguity → unknown). */
62
+ kind: "exact" | "intersection" | "unknown";
63
+ grant: DispatchGrant;
64
+ /** callIDs of the pending dispatches that matched. */
65
+ candidates: readonly string[];
66
+ decisionID: string | null;
67
+ /** Call budget of the matched dispatch. null (unknown binding) means the role's default budget — never unlimited. */
68
+ budget: number | null;
69
+ }
70
+
71
+ export interface BindOptions {
72
+ /**
73
+ * The role max (allow − deny) of an agent. Every grant is intersected with it; `execute` is never part of
74
+ * it. Undefined, a throw, or a missing option → no action at all (fail closed).
75
+ */
76
+ maxOf(agent: string): Iterable<AuthorityAction> | undefined;
77
+ }
78
+
79
+ /** Pending entries live at most 30 min (§2.5); retired nonces and deleted sessions are remembered as long. */
80
+ export const PENDING_TTL_MS = 30 * 60 * 1000;
81
+ /** Pending entries kept at most; the oldest is evicted first. */
82
+ export const PENDING_MAX = 512;
83
+ /** Bound children kept at most (least recently used evicted first). */
84
+ export const BOUND_MAX = 4096;
85
+ const RETIRED_MAX = 1024;
86
+ const DELETED_MAX = 4096;
87
+
88
+ /** A valid dispatch nonce. */
89
+ export const NONCE_PATTERN = /^[A-Za-z0-9_-]{16,128}$/;
90
+ /** The title marker: only a trailing suffix counts. */
91
+ const TITLE_MARKER = / \[nonce ([A-Za-z0-9_-]{16,128})\]$/;
92
+ /** The prompt marker: only the whole last non-empty line counts. */
93
+ const PROMPT_MARKER = /^OMR_NONCE=([A-Za-z0-9_-]{16,128})$/;
94
+
95
+ /** The local action class (§2.2). */
96
+ export const LOCAL_ACTIONS: readonly AuthorityAction[] = Object.freeze(["read", "glob", "grep", "router_git"]);
97
+ const EGRESS: ReadonlySet<AuthorityAction> = new Set<AuthorityAction>(["webfetch", "websearch", "context7", "execute"]);
98
+ /** Canonical order; anything else in a grant is dropped (an unknown name never grants). */
99
+ const ACTION_ORDER: readonly AuthorityAction[] = [
100
+ "read", "glob", "grep", "router_git", "router_run", "edit", "webfetch", "websearch", "context7", "execute",
101
+ ];
102
+ const NO_ACTIONS: ReadonlySet<AuthorityAction> = new Set<AuthorityAction>();
103
+
104
+ /** Notes a binding can carry (exact texts, shared with the runtime and the tests). */
105
+ export const BINDING_NOTES = {
106
+ unknown:
107
+ // QA-G-A1-4 (R8(4)): a request from an unknown binding is dropped on resume, so the note never points at the ladder.
108
+ "binding unknown: this session could not be matched to its dispatch; local actions only, no work root, no router_run — authority is not widened for it: dispatch a fresh task",
109
+ lookupFailed: "binding unknown: session lookup failed",
110
+ noParent: "binding unknown: the session lookup reported no parent or agent",
111
+ noNonce: "binding unknown: this session carries no dispatch nonce",
112
+ foreignNonce: "binding unknown: the dispatch named by this session's nonce is not pending for its parent and agent",
113
+ markers: "binding unknown: the session's title and first message name different dispatch nonces",
114
+ claimed: "binding unknown: the dispatch named by this session's nonce is already bound to another session",
115
+ beyondMax: (actions: readonly AuthorityAction[]): string => `outside the role max, dropped: ${actions.join(", ")}`,
116
+ noWorkRoot: "router_run and edit need a bound work root (root=) — not granted",
117
+ separation: GRANT_NOTES.separation,
118
+ widened: (actions: readonly AuthorityAction[]): string => `authority widened on resume: ${actions.join(", ")}`,
119
+ notBound: "no binding for this session: nothing widened",
120
+ } as const;
121
+
122
+ /** A fresh, unguessable per-dispatch nonce (never a provider tool-call id); matches {@link NONCE_PATTERN}. */
123
+ export function newDispatchNonce(): string {
124
+ return randomUUID();
125
+ }
126
+
127
+ /** Title suffix carrying a dispatch nonce (P-2); P2.1 appends it to the `subagent` description. */
128
+ export function nonceTitleSuffix(nonce: string): string {
129
+ return ` [nonce ${nonce}]`;
130
+ }
131
+
132
+ /** Prompt line carrying a dispatch nonce (P-2); P2.1 appends it as the LAST line of the `subagent` prompt. */
133
+ export function noncePromptLine(nonce: string): string {
134
+ return `OMR_NONCE=${nonce}`;
135
+ }
136
+
137
+ // ---------------------------------------------------------------------------
138
+ // Process-wide registry
139
+ // ---------------------------------------------------------------------------
140
+
141
+ interface PendingSlot {
142
+ entry: PendingDispatch;
143
+ /** Start of the TTL: the entry's registeredAt, never later than the moment it was stored. */
144
+ start: number;
145
+ /** The child bound exactly to this dispatch. */
146
+ claimedBy: string | undefined;
147
+ }
148
+
149
+ interface BoundSlot {
150
+ binding: Binding;
151
+ parentSessionID: string | undefined;
152
+ agent: string | undefined;
153
+ }
154
+
155
+ /** A cacheable decision always knows the child's parent and agent; a retryable one may not. */
156
+ type Decision =
157
+ | { binding: Binding; parentSessionID: string; agent: string; cacheable: true }
158
+ | { binding: Binding; parentSessionID: string | undefined; agent: string | undefined; cacheable: false };
159
+
160
+ interface Inflight {
161
+ promise: Promise<Decision>;
162
+ token: object;
163
+ }
164
+
165
+ interface Registry {
166
+ readonly version: 2;
167
+ readonly pending: Map<string, PendingSlot>;
168
+ readonly bound: Map<string, BoundSlot>;
169
+ readonly inflight: Map<string, Inflight>;
170
+ /** nonce → retiredAt */
171
+ readonly retired: Map<string, number>;
172
+ /** deleted session → deletedAt */
173
+ readonly deleted: Map<string, number>;
174
+ }
175
+
176
+ /** Versioned: a copy of another registry layout uses another key instead of fighting over this one. */
177
+ const REGISTRY_KEY = Symbol.for("opencode-model-router.role-binding@2");
178
+
179
+ function isRegistry(value: unknown): value is Registry {
180
+ if (typeof value !== "object" || value === null) return false;
181
+ const r = value as Partial<Registry>;
182
+ return r.version === 2 && r.pending instanceof Map && r.bound instanceof Map
183
+ && r.inflight instanceof Map && r.retired instanceof Map && r.deleted instanceof Map;
184
+ }
185
+
186
+ function registry(): Registry {
187
+ const existing: unknown = Reflect.get(globalThis, REGISTRY_KEY);
188
+ if (isRegistry(existing)) return existing;
189
+ const created: Registry = {
190
+ version: 2, pending: new Map(), bound: new Map(), inflight: new Map(), retired: new Map(), deleted: new Map(),
191
+ };
192
+ Reflect.set(globalThis, REGISTRY_KEY, created);
193
+ return created;
194
+ }
195
+
196
+ function pendingKey(parentSessionID: string, callID: string): string {
197
+ return JSON.stringify([parentSessionID, callID]);
198
+ }
199
+
200
+ /** Inserts at the newest position and drops the oldest entries beyond `max`. */
201
+ function remember<K, V>(map: Map<K, V>, key: K, value: V, max: number): void {
202
+ map.delete(key);
203
+ map.set(key, value);
204
+ for (const oldest of map.keys()) {
205
+ if (map.size <= max) break;
206
+ map.delete(oldest);
207
+ }
208
+ }
209
+
210
+ function removePending(reg: Registry, key: string, slot: PendingSlot, now: number): void {
211
+ reg.pending.delete(key);
212
+ remember(reg.retired, slot.entry.nonce, now, RETIRED_MAX);
213
+ }
214
+
215
+ /** Drops expired pending entries (their nonces retire), expired retired nonces and deleted-session tombstones. */
216
+ function prune(reg: Registry, now: number): void {
217
+ for (const [key, slot] of reg.pending) if (now - slot.start >= PENDING_TTL_MS) removePending(reg, key, slot, now);
218
+ for (const [nonce, at] of reg.retired) if (now - at >= PENDING_TTL_MS) reg.retired.delete(nonce);
219
+ for (const [id, at] of reg.deleted) if (now - at >= PENDING_TTL_MS) reg.deleted.delete(id);
220
+ }
221
+
222
+ function isDeleted(reg: Registry, id: string, now: number): boolean {
223
+ const at = reg.deleted.get(id);
224
+ return at !== undefined && now - at < PENDING_TTL_MS;
225
+ }
226
+
227
+ // ---------------------------------------------------------------------------
228
+ // Grants
229
+ // ---------------------------------------------------------------------------
230
+
231
+ function ordered(actions: Iterable<AuthorityAction>): Set<AuthorityAction> {
232
+ const have = new Set<AuthorityAction>(actions);
233
+ return new Set(ACTION_ORDER.filter((a) => have.has(a)));
234
+ }
235
+
236
+ /** An absolute work root, or null (undefined, "", relative or NUL-carrying roots never grant). */
237
+ function rootOrNull(root: unknown): string | null {
238
+ return typeof root === "string" && root !== "" && !root.includes("\0") && isAbsolute(root) ? root : null;
239
+ }
240
+
241
+ /** The role max of `agent` from the caller's options: never `execute`; anything invalid → nothing. */
242
+ function maxFor(opts: BindOptions | undefined, agent: string | undefined): ReadonlySet<AuthorityAction> {
243
+ if (agent === undefined || typeof opts?.maxOf !== "function") return NO_ACTIONS;
244
+ try {
245
+ const max = opts.maxOf(agent);
246
+ if (max === undefined || max === null) return NO_ACTIONS;
247
+ const set = ordered(max);
248
+ set.delete("execute");
249
+ return set;
250
+ } catch {
251
+ return NO_ACTIONS;
252
+ }
253
+ }
254
+
255
+ /** ∩ max first, then the separation rule, then the work-root rule. Only removes. */
256
+ function restrict(
257
+ actions: Iterable<AuthorityAction>,
258
+ notes: readonly string[],
259
+ workRoot: unknown,
260
+ max: ReadonlySet<AuthorityAction>,
261
+ reportBeyond = true,
262
+ ): DispatchGrant {
263
+ const all = ordered(actions);
264
+ const kept = new Set([...all].filter((a) => max.has(a)));
265
+ const root = rootOrNull(workRoot);
266
+ const extra: string[] = [];
267
+ const beyond = [...all].filter((a) => !max.has(a));
268
+ if (beyond.length > 0 && reportBeyond) extra.push(BINDING_NOTES.beyondMax(beyond));
269
+ const list = [...kept];
270
+ if (list.some((a) => EGRESS.has(a)) && list.some((a) => !EGRESS.has(a))) {
271
+ for (const a of EGRESS) kept.delete(a);
272
+ extra.push(BINDING_NOTES.separation);
273
+ }
274
+ if (root === null && kept.delete("router_run")) extra.push(BINDING_NOTES.noWorkRoot);
275
+ return { actions: kept, notes: [...new Set([...notes, ...extra])], workRoot: root };
276
+ }
277
+
278
+ function copyGrant(grant: DispatchGrant): DispatchGrant {
279
+ return { actions: ordered(grant.actions), notes: [...grant.notes], workRoot: grant.workRoot };
280
+ }
281
+
282
+ /**
283
+ * A caller's view of a stored decision. Decisions are stored unrestricted (only the work root is coerced at
284
+ * registration), so no caller's max ever shapes another caller's view: each view is the decision ∩ the
285
+ * caller's own max, then the separation and work-root rules.
286
+ */
287
+ function view(binding: Binding, max: ReadonlySet<AuthorityAction>): Binding {
288
+ const { actions, notes, workRoot } = binding.grant;
289
+ return {
290
+ ...binding,
291
+ grant: restrict(actions, notes, workRoot, max, binding.kind !== "unknown"),
292
+ candidates: [...binding.candidates],
293
+ };
294
+ }
295
+
296
+ function exact(childSessionID: string, entry: PendingDispatch): Binding {
297
+ return {
298
+ childSessionID, kind: "exact", grant: copyGrant(entry.grant),
299
+ candidates: [entry.callID], decisionID: entry.decisionID, budget: entry.budget,
300
+ };
301
+ }
302
+
303
+ /** Unknown: the local class, narrowed by every view to max ∩ local (I9) — never derived from a dispatch grant. */
304
+ function unknown(childSessionID: string, cause: string): Binding {
305
+ return {
306
+ childSessionID,
307
+ kind: "unknown",
308
+ grant: { actions: ordered(LOCAL_ACTIONS), notes: [BINDING_NOTES.unknown, cause], workRoot: null },
309
+ candidates: [],
310
+ decisionID: null,
311
+ budget: null,
312
+ };
313
+ }
314
+
315
+ // ---------------------------------------------------------------------------
316
+ // Matching
317
+ // ---------------------------------------------------------------------------
318
+
319
+ function titleNonce(title: unknown): string | undefined {
320
+ return typeof title === "string" ? TITLE_MARKER.exec(title.trimEnd())?.[1] : undefined;
321
+ }
322
+
323
+ function promptNonce(text: unknown): string | undefined {
324
+ if (typeof text !== "string") return undefined;
325
+ const last = text.split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== "").pop();
326
+ return last === undefined ? undefined : PROMPT_MARKER.exec(last)?.[1];
327
+ }
328
+
329
+ function text(value: unknown): string | undefined {
330
+ return typeof value === "string" && value !== "" ? value : undefined;
331
+ }
332
+
333
+ /** The unrestricted decision; callers only ever see it through {@link view}. */
334
+ async function decide(childSessionID: string, getSession: SessionLookup): Promise<Decision> {
335
+ let session: Awaited<ReturnType<SessionLookup>>;
336
+ try {
337
+ session = await getSession(childSessionID);
338
+ } catch {
339
+ session = undefined;
340
+ }
341
+ if (typeof session !== "object" || session === null) {
342
+ return { binding: unknown(childSessionID, BINDING_NOTES.lookupFailed), parentSessionID: undefined, agent: undefined, cacheable: false };
343
+ }
344
+ const parent = text(session.parentID);
345
+ const agent = text(session.agent);
346
+ if (parent === undefined || agent === undefined) {
347
+ return { binding: unknown(childSessionID, BINDING_NOTES.noParent), parentSessionID: parent, agent, cacheable: false };
348
+ }
349
+ const out = (binding: Binding): Decision => ({ binding, parentSessionID: parent, agent, cacheable: true });
350
+ const fromTitle = titleNonce(session.title);
351
+ const fromPrompt = promptNonce(session.firstText);
352
+ if (fromTitle !== undefined && fromPrompt !== undefined && fromTitle !== fromPrompt) {
353
+ return out(unknown(childSessionID, BINDING_NOTES.markers));
354
+ }
355
+ const nonce = fromPrompt ?? fromTitle;
356
+ if (nonce === undefined) return out(unknown(childSessionID, BINDING_NOTES.noNonce));
357
+ const reg = registry();
358
+ prune(reg, Date.now());
359
+ // Live nonces are unique and never retired (registerPending refuses both), so a retired, unregistered or
360
+ // forged nonce finds no slot.
361
+ const slot = [...reg.pending.values()].find((s) => s.entry.nonce === nonce);
362
+ if (slot === undefined || slot.entry.parentSessionID !== parent || slot.entry.agent !== agent) {
363
+ return out(unknown(childSessionID, BINDING_NOTES.foreignNonce));
364
+ }
365
+ if (slot.claimedBy !== undefined && slot.claimedBy !== childSessionID) {
366
+ return out(unknown(childSessionID, BINDING_NOTES.claimed));
367
+ }
368
+ slot.claimedBy = childSessionID;
369
+ return out(exact(childSessionID, slot.entry));
370
+ }
371
+
372
+ function validEntry(entry: PendingDispatch): boolean {
373
+ return typeof entry === "object" && entry !== null && text(entry.parentSessionID) !== undefined
374
+ && text(entry.callID) !== undefined && text(entry.agent) !== undefined
375
+ && typeof entry.nonce === "string" && NONCE_PATTERN.test(entry.nonce)
376
+ && typeof entry.grant === "object" && entry.grant !== null && entry.grant.actions instanceof Set
377
+ && typeof entry.budget === "number" && Number.isFinite(entry.budget) && entry.budget > 0;
378
+ }
379
+
380
+ // ---------------------------------------------------------------------------
381
+ // API
382
+ // ---------------------------------------------------------------------------
383
+
384
+ /**
385
+ * Registers a dispatch, keyed by parent + callID. Refused (no-op): invalid entries (empty ids, a nonce outside
386
+ * {@link NONCE_PATTERN}, a non-Set grant, a budget that is not finite and > 0), a deleted parent, a retired
387
+ * nonce, a nonce another live dispatch holds, an entry already older than the TTL. The grant is copied (a later
388
+ * mutation cannot widen it) and a work root that is not an absolute path becomes null. Re-registering a key
389
+ * replaces the entry; a changed nonce retires the old one and resets the claim.
390
+ */
391
+ export function registerPending(entry: PendingDispatch): void {
392
+ if (!validEntry(entry)) return;
393
+ const reg = registry();
394
+ const now = Date.now();
395
+ prune(reg, now);
396
+ const key = pendingKey(entry.parentSessionID, entry.callID);
397
+ const previous = reg.pending.get(key);
398
+ if (isDeleted(reg, entry.parentSessionID, now) || reg.retired.has(entry.nonce)) return;
399
+ if ([...reg.pending].some(([k, s]) => k !== key && s.entry.nonce === entry.nonce)) return;
400
+ const start = Number.isFinite(entry.registeredAt) ? Math.min(entry.registeredAt, now) : now;
401
+ if (now - start >= PENDING_TTL_MS) {
402
+ remember(reg.retired, entry.nonce, now, RETIRED_MAX);
403
+ return;
404
+ }
405
+ const keepClaim = previous !== undefined && previous.entry.nonce === entry.nonce;
406
+ if (previous !== undefined && !keepClaim) remember(reg.retired, previous.entry.nonce, now, RETIRED_MAX);
407
+ const grant: DispatchGrant = { ...copyGrant(entry.grant), workRoot: rootOrNull(entry.grant.workRoot) };
408
+ const stored: PendingDispatch = Object.freeze({ ...entry, grant });
409
+ remember(reg.pending, key, { entry: stored, start, claimedBy: keepClaim ? previous.claimedBy : undefined }, Infinity);
410
+ for (const [oldestKey, oldest] of reg.pending) {
411
+ if (reg.pending.size <= PENDING_MAX) break;
412
+ removePending(reg, oldestKey, oldest, now);
413
+ }
414
+ }
415
+
416
+ /**
417
+ * Binds a child session to its dispatch (rules in the module comment) and returns the binding ∩ this
418
+ * caller's max. One decision per child: a cached binding is returned as is (with any widening), and
419
+ * concurrent calls — from any plugin instance — share one lookup and one decision. Never throws.
420
+ */
421
+ export async function bind(childSessionID: string, getSession: SessionLookup, opts: BindOptions): Promise<Binding> {
422
+ const reg = registry();
423
+ const cached = reg.bound.get(childSessionID);
424
+ if (cached) {
425
+ remember(reg.bound, childSessionID, cached, BOUND_MAX);
426
+ return view(cached.binding, maxFor(opts, cached.agent));
427
+ }
428
+ const running = reg.inflight.get(childSessionID);
429
+ if (running) {
430
+ const shared = await running.promise;
431
+ return view(shared.binding, maxFor(opts, shared.agent));
432
+ }
433
+ const token = {};
434
+ const promise = decide(childSessionID, getSession);
435
+ reg.inflight.set(childSessionID, { promise, token });
436
+ try {
437
+ const decision = await promise;
438
+ const latest = registry();
439
+ const now = Date.now();
440
+ // An evict() of the child or its parent while the lookup ran: the decision is returned, never stored.
441
+ if (latest.inflight.get(childSessionID)?.token === token && decision.cacheable
442
+ && !isDeleted(latest, childSessionID, now) && !isDeleted(latest, decision.parentSessionID, now)) {
443
+ const { binding, parentSessionID, agent } = decision;
444
+ remember(latest.bound, childSessionID, { binding, parentSessionID, agent }, BOUND_MAX);
445
+ }
446
+ return view(decision.binding, maxFor(opts, decision.agent));
447
+ } finally {
448
+ const latest = registry();
449
+ if (latest.inflight.get(childSessionID)?.token === token) latest.inflight.delete(childSessionID);
450
+ }
451
+ }
452
+
453
+ /** The cached binding of a child ∩ the caller's max, or undefined when it is not bound. No lookup. */
454
+ export function currentBinding(childSessionID: string, opts: BindOptions): Binding | undefined {
455
+ const slot = registry().bound.get(childSessionID);
456
+ return slot ? view(slot.binding, maxFor(opts, slot.agent)) : undefined;
457
+ }
458
+
459
+ /**
460
+ * Widens the grant of a bound child (the authority ladder's resume path) and returns the new grant. The
461
+ * stored grant is first narrowed to `max`, then only actions inside `max` are added: never `execute`,
462
+ * `router_run` and `edit` only with a work root (QA-G-B-2), nothing across the separation rule. `max` undefined → nothing is added
463
+ * and nothing stored; an unbound child gets an empty grant.
464
+ */
465
+ export function widen(
466
+ childSessionID: string,
467
+ actions: readonly AuthorityAction[],
468
+ max: Iterable<AuthorityAction>,
469
+ ): DispatchGrant {
470
+ const reg = registry();
471
+ const slot = reg.bound.get(childSessionID);
472
+ if (!slot) return { actions: new Set<AuthorityAction>(), notes: [BINDING_NOTES.notBound], workRoot: null };
473
+ if (max === undefined || max === null) return copyGrant(slot.binding.grant);
474
+ const allowed = ordered(max);
475
+ allowed.delete("execute");
476
+ const before = restrict(slot.binding.grant.actions, slot.binding.grant.notes, slot.binding.grant.workRoot, allowed);
477
+ const next = new Set(before.actions);
478
+ const notes = [...before.notes];
479
+ const added: AuthorityAction[] = [];
480
+ for (const action of ordered(actions)) {
481
+ if (next.has(action) || !allowed.has(action)) continue;
482
+ // QA-G-B-2 (R7 null-root contract, I3): no write and no run without a bound work root.
483
+ if ((action === "router_run" || action === "edit") && before.workRoot === null) {
484
+ notes.push(BINDING_NOTES.noWorkRoot);
485
+ continue;
486
+ }
487
+ const egress = EGRESS.has(action);
488
+ if ([...next].some((a) => EGRESS.has(a) !== egress)) {
489
+ notes.push(BINDING_NOTES.separation);
490
+ continue;
491
+ }
492
+ next.add(action);
493
+ added.push(action);
494
+ }
495
+ if (added.length > 0) notes.push(BINDING_NOTES.widened(added));
496
+ const grant: DispatchGrant = { actions: ordered(next), notes: [...new Set(notes)], workRoot: before.workRoot };
497
+ remember(reg.bound, childSessionID, { ...slot, binding: { ...slot.binding, grant } }, BOUND_MAX);
498
+ return copyGrant(grant);
499
+ }
500
+
501
+ /** The parent's `subagent` call completed (`execute.after`): drops that one pending entry; its nonce retires. */
502
+ export function evictCall(parentSessionID: string, callID: string): void {
503
+ const reg = registry();
504
+ const key = pendingKey(parentSessionID, callID);
505
+ const slot = reg.pending.get(key);
506
+ if (slot) removePending(reg, key, slot, Date.now());
507
+ }
508
+
509
+ /**
510
+ * A session was deleted (`session.deleted`): drops its binding and in-flight decision, and — when it is a
511
+ * parent — its pending entries (nonces retire) and its children's bindings. The id is tombstoned for the TTL,
512
+ * so neither a running lookup nor a later registration can attach anything to it.
513
+ */
514
+ export function evict(sessionID: string): void {
515
+ const reg = registry();
516
+ const now = Date.now();
517
+ remember(reg.deleted, sessionID, now, DELETED_MAX);
518
+ for (const [key, slot] of reg.pending) if (slot.entry.parentSessionID === sessionID) removePending(reg, key, slot, now);
519
+ reg.bound.delete(sessionID);
520
+ for (const [child, slot] of reg.bound) if (slot.parentSessionID === sessionID) reg.bound.delete(child);
521
+ reg.inflight.delete(sessionID);
522
+ }
523
+
524
+ /** Sizes of the registry (observability and tests). */
525
+ export function bindingRegistrySize(): { pending: number; bound: number; retired: number; deleted: number } {
526
+ const reg = registry();
527
+ return { pending: reg.pending.size, bound: reg.bound.size, retired: reg.retired.size, deleted: reg.deleted.size };
528
+ }
529
+
530
+ /** Test only: forgets a child's cached decision as an LRU eviction would (no tombstone, claims kept). */
531
+ export function dropBindingCacheForTests(childSessionID: string): void {
532
+ registry().bound.delete(childSessionID);
533
+ }
534
+
535
+ /** Test only: empties the process-wide registry. */
536
+ export function resetBindingRegistryForTests(): void {
537
+ const reg = registry();
538
+ reg.pending.clear();
539
+ reg.bound.clear();
540
+ reg.inflight.clear();
541
+ reg.retired.clear();
542
+ reg.deleted.clear();
543
+ }