Skip to content
pleach
Build

Subagents

Spawn child runtimes from a tool call. Every child call lands on the ledger with its parent turn, root turn and subagent depth — fan-out rolls back to the user turn.

A subagent is a child runtime spawned from a tool call. The parent turn pauses on the subagent's tool, the subagent runs its own anchor-plan → tool-loop → synthesize → post-turn cycle, and the result bubbles back to the parent as the tool result. Every call the child makes lands on the same audit ledger with parent-turn, root-turn and subagent-depth fields set, so a group-by on the root turn rolls nested fan-out, at any depth, back to the user message that caused it. See Event log for the broader projection surface.

Subagent is one of three concepts in the composing-agents cluster, alongside the skill that defines the spec and the agent profile that records every invocation. The subagent is the runtime spawn; the skill is the durable definition; the profile is the rolling signal that decides whether the spec gets routed to again.

Subagents are off by default — the substrate runs strictly serial. Enable them when the parent agent decomposes work into independent subtasks (research fan-out, multi-document analysis, parallel benchmark runs).

import {
  SubagentManager,
  createSubagentManager,
  SUBAGENT_LIMITS,
  buildDependencyGraph,
  topologicalSort,
} from "@pleach/core";
import type {
  Subagent,
  SubagentStatus,
  SubagentTask,
  SubagentSpawnConfig,
  SubAgentConfig,
  SubAgentHandle,
  SubAgentResult,
  SubAgentToolCall,
  SubagentSessionFlags,
} from "@pleach/core";

// LightweightSessionRuntime, the workspace-context helpers, and the
// WorkspaceContext type ship only from the `@pleach/core/subagents`
// subpath — they are not re-exported from the root barrel.
import {
  LightweightSessionRuntime,
  fetchWorkspaceContext,
  formatWorkspaceContextPrompt,
} from "@pleach/core/subagents";
import type { WorkspaceContext } from "@pleach/core/subagents";

Enabling subagents

import { SessionRuntime } from "@pleach/core";

const runtime = new SessionRuntime({
  storage: supabaseAdapter,
  enableSubagentConcurrency: true,
  maxConcurrentSubagents:    4,
  userId: "user_123",
});
Config fieldDefaultEffect
enableSubagentConcurrencyfalseMaster switch
maxConcurrentSubagents4Cap on the SubagentManager (the host-driven queue path)

Bare core needs a host-supplied executor

The flags above turn the surface on; they don't make a subagent run on bare @pleach/core. The runtime's default executor is a no-op that returns an "executor not configured" failure, so the spawn emits subagent.spawned then subagent.failed with no work done. To actually run subagents the host supplies a subagentExecutor on SessionRuntimeConfig (the LLM call is bring-your-own) and/or drives the SubagentManager itself. Without that wiring the model is offered no delegation tool and spawns don't execute. @pleach/core provides scheduling and lifecycle, not the model call.

createToolLoopSubagentExecutor is the in-core option: it runs the child's model calls on the parent's provider stream. See the tool-loop executor.

Two concurrency paths exist, and they cap differently.

The imperative spawn path (runtime.async.spawn / spawnAgent) caps on the hard SUBAGENT_LIMITS.maxConcurrent constant (3), not on maxConcurrentSubagents. When the active subagent count is already at that limit, the spawn does not queue or wait — it returns a failed SubAgentResult (status: "failed", error Sub-agent concurrency limit reached) and emits subagent.spawned immediately followed by subagent.failed. Depth behaves the same way: exceeding SUBAGENT_LIMITS.maxDepth (3) rejects the spawn rather than queuing it.

maxConcurrentSubagents (default 4) caps the SubagentManager — the queue/DAG fan-out component. The runtime constructs a SubagentManager when enableSubagentConcurrency is set, but does not drive it on the imperative spawn path. The queue, buildDependencyGraph, and topologicalSort are a host-driven surface: a host that wants queue-on-cap (rather than fail-on-cap) fan-out orchestrates the SubagentManager directly.

How a subagent gets spawned

Spawns are imperative in bare @pleach/core — there is no metadata-flag auto-escalation. The entry points are:

  • runtime.async.spawn(config) (or the @deprecated runtime.spawnAgent(config)) — the host or a tool calls it directly with a SubAgentConfig.
  • The SubagentManager API — createSubagentManager(...) then its spawn/queue methods, for host-driven fan-out.
  • A host OrchestratorAdapter that surfaces delegation tools (an embedding host might use a delegate_to_* prefix; the prefix is host-configurable via delegationToolPrefix). The model calling one of those tools routes through the host's subagentExecutor.

