Skip to content
pleach
Cookbook

Deep research agent

An anchor agent that dispatches bounded subagents, with depth-tracked fanout and a turn-rooted tree you can read top-down from the ledger.

A research agent is the canonical multi-subagent workload: one anchor turn fans out into N parallel investigations, each of which may itself recurse. Pleach tracks the tree by construction — every subagent carries its parent's turnId and its own subagentDepth, so the whole investigation is one query against the ledger.

This page walks the anchor → subagent shape, the fanout limits that protect the budget, and the rollup query that turns the tree into a UI.

Related shapes. Coding agent if subagents run code in a sandbox. Customer support agent if the anchor turn is part of a longer-lived support session. Multi-tenant SaaS agent if one runtime serves many research customers.

What you're building

An agent that takes a research question and returns a synthesized answer, citing the sources it consulted. Under the hood:

  • The anchor agent decomposes the question into sub-questions.
  • Each sub-question dispatches a web_search subagent.
  • Each subagent has its own bounded tool surface and its own context window.
  • The anchor synthesizes the subagent returns into one answer.

The anchor and the subagents all write to the same audit ledger. The tree is recoverable from the root turn id, parent turn id, and sub-agent depth.

Subagent spec

A subagent spec is a SubAgentSpec entry in a registry you own: a name, a description, its tools and a step budget. Skills are separate: a skill is a markdown file the SkillLoader discovers at session start, and its 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.

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

export const SPECS: Record<string, SubAgentSpec> = {
  "web-search": {
    name: "web-search",
    description: "Investigate one sub-question. Return up to 5 cited findings.",
    tools: ["search_web", "fetch_page"],
    maxSteps: 6,
  },
  "deep-read": {
    name: "deep-read",
    description: "Read one source in depth and return its key claims with citations.",
    tools: ["fetch_page"],
    maxSteps: 6,
  },
};

createDelegateTools(SPECS) turns each entry into a delegate_to_<name> tool that carries the spec's description. A skill file is separate: it adds prompt content to a turn. A skill with an execution block can also be derived into a spec with deriveSubAgentSpecs when you add the result to your registry and create its tool with createDelegateToolLite; see Skills as sub-agents.

Pass the spec's tools as SubAgentConfig.tools when you spawn the child (a list of names, "inherit" or "none"). The tool-loop executor intersects that list with the parent's allow-list and removes the parent's deny-list, so a child never holds a tool the parent doesn't. An explicit list also admits the three read-only pull tools (skill_search, recall_facts, todo_read). Tools that need approval are withheld from a child, and a child can't spawn past SUBAGENT_LIMITS.maxDepth. The boundary is structural, not prompted.

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

Dispatch from the anchor

The anchor agent runs on SessionRuntime with subagent concurrency enabled. Register delegation tools (createDelegateTools, or enableSubagents on createPleachAgent); the model then delegates by calling them. createDelegateTools returns definitions only, so your tool handler maps each call back with specNameFromDelegateTool and spawns the child (see Distinct delegate_to_* tools). The cap is enforced at the runtime level. Spawning a child also needs a subagentExecutor on the runtime config, such as createToolLoopSubagentExecutor (see The tool-loop executor); without one, a spawn returns a failed result.

import {
  SessionRuntime,
  AiSdkProvider,
  SUBAGENT_LIMITS,
} from "@pleach/core";
import { SupabaseAdapter, createSupabaseAdapter } from "@pleach/core/sessions";
import { createOpenRouter } from "@openrouter/ai-sdk-provider";

const openrouter = createOpenRouter({
  apiKey: process.env.OPENROUTER_API_KEY!,
});

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

  // Subagent concurrency — off by default; cap is per-session.
  // The substrate enforces SUBAGENT_LIMITS.maxDepth (3) and
  // SUBAGENT_LIMITS.maxPerTurn (5) independently.
  enableSubagentConcurrency: true,
  maxConcurrentSubagents:    Math.min(5, SUBAGENT_LIMITS.maxConcurrent),

  // Anchor-side orchestrator wiring (provider, intent detector,
  // prompt contributions) goes through orchestratorConfig; the
  // anchor's tool surface is registered with the orchestrator,
  // not on this config object directly.
  orchestratorConfig: {
    provider: new AiSdkProvider({
      model: openrouter("anthropic/claude-sonnet-4-5"),
    }),
  },
});

maxConcurrentSubagents caps how many subagents run in parallel within one session — additional spawns queue until a slot frees. SUBAGENT_LIMITS are the substrate-enforced hard ceilings (read-only constants):

LimitValueWhat it caps
maxDepth3Parent → child → grandchild nesting
maxConcurrent3Concurrent subagents per session
maxPerTurn5Subagents spawned in one parent turn; the sixth spawnAgent call returns a failed result with refusal.kind: "spawnsPerTurn" (no throw)
timeoutMs120_000Default per-subagent timeout

maxConcurrentSubagents (default 4) and SUBAGENT_LIMITS.maxConcurrent (3) are separate limits on separate paths — the former caps the SubagentManager queue/DAG fan-out, the latter caps the imperative spawn path. Neither is clamped to the other.

