opencode-model-router 2.3.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/README.md +56 -10
  3. package/package.json +1 -1
  4. package/src/commands/output.ts +21 -1
  5. package/src/compat/v2-hooks.ts +1322 -18
  6. package/src/escalate/ladder.ts +12 -0
  7. package/src/guard/enforce.ts +186 -22
  8. package/src/guard/guards.ts +132 -6
  9. package/src/guard/store.ts +5 -0
  10. package/src/index.ts +718 -29
  11. package/src/router/config.ts +247 -1
  12. package/src/router/dispatch-header.ts +46 -4
  13. package/src/router/git-tools.ts +1152 -0
  14. package/src/router/guard-profile.ts +100 -0
  15. package/src/router/plugin-agents.ts +433 -0
  16. package/src/router/prompts.ts +26 -1
  17. package/src/router/protocol.ts +133 -0
  18. package/src/router/read-only.ts +149 -0
  19. package/src/router/role-agents.ts +409 -0
  20. package/src/router/roles-config.ts +429 -0
  21. package/src/router/roles.ts +600 -0
  22. package/src/router/run-tools.ts +913 -0
  23. package/src/router/sensitive-paths.ts +101 -0
  24. package/src/router/sessions.ts +92 -0
  25. package/src/router/subagents.ts +28 -1
  26. package/src/routing/advisor/findings.ts +193 -1
  27. package/src/routing/advisor/index.ts +13 -5
  28. package/src/routing/classify/index.ts +23 -5
  29. package/src/routing/classify/route-line.ts +67 -3
  30. package/src/routing/classify/rules.ts +80 -20
  31. package/src/routing/classify/types.ts +34 -4
  32. package/src/routing/commands/stats.ts +3 -0
  33. package/src/routing/engine/kernel.ts +163 -0
  34. package/src/routing/engine/ladders.ts +242 -1
  35. package/src/routing/engine/protocol-line.ts +17 -0
  36. package/src/routing/engine/roles-taxonomy.ts +52 -0
  37. package/src/routing/engine/types.ts +99 -1
  38. package/src/routing/outcomes/beta.ts +10 -4
  39. package/src/routing/outcomes/index.ts +44 -1
  40. package/src/routing/outcomes/ingest.ts +163 -15
  41. package/src/routing/outcomes/persist.ts +23 -1
  42. package/src/routing/outcomes/signals.ts +650 -0
  43. package/src/routing/outcomes/stats.ts +273 -2
  44. package/src/routing/outcomes/store.ts +25 -5
  45. package/src/routing/outcomes/types.ts +145 -6
  46. package/src/routing/roles/authority.ts +495 -0
  47. package/src/routing/roles/binding.ts +543 -0
  48. package/src/routing/roles/policy.ts +416 -0
  49. package/src/routing/roles/work-root.ts +132 -0
  50. package/src/routing/wire/dispatch.ts +1306 -17
  51. package/src/routing/wire/hint.ts +14 -0
  52. package/src/routing/wire/runtime.ts +117 -28
  53. package/src/v2.ts +26 -1
  54. package/src/verify/checker.ts +249 -7
  55. package/src/verify/deterministic.ts +10 -1
  56. package/src/verify/dispatch.ts +63 -6
  57. package/src/verify/dod.ts +127 -10
  58. package/src/verify/gate.ts +75 -7
  59. package/src/verify/types.ts +12 -0
  60. package/src/verify/wiring.ts +55 -10
  61. package/tiers.json +13 -5
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Guard profiles (plan §2.6, §2.9 E6). Pure.
3
+ *
4
+ * A dispatch is guarded as a READER (no consecutive-non-producing denial: reading
5
+ * is the work) or as a PRODUCER (the read/draft guard pushes towards a write).
6
+ * Role dispatches carry an explicit `GuardProfile`; tier dispatches are readers when
7
+ * the tier is read-only (#78), when the routed class is review/recon/search, or when
8
+ * the dispatch is uncapped by a justified `CAP:none` + `reason:`.
9
+ */
10
+ import type { RoleSpec } from "./roles";
11
+
12
+ /** Per-delegation guard profile; buildGuardPolicy accepts it optionally. */
13
+ export interface GuardProfile {
14
+ kind: "reader" | "producer";
15
+ budget: number;
16
+ cumulative: number;
17
+ }
18
+
19
+ /** Total tool-call budget of a tier dispatch (re-exported as DEFAULT_GUARD_BUDGET by enforce.ts). */
20
+ export const TIER_GUARD_BUDGET = 25;
21
+
22
+ /** Cumulative ceiling across resumed dispatches = this multiple of the total budget. */
23
+ export const GUARD_CUMULATIVE_MULTIPLIER = 3;
24
+
25
+ /**
26
+ * Refused tool calls allowed per dispatch round before every call is refused
27
+ * (QA-P15-1-4): min(budget, REFUSAL_CAP). Refusals are not charged to the
28
+ * budget, so a child can take up to budget + REFUSAL_CAP steps; the host
29
+ * `steps` limit must sit above that (P-4: steps = top budget + REFUSAL_CAP + margin).
30
+ */
31
+ export const REFUSAL_CAP = 10;
32
+
33
+ /** A route-line `budget=` raises a role budget to at most this multiple of it. */
34
+ export const ROUTE_BUDGET_RAISE_MAX = 2;
35
+
36
+ /** Routed task classes whose dispatches read rather than produce. */
37
+ export const READER_CLASSES: ReadonlySet<string> = new Set(["review", "recon", "search"]);
38
+
39
+ export type ReaderReason = "role" | "read-only-tier" | "class" | "uncapped";
40
+
41
+ export interface ReaderSignals {
42
+ /** A role dispatch's profile: its kind decides alone. */
43
+ profile?: GuardProfile;
44
+ /** The dispatch runs on a read-only tier (`isReadOnlyTier`). */
45
+ readOnlyTier?: boolean;
46
+ /** The routed task class of the dispatch, when known. */
47
+ taskClass?: string | null;
48
+ /** The honoured CAP directive: "none" only for `CAP:none` with a `reason:` line. */
49
+ cap?: number | "none" | null;
50
+ }
51
+
52
+ /** Why a dispatch is guarded as a reader, or null for a producer. */
53
+ export function readerReason(signals: ReaderSignals): ReaderReason | null {
54
+ if (signals.profile !== undefined) return signals.profile.kind === "reader" ? "role" : null;
55
+ if (signals.readOnlyTier === true) return "read-only-tier";
56
+ if (typeof signals.taskClass === "string" && READER_CLASSES.has(signals.taskClass)) return "class";
57
+ if (signals.cap === "none") return "uncapped";
58
+ return null;
59
+ }
60
+
61
+ /** A positive integer, or undefined for anything else (NaN, ≤ 0, ±Infinity). */
62
+ export function positiveBudget(value: unknown): number | undefined {
63
+ if (typeof value !== "number" || !Number.isFinite(value)) return undefined;
64
+ const n = Math.floor(value);
65
+ return n >= 1 ? n : undefined;
66
+ }
67
+
68
+ /**
69
+ * The total budget after a route-line `budget=`: raise-only, at most
70
+ * ROUTE_BUDGET_RAISE_MAX × base. An absent or invalid request keeps the base.
71
+ */
72
+ export function raisedBudget(base: number, requested?: number | null): number {
73
+ const asked = positiveBudget(requested);
74
+ if (asked === undefined) return base;
75
+ return Math.min(Math.max(base, asked), base * ROUTE_BUDGET_RAISE_MAX);
76
+ }
77
+
78
+ /** The role's own budget for `tier` (a positive integer), or undefined. */
79
+ function ownBudget(role: Pick<RoleSpec, "budget">, tier: string): number | undefined {
80
+ return positiveBudget(Object.prototype.hasOwnProperty.call(role.budget, tier) ? role.budget[tier] : undefined);
81
+ }
82
+
83
+ /**
84
+ * The guard profile of a role dispatch on `tier`: total = the role's budget for the
85
+ * tier, raised by `budget=` up to 2×; cumulative = total × GUARD_CUMULATIVE_MULTIPLIER.
86
+ * A tier the role has no budget for (a floor lifted above the role's ceiling, an
87
+ * invalid entry) gets max(the role's budget for its ceiling tier, TIER_GUARD_BUDGET)
88
+ * (QA-G-A3-7): a lifted dispatch never gets less than the role on its ceiling, nor
89
+ * less than a tier agent. Without a known ceiling: TIER_GUARD_BUDGET.
90
+ */
91
+ export function roleGuardProfile(
92
+ role: Pick<RoleSpec, "guard" | "budget"> & { readonly tierRange?: Pick<RoleSpec["tierRange"], "ceiling"> },
93
+ tier: string,
94
+ routeBudget?: number | null,
95
+ ): GuardProfile {
96
+ const ceiling = role.tierRange === undefined ? undefined : ownBudget(role, role.tierRange.ceiling);
97
+ const base = ownBudget(role, tier) ?? Math.max(ceiling ?? 0, TIER_GUARD_BUDGET);
98
+ const budget = raisedBudget(base, routeBudget);
99
+ return { kind: role.guard, budget, cumulative: budget * GUARD_CUMULATIVE_MULTIPLIER };
100
+ }
@@ -0,0 +1,433 @@
1
+ import type { Preset, TierConfig } from "./config";
2
+ import {
3
+ evaluatePermission, legacyReadOnlyTools, mergePermissions, permissionMatches, permissionRules, readOnlyPermissions,
4
+ type PermissionEffect, type PermissionMap, type PermissionRule,
5
+ } from "./read-only";
6
+ import { SENSITIVE_PERMISSION_EXCEPTIONS, SENSITIVE_PERMISSION_GLOBS } from "./sensitive-paths";
7
+
8
+ /**
9
+ * A subagent defined in the router config (`agents.<name>` in tiers.json or the
10
+ * global override) instead of the host's opencode.json (#81). Its model and
11
+ * variant always follow `tier` in the active preset; its mode is always
12
+ * `subagent`; its permissions are always published by the router.
13
+ */
14
+ export interface PluginAgentConfig {
15
+ /** Tier of the active preset whose model/variant the agent runs on. */
16
+ tier: string;
17
+ description: string;
18
+ /** System prompt. Used verbatim (never rewritten for the host vocabulary). */
19
+ prompt?: string;
20
+ /** Turn budget. Defaults to the tier's `steps`. */
21
+ steps?: number;
22
+ /** Reuse the #77 read-only policy (deny-by-default, sensitive-read asks). */
23
+ readOnly?: boolean;
24
+ /** Exact or wildcard actions allowed on top of the policy (MCP tools, webfetch, …). */
25
+ allowTools?: string[];
26
+ /**
27
+ * v1-style permission object, canonical v2 action names (`shell`,
28
+ * `subagent`; `bash`/`task` are accepted aliases). Each action maps to an
29
+ * effect or to an ordered `{ pattern: effect }` object; `{ effect: [patterns] }`
30
+ * is accepted too and normalised to the former.
31
+ */
32
+ permission?: PermissionMap;
33
+ }
34
+
35
+ export interface PluginAgentIssue {
36
+ /** Config key path, e.g. `agents.reviewer.tier`. */
37
+ path: string;
38
+ message: string;
39
+ /** The agent concerned; absent when the whole block is. */
40
+ name?: string;
41
+ }
42
+
43
+ /** The v2 grader's agent id (mirrors `V2_GRADER_AGENT`; a unit test pins the two together). */
44
+ export const GRADER_AGENT_NAME = "model-router-grader";
45
+
46
+ /**
47
+ * Names a plugin agent may never take, besides every tier of the active preset:
48
+ * the router's conventional tiers, the grader, and the host's primary/hidden agents.
49
+ */
50
+ export const RESERVED_AGENT_NAMES: readonly string[] = [
51
+ "fast", "medium", "heavy", GRADER_AGENT_NAME, "build", "plan", "title", "summary", "compaction",
52
+ ];
53
+
54
+ /**
55
+ * Actions a plugin agent's `allowTools` may never match. Shell, edits, code execution and delegation
56
+ * are what makes an agent read-only or not; `read` carries the sensitive-path asks. They belong in
57
+ * `permission`. `multiedit`/`apply_patch` are edit tools (the v1 host maps legacy edit tools to the
58
+ * `edit` permission); `execute` is Code Mode; `delegate` is the router's delegation tool. On v2 a
59
+ * `permission` key naming an edit tool only narrows it and `edit` decides; a key that allows what
60
+ * `edit` denies gets a config notice ({@link editToolKeyNotices}, QA-G-A2-2 round 2).
61
+ */
62
+ export const POLICY_ACTIONS: readonly string[] = [
63
+ "shell", "bash", "edit", "write", "patch", "multiedit", "apply_patch", "execute", "subagent", "task", "delegate", "read",
64
+ ];
65
+
66
+ /** The capabilities a read-only agent's own `permission` may never ask for (only deny). */
67
+ const HARD_ACTIONS: readonly string[] = POLICY_ACTIONS.filter((action) => action !== "read");
68
+
69
+ const ENTRY_KEYS = new Set(["tier", "description", "prompt", "steps", "readOnly", "allowTools", "permission"]);
70
+ const EFFECTS = new Set<string>(["allow", "deny", "ask"]);
71
+ const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
72
+ const UNSAFE_NAMES = new Set(["__proto__", "constructor", "prototype"]);
73
+ const ACTION_ALIASES: Readonly<Record<string, string>> = { bash: "shell", task: "subagent" };
74
+ const V1_ACTIONS: Readonly<Record<string, string>> = { shell: "bash", subagent: "task" };
75
+
76
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
77
+ return typeof v === "object" && v !== null && !Array.isArray(v);
78
+ }
79
+
80
+ function isEffect(v: unknown): v is PermissionEffect {
81
+ return typeof v === "string" && EFFECTS.has(v);
82
+ }
83
+
84
+ type Checked<T> = { ok: true; value: T } | { ok: false; issue: PluginAgentIssue };
85
+ const fail = <T>(path: string, message: string): Checked<T> => ({ ok: false, issue: { path, message } });
86
+
87
+ /** Insert `key` last, keeping order meaningful (last match wins on both hosts). */
88
+ function putLast<T>(target: Record<string, T>, key: string, value: T): void {
89
+ delete target[key];
90
+ target[key] = value;
91
+ }
92
+
93
+ /**
94
+ * Normalise a `permission` object: aliases resolved to the v2 names, the
95
+ * `{ effect: [patterns] }` form flattened, insertion order preserved.
96
+ */
97
+ export function normalizePermission(value: unknown, path: string): Checked<PermissionMap> {
98
+ if (!isPlainObject(value)) return fail(path, "must be an object of action rules");
99
+ const out: PermissionMap = {};
100
+ for (const [rawAction, rule] of Object.entries(value)) {
101
+ const at = `${path}.${rawAction}`;
102
+ if (rawAction === "" || rawAction === "__proto__") return fail(at, "is not a valid action");
103
+ const action = ACTION_ALIASES[rawAction] ?? rawAction;
104
+ let normalized: PermissionEffect | Record<string, PermissionEffect>;
105
+ if (typeof rule === "string") {
106
+ if (!isEffect(rule)) return fail(at, "must be allow, deny or ask");
107
+ normalized = rule;
108
+ } else if (isPlainObject(rule)) {
109
+ const keys = Object.keys(rule);
110
+ const grouped = keys.length > 0 && keys.every((key) => EFFECTS.has(key) && Array.isArray(rule[key]));
111
+ const resources: Record<string, PermissionEffect> = {};
112
+ if (grouped) {
113
+ for (const [effect, patterns] of Object.entries(rule)) {
114
+ for (const pattern of patterns as unknown[]) {
115
+ if (typeof pattern !== "string" || pattern === "" || pattern === "__proto__") return fail(`${at}.${effect}`, "must list non-empty patterns");
116
+ putLast(resources, pattern, effect as PermissionEffect);
117
+ }
118
+ }
119
+ } else {
120
+ for (const [pattern, effect] of Object.entries(rule)) {
121
+ if (pattern === "" || pattern === "__proto__") return fail(at, "has an invalid pattern");
122
+ if (!isEffect(effect)) return fail(`${at}.${pattern}`, "must be allow, deny or ask");
123
+ putLast(resources, pattern, effect);
124
+ }
125
+ }
126
+ if (Object.keys(resources).length === 0) return fail(at, "must not be empty");
127
+ normalized = resources;
128
+ } else {
129
+ return fail(at, "must be allow, deny, ask or an object of patterns");
130
+ }
131
+ const previous = out[action];
132
+ if (isPlainObject(previous) && typeof normalized === "object") {
133
+ const merged = { ...previous };
134
+ for (const [pattern, effect] of Object.entries(normalized)) putLast(merged, pattern, effect);
135
+ putLast<PermissionMap[string]>(out, action, merged);
136
+ } else {
137
+ putLast(out, action, normalized);
138
+ }
139
+ }
140
+ return { ok: true, value: out };
141
+ }
142
+
143
+ /** Validate one `agents.<name>` entry; never throws. */
144
+ export function validatePluginAgent(
145
+ name: string,
146
+ entry: unknown,
147
+ ctx: { activePreset: string; tiers: Preset },
148
+ ): Checked<PluginAgentConfig> {
149
+ const at = `agents.${name}`;
150
+ if (!NAME_PATTERN.test(name) || UNSAFE_NAMES.has(name)) {
151
+ return fail(at, "invalid agent name (letters, digits, '.', '_' and '-', at most 64 characters, starting with a letter or digit)");
152
+ }
153
+ if (RESERVED_AGENT_NAMES.includes(name) || Object.hasOwn(ctx.tiers, name)) {
154
+ return fail(at, `'${name}' is reserved (a router tier, the grader, or a host primary/hidden agent)`);
155
+ }
156
+ if (!isPlainObject(entry)) return fail(at, "must be an object");
157
+ for (const key of Object.keys(entry)) {
158
+ if (ENTRY_KEYS.has(key)) continue;
159
+ return fail(`${at}.${key}`, ["model", "variant", "mode"].includes(key)
160
+ ? "is not configurable: the model and variant follow the tier, and the mode is always subagent"
161
+ : "unknown key");
162
+ }
163
+ const { tier, description, prompt, steps, readOnly, allowTools, permission } = entry;
164
+ if (typeof tier !== "string" || tier === "") return fail(`${at}.tier`, "must be a non-empty tier name");
165
+ if (!Object.hasOwn(ctx.tiers, tier)) {
166
+ return fail(`${at}.tier`, `tier '${tier}' is not defined by the active preset '${ctx.activePreset}'; agent skipped`);
167
+ }
168
+ if (typeof description !== "string" || description.trim() === "") return fail(`${at}.description`, "must be a non-empty string");
169
+ if (prompt !== undefined && typeof prompt !== "string") return fail(`${at}.prompt`, "must be a string");
170
+ if (steps !== undefined && (typeof steps !== "number" || !Number.isInteger(steps) || steps < 1)) {
171
+ return fail(`${at}.steps`, "must be a positive integer");
172
+ }
173
+ if (readOnly !== undefined && typeof readOnly !== "boolean") return fail(`${at}.readOnly`, "must be a boolean");
174
+ let tools: string[] | undefined;
175
+ if (allowTools !== undefined) {
176
+ if (!Array.isArray(allowTools)) return fail(`${at}.allowTools`, "must be an array of tool names");
177
+ tools = [];
178
+ for (const [i, tool] of allowTools.entries()) {
179
+ if (typeof tool !== "string" || tool === "" || tool === "__proto__") return fail(`${at}.allowTools[${i}]`, "must be a non-empty tool name");
180
+ // A leading wildcard (`*_*`, `?x`) matches tools the router cannot enumerate, including future host tools.
181
+ if (tool[0] === "*" || tool[0] === "?") return fail(`${at}.allowTools[${i}]`, `'${tool}' starts with a wildcard; name the tool or a prefix such as 'context7_*'`);
182
+ const hit = POLICY_ACTIONS.find((action) => permissionMatches(action, tool));
183
+ if (hit !== undefined) return fail(`${at}.allowTools[${i}]`, `'${tool}' matches '${hit}'; shell, edit, delegation and read rules belong in 'permission'`);
184
+ tools.push(tool);
185
+ }
186
+ }
187
+ let rules: PermissionMap | undefined;
188
+ if (permission !== undefined) {
189
+ const checked = normalizePermission(permission, `${at}.permission`);
190
+ if (!checked.ok) return checked;
191
+ rules = checked.value;
192
+ }
193
+ if (readOnly !== true && rules === undefined) {
194
+ return fail(at, "needs readOnly: true or an explicit permission (a plugin agent never inherits the host's allow-all defaults)");
195
+ }
196
+ if (readOnly === true && rules !== undefined) {
197
+ for (const rule of permissionRules(rules)) {
198
+ if (rule.effect === "allow") {
199
+ return fail(`${at}.permission.${rule.action}`, "a readOnly agent's permission may only add deny or ask rules; grant tools with allowTools");
200
+ }
201
+ if (rule.effect === "ask" && HARD_ACTIONS.some((action) => permissionMatches(action, rule.action))) {
202
+ return fail(`${at}.permission.${rule.action}`, "a readOnly agent may never ask for shell, edit or delegation");
203
+ }
204
+ }
205
+ }
206
+ return {
207
+ ok: true,
208
+ value: {
209
+ tier, description,
210
+ ...(prompt === undefined ? {} : { prompt }),
211
+ ...(steps === undefined ? {} : { steps }),
212
+ ...(readOnly === undefined ? {} : { readOnly }),
213
+ ...(tools === undefined ? {} : { allowTools: tools }),
214
+ ...(rules === undefined ? {} : { permission: rules }),
215
+ },
216
+ };
217
+ }
218
+
219
+ /**
220
+ * Validate a merged `agents` block against the active preset. Never throws: a
221
+ * bad entry is left out and reported; the other entries are kept (#80).
222
+ * `undefined` in → `undefined` out, so a config without the block is unchanged.
223
+ */
224
+ export function sanitizePluginAgents(
225
+ raw: unknown,
226
+ ctx: { activePreset: string; tiers: Preset },
227
+ ): { agents: Record<string, PluginAgentConfig> | undefined; issues: PluginAgentIssue[] } {
228
+ const issues: PluginAgentIssue[] = [];
229
+ if (raw === undefined) return { agents: undefined, issues };
230
+ if (!isPlainObject(raw)) {
231
+ issues.push({ path: "agents", message: "must be an object mapping agent names to definitions; ignored" });
232
+ return { agents: undefined, issues };
233
+ }
234
+ const agents: Record<string, PluginAgentConfig> = {};
235
+ for (const [name, entry] of Object.entries(raw)) {
236
+ const checked = validatePluginAgent(name, entry, ctx);
237
+ if (checked.ok) {
238
+ agents[name] = checked.value;
239
+ issues.push(...editToolKeyNotices(name, checked.value));
240
+ } else {
241
+ issues.push({ ...checked.issue, name });
242
+ }
243
+ }
244
+ return { agents, issues };
245
+ }
246
+
247
+ /** The host edit tools whose permission the OpenCode v2 host checks as `edit`. */
248
+ const EDIT_TOOL_KEYS: readonly string[] = ["write", "patch", "multiedit", "apply_patch"];
249
+
250
+ /**
251
+ * QA-G-A2-2 (round 2, nit 2): notices (the agent is kept) for `permission` keys that name an edit tool (`write`, `patch`,
252
+ * `multiedit`, `apply_patch`, or a pattern matching one but not `edit` itself) and allow or ask for a resource the agent's
253
+ * own `edit` rules deny. On OpenCode v2 the host checks `edit` for these tools, and the router's catalog filter keeps one
254
+ * only when `edit` is not denied: such a key can only narrow (a deny of the tool's own name removes it), never grant.
255
+ */
256
+ function editToolKeyNotices(name: string, entry: PluginAgentConfig): PluginAgentIssue[] {
257
+ if (entry.permission === undefined) return [];
258
+ const rules = permissionRules(pluginAgentPolicy(entry, { context7: false, host: "v2" }).permission);
259
+ const notices: PluginAgentIssue[] = [];
260
+ for (const [key, rule] of Object.entries(entry.permission)) {
261
+ if (permissionMatches("edit", key) || !EDIT_TOOL_KEYS.some((tool) => permissionMatches(tool, key))) continue;
262
+ const grants = typeof rule === "string" ? [["*", rule] as const] : Object.entries(rule);
263
+ const dropped = grants.some(([resource, effect]) => effect !== "deny" && evaluatePermission(rules, "edit", resource) === "deny");
264
+ if (!dropped) continue;
265
+ notices.push({
266
+ name, path: `agents.${name}.permission.${key}`,
267
+ message: "on OpenCode v2 the host checks `edit` for these tools: this key can only narrow them (a deny removes the tool), "
268
+ + "`edit` decides; it allows or asks for something the agent's `edit` rules deny, so the tool is not offered there. Grant `edit` instead",
269
+ });
270
+ }
271
+ return notices;
272
+ }
273
+
274
+ /**
275
+ * The ask rules that protect sensitive paths reachable through one read grant
276
+ * of `resource`, placed right after it. Never wider than the grant itself:
277
+ * - `*`/`**`: every sensitive glob asks, the documented exceptions keep the grant's effect;
278
+ * - an exact path: asks when it is sensitive (unless it is an exception);
279
+ * - any other wildcard: the sensitive globs are denied at that position instead
280
+ * (an intersection the host's matcher can express is not computed; deny is only ever stricter).
281
+ */
282
+ function sensitiveRulesFor(resource: string, effect: PermissionEffect): Array<[string, PermissionEffect]> {
283
+ if (resource === "*" || resource === "**") {
284
+ return [
285
+ ...SENSITIVE_PERMISSION_GLOBS.map((glob): [string, PermissionEffect] => [glob, "ask"]),
286
+ ...(effect === "allow" ? SENSITIVE_PERMISSION_EXCEPTIONS.map((glob): [string, PermissionEffect] => [glob, "allow"]) : []),
287
+ ];
288
+ }
289
+ if (!/[*?]/.test(resource)) {
290
+ const sensitive = SENSITIVE_PERMISSION_GLOBS.some((glob) => permissionMatches(resource, glob))
291
+ && !SENSITIVE_PERMISSION_EXCEPTIONS.some((glob) => permissionMatches(resource, glob));
292
+ return sensitive && effect === "allow" ? [[resource, "ask"]] : [];
293
+ }
294
+ return SENSITIVE_PERMISSION_GLOBS.map((glob): [string, PermissionEffect] => [glob, "deny"]);
295
+ }
296
+
297
+ /**
298
+ * Every rule that applies to `read`, in order, with the sensitive-path rules
299
+ * interleaved right after each grant. Interleaving (rather than appending all
300
+ * asks at the end) keeps a later deny a deny: an ask placed after it would
301
+ * turn it into a prompt that `--auto` answers.
302
+ */
303
+ function readBlock(rules: readonly PermissionRule[]): Record<string, PermissionEffect> {
304
+ const block: Record<string, PermissionEffect> = {};
305
+ for (const rule of rules) {
306
+ if (!permissionMatches("read", rule.action)) continue;
307
+ putLast(block, rule.resource, rule.effect);
308
+ if (rule.effect === "deny") continue;
309
+ for (const [resource, effect] of sensitiveRulesFor(rule.resource, rule.effect)) putLast(block, resource, effect);
310
+ }
311
+ return block;
312
+ }
313
+
314
+ export interface PluginAgentPolicy {
315
+ /** Ordered permission map in the host's vocabulary (v1: `bash`/`task`). */
316
+ permission: PermissionMap;
317
+ }
318
+
319
+ /**
320
+ * The permission policy published for a plugin agent.
321
+ * - readOnly: the #77 read-only map, then `allowTools`, then the agent's own
322
+ * (deny/ask-only) rules.
323
+ * - explicit: `* deny` first, then `allowTools`, then the agent's rules; the
324
+ * `read` rules are rebuilt last with the sensitive-path asks re-applied after
325
+ * every read grant (see {@link readBlock}).
326
+ */
327
+ export function pluginAgentPolicy(
328
+ entry: Pick<PluginAgentConfig, "readOnly" | "allowTools" | "permission">,
329
+ opts: { context7: boolean; host: "v1" | "v2" },
330
+ ): PluginAgentPolicy {
331
+ const tools: PermissionMap = Object.fromEntries((entry.allowTools ?? []).map((tool) => [tool, "allow" as const]));
332
+ const own = entry.permission ?? {};
333
+ let permission: PermissionMap;
334
+ if (entry.readOnly === true) {
335
+ permission = mergePermissions(mergePermissions(readOnlyPermissions(opts.context7), tools), own);
336
+ } else {
337
+ const merged = mergePermissions(mergePermissions({ "*": "deny" }, tools), own);
338
+ const block = readBlock(permissionRules(merged));
339
+ permission = { ...merged };
340
+ delete permission.read;
341
+ permission.read = block;
342
+ }
343
+ return { permission: opts.host === "v1" ? toV1Actions(permission) : permission };
344
+ }
345
+
346
+ /** Rename the v2 actions to the v1 host's (`shell` → `bash`, `subagent` → `task`), keeping order. */
347
+ export function toV1Actions(permission: PermissionMap): PermissionMap {
348
+ const out: PermissionMap = {};
349
+ for (const [action, rule] of Object.entries(permission)) {
350
+ const name = V1_ACTIONS[action] ?? action;
351
+ const previous = out[name];
352
+ if (isPlainObject(previous) && typeof rule === "object") {
353
+ const merged = { ...previous };
354
+ for (const [pattern, effect] of Object.entries(rule)) putLast(merged, pattern, effect);
355
+ putLast<PermissionMap[string]>(out, name, merged);
356
+ } else {
357
+ putLast(out, name, rule);
358
+ }
359
+ }
360
+ return out;
361
+ }
362
+
363
+ /** Marks an `agent.<name>` definition the router built from the `agents` block. */
364
+ export const PLUGIN_AGENT = Symbol.for("opencode-model-router.plugin-agent");
365
+
366
+ export interface PluginAgentMarker {
367
+ tier: string;
368
+ readOnly: boolean;
369
+ /** v1 only: the opencode.json entry the definition was merged with, if any. */
370
+ hostEntry?: Record<string, unknown>;
371
+ }
372
+
373
+ export function pluginAgentMarker(definition: unknown): PluginAgentMarker | undefined {
374
+ if (!isPlainObject(definition)) return undefined;
375
+ const marker = (definition as Record<PropertyKey, unknown>)[PLUGIN_AGENT];
376
+ return isPlainObject(marker) ? marker as unknown as PluginAgentMarker : undefined;
377
+ }
378
+
379
+ /**
380
+ * The host `agent.<name>` definition of a plugin agent (v1 config shape; the v2
381
+ * adapter translates it). Model and variant come from the active tier; a tier
382
+ * without a variant leaves none behind.
383
+ */
384
+ export function buildPluginAgentDefinition(
385
+ entry: PluginAgentConfig,
386
+ tier: Pick<TierConfig, "model" | "variant" | "steps">,
387
+ opts: { context7: boolean; host: "v1" | "v2" },
388
+ ): Record<string, unknown> {
389
+ const policy = pluginAgentPolicy(entry, opts);
390
+ // Legacy `tools` booleans never carry `allowTools` (QA-81-5): the v1 host maps legacy `write|edit|patch`
391
+ // tools to the `edit` permission, and the permission rules already grant every allowTools entry.
392
+ const { allowTools: _granted, ...withoutGrants } = entry;
393
+ const legacy = pluginAgentPolicy(withoutGrants, opts).permission;
394
+ const steps = entry.steps ?? tier.steps;
395
+ const definition: Record<string, unknown> = {
396
+ model: tier.model,
397
+ mode: "subagent",
398
+ description: entry.description,
399
+ ...(entry.prompt === undefined ? {} : { prompt: entry.prompt }),
400
+ ...(steps === undefined ? {} : { steps, maxSteps: steps }),
401
+ ...(tier.variant ? { variant: tier.variant } : {}),
402
+ permission: policy.permission,
403
+ tools: legacyReadOnlyTools(legacy),
404
+ };
405
+ const marker: PluginAgentMarker = { tier: entry.tier, readOnly: entry.readOnly === true };
406
+ Object.defineProperty(definition, PLUGIN_AGENT, { value: marker, enumerable: false, configurable: true });
407
+ return definition;
408
+ }
409
+
410
+ /**
411
+ * v1 precedence, matching what the v2 host does on its own: an opencode.json
412
+ * `agent.<name>` entry wins for every field it sets; its permission rules are
413
+ * placed after the router's (last match wins) and its `tools` over the router's.
414
+ */
415
+ export function mergeHostAgentEntry(
416
+ definition: Record<string, unknown>,
417
+ hostEntry: Record<string, unknown>,
418
+ ): Record<string, unknown> {
419
+ const merged: Record<string, unknown> = { ...definition };
420
+ for (const [key, value] of Object.entries(hostEntry)) {
421
+ if (value === undefined) continue;
422
+ if (key === "permission" && isPlainObject(value) && isPlainObject(definition.permission)) {
423
+ merged.permission = mergePermissions(definition.permission as PermissionMap, value as PermissionMap);
424
+ } else if (key === "tools" && isPlainObject(value) && isPlainObject(definition.tools)) {
425
+ merged.tools = { ...definition.tools, ...value };
426
+ } else {
427
+ merged[key] = value;
428
+ }
429
+ }
430
+ const marker = pluginAgentMarker(definition);
431
+ if (marker) Object.defineProperty(merged, PLUGIN_AGENT, { value: { ...marker, hostEntry }, enumerable: false, configurable: true });
432
+ return merged;
433
+ }
@@ -18,6 +18,29 @@ import {
18
18
  type RouterConfig,
19
19
  type TierConfig,
20
20
  } from "./config";
