opencode-model-router 2.3.0 → 2.5.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 (68) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +86 -11
  3. package/package.json +6 -1
  4. package/src/commands/output.ts +21 -1
  5. package/src/compat/v2-hooks.ts +1374 -24
  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/tui/effort-channel.ts +220 -0
  54. package/src/tui/effort-rpc.ts +60 -0
  55. package/src/tui/host-types.ts +154 -0
  56. package/src/tui/opentui-solid.d.ts +16 -0
  57. package/src/tui/plugin.ts +1007 -0
  58. package/src/tui/status-model.ts +561 -0
  59. package/src/v2.ts +26 -1
  60. package/src/verify/checker.ts +249 -7
  61. package/src/verify/deterministic.ts +10 -1
  62. package/src/verify/dispatch.ts +63 -6
  63. package/src/verify/dod.ts +127 -10
  64. package/src/verify/gate.ts +75 -7
  65. package/src/verify/types.ts +12 -0
  66. package/src/verify/wiring.ts +55 -10
  67. package/tiers.json +13 -5
  68. package/tui.ts +4 -0
@@ -0,0 +1,495 @@
1
+ /**
2
+ * Authority ladder (plan §2.5, R6, R7): the `router_request_authority` tool definition and its state. P2.1
3
+ * registers the tool for dynamic role agents and wires the dependencies (role by child session, the role
4
+ * table, optionally the running dispatch); nothing is registered here.
5
+ *
6
+ * - Not a role child, or a fixed role → refused (fixed authority is never widened), naming the role to use.
7
+ * - Dynamic role: actions inside the role max (allow − deny; `execute` never) are recorded for the child and
8
+ * the child is told to stop with `ESCALATE: authority`; actions outside it are refused, naming the role that
9
+ * has them (egress → `researcher`, …); `router_run` and `edit` without a bound work root are refused (I9, QA-G-B-2); actions
10
+ * already granted are reported as such. A request needs no binding and no known call: unknown children can
11
+ * use the ladder.
12
+ * - A replay (every action already on the unattached record) changes nothing and returns the same text.
13
+ * - The record is tied to a call when it is annotated: P2.1 calls `markAnnotated(child, callID)` in
14
+ * `execute.after` when the call ended with `ESCALATE: authority` (and annotates the parent's result), and
15
+ * `discardAuthority(child, callID)` otherwise. Only the first resume after that annotated call applies it:
16
+ * `consumeAuthority(child, deps, { afterCall })` widens by recorded ∩ the CURRENT role max (binding.ts
17
+ * `widen` bounds it again) and clears the record; any other outcome drops it and says why. Records expire
18
+ * after {@link AUTHORITY_TTL_MS} and go with their parent.
19
+ *
20
+ * State lives on `globalThis` under a versioned `Symbol.for` key (one state for every plugin instance).
21
+ */
22
+
23
+ import { tool } from "@opencode-ai/plugin";
24
+ import type { AuthorityAction, RoleSpec } from "../../router/roles";
25
+ import { currentBinding, widen as widenBinding, type Binding } from "./binding";
26
+ import type { DispatchGrant } from "./policy";
27
+
28
+ export const AUTHORITY_TOOL_NAME = "router_request_authority";
29
+
30
+ export interface AuthorityDeps {
31
+ /** Role of a child session; undefined → not a role child. */
32
+ roleOf(childSessionID: string): RoleSpec | undefined;
33
+ /** Enabled roles, to name the role to use in a refusal. */
34
+ roles(): ReadonlyMap<string, RoleSpec>;
35
+ /** The parent's running call for this child, when P2.1 knows it: only its parent is kept (for eviction). */
36
+ dispatchOf?(childSessionID: string): { parentSessionID: string; callID: string } | undefined;
37
+ /** The child's binding. Default: binding.ts `currentBinding` ∩ the child's role max. */
38
+ bindingOf?(childSessionID: string): Binding | undefined;
39
+ /** The resume path's widening. Default: binding.ts `widen`. */
40
+ widen?(childSessionID: string, actions: readonly AuthorityAction[], max: Iterable<AuthorityAction>): DispatchGrant;
41
+ }
42
+
43
+ export interface AuthorityRequest {
44
+ actions: readonly string[];
45
+ reason: string;
46
+ }
47
+
48
+ export interface AuthorityRefusal {
49
+ action: string;
50
+ reason: string;
51
+ }
52
+
53
+ export interface AuthorityResult {
54
+ /** recorded: something is on record for this request; granted: all already granted; refused: nothing usable. */
55
+ status: "recorded" | "granted" | "refused";
56
+ /** Actions of this request now on record (sorted). */
57
+ recorded: readonly AuthorityAction[];
58
+ /** Actions of this request already in the child's grant. */
59
+ granted: readonly AuthorityAction[];
60
+ refused: readonly AuthorityRefusal[];
61
+ /** True when every recorded action was already on the unattached record (state unchanged). */
62
+ replay: boolean;
63
+ text: string;
64
+ }
65
+
66
+ export interface AuthorityRecord {
67
+ /** Known from `dispatchOf` or `markAnnotated`; used to drop the record with its parent. */
68
+ parentSessionID: string | undefined;
69
+ /** The call the record is attached to (set by `markAnnotated`). */
70
+ callID: string | undefined;
71
+ actions: readonly AuthorityAction[];
72
+ /** Child-supplied, cleaned by {@link cleanReason}; present them with {@link quoteChildText}. */
73
+ reasons: readonly string[];
74
+ annotated: boolean;
75
+ }
76
+
77
+ /** The resume path's outcome; a dropped request carries a reason P2.1 can show the parent or the child. */
78
+ export type ConsumeResult =
79
+ | { status: "none" }
80
+ | { status: "dropped"; reason: string }
81
+ | { status: "widened"; grant: DispatchGrant; widened: readonly AuthorityAction[] };
82
+
83
+ /** Children with a request kept at most (oldest first out). */
84
+ export const AUTHORITY_REQUESTS_MAX = 512;
85
+ /** A request expires 30 min after it was made. */
86
+ export const AUTHORITY_TTL_MS = 30 * 60 * 1000;
87
+ const REASONS_MAX = 8;
88
+ const REASON_CHARS = 500;
89
+ const ACTIONS_MAX = 16;
90
+ const ACTION_CHARS = 64;
91
+ const REASON_INPUT_CHARS = 2000;
92
+
93
+ const ACTIONS: readonly AuthorityAction[] = [
94
+ "read", "glob", "grep", "router_git", "router_run", "edit", "webfetch", "websearch", "context7", "execute",
95
+ ];
96
+ const LOCAL: ReadonlySet<AuthorityAction> = new Set<AuthorityAction>(["read", "glob", "grep", "router_git"]);
97
+ const EGRESS: ReadonlySet<AuthorityAction> = new Set<AuthorityAction>(["webfetch", "websearch", "context7", "execute"]);
98
+ const WRITE_ALIASES: ReadonlySet<string> = new Set(["write", "patch", "multiedit", "apply_patch"]);
99
+ const SHELL_ALIASES: ReadonlySet<string> = new Set(["shell", "bash", "network"]);
100
+ const REQUESTABLE = ACTIONS.filter((a) => a !== "execute").join(", ");
101
+
102
+ /** Roles that hold an action, preferred first (§2.2 table). */
103
+ const PREFERRED: Readonly<Record<"local" | "exec" | "write" | "egress", readonly string[]>> = {
104
+ local: ["explorer", "architect"],
105
+ exec: ["runner", "implementer", "general"],
106
+ write: ["implementer", "general"],
107
+ egress: ["researcher"],
108
+ };
109
+
110
+ /** Router control tokens a child-supplied text must never carry into router-framed text. */
111
+ const CONTROL_TOKENS: readonly RegExp[] = [
112
+ /\[\s*\/?\s*(?:route|router|tier|nonce|acceptance|cap)\b[^\]]*\]/gi,
113
+ /OMR_NONCE\s*=\s*\S*/gi,
114
+ /\bCAP\s*:\s*(?:none|\d+)\b/gi,
115
+ /\b(?:task_id|session_?id)\s*[=:]\s*\S*/gi,
116
+ ];
117
+ /** Return-contract prefixes a child-supplied text must not lead with. */
118
+ const RETURN_PREFIX = /^(?:(?:ESCALATE|DONE|NEED\s+MORE)\s*:\s*)+/i;
119
+
120
+ /** Refusal and drop reasons (exact texts, shared with the tests and P2.1). */
121
+ export const AUTHORITY_TEXT = {
122
+ notRole: "router_request_authority is only for role agents",
123
+ fixed: (agent: string): string => `${agent} has a fixed authority that is never widened`,
124
+ execute: "`execute` (Code Mode) is never granted to role agents — dispatch a tier agent explicitly",
125
+ shell: "raw shell is outside roles mode — request `router_run` for repository scripts, or dispatch a tier agent explicitly",
126
+ unknown: `unknown action; requestable: ${REQUESTABLE}`,
127
+ // QA-G-B-2 (R7 null-root contract, I3): `edit` is refused like `router_run` — without a bound work root it would land in the base checkout.
128
+ noWorkRoot: "router_run and edit need a work root bound to this dispatch (root=) — return `ESCALATE: authority` so the parent re-dispatches with root=",
129
+ outside: (agent: string, role: string | undefined): string => role === undefined
130
+ ? `outside ${agent}'s authority and no role grants it — dispatch a tier agent explicitly`
131
+ : `outside ${agent}'s authority — dispatch \`${role}\` for it`,
132
+ dropped: {
133
+ notAnnotated: "authority request not applied: its call did not end with an annotated `ESCALATE: authority`",
134
+ otherCall: "authority request not applied: it belongs to another call than the one being resumed",
135
+ notDynamic: "authority request not applied: the session is no longer a dynamic role",
136
+ notBound: "authority request not applied: the session had no binding when it was resumed — ask again with `router_request_authority`",
137
+ /** QA-G-A1-2: only the session the request was escalated to (the record's parent) may apply it. */
138
+ otherParent: "authority request not applied: the session resuming this task is not the one the request was escalated to",
139
+ /** Q1 (P2.1 call site): only an exact binding widens. */
140
+ bindingUnknown: "authority request not applied: binding unknown: dispatch a fresh task",
141
+ },
142
+ } as const;
143
+
144
+ // ---------------------------------------------------------------------------
145
+ // Process-wide state
146
+ // ---------------------------------------------------------------------------
147
+
148
+ interface RequestRecord {
149
+ parentSessionID: string | undefined;
150
+ callID: string | undefined;
151
+ actions: Set<AuthorityAction>;
152
+ reasons: string[];
153
+ at: number;
154
+ annotated: boolean;
155
+ }
156
+
157
+ interface AuthorityState {
158
+ readonly version: 2;
159
+ readonly requests: Map<string, RequestRecord>;
160
+ }
161
+
162
+ /** Versioned: a copy of another state layout uses another key instead of fighting over this one. */
163
+ const STATE_KEY = Symbol.for("opencode-model-router.role-authority@2");
164
+
165
+ function state(): AuthorityState {
166
+ const existing: unknown = Reflect.get(globalThis, STATE_KEY);
167
+ if (typeof existing === "object" && existing !== null
168
+ && (existing as Partial<AuthorityState>).version === 2
169
+ && (existing as Partial<AuthorityState>).requests instanceof Map) {
170
+ return existing as AuthorityState;
171
+ }
172
+ const created: AuthorityState = { version: 2, requests: new Map() };
173
+ Reflect.set(globalThis, STATE_KEY, created);
174
+ return created;
175
+ }
176
+
177
+ /** The child's record, or undefined; an expired record is dropped. */
178
+ function liveRecord(childSessionID: string): RequestRecord | undefined {
179
+ const { requests } = state();
180
+ const record = requests.get(childSessionID);
181
+ if (record !== undefined && Date.now() - record.at >= AUTHORITY_TTL_MS) {
182
+ requests.delete(childSessionID);
183
+ return undefined;
184
+ }
185
+ return record;
186
+ }
187
+
188
+ // ---------------------------------------------------------------------------
189
+ // Helpers
190
+ // ---------------------------------------------------------------------------
191
+
192
+ function sorted(actions: Iterable<AuthorityAction>): AuthorityAction[] {
193
+ const have = new Set(actions);
194
+ return ACTIONS.filter((a) => have.has(a));
195
+ }
196
+
197
+ /** The role max: allow − deny, known actions only, never `execute` (P-6). */
198
+ export function roleMax(role: RoleSpec): ReadonlySet<AuthorityAction> {
199
+ const denied = new Set<string>(role.authority.deny);
200
+ const allowed = new Set<string>(role.authority.allow);
201
+ return new Set(ACTIONS.filter((a) => a !== "execute" && allowed.has(a) && !denied.has(a)));
202
+ }
203
+
204
+ function classOf(action: AuthorityAction): keyof typeof PREFERRED {
205
+ if (LOCAL.has(action)) return "local";
206
+ if (EGRESS.has(action)) return "egress";
207
+ return action === "edit" ? "write" : "exec";
208
+ }
209
+
210
+ /** The role to use for an action: the preferred enabled role holding it, else any enabled one. */
211
+ export function roleFor(action: AuthorityAction, roles: ReadonlyMap<string, RoleSpec>): string | undefined {
212
+ if (action === "execute") return undefined;
213
+ const holds = (spec: RoleSpec | undefined): spec is RoleSpec => spec !== undefined && spec.enabled && roleMax(spec).has(action);
214
+ for (const name of PREFERRED[classOf(action)]) if (holds(roles.get(name))) return name;
215
+ for (const spec of roles.values()) if (holds(spec)) return spec.agent;
216
+ return undefined;
217
+ }
218
+
219
+ type Parsed = { kind: "action"; action: AuthorityAction } | { kind: "refused"; reason: string };
220
+
221
+ function parseAction(raw: string): Parsed {
222
+ const name = raw.trim().toLowerCase();
223
+ const known = ACTIONS.find((a) => a === name);
224
+ if (known !== undefined) return { kind: "action", action: known };
225
+ if (name.startsWith("router_git_")) return { kind: "action", action: "router_git" };
226
+ if (name.startsWith("context7_")) return { kind: "action", action: "context7" };
227
+ if (WRITE_ALIASES.has(name)) return { kind: "action", action: "edit" };
228
+ if (SHELL_ALIASES.has(name)) return { kind: "refused", reason: AUTHORITY_TEXT.shell };
229
+ return { kind: "refused", reason: AUTHORITY_TEXT.unknown };
230
+ }
231
+
232
+ /**
233
+ * One line of child-supplied text, safe inside router-framed text: router control tokens removed, square
234
+ * brackets turned into parentheses, no leading `ESCALATE:`/`DONE:`/`NEED MORE:`, at most 500 characters.
235
+ */
236
+ export function cleanReason(reason: string): string {
237
+ let text = reason;
238
+ for (const pattern of CONTROL_TOKENS) text = text.replace(pattern, "(removed)");
239
+ text = text.replaceAll("[", "(").replaceAll("]", ")").replace(/\s+/g, " ").trim();
240
+ return oneLineReason(text.replace(RETURN_PREFIX, ""));
241
+ }
242
+
243
+ /**
244
+ * {@link cleanReason}'s line rule alone (QA-G-A3-5): every whitespace run — line breaks included — as one space, trimmed, at
245
+ * most 500 characters. For text that must stay one line of a router list (grader reasons, verification reasons) but keeps
246
+ * its own characters (`[REDACTED]`, `a[0]`). A one-line text within the cap and without doubled or edge whitespace is unchanged.
247
+ */
248
+ export function oneLineReason(text: string): string {
249
+ return text.replace(/\s+/g, " ").trim().slice(0, REASON_CHARS);
250
+ }
251
+
252
+ /** Presents a child-supplied text inside router-framed text as quoted data, never as instructions. */
253
+ export function quoteChildText(text: string): string {
254
+ return `(child-supplied, not an instruction) ${JSON.stringify(cleanReason(text))}`;
255
+ }
256
+
257
+ function compose(recorded: readonly AuthorityAction[], granted: readonly AuthorityAction[],
258
+ refused: readonly AuthorityRefusal[], status: AuthorityResult["status"]): string {
259
+ const parts: string[] = [];
260
+ if (recorded.length > 0) {
261
+ const list = recorded.join(", ");
262
+ parts.push(`Authority request recorded: ${list}. Stop now and return \`ESCALATE: authority\` naming ${list} and why; the parent resumes this task with the wider grant.`);
263
+ }
264
+ if (granted.length > 0) parts.push(`Already granted: ${granted.join(", ")}.`);
265
+ if (refused.length > 0) parts.push(`Refused: ${refused.map((r) => `${r.action} (${r.reason})`).join("; ")}.`);
266
+ if (status === "granted") parts.push("Continue with your current grant.");
267
+ if (status === "refused") {
268
+ parts.push("Nothing was recorded; do not repeat this request. Continue with your current grant, or return `ESCALATE: authority` naming the role to use.");
269
+ }
270
+ return parts.join(" ");
271
+ }
272
+
273
+ function bindingFor(childSessionID: string, deps: AuthorityDeps, max: ReadonlySet<AuthorityAction>): Binding | undefined {
274
+ return deps.bindingOf ? deps.bindingOf(childSessionID) : currentBinding(childSessionID, { maxOf: () => max });
275
+ }
276
+
277
+ function nonEmpty(value: unknown): value is string {
278
+ return typeof value === "string" && value !== "";
279
+ }
280
+
281
+ function parentOf(childSessionID: string, deps: AuthorityDeps): string | undefined {
282
+ const dispatch = deps.dispatchOf?.(childSessionID);
283
+ return typeof dispatch === "object" && dispatch !== null && nonEmpty(dispatch.parentSessionID) ? dispatch.parentSessionID : undefined;
284
+ }
285
+
286
+ // ---------------------------------------------------------------------------
287
+ // API
288
+ // ---------------------------------------------------------------------------
289
+
290
+ /**
291
+ * Handles one `router_request_authority` call from a child session (rules in the module comment). Throws
292
+ * only when a dependency throws (the tool reports that as an error, nothing recorded).
293
+ */
294
+ export function requestAuthority(childSessionID: string, input: AuthorityRequest, deps: AuthorityDeps): AuthorityResult {
295
+ const refused: AuthorityRefusal[] = [];
296
+ const requested: AuthorityAction[] = [];
297
+ for (const raw of input.actions) {
298
+ const parsed = parseAction(raw);
299
+ if (parsed.kind === "refused") refused.push({ action: raw, reason: parsed.reason });
300
+ else if (!requested.includes(parsed.action)) requested.push(parsed.action);
301
+ }
302
+ const done = (recorded: AuthorityAction[], granted: AuthorityAction[], replay: boolean): AuthorityResult => {
303
+ const status = recorded.length > 0 ? "recorded" : granted.length > 0 && refused.length === 0 ? "granted" : "refused";
304
+ return { status, recorded, granted, refused, replay, text: compose(recorded, granted, refused, status) };
305
+ };
306
+ const role = deps.roleOf(childSessionID);
307
+ if (role === undefined) {
308
+ for (const action of sorted(requested)) refused.push({ action, reason: AUTHORITY_TEXT.notRole });
309
+ return done([], [], false);
310
+ }
311
+ const roles = deps.roles();
312
+ const max = roleMax(role);
313
+ const fixed = role.authority.mode === "fixed";
314
+ const grant = bindingFor(childSessionID, deps, max)?.grant;
315
+ const inside: AuthorityAction[] = [];
316
+ const granted: AuthorityAction[] = [];
317
+ for (const action of sorted(requested)) {
318
+ if (action === "execute") refused.push({ action, reason: AUTHORITY_TEXT.execute });
319
+ else if (!max.has(action)) refused.push({ action, reason: AUTHORITY_TEXT.outside(role.agent, roleFor(action, roles)) });
320
+ else if (grant?.actions.has(action)) granted.push(action);
321
+ else if (fixed) refused.push({ action, reason: AUTHORITY_TEXT.fixed(role.agent) });
322
+ else if ((action === "router_run" || action === "edit") && !grant?.workRoot) refused.push({ action, reason: AUTHORITY_TEXT.noWorkRoot });
323
+ else inside.push(action);
324
+ }
325
+ if (inside.length === 0) return done([], granted, false);
326
+ const { requests } = state();
327
+ const existing = liveRecord(childSessionID);
328
+ // An annotated record belongs to a finished call; a new request starts a new, unattached record.
329
+ const open = existing !== undefined && !existing.annotated ? existing : undefined;
330
+ const replay = open !== undefined && inside.every((a) => open.actions.has(a));
331
+ if (!replay) {
332
+ const record: RequestRecord = open ?? {
333
+ parentSessionID: undefined, callID: undefined, actions: new Set(), reasons: [], at: Date.now(), annotated: false,
334
+ };
335
+ record.parentSessionID ??= parentOf(childSessionID, deps);
336
+ for (const action of inside) record.actions.add(action);
337
+ const reason = cleanReason(input.reason);
338
+ if (reason !== "" && !record.reasons.includes(reason) && record.reasons.length < REASONS_MAX) record.reasons.push(reason);
339
+ requests.delete(childSessionID);
340
+ requests.set(childSessionID, record);
341
+ for (const oldest of requests.keys()) {
342
+ if (requests.size <= AUTHORITY_REQUESTS_MAX) break;
343
+ requests.delete(oldest);
344
+ }
345
+ }
346
+ return done(inside, granted, replay);
347
+ }
348
+
349
+ /** The child's live, unconsumed request (for the parent's annotation), or undefined. */
350
+ export function requestedAuthority(childSessionID: string): AuthorityRecord | undefined {
351
+ const record = liveRecord(childSessionID);
352
+ if (record === undefined) return undefined;
353
+ const { parentSessionID, callID, reasons, annotated } = record;
354
+ return { parentSessionID, callID, actions: sorted(record.actions), reasons: [...reasons], annotated };
355
+ }
356
+
357
+ /**
358
+ * The parent's call `callID` ended with `ESCALATE: authority` and P2.1 annotated its result: the open request
359
+ * is attached to that call and becomes consumable by the next resume. True when a request is attached to
360
+ * `callID` (repeating it is harmless); false when there is no live request, or it is attached to another call.
361
+ */
362
+ export function markAnnotated(childSessionID: string, callID: string, parentSessionID?: string): boolean {
363
+ const record = liveRecord(childSessionID);
364
+ if (record === undefined || !nonEmpty(callID)) return false;
365
+ if (record.annotated) return record.callID === callID;
366
+ record.callID = callID;
367
+ record.annotated = true;
368
+ // QA-G-A1-2-1: the session whose call was annotated is the one the request was escalated to — it replaces the parent the
369
+ // record started with (the dispatch registry's, which still names the original dispatcher during a delegate's resume).
370
+ if (nonEmpty(parentSessionID)) record.parentSessionID = parentSessionID;
371
+ return true;
372
+ }
373
+
374
+ /** The parent's call `callID` ended without `ESCALATE: authority`: an open request, or one of that call, is dropped. */
375
+ export function discardAuthority(childSessionID: string, callID: string): void {
376
+ const record = liveRecord(childSessionID);
377
+ if (record !== undefined && (!record.annotated || record.callID === callID)) state().requests.delete(childSessionID);
378
+ }
379
+
380
+ /**
381
+ * What the resume path checks before it applies a request ({@link consumeAuthority} / {@link previewAuthority}).
382
+ * - `afterCall`: the call being resumed after; the request must be attached to it.
383
+ * - `parentSessionID` (QA-G-A1-2): the session resuming the child; when given, it must be the record's parent (the session the
384
+ * request was escalated to), else the request is dropped with {@link AUTHORITY_TEXT}.dropped.otherParent.
385
+ * - `exactOnly` (Q1, QA-G-A1-3): a binding that is not `exact` drops the request with {@link AUTHORITY_TEXT}.dropped.bindingUnknown.
386
+ */
387
+ export interface AuthorityResumeOptions {
388
+ afterCall: string;
389
+ parentSessionID?: string;
390
+ exactOnly?: boolean;
391
+ }
392
+
393
+ /** The first reason a live record cannot be applied for this resume, or the binding it widens. */
394
+ function resumeCheck(
395
+ childSessionID: string,
396
+ record: RequestRecord,
397
+ deps: AuthorityDeps,
398
+ opts: AuthorityResumeOptions,
399
+ ): { reason: string } | { max: ReadonlySet<AuthorityAction>; binding: Binding } {
400
+ if (!record.annotated) return { reason: AUTHORITY_TEXT.dropped.notAnnotated };
401
+ if (opts.parentSessionID !== undefined && record.parentSessionID !== opts.parentSessionID) return { reason: AUTHORITY_TEXT.dropped.otherParent };
402
+ if (record.callID !== opts.afterCall) return { reason: AUTHORITY_TEXT.dropped.otherCall };
403
+ const role = deps.roleOf(childSessionID);
404
+ if (role === undefined || role.authority.mode === "fixed") return { reason: AUTHORITY_TEXT.dropped.notDynamic };
405
+ const max = roleMax(role);
406
+ const binding = bindingFor(childSessionID, deps, max);
407
+ if (binding === undefined) return { reason: AUTHORITY_TEXT.dropped.notBound };
408
+ if (opts.exactOnly === true && binding.kind !== "exact") return { reason: AUTHORITY_TEXT.dropped.bindingUnknown };
409
+ return { max, binding };
410
+ }
411
+
412
+ /**
413
+ * Resume path (P2.1, `execute.before` of a resume of `childSessionID`; `afterCall` = the call being resumed
414
+ * after). Applies the request only when it is attached to `afterCall` (and, with the options, escalated to the resuming
415
+ * session and held by an exact binding): recorded ∩ the current role max → `widen`. The record is cleared in every case — a
416
+ * request widens at most once, on the first resume after its call; a dropped request carries the reason (P2.1 shows it).
417
+ */
418
+ export function consumeAuthority(childSessionID: string, deps: AuthorityDeps, opts: AuthorityResumeOptions): ConsumeResult {
419
+ const record = liveRecord(childSessionID);
420
+ if (record === undefined) return { status: "none" };
421
+ state().requests.delete(childSessionID);
422
+ const checked = resumeCheck(childSessionID, record, deps, opts);
423
+ if ("reason" in checked) return { status: "dropped", reason: checked.reason };
424
+ const { max, binding } = checked;
425
+ const actions = sorted(record.actions).filter((a) => max.has(a));
426
+ const grant = (deps.widen ?? widenBinding)(childSessionID, actions, max);
427
+ return { status: "widened", grant, widened: sorted(grant.actions).filter((a) => !binding.grant.actions.has(a)) };
428
+ }
429
+
430
+ /**
431
+ * What {@link consumeAuthority} would do for this resume, without doing it (P2.1 QA nit 2): no record is cleared, nothing is
432
+ * widened. `widened` are the recorded actions inside the CURRENT role max that the binding does not hold yet (binding.ts `widen`
433
+ * may still refuse one, e.g. `router_run` without a work root). `exactOnly` (Q1): a binding that is not `exact` is dropped with
434
+ * {@link AUTHORITY_TEXT}.dropped.bindingUnknown. A record past its TTL reads as none (left for the next access to drop).
435
+ */
436
+ export type AuthorityPreview =
437
+ | { status: "none" }
438
+ | { status: "dropped"; reason: string }
439
+ | { status: "widened"; widened: readonly AuthorityAction[] };
440
+
441
+ export function previewAuthority(
442
+ childSessionID: string,
443
+ deps: AuthorityDeps,
444
+ opts: AuthorityResumeOptions,
445
+ ): AuthorityPreview {
446
+ const record = state().requests.get(childSessionID);
447
+ if (record === undefined || Date.now() - record.at >= AUTHORITY_TTL_MS) return { status: "none" };
448
+ const checked = resumeCheck(childSessionID, record, deps, opts);
449
+ if ("reason" in checked) return { status: "dropped", reason: checked.reason };
450
+ const { max, binding } = checked;
451
+ return { status: "widened", widened: sorted(record.actions).filter((a) => max.has(a) && !binding.grant.actions.has(a)) };
452
+ }
453
+
454
+ /** A session was deleted: drops its own request and the requests of its children (it was their parent). */
455
+ export function evictAuthority(sessionID: string): void {
456
+ const { requests } = state();
457
+ requests.delete(sessionID);
458
+ for (const [child, record] of requests) if (record.parentSessionID === sessionID) requests.delete(child);
459
+ }
460
+
461
+ /** Test only: empties the process-wide authority state. */
462
+ export function resetAuthorityForTests(): void {
463
+ state().requests.clear();
464
+ }
465
+
466
+ function errorText(error: unknown): string {
467
+ return (error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ").trim();
468
+ }
469
+
470
+ /**
471
+ * The `router_request_authority` tool. The child is the calling session (`context.sessionID`). The advertised
472
+ * argument schema is the one enforced. Never throws into the session: invalid arguments and dependency
473
+ * errors are reported, nothing is recorded.
474
+ */
475
+ export function authorityTool(deps: AuthorityDeps) {
476
+ const args = {
477
+ actions: tool.schema.array(tool.schema.string().min(1).max(ACTION_CHARS)).min(1).max(ACTIONS_MAX)
478
+ .describe(`Actions needed: ${REQUESTABLE}`),
479
+ reason: tool.schema.string().min(1).max(REASON_INPUT_CHARS).describe("Why the task needs them, in one or two sentences"),
480
+ };
481
+ const inputSchema = tool.schema.object(args).strict();
482
+ return tool({
483
+ description: "Ask for an action your role may use but this dispatch was not granted (for example `edit` or `router_run`). "
484
+ + "If your role allows it, the request is recorded and you must stop and return `ESCALATE: authority`; the parent resumes you with the wider grant. "
485
+ + "Otherwise the reply names the role to use. Never repeat a refused request.",
486
+ args,
487
+ async execute(input, context) {
488
+ try {
489
+ return requestAuthority(context.sessionID, inputSchema.parse(input), deps).text;
490
+ } catch (error) {
491
+ return `[${AUTHORITY_TOOL_NAME}] error: ${errorText(error)}`;
492
+ }
493
+ },
494
+ });
495
+ }