Skip to content

Commit 4fcd4b3

Browse files
Claude Agentclaude
andcommitted
docs: document subagent nesting, limits, and permission routing
- agents: new Nesting section (depth model, limits table, opt-out subagent_max_depth: 2 = previous behavior, 1 = kill switch, permission semantics in nested trees); task-permission wildcard note - config: experimental.subagent_max_depth reference - permissions: asks from nested subagents land on the root session, always applies tree-wide, origin metadata - sdk: release notes for PermissionRequest.sessionID = tree root and metadata.originSessionID/originAgent/originDepth (no schema change) - add .nested-agents-followups.md with phase-2 follow-up issues incl. the binding parallelism-cap deadlock design note (verbatim) Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 0831b5f commit 4fcd4b3

5 files changed

Lines changed: 200 additions & 1 deletion

File tree

‎.nested-agents-followups.md‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# Follow-up-Issues: Nested-Agent-Spawning (Phase 2)
2+
3+
Quelle: `design-final.md` §9/§10 (Branch `feat/nested-agents`). Jedes Kapitel ist als
4+
eigenständiges GitHub-Issue gedacht. Keines dieser Themen ist Teil von V1.
5+
6+
---
7+
8+
## Issue 1: Parallelitäts-Cap für Subagent-Spawns
9+
10+
**Kontext:** V1 hat bewusst keinen Semaphor (design-final §2.2): Foreground-Tasks blockieren
11+
ihren Eltern-Step ohnehin, Background bleibt flag-gated
12+
(`OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS`), Lifetime-Cap (200/Baum) + Tiefenlimit
13+
begrenzen den Fan-out. Ein Parallelitäts-Cap ist ein reines Phase-2-Thema.
14+
15+
**Scope:** Begrenzung gleichzeitig laufender Subagents pro Session-Baum bzw. pro Ebene.
16+
17+
**BINDENDE DESIGN-NOTIZ (design-final.md §10, wörtlich — bei der Umsetzung zwingend beachten):**
18+
19+
> **NIEMALS ein einzelner baumweiter Semaphor über Foreground-Ketten.** Beweisbares
20+
> Gegenbeispiel: Cap 2, zwei parallele L2-Foreground-Tasks halten beide Permits und warten auf
21+
> L3-Kinder, die nie ein Permit bekommen → Deadlock (wartende Eltern halten Permits, die ihre
22+
> Kinder brauchen). Zulässige Varianten: (a) Per-Ebene-Permits — Pools strikt nach Ebene
23+
> geordnet, ein Halter von Ebene N wartet nie auf Ebene ≤ N, Ebene `max_depth` spawnt nie ⇒ per
24+
> Induktion drainieren alle Pools; (b) Fail-Fast-Breiten-Cap pro Session mit klarem Fehlertext
25+
> (kein stilles Queuing). In beiden Fällen muss das Warten interrupt-fähig sein (Abort-Kaskade
26+
> darf nie an einem Permit hängen). Diese Notiz gehört wörtlich in das Follow-up-Issue.
27+
28+
**Akzeptanzkriterien:**
29+
- Implementierung ist Variante (a) Per-Ebene-Permits ODER (b) Fail-Fast-Breiten-Cap pro
30+
Session — KEIN baumweiter Semaphor über Foreground-Ketten.
31+
- Warten ist interrupt-fähig: Die Abort-Kaskade darf nie an einem Permit hängen
32+
(Regressionstest analog Abort-Kaskaden-Test in `test/session/nested-task.test.ts`).
33+
- Deadlock-Gegenbeispiel aus der Notiz (Cap 2, zwei parallele L2-Foreground-Tasks mit
34+
L3-Kindern) als Test abgedeckt.
35+
36+
---
37+
38+
## Issue 2: Config-Key für das Tree-Limit
39+
40+
**Kontext:** `SUBAGENT_TREE_LIMIT = 200` ist in V1 eine Konstante mit Test-Seam
41+
(`__testHooks.treeLimit` in `packages/opencode/src/session/subagent-limits.ts`, Vorbild
42+
`__testHooks.agentLimit` in workflow.ts). design-final §2.5: Config-Key = Phase 2.
43+
44+
**Scope:** `experimental`-Config-Key (z. B. `subagent_tree_limit`), Konsum ausschließlich
45+
über einen Clamp-Helper in `subagent-limits.ts` (Single Source of Truth, analog `maxDepth(cfg)`).
46+
Der Zähler bleibt in-memory pro Prozess-Lebensdauer (Safety-Ceiling, kein Abrechnungszähler —
47+
DB-Priming wurde in design-final §1.3 explizit verworfen).
48+
49+
---
50+
51+
## Issue 3: `depth`/`rootID` als additive Wire-Felder
52+
53+
**Kontext:** V1 leitet Tiefe und Root rein aus der `parentID`-Kette ab (`Session.lineage`),
54+
null Schema-Änderungen. Phase 2 kann beide Werte als Convenience-Felder am Wire nachrüsten
55+
(design-final §3/§9) — jederzeit additiv möglich, Wire-Format bleibt kompatibel.
56+
57+
**Scope:**
58+
- `depth` und `rootID` als additive Felder an `Session.Info` / OpenAPI / SDK (Regeneration).
59+
- **Backfill für Bestandsdaten: einmalige Migration per rekursiver CTE** (Vorlage in
60+
design-robust). **NICHT Lazy-Backfill-on-read** (Write in Lesepfaden = Wartbarkeits-Smell,
61+
zwei Wahrheitsquellen — in design-final §1.3 explizit verworfen).
62+
- `recursive`-Param für `GET /session/:id/children`.
63+
64+
---
65+
66+
## Issue 4: TUI-Baumansicht / Breadcrumbs / Tiefen-Badges
67+
68+
**Kontext:** V1 verzichtet bewusst auf den UI-Umbau (größte Regressionsoberfläche,
69+
design-final §1.3). Root-Routing der Permission-Asks macht die TUI bereits ohne Umbau
70+
funktionsfähig; Ebene-3+-Navigation läuft pro Ebene über die bestehenden
71+
`session_child_*`-Keybinds.
72+
73+
**Scope (Komfort, Folge-PRs):** Baumansicht für Session-Hierarchien, Breadcrumb-Kette in der
74+
Kopfzeile, Tiefen-Badges an Task-Cards, Run-Footer-Gruppierung nach Teilbaum, Tree-Dialog.
75+
UIs können "asked by @agent (depth N)" aus `metadata.originSessionID`/`originAgent`/
76+
`originDepth` der Permission-Requests rendern. Profitiert von Issue 3 (Wire-Felder), hängt
77+
aber nicht hart daran (Lineage-Walk reicht).
78+
79+
---
80+
81+
## Issue 5: Per-Task-Timeout
82+
83+
**Kontext:** V1 hat kein Timeout pro Ebene (design-final §2.2): Abort-Kaskade + Budget genügen;
84+
der Zyklen-Deadlock ist durch die `task_id`-Ancestry-Validierung (nur direkte Kinder)
85+
geschlossen.
86+
87+
**Scope:** Optionales Timeout pro Task-Spawn (Config und/oder Tool-Param). Muss sauber in die
88+
Abort-Kaskade integrieren (Timeout = Abort des Teilbaums, kein verwaister Job) und darf
89+
Foreground-Eltern nicht in undefinierte Zustände bringen.
90+
91+
---
92+
93+
## Issue 6: Kosten-Rollup über den Session-Baum
94+
95+
**Kontext:** V1 zählt Kosten wie heute pro Session, keine Doppelzählung, kein Rollup
96+
(design-final §4.6). Für tiefe Bäume fehlt die aggregierte Sicht.
97+
98+
**Scope:** Anzeige-Rollup der Kind-Kosten in der Task-Part-Metadata (Anzeige, keine
99+
Doppel-Abrechnung); Aggregation über `Session.descendants` oder die Wire-Felder aus Issue 3.