21
+ import type { RoleKind } from "./roles";
22
+
23
+ /**
24
+ * Roles protocol (v2 roles mode, plan #84 T2.2.1): the intent of each role kind as the orchestrator's role menu
25
+ * shows it, one line each. Keyed by kind, never by tier or model; the menu appends the role's authority in plain
26
+ * words from its (possibly narrowed) allow list, so a narrowing in `roleAgents.<name>.deny` shows there.
27
+ */
28
+ export const ROLE_MENU_INTENT: Readonly<Record<RoleKind, string>> = Object.freeze({
29
+ explore: "lookups: files, symbols, facts, git history.",
30
+ research: "web and library docs; no local files.",
31
+ run: "runs allowlisted scripts and commands (tests, typecheck, lint, build).",
32
+ implement: "scoped code changes.",
33
+ review: "senior QA review: defects, risks, regressions.",
34
+ design: "design: options, tradeoffs, a recommendation.",
35
+ general: "small mixed tasks.",
36
+ });
37
+
38
+ /**
39
+ * Opening tag of the note the router appends to a role's result when its tool-call budget ran out (QA-P22-1-6).
40
+ * The roles protocol tells the orchestrator to resume the same session on it; the runtime (P2.1, T2.1.4) writes
41
+ * the note with this exact prefix, so the two cannot drift.
42
+ */
43
+ export const ROUTER_BUDGET_NOTE_PREFIX = "[router budget]";
21
44
 
