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.
- package/CHANGELOG.md +149 -0
- package/README.md +56 -10
- package/package.json +1 -1
- package/src/commands/output.ts +21 -1
- package/src/compat/v2-hooks.ts +1322 -18
- 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/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/src/router/protocol.ts
CHANGED
|
@@ -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
|
|
@@ -374,3 +463,47 @@ export function assembleSystemPrompt(
|
|
|
374
463
|
: CLAUDE_ORCHESTRATOR_PREFIX;
|
|
375
464
|
return `${claudePrefix}\n\n---\n\n${delegationProtocol}${dodSection}`;
|
|
376
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
|
+
}
|