claudeers.

🔓 unclaimed — this page was auto-generated from GitHub. Are you the creator?

Claim this page →
// Developer Tools

pi-subagents

Pi extension for async subagent delegation with truncation, artifacts, and session sharing

// Developer Tools[ api ][ web ][ claude ]#claude#devtools$open-sourceupdated 14 days ago
Actively maintained
100/100
last commit 5 days ago
last release 5 days ago
releases 86
open issues 3
// install
git clone https://github.com/nicobailon/pi-subagents

pi-subagents

pi-subagents

pi-subagents lets Pi delegate work to focused child agents. Use it for code review, scouting, implementation, parallel audits, saved workflows, background jobs, and anything else that benefits from a second or third set of model eyes.

https://github.com/user-attachments/assets/702554ec-faaf-4635-80aa-fb5d6e292fd1

Installation

pi install npm:pi-subagents

That is the only required step. You can add optional pieces later.

Try this first

You do not need to create agents, write config, or learn slash commands. After installing, ask Pi for delegation in plain language:

Use reviewer to review this diff.
Ask oracle for a second opinion on my current plan.
Use scout to understand this code based on our discussion then ask me clarification questions.
Run parallel reviewers: one for correctness, one for tests, and one for unnecessary complexity.

That is enough to start.

What happens

Pi is the parent session. A subagent is a focused child Pi session with its own job.

When you ask for a subagent, Pi starts the child, gives it the task, and brings the result back. Foreground runs stream in the conversation. Background runs keep working and can be checked later.

Installing the extension does not start an automatic reviewer in the background. It gives Pi a delegation tool. If you want every implementation reviewed, say that in your prompt or put it in your project instructions:

When you finish implementing, run a reviewer subagent before summarizing.

Good first prompts

These cover most day-to-day use:

Ask oracle for a second opinion on my current plan. Challenge assumptions and tell me what I might be missing.
Use oracle to help solve this hard bug. Have it inspect the code and propose the best next move before we edit anything.
Run parallel reviewers on this diff. I want one focused on correctness, one on tests, and one on unnecessary complexity.
Have worker implement this approved plan. Afterward, run parallel reviewers, summarize their feedback, and apply the fixes that make sense.
Run a review loop on this change until reviewers stop finding fixes worth doing, with a max of 3 rounds.
Use scout to understand the auth flow, then have planner turn that into an implementation plan.

Those are ordinary Pi requests. Pi decides whether to call subagent, which agent to use, and whether a chain or parallel run makes sense.

Common workflows

WantAsk naturally
Get a second opinion“Ask oracle to review this plan and challenge assumptions.”
Solve a hard problem“Use oracle to investigate this bug before we edit.”
Review a diff“Use reviewer to review this diff.”
Run parallel reviewers“Run reviewers for correctness, tests, and cleanup.”
Implement then review“Implement this, then review it.”
Review until clean“Run a review loop on this change with a max of 3 rounds.”
Execute a plan carefully“Have worker implement this approved plan, then run reviewers and apply the feedback.”
Scout before planning“Use scout to inspect the auth flow before planning.”
Run in the background“Run this in the background.”
Browse agents“Show me the available subagents.”
Use a saved workflow“Run the review chain on this branch.”
See running work“Show active async runs.”
Check setup“Check whether subagents are configured correctly.”

The extension ships with builtin agents you can use immediately.

Builtin agents in plain English

AgentUse it when you want...
scoutFast local codebase recon: relevant files, entry points, data flow, risks, and where another agent should start.
researcherWeb/docs research with sources: official docs, specs, benchmarks, recent changes, and a concise research brief.
plannerA concrete implementation plan from existing context. It should read and plan, not edit code.
workerImplementation work, including approved oracle handoffs. It edits files, validates, and escalates unapproved decisions instead of guessing.
reviewerCode review and small fixes. It checks the implementation against the task/plan, tests, edge cases, and simplicity.
context-builderA stronger setup pass before planning: gathers code context and writes handoff material such as context.md and meta-prompt.md.
oracleA second opinion before acting. It challenges assumptions, catches drift, and recommends the safest next move without editing.
delegateA lightweight general delegate when you want a child agent that behaves close to the parent session.

A simple rule of thumb: use scout before you understand the code, researcher before you trust external facts, planner before a bigger change, worker to implement, reviewer to check, and oracle when the decision itself feels risky.

Changing an agent's model

Builtin agents inherit your current Pi default model by default. This keeps new installs from depending on a provider you may not have configured. If you want a role to use a specific model, set an override instead of copying the bundled agent file.

For one run, put the override in the command:

/run reviewer[model=anthropic/claude-sonnet-4:high] "Review this diff"

For a persistent override, edit settings. This example pins the reviewer everywhere, adds a backup model for provider failures, and keeps the other builtins on your normal default model:

{
  "subagents": {
    "agentOverrides": {
      "reviewer": {
        "model": "anthropic/claude-sonnet-4",
        "thinking": "high",
        "fallbackModels": ["openai/gpt-5-mini"]
      }
    }
  }
}

Use ~/.pi/agent/settings.json for a user override or the project config settings file (.pi/settings.json in standard Pi) for a project override. The same agentOverrides block can change tools, skills, inherited context, prompt text, or disable a builtin. Matching user and project agents also receive override fields that their frontmatter leaves unset, so a shared project config agent can keep the persona while local settings choose the model. Explicit frontmatter still wins.

