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