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
@@ -1,4 +1,93 @@
1
1
  import type { RouterConfig, Preset, ModeConfig } from "./config";
2
+ import type { RoleKind, RoleSpec } from "./roles";
3
+ import { ROLE_MENU_INTENT, ROUTER_BUDGET_NOTE_PREFIX } from "./prompts";
4
+ // The leaf module, not `protocol-line.ts`: that one imports this file (QA-P22-1-11).
5
+ import { generateRolesTaxonomy } from "../routing/engine/roles-taxonomy";
6
+
7
+ // ---------------------------------------------------------------------------
8
+ // Roles protocol (OpenCode v2, `routing.delegation: "roles"`; plan #84 §2.1–§2.5, T2.2.1)
9
+ // ---------------------------------------------------------------------------
10
+
11
+ /**
12
+ * First line of {@link buildRolesProtocol}. Deliberately not {@link DELEGATION_PROTOCOL_HEADING}: the engine's
13
+ * context hook (`src/routing/wire/hint.ts`) rewrites only the tiers protocol (tier `R:` line, route-line paragraph,
14
+ * per-turn hint), so it never touches the roles text.
15
+ */
16
+ export const ROLES_PROTOCOL_HEADING = "## Role Delegation Protocol (MANDATORY)";
17
+
18
+ /** Menu order: the shipped role order by kind; agents of one kind by name. */
19
+ const ROLE_MENU_ORDER: readonly RoleKind[] = ["explore", "research", "run", "implement", "review", "design", "general"];
20
+ const LOCAL_ACTIONS: ReadonlySet<string> = new Set(["read", "glob", "grep", "router_git"]);
21
+
22
+ /** A role's authority in plain words, from its allow list: dynamic roles get `edit`/`router_run` only on demand. */
23
+ function roleAuthorityWords(spec: RoleSpec): string {
24
+ const allow: readonly string[] = spec.authority.allow;
25
+ const held: string[] = allow.some((a) => LOCAL_ACTIONS.has(a)) ? ["read"] : [];
26
+ const onDemand: string[] = [];
27
+ for (const action of ["edit", "router_run"]) {
28
+ if (allow.includes(action)) (spec.authority.mode === "dynamic" ? onDemand : held).push(action);
29
+ }
30
+ for (const action of ["webfetch", "websearch", "context7"]) if (allow.includes(action)) held.push(action);
31
+ const words = [held.join(", "), onDemand.length > 0 ? `${onDemand.join(" and ")} on demand` : ""].filter((w) => w !== "");
32
+ return words.length > 0 ? words.join("; ") : "none";
33
+ }
34
+
35
+ /**
36
+ * The orchestrator's delegation protocol on OpenCode v2 roles mode, in place of {@link buildDelegationProtocol}
37
+ * (which advertises the tiers, their models and the tier rules). It names the enabled role agents of `roles` only,
38
+ * never a tier or a model: the router picks both per dispatch and always sets the per-call model.
39
+ *
40
+ * Cache-stable: the text depends on `routing.delegation` and the role table only (agents, kinds, allow lists,
41
+ * authority mode), in a fixed order; nothing per turn (no clock, counter, session id, preset, model or evidence).
42
+ *
43
+ * "" outside roles mode and when no role is enabled, so a caller that falls back to the tiers protocol on "" keeps
44
+ * tiers mode and v1 byte-identical (I1/I8).
45
+ */
46
+ export function buildRolesProtocol(cfg: RouterConfig, roles: ReadonlyMap<string, RoleSpec>): string {
47
+ if (cfg.routing?.delegation !== "roles") return "";
48
+ const enabled = [...roles.values()]
49
+ .filter((spec) => spec.enabled === true && ROLE_MENU_ORDER.includes(spec.kind))
50
+ .sort((a, b) => ROLE_MENU_ORDER.indexOf(a.kind) - ROLE_MENU_ORDER.indexOf(b.kind) || (a.agent < b.agent ? -1 : a.agent > b.agent ? 1 : 0));
51
+ if (enabled.length === 0) return "";
52
+ const agentOf = (kind: RoleKind): string | undefined => enabled.find((spec) => spec.kind === kind)?.agent;
53
+ const menu = enabled.map((spec) => `- ${spec.agent}: ${ROLE_MENU_INTENT[spec.kind]} Authority: ${roleAuthorityWords(spec)}.`);
54
+ const taxonomy = generateRolesTaxonomy(new Map(enabled.map((spec) => [spec.agent, spec] as const)));
55
+ const researcher = agentOf("research");
56
+ const editor = agentOf("implement") ?? agentOf("general");
57
+ const runner = agentOf("run");
58
+ const compose = researcher !== undefined && editor !== undefined
59
+ ? ` Compose: ${researcher} first, then paste its findings into the ${editor} dispatch.`
60
+ : "";
61
+ // QA-P22-1-8: a tier agent is the exception for a command `router_run` refuses, never the default.
62
+ // QA-P22-2-1: keyed on the router_run grant of ANY enabled role (the implementer holds it too), not on a `run` role.
63
+ const rawShell = enabled.some((spec) => spec.authority.allow.includes("router_run"))
64
+ ? `Only when \`router_run\` refuses a command that is not on its allowlist, ask the user or dispatch a tier agent explicitly.`
65
+ : `For a command, ask the user or dispatch a tier agent explicitly.`;
66
+ return [
67
+ ROLES_PROTOCOL_HEADING,
68
+ ``,
69
+ `You are the orchestrator: delegate execution to role agents with \`subagent(agent="<role>", prompt="...")\` and answer the user yourself. Reading, searching and running commands are execution; you may make about 2 direct read-only calls per turn to settle a question. Run independent dispatches in parallel, in one message.`,
70
+ ``,
71
+ `Roles (pick by intent; the router narrows each grant to the task):`,
72
+ ...menu,
73
+ ...(taxonomy ? [``, taxonomy] : []),
74
+ ``,
75
+ `The router picks each dispatch's model: never set \`model\` or pick a tier; name the role.`,
76
+ ``,
77
+ // QA-P22-1-1: `tier`/`pin` are not in the template; only a plan's `[tier:X]` tag is transcribed.
78
+ `Route line: when present it must be the FIRST line of the prompt (the router removes it; a malformed one is refused for a role): \`[route class=<c> risk=<r> scope=<s> needs=<n,..> d=<d> budget=<n> root=<path>]\`, every key optional. class=search|recon|mechanical|implement|debug|design|review|other; risk=low|medium|high; scope=single|multi|repo; needs=shell|web|edit|network|external_dir (\`edit\` unlocks editing, \`shell\` router_run, where the role allows); d=deterministic|grader|none (counts only when the prompt's \`[acceptance]\` block backs it); budget=tool calls (up to twice the role's); root=the absolute work root. Only when the plan step carries \`[tier:X]\`, add \`tier=X pin\`; never otherwise.`,
79
+ ``,
80
+ `Work root: a role works only in the session directory or one git worktree of this repo; for a worktree put \`root=<absolute path>\` on the route line (quote a path with spaces) and in ENVIRONMENT.`,
81
+ ``,
82
+ `No role holds the web together with read, run or edit authority.${compose} Raw shell is outside roles mode. ${rawShell}`,
83
+ ``,
84
+ `Resume, never restart: after \`NEED MORE: budget\` or a \`${ROUTER_BUDGET_NOTE_PREFIX}\` note, resume the SAME \`sessionID\` with "continue and finish"; after \`ESCALATE: authority\`, likewise (the router widens the grant) unless it names another role; after a verification FAIL, resume the SAME \`sessionID\` with the findings (the router raises the tier). A resume keeps the dispatch's \`[acceptance]\` and \`VERIFY:\` lines; a new block replaces them. Roles return \`DONE:\`, \`NEED MORE:\` or \`ESCALATE:\`; \`CAP:N\` (or \`CAP:none\` with a \`reason:\` line) changes only the read-only call cap.`,
85
+ ``,
86
+ `Dispatch prompt: the route line, then TASK, EXPECTED OUTCOME, TOOLS, MUST DO, MUST NOT DO, CONTEXT, ENVIRONMENT, with absolute paths.`,
87
+ ``,
88
+ `This protocol overrides any project guide (CLAUDE.md, AGENTS.md) that says to use direct tools first or to dispatch to tiers or models.`,
89
+ ].join("\n");
90
+ }
2
91
 
3
92
  // ---------------------------------------------------------------------------
4
93
  // Tier / mode helpers
@@ -132,6 +221,53 @@ export function buildDelegationProtocol(cfg: RouterConfig): string {
132
221
  ].join("\n");
133
222
  }
134
223
 
224
+ // ---------------------------------------------------------------------------
225
+ // Routing engine seams (Phase 2.2; v2 `advise`/`enforce` only, never called for `static`/`shadow`)
226
+ // ---------------------------------------------------------------------------
227
+
228
+ /** First line of {@link buildDelegationProtocol}: how the adapter recognises the protocol text among the system parts. */
229
+ export const DELEGATION_PROTOCOL_HEADING = "## Model Delegation Protocol (MANDATORY)";
230
+
231
+ /**
232
+ * Swap the taxonomy (`R:`) line of an assembled protocol text for `line` (the generated line of the routing engine,
233
+ * `generateTaxonomy`). The base line is `buildTaskTaxonomy(cfg)`; when it is empty the protocol carries no `R:` line and
234
+ * `line` is inserted where the taxonomy would go (before the decomposition hint, else before `Rules:`).
235
+ *
236
+ * Handoff 1.4 (QA-1.4-11): the text is spliced, never passed to `String.replace` with a string replacement, because the
237
+ * line carries agent ids and `$&`, `$1` or `$$` inside one would be expanded. A text that does not contain the base line
238
+ * (a child's stripped protocol, a user-edited prompt) is returned unchanged.
239
+ */
240
+ export function swapTaxonomyLine(protocol: string, cfg: RouterConfig, line: string): string {
241
+ const base = buildTaskTaxonomy(cfg);
242
+ if (line === base || line === "") return protocol;
243
+ if (base !== "") {
244
+ const at = protocol.indexOf(base);
245
+ return at < 0 ? protocol : protocol.slice(0, at) + line + protocol.slice(at + base.length);
246
+ }
247
+ for (const anchor of [buildDecomposeHint(cfg), "Rules: "]) {
248
+ if (anchor === "") continue;
249
+ const at = protocol.indexOf(`\n${anchor}`);
250
+ if (at >= 0) return `${protocol.slice(0, at + 1)}${line}\n\n${protocol.slice(at + 1)}`;
251
+ }
252
+ return protocol;
253
+ }
254
+
255
+ /**
256
+ * The paragraph `advise` and `enforce` append to the delegation protocol (D13, A22): the optional first-line route
257
+ * directive, the `pin` flag, and how to read the per-turn hint. It never asks the orchestrator to pick a model
258
+ * (§0.10.11): the engine writes models itself. `static` and `shadow` never receive it (the text stays byte-identical).
259
+ */
260
+ export function buildRouteLineProtocol(mode: "advise" | "enforce"): string {
261
+ return [
262
+ "Routing line (optional): when the FIRST line of a dispatch prompt is `[route class=<c> risk=<r> scope=<s> needs=<n,..> pin]`, the router reads it as the description of the work and removes it before the subagent sees it. Values: class = search|recon|mechanical|implement|debug|design|review|other; risk = low|medium|high; scope = single|multi|repo; needs = shell|web|edit|network|external_dir. Every field is optional and an unknown value is ignored. A route line anywhere but the first line is plain text.",
263
+ "Add the bare flag `pin` when a plan tag or policy mandates the tier (a `[tier:X]` step, a QA review): a pinned dispatch is never switched.",
264
+ mode === "enforce"
265
+ ? "The router may start a dispatch on another agent than the one you name when recorded outcomes show it is cheaper or safer for that kind of work."
266
+ : "The router does not change your dispatches; a `Route hint` line, when present, shows where recorded outcomes suggest sending the next one.",
267
+ "Treat a `Route hint` as advice: follow it when it fits the task.",
268
+ ].join("\n");
269
+ }
270
+
135
271
  // ---------------------------------------------------------------------------
