opencode-model-router 2.2.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 (83) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +90 -12
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +24 -1
  5. package/src/compat/child-session.ts +43 -0
  6. package/src/compat/v2-client.ts +107 -7
  7. package/src/compat/v2-hooks.ts +1435 -44
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +496 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/guard/enforce.ts +186 -22
  13. package/src/guard/guards.ts +132 -6
  14. package/src/guard/store.ts +5 -0
  15. package/src/index.ts +1193 -56
  16. package/src/router/build-info.ts +151 -0
  17. package/src/router/config.ts +1611 -19
  18. package/src/router/dispatch-header.ts +46 -4
  19. package/src/router/git-tools.ts +1152 -0
  20. package/src/router/guard-profile.ts +100 -0
  21. package/src/router/plugin-agents.ts +433 -0
  22. package/src/router/prompts.ts +26 -1
  23. package/src/router/protocol.ts +180 -0
  24. package/src/router/read-only.ts +149 -0
  25. package/src/router/role-agents.ts +409 -0
  26. package/src/router/roles-config.ts +429 -0
  27. package/src/router/roles.ts +600 -0
  28. package/src/router/run-tools.ts +913 -0
  29. package/src/router/sensitive-paths.ts +101 -0
  30. package/src/router/sessions.ts +533 -9
  31. package/src/router/subagents.ts +28 -1
  32. package/src/routing/advisor/findings.ts +898 -0
  33. package/src/routing/advisor/index.ts +614 -0
  34. package/src/routing/classify/backends/host.ts +163 -0
  35. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  36. package/src/routing/classify/backends/shared.ts +741 -0
  37. package/src/routing/classify/backends/typesafe.ts +315 -0
  38. package/src/routing/classify/fences.ts +96 -0
  39. package/src/routing/classify/index.ts +594 -0
  40. package/src/routing/classify/route-line.ts +362 -0
  41. package/src/routing/classify/rules.ts +667 -0
  42. package/src/routing/classify/scrub.ts +214 -0
  43. package/src/routing/classify/state.ts +148 -0
  44. package/src/routing/classify/text.ts +20 -0
  45. package/src/routing/classify/types.ts +1310 -0
  46. package/src/routing/commands/annotate-plan.ts +652 -0
  47. package/src/routing/commands/stats.ts +134 -0
  48. package/src/routing/commands/v1-roles.ts +64 -0
  49. package/src/routing/engine/index.ts +32 -0
  50. package/src/routing/engine/kernel.ts +760 -0
  51. package/src/routing/engine/ladders.ts +802 -0
  52. package/src/routing/engine/plan.ts +404 -0
  53. package/src/routing/engine/protocol-line.ts +150 -0
  54. package/src/routing/engine/roles-taxonomy.ts +52 -0
  55. package/src/routing/engine/simulate.ts +167 -0
  56. package/src/routing/engine/types.ts +368 -0
  57. package/src/routing/file-lock.ts +53 -0
  58. package/src/routing/outcomes/beta.ts +147 -0
  59. package/src/routing/outcomes/cost.ts +313 -0
  60. package/src/routing/outcomes/index.ts +215 -0
  61. package/src/routing/outcomes/ingest.ts +960 -0
  62. package/src/routing/outcomes/persist.ts +1080 -0
  63. package/src/routing/outcomes/signals.ts +650 -0
  64. package/src/routing/outcomes/stats.ts +873 -0
  65. package/src/routing/outcomes/store.ts +673 -0
  66. package/src/routing/outcomes/types.ts +1093 -0
  67. package/src/routing/roles/authority.ts +495 -0
  68. package/src/routing/roles/binding.ts +543 -0
  69. package/src/routing/roles/policy.ts +416 -0
  70. package/src/routing/roles/work-root.ts +132 -0
  71. package/src/routing/wire/dispatch.ts +2088 -0
  72. package/src/routing/wire/hint.ts +222 -0
  73. package/src/routing/wire/host-info.ts +256 -0
  74. package/src/routing/wire/runtime.ts +348 -0
  75. package/src/v2.ts +40 -1
  76. package/src/verify/checker.ts +249 -7
  77. package/src/verify/deterministic.ts +10 -1
  78. package/src/verify/dispatch.ts +63 -6
  79. package/src/verify/dod.ts +127 -10
  80. package/src/verify/gate.ts +75 -7
  81. package/src/verify/types.ts +12 -0
  82. package/src/verify/wiring.ts +55 -10
  83. package/tiers.json +13 -5
@@ -2,16 +2,47 @@ import type { Hooks } from "@opencode-ai/plugin";
2
2
  import { tool } from "@opencode-ai/plugin";
3
3
  import type { Context } from "@opencode/plugin/promise/plugin";
4
4
  import type { ToolContext } from "@opencode/plugin/promise/tool";
5
+ import type { SessionContext } from "@opencode/plugin/promise/session";
5
6
  import type { SystemPart } from "@opencode/ai";
6
7
  import type { V2Runtime } from "./v2-client";
7
8
  import { V2_GRADER_AGENT } from "./v2-client";
8
9
  import { DEPTH_BANNER, TASK_VERIFICATION } from "./child-session";
9
- import { isAbsolute, resolve } from "node:path";
10
+ import { realpathSync, statSync } from "node:fs";
11
+ import { isAbsolute, join, posix, resolve, win32 } from "node:path";
10
12
  import { loadConfig } from "../router/config";
11
13
  import { getActiveTiers } from "../router/protocol";
12
- import { resolveSubagentOverrides } from "../router/subagents";
14
+ import { DEFER_MISSING_SUBAGENT_NOTICE, HOST_SEED_AGENTS, resolveSubagentOverrides } from "../router/subagents";
15
+ import { warnAgentOptionsEffortOnce } from "../router/agent-options";
16
+ import { pluginAgentMarker } from "../router/plugin-agents";
17
+ import { registerRoleAgents, roleAgentAlias, roleAgentOf, roleAgentSteps } from "../router/role-agents";
13
18
  import { stripDelegateInstructions } from "../router/instructions";
14
- import { GRADER_SYSTEM } from "../verify/checker";
19
+ import { createPluginLogger } from "../router/logger";
20
+ import { budgetClaimObserved, GRADER_SYSTEM } from "../verify/checker";
21
+ import { EXECUTION_END_TYPES, FLUSH_EVENT_TYPES, NOOP_INGEST } from "../routing/outcomes/ingest";
22
+ import type { Ingest } from "../routing/outcomes/ingest";
23
+ import { createEngineRuntime } from "../routing/wire/runtime";
24
+ import {
25
+ annotateSubagentResult, childSessionOf, createDispatchRouter, forgetRoutedRole, gitWorktreeList, normalizeRootText, parseWorktreeList,
26
+ roleMaxActions, routedRoleOf, takeSubagentAnnotations,
27
+ } from "../routing/wire/dispatch";
28
+ import type { RouterConfig } from "../router/config";
29
+ import { resolveRoles, type AuthorityAction, type RoleSpec } from "../router/roles";
30
+ import {
31
+ BINDING_NOTES, bind, currentBinding, evict as evictBinding, evictCall, type Binding, type SessionLookup,
32
+ } from "../routing/roles/binding";
33
+ import type { DispatchGrant } from "../routing/roles/policy";
34
+ import {
35
+ AUTHORITY_TEXT, AUTHORITY_TOOL_NAME, consumeAuthority, discardAuthority, evictAuthority, markAnnotated, previewAuthority, quoteChildText,
36
+ requestedAuthority, type AuthorityDeps,
37
+ } from "../routing/roles/authority";
38
+ import { budgetExhausted, type BudgetSnapshot } from "../guard/enforce";
39
+ import { ROUTER_BUDGET_NOTE_PREFIX } from "../router/prompts";
40
+ import { parseReturnPrefix } from "../routing/outcomes/signals";
41
+ import { lookupDispatch } from "../router/sessions";
42
+ import { createSystemAugmenter } from "../routing/wire/hint";
43
+ import { CONTEXT7_DOC_TOOLS, evaluatePermission, permissionMatches, permissionRules, publishReadOnlyPermissions } from "../router/read-only";
44
+ import { filterSensitiveGrep, isSensitivePath } from "../router/sensitive-paths";
45
+ import { canonicalAuthorityPath, insideWorkRoot } from "../routing/roles/work-root";
15
46
 
16
47
  /** Translate the router's own v1 tool vocabulary at the v2 boundary. */
