Skip to content

Commit 7a1c057

Browse files
Claude Agentclaude
andcommitted
feat(opencode): open nested subagent spawning by default up to depth 5
Depth-gate the subagent auto-denies instead of blanket-blocking every child (T6, design-final §2/§4): - deriveSubagentSessionPermission gains {childDepth, maxDepth}: the task deny (plus a NEW workflow deny) is emitted only for a child AT the maximum nesting depth; the canTask exact-match asymmetry is gone, so the default wildcard allow suffices to spawn. Single source of the task/todowrite/workflow auto-denies — task.ts keeps only the experimental.primary_tools denies. - workflow agent dispatch derives the child depth from the run session's real lineage and guards before sessions.create; a depth violation maps onto node `failed` like AgentLimitError and is never swallowed by onError:"null". - config: experimental.subagent_max_depth (PositiveInt; default 5, 2 = pre-nesting behavior, 1 = kill switch), consumed only via the SubagentLimits.maxDepth clamp helper. - resolve-time filter: SessionTools.resolve derives the session depth once (shared with ask-origin attribution; lineage failure => Infinity) and ToolRegistry.tools filters task+workflow at depth >= maxDepth — covering the kill switch and a lowered max_depth — and appends the depth hint to the task description on levels 2..max-1. - task.txt documents nesting, the deepest work-only level, and the task_id own-children-only rule. - tests: depth-gating + deny-monotonicity property suite for the derive helper, registry depth-filter/hint/kill-switch cases, task child-permission pins updated (general child may now spawn; at-limit child carries task+workflow denies), workflow depth guard + callsite regression, subtask PIN flipped with a new at-limit case, config parse test. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 5582da5 commit 7a1c057

15 files changed

Lines changed: 610 additions & 57 deletions

File tree

