mirror of
https://github.com/openclaw/openclaw.git
synced 2026-04-19 02:57:27 +00:00
Agents: add nested subagent orchestration controls and reduce subagent token waste (#14447)
* Agents: add subagent orchestration controls
* Agents: add subagent orchestration controls (WIP uncommitted changes)
* feat(subagents): add depth-based spawn gating for sub-sub-agents
* feat(subagents): tool policy, registry, and announce chain for nested agents
* feat(subagents): system prompt, docs, changelog for nested sub-agents
* fix(subagents): prevent model fallback override, show model during active runs, and block context overflow fallback
Bug 1: When a session has an explicit model override (e.g., gpt/openai-codex),
the fallback candidate logic in resolveFallbackCandidates silently appended the
global primary model (opus) as a backstop. On reinjection/steer with a transient
error, the session could fall back to opus which has a smaller context window
and crash. Fix: when storedModelOverride is set, pass fallbacksOverride ?? []
instead of undefined, preventing the implicit primary backstop.
Bug 2: Active subagents showed 'model n/a' in /subagents list because
resolveModelDisplay only read entry.model/modelProvider (populated after run
completes). Fix: fall back to modelOverride/providerOverride fields which are
populated at spawn time via sessions.patch.
Bug 3: Context overflow errors (prompt too long, context_length_exceeded) could
theoretically escape runEmbeddedPiAgent and be treated as failover candidates
in runWithModelFallback, causing a switch to a model with a smaller context
window. Fix: in runWithModelFallback, detect context overflow errors via
isLikelyContextOverflowError and rethrow them immediately instead of trying the
next model candidate.
* fix(subagents): track spawn depth in session store and fix announce routing for nested agents
* Fix compaction status tracking and dedupe overflow compaction triggers
* fix(subagents): enforce depth block via session store and implement cascade kill
* fix: inject group chat context into system prompt
* fix(subagents): always write model to session store at spawn time
* Preserve spawnDepth when agent handler rewrites session entry
* fix(subagents): suppress announce on steer-restart
* fix(subagents): fallback spawned session model to runtime default
* fix(subagents): enforce spawn depth when caller key resolves by sessionId
* feat(subagents): implement active-first ordering for numeric targets and enhance task display
- Added a test to verify that subagents with numeric targets follow an active-first list ordering.
- Updated `resolveSubagentTarget` to sort subagent runs based on active status and recent activity.
- Enhanced task display in command responses to prevent truncation of long task descriptions.
- Introduced new utility functions for compacting task text and managing subagent run states.
* fix(subagents): show model for active runs via run record fallback
When the spawned model matches the agent's default model, the session
store's override fields are intentionally cleared (isDefault: true).
The model/modelProvider fields are only populated after the run
completes. This left active subagents showing 'model n/a'.
Fix: store the resolved model on SubagentRunRecord at registration
time, and use it as a fallback in both display paths (subagents tool
and /subagents command) when the session store entry has no model info.
Changes:
- SubagentRunRecord: add optional model field
- registerSubagentRun: accept and persist model param
- sessions-spawn-tool: pass resolvedModel to registerSubagentRun
- subagents-tool: pass run record model as fallback to resolveModelDisplay
- commands-subagents: pass run record model as fallback to resolveModelDisplay
* feat(chat): implement session key resolution and reset on sidebar navigation
- Added functions to resolve the main session key and reset chat state when switching sessions from the sidebar.
- Updated the `renderTab` function to handle session key changes when navigating to the chat tab.
- Introduced a test to verify that the session resets to "main" when opening chat from the sidebar navigation.
* fix: subagent timeout=0 passthrough and fallback prompt duplication
Bug 1: runTimeoutSeconds=0 now means 'no timeout' instead of applying 600s default
- sessions-spawn-tool: default to undefined (not 0) when neither timeout param
is provided; use != null check so explicit 0 passes through to gateway
- agent.ts: accept 0 as valid timeout (resolveAgentTimeoutMs already handles
0 → MAX_SAFE_TIMEOUT_MS)
Bug 2: model fallback no longer re-injects the original prompt as a duplicate
- agent.ts: track fallback attempt index; on retries use a short continuation
message instead of the full original prompt since the session file already
contains it from the first attempt
- Also skip re-sending images on fallback retries (already in session)
* feat(subagents): truncate long task descriptions in subagents command output
- Introduced a new utility function to format task previews, limiting their length to improve readability.
- Updated the command handler to use the new formatting function, ensuring task descriptions are truncated appropriately.
- Adjusted related tests to verify that long task descriptions are now truncated in the output.
* refactor(subagents): update subagent registry path resolution and improve command output formatting
- Replaced direct import of STATE_DIR with a utility function to resolve the state directory dynamically.
- Enhanced the formatting of command output for active and recent subagents, adding separators for better readability.
- Updated related tests to reflect changes in command output structure.
* fix(subagent): default sessions_spawn to no timeout when runTimeoutSeconds omitted
The previous fix (75a791106) correctly handled the case where
runTimeoutSeconds was explicitly set to 0 ("no timeout"). However,
when models omit the parameter entirely (which is common since the
schema marks it as optional), runTimeoutSeconds resolved to undefined.
undefined flowed through the chain as:
sessions_spawn → timeout: undefined (since undefined != null is false)
→ gateway agent handler → agentCommand opts.timeout: undefined
→ resolveAgentTimeoutMs({ overrideSeconds: undefined })
→ DEFAULT_AGENT_TIMEOUT_SECONDS (600s = 10 minutes)
This caused subagents to be killed at exactly 10 minutes even though
the user's intent (via TOOLS.md) was for subagents to run without a
timeout.
Fix: default runTimeoutSeconds to 0 (no timeout) when neither
runTimeoutSeconds nor timeoutSeconds is provided by the caller.
Subagent spawns are long-running by design and should not inherit the
600s agent-command default timeout.
* fix(subagent): accept timeout=0 in agent-via-gateway path (second 600s default)
* fix: thread timeout override through getReplyFromConfig dispatch path
getReplyFromConfig called resolveAgentTimeoutMs({ cfg }) with no override,
always falling back to the config default (600s). Add timeoutOverrideSeconds
to GetReplyOptions and pass it through as overrideSeconds so callers of the
dispatch chain can specify a custom timeout (0 = no timeout).
This complements the existing timeout threading in agentCommand and the
cron isolated-agent runner, which already pass overrideSeconds correctly.
* feat(model-fallback): normalize OpenAI Codex model references and enhance fallback handling
- Added normalization for OpenAI Codex model references, specifically converting "gpt-5.3-codex" to "openai-codex" before execution.
- Updated the `resolveFallbackCandidates` function to utilize the new normalization logic.
- Enhanced tests to verify the correct behavior of model normalization and fallback mechanisms.
- Introduced a new test case to ensure that the normalization process works as expected for various input formats.
* feat(tests): add unit tests for steer failure behavior in openclaw-tools
- Introduced a new test file to validate the behavior of subagents when steer replacement dispatch fails.
- Implemented tests to ensure that the announce behavior is restored correctly and that the suppression reason is cleared as expected.
- Enhanced the subagent registry with a new function to clear steer restart suppression.
- Updated related components to support the new test scenarios.
* fix(subagents): replace stop command with kill in slash commands and documentation
- Updated the `/subagents` command to replace `stop` with `kill` for consistency in controlling sub-agent runs.
- Modified related documentation to reflect the change in command usage.
- Removed legacy timeoutSeconds references from the sessions-spawn-tool schema and tests to streamline timeout handling.
- Enhanced tests to ensure correct behavior of the updated commands and their interactions.
* feat(tests): add unit tests for readLatestAssistantReply function
- Introduced a new test file for the `readLatestAssistantReply` function to validate its behavior with various message scenarios.
- Implemented tests to ensure the function correctly retrieves the latest assistant message and handles cases where the latest message has no text.
- Mocked the gateway call to simulate different message histories for comprehensive testing.
* feat(tests): enhance subagent kill-all cascade tests and announce formatting
- Added a new test to verify that the `kill-all` command cascades through ended parents to active descendants in subagents.
- Updated the subagent announce formatting tests to reflect changes in message structure, including the replacement of "Findings:" with "Result:" and the addition of new expectations for message content.
- Improved the handling of long findings and stats in the announce formatting logic to ensure concise output.
- Refactored related functions to enhance clarity and maintainability in the subagent registry and tools.
* refactor(subagent): update announce formatting and remove unused constants
- Modified the subagent announce formatting to replace "Findings:" with "Result:" and adjusted related expectations in tests.
- Removed constants for maximum announce findings characters and summary words, simplifying the announcement logic.
- Updated the handling of findings to retain full content instead of truncating, ensuring more informative outputs.
- Cleaned up unused imports in the commands-subagents file to enhance code clarity.
* feat(tests): enhance billing error handling in user-facing text
- Added tests to ensure that normal text mentioning billing plans is not rewritten, preserving user context.
- Updated the `isBillingErrorMessage` and `sanitizeUserFacingText` functions to improve handling of billing-related messages.
- Introduced new test cases for various scenarios involving billing messages to ensure accurate processing and output.
- Enhanced the subagent announce flow to correctly manage active descendant runs, preventing premature announcements.
* feat(subagent): enhance workflow guidance and auto-announcement clarity
- Added a new guideline in the subagent system prompt to emphasize trust in push-based completion, discouraging busy polling for status updates.
- Updated documentation to clarify that sub-agents will automatically announce their results, improving user understanding of the workflow.
- Enhanced tests to verify the new guidance on avoiding polling loops and to ensure the accuracy of the updated prompts.
* fix(cron): avoid announcing interim subagent spawn acks
* chore: clean post-rebase imports
* fix(cron): fall back to child replies when parent stays interim
* fix(subagents): make active-run guidance advisory
* fix(subagents): update announce flow to handle active descendants and enhance test coverage
- Modified the announce flow to defer announcements when active descendant runs are present, ensuring accurate status reporting.
- Updated tests to verify the new behavior, including scenarios where no fallback requester is available and ensuring proper handling of finished subagents.
- Enhanced the announce formatting to include an `expectFinal` flag for better clarity in the announcement process.
* fix(subagents): enhance announce flow and formatting for user updates
- Updated the announce flow to provide clearer instructions for user updates based on active subagent runs and requester context.
- Refactored the announcement logic to improve clarity and ensure internal context remains private.
- Enhanced tests to verify the new message expectations and formatting, including updated prompts for user-facing updates.
- Introduced a new function to build reply instructions based on session context, improving the overall announcement process.
* fix: resolve prep blockers and changelog placement (#14447) (thanks @tyler6204)
* fix: restore cron delivery-plan import after rebase (#14447) (thanks @tyler6204)
* fix: resolve test failures from rebase conflicts (#14447) (thanks @tyler6204)
* fix: apply formatting after rebase (#14447) (thanks @tyler6204)
This commit is contained in:
@@ -6,465 +6,208 @@ read_when:
|
||||
title: "Sub-Agents"
|
||||
---
|
||||
|
||||
# Sub-Agents
|
||||
# Sub-agents
|
||||
|
||||
Sub-agents let you run background tasks without blocking the main conversation. When you spawn a sub-agent, it runs in its own isolated session, does its work, and announces the result back to the chat when finished.
|
||||
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.
|
||||
|
||||
**Use cases:**
|
||||
## Slash command
|
||||
|
||||
- Research a topic while the main agent continues answering questions
|
||||
- Run multiple long tasks in parallel (web scraping, code analysis, file processing)
|
||||
- Delegate tasks to specialized agents in a multi-agent setup
|
||||
Use `/subagents` to inspect or control sub-agent runs for the **current session**:
|
||||
|
||||
## Quick Start
|
||||
- `/subagents list`
|
||||
- `/subagents kill <id|#|all>`
|
||||
- `/subagents log <id|#> [limit] [tools]`
|
||||
- `/subagents info <id|#>`
|
||||
- `/subagents send <id|#> <message>`
|
||||
|
||||
The simplest way to use sub-agents is to ask your agent naturally:
|
||||
`/subagents info` shows run metadata (status, timestamps, session id, transcript path, cleanup).
|
||||
|
||||
> "Spawn a sub-agent to research the latest Node.js release notes"
|
||||
Primary goals:
|
||||
|
||||
The agent will call the `sessions_spawn` tool behind the scenes. When the sub-agent finishes, it announces its findings back into your chat.
|
||||
- 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.
|
||||
|
||||
You can also be explicit about options:
|
||||
Cost note: each sub-agent has its **own** context and token usage. For heavy or repetitive
|
||||
tasks, set a cheaper model for sub-agents and keep your main agent on a higher-quality model.
|
||||
You can configure this via `agents.defaults.subagents.model` or per-agent overrides.
|
||||
|
||||
> "Spawn a sub-agent to analyze the server logs from today. Use gpt-5.2 and set a 5-minute timeout."
|
||||
## Tool
|
||||
|
||||
## How It Works
|
||||
Use `sessions_spawn`:
|
||||
|
||||
<Steps>
|
||||
<Step title="Main agent spawns">
|
||||
The main agent calls `sessions_spawn` with a task description. The call is **non-blocking** — the main agent gets back `{ status: "accepted", runId, childSessionKey }` immediately.
|
||||
</Step>
|
||||
<Step title="Sub-agent runs in the background">
|
||||
A new isolated session is created (`agent:<agentId>:subagent:<uuid>`) on the dedicated `subagent` queue lane.
|
||||
</Step>
|
||||
<Step title="Result is announced">
|
||||
When the sub-agent finishes, it announces its findings back to the requester chat. The main agent posts a natural-language summary.
|
||||
</Step>
|
||||
<Step title="Session is archived">
|
||||
The sub-agent session is auto-archived after 60 minutes (configurable). Transcripts are preserved.
|
||||
</Step>
|
||||
</Steps>
|
||||
- Starts a sub-agent run (`deliver: false`, global lane: `subagent`)
|
||||
- Then runs an announce step and posts the announce reply to the requester chat channel
|
||||
- Default model: inherits the caller unless you set `agents.defaults.subagents.model` (or per-agent `agents.list[].subagents.model`); an explicit `sessions_spawn.model` still wins.
|
||||
- Default thinking: inherits the caller unless you set `agents.defaults.subagents.thinking` (or per-agent `agents.list[].subagents.thinking`); an explicit `sessions_spawn.thinking` still wins.
|
||||
|
||||
<Tip>
|
||||
Each sub-agent has its **own** context and token usage. Set a cheaper model for sub-agents to save costs — see [Setting a Default Model](#setting-a-default-model) below.
|
||||
</Tip>
|
||||
Tool params:
|
||||
|
||||
## Configuration
|
||||
- `task` (required)
|
||||
- `label?` (optional)
|
||||
- `agentId?` (optional; spawn under another agent id if allowed)
|
||||
- `model?` (optional; overrides the sub-agent model; invalid values are skipped and the sub-agent runs on the default model with a warning in the tool result)
|
||||
- `thinking?` (optional; overrides thinking level for the sub-agent run)
|
||||
- `runTimeoutSeconds?` (default `0`; when set, the sub-agent run is aborted after N seconds)
|
||||
- `cleanup?` (`delete|keep`, default `keep`)
|
||||
|
||||
Sub-agents work out of the box with no configuration. Defaults:
|
||||
Allowlist:
|
||||
|
||||
- Model: target agent’s normal model selection (unless `subagents.model` is set)
|
||||
- Thinking: no sub-agent override (unless `subagents.thinking` is set)
|
||||
- Max concurrent: 8
|
||||
- Auto-archive: after 60 minutes
|
||||
- `agents.list[].subagents.allowAgents`: list of agent ids that can be targeted via `agentId` (`["*"]` to allow any). Default: only the requester agent.
|
||||
|
||||
### Setting a Default Model
|
||||
Discovery:
|
||||
|
||||
Use a cheaper model for sub-agents to save on token costs:
|
||||
- Use `agents_list` to see which agent ids are currently allowed for `sessions_spawn`.
|
||||
|
||||
Auto-archive:
|
||||
|
||||
- Sub-agent sessions are automatically archived after `agents.defaults.subagents.archiveAfterMinutes` (default: 60).
|
||||
- Archive uses `sessions.delete` and renames the transcript to `*.deleted.<timestamp>` (same folder).
|
||||
- `cleanup: "delete"` archives immediately after announce (still keeps the transcript via rename).
|
||||
- Auto-archive is best-effort; pending timers are lost if the gateway restarts.
|
||||
- `runTimeoutSeconds` does **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.
|
||||
|
||||
## Nested Sub-Agents
|
||||
|
||||
By default, sub-agents cannot spawn their own sub-agents (`maxSpawnDepth: 1`). You can enable one level of nesting by setting `maxSpawnDepth: 2`, which allows the **orchestrator pattern**: main → orchestrator sub-agent → worker sub-sub-agents.
|
||||
|
||||
### How to enable
|
||||
|
||||
```json5
|
||||
{
|
||||
agents: {
|
||||
defaults: {
|
||||
subagents: {
|
||||
model: "minimax/MiniMax-M2.1",
|
||||
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)
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Setting a Default Thinking Level
|
||||
### Depth levels
|
||||
|
||||
```json5
|
||||
{
|
||||
agents: {
|
||||
defaults: {
|
||||
subagents: {
|
||||
thinking: "low",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
| 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 |
|
||||
|
||||
### Per-Agent Overrides
|
||||
### Announce chain
|
||||
|
||||
In a multi-agent setup, you can set sub-agent defaults per agent:
|
||||
Results flow back up the chain:
|
||||
|
||||
```json5
|
||||
{
|
||||
agents: {
|
||||
list: [
|
||||
{
|
||||
id: "researcher",
|
||||
subagents: {
|
||||
model: "anthropic/claude-sonnet-4",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant",
|
||||
subagents: {
|
||||
model: "minimax/MiniMax-M2.1",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
1. Depth-2 worker finishes → announces to its parent (depth-1 orchestrator)
|
||||
2. Depth-1 orchestrator receives the announce, synthesizes results, finishes → announces to main
|
||||
3. Main agent receives the announce and delivers to the user
|
||||
|
||||
### Concurrency
|
||||
Each level only sees announces from its direct children.
|
||||
|
||||
Control how many sub-agents can run at the same time:
|
||||
### Tool policy by depth
|
||||
|
||||
```json5
|
||||
{
|
||||
agents: {
|
||||
defaults: {
|
||||
subagents: {
|
||||
maxConcurrent: 4, // default: 8
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
- **Depth 1 (orchestrator, when `maxSpawnDepth >= 2`)**: Gets `sessions_spawn`, `subagents`, `sessions_list`, `sessions_history` so 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_spawn` is always denied at depth 2. Cannot spawn further children.
|
||||
|
||||
Sub-agents use a dedicated queue lane (`subagent`) separate from the main agent queue, so sub-agent runs don't block inbound replies.
|
||||
### Per-agent spawn limit
|
||||
|
||||
### Auto-Archive
|
||||
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.
|
||||
|
||||
Sub-agent sessions are automatically archived after a configurable period:
|
||||
### Cascade stop
|
||||
|
||||
```json5
|
||||
{
|
||||
agents: {
|
||||
defaults: {
|
||||
subagents: {
|
||||
archiveAfterMinutes: 120, // default: 60
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
Stopping a depth-1 orchestrator automatically stops all its depth-2 children:
|
||||
|
||||
<Note>
|
||||
Archive renames the transcript to `*.deleted.<timestamp>` (same folder) — transcripts are preserved, not deleted. Auto-archive timers are best-effort; pending timers are lost if the gateway restarts.
|
||||
</Note>
|
||||
|
||||
## The `sessions_spawn` Tool
|
||||
|
||||
This is the tool the agent calls to create sub-agents.
|
||||
|
||||
### Parameters
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
| ------------------- | ---------------------- | ------------------ | -------------------------------------------------------------- |
|
||||
| `task` | string | _(required)_ | What the sub-agent should do |
|
||||
| `label` | string | — | Short label for identification |
|
||||
| `agentId` | string | _(caller's agent)_ | Spawn under a different agent id (must be allowed) |
|
||||
| `model` | string | _(optional)_ | Override the model for this sub-agent |
|
||||
| `thinking` | string | _(optional)_ | Override thinking level (`off`, `low`, `medium`, `high`, etc.) |
|
||||
| `runTimeoutSeconds` | number | `0` (no limit) | Abort the sub-agent after N seconds |
|
||||
| `cleanup` | `"delete"` \| `"keep"` | `"keep"` | `"delete"` archives immediately after announce |
|
||||
|
||||
### Model Resolution Order
|
||||
|
||||
The sub-agent model is resolved in this order (first match wins):
|
||||
|
||||
1. Explicit `model` parameter in the `sessions_spawn` call
|
||||
2. Per-agent config: `agents.list[].subagents.model`
|
||||
3. Global default: `agents.defaults.subagents.model`
|
||||
4. Target agent’s normal model resolution for that new session
|
||||
|
||||
Thinking level is resolved in this order:
|
||||
|
||||
1. Explicit `thinking` parameter in the `sessions_spawn` call
|
||||
2. Per-agent config: `agents.list[].subagents.thinking`
|
||||
3. Global default: `agents.defaults.subagents.thinking`
|
||||
4. Otherwise no sub-agent-specific thinking override is applied
|
||||
|
||||
<Note>
|
||||
Invalid model values are silently skipped — the sub-agent runs on the next valid default with a warning in the tool result.
|
||||
</Note>
|
||||
|
||||
### Cross-Agent Spawning
|
||||
|
||||
By default, sub-agents can only spawn under their own agent id. To allow an agent to spawn sub-agents under other agent ids:
|
||||
|
||||
```json5
|
||||
{
|
||||
agents: {
|
||||
list: [
|
||||
{
|
||||
id: "orchestrator",
|
||||
subagents: {
|
||||
allowAgents: ["researcher", "coder"], // or ["*"] to allow any
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
<Tip>
|
||||
Use the `agents_list` tool to discover which agent ids are currently allowed for `sessions_spawn`.
|
||||
</Tip>
|
||||
|
||||
## Managing Sub-Agents (`/subagents`)
|
||||
|
||||
Use the `/subagents` slash command to inspect and control sub-agent runs for the current session:
|
||||
|
||||
| Command | Description |
|
||||
| ---------------------------------------- | ---------------------------------------------- |
|
||||
| `/subagents list` | List all sub-agent runs (active and completed) |
|
||||
| `/subagents stop <id\|#\|all>` | Stop a running sub-agent |
|
||||
| `/subagents log <id\|#> [limit] [tools]` | View sub-agent transcript |
|
||||
| `/subagents info <id\|#>` | Show detailed run metadata |
|
||||
| `/subagents send <id\|#> <message>` | Send a message to a running sub-agent |
|
||||
|
||||
You can reference sub-agents by list index (`1`, `2`), run id prefix, full session key, or `last`.
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Example: list and stop a sub-agent">
|
||||
```
|
||||
/subagents list
|
||||
```
|
||||
|
||||
```
|
||||
🧭 Subagents (current session)
|
||||
Active: 1 · Done: 2
|
||||
1) ✅ · research logs · 2m31s · run a1b2c3d4 · agent:main:subagent:...
|
||||
2) ✅ · check deps · 45s · run e5f6g7h8 · agent:main:subagent:...
|
||||
3) 🔄 · deploy staging · 1m12s · run i9j0k1l2 · agent:main:subagent:...
|
||||
```
|
||||
|
||||
```
|
||||
/subagents stop 3
|
||||
```
|
||||
|
||||
```
|
||||
⚙️ Stop requested for deploy staging.
|
||||
```
|
||||
|
||||
</Accordion>
|
||||
<Accordion title="Example: inspect a sub-agent">
|
||||
```
|
||||
/subagents info 1
|
||||
```
|
||||
|
||||
```
|
||||
ℹ️ Subagent info
|
||||
Status: ✅
|
||||
Label: research logs
|
||||
Task: Research the latest server error logs and summarize findings
|
||||
Run: a1b2c3d4-...
|
||||
Session: agent:main:subagent:...
|
||||
Runtime: 2m31s
|
||||
Cleanup: keep
|
||||
Outcome: ok
|
||||
```
|
||||
|
||||
</Accordion>
|
||||
<Accordion title="Example: view sub-agent log">
|
||||
```
|
||||
/subagents log 1 10
|
||||
```
|
||||
|
||||
Shows the last 10 messages from the sub-agent's transcript. Add `tools` to include tool call messages:
|
||||
|
||||
```
|
||||
/subagents log 1 10 tools
|
||||
```
|
||||
|
||||
</Accordion>
|
||||
<Accordion title="Example: send a follow-up message">
|
||||
```
|
||||
/subagents send 3 "Also check the staging environment"
|
||||
```
|
||||
|
||||
Sends a message into the running sub-agent's session and waits up to 30 seconds for a reply.
|
||||
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Announce (How Results Come Back)
|
||||
|
||||
When a sub-agent finishes, it goes through an **announce** step:
|
||||
|
||||
1. The sub-agent's final reply is captured
|
||||
2. A summary message is sent to the main agent's session with the result, status, and stats
|
||||
3. The main agent posts a natural-language summary to your chat
|
||||
|
||||
Announce replies preserve thread/topic routing when available (Slack threads, Telegram topics, Matrix threads).
|
||||
|
||||
### Announce Stats
|
||||
|
||||
Each announce includes a stats line with:
|
||||
|
||||
- Runtime duration
|
||||
- Token usage (input/output/total)
|
||||
- Estimated cost (when model pricing is configured via `models.providers.*.models[].cost`)
|
||||
- Session key, session id, and transcript path
|
||||
|
||||
### Announce Status
|
||||
|
||||
The announce message includes a status derived from the runtime outcome (not from model output):
|
||||
|
||||
- **successful completion** (`ok`) — task completed normally
|
||||
- **error** — task failed (error details in notes)
|
||||
- **timeout** — task exceeded `runTimeoutSeconds`
|
||||
- **unknown** — status could not be determined
|
||||
|
||||
<Tip>
|
||||
If no user-facing announcement is needed, the main-agent summarize step can return `NO_REPLY` and nothing is posted.
|
||||
This is different from `ANNOUNCE_SKIP`, which is used in agent-to-agent announce flow (`sessions_send`).
|
||||
</Tip>
|
||||
|
||||
## Tool Policy
|
||||
|
||||
By default, sub-agents get **all tools except** a set of denied tools that are unsafe or unnecessary for background tasks:
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Default denied tools">
|
||||
| Denied tool | Reason |
|
||||
|-------------|--------|
|
||||
| `sessions_list` | Session management — main agent orchestrates |
|
||||
| `sessions_history` | Session management — main agent orchestrates |
|
||||
| `sessions_send` | Session management — main agent orchestrates |
|
||||
| `sessions_spawn` | No nested fan-out (sub-agents cannot spawn sub-agents) |
|
||||
| `gateway` | System admin — dangerous from sub-agent |
|
||||
| `agents_list` | System admin |
|
||||
| `whatsapp_login` | Interactive setup — not a task |
|
||||
| `session_status` | Status/scheduling — main agent coordinates |
|
||||
| `cron` | Status/scheduling — main agent coordinates |
|
||||
| `memory_search` | Pass relevant info in spawn prompt instead |
|
||||
| `memory_get` | Pass relevant info in spawn prompt instead |
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### Customizing Sub-Agent Tools
|
||||
|
||||
You can further restrict sub-agent tools:
|
||||
|
||||
```json5
|
||||
{
|
||||
tools: {
|
||||
subagents: {
|
||||
tools: {
|
||||
// deny always wins over allow
|
||||
deny: ["browser", "firecrawl"],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
To restrict sub-agents to **only** specific tools:
|
||||
|
||||
```json5
|
||||
{
|
||||
tools: {
|
||||
subagents: {
|
||||
tools: {
|
||||
allow: ["read", "exec", "process", "write", "edit", "apply_patch"],
|
||||
// deny still wins if set
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
<Note>
|
||||
Custom deny entries are **added to** the default deny list. If `allow` is set, only those tools are available (the default deny list still applies on top).
|
||||
</Note>
|
||||
- `/stop` in 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 all` stops all sub-agents for the requester and cascades.
|
||||
|
||||
## Authentication
|
||||
|
||||
Sub-agent auth is resolved by **agent id**, not by session type:
|
||||
|
||||
- The auth store is loaded from the target agent's `agentDir`
|
||||
- The main agent's auth profiles are merged in as a **fallback** (agent profiles win on conflicts)
|
||||
- The merge is additive — main profiles are always available as fallbacks
|
||||
- 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.
|
||||
|
||||
<Note>
|
||||
Fully isolated auth per sub-agent is not currently supported.
|
||||
</Note>
|
||||
Note: the merge is additive, so main profiles are always available as fallbacks. Fully isolated auth per agent is not supported yet.
|
||||
|
||||
## Context and System Prompt
|
||||
## Announce
|
||||
|
||||
Sub-agents receive a reduced system prompt compared to the main agent:
|
||||
Sub-agents report back via an announce step:
|
||||
|
||||
- **Included:** Tooling, Workspace, Runtime sections, plus `AGENTS.md` and `TOOLS.md`
|
||||
- **Not included:** `SOUL.md`, `IDENTITY.md`, `USER.md`, `HEARTBEAT.md`, `BOOTSTRAP.md`
|
||||
- The announce step runs inside the sub-agent session (not the requester session).
|
||||
- If the sub-agent replies exactly `ANNOUNCE_SKIP`, nothing is posted.
|
||||
- Otherwise the announce reply is posted to the requester chat channel via a follow-up `agent` call (`deliver=true`).
|
||||
- Announce replies preserve thread/topic routing when available (Slack threads, Telegram topics, Matrix threads).
|
||||
- Announce messages are normalized to a stable template:
|
||||
- `Status:` derived from the run outcome (`success`, `error`, `timeout`, or `unknown`).
|
||||
- `Result:` the summary content from the announce step (or `(not available)` if missing).
|
||||
- `Notes:` error details and other useful context.
|
||||
- `Status` is not inferred from model output; it comes from runtime outcome signals.
|
||||
|
||||
The sub-agent also receives a task-focused system prompt that instructs it to stay focused on the assigned task, complete it, and not act as the main agent.
|
||||
Announce payloads include a stats line at the end (even when wrapped):
|
||||
|
||||
## Stopping Sub-Agents
|
||||
- Runtime (e.g., `runtime 5m12s`)
|
||||
- Token usage (input/output/total)
|
||||
- Estimated cost when model pricing is configured (`models.providers.*.models[].cost`)
|
||||
- `sessionKey`, `sessionId`, and transcript path (so the main agent can fetch history via `sessions_history` or inspect the file on disk)
|
||||
|
||||
| Method | Effect |
|
||||
| ---------------------- | ------------------------------------------------------------------------- |
|
||||
| `/stop` in the chat | Aborts the main session **and** all active sub-agent runs spawned from it |
|
||||
| `/subagents stop <id>` | Stops a specific sub-agent without affecting the main session |
|
||||
| `runTimeoutSeconds` | Automatically aborts the sub-agent run after the specified time |
|
||||
## Tool Policy (sub-agent tools)
|
||||
|
||||
<Note>
|
||||
`runTimeoutSeconds` does **not** auto-archive the session. The session remains until the normal archive timer fires.
|
||||
</Note>
|
||||
By default, sub-agents get **all tools except session tools** and system tools:
|
||||
|
||||
## Full Configuration Example
|
||||
- `sessions_list`
|
||||
- `sessions_history`
|
||||
- `sessions_send`
|
||||
- `sessions_spawn`
|
||||
|
||||
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:
|
||||
|
||||
<Accordion title="Complete sub-agent configuration">
|
||||
```json5
|
||||
{
|
||||
agents: {
|
||||
defaults: {
|
||||
model: { primary: "anthropic/claude-sonnet-4" },
|
||||
subagents: {
|
||||
model: "minimax/MiniMax-M2.1",
|
||||
thinking: "low",
|
||||
maxConcurrent: 4,
|
||||
archiveAfterMinutes: 30,
|
||||
maxConcurrent: 1,
|
||||
},
|
||||
},
|
||||
list: [
|
||||
{
|
||||
id: "main",
|
||||
default: true,
|
||||
name: "Personal Assistant",
|
||||
},
|
||||
{
|
||||
id: "ops",
|
||||
name: "Ops Agent",
|
||||
subagents: {
|
||||
model: "anthropic/claude-sonnet-4",
|
||||
allowAgents: ["main"], // ops can spawn sub-agents under "main"
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
tools: {
|
||||
subagents: {
|
||||
tools: {
|
||||
deny: ["browser"], // sub-agents can't use the browser
|
||||
// deny wins
|
||||
deny: ["gateway", "cron"],
|
||||
// if allow is set, it becomes allow-only (deny still wins)
|
||||
// allow: ["read", "exec", "process"]
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
## Concurrency
|
||||
|
||||
Sub-agents use a dedicated in-process queue lane:
|
||||
|
||||
- Lane name: `subagent`
|
||||
- Concurrency: `agents.defaults.subagents.maxConcurrent` (default `8`)
|
||||
|
||||
## Stopping
|
||||
|
||||
- Sending `/stop` in 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
|
||||
|
||||
<Warning>
|
||||
- **Best-effort announce:** If the gateway restarts, pending announce work is lost.
|
||||
- **No nested spawning:** Sub-agents cannot spawn their own sub-agents.
|
||||
- **Shared resources:** Sub-agents share the gateway process; use `maxConcurrent` as a safety valve.
|
||||
- **Auto-archive is best-effort:** Pending archive timers are lost on gateway restart.
|
||||
</Warning>
|
||||
|
||||
## See Also
|
||||
|
||||
- [Session Tools](/concepts/session-tool) — details on `sessions_spawn` and other session tools
|
||||
- [Multi-Agent Sandbox and Tools](/tools/multi-agent-sandbox-tools) — per-agent tool restrictions and sandboxing
|
||||
- [Configuration](/gateway/configuration) — `agents.defaults.subagents` reference
|
||||
- [Queue](/concepts/queue) — how the `subagent` lane works
|
||||
- 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 `maxConcurrent` as a safety valve.
|
||||
- `sessions_spawn` is always non-blocking: it returns `{ status: "accepted", runId, childSessionKey }` immediately.
|
||||
- Sub-agent context only injects `AGENTS.md` + `TOOLS.md` (no `SOUL.md`, `IDENTITY.md`, `USER.md`, `HEARTBEAT.md`, or `BOOTSTRAP.md`).
|
||||
- Maximum nesting depth is 5 (`maxSpawnDepth` range: 1–5). Depth 2 is recommended for most use cases.
|
||||
- `maxChildrenPerAgent` caps active children per session (default: 5, range: 1–20).
|
||||
|
||||
Reference in New Issue
Block a user