Subagents — Design
A subagent becomes a session like any other: it has an actor, a log, a place in its parent's transcript you can watch live, and a reply box. Stopping one, or losing it to a worker restart, leaves its work in place. The agent that started it, or you, can read that work and continue the same subagent with its history instead of starting over. Subagents can start subagents of their own.
Native sessions on every tool profile can use subagents, including GPT models on a ChatGPT connection (the Codex profile). Generic and Codex expose task and send_message; Claude exposes Task and SendMessage. Start or continue in the foreground, or set run_in_background: true for a pushed report. bash_output / BashOutput reads output or status, and kill_shell / KillShell stops a background subagent. These are the same implementations across profiles: named agents, allowed connections and templates, tool policies, depth, hop, concurrency and rate limits all apply unchanged. At the depth limit both start and message tools are removed, while output and stop remain available if the tool policy allows them.
1. Where things stand
What exists today (native sessions):
- The log is kept.
Task→subagent::Runner::runcreates a child session in the worker journal (SessionStarted.parent_session_id/parent_call_id). Its events sync like any session's. The head creates its row on the first event (store::create_subagent_session) in the parent's realm, with the parent's labels. The child's cost counts toward the parent, one level deep (usage::cost_of). - But it is not an actor. The child's turn runs inside the parent's tool call, with an in-memory
Conversationand one turn. It has no inbox and gets noCheckpoint. Once that call returns, nothing can run it again. - The head refuses it as a session. Messages ("run once"), rewinds, side chats and
Restoreare all refused forparent_call_idsessions. - The UI only links to it. The Task card has an open subagent link, which shows up once the child's row exists. The link opens the child in its own column, with no reply box. Nothing in the parent's transcript shows the child's progress.
- Interrupts lose the thread. Stopping the parent turn cancels the child.
run_turnendsInterrupted, the runner returnsErr("ended without a report"), and the parent's tool result is a bare error. Only a successful report carries[subagent session <id>]. So after an interrupt, the parent model can't point to the work that was done. - Restarts mislabel the work.
recover()closes the child's open turn (WorkerRestarted), so its log survives. The parent's background notice still says "lost … its output is gone", which isn't true. - The parent log has no record of the child.
SubagentSpawnedis listed in architecture §5 but was never built. The only link is the child'sSessionStarted, so the parent can't show a child before the head has ingested it. - No nesting. A subagent's tools are its parent's minus
Task. - Claude Code sessions drop subagents. Stream messages with a
parent_tool_use_idare thrown away (claude_code.rs).
2. Goals
- You can watch a subagent from the parent session, live, inline, the way side chats work.
- A stopped, failed or lost subagent leaves its partial work readable by you and by its parent agent.
- The parent agent or you can continue the same subagent with its history: to resume it after an interrupt, to send a finished one a follow-up, or to steer one that is running.
- Subagents can start subagents, within limits you set.
- Claude Code sessions show their subagents too, read-only.
Not a goal: rewinding a subagent.
3. Words
- Subagent: a child session started by a tool call, rather than by you branching off (that is a side chat). It is still
parent_idplusparent_call_id. Its parent may itself be a subagent. The main agent is the top-level session at the root of the tree. - Delegation: one request that starts a turn in a subagent. It comes from a
Taskcall (the first one), aSendMessagecall from its parent, or a message from you. Each delegation causes one turn. - Report: the final nonempty assistant message of the final turn. No explicit report tool or special wording is required; local waiters and remote relays use the same extraction.
- Outcome: how a delegation's turn ended:
completed,interrupted,failedorlost(the existingTurnEndReason). - Waiting call: a foreground
TaskorSendMessagecall in the parent that has not returned yet. It waits on exactly one delegation.
4. Data model
Worker: the subagent is an actor
Runner::run no longer runs the loop itself. It asks the session manager for a child actor and talks to it like any other session:
- Create. Create the child with a
CreateSessionthat carries a newDelegationfield: parent session, parent call, the named agent (its prompt, allowed tools and model, asagent_json) anddepth(the parent's plus one; the main agent is 0). The journal stores this spec, so a reload rebuilds the same tools:build_tools, filtered by the agent, with the agent's system prompt and model.TaskandSendMessageare included whiledepth < max_subagent_depth(§7). That fixes the problem that today's journaled spec is the parent's. - Send input. Send the prompt as
PendingInput. It now has adelegated_bycall id and an optionalon_turn_end: oneshot<Outcome>. - Wait or don't. Foreground: wait for the oneshot. Background: register the task as today and let the oneshot finish it.
- Cascade interrupts. If the parent's cancel token fires, the runner sends
Interruptto the child actor; it does not just drop a future. A subagent interrupted this way interrupts its own foreground subagents the same way, so a stop runs down the tree.
The child then gets everything an actor already has for free: inbox delivery at model boundaries, reload from the journal, history repair for tool calls that never got a result, Restore, and its own subagent runner. Nesting therefore needs no separate code path. It takes no Checkpoints: subagents are not rewound, and the parent's checkpoints cover the same folder.
Events
| Event | Log | New fields | Purpose |
|---|---|---|---|
SubagentSpawned | parent | call_id, child_session_id, agent, description, background_task_id | Written before the child starts. The parent's log now links to its children itself, so the UI can show a thread at once and recovery knows which calls were delegations. |
UserMessage | child | + delegated_by (a parent call id, or empty when you sent it), + wake | Each turn of the child is tied to its delegation. The UI marks turns "from its parent" or "from you"; wake is what you chose for reporting back (§6). |
SessionStarted | child | + agent, + depth | Shown in the UI; used again on reload. |
No new turn-end reasons are needed.
Head
- Migration:
sessions.agent(the named agent,''for general-purpose),sessions.end_reason(the lastTurnEndedreason, set at ingest),sessions.root_id(the top-level session, set at creation,NULLfor a top-level one; migration 0040 fills it in for existing side chats and subagents) andsessions.observed(§8). With these, thread headers and the subagents strip (§9) can show states without loading each child's log, and whole trees can be queried without recursion. GET /sessions/{id}/childrenreturns these columns, plus thedelegated_bycall of each child turn.?tree=1returns the whole subtree byroot_id.- Lift the refusals. Messages to subagent sessions are allowed (§6). Side chats on subagents are allowed too; they're seeded from the child's log as usual.
Restoreis allowed, so a trimmed child can still be resumed. Rewind stays refused, since it would change what the parent was already told. - Trees, not one level. Everything that follows
parent_idone step today follows the whole tree:- cost (
usage::cost_of), so a session's cost includes every level below it; - find in session, which today covers side chats only;
- search's
open=chain, which can now mix side chats and subagents (a side chat on a subagent of a subagent); - archiving, where a parent archives its whole subtree.
- cost (
- Journal trimming drops a child only once its root is trimmed.
5. Lifecycle
Notice semantics
A delegation finishes only after its foreground turn, counted background work, and the follow-up turn consuming waking task notices have settled. A turn that ends while that work remains may send a progress notice; it is not a completion or a reportless failure. Progress is keyed by the child's turn so retries cannot repeat it.
Each delegation/background-task identity receives at most one terminal report.
The background-task notice carries the last turn's final report, not the opening
plan. A genuinely empty final response is reported once as completed with no output. Parent journal notices and child SubagentReported receipts survive
worker recovery; the head claims remote obligations and enqueues their reports
in one transaction. A terminal background-task event and its notice obligation
are also journaled together, so a restart cannot mistake the gap before notice
delivery for completion. Continuing a finished child creates a new delegation.
A normal end with no assistant text is completed with no output, not a
failed background task. Only a real run error, interruption/cancellation, worker
loss, or an exhausted run limit makes a delegation unsuccessful. Earlier tool
failures that the agent recovered from never change that outcome; successful
reports may include Errors: n (last: …) as informational diagnostics. The
terminal background task uses the same success/failure decision as its report.
Task / SendMessage call, or your message
│
┌──────────► running ◄───────────────┐
│ │ │ continue: SendMessage from
│ ┌───────┼────────┬─────────┐ │ its parent, or your reply /
│ ▼ ▼ ▼ ▼ │ Resume
│ completed interrupted failed lost┘
│ │ (you or parent (error) (worker restarted)
│ │ stopped it)
│ └── report → waiting call, or notice to its parent
│
new delegation
A subagent is idle between delegations, like any session. Its state in the UI is its status (running or idle) plus end_reason.
What the parent gets
-
Completed (foreground): the report, as today, with
[subagent <id>]always appended. -
Anything else (foreground): a tool result that isn't a bare error. It carries the outcome, the subagent's id, a digest of its partial work, and how to continue. For example:
<subagent id="0199…" status="interrupted" by="user" turns="1" tool_calls="14" elapsed="2m 10s"> Last message: "Found the three call sites; now updating parser.rs…" Changed: crates/c6-head/src/parser.rs, crates/c6-head/src/store.rs Errors: 1 (cargo check: unresolved import) Subagents: 0199…a2 (interrupted), 0199…b7 (completed) </subagent>Then comes the line saying how to continue, which is an editable prompt (§10). The digest is built from the child's events:
- the last assistant text;
- its write and edit tool calls (exact paths, not a git diff, so the parent's and siblings' edits don't show up);
- failed calls;
- the subagents it started and their states.
It is mechanism output, not instructions.
-
Background: the same text, in the
task-notificationnotice. -
Lost (worker restart): the existing
losthandling changes in two ways.- Background tasks say the log is kept and can be resumed (no more "its output is gone").
- When an actor reloads, any
SubagentSpawnedwhose call has noToolResultgets one written before its open turn is closed, with the digest andstatus="lost". Each level does this for its own calls. The model then sees the id, not the generic repair placeholder.
Interrupts
| You do | Foreground subagents | Background subagents |
|---|---|---|
| Stop the main turn (Esc) | Interrupted too, all the way down. Each one's partial result is recorded as its call's result. | Keep running (their own token, as today). |
| Stop a subagent (its thread's Stop) | Its turn ends, and so do its own foreground subagents. The waiting call returns interrupted, and the parent carries on and decides what to do. | Same as the kill tool or StopTask; the notice says stopped_by_user. |
| Kill tool from the parent model | n/a | Interrupts the child's turn; its log is kept and it can be resumed. |
Stopping one subagent is the main new control: you can stop one that has gone off track without throwing away its parent's turn.
6. Continuing a subagent
From its parent: SendMessage
A new tool, SendMessage in the Claude tool set and send_message in the others, with to (a subagent id) and message:
- The subagent is idle: the message starts a new delegation, and its whole conversation continues with the same tools, agent and model. It also keeps the same cache key, so continuing it soon after reuses the prompt cache. The call waits for the report, unless
run_in_backgroundis set (then it is tracked like a backgroundTask). - The subagent is running: the message goes into its inbox and arrives at its next model boundary. The call returns at once, whether
run_in_backgroundis omitted, false or true; its report arrives as a background notice when it finishes. Steering never waits for a running child's validation command or current turn. - Allowed targets: an agent can message only its own children (
parent_id= caller). Messaging any other session is refused.
A user message also releases an idle-child foreground Task or SendMessage
wait: the same delegation continues in the background and its result arrives
later as a notice. The built-in agent uses its existing task-notice path;
Claude Code automatically applies Send now to carbon6-owned blocking MCP
calls (Task, SendMessage, wait_for). Neither mechanism interrupts the
child. Other Claude Code tools retain their normal queued-message behavior.
Remote background steers need an updated head and worker for call-specific
report notices. A worker talking to an older head falls back to that head's
ordinary report-notice path rather than keeping a waiter the head cannot settle.
Report ownership survives the task (2026-11-07). A running child may already be on a later turn, resumed by its own shell notices after its original background task failed, stopped or was lost. A steer still owns a report for the turn that actually consumes it. If no call waits for that turn, the report is a waking notice to the recorded parent; it does not depend on the old background task still existing. A steer queued after a final model request belongs to the next turn, not the turn that is finishing. A child's own task-notification turns report back too. Direct messages from you still respect your Wake the parent choice, and the notice scheduler still applies.
Local report recovery reads consumed inputs and turn ends from the journal.
Stable subagent:local:<child>:<end-seq> notice IDs deduplicate retries; a child
receipt is written only after its parent recorded the notice, or recovery
finds the waiting call's durable result/background notice. Merely sending a
oneshot is not a durable receipt. All unreceipted turns are considered, not
only the last one. Startup scans local children for these obligations without
the held-notice recovery window, but does not recreate tools/MCP processes for
children whose parents already durably recorded their reports. A tracking boundary on creation/first load
avoids replaying already-reported history from older versions; this is not a
backfill of old lost reports. An unavailable local parent leaves a visible
Subagent report delivery failed notice on the child and keeps the report
pending. Remote delivery and rejection visibility are in remote-subagents.md
§12. Delivery is at-least-once across crashes, not an exactly-once promise.
The tool also preserves a report returned when a running snapshot becomes
idle before SendMessage delivers its input, rather than replacing that report
with a misleading “Sent” response.
bash_output / BashOutput take a subagent id (a background task id or a session id). They return the digest above plus any new events since the last read, so a parent can check on a background subagent without waiting for it.
Why a separate tool and not a resume parameter on Task:
Taskstays "start one"; itssubagent_typeanddescriptionwould mean nothing on a resume.- A separate tool can steer a running subagent, which a
Taskresume would have to refuse. - Weaker models misuse overloaded schemas less often.
- Current Claude Code continues agents with a separate
SendMessagetool, so Claude models expect this shape.
From you
A subagent's thread (§9) has a reply box and, after an interrupted, failed or lost turn, a Resume button. Resume sends the resume prompt.
-
While a call is waiting on the subagent, your message goes into the subagent's inbox. It arrives at the next model boundary, so you are steering it, and the parent keeps waiting for the report.
-
When no call is waiting, your message starts a new delegation that you own. When that turn ends, its report goes to the subagent's parent as a
task-notificationnotice:- If the parent is running, the notice arrives at its next model boundary. It is acting, so it needs to know what changed.
- If the parent is idle, the notice waits and arrives with the parent's next input. It doesn't start a turn by itself.
- With Wake the parent ticked, the notice can start a turn in an idle parent. The notice scheduler merges arrivals and applies progress and spending guards.
The parent never acts on stale information, and nothing runs behind your back unless you ask for it. To only ask a subagent something, use a side chat on it (↳ Ask); side chats don't report back.
-
In a tree, the rule repeats one level at a time. A report from a woken parent goes to its own parent under the same rule, and
wakecarries up only as far as you ticked it (stored on theUserMessage).
The report names the input's source, in both the parent's transcript and its waiting-notices pill. A direct user message from the UI says so; a UI Resume request says the subagent resumed, without claiming you wrote the resume prompt. An HTTP API message or Resume request says Sent to subagent <id> via the API (token "<name>"): …, using only the token's display name, never its secret (or just via the API when no name is known with sign-in off). A session message names its sending session; when the sender is the subagent itself, it says the subagent resumed itself. Local workers and the head's remote-subagent relay use the same attribution. UserInput.api_origin (15) and UserMessage.api_origin (12) carry this optional origin additively; update both head and workers for API attribution, since older workers ignore it. Old workers' unlabelled input text is shown neutrally rather than guessed to be yours.
History after an interrupt
This comes from history_from_events. A tool call that was cut off gets its repaired "interrupted" result, so the model sees exactly where it stopped.
7. Nesting
-
Limits (settings):
max_depth(max_subagent_depthon the worker): the main agent is depth 0, its subagents depth 1, and so on. Default: 5.max_running(max_running_subagentson the worker): an optional count cap per tree. Default: 0, meaning no count cap.
At the depth limit, the subagent isn't given
TaskorSendMessage. If you set an explicit running cap,Taskrefuses a launch above it and tells the agent how many are running. A named agent whose tool list leaves outTaskcan't nest, whatever its depth.Independently of the count cap, a worker can hold a subagent launch or continuation when it detects low memory headroom or high system load. The transcript shows “Queued: worker busy” and the launch is retried as headroom returns. This is a best-effort check on the worker, not a memory limit or an OOM guarantee; it does not measure the SSH host or predict the resource use of later tools.
Saved settings that match the previous defaults adopt the new defaults on upgrade. Custom caps stay in effect, and you can explicitly set an old value again after upgrading.
-
Inheritance:
- Every level gets the root's tool hooks (not Stop), secrets, publisher, memory and notice sinks, as
subagent::Parentdoes now. - Every level stays in the root's realm and keeps its labels.
- The routing rule's
subagent_modelapplies at every depth (a named agent's model still wins). - The routing rule's
toolslist applies at every depth. A named agent's own list narrows it further; changing model profiles does not widen it.
- Every level gets the root's tool hooks (not Stop), secrets, publisher, memory and notice sinks, as
-
Who talks to whom:
- Reports and notices go up one level.
SendMessagegoes down one level.- You can reach any level from the UI.
-
Notice chains. Distinct reports can keep waking an idle parent; there is no fixed wake limit. For repeated activity without progress, the runaway guard warns the agent, then slows delivery, then pauses with evidence if the loop persists. Quiet user reports do not wake an idle parent. The default session-message ceiling is 50 hops as a last resort; the deprecated hourly message cap and the optional hourly notice token cap are off by default.
8. Claude Code sessions
The worker turns parent_tool_use_id traffic for Claude Code's own Agent or Task tool into an observed child session instead of dropping it. These tools are off by default; mirroring still works when Settings keeps all of Claude Code's tools (background.md §4). On the first message for a known Agent or Task tool_use, it creates a child (SessionStarted.parent_call_id = that tool_use id, title from its description) and appends assistant and tool-result events to it. Nested ones nest the same way, by their own parent_tool_use_id. Traffic under other calls, including Bash, never creates a mirror: a local_bash task is a native task, not a subagent, whether foreground, started in the background or moved there later. The head's catch-up filter still excludes shell-command SubagentSpawned events from older worker logs.
It ends when the Task call gets its result. A subagent Claude Code runs in the background is different: its call returns at once ("launched") while it keeps working. Its task_started names the call (tool_use_id) and says is_backgrounded, so that early result is ignored and the child ends with its task's task_notification (completed, failed as an error, stopped as interrupted). A foreground subagent the CLI moves to the background (Send now, docs/background.md §4) gets the same once its task_updated says is_backgrounded. Before this, such a child stayed running until the Claude Code process exited, and its parent showed as running after its own turn had ended.
The UI shows it as a read-only thread: no reply box, no Resume, no Stop. Claude Code owns that subagent's lifecycle, and its own agent can continue it. The head sets sessions.observed, so it refuses messages to these sessions.
9. UI
The subagent thread
A Task call's card turns into a thread under the call, like a side chat but in violet:
● Task Find all callers of parse_spec (code-explorer · haiku-4.5) ⏸ interrupted · 14 calls · 2m10s · $0.04 ↗
│ ▸ Read crates/c6-head/src/store.rs
│ ▸ Grep "parse_spec(" → 3 files
│ ● Task Check the tests (general · haiku-4.5) ✓ done · 6 calls ← a nested thread
│ Found the three call sites; now updating parser.rs…
│ ▸ Edit parser.rs ✕ cargo check failed
│ ─ interrupted by you ─
│ [ Resume ] [ Reply to the subagent… ] ☐ Wake the parent
- Header: the named agent, the description, the model, a state pill (● running, ✓ done, ⏸ interrupted, ✕ failed, ⚠ lost), tool calls, elapsed time and cost (its subtree included). ↗ opens the subagent in its own column.
- Live tail while it runs: a foreground subagent opens showing its last few events (a "peek"). Clicking the header expands the full transcript; the open/closed choice is saved per thread, as for side chats. Tool calls start collapsed. The prompt isn't repeated, since the Task card above already shows it.
- Waiting on you: approvals and questions in carbon6 subagents, at any depth, also appear in the parent session's header list and in an amber held-notices-style box above its message box, outside the transcript's scroll area. Each has Show: open the threads down to its answerable card, or open the subagent's own session at that card if its thread isn't drawn. A held tool call opens the same decision and sends the same approval notification as one in a top-level session; it counts once in What needs you, regardless of how many ancestors show it. Side chats are independent conversations, not part of this subagent waiting list. The session's own open decisions and offered task cards are included in its header list too (offered tasks still don't count in What needs you).
- Head query:
GET /api/v1/sessions/{id}/waitingreturnsAttentionItemrows for the session's open decisions/cards (including decisions naming it as a working session), plus approvals/questions in its subagent tree. It includes snoozed decisions only once due, is realm-scoped, and does not depend on the top-level live session list or the loaded transcript window. Attention pings and reconnects refresh it. No schema migration is needed: it reads the existing decisions and session ancestry. - When it completes, the thread collapses to the header and the report shows as the call's result. Turns are labelled by delegation: "from its parent (this call)", "continued by its parent ↗ call", "from you".
- A
SendMessagecall gets a small card ("↻ continued Find all callers…", or "→ sent to … while running") that scrolls to the subagent's thread. The new turn appears there, so one subagent stays in one place. - Nested subagents are threads inside threads. Beyond two levels of indentation, a nested subagent shows as a one-line row (header only) that opens in its own column, so deep trees don't squeeze the page.
- Controls: Stop while it runs (it stops the subagent's own foreground subagents too); Resume after a turn that did not complete; the reply box at any time; ↳ Ask (a side chat on the subagent) on its messages. Observed (Claude Code) threads have none of these.
The subagents strip
This answers the open item in architecture §17 about rendering a session with many subagents. Next to RunningTasks, the session header gets a Subagents pill with counts for the whole tree (3 running · 5 done · 1 interrupted). It opens the tree: an indented list showing each subagent's state, agent, description, elapsed time and cost. Clicking one scrolls to its thread, expanding the threads above it. Several Task calls in one message show as a stack of compact one-line threads, so a fan-out of 8 doesn't push the conversation off screen.
A subagent's own page
The breadcrumb shows the chain, for example "main session › Find all callers… › Check the tests". Each step jumps to the call that started the next. The page has the reply box, with the same rules as the thread's, and its own subagents strip for its subtree.
10. Settings (no new strings in code)
Prompts go in Settings → Prompts, with shipped defaults, next to session.subagent:
session.subagent_resume: what the subagent is told on Resume ("You were stopped partway through. Your work so far is above. Continue the task…").session.subagent_partial: the line after the digest in the parent's tool result (how to continue withSendMessage, or that it can start fresh).- The compaction prompts gain a line asking to keep subagent ids that may need continuing. This edits the existing editable prompts, not code.
Limits go in Settings → General: max_subagent_depth and max_running_subagents.
11. Edge cases
- The parent rewinds past a Task call. The subagent stays (the logs are append-only), folded with the rewound events. Only you can continue it, since the parent no longer knows about it.
- Edits run at the same time. Subagents still share the root's work tree, at any depth. Nothing changes here, but the digest lists only the subagent's own edits.
SendMessageto a subagent the caller is waiting on. This can't happen, because a waiting caller isn't running. Two calls in one message that target the same idle subagent are refused for the second one ("already running").
12. Steps
As built: all six steps on 2026-10-14.
- A background subagent's session is found through
SubagentSpawned.background_task_id, soBackgroundTaskgained no field. - A reloaded or restored subagent keeps the tools its
SessionStartedlists, soDelegation.agent_jsonis informational. - Without its parent on the worker (both were trimmed), a restored subagent runs with hooks of its own.
- An agent may message a subagent that has a
SubagentSpawnedin its own log, by session id or background task id. - Resume is
POST /sessions/{id}/resume: it sends the realm'ssession.subagent_resumeprompt as a message withcommand: "resume", and only after a turn that was interrupted, failed or lost. - The limits are the head's
subagent-limitssetting (Settings → Agents), sent in each spec asmax_subagent_depthandmax_running_subagents. The running limit counts delegations a parent waits on or runs in the background (not your own messages to subagents) per top-level session, on the worker. - Tree-wide on the head: cost (
usage::cost_of, and the usage report's per-session rows), archiving,GET /sessions/{id}/children?tree=1, find in session (a subagent's matches sort at itsSubagentSpawnedevent) and search links (OpenIn.side_chatslists side chats and subagents to expand). - The UI learns that a subagent started or stopped working, without an event in the parent, from
Session.subagents_runningin the live session list (counted per tree byroot_id); transcripts and the ◆ list refresh their children when it changes. A collapsed thread follows the subagent's stream only while it runs. - Claude Code's subagents:
claude_code::Mappercreates a mirror session the first time a message carries aparent_tool_use_idnaming a known Claude CodeAgentorTaskcall, under the session (or mirrored subagent) whose call it is, and logsSubagentSpawnedthere. It records the subagent's task, whole messages (not partial deltas) and tool results, and ends its single turn when the call's result arrives, or as interrupted (or failed) if the process stops first. Its spec hasDelegation.observed; the head setssessions.observed(migration 0041) from itsclaude_codeprofile and refuses messages, Resume and restores for it. - Threads show the subagent's
SessionStartedline (its tools and prompt matter for a named agent) and skip nothing else; the peek shows the last three steps. A subagent uses its parent's live tool hooks and policies, so calls held for approval wait in the parent as before;SessionManagerkeeps each actor'sSessionToolsfor this and loads the parent first when a subagent is loaded after a restart. Secrets go by the root session (Delegation.root_session_id), since a new child's row may not be on the head yet.
- Actor-backed subagents.
DelegationinCreateSession,SubagentSpawned, the child built and reloaded as an actor, interrupts cascaded through the actor. Depth limit 1, so visible behavior stays as today. Tested by killing the worker mid-subagent and reloading. - Partial results. The digest; foreground and background results for every outcome; recovery writing results for dangling delegations; the corrected
losttext; the head columns. - Continuing.
SendMessage,bash_outputfor subagents, the head accepting input (withwake),Restoreand side chats for children, the prompts. - Nesting.
TaskandSendMessagefor children under the limits, tree-wide cost, find in session, search chains and archiving. - UI. Threads with live peek, nested threads, Stop, Resume, the reply box, the subagents strip, the breadcrumb.
- Claude Code observed children.
13. Decisions (settled 2026-10-14)
- Stopping the main turn stops its foreground subagents, all the way down.
- Messaging a subagent that a call is waiting on steers it; the parent keeps waiting.
- Reporting back: your follow-ups always report to the parent. A running parent hears at its next step; an idle one hears with its next input, unless you tick Wake the parent.
- Continuing: a separate
SendMessagetool rather thanresumeonTask. - Claude Code subagents are shown read-only.
- Subagents can start subagents.
- Default limits:
max_subagent_depth= 5 andmax_running_subagents= 0 (no count cap) per tree.
Background tasks: completion and inspection
carbon6-managed shell tasks use the same background manager across the Generic, Claude and Codex tool profiles. Set run_in_background: true on Bash / shell. Completion is pushed to the session: a running model receives the notice at its next boundary, and an idle session merges completions before waking, subject to progress and spending guards. Held notices survive worker restart. The model need not poll output simply to wait. Use notify: false for servers and watchers that should not wake it. See Notice scheduling.
For background Task calls, set group to a fresh name for each fan-out and wake to all (the default), count:N, or any. A group waits for its threshold of completed tasks before waking an idle parent; a failed or lost member bypasses the threshold, but not the guards. The report includes a group summary. The same arguments are available on Claude Code's carbon6 Task bridge.
The session's Tasks control shows the running count and lifecycle history, including completed, stopped and lost tasks. A compact task badge stays in the tile bar, including on mobile, so it is reachable while the transcript is scrolled. Inspect opens command, status, elapsed time and separate stdin/stdout/stderr panes; Stop is available while running. Opening the inspector, pressing Refresh, or receiving a lifecycle change fetches a snapshot. There is no periodic output polling and inspecting does not wake the model or advance its incremental output cursor.
- Local shell stdin is closed. SSH stdin carries the launch script and closes; it is not interactive. The inspector is read-only, not a terminal.
- stdout and stderr each retain the most recent 1 MiB; truncation is shown. The model's combined incremental output remains separate from the user's snapshot cursor. Commands and captured output are secret-redacted.
- Subagent panes describe completed reports and failures, not invented operating-system streams. Running subagent progress is in its child session transcript.
- Lifecycle metadata is durable, but stream buffers are held in worker memory. After a restart or while offline, the inspector explicitly reports unavailable streams rather than presenting empty output as success. Existing tasks whose streams were already combined cannot be retroactively separated.
GET /api/v1/sessions/{id}/tasks/{task}exposes the same read-only snapshot under the session's realm permissions.
Claude Code CLI-native tasks appear in the same list, observed from the CLI's task lifecycle messages rather than run a second time. Claude Code handles their completion notices itself; carbon6 does not create duplicate model wakeups. The session's Claude Code process stays up between turns, so a task outlives the turn that started it, and its end wakes the agent (background.md §4). Native outcomes are shown without inventing numeric process exit codes. If the CLI exits without an outcome, the task is marked lost rather than successful. Stop asks the CLI to stop that one task (stop_task); stopping the turn does not stop its tasks.
Native stdin and separate stdout/stderr are unavailable. When the CLI supplies a task output file, carbon6 exposes a separately labelled combined output pane, bounded and redacted. The supported CLI protocol supplies that path at terminal notification, so running native tasks show upstream metadata rather than live stream bytes. Only regular task-output files under the private temporary directory assigned to that CLI process may be read; paths escaping the directory, symlinks and other file types are rejected. When no supported output is supplied, the inspector explains the limitation and shows task-summary metadata instead of fabricating streams.
14. Where a subagent runs
For a subagent on another worker, folder or repository, started from a template, see docs/remote-subagents.md.
A subagent may run on another connection and model than its parent: a cheap model for searches, or a GPT model under a Claude session. carbon6 runs it in its own loop whatever the parent runs on, so it works for every main model, Claude Code included. One on a Claude Code connection is the exception: it runs as a Claude Code session of its own (see "On Claude Code" below).
Choosing
The connection, model and effort come from the first of these that says, most specific first:
- The
Taskcall:connection(a name or id from the list in the tool's description),model(a model id, orconnection/model) andeffort. The model sets them when you ask ("use a subagent on my work ChatGPT connection with gpt-6.1-sol at high"). A connection without a model runs its default model. - A named agent's
model: an alias (opus,sonnet,haiku) on an Anthropic connection, orconnection/modelon any. - The session's default for subagents: picked in the session (the Subagents row under the message box;
PUT /sessions/{id}/subagent-model), else the routing rule's (Subagent connection, Subagent model, Subagent effort). - The connection's subagent model: set on the session's connection (Settings → Connections → Edit → Subagent model), on that same connection. A smaller model there (
gpt-6-lunaundergpt-6.1-sol) makes searching and reading far cheaper; subagents were a third of the calls when a ChatGPT plan ran out in three days. - The parent's own model.
The effort carries over only while the subagent stays on the same connection. Its own subagents inherit the session's default.
What may be used
The head sends each session the connections its realm may use (CreateSession.subagent_connections_json), Claude Code ones included, except for SSH sessions, which can't start the CLI on their host. The worker refuses anything else with an error that lists the available connections. The parent's own connection is always allowed. A worker gets a connection's credentials only if some realm it serves may use that connection.
Task lists exactly that head-supplied catalog, with connection display names
and an alias's own name (not its target's name or its raw ID). Replayed model
and subagent-default events do not add advertised connections. A pre-catalog
journal can still use its head-authorized default without naming a connection
(never a Claude Code default over SSH); the next attach refresh supplies the
real realm/SSH/worker-capability-filtered named choices.
Until 2026-11-09 Claude Code was left out. A Claude Code session's agent then named the API connection for its subagents to run at all, which billed every one per call instead of on the Claude Code plan. Claude Code sessions are now told their subagents run on Claude Code unless the user asks for another model (CLAUDE_CODE_NOTE).
Long conversations shed old tool output
In carbon6's own loop, a subagent whose request would read more than 200k tokens (or half its model's window, if that is smaller) has its old tool output trimmed first (history::trim_old_tool_output, TurnConfig.trim_at).
- What stays: the latest 8 outputs, the first 5 after every message to the agent (what it read to learn each instruction), and outputs under 400 characters.
- What goes: each other output becomes the editable prompt
session.trimmed_output("[Earlier output of ‹call› removed to save context. Run the tool again if you need it.]"). - Cache-friendly: a trim happens only when it saves at least a fifth, and trimmed outputs stay trimmed, so the cached prefix changes about as often as with compaction, which still comes after if needed.
- Evidence: in step replays of 30 points from subagents of a long-running private project, this policy read 52% less context with no loss beyond the judge's own noise (docs/replay-eval.md).
- Scope in carbon6's own loop: only subagents are trimmed; your top-level sessions aren't.
Claude Code sessions, including top-level sessions and carbon6-managed
subagents, use the same policy between turns. Claude Code owns its in-memory
context, so carbon6 cannot change it during a call. As a turn ends at a quiet
boundary (and before sending input on a later turn), carbon6 checks the last call's
reported context against min(200000, window / 2). It does not restart a
process with an unacknowledged input, a pending native turn or notification,
or Claude Code's own running background tasks/agents. Large conversations wait
until those finish; no active turn is cut short to save tokens. Work carbon6
holds (its background subagents and held shells) survives the CLI's restart,
so it does not block trimming: a wait on that work starts with the smaller
transcript. Trimming itself makes no model call and does not keep caches warm.
Consuming the last idle-only message or native task completion retries the
quiet check, so deferred maintenance does not require another user message.
The worker first checks that trimming would save at least 20% of the live
message content, then uses the existing quiet-restart path to stop the whole
Claude Code process group. Only then does it re-read and atomically replace
the native JSONL transcript in place, retaining its conversation ID, UUIDs,
parent links, tool calls and result pairing. Only text-only old tool results
after the latest native compact_boundary change; media, assistant text,
user instructions and compacted history stay. Unknown or malformed transcript
shapes defer maintenance rather than risk the conversation. Resume and moves
preserve the native ID and file layout; Rewind forks the already-trimmed
history through its selected cutoff into a new native conversation.
Claude Code resumes that transcript with --resume. Previously trimmed stubs
stay byte-for-byte unchanged, including when the editable prompt changes.
carbon6's event log and the full outputs shown in the UI are not rewritten.
A quiet line reports the number of outputs trimmed and the estimated smaller
context (the byte reduction scaled to the last reported token count, not an
exact tokenizer measurement). The first call after trimming writes a new,
smaller cache prefix; at these sizes the savings pay for that write within a
couple of calls.
Settings → Agents → Limits, per realm (or
GET/PUT /api/v1/settings/subagent-limits):
claude_code_trim_enabled:trueby default;falsedisables native trimming.claude_code_trim_at: token threshold;0(default) uses the window-aware threshold above. This also applies to existing sessions and is inherited by new subagents. It does not change carbon6's own-loop trimming threshold.
Tools and prompt
Where the subagent's model takes the parent's tool profile, it shares the parent's tools as before. Otherwise (a GPT subagent under a Claude parent, or any subagent of a Claude Code session) it gets tools of its own in its model's profile, with the inherited routing rule's tool list, then the same filters: the named agent's tools, the depth limit, no task cards. Its system prompt is the parent's with the skills index renamed for the profile, shown only if the skill loader is present. Under Claude Code, whose prompt is its own, it gets the prompt a carbon6 session would have. SessionStarted.tool_profile, tools and context_window are the subagent's own, so a reload rebuilds the same set.
On Claude Code
A subagent on a Claude Code connection is a Claude Code session of its own, a child like any other (SubagentSpawned, its report back to the Task call, SendMessage to continue it). It has Claude Code's prompt and tool profile, and carbon6's tools reach it over the MCP bridge. A named agent's instructions go ahead of its task, since the prompt is Claude Code's.
Its tools are narrowed as filter_tools narrows others:
- Its named agent's list travels in its delegation (
subagent::agent_tools). It narrows both Claude Code's own tools (claude_code_native, even where Settings keeps all of them) and carbon6's on the bridge,Taskand documents included. - The parent's limits go into its tool list: a named parent's list, and in carbon6's own loop the parent's tools. A combination that leaves no tool is refused.
- No hosted search where the parent has none: Settings' "all of Claude Code's tools" doesn't apply to it then.
- The depth limit applies to the bridge's
Taskas to any Claude Code session.
Tool lists from routing rules
Settings → Model routing (Routes) has a Tools field: comma-separated names; empty means all tools. The API (settings.routes.put, PUT /api/v1/settings/routes) uses a JSON array. For example, a rule for a local mail session could include:
{
"name": "Mail locally",
"applies_to": ["mail"],
"connection": "ollama",
"model": "qwen3.6:27b",
"tools": ["mail_threads", "mail_thread", "memex_search", "memex_get", "remember"]
}
The first enabled matching rule supplies the list when it picks a new session's model. Starting with an explicit model bypasses routing, including its tools. Only the listed tools' definitions are sent to the model; a deny policy still sends the definition and refuses calls, so it does not save that prompt space. An unavailable conditional tool (such as mail without mail access) stays unavailable even when listed. A nonempty list with no available tools gives the model no tools.
Names use the same matching as named agents, across profiles: read/Read/read_file, bash/Bash/shell, edit/Edit/apply_patch/MultiEdit, update_plan/TodoWrite, load_skill/skill/Skill, and snake_case/PascalCase pairs such as memex_search/MemexSearch. Saving rejects unknown built-in names and lists the valid names. Optional tools (memex, mail, calendar, chat, skills, web search and browser) are valid even before their services are available. MCP tools use their full, case-sensitive mcp__<server>__<tool> name. They are discovered at runtime, so saving checks only the shape: nonempty server and tool parts, with ASCII letters, digits, _ and -; it does not require a configured server.
A session keeps its starting list, like its hooks, MCP servers and skills. Editing a rule affects new sessions; resuming or restarting a worker keeps the saved list. Side chats inherit their parent's list, and carbon6 subagents inherit it in every model profile. A named agent's list can only narrow it. Leave task/Task in the list to allow carbon6 sessions to start subagents.
The assistant runs in the head with its own tools and is unaffected. In Claude Code sessions the list narrows carbon6's tools on the MCP bridge and the coding tools Claude Code keeps (Bash, Read, Write, Edit); its others are off (background.md §4). A Claude Code parent's carbon6 subagents inherit the saved list, and a hand-over to carbon6's loop applies it.
With a list, the stock base-prompt sentences about file and shell tools are omitted when the required tools are removed. Memory notes remain, with remember and forget instructions only for the available tools. The secrets section needs a shell tool or browser; the skills index needs the skill loader; task-card guidance needs both task_propose and task_withdraw. The stock tool instructions in memex briefs and side-chat notes are also omitted when their tools are removed. Without a list, or with those tools retained, the prompt bytes stay the same. The editable session.base is not rewritten: assembly removes only the exact stock tool sentences. Keep any custom tool instructions consistent with your lists.
Records
SubagentSpawned.model and the child's session row (connection_id, model, effort) name where it runs, so the thread header shows "connection · model" and its cost is priced on its own connection. Changing the session's default writes SubagentModelSet (applied with its command id, replayed on reload) and updates sessions.subagent_connection_id, subagent_model and subagent_effort. A change made while a turn runs applies to that turn's next Task call.
Claude Code sessions
Claude Code never sees carbon6's tools, so for as long as its process runs the worker serves Task and SendMessage to it as a local MCP server: streamable HTTP on 127.0.0.1, behind a secret path that lasts as long as the process, passed with --mcp-config. Claude Code knows them as mcp__carbon6__Task and mcp__carbon6__SendMessage. They can run in the background: the report reaches Claude Code as a notice written to its process (background.md §4). mcp__carbon6__TaskOutput and mcp__carbon6__TaskStop check on and stop them. The subagent shows as a thread under the call (matched by tool name and arguments in the log), and stopping the turn stops a foreground one. Claude Code's own Task subagents, where Settings keeps all of Claude Code's tools (by default its subagent tool is off: background.md §4), are still mirrored read-only (§8); what Claude Code says under a call of one of carbon6's MCP tools is not mirrored (it would show as an empty copy of carbon6's subagent). A subagent of a Claude Code session publishes, remembers and notifies through its parent (its files are in the parent's Outputs), and runs the head's hooks and policies itself, since its parent's run in the CLI. A subagent of a Claude Code session gets the head's hooks and policies itself, since carbon6 runs none for its parent; the parent's own calls of carbon6's tools over the bridge are checked against its policies (background.md §4).