Skip to content

Commit 1e9c45f

Browse files
author
Claude Agent
committed
merge: task 3n — workflow subagents inherit parent permissions, anomalyco#26514 regression (reviewed)
2 parents dc988f3 + 92e5542 commit 1e9c45f

4 files changed

Lines changed: 169 additions & 1 deletion

File tree

‎packages/opencode/src/server/routes/instance/httpapi/handlers/workflow.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,12 @@ export const workflowHandlers = HttpApiBuilder.group(InstanceHttpApi, "workflow"
5757
budget: ctx.payload?.budget,
5858
// Already branded by the StartPayload schema decode (SessionID).
5959
permissionSessionID: ctx.payload?.permissionSessionID,
60+
// When the HTTP caller supplied a session identity, derive subagent
61+
// permission inheritance from it (parent-session deny/external_directory
62+
// rules). The HTTP payload carries no caller-agent, so the agent-level
63+
// edit denies (Plan Mode) are only inherited on the tool path; without a
64+
// session id this is the documented fallback (no inherited ruleset).
65+
caller: ctx.payload?.permissionSessionID ? { sessionID: ctx.payload.permissionSessionID } : undefined,
6066
prompt,
6167
})
6268
.pipe(Effect.mapError(apiError(ctx.params.name)))

‎packages/opencode/src/tool/workflow.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,10 @@ function startWorkflow(input: {
372372
budget: input.params.budget,
373373
prompt: ops,
374374
permissionSessionID: input.ctx.sessionID,
375+
// Pass the caller's identity so every subagent the run spawns inherits
376+
// this session's deny/external_directory rules and this agent's edit-class
377+
// denies (Plan Mode) — the same ruleset the task tool derives (#26514).
378+
caller: { sessionID: input.ctx.sessionID, agent: input.ctx.agent },
375379
source: input.source,
376380
temporary: input.temporary,
377381
})

‎packages/opencode/src/workflow/workflow.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { Config } from "@/config/config"
22
import { Agent } from "@/agent/agent"
3+
import { deriveSubagentSessionPermission } from "@/agent/subagent-permissions"
34
import { EffectBridge } from "@/effect/bridge"
45
import { InstanceState } from "@/effect/instance-state"
56
import { Identifier } from "@/id/id"
@@ -193,6 +194,17 @@ export type StartOptions = StartInput & {
193194
source?: string
194195
temporary?: boolean
195196
permissionSessionID?: SessionID
197+
/**
198+
* Identity of the caller that started this run (the tool/session that asked).
199+
* Used to derive the inherited `permission` ruleset for every subagent session
200+
* the run spawns (parent-session deny/external_directory rules + the caller
201+
* agent's edit-class denies, i.e. Plan Mode — regression of #26514). This is
202+
* distinct from `permissionSessionID`, which only controls WHERE interactive
203+
* permission prompts surface, not WHICH rules apply. Absent on a purely
204+
* programmatic/HTTP start with no session identity — the documented fallback
205+
* (no inherited ruleset) preserves the prior behavior.
206+
*/
207+
caller?: { sessionID: SessionID; agent?: string }
196208
}
197209

