* refactor: remove stale file-backed shims * fix: harden sqlite state ci boundaries * refactor: store matrix idb snapshots in sqlite * fix: satisfy rebased CI guardrails * refactor: store current conversation bindings in sqlite table * refactor: store tui last sessions in sqlite table * refactor: reset sqlite schema history * refactor: drop unshipped sqlite table migration * refactor: remove plugin index file rollback * refactor: drop unshipped sqlite sidecar migrations * refactor: remove runtime commitments kv migration * refactor: preserve kysely sync result types * refactor: drop unshipped sqlite schema migration table * test: keep session usage coverage sqlite-backed * refactor: keep sqlite migration doctor-only * refactor: isolate device legacy imports * refactor: isolate push voicewake legacy imports * refactor: isolate remaining runtime legacy imports * refactor: tighten sqlite migration guardrails * test: cover sqlite persisted enum parsing * refactor: isolate legacy update and tui imports * refactor: tighten sqlite state ownership * refactor: move legacy imports behind doctor * refactor: remove legacy session row lookup * refactor: canonicalize memory transcript locators * refactor: drop transcript path scope fallbacks * refactor: drop runtime legacy session delivery pruning * refactor: store tts prefs only in sqlite * refactor: remove cron store path runtime * refactor: use cron sqlite store keys * refactor: rename telegram message cache scope * refactor: read memory dreaming status from sqlite * refactor: rename cron status store key * refactor: stop remembering transcript file paths * test: use sqlite locators in agent fixtures * refactor: remove file-shaped commitments and cron store surfaces * refactor: keep compaction transcript handles out of session rows * refactor: derive transcript handles from session identity * refactor: derive runtime transcript handles * refactor: remove gateway session locator reads * refactor: remove transcript locator from session rows * refactor: store raw stream diagnostics in sqlite * refactor: remove file-shaped transcript rotation * refactor: hide legacy trajectory paths from runtime * refactor: remove runtime transcript file bridges * refactor: repair database-first rebase fallout * refactor: align tests with database-first state * refactor: remove transcript file handoffs * refactor: sync post-compaction memory by transcript scope * refactor: run codex app-server sessions by id * refactor: bind codex runtime state by session id * refactor: pass memory transcripts by sqlite scope * refactor: remove transcript locator cleanup leftovers * test: remove stale transcript file fixtures * refactor: remove transcript locator test helper * test: make cron sqlite keys explicit * test: remove cron runtime store paths * test: remove stale session file fixtures * test: use sqlite cron keys in diagnostics * refactor: remove runtime delivery queue backfill * test: drop fake export session file mocks * refactor: rename acp session read failure flag * refactor: rename acp row session key * refactor: remove session store test seams * refactor: move legacy session parser tests to doctor * refactor: reindex managed memory in place * refactor: drop stale session store wording * refactor: rename session row helpers * refactor: rename sqlite session entry modules * refactor: remove transcript locator leftovers * refactor: trim file-era audit wording * refactor: clean managed media through sqlite * fix: prefer explicit agent for exports * fix: use prepared agent for session resets * fix: canonicalize legacy codex binding import * test: rename state cleanup helper * docs: align backup docs with sqlite state * refactor: drop legacy Pi usage auth fallback * refactor: move legacy auth profile imports to doctor * refactor: keep Pi model discovery auth in memory * refactor: remove MSTeams legacy learning key fallback * refactor: store model catalog config in sqlite * refactor: use sqlite model catalog at runtime * refactor: remove model json compatibility aliases * refactor: store auth profiles in sqlite * refactor: seed copied auth profiles in sqlite * refactor: make auth profile runtime sqlite-addressed * refactor: migrate hermes secrets into sqlite auth store * refactor: move plugin install config migration to doctor * refactor: rename plugin index audit checks * test: drop auth file assumptions * test: remove legacy transcript file assertions * refactor: drop legacy cli session aliases * refactor: store skill uploads in sqlite * refactor: keep subagent attachments in sqlite vfs * refactor: drop subagent attachment cleanup state * refactor: move legacy session aliases to doctor * refactor: require node 24 for sqlite state runtime * refactor: move provider caches into sqlite state * fix: harden virtual agent filesystem * refactor: enforce database-first runtime state * refactor: rename compaction transcript rotation setting * test: clean sqlite refactor test types * refactor: consolidate sqlite runtime state * refactor: model session conversations in sqlite * refactor: stop deriving cron delivery from session keys * refactor: stop classifying sessions from key shape * refactor: hydrate announce targets from typed delivery * refactor: route heartbeat delivery from typed sqlite context * refactor: tighten typed sqlite session routing * refactor: remove session origin routing shadow * refactor: drop session origin shadow fixtures * perf: query sqlite vfs paths by prefix * refactor: use typed conversation metadata for sessions * refactor: prefer typed session routing metadata * refactor: require typed session routing metadata * refactor: resolve group tool policy from typed sessions * refactor: delete dead session thread info bridge * Show Codex subscription reset times in channel errors (#80456) * feat(plugin-sdk): consolidate session workflow APIs * fix(agents): allow read-only agent mount reads * [codex] refresh plugin regression fixtures * fix(agents): restore compaction gateway logs * test: tighten gateway startup assertions * Redact persisted secret-shaped payloads [AI] (#79006) * test: tighten device pair notify assertions * test: tighten hermes secret assertions * test: assert matrix client error shapes * test: assert config compat warnings * fix(heartbeat): remap cron-run exec events to session keys (#80214) * fix(codex): route btw through native side threads * fix(auth): accept friendly OpenAI order for Codex profiles * fix(codex): rotate auth profiles inside harness * fix: keep browser status page probe within timeout * test: assert agents add outputs * test: pin cron read status * fix(agents): avoid Pi resource discovery stalls Co-authored-by: dataCenter430 <titan032000@gmail.com> * fix: retire timed-out codex app-server clients * test: tighten qa lab runtime assertions * test: check security fix outputs * test: verify extension runtime messages * feat(wake): expose typed sessionKey on wake protocol + system event CLI * fix(gateway): await session_end during shutdown drain and track channel + compaction lifecycle paths (#57790) * test: guard talk consult call helper * fix(codex): scale context engine projection (#80761) * fix(codex): scale context engine projection * fix: document Codex context projection scaling * fix: document Codex context projection scaling * fix: document Codex context projection scaling * fix: document Codex context projection scaling * chore: align Codex projection changelog * chore: realign Codex projection changelog * fix: isolate Codex projection patch --------- Co-authored-by: Eva (agent) <eva+agent-78055@100yen.org> Co-authored-by: Josh Lehman <josh@martian.engineering> * refactor: move agent runtime state toward piless * refactor: remove cron session reaper * refactor: move session management to sqlite * refactor: finish database-first state migration * chore: refresh generated sqlite db types * refactor: remove stale file-backed shims * test: harden kysely type coverage # Conflicts: # .agents/skills/kysely-database-access/SKILL.md # src/infra/kysely-sync.types.test.ts # src/proxy-capture/store.sqlite.test.ts # src/state/openclaw-agent-db.test.ts # src/state/openclaw-state-db.test.ts * refactor: remove cron store path runtime * refactor: keep compaction transcript handles out of session rows * refactor: derive embedded transcripts from sqlite identity * refactor: remove embedded transcript locator handoff * refactor: remove runtime transcript file bridges * refactor: remove transcript file handoffs * refactor: remove MSTeams legacy learning key fallback * refactor: store model catalog config in sqlite * refactor: use sqlite model catalog at runtime # Conflicts: # docs/cli/secrets.md # docs/gateway/authentication.md # docs/gateway/secrets.md * fix: keep oauth sibling sync sqlite-local # Conflicts: # src/commands/onboard-auth.test.ts * refactor: remove task session store maintenance # Conflicts: # src/commands/tasks.ts * refactor: keep diagnostics in state sqlite * refactor: enforce database-first runtime state * refactor: consolidate sqlite runtime state * Show Codex subscription reset times in channel errors (#80456) * fix(codex): refresh subscription limit resets * fix(codex): format reset times for channels * Update CHANGELOG with latest changes and fixes Updated CHANGELOG with recent fixes and improvements. * fix(codex): keep command load failures on codex surface * fix(codex): format account rate limits as rows * fix(codex): summarize account limits as usage status * fix(codex): simplify account limit status * test: tighten subagent announce queue assertion * test: tighten session delete lifecycle assertions * test: tighten cron ops assertions * fix: track cron execution milestones * test: tighten hermes secret assertions * test: assert matrix sync store payloads * test: assert config compat warnings * fix(codex): align btw side thread semantics * fix(codex): honor codex fallback blocking * fix(agents): avoid Pi resource discovery stalls * test: tighten codex event assertions * test: tighten cron assertions * Fix Codex app-server OAuth harness auth * refactor: move agent runtime state toward piless * refactor: move device and push state to sqlite * refactor: move runtime json state imports to doctor * refactor: finish database-first state migration * chore: refresh generated sqlite db types * refactor: clarify cron sqlite store keys * refactor: remove stale file-backed shims * refactor: bind codex runtime state by session id * test: expect sqlite trajectory branch export * refactor: rename session row helpers * fix: keep legacy device identity import in doctor * refactor: enforce database-first runtime state * refactor: consolidate sqlite runtime state * build: align pi contract wrappers * chore: repair database-first rebase * refactor: remove session file test contracts * test: update gateway session expectations * refactor: stop routing from session compatibility shadows * refactor: stop persisting session route shadows * refactor: use typed delivery context in clients * refactor: stop echoing session route shadows * refactor: repair embedded runner rebase imports # Conflicts: # src/agents/pi-embedded-runner/run/attempt.tool-call-argument-repair.ts * refactor: align pi contract imports * refactor: satisfy kysely sync helper guard * refactor: remove file transcript bridge remnants * refactor: remove session locator compatibility * refactor: remove session file test contracts * refactor: keep rebase database-first clean * refactor: remove session file assumptions from e2e * docs: clarify database-first goal state * test: remove legacy store markers from sqlite runtime tests * refactor: remove legacy store assumptions from runtime seams * refactor: align sqlite runtime helper seams * test: update memory recall sqlite audit mock * refactor: align database-first runtime type seams * test: clarify doctor cron legacy store names * fix: preserve sqlite session route projections * test: fix copilot token cache test syntax * docs: update database-first proof status * test: align database-first test fixtures * docs: update database-first proof status * refactor: clean extension database-first drift * test: align agent session route proof * test: clarify doctor legacy path fixtures * chore: clean database-first changed checks * chore: repair database-first rebase markers * build: allow baileys git subdependency * chore: repair exp-vfs rebase drift * chore: finish exp-vfs rebase cleanup * chore: satisfy rebase lint drift * chore: fix qqbot rebase type seam * chore: fix rebase drift leftovers * fix: keep auth profile oauth secrets out of sqlite * fix: repair rebase drift tests * test: stabilize pairing request ordering * test: use source manifests in plugin contract checks * fix: restore gateway session metadata after rebase * fix: repair database-first rebase drift * fix: clean up database-first rebase fallout * test: stabilize line quick reply receipt time * fix: repair extension rebase drift * test: keep transcript redaction tests sqlite-backed * fix: carry injected transcript redaction through sqlite * chore: clean database branch rebase residue * fix: repair database branch CI drift * fix: repair database branch CI guard drift * fix: stabilize oauth tls preflight test * test: align database branch fast guards * test: repair build artifact boundary guards * chore: clean changelog rebase markers --------- Co-authored-by: pashpashpash <nik@vault77.ai> Co-authored-by: Eva <eva@100yen.org> Co-authored-by: stainlu <stainlu@newtype-ai.org> Co-authored-by: Jason Zhou <jason.zhou.design@gmail.com> Co-authored-by: Ruben Cuevas <hi@rubencu.com> Co-authored-by: Pavan Kumar Gondhi <pavangondhi@gmail.com> Co-authored-by: Shakker <shakkerdroid@gmail.com> Co-authored-by: Kaspre <36520309+Kaspre@users.noreply.github.com> Co-authored-by: dataCenter430 <titan032000@gmail.com> Co-authored-by: Kaspre <kaspre@gmail.com> Co-authored-by: pandadev66 <nova.full.stack@outlook.com> Co-authored-by: Eva <admin@100yen.org> Co-authored-by: Eva (agent) <eva+agent-78055@100yen.org> Co-authored-by: Josh Lehman <josh@martian.engineering> Co-authored-by: jeffjhunter <support@aipersonamethod.com>
32 KiB
summary, read_when, title, sidebarTitle
| summary | read_when | title | sidebarTitle | |||
|---|---|---|---|---|---|---|
| Spawn isolated background agent runs that announce results back to the requester chat |
|
Sub-agents | Sub-agents |
Sub-agents are background agent runs spawned from an existing agent run.
They run in their own session (agent:<agentId>:subagent:<uuid>) and,
when finished, announce their result back to the requester chat
channel. Each sub-agent run is tracked as a
background task.
Primary goals:
- Parallelize "research / long task / slow tool" work without blocking the main run.
- Keep sub-agents isolated by default (session separation + optional sandboxing).
- Keep the tool surface hard to misuse: sub-agents do not get session tools by default.
- Support configurable nesting depth for orchestrator patterns.
Slash command
Use /subagents to inspect or control sub-agent runs for the current
session:
/subagents list
/subagents kill <id|#|all>
/subagents log <id|#> [limit] [tools]
/subagents info <id|#>
/subagents send <id|#> <message>
/subagents steer <id|#> <message>
/subagents spawn <agentId> <task> [--model <model>] [--thinking <level>]
Use top-level /steer <message> to steer the current requester session's active run. Use /subagents steer <id|#> <message> when the target is a child run.
/subagents info shows run metadata (status, timestamps, session id, cleanup).
Use sessions_history for a bounded, safety-filtered recall view; inspect the
SQLite transcript rows or export a debug bundle when you need the raw full
transcript.
Thread binding controls
These commands work on channels that support persistent thread bindings. See Thread supporting channels below.
/focus <subagent-label|session-key|session-id|session-label>
/unfocus
/agents
/session idle <duration|off>
/session max-age <duration|off>
Spawn behavior
/subagents spawn starts a background sub-agent as a user command (not an
internal relay) and sends one final completion update back to the
requester chat when the run finishes.
- `Result` — latest visible `assistant` reply text, otherwise sanitized latest tool/toolResult text. Terminal failed runs do not reuse captured reply text.
- `Status` — `completed successfully` / `failed` / `timed out` / `unknown`.
- Compact runtime/token stats.
- A delivery instruction telling the requester agent to rewrite in normal assistant voice (not forward raw internal metadata).
- `--model` and `--thinking` override defaults for that specific run.
- Use `info`/`log` to inspect details and output after completion.
- `/subagents spawn` is one-shot mode (`mode: "run"`). For persistent thread-bound sessions, use `sessions_spawn` with `thread: true` and `mode: "session"`.
- For ACP harness sessions (Claude Code, Gemini CLI, OpenCode, or explicit Codex ACP/acpx), use `sessions_spawn` with `runtime: "acp"` when the tool advertises that runtime. See [ACP delivery model](/tools/acp-agents#delivery-model) when debugging completions or agent-to-agent loops. When the `codex` plugin is enabled, Codex chat/thread control should prefer `/codex ...` over ACP unless the user explicitly asks for ACP/acpx.
- OpenClaw hides `runtime: "acp"` until ACP is enabled, the requester is not sandboxed, and a backend plugin such as `acpx` is loaded. `runtime: "acp"` expects an external ACP harness id, or an `agents.list[]` entry with `runtime.type="acp"`; use the default sub-agent runtime for normal OpenClaw config agents from `agents_list`.
Context modes
Native sub-agents start isolated unless the caller explicitly asks to fork the current transcript.
| Mode | When to use it | Behavior |
|---|---|---|
isolated |
Fresh research, independent implementation, slow tool work, or anything that can be briefed in the task text | Creates a clean child transcript. This is the default and keeps token use lower. |
fork |
Work that depends on the current conversation, prior tool results, or nuanced instructions already present in the requester transcript | Branches the requester transcript into the child session before the child starts. |
Use fork sparingly. It is for context-sensitive delegation, not a
replacement for writing a clear task prompt.
Tool: sessions_spawn
Starts a sub-agent run with deliver: false on the global subagent lane,
then runs an announce step and posts the announce reply to the requester
chat channel.
Availability depends on the caller's effective tool policy. The coding and
full profiles expose sessions_spawn by default. The messaging profile
does not; add tools.alsoAllow: ["sessions_spawn", "sessions_yield", "subagents"] or use tools.profile: "coding" for agents that should delegate
work. Channel/group, provider, sandbox, and per-agent allow/deny policies can
still remove the tool after the profile stage. Use /tools from the same
session to confirm the effective tool list.
Defaults:
- Model: inherits the caller unless you set
agents.defaults.subagents.model(or per-agentagents.list[].subagents.model); an explicitsessions_spawn.modelstill wins. - Thinking: inherits the caller unless you set
agents.defaults.subagents.thinking(or per-agentagents.list[].subagents.thinking); an explicitsessions_spawn.thinkingstill wins. - Run timeout: if
sessions_spawn.runTimeoutSecondsis omitted, OpenClaw usesagents.defaults.subagents.runTimeoutSecondswhen set; otherwise it falls back to0(no timeout). - Task delivery: native sub-agents receive the delegated task in their first visible
[Subagent Task]message. The sub-agent system prompt carries runtime rules and routing context, not a hidden duplicate of the task.
Delegation prompt mode
agents.defaults.subagents.delegationMode controls prompt guidance only; it does not change tool policy or enforce delegation.
suggest(default): keep the standard prompt nudge to use sub-agents for larger or slower work.prefer: tell the main agent to stay responsive and delegate anything more involved than a direct reply throughsessions_spawn.
Per-agent overrides use agents.list[].subagents.delegationMode.
{
agents: {
defaults: {
subagents: {
delegationMode: "prefer",
maxConcurrent: 4,
},
},
list: [
{
id: "coordinator",
subagents: { delegationMode: "prefer" },
},
],
},
}
Tool parameters
The task description for the sub-agent. Optional stable handle for later `subagents` targeting. Must match `[a-z][a-z0-9_]{0,63}` and cannot be reserved targets such as `last` or `all`. Prefer it when the coordinator may need to steer, kill, or identify a specific child after spawning several children. Optional human-readable label. Spawn under another agent id when allowed by `subagents.allowAgents`. `acp` is only for external ACP harnesses (`claude`, `droid`, `gemini`, `opencode`, or explicitly requested Codex ACP/acpx) and for `agents.list[]` entries whose `runtime.type` is `acp`. ACP-only. Resumes an existing ACP harness session when `runtime: "acp"`; ignored for native sub-agent spawns. ACP-only. Streams ACP run output to the parent session when `runtime: "acp"`; omit for native sub-agent spawns. Override the sub-agent model. Invalid values are skipped and the sub-agent runs on the default model with a warning in the tool result. Override thinking level for the sub-agent run. Defaults to `agents.defaults.subagents.runTimeoutSeconds` when set, otherwise `0`. When set, the sub-agent run is aborted after N seconds. When `true`, requests channel thread binding for this sub-agent session. If `thread: true` and `mode` omitted, default becomes `session`. `mode: "session"` requires `thread: true`. `"delete"` archives immediately after announce (still keeps the transcript via rename). `require` rejects spawn unless the target child runtime is sandboxed. `fork` branches the requester's current transcript into the child session. Native sub-agents only. Thread-bound spawns default to `fork`; non-thread spawns default to `isolated`. `sessions_spawn` does **not** accept channel-delivery params (`target`, `channel`, `to`, `threadId`, `replyTo`, `transport`). For delivery, use `message`/`sessions_send` from the spawned run.Task names and targeting
taskName is a model-facing handle for orchestration, not a session key.
Use it for stable child names such as review_subagents,
linux_validation, or docs_update when a coordinator may need to steer
or kill that child later.
Target resolution accepts exact taskName matches and unambiguous
prefixes. Matching is scoped to the same active/recent target window used
by numbered /subagents targets, so a stale completed child does not make
a reused handle ambiguous. If two active or recent children share the same
taskName, the target is ambiguous; use the list index, session key, or
run id instead.
The reserved targets last and all are not valid taskName values
because they already have control meanings.
Tool: sessions_yield
Ends the current model turn and waits for runtime events, primarily sub-agent completion events, to arrive as the next message. Use it after spawning required child work when the requester cannot produce a final answer until those completions arrive.
sessions_yield is the waiting primitive. Do not replace it with polling
loops over subagents, sessions_list, sessions_history, shell
sleep, or process polling just to detect child completion.
Only use sessions_yield when the session's effective tool list includes
it. Some minimal or custom tool profiles may expose sessions_spawn and
subagents without exposing sessions_yield; in that case, do not invent
a polling loop just to wait for completion.
When active children exist, OpenClaw injects a compact runtime-generated
Active Subagents prompt block into normal turns so the requester can see
the current child sessions, run ids, statuses, labels, tasks, and
taskName aliases without polling. The task and label fields in that
block are quoted as data, not instructions, because they can originate
from user/model-provided spawn arguments.
Tool: subagents
Lists, steers, or kills spawned sub-agent runs owned by the requester session. It is scoped to the current requester; a child can only see/control its own controlled children.
Use subagents for on-demand status, debugging, steering, or killing.
Use sessions_yield to wait for completion events.
Thread-bound sessions
When thread bindings are enabled for a channel, a sub-agent can stay bound to a thread so follow-up user messages in that thread keep routing to the same sub-agent session.
Thread supporting channels
Discord is currently the only supported channel. It supports
persistent thread-bound subagent sessions (sessions_spawn with
thread: true), manual thread controls (/focus, /unfocus, /agents,
/session idle, /session max-age), and adapter keys
channels.discord.threadBindings.enabled,
channels.discord.threadBindings.idleHours,
channels.discord.threadBindings.maxAgeHours, and
channels.discord.threadBindings.spawnSessions.
Quick flow
`sessions_spawn` with `thread: true` (and optionally `mode: "session"`). OpenClaw creates or binds a thread to that session target in the active channel. Replies and follow-up messages in that thread route to the bound session. Use `/session idle` to inspect/update inactivity auto-unfocus and `/session max-age` to control the hard cap. Use `/unfocus` to detach manually.Manual controls
| Command | Effect |
|---|---|
/focus <target> |
Bind the current thread (or create one) to a sub-agent/session target |
/unfocus |
Remove the binding for the current bound thread |
/agents |
List active runs and binding state (thread:<id> or unbound) |
/session idle |
Inspect/update idle auto-unfocus (focused bound threads only) |
/session max-age |
Inspect/update hard cap (focused bound threads only) |
Config switches
- Global default:
session.threadBindings.enabled,session.threadBindings.idleHours,session.threadBindings.maxAgeHours. - Channel override and spawn auto-bind keys are adapter-specific. See Thread supporting channels above.
See Configuration reference and Slash commands for current adapter details.
Allowlist
List of agent ids that can be targeted via explicit `agentId` (`["*"]` allows any). Default: only the requester agent. If you set a list and still want the requester to spawn itself with `agentId`, include the requester id in the list. Default target-agent allowlist used when the requester agent does not set its own `subagents.allowAgents`. Block `sessions_spawn` calls that omit `agentId` (forces explicit profile selection). Per-agent override: `agents.list[].subagents.requireAgentId`. Per-call timeout for gateway `agent` announce delivery attempts. Values are positive integer milliseconds and are clamped to the platform-safe timer maximum. Transient retries can make the total announce wait longer than one configured timeout.If the requester session is sandboxed, sessions_spawn rejects targets
that would run unsandboxed.
Discovery
Use agents_list to see which agent ids are currently allowed for
sessions_spawn. The response includes each listed agent's effective
model and embedded runtime metadata so callers can distinguish PI, Codex
app-server, and other configured native runtimes.
Auto-archive
- Sub-agent sessions are automatically archived after
agents.defaults.subagents.archiveAfterMinutes(default60). - Archive uses
sessions.deleteto remove the SQLite session row and transcript rows. cleanup: "delete"deletes the child SQLite session immediately after announce.- Auto-archive is best-effort; pending timers are lost if the gateway restarts.
runTimeoutSecondsdoes not auto-archive; it only stops the run. The session remains until auto-archive.- Auto-archive applies equally to depth-1 and depth-2 sessions.
- Browser cleanup is separate from archive cleanup: tracked browser tabs/processes are best-effort closed when the run finishes, even if the transcript/session record is kept.
Nested sub-agents
By default, sub-agents cannot spawn their own sub-agents
(maxSpawnDepth: 1). Set maxSpawnDepth: 2 to enable one level of
nesting — the orchestrator pattern: main → orchestrator sub-agent →
worker sub-sub-agents.
{
agents: {
defaults: {
subagents: {
maxSpawnDepth: 2, // allow sub-agents to spawn children (default: 1)
maxChildrenPerAgent: 5, // max active children per agent session (default: 5)
maxConcurrent: 8, // global concurrency lane cap (default: 8)
runTimeoutSeconds: 900, // default timeout for sessions_spawn when omitted (0 = no timeout)
announceTimeoutMs: 120000, // per-call gateway announce timeout
},
},
},
}
Depth levels
| Depth | Session key shape | Role | Can spawn? |
|---|---|---|---|
| 0 | agent:<id>:main |
Main agent | Always |
| 1 | agent:<id>:subagent:<uuid> |
Sub-agent (orchestrator when depth 2 allowed) | Only if maxSpawnDepth >= 2 |
| 2 | agent:<id>:subagent:<uuid>:subagent:<uuid> |
Sub-sub-agent (leaf worker) | Never |
Announce chain
Results flow back up the chain:
- Depth-2 worker finishes → announces to its parent (depth-1 orchestrator).
- Depth-1 orchestrator receives the announce, synthesizes results, finishes → announces to main.
- Main agent receives the announce and delivers to the user.
Each level only sees announces from its direct children.
**Operational guidance:** start child work once and wait for completion events instead of building poll loops around `sessions_list`, `sessions_history`, `/subagents list`, or `exec` sleep commands. `sessions_list` and `/subagents list` keep child-session relationships focused on live work — live children remain attached, ended children stay visible for a short recent window, and stale store-only child links are ignored after their freshness window. This prevents old `spawnedBy` / `parentSessionKey` metadata from resurrecting ghost children after restart. If a child completion event arrives after you already sent the final answer, the correct follow-up is the exact silent token `NO_REPLY` / `no_reply`.Tool policy by depth
- Role and control scope are written into session metadata at spawn time. That keeps flat or restored session keys from accidentally regaining orchestrator privileges.
- Depth 1 (orchestrator, when
maxSpawnDepth >= 2): getssessions_spawn,subagents,sessions_list,sessions_historyso it can manage its children. Other session/system tools remain denied. - Depth 1 (leaf, when
maxSpawnDepth == 1): no session tools (current default behavior). - Depth 2 (leaf worker): no session tools —
sessions_spawnis always denied at depth 2. Cannot spawn further children.
Per-agent spawn limit
Each agent session (at any depth) can have at most maxChildrenPerAgent
(default 5) active children at a time. This prevents runaway fan-out
from a single orchestrator.
Cascade stop
Stopping a depth-1 orchestrator automatically stops all its depth-2 children:
/stopin the main chat stops all depth-1 agents and cascades to their depth-2 children./subagents kill <id>stops a specific sub-agent and cascades to its children./subagents kill allstops all sub-agents for the requester and cascades.
Authentication
Sub-agent auth is resolved by agent id, not by session type:
- The sub-agent session key is
agent:<agentId>:subagent:<uuid>. - The auth store is loaded from that agent's
agentDir. - The main agent's auth profiles are merged in as a fallback; agent profiles override main profiles on conflicts.
The merge is additive, so main profiles are always available as fallbacks. Fully isolated auth per agent is not supported yet.
Announce
Sub-agents report back via an announce step:
- The announce step runs inside the sub-agent session (not the requester session).
- If the sub-agent replies exactly
ANNOUNCE_SKIP, nothing is posted. - If the latest assistant text is the exact silent token
NO_REPLY/no_reply, announce output is suppressed even if earlier visible progress existed.
Delivery depends on requester depth:
- Top-level requester sessions use a follow-up
agentcall with external delivery (deliver=true). - Nested requester subagent sessions receive an internal follow-up injection (
deliver=false) so the orchestrator can synthesize child results in-session. - If a nested requester subagent session is gone, OpenClaw falls back to that session's requester when available.
For top-level requester sessions, completion-mode direct delivery first resolves any bound conversation/thread route and hook override, then fills missing channel-target fields from the requester session's stored route. That keeps completions on the right chat/topic even when the completion origin only identifies the channel.
Child completion aggregation is scoped to the current requester run when building nested completion findings, preventing stale prior-run child outputs from leaking into the current announce. Announce replies preserve thread/topic routing when available on channel adapters.
Announce context
Announce context is normalized to a stable internal event block:
| Field | Source |
|---|---|
| Source | subagent or cron |
| Session ids | Child session key/id |
| Type | Announce type + task label |
| Status | Derived from runtime outcome (success, error, timeout, or unknown) — not inferred from model text |
| Result content | Latest visible assistant text, otherwise sanitized latest tool/toolResult text |
| Follow-up | Instruction describing when to reply vs stay silent |
Terminal failed runs report failure status without replaying captured reply text. On timeout, if the child only got through tool calls, announce can collapse that history into a short partial-progress summary instead of replaying raw tool output.
Stats line
Announce payloads include a stats line at the end (even when wrapped):
- Runtime (e.g.
runtime 5m12s). - Token usage (input/output/total).
- Estimated cost when model pricing is configured (
models.providers.*.models[].cost). sessionKeyandsessionIdso the main agent can fetch history viasessions_historyor inspect the SQLite transcript rows.
Internal metadata is meant for orchestration only; user-facing replies should be rewritten in normal assistant voice.
Why prefer sessions_history
sessions_history is the safer orchestration path:
- Assistant recall is normalized first: thinking tags stripped;
<relevant-memories>/<relevant_memories>scaffolding stripped; plain-text tool-call XML payload blocks (<tool_call>,<function_call>,<tool_calls>,<function_calls>) stripped, including truncated payloads that never close cleanly; downgraded tool-call/result scaffolding and historical-context markers stripped; leaked model control tokens (<|assistant|>, other ASCII<|...|>, full-width<|...|>) stripped; malformed MiniMax tool-call XML stripped. - Credential/token-like text is redacted.
- Long blocks can be truncated.
- Very large histories can drop older rows or replace an oversized row with
[sessions_history omitted: message too large]. - Raw on-disk transcript inspection is the fallback when you need the full byte-for-byte transcript.
Tool policy
Sub-agents use the same profile and tool-policy pipeline as the parent or target agent first. After that, OpenClaw applies the sub-agent restriction layer.
With no restrictive tools.profile, sub-agents get all tools except
session tools and system tools:
sessions_listsessions_historysessions_sendsessions_spawn
sessions_history remains a bounded, sanitized recall view here too — it
is not a raw transcript dump.
When maxSpawnDepth >= 2, depth-1 orchestrator sub-agents additionally
receive sessions_spawn, subagents, sessions_list, and
sessions_history so they can manage their children.
Override via config
{
agents: {
defaults: {
subagents: {
maxConcurrent: 1,
},
},
},
tools: {
subagents: {
tools: {
// deny wins
deny: ["gateway", "cron"],
// if allow is set, it becomes allow-only (deny still wins)
// allow: ["read", "exec", "process"]
},
},
},
}
tools.subagents.tools.allow is a final allow-only filter. It can narrow
the already-resolved tool set, but it cannot add back a tool removed
by tools.profile. For example, tools.profile: "coding" includes
web_search/web_fetch but not the browser tool. To let
coding-profile sub-agents use browser automation, add browser at the
profile stage:
{
tools: {
profile: "coding",
alsoAllow: ["browser"],
},
}
Use per-agent agents.list[].tools.alsoAllow: ["browser"] when only one
agent should get browser automation.
Concurrency
Sub-agents use a dedicated in-process queue lane:
- Lane name:
subagent - Concurrency:
agents.defaults.subagents.maxConcurrent(default8)
Liveness and recovery
OpenClaw does not treat endedAt absence as permanent proof that a
sub-agent is still alive. Unended runs older than the stale-run window
stop counting as active/pending in /subagents list, status summaries,
descendant completion gating, and per-session concurrency checks.
After a gateway restart, stale unended restored runs are pruned unless
their child session is marked abortedLastRun: true. Those
restart-aborted child sessions remain recoverable through the sub-agent
orphan recovery flow, which sends a synthetic resume message before
clearing the aborted marker.
Automatic restart recovery is bounded per child session. If the same
sub-agent child is accepted for orphan recovery repeatedly inside the
rapid re-wedge window, OpenClaw persists a recovery tombstone on that
session and stops auto-resuming it on later restarts. Run
openclaw tasks maintenance --apply to reconcile the task record, or
openclaw doctor --fix to clear stale aborted recovery flags on
tombstoned sessions.
Stopping
- Sending
/stopin the requester chat aborts the requester session and stops any active sub-agent runs spawned from it, cascading to nested children. /subagents kill <id>stops a specific sub-agent and cascades to its children.
Limitations
- Sub-agent announce is best-effort. If the gateway restarts, pending "announce back" work is lost.
- Sub-agents still share the same gateway process resources; treat
maxConcurrentas a safety valve. sessions_spawnis always non-blocking: it returns{ status: "accepted", runId, childSessionKey }immediately.- Sub-agent context only injects
AGENTS.md,TOOLS.md,SOUL.md,IDENTITY.mdandUSER.md(noMEMORY.md,HEARTBEAT.md, orBOOTSTRAP.md). - Maximum nesting depth is 5 (
maxSpawnDepthrange: 1–5). Depth 2 is recommended for most use cases. maxChildrenPerAgentcaps active children per session (default5, range1–20).