If your provider rejects model IDs with thinking suffixes, set subagents.disableThinking: true in user or project settings. That clears bundled builtin thinking defaults in one place; an explicit higher-precedence agentOverrides.<name>.thinking value can opt a role back in.

To inspect what pi-subagents has actually loaded right now, use:

/subagents-models
/subagents-models reviewer

That reports the live runtime mapping, which can differ from settings on disk until you reload Pi.

Where running subagents show up

Foreground runs stream progress in the conversation while they run.

Background runs keep working after control returns to you. Inspect active runs with subagent({ action: "status" }), or a specific run with subagent({ action: "status", id: "..." }).

They also show a compact async widget and send completion notifications. Parallel background runs show per-agent progress instead of fake chain steps. Chains with parallel groups keep their grouped shape in progress and results, so failed or paused agents stay visible next to completed ones. When a child is explicitly allowed to fan out with tools: subagent, its nested runs appear under that parent child in the main status tree instead of being hidden inside the child process.

You can also ask naturally:

Show me the current async runs.

If something feels misconfigured, run:

/subagents-doctor

or ask:

Check whether subagents and intercom are set up correctly.

Use orchestration as parent-agent guidance, not as a runtime workflow mode. For implementation work, the recommended loop is:

clarify → planner → worker → fresh reviewers → worker

Use the optional prompt shortcuts below when you want the pattern to be repeatable.

Packaged planner, worker, and oracle default to forked context when a launch omits context; pass context: "fresh" when you intentionally want a fresh child run.

Child-safety boundaries are enforced at runtime. Spawned child sessions do not receive the bundled pi-subagents skill, and forked child context filtering removes parent-only subagent artifacts (including old hidden orchestration-instruction messages, slash/status/control messages, and prior parent subagent tool-call/tool-result history) while preserving ordinary prose and unrelated tool calls/results. By default, children do not register the subagent tool and receive boundary instructions that they are not the parent orchestrator and must not propose or run subagents. The explicit exception is an agent whose resolved builtin tools includes subagent; that child gets a child-safe subagent tool for the fanout work the parent assigned, still bounded by maxSubagentDepth.

Optional shortcuts

The package includes reusable prompt templates for common workflows. You do not need them, but they are handy when you want the same shape every time:

PromptUse it for
/parallel-reviewLaunch fresh-context reviewers with distinct angles, then synthesize what to fix.
/review-loopRun parent-controlled worker, reviewer, and fix-worker cycles until clean or capped.
/parallel-researchCombine researcher and scout for external evidence, local code context, and practical tradeoffs.
/parallel-context-buildRun context-builder agents in parallel to produce planning handoff context and meta-prompts.
/parallel-handoff-planCombine external research and context-builder passes into an implementation handoff plan and meta-prompt.
/gather-context-and-clarifyScout/research first, then ask the user the clarification questions that matter.
/parallel-cleanupRun review-only cleanup passes after implementation.

Add autofix to /parallel-review or /parallel-cleanup to apply only the synthesized fixes worth doing now after reviewers return.

Optional pi-intercom companion

pi-subagents works without pi-intercom. Install pi-intercom only if you want child agents to talk back to the parent Pi session while they are running.

pi install npm:pi-intercom

Most users do not call intercom directly. After pi-intercom is installed, pi-subagents can automatically give child agents a private coordination channel back to the parent session. The bridge recognizes the normal pi install npm:pi-intercom package install as well as legacy local extension checkouts.

Use it for work where the child might need a decision instead of guessing:

Run this implementation in the background. If the worker gets blocked or needs a product decision, have it ask me through intercom.
Ask oracle to review this plan. If it sees a decision I need to make, have it ask me instead of assuming.

The child can use one dedicated coordination tool:

  • contact_supervisor: the child contacts the parent/supervisor session that delegated the task. Use reason: "need_decision" for blocking decisions or clarification, and reason: "progress_update" for short non-blocking updates when a discovery changes the plan. Do not ask for clarification when the only conflict is review-only/no-edit versus progress-writing or artifact-writing instructions; no-edit wins.

Child-side routine completion handoffs are still not expected. With the intercom bridge active, parent-side pi-subagents sends grouped completion results through pi-intercom: one grouped message per foreground parent subagent run and one per completed async result file. Acknowledged foreground delivery returns a compact receipt with artifact/session paths; if unacknowledged, the normal full output is preserved. Grouped messages include child intercom targets, full child summaries, and compact nested child summaries under the parent child that launched them.

If a child appears stalled, needs-attention notices can show up in the parent session with useful next actions, such as checking subagent({ action: "status" }), interrupting the run, or nudging the child.

If messages do not show up, run:

/subagents-doctor

For normal use, you do not need to configure anything. Advanced users can tune the bridge with intercomBridge in the configuration section below.

At this point, you know enough to use the plugin. The rest of this README is reference material for exact command syntax, custom agents, saved chains, worktrees, and configuration.

Optional pi-permission-system integration

@gotgenes/pi-permission-system adds a second policy layer — allow / ask / deny — on top of pi-subagents' visibility-based tool restrictions.

The two compose independently:

LayerWhat it controlsWho provides it
VisibilityWhich tools are registered before the session startspi-subagents (tools: frontmatter key)
PolicyRuntime allow/ask/deny decisions on every tool call, bash command, MCP operationpi-permission-system (permission: frontmatter key)

