> 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.2-sub-agents.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 39.2 Sub-Agents

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~300k tokens, Output \~8k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

The previous section introduced static configuration and parsing of multiple Agents. This section delves into the **Sub-Agent** mechanism—the ability of one Agent to dynamically spawn another Agent to execute specific tasks. This is the most dynamic part of OpenClaw's multi-agent architecture.

> **Sidebar: Sub-Agent Pattern** The sub-agent pattern originates from the **Actor Model** in distributed computing—each Actor is an independent computational unit communicating via message passing. The sub-agent pattern applies this to the AI Agent domain: the main Agent acts like a "manager" delegating tasks to specialized sub-Agents, which report results upon completion. This resembles the `fork` + `wait` semantics in operating systems, but operates at a higher semantic level.

## 39.2.1 Sub-Agent Registry

The lifecycle management of sub-agents is implemented by `subagent-registry.ts`. It maintains records of all active and archived sub-agent runs.

### SubagentRunRecord Data Structure

```typescript
// src/agents/subagent-registry.ts (simplified)

type SubagentRunRecord = {
  runId: string;              // Globally unique run ID (UUID)
  childSessionKey: string;    // Sub-agent session key
  requesterSessionKey: string; // Requester session key
  task: string;               // Task description
  cleanup: "delete" | "keep"; // Cleanup strategy after completion
  label?: string;             // Human-readable label
  createdAt: number;          // Creation timestamp (ms)
  startedAt?: number;         // Actual start time
  endedAt?: number;           // End time
  outcome?: "ok" | "error" | "timeout"; // Final status
  archiveAtMs?: number;       // Archive time point
};
```

Each sub-agent run has complete lifecycle tracking. The `cleanup` field determines behavior after task completion: `"delete"` automatically clears the sub-agent's session record (including transcript files), while `"keep"` preserves it for later review.

### Registration and Lifecycle Listening

```typescript
const RUNS = new Map<string, SubagentRunRecord>();
const ARCHIVED: SubagentRunRecord[] = [];

export function registerSubagentRun(record: SubagentRunRecord) {
  RUNS.set(record.runId, record);
  persistSubagentRuns();    // Async persistence to disk
  startLifecycleListener(); // Ensure listener is active
}
```

After registration, the system immediately persists the record to disk and ensures the lifecycle listener is active.

### Lifecycle Event Stream

Sub-agent state changes are tracked via Gateway's event stream (Server-Sent Events):

```typescript
async function startLifecycleListener() {
  if (listenerActive) return;
  listenerActive = true;

  // Subscribe to Gateway's lifecycle event stream
  const stream = await callGateway({
    method: "events.subscribe",
    params: {
      stream: "lifecycle",
      filter: { /* match sub-agent sessions */ }
    },
  });

  // Handle three lifecycle phases
  for await (const event of stream) {
    const { phase, sessionKey, runId } = event;
    const record = RUNS.get(runId);
    if (!record) continue;

    switch (phase) {
      case "start":
        record.startedAt = Date.now();
        break;
      case "end":
        record.endedAt = Date.now();
        record.outcome = "ok";
        scheduleArchive(record);
        break;
      case "error":
        record.endedAt = Date.now();
        record.outcome = "error";
        scheduleArchive(record);
        break;
    }
    persistSubagentRuns();
  }
}
```

Lifecycle events are broadcast via Gateway's WebSocket event system, encompassing three phases: `start` (Agent begins processing), `end` (normal completion), `error` (abnormal termination).

### Sweeper

A background sweeper runs at 60-second intervals, responsible for archiving and cleaning up expired sub-agent records:

```typescript
const SWEEP_INTERVAL_MS = 60_000;

function startSweeper() {
  setInterval(() => {
    const now = Date.now();
    for (const [runId, record] of RUNS) {
      if (record.archiveAtMs && now >= record.archiveAtMs) {
        RUNS.delete(runId);
        ARCHIVED.push(record);
        finalizeSubagentCleanup(record); // Execute delete or keep
      }
    }
    // Limit archived list size
    while (ARCHIVED.length > 100) {
      ARCHIVED.shift();
    }
    persistSubagentRuns();
  }, SWEEP_INTERVAL_MS);
}
```

