@@ -9,6 +9,8 @@ import { MessageV2 } from "../session/message-v2"
99import { Agent } from "../agent/agent"
1010import { deriveSubagentSessionPermission } from "../agent/subagent-permissions"
1111import type { SessionPrompt } from "../session/prompt"
12+ import { SubagentLimits } from "../session/subagent-limits"
13+ import { TurnBudget } from "../session/turn-budget"
1214import { Config } from "@/config/config"
1315import { Effect , Exit , Schema , Scope } from "effect"
1416import { EffectBridge } from "@/effect/bridge"
@@ -18,7 +20,15 @@ import { Database } from "@opencode-ai/core/database/database"
1820export interface TaskPromptOps {
1921 cancel ( sessionID : SessionID ) : Effect . Effect < void >
2022 resolvePromptParts ( template : string ) : Effect . Effect < SessionPrompt . PromptInput [ "parts" ] >
21- prompt ( input : SessionPrompt . PromptInput ) : Effect . Effect < SessionV1 . WithParts >
23+ /**
24+ * design-final §4.6: `turnBudgetPool` is the root turn's live TurnBudget.Pool,
25+ * shared BY REFERENCE through every nesting level (the non-serializable
26+ * intersection follows the LoopOptions pattern — the pool must never ride a
27+ * schema). The receiving side (SessionPrompt.prompt) prefers the pool over
28+ * creating a fresh one from `turnBudget`, so the child loop charges the same
29+ * headroom as the root turn.
30+ */
31+ prompt ( input : SessionPrompt . PromptInput & { turnBudgetPool ?: TurnBudget . Pool } ) : Effect . Effect < SessionV1 . WithParts >
2232 /**
2333 * The session's currently RESOLVED model (session.model → last user message's
2434 * model → provider default) — the same chain the prompt loop uses for a turn
@@ -98,6 +108,12 @@ export const TaskTool = Tool.define(
98108 const flags = yield * RuntimeFlags . Service
99109 const database = yield * Database . Service
100110
111+ // In-memory lifetime counter of subagents started per session TREE, keyed
112+ // by the root session id (design-final §2.2). A safety ceiling against
113+ // runaway delegation within one process run — deliberately not persisted;
114+ // resumes/extends do not count and workflow dispatches keep their own cap.
115+ const treeSpawnCounts = new Map < SessionID , number > ( )
116+
101117 const run = Effect . fn ( "TaskTool.execute" ) ( function * (
102118 params : Schema . Schema . Type < typeof Parameters > ,
103119 ctx : Tool . Context ,
@@ -110,6 +126,19 @@ export const TaskTool = Tool.define(
110126 )
111127 }
112128
129+ // Runtime depth guard (defense line 3, design-final §4.1): depth is
130+ // derived from the real parent chain at spawn time, so resumed sessions
131+ // keep their stored depth and a lineage failure (cyclic parents) refuses
132+ // the spawn with its own typed error. Deliberately BEFORE ctx.ask — the
133+ // subtask path calls execute with bypassAgentCheck and skips the ask.
134+ const chain = yield * sessions . lineage ( ctx . sessionID )
135+ const spawnerDepth = chain . length
136+ const rootID = chain . at ( - 1 ) ! . id
137+ const depthLimit = SubagentLimits . maxDepth ( cfg )
138+ if ( spawnerDepth >= depthLimit ) {
139+ return yield * Effect . fail ( SubagentLimits . depthError ( { depth : spawnerDepth , limit : depthLimit } ) )
140+ }
141+
113142 if ( ! ctx . extra ?. bypassAgentCheck ) {
114143 yield * ctx . ask ( {
115144 permission : id ,
@@ -130,6 +159,13 @@ export const TaskTool = Tool.define(
130159 const session = params . task_id
131160 ? yield * sessions . get ( SessionID . make ( params . task_id ) ) . pipe ( Effect . catchCause ( ( ) => Effect . succeed ( undefined ) ) )
132161 : undefined
162+ // task_id may only resume DIRECT children (design-final §4.4): resuming
163+ // an ancestor or a foreign session was silently adopted before and could
164+ // deadlock (child waiting on its own ancestor's runner). Unknown ids
165+ // still fall through to a fresh session below.
166+ if ( session !== undefined && session . parentID !== ctx . sessionID ) {
167+ return yield * Effect . fail ( SubagentLimits . resumeError ( { taskID : session . id } ) )
168+ }
133169 const parent = yield * sessions . get ( ctx . sessionID )
134170 const childPermission = deriveSubagentSessionPermission ( {
135171 parentSessionPermission : parent . permission ?? [ ] ,
@@ -150,20 +186,44 @@ export const TaskTool = Tool.define(
150186 ]
151187 const nextSession =
152188 session ??
153- ( yield * sessions . create ( {
154- parentID : ctx . sessionID ,
155- title : params . description + ` (@${ next . name } subagent)` ,
156- agent : next . name ,
157- permission : [
158- ...childPermission ,
159- ...childToolDenies . filter (
160- ( deny ) =>
161- ! childPermission . some (
162- ( rule ) =>
163- rule . permission === deny . permission && rule . pattern === deny . pattern && rule . action === deny . action ,
164- ) ,
165- ) ,
166- ] ,
189+ ( yield * Effect . gen ( function * ( ) {
190+ // Tree lifetime cap (design-final §2.2): gates NEW spawns only —
191+ // the resume/extend path never reaches this branch. Counted against
192+ // the tree's root so every level shares one ceiling.
193+ const treeLimit = SubagentLimits . __testHooks . treeLimit ?? SubagentLimits . SUBAGENT_TREE_LIMIT
194+ const started = treeSpawnCounts . get ( rootID ) ?? 0
195+ if ( started >= treeLimit ) {
196+ return yield * Effect . fail ( SubagentLimits . treeLimitError ( { started, limit : treeLimit } ) )
197+ }
198+ // Budget spawn gate (design-final §4.6, soft cap): an exhausted
199+ // shared turn pool refuses NEW subagents while running ones finish.
200+ // No pool (the interactive default) means no gate.
201+ const pool = ctx . extra ?. turnBudget as TurnBudget . Pool | undefined
202+ if ( pool !== undefined ) {
203+ const headroom = TurnBudget . remaining ( pool )
204+ if ( headroom . usd === 0 || headroom . tokens === 0 ) {
205+ return yield * Effect . fail ( SubagentLimits . budgetError ( ) )
206+ }
207+ }
208+ const created = yield * sessions . create ( {
209+ parentID : ctx . sessionID ,
210+ title : params . description + ` (@${ next . name } subagent)` ,
211+ agent : next . name ,
212+ permission : [
213+ ...childPermission ,
214+ ...childToolDenies . filter (
215+ ( deny ) =>
216+ ! childPermission . some (
217+ ( rule ) =>
218+ rule . permission === deny . permission &&
219+ rule . pattern === deny . pattern &&
220+ rule . action === deny . action ,
221+ ) ,
222+ ) ,
223+ ] ,
224+ } )
225+ treeSpawnCounts . set ( rootID , started + 1 )
226+ return created
167227 } ) )
168228
169229 const msg = yield * MessageV2 . get ( { sessionID : ctx . sessionID , messageID : ctx . messageID } ) . pipe (
@@ -179,6 +239,11 @@ export const TaskTool = Tool.define(
179239 }
180240 const metadata = {
181241 parentSessionId : ctx . sessionID ,
242+ // Root of the session tree (design-final §4.5 Ü1): second cancel
243+ // source for cancelBackgroundJobs — root-level cancels match jobs by
244+ // rootSessionId even when the parentSessionId chain has a completed
245+ // (non-running) gap in the middle.
246+ rootSessionId : rootID ,
182247 sessionId : nextSession . id ,
183248 model,
184249 ...( runInBackground ? { background : true } : { } ) ,
@@ -197,7 +262,14 @@ export const TaskTool = Tool.define(
197262 const result = yield * ops . prompt ( {
198263 messageID : MessageID . ascending ( ) ,
199264 sessionID : nextSession . id ,
200- permissionSessionID : ctx . sessionID ,
265+ // Permission asks bubble to the tree ROOT (design-final §4.3): every
266+ // level recomputes its own root, so the value is transitively the
267+ // same across the whole tree and depth ≤ 2 stays byte-identical to
268+ // the previous behavior (rootID === ctx.sessionID).
269+ permissionSessionID : rootID ,
270+ // The shared turn pool travels BY REFERENCE into the child loop so
271+ // all nesting levels charge the root turn's budget (§4.6).
272+ turnBudgetPool : ctx . extra ?. turnBudget as TurnBudget . Pool | undefined ,
201273 model : {
202274 modelID : model . modelID ,
203275 providerID : model . providerID ,
0 commit comments