There is no spawnsSubagent: true tool-metadata flag in core (the field does not exist), and bare core wires neither a planner-emitted subagent task nor an intent-classifier route to a spec — those are host responsibilities.

When a spawn runs, the runtime allocates a LightweightSessionRuntime and dispatches through the configured subagentExecutor.

Namespacing in the event stream

Every event a subagent emits carries namespace: string[]. Empty array for the root orchestrator; populated for events emitted from inside a subagent.

for await (const event of runtime.executeMessage(sessionId, prompt)) {
  if (event.namespace && event.namespace.length > 0) {
    // Subagent event — route to a sub-panel
    renderInSubagentPanel(event.namespace, event);
  } else {
    renderInRootPanel(event);
  }
}

The namespace path is the subagent tree — a subagent that itself spawns a subagent emits events with namespace: ["parent", "child"]. UIs render this as a tree of nested transcripts.

Subagent lifecycle events

Four stream events bracket a subagent's life:

EventPayloadWhen
subagent.spawned{ subagentId, task, specName?, context? }Allocated; runtime is starting it
subagent.progress{ subagentId, progress, message?, activeToolName? }Periodic progress update
subagent.completed{ subagentId, content, toolsUsed, toolCallDetails? }Finished cleanly
subagent.failed{ subagentId, error, terminalStatus?, code? }Errored; terminalStatus discriminates cancelled / failed / timeout. code is a closed failure code

progress is 0–1. activeToolName lets a UI show what the subagent is currently doing without subscribing to its full event stream.

Durable subagent audit rows

The four events above are the live stream. The audit ledger also records subagent activity durably, one row per tool the subagent uses: subagent.tool_used carries { subagentId, payload: { tool_name } }, while subagent.completed and subagent.failed land as terminal rows (the failed row carries terminal_status). The failed row doesn't store the error text, which can quote a provider response or the user's prompt. Its error is a fixed line, Sub-agent failed; the error detail is withheld., and three fields describe the failure: code, error_class and message_length. Branch on code, not on text. These are what a replay or an audit query reconstructs a subagent's tool history from after the turn — independent of whether any UI was subscribed to the stream.

WorkspaceContext

Live workspace state a subagent can inherit when its spec is workspaceAware. Queried from a sandbox-style execution environment at spawn time so the subagent doesn't burn a turn asking what's installed.

interface WorkspaceContext {
  pythonVersion: string;
  packages:      Array<{ name: string; version: string }>;
  cliTools:      string[];
  disk?:         { total: string; used: string; available: string; usePct: string };
  fileCount:     number;
  files?:        string[];
}

fetchWorkspaceContext(sandbox) queries a sandbox connection and returns the snapshot (or null if the sandbox isn't active — callers proceed without context rather than failing the spawn). By default it posts the query to the connection's ${tunnelUrl}/exec. When the caller can't reach the sandbox directly (browser code behind a Content-Security-Policy, say), pass a transport as the second argument and route the query through your own same-origin endpoint instead. With a transport the connection needs no tunnelUrl or sessionToken:

import type { WorkspaceContextTransport } from "@pleach/core/subagents";

const transport: WorkspaceContextTransport = ({ command, timeout, signal }) =>
  fetch("/api/sandbox/exec", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ command, timeout }),
    signal,
  });

const context = await fetchWorkspaceContext(sandbox, { transport });

The transport returns the /exec response; its JSON body carries stdout. formatWorkspaceContextPrompt(ctx) renders the snapshot as a prompt section. setDomainClassifierPatterns(patterns) configures the file-classification heuristic that picks which files surface in files.

A workspace-aware subagent needs the host to supply the sandbox connection. Hosts wire one in via the contributeSandboxBridge plugin hook — see Plugin contract for the bridge surface.

SubAgentConfig and the spawn surface