Installing

pi install npm:@gotgenes/pi-permission-system

No configuration is required for the integration — it is automatic when both extensions are installed. pi-subagents passes the parent session identity to child processes via the PI_SUBAGENT_PARENT_SESSION environment variable, which the permission system uses to forward ask prompts from headless subagent processes back to the parent session's UI.

Per-agent permission frontmatter

Agent files can include a permission: block alongside the standard tools: key. The permission system reads it independently:

---
name: worker
tools: bash,read,write,edit
permission:
  "*": ask
  read: allow
  bash:
    "*": ask
    "git *": allow
    "npm test": allow
---

In this example the subagent extension restricts visibility to four tools, and the permission system then applies ask/allow policy within that visible set. Both keys coexist without collision.

Checking the integration

Run /subagents-doctor to check the permission system status. If ask prompts from children are not reaching the parent UI, verify both extensions are installed:

pi list

How it works

At session start, the interactive (root) session records its own identity in PI_SUBAGENT_PARENT_SESSION. When pi-subagents launches a child, it passes the launching session's identity to that child explicitly, falling back to the inherited environment variable. When the permission system inside a child encounters an ask permission, it reads this variable to locate the parent session and forwards the confirmation request there.

This resolves an interactive prompt only when the parent it points at is the interactive session — i.e. for the direct children of the root session. A nested child's parent is itself a headless subagent process with no UI to surface the prompt, so ask policies are best placed on agents that run as direct children of the interactive session.

Direct commands

Skip this section until you want exact syntax.

CommandDescription
/run <agent> [task]Run one agent; omit the task for self-contained agents
/chain agent1 "task1" -> agent2 "task2"Run agents in sequence
/parallel agent1 "task1" -> agent2 "task2"Run agents in parallel
/run-chain <chainName> -- <task>Launch a saved .chain.md or .chain.json workflow
/subagents-doctorShow read-only setup diagnostics
/subagents-models [agent]Show the runtime-loaded builtin model mapping, optionally filtered to one builtin

Commands validate agent names locally, support tab completion, and send results back into the conversation.

Per-step tasks

Use -> to separate steps and give each step its own task:

/chain scout "scan the codebase" -> planner "create an implementation plan"
/parallel scanner "find security issues" -> reviewer "check code style"

Both double and single quotes work. You can also use -- as a delimiter:

/chain scout -- scan code -> planner -- analyze auth

Steps without a task inherit behavior from the execution mode. Chain steps get {previous}, the prior step’s output. Parallel steps use the first available task as a fallback.

/chain scout "analyze auth" -> planner -> worker
# scout gets "analyze auth"; planner gets scout output; worker gets planner output

For a shared task, list agents and place one -- before the task:

/chain scout planner -- analyze the auth system
/parallel scout reviewer -- check for security issues

Inline per-step config

Append [key=value,...] to an agent name to override defaults for that step:

/chain scout[output=context.md] "scan code" -> planner[reads=context.md] "analyze auth"
/run scout[model=anthropic/claude-sonnet-4] summarize this codebase
/parallel reviewer[skills=code-review+security] "review backend" -> reviewer[model=openai/gpt-5-mini] "review frontend"
KeyExampleDescription
outputoutput=context.mdWrite results to a file. For /chain and /parallel, relative paths live under the chain directory; for /run, relative paths resolve against cwd.
outputModeoutputMode=file-onlyReturn only a concise file reference for saved output instead of the full saved content. Requires output; default is inline.
readsreads=a.md+b.mdRead files before executing. + separates multiple paths.
modelmodel=anthropic/claude-sonnet-4Override model for this step.
skillsskills=planning+reviewOverride available skills. + separates multiple skills.
progressprogressEnable progress tracking.

Set output=false, reads=false, or skills=false to disable that behavior explicitly. Do not use output=false for file-only returns; use outputMode=file-only with an output path.

Background and forked runs

Add --bg to run in the background:

/run scout "audit the codebase" --bg
/chain scout "analyze auth" -> planner "design refactor" -> worker --bg
/parallel scout "scan frontend" -> scout "scan backend" --bg

Add --fork to start each child from a real branched session created from the parent’s current leaf:

/run reviewer "review this diff" --fork
/chain scout "analyze this branch" -> planner "plan next steps" --fork
/parallel scout "audit frontend" -> reviewer "audit backend" --fork

You can combine them in either order:

/run reviewer "review this diff" --fork --bg
/run reviewer "review this diff" --bg --fork

Background runs are detached. If the parent agent has other independent work, it should keep working. If it has nothing useful to do until the background result arrives, it should end the turn instead of running sleep or status-polling loops. Pi will deliver the completion when the run finishes.

The oracle and worker builtins are designed for an explicit decision loop. A typical pattern is to ask oracle for diagnosis and a recommended execution prompt, then only run worker after the main agent approves that direction.

Clarify and launch UI

Chains open a clarify UI by default so you can preview and edit the workflow before it runs. Single and parallel tool calls can opt into the same flow with clarify: true; slash commands launch directly.

Common clarify keys:

  • Enter runs in the foreground, or in the background if background is toggled on
  • Esc cancels or backs out
  • ↑↓ moves between steps or tasks
  • e edits the task/template
  • m selects a model
  • t selects thinking level
  • s selects skills
  • b toggles background execution
  • w edits output/write behavior where supported
  • r edits reads where supported
  • p toggles progress tracking where supported Picker screens use ↑↓, Enter, Esc, and type-to-filter. The full-screen editor supports word wrapping, paste, Esc to save, and Ctrl+C to discard.