maxPerTurn is enforced in spawnAgent by a per-turn ledger. An over-cap spawn returns a failed result with refusal: { kind: "spawnsPerTurn", limit: 5, actual: 6 } and doesn't throw. The throwing cap is maxSubagentFanOutPerTurn (default 10) on spawn(). See SUBAGENT_LIMITS and depth tracking and Subagents for the full spawn / lifecycle surface.

What the event stream looks like

Subagent events are namespaced. The frontend can render a tree without rebuilding the structure from string parsing.

turn-start         (anchor)
  tool-call        synthesize_findings.preflight
  subagent-spawn   web_search#1   question="...", depth=1
  subagent-spawn   web_search#2   question="...", depth=1
  subagent-spawn   web_search#3   question="...", depth=1
    text-delta     [web_search#1] "checking..."
    tool-call      [web_search#1] search_web
    tool-result    [web_search#1] search_web ok
    subagent-end   web_search#1   ok, 4 findings
    ...
  tool-call        synthesize_findings
  text-delta       "Based on the investigation..."
turn-complete

The [name#id] prefix is added by the runtime; you don't have to maintain it. See Stream events for the event taxonomy.

The tree query

Every audit row carries a root turn id (the user turn), a parent turn id (the turn that spawned it), a sub-agent depth, and a tool name. One filter on the root turn id returns the whole investigation at any depth. Order the rows by depth, then creation time, to read it top down.

Per-investigation spend is the same key with a group-by: sum each call row's costUsd for a tenant, grouped by root turn id.

This is enough to render the full investigation as a tree, with each node's tool calls, model outputs, and timing.

Budget guard

Subagent fanout is where budgets evaporate. Two patterns to put in production from day one:

  1. Per-turn token budget. Set maxTokensPerTurn on the runtime. The runtime aborts the turn when the cumulative token count across the anchor and all subagents crosses the line. The audit ledger records the cutoff.

  2. Per-tenant rate limit. Outside the runtime, gate runtime.runTurn calls per tenant. The ledger's tenant id makes after-the-fact attribution one query, but it doesn't stop a runaway request before it costs you.

Eval: lock the tree, vary the model

The investigation tree is recordable. Record one golden run, then replay it against a fresh runtime built around a different provider. The diff tells you whether the new model investigates differently or just synthesizes differently.

The recording lives on the event log as a sequence of subagent.spawned / subagent.completed rows keyed by chatId + turnId. Replay is built on top via @pleach/replay's ReplayClient (which consumes the public runtime.events.iterate surface — no raw DB access).

import { SessionRuntime, AiSdkProvider } from "@pleach/core";
import { createReplayRuntime } from "@pleach/replay";

const challenger = new SessionRuntime({
  storage:  createSupabaseAdapter({ client: supabase }),
  userId:   "user_123",
  tenantId: "tenant_abc",
  enableSubagentConcurrency: true,
  orchestratorConfig: {
    provider: new AiSdkProvider({
      model: openrouter("anthropic/claude-opus-4-7"), // the candidate
    }),
  },
});

const replayRuntime = createReplayRuntime({
  sessionRuntime: challenger,
  tenantId:       "tenant_abc",
});

// Replays the new provider through the same anchor → subagent dispatch tree
// captured in the ledger; diverging spawn shapes surface in the rebuilt state.
const result = await replayRuntime.replayTurn({
  chatId:    goldenChatId,
  tenantId:  "tenant_abc",
  messageId: goldenTurnId,
});

// `result.state` is the reconstructed HydratedHarnessState (typed `unknown`) —
// inspect it to compare the subagent spawn tree and the synthesis against the
// recorded turn.
console.log(result.state);

See Eval and replay for the recording workflow and the full ReplayClient surface.

Project layout

Two adds on top of the baseline: a subagents/ module — separate from tools/ because subagents have their own contract — and an eval/ entry point so the "lock the tree, vary the model" walk is one command, not a hand-assembled script.

my-app/
  src/
    pleach/
      runtime.ts                # constructs SessionRuntime + SkillLoader
      specs.ts                  # the SubAgentSpec registry
      tools/
        synthesize-findings.ts  # the anchor's tools
      eval/
        replay-fixed-tree.ts    # createReplayRuntime + replayTurn
    app/
      api/agents/[id]/route.ts
  skills/
    builtin/
      web-search/SKILL.md       # skill — prompt body
      deep-read/SKILL.md        # skill — prompt body
  evals/
    fixtures/                   # recorded sessions, gitignored or LFS

What changes from the baseline:

  • skills/ and specs.ts are separate from src/pleach/tools/. A subagent isn't a tool — it has its own tool list (the tools you pass when spawning it), its own budget guard, and its own channel for stream isolation. Skill files live at the repo root under skills/builtin/<name>/SKILL.md because that's where the SkillLoader scans by default. Keeping skills out of src/pleach/tools/ stops the two from drifting into each other and matches the Subagents contract.
  • eval/ is in src/, not tests/. The replay path is product code — replayTurn runs against the same SessionRuntime your host route uses, just with mode: "replay". Putting it under src/pleach/eval/ means it imports the live runtime, not a test double.
  • evals/fixtures/ holds recorded sessions. The fixtures are what the eval section diffs against. Treat them like checked-in test data: small fixtures in git, large ones in LFS or object storage.

Where to go next