`archiveAtMs` defaults to `endedAt + archiveAfterMinutes * 60_000`, where `archiveAfterMinutes` defaults to 60 minutes. This means after a sub-agent completes, its record remains in memory for one hour (for querying and debugging), then gets archived.

### Waiting for Sub-Agent Completion

The main Agent can synchronously wait for sub-agent completion:

```typescript
export async function waitForSubagentCompletion(params: {
  runId: string;
  timeoutMs: number;
}): Promise<{ status: string; startedAt?: number; endedAt?: number }> {
  return callGateway({
    method: "agent.wait",
    params: {
      runId: params.runId,
      timeoutMs: params.timeoutMs,
    },
    timeoutMs: params.timeoutMs + 2000,
  });
}
```

`agent.wait` is a blocking RPC call—the Gateway suspends this request until the target sub-agent completes or times out. Note the `timeoutMs + 2000` design: the Gateway-side timeout is 2 seconds longer than the request parameter, preventing the request itself from timing out prematurely due to network latency.

### Disk Persistence and Recovery

Sub-agent records are persisted to disk, ensuring recovery after Gateway restart:

```typescript
function persistSubagentRuns() {
  const data = {
    runs: Object.fromEntries(RUNS),
    archived: ARCHIVED.slice(-50), // Keep only last 50 archived records
  };
  fs.writeFileSync(PERSIST_PATH, JSON.stringify(data));
}

export function restoreSubagentRunsOnce() {
  if (restored) return;
  restored = true;
  const raw = fs.readFileSync(PERSIST_PATH, "utf-8");
  const data = JSON.parse(raw);
  for (const [runId, record] of Object.entries(data.runs)) {
    RUNS.set(runId, record as SubagentRunRecord);
  }
}
```

`restoreSubagentRunsOnce()` uses a module-level `restored` flag to ensure restoration happens only once. Archived records keep only the last 50 to prevent unbounded disk file growth.

## 39.2.2 sessions\_spawn Tool

Sub-agent creation is accomplished via the `sessions_spawn` tool. This is a tool exposed to AI Agents, allowing them to dynamically spawn sub-agents during conversation.

### Tool Parameters

```typescript
// src/agents/tools/sessions-spawn-tool.ts (simplified)

const TOOL_PARAMS = {
  task: { type: "string", description: "Task description" },
  label: { type: "string", description: "Human-readable label" },
  agentId: { type: "string", description: "Target Agent ID" },
  model: { type: "string", description: "Model override" },
  thinking: { type: "string", description: "Thinking level" },
  runTimeoutSeconds: { type: "number", description: "Timeout (seconds)" },
  cleanup: {
    type: "string",
    enum: ["delete", "keep"],
    description: "Whether to delete session after completion"
  },
};
```

### Cross-Agent Access Control

Not all Agents can spawn arbitrary other Agents. Access control is implemented via `subagents.allowAgents` configuration:

```typescript
// Check if current Agent is allowed to spawn target Agent
const agentConfig = resolveAgentConfig(cfg, currentAgentId);
const allowList = agentConfig?.subagents?.allowAgents;

if (allowList) {
  const isWildcard = allowList.includes("*");
  if (!isWildcard && !allowList.includes(targetAgentId)) {
    throw new Error(
      `Agent "${currentAgentId}" is not allowed to spawn "${targetAgentId}"`
    );
  }
}
```

Security rules:

| Configuration                          | Behavior                             |
| -------------------------------------- | ------------------------------------ |
| `allowAgents: ["*"]`                   | Allow spawning any Agent             |
| `allowAgents: ["coder", "researcher"]` | Only allow spawning specified Agents |
| `allowAgents` not set                  | Use global default policy            |

Additionally, the system prevents **sub-agent nesting** via `isSubagentSessionKey()` check—sub-agents cannot spawn their own sub-agents, avoiding infinite recursion:

```typescript
if (isSubagentSessionKey(currentSessionKey)) {
  throw new Error("Sub-agents cannot spawn further sub-agents");
}
```

### Session Key Generation

Each sub-agent receives a unique session key:

```typescript
const childSessionKey =
  `agent:${targetAgentId}:subagent:${crypto.randomUUID()}`;
```

