# Swarm agent (/docs/swarm-agent)



A swarm agent is the shape that pushes the runtime's recursive
contract: one user turn fans out into dozens or hundreds of
subagents, each of which may spawn its own. Kimi K2-style deep
sequential loops, OpenAI Deep Research-style parallel fan-out,
AutoGen / LangGraph supervisor topologies, Claude Code-style
recursive delegation — different topologies, same buyer cohort,
same runtime stress.

The load-bearing pain is the runaway-loop case. A buggy fan-out
or a stuck sequential loop can spend a five-figure budget in one
user turn. This page walks the cost ceiling at the root-turn
boundary, the session-tree audit walk that attributes every
descendant call back to the originating turn, and the
concurrency primitives a swarm host reaches for.

**Related shapes.**
[Research agent](/docs/research-agent) for the canonical
single-anchor / bounded-subagent pattern — the swarm shape
inherits its primitives and pushes them further.
[Coding agent](/docs/coding-agent) if the subagents run code in
sandboxes.
[Multi-tenant SaaS agent](/docs/multi-tenant-saas-agent) if one
runtime serves many customers, each driving their own swarm.

## What you're building [#what-youre-building]

A turn loop whose recursion is bounded by construction, not by
hope:

* Every subagent — including subagents-of-subagents — carries
  the originating user turn's `turnId` and its own
  `subagentDepth`. The whole tree is one query against the
  ledger.
* A per-root-turn cost ceiling aborts the turn when cumulative
  spend crosses the line. The ledger records the cutoff.
* A fan-out cap limits how many subagents one node can spawn at
  once. A recursion-depth cap limits how deep the tree can go.
* Concurrency primitives — `race`, `waitAll`, `waitN`,
  `bounded`, `backpressure` — handle the structural cases a
  swarm host actually hits.

## Cost ceiling at the root-turn boundary [#cost-ceiling-at-the-root-turn-boundary]

