subagents
js/ai/subagents.ts
fino:ai/subagents — durable child agents a parent agent can fan work out to.
A SubagentPool lets one parent conversation delegate focused tasks to
child agents that run concurrently. Each child is an ordinary
fino:ai/session thread in the parent's AtomicStore. The parent plays the
user role in it — the task prompt and every follow-up are user messages —
and the child is the assistant. subagentTools() hands the pool to a parent
model as tools: spawn (returns at once), status, send, a blocking wait,
finalize, and cancel.
Lifecycle
working— a run is being driven by this pool.awaiting_approval— a gated tool call suspended the child. Human approval passes through unchanged: the application callsapprove()orreject(); the parent model cannot.awaiting_input— the child suspended for input;send()answers it.awaiting_review— the child's run finished. The parent either accepts it withfinalize()or keeps iterating withsend().done,failed,cancelled— finalized, errored, or cancelled.send()revives any of them with a new run on the same thread, so a child keeps its whole conversation across parent turns.
Children report completion through the subagent_complete tool handed to
buildAgent as ctx.completeTool; the report is shown to the parent when
the run that made it is reviewed.
Storage model
The pool stores one small record per child — spec, name, thread id, the
latest completion report, and a close marker — in its own namespace of the
store. Everything else is read from the child's session data: status comes
from the run that committed the thread head (ThreadState.runId), and
reports and close markers apply only while that same run is the head, so a
revived child never shows a stale report or a stale done.
SubagentPool.open() rebuilds a pool from those records after a restart:
runs whose checkpoint says running are re-driven with Session.resume(),
children that never reached a first checkpoint are started again from
their task, and suspended children surface their original resume tokens.
Failed runs are not retried automatically; send() revives them.
Limits
- One live pool per pool id. Two processes opening the same pool would both re-drive interrupted runs; the session layer rejects the second commit, which then fails that child.
send()to aworkingchild is refused rather than steering it mid-run; wait for it to settle or cancel it first.- Child agent events are not forwarded. Observe
watch()for status andhistory()for the conversation.
import { agent } from 'fino:ai/agent';
import { anthropic } from 'fino:ai/model';
import { sqliteStore } from 'fino:store';
import { session } from 'fino:ai/session';
import { SubagentPool, subagentTools } from 'fino:ai/subagents';
const store = await sqliteStore({ path: '.fino/sessions.db' });
const pool = await SubagentPool.open({
id: 'parent-thread',
store,
buildAgent: (spec, ctx) =>
agent({
model: anthropic({ model: spec.model ?? 'claude-sonnet-4-5' }),
instructions: `You are a sub-agent. Task: ${spec.task}`,
tools: [ctx.completeTool],
}),
});
const parent = session({
store,
threadId: 'parent-thread',
agent: agent({ model: anthropic(), tools: subagentTools(pool) }),
});
await parent.start('Split the audit across two sub-agents and merge their findings.');Interfaces
interface SubagentSpec {
What to spawn. Stored verbatim and passed to buildAgent again when the
pool reopens, so it must be structured-cloneable and buildAgent must give
the same agent for the same spec.
Properties
task: string
Task prompt delivered to the child as its first user message.
name?: string
Display name; defaults to agent-<n>.
model?: string
Model id for the child; buildAgent decides what omission means.
readOnly?: boolean
Request read-only capabilities; buildAgent decides what that means.
interface SubagentBuildContext {
Context passed to buildAgent alongside the spec.
Properties
id: string
Pool-assigned child id.
completeTool: Tool
The child's subagent_complete tool; include it in the child's tools.
interface SubagentState {
Snapshot of one child.
Properties
id: string
Pool-assigned id, echoed by every subagent tool.
name: string
Display name.
spec: SubagentSpec
Spec the child was spawned from, with its resolved name.
status: SubagentStatus
Current lifecycle status.
threadId: string
Durable thread id of the child conversation.
runId?: string
Run that committed the child's thread head, once one has.
report?: string
Summary reported through subagent_complete during that run.
text?: string
Final assistant text of that run when it finished.
error?: string
Failure message while failed.
approval?: { token: string; request: ToolApprovalRequest }
Pending tool approval while awaiting_approval.
input?: { token: string; reason?: string }
Pending suspension while awaiting_input.
usage: Usage
Token usage of that run.
interface SubagentPoolOptions {
Options for SubagentPool.open().
Properties
id: string
Stable pool identity, conventionally the parent's thread id. Children
use <id>:<childId> as their thread ids.
store: AtomicStore
Store shared with the parent session.
buildAgent: (spec: SubagentSpec, ctx: SubagentBuildContext) => Agent | Promise<Agent>
Build a child agent; called on spawn and again whenever a run is driven.
Types
type SubagentStatus =
| 'working'
| 'awaiting_approval'
| 'awaiting_input'
| 'awaiting_review'
| 'done'
| 'failed'
| 'cancelled'
Lifecycle status of a child; see the module's lifecycle section.
Classes
class SubagentPool {
A parent conversation's durable set of child agents.
Open one with SubagentPool.open(); the constructor is private. Children
run independently and concurrently. Every method that starts work
(spawn, send, approve, reject) returns once the work has started;
use waitForSettled() or watch() to follow it.
Static Methods
static async open(opts: SubagentPoolOptions): Promise<SubagentPool>
Open the pool opts.id in opts.store, restoring its children and
resuming interrupted work as described in the module's storage model.
Resolves once every child's state is loaded; resumed runs continue in the
background.
const pool = await SubagentPool.open({ id: threadId, store, buildAgent });
console.log(pool.status().map((child) => `${child.name}: ${child.status}`));Methods
async spawn(spec: SubagentSpec): Promise<SubagentState>
Spawn a child and return its initial state; its first run starts at once.
Throws a TypeError for an empty task or a non-string name.
const child = await pool.spawn({ task: 'List every caller of loadConfig()', name: 'callers' });status(): SubagentState[]
Snapshot every child in spawn order.
for (const child of pool.status()) console.log(child.id, child.status);status(id: string): SubagentState
Snapshot one child; throws for an unknown id.
status(id?: string): SubagentState | SubagentState[]
watch(): ReadonlySignal<SubagentState[]>
Signal holding status(), updated on every checkpoint and transition.
pool.watch().subscribe((children) => render(children));send(id: string, text: string): void
Send a message from the parent. An awaiting_input child is resumed
with it; any other settled child starts a new run on its thread with
the message as the user turn. Throws while the child is working
(no mid-run steering) or awaiting_approval (use approve() /
reject()).
pool.send('sa_1', 'Also check the test helpers.');approve(id: string, opts: { approval?: unknown } = {}): void
Approve a child's pending gated tool call and continue its run.
opts.approval is forwarded to the tool's execution context.
reject(id: string, reason?: string): void
Reject a child's pending gated tool call with a model-visible reason.
async finalize(id: string): Promise<SubagentState>
Accept a child's finished run. Only valid while awaiting_review; the
child shows done until a later send() revives it.
async cancel(id: string): Promise<SubagentState>
Cancel a child. A working run is aborted and commits a cancelled
checkpoint; a child waiting on approval, input, or review is closed as
cancelled without touching its run. Finished and failed children are
left as they are. Resolves once the child is no longer working.
async waitForSettled(
opts: {
ids?: string[];
mode?: 'all' | 'any';
includeApprovals?: boolean;
signal?: AbortSignal;
} = {},
): Promise<SubagentState[]>
Wait until children settle: awaiting_input, awaiting_review, done,
failed, or cancelled. A pending approval counts as unsettled — a
human decision is part of the work — unless includeApprovals is set.
mode: 'all' (the default) resolves when every targeted child has
settled, 'any' when one has. Resolves immediately with no targets and
rejects when signal aborts. Resolves with the settled targets.
async history(id: string): Promise<ModelMessage[]>
Render a child's committed conversation; empty before its first checkpoint.
Getters
get active(): boolean
Whether any child is working or waiting on an approval decision.
Functions
function subagentTools(pool: SubagentPool): Tool[]
The parent-side tool set for a pool.
subagent_spawn returns an id at once; subagent_wait blocks inside the
tool call, which keeps the parent's turn active while children work;
subagent_send answers or revives a child; subagent_finalize accepts a
finished child; subagent_cancel stops one; subagent_status reads state.
Misuse — an unknown id, sending to a working child — returns an error
result the model can recover from rather than failing the parent run.
const parent = agent({ model, tools: [...workspaceTools, ...subagentTools(pool)] });