diff --git a/README.md b/README.md index 333dd99..7757783 100644 --- a/README.md +++ b/README.md @@ -338,23 +338,83 @@ The [`dynamic-workflows` skill](packages/plugin/skill/dynamic-workflows/SKILL.md | `model` | The launching session's model as `"provider/model#variant"`, or `null` for a headless/synthetic caller. What `agent(…, { model: "inherit" })` and a bare `effort` inherit. | | `$`, `file`, `fetch` | Shell, files and HTTP, confined to the project and recorded in the Run's activity. | | `workflow(name, args?)` | Run a saved Workflow as one step of this Run (one level deep). | -| `worktrees()` | The git worktrees kept by `isolation: "worktree"` Units that changed files. | +| `worktrees()` | The git worktrees kept by `worktree: true` Units that changed files. | `agent()` options: `schema`, `label`, `phase`, `subagent` (alias `agentType`; default `general`), `model` (`"provider/model#variant"`, `{ providerID, modelID }`, or `"inherit"` for the launching session's model), `effort` (the reasoning variant; with no `model` the Unit inherits the caller's model at that effort), `retries` (repair turns, -default 2), `timeoutMs`, `permissions`, `isolation: "worktree"` (a fresh git worktree, removed if unchanged), +default 2), `timeoutMs`, `permissions`, `worktree: true` (a fresh git worktree, removed if unchanged), +`isolation` (narrow THIS Unit's policy below `meta.isolation`; see [Isolating a Run](#isolating-a-run)), `location` (another directory) and `session` (continue an existing session — see [Continuing a Unit](#continuing-a-unit)). `{ receipts: true }` and `{ keepSession: true }` are separate flags rather than options — see [Asserting what a Unit did](#asserting-what-a-unit-did) and [Continuing a Unit](#continuing-a-unit). `meta`: `name`, `description`, `whenToUse`, `phases`, `args` (zod), `concurrency`, `unitTimeout`, `budget` (a number, -or `{ tokens, hard: true }` to stop at the limit), `permissions` (rules for every Unit), `limits`, and -`interaction: { permissions: "ask" | "auto" | "deny", graceMs }`. +or `{ tokens, hard: true }` to stop at the limit), `permissions` (rules for every Unit), `isolation` (skills, +subagents, and MCP servers every Unit may use — deny-by-default; see [Isolating a Run](#isolating-a-run)), `limits`, +and `interaction: { permissions: "ask" | "auto" | "deny", graceMs }`. Default to `pipeline`. Use `parallel` as a barrier only when a stage needs every result of the previous one, such as deduplicating findings across all files before verifying them. +### Isolating a Run + +By default a Unit sees every skill, subagent, and MCP server the surrounding OpenCode config exposes. To bound that, +declare `meta.isolation` — a **deny-by-default allow-list** (a name not listed cannot be used by any Unit of the Run): + +```ts +export default defineWorkflow({ + meta: { + name: "audit", + description: "Read-only audit", + isolation: { skills: ["code-markup"], subagents: ["explore"], mcp: ["playwright"] }, + }, + async run({ agent }) { + await agent("audit the repo", { subagent: "explore" }) + }, +}) +``` + +Each axis is independent: omit a field to leave that axis unrestricted; `[]` allows nothing. A Workflow that names a +subagent outside `isolation.subagents` fails that Unit **before a session is created**, with a clear message. + +**Narrow-only at every level.** Three sources are intersected, so no level can widen another: + +| Level | Where | Role | +| --- | --- | --- | +| Workflow | `meta.isolation` | the author's contract | +| Unit | `agent(prompt, { isolation })` | this one Unit tightens further | +| Caller | `workflow({ isolation })` | ad-hoc bound for the caller | + +A Workflow can keep its policy in `workflows.json` and import it — the plugin reads no files of its own, an ordinary +JSON import is inlined by the bundler: + +```ts +import manifest from "./workflows.json" + +export default defineWorkflow({ + meta: { name: "audit", description: "…", isolation: manifest.workflows.audit.isolation }, + async run({ agent }) { /* … */ }, +}) +``` + +Because every level is intersected, an imported policy is a floor: `meta.isolation` (when also set) and a Unit's +a Unit `isolation` can tighten it, never loosen it. + +A Unit tightens with its own `isolation`: + +```ts +await agent("review only", { subagent: "explore", isolation: { mcp: [] } }) +``` + +For a region of the script where many Units share a tighter policy, `withIsolation(ctx, policy)` returns a view whose +`agent` carries the narrower policy — sugar over the Unit `isolation`. It is **not** a security boundary: `parallel`/`pipeline` +thunks close over whatever `ctx` is in scope, so a thunk that calls the original `ctx.agent` bypasses the view. Use +the Unit `isolation` option when a Unit must be provably narrowed. + +MCP is enforced by hiding the disallowed servers' tools from the Unit's toolset and denying them by name as a second +layer — a server not listed is not just refused, it is not shown to the model. + ### Typed results A Unit with a `schema` gets a `workflow_result` tool whose input is your schema. The tool validates each call, so the diff --git a/docs/development.md b/docs/development.md index b973c3b..6b88af3 100644 --- a/docs/development.md +++ b/docs/development.md @@ -55,7 +55,7 @@ Point a test project at the package directory (OpenCode resolves a directory plu build whose desktop app hosts `./gui-experimental` bundles; it loads beside the TUI, not instead of it. - **Web app changes**: `bun run --cwd packages/web dev` serves it with hot reload and forwards `/v1` to `WF_GATEWAY` (default `http://127.0.0.1:4320`). -- **Worktree Units** (`isolation: "worktree"`) only work when the plugin is configured in a committed +- **Worktree Units** (`worktree: true`) only work when the plugin is configured in a committed `opencode.json` (or globally): worktrees check out the committed tree. - **Do not load the checkout where the published package is installed.** A checkout (plugin id = its path) and the npm package (id `@syn7xx/opencode-dynamic-workflows`) are two plugins to OpenCode: both load, both register diff --git a/packages/plugin/README.md b/packages/plugin/README.md index 6771575..559caba 100644 --- a/packages/plugin/README.md +++ b/packages/plugin/README.md @@ -340,23 +340,83 @@ The [`dynamic-workflows` skill](https://github.com/syn7xx/opencode-dynamic-workf | `model` | The launching session's model as `"provider/model#variant"`, or `null` for a headless/synthetic caller. What `agent(…, { model: "inherit" })` and a bare `effort` inherit. | | `$`, `file`, `fetch` | Shell, files and HTTP, confined to the project and recorded in the Run's activity. | | `workflow(name, args?)` | Run a saved Workflow as one step of this Run (one level deep). | -| `worktrees()` | The git worktrees kept by `isolation: "worktree"` Units that changed files. | +| `worktrees()` | The git worktrees kept by `worktree: true` Units that changed files. | `agent()` options: `schema`, `label`, `phase`, `subagent` (alias `agentType`; default `general`), `model` (`"provider/model#variant"`, `{ providerID, modelID }`, or `"inherit"` for the launching session's model), `effort` (the reasoning variant; with no `model` the Unit inherits the caller's model at that effort), `retries` (repair turns, -default 2), `timeoutMs`, `permissions`, `isolation: "worktree"` (a fresh git worktree, removed if unchanged), +default 2), `timeoutMs`, `permissions`, `worktree: true` (a fresh git worktree, removed if unchanged), +`isolation` (narrow THIS Unit's policy below `meta.isolation`; see [Isolating a Run](#isolating-a-run)), `location` (another directory) and `session` (continue an existing session — see [Continuing a Unit](#continuing-a-unit)). `{ receipts: true }` and `{ keepSession: true }` are separate flags rather than options — see [Asserting what a Unit did](#asserting-what-a-unit-did) and [Continuing a Unit](#continuing-a-unit). `meta`: `name`, `description`, `whenToUse`, `phases`, `args` (zod), `concurrency`, `unitTimeout`, `budget` (a number, -or `{ tokens, hard: true }` to stop at the limit), `permissions` (rules for every Unit), `limits`, and -`interaction: { permissions: "ask" | "auto" | "deny", graceMs }`. +or `{ tokens, hard: true }` to stop at the limit), `permissions` (rules for every Unit), `isolation` (skills, +subagents, and MCP servers every Unit may use — deny-by-default; see [Isolating a Run](#isolating-a-run)), `limits`, +and `interaction: { permissions: "ask" | "auto" | "deny", graceMs }`. Default to `pipeline`. Use `parallel` as a barrier only when a stage needs every result of the previous one, such as deduplicating findings across all files before verifying them. +### Isolating a Run + +By default a Unit sees every skill, subagent, and MCP server the surrounding OpenCode config exposes. To bound that, +declare `meta.isolation` — a **deny-by-default allow-list** (a name not listed cannot be used by any Unit of the Run): + +```ts +export default defineWorkflow({ + meta: { + name: "audit", + description: "Read-only audit", + isolation: { skills: ["code-markup"], subagents: ["explore"], mcp: ["playwright"] }, + }, + async run({ agent }) { + await agent("audit the repo", { subagent: "explore" }) + }, +}) +``` + +Each axis is independent: omit a field to leave that axis unrestricted; `[]` allows nothing. A Workflow that names a +subagent outside `isolation.subagents` fails that Unit **before a session is created**, with a clear message. + +**Narrow-only at every level.** Three sources are intersected, so no level can widen another: + +| Level | Where | Role | +| --- | --- | --- | +| Workflow | `meta.isolation` | the author's contract | +| Unit | `agent(prompt, { isolation })` | this one Unit tightens further | +| Caller | `workflow({ isolation })` | ad-hoc bound for the caller | + +A Workflow can keep its policy in `workflows.json` and import it — the plugin reads no files of its own, an ordinary +JSON import is inlined by the bundler: + +```ts +import manifest from "./workflows.json" + +export default defineWorkflow({ + meta: { name: "audit", description: "…", isolation: manifest.workflows.audit.isolation }, + async run({ agent }) { /* … */ }, +}) +``` + +Because every level is intersected, an imported policy is a floor: `meta.isolation` (when also set) and a Unit's +a Unit `isolation` can tighten it, never loosen it. + +A Unit tightens with its own `isolation`: + +```ts +await agent("review only", { subagent: "explore", isolation: { mcp: [] } }) +``` + +For a region of the script where many Units share a tighter policy, `withIsolation(ctx, policy)` returns a view whose +`agent` carries the narrower policy — sugar over the Unit `isolation`. It is **not** a security boundary: `parallel`/`pipeline` +thunks close over whatever `ctx` is in scope, so a thunk that calls the original `ctx.agent` bypasses the view. Use +the Unit `isolation` option when a Unit must be provably narrowed. + +MCP is enforced by hiding the disallowed servers' tools from the Unit's toolset and denying them by name as a second +layer — a server not listed is not just refused, it is not shown to the model. + ### Typed results A Unit with a `schema` gets a `workflow_result` tool whose input is your schema. The tool validates each call, so the diff --git a/packages/plugin/skill/dynamic-workflows/SKILL.md b/packages/plugin/skill/dynamic-workflows/SKILL.md index e7de33f..64a649c 100644 --- a/packages/plugin/skill/dynamic-workflows/SKILL.md +++ b/packages/plugin/skill/dynamic-workflows/SKILL.md @@ -68,7 +68,7 @@ export default defineWorkflow({ | `model` | The launching session's model (`"provider/model#variant"`), or `null` for a headless/synthetic caller. What `agent(…, { model: "inherit" })` and a bare `effort` inherit. | | `$`, `file`, `fetch` | Shell, files and HTTP, confined to the project (see below). | | `workflow(name, args?)` | Run a **saved** Workflow as one step of this Run and get its result (see below). | -| `worktrees()` | The worktrees kept by `isolation: "worktree"` Units that changed files. | +| `worktrees()` | The worktrees kept by `worktree: true` Units that changed files. | ### `agent()` options @@ -84,6 +84,7 @@ export default defineWorkflow({ | `timeoutMs` | A deadline for this Unit. There is none by default. | | `permissions` | Rules for this Unit's session, e.g. `[{ action: "edit", resource: "*", effect: "deny" }]`. | | `isolation` | `"worktree"`: run the Unit in a fresh git worktree — for Units that **edit files in parallel** (see below). | +| `isolation` | Narrow THIS Unit's access below the Workflow (`{ skills?, subagents?, mcp? }`). Intersected, never replaces: a Unit can tighten, never widen. Use when one Unit legitimately needs fewer skills/subagents/MCP servers than the rest. | | `location` | Run the Unit in a directory you prepared yourself. | | `session` | Send this turn into an existing session (`handle.sessionID`) — a follow-up, not a new Unit session. Refuses `subagent`, `model`, `effort`, `location`, `isolation`, `permissions`. | @@ -262,7 +263,7 @@ Parallel Units editing the same checkout overwrite each other. Give each its own ```ts const results = await pipeline(modules, (m) => - agent(`Migrate ${m} to the new API. Commit your change with a clear message.`, { label: m, isolation: "worktree" }), + agent(`Migrate ${m} to the new API. Commit your change with a clear message.`, { label: m, worktree: true }), ) for (const tree of worktrees()) log(`review and merge: ${tree.branch} (${tree.directory})`) ``` @@ -272,6 +273,76 @@ script (or the person) can merge it — e.g. a final Unit, or `$\`git merge ${br and disk: use them only for Units that write. The plugin must be active in the worktree, so it has to be configured in a committed `opencode.json` (or globally); otherwise those Units fail with a clear message. +## Isolating what a Unit may use + +A Unit sees whatever skills, subagents, and MCP servers the surrounding OpenCode config exposes. When a Workflow must +run predictably — regardless of what else is installed locally — declare `meta.isolation`: a **deny-by-default +allow-list** on three independent axes. A name not listed cannot be used by any Unit of the Run. + +```ts +import { defineWorkflow } from "@syn7xx/opencode-dynamic-workflows/workflow" + +export default defineWorkflow({ + meta: { + name: "audit", + description: "Read-only audit that cannot touch the delivery toolchain", + isolation: { skills: ["code-markup"], subagents: ["explore"], mcp: ["playwright"] }, + }, + async run({ agent }) { + await agent("audit the repo", { subagent: "explore" }) + }, +}) +``` + +- Each axis is independent: **omit** a field to leave that axis unrestricted; `[]` allows nothing on it. +- A Unit naming a subagent outside `isolation.subagents` fails **before a session is created**, with a clear message — + a misconfiguration surfaces immediately, not as a denied tool mid-turn. +- MCP is enforced twice: the disallowed servers' tools are **hidden** from the Unit's toolset (the model never sees + them) and, as a second layer, denied by name if the model invents one. + +**Narrow-only, three levels.** Every level is intersected (`meta ∩ unit ∩ caller`), so nothing can widen +anything else: + +| Level | Where | When to use | +| -------- | ------------------------------------------------------------ | ---------------------------------------------------------------------------- | +| Imported | `import manifest from "./workflows.json"` → `meta.isolation` | the policy lives in a JSON file you import; the plugin reads no files itself | +| Workflow | `meta.isolation` | the default for the whole Run — declare it here | +| Unit | `agent(prompt, { isolation })` | one Unit legitimately needs fewer skills/subagents/MCP than the rest | +| Caller | `workflow({ isolation })` | an ad-hoc bound for a Workflow that declares nothing | + +A policy kept in a JSON file (e.g. `workflows/workflows.json`) is imported, not read by the plugin: + +```ts +// workflows/audit.ts — the policy is inlined from the imported JSON by the bundler +import manifest from "./workflows.json" +// meta: { …, isolation: manifest.workflows.audit.isolation } +``` + +Tighten a single Unit when it needs a smaller surface than the Workflow: + +```ts +await agent("review only", { subagent: "explore", isolation: { mcp: [] } }) +``` + +`withIsolation(ctx, policy)` returns a view whose `agent` carries the narrower policy — sugar over the Unit `isolation` for a region +where many Units share a tighter policy: + +```ts +import { withIsolation } from "@syn7xx/opencode-dynamic-workflows/workflow" + +async run(ctx) { + const viewing = withIsolation(ctx, { mcp: ["playwright"] }) + await viewing.agent("look, don't touch") +} +``` + +It is **not a security boundary**: `parallel`/`pipeline` thunks close over whatever `ctx` is in scope, so a thunk +that calls the original `ctx.agent` bypasses the view. Use the Unit `isolation` option when a Unit must be provably narrowed. + +Guidance: put the Run-wide bound in `meta.isolation` (one place, easy to review); reach for the Unit `isolation` only when a +Unit genuinely differs. Do not use permissions for isolation — a `permissions` rule can `allow` but cannot narrow +what `meta.isolation` already permits. + ## pipeline by default Default to `pipeline`. Use a barrier only when a stage needs cross-item context from _all_ results of the previous diff --git a/packages/plugin/src/context.ts b/packages/plugin/src/context.ts index 6930095..b237c37 100644 --- a/packages/plugin/src/context.ts +++ b/packages/plugin/src/context.ts @@ -7,6 +7,7 @@ import { type HostModelRef, type HostPermissionRule, } from "./host" +import { intersectIsolation, mcpServersToHide, subagentAllowed } from "./isolation" import { emptyUsage, type Unit, type Usage } from "./protocol" import { DEFAULT_SUBAGENT, runUnit, stringifyError, type TurnSlice, type UnitRunResult } from "./runner" import { toUnitOutput } from "./runs" @@ -29,6 +30,7 @@ import type { AskOptions, AskQuestion, ContinuationOpts, + IsolationPolicy, UnitHandle, UnitReceipt, UnitToolCall, @@ -57,7 +59,7 @@ export interface EngineState { usage: Usage /** Units started and not yet settled — including ones the script never awaited. */ inflight: Set> - /** Worktrees kept by `isolation: "worktree"` Units that changed something. */ + /** Worktrees kept by `worktree: true` Units that changed something. */ worktrees: Array<{ unit: string; directory: string; branch: string | null }> /** * Sessions this Run may continue (`agent(…, { keepSession })`), with what the session decided at create time and @@ -219,6 +221,10 @@ export interface CreateContextInput { permissionPolicy?: UnitBinding["permissionPolicy"] /** Workflow-level rules applied to every Unit session. */ permissions?: HostPermissionRule[] + /** Isolation from ambient skills/subagents; its rules are appended LAST (after engine rules) in the runner. */ + isolation?: IsolationPolicy + /** Every MCP server name the process knows — needed to resolve `_` for `meta.isolation.mcp`. */ + mcpServers?: string[] limits?: Partial /** A limit was hit: the orchestrator stops the Run with this message. */ onLimit?: (message: string) => void @@ -286,6 +292,7 @@ function continuationError(opts: AgentOpts): string | null { ["model", opts.model], ["effort", opts.effort], ["location", opts.location], + ["worktree", opts.worktree], ["isolation", opts.isolation], ["permissions", opts.permissions], ] @@ -443,6 +450,24 @@ export function createWorkflowContext(input: CreateContextInput): Workflow state.errors.push({ unit: label ?? subagent, prompt, subagent, error: message }) return outcome(null) } + // Effective isolation for THIS Unit: the Workflow's policy intersected with the Unit's own `restrict` (narrow-only + // — a Unit can tighten, never widen). A continuation keeps its session's ruleset, so `restrict` is refused there + // (see the continuation check below) and only the Workflow policy applies. + const unitIsolation = continuing ? input.isolation : intersectIsolation(input.isolation, opts.isolation) + // MCP servers this Unit must not see, from the effective policy and the process's server list. + const hiddenMcpServers = mcpServersToHide(unitIsolation, input.mcpServers ?? []) ?? [] + // Isolation: a Unit may only run on a subagent the effective allow-list permits. Checked before any session + // exists, so a misconfigured Workflow fails fast with a clear message rather than being denied mid-turn. + // `undefined` isolation or `undefined subagents` means unrestricted. + if (!subagentAllowed(unitIsolation, subagent)) { + const allowed = unitIsolation?.subagents ?? [] + const message = + `agent(): subagent ${JSON.stringify(subagent)} is not in the isolation allow-list ` + + `[${allowed.map((name) => JSON.stringify(name)).join(", ")}]. Add it to meta.isolation.subagents, this ` + + `Unit's \`restrict\`, or choose one of the allowed subagents.` + state.errors.push({ unit: label ?? subagent, prompt, subagent, error: message }) + return outcome(null) + } const unit = newUnit({ runId: input.runId, unitId, @@ -564,8 +589,8 @@ export function createWorkflowContext(input: CreateContextInput): Workflow let current: Unit = { ...unit, status: "running", startedAt: Date.now() } emit(current) let worktree: { directory: string; branch: string | null; base: string | null } | null = null - if (opts.isolation === "worktree" && !opts.location) { - if (!input.host.worktree) throw new UnitSetupError('isolation: "worktree" is not available on this host') + if (opts.worktree === true && !opts.location) { + if (!input.host.worktree) throw new UnitSetupError("worktree: true is not available on this host") try { worktree = await input.host.worktree.create(`wf-${input.runId.slice(0, 8)}-${ordinal}`) } catch (error) { @@ -602,6 +627,9 @@ export function createWorkflowContext(input: CreateContextInput): Workflow ...(input.slot ? { slot: input.slot } : {}), maxSteps: limits.maxUnitSteps, permissions: [...(input.permissions ?? []), ...(opts.permissions ?? [])], + isolation: unitIsolation, + ...(input.mcpServers ? { knownMcpServers: input.mcpServers } : {}), + ...(hiddenMcpServers.length > 0 ? { hiddenMcpServers } : {}), ask: noAgentQuestions, permissionPolicy: input.permissionPolicy ?? (() => "deny"), onSession: (id, stop, resolved, sessionDirectory) => { diff --git a/packages/plugin/src/host.ts b/packages/plugin/src/host.ts index 80ce824..bcbeb9d 100644 --- a/packages/plugin/src/host.ts +++ b/packages/plugin/src/host.ts @@ -75,7 +75,7 @@ export interface HostSessionApi { get(input: { sessionID: string }): Promise } -/** Git worktrees for `agent({ isolation: "worktree" })` (OpenCode's own worktree service). */ +/** Git worktrees for `agent({ worktree: true })` (OpenCode's own worktree service). */ export interface HostWorktreeApi { /** Create a worktree of the Run's project; `base` is the commit it starts from. */ create(name: string): Promise<{ directory: string; branch: string | null; base: string | null }> diff --git a/packages/plugin/src/host/description.ts b/packages/plugin/src/host/description.ts index 8d8e084..2c4effb 100644 --- a/packages/plugin/src/host/description.ts +++ b/packages/plugin/src/host/description.ts @@ -22,7 +22,7 @@ concurrency?, budget?, permissions?, limits? }. run(ctx) returns the result. ctx session's model, or null for a headless caller — what { model: "inherit" } and a bare { effort } inherit) - ask(question, { fallback }) — ask the person; the fallback answers when nobody is watching. - $\\\`cmd \\\${value}\\\` / file.read|write / fetch — shell, files, HTTP confined to the project. - - workflow(name, args) — run a saved Workflow as one step · agent(…, { isolation: "worktree" }) for Units that edit + - workflow(name, args) — run a saved Workflow as one step · agent(…, { worktree: true }) for Units that edit files in parallel; worktrees() lists the ones kept.` const EXAMPLE = `Example — review each file, verify each finding as soon as its review is done: @@ -55,6 +55,10 @@ MODES (pick one): - save_run: "" — keep an inline Run's script as a saved Workflow. To run a script you write yourself, use \`workflow_inline\`. Pass args as JSON values, not JSON strings. +ISOLATION (optional, per Run): pass \`isolation: { skills?: string[], subagents?: string[], mcp?: string[] }\` to +restrict this Run's Units to an allow-list — every other skill/subagent/MCP server is denied (deny-by-default; [] +allows nothing). A Workflow that declares \`meta.isolation\` keeps it: a caller can neither widen nor narrow it. + ${SKILL_POINTER} ${CONTEXT_REFERENCE} diff --git a/packages/plugin/src/host/plugin.ts b/packages/plugin/src/host/plugin.ts index ae4b226..c764464 100644 --- a/packages/plugin/src/host/plugin.ts +++ b/packages/plugin/src/host/plugin.ts @@ -28,6 +28,7 @@ import { confine } from "../capabilities" import { configureLimits, engineGlobal, locationSlot } from "../engine-global" import { ensureGateway, type GatewayHandle } from "../gateway/server" import type { EngineHost, HostSessionInfo } from "../host" +import { isHiddenMcpTool } from "../isolation" import { createJournal, journalRoot, subscribeJournal } from "../journal" import { InvalidArgsError } from "../orchestrator" import { WorkflowProtocolError, type InteractionQuestion, type ProtocolEvent } from "../protocol" @@ -38,6 +39,7 @@ import { parseConfig, type PluginConfig } from "../service/config" import { locateServiceForRun } from "../service/locate" import { WorkflowRpc } from "../service/rpc" import { WorkflowService, argsSchemaOf } from "../service/service" +import type { IsolationPolicy } from "../workflow" import { RESULT_TOOL_DESCRIPTION, WORKFLOW_COMMAND_TEMPLATE, @@ -51,6 +53,24 @@ export const PLUGIN_ID = "opencode-dynamic-workflows" type ToolResult = { content: string; metadata?: Record } +/** + * The `isolation` argument shared by `workflow` and `workflow_inline`: a deny-by-default allow-list for skills, + * subagents, and MCP servers. Applies only when the Workflow declares no `meta.isolation` (an author's policy is + * never overridden). Omit a field to leave that axis unrestricted; `[]` allows nothing. + */ +const ISOLATION_INPUT_SCHEMA = { + type: "object", + description: + "Restrict this Run's Units to skill/subagent/MCP allow-lists (deny-by-default). Ignored when the Workflow " + + "declares meta.isolation. Omit a field to leave that axis unrestricted; [] allows nothing.", + additionalProperties: false, + properties: { + skills: { type: "array", items: { type: "string" }, description: "Skill IDs (path-derived)." }, + subagents: { type: "array", items: { type: "string" }, description: "Subagent IDs." }, + mcp: { type: "array", items: { type: "string" }, description: "MCP server names." }, + }, +} as const + function canonical(directory: string): string { try { return realpathSync(directory) @@ -135,6 +155,26 @@ export function toQuestions(input: QuestionToolInput): InteractionQuestion[] { })) } +/** + * Normalizes a tool's `isolation` input into a policy, or `undefined` when absent/malformed. Unknown shapes are + * ignored (the Run then follows `meta.isolation` or runs unrestricted) rather than failing the call. + */ +function toIsolation(input: unknown): IsolationPolicy | undefined { + if (typeof input !== "object" || input === null || Array.isArray(input)) return undefined + const record = input as { skills?: unknown; subagents?: unknown; mcp?: unknown } + const list = (value: unknown): string[] | undefined => + Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : undefined + const skills = list(record.skills) + const subagents = list(record.subagents) + const mcp = list(record.mcp) + if (skills === undefined && subagents === undefined && mcp === undefined) return undefined + return { + ...(skills !== undefined ? { skills } : {}), + ...(subagents !== undefined ? { subagents } : {}), + ...(mcp !== undefined ? { mcp } : {}), + } +} + function protocolErrorText(error: unknown, schema?: Record | null): string { if (error instanceof InvalidArgsError) return `${error.message}${schema ? `\nExpected args JSON Schema: ${JSON.stringify(schema)}` : ""}` @@ -206,6 +246,15 @@ function ensureService( }, gatewayUrl: () => (engineGlobal().singletons.get("gateway") as GatewayHandle | undefined)?.url ?? null, gatewayWeb: () => (engineGlobal().singletons.get("gateway") as GatewayHandle | undefined)?.web ?? false, + mcpServers: async () => { + try { + const listed = await ctx.mcp.list() + const data = (listed as { data?: Array<{ name?: unknown }> }).data ?? [] + return data.map((server) => server.name).filter((name): name is string => typeof name === "string") + } catch { + return [] + } + }, }) holder.gatewayAttached = () => (engineGlobal().singletons.get("gateway") as GatewayHandle | undefined)?.attached(location) ?? false @@ -359,6 +408,7 @@ export async function setup(ctx: Context): Promise<() => Promise> { const name = input.name const listing = await service.listWorkflows() const schema = listing.workflows.find((entry) => entry.key === name)?.args ?? null + const isolation = toIsolation(input.isolation) return runForeground( () => service.startRun( @@ -366,6 +416,7 @@ export async function setup(ctx: Context): Promise<() => Promise> { { background: input.background === true, ...(input.background === true ? {} : { signal: tc.signal }), + ...(isolation ? { isolation } : {}), surface: "the workflow tool", }, ), @@ -421,6 +472,7 @@ export async function setup(ctx: Context): Promise<() => Promise> { { background: input.background === true, ...(input.background === true ? {} : { signal: tc.signal }), + ...(toIsolation(input.isolation) ? { isolation: toIsolation(input.isolation) } : {}), surface: "workflow_inline", }, ), @@ -446,6 +498,7 @@ export async function setup(ctx: Context): Promise<() => Promise> { resume: { type: "string", description: "runId: resume an interrupted or failed Run." }, resumeFromRunId: { type: "string", description: "Alias of `resume`." }, save_run: { type: "string", description: "runId: save an inline Run's script as a durable Workflow." }, + isolation: ISOLATION_INPUT_SCHEMA, }, additionalProperties: false, }, @@ -469,6 +522,7 @@ export async function setup(ctx: Context): Promise<() => Promise> { type: "string", description: "Save the source as .opencode/workflows/.ts instead of running it.", }, + isolation: ISOLATION_INPUT_SCHEMA, }, additionalProperties: false, }, @@ -577,6 +631,14 @@ export async function setup(ctx: Context): Promise<() => Promise> { } // A Unit must ask through the broker, never through a native form nobody may be able to answer. delete event.tools.question + // MCP isolation: hide the tools of servers `meta.isolation.mcp` excludes. This is the reliable half — the model + // never sees the tool. `permission evaluate` denies them by name as a second layer. + if (binding.hiddenMcpServers && binding.hiddenMcpServers.length > 0) { + const known = binding.knownMcpServers ?? [] + for (const tool of Object.keys(event.tools)) { + if (isHiddenMcpTool(tool, binding.hiddenMcpServers, known)) delete event.tools[tool] + } + } binding.steps += 1 if (binding.steps > binding.maxSteps) binding.onStepLimit() event.system.push({ type: "text", text: QUESTION_INSTRUCTION } as never) @@ -593,7 +655,19 @@ export async function setup(ctx: Context): Promise<() => Promise> { await ctx.permission.hook("evaluate", (event) => { const binding = units.get(event.sessionID) - if (!binding || event.effect !== "ask") return + if (!binding) return + // MCP isolation second layer: deny a tool of an excluded server even if the model names it directly. Applies to + // every decision (not only `ask`: a saved approval or a permissive rule must not let it through). + if (binding.hiddenMcpServers && binding.hiddenMcpServers.length > 0) { + const known = binding.knownMcpServers ?? [] + const toolName = `${event.action}` + if (isHiddenMcpTool(toolName, binding.hiddenMcpServers, known)) { + event.effect = "deny" + event.message = `Workflow isolation denies the MCP tool "${toolName}". Continue without it, or report that you need it.` + return + } + } + if (event.effect !== "ask") return const policy = binding.permissionPolicy() if (policy === "auto") { event.effect = "allow" diff --git a/packages/plugin/src/isolation.ts b/packages/plugin/src/isolation.ts new file mode 100644 index 0000000..4c4e220 --- /dev/null +++ b/packages/plugin/src/isolation.ts @@ -0,0 +1,126 @@ +/** + * Isolation rules for a Workflow's Units — the deny-by-default subset of `meta.isolation`. + * + * Why a separate module: the rules must be appended LAST to a Unit session's ruleset (after author rules, unit + * rules, and the engine's own rules), and OpenCode's "last match wins" makes that ordering the whole guarantee. + * Keeping the ordering rule and the emission logic in one place means a caller cannot get it subtly wrong. + * + * Skills and subagents map cleanly to one permission action each. MCP does not: a server contributes many tools + * (`_`), so isolation there is enforced by HIDING the disallowed servers' tools from the Unit's + * toolset (`context` hook) and by DENYING them by name (`permission evaluate` hook). Both helpers live here so the + * two hooks agree on exactly which servers are hidden. + */ +import type { HostPermissionRule } from "./host" +import type { IsolationPolicy } from "./workflow" + +/** + * Is the named subagent allowed by an isolation policy? Used to fail a Unit fast at authoring/launch time with a + * clear message, rather than letting it start and be denied by a permission rule mid-turn. + * + * `undefined` → allowed (axis unrestricted). An explicit list → membership. + */ +export function subagentAllowed(isolation: IsolationPolicy | undefined, subagent: string): boolean { + if (!isolation || isolation.subagents === undefined) return true + return isolation.subagents.includes(subagent) +} + +/** + * Rules for one axis: `deny *` then `allow` per id. Order is load-bearing — `deny` first so the specific + * `allow`s win under last-match-wins. + */ +function axisRules(action: string, allowed: string[] | undefined): HostPermissionRule[] { + if (allowed === undefined) return [] + const rules: HostPermissionRule[] = [{ action, resource: "*", effect: "deny" }] + for (const id of allowed) rules.push({ action, resource: id, effect: "allow" }) + return rules +} + +/** + * The isolation ruleset for `meta.isolation`, to be appended AFTER every other rule (the engine puts them last in + * the Unit session's `permissions`). Returns `[]` when there is no isolation, so callers can spread unconditionally. + * + * MCP is deliberately absent: it has no single-action form (see {@link mcpToolServersToHide}). + */ +export function isolationRules(isolation: IsolationPolicy | undefined): HostPermissionRule[] { + if (!isolation) return [] + return [...axisRules("skill", isolation.skills), ...axisRules("subagent", isolation.subagents)] +} + +/** The server part of an MCP tool name: `_` → ``. Falls back to the whole name. */ +export function mcpToolServer(toolName: string, knownServers: readonly string[]): string | undefined { + // Prefer a known server exactly: names may contain `_`, so a bare split is ambiguous. Longest match wins. + const match = [...knownServers] + .filter((server) => toolName.startsWith(`${server}_`)) + .toSorted((a, b) => b.length - a.length)[0] + return match +} + +/** + * Which configured MCP servers a Unit must not see, or `undefined` when MCP is unrestricted (isolation absent or + * `mcp` left `undefined`). A Unit may use only the servers named in `meta.isolation.mcp`; every other configured + * server is hidden. `[]` hides them all. + * + * `configured` is every MCP server name the process currently knows (`ctx.mcp.list()`), so the result is exact even + * though the allowlist is small. Order is stable (the caller's `configured` order) for legible logs. + */ +export function mcpServersToHide( + isolation: IsolationPolicy | undefined, + configured: readonly string[], +): string[] | undefined { + if (!isolation || isolation.mcp === undefined) return undefined + const allowed = new Set(isolation.mcp) + return configured.filter((server) => !allowed.has(server)) +} + +/** + * Does a tool name belong to one of the hidden MCP servers? Used by the `context` hook (hide the tool) and the + * `permission evaluate` hook (deny it if the model still names it). + */ +export function isHiddenMcpTool( + toolName: string, + hiddenServers: readonly string[], + knownServers: readonly string[], +): boolean { + if (hiddenServers.length === 0) return false + const server = mcpToolServer(toolName, knownServers) + return server !== undefined && hiddenServers.includes(server) +} + +/** + * Intersect two allow-lists: the ids both permit. Narrow-only by construction — a later level can never widen an + * earlier one. `undefined` means "this level imposes nothing", so it yields the other side unchanged; an empty + * array means "nothing allowed" and collapses the axis to empty. + */ +function intersectAxis(a: string[] | undefined, b: string[] | undefined): string[] | undefined { + if (a === undefined) return b + if (b === undefined) return a + const allowed = new Set(b) + return a.filter((id) => allowed.has(id)) +} + +/** + * The effective isolation of a Unit: the intersection of every level that declared something (manifest, `meta`, + * per-Unit `restrict`, caller override). Narrow-only: no level can widen another. Returns `undefined` when no level + * constrained any axis, so a Unit with no isolation behaves exactly as before. + * + * A Unit's `restrict` can only make a Workflow's policy stricter — never looser — which is why this is an + * intersection and not a precedence chain. + */ +export function intersectIsolation(...policies: Array): IsolationPolicy | undefined { + const defined = policies.filter((policy): policy is IsolationPolicy => policy !== undefined) + if (defined.length === 0) return undefined + const axis = (key: keyof IsolationPolicy): string[] | undefined => + defined + .map((policy) => policy[key]) + .reduce((acc, next) => intersectAxis(acc, next), undefined) + const skills = axis("skills") + const subagents = axis("subagents") + const mcp = axis("mcp") + // No axis constrained at all (every policy was `{}`): no isolation, not an empty object. + if (skills === undefined && subagents === undefined && mcp === undefined) return undefined + return { + ...(skills !== undefined ? { skills } : {}), + ...(subagents !== undefined ? { subagents } : {}), + ...(mcp !== undefined ? { mcp } : {}), + } +} diff --git a/packages/plugin/src/orchestrator.ts b/packages/plugin/src/orchestrator.ts index 35d4f88..7e63fe0 100644 --- a/packages/plugin/src/orchestrator.ts +++ b/packages/plugin/src/orchestrator.ts @@ -15,7 +15,7 @@ import type { Run, WorkflowIdentity } from "./protocol" import { isTerminal, newRun, type RunStore } from "./runs" import { Semaphore } from "./scheduler" import type { UnitIndex } from "./units" -import type { DefineWorkflowConfig, WorkflowMeta } from "./workflow" +import type { DefineWorkflowConfig, IsolationPolicy, WorkflowMeta } from "./workflow" /** Units in flight for one Run: the author's `meta.concurrency`, never above the configured cap. */ export function resolveConcurrency(fromMeta: number | undefined, cap = DEFAULT_UNITS_PER_RUN): number { @@ -110,6 +110,17 @@ export interface RunWorkflowInput { resumeOf?: string | null /** Rules applied to every Unit session in addition to `meta.permissions`. */ permissions?: HostPermissionRule[] + /** + * Every MCP server name the process knows (`ctx.mcp.list()`), captured at Run start. Used to resolve a tool name + * `_` back to its server so `meta.isolation.mcp` can hide the right servers. Absent → MCP isolation + * is not enforced (no server list to compare against). + */ + mcpServers?: string[] + /** + * Isolation for this Run (skills/subagents/MCP), resolved by the caller as `meta.isolation ?? override`. + * The orchestrator applies it as-is; `undefined` ⇒ unrestricted. + */ + isolation?: IsolationPolicy /** Extra context members. */ extend?: Record /** `ctx.$` / `ctx.file` / `ctx.fetch`: off (with the reason) or on. */ @@ -257,6 +268,9 @@ export async function runWorkflow(input: RunWorkflowInput): Promise resolvePermissionPolicy(meta), ask: (form, options) => input.broker.ask({ @@ -325,6 +339,7 @@ export async function runWorkflow(input: RunWorkflowInput): Promise extends WorkflowCapabilities { * `meta.args` (an invalid call throws). One level only: calling `workflow` inside it throws. */ workflow: (name: string, args?: unknown) => Promise - /** Worktrees kept by `isolation: "worktree"` Units that changed something, in the order they finished. */ + /** Worktrees kept by `worktree: true` Units that changed something, in the order they finished. */ worktrees: () => ReadonlyArray<{ unit: string; directory: string; branch: string | null }> /** The Run's abort signal. Aborting stops launching queued Units AND interrupts in-flight Unit sessions; each dropped Unit is recorded in {@link errors}. */ signal: AbortSignal @@ -585,3 +648,53 @@ export function defineWorkflow( } return config } + +/** + * A view of a Workflow's context whose `agent` (and the Units inside `parallel`/`pipeline`) run under a NARROWER + * isolation than the Workflow allows. Sugar over `agent(prompt, { isolation })` for the case where MANY Units in one + * region of the script share a tighter policy: + * + * const audited = withIsolation(ctx, { mcp: ["playwright"] }) + * await audited.agent("review only", { label: "review" }) + * + * Narrow-only, like the Unit `isolation`: the policy is intersected with the Workflow's own (a view can tighten, + * never widen). + * + * **Not a security boundary.** `parallel`/`pipeline` thunks take no arguments and close over whatever `ctx` is in + * scope, so a thunk that calls the ORIGINAL `ctx.agent` bypasses the view. Use this for legibility, and + * `agent(prompt, { isolation })` when a Unit must be provably narrowed. + */ +export function withIsolation(ctx: WorkflowContext, isolation: IsolationPolicy): WorkflowContext { + const narrowed = ( + prompt: string, + opts: AgentOpts = {} as AgentOpts, + ): ReturnType => + ctx.agent(prompt, { + ...opts, + isolation: mergeIsolation(opts.isolation, isolation), + } as AgentOpts) as ReturnType + return { ...ctx, agent: narrowed as AgentFn } +} + +/** + * Combine two Unit-level isolation policies: intersection per axis, so a nested `withIsolation` view stays + * narrow-only. `undefined` on a side means "that side imposes nothing". + */ +function mergeIsolation(a: IsolationPolicy | undefined, b: IsolationPolicy): IsolationPolicy { + const axis = (key: keyof IsolationPolicy): string[] | undefined => { + const left = a?.[key] + const right = b[key] + if (left === undefined) return right + if (right === undefined) return left + const allowed = new Set(right) + return left.filter((id) => allowed.has(id)) + } + const skills = axis("skills") + const subagents = axis("subagents") + const mcp = axis("mcp") + return { + ...(skills !== undefined ? { skills } : {}), + ...(subagents !== undefined ? { subagents } : {}), + ...(mcp !== undefined ? { mcp } : {}), + } +} diff --git a/packages/plugin/test/context.test.ts b/packages/plugin/test/context.test.ts index 7034d07..99dd488 100644 --- a/packages/plugin/test/context.test.ts +++ b/packages/plugin/test/context.test.ts @@ -560,7 +560,7 @@ describe("audit round 4 — a hung interrupt cannot hold the Unit", () => { describe("worktree isolation", () => { test("an unchanged worktree is removed; the Unit ran there", async () => { const { ctx, host } = makeCtx({ worktree: { changed: false } }) - expect(await ctx.agent("edit", { isolation: "worktree", label: "w" })).toBe("edit") + expect(await ctx.agent("edit", { worktree: true, label: "w" })).toBe("edit") expect(host.creates[0]!.location).toEqual({ directory: "/wt/wf-run-test-1" }) expect(host.worktreeLog).toEqual(["create wf-run-test-1", "changed /wt/wf-run-test-1", "remove /wt/wf-run-test-1"]) expect(ctx.worktrees()).toEqual([]) @@ -568,21 +568,21 @@ describe("worktree isolation", () => { test("a changed worktree is kept and listed for merging", async () => { const { ctx, host } = makeCtx({ worktree: { changed: true } }) - await ctx.agent("edit", { isolation: "worktree", label: "w" }) + await ctx.agent("edit", { worktree: true, label: "w" }) expect(host.worktreeLog.some((line) => line.startsWith("remove"))).toBe(false) expect(ctx.worktrees()).toEqual([{ unit: "w", directory: "/wt/wf-run-test-1", branch: "wt-wf-run-test-1" }]) }) test("a location without the plugin fails the Unit early, legibly", async () => { const { ctx, host, state } = makeCtx({ worktree: { active: false } }) - expect(await ctx.agent("edit", { isolation: "worktree" })).toBeNull() + expect(await ctx.agent("edit", { worktree: true })).toBeNull() expect(state.errors[0]?.error).toContain("the workflow plugin is not active in /wt/wf-run-test-1") expect(host.interrupts).toEqual(["ses_fake_1"]) }) test("a host without worktrees fails the Unit, not the Run", async () => { const { ctx, state } = makeCtx() - expect(await ctx.agent("edit", { isolation: "worktree" })).toBeNull() + expect(await ctx.agent("edit", { worktree: true })).toBeNull() expect(state.errors[0]?.error).toContain("not available on this host") }) }) diff --git a/packages/plugin/test/conversation.test.ts b/packages/plugin/test/conversation.test.ts index dd72c1c..ad0191e 100644 --- a/packages/plugin/test/conversation.test.ts +++ b/packages/plugin/test/conversation.test.ts @@ -46,7 +46,7 @@ describe("agent({ keepSession }) — a conversation", () => { { model: "acme/other" }, { effort: "high" }, { location: "/elsewhere" }, - { isolation: "worktree" }, + { worktree: true }, { permissions: [{ action: "edit", resource: "*", effect: "allow" }] }, ] for (const extra of cases) { diff --git a/packages/plugin/test/isolation.test.ts b/packages/plugin/test/isolation.test.ts new file mode 100644 index 0000000..fe9bfac --- /dev/null +++ b/packages/plugin/test/isolation.test.ts @@ -0,0 +1,276 @@ +/** + * Isolation of a Workflow's Units from ambient skills, subagents, and MCP servers (`meta.isolation`). + * + * Covers: rule emission and ORDER (deny-all first, allow per id after — last match wins), the subagent allow-list + * predicate, MCP server/tool resolution and hiding, the runner appending isolation rules LAST to a Unit session's + * ruleset, and a Unit failing fast when it names a subagent the allow-list excludes. + */ +import { describe, expect, test } from "bun:test" + +import { + intersectIsolation, + isHiddenMcpTool, + isolationRules, + mcpServersToHide, + mcpToolServer, + subagentAllowed, +} from "../src/isolation" +import { withIsolation } from "../src/workflow" +import { makeCtx } from "./helpers" + +describe("isolationRules", () => { + test("undefined policy emits nothing", () => { + expect(isolationRules(undefined)).toEqual([]) + }) + + test("skills and subagents: deny-all first, then allow per id", () => { + const rules = isolationRules({ skills: ["code-markup", "design-system"], subagents: ["Reviewer"] }) + expect(rules).toEqual([ + { action: "skill", resource: "*", effect: "deny" }, + { action: "skill", resource: "code-markup", effect: "allow" }, + { action: "skill", resource: "design-system", effect: "allow" }, + { action: "subagent", resource: "*", effect: "deny" }, + { action: "subagent", resource: "Reviewer", effect: "allow" }, + ]) + }) + + test("empty list allows nothing (deny-all only)", () => { + expect(isolationRules({ skills: [], subagents: [] })).toEqual([ + { action: "skill", resource: "*", effect: "deny" }, + { action: "subagent", resource: "*", effect: "deny" }, + ]) + }) + + test("a field left undefined does not restrict that axis", () => { + expect(isolationRules({ skills: ["only"] })).toEqual([ + { action: "skill", resource: "*", effect: "deny" }, + { action: "skill", resource: "only", effect: "allow" }, + ]) + }) +}) + +describe("subagentAllowed", () => { + test("no isolation or no subagents field means unrestricted", () => { + expect(subagentAllowed(undefined, "anything")).toBe(true) + expect(subagentAllowed({}, "anything")).toBe(true) + expect(subagentAllowed({ skills: [] }, "anything")).toBe(true) + }) + + test("explicit list is a membership check", () => { + const iso = { subagents: ["NodeJsDeveloper"] } + expect(subagentAllowed(iso, "NodeJsDeveloper")).toBe(true) + expect(subagentAllowed(iso, "ForeignAgent")).toBe(false) + }) + + test("empty list allows no subagent", () => { + expect(subagentAllowed({ subagents: [] }, "general")).toBe(false) + }) +}) + +describe("runner appends isolation rules LAST", () => { + test("the created session's ruleset ends with the isolation rules", async () => { + const { ctx, host } = makeCtx( + {}, + { + // Author rules that would allow everything — isolation must still come after and win. + permissions: [{ action: "skill", resource: "*", effect: "allow" }], + // Restrict skills only; leave subagents unrestricted so the default Unit can start. + isolation: { skills: ["code-markup"] }, + }, + ) + await ctx.agent("hi") + const created = host.creates[0]! + const tail = created.permissions.slice(-4) + expect(tail).toEqual([ + // ENGINE_UNIT_RULES tail then isolation — order is what makes it win. + { action: "workflow", resource: "*", effect: "deny" }, + { action: "workflow_inline", resource: "*", effect: "deny" }, + { action: "skill", resource: "*", effect: "deny" }, + { action: "skill", resource: "code-markup", effect: "allow" }, + ]) + }) +}) + +describe("fail-fast on a subagent outside the allow-list", () => { + test("a Unit naming a disallowed subagent fails without a session", async () => { + const { ctx, host } = makeCtx({}, { isolation: { subagents: ["NodeJsDeveloper"] } }) + const result = await ctx.agent("hi", { subagent: "ForeignAgent" }) + expect(result).toBeNull() + expect(host.creates.length).toBe(0) + expect(ctx.errors.at(-1)?.error).toContain("is not in the isolation allow-list") + }) + + test("a Unit naming an allowed subagent runs", async () => { + const { ctx, host } = makeCtx({}, { isolation: { subagents: ["NodeJsDeveloper"] } }) + await ctx.agent("hi", { subagent: "NodeJsDeveloper" }) + expect(host.creates.length).toBe(1) + }) +}) + +describe("isolation survives a continuation", () => { + test("a continuation of an isolated Run reuses the session's ruleset (no re-decision, no bypass)", async () => { + const { ctx, host } = makeCtx({}, { isolation: { subagents: ["NodeJsDeveloper"] } }) + const handle = await ctx.agent("first", { subagent: "NodeJsDeveloper", keepSession: true }) + expect(handle.sessionID).not.toBeNull() + // A follow-up turn runs in the SAME session; it does not create a new one, so its ruleset is the one set at + // create time — the isolation the first turn decided still holds. + const before = host.creates.length + await handle.ask("second") + expect(host.creates.length).toBe(before) + }) +}) + +describe("MCP isolation — server resolution and hiding", () => { + const configured = ["playwright", "github", "sentry"] + + test("mcpToolServer resolves the server by longest known prefix (names may contain _)", () => { + expect(mcpToolServer("github_create_issue", configured)).toBe("github") + expect(mcpToolServer("playwright_click", configured)).toBe("playwright") + // An unknown prefix resolves to none (not hidden by accident). + expect(mcpToolServer("other_tool", configured)).toBeUndefined() + }) + + test("mcpServersToHide: undefined mcp leaves MCP unrestricted", () => { + expect(mcpServersToHide(undefined, configured)).toBeUndefined() + expect(mcpServersToHide({}, configured)).toBeUndefined() + expect(mcpServersToHide({ skills: [] }, configured)).toBeUndefined() + }) + + test("mcpServersToHide returns every configured server not in the allow-list", () => { + expect(mcpServersToHide({ mcp: ["playwright"] }, configured)).toEqual(["github", "sentry"]) + expect(mcpServersToHide({ mcp: [] }, configured)).toEqual(["playwright", "github", "sentry"]) + expect(mcpServersToHide({ mcp: [...configured] }, configured)).toEqual([]) + }) + + test("isHiddenMcpTool matches only tools of hidden servers", () => { + const hidden = ["github", "sentry"] + expect(isHiddenMcpTool("github_create_issue", hidden, configured)).toBe(true) + expect(isHiddenMcpTool("sentry_list_issues", hidden, configured)).toBe(true) + expect(isHiddenMcpTool("playwright_click", hidden, configured)).toBe(false) + expect(isHiddenMcpTool("write", hidden, configured)).toBe(false) + expect(isHiddenMcpTool("github_create_issue", [], configured)).toBe(false) + }) +}) + +describe("MCP isolation reaches the Unit binding", () => { + // The binding is live only while the Unit runs; a hanging prompt keeps it bound so it can be inspected. + test("hiddenMcpServers is stored on the Unit binding from meta.isolation.mcp", async () => { + const { ctx, host, index } = makeCtx( + { promptHang: true }, + { isolation: { mcp: ["playwright"] }, mcpServers: ["playwright", "github", "sentry"] }, + ) + void ctx.agent("hi") + await new Promise((resolve) => setTimeout(resolve, 20)) + const sessionID = host.prompts[0]?.sessionID ?? host.sessions.keys().next().value + const binding = index.get(sessionID!) + expect(binding?.hiddenMcpServers).toEqual(["github", "sentry"]) + expect(binding?.knownMcpServers).toEqual(["playwright", "github", "sentry"]) + }) + + test("no mcp field ⇒ no hidden servers on the binding", async () => { + const { ctx, host, index } = makeCtx({ promptHang: true }, { isolation: { skills: [] }, mcpServers: ["github"] }) + void ctx.agent("hi") + await new Promise((resolve) => setTimeout(resolve, 20)) + const sessionID = host.prompts[0]?.sessionID ?? host.sessions.keys().next().value + expect(index.get(sessionID!)?.hiddenMcpServers).toBeUndefined() + }) +}) + +describe("intersectIsolation — narrow-only across levels", () => { + test("no policy constrains anything ⇒ undefined", () => { + expect(intersectIsolation(undefined, undefined)).toBeUndefined() + expect(intersectIsolation()).toBeUndefined() + expect(intersectIsolation({}, {})).toBeUndefined() + }) + + test("undefined on one side yields the other unchanged", () => { + expect(intersectIsolation({ skills: ["a", "b"] }, undefined)).toEqual({ skills: ["a", "b"] }) + expect(intersectIsolation(undefined, { skills: ["a"] })).toEqual({ skills: ["a"] }) + }) + + test("two allow-lists intersect; [] collapses to empty", () => { + expect(intersectIsolation({ skills: ["a", "b", "c"] }, { skills: ["b", "c", "d"] })).toEqual({ skills: ["b", "c"] }) + expect(intersectIsolation({ skills: ["a"] }, { skills: [] })).toEqual({ skills: [] }) + }) + + test("axes are independent", () => { + expect( + intersectIsolation({ skills: ["a"], subagents: ["x", "y"], mcp: ["p", "q"] }, { subagents: ["y"], mcp: ["p"] }), + ).toEqual({ skills: ["a"], subagents: ["y"], mcp: ["p"] }) + }) +}) + +describe("per-Unit isolation — a Unit can tighten but never widen", () => { + test("isolation narrows the effective subagent allow-list (fail-fast on the intersection)", async () => { + const { ctx, host } = makeCtx({}, { isolation: { subagents: ["A", "B"] } }) + // "B" is allowed by the Workflow but excluded by this Unit's isolation ⇒ rejected before any session. + const result = await ctx.agent("hi", { subagent: "B", isolation: { subagents: ["A"] } }) + expect(result).toBeNull() + expect(host.creates.length).toBe(0) + expect(ctx.errors.at(-1)?.error).toContain("is not in the isolation allow-list") + }) + + test("isolation cannot widen: a subagent outside the Workflow policy stays rejected", async () => { + const { ctx, host } = makeCtx({}, { isolation: { subagents: ["A"] } }) + const result = await ctx.agent("hi", { subagent: "Z", isolation: { subagents: ["Z"] } }) + expect(result).toBeNull() + expect(host.creates.length).toBe(0) + }) + + test("a Unit's narrower ruleset ends with the Intersected rules", async () => { + const { ctx, host } = makeCtx({}, { isolation: { skills: ["a", "b"] } }) + await ctx.agent("hi", { isolation: { skills: ["b"] } }) + const tail = host.creates[0]!.permissions.slice(-2) + expect(tail).toEqual([ + { action: "skill", resource: "*", effect: "deny" }, + { action: "skill", resource: "b", effect: "allow" }, + ]) + }) + + test("isolation is refused on a continuation (the session's ruleset is fixed)", async () => { + const { ctx } = makeCtx({}) + const handle = await ctx.agent("first", { keepSession: true }) + // The continuation resolves to a handle whose value is null and records the refusal in ctx.errors. + const next = await handle.ask("second", { isolation: { skills: [] } } as never) + expect(next.value).toBeNull() + expect(ctx.errors.at(-1)?.error).toContain("keeps its session's") + }) +}) + +describe("withIsolation — sugar over Unit isolation (not a security boundary)", () => { + test("Units on the narrowed view carry the intersected restriction", async () => { + const { ctx, host } = makeCtx({}, { isolation: { skills: ["a", "b"] } }) + const view = withIsolation(ctx, { skills: ["b"] }) + await view.agent("hi") + const tail = host.creates[0]!.permissions.slice(-2) + expect(tail).toEqual([ + { action: "skill", resource: "*", effect: "deny" }, + { action: "skill", resource: "b", effect: "allow" }, + ]) + }) + + test("nested withIsolation stays narrow-only (intersection, not replacement)", async () => { + const { ctx, host } = makeCtx({}, { isolation: { skills: ["a", "b", "c"] } }) + const outer = withIsolation(ctx, { skills: ["a", "b"] }) + const inner = withIsolation(outer, { skills: ["b", "c"] }) + await inner.agent("hi") + const tail = host.creates[0]!.permissions.slice(-2) + expect(tail).toEqual([ + { action: "skill", resource: "*", effect: "deny" }, + { action: "skill", resource: "b", effect: "allow" }, + ]) + }) + + test("the original ctx is unaffected by a narrowed view (documents the non-boundary)", async () => { + const { ctx, host } = makeCtx({}, { isolation: { skills: ["a", "b"] } }) + withIsolation(ctx, { skills: ["a"] }) + await ctx.agent("via original") + // Original ctx still allows both — a view never mutates the ctx it wraps. + const tail = host.creates[0]!.permissions.slice(-3) + expect(tail).toEqual([ + { action: "skill", resource: "*", effect: "deny" }, + { action: "skill", resource: "a", effect: "allow" }, + { action: "skill", resource: "b", effect: "allow" }, + ]) + }) +}) diff --git a/packages/plugin/test/live/features.live.ts b/packages/plugin/test/live/features.live.ts index 65b068a..5e33a3c 100644 --- a/packages/plugin/test/live/features.live.ts +++ b/packages/plugin/test/live/features.live.ts @@ -26,8 +26,8 @@ export default defineWorkflow({ meta: { name: "edit", description: "two Units edit files in their own worktrees" }, async run({ agent, parallel, worktrees }) { await parallel([ - () => agent("Create a file named a.txt containing exactly the word alpha, using the write tool. Then reply: done", { label: "writer a", isolation: "worktree", permissions: [{ action: "edit", resource: "*", effect: "allow" }] }), - () => agent("Reply with exactly: nothing to change", { label: "reader", isolation: "worktree" }), + () => agent("Create a file named a.txt containing exactly the word alpha, using the write tool. Then reply: done", { label: "writer a", worktree: true, permissions: [{ action: "edit", resource: "*", effect: "allow" }] }), + () => agent("Reply with exactly: nothing to change", { label: "reader", worktree: true }), ]) return worktrees() }, diff --git a/packages/plugin/test/service.test.ts b/packages/plugin/test/service.test.ts index 4748a2b..353f525 100644 --- a/packages/plugin/test/service.test.ts +++ b/packages/plugin/test/service.test.ts @@ -339,6 +339,113 @@ describe("durable resume — a decomposed Workflow resumes from its own journal" }) }) +describe("isolation comes from a JSON import in the Workflow, intersected with meta and caller (narrow-only)", () => { + const made: string[] = [] + afterAll(() => Promise.all(made.map((dir) => rm(dir, { recursive: true, force: true })))) + + /** + * A Workflow that IMPORTS its isolation from `workflows.json` (no filesystem read by the plugin) and passes it to + * `meta.isolation`. This is how a preset/manifest policy reaches a Run: an ordinary JSON import, inlined by the + * bundler. + */ + async function projectWith(importedIsolation: unknown, metaIsolation?: unknown): Promise { + const dir = await mkdtemp(path.join(os.tmpdir(), "wf-iso-levels-")) + made.push(dir) + await Bun.write( + path.join(dir, ".opencode", "workflows", "workflows.json"), + JSON.stringify({ workflows: { levels: { isolation: importedIsolation } } }), + ) + const meta = metaIsolation ? `, ${JSON.stringify(metaIsolation)}` : "" + await Bun.write( + path.join(dir, ".opencode", "workflows", "levels.ts"), + `import { defineWorkflow } from "@syn7xx/opencode-dynamic-workflows/workflow"\n` + + `import manifest from "./workflows.json"\n` + + `const iso = manifest.workflows.levels.isolation\n` + + `export default defineWorkflow({ meta: { name: "levels", description: "d", isolation: iso${meta} }, async run({ agent }) {\n` + + ` return agent("hi", { label: "u", subagent: "NodeJsDeveloper" })\n` + + `} })\n`, + ) + return dir + } + + it("the Workflow's imported + meta isolation is applied to every Unit session", async () => { + const dir = await projectWith({ skills: ["b"], subagents: ["NodeJsDeveloper"] }) + const { service: svc, host } = service({ location: dir, host: { reply: { text: "ok" } } }) + const started = await svc.startRun({ name: "levels", args: {}, parentSessionID: "p" }) + expect((await started.done).run.status).toBe("succeeded") + const created = host.creates.find((create) => create.agent === "NodeJsDeveloper")! + const skillRules = created.permissions.filter((rule) => rule.action === "skill") + expect(skillRules).toEqual([ + { action: "skill", resource: "*", effect: "deny" }, + { action: "skill", resource: "b", effect: "allow" }, + ]) + }) + + it("a caller override cannot widen the Workflow's policy: intersection, never replacement", async () => { + const dir = await projectWith({ skills: ["a"] }) + const { service: svc, host } = service({ location: dir, host: { reply: { text: "ok" } } }) + // Caller asks for ["a","z"] — "z" is not in the Workflow's policy, so the intersection keeps only "a". + const started = await svc.startRun( + { name: "levels", args: {}, parentSessionID: "p" }, + { isolation: { skills: ["a", "z"] } }, + ) + expect((await started.done).run.status).toBe("succeeded") + const created = host.creates.find((create) => create.agent === "NodeJsDeveloper")! + const skillRules = created.permissions.filter((rule) => rule.action === "skill") + expect(skillRules).toEqual([ + { action: "skill", resource: "*", effect: "deny" }, + { action: "skill", resource: "a", effect: "allow" }, + ]) + }) +}) + +describe("isolation from a Workflow's meta reaches every Unit session", () => { + const made: string[] = [] + afterAll(() => Promise.all(made.map((dir) => rm(dir, { recursive: true, force: true })))) + + it("meta.isolation is applied to the Unit's ruleset, appended last", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "wf-isolation-")) + made.push(dir) + await Bun.write( + path.join(dir, ".opencode", "workflows", "iso.ts"), + `import { defineWorkflow } from "@syn7xx/opencode-dynamic-workflows/workflow"\n` + + `export default defineWorkflow({ meta: { name: "iso", description: "d", isolation: { subagents: ["NodeJsDeveloper"] } }, async run({ agent }) {\n` + + ` return agent("hi", { label: "u", subagent: "NodeJsDeveloper" })\n` + + `} })\n`, + ) + const { service: svc, host } = service({ location: dir, host: { reply: { text: "ok" } } }) + const started = await svc.startRun({ name: "iso", args: {}, parentSessionID: "p" }) + expect((await started.done).run.status).toBe("succeeded") + const created = host.creates.find((create) => create.agent === "NodeJsDeveloper") + expect(created).toBeDefined() + // Isolation rules are last in the session's ruleset (last match wins). + expect(created!.permissions.slice(-2)).toEqual([ + { action: "subagent", resource: "*", effect: "deny" }, + { action: "subagent", resource: "NodeJsDeveloper", effect: "allow" }, + ]) + }) + + it("a Workflow naming a subagent outside meta.isolation fails fast (no session created)", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "wf-isolation-deny-")) + made.push(dir) + await Bun.write( + path.join(dir, ".opencode", "workflows", "iso-bad.ts"), + `import { defineWorkflow } from "@syn7xx/opencode-dynamic-workflows/workflow"\n` + + `export default defineWorkflow({ meta: { name: "iso-bad", description: "d", isolation: { subagents: ["NodeJsDeveloper"] } }, async run({ agent }) {\n` + + ` return agent("hi", { label: "u", subagent: "ForeignAgent" })\n` + + `} })\n`, + ) + const { service: svc, host } = service({ location: dir, host: { reply: { text: "ok" } } }) + const started = await svc.startRun({ name: "iso-bad", args: {}, parentSessionID: "p" }) + const { run } = await started.done + // The Unit was rejected before any session existed for that agent. + expect(host.creates.some((create) => create.agent === "ForeignAgent")).toBe(false) + // A Unit-less failure is recorded on the Run's errors (no Unit emitted). + expect(run.units.length).toBe(0) + expect(run.errors[0]?.error).toContain("is not in the isolation allow-list") + }) +}) + describe("resume — a replayed Unit's receipt reads the original Run's session", () => { it("threads the recorded sessionID through the ReplayPlan to the receipt's toolCalls, across repeated resumes", async () => { const dir = await mkdtemp(path.join(os.tmpdir(), "wf-receipt-resume-"))