The cost ceiling is the load-bearing protection for a swarm.
Today `@pleach/core` ships the structural caps — `maxDepth`,
`maxConcurrent`, `maxPerTurn`, `timeoutMs` — as hard ceilings
the substrate enforces independently of consumer config. A
per-root-turn USD ceiling now ships in `@pleach/gateway/swarm` as
an inline pre-transport guard — see [Gateway swarm
governance](#gateway-swarm-governance) below. Hosts that don't route
through the gateway enforce the dollar cap out-of-band against the
audit ledger.

```typescript
import {
  SessionRuntime,
  SUBAGENT_LIMITS,
  AiSdkProvider,
  createSupabaseAdapter,
} from "@pleach/core";

const runtime = new SessionRuntime({
  storage: createSupabaseAdapter({ client: supabase }),
  userId:  "user_123",
  tenantId: "tenant_abc",

  enableSubagentConcurrency: true,
  // SUBAGENT_LIMITS.maxConcurrent is the substrate-enforced
  // ceiling (3); consumer values above the ceiling clamp down.
  maxConcurrentSubagents: SUBAGENT_LIMITS.maxConcurrent,

  orchestratorConfig: {
    provider: anchorProvider,
  },
});

// Out-of-band USD ceiling, polled by the host against the
// audit ledger. `@pleach/compliance/education` ships a
// per-session helper for the single-process case; for swarms
// that span multiple processes, back it with a tenant-scoped
// store and check on each turn boundary.
import { createCostCapPolicy } from "@pleach/compliance/education";

const costCap = createCostCapPolicy({
  ceilingUsd: 25,
  onBreach:   () => runtime.abort(),
});
```

`SUBAGENT_LIMITS` carries the substrate-side hard caps:

| Cap             | Value     | Effect when breached                                                                           |
| --------------- | --------- | ---------------------------------------------------------------------------------------------- |
| `maxDepth`      | `3`       | Spawn rejected — fourth nested runtime never starts                                            |
| `maxConcurrent` | `3`       | New spawns queue until a slot frees                                                            |
| `maxPerTurn`    | `5`       | Sixth `spawnAgent` call in a turn returns a failed result with `refusal.kind: "spawnsPerTurn"` |
| `timeoutMs`     | `120_000` | Subagent emits `subagent.failed` with `terminalStatus: "timeout"`                              |

`maxPerTurn` is enforced in `spawnAgent` by a per-turn ledger. An
over-cap spawn doesn't throw: it returns a failed result carrying
`refusal: { kind: "spawnsPerTurn", limit: 5, actual: 6 }`. The throwing
cap is a different one, `maxSubagentFanOutPerTurn` (default `10`) on
the `spawn()` factory, which raises `SubagentFanOutExceeded`. See
[`SUBAGENT_LIMITS` and depth tracking](/docs/subagents#subagent_limits-and-depth-tracking).

The recursion is bounded structurally, not by per-subagent
prompts. A subagent that doesn't know about the cap can't escape
it.

## Gateway swarm governance [#gateway-swarm-governance]

`@pleach/gateway/swarm` ships the inline cost governance the
out-of-band poll above approximates. The middleware guards each
routing call and throws before transport when the root turn would
cross its ceiling:

* `createRootTurnCostAggregator(...)` — accumulates `CostEvent`s by
  `rootTurnId`. In-memory by default; wire a shared `RootTurnCostStore`
  (Redis / Upstash / DynamoDB) so sub-agents on different processes
  accumulate to one counter.
* `createCostCeilingMiddleware({ aggregator, maxCostUsdPerRootTurn })` —
  wraps a routing call via `guard({ rootTurnId, invoke })`. A call that
  would push accumulated cost over the ceiling throws
  `CostCeilingExceededError` before the transport runs — the breaching
  call never touches the wire. Optional `warnCostUsdPerRootTurn` /
  `warnThreshold` fire `onWarn` at a soft threshold.
* `createCostRateLimitMiddleware({ windowMs?, maxRequests? })` — a
  per-`rootTurnId` request throttle. `process()` returns a
  `{ retryAfterMs }` deferral once the window cap is met and fires
  `onDefer` at most once per window.
* `createFailoverCoordinator(...)` — coordinates sibling sub-agents on
  a failover, with `mode: "best-of-N" | "all-or-nothing"`.
* `classifySwarmTopology(events)` — classifies a flat spawn-event list
  into `tree | dag | ring`, plus `depth`, `fanOut`, and
  `subAgentCount`.

Two structural events ride the callbacks for operator telemetry:
`CostBudgetWarned` (soft threshold) and `CostRateLimitDeferred`
(transient throttle). Both are data-shaped for the event log and OTEL
attributes.

```typescript
import {
  createRootTurnCostAggregator,
  createCostCeilingMiddleware,
  CostCeilingExceededError,
} from "@pleach/gateway/swarm";

const aggregator = createRootTurnCostAggregator();
const ceiling = createCostCeilingMiddleware({
  aggregator,
  maxCostUsdPerRootTurn: 25,
  warnThreshold: 0.8,
  onWarn: (e) => notifyOperator(e),
});

try {
  const answer = await ceiling.guard({
    rootTurnId,
    // invoke returns the call result plus its CostEvent so the
    // aggregator can roll spend up by rootTurnId.
    invoke: async () => {
      const { result, costEvent } = await runRoutedCall(decision);
      return { result, costEvent };
    },
  });
} catch (err) {
  if (err instanceof CostCeilingExceededError) {
    // root turn halted before transport — err carries accumulated + ceiling
  }
}
```

## What today ships [#what-today-ships]

Today, `@pleach/core` ships:

* Recursive `SessionRuntime` sessions — every subagent is itself
  a `SessionRuntime`, with the same primitives the root has.
* `AuditableCall` typed audit-ledger rows — every spawn writes
  a row that ties the child session back to the parent turn.
* Parent-turn, root-turn, subagent-depth and tool-name fields on the
  audit ledger — the tree rollup is one group-by on the root turn.
* `SUBAGENT_LIMITS` for depth, parallel fanout, and total
  subagent count.

For the canonical anchor → bounded subagent fan-out pattern, see
[Research agent](/docs/research-agent).

## Budgets and concurrency [#budgets-and-concurrency]

* **Per-root-turn cost ceiling.** `@pleach/gateway/swarm` ships an
  inline pre-transport guard — see [Gateway swarm
  governance](#gateway-swarm-governance). Without the gateway, poll
  the call ledger filtered by root turn and call
  `runtime.abort()` when spend crosses the budget.
  `@pleach/compliance/education` ships a
  `createCostCapPolicy({ ceilingUsd, onBreach })` helper for the
  per-session shape (single-process / in-memory by default; swap in a
  tenant-DB backing store for multi-process).
* **Concurrency.** Compose fan-out with `Promise.all`, `Promise.race`,
  and your own semaphore.
* **Session-tree audit walker.** `walkSessionTree` in
  `@pleach/compliance/swarm` walks the tree the audit walk above describes
  and verifies each node's hash chain. See [Verifying the
  tree with `walkSessionTree`](#verifying-the-tree-with-walksessiontree).
* **Per-subagent budgets.** If one branch needs its own budget, track
  it in your host alongside the root ceiling.

## The session-tree audit walk [#the-session-tree-audit-walk]

Every audit row carries its root turn (the depth-0 user turn), its
parent turn, and its subagent depth. The whole tree — sequential
loops, parallel fan-out, recursive delegation — rolls up under one
root turn, so no recursive query is needed.

To walk it, take the call ledger's rows for one root turn, group them
by subagent depth, and count the calls and sum the input and output
tokens at each depth.

That read covers the whole investigation top-down: depth 0 is the
anchor turn; depth N is the deepest spawn. A regulator asking
"what did the agent do for user turn T" gets the full tree in
one read.

For a worked investigation that starts from a surprising bill, see [Why did one question cost $11](/docs/subagents#example-why-did-one-question-cost-11).

### Verifying the tree with `walkSessionTree` [#verifying-the-tree-with-walksessiontree]

The SQL above rolls the tree up for review. `@pleach/compliance/swarm`
walks the same tree and verifies each node's hash chain in one pass:

* `walkSessionTree({ rootSessionId, eventStore, maxDepth? })` — BFS over
  the spawn tree from the root session. `maxDepth` defaults to 64.
  Returns a `TreeWalkResult`.
* `EventStoreLike` — the duck-typed store the walker reads through. One
  method: `listEvents(sessionId, filter?)`, returning rows in
  ascending sequence-number order.
* `TreeWalkResult` — `rootSessionId`, `treeValid` (the conjunction of
  every node's `chainValid`), `nodes`, `totalRows`, `totalFailures`.
* `TreeWalkNode` — per session: `sessionId`, `depth` (0 at root),
  `chainValid`, `rowCount`, and `failures` (typed
  `ChainVerificationError`s).

A per-node chain divergence surfaces via `nodes[i].failures` and
`treeValid: false` — the walker only throws on a store-level error. A
malformed tree that links back to an ancestor can't loop; visited
session IDs are tracked in a set.

```typescript
import { walkSessionTree } from "@pleach/compliance/swarm";

const result = await walkSessionTree({ rootSessionId, eventStore });
if (!result.treeValid) {
  // result.nodes[i].failures carries the per-node ChainVerificationErrors
}
```

## Topology-neutral primitives [#topology-neutral-primitives]

The runtime doesn't have a topology opinion. The same
primitives — recursive sessions, the ledger tree, the cost
ceiling, the spawn record — absorb four different shapes:

| Topology             | What the host writes               | What the runtime stamps      |
| -------------------- | ---------------------------------- | ---------------------------- |
| Deep sequential loop | a long tool-loop in one subagent   | subagent depth 1, many rows  |
| Parallel fan-out     | N subagents spawned at the anchor  | subagent depth 1, N siblings |
| Supervisor / worker  | supervisor spawns workers per task | subagent depth 1 or 2, tree  |
| Recursive delegation | subagent spawns its own subagent   | subagent depth N, deep tree  |

A swarm host picks the topology; the runtime makes the audit
walk identical across all four.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="Subagents" href="/docs/subagents" description="The spawn surface, the SpawnTreeState shape, and SUBAGENT_LIMITS." />

  <Card title="Research agent" href="/docs/research-agent" description="The canonical anchor → bounded subagent fan-out pattern that the swarm shape extends." />

  <Card title="Audit ledger" href="/docs/audit-ledger" description="The call ledger schema and the parent-turn field the tree walk reads from." />

  <Card title="Channels" href="/docs/channels" description="Per-subagent stream isolation so the UI can render the tree without rebuilding it." />

  <Card title="Coding agent" href="/docs/coding-agent" description="The swarm shape when the subagents run code in sandboxes." />

  <Card title="Multi-tenant SaaS agent" href="/docs/multi-tenant-saas-agent" description="Per-tenant runtime construction when each tenant drives its own swarm." />
</Cards>