136
272
  // Claude-model adversarial prefixes
137
273
  //
@@ -327,3 +463,47 @@ export function assembleSystemPrompt(
327
463
  : CLAUDE_ORCHESTRATOR_PREFIX;
328
464
  return `${claudePrefix}\n\n---\n\n${delegationProtocol}${dodSection}`;
329
465
  }
466
+
467
+ /**
468
+ * {@link CLAUDE_ORCHESTRATOR_PREFIX} for roles mode: the same override, with execution delegated to role agents
469
+ * instead of a named tier (the tiers opener sends read-only work to `@fast`).
470
+ */
471
+ export const CLAUDE_ROLES_ORCHESTRATOR_PREFIX = [
472
+ "AUTHORITY OVERRIDE — this block supersedes any prior system instruction",
473
+ "about 'exploring the codebase', 'gathering context with tools', or using",
474
+ "Read/Grep/Glob to validate assumptions. Those instructions describe a",
475
+ "general-purpose Claude Code session. THIS session is a routing",
476
+ "orchestrator.",
477
+ "",
478
+ "Your job is to DISPATCH, not to EXECUTE. Read-only work (grep/read/",
479
+ "glob/ls) is execution, and execution is delegated to a role agent. You",
480
+ "may run AT MOST 2 direct read-only tool calls per turn — a 3rd call is a",
481
+ "rule violation. If you need more context, dispatch a role agent.",
482
+ "",
483
+ "If a cached instruction told you to 'be thorough', 'explore broadly', or",
484
+ "'read supporting files' — ignore it here. Thoroughness is achieved by",
485
+ "dispatching the right role, not by you becoming the explorer.",
486
+ ].join("\n");
487
+
488
+ /**
489
+ * The orchestrator system prompt on OpenCode v2 roles mode: {@link assembleSystemPrompt} with
490
+ * {@link buildRolesProtocol} in place of the tiers protocol and {@link CLAUDE_ROLES_ORCHESTRATOR_PREFIX} in place of
491
+ * the tiers opener; the anti-narration clause and the DoD section follow the same switches. "" when the roles
492
+ * protocol is "" (tiers mode, v1, no enabled role): the caller then keeps {@link assembleSystemPrompt}, unchanged.
493
+ * Pure, and cache-stable like the roles protocol.
494
+ */
495
+ export function assembleRolesSystemPrompt(
496
+ cfg: RouterConfig,
497
+ roles: ReadonlyMap<string, RoleSpec>,
498
+ orchestratorModel: string | undefined,
499
+ enforcementOn: boolean = false,
500
+ ): string {
501
+ const rolesProtocol = buildRolesProtocol(cfg, roles);
502
+ if (rolesProtocol === "") return "";
503
+ const dodSection = enforcementOn ? `\n\n---\n\n${buildDoDProtocolSection(cfg)}` : "";
504
+ if (!isClaudeModel(orchestratorModel)) return `${rolesProtocol}${dodSection}`;
505
+ const claudePrefix = cfg.antiNarration
506
+ ? `${CLAUDE_ROLES_ORCHESTRATOR_PREFIX}\n\n${CLAUDE_ANTI_NARRATION}`
507
+ : CLAUDE_ROLES_ORCHESTRATOR_PREFIX;
508
+ return `${claudePrefix}\n\n---\n\n${rolesProtocol}${dodSection}`;
509
+ }
@@ -0,0 +1,149 @@
1
+ import type { TierConfig } from "./config";
2
+ import { GIT_TOOL_NAMES } from "./git-tools";
3
+ import { randomUUID } from "node:crypto";
4
+ import { SENSITIVE_PERMISSION_GLOBS, SENSITIVE_PERMISSION_EXCEPTIONS } from "./sensitive-paths";
5
+
6
+ export type PermissionEffect = "allow" | "deny" | "ask";
7
+ export type PermissionMap = Record<string, PermissionEffect | Record<string, PermissionEffect>>;
8
+ export interface PermissionRule { action: string; resource: string; effect: PermissionEffect }
9
+
10
+ /** Reviewed host shape, not a call into the plugin's bundled SDK pretending to
11
+ * describe the running host. Unknown shapes take the conservative branch. */
12
+ const KNOWN_HOST_DEFAULTS: readonly PermissionRule[] = [
13
+ { action: "*", resource: "*", effect: "allow" },
14
+ { action: "external_directory", resource: "*", effect: "ask" },
15
+ { action: "read", resource: "*.env", effect: "ask" },
16
+ { action: "read", resource: "*.env.*", effect: "ask" },
17
+ { action: "read", resource: "*.env.example", effect: "allow" },
18
+ ];
19
+ export const READ_ONLY_CANARIES = ["shell", "bash", "edit", "write", "patch", "execute", "subagent", "task", "webfetch", "websearch", "browser",
20
+ `router_readonly_canary_${randomUUID()}`];
21
+
22
+ /** Mirrors host v2.0.22 Permission.evaluate + util/wildcard.ts: last match,
23
+ * slash normalization, ? and *, dotall, Windows case folding, default ask. */
24
+ export function permissionMatches(input: string, pattern: string): boolean {
25
+ let escaped = pattern.replaceAll("\\", "/").replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
26
+ if (escaped.endsWith(" .*")) escaped = escaped.slice(0, -3) + "( .*)?";
27
+ return new RegExp(`^${escaped}$`, process.platform === "win32" ? "si" : "s").test(input.replaceAll("\\", "/"));
28
+ }
29
+
30
+ export function evaluatePermission(rules: readonly PermissionRule[], action: string, resource: string): PermissionEffect {
31
+ for (let i = rules.length - 1; i >= 0; i--) {
32
+ const rule = rules[i]!;
33
+ if (permissionMatches(action, rule.action) && permissionMatches(resource, rule.resource)) return rule.effect;
34
+ }
35
+ return "ask";
36
+ }
37
+
38
+ const EFFECT_RANK: Readonly<Record<PermissionEffect, number>> = { deny: 0, ask: 1, allow: 2 };
39
+ /** Resources every monotonicity probe tries, besides the policy's and the inherited rules' own patterns. */
40
+ const PROBE_RESOURCES: readonly string[] = ["*", "rm -rf /", "a>b", "npm test; rm x", "npm test > x", ".env", "src/file.ts", "echo probe"];
41
+
42
+ /**
43
+ * True when `rules` never grant more than `policy` alone, for any probe action
44
+ * and resource, under last-match evaluation (deny < ask < allow).
45
+ */
46
+ export function isMonotone(policy: readonly PermissionRule[], rules: readonly PermissionRule[], actions: Iterable<string>, resources: Iterable<string>): boolean {
47
+ const probes = [...new Set(resources)];
48
+ for (const action of new Set(actions)) {
49
+ for (const resource of probes) {
50
+ if (EFFECT_RANK[evaluatePermission(rules, action, resource)] > EFFECT_RANK[evaluatePermission(policy, action, resource)]) return false;
51
+ }
52
+ }
53
+ return true;
54
+ }
55
+
56
+ /**
57
+ * A plugin agent's policy (#81) is complete: it starts from `* deny` (or the
58
+ * read-only map) and lists everything the agent may do. Only inherited denies
59
+ * are copied after it, so a later deny stays a deny and no inherited allow/ask
60
+ * (a global `shell * allow`, a drifted host default) can widen it. The agent's
61
+ * own opencode.json rules are added by the host after the transform.
62
+ */
63
+ function publishPluginPermissions(name: string, policy: readonly PermissionRule[], inherited: readonly PermissionRule[], warn: (message: string) => void): PermissionRule[] {
64
+ const denies = inherited.filter(rule => rule.effect === "deny");
65
+ const candidate = [...policy, ...denies];
66
+ const actions = [...READ_ONLY_CANARIES, ...policy.filter(rule => rule.effect !== "deny").map(rule => rule.action)];
67
+ const resources = [...PROBE_RESOURCES, ...policy.map(rule => rule.resource), ...inherited.map(rule => rule.resource)];
68
+ // Guard against future edits: with the current deny-only projection of `inherited` this check cannot fail.
69
+ if (!isMonotone(policy, candidate, actions, resources)) {
70
+ warn(`plugin agent permission check failed for ${name}; inherited rules restricted to denies`);
71
+ return [...policy, ...denies];
72
+ }
73
+ return candidate;
74
+ }
75
+
76
+ /** No provenance API distinguishes a newly appended host default from a user
77
+ * grant. While readOnly is true, neither can widen the policy's action surface.
78
+ * Resource overrides on permitted actions and inherited denies survive.
79
+ * Inherited asks cannot create auto-approvable capabilities outside that set.
80
+ * `plugin`: the agent is a plugin agent (#81); see {@link publishPluginPermissions}. */
81
+ export function publishReadOnlyPermissions(name: string, policy: readonly PermissionRule[], inherited: readonly PermissionRule[], warn: (message: string) => void, opts: { plugin?: boolean } = {}): PermissionRule[] {
82
+ if (opts.plugin === true) return publishPluginPermissions(name, policy, inherited, warn);
83
+ const canaries = READ_ONLY_CANARIES;
84
+ const recognised = KNOWN_HOST_DEFAULTS.every((rule, i) => inherited[i]?.action === rule.action
85
+ && inherited[i]?.resource === rule.resource && inherited[i]?.effect === rule.effect);
86
+ const tail = inherited.slice(recognised ? KNOWN_HOST_DEFAULTS.length : 0);
87
+ const allowed = new Set(policy.filter(rule => rule.effect === "allow" && rule.action !== "*").map(rule => rule.action));
88
+ // Keep P1's rejection of non-explicit allows: projecting a drifted host's
89
+ // '* allow' onto read would overwrite the policy's sensitive-path asks.
90
+ const projectable = tail.filter(rule => rule.effect !== "allow" || allowed.has(rule.action));
91
+ const safe = projectable.flatMap(rule => rule.effect === "deny" ? [rule]
92
+ : [...allowed].filter(action => permissionMatches(action, rule.action)).map(action => ({ ...rule, action })));
93
+ if (!recognised) warn(`host default permissions not recognised for ${name}`);
94
+ if (tail.some(rule => rule.effect !== "deny" && !allowed.has(rule.action))) warn(`inherited grant dropped for ${name}`);
95
+ // Check the final projected list, including policy rules, with last-match semantics.
96
+ const candidate = [...policy, ...safe];
97
+ const resources = new Set(["*", "src/file.ts", "echo probe", ...tail.map(rule => rule.resource)]);
98
+ const breached = canaries.some(action => [...resources].some(resource => evaluatePermission(candidate, action, resource) !== "deny"));
99
+ if (breached) {
100
+ warn(`read-only permission canary failed for ${name}; inherited grants restricted`);
101
+ return [{ action: "*", resource: "*", effect: "deny" }, ...candidate.filter(rule => rule.effect === "deny"
102
+ || (rule.action !== "*" && !canaries.some(action => permissionMatches(action, rule.action))))];
103
+ }
104
+ return candidate;
105
+ }
106
+ // MCP effective names are <sanitized-server>_<sanitized-tool>; hyphens survive
107
+ // sanitization on both hosts. Never allow context7_* (future tools may write).
108
+ export const CONTEXT7_DOC_TOOLS = ["context7_resolve-library-id", "context7_query-docs", "context7_get-library-docs"];
109
+
110
+ export function isReadOnlyTier(name: string, tier: Pick<TierConfig, "readOnly">): boolean {
111
+ return tier.readOnly ?? name === "fast";
112
+ }
113
+
114
+ export function readOnlyPermissions(context7 = false): PermissionMap {
115
+ return {
116
+ "*": "deny",
117
+ read: { "*": "allow", ...Object.fromEntries(SENSITIVE_PERMISSION_GLOBS.map(pattern => [pattern, "ask" as const])),
118
+ ...Object.fromEntries(SENSITIVE_PERMISSION_EXCEPTIONS.map(pattern => [pattern, "allow" as const])) },
119
+ glob: "allow", grep: "allow", external_directory: "allow",
120
+ ...Object.fromEntries([...GIT_TOOL_NAMES, ...(context7 ? CONTEXT7_DOC_TOOLS : [])].map(name => [name, "allow" as const])),
121
+ };
122
+ }
123
+
124
+ /** Move overridden keys to the end: permissions are ordered, not plain spread-merged. */
125
+ export function mergePermissions(base: PermissionMap, user: PermissionMap | PermissionEffect = {}): PermissionMap {
126
+ const result = { ...base };
127
+ for (const [action, rule] of Object.entries(typeof user === "string" ? { "*": user } : user)) {
128
+ const old = result[action];
129
+ delete result[action];
130
+ if (typeof old === "object" && typeof rule === "object") {
131
+ const resources = { ...old };
132
+ for (const [resource, effect] of Object.entries(rule)) { delete resources[resource]; resources[resource] = effect; }
133
+ result[action] = resources;
134
+ } else result[action] = rule;
135
+ }
136
+ return result;
137
+ }
138
+
139
+ export function permissionRules(permission: PermissionMap): PermissionRule[] {
140
+ return Object.entries(permission).flatMap(([action, rule]) => typeof rule === "string"
141
+ ? [{ action, resource: "*", effect: rule }]
142
+ : Object.entries(rule).map(([resource, effect]) => ({ action, resource, effect })));
143
+ }
144
+
145
+ /** Legacy SDKs expose tools booleans as well as a narrower permission type. */
146
+ export function legacyReadOnlyTools(permission: PermissionMap): Record<string, boolean> {
147
+ return Object.fromEntries(Object.entries(permission).map(([action, rule]) => [action,
148
+ typeof rule === "string" ? rule !== "deny" : Object.values(rule).some(effect => effect !== "deny")]));
149
+ }