22
45
  /**
23
46
  * Provider-neutral tool-authority clause, appended once to every tier agent's assembled prompt (see src/index.ts).
@@ -43,7 +66,9 @@ Your goal is to answer the dispatch with exactly the findings requested, reporte
43
66
 
44
67
  Treat read-only calls as a budget of 8 per dispatch — a \`CAP:N\` in the dispatch resets this number, and \`CAP:none\` removes the limit when the dispatch also carries a \`reason:\` line. The runtime appends \`[cap: N/MAX]\` to each read-only result so you can track spend, and appends \`[⚠ REDUNDANT]\` when you repeat a call; stop repeating covered ground, not working: a different region of the same file is not a repeat. A rare overrun is acceptable if you prefix one line with \`reason:\`.
45
68
 
46
- Begin your response with exactly one of \`DONE:\` (with findings), \`NEED MORE:\`, or \`ESCALATE:\`.`,
69
+ Begin your response with exactly one of \`DONE:\` (with findings), \`NEED MORE:\`, or \`ESCALATE:\`.
70
+
71
+ Direct tools (read, glob, grep, router_git_*) and the Code Mode catalog are separate; an empty Code Mode search does not mean a direct tool is missing. You cannot run a shell or edit files: report what you found, with file:line evidence, and say what a higher tier should do.`,
47
72
  medium: `You are @medium, an implementation specialist: writing and editing code, refactoring, adding tests, fixing bugs, repairing builds, creating files, configuring, and wiring APIs. You execute this dispatch yourself and do not re-delegate it.
48
73
 
49
74
  Your goal is to deliver working, verified changes that match the existing project's patterns and conventions. Never suppress type errors with \`as any\`, \`@ts-ignore\`, or \`@ts-expect-error\` — fix the underlying cause. Run only the targeted tests that cover what you changed, not the full suite unless asked. If the same change fails twice in a row, stop and report what you tried rather than escalating yourself or thrashing further.