interface SubAgentConfig {
  task:                 string;
  name?:                string;       // spec name; default "general-purpose"
  tools?:               string[] | "inherit" | "none";
  context?:             { conversationSummary?: string; variables?: Record<string, unknown> };
  maxSteps?:            number;       // default 5
  maxDepth?:            number;       // checked at spawn time
  timeout?:             number;       // default 120_000ms
  streamProgress?:      boolean;
  systemPromptSuffix?:  string;
  resumeId?:            string;       // resume a prior subagent's transcript
}

interface SubAgentHandle {
  id:        string;
  status:    "cancelled" | "completed" | "failed" | "pending" | "running";
  progress?: number;  // 0–100
}

interface SubAgentResult {
  id:        string;
  status:    "cancelled" | "completed" | "failed" | "timeout";
  content:   string;
  toolCalls: SubAgentToolCall[];
  error?:    string;
  metrics:   {
    totalSteps:    number;
    durationMs:    number;
    inputTokens?:  number;
    outputTokens?: number;
  };
  transcript?:    Array<{ role: string; content: unknown }>;
  agentName?:     string;
  checkpointId?:  string;
  turnMetrics?:   {
    successfulToolNames: string[];
    failedToolNames:     string[];
    turnHadFailedTools:  boolean;
    retryCount:          number;
    totalToolCalls:      number;
  };
}

`context.variables` is currently inert

context.variables is accepted on SubAgentConfig but the runtime does not consume it — when a spawn supplies it, the runtime logs a warning (context.variables provided but executor does not consume them; embed into context.conversationSummary or task) and proceeds without it. Put anything the child needs into context.conversationSummary or task instead.

SubagentSessionFlags propagates parent-session state into the child so the subagent doesn't re-offer tools the parent already knows are unavailable:

interface SubagentSessionFlags {
  sandboxUnavailableInSession?: boolean;
  filteredToolNames?:           string[];
}

LightweightSessionRuntime

Subagents run on LightweightSessionRuntime — a slimmer SessionRuntime variant that shares the parent's storage, checkpointer, and plugin set but isolates its channels and event stream. It is exported from the @pleach/core/subagents subpath, not the root barrel.

import { LightweightSessionRuntime } from "@pleach/core/subagents";

// Usually you don't construct this directly — the SubagentManager does.
// Direct construction is for testing or custom orchestration:
const sub = new LightweightSessionRuntime({
  parentSessionId:      runtime.sessionId,
  agentName:            "research-fanout",
  parentPluginManager:  pluginManager,   // optional
  store:                baseStore,        // optional (BaseStore)
  sessionFlags: {                         // optional
    sandboxUnavailableInSession: false,
    filteredToolNames: [],
  },
});

The lightweight runtime inherits:

From parentWhat
Storage adapterReads + writes the same DB; isolated subagent_id column scope
CheckpointerSubagent checkpoints land in the same store with parent-id provenance
Plugin setPlugins are shared; per-subagent contributions are filtered by scope
Audit ledgerSubagent calls write to the same ledger with the subagent's id

What's isolated:

  • Channels — the subagent has its own per-channel state
  • Event log namespace — events tagged with the subagent's path
  • Tool registry filter — subagents typically run a narrower tool set than their parent

SUBAGENT_LIMITS and depth tracking

Hard limits the substrate enforces independently of consumer config:

const SUBAGENT_LIMITS = {
  maxDepth:      3,        // parent → child → grandchild
  maxConcurrent: 3,        // concurrent subagents per session
  maxPerTurn:    5,        // subagents spawned in one turn
  timeoutMs:     120_000,  // default timeout
} as const;

Depth is checked at spawn time — exceeding maxDepth rejects the spawn rather than proceeding into a fourth nested runtime.

maxPerTurn is enforced inside SessionRuntime.spawnAgent by a per-turn spawn ledger (PerTurnSpawnLedger, one per runtime). It counts every spawn a turn makes across all of its tool-loop steps, not one tool batch. The sixth spawn in a turn doesn't throw. It returns a failed SubAgentResult whose refusal is { kind: "spawnsPerTurn", limit: 5, actual: 6 }. The guard runs last in the ladder, so only a spawn that will actually run uses a slot.

A different cap throws. maxSubagentFanOutPerTurn (default 10) bounds the spawn() child-runtime factory and raises SubagentFanOutExceeded (exported from @pleach/core), alongside maxSubagentDepth and maxSubagentTotalPerRootTurn. The two caps count different paths.