17
48
  export function v2Instructions(text: string): string {
@@ -25,7 +56,7 @@ export function v2Instructions(text: string): string {
25
56
  }
26
57
 
27
58
  type LegacyAgent = Record<string, any>;
28
- type LegacyConfig = { agent: Record<string, LegacyAgent>; command: Record<string, any> };
59
+ type LegacyConfig = { agent: Record<string, LegacyAgent>; command: Record<string, any>; mcp?: Parameters<NonNullable<Hooks["config"]>>[0]["mcp"] };
29
60
  type LegacyHook = (input: any, output: any) => Promise<void>;
30
61
 
31
62
  function modelRef(value: string, variant?: string): any {
@@ -43,11 +74,15 @@ function taskArgs(toolName: string, input: unknown): any {
43
74
  return input;
44
75
  }
45
76
 
46
- function nativeArgs(toolName: string, args: any, original: any, verifying: boolean): any {
77
+ /**
78
+ * `foreground` (#84 P-5): a role dispatch is forced to the foreground whatever the verification settings, so the router can
79
+ * annotate its result (budget, authority) in `execute.after`. A separate flag: it never marks the call as verifying.
80
+ */
81
+ function nativeArgs(toolName: string, args: any, original: any, verifying: boolean, foreground = false): any {
47
82
  if (!args || typeof args !== "object") return args;
48
83
  if (toolName === "subagent") {
49
84
  const { subagent_type, task_id, ...rest } = args;
50
- return { ...rest, agent: subagent_type, ...(task_id === undefined ? {} : { sessionID: task_id }), ...(verifying ? { background: false } : {}) };
85
+ return { ...rest, agent: subagent_type, ...(task_id === undefined ? {} : { sessionID: task_id }), ...(verifying || foreground ? { background: false } : {}) };
51
86
  }
52
87
  if (toolName === "shell") { const { cwd, ...rest } = args; return { ...rest, ...(cwd === undefined ? {} : { workdir: cwd }) }; }
53
88
  if (["read", "write", "edit"].includes(toolName)) {
@@ -75,11 +110,591 @@ function translateAdded(before: string, after: string): string {
75
110
  return after.slice(0, prefix) + v2Instructions(after.slice(prefix, after.length - suffix)) + after.slice(after.length - suffix);
76
111
  }
77
112
 
113
+ // ---------------------------------------------------------------------------
114
+ // #84 P2.1 (T2.1.3, T2.1.4): role-dispatch helpers of the adapter. Roles mode on v2 only; tiers mode never reaches them.
115
+ // ---------------------------------------------------------------------------
116
+
117
+ /** The text of one session-context message: its `text`, else its text parts (`content` or `parts`) joined. */
118
+ function messageText(message: unknown): string | undefined {
119
+ if (!message || typeof message !== "object") return undefined;
120
+ const m = message as Record<string, unknown>;
121
+ if (typeof m.text === "string") return m.text;
122
+ const parts = Array.isArray(m.content) ? m.content : Array.isArray(m.parts) ? m.parts : undefined;
123
+ if (parts === undefined) return undefined;
124
+ const texts = parts.flatMap((part) => part && typeof part === "object" && (part as Record<string, unknown>).type === "text"
125
+ && typeof (part as Record<string, unknown>).text === "string" ? [(part as Record<string, unknown>).text as string] : []);
126
+ return texts.length > 0 ? texts.join("\n") : undefined;
127
+ }
128
+
129
+ /**
130
+ * Handoff 32: `SessionLookup.firstText` — the text parts of the session's first user message, joined (the binding reads the
131
+ * nonce from its last line). A context without a user message falls back to its first message with text.
132
+ */
133
+ export function firstMessageText(messages: unknown): string | undefined {
134
+ if (!Array.isArray(messages)) return undefined;
135
+ const isUser = (m: unknown): boolean => !!m && typeof m === "object"
136
+ && ((m as Record<string, unknown>).role === "user" || (m as Record<string, unknown>).type === "user");
137
+ const user = messages.find(isUser);
138
+ return user !== undefined ? messageText(user) : messages.map(messageText).find((text) => text !== undefined);
139
+ }
140
+
141
+ /**
142
+ * T2.1.4 (P-5, S6): resume guidance appended to the parent's result when a role child was stopped before finishing — by the
143
+ * router's guard on its call budget (`guard`), or by the host itself: its step limit or a context overflow (`host`, handoff 22).
144
+ */
145
+ export function roleBudgetNotice(agent: string, childSessionID: string, cause: "guard" | "host" = "guard"): string {
146
+ const what = cause === "guard" ? "its tool-call budget" : "the host's step or context limit";
147
+ // P2.2 handoff: the roles protocol tells the orchestrator to resume on a note that starts with ROUTER_BUDGET_NOTE_PREFIX.
148
+ return `${ROUTER_BUDGET_NOTE_PREFIX} @${agent} stopped on ${what} before finishing: this is not a failed result. `
149
+ + `NEXT: resume the same sessionID ("${childSessionID}") with @${agent} and the prompt "continue and finish"; `
150
+ + "do not start a new task and do not set `model` (the router keeps the child's tier).";
151
+ }
152
+
153
+ /**
154
+ * QA-G-A3-4: a `[router` that starts a line — after blanks and markdown quote, list or emphasis marks, any case, blanks allowed
155
+ * between `[` and `router`. The router's notes start a line with it; a child's text must not. QA-G-A3-2-3: the blanks are every
156
+ * Unicode space separator (`\p{Zs}`: no-break, ideographic, em …), tab and the zero-width ones (U+200B–U+200D, U+2060, U+FEFF);
157
+ * the marks include `+` and numbered list marks (`1.`, `12)`); the bracket may be the full-width `[` (U+FF3B).
158
+ */
159
+ const ROUTER_LINE_START = /^((?:[\p{Zs}\t\u200b-\u200d\u2060\ufeff>*_#`+\-]|\d{1,9}[.)])*)[\[\uff3b](?=[\p{Zs}\t\u200b-\u200d\u2060\ufeff]*router\b)/gimu;
160
+
161
+ /** QA-G-A3-4: `text` with the `[` (or `[`) of every line-start `[router` turned into `(`; every other character kept. */
162
+ export function defangRouterLines(text: string): string {
163
+ return text.replace(ROUTER_LINE_START, "$1(");
164
+ }
165
+
166
+ /**
167
+ * QA-G-A3-4: a role dispatch's result with the child's text defanged ({@link defangRouterLines}) in every place the parent reads
168
+ * it: the text parts of `content` (or a string `content`) and the structured `output` (a string, or its `output` string). Fields
169
+ * the result does not have stay absent.
170
+ */
171
+ export function defangChildResult<R extends { readonly content?: unknown; readonly output?: unknown }>(result: R): R {
172
+ const part = (value: unknown): unknown => {
173
+ if (value === null || typeof value !== "object") return value;
174
+ const p = value as { type?: unknown; text?: unknown };
175
+ return p.type === "text" && typeof p.text === "string" ? { ...p, text: defangRouterLines(p.text) } : value;
176
+ };
177
+ const out: Record<string, unknown> = { ...result };
178
+ if (Array.isArray(result.content)) out.content = result.content.map(part);
179
+ else if (typeof result.content === "string") out.content = defangRouterLines(result.content);
180
+ const output = result.output;
181
+ if (typeof output === "string") out.output = defangRouterLines(output);
182
+ else if (output !== null && typeof output === "object" && typeof (output as { output?: unknown }).output === "string") {
183
+ out.output = { ...(output as Record<string, unknown>), output: defangRouterLines((output as { output: string }).output) };
184
+ }
185
+ return out as R;
186
+ }
187
+
188
+ // ---------------------------------------------------------------------------
189
+ // #84 P2.1 (handoff 22): the host's own budget stops of a child, from the event stream (spike S4)
190
+ // ---------------------------------------------------------------------------
191
+
192
+ /** A budget stop as handed to the signals: observed true/false, or not observable for this attempt. */
193
+ export type HostBudgetObservation = boolean | "unobserved";
194
+
195
+ /**
196
+ * S4 (measured on 2.0.24): a tool call made on the last allowed step is answered by the host with this error
197
+ * (`session.tool.failed`). Only a model that ignores the step's `tool_choice: none` makes such a call.
198
+ */
199
+ export const HOST_STEP_LIMIT_TOOL_ERROR = /maximum agent steps/i;
200
+ /**
201
+ * NOT measured (S4 covers step limits and guard denials only): how a context-overflow failure is recognised in a
202
+ * `session.step.failed` / `session.execution.failed` error (`type` and `message`). A failure that matches nothing here makes the
203
+ * attempt's host observation `unobserved`, never `false`.
204
+ */
205
+ export const HOST_CONTEXT_OVERFLOW_ERROR = /context.?(?:overflow|length|window|limit)|prompt is too long|too many tokens|maximum context/i;
206
+
207
+ export interface HostBudgetObserver {
208
+ /** A role child's attempt starts again (a resume): its counters start over. */
209
+ begin(childSessionID: string): void;
210
+ /** Every host event (only step/tool/execution events of a session are read). Never throws. */
211
+ onEvent(type: string, data: unknown): void;
212
+ /**
213
+ * The host stopped the child's current attempt: `true` when it ran `stepLimit` steps (S4: the last of N allowed steps carries the
214
+ * host's max-steps note and `tool_choice: none`), a tool call was refused for the step limit, or a step failed with a context
215
+ * overflow; `false` when its execution ended without any of these and without an unrecognised failure; else `unobserved`.
216
+ */
217
+ observe(childSessionID: string, stepLimit: number | null): HostBudgetObservation;
218
+ /** Resolves when the child's execution end was seen, or after `timeoutMs` (the event may trail the tool result). */
219
+ settled(childSessionID: string, timeoutMs: number): Promise<void>;
220
+ forget(sessionID: string): void;
221
+ }
222
+
223
+ /**
224
+ * QA-G-A3-2 / QA-G-A3-2-4: a tool error that is a permission refusal — only by STRUCTURE, or by this adapter's own text:
225
+ * - a `_tag`/`name` `Permission.<…>Error` (spike S4 (d): the tool hook sees `Permission.BlockedError` on a plugin `evaluate` deny),
226
+ * or a `type` `permission.rejected` (the tool state's error type), on the error or its cause (two levels);
227
+ * - a message this adapter's `evaluate` hook wrote: `Permission denied by role agent …` / `… plugin agent …` / `… read-only agent …`.
228
+ * Never free text alone: an OS error such as ripgrep's `Permission denied (os error 13)` is a failed call, not a refusal. The
229
+ * adapter's own `execute.before` refusals (`[router] Refused …`) are not one either: they are counted where they are thrown.
230
+ */
231
+ const PERMISSION_TAG = /^Permission\.[A-Za-z]*Error$/;
232
+ const PERMISSION_TYPE = "permission.rejected";
233
+ const ROUTER_PERMISSION_TEXT = /^Permission denied by (?:role|plugin|read-only) agent /;
234
+
235
+ export function isPermissionRefusal(error: unknown): boolean {
236
+ const refusal = (value: unknown, depth: number): boolean => {
237
+ if (typeof value === "string") return ROUTER_PERMISSION_TEXT.test(value);
238
+ if (value === null || typeof value !== "object" || depth > 2) return false;
239
+ const e = value as Record<string, unknown>;
240
+ if ([e._tag, e.name].some((tag) => typeof tag === "string" && PERMISSION_TAG.test(tag))) return true;
241
+ if (e.type === PERMISSION_TYPE || e._tag === PERMISSION_TYPE) return true;
242
+ if (typeof e.message === "string" && ROUTER_PERMISSION_TEXT.test(e.message)) return true;
243
+ return ["error", "cause", "data"].some((key) => refusal(e[key], depth + 1));
244
+ };
245
+ return refusal(error, 0);
246
+ }
247
+
248
+ /** Q1 (P2.3 decision at the P2.1 call site): an authority request of a child whose binding is not exact is never applied. */
249
+ export const AUTHORITY_BINDING_UNKNOWN_DROP = `${AUTHORITY_TEXT.dropped.bindingUnknown}.`;
250
+
251
+ /** QA-P21-1-8: logged once when `routing.delegation` becomes `roles` while OpenCode runs in tiers mode. */
252
+ export const ROLES_RESTART_NOTICE =
253
+ "roles mode (OpenCode v2 only): routing.delegation is now `roles`, but this OpenCode instance started in tiers mode; restart OpenCode to register the role agents and tools (tiers mode stays active until then)";
254
+
255
+ /** Bounded per-instance state (oldest child first out). */
256
+ export function createHostBudgetObserver(max = 1000): HostBudgetObserver {
257
+ interface ChildState {
258
+ steps: number;
259
+ /** QA-P21-1-12: assistant messages already counted as a step (a retried step that keeps its message counts once). */
260
+ stepMessages: Set<string>;
261
+ toolLimit: boolean;
262
+ failure: "overflow" | "other" | null;
263
+ ended: boolean;
264
+ waiters: Set<() => void>;
265
+ }
266
+ const children = new Map<string, ChildState>();
267
+ /**
268
+ * One host step. QA-P21-1-12: a step event that names an assistant message already counted (a provider retry that reuses its
269
+ * message) is the same step and counts once. A retry under a NEW message id cannot be told apart from a new step on the event
270
+ * stream (no retry marker): it counts again, which can only make the step-limit observation earlier, never miss one.
271
+ */
272
+ const countStep = (state: ChildState, event: Record<string, unknown>): void => {
273
+ const message = event.assistantMessageID;
274
+ if (typeof message === "string" && message !== "") {
275
+ if (state.stepMessages.has(message)) return;
276
+ state.stepMessages.add(message);
277
+ }
278
+ state.steps += 1;
279
+ };
280
+ const wake = (state: ChildState): void => {
281
+ for (const waiter of [...state.waiters]) waiter();
282
+ state.waiters.clear();
283
+ };
284
+ const stateOf = (id: string): ChildState => {
285
+ let state = children.get(id);
286
+ if (state === undefined) {
287
+ state = { steps: 0, stepMessages: new Set(), toolLimit: false, failure: null, ended: false, waiters: new Set() };
288
+ children.set(id, state);
289
+ while (children.size > max) {
290
+ const oldest = children.keys().next().value as string;
291
+ const dropped = children.get(oldest);
292
+ children.delete(oldest);
293
+ if (dropped !== undefined) wake(dropped);
294
+ }
295
+ }
296
+ return state;
297
+ };
298
+ const errorText = (error: unknown): string => {
299
+ if (typeof error === "string") return error;
300
+ if (!error || typeof error !== "object") return "";
301
+ const e = error as Record<string, unknown>;
302
+ // QA-P21-2 nit 1: a host error may carry its text one level down (`error.data.message`).
303
+ const data = e.data !== null && typeof e.data === "object" ? (e.data as Record<string, unknown>) : undefined;
304
+ return [e.type, e.name, e.message, data?.message].filter((part) => typeof part === "string").join(" ");
305
+ };
306
+ const classify = (state: ChildState, error: unknown): void => {
307
+ if (state.failure === "overflow") return;
308
+ state.failure = HOST_CONTEXT_OVERFLOW_ERROR.test(errorText(error)) ? "overflow" : "other";
309
+ };
310
+ return {
311
+ begin(id) {
312
+ const old = children.get(id);
313
+ children.delete(id);
314
+ if (old !== undefined) wake(old);
315
+ stateOf(id);
316
+ },
317
+ onEvent(type, data) {
318
+ if (!data || typeof data !== "object") return;
319
+ const event = data as Record<string, unknown>;
320
+ const id = event.sessionID;
321
+ if (typeof id !== "string" || id === "") return;
322
+ // QA-P21-1-12: the error text is read from `error` (type/name/message) and from the event's own `message` field.
323
+ const failureOf = (): string => [errorText(event.error), typeof event.message === "string" ? event.message : ""].filter(Boolean).join(" ");
324
+ if (type === "session.step.ended") {
325
+ countStep(stateOf(id), event);
326
+ } else if (type === "session.step.failed") {
327
+ const state = stateOf(id);
328
+ countStep(state, event);
329
+ classify(state, failureOf());
330
+ } else if (type === "session.tool.failed") {
331
+ if (HOST_STEP_LIMIT_TOOL_ERROR.test(failureOf())) stateOf(id).toolLimit = true;
332
+ } else if (EXECUTION_END_TYPES.has(type)) {
333
+ const state = stateOf(id);
334
+ if (type === "session.execution.failed" && (event.error !== undefined || typeof event.message === "string")) classify(state, failureOf());
335
+ state.ended = true;
336
+ wake(state);
337
+ }
338
+ },
339
+ observe(id, stepLimit) {
340
+ const state = children.get(id);
341
+ if (state === undefined) return "unobserved";
342
+ if (state.toolLimit || state.failure === "overflow" || (stepLimit !== null && stepLimit > 0 && state.steps >= stepLimit)) return true;
343
+ return !state.ended || state.failure === "other" ? "unobserved" : false;
344
+ },
345
+ settled(id, timeoutMs) {
346
+ const state = stateOf(id);
347
+ if (state.ended || !(timeoutMs > 0)) return Promise.resolve();
348
+ return new Promise<void>((resolve) => {
349
+ const done = (): void => {
350
+ clearTimeout(timer);
351
+ state.waiters.delete(done);
352
+ resolve();
353
+ };
354
+ const timer = setTimeout(done, timeoutMs);
355
+ timer.unref?.();
356
+ state.waiters.add(done);
357
+ });
358
+ },
359
+ forget(id) {
360
+ const state = children.get(id);
361
+ children.delete(id);
362
+ if (state !== undefined) wake(state);
363
+ },
364
+ };
365
+ }
366
+
367
+ /**
368
+ * Handoffs 34 and 37: the parent's annotation when a role child stopped with `ESCALATE: authority` after recording a request
369
+ * (`router_request_authority`). The child's reasons are quoted as data, never as instructions.
370
+ */
371
+ export function roleAuthorityNotice(agent: string, childSessionID: string, actions: readonly string[], reasons: readonly string[]): string {
372
+ const why = reasons.length > 0 ? ` Reasons: ${reasons.map(quoteChildText).join("; ")}.` : "";
373
+ return `[router] @${agent} asked for more authority: ${actions.join(", ")}.${why} `
374
+ + `NEXT: if the task needs it, resume the same sessionID ("${childSessionID}") with @${agent} to continue with the wider grant `
375
+ + "(the router recomputes the tier floor; do not set `model`); otherwise dispatch the role the reply names.";
376
+ }
377
+
378
+ // ---------------------------------------------------------------------------
379
+ // #84 P2.3 (T2.3.1, T2.3.2): per-session authority of role agents (plan §2.2, §2.5, §2.8 I3/I5/I9; spikes S3, S8, S11;
380
+ // amendments P-3, P-12, P-13, P-17). The agent's MAX policy (registration, P2.1) bounds every child of a role; these helpers
381
+ // narrow ONE session to its dispatch grant. They only ever remove: an action the max policy refuses is refused before them.
382
+ // ---------------------------------------------------------------------------
383
+
384
+ /**
385
+ * The role action a host permission action or tool name stands for (§2.2): `read`, `glob`, `grep`, `edit`, `webfetch`,
386
+ * `websearch` and `router_run` as named; `write`, `patch`, `multiedit`, `apply_patch` are `edit`; every `router_git_*` is
387
+ * `router_git`; every `context7_*` is `context7`; `external_directory` is its own class (a path check, local class). Anything else
388
+ * (`execute`, `shell`, `subagent`, todo tools, MCP tools, …) stands for no role action: never granted to a role session.
389
+ */
390
+ export function roleActionOf(name: string): AuthorityAction | "external_directory" | undefined {
391
+ switch (name) {
392
+ case "read": case "glob": case "grep": case "edit": case "webfetch": case "websearch": case "router_run":
393
+ return name;
394
+ case "write": case "patch": case "multiedit": case "apply_patch":
395
+ return "edit";
396
+ case "external_directory":
397
+ return "external_directory";
398
+ default:
399
+ if (name.startsWith("router_git_")) return "router_git";
400
+ if (name.startsWith("context7_")) return "context7";
401
+ return undefined;
402
+ }
403
+ }
404
+
405
+ // #84 P3.3 (QA-P33F1-1-2): the work-root containment rule lives in routing/roles/work-root.ts, shared with the verifier.
406
+ export { canonicalAuthorityPath, insideWorkRoot };
407
+
408
+ /**
409
+ * QA-P23-A3: every path an `apply_patch` (`patch`) call touches, from the headers of the host's patch format (OpenCode v2
410
+ * `Patch.parse`: `*** Add File:`, `*** Update File:`, `*** Delete File:` and the `*** Move to:` that follows an update; a header
411
+ * with leading blanks counts too). Undefined — the caller refuses — when a header names no path or no header is found (a unified
412
+ * diff, which the v2 host's tool does not take, therefore refuses).
413
+ */
414
+ export function patchPaths(patchText: string): string[] | undefined {
415
+ const paths: string[] = [];
416
+ for (const raw of patchText.split(/\r?\n/)) {
417
+ const line = raw.trimStart();
418
+ const header = ["*** Add File:", "*** Update File:", "*** Delete File:", "*** Move to:"].find((prefix) => line.startsWith(prefix));
419
+ if (header === undefined) continue;
420
+ const path = line.slice(header.length).trim();
421
+ if (path === "") return undefined;
422
+ paths.push(path);
423
+ }
424
+ return paths.length > 0 ? paths : undefined;
425
+ }
426
+
427
+ /**
428
+ * QA-P23-A9: a `glob` pattern or `grep` `include` glob that could reach outside the search root by itself — absolute,
429
+ * drive-qualified (`C:…`), UNC/device (`\\…`, `//…`) or with a `..` segment. Residual (documented): links inside the work root
430
+ * are followed or not by the host's own search (ripgrep), which the router does not see.
431
+ */
432
+ export function unsafeSearchPattern(pattern: string): boolean {
433
+ const text = pattern.trim();
434
+ return /^[\\/]/.test(text) || /^[A-Za-z]:/.test(text) || /(?:^|[\\/])\.\.(?:[\\/]|$)/.test(text);
435
+ }
436
+
437
+ /**
438
+ * QA-P23-A2/A3: every path a role session's own `read`/`write`/`edit`/`apply_patch` call names — each string among `filePath`,
439
+ * `path`, `file_path`, each `edits[]` entry's, and every path of a patch text. Undefined when the call names none, or a patch
440
+ * cannot be read (the caller refuses).
441
+ */
442
+ export function toolCallPaths(tool: string, args: unknown): string[] | undefined {
443
+ const record = args !== null && typeof args === "object" ? args as Record<string, unknown> : {};
444
+ const strings = (value: unknown): string[] => (typeof value === "string" && value.trim() !== "" ? [value] : []);
445
+ const fields = (entry: Record<string, unknown>): string[] => [...strings(entry.filePath), ...strings(entry.path), ...strings(entry.file_path)];
446
+ const paths = [...fields(record)];
447
+ if (Array.isArray(record.edits)) {
448
+ for (const edit of record.edits) if (edit !== null && typeof edit === "object") paths.push(...fields(edit as Record<string, unknown>));
449
+ }
450
+ if (tool === "patch" || tool === "apply_patch") {
451
+ const text = [record.patchText, record.patch_text, record.patch, record.input].find((value) => typeof value === "string");
452
+ if (typeof text !== "string") return paths.length > 0 ? paths : undefined;
453
+ const fromPatch = patchPaths(text);
454
+ if (fromPatch === undefined) return undefined;
455
+ paths.push(...fromPatch);
456
+ }
457
+ return paths.length > 0 ? paths : undefined;
458
+ }
459
+
460
+ /**
461
+ * QA-G-A2-2: a path segment that names git's metadata entry `.git` — compared case-insensitively (win32, and stricter
462
+ * elsewhere), with the trailing dots and spaces win32 drops and an NTFS `:stream` suffix removed (`.git.`, `.GIT`,
463
+ * `.git::$INDEX_ALLOCATION` all name `.git` there).
464
+ */
465
+ function gitMetadataSegment(segment: string): boolean {
466
+ return segment.replace(/:.*$/s, "").replace(/[. ]+$/, "").toLowerCase() === ".git";
467
+ }
468
+
469
+ /**
470
+ * QA-G-A2-2: an edit of `path` (canonical `target`, inside `root`) would write `.git` or anything below it — the work root's own
471
+ * repository pointer (a file in a linked worktree) or metadata (config, hooks, `commondir`), or a nested repository's. Such an
472
+ * edit could redirect router_git_* (and the work-root guards) to another repository or a network path. Checked on the canonical
473
+ * path below the root (a link or junction that resolves into `.git` counts, 8.3 spellings never reach here) and on every segment
474
+ * of the path as written.
475
+ */
476
+ export function editsGitMetadata(path: string, target: string, root: string): boolean {
477
+ const base = root.replace(/[\\/]+$/, "");
478
+ const below = target.length > base.length ? target.slice(base.length) : "";
479
+ return [path, below].some((text) => text.split(/[\\/]/).some(gitMetadataSegment));
480
+ }
481
+
482
+ /** The decision for one role-session action: allowed, or refused with the reason the child sees. */
483
+ export type RoleAuthorityDecision = { readonly allow: true } | { readonly allow: false; readonly reason: string };
484
+
485
+ const ALLOW: RoleAuthorityDecision = Object.freeze({ allow: true });
486
+ const refuse = (reason: string): RoleAuthorityDecision => ({ allow: false, reason });
487
+
488
+ export interface RoleAuthorityInput {
489
+ /** The host permission action (`event.action`) or the tool name (`execute.before`). */
490
+ readonly action: string;
491
+ /** The paths the action touches (read/edit files, glob/grep search roots, `external_directory` `<dir>/*` resources). */
492
+ readonly paths: readonly string[];
493
+ /** The child's binding ∩ its role max (binding.ts view). */
494
+ readonly binding: Pick<Binding, "kind" | "grant">;
495
+ /** The role is dynamic: `router_request_authority` is part of its catalog (ladder, §2.5). */
496
+ readonly dynamic: boolean;
497
+ /** Base of relative paths: the child session's directory (what the host resolves them against). */
498
+ readonly sessionDirectory: string;
499
+ /** Canonical long form of the plugin's own directory: the work root of a grant without one (`workRoot: null`, I9). */
500
+ readonly fallbackRoot: string | undefined;
501
+ readonly canonical?: (path: string, base: string) => string | undefined;
502
+ /** `glob` patterns / `grep` include globs of the call (QA-P23-A9): refused when {@link unsafeSearchPattern}. */
503
+ readonly patterns?: readonly string[];
504
+ /**
505
+ * QA-P23-2-A1: canonical paths of THIS session's own truncated tool outputs (the host's tool-output store): `read` and `grep`
506
+ * of exactly these files — and, for an exact binding, `external_directory` of their directory — are allowed outside the work
507
+ * root. Never `edit`, `glob` or anything else.
508
+ */
509
+ readonly ownOutputs?: ReadonlySet<string>;
510
+ }
511
+
512
+ /** The shape of a tool-output store file: `<data>/tool-output/tool_<id>` (`MANAGED_DIRECTORY`, `tool_${Identifier.ascending()}`). */
513
+ const TOOL_OUTPUT_FILE = /[\\/]tool-output[\\/]tool_[A-Za-z0-9_-]+$/;
514
+ /** The host's tool-output `external_directory` rule (`path.join(Global.Path.data, "tool-output", "*")`). */
515
+ const TOOL_OUTPUT_GLOB = /[\\/]tool-output[\\/]\*$/;
516
+
517
+ /**
518
+ * QA-P23-3-1: the host's tool-success event — the only source of a session's own truncated outputs (its structured
519
+ * `outputPaths`). OpenCode source (`packages/schema/src/session-event.ts` `SessionEvent.Tool.Success`, published by
520
+ * `session/runner/publish-llm-event.ts` with the `outputPaths` of `ToolOutputStore.bound`, `tool/registry.ts`):
521
+ * `session.next.tool.success`, versioned `.<n>` when published; the plugin protocol the router builds against (2.0.22) names it
522
+ * `session.tool.success`. Exactly these names; no other event, and never text in a tool result, makes an output a session's own.
523
+ */
524
+ export const HOST_TOOL_SUCCESS_EVENT = /^session\.(?:next\.)?tool\.success(?:\.\d+)?$/;
525
+
526
+ /** `target` (canonical) is exactly one of the session's own truncated outputs (win32 case folding, the max policy's matcher). */
527
+ function ownOutput(target: string, outputs: ReadonlySet<string> | undefined): boolean {
528
+ if (outputs === undefined) return false;
529
+ for (const file of outputs) if (permissionMatches(target, file)) return true;
530
+ return false;
531
+ }
532
+
533
+ /** `dir` (canonical) is the directory of one of the session's own truncated outputs. */
534
+ function ownOutputDirectory(dir: string, outputs: ReadonlySet<string> | undefined): boolean {
535
+ if (outputs === undefined) return false;
536
+ for (const file of outputs) if (permissionMatches(dir, file.replace(/[\\/][^\\/]+$/, ""))) return true;
537
+ return false;
538
+ }
539
+
540
+ /**
541
+ * §2.2 / QA-P23-A4 / QA-P23-2-A3: `root` is still a worktree of `git worktree list --porcelain` (prunable entries dropped by
542
+ * `parseWorktreeList`) whose `.git` still has a worktree's shape — a linked worktree's is a file; the main worktree's (the first
543
+ * entry) a directory, or a file for a submodule's main checkout.
544
+ */
545
+ export function listedWorktreeRoot(
546
+ porcelain: string,
547
+ root: string,
548
+ opts: { realpath?: (path: string) => string; gitEntry?: (path: string) => "file" | "directory" | undefined } = {},
549
+ ): boolean {
550
+ const realpath = opts.realpath ?? ((p: string) => realpathSync.native(p));
551
+ const gitEntry = opts.gitEntry ?? ((p: string) => {
552
+ try {
553
+ const stat = statSync(p);
554
+ return stat.isFile() ? "file" : stat.isDirectory() ? "directory" : undefined;
555
+ } catch {
556
+ return undefined;
557
+ }
558
+ });
559
+ const want = normalizeRootText(root);
560
+ for (const [index, entry] of parseWorktreeList(porcelain).entries()) {
561
+ let real: string | undefined;
562
+ try {
563
+ real = realpath(entry);
564
+ } catch {
565
+ real = undefined;
566
+ }
567
+ if (normalizeRootText(entry) !== want && (real === undefined || normalizeRootText(real) !== want)) continue;
568
+ const kind = gitEntry(join(real ?? entry, ".git"));
569
+ return index === 0 ? kind === "directory" || kind === "file" : kind === "file";
570
+ }
571
+ return false;
572
+ }
573
+
574
+ /**
575
+ * T2.3.1 / T2.3.2: may this role session use `action` on `paths`? (plan §2.2, §2.5; I3, I5, I9; P-13)
576
+ * - `execute` (Code Mode) never (R6/P-6: its inner calls are never evaluated); `router_request_authority` for dynamic roles only.
577
+ * - an action outside every role class → refused; a role action outside the dispatch grant → refused (an unknown binding's grant
578
+ * is the role max ∩ local, binding.ts);
579
+ * - `external_directory` (P-13): only an EXACT binding with a work root and a local action, every resource inside that root;
580
+ * an unknown binding or a grant without a root → refused (I9);
581
+ * - path actions (`read`, `edit`, `glob`, `grep`): every path, canonical ({@link canonicalAuthorityPath}; case folded on win32),
582
+ * inside the bound work root — the plugin's directory when the grant has none, except for `edit`, which a grant without a work
583
+ * root never allows (QA-G-B-2); `read`/`edit` with no path refuse (QA-P23-A5);
584
+ * a `glob`/`grep` pattern that reaches outside its search root by itself refuses (QA-P23-A9); every edit tool refuses `.git`
585
+ * and everything below it ({@link editsGitMetadata}, QA-G-A2-2).
586
+ */
587
+ export function roleAuthorityDecision(input: RoleAuthorityInput): RoleAuthorityDecision {
588
+ const { action, binding } = input;
589
+ const grant: DispatchGrant = binding.grant;
590
+ if (action === "execute") return refuse("`execute` (Code Mode) is never available to a role agent");
591
+ if (action === AUTHORITY_TOOL_NAME) {
592
+ return input.dynamic ? ALLOW : refuse(`${AUTHORITY_TOOL_NAME} is only for dynamic roles`);
593
+ }
594
+ const canonical = input.canonical ?? ((path: string, base: string) => canonicalAuthorityPath(path, base));
595
+ const cls = roleActionOf(action);
596
+ if (cls === undefined) return refuse(`${action} is outside every role's authority`);
597
+ if (cls === "external_directory") {
598
+ if (binding.kind !== "exact") return refuse("external_directory: this session is not bound to its dispatch (binding unknown, I9)");
599
+ const root = grant.workRoot;
600
+ if (![...grant.actions].some((a) => a === "read" || a === "glob" || a === "grep" || a === "router_git")) {
601
+ return refuse("external_directory: this dispatch grants no local action");
602
+ }
603
+ if (input.paths.length === 0) return refuse("external_directory: no path to check");
604
+ // QA-P23-2-A1: the directory of the session's own truncated output, for `read`/`grep` of exactly those files.
605
+ const outputs = grant.actions.has("read") || grant.actions.has("grep") ? input.ownOutputs : undefined;
606
+ for (const resource of input.paths) {
607
+ const dir = resource.replace(/[\\/]\*$/, "");
608
+ const target = dir === "" ? undefined : canonical(dir, input.sessionDirectory);
609
+ if (target !== undefined && root !== null && insideWorkRoot(target, root)) continue;
610
+ if (target !== undefined && ownOutputDirectory(target, outputs)) continue;
611
+ return refuse(root === null
612
+ ? "external_directory: this dispatch has no work root (root=)"
613
+ : `external_directory: ${resource} is outside this dispatch's work root ${root}`);
614
+ }
615
+ return ALLOW;
616
+ }
617
+ if (!grant.actions.has(cls)) return refuse(`${action} is not in this dispatch's grant (${[...grant.actions].join(", ") || "none"})`);
618
+ if (cls === "read" || cls === "edit" || cls === "glob" || cls === "grep") {
619
+ // QA-G-B-2 (R7 null-root contract, I3): an edit never falls back to the plugin's directory — without a bound work root it would
620
+ // land in the base checkout. Only the local reads keep the fallback.
621
+ if (cls === "edit" && grant.workRoot === null) return refuse(`${action}: this dispatch has no work root (root=)`);
622
+ const root = grant.workRoot ?? input.fallbackRoot;
623
+ if (root === undefined) return refuse(`${action}: no work root could be resolved`);
624
+ if ((cls === "read" || cls === "edit") && input.paths.length === 0) return refuse(`${action}: no path to check`);
625
+ for (const pattern of input.patterns ?? []) {
626
+ if (unsafeSearchPattern(pattern)) return refuse(`${action}: the pattern ${pattern} reaches outside its search root (use a relative pattern and \`path\`)`);
627
+ }
628
+ for (const path of input.paths) {
629
+ const target = canonical(path, input.sessionDirectory);
630
+ if (target !== undefined && insideWorkRoot(target, root)) {
631
+ if (cls === "edit" && editsGitMetadata(path, target, root)) {
632
+ return refuse(`${action}: ${path} is repository metadata (\`.git\` or below it); a role never edits it`);
633
+ }
634
+ continue;
635
+ }
636
+ if (target !== undefined && (cls === "read" || cls === "grep") && ownOutput(target, input.ownOutputs)) continue; // QA-P23-2-A1
637
+ return refuse(`${action}: ${path} is outside this dispatch's work root ${root} (use an absolute path inside it)`);
638
+ }
639
+ }
640
+ return ALLOW;
641
+ }
642
+
643
+ /**
644
+ * T2.3.2: a tool a role session keeps in its catalog — `execute` never (S8), `router_request_authority` for dynamic roles only
645
+ * (also under an unknown binding: the ladder is how it asks), any other tool only when its role action is in the grant.
646
+ */
647
+ export function roleToolKept(name: string, grant: Pick<DispatchGrant, "actions">, dynamic: boolean): boolean {
648
+ if (name === "execute") return false;
649
+ if (name === AUTHORITY_TOOL_NAME) return dynamic;
650
+ const cls = roleActionOf(name);
651
+ return cls !== undefined && cls !== "external_directory" && grant.actions.has(cls);
652
+ }
653
+
654
+ /** P-3: the parent's annotation when a role child's tool catalog could not be built for at least one of its steps. */
655
+ export function roleCatalogFailureNotice(agent: string, childSessionID: string): string {
656
+ return `[router] @${agent} had no tools for at least one step; check that its result is grounded in tool output, otherwise dispatch `
657
+ + `again (the router could not build its tool catalog for this dispatch: fail closed, session "${childSessionID}").`;
658
+ }
659
+
78
660
  /** Register the existing router engine on the public OpenCode 2 domain APIs. */
79
661
  export async function registerV2Hooks(
80
662
  ctx: Context,
81
663
  hooks: Hooks,
82
664
  runtime?: Pick<V2Runtime, "withToolContext" | "applyChildSystem"> & Partial<Pick<V2Runtime, "dispose" | "forgetSession">>,
665
+ /**
666
+ * `ingest`: the plugin instance's telemetry ingest (M6, QA-2.1-7); without one the adapter ingests nothing.
667
+ * `isBypassed`: the plugin's `/bypass` state (#84 P2.1: the role path's router-gate condition, S10/P-9).
668
+ * `hostBudget`: the host-side budget observer (handoff 22); a private one when absent. `onHostBudget` receives its `observe`,
669
+ * so the plugin's signals read the same observations (src/v2.ts).
670
+ * `hostSettleMs`: how long a role dispatch's result waits for the child's execution-end event (default 500 ms).
671
+ */
672
+ options: {
673
+ ingest?: Ingest; isBypassed?: () => boolean; hostBudget?: HostBudgetObserver; hostSettleMs?: number;
674
+ onHostBudget?: (observe: (childSessionID: string, stepLimit: number | null) => HostBudgetObservation) => void;
675
+ /**
676
+ * QA-P21-1-3: the plugin's budget snapshot of a child (guard state AND the session store's read-only CAP state, the same
677
+ * `captureBudget(child, readCapReached)` its signals read). Absent: the guard's `budgetExhausted` alone.
678
+ */
679
+ budgetSnapshot?: (childSessionID: string) => BudgetSnapshot;
680
+ /** QA-P21-2-4: receives the adapter's "this role agent is registered" check, so the plugin's role runtime follows it. */
681
+ onRoleLive?: (isLive: (agent: string) => boolean) => void;
682
+ /** QA-P21-2 nit 3: `router_verify` is registered (index.ts `routerVerifyEnabled`); nothing is deferred otherwise. */
683
+ routerVerifyEnabled?: () => boolean;
684
+ /**
685
+ * #84 P2.3 (§2.2): `git worktree list --porcelain` in a directory (stdout), for the fresh re-check of a sibling work root when
686
+ * a role session's `external_directory` is evaluated. Default: `gitWorktreeList` (dispatch.ts).
687
+ */
688
+ listWorktrees?: (cwd: string) => Promise<string>;
689
+ /** Role-agent registration (roles mode): the repository's worktree roots for the `external_directory` allow rules. Default: `listWorktrees` (role-agents.ts, a real `git worktree list`). */
690
+ listRegistrationWorktrees?: (directory: string) => Promise<string[]>;
691
+ /**
692
+ * QA-G-A3-2: the plugin's count of a role child's call refused outside its guard (index.ts `recordRoleRefusal`): the router's
693
+ * role-authority refusal here in `execute.before`, a host permission denial in `execute.after`. Returns the guard's text to
694
+ * add to the refusal (its denied_cap stop or advisory banner), or undefined. Absent: refusals are not counted.
695
+ */
696
+ recordRefusal?: (sessionID: string, agent: string | undefined, tool: string, args: unknown) => string | undefined;
697
+ } = {},
83
698
  ): Promise<() => Promise<void>> {
84
699
  // The old plugin surface uses separate mutable input/output bags. Keep those
85
700
  // casts confined to this adapter, rather than weakening the v2 event types.
@@ -88,6 +703,290 @@ export async function registerV2Hooks(
88
703
  const abort = new AbortController();
89
704
  const verifyingCalls = new Set<string>();
90
705
  const depthBanners = new Map<string, string>();
706
+ // M6 (2.1.3): child-session outcomes and costs reach the outcome store through the plugin instance's ingest, which
707
+ // does nothing unless routing.engine != static (its settings are null otherwise: no bundle, no files).
708
+ const ingestLogger = createPluginLogger();
709
+ const ingest: Ingest = options.ingest ?? NOOP_INGEST;
710
+ // An ingestion error is logged and the loop carries on: it must never cost the router an event.
711
+ const ingesting = async (what: string, run: () => void | Promise<void>): Promise<void> => {
712
+ try {
713
+ await run();
714
+ } catch (error) {
715
+ if (!abort.signal.aborted) ingestLogger.warn(`[router] telemetry ingestion: ${what} failed`, { error: error instanceof Error ? error.message : String(error) });
716
+ }
717
+ };
718
+ // M7 (2.2): dispatch routing and the protocol/hint adaptation share one runtime; it touches nothing (no host call, no
719
+ // store, no disk) while routing.engine is static, which is the default and what every config without a `routing` block is.
720
+ const sessionOf = (sessionID: string): Promise<unknown> => ctx.session.get({ sessionID } as Parameters<typeof ctx.session.get>[0]);
721
+ /**
722
+ * QA-P21-1-8: this instance started in roles mode (set by the first agent build at setup). Role agents, role routing and the
723
+ * role tools (index.ts registers them at start) exist only then; a switch to roles at runtime is refused with a notice
724
+ * ("restart OpenCode"), and a switch back to tiers drops the role agents on the next build. Plan amendment R8.
725
+ */
726
+ let rolesStarted: boolean | undefined;
727
+ /**
728
+ * QA-P21-2-4: a role agent is live only when its registration succeeded (the agent map the transform publishes holds it as a
729
+ * role agent). Set once the agent map exists; until then nothing is registered.
730
+ */
731
+ let registeredRole: (agent: string) => boolean = () => false;
732
+ options.onRoleLive?.((agent) => rolesStarted === true && registeredRole(agent));
733
+ const engine = createEngineRuntime({
734
+ loadConfig: () => loadConfig(ctx.location.directory),
735
+ listAgents: async () => (await ctx.agent.list()).data,
736
+ listModels: async () => (await ctx.model.list({ location: { directory: ctx.location.directory } })).data,
737
+ ...(ctx.generate === undefined ? {} : { generate: ctx.generate }),
738
+ logger: ingestLogger,
739
+ });
740
+ const dispatchRouter = createDispatchRouter({
741
+ runtime: engine, getSession: sessionOf, graderAgent: V2_GRADER_AGENT, directory: ctx.location.directory,
742
+ logger: { warn: (message, extra) => ingestLogger.warn(message, extra), debug: (message, extra) => console.debug(message, extra ?? "") },
743
+ ...(options.isBypassed === undefined ? {} : { isBypassed: () => options.isBypassed?.() === true }),
744
+ // QA-P21-1-8 / QA-P21-2-4: started in roles mode AND this role agent's registration succeeded.
745
+ rolesEnabled: (agent) => rolesStarted === true && registeredRole(agent),
746
+ ...(options.routerVerifyEnabled === undefined ? {} : { routerVerifyEnabled: options.routerVerifyEnabled }),
747
+ });
748
+ // #84 P2.1: the role table of a config (empty in tiers mode, where every role branch below is skipped), cached per config object.
749
+ // QA-P21-1-8: also empty unless this instance STARTED in roles mode (its role agents and tools are registered only then).
750
+ const roleTables = new WeakMap<RouterConfig, ReadonlyMap<string, RoleSpec>>();
751
+ const NO_ROLES: ReadonlyMap<string, RoleSpec> = new Map();
752
+ const rolesOf = (cfg: RouterConfig): ReadonlyMap<string, RoleSpec> => {
753
+ if (rolesStarted !== true) return NO_ROLES;
754
+ let roles = roleTables.get(cfg);
755
+ if (roles === undefined) {
756
+ try {
757
+ roles = resolveRoles(cfg, "v2");
758
+ } catch (error) {
759
+ roles = new Map();
760
+ ingestLogger.warn("[router] roles: the role table could not be resolved; no role runtime for this config", { error: String(error) });
761
+ }
762
+ roleTables.set(cfg, roles);
763
+ }
764
+ // QA-P21-2-4: only the role agents whose registration succeeded are live.
765
+ const live = [...roles].filter(([name]) => registeredRole(name));
766
+ return live.length === roles.size ? roles : new Map(live);
767
+ };
768
+ const maxOfRoles = (roles: ReadonlyMap<string, RoleSpec>) => (agent: string) => roleMaxActions(roles.get(agent));
769
+ /** Handoff 32: what the binding reads of a child session (parent, agent, title, first message text). */
770
+ const bindingLookup: SessionLookup = async (id) => {
771
+ const session = await ctx.session.get({ sessionID: id } as Parameters<typeof ctx.session.get>[0]) as unknown as Record<string, unknown>;
772
+ let firstText: string | undefined;
773
+ try {
774
+ firstText = firstMessageText(await ctx.session.context({ sessionID: id } as Parameters<typeof ctx.session.context>[0]));
775
+ } catch {
776
+ firstText = undefined; // the title marker still binds
777
+ }
778
+ const text = (value: unknown): string | undefined => (typeof value === "string" && value !== "" ? value : undefined);
779
+ // QA-P23-2-B1: whether the session named an agent, for the context hook's "no binding" decision.
780
+ lookupNamedAgent.delete(id);
781
+ lookupNamedAgent.set(id, text(session.agent) !== undefined);
782
+ while (lookupNamedAgent.size > 1000) lookupNamedAgent.delete(lookupNamedAgent.keys().next().value!);
783
+ return {
784
+ ...(text(session.parentID) === undefined ? {} : { parentID: text(session.parentID) }),
785
+ ...(text(session.agent) === undefined ? {} : { agent: text(session.agent) }),
786
+ ...(text(session.title) === undefined ? {} : { title: text(session.title) }),
787
+ ...(firstText === undefined ? {} : { firstText }),
788
+ };
789
+ };
790
+ /** QA-P23-2-B1: the last binding lookup of a session named an agent (bounded). */
791
+ const lookupNamedAgent = new Map<string, boolean>();
792
+ /** Handoff 22: the host's own stops of role children (step limit, context overflow), from the event stream. */
793
+ const hostBudget = options.hostBudget ?? createHostBudgetObserver();
794
+ options.onHostBudget?.((childSessionID, stepLimit) => hostBudget.observe(childSessionID, stepLimit));
795
+ const hostSettleMs = options.hostSettleMs ?? 500;
796
+ /** The host `steps` limit the router registers for a role agent (P-4); null for any other agent. */
797
+ const hostStepLimitOf = (roles: ReadonlyMap<string, RoleSpec>, agent: string): number | null => {
798
+ const spec = roles.get(agent);
799
+ return spec === undefined ? null : roleAgentSteps(spec);
800
+ };
801
+ /** Handoff 36: the parent's last `subagent` call of each role child (the call a resume follows, `consumeAuthority` `afterCall`). */
802
+ const lastCallOfChild = new Map<string, string>();
803
+ const rememberLastCall = (child: string, callID: string): void => {
804
+ lastCallOfChild.delete(child);
805
+ lastCallOfChild.set(child, callID);
806
+ while (lastCallOfChild.size > 1000) lastCallOfChild.delete(lastCallOfChild.keys().next().value!);
807
+ };
808
+ const authorityDeps = (roles: ReadonlyMap<string, RoleSpec>, fallbackAgent: string | undefined): AuthorityDeps => ({
809
+ roleOf: (child) => roles.get(lookupDispatch(child)?.agent ?? fallbackAgent ?? ""),
810
+ roles: () => roles,
811
+ bindingOf: (child) => currentBinding(child, { maxOf: maxOfRoles(roles) }),
812
+ });
813
+ // -------------------------------------------------------------------------
814
+ // #84 P2.3 (T2.3.1, T2.3.2): the per-session authority of a role session, shared by the evaluate, context and execute.before
815
+ // hooks. Every view is the child's binding ∩ the role max of the agent the HOOK names ∩ the role max of the agent the child
816
+ // was bound as (a session resumed under another role never gets the union).
817
+ // -------------------------------------------------------------------------
818
+ /**
819
+ * Canonical long form of the plugin's directory: the work root of a grant without one (I9), for local reads only — never for
820
+ * `edit` (QA-G-B-2); undefined when it does not resolve.
821
+ * QA-P23-A11: only a resolved directory is cached; a failure is retried on the next call.
822
+ */
823
+ let pluginRoot: string | undefined;
824
+ const fallbackRoot = (): string | undefined => {
825
+ if (pluginRoot === undefined) {
826
+ try {
827
+ pluginRoot = realpathSync.native(ctx.location.directory);
828
+ } catch {
829
+ return undefined;
830
+ }
831
+ }
832
+ return pluginRoot;
833
+ };
834
+ /**
835
+ * The live role spec and the binding view of a role session; undefined when the role table has no live spec for `agent`.
836
+ * `stored`: the decision is in the registry (QA-P23-B1/B2) — false when the session lookup failed or reported no parent/agent
837
+ * (binding.ts does not cache those) or the session was deleted meanwhile.
838
+ */
839
+ const roleAuthorityOf = async (sessionID: string, agent: string): Promise<{ spec: RoleSpec; binding: Binding; stored: boolean } | undefined> => {
840
+ const roles = rolesOf(loadConfig(ctx.location.directory));
841
+ const spec = roles.get(agent);
842
+ if (spec === undefined) return undefined;
843
+ const own = roleMaxActions(spec) ?? [];
844
+ const maxOf = (bound: string): AuthorityAction[] | undefined => {
845
+ const boundMax = roleMaxActions(roles.get(bound));
846
+ return boundMax === undefined ? undefined : boundMax.filter((action) => own.includes(action));
847
+ };
848
+ // P-2: lazy, at the first context build or permission evaluation (one decision per child, shared with execute.before).
849
+ const binding = await bind(sessionID, bindingLookup, { maxOf });
850
+ const stored = currentBinding(sessionID, { maxOf }) !== undefined;
851
+ if (stored) dispatchRouter.noteBinding(sessionID, binding); // the observed kind (QA-P21-1-11), once per child; QA-P23-B2
852
+ return { spec, binding, stored };
853
+ };
854
+ /**
855
+ * QA-P23-A8: the role of a session the router knows as a role child — its dispatch record names a registered role agent, or the
856
+ * binding registry holds a decision for it — whatever agent name a hook event carries (or lacks). Undefined otherwise.
857
+ */
858
+ const knownRoleSession = (sessionID: string): string | undefined => {
859
+ const recorded = lookupDispatch(sessionID)?.agent;
860
+ if (typeof recorded === "string" && registeredRole(recorded)) return recorded;
861
+ return currentBinding(sessionID, { maxOf: () => [] }) !== undefined ? "(bound role session)" : undefined;
862
+ };
863
+ /** The directory the host resolves a session's relative paths against (its location), else the plugin's. */
864
+ const sessionDirectoryOf = async (sessionID: string): Promise<string> => {
865
+ const session = await ctx.session.get({ sessionID } as Parameters<typeof ctx.session.get>[0]) as unknown as { location?: { directory?: unknown } };
866
+ const directory = session?.location?.directory;
867
+ return typeof directory === "string" && directory !== "" ? directory : ctx.location.directory;
868
+ };
869
+ /**
870
+ * §2.2: a sibling work root is re-checked against a fresh `git worktree list --porcelain` when `external_directory` is
871
+ * evaluated (a removed worktree, or a plain directory created in its place, no longer counts). QA-P23-A4: `prunable` entries
872
+ * never count (`parseWorktreeList`), and the listed root must still look like that worktree on disk — `<root>/.git` a directory
873
+ * for the main worktree (the first entry), a file for a linked one. Cached 5 s per root; concurrent checks of one root share one
874
+ * `git` run (QA-P23-A12); any failure → not listed (fail closed).
875
+ */
876
+ const listWorktreesOf = options.listWorktrees ?? gitWorktreeList;
877
+ const worktreeChecks = new Map<string, { at: number; listed: Promise<boolean> }>();
878
+ const checkWorktree = async (root: string): Promise<boolean> => {
879
+ try {
880
+ return listedWorktreeRoot(await listWorktreesOf(ctx.location.directory), root);
881
+ } catch {
882
+ return false;
883
+ }
884
+ };
885
+ /**
886
+ * QA-P23-2-A1 / QA-P23-3-1: per session, the canonical paths of its OWN truncated tool outputs — ONLY the structured
887
+ * `outputPaths` the host puts on that session's own tool-success event ({@link HOST_TOOL_SUCCESS_EVENT}). Free text (a
888
+ * truncation marker in a tool result, a file's content, a run's output) never makes a file a session's own. A path must have the
889
+ * tool-output store's shape (`…/tool-output/tool_<id>`) before and after canonicalisation. Bounded (1000 sessions, 64 files each,
890
+ * oldest first out); cleared on `session.deleted`.
891
+ */
892
+ const ownOutputs = new Map<string, Set<string>>();
893
+ const rememberOutputs = (sessionID: unknown, paths: readonly string[]): void => {
894
+ if (typeof sessionID !== "string" || sessionID === "" || paths.length === 0) return;
895
+ for (const path of paths) {
896
+ if (!(posix.isAbsolute(path) || win32.isAbsolute(path)) || !TOOL_OUTPUT_FILE.test(path) || /[*?\0]/.test(path)) continue;
897
+ const canonical = canonicalAuthorityPath(path, path.replace(/[\\/][^\\/]+$/, ""));
898
+ if (canonical === undefined || !TOOL_OUTPUT_FILE.test(canonical)) continue;
899
+ const files = ownOutputs.get(sessionID) ?? new Set<string>();
900
+ ownOutputs.delete(sessionID);
901
+ files.delete(canonical);
902
+ files.add(canonical);
903
+ while (files.size > 64) files.delete(files.values().next().value!);
904
+ ownOutputs.set(sessionID, files);
905
+ while (ownOutputs.size > 1000) ownOutputs.delete(ownOutputs.keys().next().value!);
906
+ }
907
+ };
908
+ const stillAWorktree = (root: string): Promise<boolean> => {
909
+ const own = fallbackRoot();
910
+ if (own !== undefined && normalizeRootText(own) === normalizeRootText(root)) return Promise.resolve(true);
911
+ const cached = worktreeChecks.get(root);
912
+ if (cached !== undefined && Date.now() - cached.at < 5_000) return cached.listed;
913
+ const listed = checkWorktree(root);
914
+ worktreeChecks.delete(root);
915
+ worktreeChecks.set(root, { at: Date.now(), listed });
916
+ while (worktreeChecks.size > 64) worktreeChecks.delete(worktreeChecks.keys().next().value!);
917
+ return listed;
918
+ };
919
+ /** QA-P23-A9: the `glob` pattern / `grep` include glob of a call, from the tool's input or the evaluated event. */
920
+ const searchPatterns = (cls: ReturnType<typeof roleActionOf>, pattern: unknown, include: unknown): string[] => {
921
+ const text = (value: unknown): string[] => (typeof value === "string" && value !== "" ? [value] : []);
922
+ return cls === "glob" ? text(pattern) : cls === "grep" ? text(include) : [];
923
+ };
924
+ /**
925
+ * T2.3.1: the reason a role session's permission request is refused, or undefined when its dispatch grants it. Paths
926
+ * (OpenCode v2 host, `packages/core/src/tool`): the resources of `read`/`edit` (`write`, `apply_patch` assert `edit`) are
927
+ * Location-relative or canonical absolute; `external_directory` resources are `<canonical dir>/*`. `glob`/`grep` resources are
928
+ * their PATTERN, not a path, and the host asserts NO `external_directory` for them (QA-P23-N1): their search root comes from the
929
+ * event's `metadata.path` (default `.`, the session's Location) and is checked here, and again from the call's own input in
930
+ * `execute.before`.
931
+ */
932
+ const roleEvaluateRefusal = async (
933
+ event: { sessionID: unknown; action: string; resources: readonly string[]; metadata?: Record<string, unknown> | undefined },
934
+ agent: string,
935
+ ): Promise<string | undefined> => {
936
+ const sessionID = String(event.sessionID);
937
+ const authority = await roleAuthorityOf(sessionID, agent);
938
+ if (authority === undefined) return "the role table is unavailable (fail closed)";
939
+ const cls = roleActionOf(event.action);
940
+ const metadata = event.metadata !== null && typeof event.metadata === "object" ? event.metadata : undefined;
941
+ const search = cls === "glob" || cls === "grep";
942
+ const paths = cls === "read" || cls === "edit" || cls === "external_directory" ? event.resources
943
+ : search && metadata !== undefined ? [typeof metadata.path === "string" && metadata.path !== "" ? metadata.path : "."] : [];
944
+ const patterns = searchPatterns(cls, event.resources[0], metadata?.include);
945
+ const decision = roleAuthorityDecision({
946
+ action: event.action, paths, patterns, binding: authority.binding, dynamic: authority.spec.authority.mode === "dynamic",
947
+ sessionDirectory: paths.length > 0 ? await sessionDirectoryOf(sessionID) : ctx.location.directory, fallbackRoot: fallbackRoot(),
948
+ ownOutputs: ownOutputs.get(sessionID),
949
+ });
950
+ if (!decision.allow) return decision.reason;
951
+ const root = authority.binding.grant.workRoot;
952
+ if (cls === "external_directory" && root !== null && !(await stillAWorktree(root))) {
953
+ return `external_directory: the work root ${root} is no longer a worktree listed by \`git worktree list --porcelain\``;
954
+ }
955
+ return undefined;
956
+ };
957
+ /**
958
+ * T2.3.1 (P-12, S11): the `execute.before` side of EVERY tool call a role session makes — the tool's role action must be in the
959
+ * grant and its paths inside the work root. Paths: every path a `read`/`write`/`edit`/`apply_patch` call names
960
+ * ({@link toolCallPaths}: `filePath`, `path`, `file_path`, `edits[]`, patch headers; none → refused), the search root of
961
+ * `glob`/`grep` (default: the session directory) and their pattern (QA-P23-A9). The only router check that fires for plugin tools
962
+ * (`router_run`, `router_git_*`: no `evaluate`, S11) and for Code Mode `execute` (S8). A tool outside every role class —
963
+ * `subagent` included — is refused here too (QA-P23-A7), whatever the agent's max policy or the parent's grants say.
964
+ */
965
+ const roleToolRefusal = async (event: { sessionID: unknown; tool: string }, args: any, agent: string): Promise<string | undefined> => {
966
+ const cls = roleActionOf(event.tool);
967
+ if (cls === undefined && event.tool !== "execute" && event.tool !== AUTHORITY_TOOL_NAME) return `${event.tool} is outside every role's authority`;
968
+ const sessionID = String(event.sessionID);
969
+ const authority = await roleAuthorityOf(sessionID, agent);
970
+ if (authority === undefined) return "the role table is unavailable (fail closed)";
971
+ const record = args !== null && typeof args === "object" ? args as Record<string, unknown> : {};
972
+ const sessionDirectory = await sessionDirectoryOf(sessionID);
973
+ let paths: string[] = [];
974
+ if (cls === "read" || cls === "edit") {
975
+ const named = toolCallPaths(event.tool, record);
976
+ if (named === undefined) return `${event.tool}: no path to check (or a patch whose paths cannot be read)`;
977
+ paths = named;
978
+ } else if (cls === "glob" || cls === "grep") {
979
+ paths = [typeof record.path === "string" && record.path !== "" ? record.path : sessionDirectory];
980
+ }
981
+ const decision = roleAuthorityDecision({
982
+ action: event.tool, paths, patterns: searchPatterns(cls, record.pattern, record.include), binding: authority.binding,
983
+ dynamic: authority.spec.authority.mode === "dynamic", sessionDirectory, fallbackRoot: fallbackRoot(), ownOutputs: ownOutputs.get(sessionID),
984
+ });
985
+ return decision.allow ? undefined : decision.reason;
986
+ };
987
+ /** P-3: role children whose catalog failure is already annotated for the parent's current call (cleared when it ends). */
988
+ const catalogFailures = new Set<string>();
989
+ const systemAugmenter = createSystemAugmenter({ runtime: engine, getSession: sessionOf, logger: ingestLogger });
91
990
  let eventTask: Promise<void> | undefined;
92
991
  let disposed = false;
93
992
  const within = <T>(context: ToolContext, operation: () => Promise<T>): Promise<T> =>
@@ -108,6 +1007,10 @@ export async function registerV2Hooks(
108
1007
  disposed = true;
109
1008
  abort.abort();
110
1009
  await runtime?.dispose?.();
1010
+ // Before the event task: disposing releases a step handler that waits for the model catalog (QA-2.1-5).
1011
+ await ingest.dispose();
1012
+ dispatchRouter.dispose(); // this location no longer owns its sessions
1013
+ await engine.dispose();
111
1014
  await eventTask;
112
1015
  await Promise.allSettled(registrations.map((registration) => registration.dispose()));
113
1016
  await hooks.dispose?.();
@@ -124,15 +1027,103 @@ export async function registerV2Hooks(
124
1027
  variant: agent.model?.variant,
125
1028
  };
126
1029
  let config: LegacyConfig = { agent: {}, command: {} };
1030
+ registeredRole = (agent) => roleAgentOf(config.agent[agent]) === agent; // QA-P21-2-4
127
1031
  let originals = new Map<string, string>();
128
1032
  let agentOptions = new Map<string, Record<string, unknown>>();
1033
+ const warnedPermissions = new Set<string>();
1034
+ const warnPermissionOnce = (message: string) => {
1035
+ if (warnedPermissions.has(message)) return;
1036
+ warnedPermissions.add(message);
1037
+ ingestLogger.warn(message);
1038
+ };
1039
+ const warnedRoles = new Set<string>();
1040
+ const warnRoleOnce = (key: string, message: string) => {
1041
+ if (warnedRoles.has(key)) return;
1042
+ warnedRoles.add(key);
1043
+ ingestLogger.warn(message);
1044
+ };
1045
+ // Plugin agents (#81) are protected like read-only tiers: readOnly ones and explicit-permission ones
1046
+ // (which start from `* deny`) both keep their own deny/ask rules against inherited session grants.
1047
+ // The config hook builds plugin agents in the v1 vocabulary (`bash`, `task`); the v2 host evaluates `shell`/`subagent`.
1048
+ const V2_ACTIONS: Readonly<Record<string, string>> = { bash: "shell", task: "subagent" };
1049
+ const v2Actions = (rules: ReturnType<typeof permissionRules>) => rules.map((rule) => ({ ...rule, action: V2_ACTIONS[rule.action] ?? rule.action }));
1050
+ const protectedAgent = (name: string | undefined) => name !== undefined
1051
+ && (config.agent[name]?.permission?.["*"] === "deny" || pluginAgentMarker(config.agent[name]) !== undefined);
1052
+ const agentLabel = (name: string | undefined): string => {
1053
+ const marker = name === undefined ? undefined : pluginAgentMarker(config.agent[name]);
1054
+ return marker !== undefined && !marker.readOnly ? "plugin agent" : "read-only agent";
1055
+ };
1056
+ // Host agents appear after setup (the host's config-agent plugin activates after the router). Names
1057
+ // the router created itself never count as host agents, or a tier would look like an existing one.
1058
+ const routerCreated = new Set<string>();
1059
+ let promptChecked = false;
1060
+ const pendingSubagentNames = (): string[] => {
1061
+ const routerConfig = loadConfig(ctx.location.directory);
1062
+ const tiers = getActiveTiers(routerConfig);
1063
+ return Object.keys(routerConfig.subagentTiers ?? {}).filter((name) =>
1064
+ !Object.hasOwn(tiers, name) && !Object.hasOwn(routerConfig.agents ?? {}, name) && !Object.hasOwn(baseSeed, name));
1065
+ };
1066
+ /** Adds host agents that appeared since setup to the seed; true when the seed grew. */
1067
+ const discoverHostAgents = async (): Promise<boolean> => {
1068
+ const pending = pendingSubagentNames();
1069
+ if (pending.length === 0) return false;
1070
+ let grew = false;
1071
+ for (const agent of (await ctx.agent.list()).data) {
1072
+ if (!pending.includes(agent.id) || routerCreated.has(agent.id) || Object.hasOwn(baseSeed, agent.id)) continue;
1073
+ baseSeed[agent.id] = {
1074
+ mode: agent.mode,
1075
+ model: agent.model && `${agent.model.providerID}/${agent.model.id}`,
1076
+ variant: agent.model?.variant,
1077
+ };
1078
+ grew = true;
1079
+ }
1080
+ return grew;
1081
+ };
129
1082
  let lastConfig: unknown;
130
1083
  // Returns the router config the registry state was built from; the caller
131
1084
  // advances `lastConfig` only once the host registries have reloaded from it.
132
1085
  const buildConfig = async (): Promise<unknown> => {
133
1086
  const next: LegacyConfig = { agent: JSON.parse(JSON.stringify(baseSeed)), command: {} };
1087
+ const context7 = ctx.mcp && (await ctx.mcp.list()).data.some(server => server.name === "context7" && server.status.status !== "disabled");
1088
+ // Presence-only bridge input, never registered as an MCP definition.
1089
+ if (context7) next.mcp = { context7: { type: "local", command: [], enabled: true } };
134
1090
  const nextOriginals = new Map(Object.entries(next.agent).map(([id, agent]) => [id, JSON.stringify(agent)]));
1091
+ // The "no such agent" notice for `subagentTiers` waits for the first prompt-time check (see the prompt hook).
1092
+ Object.defineProperty(next, DEFER_MISSING_SUBAGENT_NOTICE, { value: !promptChecked, enumerable: false });
1093
+ // Names in the setup seed are host built-in agents (not opencode.json entries the config hook can tell apart).
1094
+ Object.defineProperty(next, HOST_SEED_AGENTS, { value: new Set(Object.keys(baseSeed)), enumerable: false });
135
1095
  await hooks.config?.(next);
1096
+ const routerConfig = loadConfig(ctx.location.directory);
1097
+ // #84 P2.1: the role agents (roles mode only; tiers mode returns at once). Built like plugin agents, so the transform
1098
+ // below publishes their max policy and protectedAgent() holds for each; fail closed (no role agent) on any error.
1099
+ // QA-P21-1-8: only when this instance STARTED in roles mode; a runtime switch to roles registers nothing (a restart does).
1100
+ const rolesRequested = routerConfig.routing?.delegation === "roles";
1101
+ rolesStarted ??= rolesRequested;
1102
+ if (rolesStarted) {
1103
+ const registration = await registerRoleAgents(next.agent, routerConfig, {
1104
+ context7: Boolean(context7), directory: ctx.location.directory, seed: baseSeed, warn: warnRoleOnce,
1105
+ ...(options.listRegistrationWorktrees ? { listWorktrees: options.listRegistrationWorktrees } : {}),
1106
+ });
1107
+ // #84 P2.3 (T2.3.3, §2.5): the ladder tool is a plugin tool, advertised to a deny-by-default agent only with an explicit
1108
+ // allow (S11 (a)); the router's catalog filter then keeps it for dynamic roles only. Fixed roles never get it.
1109
+ if (!registration.failed && registration.registered.length > 0) {
1110
+ let roleTable: ReadonlyMap<string, RoleSpec> = new Map();
1111
+ try {
1112
+ roleTable = resolveRoles(routerConfig, "v2");
1113
+ } catch {
1114
+ roleTable = new Map(); // no allow written: the role keeps no ladder (fail closed)
1115
+ }
1116
+ for (const name of registration.registered) {
1117
+ const definition = next.agent[name];
1118
+ if (roleTable.get(name)?.authority.mode !== "dynamic" || definition === undefined || roleAgentOf(definition) !== name) continue;
1119
+ const permission = definition.permission;
1120
+ if (permission !== null && typeof permission === "object") definition.permission = { ...permission, [AUTHORITY_TOOL_NAME]: "allow" };
1121
+ }
1122
+ }
1123
+ } else if (rolesRequested) {
1124
+ warnRoleOnce("roles:restart", ROLES_RESTART_NOTICE);
1125
+ }
1126
+ for (const name of Object.keys(next.agent)) if (!Object.hasOwn(baseSeed, name)) routerCreated.add(name);
136
1127
  const nextOptions = new Map<string, Record<string, unknown>>();
137
1128
  for (const [name, definition] of Object.entries(next.agent)) {
138
1129
  if (nextOriginals.get(name) === JSON.stringify(definition) || !definition.options) continue;
@@ -146,7 +1137,7 @@ export async function registerV2Hooks(
146
1137
  config = next;
147
1138
  originals = nextOriginals;
148
1139
  agentOptions = nextOptions;
149
- return loadConfig(ctx.location.directory);
1140
+ return routerConfig;
150
1141
  };
151
1142
  lastConfig = await buildConfig();
152
1143
  let refreshChain: Promise<void> = Promise.resolve();
@@ -176,13 +1167,86 @@ export async function registerV2Hooks(
176
1167
  if (definition.model) agent.model = modelRef(definition.model, definition.variant);
177
1168
  if (definition.mode) agent.mode = definition.mode;
178
1169
  if (definition.description !== undefined) agent.description = definition.description;
179
- if (definition.prompt !== undefined) agent.system = v2Instructions(definition.prompt);
1170
+ // A plugin agent's prompt is the user's own text: used verbatim, never rewritten for the host vocabulary.
1171
+ const marker = pluginAgentMarker(definition);
1172
+ if (definition.prompt !== undefined) agent.system = marker ? definition.prompt : v2Instructions(definition.prompt);
180
1173
  if (definition.color !== undefined) agent.color = definition.color;
181
1174
  if (definition.steps !== undefined) agent.steps = definition.steps;
1175
+ if (definition.permission) {
1176
+ const inherited = (agent.permissions ?? []) as ReturnType<typeof permissionRules>;
1177
+ let rules = marker ? v2Actions(permissionRules(definition.permission)) : permissionRules(definition.permission);
1178
+ // #84 QA-P23-2-A1: a reading role agent keeps the host's own tool-output directory rule (`<data>/tool-output/*`, host
1179
+ // plugin/agent.ts TRUNCATION_GLOB) so a child can read its truncated output; the router's evaluate hook narrows it to
1180
+ // the session's own files. Placed before the inherited denies, which still win.
1181
+ if (roleAgentOf(definition) === name && evaluatePermission(rules, "read", "x.ts") !== "deny") {
1182
+ const outputs = inherited.filter((rule) => rule.action === "external_directory" && rule.effect === "allow"
1183
+ && TOOL_OUTPUT_GLOB.test(rule.resource));
1184
+ rules = [...rules, ...outputs.map((rule) => ({ action: rule.action, resource: rule.resource, effect: rule.effect }))];
1185
+ }
1186
+ agent.permissions = publishReadOnlyPermissions(
1187
+ name, rules, inherited, warnPermissionOnce, { plugin: marker !== undefined },
1188
+ );
1189
+ }
182
1190
  });
183
1191
  }
184
1192
  }));
185
1193
 
1194
+ // Enforce the protected agent's own deny/ask without destroying inherited
1195
+ // grants: the same session can later resume as medium/heavy (P-R2-3).
1196
+ /** #84 P2.3: a registered role agent (its registration succeeded); every role agent is also a protected agent (P-19). */
1197
+ const roleAgentName = (name: unknown): string | undefined => (typeof name === "string" && registeredRole(name) ? name : undefined);
1198
+ registrations.push(await ctx.permission.hook("evaluate", async event => {
1199
+ let name: string | undefined = event.agent;
1200
+ let protectedKnown = protectedAgent(name);
1201
+ let role = roleAgentName(name);
1202
+ try {
1203
+ // An explicit event agent is authoritative, even when session lookup
1204
+ // would fail or still refers to the previous agent during a switch.
1205
+ name ??= (await ctx.session.get({ sessionID: event.sessionID })).agent;
1206
+ if (name === undefined) {
1207
+ // QA-P23-2-A2: neither the event nor the session names an agent — a session the router knows as a role child is denied.
1208
+ const known = knownRoleSession(String(event.sessionID));
1209
+ if (known !== undefined) {
1210
+ event.effect = "deny";
1211
+ event.message = `Permission denied by role agent ${known}: the session names no agent (fail closed)`;
1212
+ return;
1213
+ }
1214
+ }
1215
+ protectedKnown = protectedAgent(name);
1216
+ role = roleAgentName(name);
1217
+ if (!protectedKnown && role === undefined) return; // QA-P23-A10: every role agent is protected; never skip one
1218
+ const agent = (await ctx.agent.list()).data.find(agent => agent.id === name);
1219
+ const effects = agent ? event.resources.map(resource => evaluatePermission(agent.permissions, event.action, resource)) : ["deny"];
1220
+ if (effects.includes("deny")) {
1221
+ event.effect = "deny";
1222
+ event.message = `Permission denied by ${agentLabel(name)} ${name}: ${event.action}`;
1223
+ } else if (effects.includes("ask") && event.effect === "allow") {
1224
+ event.effect = "ask";
1225
+ event.message = `Approval required by ${agentLabel(name)} ${name}: ${event.action}`;
1226
+ }
1227
+ // #84 P2.3 (T2.3.1, P-13, I3/I9): a role session is narrowed to ITS dispatch grant and work root. Only ever a deny: an
1228
+ // action the max policy refused stays refused, a sensitive-read ask stays an ask when the grant covers it.
1229
+ if (role !== undefined && event.effect !== "deny") {
1230
+ const refusal = await roleEvaluateRefusal(event, role);
1231
+ if (refusal !== undefined) {
1232
+ event.effect = "deny";
1233
+ event.message = `Permission denied by role agent ${role} for this dispatch: ${refusal}`;
1234
+ }
1235
+ }
1236
+ } catch (error) {
1237
+ // QA-P23-A8: no agent on the event and the session lookup failed — a session the router knows as a role child (its
1238
+ // dispatch record or its binding) is still a role session, and is denied.
1239
+ if (role === undefined && event.agent === undefined) role = knownRoleSession(String(event.sessionID));
1240
+ if (protectedKnown) event.effect = "deny";
1241
+ // P-3: a role agent's evaluation error is an explicit deny; other agents keep today's behaviour.
1242
+ if (role !== undefined) {
1243
+ event.effect = "deny";
1244
+ event.message = `Permission denied by role agent ${role}: the router could not check this dispatch's authority (fail closed)`;
1245
+ }
1246
+ warnPermissionOnce(`read-only permission evaluation failed for ${name ?? "unknown agent"}: ${String(error)}`);
1247
+ }
1248
+ }));
1249
+
186
1250
  registrations.push(await ctx.command.transform((editor) => {
187
1251
  for (const [name, definition] of Object.entries(config.command)) editor.add({
188
1252
  name,
@@ -213,6 +1277,12 @@ export async function registerV2Hooks(
213
1277
  }));
214
1278
 
215
1279
  registrations.push(await ctx.tool.transform((editor) => {
1280
+ // execute is denied for read-only tiers. Keep the explicitly allowed docs
1281
+ // lookups directly callable rather than stranding them in Code Mode.
1282
+ if (config.mcp?.context7) for (const name of CONTEXT7_DOC_TOOLS) editor.update(name, definition => {
1283
+ const { pinned: _pinned, ...options } = definition.options ?? {};
1284
+ definition.options = { ...options, codemode: false };
1285
+ });
216
1286
  for (const [name, definition] of Object.entries(hooks.tool ?? {})) editor.add({
217
1287
  name,
218
1288
  description: v2Instructions(definition.description),
@@ -220,9 +1290,12 @@ export async function registerV2Hooks(
220
1290
  // Router tools must remain directly callable, matching v1 tool exposure.
221
1291
  options: { codemode: false },
222
1292
  execute: async (args, context) => within(context, async () => {
1293
+ const directory = name.startsWith("router_git_")
1294
+ ? (await ctx.session.get({ sessionID: context.sessionID })).location?.directory ?? ctx.location.directory
1295
+ : ctx.location.directory;
223
1296
  const result = await definition.execute(args, {
224
1297
  sessionID: context.sessionID, messageID: context.messageID, agent: context.agent,
225
- directory: ctx.location.directory, worktree: ctx.location.project.directory,
1298
+ directory, worktree: name.startsWith("router_git_") ? "" : ctx.location.project.directory, // Session.Info.location has no project; discover from its directory, never the plugin's project.
226
1299
  abort: context.signal,
227
1300
  metadata: (metadata) => { void context.progress(metadata); },
228
1301
  ask: async () => { throw new Error("[model-router] This tool cannot request v1 permissions on OpenCode 2"); },
@@ -246,16 +1319,67 @@ export async function registerV2Hooks(
246
1319
  const output = { message: { agent: session.agent }, parts: [{ type: "text", text: event.prompt.text }] };
247
1320
  await legacy["chat.message"]?.({ sessionID: event.sessionID, agent: session.agent }, output);
248
1321
  event.prompt.text = output.parts.map((part) => part.text).join("\n\n");
249
- if (loadConfig(ctx.location.directory) !== lastConfig) await refresh();
1322
+ // Host agents defined in opencode.json appear after setup: refresh once a pending `subagentTiers` name shows up.
1323
+ const discovered = await discoverHostAgents();
1324
+ if (loadConfig(ctx.location.directory) !== lastConfig || discovered) await refresh();
1325
+ if (!promptChecked) {
1326
+ promptChecked = true;
1327
+ for (const name of pendingSubagentNames()) {
1328
+ warnAgentOptionsEffortOnce(`subagent-tiers:missing:${name}`, `subagentTiers: '${name}' is not defined in opencode.json or the router \`agents\` block; skipped (the router never creates it)`, ingestLogger);
1329
+ }
1330
+ }
250
1331
  }));
251
- registrations.push(await ctx.session.hook("context", async (event) => {
1332
+ /** The context hook's body (QA-P23-B5: declared before the hook that calls it). */
1333
+ async function buildContext(event: SessionContext, role: string | undefined): Promise<void> {
1334
+ if (protectedAgent(event.agent)) {
1335
+ try {
1336
+ // Catalogs use merged session rules; remove widened tools from this
1337
+ // request snapshot only. Resource-specific asks remain callable.
1338
+ const agent = (await ctx.agent.list()).data.find(agent => agent.id === event.agent);
1339
+ for (const name of Object.keys(event.tools ?? {})) {
1340
+ // QA-G-A1-1: every host edit tool (`write`, `patch`, `multiedit`, `apply_patch`) is checked as `edit`, the permission
1341
+ // the host asserts for it; a rule naming the tool itself (never the `*` catch-all) can still deny it.
1342
+ const action = roleActionOf(name) === "edit" ? "edit" : name;
1343
+ const denied = (checked: string): boolean => evaluatePermission(agent!.permissions, checked, "*") === "deny"
1344
+ && !agent!.permissions.some(rule => rule.effect !== "deny" && rule.action === checked && rule.resource !== "*");
1345
+ const ownDeny = (): boolean => action !== name
1346
+ && evaluatePermission(agent!.permissions.filter(rule => rule.action !== "*"), name, "*") === "deny";
1347
+ if (!agent || denied(action) || ownDeny()) delete event.tools[name];
1348
+ }
1349
+ } catch (error) {
1350
+ // QA-P23-B1: a role session's failure goes to the hook's own catch (empty catalog AND the parent's annotation).
1351
+ if (role !== undefined) throw error;
1352
+ // Known protected agent: no usable catalog is safer than widened
1353
+ // tools. Never turn a hook rejection into a host operation failure.
1354
+ for (const name of Object.keys(event.tools ?? {})) delete event.tools[name];
1355
+ warnPermissionOnce(`read-only tool catalog failed for ${event.agent}: ${String(error)}`);
1356
+ }
1357
+ }
1358
+ // #84 P2.3 (T2.3.2, I3): a role session keeps only the tools of ITS dispatch grant (this request snapshot only; sibling
1359
+ // sessions of the same agent are untouched), `execute` never (S8), `router_request_authority` for dynamic roles only — also
1360
+ // under an unknown binding, whose grant is the role max ∩ local (I9). The binding is made here at the latest (P-2).
1361
+ if (role !== undefined) {
1362
+ const authority = await roleAuthorityOf(String(event.sessionID), role);
1363
+ if (authority === undefined) throw new Error(`role ${role}: no live role spec (fail closed)`);
1364
+ // QA-P23-B1: a decision the registry could not keep (the session lookup failed or named no parent/agent) is not a
1365
+ // binding: the catalog is emptied and the parent told, instead of a silently reduced child.
1366
+ // QA-P23-2-B1: only a failed lookup or a session that names no agent; one with an agent but no parent is an unknown
1367
+ // binding (I9 (a): the role max ∩ local), not a failure.
1368
+ if (!authority.stored && (authority.binding.grant.notes.includes(BINDING_NOTES.lookupFailed)
1369
+ || lookupNamedAgent.get(String(event.sessionID)) !== true)) {
1370
+ throw new Error(`role ${role}: the session could not be bound to its dispatch (lookup failed or no agent)`);
1371
+ }
1372
+ const dynamic = authority.spec.authority.mode === "dynamic";
1373
+ for (const name of Object.keys(event.tools ?? {})) if (!roleToolKept(name, authority.binding.grant, dynamic)) delete event.tools[name];
1374
+ }
252
1375
  const input = { sessionID: event.sessionID, agent: event.agent, model: { ...event.model, modelID: event.model.id } };
253
1376
  // V2 consumes per-turn options, not Agent.Info.request.settings.
254
1377
  for (const [key, value] of Object.entries(agentOptions.get(event.agent) ?? {})) {
255
1378
  if (!(key in event.options)) event.options[key] = value;
256
1379
  }
257
1380
  await legacy["chat.params"]?.(input, event.options);
258
- const verify = loadConfig(ctx.location.directory).enforcement?.verify;
1381
+ const routerConfig = loadConfig(ctx.location.directory);
1382
+ const verify = routerConfig.enforcement?.verify;
259
1383
  if (event.agent === V2_GRADER_AGENT
260
1384
  && (verify?.graderTemperature === null
261
1385
  || !(verify?.graderTemperatureModels ?? []).includes(`${event.model.providerID}/${event.model.id}`))) {
@@ -276,6 +1400,11 @@ export async function registerV2Hooks(
276
1400
  return Array.prototype.push.apply(output.system, texts);
277
1401
  } });
278
1402
  await legacy["experimental.chat.system.transform"]?.(input, output);
1403
+ // M7 (2.2): advise/enforce swap the R: line, append the route-line paragraph and add the per-turn hint.
1404
+ // static/shadow (and every config without a routing block) leave `output.system` exactly as the legacy hook built it.
1405
+ await systemAugmenter.augment({
1406
+ sessionID: event.sessionID, agent: event.agent, parentModel: `${event.model.providerID}/${event.model.id}`, messages: event.messages, cfg: routerConfig,
1407
+ }, output.system, added);
279
1408
  event.system = output.system.map((text): SystemPart =>
280
1409
  original.get(text)?.shift() ?? { type: "text", text: added.has(text) ? v2Instructions(text) : text });
281
1410
  runtime?.applyChildSystem(event.sessionID, event.system);
@@ -307,49 +1436,265 @@ export async function registerV2Hooks(
307
1436
  }
308
1437
  }
309
1438
  }
1439
+ }
1440
+ registrations.push(await ctx.session.hook("context", async (event) => {
1441
+ // #84 P2.3 (P-3, I9): a role session's context hook never fails the child. ANY error below empties its catalog (the
1442
+ // strictest outcome) and is annotated for the parent's `subagent` result; every other agent keeps today's behaviour.
1443
+ const role = roleAgentName(event.agent);
1444
+ try {
1445
+ await buildContext(event, role);
1446
+ } catch (error) {
1447
+ if (role === undefined) throw error;
1448
+ for (const name of Object.keys(event.tools ?? {})) delete event.tools[name];
1449
+ warnPermissionOnce(`role tool catalog failed for ${role}: ${String(error)}`);
1450
+ const child = String(event.sessionID);
1451
+ if (!catalogFailures.has(child)) {
1452
+ catalogFailures.add(child);
1453
+ while (catalogFailures.size > 1000) catalogFailures.delete(catalogFailures.values().next().value!);
1454
+ annotateSubagentResult("authority", child, roleCatalogFailureNotice(role, child));
1455
+ }
1456
+ }
310
1457
  }));
311
1458
 
312
1459
  registrations.push(await ctx.tool.hook("execute.before", async (event) => {
313
1460
  const args = await scopedArgs(event);
314
- const original = args && typeof args === "object" ? { ...args } : args;
315
- const output = { args };
316
- if (event.tool === "subagent" && args && typeof args.agent === "string" && args.model === undefined) {
317
- const cfg = loadConfig(ctx.location.directory);
318
- if (cfg.subagentTiers?.[args.agent]) {
319
- const actual = await ctx.agent.list();
320
- const overrides = actual.data.some((agent) => agent.id === args.agent) ? resolveSubagentOverrides({
321
- subagentTiers: cfg.subagentTiers, tiers: getActiveTiers(cfg),
322
- existingAgents: Object.fromEntries(actual.data.map((agent) => [agent.id, { mode: agent.mode }])),
323
- }) : {};
324
- const override = overrides[args.agent];
325
- if (override) args.model = `${override.model}${override.variant ? `#${override.variant}` : ""}`;
326
- }
1461
+ // #84 P2.1 (P-2, handoffs 11/32/33): a role child binds to its dispatch before its tool runs, so `router_run` and
1462
+ // `router_git_*` resolve the bound work root and the guard reads the dispatch budget. Tiers mode: no role table, no call.
1463
+ const callerRoles = rolesOf(loadConfig(ctx.location.directory));
1464
+ if (callerRoles.size > 0 && typeof event.agent === "string" && callerRoles.has(event.agent)) {
1465
+ const maxOf = maxOfRoles(callerRoles);
1466
+ const binding = await bind(String(event.sessionID), bindingLookup, { maxOf });
1467
+ // QA-P21-1-11: the observed kind, once per child; QA-P23-B2: only a decision the registry kept.
1468
+ if (currentBinding(String(event.sessionID), { maxOf }) !== undefined) dispatchRouter.noteBinding(String(event.sessionID), binding);
327
1469
  }
328
- await within(hookContext(event), async () => {
329
- await legacy["tool.execute.before"]?.({ ...event, tool: legacyToolName(event.tool), callID: event.id }, output);
330
- });
331
- const verifying = (output as Record<PropertyKey, unknown>)[TASK_VERIFICATION] === true;
332
- const banner = (output as Record<PropertyKey, unknown>)[DEPTH_BANNER];
333
- if (typeof banner === "string") {
334
- depthBanners.delete(event.id);
335
- depthBanners.set(event.id, banner);
336
- while (depthBanners.size > 1000) depthBanners.delete(depthBanners.keys().next().value!);
1470
+ // #84 P2.3 (T2.3.1, I3, P-12): EVERY tool call of a role session (`subagent` included, QA-P23-A7) stays inside its dispatch
1471
+ // grant and work root. This is the router check that fires for plugin tools and Code Mode `execute` (no `evaluate` does,
1472
+ // S8/S11); errors refuse (fail closed). QA-P23-A8: an event without an agent from a session the router knows as a role child
1473
+ // is refused outright.
1474
+ // QA-G-A3-2: a refusal here is thrown before the legacy hook (and its guard) sees the call: the plugin counts it on the
1475
+ // child's guard state, and the guard's stop (denied_cap) or advisory banner is added to the refusal the child sees.
1476
+ const refused = (message: string, agent: string | undefined): Error => {
1477
+ const guard = options.recordRefusal?.(String(event.sessionID), agent, event.tool, args);
1478
+ return new Error(guard === undefined ? message : `${message}\n${guard}`);
1479
+ };
1480
+ if (typeof event.agent !== "string" || event.agent === "") {
1481
+ const known = knownRoleSession(String(event.sessionID));
1482
+ if (known !== undefined) throw refused(`[router] Refused for role session ${String(event.sessionID)}: the calling agent is unknown (fail closed)`, known);
1483
+ }
1484
+ const callerRole = roleAgentName(event.agent);
1485
+ if (callerRole !== undefined) {
1486
+ let refusal: string | undefined;
1487
+ try {
1488
+ refusal = await roleToolRefusal(event, args, callerRole);
1489
+ } catch {
1490
+ refusal = "the router could not check this dispatch's authority (fail closed)";
1491
+ }
1492
+ if (refusal !== undefined) throw refused(`[router] Refused for role agent ${callerRole} in this dispatch: ${refusal}`, callerRole);
337
1493
  }
338
- if (verifying) {
339
- verifyingCalls.add(event.id);
340
- while (verifyingCalls.size > 1000) verifyingCalls.delete(verifyingCalls.values().next().value!);
1494
+ // #84 P-5: a routed role dispatch runs in the foreground (separate from `verifying`).
1495
+ let roleForeground = false;
1496
+ if (event.tool === "subagent" && args && typeof args.agent === "string") {
1497
+ // The model `subagentTiers` would fill in when the call names none (unchanged behaviour: only then, only for a mapped agent).
1498
+ const cfg = loadConfig(ctx.location.directory);
1499
+ // #84 P-7: roles mode dispatches the host-native `explore` as the `explorer` role agent. Legacy shape: nativeArgs
1500
+ // derives `agent` from `subagent_type`; `args.agent` is set too, so everything below keys on the role name.
1501
+ const alias = roleAgentAlias(args.agent, cfg, (name) => roleAgentOf(config.agent[name]) === name);
1502
+ if (alias !== undefined) { args.agent = alias; args.subagent_type = alias; }
1503
+ let tierModel: string | undefined;
1504
+ if (args.model === undefined) {
1505
+ if (cfg.subagentTiers?.[args.agent]) {
1506
+ const actual = await ctx.agent.list();
1507
+ const overrides = actual.data.some((agent) => agent.id === args.agent) ? resolveSubagentOverrides({
1508
+ subagentTiers: cfg.subagentTiers, tiers: getActiveTiers(cfg), pluginAgents: cfg.agents,
1509
+ existingAgents: Object.fromEntries(actual.data.map((agent) => [agent.id, { mode: agent.mode }])),
1510
+ }) : {};
1511
+ const override = overrides[args.agent];
1512
+ if (override) tierModel = `${override.model}${override.variant ? `#${override.variant}` : ""}`;
1513
+ }
1514
+ }
1515
+ // M7 (2.2): the engine goes first. Static (the default) returns untouched without any host call; shadow/advise only
1516
+ // log and strip `[route …]`; enforce may also replace agent and model. `subagentTiers` then only fills a missing model.
1517
+ // #84 P2.1 (handoff 36): a resume of a role child applies the authority its previous call recorded and annotated; the
1518
+ // widened actions recompute the tier floor in `route()`. QA-P21-1-10: the request is only READ before routing and
1519
+ // consumed once `route()` succeeded — a refused dispatch keeps it and queues no notice. Q1 (P2.3 call site): only an
1520
+ // EXACT binding widens; any other drops the request ("binding unknown: dispatch a fresh task"), shown on this result.
1521
+ // QA-G-A1-2: a resume by another session than the one the request was escalated to drops it, with the notice.
1522
+ const roles = rolesOf(cfg);
1523
+ const resumeID = typeof args.sessionID === "string" && args.sessionID !== "" ? args.sessionID : undefined;
1524
+ let widened: AuthorityAction[] | undefined;
1525
+ let afterRoute: (() => void) | undefined;
1526
+ if (resumeID !== undefined && roles.has(args.agent)) {
1527
+ hostBudget.begin(resumeID); // handoff 22: the host's step count starts over with the resumed attempt
1528
+ // QA-P21-2 nit 2: one preview (authority.ts) decides what consumeAuthority would do; Q1 via `exactOnly`. QA-G-A1-2: only
1529
+ // the session the request was escalated to may apply it (`parentSessionID`); any other resuming session drops it.
1530
+ const deps = authorityDeps(roles, args.agent);
1531
+ const resume = { afterCall: lastCallOfChild.get(resumeID) ?? "", exactOnly: true, parentSessionID: String(event.sessionID) };
1532
+ const preview = previewAuthority(resumeID, deps, resume);
1533
+ if (preview.status === "widened") widened = [...preview.widened];
1534
+ if (preview.status === "dropped" && preview.reason === AUTHORITY_TEXT.dropped.bindingUnknown) {
1535
+ afterRoute = () => {
1536
+ evictAuthority(resumeID); // consumeAuthority would widen a non-exact binding: the request is dropped here instead
1537
+ annotateSubagentResult("authority", resumeID, `[router] ${AUTHORITY_BINDING_UNKNOWN_DROP}`);
1538
+ };
1539
+ } else if (preview.status !== "none") {
1540
+ afterRoute = () => {
1541
+ // QA-G-A1-3: `exactOnly` here too, so the consume can never widen a binding the preview did not see as exact.
1542
+ const consumed = consumeAuthority(resumeID, deps, resume);
1543
+ if (consumed.status === "dropped") annotateSubagentResult("authority", resumeID, `[router] ${consumed.reason}.`);
1544
+ };
1545
+ }
1546
+ }
1547
+ const routed = await dispatchRouter.route({
1548
+ callID: event.id, sessionID: event.sessionID, agent: event.agent, args, tierModel, cfg,
1549
+ ...(widened === undefined ? {} : { widened }),
1550
+ });
1551
+ // QA-G-A1-2: a delegate's resume (the unparsed, floor-rung path) never consumes the request: it widens nothing, and the
1552
+ // request stays for the session it was escalated to. QA-G-A1-2-2: neither does a resume route() left untouched (no role
1553
+ // decision: a runner-announced call, a call another instance handled) — consuming it would widen the binding outside a
1554
+ // routed decision, with no floor recomputed.
1555
+ if (routed.role !== undefined && routed.role.delegate !== true) afterRoute?.();
1556
+ if (routed.prompt !== undefined) args.prompt = routed.prompt;
1557
+ // #84 P2.1-C: a fresh role dispatch carries its nonce at the END of the description (title marker, handoff 31).
1558
+ if (routed.description !== undefined) args.description = routed.description;
1559
+ if (routed.role !== undefined) roleForeground = true;
1560
+ if (routed.agent !== undefined) { args.agent = routed.agent; args.subagent_type = routed.agent; }
1561
+ if (routed.model !== undefined) args.model = routed.model;
1562
+ if (args.model === undefined && tierModel !== undefined) args.model = tierModel;
341
1563
  }
342
- if (event.tool === "subagent" && typeof output.args?.prompt === "string") {
343
- const prompt = typeof original?.prompt === "string" ? original.prompt : typeof original?.description === "string" ? original.description : "";
344
- output.args.prompt = translateAdded(prompt, output.args.prompt);
1564
+ // After routing: the prompt the legacy hook starts from is the one the engine left (a stripped route line is not "added" text).
1565
+ try {
1566
+ const original = args && typeof args === "object" ? { ...args } : args;
1567
+ const output = { args };
1568
+ await within(hookContext(event), async () => {
1569
+ await legacy["tool.execute.before"]?.({ ...event, tool: legacyToolName(event.tool), callID: event.id }, output);
1570
+ });
1571
+ const verifying = (output as Record<PropertyKey, unknown>)[TASK_VERIFICATION] === true;
1572
+ const banner = (output as Record<PropertyKey, unknown>)[DEPTH_BANNER];
1573
+ if (typeof banner === "string") {
1574
+ depthBanners.delete(event.id);
1575
+ depthBanners.set(event.id, banner);
1576
+ while (depthBanners.size > 1000) depthBanners.delete(depthBanners.keys().next().value!);
1577
+ }
1578
+ if (verifying) {
1579
+ verifyingCalls.add(event.id);
1580
+ while (verifyingCalls.size > 1000) verifyingCalls.delete(verifyingCalls.values().next().value!);
1581
+ }
1582
+ if (event.tool === "subagent" && typeof output.args?.prompt === "string") {
1583
+ const prompt = typeof original?.prompt === "string" ? original.prompt : typeof original?.description === "string" ? original.description : "";
1584
+ output.args.prompt = translateAdded(prompt, output.args.prompt);
1585
+ }
1586
+ event.input = nativeArgs(event.tool, output.args, original, verifying, roleForeground);
1587
+ } catch (error) {
1588
+ dispatchRouter.onCallFinished(event.id); // the hook chain rejected the call: it will never reach execute.after (2.2)
1589
+ throw error;
345
1590
  }
346
- event.input = nativeArgs(event.tool, output.args, original, verifying);
1591
+ // The input the host will execute (after the legacy hook): the dispatch is registered for ingestion from it, not from what the engine decided (2.2).
1592
+ dispatchRouter.commit(event.id, event.input);
347
1593
  }));
1594
+ /**
1595
+ * #84 P2.1 (T2.1.4; handoffs 28, 34, 37): the parent's `subagent` call of a role child ended. Computed BEFORE the legacy hook
1596
+ * (whose signals read the authority record and the guard state): the notices for the parent's result — resume guidance when
1597
+ * the guard stopped the child on its budget, the child's recorded authority request on `ESCALATE: authority`, a request this
1598
+ * resume dropped. `finish()` runs after the legacy hook: the request is attached to this call on `ESCALATE: authority`
1599
+ * (`markAnnotated`), else dropped (`discardAuthority`); then the call's pending binding entry is evicted (`evictCall`).
1600
+ * `undefined` for every call that is not a role dispatch (tiers mode: always).
1601
+ */
1602
+ const roleAfterCall = async (end: {
1603
+ readonly id: string; readonly sessionID: string; readonly status: string; readonly result: unknown; readonly input: unknown;
1604
+ }): Promise<{ readonly notice: string | undefined; readonly finish: () => void; readonly child: string | null } | undefined> => {
1605
+ const record = (value: unknown): Record<string, unknown> | undefined =>
1606
+ value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
1607
+ const routedRole = routedRoleOf(end.id);
1608
+ const calledAgent = record(end.input)?.agent;
1609
+ const agent = routedRole?.agent ?? (typeof calledAgent === "string" ? calledAgent : undefined);
1610
+ const roles = rolesOf(loadConfig(ctx.location.directory));
1611
+ if (agent === undefined || (routedRole === undefined && !roles.has(agent))) return undefined;
1612
+ const child = end.status === "completed" ? childSessionOf(end.result) : null;
1613
+ const structured = record(end.result)?.output;
1614
+ const running = record(structured)?.status === "running";
1615
+ const output = record(structured)?.output;
1616
+ const text = typeof output === "string" ? output : contentText(record(end.result)?.content);
1617
+ const contract = child === null || running ? null : parseReturnPrefix(text);
1618
+ const escalated = contract?.prefix === "escalate" && contract.claim === "authority";
1619
+ const notices: string[] = [];
1620
+ if (child !== null && !running) {
1621
+ const request = requestedAuthority(child);
1622
+ if (escalated && request !== undefined && request.actions.length > 0 && (!request.annotated || request.callID === end.id)) {
1623
+ annotateSubagentResult("authority", child, roleAuthorityNotice(agent, child, request.actions, request.reasons));
1624
+ }
1625
+ // Handoff 22: the host's own stop (step limit, context overflow) counts like the guard's; its events may trail the result.
1626
+ await hostBudget.settled(child, hostSettleMs);
1627
+ // QA-P21-1-3: the plugin's snapshot (guard stop OR the read-only CAP reached), as its signals read it.
1628
+ const snapshot = options.budgetSnapshot?.(child);
1629
+ // QA-P21-3-1: a reached read cap counts only with a `NEED MORE` return (a DONE at the cap is a finished task).
1630
+ const capStop = snapshot?.readCapReached === true && contract?.prefix === "need-more";
1631
+ // QA-G-A3-1: in advisory mode the guard enforces no stop; a `NEED MORE: budget` return of a tracked child whose budget is
1632
+ // used up is one all the same (the signals' rule), so the parent gets the resume guidance too.
1633
+ const stopped = snapshot === undefined ? budgetExhausted(child) : snapshot.stopped || capStop || budgetClaimObserved(text, snapshot);
1634
+ if (stopped) annotateSubagentResult("budget", child, roleBudgetNotice(agent, child));
1635
+ else if (hostBudget.observe(child, hostStepLimitOf(roles, agent)) === true) annotateSubagentResult("budget", child, roleBudgetNotice(agent, child, "host"));
1636
+ for (const annotation of takeSubagentAnnotations(child)) notices.push(annotation.text);
1637
+ }
1638
+ return {
1639
+ notice: notices.length > 0 ? notices.join("\n\n") : undefined,
1640
+ child,
1641
+ finish: () => {
1642
+ try {
1643
+ if (child !== null) {
1644
+ if (!running && !(escalated && markAnnotated(child, end.id, end.sessionID))) discardAuthority(child, end.id);
1645
+ rememberLastCall(child, end.id);
1646
+ if (!running) catalogFailures.delete(child); // P-3: the next attempt's catalog failure is annotated again
1647
+ }
1648
+ evictCall(end.sessionID, end.id);
1649
+ } catch (error) {
1650
+ ingestLogger.warn("[router] roles: the finished role dispatch could not be released", { error: String(error) });
1651
+ }
1652
+ },
1653
+ };
1654
+ };
348
1655
  registrations.push(await ctx.tool.hook("execute.after", async (event) => {
349
- const banner = depthBanners.get(event.id);
1656
+ // 2.2: the result names the child. A dispatch still waiting for it is registered under it, and a heuristic claim that picked
1657
+ // the wrong child is corrected here, before the legacy hook below records the verdict. A call without a result is just dropped.
1658
+ dispatchRouter.onCallResult(event.id, event.status === "completed" ? childSessionOf(event.result) : null);
1659
+ const role = event.tool === "subagent" ? await roleAfterCall({
1660
+ id: event.id, sessionID: String(event.sessionID), status: event.status,
1661
+ result: (event as { result?: unknown }).result, input: (event as { input?: unknown }).input,
1662
+ }) : undefined;
1663
+ try {
1664
+ const depthBanner = depthBanners.get(event.id);
1665
+ // The role notices ride with the depth banner: appended last to the parent's result on every path below.
1666
+ const banner = role?.notice === undefined ? depthBanner : depthBanner === undefined ? role.notice : `${depthBanner}\n\n${role.notice}`;
350
1667
  depthBanners.delete(event.id);
351
1668
  const verifying = verifyingCalls.delete(event.id);
1669
+ // QA-G-A3-2: a role child's call the host refused on a permission (the agent's policy, or this adapter's `evaluate` deny) never
1670
+ // ran and never reached the guard's after-hook: the plugin counts it like the guard's own refusals.
1671
+ if (event.status === "error" && isPermissionRefusal(event.error)) {
1672
+ const agent = roleAgentName(event.agent) ?? (typeof event.agent === "string" && event.agent !== "" ? undefined : knownRoleSession(String(event.sessionID)));
1673
+ if (agent !== undefined) options.recordRefusal?.(String(event.sessionID), agent, event.tool, (event as { input?: unknown }).input);
1674
+ }
352
1675
  if (event.status !== "completed") return;
1676
+ if (event.tool === "grep" && protectedAgent(event.agent)) {
1677
+ const content = event.result.content;
1678
+ event.result = {
1679
+ ...event.result,
1680
+ content: filterSensitiveGrep(contentText(content)),
1681
+ // Native grep also exposes raw matches to SDK callers. Do not leave
1682
+ // their text behind after scrubbing the model-facing representation.
1683
+ ...(Array.isArray(event.result.output) ? { output: event.result.output.filter(match => {
1684
+ if (!match || typeof match !== "object" || !("entry" in match)) return false;
1685
+ const entry = match.entry;
1686
+ return entry !== null && typeof entry === "object" && "path" in entry
1687
+ && typeof entry.path === "string" && !isSensitivePath(entry.path);
1688
+ }) } : {}),
1689
+ };
1690
+ }
1691
+ // QA-G-A3-4 (§2.5): a role child's own text reaches the parent, and a line of it that starts with `[router` would pose as a
1692
+ // router note (`[router budget] … resume …`, `[router ✓ verified: deterministic]`). Every such line start of the child's
1693
+ // text is defanged to `(router` BEFORE the router reads the result and appends its own notes. Role dispatches only: a tier
1694
+ // dispatch's result is untouched (I1); a running acknowledgement is the host's text, not the child's.
1695
+ if (role !== undefined && event.tool === "subagent" && event.result.output?.status !== "running") {
1696
+ event.result = defangChildResult(event.result);
1697
+ }
353
1698
  const structured = event.result.output;
354
1699
  // A user can background a foreground subagent while it is running. That
355
1700
  // acknowledgement is not a final result and must never enter acceptance.
@@ -371,7 +1716,16 @@ export async function registerV2Hooks(
371
1716
  }
372
1717
  const text = event.tool === "subagent" && structured && typeof structured === "object" && typeof structured.output === "string"
373
1718
  ? structured.output : contentText(event.result.content);
374
- const output = { title: "", output: text, metadata: { ...event.result.metadata } };
1719
+ // QA-P21-1-3: the plugin's signals and gate read the child from the legacy metadata; a role result names it there too when
1720
+ // the host reports it only in the structured output (spike S1: `result.output.sessionID`). Tier calls: unchanged.
1721
+ const resultMetadata = event.result.metadata as Record<string, unknown> | undefined;
1722
+ const output = {
1723
+ title: "", output: text,
1724
+ metadata: {
1725
+ ...resultMetadata,
1726
+ ...(role?.child != null && resultMetadata?.sessionID === undefined && resultMetadata?.sessionId === undefined ? { sessionID: role.child } : {}),
1727
+ },
1728
+ };
375
1729
  await within(hookContext(event), async () => {
376
1730
  await legacy["tool.execute.after"]?.({
377
1731
  ...event, tool: legacyToolName(event.tool),
@@ -409,6 +1763,10 @@ export async function registerV2Hooks(
409
1763
  : structured && typeof structured === "object" && typeof structured.output === "string"
410
1764
  ? { output: { ...structured, output: final } } : {}),
411
1765
  };
1766
+ } finally {
1767
+ role?.finish();
1768
+ if (event.tool === "subagent") forgetRoutedRole(event.id);
1769
+ }
412
1770
  }));
413
1771
 
414
1772
  // V2 events are immutable facts. A completed-text warning is a synthetic
@@ -418,7 +1776,40 @@ export async function registerV2Hooks(
418
1776
  if (abort.signal.aborted) break;
419
1777
  try {
420
1778
  const data = event.data as Record<string, any>;
421
- if (event.type === "session.deleted") runtime?.forgetSession?.(data.sessionID);
1779
+ hostBudget.onEvent(event.type, data); // handoff 22 (S4): step counts, step-limit tool refusals, overflow failures
1780
+ // QA-P23-2-A1 / QA-P23-3-1: the host names a tool result's saved full output on that session's tool-success event only.
1781
+ if (HOST_TOOL_SUCCESS_EVENT.test(event.type) && data && Array.isArray(data.outputPaths)) {
1782
+ rememberOutputs(data.sessionID, data.outputPaths.filter((path: unknown): path is string => typeof path === "string"));
1783
+ }
1784
+ if (event.type === "session.step.ended" || event.type === "session.step.failed") {
1785
+ // Cost and tokens of a registered child dispatch (ingest ignores every other session).
1786
+ await ingesting(event.type, () => ingest.onStepEnded(event));
1787
+ continue;
1788
+ }
1789
+ // A new child session: the dispatch the engine routed for it is registered with the 2.1 registry (2.2).
1790
+ if (event.type === "session.created") dispatchRouter.onSessionCreated({ sessionID: data.sessionID, parentID: data.parentID, agent: data.agent, title: data.title });
1791
+ if (event.type === "session.deleted") {
1792
+ runtime?.forgetSession?.(data.sessionID);
1793
+ // #84 P2.1 (handoff 35): the session's binding (as a parent: its pending dispatches and children's bindings) and its
1794
+ // authority requests go with it.
1795
+ if (typeof data.sessionID === "string") {
1796
+ evictBinding(data.sessionID);
1797
+ evictAuthority(data.sessionID);
1798
+ ownOutputs.delete(data.sessionID); // QA-P23-2-A1
1799
+ lookupNamedAgent.delete(data.sessionID);
1800
+ lastCallOfChild.delete(data.sessionID);
1801
+ hostBudget.forget(data.sessionID);
1802
+ }
1803
+ await ingesting("session.deleted", () => ingest.onSessionGone(data.sessionID));
1804
+ } else if (FLUSH_EVENT_TYPES.has(event.type)) {
1805
+ // The v2 equivalents of session.idle: coalesced, throttled flush (D15); never awaited.
1806
+ await ingesting(event.type, () => {
1807
+ // The child's attempt is over: fold it before the flush that persists it.
1808
+ if (EXECUTION_END_TYPES.has(event.type)) ingest.onExecutionEnded(data.sessionID, event.id);
1809
+ ingest.sweep();
1810
+ ingest.requestFlush();
1811
+ });
1812
+ }
422
1813
  if (event.type === "session.text.ended") {
423
1814
  const output = { text: data.text };
424
1815
  await legacy["experimental.text.complete"]?.({ sessionID: data.sessionID, messageID: data.assistantMessageID }, output);