opencode-model-router 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +90 -12
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +24 -1
  5. package/src/compat/child-session.ts +43 -0
  6. package/src/compat/v2-client.ts +107 -7
  7. package/src/compat/v2-hooks.ts +1435 -44
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +496 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/guard/enforce.ts +186 -22
  13. package/src/guard/guards.ts +132 -6
  14. package/src/guard/store.ts +5 -0
  15. package/src/index.ts +1193 -56
  16. package/src/router/build-info.ts +151 -0
  17. package/src/router/config.ts +1611 -19
  18. package/src/router/dispatch-header.ts +46 -4
  19. package/src/router/git-tools.ts +1152 -0
  20. package/src/router/guard-profile.ts +100 -0
  21. package/src/router/plugin-agents.ts +433 -0
  22. package/src/router/prompts.ts +26 -1
  23. package/src/router/protocol.ts +180 -0
  24. package/src/router/read-only.ts +149 -0
  25. package/src/router/role-agents.ts +409 -0
  26. package/src/router/roles-config.ts +429 -0
  27. package/src/router/roles.ts +600 -0
  28. package/src/router/run-tools.ts +913 -0
  29. package/src/router/sensitive-paths.ts +101 -0
  30. package/src/router/sessions.ts +533 -9
  31. package/src/router/subagents.ts +28 -1
  32. package/src/routing/advisor/findings.ts +898 -0
  33. package/src/routing/advisor/index.ts +614 -0
  34. package/src/routing/classify/backends/host.ts +163 -0
  35. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  36. package/src/routing/classify/backends/shared.ts +741 -0
  37. package/src/routing/classify/backends/typesafe.ts +315 -0
  38. package/src/routing/classify/fences.ts +96 -0
  39. package/src/routing/classify/index.ts +594 -0
  40. package/src/routing/classify/route-line.ts +362 -0
  41. package/src/routing/classify/rules.ts +667 -0
  42. package/src/routing/classify/scrub.ts +214 -0
  43. package/src/routing/classify/state.ts +148 -0
  44. package/src/routing/classify/text.ts +20 -0
  45. package/src/routing/classify/types.ts +1310 -0
  46. package/src/routing/commands/annotate-plan.ts +652 -0
  47. package/src/routing/commands/stats.ts +134 -0
  48. package/src/routing/commands/v1-roles.ts +64 -0
  49. package/src/routing/engine/index.ts +32 -0
  50. package/src/routing/engine/kernel.ts +760 -0
  51. package/src/routing/engine/ladders.ts +802 -0
  52. package/src/routing/engine/plan.ts +404 -0
  53. package/src/routing/engine/protocol-line.ts +150 -0
  54. package/src/routing/engine/roles-taxonomy.ts +52 -0
  55. package/src/routing/engine/simulate.ts +167 -0
  56. package/src/routing/engine/types.ts +368 -0
  57. package/src/routing/file-lock.ts +53 -0
  58. package/src/routing/outcomes/beta.ts +147 -0
  59. package/src/routing/outcomes/cost.ts +313 -0
  60. package/src/routing/outcomes/index.ts +215 -0
  61. package/src/routing/outcomes/ingest.ts +960 -0
  62. package/src/routing/outcomes/persist.ts +1080 -0
  63. package/src/routing/outcomes/signals.ts +650 -0
  64. package/src/routing/outcomes/stats.ts +873 -0
  65. package/src/routing/outcomes/store.ts +673 -0
  66. package/src/routing/outcomes/types.ts +1093 -0
  67. package/src/routing/roles/authority.ts +495 -0
  68. package/src/routing/roles/binding.ts +543 -0
  69. package/src/routing/roles/policy.ts +416 -0
  70. package/src/routing/roles/work-root.ts +132 -0
  71. package/src/routing/wire/dispatch.ts +2088 -0
  72. package/src/routing/wire/hint.ts +222 -0
  73. package/src/routing/wire/host-info.ts +256 -0
  74. package/src/routing/wire/runtime.ts +348 -0
  75. package/src/v2.ts +40 -1
  76. package/src/verify/checker.ts +249 -7
  77. package/src/verify/deterministic.ts +10 -1
  78. package/src/verify/dispatch.ts +63 -6
  79. package/src/verify/dod.ts +127 -10
  80. package/src/verify/gate.ts +75 -7
  81. package/src/verify/types.ts +12 -0
  82. package/src/verify/wiring.ts +55 -10
  83. package/tiers.json +13 -5