SubAgentToolCall.resultPreview is truncated at 400 characters so the per-step records on the parent's SubAgentResult.toolCalls stay bounded. turnDepth on RuntimeStateSnapshot (passed to runtime-aware prompt contributions) reports the same value the subagent sees.

The depth value is also what lands on every AuditableCall row emitted from inside a subagent — payload.subagentDepth carries 1 for a direct child, 2 for a grandchild. The ledger also writes it to its own depth field, so grouping by depth answers "how much did the fan-out tier cost relative to the root turn." The same field threads through llm.turn.depth on the stream, so a UI panel can colour-code per-tier spend without joining back to the ledger.

Authoring subagent specs

A subagent spec is an entry in a registry you own: a SubAgentSpec with a name, a description, the tools it may use and a step budget. The model delegates by calling spawn_agent with a task for ad-hoc work, or a delegate_to_* tool generated from the registry (see Distinct delegate_to_* tools).

Skills are a separate surface. A skill is a markdown file with YAML frontmatter, loaded by SkillLoader from @pleach/core/skills, whose body is prompt content. Its intents field is one signal for when the skill is surfaced: a skill with activation: auto or intent-matched is offered on a turn whose detected intent is listed there.

A minimal skill file at skills/builtin/research-fanout/SKILL.md:

---
name: research-fanout
description: Fan out searches across multiple sources in parallel.
allowed-tools:
  - search_corpus
  - search_news
intents:
  - research
  - literature_review
activation: intent-matched
---

Run each search in parallel and synthesise the results into a single
structured report.

Specs passed in the subagentSpecs array of the SkillLoader constructor are also loaded as builtin, manual-activation skills. A spec whose name matches an existing skill file is skipped.

The other direction is opt-in. A skill that carries an execution block can be derived into a SubAgentSpec with deriveSubAgentSpecs from @pleach/core/skills. Add the derived specs to your registry and create a tool for each with createDelegateToolLite from @pleach/core/subagents. The spec's tools come only from the skill's allowedTools (none when there is no list); the tool-loop executor narrows them against the parent and adds the read-only pull tools to a non-empty list. createToolLoopSubagentExecutor runs the agent with no way to delegate further. promoted skills are not converted. See Skills as sub-agents.

See Skills for the full Skill shape, the three-source merge order, and the getByIntent / getByName loader API.

Distinct delegate_to_* tools from a spec registry

The generic spawn_agent tool takes a task ({ task }), and its optional name is only a role label in the child's prompt. An alternative that measurably improves the model's routing accuracy is to give it a DISTINCT tool per specialist — delegate_to_research, delegate_to_compound, … — each carrying that spec's own description. createDelegateTools generates them from your registry:

import { createDelegateTools, type SubAgentSpec } from "@pleach/core/subagents";

const SPECS: Record<string, SubAgentSpec> = {
  research: { name: "research", description: "Multi-source literature fan-out.", tools: ["search_corpus"], maxSteps: 6 },
  // …your specialists
};

const delegateTools = createDelegateTools(SPECS);
// → [{ name: "delegate_to_research", description: "Delegate a task to the research specialist agent. …", … }]

The definitions carry a name, a description and parameters, and no handler. Your tool handler maps a delegate_to_* call back to its spec and spawns the child. Build the config with subAgentSpecToConfig so the spec's prompt suffix, step budget, timeout and tool restrictions reach the spawn:

import { specNameFromDelegateTool, subAgentSpecToConfig } from "@pleach/core/subagents";

// Inside your handler for a delegate_to_* call, with `runtime` a
// SessionRuntime built with `subagentExecutor` (see "The tool-loop
// executor" below) and `args` the parsed tool arguments ({ task, context? }):
const specName = specNameFromDelegateTool(toolName, SPECS);
const spec = specName ? SPECS[specName] : undefined;
if (!spec) throw new Error(`Unknown delegate tool: ${toolName}`);

const result = await runtime.spawnAgent(
  subAgentSpecToConfig(spec, args.task, {
    ...(args.context ? { context: { conversationSummary: args.context } } : {}),
    spawnToolName: toolName,
  }),
);

subAgentSpecToConfig(spec, task, extras?) takes the spec, the task string and optional context, attribution, spawnToolName, fanOutBatchId, streamProgress and resumeId. For specs derived from skills, createDelegateToolLite does this wiring for you, including the dispatching turn's depth, so prefer it there.

