> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch39-multi-agent-architecture/39.4-source-deep-dive-subagent-spawn-and-communication.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 39.4 Source Deep Dive: Subagent Spawning and Cross-Agent Communication

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~228,000 tokens, Output \~9,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`); line numbers refer to this commit

***

§39.1–39.3 covered multi-agent design and configuration. This section reads the source for three spawning mechanisms — **static multi-agent**, **subagents**, and **ACP external agents** — and the boundaries between them.

## 39.4.1 Static Multi-Agent: The Isolation Granularity of `agents.list[]`

`agent-scope.ts` parses the `agents.list[]` configuration. Each `agentId` receives a full set of independent resources:

| Resource        | Default / notes                                        |
| --------------- | ------------------------------------------------------ |
| workspace       | `<stateDir>/workspace-<id>` (`agent-scope.ts:256-272`) |
| agentDir        | Independent **auth profiles** and **session storage**  |
| Models          | Independent primary model plus fallback chain          |
| Skill filtering | Independently configured                               |
| Tool policy     | Independently configured (layer 4 of §22.5.1's seven)  |

**Routing works off the sessionKey prefix**: `agent:<id>:...` decides which agent a message belongs to.

Note that an independent agentDir means **independent auth profiles** — you can give a work agent the company account and a personal agent your own, with their cooldown states and round-robin pointers entirely separate (§16.5).

## 39.4.2 Subagents: `sessions_spawn` and Push-Mode Notification

### Spawning and depth limits

`subagent-spawn.ts` starts a new session through the gateway's `agent` RPC with `runtime="subagent"`.

**It carries a depth limit** (`subagent-spawn.ts:321`): exceeding `maxSpawnDepth` is rejected outright.

That defends against a **fork bomb** — subagents spawning subagents, expanding exponentially. In an agent system this isn't a theoretical risk: a prompt that says "break the task down and delegate to subagents," if inherited by the subagent, recurses indefinitely, burning tokens at every level.

### Notification is push-mode, and the wording isn't polite

```ts
// src/agents/subagent-spawn.ts:82-83
export const SUBAGENT_SPAWN_ACCEPTED_NOTE =
  "Auto-announce is push-based. After spawning children, do NOT call sessions_list,
   sessions_history, exec sleep, or any polling tool. Wait for completion events...";
```

The bluntness of that wording tells you it's a repeatedly-triggered behavior. The model's default instinct is "I delegated a task, I should go check whether it's done" — so it starts calling `sessions_list` every few seconds, or worse, `exec sleep 10` followed by another check.

**Every poll is an entire LLM turn.** Ten polls can cost more than the subtask itself.

The handling is worth learning from: **rather than forbidding polling through tool permissions (too blunt), it states the mechanism explicitly in the system prompt and prohibits the specific behaviors.** When instructing a model, **"tell it the alternative" works far better than a bare prohibition.**

### Idempotency keys for completion notifications

The announce path (`subagent-announce*.ts` + `subagent-registry*.ts`) injects a subagent's completion event into the parent session **as a user message**.

Replay protection comes from an idempotency key:

```ts
// src/agents/announce-idempotency.ts:6-8
export function buildAnnounceIdFromChildRun(params: AnnounceIdFromChildRunParams): string {
  return `v1:${params.childSessionKey}:${params.childRunId}`;
}
```

**Child session key plus run id form a naturally unique idempotency key.** Queue retries and process restarts will never deliver "completed" to the parent twice.

The `v1:` prefix is worth noting too — reserving a version slot in the key so a future change to the key structure won't collide with old keys.

### What about late events

If the parent agent already replied to the user before all announces arrived, what happens to a late completion event?

The convention is to **swallow it silently with `NO_REPLY`** — the parent receives the event but produces no user-visible output.

That's another application of §44.5.4's traceless-turn thinking: **a background event's visibility is determined by whether it still matters.** The task has been wrapped up; a stray "oh, and that other subtask finished too" only confuses.

## 39.4.3 ACP Spawning: Delegating to an External Agent

`acp-spawn.ts` delegates a task to an external ACP-protocol agent (Claude Code, for instance) with `runtime="acp"`. It can optionally bind to a chat thread to form a persistent session.

### The security boundary is stated explicitly

```
(semantics of acp-spawn.ts:99-118)
ACP runs on the host machine
  → sandboxed sessions are forbidden from spawning ACP
  → sandbox="require" has no effect on ACP
  → if you want isolation, use a subagent