Agents and chains

Agents are markdown files with YAML frontmatter and a system prompt body. They define the specialist that will run in the child Pi process.

Agent locations, lowest to highest priority:

ScopePath
Builtin~/.pi/agent/extensions/subagent/agents/
Installed packagepackage.json pi-subagents.agents or pi.subagents.agents
User~/.pi/agent/agents/**/*.md
ProjectProject config agents/**/*.md (.pi/agents/**/*.md in standard Pi)

Project discovery also reads legacy .agents/**/*.md files. Nested subdirectories are discovered recursively. .chain.md files do not define agents. Installed Pi packages can expose agent directories from either {"pi-subagents":{"agents":["./agents"]}} or {"pi":{"subagents":{"agents":["./agents"]}}} in their package manifest. Package agents load above builtins and below user/project agents. If both .agents/ and the project config agents directory define the same parsed runtime agent name, the project config directory wins. Use agentScope: "user" | "project" | "both" to control discovery; both is the default and project definitions win runtime-name collisions.

Builtin agents load at the lowest priority, so a user or project agent with the same name overrides them. They do not pin a provider model; they inherit your current Pi default model unless you set subagents.agentOverrides.<name>.model. oracle is an advisory reviewer that critiques direction and proposes an execution prompt without editing files. worker is the implementation agent for normal tasks and approved oracle handoffs.

The researcher builtin uses web_search, fetch_content, and get_search_content; those require pi-web-access:

pi install npm:pi-web-access

Builtin overrides

You can override selected builtin fields without copying the whole agent. Overrides live in settings:

  • User: ~/.pi/agent/settings.json
  • Project: project config settings file (.pi/settings.json in standard Pi)

Example:

{
  "subagents": {
    "agentOverrides": {
      "reviewer": {
        "inheritProjectContext": false
      }
    }
  }
}

Supported override fields are model, fallbackModels, thinking, systemPromptMode, inheritProjectContext, inheritSkills, defaultContext, disabled, skills, tools, and systemPrompt. Use defaultContext: false in builtin overrides to clear an inherited context default. Project overrides beat user overrides.

Set disabled: true to hide a builtin from runtime discovery and agent-facing subagent({ action: "list" }) output. For bulk control, set subagents.disableBuiltins: true in settings.

Set subagents.disableThinking: true to clear bundled builtin thinking defaults globally for providers that do not support :low, :medium, :high, or similar model suffixes. A higher-precedence per-agent thinking override can opt one builtin back in.

Prompt assembly

Subagents are designed to be narrow by default. Custom agents start with a clean system prompt and only the context you intentionally give them. They do not automatically inherit Pi’s whole base prompt, project instruction files, or discovered skills catalog.

Use these fields when an agent should see more:

FieldEffect
systemPromptMode: appendAppend the agent prompt to Pi’s normal base prompt.
inheritProjectContext: trueKeep inherited project instructions from files like AGENTS.md and CLAUDE.md.
inheritSkills: trueLet the child see Pi’s discovered skills catalog.
defaultContext: forkUse forked session context when a launch omits context; explicit context: "fresh" still wins.

Builtin agents opt into project instruction inheritance by default so they follow repo-specific rules out of the box. delegate also uses append mode because its job is orchestration inside the parent workflow.

Agent frontmatter

A typical agent looks like this:

---
name: scout
# Optional: registers this as code-analysis.scout while preserving name: scout
package: code-analysis
description: Fast codebase recon
tools: read, grep, find, ls, bash, mcp:chrome-devtools
extensions:
subagentOnlyExtensions: ./tools/child-only-search.ts
model: claude-haiku-4-5
fallbackModels: openai/gpt-5-mini, anthropic/claude-sonnet-4
thinking: high
systemPromptMode: replace
inheritProjectContext: false
inheritSkills: false
skills: safe-bash, chrome-devtools
output: context.md
defaultReads: context.md
defaultProgress: true
completionGuard: false
interactive: true
maxSubagentDepth: 1
---

Your system prompt goes here.

Important fields:

FieldNotes
packageOptional package identifier. A file with name: scout and package: code-analysis registers as code-analysis.scout; serialization keeps name and package separate.
toolsBuiltin tool allowlist. mcp: entries select direct MCP tools when pi-mcp-adapter is installed.
extensionsOmitted means normal extensions; empty means no extensions; comma-separated values allowlist specific extensions.
subagentOnlyExtensionsComma-separated extension paths loaded only in spawned child sessions for this agent. Tools registered there are unavailable to the main agent unless also installed through normal Pi extension configuration.
modelDefault model. Bare ids prefer the current provider when possible, then unique registry matches.
fallbackModelsOrdered backup models for provider/model failures such as quota, auth, timeout, or unavailable model. Ordinary task failures do not trigger fallback.
thinkingAppended as a :level suffix at runtime unless a suffix is already present.
systemPromptModereplace by default; append keeps Pi’s base prompt.
inheritProjectContextKeeps or strips inherited project instruction blocks.
inheritSkillsKeeps or strips Pi’s discovered skills catalog.
defaultContextOptional fresh or fork launch context default for this agent.
skillsAdds specific skills to the child’s available skill list, regardless of inheritSkills.
outputDefault single-agent output file.
defaultReadsFiles to read before running in chain/parallel behavior.
defaultProgressMaintain progress.md.
completionGuardSet false only for non-implementation agents that may mention implementation words while using mutation-capable tools such as bash.
interactiveParsed for compatibility but not enforced in v1.
maxSubagentDepthTightens nested delegation for this agent’s children.

Tool and extension selection

If tools is omitted, pi-subagents does not pass --tools, so the child gets Pi’s normal builtin tools. If tools is present, regular tool names become an explicit allowlist. mcp: entries are split out and forwarded as direct MCP selections. Path-like tools entries, such as extension paths or .ts/.js files, are treated as tool-extension paths rather than builtin tool names. Agents that declare only known read-only builtin tools skip the implementation completion guard, but bash, unknown tools, and MCP tools stay mutation-capable. Use completionGuard: false for bash-enabled validators or advisors that should never be judged as implementation agents.

Examples:

  • tools omitted and extensions omitted: normal builtins and normal extensions.
  • tools: mcp:chrome-devtools: normal builtins plus direct Chrome DevTools MCP tools.
  • tools: read, bash, mcp:chrome-devtools: only read and bash as builtins, plus direct Chrome DevTools MCP tools.
  • tools: subagent, read: a child-safe subagent tool is available inside that child so it can run explicitly assigned nested fanout.

Direct MCP tools require pi-mcp-adapter. Subagents only receive direct MCP tools when mcp: entries are listed in their frontmatter; global directTools: true in mcp.json is not enough by itself. The generic mcp proxy tool can still be used for discovery when available. The adapter caches tool metadata at startup, so after connecting a new MCP server for the first time, restart Pi before relying on direct tools. An mcp: entry named subagent does not authorize nested fanout; only the builtin subagent tool name does.

extensions controls child extension loading:

# Omitted: all normal extensions load

# Empty: no extensions
extensions:

# Allowlist
extensions: /abs/path/to/ext-a.ts, /abs/path/to/ext-b.ts

When extensions is present, it takes precedence over extension paths implied by tools entries.

Use subagentOnlyExtensions when a custom extension tool should exist only inside child sessions. It is scoped by agent config: every run of that agent receives those extension paths, while other agents do not unless they declare the same field. The current model does not have a separate named-subagent audience inside one agent definition.

Chain files

Chains are reusable workflows stored separately from agent files. Use .chain.md for simple sequential saved chains. Use .chain.json when a chain needs dynamic fanout.

ScopePath
Installed packagepackage.json pi-subagents.chains or pi.subagents.chains
User~/.pi/agent/chains/**/*.chain.md, ~/.pi/agent/chains/**/*.chain.json
ProjectProject config chains/**/*.chain.md, chains/**/*.chain.json (.pi/chains/... in standard Pi)

Nested subdirectories are discovered recursively. Installed Pi packages can expose chain directories from either {"pi-subagents":{"chains":["./chains"]}} or {"pi":{"subagents":{"chains":["./chains"]}}} in their package manifest. Package chains load below user/project chains. If both .chain.md and .chain.json define the same parsed runtime chain name in the same scope, .chain.json wins. If user and project scopes define the same parsed runtime chain name, the project chain wins. Chains support the same optional package frontmatter as agents; name: review-flow plus package: code-analysis runs as code-analysis.review-flow.

Example:

---
name: scout-planner
description: Gather context then plan implementation
---

## scout
phase: Context
label: Map auth flow
as: context
output: context.md

Analyze the codebase for {task}

## planner
phase: Planning
label: Implementation plan
reads: context.md
model: anthropic/claude-sonnet-4-5:high
progress: true

Create an implementation plan based on {outputs.context}

Each .chain.md ## agent-name section is a step. Config lines such as phase, label, as, outputSchema, output, outputMode, reads, model, skills, and progress go immediately after the header. A blank line separates config from task text. In saved .chain.md files, outputSchema is a path to a JSON Schema file; direct tool calls and .chain.json files can pass the schema object inline.

For output, reads, skills, and progress, chain behavior is three-state: omitted inherits from the agent, a value overrides, and false disables.

Use phase to group related work in status output, label for a readable step name, and as to store a successful step or parallel task result for later {outputs.name} references. Duplicate as names, invalid identifiers, and unknown output references fail before child execution.

Dynamic fanout is available only through direct subagent({ chain: [...] }) JSON or saved .chain.json files. It expands an array from a prior structured named output, runs one child template per item, and stores the ordered collection under collect.as. The source must be structured output; prose is never parsed. expand.maxItems is required, over-limit arrays fail, nested fanout and arbitrary expressions are not supported, and .chain.md has no dynamic syntax in this release.

{
  "name": "dynamic-review",
  "description": "Find review targets, fan out reviewers, then synthesize.",
  "chain": [
    {
      "agent": "scout",
      "task": "Return {\"items\":[{\"path\":\"...\",\"reason\":\"...\"}]} via structured_output.",
      "as": "targets",
      "outputSchema": { "type": "object" }
    },
    {
      "expand": {
        "from": { "output": "targets", "path": "/items" },
        "item": "target",
        "key": "/path",
        "maxItems": 12
      },
      "parallel": {
        "agent": "reviewer",
        "label": "Review {target.path}",
        "task": "Review {target.path}. Reason: {target.reason}",
        "outputSchema": { "type": "object" }
      },
      "collect": { "as": "reviews" },
      "concurrency": 4
    },
    {
      "agent": "worker",
      "task": "Synthesize fixes from {outputs.reviews}"
    }
  ]
}