The format is `agent:{targetAgentId}:subagent:{uuid}`. This key encodes two critical pieces of information: the target Agent's ID and a globally unique identifier. The Gateway parses this key to route sub-agent requests to the correct Agent configuration.

### Model Resolution Chain

The sub-agent's model is resolved through a three-level priority chain:

```
Explicit parameter (model passed in tool call)
    ↓ (not specified)
Agent-level configuration (agents.list[].subagents.model)
    ↓ (not specified)
Global default (defaults.subagents.model)
    ↓ (not specified)
Agent's own primary model
```

After resolution, the model is applied to the sub-agent session via `sessions.patch` RPC:

```typescript
if (resolvedModel) {
  await callGateway({
    method: "sessions.patch",
    params: {
      key: childSessionKey,
      model: resolvedModel,
      thinking: normalizedThinking,
    },
  });
}
```

### Thinking Level Normalization

The `thinking` parameter supports multiple input formats and unifies them:

```typescript
// "high" → "high", "enabled" → "medium", "off" → undefined
function normalizeThinkingLevel(raw?: string) {
  if (!raw) return undefined;
  const normalized = raw.trim().toLowerCase();
  if (normalized === "off" || normalized === "none") return undefined;
  if (normalized === "enabled" || normalized === "on") return "medium";
  return normalized; // "low", "medium", "high"
}
```

### Sub-Agent System Prompt

Each sub-agent receives a special system prompt upon startup, clarifying its role and constraints:

```typescript
export function buildSubagentSystemPrompt(params: {
  requesterSessionKey?: string;
  requesterOrigin?: DeliveryContext;
  childSessionKey: string;
  label?: string;
  task?: string;
}) {
  const lines = [
    "# Subagent Context",
    "",
    "You are a **subagent** spawned by the main agent.",
    "",
    "## Your Role",
    `- You were created to handle: ${taskText}`,
    "- Complete this task. That's your entire purpose.",
    "",
    "## Rules",
    "1. **Stay focused** - Do your assigned task, nothing else",
    "2. **Complete the task** - Your final message will be reported",
    "3. **Don't initiate** - No heartbeats, no proactive actions",
    "4. **Be ephemeral** - You may be terminated after completion.",
    "",
    "## What You DON'T Do",
    "- NO user conversations",
    "- NO external messages (unless explicitly tasked)",
    "- NO cron jobs or persistent state",
    "- NO pretending to be the main agent",
    // ...
  ];
  return lines.join("\n");
}
```

This system prompt ensures sub-agents:

* Focus on assigned tasks
* Don't interact with users without authorization
* Don't create persistent side effects (like scheduled tasks)
* Understand they are temporary and can be destroyed

### Complete spawn Flow

Linking the above components together, the complete execution flow of `sessions_spawn` is as follows:

```
1. Verify permissions (allowAgents check + nesting check)
     ↓
2. Generate childSessionKey
     ↓
3. Resolve model and thinking level
     ↓
4. sessions.patch set model/thinking
     ↓
5. buildSubagentSystemPrompt generate system prompt
     ↓
6. callGateway("agent") start sub-agent
     Parameters: lane=AGENT_LANE_SUBAGENT, deliver=false, spawnedBy=runId
     ↓
7. registerSubagentRun register to registry
     ↓
8. Return { runId, sessionKey } to main Agent
```

`lane=AGENT_LANE_SUBAGENT` tells the Gateway this is a sub-agent run, `deliver=false` means the sub-agent's output doesn't directly deliver to user channels—instead it goes through the announcement process (next subsection) where the main Agent translates it.

## 39.2.3 Sub-Agent Announcement

After a sub-agent completes its task, its results need to be **announced** to the main Agent, which then informs the user in a natural way. `subagent-announce.ts` implements this bridging mechanism.

### Announcement Flow Overview

```
Sub-agent completes
     ↓
runSubagentAnnounceFlow()
     ↓
waitForSessionUsage() — wait for token stats ready
     ↓
buildSubagentStatsLine() — build stats line
     ↓
Build trigger message (containing sub-agent result + stats + instructions)
     ↓
maybeQueueSubagentAnnounce() — decide delivery method
     ↓
┌── steered → inject into current active Agent conversation
├── queued  → put in announcement queue awaiting suitable moment
└── none    → send directly to main Agent
```