It's domain-free by dependency injection: you own the registry (the domain lives in its values), and the generator maps the shape. A general-purpose spec is excluded by default (it already maps to spawn_agent); pass { exclude: [...] } to change that. The companion isDelegateTool(name) and specNameFromDelegateTool(name, specs?) identify a delegate call and map it back to its spec.

The tool-loop executor

createToolLoopSubagentExecutor is a ready-made subagentExecutor. It runs one child turn with a narrowed tool set and a bounded model-call budget, then digests the result back to the parent as a SubAgentResult. It is exported from @pleach/core/subagents.

It sits on top of SessionRuntime.spawnAgent, not beside it. Spawn guards, the sub_<uuid> id, the durable subagent.* rows, and the descendant cost push into getTurnCostRollup all stay with spawnAgent. The executor only runs the child.

import { SessionRuntime } from "@pleach/core";
import { createToolLoopSubagentExecutor } from "@pleach/core/subagents";

const runtime = new SessionRuntime({
  storage: supabaseAdapter,
  enableSubagentConcurrency: true,
  subagentExecutor: createToolLoopSubagentExecutor({
    stream: providerStream,          // the parent's StandardProviderStream
    getTools: () => registeredTools, // read at spawn time
    maxSteps: 8,                     // default 5, clamped to 1-40
    maxDepth: 2,                     // default SUBAGENT_LIMITS.maxDepth
    onModelCall: (call) => metrics.record(call),
  }),
});

stream is the same provider stream the parent turn resolved, so child calls use the parent's model. getTools returns the registry a child may be offered. A definition without execute is never offered.

Options

OptionDefaultEffect
streamrequiredProvider stream every child model call goes through
getToolsrequiredTool registry the child draws from, read at spawn time
maxSteps5Model-call budget per child. A spawn's own maxSteps wins, except for a skill-derived child (noNestedSpawn), where a maxSteps you set here is a cap that can only lower it. Clamped to 1-40
maxDepthSUBAGENT_LIMITS.maxDepth (3)A child at this depth is offered no spawn tool. A spawn beyond it fails with no model call
maxToolResultChars8000Bound on one tool result fed back into the child
maxToolCallsPerStep8Extra calls in one step are refused, not run. Ceiling 32
maxTranscriptChars120000Once spent, the next call is the final, tool-less one. Ceiling 1000000
interruptnoneinterruptBefore / interruptAfter / interruptOn from the route, used to gate tools
isApprovalGatednoneHost predicate. true, or a throw, marks a tool approval-gated for children
onModelCallnoneOne record per child model call. A throw never breaks the child
onLifecyclenonespawned, then completed or failed, per child

Pairing a child call with your cost row

Each child model dispatch gets a fresh auditLinkKey and auditInvocationId. The executor records the call's modelCall audit row with them and passes the same pair, as optional fields, on the onModelCall record. If you record your own cost or decision row for a child call, from onModelCall or from a custom recordSubagentCall, copy both onto that row's audit input. The row then pairs only with its own call.

A row that lacks them is not paired, so that call is counted twice: once on its modelCall row and once on yours. It over-counts spend and never counts a call zero times. Keep both ids server-side: never send them to a client or write them into a client-visible event.

What the child can and can't do

The child's tools are narrowed, never widened. The runtime takes the spec's tool list (tools: names, "inherit", or "none", plus any pull tools it admits), intersects it with the parent's allow-list, and removes the parent's deny-list. Then it removes two more groups:

  • Approval-gated tools. A child can't answer a human-in-the-loop pause, so the executor fails closed. That covers requiresApproval, needsApproval (a set or a function), requiresGPU, names in interruptBefore / interruptAfter, every tool when an interruptOn predicate exists, and anything your isApprovalGated flags.
  • Spawn tools at the depth cap, or when no spawn handle exists. isSubagentSpawnToolName(name) is the by-name test. It matches spawn_agent and spawn_agents (SUBAGENT_SPAWN_TOOL_NAMES), every delegate_to_* tool, and the task-start tool of a wired async-task handler factory, which is start_async_task in the standard wiring. A started task may be a sub-agent, so that tool counts as a spawn tool too.