Create simple .chain.md chains by writing files directly or with the subagent({ action: "create", config: ... }) management action. Create dynamic .chain.json chains by writing the JSON file directly. Run saved chains with natural language or:

/run-chain scout-planner -- refactor authentication

Chain variables

Task templates support:

VariableDescription
{task}Original task from the first step.
{previous}Output from the prior step, or aggregated output from a parallel step.
{chain_dir}Path to the chain artifact directory.
{outputs.name}Text value from a prior step or completed parallel task with as: "name".

Parallel outputs are aggregated with clear separators before being passed to the next step:

=== Parallel Task 1 (worker) ===
...

=== Parallel Task 2 (worker) ===
...

Skills

Skills are SKILL.md files made available to an agent. The prompt includes skill metadata and the file location; the agent reads the full skill file only when the task matches.

Discovery uses project-first precedence:

  1. Project config skills/{name}/SKILL.md (.pi/skills/{name}/SKILL.md in standard Pi)
  2. Project packages and project settings packages via package.json -> pi.skills
  3. Current task cwd package via package.json -> pi.skills
  4. Project config settings.json -> skills
  5. ~/.pi/agent/skills/{name}/SKILL.md
  6. User packages and user settings packages via package.json -> pi.skills
  7. ~/.pi/agent/settings.json -> skills

Use agent defaults, override them at runtime, or disable them:

{ agent: "scout", task: "..." }
{ agent: "scout", task: "...", skill: "tmux, safe-bash" }
{ agent: "scout", task: "...", skill: false }

For chains, skill at the top level is additive. A step-level skill overrides that step; false disables skills for that step.

Available skills use this shape:

The following configured skills are available to this subagent.
Use the read tool to load a skill's file when the task matches its description.
When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.

<available_skills>
  <skill>
    <name>safe-bash</name>
    <description>Run shell commands safely.</description>
    <location>/absolute/path/to/safe-bash/SKILL.md</location>
  </skill>
</available_skills>

If an agent has an explicit tools allowlist and resolved skills, read is added for that child run so the listed skill files can be loaded on demand.

Missing skills do not fail execution. The result summary shows a warning.

Bundled skill

The package bundles a pi-subagents skill that is automatically available to the parent agent when the extension is installed. It is for the orchestrating parent only: child subagents never receive it, and their context is explicitly filtered to strip parent-only orchestration instructions.

What the bundled skill covers:

  • Delegation patterns: when to launch which agent, whether to use single, parallel, chain, or async mode, and whether to use fresh or forked context
  • Prompt workflow recipes: how to apply the packaged techniques directly with subagent(...) when the user describes the workflow in natural language instead of invoking a slash command. This includes parallel review, review-loop, parallel research, parallel context-build, parallel handoff-plan, gather-context-and-clarify, and parallel cleanup
  • Role-agent prompting guidance: compact contract prompts instead of long scripts, what to include in role-specific meta prompts, and retrieval budgets for researchers
  • Safety boundaries: child agents must not run subagents unless their resolved builtin tools explicitly include subagent, must not invent intercom targets, and must escalate unapproved decisions
  • Intercom conventions: when to ask vs send, and how parent-side result delivery works with pi-intercom
  • Control and diagnostics: attention signals, soft interrupts, status, and the doctor action

If you are writing an agent that orchestrates subagents, the bundled skill helps it behave correctly without guessing the patterns. If you are a human user, you do not need to read it directly; the README and prompt shortcuts encode the same workflows in user-facing form.

Programmatic tool usage

These are the parameters the LLM passes when it calls the subagent tool. Most users ask naturally or use slash commands instead.

Execution examples

// Single agent
{ agent: "worker", task: "refactor auth" }
{ agent: "scout", task: "find todos", maxOutput: { lines: 1000 } }
{ agent: "scout", task: "investigate", output: false }
{ agent: "scout", task: "write a large report", output: "reports/scout.md", outputMode: "file-only" }

// Forked context
{ agent: "worker", task: "continue this thread", context: "fork" }

// Parallel
{ tasks: [{ agent: "scout", task: "a" }, { agent: "reviewer", task: "b" }] }
{ tasks: [{ agent: "scout", task: "audit auth", count: 3 }] }
{ tasks: [{ agent: "scout", task: "audit frontend" }, { agent: "reviewer", task: "audit backend" }], context: "fork" }

// Chain
{ chain: [
  { agent: "scout", task: "Gather context for auth refactor" },
  { agent: "planner" },
  { agent: "worker" },
  { agent: "reviewer" }
]}

// Chain in the background, suitable for unblocking the main chat
{ chain: [...], async: true }

// Chain with fan-out/fan-in
{ chain: [
  { agent: "scout", task: "Gather context", phase: "Context", label: "Map code", as: "context" },
  { parallel: [
    { agent: "worker", task: "Implement feature A from {outputs.context}", label: "Feature A", as: "featureA" },
    { agent: "worker", task: "Implement feature B from {outputs.context}", label: "Feature B", as: "featureB" }
  ], concurrency: 2, failFast: true },
  { agent: "reviewer", task: "Review {outputs.featureA} and {outputs.featureB}" }
]}