‎packages/core/src/v1/config/config.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,10 @@ export const Info = Schema.Struct({
214214
mcp_timeout: Schema.optional(PositiveInt).annotate({
215215
description: "Timeout in milliseconds for model context protocol (MCP) requests",
216216
}),
217+
subagent_max_depth: Schema.optional(PositiveInt).annotate({
218+
description:
219+
"Maximum subagent nesting depth (the root session is depth 1; clamped to 1..10). Default 5. Set 2 to restore the pre-nesting behavior (the root spawns, subagents do not); 1 is the kill switch that removes the task tool entirely.",
220+
}),
217221
policies: Schema.optional(Schema.mutable(Schema.Array(ConfigExperimental.Policy))).annotate({
218222
description: "Policy statements applied to supported resources, such as provider access",
219223
}),

‎packages/opencode/src/agent/subagent-permissions.ts‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,48 @@ import type { Agent } from "./agent"
33

44
/**
55
* Build the `permission` ruleset for a subagent's session when it's spawned
6-
* via the task tool. Combines:
6+
* via the task tool, the subtask (@agent) path, or a workflow agent dispatch.
7+
* This function is the SINGLE source of the task/todowrite/workflow
8+
* auto-denies (task.ts keeps only the `experimental.primary_tools` denies).
9+
* Combines:
710
*
811
* 1. The parent session's deny rules and external_directory rules.
912
* Parent agent restrictions only govern that agent; the subagent's own
10-
* permissions determine its capabilities.
11-
* 2. Default `todowrite` and `task` denies if the subagent's own ruleset
12-
* doesn't already permit them.
13+
* permissions determine its capabilities. Inherited denies are monotone
14+
* ceilings: a deny on level ≤ n can never evaluate to allow on level n+1.
15+
* 2. A default `todowrite` deny if the subagent's own ruleset doesn't
16+
* already permit it (unchanged by nesting).
17+
* 3. Depth gating (design-final §4.1, defense line 1): `task` AND `workflow`
18+
* denies are added ONLY for a child at the maximum nesting depth
19+
* (childDepth >= maxDepth) — the last level is a pure work level that
20+
* never spawns, regardless of the agent's own config. Below the limit no
21+
* auto-deny is emitted; spawn capability is governed by the agent's
22+
* permission via the runtime merge (tools.ts / llm/request.ts), so the
23+
* default wildcard `'*': allow` suffices and no exact `task` rule is
24+
* required anymore. Because the auto-deny only ever lands on the
25+
* never-spawning last level, it cannot be wrongly re-inherited down a
26+
* spawning chain (the former sticky-deny problem).
1327
*/
1428
export function deriveSubagentSessionPermission(input: {
1529
parentSessionPermission: PermissionV1.Ruleset
1630
subagent: Agent.Info
31+
/** Depth of the child session being spawned (the root session is depth 1). */
32+
childDepth: number
33+
/** Effective maximum nesting depth — resolve via `SubagentLimits.maxDepth(cfg)`. */
34+
maxDepth: number
1735
}): PermissionV1.Ruleset {
18-
const canTask = input.subagent.permission.some((rule) => rule.permission === "task")
1936
const canTodo = input.subagent.permission.some((rule) => rule.permission === "todowrite")
37+
const atLimit = input.childDepth >= input.maxDepth
2038
return [
2139
...input.parentSessionPermission.filter(
2240
(rule) => rule.permission === "external_directory" || rule.action === "deny",
2341
),
2442
...(canTodo ? [] : [{ permission: "todowrite" as const, pattern: "*" as const, action: "deny" as const }]),
25-
...(canTask ? [] : [{ permission: "task" as const, pattern: "*" as const, action: "deny" as const }]),
43+
...(atLimit
44+
? [
45+
{ permission: "task" as const, pattern: "*" as const, action: "deny" as const },
46+
{ permission: "workflow" as const, pattern: "*" as const, action: "deny" as const },
47+
]
48+
: []),
2649
]
2750
}

‎packages/opencode/src/session/tools.ts‎

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -57,27 +57,34 @@ export const resolve = Effect.fn("SessionTools.resolve")(function* (input: {
5757
const truncate = yield* Truncate.Service
5858
const sessions = yield* Session.Service
5959

60+
// Nesting depth of THIS session (root = 1, no walk), derived ONCE per
61+
// resolve from the real parent chain and consumed twice: the registry
62+
// filters task/workflow at depth >= maxDepth (design-final §4.1, defense
63+
// line 2) and routed permission asks carry the depth as origin attribution.
64+
// A failed walk (cyclic parents) yields Infinity — the safest reading: the
65+
// session cannot spawn (tools filtered) and the ask omits originDepth, but
66+
// neither the resolve nor the ask ever fails on it.
67+
const depth =
68+
input.session.parentID === undefined
69+
? 1
70+
: yield* sessions.lineage(input.session.id).pipe(
71+
Effect.map((chain) => chain.length),
72+
Effect.catch(() => Effect.succeed(Number.POSITIVE_INFINITY)),
73+
)
74+
6075
// Nested subagents route their permission asks to the root session
6176
// (permissionSessionID); without attribution UIs and third-party clients
6277
// would lose WHO asked. Whenever the ask is routed away from this session,
6378
// attach the origin (asking session, its agent, its depth) to the request
64-
// metadata. ONE lineage walk per resolve (roots skip it); a failed walk only
65-
// omits originDepth — an ask must never fail on attribution.
66-
const origin = yield* Effect.gen(function* () {
67-
if (input.permissionSessionID === undefined || input.permissionSessionID === input.session.id) return undefined
68-
const originDepth =
69-
input.session.parentID === undefined
70-
? 1
71-
: yield* sessions.lineage(input.session.id).pipe(
72-
Effect.map((chain) => chain.length),
73-
Effect.catch(() => Effect.succeed(undefined)),
74-
)
75-
return {
76-
originSessionID: input.session.id,
77-
originAgent: input.agent.name,
78-
...(originDepth !== undefined ? { originDepth } : {}),
79-
}
80-
})
79+
// metadata.
80+
const origin =
81+
input.permissionSessionID === undefined || input.permissionSessionID === input.session.id
82+
? undefined
83+
: {
84+
originSessionID: input.session.id,
85+
originAgent: input.agent.name,
86+
...(Number.isFinite(depth) ? { originDepth: depth } : {}),
87+
}
8188

8289
const context = (args: Record<string, unknown>, options: ToolExecutionOptions): Tool.Context => ({
8390
sessionID: input.session.id,
@@ -126,6 +133,9 @@ export const resolve = Effect.fn("SessionTools.resolve")(function* (input: {
126133
// Item 13: ultracode sessions get the workflow tool with the standing
127134
// "quality over cost" gate instead of the anti-default sentence.
128135
ultracode: input.session.metadata?.["ultracode"] === true,
136+
// Depth-aware tool list: task/workflow are filtered at the maximum
137+
// nesting depth and the task description gains the mid-level depth hint.
138+
depth,
129139
})) {
130140
const schema = ProviderTransform.schema(input.model, ToolJsonSchema.fromTool(item))
131141
tools[item.id] = tool({

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

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ import { ProviderV2 } from "@opencode-ai/core/provider"
5454
import { ModelV2 } from "@opencode-ai/core/model"
5555
import { Workflow } from "@/workflow/workflow"
5656
import { WorkflowTool, workflowDescription } from "./workflow"
57+
import { SubagentLimits } from "@/session/subagent-limits"
5758

5859
export function webSearchEnabled(providerID: ProviderV2.ID, flags = { exa: false, parallel: false }) {
5960
return providerID === ProviderV2.ID.opencode || flags.exa || flags.parallel
@@ -84,6 +85,16 @@ export interface Interface {
8485
* only seam that can vary by session).
8586
*/
8687
ultracode?: boolean
88+
/**
89+
* Nesting depth of the requesting session (root = 1), derived from the
90+
* real parent chain by SessionTools.resolve. At depth >= maxDepth the
91+
* task and workflow tools are filtered from the list (design-final §4.1,
92+
* defense line 2); on levels 2..max−1 the task description carries a
93+
* depth hint. Infinity marks an unresolvable lineage (treated as
94+
* at-limit). Callers that don't know their depth (debug/HTTP listings)
95+
* default to the root's depth 1.
96+
*/
97+
depth?: number
8798
}) => Effect.Effect<Tool.Def[]>
8899
}
89100

@@ -277,7 +288,19 @@ export const layer = Layer.effect(
277288
})
278289

279290
const tools: Interface["tools"] = Effect.fn("ToolRegistry.tools")(function* (input) {
291+
// Resolve-time depth gate (design-final §4.1, defense line 2):
292+
// config-aware on purpose — it also covers the kill switch
293+
// (`subagent_max_depth: 1` removes task from the ROOT, which has no
294+
// persisted deny) and a later LOWERING of max_depth for existing
295+
// sessions whose ruleset predates the change.
296+
const depthLimit = SubagentLimits.maxDepth(yield* config.get())
297+
const depth = input.depth ?? 1
280298
const filtered = (yield* all()).filter((tool) => {
299+
// At the maximum nesting depth the task and workflow tools are not in
300+
// the tool list at all (Claude-Code parity: the model plans without
301+
// delegation instead of burning turns on refused calls).
302+
if ((tool.id === TaskTool.id || tool.id === WorkflowTool.id) && depth >= depthLimit) return false
303+
281304
if (tool.id === WebSearchTool.id) {
282305
return webSearchEnabled(input.providerID, { exa: flags.enableExa, parallel: flags.enableParallel })
283306
}
@@ -311,9 +334,17 @@ export const layer = Layer.effect(
311334
tool.id === WorkflowTool.id && input.ultracode && output.description === workflowDescription(false)
312335
? workflowDescription(true)
313336
: output.description
337+
// Depth hint (design-final Ü5): sub-agents on levels 2..max−1 are
338+
// told their remaining delegation budget instead of discovering it
339+
// by failed calls. Applied after plugin.trigger like the roster
340+
// below; the root's description stays byte-identical.
341+
const depthHint =
342+
tool.id === TaskTool.id && depth >= 2 && depth < depthLimit
343+
? SubagentLimits.depthHint(depth, depthLimit)
344+
: undefined
314345
return {
315346
id: tool.id,
316-
description: [description, tool.id === TaskTool.id ? yield* describeTask(input.agent) : undefined]
347+
description: [description, depthHint, tool.id === TaskTool.id ? yield* describeTask(input.agent) : undefined]
317348
.filter(Boolean)
318349
.join("\n"),
319350
parameters: output.parameters,

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

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -167,23 +167,22 @@ export const TaskTool = Tool.define(
167167
return yield* Effect.fail(SubagentLimits.resumeError({ taskID: session.id }))
168168
}
169169
const parent = yield* sessions.get(ctx.sessionID)
170+
// The task/todowrite/workflow auto-denies live in ONE place
171+
// (deriveSubagentSessionPermission, design-final §4.2) and are depth
172+
// gated there: only a child AT maxDepth gets them. This call keeps only
173+
// the `experimental.primary_tools` denies.
170174
const childPermission = deriveSubagentSessionPermission({
171175
parentSessionPermission: parent.permission ?? [],
172176
subagent: next,
177+
childDepth: spawnerDepth + 1,
178+
maxDepth: depthLimit,
173179
})
174-
const childToolDenies = [
175-
...(next.permission.some((rule) => rule.permission === "todowrite")
176-
? []
177-
: [{ permission: "todowrite" as const, pattern: "*" as const, action: "deny" as const }]),
178-
...(next.permission.some((rule) => rule.permission === id)
179-
? []
180-
: [{ permission: id, pattern: "*" as const, action: "deny" as const }]),
181-
...(cfg.experimental?.primary_tools?.map((permission) => ({
180+
const childToolDenies =
181+
cfg.experimental?.primary_tools?.map((permission) => ({
182182
permission,
183183
pattern: "*" as const,
184184
action: "deny" as const,
185-
})) ?? []),
186-
]
185+
})) ?? []
187186
const nextSession =
188187
session ??
189188
(yield* Effect.gen(function* () {

‎packages/opencode/src/tool/task.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,5 @@ Usage notes:
1717
5. The agent's outputs should generally be trusted
1818
6. Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent. Tell it how to verify its work if possible (e.g., relevant test commands).
1919
7. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.
20+
8. Agents may themselves delegate to deeper sub-agents. Nesting is allowed up to a configured maximum depth (your own session counts as one level; the root session is depth 1). On the deepest level this tool is not available — an agent there must do the remaining work itself and report results in its final message.
21+
9. task_id can only resume tasks that THIS session started itself (its own direct children). Passing the id of a parent, sibling, or unrelated session fails; an unknown id starts a fresh session.

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

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { Provider } from "@/provider/provider"
1212
import { Session } from "@/session/session"
1313
import type { SessionPrompt } from "@/session/prompt"
1414
import { SessionID } from "@/session/schema"
15+
import { SubagentLimits } from "@/session/subagent-limits"
1516
import { Database } from "@opencode-ai/core/database/database"
1617
import { Global } from "@opencode-ai/core/global"
1718
import { Permission } from "@/permission"
@@ -3172,25 +3173,50 @@ export const layer = Layer.effect(
31723173
}
31733174
}
31743175
}
3176+
// Nested subagents (design-final §4.7 / Ü4): the agent session is
3177+
// created with `parentID = run.session_id` below, so it occupies a
3178+
// REAL nesting level and the workflow tool is no ladder past the
3179+
// depth limit. The child's depth derives from the run session's
3180+
// actual parent chain; without a run session (purely programmatic
3181+
// start) the agent session is a root (depth 1). A failed walk
3182+
// (cyclic parents, SubagentLineageError) fails the step like a
3183+
// depth violation — node `failed`, the same error path as
3184+
// AgentLimitError. The guard sits BEFORE sessions.create (and
3185+
// before the worktree setup), so a refused dispatch creates
3186+
// nothing and wastes no turn.
3187+
const depthLimit = SubagentLimits.maxDepth(yield* config.get())
3188+
const runChain = active.run.session_id
3189+
? yield* sessions.lineage(SessionID.make(active.run.session_id)).pipe(
3190+
// An unknown run session is an orphan, and orphans are roots.
3191+
Effect.catchTag("NotFoundError", () => Effect.succeed([])),
3192+
)
3193+
: []
3194+
const childDepth = runChain.length + 1
3195+
if (childDepth > depthLimit) {
3196+
return yield* SubagentLimits.depthError({ depth: runChain.length, limit: depthLimit })
3197+
}
31753198
// Security (#26514 regression, Fund N9): a workflow subagent MUST
31763199
// inherit the caller's deny/external_directory rules — exactly like
31773200
// the task tool derives a subagent's ruleset (since #31696 parent
31783201
// AGENT restrictions are deliberately NOT inherited; the subagent's
31793202
// own permissions determine its capabilities). Without the caller's
31803203
// identity (a purely programmatic/HTTP start with no session) we fall
31813204
// back to the prior behavior: no inherited ruleset (the engine still
3182-
// defaults task/todowrite denies for any non-permitting subagent via
3205+
// defaults the todowrite deny for any non-permitting subagent via
31833206
// the normal session permission path).
31843207
const callerSession = input.caller
31853208
? yield* sessions.get(input.caller.sessionID).pipe(Effect.catchCause(() => Effect.succeed(undefined)))
31863209
: undefined
31873210
// The inherited subagent ruleset: parent session denies/external_directory,
3188-
// default task/todowrite denies. Absent a caller identity there is
3211+
// default todowrite deny, plus the depth-gated task/workflow denies
3212+
// for a child AT the limit. Absent a caller identity there is
31893213
// nothing to inherit (prior fallback).
31903214
const derivedPermission = callerSession
31913215
? deriveSubagentSessionPermission({
31923216
parentSessionPermission: callerSession.permission ?? [],
31933217
subagent: selected,
3218+
childDepth,
3219+
maxDepth: depthLimit,
31943220
})
31953221
: undefined
31963222
// Security (compose, never override): per-step tool scoping must NEVER
@@ -3643,7 +3669,12 @@ export const layer = Layer.effect(
36433669
agentInput.onError === "null" &&
36443670
!(error instanceof CancelledError) &&
36453671
!(error instanceof BudgetExceededError) &&
3646-
!(error instanceof AgentLimitError)
3672+
!(error instanceof AgentLimitError) &&
3673+
// The depth gate is deterministic for the whole run (every
3674+
// dispatch from the same run session fails the same way), so
3675+
// nulling it inside a while-loop would spin forever — same
3676+
// rationale as the lifetime/budget gates above.
3677+
!(error instanceof SubagentLimits.SubagentDepthError)
36473678
) {
36483679
return null
36493680
}

‎packages/opencode/test/agent/plan-mode-subagent-bypass.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ it.instance("subagent permissions take precedence over parent agent restrictions
4242
const subagentSessionPermission = deriveSubagentSessionPermission({
4343
parentSessionPermission,
4444
subagent: generalAgent!,
45+
childDepth: 2,
46+
maxDepth: 5,
4547
})
4648

4749
// Mirror the runtime evaluation in session/prompt.ts (~line 410, 639):
@@ -62,6 +64,8 @@ it.instance("subagent's own read-only restriction remains effective", () =>
6264
const subagentSessionPermission = deriveSubagentSessionPermission({
6365
parentSessionPermission,
6466
subagent: explore!,
67+
childDepth: 2,
68+
maxDepth: 5,
6569
})
6670
const effective = Permission.merge(explore!.permission, subagentSessionPermission)
6771

@@ -82,6 +86,8 @@ it.instance(
8286
const subagentSessionPermission = deriveSubagentSessionPermission({
8387
parentSessionPermission,
8488
subagent: my!,
89+
childDepth: 2,
90+
maxDepth: 5,
8591
})
8692
const effective = Permission.merge(my!.permission, subagentSessionPermission)
8793

@@ -126,6 +132,8 @@ it.effect("subagent self permissions are preserved", () =>
126132
deriveSubagentSessionPermission({
127133
parentSessionPermission: [],
128134
subagent: executor,
135+
childDepth: 2,
136+
maxDepth: 5,
129137
}),
130138
)
131139

@@ -151,6 +159,8 @@ it.effect("subagent inherits parent session deny rules as hard runtime ceilings"
151159
deriveSubagentSessionPermission({
152160
parentSessionPermission: Permission.fromConfig({ bash: "deny" }),
153161
subagent: executor,
162+
childDepth: 2,
163+
maxDepth: 5,
154164
}),
155165
)
156166

0 commit comments

Comments
 (0)