A background sub-agent keeps the restrictions of the sub-agent that started it. When a task is enqueued from inside a sub-agent, the stored task records that frame's depth, its tool denial and its allow-list. The executor refuses a task from a frame with no spawn path, and it never starts the child shallower than the frame that enqueued it. The stored allow-list survives a checkpoint, so a task rehydrated after a restart stays inside it instead of falling back to the resuming session's tools. A stored value of the wrong shape is refused. A task that carries an inherited denial is refused when the host's executor doesn't declare that it honours containment.

Each tool call dispatches through the spawning runtime: beforeToolCall middleware, the block_tool_call safety gate, the tool pipeline, then afterToolCall. A per-call approval re-check runs first, and a positive or throwing check refuses the call. With no dispatcher the child has no tools.

A child's tools run with the child's depth. A grandchild that calls spawn re-enters spawnAgent at its real depth, so maxDepth sees it.

The loop is bounded by maxSteps. The last step offers no tools, so the loop always ends on an answer attempt. If the child uses every step without answering, the result is failed with Sub-agent used its N-step budget without an answer.. timeout is clamped to SUBAGENT_LIMITS.timeoutMs.

Each child call is billed and budgeted

Before every child model call the spawning runtime's gate runs. It checks the parent turn's budget without touching the parent's stop latch, then runs beforeModelCall middleware that opts in to sub-agent calls. A deny or a throw stops the child as failed, with no call made. This is stricter than the root path, where a middleware throw is logged and ignored.

The call is then recorded through the root recorder, so it writes one modelCall row with the root outcome taxonomy. The row is attributed to the child: subagentId, subagentDepth, and parentTurnId. It carries the usage the provider reported (never a defaulted 0) and is priced like a root call. A call cut off by Stop or timeout still gets its row.

Where the attribution is stored

parentTurnId, subagentDepth, and the derived rootTurnId are on the AuditableCall record. The Postgres provider-decision ledger writes them to dedicated parent-turn, subagent-depth and root-turn fields (plus the tool name) by default. On a table that predates those fields, it falls back to the payload only, so run the schema migration to query by field. For per-turn spend across depths, group by the root turn. For the in-process read, call runtime.getTurnCostRollup(), as described in Cost attribution.

Limits at a glance

LimitValueEnforced byOn breach
Model calls per childmaxSteps, ceiling 40ExecutorLast step is tool-less; failed if no answer
Nesting depthSUBAGENT_LIMITS.maxDepth (3)spawnAgent and executor maxDepthFailed result, no model call
Concurrent childrenSUBAGENT_LIMITS.maxConcurrent (3)spawnAgentFailed result
Spawns per turnSUBAGENT_LIMITS.maxPerTurn (5)spawnAgent per-turn ledgerFailed result, refusal.kind: "spawnsPerTurn"
Tool calls per step8, ceiling 32ExecutorExtra calls refused
Child timeoutSUBAGENT_LIMITS.timeoutMs (120_000)Executortimeout status

Cost attribution

runtime.getTurnCostRollup(turnId?) reports what one root turn cost, split by who made the call. Read it on the root runtime after the turn's stream settles.

The durable equivalent is one grouped query over the call ledger. Every row records its depth-0 root turn, so group by that and sum each call's cost. No recursive query is needed.

Rows written before the root-turn field existed carry no root turn. Across mixed history, group on the root turn, then the parent turn, then the row's own turn.

const rollup = runtime.getTurnCostRollup(); // defaults to the active turn
if (rollup) {
  rollup.self;        // calls the root runtime made itself
  rollup.descendants; // calls made by sub-agents at any depth under this turn
  rollup.total;       // self + descendants
  rollup.partial;     // true when any figure is a floor
  rollup.truncated;   // true when rows recorded before a release or eviction are missing
}

turnId accepts either turn:<userMsgId> or the bare user-message id. The method returns undefined when no cost row was ever attributed to that turn. It never returns a zero-filled rollup.

descendants holds two sources: the child calls a spawnAgent executor reports in its result metrics, and every call made by a runtime that spawn() minted under the root turn (child, grandchild, and so on). A row lands in exactly one of self or descendants.

Each of self, descendants, and total is a TurnCostBucket:

FieldMeaning
callCountModel calls attributed to the bucket, priced and unpriced.
pricedCallsCalls that carried a finite costUsd.
unpricedCallsCalls with no known cost. They are counted, never priced at $0.
costUsdSum over the priced calls. Omitted when pricedCalls is 0.
inputTokens · outputTokens · cachedInputTokens · thinkingTokensToken totals. An absent token field on a row counts as 0.