// Dynamic fanout from structured output
{ chain: [
  {
    agent: "scout",
    task: "Return review targets as structured_output: { items: [{ path, reason }] }",
    as: "targets",
    outputSchema: { type: "object" }
  },
  {
    expand: { from: { output: "targets", path: "/items" }, item: "target", key: "/path", maxItems: 12 },
    parallel: { agent: "reviewer", task: "Review {target.path}. Reason: {target.reason}", outputSchema: { type: "object" } },
    collect: { as: "reviews" },
    concurrency: 4
  },
  { agent: "worker", task: "Synthesize fixes from {outputs.reviews}" }
] }

// Strict structured output for reliable handoff data
{ chain: [
  {
    agent: "scout",
    task: "Return the key files and risks for {task}",
    as: "scan",
    outputSchema: {
      type: "object",
      required: ["files", "risks"],
      properties: {
        files: { type: "array", items: { type: "string" } },
        risks: { type: "array", items: { type: "string" } }
      }
    }
  },
  { agent: "planner", task: "Plan from this scan: {outputs.scan}" }
] }

// Worktree isolation
{ tasks: [
  { agent: "worker", task: "Implement auth" },
  { agent: "worker", task: "Implement API" }
], worktree: true }

Management actions

Agent definitions are not loaded into context by default. Management actions let the LLM discover, inspect, create, update, and delete agents and chains at runtime.

{ action: "list" }
{ action: "list", agentScope: "project" }
{ action: "get", agent: "scout" }
{ action: "models" }
{ action: "models", agent: "reviewer" }
{ action: "get", agent: "code-analysis.scout" }
{ action: "get", chainName: "review-pipeline" }

{ action: "create", config: {
  name: "Code Scout",
  package: "code-analysis",
  description: "Scans codebases for patterns and issues",
  scope: "user",
  systemPrompt: "You are a code scout...",
  systemPromptMode: "replace",
  inheritProjectContext: false,
  inheritSkills: false,
  model: "anthropic/claude-sonnet-4",
  fallbackModels: ["openai/gpt-5-mini", "anthropic/claude-haiku-4-5"],
  tools: "read, bash, mcp:github/search_repositories",
  extensions: "",
  skills: "parallel-scout",
  thinking: "high",
  output: "context.md",
  reads: "shared-context.md",
  progress: true
}}

{ action: "create", config: {
  name: "review-pipeline",
  description: "Scout then review",
  scope: "project",
  steps: [
    { agent: "scout", task: "Scan {task}", output: "context.md" },
    { agent: "reviewer", task: "Review {previous}", reads: ["context.md"] }
  ]
}}

{ action: "update", agent: "code-analysis.scout", config: { model: "openai/gpt-4o" } }
{ action: "update", chainName: "review-pipeline", config: { steps: [...] } }
{ action: "delete", agent: "scout" }
{ action: "delete", chainName: "review-pipeline" }

create uses config.scope, not agentScope. config.name is the local frontmatter name; optional config.package registers the runtime name as {package}.{name} and is saved as separate name and package frontmatter. update and delete use the runtime name and agentScope only when the same runtime name exists in multiple scopes. To clear optional string fields, including package, set them to false or "".

Parameter reference

ParamTypeDefaultDescription
agentstring-Agent name for single mode, or target for management actions.
taskstring-Task string for single mode.
actionstring-list, get, create, update, delete, status, interrupt, resume, append-step, or doctor.
chainNamestring-Chain name for management actions.
configobject/string-Agent or chain config for create/update.
outputstring | falseagent defaultOverride single-agent output file.
outputMode"inline" | "file-only"inlineReturn saved output inline or as a concise saved-file reference. file-only requires an output path.
skillstring | string[] | falseagent defaultOverride skills or disable all.
modelstringagent defaultOverride model.
tasksarray-Top-level parallel tasks. Supports agent, task, cwd, count, output, outputMode, reads, progress, skill, model, and acceptance.
concurrencynumberconfig or 4Top-level parallel concurrency.
worktreebooleanfalseCreate isolated git worktrees for parallel tasks.
chainarray-Sequential, static parallel, and dynamic fanout chain steps. Steps and chain parallel tasks support phase, label, as, outputSchema, and acceptance in addition to the usual execution fields. Dynamic fanout uses expand, one child parallel template, and collect. With action: "append-step", pass exactly one step to append to a running async chain.
contextfresh | forkper-agent default or freshExplicit fresh or fork overrides every child. When omitted, each agent uses its own defaultContext; fork creates real branched sessions from the parent leaf. Packaged planner, worker, and oracle default to fork.
chainDirstringtemp chain dirPersistent directory for chain artifacts.
clarifybooleantrue for chainsShow TUI preview/edit flow.
agentScopeuser | project | bothbothAgent discovery scope. Project wins on collisions.
asyncbooleanfalseBackground execution. For chains, clarify: true explicitly keeps the run foreground for the clarify UI.
cwdstringruntime cwdOverride working directory.
maxOutputobject200KB, 5000 linesFinal output truncation limits.
artifactsbooleantrueWrite debug artifacts.
includeProgressbooleanfalseInclude full progress in result.
sharebooleanfalseUpload session export to GitHub Gist.
sessionDirstringderivedOverride session log directory.
acceptancestring/object/falseinferredOverride the run's inferred acceptance gates. Use "auto", "attested", "checked", "verified", "reviewed", or { level: "none", reason: "..." }.