### Waiting for Usage Statistics

After a sub-agent completes, token usage may not yet be written to session storage (writing is asynchronous). `waitForSessionUsage()` waits via polling:

```typescript
async function waitForSessionUsage(params: { sessionKey: string }) {
  let entry = loadSessionStore(storePath)[params.sessionKey];
  const hasTokens = () =>
    entry &&
    (typeof entry.totalTokens === "number" ||
     typeof entry.inputTokens === "number" ||
     typeof entry.outputTokens === "number");

  if (hasTokens()) return { entry, storePath };

  // At most 4 × 200ms = 800ms
  for (let attempt = 0; attempt < 4; attempt++) {
    await new Promise((r) => setTimeout(r, 200));
    entry = loadSessionStore(storePath)[params.sessionKey];
    if (hasTokens()) break;
  }
  return { entry, storePath };
}
```

4 retries, 200ms interval each—total maximum wait of 800ms. This is a typical **eventual consistency** waiting pattern: the system doesn't guarantee usage data is immediately available, but converges within reasonable time.

### Stats Line Building

```typescript
async function buildSubagentStatsLine(params: {
  sessionKey: string;
  startedAt?: number;
  endedAt?: number;
}) {
  // ...
  const parts: string[] = [];
  parts.push(`runtime ${formatDurationShort(runtimeMs) ?? "n/a"}`);
  parts.push(`tokens ${totalText} (in ${inputText} / out ${outputText})`);
  if (costText) parts.push(`est ${costText}`);
  parts.push(`sessionKey ${params.sessionKey}`);
  // ...
  return `Stats: ${parts.join(" • ")}`;
}
```

The stats line includes runtime, token consumption, estimated cost, session key, and transcript file path. Cost estimation is based on model pricing information in configuration (`models.providers[provider].models[].cost`).

Formatting utility functions follow human-readable principles:

| Value       | `formatTokenCount` | `formatDurationShort` | `formatUsd` |
| ----------- | ------------------ | --------------------- | ----------- |
| 1,500,000   | `"1.5m"`           | —                     | —           |
| 42,300      | `"42.3k"`          | —                     | —           |
| 185 seconds | —                  | `"3m5s"`              | —           |
| 0.0042      | —                  | —                     | `"$0.0042"` |
| 1.23        | —                  | —                     | `"$1.23"`   |

### Trigger Message Construction

The core of announcement is constructing a **trigger message** to send to the main Agent, letting it naturally translate the results:

```typescript
const triggerMessage = [
  `A background task "${taskLabel}" just ${statusLabel}.`,
  "",
  "Findings:",
  reply || "(no output)",
  "",
  statsLine,
  "",
  "Summarize this naturally for the user. Keep it brief.",
  "Do not mention technical details like tokens or stats.",
  "You can respond with NO_REPLY if no announcement is needed.",
].join("\n");
```

This message contains the sub-agent's complete output, but the final instruction asks the main Agent to **translate** rather than forward directly. Users see the main Agent's natural, fluent summary, not a mechanical technical report.

### Delivery Strategy

`maybeQueueSubagentAnnounce()` decides how to deliver based on the main Agent's current state:

```typescript
async function maybeQueueSubagentAnnounce(params) {
  const queueSettings = resolveQueueSettings({ cfg, channel, sessionEntry });
  const isActive = isEmbeddedPiRunActive(sessionId);

  // Mode 1: steer — inject into current active conversation
  if (shouldSteer) {
    const steered = queueEmbeddedPiMessage(sessionId, triggerMessage);
    if (steered) return "steered";
  }

  // Mode 2: queue — put in queue to wait
  if (isActive && shouldFollowup) {
    enqueueAnnounce({ key, item, settings, send });
    return "queued";
  }

  // Mode 3: none — send directly
  return "none";
}
```

Three delivery modes:

| Mode                   | Condition                                  | Behavior                                                                        |
| ---------------------- | ------------------------------------------ | ------------------------------------------------------------------------------- |
| **steer**              | Main Agent running + steer mode            | Inject message into current Agent turn, Agent can naturally mention it in reply |
| **queued**             | Main Agent running + followup/collect mode | Put in announcement queue, deliver in batch when Agent idle                     |
| **none** / direct send | Main Agent idle                            | Send trigger message immediately, start new Agent turn                          |