@@ -0,0 +1,409 @@
1
+ /**
2
+ * Role agent registration on OpenCode v2 (issue #84, plan P2.1 T2.1.1).
3
+ *
4
+ * In roles mode (`routing.delegation: "roles"`, v2 only) the router registers every enabled role
5
+ * of the role table as a router-defined agent with the role's MAX policy: deny-by-default, only
6
+ * the role's actions under their host names, `execute`/`subagent`/`task`/`delegate`/`shell`
7
+ * denied explicitly, the read-only tiers' sensitive-read asks, and `external_directory` allowed
8
+ * only for the repository's worktree roots (listed at registration) and the `routing.workRoots`
9
+ * patterns. The definitions carry the plugin-agent marker, so the v2 adapter publishes them like
10
+ * #81 plugin agents (inherited denies only) and `protectedAgent()` holds for each of them (P-19):
11
+ * the router's evaluate and context hooks then enforce the policy under a granting parent too.
12
+ *
13
+ * Nothing here runs on v1 or in tiers mode: {@link registerRoleAgents} returns before touching
14
+ * anything (I1/I8). A failure while resolving or building the roles registers no role agent at
15
+ * all (fail closed); tier agents are never touched.
16
+ */
17
+ import { realpathSync } from "node:fs";
18
+ import { join } from "node:path";
19
+ import { resolveActiveTiers, resolveRolesRouting, type RouterConfig, type TierConfig } from "./config";
20
+ import { GIT_TOOL_NAMES, gitEnvironment, gitExecutable, hardeningArgs, inheritedSafeDirectoryArgs, spawnBounded } from "./git-tools";
21
+ import { positiveBudget, REFUSAL_CAP, ROUTE_BUDGET_RAISE_MAX, TIER_GUARD_BUDGET } from "./guard-profile";
22
+ import { PLUGIN_AGENT, pluginAgentMarker, pluginAgentPolicy, type PluginAgentMarker } from "./plugin-agents";
23
+ import { CONTEXT7_DOC_TOOLS, type PermissionMap } from "./read-only";
24
+ import { ACTION_CLASS, HOST_NATIVE_ROLE_NAMES, resolveRoleTable, SHIPPED_ROLE_SPECS, type AuthorityAction, type RoleSpec, type RoleTable } from "./roles";
25
+ import { workRootProblem } from "./roles-config";
26
+
27
+ /**
28
+ * Steps above the largest guard budget a role dispatch can reach. The guard's `NEED MORE: budget`
29
+ * must fire before the host's step limit (P-4): a limit of N leaves N-1 tool-capable steps, one
30
+ * step is the final text-only answer after the budget stop, and three are headroom.
31
+ */
32
+ export const ROLE_STEPS_MARGIN = 5;
33
+
34
+ /** Host actions no role agent is ever granted, listed as explicit denies (R6/P-6, §2.2). */
35
+ export const ROLE_DENIED_ACTIONS: readonly string[] = Object.freeze(["execute", "subagent", "task", "delegate", "shell"]);
36
+
37
+ /** Host-native agent names dispatched in roles mode under a role agent's name (P-7, spike S9). */
38
+ export const ROLE_AGENT_ALIASES: Readonly<Record<string, string>> = Object.freeze({ explore: "explorer" });
39
+
40
+ /**
41
+ * The host `steps` limit of a role agent: the largest guard budget any dispatch of the role can
42
+ * get (the role's top tier budget raised by a route-line `budget=` up to
43
+ * {@link ROUTE_BUDGET_RAISE_MAX}×), plus {@link REFUSAL_CAP} refused calls the guard does not
44
+ * charge, plus {@link ROLE_STEPS_MARGIN}. QA-G-A3-6: the top budget is never below
45
+ * {@link TIER_GUARD_BUDGET}, the budget a tier the role has no budget for can get
46
+ * (`roleGuardProfile`'s fallback), so the guard still stops before the host's step limit.
47
+ */
48
+ export function roleAgentSteps(spec: Pick<RoleSpec, "budget">): number {
49
+ const budgets = Object.values(spec.budget).map((n) => positiveBudget(n) ?? TIER_GUARD_BUDGET);
50
+ const top = Math.max(budgets.length > 0 ? Math.max(...budgets) : TIER_GUARD_BUDGET, TIER_GUARD_BUDGET);
51
+ return ROUTE_BUDGET_RAISE_MAX * top + REFUSAL_CAP + ROLE_STEPS_MARGIN;
52
+ }
53
+
54
+ /** Host action (tool) names one role action stands for; `execute` stands for none. */
55
+ function hostNames(action: AuthorityAction, context7: boolean): readonly string[] {
56
+ switch (action) {
57
+ case "router_git": return GIT_TOOL_NAMES;
58
+ case "context7": return context7 ? CONTEXT7_DOC_TOOLS : [];
59
+ case "execute": return [];
60
+ default: return [action];
61
+ }
62
+ }
63
+
64
+ /**
65
+ * The host action names a role's max policy allows, in the role's order: `read`, `glob`, `grep`,
66
+ * `edit`, `webfetch`, `websearch` and `router_run` as named, `router_git` as every
67
+ * `router_git_*` tool (P-12), `context7` as the documentation tools only when the context7 MCP
68
+ * server is configured, `execute` never.
69
+ */
70
+ export function roleHostActions(spec: Pick<RoleSpec, "authority">, opts: { context7: boolean }): string[] {
71
+ const out: string[] = [];
72
+ for (const action of spec.authority.allow) {
73
+ for (const name of hostNames(action, opts.context7)) if (!out.includes(name)) out.push(name);
74
+ }
75
+ return out;
76
+ }
77
+
78
+ /** True when a role has an action of the local class, the only class `external_directory` belongs to (§2.2). */
79
+ export function roleHasLocalActions(spec: Pick<RoleSpec, "authority">): boolean {
80
+ return spec.authority.allow.some((action) => ACTION_CLASS[action] === "local");
81
+ }
82
+
83
+ /**
84
+ * A role's max permission policy (v2 action names, ordered, last match wins): `* deny` first,
85
+ * then an allow per {@link roleHostActions}, then `external_directory` allows for `externalDirectory`
86
+ * (local roles only; a bare `*` is never written), then the {@link ROLE_DENIED_ACTIONS} denies;
87
+ * the `read` rules are rebuilt by the plugin-agent policy with the sensitive-read asks after the
88
+ * grant (a role without `read` gets `read: { "*": "deny" }`).
89
+ */
90
+ export function roleMaxPermission(
91
+ spec: Pick<RoleSpec, "authority">,
92
+ opts: { context7: boolean; externalDirectory: readonly string[] },
93
+ ): PermissionMap {
94
+ const own: PermissionMap = { "*": "deny" };
95
+ for (const name of roleHostActions(spec, opts)) own[name] = "allow";
96
+ const patterns = roleHasLocalActions(spec)
97
+ ? [...new Set(opts.externalDirectory)].filter((pattern) => pattern !== "" && !/^[*?]+$/.test(pattern))
98
+ : [];
99
+ if (patterns.length > 0) own.external_directory = Object.fromEntries(patterns.map((pattern) => [pattern, "allow" as const]));
100
+ for (const action of ROLE_DENIED_ACTIONS) own[action] = "deny";
101
+ return pluginAgentPolicy({ permission: own }, { context7: opts.context7, host: "v2" }).permission;
102
+ }
103
+
104
+ /** The plugin-agent marker of a role agent definition: `role` names the role. */
105
+ export interface RoleAgentMarker extends PluginAgentMarker {
106
+ role: string;
107
+ }
108
+
109
+ /** The role a definition was registered for, or undefined (tier agents, #81 plugin agents, host agents). */
110
+ export function roleAgentOf(definition: unknown): string | undefined {
111
+ const marker = pluginAgentMarker(definition) as Partial<RoleAgentMarker> | undefined;
112
+ return typeof marker?.role === "string" ? marker.role : undefined;
113
+ }
114
+
115
+ function validModel(model: unknown): model is string {
116
+ return typeof model === "string" && model.indexOf("/") >= 1;
117
+ }
118
+
119
+ /**
120
+ * The host `agent.<name>` definition of a role agent (the v1 config shape the v2 adapter
121
+ * translates): the floor tier's model and variant as registered fallback (P-1, spike S1: a
122
+ * model-less child would inherit the parent's model), the role prompt verbatim, the role's max
123
+ * policy, `steps` per {@link roleAgentSteps}, mode `subagent`, and the plugin-agent marker.
124
+ */
125
+ export function buildRoleAgentDefinition(
126
+ spec: RoleSpec,
127
+ floor: Pick<TierConfig, "model" | "variant">,
128
+ opts: { context7: boolean; externalDirectory: readonly string[] },
129
+ ): Record<string, unknown> {
130
+ if (!validModel(floor.model)) throw new Error(`role ${spec.agent}: floor tier ${spec.tierRange.floor} has no provider/model reference`);
131
+ const steps = roleAgentSteps(spec);
132
+ const definition: Record<string, unknown> = {
133
+ model: floor.model,
134
+ mode: "subagent",
135
+ description: spec.description,
136
+ prompt: spec.prompt,
137
+ steps,
138
+ maxSteps: steps,
139
+ ...(floor.variant ? { variant: floor.variant } : {}),
140
+ permission: roleMaxPermission(spec, opts),
141
+ };
142
+ const marker: RoleAgentMarker = { tier: spec.tierRange.floor, readOnly: !spec.authority.allow.includes("edit"), role: spec.agent };
143
+ Object.defineProperty(definition, PLUGIN_AGENT, { value: marker, enumerable: false, configurable: true });
144
+ return definition;
145
+ }
146
+
147
+ // ---------------------------------------------------------------------------
148
+ // external_directory: worktree roots and routing.workRoots (§2.2, R4, P-11, spike S11)
149
+ // ---------------------------------------------------------------------------
150
+
151
+ /** Worktree paths of `git worktree list --porcelain` output; bare entries carry no working tree. */
152
+ export function parseWorktreeList(stdout: string): string[] {
153
+ const out: string[] = [];
154
+ for (const block of stdout.replace(/\r\n/g, "\n").split(/\n\s*\n/)) {
155
+ const lines = block.split("\n");
156
+ const head = lines.find((line) => line.startsWith("worktree "));
157
+ if (head === undefined || lines.includes("bare")) continue;
158
+ const path = head.slice("worktree ".length);
159
+ if (path !== "" && !out.includes(path)) out.push(path);
160
+ }
161
+ return out;
162
+ }
163
+
164
+ const WORKTREE_LIST_TIMEOUT_MS = 10_000;
165
+
166
+ /**
167
+ * The worktree paths of the repository `directory` belongs to, as `git worktree list --porcelain`
168
+ * prints them (hardened git: no hooks, no fsmonitor, no global/system config). The user's
169
+ * system/global `safe.directory` values are passed back as `-c safe.directory=…` pairs
170
+ * (QA-G-A2-2-1), so a repository trusted that way is not refused as "dubious ownership". Throws
171
+ * when git fails, so the caller registers no worktree rule.
172
+ */
173
+ export async function listWorktrees(directory: string): Promise<string[]> {
174
+ const started = performance.now();
175
+ const executable = gitExecutable();
176
+ const trusted = await inheritedSafeDirectoryArgs(executable, WORKTREE_LIST_TIMEOUT_MS);
177
+ const result = await spawnBounded(executable, [...hardeningArgs(), ...trusted, "worktree", "list", "--porcelain"], directory, {
178
+ env: gitEnvironment(), timeoutMs: Math.max(1, WORKTREE_LIST_TIMEOUT_MS - (performance.now() - started)), maxBytes: 1024 * 1024,
179
+ });
180
+ if (result.code !== 0 || result.truncated) {
181
+ throw new Error(`git worktree list failed (exit ${String(result.code)}${result.truncated ? ", output truncated" : ""}): ${result.stderr.toString("utf8").trim()}`);
182
+ }
183
+ return parseWorktreeList(result.output.toString("utf8"));
184
+ }
185
+
186
+ type Realpath = (path: string) => string;
187
+ const nativeRealpath: Realpath = (path) => realpathSync.native(path);
188
+
189
+ function sep(): string {
190
+ return process.platform === "win32" ? "\\" : "/";
191
+ }
192
+
193
+ /**
194
+ * The `external_directory` allow pattern of one existing worktree root: its canonical long form
195
+ * (`realpathSync.native`) followed by `<sep>*`, the shape spike S11 proved; undefined when the
196
+ * root does not resolve or its canonical form still fails the P1.1 rules (an 8.3 component, …).
197
+ */
198
+ export function worktreeRootPattern(root: string, realpath: Realpath = nativeRealpath): string | undefined {
199
+ let canonical: string;
200
+ try {
201
+ canonical = realpath(root);
202
+ } catch {
203
+ return undefined;
204
+ }
205
+ return workRootProblem(canonical) === undefined ? join(canonical, "*") : undefined;
206
+ }
207
+
208
+ /**
209
+ * The `external_directory` allow pattern of one `routing.workRoots` entry (P-11): the static
210
+ * directory before the first wildcard in its canonical long form, then the glob tail verbatim
211
+ * (`D:/git/omr-rta-*` → `D:\git\omr-rta-*`); an entry without a wildcard is a root (`<root>\*`).
212
+ * Undefined, with the reason, when the entry or its canonical form fails the P1.1 rules or the
213
+ * static directory does not exist: fail closed, never a wider pattern.
214
+ */
215
+ export function workRootPattern(entry: string, realpath: Realpath = nativeRealpath): { pattern?: string; problem?: string } {
216
+ const problem = workRootProblem(entry);
217
+ if (problem !== undefined) return { problem };
218
+ const globAt = entry.search(/[*?[\]{}]/);
219
+ if (globAt === -1) {
220
+ const pattern = worktreeRootPattern(entry, realpath);
221
+ return pattern === undefined ? { problem: "does not resolve to a directory in canonical long form" } : { pattern };
222
+ }
223
+ const prefix = entry.slice(0, globAt);
224
+ const cut = Math.max(prefix.lastIndexOf("/"), prefix.lastIndexOf("\\"));
225
+ const directory = prefix.slice(0, cut + 1);
226
+ const tail = entry.slice(cut + 1);
227
+ let canonical: string;
228
+ try {
229
+ canonical = realpath(directory);
230
+ } catch {
231
+ return { problem: `static directory ${directory} does not exist` };
232
+ }
233
+ const pattern = /[\\/]$/.test(canonical) ? canonical + tail : canonical + sep() + tail;
234
+ const after = workRootProblem(pattern);
235
+ return after === undefined ? { pattern } : { problem: `canonical form ${pattern} ${after}` };
236
+ }
237
+
238
+ /**
239
+ * Every `external_directory` allow pattern of the role max policies: the worktree roots listed at
240
+ * registration, then the `routing.workRoots` patterns; duplicates dropped, a bare `*` never.
241
+ */
242
+ export function externalDirectoryPatterns(
243
+ worktrees: readonly string[],
244
+ workRoots: readonly string[],
245
+ realpath: Realpath = nativeRealpath,
246
+ ): { patterns: string[]; problems: string[] } {
247
+ const patterns: string[] = [];
248
+ const problems: string[] = [];
249
+ const add = (pattern: string) => {
250
+ if (!/^[*?]+$/.test(pattern) && !patterns.includes(pattern)) patterns.push(pattern);
251
+ };
252
+ for (const root of worktrees) {
253
+ const pattern = worktreeRootPattern(root, realpath);
254
+ if (pattern === undefined) problems.push(`worktree ${root} has no canonical long form; not granted`);
255
+ else add(pattern);
256
+ }
257
+ for (const entry of workRoots) {
258
+ const result = workRootPattern(entry, realpath);
259
+ if (result.pattern === undefined) problems.push(`routing.workRoots entry ${entry} ${result.problem ?? "is not usable"}; not granted`);
260
+ else add(result.pattern);
261
+ }
262
+ return { patterns, problems };
263
+ }
264
+
265
+ // ---------------------------------------------------------------------------
266
+ // Registration
267
+ // ---------------------------------------------------------------------------
268
+
269
+ export interface RoleRegistration {
270
+ /** Role agents written into the agent map. */
271
+ readonly registered: readonly string[];
272
+ /** #81 agents with a role name removed (dropped by the table, or every one on failure). */
273
+ readonly removed: readonly string[];
274
+ /** #81 agents with a role name kept in place of the shipped role. */
275
+ readonly replaced: readonly string[];
276
+ /** `external_directory` allow patterns written into local roles. */
277
+ readonly externalDirectory: readonly string[];
278
+ /** True when registration failed and no role agent was registered. */
279
+ readonly failed: boolean;
280
+ }
281
+
282
+ const NONE: RoleRegistration = Object.freeze({
283
+ registered: Object.freeze([]), removed: Object.freeze([]), replaced: Object.freeze([]), externalDirectory: Object.freeze([]), failed: false,
284
+ });
285
+
286
+ export interface RoleRegistrationOptions {
287
+ /** The context7 MCP server is configured (its documentation tools become direct tools). */
288
+ context7: boolean;
289
+ /** The project directory: its repository's worktrees are listed. */
290
+ directory: string;
291
+ /** The host's own agents at setup (name → seed definition); a removed #81 entry falls back to it. */
292
+ seed: Readonly<Record<string, Record<string, unknown>>>;
293
+ /** Logs `message` once per `key`. */
294
+ warn: (key: string, message: string) => void;
295
+ /** Injection points (tests). */
296
+ listWorktrees?: (directory: string) => Promise<string[]>;
297
+ resolveTable?: (cfg: RouterConfig, host: "v1" | "v2", opts: { context7?: boolean }) => RoleTable;
298
+ realpath?: Realpath;
299
+ }
300
+
301
+ const PREFIX = "roles mode (OpenCode v2 only): ";
302
+
303
+ /** Removes a router-built agent: the host seed comes back when the name is a host agent. */
304
+ function remove(agents: Record<string, Record<string, unknown>>, name: string, seed: RoleRegistrationOptions["seed"]): void {
305
+ if (Object.hasOwn(seed, name)) agents[name] = JSON.parse(JSON.stringify(seed[name])) as Record<string, unknown>;
306
+ else delete agents[name];
307
+ }
308
+
309
+ /**
310
+ * Registers the role agents into `agents` (the v1-shaped `agent` map the v2 adapter's agent
311
+ * transform publishes). v2 only, and only when `routing.delegation` is `roles`; otherwise returns
312
+ * at once without reading anything else (I1). Uses the role table with the real context7 flag:
313
+ * every enabled role is written under its name (a host-native one such as `general` is replaced,
314
+ * {@link HOST_NATIVE_ROLE_NAMES}); a #81 agent the table drops is removed (overwritten by the
315
+ * role); one that replaces a role is left as built. All-or-nothing: when resolution or a
316
+ * definition throws, no role agent is registered, every #81 agent with a role name is removed
317
+ * (its separation cannot be checked) and one notice is logged; tier agents are untouched.
318
+ */
319
+ export async function registerRoleAgents(
320
+ agents: Record<string, Record<string, unknown>>,
321
+ cfg: RouterConfig,
322
+ opts: RoleRegistrationOptions,
323
+ ): Promise<RoleRegistration> {
324
+ // QA-P21-1-9: tiers mode returns before anything is resolved, so no resolution error can touch the agent map (I1).
325
+ if (cfg.routing?.delegation !== "roles") return NONE;
326
+ let routing: ReturnType<typeof resolveRolesRouting>;
327
+ try {
328
+ routing = resolveRolesRouting(cfg, "v2");
329
+ } catch (error) {
330
+ return fail(agents, opts, error);
331
+ }
332
+ if (routing.delegation !== "roles") return NONE;
333
+ let built: Map<string, Record<string, unknown>>;
334
+ let table: RoleTable;
335
+ let externalDirectory: string[] = [];
336
+ try {
337
+ table = (opts.resolveTable ?? resolveRoleTable)(cfg, "v2", { context7: opts.context7 });
338
+ const tiers = resolveActiveTiers(cfg);
339
+ let worktrees: string[] = [];
340
+ if ([...table.roles.values()].some(roleHasLocalActions)) {
341
+ try {
342
+ worktrees = await (opts.listWorktrees ?? listWorktrees)(opts.directory);
343
+ } catch (error) {
344
+ opts.warn("roles:worktrees", `${PREFIX}the repository's worktrees could not be listed (${errorText(error)}); role agents get no worktree external_directory rule`);
345
+ }
346
+ }
347
+ const found = externalDirectoryPatterns(worktrees, routing.workRoots, opts.realpath ?? nativeRealpath);
348
+ for (const problem of found.problems) opts.warn(`roles:external:${problem}`, `${PREFIX}${problem}`);
349
+ externalDirectory = found.patterns;
350
+ built = new Map();
351
+ for (const [name, spec] of table.roles) {
352
+ const floor = tiers[spec.tierRange.floor];
353
+ if (floor === undefined) throw new Error(`role ${name}: floor tier ${spec.tierRange.floor} is not in the active preset`);
354
+ built.set(name, buildRoleAgentDefinition(spec, floor, { context7: opts.context7, externalDirectory }));
355
+ }
356
+ } catch (error) {
357
+ return fail(agents, opts, error);
358
+ }
359
+ const removed: string[] = [];
360
+ for (const name of table.droppedAgents) {
361
+ if (built.has(name)) continue; // overwritten below
362
+ if (pluginAgentMarker(agents[name]) !== undefined) {
363
+ remove(agents, name, opts.seed);
364
+ removed.push(name);
365
+ }
366
+ }
367
+ for (const [name, definition] of built) {
368
+ if (table.droppedAgents.includes(name)) removed.push(name);
369
+ if (Object.hasOwn(opts.seed, name) && !HOST_NATIVE_ROLE_NAMES.includes(name)) {
370
+ opts.warn(`roles:host-agent:${name}`, `${PREFIX}host agent ${name} is replaced by the router's role agent ${name}`);
371
+ }
372
+ agents[name] = definition;
373
+ }
374
+ return Object.freeze({
375
+ registered: Object.freeze([...built.keys()]),
376
+ removed: Object.freeze(removed),
377
+ replaced: Object.freeze([...table.replacedRoles]),
378
+ externalDirectory: Object.freeze([...externalDirectory]),
379
+ failed: false,
380
+ });
381
+ }
382
+
383
+ function errorText(error: unknown): string {
384
+ return (error instanceof Error ? error.message : String(error)).replace(/[\r\n]+\s*/g, " ");
385
+ }
386
+
387
+ function fail(agents: Record<string, Record<string, unknown>>, opts: RoleRegistrationOptions, error: unknown): RoleRegistration {
388
+ const removed: string[] = [];
389
+ for (const spec of SHIPPED_ROLE_SPECS) {
390
+ const name = spec.agent;
391
+ if (pluginAgentMarker(agents[name]) === undefined) continue;
392
+ remove(agents, name, opts.seed);
393
+ removed.push(name);
394
+ }
395
+ opts.warn("roles:registration-failed", `${PREFIX}role agent registration failed (${errorText(error)}); no role agent is registered`);
396
+ return Object.freeze({ ...NONE, removed: Object.freeze(removed), failed: true });
397
+ }
398
+
399
+ /**
400
+ * The role agent a `subagent` call naming `agent` is aliased to (P-7: `explore` → `explorer`), or
401
+ * undefined. Only in roles mode on v2 and only when the target is a registered role agent
402
+ * (`registered(name)`); tiers mode and v1 never alias (I1).
403
+ */
404
+ export function roleAgentAlias(agent: unknown, cfg: RouterConfig, registered: (name: string) => boolean): string | undefined {
405
+ if (typeof agent !== "string" || !Object.hasOwn(ROLE_AGENT_ALIASES, agent)) return undefined;
406
+ if (cfg.routing?.delegation !== "roles") return undefined;
407
+ const target = ROLE_AGENT_ALIASES[agent]!;
408
+ return registered(target) ? target : undefined;
409
+ }