Cost rows are buffered per turn

Each in-flight turn keeps its own pending cost rows, so an earlier turn's late row can't land in a later turn's cost.rollup when turns overlap on one runtime. The seam's onCostEvent now takes a second, optional argument: onCostEvent(row, owner?). owner carries the turn signal the call ran under. A handler that takes only the row keeps working, and the owner is never written onto the row.

A row that arrives after its turn's cost.rollup is still billed under its own turn. The runtime reports each late row through its probe channel. When the row arrives after the turn's rollup was written, the turn writes one more cumulative cost.rollup for the same message id. Read cost.rollup as the row with the highest call_count per message id. Never add the rows up.

What the figures leave out

  • Background async.spawn tasks are excluded. They don't bill the spawning turn, so their spend never reaches this rollup.
  • callCount and costUsd are floors when calls are unpriced. Any unpriced call sets partial: true. An executor that reports no per-call metrics contributes one coarse row built from its token totals, so callCount undercounts its real calls.
  • total can differ from the durable cost.rollup row. Calls from a spawn() subtree are in descendants, but they never enter the root runtime's per-turn cost buffer, so the durable row doesn't include them.
  • Retention is LRU over 32 turns. The runtime keeps the 32 most-recently-recorded turns. runtime.releaseTurnCostRollup(turnId) drops one early. A row that arrives after its turn was released or evicted starts a fresh entry marked truncated: true and partial: true.

A subagentExecutor should either report its child's calls in metrics or run the child as a spawn()-minted runtime, not both. Doing both counts the same calls twice in descendants.

The quickstart route writes a snapshot of this rollup onto each turn's message.assistant row; see payload.cost_rollup.

Example: why did one question cost $11

Example: a question fanned out three levels deep and cost $11. An operator sees one user turn billed at $11, with about 40 model calls under it. The question is which spawn drove the spend, and whether the figure can be trusted.

  1. Take the call rows for that root turn and group them by subagent depth. Count calls and sum costUsd at each depth (auditable call row).
  2. Within the heaviest depth, group by parent turn to find the spawn that produced most of the calls. That is the runaway.
  3. Check the rollup flags. partial means some calls were unpriced, so $11 is a floor. truncated means rows were released or evicted before the read.
  4. Read descendants against self in runtime.getTurnCostRollup to see how much came from children rather than the root runtime.
  5. Run walkSessionTree (swarm agent) and confirm treeValid is true. A false result means a node's hash chain diverged, so treat its rows with care.

Background async.spawn tasks never reach this rollup. The record locates the spend. It doesn't say whether the spawn was a good idea.

Bounded fan-out

boundedFanout(items, { width, run, onItemError?, timeoutMs? }) from @pleach/core/subagents runs run over items with at most width in flight. Results come back in input order. A run that throws goes through onItemError when you pass one, so one bad item doesn't abort its siblings.

By default there's no per-item bound, and a run that never settles holds its worker forever. Set timeoutMs to race each item against a deadline. A timed-out item behaves like a thrown run: it goes to onItemError, or rejects the whole call without one. The error is a BoundedFanoutTimeoutError carrying the deadline it hit. The attempt is abandoned, not cancelled, so pass an AbortSignal into run if the work supports one. Omitted or non-positive timeoutMs keeps the unbounded behaviour.

Aborting a subagent

The parent's AbortSignal propagates to every active subagent — aborting the parent turn cancels every running child. That's the primary cancel path today: cancel the parent and every active child unwinds.

Per-subagent cancellation is partially wired. SubagentManager marks the subagent "cancelled" and emits subagent.cancelled, but the async-task path (Async tasks) currently logs a warning rather than tearing down the running worker — cancellation is cooperative, not preemptive. A subagent mid-tool-call won't stop until that call returns.

The aborted subagent emits subagent.failed with terminalStatus: "cancelled". The discriminator matters for dashboards: "cancelled" is user-driven, "failed" is an error inside the subagent's own runtime (a tool threw, a provider call exhausted its cascade), and "timeout" is the SubAgentConfig.timeout ceiling firing — typically 120_000ms. Alert on "failed"; don't alert on "cancelled".

Where to go next