### Cleanup and Finalization

The announcement flow's `finally` block handles finalization:

```typescript
finally {
  // Set sub-agent session label
  if (params.label) {
    await callGateway({
      method: "sessions.patch",
      params: { key: childSessionKey, label: params.label },
    });
  }
  // Handle session per cleanup strategy
  if (params.cleanup === "delete") {
    await callGateway({
      method: "sessions.delete",
      params: { key: childSessionKey, deleteTranscript: true },
    });
  }
}
```

## 39.2.4 Announcement Queue

When multiple sub-agents complete simultaneously, their announcements need to be delivered to the main Agent in order, preventing message flooding. `subagent-announce-queue.ts` implements this queue mechanism.

### Queue State

```typescript
type AnnounceQueueState = {
  items: AnnounceQueueItem[];  // Pending announcements
  draining: boolean;           // Whether currently draining
  lastEnqueuedAt: number;      // Last enqueue time
  mode: QueueMode;             // Queue mode
  debounceMs: number;          // Debounce interval (default 1000ms)
  cap: number;                 // Max capacity (default 20)
  dropPolicy: QueueDropPolicy; // Overflow policy
  droppedCount: number;        // Dropped count
  summaryLines: string[];      // Summary lines for dropped messages
  send: (item) => Promise<void>; // Send callback
};
```

### Debounce and Batch Delivery

The queue uses a **debounce** strategy: after enqueuing, wait `debounceMs` (default 1 second); if new messages arrive during this period, reset the timer. This way, multiple sub-agents completing in short succession have their announcements batched together.

When queue mode is `"collect"`, all pending messages are merged into one:

```typescript
if (queue.mode === "collect") {
  // Cross-channel detection: messages from different channels can't merge
  if (isCrossChannel) {
    // Send one by one
    const next = queue.items.shift();
    await queue.send(next);
    continue;
  }
  // Same channel: merge all messages
  const items = queue.items.splice(0, queue.items.length);
  const prompt = buildCollectPrompt({
    title: "[Queued announce messages while agent was busy]",
    items,
    renderItem: (item, idx) => `Queued #${idx + 1}\n${item.prompt}`,
  });
  await queue.send({ ...last, prompt });
}
```

Note **cross-channel safety**: if pending messages come from different channels (e.g., one from Telegram, one from Discord), the system switches to one-by-one delivery mode, avoiding mixing contexts from different channels.

### Overflow Policy

When the queue reaches capacity (default 20 items), `dropPolicy` determines how to handle new messages:

| Policy        | Behavior                                                                              |
| ------------- | ------------------------------------------------------------------------------------- |
| `"summarize"` | Drop message but record summary line, ultimately notify main Agent in summarized form |
| `"new"`       | Drop newly enqueued messages (keep old ones)                                          |
| `"old"`       | Drop oldest messages (accept new ones)                                                |

`"summarize"` is the default policy—even if messages are dropped, the main Agent still receives notification like "N other announcements were summarized," ensuring no information is completely lost.

***

## Section Summary

1. **SubagentRunRecord** tracks complete sub-agent lifecycle: from creation to archival, including timestamps, status, cleanup policy, and other metadata.
2. **Lifecycle listening** updates sub-agent status in real-time via Gateway's lifecycle event stream (start/end/error).
3. **Sweeper** runs at 60-second intervals, archiving timed-out records (default 60 minutes), limiting archived list to 100 items.
4. **sessions\_spawn** tool implements complete spawn flow: permission check → session key generation → model resolution → system prompt injection → Gateway call → registry recording.
5. **Cross-agent security**: `allowAgents` configuration controls which Agents can be spawned, sub-agents cannot nest (preventing infinite recursion).
6. **Sub-agent system prompt** clarifies role constraints: focus on task, don't interact with users, don't create persistent side effects.
7. **Announcement flow** transforms sub-agent results into natural language, delivering to main Agent via steer/queue/direct three strategies.
8. **Announcement queue** uses debounce, batch merging, and cross-channel safety detection to prevent message flooding and ensure smooth user experience.