‎packages/web/src/content/docs/agents.mdx‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ look at these below.
3434

3535
### Subagents
3636

37-
Subagents are specialized assistants that primary agents can invoke for specific tasks. You can also manually invoke them by **@ mentioning** them in your messages.
37+
Subagents are specialized assistants that agents can invoke for specific tasks. You can also manually invoke them by **@ mentioning** them in your messages. Subagents can delegate to subagents of their own — see [Nesting](#nesting) for the depth model and limits.
3838

3939
OpenCode comes with three built-in subagents, **General**, **Explore**, and **Scout**. We'll look at this below.
4040

@@ -139,6 +139,59 @@ Hidden system agent that creates session summaries. It runs automatically and is
139139

140140
---
141141

142+
## Nesting
143+
144+
Subagents can spawn subagents of their own. A session tree starts at your main session — that's **depth 1**. Every Task tool call, `@` mention, or workflow agent dispatch creates a child session one level deeper.
145+
146+
By default, nesting is allowed up to **depth 5**. Sessions at depth 1 through 4 can delegate; sessions at the maximum depth are pure workers — the `task` and `workflow` tools are removed from their tool list entirely, so the model plans around it instead of wasting turns on failed attempts.
147+
148+
---
149+
150+
### Limits
151+
152+
| Limit | Default | On violation |
153+
| -------------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
154+
| Maximum nesting depth | `5` (root session = depth 1), configurable via `experimental.subagent_max_depth`, clamped to 1–10 | The `task` and `workflow` tools are removed at the last level; any remaining spawn attempt fails with a typed `SubagentDepthError` |
155+
| Subagents per session tree | `200` started subagents over the lifetime of the tree | Further spawns fail with `SubagentTreeLimitError` |
156+
| `task_id` resume | Only tasks the session started itself (direct children) | Other session IDs fail with `SubagentResumeError`; unknown IDs still start a fresh session |
157+
| Permission prompts | Raised anywhere in the tree, answered on the **root session** of the tree | — see [permissions in nested trees](#permissions-in-nested-trees) |
158+
159+
---
160+
161+
### Configure the depth
162+
163+
Set the maximum nesting depth with `experimental.subagent_max_depth`:
164+
165+
```json title="opencode.json"
166+
{
167+
"$schema": "https://opencode.ai/config.json",
168+
"experimental": {
169+
"subagent_max_depth": 5
170+
}
171+
}
172+
```
173+
174+
- `5` — the default, nesting up to 5 levels.
175+
- `2` — restores the previous behavior: your main session can spawn subagents, but subagents cannot spawn further subagents.
176+
- `1` — kill switch: the `task` tool is removed everywhere, including from the main session.
177+
178+
Values are clamped to the range 1–10.
179+
180+
---
181+
182+
### Permissions in nested trees
183+
184+
- Whether an agent below the depth limit can spawn is governed by its regular [task permissions](#task-permissions). The default wildcard `"*": "allow"` is enough — an exact `task` rule is no longer required.
185+
- A user-configured `task: deny` stays sticky: it blocks delegation for the entire subtree below it.
186+
- Permission prompts raised anywhere in the tree appear on the **root session**, so you can answer them without navigating into child sessions. Each prompt carries its origin in `metadata.originSessionID`, `metadata.originAgent`, and `metadata.originDepth`.
187+
- Answering a prompt with `always` sticks to the root session and applies **tree-wide**.
188+
189+
:::note
190+
Child sessions created before nesting support keep their stored `task` deny — resuming one of these older subagent sessions leaves it unable to spawn. The same applies after **raising** `subagent_max_depth`: existing child sessions created at the old limit keep their stored deny. **Lowering** the limit takes effect immediately for all sessions.
191+
:::
192+
193+
---
194+
142195
## Configure
143196

144197
You can customize the built-in agents or create your own through configuration. Agents can be configured in two ways:
@@ -621,6 +674,8 @@ Control which subagents an agent can invoke via the Task tool with `permission.t
621674

622675
When set to `deny`, the subagent is removed from the Task tool description entirely, so the model won't attempt to invoke it.
623676

677+
Task permissions apply at every level of a [nested](#nesting) session tree. The default wildcard `"*": "allow"` is sufficient for an agent — including a subagent — to spawn subagents; an exact `task` rule is no longer required. A `deny` blocks delegation for the entire subtree below the agent.
678+
624679
:::tip
625680
Rules are evaluated in order, and the **last matching rule wins**. In the example above, `orchestrator-planner` matches both `*` (deny) and `orchestrator-*` (allow), but since `orchestrator-*` comes after `*`, the result is `allow`.
626681
:::

‎packages/web/src/content/docs/config.mdx‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -865,6 +865,21 @@ The `experimental` key contains options that are under active development.
865865
Experimental options are not stable. They may change or be removed without notice.
866866
:::
867867

868+
#### Subagent nesting depth
869+
870+
Use `experimental.subagent_max_depth` to control how deep subagents can [nest](/docs/agents#nesting). The root session is depth 1; values are clamped to 1–10.
871+
872+
```json title="opencode.json"
873+
{
874+
"$schema": "https://opencode.ai/config.json",
875+
"experimental": {
876+
"subagent_max_depth": 5
877+
}
878+
}
879+
```
880+
881+
The default is `5`. Set it to `2` to restore the previous behavior (the main session spawns subagents, subagents do not), or to `1` to disable the task tool entirely.
882+
868883
---
869884

870885
## Variables

‎packages/web/src/content/docs/permissions.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,8 @@ When OpenCode prompts for approval, the UI offers three outcomes:
178178

179179
The set of patterns that `always` would approve is provided by the tool (for example, bash approvals typically whitelist a safe command prefix like `git status*`).
180180

181+
When the request comes from a [nested subagent](/docs/agents#nesting), the prompt is attributed to the **root session** of the session tree — you answer it there, without navigating into child sessions. The prompt's `metadata.originSessionID`, `metadata.originAgent`, and `metadata.originDepth` identify the subagent that asked. Answering `always` sticks to the root session and applies tree-wide.
182+
181183
---
182184

183185
## Agents

‎packages/web/src/content/docs/sdk.mdx‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,34 @@ All types are generated from the server's OpenAPI specification and available in
103103

104104
---
105105

106+
### Permission requests in nested session trees
107+
108+
With [subagent nesting](/docs/agents#nesting), the `sessionID` on a permission request refers to the **root session** of the session tree the request came from — not necessarily the session that raised it. For trees of depth ≤ 2 (a main session and its direct subagents) this is identical to previous releases, so most clients are unaffected.
109+
110+
To identify the subagent that actually asked, read the request's `metadata`:
111+
112+
- `metadata.originSessionID` — the session that raised the request
113+
- `metadata.originAgent` — the agent name of that session
114+
- `metadata.originDepth` — its depth in the tree (root session = 1)
115+
116+
These fields are only present when the request was raised below the root. There is **no schema change** — `metadata` was already an open record, so existing clients keep working without regenerating. Clients that attribute requests to a session via `sessionID` should switch to `metadata.originSessionID` when it is present.
117+
118+
```javascript
119+
const events = await client.event.subscribe()
120+
for await (const event of events.stream) {
121+
if (event.type !== "permission.updated") continue
122+
const request = event.properties
123+
// Session to respond on — the root of the tree
124+
const respondOn = request.sessionID
125+
// Session that actually asked — falls back to the root itself
126+
const askedBy = request.metadata.originSessionID ?? request.sessionID
127+
}
128+
```
129+
130+
Respond via `postSessionByIdPermissionsByPermissionId` using the root `sessionID`. An `always` response sticks to the root session and applies to the entire session tree.
131+
132+
---
133+
106134
## Errors
107135
108136
The SDK can throw errors that you can catch and handle:

0 commit comments

Comments
 (0)