198210
export type WaitInput = {
@@ -1381,11 +1393,35 @@ export const layer = Layer.effect(
13811393
Effect.gen(function* () {
13821394
const selected = agentInput.agent ? yield* agents.get(agentInput.agent) : yield* agents.defaultInfo()
13831395
const modelInfo = agentInput.model ? Provider.parseModel(agentInput.model) : selected.model
1396+
// Security (#26514 regression, Fund N9): a workflow subagent MUST
1397+
// inherit the caller's deny/external_directory rules and the caller
1398+
// agent's edit-class denies (Plan Mode lives on the agent ruleset,
1399+
// not the session) — exactly like the task tool derives a subagent's
1400+
// ruleset. Without the caller's identity (a purely programmatic/HTTP
1401+
// start with no session) we fall back to the prior behavior: no
1402+
// inherited ruleset (the engine still defaults task/todowrite denies
1403+
// for any non-permitting subagent via the normal session permission
1404+
// path). `agents.get` on the caller agent uses the same catchCause
1405+
// fallback as task.ts so an unknown caller agent never fails the run.
1406+
const callerSession = input.caller
1407+
? yield* sessions.get(input.caller.sessionID).pipe(Effect.catchCause(() => Effect.succeed(undefined)))
1408+
: undefined
1409+
const callerAgent =
1410+
input.caller?.agent !== undefined
1411+
? yield* agents.get(input.caller.agent).pipe(Effect.catchCause(() => Effect.succeed(undefined)))
1412+
: undefined
13841413
const session = yield* sessions.create({
13851414
parentID: active.run.session_id ? SessionID.make(active.run.session_id) : undefined,
13861415
title: `${active.run.workflow} ${node.id} (@${selected.name} subagent)`,
13871416
agent: selected.name,
13881417
model: modelInfo ? { id: modelInfo.modelID, providerID: modelInfo.providerID } : undefined,
1418+
permission: callerSession
1419+
? deriveSubagentSessionPermission({
1420+
parentSessionPermission: callerSession.permission ?? [],
1421+
parentAgent: callerAgent,
1422+
subagent: selected,
1423+
})
1424+
: undefined,
13891425
})
13901426
node.agent = selected.name
13911427
if (modelInfo) node.model = `${modelInfo.providerID}/${modelInfo.modelID}`

‎packages/opencode/test/workflow/workflow.test.ts‎

Lines changed: 123 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { describe, expect, test } from "bun:test"
22
import { Workflow } from "@/workflow/workflow"
3+
import { Session } from "@/session/session"
4+
import { Agent } from "@/agent/agent"
5+
import { SessionID } from "@/session/schema"
36
import type { SessionPrompt } from "@/session/prompt"
47
import type { SessionV1 } from "@opencode-ai/core/v1/session"
58
import { Database } from "@opencode-ai/core/database/database"
@@ -17,7 +20,19 @@ import path from "path"
1720

1821
// Database.defaultLayer is merged so the orphan-sweep tests can seed a row
1922
// directly through the same in-memory SQLite connection the engine uses.
20-
const it = testEffect(Layer.mergeAll(Workflow.defaultLayer, Database.defaultLayer, CrossSpawnSpawner.defaultLayer))
23+
// Session/Agent.defaultLayer are merged so the subagent-permission-inheritance
24+
// tests can create a caller session (with a deny ruleset) and read back the
25+
// child session the engine spawns — through the SAME memoised services the
26+
// engine resolves (Effect dedupes shared layer builds, exactly as for Database).
27+
const it = testEffect(
28+
Layer.mergeAll(
29+
Workflow.defaultLayer,
30+
Database.defaultLayer,
31+
Session.defaultLayer,
32+
Agent.defaultLayer,
33+
CrossSpawnSpawner.defaultLayer,
34+
),
35+
)
2136

2237
const HELLO_FIXTURE = "hello"
2338

@@ -171,6 +186,28 @@ export async function run(args, ctx) {
171186
}
172187
`
173188

189+
// Subagent-permission-inheritance fixture (#26514 regression / Fund N9): a
190+
// single agent step that completes. The engine must spawn its child session
191+
// with a derived `permission` ruleset when a `caller` context is supplied.
192+
const SINGLE_AGENT_FIXTURE = "single-agent"
193+
const SINGLE_AGENT_WORKFLOW = `export const meta = { name: "${SINGLE_AGENT_FIXTURE}", phases: ["run"] }
194+
export async function run(args, ctx) {
195+
ctx.setPhase("run")
196+
await ctx.agent({ prompt: "do the thing" })
197+
return { ok: true }
198+
}
199+
`
200+
201+
// Prompt-ops that resolve every agent prompt immediately (no hang), so the run
202+
// reaches `completed` and the child session is fully created/projected.
203+
function immediatePromptOps() {
204+
const ops: { prompt: SessionPrompt.Interface["prompt"]; cancel: SessionPrompt.Interface["cancel"] } = {
205+
prompt: () => Effect.succeed(assistantReply()),
206+
cancel: () => Effect.void,
207+
}
208+
return ops
209+
}
210+
174211
// N11-Fixture: Der Body startet einen Agenten OHNE ihn zu awaiten (fire-and-
175212
// forget) — der hängende ctx.agent-Promise settelt nie vor Body-Ende — und
176213
// returnt sofort. Die Pause gibt dem dispatchten Agent-Fiber Zeit, seine
@@ -2456,6 +2493,91 @@ export async function run() { return { ok: true } }
24562493
}),
24572494
)
24582495

2496+
// #26514 regression / Fund N9 (security): a workflow subagent MUST inherit the
2497+
// caller's deny/external_directory rules (and the caller agent's edit-class
2498+
// denies, i.e. Plan Mode) — the same ruleset the task tool derives. Before the
2499+
// fix the engine spawned the child session with NO `permission`, so a parent
2500+
// `edit: deny` (Plan Mode) or `external_directory` confinement silently leaked.
2501+
it.instance("workflow subagent inherits the caller session's deny/external_directory rules", () =>
2502+
Effect.gen(function* () {
2503+
const test = yield* TestInstance
2504+
yield* Effect.promise(() => writeWorkflow(test.directory, SINGLE_AGENT_FIXTURE, SINGLE_AGENT_WORKFLOW))
2505+
const workflow = yield* Workflow.Service
2506+
const sessions = yield* Session.Service
2507+
2508+
// The caller session carries the exact rules a Plan-Mode / confined parent
2509+
// would: an edit deny and an external_directory rule. The fix must forward
2510+
// both onto every subagent session the run spawns.
2511+
const caller = yield* sessions.create({
2512+
title: "Caller",
2513+
permission: [
2514+
{ permission: "edit", pattern: "**", action: "deny" },
2515+
{ permission: "external_directory", pattern: "/outside/**", action: "allow" },
2516+
],
2517+
})
2518+
2519+
const run = yield* workflow.start({
2520+
name: SINGLE_AGENT_FIXTURE,
2521+
args: {},
2522+
prompt: immediatePromptOps(),
2523+
caller: { sessionID: caller.id, agent: "build" },
2524+
})
2525+
const done = (yield* workflow.wait({ id: run.id })).run ?? (yield* Effect.fail(new Error("did not finish")))
2526+
expect(done.status).toBe("completed")
2527+
2528+
const childSessionID = done.agents[0]?.session_id
2529+
expect(childSessionID).toBeDefined()
2530+
// The projector persists the session row off the Created event, so poll the
2531+
// read until the row (and its derived permission) is visible. A not-yet-
2532+
// projected row fails get() with NotFound → map to undefined to keep polling.
2533+
const child = yield* pollWithTimeout(
2534+
sessions
2535+
.get(SessionID.make(childSessionID!))
2536+
.pipe(
2537+
Effect.map((s) => (s.permission ? s : undefined)),
2538+
Effect.catchCause(() => Effect.succeed(undefined)),
2539+
),
2540+
"child session permission never populated",
2541+
)
2542+
const rules = child.permission ?? []
2543+
// Core security assertion: the caller's deny + external_directory rules are
2544+
// present on the child (regression of #26514 would leave these absent).
2545+
expect(rules).toContainEqual({ permission: "edit", pattern: "**", action: "deny" })
2546+
expect(rules).toContainEqual({ permission: "external_directory", pattern: "/outside/**", action: "allow" })
2547+
}),
2548+
)
2549+
2550+
// Fallback (documented behavior): a programmatic start with NO caller context
2551+
// keeps the prior behavior — the child session carries no derived `permission`.
2552+
it.instance("workflow subagent has no inherited ruleset when no caller context is supplied", () =>
2553+
Effect.gen(function* () {
2554+
const test = yield* TestInstance
2555+
yield* Effect.promise(() => writeWorkflow(test.directory, SINGLE_AGENT_FIXTURE, SINGLE_AGENT_WORKFLOW))
2556+
const workflow = yield* Workflow.Service
2557+
const sessions = yield* Session.Service
2558+
2559+
const run = yield* workflow.start({
2560+
name: SINGLE_AGENT_FIXTURE,
2561+
args: {},
2562+
prompt: immediatePromptOps(),
2563+
})
2564+
const done = (yield* workflow.wait({ id: run.id })).run ?? (yield* Effect.fail(new Error("did not finish")))
2565+
expect(done.status).toBe("completed")
2566+
2567+
const childSessionID = done.agents[0]?.session_id
2568+
expect(childSessionID).toBeDefined()
2569+
// No caller ⇒ no derived ruleset. The session row exists (the run created
2570+
// it), but its `permission` column stays unset (fromRow → undefined). Poll
2571+
// until the row is visible (NotFound → undefined keeps polling), then assert
2572+
// no permission was stored.
2573+
const child = yield* pollWithTimeout(
2574+
sessions.get(SessionID.make(childSessionID!)).pipe(Effect.catchCause(() => Effect.succeed(undefined))),
2575+
"child session never created",
2576+
)
2577+
expect(child.permission).toBeUndefined()
2578+
}),
2579+
)
2580+
24592581
// Fund 18 (medium): die drei Workflow-Zeitfelder (LogEntry.time,
24602582
// AgentRun.started_at/completed_at) sind Epoch-Millis und damit IMMER endlich.
24612583
// Als `Schema.Number` erzeugte der SDK-Generator für sie eine NaN/Infinity-

0 commit comments

Comments
 (0)