```

That boundary is important enough to unpack.

Suppose it didn't exist: a session confined to a sandbox could use `sessions_spawn(runtime="acp")` to delegate a task to Claude Code on the host — **and the sandbox is bypassed.**

So the rule is: **a sandboxed session may only spawn subagents (also in the sandbox), never ACP (on the host).**

The `sandbox="require"` clause is especially important — it isn't "ACP will try its best to honor the sandbox request," it's an **explicit declaration that the parameter has no effect on the ACP path**, so callers can't believe they're protected.

> Consistent with §44.4's trust model: **better to say plainly "there is no protection here" than to hand out a switch that looks effective and isn't.**

### Streaming relay

`acp-spawn-parent-stream.ts` supports relaying a subagent's streaming output **live back to the parent session's channel**.

So you can, from Telegram, have the agent delegate a coding task to Claude Code and watch Claude Code's output stream back into Telegram.

## 39.4.4 Steering's Wiring

§44.5.1 covered steer semantics. It appears in the multi-agent chapter because **it's fundamentally another mechanism for injecting a message into a running session.**

The wiring point is `attempt.ts:1552-1560`: the exposed `queueHandle.queueMessage` calls pi's `session.steer(text)` directly.

The semantics (`docs/concepts/agent.md`):

```
queued messages are checked after each tool call
   ↓ a steering message is found
skip all remaining tool calls in the current assistant message
   (terminating them with a "Skipped due to queued user message" error result)
   ↓
insert the user's new message into the loop
```

**This is a capability messaging products must have and CLI tools usually don't.**

The difference is the interaction shape: at a CLI the user watches a terminal and hits Ctrl-C to start over when impatient; in a chat channel the user simply sends the next message, and the system has to figure out whether it's an interjection or a new task.

What's interesting is that subagent completion notifications (§39.4.2) and steering use the **same injection channel** — both push a user message into a running session. The former originates from the system, the latter from the user.

***

## Section Summary

1. **Static multi-agent isolation is fine-grained**: each `agentId` gets its own workspace, agentDir (**including independent auth profiles and session storage**), model chain, skill filtering, and tool policy; routing works off the `agent:<id>:` sessionKey prefix.
2. **Subagents carry a depth limit against fork bombs** — a "delegate to subagents" prompt inherited by the subagent recurses indefinitely, burning tokens.
3. **Completion notification is push-mode, with polling explicitly forbidden in the system prompt** (`sessions_list` / `exec sleep`); every poll is a full LLM turn, potentially costing more than the subtask. When instructing a model, **"explain the mechanism and offer the alternative" beats a bare prohibition.**
4. **The idempotency key is child session key + run id** — naturally unique, so queue retries and process restarts never double-announce; the `v1:` prefix reserves a version slot in the key structure.
5. **Late completion events are swallowed with `NO_REPLY`** — a background event's visibility depends on whether it still matters (§44.5.4's traceless-turn thinking).
6. **ACP's security boundary is hard**: ACP runs on the host, so **sandboxed sessions are forbidden from spawning ACP**, and `sandbox="require"` is **explicitly ineffective** — better to say plainly there's no protection than to hand out a switch that looks effective.
7. **Steering and subagent completion notifications share one injection channel** (pushing a user message into a running session); the only difference is whether the message comes from a user or the system.