context: "fork" fails fast when the parent session is not persisted, the current leaf is missing, or the branched child session cannot be created. It never silently downgrades to fresh. In multi-agent runs that omit context, each agent/task/step follows its own defaultContext, so a fresh-default scout can run fresh beside a fork-default worker. Pass explicit context: "fork" or context: "fresh" when you intentionally want one context for every child.

Use outputMode: "file-only" when a saved output may be large and the parent only needs a pointer. The returned text is a compact reference like Output saved to: /abs/report.md (48.2 KB, 2847 lines). Read this file if needed. Failed runs and save errors still return normal inline output for debugging. In chains, later {previous} steps receive the same compact reference when the prior step used file-only mode.

Sequential and parallel chain tasks accept agent, task, phase, label, as, outputSchema, cwd, output, outputMode, reads, progress, skill, and model. Parallel tasks also accept count. Parallel step groups accept parallel, concurrency, failFast, and worktree. If outputSchema is present, the child must call structured_output with schema-valid JSON; prose-only completion or invalid JSON fails the step. Validated structured values are preserved on the step result, and as also exposes a compact text representation through {outputs.name}.

Status and control actions:

subagent({ action: "status" })
subagent({ action: "status", id: "<run-id>" })
subagent({ action: "status", id: "<nested-run-id>" })
subagent({ action: "interrupt", id: "<run-id>" })
subagent({ action: "interrupt", id: "<nested-run-id>" })
subagent({ action: "resume", id: "<run-id>", message: "follow-up question" })
subagent({ action: "resume", id: "<run-id>", index: 1, message: "follow-up for child 2" })
subagent({ action: "resume", id: "<nested-run-id>", message: "follow-up for a nested child" })
subagent({ action: "append-step", id: "<run-id>", chain: [{ agent: "worker", task: "Continue from {previous}" }] })
subagent({ action: "doctor" })

status resolves exact foreground ids, top-level async ids, and nested run ids before falling back to prefix matching. Nested status shows the root/parent path, nested children, session/artifact paths when known, and nested control commands. Inside child-safe fanout mode, bare status requires an id when no local foreground run is active, so children cannot enumerate unrelated top-level async runs. Bare interrupt still targets only the visible top-level run; interrupting a nested run requires its explicit nested id.

resume sends the follow-up directly when an async child is still reachable over intercom. After completion, it revives the child by starting a new async child from the stored child session file. Multi-child async runs and remembered foreground single, parallel, or chain runs can be revived by passing index to choose the child. Nested runs can be resumed by nested id when their live route or persisted session metadata is available. Revive starts a new child process from the old session context; it does not restart the same OS process, and it requires the chosen child to have a persisted .jsonl session file.

append-step accepts exactly one sequential, static parallel, or dynamic fanout chain step for a top-level async chain whose status is still running. The step is persisted in the run directory and becomes eligible only after the chain's already-queued steps finish; completed, failed, paused, foreground, single, and top-level parallel runs reject appends.

Worktree isolation

Parallel agents can clobber each other if they edit the same checkout. worktree: true gives each parallel child its own git worktree branched from HEAD.

{ tasks: [
  { agent: "worker", task: "Implement auth", count: 2 },
  { agent: "worker", task: "Implement API" }
], worktree: true }

{ chain: [
  { agent: "scout", task: "Gather context" },
  { parallel: [
    { agent: "worker", task: "Implement feature A from {previous}" },
    { agent: "worker", task: "Implement feature B from {previous}" }
  ], worktree: true },
  { agent: "reviewer", task: "Review all changes from {previous}" }
]}

Requirements:

view the full README on GitHub.

// compatibility

Platformsapi, web
Operating systems
AI compatibilityclaude
License
Pricingopen-source
LanguageTypeScript

// faq

What is pi-subagents?

Pi extension for async subagent delegation with truncation, artifacts, and session sharing. It is open-source on GitHub.

Is pi-subagents free to use?

pi-subagents is open-source, so it is free to use.

What category does pi-subagents belong to?

pi-subagents is listed under plugins in the Claudeers registry of Claude-compatible tools.

0 views
2,394 stars
unclaimed
updated 14 days ago

// embed badge

pi-subagents on Claudeers
[![Claudeers](https://claudeers.com/api/badge/pi-subagents.svg)](https://claudeers.com/pi-subagents)

// retro hit counter

pi-subagents hit counter
[![Hits](https://claudeers.com/api/counter/pi-subagents.svg)](https://claudeers.com/pi-subagents)

// reviews

// guestbook

0/500

// related in Developer Tools

🔓

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Curs…

// devtoolsaffaan-m/JavaScript225,699MIT[ claude ]
🔓

Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA

// devtoolsgarrytan/TypeScript119,234MIT[ claude ]
🔓

🙌 OpenHands: AI-Driven Development

// devtoolsOpenHands/Python79,324NOASSERTION[ claude ]
🔓

Makes your AI agent think like the laziest senior dev in the room. The best code is the code you never wrote.

// devtoolsDietrichGebert/JavaScript73,042MIT[ claude ]

// built by

1 of its contributors also build on official projectsclaude-code, claude-cookbooks, claude-plugins-official

→ see how pi-subagents connects across the ecosystem