Sub-agents, skills or flows?
Quick start
Give each sub-agent adescription (the lead model reads it to choose), then
pass them to the lead as subagents:
AgentExecutor.execute() takes the same subagents and maxSubagentDepth
options. Use it when you need hooks or tracing on the lead run - sub-agents
inherit those (see Inheritance). Approvals work
from createAgent() too (see Approvals).
How it works
Withsubagents, the lead agent gets:
- An Available sub-agents block in its system prompt: one line per
sub-agent (
- name: description), plus a sentence saying that a sub-agent sees only the prompt it is given. - ONE tool,
task, with the input{ agent: <one of the names>, prompt: string, description?: string, background?: boolean, taskId?: string, mode?: 'new' | 'resume' | 'fork' }(descriptionis an optional 3-5 word label used in events and hooks;taskIdandmodecontinue an earlier task, see Continuing a task;subagentOptions: { continuation: false }leaves them out). - Three tools for background tasks:
agent_status,agent_awaitandagent_cancel(see Background sub-agents).
task, the named sub-agent runs on prompt alone. The
tool result is the sub-agent’s final text plus a small footer the lead can
use:
maxSteps, stops at
a budget limit, or is aborted - the lead gets an error result (isError: true)
that says why, for example Sub-agent 'researcher' used all 10 of its steps (maxSteps) without giving a final answer. An unknown agent name is also an
error result listing the valid names. An answer cut off at the sub-agent’s
output token limit (finish reason 'length') is still returned, with a line
after the footer saying it may be incomplete. A sub-agent with an output
schema that runs out of steps makes one last forced call
(Out of steps): when that call returns
a valid object, the task result is that object (finish reason 'max-steps'
in the footer, plus a line saying the steps ran out), not an error. Sub-agent
token usage is added to the lead’s result.usage, a
remote sub-agent’s too. The lead’s own result.toolErrors
counts only the lead’s tool calls; the calls that failed inside its sub-agents
(and theirs) are counted on result.usage.delegated.toolErrors.
Errors at setup time are thrown with a fix: a sub-agent without a
description, a value that is not a createAgent() agent, or a tool of your
own already named task (or agent_status, agent_await, agent_cancel).
Continuing a task
Eachtask call runs in a child conversation with a taskId (task_1,
task_2, … in the footer). The lead can come back to it:
The model learns this from the
task tool description, so asking a follow-up
needs no code. A lead that keeps its work across turns or restarts needs a
store and a session:
- With
createAgent({ store })(store.sessions) and a lead run that has asessionId(a checkpointedsend(message, { sessionId })or a session turn), each task is saved instore.sessionsafter its run, under a key hashed from the lead session id and thetaskId. They outlive the lead run: later turns of the same session, a lead resumed withagent.resume()orapprovals.resolve(), and a new process on the same durable store can continue them. AtaskIdfrom another lead session never matches. The session store has no list API, so these entries are not listed or deleted with the lead session; delete the store’s data to drop them. ForAgentExecutor.execute(), set the store withwithSubagentOptions(subagents, { sessions }). - Otherwise (no session store, or a lead run without a
sessionId) a task lives in memory for that oneexecute()/send()call: a run that pauses for approval and is resumed starts with none. A sub-agent that the approval itself resumes still answers the lead (as thetaskoragent_awaitresult), but it cannot be continued bytaskIdafterwards; use a session store for that.
stop, length or max-steps) are saved, so a
task that failed or was cancelled cannot be continued. Errors reach the lead
as structured tool errors: an unknown taskId, one of another lead session,
or one that belongs to another sub-agent fails with
LOUSHO_SUBAGENT_TASK_NOT_FOUND; a task that is still running (a background
task that has not ended) fails with LOUSHO_SUBAGENT_TASK_BUSY, telling the
model to agent_await or agent_cancel it first. The error for another
sub-agent’s taskId tells the model to omit taskId to start a new task.
A lead that never needs follow-ups can leave continuation out with
subagentOptions: { continuation: false }: the task tool then has no
taskId or mode argument, every call starts a new task, and neither the
tool description nor the prompt block mentions taskIds. Weaker lead models
sometimes pass one sub-agent’s taskId to another and waste a turn on the
error; this removes the option.
task call otherwise: it can run in the
background (it keeps its taskId), an approval inside it pauses and resumes
the lead like any sub-agent approval, and its usage counts toward the lead’s
usage and limits. The child sees its whole transcript again on every
resume, so a long-lived task costs more tokens each time.
Parallel tasks
Tool calls of one model turn run concurrently (seetoolConcurrency), so when
the lead calls task several times in one turn, those sub-agents run in
parallel. Results reach the lead’s transcript in the order the model made the
calls. Cap it with toolConcurrency on the lead (1 runs them one at a time).
Background sub-agents
Withbackground: true, task starts the sub-agent and returns at once with
{ taskId, status: 'running', agent }, so the lead can keep working (or start
more tasks) while it runs. The lead then uses:
At most
maxConcurrent background sub-agents of one lead run run at once
(default 3); further background: true calls get status: 'queued' and start
as slots free. Set it with subagentOptions on createAgent():
AgentExecutor.execute(), attach the same options to the subagents
value with withSubagentOptions(subagents, options), which returns it. On
createAgent(), subagentOptions override options attached that way.
A lead that never needs background tasks can leave them out with
subagentOptions: { background: false }: the lead then gets only the task
tool, without its background argument, and the prompt block does not mention
background tasks. That saves the three tools’ schemas and text (several hundred
tokens) on every lead request.
A background sub-agent inherits from the lead run like a synchronous one
(hooks, tracing, event listeners, usage roll-up), and maxSubagentDepth applies the
same way. Aborting the lead’s signal cancels its background sub-agents, queued
or running.
When the lead run ends
Background tasks belong to one run (oneexecute() / send() / stream()).
When that run ends, however it ends, the tasks still queued or running are
cancelled by default (their runs are aborted). With
awaitBackgroundOnFinish: true the run instead waits for them to finish
before it resolves (an aborted or failed lead run still cancels them). Either
way the run resolves only once their runs have stopped, so no sub-agent event
reaches the run’s listeners after it; with awaitBackgroundOnFinish their
events arrive before the lead’s run.done.
The result lists every background task of the run with its final status:
result.backgroundTasks holds { taskId, agent, status, elapsedMs, error?, approvalId?, toolName? } per task (the agent_status shape) and is absent
when the run started none. Use agent_await in the lead (the system prompt
tells it to) to get their answers into the conversation.
The executor hook behind this is public: ExecuteOptions.onRunEnd is called
exactly once per run, with { result } (whatever the finishReason) or
{ error }; the run settles after it returns. Background tasks are reported
on result before your onRunEnd sees it.
Limits:
- A lead run that pauses for approval (
finishReason: 'awaiting-approval') ends there: its background tasks still queued or running are cancelled (or awaited) like at any other end, and the resumed run starts with none. The resumed run is a separate run with no link to the paused one’s tasks (it may even run in another process), so they cannot be kept alive across the pause. - A background sub-agent that needs approval stops with
status: 'awaiting-approval'(with the child’sapprovalIdandtoolName); its call does not run yet. It continues only when the lead waits for it withagent_await(thetaskandagent_statustool descriptions tell the model so). Then the lead pauses on that approval, like for a synchronous sub-agent: the lead’s result hasfinishReason: 'awaiting-approval', the pending approval names the child’s call withsubagentPath: ['<agent>'], and it is listed byagent.approvals.list().approvals.resolve()(orresume()after a restart, with a durable store) runs or rejects the child’s call, lets the child finish, and the continued lead gets the child’s answer as theagent_awaitresult (status: 'done'withresult, or'failed'). The child’s usage is added to the lead’s, and its conversation is saved under itstaskIdlike any task’s, sotask({ taskId })can continue it. - If the child pauses again, the lead pauses again with the next approval. If
one
agent_awaitcall waits on several tasks that are all paused, the lead pauses on them one after another, then that call returns every answer at once. - A task that is still
awaiting-approvalwhen the lead ends without having awaited it is reported inresult.backgroundTaskswith that status and cannot be resumed: the model chose not to wait for it.
Dynamic catalogs
Instead of a fixed record, pass a catalog withlist() and resolve(name).
list() is called at the start of every run that offers the task tool, so
the set can change between runs; resolve() is called when the lead picks a
name (return undefined for an unknown one).
Remote sub-agents
remoteAgent() uses an agent you already deployed (lousho build --target=node-server, docker or cloudflare-worker) as a sub-agent. It goes in subagents
next to local ones, and the lead delegates to it with the same task tool,
including background: true.
POST <url>/chat with
{ sessionId, input }, read as the SSE event stream, see
Deployment), sends the task prompt and returns the
remote agent’s final text (its object as JSON when the deployed agent has an
output schema, see Structured output), followed by
a footer naming the session and the taskId. A task call that resumes that taskId posts to the same remote
session, so the remote agent continues with its own history (keep it in a
store on the remote side); a remote task cannot be forked. The remote
agent sees only that prompt, and runs with its own model, tools and limits, so
the lead’s runtime (hooks, sandbox, approval store) does not reach it. The
lead run’s abort signal aborts the request. Options: url, auth, name,
description, headers, and fetch (inject one in tests; an in-process agent behind
createRouteHandler(agent, { basePath: '/' }).handler — the exported Fetch
handler, see Deployment — works as a fake
deployment: fetch: (input, init) => handler(new Request(input, init))).
Failures (the agent is unreachable, a 401 or other non-2xx answer, a malformed
stream, or a remote run that ends in an error) reach the lead as the
structured tool error with the code LOUSHO_REMOTE_REQUEST_FAILED (LOUSHO_REMOTE_UNAUTHORIZED for a 401); the token is
never part of an error or an event.
The remote run’s token usage, as the remote agent reports it on its run.done
event, is added to the lead’s result.usage: to the totals, to
usage.delegated, and to byModel['remote:<name>'] (<name> is the key in
subagents). The remote sends no per-model breakdown, so that one entry holds
its totals and the remote’s own costUsd estimate; when the remote sends no
cost, the lead’s costUsd becomes undefined. The lead trusts these numbers:
it cannot check them. A deployment from before this change sends no usage, and
then nothing is added. A remote run that pauses for an approval adds what it
spent up to the pause, and the continuation adds only what it spent after it.
The usage arrives when the remote run ends, so the lead’s limits see it only
after the task call returns. A hand-written RemoteSubagent gets the
per-turn usage through the onUsage option of its run().
Remote approvals
If the remote run pauses for an approval, the lead run pauses on it exactly as for a local sub-agent:result.finishReason is 'awaiting-approval', and the
pending approval in agent.approvals.list() (and in channel buttons, the dev
chat and ACP permission requests) has the remote tool’s name and input, with
subagentPath: ['researcher']. A remote ask_question call arrives as a
question (kind: 'question') that agent.approvals.answer() answers.
Deciding it on the lead (resolve, streamResolve, answer) posts the
decision to the remote agent’s approvals route
(POST <url>/chat/<session>/approvals/<id>), reads the continuation, and its
final answer becomes the task result; a continuation that pauses again pauses
the lead again.
taskId and the sub-agent’s name, so a fresh lead process on
the same store can decide it; the bearer token is never stored (it is read from
the remoteAgent() options again). A failure while deciding (a 401, any other
non-2xx answer such as the remote’s 404 for an approval no longer pending, a
network error) is the structured tool error of that task call with the codes
above, and the lead run continues. Only a run without an approval store (a bare
AgentExecutor) still fails the task with LOUSHO_SESSION_AWAITING_APPROVAL,
naming the remote session and approval id to decide on the remote agent.
remoteAgent() covers agents deployed over HTTP. A different kind of
“remote” sub-agent is another agent framework’s runner used in process -
build one against the same contract with defineRemoteSubagent() (below) or
use the ready-made Pi adapter.
Pi coding-agent sub-agents (piAgent())
piAgent() runs a Pi coding agent
(@earendil-works/pi-coding-agent, an optional peer - npm install @earendil-works/pi-coding-agent) in process as a sub-agent. It is Node-only:
Pi’s tools (read, bash, edit, write, …) work on a local directory.
task call is one Pi session: the task’s sessionId becomes the Pi
session id, so a taskId resume - and the resume after an approval pause,
even in a fresh process - reopens the same session file and the next prompt
continues its transcript. A pi task cannot be forked (the task call fails
with the remote-session “cannot be copied” error). Options: cwd (required),
model, modelRuntime, description (required), name, permissions,
agentDir, sessionDir, tools (a Pi tool allowlist), thinkingLevel.
The permissions rules gate every Pi tool call (the Pi tool_call
extension event fires before the tool runs): deny refuses the call, and
ask pauses the lead run for approval exactly like a remote sub-agent’s -
result.finishReason is 'awaiting-approval' and the pending approval
carries the Pi tool name, its arguments and subagentPath. Approving tells
Pi the call was approved and lets that exact tool name + arguments call run
once (Pi has no “run the blocked call” API, so the model re-issues it and
the gate allows that one call); rejecting sends the decision’s note as the
next user turn and the denied call never runs. Without an approval store an
ask is refused outright. A paused Pi run keeps its usage on the pause and
its continuation reports the rest, the same accounting as remoteAgent().
SubagentApprovalPause (now exported) is what such an adapter throws to
pause the lead; defineRemoteSubagent(impl) registers any object matching
RemoteSubagent for use in subagents, so a task call routes it through
the remote path.
Depth
maxSubagentDepth (default 1) bounds how deep sub-agents nest. With the
default, the lead can call sub-agents but they cannot call sub-agents of their
own: a run at the limit is simply not offered the task tool, even if it was
created with subagents. maxSubagentDepth: 2 lets the lead’s sub-agents
delegate once more. The top-level run’s value applies to the whole tree; a
sub-agent’s own maxSubagentDepth only matters when it runs as a top-level
agent.
What a sub-agent inherits
The sub-agent keeps its own instructions, model/provider, tools, skills andmaxSteps, and its context is isolated. From the run that called it, it
inherits:
Hooks inside sub-agents
See Hooks for the hook points and outcomes. A parent’s hooks apply to its sub-agents by default.ctx.subagent tells a
hook it is running inside one - the sub-agent’s name, its depth (1 for a
sub-agent of the top-level run), the lead’s toolCallId that started it, and
the enclosing sub-agent as parent when nested deeper. A hook that should only
see the top-level run returns early:
Events
agent.stream() / AgentExecutor.stream() on the lead stream each
sub-agent’s run inside the same stream - steps, text deltas, tool events and
errors - with a subagent field on every one of its events, so a UI can nest
sub-agent activity under the lead’s task call (subagent.toolCallId). See
Streaming: sub-agents.
A listener on the lead (createAgent({ onEvent }) or onAgentEvent) gets
the same events, sub-agents’ included, as they happen. See
Listening without iterating.
Approvals inside a sub-agent
When a sub-agent calls a tool thatneedsApproval, the whole run pauses:
the lead’s send() resolves with finishReason: 'awaiting-approval' and
an approvalId, and the approval store holds ONE record whose pending call is
the sub-agent’s call (toolName, args) with subagentPath naming the
sub-agents it runs inside (e.g. ['researcher']). Approve or reject it with
lead.approvals.resolve({ id, approved }) (the lead already knows its
subagents; the in-memory approval store is the default, so no approvalStore
is needed):
task result, and then
continues the lead. If the sub-agent needs another approval, the run pauses
again with a new approvalId. This works at any depth.
The lead’s approve option decides its sub-agents’ calls too.
Guarantees and limits:
- No call runs twice and none is lost: the sub-agent’s paused state is stored
inside the lead’s approval record (plain JSON, so any
ApprovalStoreworks), and the approved call runs exactly once, on resume. - Other tool calls of the same lead turn that finished keep their results and are not run again.
- One approval is pending per run. If two sub-agents pause in the same turn,
the run pauses on the first (in call order); the second sub-agent stops and
the lead gets an error result for that
taskcall saying its call was not run, so it can ask again after the approval. - A
taskcall’s pre/post tool hooks fire again on resume, like the hooks of any approved tool. - A sub-agent whose definition changed since the pause (instructions, model
or tools) is handled by the lead’s
onAgentDrift, like the lead itself:'error'rejects the resume and leaves the approval pending,'warn'(the default) warns and emitsagent.driftwithsubagentset. A sub-agent that no longer has the approved call’s tool always rejects withLOUSHO_RESUME_TOOL_MISSING. See Resuming with a changed agent. - Token usage keeps adding up across the pause: the sub-agent’s usage before
the pause is in the paused result, and what it spends after the resume is
added to the resumed lead’s
result.usage. - A background sub-agent’s approval pauses the lead when the lead awaits it
with
agent_await; see Background sub-agents.
Advanced: the executor API
WithAgentExecutor.execute() as the lead (see
the executor API), the run needs an approvalStore;
without one, the sub-agent’s call becomes an error result and nothing runs.
Resume with resumeAfterApproval(), passing the same subagents option as the
paused run: