@rotart/pi-sub

extension

Pi extension for delegating tasks to subagents with chains, parallel execution, and TUI clarification

by · v0.36.2 · published 2w ago

$ pi install npm:@rotart/pi-sub
downloads/mo
0
stars
last push
open issues

Signals

license: MITtestspi manifest: missinginstall size: —deps: 0peer deps: 0

Download trend

416 downloads · last 12 weeks (weekly)

README

@rotart/pi-sub

@rotart/pi-sub 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.

Installation

pi install npm:@rotart/pi-sub

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.” or “Show the subagent fleet.”
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 every subagent without its own model to use a different default, set subagents.defaultModel. If you want a role to use a specific model, set an override instead of copying the bundled agent file.

{
  "defaultModel": "deepseek-v4-pro",
  "subagents": {
    "defaultModel": "deepseek-v4-flash",
    "agentOverrides": {
      "oracle": {
        "model": "deepseek-v4-pro"
      }
    }
  }
}

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. subagents.defaultModel applies to builtin, package, user, and project agents that do not set model in frontmatter. Per-run model overrides and agentOverrides.<name>.model still win, and explicit agent frontmatter still wins over the global default. 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.

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 @rotart/pi-sub 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.

You do not have to spell a model exactly. Model ids are matched fuzzily against the registry, so provider separator variations (anthropic/claude-sonnet-4, anthropic:claude-sonnet-4, or anthropic.claude-sonnet-4), id separator variations (claude-haiku-4.5 vs claude-haiku-4-5), case differences (Claude-Sonnet-4 vs claude-sonnet-4), and optional trailing date stamps (claude-haiku-4-5-20251001 or claude-haiku-4-5-2025-10-01 vs claude-haiku-4-5) all resolve to the same model. Exact provider/id matches still win, and a qualified provider query never silently switches providers — it only matches within the named provider. Ambiguous bare ids that exist under multiple providers still require a provider prefix or the current session's provider to disambiguate.

Choosing a watchdog model

The subagent watchdog is not the reviewer subagent. subagents.defaultModel and subagents.agentOverrides.reviewer do not configure it. The watchdog is an opt-in adversarial change reviewer, so it should usually use a strong complementary model rather than a cheap/light model.

The watchdog reviews repo edits, not ordinary conversation. It runs at the safe agent_end boundary only when the current agent or child writer changed the final repo state since the start of that turn. Multiple edits in one turn are coalesced into one review of the final changed state, unchanged/reverted diffs are skipped, and generated .pi-subagents/ or tmp/ artifacts do not trigger review. In orchestrated runs, each writing child can review its own edited worktree, and the parent can still review the aggregate repo diff after child changes are applied.

When the watchdog is enabled, it also checks changed TypeScript and JavaScript files for fresh language-server diagnostics before the model review. It auto-detects typescript-language-server from the project node_modules/.bin or PATH; it never installs tools or scans the whole workspace. LSP errors surface as watchdog blockers, warnings as concerns, and info/hints stay in status details. Slow or missing servers are reported in /subagents-watchdog status without blocking the turn or emitting late mid-turn warnings. Configure the bounds with subagents.watchdog.lsp.enabled, timeoutMs, maxFiles, and maxDiagnostics.

Use /subagents-watchdog recommend-model to ask @rotart/pi-sub for the current strong pairing. The current recommendation policy is Opus 4.8 with thinking high or GPT 5.5 with thinking high. If your main session is using one, the watchdog should use the other when that model is authenticated.

/subagents-watchdog recommend-model
/subagents-watchdog session model recommended
/subagents-watchdog model recommended

session model recommended changes only the current Pi session. model recommended saves the recommendation to ~/.pi/agent/settings.json; it does not turn the watchdog on. Enable it separately with /subagents-watchdog on when you want the extra review pass.

You can also set the model explicitly:

/subagents-watchdog model anthropic/claude-opus-4-8:high
/subagents-watchdog model openai-codex/gpt-5.5:high
/subagents-watchdog model inherit
/subagents-watchdog check

For settings files, use subagents.watchdog.main.model and subagents.watchdog.main.thinking for the main watchdog. If main.model is omitted, the main watchdog uses the current session model and thinking level. If main.model is set without a thinking suffix or main.thinking, it runs with thinking off, so prefer :high or "thinking": "high" for the strong-watchdog pairing.

{
  "subagents": {
    "watchdog": {
      "enabled": true,
      "main": {
        "model": "anthropic/claude-opus-4-8",
        "thinking": "high"
      }
    }
  }
}

For child subagent watchdogs, use subagents.watchdog.children.model as the default child watchdog model, or subagents.watchdog.children.overrides.<agent>.model for a specific child role. Child watchdogs are still opt-in and follow the same edit-gated rule: read-only children do not trigger watchdog reviews, while writer children are reviewed at their own agent_end if their worktree changed.

Agents can configure the same values through the tool when you ask them to set up the watchdog:

subagent({ action: "watchdog.recommend-model" })
subagent({ action: "watchdog.configure", model: "recommended", scope: "session" })
subagent({ action: "watchdog.configure", model: "recommended", scope: "project" })

Persistent scopes (user or project) should only be used when you ask for a lasting default. Otherwise the agent should use scope: "session".

To keep subagents inside a budget or compliance profile, enforce a model scope. Put subagents.modelScope in user or project settings (project overrides user):

{
  "subagents": {
    "modelScope": {
      "enforce": true,
      "allow": ["anthropic/*", "openai/gpt-5-*"]
    }
  }
}

allow is a list of glob patterns matched against the resolved provider/id (only * is special, case-insensitive). A resolved model that matches none of the patterns is rejected. Models you pass explicitly — the tool-call model, --model, or a clarify pick — error and abort the run. Models that come from agent frontmatter, subagents.defaultModel, or the inherited parent session model only warn, so existing configurations keep working while you tighten the scope. enforce: true requires a non-empty allow list; otherwise the config is rejected at load time.

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: "..." }). /subagents-fleet opens a live, inspection-only fleet with current-session foreground work, recent async children, transcript tails, and completed output/session paths. Use / or j/k to select a child, PgUp/PgDn to scroll its transcript, r to refresh immediately, and Esc to close. Ctrl+Alt+F opens the same inspector even while a foreground turn is active and slash input is queued. Without a TUI, /subagents-fleet retains the textual subagent({ action: "status", view: "fleet" }) fallback. Mutations stay in explicit commands: run /subagents-stop and pick from the selector, or use /subagents-stop <run-id> / subagent({ action: "stop", id: "..." }) when you already know the id. To inspect one background child in text, use subagent({ action: "status", id: "...", view: "transcript" }); add index for a specific child in a parallel or chain run.

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.

Async runs also write machine-readable lifecycle artifacts for observability and workflow gates. For a top-level async run, details.asyncDir points at a directory containing status.json, events.jsonl, output-<index>.log, and subagent-log-<runId>.md; the final summary is written to Pi's subagent results directory as <runId>.json. Nested async runs use the same shape under the nested async root and are discoverable through status projections that read the nested-run registry. These files are append/update artifacts only; interactive foreground behavior is unchanged.

Foreground and async runners share bounded child-protocol handling. A child JSONL line above 4 MiB fails with structured protocolError code protocol_output_limit, stderr retains only its latest 128 KiB, split UTF-8 and final unterminated JSON events remain valid, and agent_end.willRetry defers completion until the child settles. Current Pi builds use agent_settled as the terminal watermark; older builds retain the bounded terminal-message fallback.

The stable v1 status/result fields are lifecycleArtifactVersion, runId/id, sessionId, mode, state, startedAt, lastUpdate, endedAt, durationMs, cwd, asyncDir, sessionFile, outputFile, workflowGraph, steps, results, totalTokens, totalCost, model/attemptedModels/modelAttempts, toolCount, turnCount, and nested children when a child is allowed to launch subagents. events.jsonl records lifecycle transitions such as subagent.run.started, subagent.step.started, subagent.step.completed/failed/paused/stopped, control attention events, nested interrupt failures, and subagent.run.completed/stopped; run boundary events include the lifecycle artifact version. Consumers should read these JSON files instead of scraping terminal output; unknown fields and event types should be ignored for forward compatibility.

Other Pi extensions can use the versioned in-process event-bus RPC instead of scraping slash output or calling internal modules. Listen for subagents:rpc:v1:ready, send requests on subagents:rpc:v1:request, and read replies from subagents:rpc:v1:reply:<requestId>.

const requestId = crypto.randomUUID();
pi.events.on(`subagents:rpc:v1:reply:${requestId}`, (reply) => {
  // { version: 1, requestId, success: true, data } or
  // { version: 1, requestId, success: false, error: { code, message } }
});
pi.events.emit("subagents:rpc:v1:request", {
  version: 1,
  requestId,
  method: "spawn",
  params: { agent: "reviewer", task: "Review the current diff", context: "fresh" }
});

The v1 methods are ping, status, spawn, interrupt, and stop. status and interrupt reuse the normal control actions. spawn is async-only: omit async or set async: true, omit clarify or set clarify: false, and do not pass management action values. It goes through the same executor as the subagent tool, so agent discovery, validation, session attribution, configured spawn caps, child-safety depth, artifacts, and async status all behave the same. stop targets current-session top-level async runs through the stop control channel and records a stopped lifecycle instead of reporting a timeout.

pi.events is in-process only. It does not reach separate Pi processes or child subagents; use the file lifecycle artifacts or pi-intercom for cross-process coordination.

If something feels misconfigured, run:

/subagents-doctor

or ask:

Check whether subagents and intercom are set up correctly.

Recommended orchestration pattern (scaffolding)

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, oracle, and advisor 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 @rotart/pi-sub 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.

Native supervisor coordination

Child agents can talk back to the parent Pi session without installing pi-intercom. @rotart/pi-sub provides the child-facing contact_supervisor tool and the parent-facing subagent_supervisor({ action: "reply" }) path natively. Requests are delivered through a file-based channel — no broker, no daemon.

Automatic wake-up

When a child sends a contact_supervisor request, the parent is automatically woken via triggerTurn and can respond without manual user input. If the parent is busy (thinking or running a tool), the request is queued and delivered as soon as the parent becomes idle.

  • Interactive (UI) sessions: requests are gated on idle to avoid interrupting active work (500ms retry loop, matching pi-intercom's pattern).
  • Headless (non-UI) sessions: triggerTurn is applied immediately with no idle check.
  • Progress updates (reason: "progress_update"): delivered as followUp without triggering a new turn.

Usage

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, reason: "interview_request" for structured input, 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.

Optional parameters for multi-request lifecycles:

ParameterTypeDescription
sessionIdstringOpaque token linking multiple requests from the same child lifecycle
previousRequestIdstringThe requestId of the previous request in this session, enabling parent-side chain display

The parent replies with subagent_supervisor({ action: "reply", replyTo, message }) or checks pending requests with subagent_supervisor({ action: "pending" }). Supervisor messages are scoped to the exact Pi session id that spawned the child. A second Pi session in the same repository does not receive those requests.

Child-side routine completion handoffs are still not expected. 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.

Note on pi-intercom coexistence

When pi-intercom is also installed, its contact_supervisor implementation takes priority (broker-based). The native file channel described here is used when pi-intercom is not installed or when its child bridge metadata is absent. The two are independent communication paths with different transport mechanisms.

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 @rotart/pi-sub's visibility-based tool restrictions.

The two compose independently:

LayerWhat it controlsWho provides it
VisibilityWhich tools are registered before the session starts@rotart/pi-sub (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. @rotart/pi-sub 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 @rotart/pi-sub 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
/chain scout "scan" -> (reviewer "A" | reviewer "B") -> writer "fix"Run a chain with a static parallel group inline
/parallel agent1 "task1" -> agent2 "task2"Run agents in parallel
/run-chain <chainName> -- <task>Launch a saved .chain.md or .chain.json workflow
/subagent-costShow parent plus child subagent token usage and cost for this session
/subagents [agent] [model|thinking|prompt|details]Interactively inspect or edit an agent's model, thinking level, or system prompt
/subagents-doctorShow read-only setup diagnostics
/subagents-models [agent]Show the runtime-loaded builtin model mapping, optionally filtered to one builtin
`/subagents-watchdog [statuson
/subagents-profilesList saved subagent profiles from ~/.pi/agent/profiles/pi-subagents/
/subagents-load-profile <name>Replace only settings.subagents with a saved profile and optionally switch this session to the profile worker model
/subagents-refresh-provider-models <provider> [--force]Create or refresh the cached provider model catalog
/subagents-generate-profiles <provider>Generate <provider>.quota.json and <provider>.quality.json profiles
/subagents-check-profile <name>Check a saved profile against the current registry and live model probes

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

/subagents opens a compact administration flow for builtin, package, user, and project agents. Model choices refresh Pi's model registry first, thinking choices are filtered to levels declared by the selected model, and prompt editing uses a blocking $VISUAL/$EDITOR command (with MarkEdit as the macOS fallback). Full metadata is opt-in through details. Edits are persisted to the field-owning layer: explicit custom-agent frontmatter remains in the agent file, while settings/profile-managed fields remain in settings.subagents.agentOverrides. Package-owned fields and definitions loaded through PI_SUBAGENT_EXTRA_AGENT_DIRS stay read-only; settings can still supply model or thinking fields omitted by a package definition.

Profiles and provider model catalogs

Profiles are stored under:

~/.pi/agent/profiles/pi-subagents/

Provider model catalogs are cached under:

~/.pi/agent/profiles/pi-subagents/providers/

Use the profile workflow like this:

/subagents-refresh-provider-models openai-codex
/subagents-generate-profiles openai-codex
/subagents-load-profile openai-codex.quota

/subagents-refresh-provider-models writes a serialized provider model catalog with observed registry data, simple role-oriented classification, and live probe results from tiny one-shot pi -p --model ... --no-tools checks. The cache refreshes when missing or stale; use --force to ignore freshness and probe again immediately.

/subagents-generate-profiles uses the provider catalog to produce quota and quality profiles. /subagents-check-profile re-checks each assigned model in a saved profile against the current registry and a live probe so you can detect model removals, auth problems, or stale assignments.

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.

Inline parallel groups in /chain

Wrap a group of agents in parentheses and separate them with | to fan them out within a single chain step. The group runs all of its tasks concurrently, then the next -> step continues once they finish:

/chain scout "scan" -> (reviewer "review A" | reviewer "review B") -> writer "fix"

Notes:

  • Groups must contain at least two tasks separated by |, each with its own task.
  • Group syntax is only valid between -> separators, and the group must appear as a complete step.
  • Only a step that opens with ( is a group. Parentheses inside a shared -- task (e.g. /chain scout -- inspect auth (backend)) stay literal text and keep the legacy single-agent behavior.
  • A group is treated as the prior step’s output for the next sequential step.
  • Tab completion suggests agents inside groups — after (, after |, and on each new -> step.

Add a [...] suffix right after the closing ) to set step-level options on the group:

/chain scout "scan" -> (reviewer "A" | reviewer "B")[concurrency=2,failFast,worktree] -> writer "fix"
Group optionDescription
concurrency=NMax tasks running at once within the group.
failFastStop the group as soon as one task fails.
worktreeRun each group task in its own git worktree.

Dynamic fanout (expand / collect) is intentionally not available inline — use the subagent({ chain: [...] }) tool API or a saved .chain.json for data-driven fan-out.

/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. /chain applies every key below; /run and /parallel use the execution-behavior keys (output, outputMode, reads, model, skills, progress) and ignore chain-only metadata such as as, label, phase, count, outputSchema, and acceptance.

/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. Absolute paths are used as-is. Relative paths in /run resolve under singleRunOutputBaseDir when configured, otherwise under the run's output artifact directory. Relative paths in /chain and /parallel live under the chain or parallel run directory.
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.
asas=contextName this step’s output so later steps can reference it.
labellabel=ReconHuman-readable label for the step.
phasephase=analysisGroup steps into a named phase.
cwdcwd=packages/apiRun the step in a subdirectory.
countcount=3Fan a group task into N copies (only inside a ( ... ) group).
outputSchemaoutputSchema=schema.jsonValidate structured output against a JSON Schema file (path resolved against the session cwd, not an inline step cwd).
acceptanceacceptance=checkedInline acceptance level: auto, attested, or checked. Use the tool API or saved .chain.json for object contracts such as none or verified; reviewed is inferred-only.

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.

Inline [...] values must not contain spaces or commas — keep label/phase to single tokens.

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. In an interactive chat, it should normally return control when ready to yield and let Pi deliver the completion notification instead of blocking merely to wait. Override that default and use subagent_wait when the current request is run-to-completion — for example, the user asked you to report results back before continuing or a skill cannot return before its work finishes. In a non-interactive run, Pi auto-drains current-session work at agent_end; use subagent_wait when this turn must receive results before it ends. It returns when the next initially active run or registered provider item finishes or a subagent needs attention; use subagent_wait({ all: true }) for all work active at call time, subagent_wait({ id }) for one async or remembered detached foreground run, and subagent_wait({ timeoutMs }) to cap the block.

A foreground child can detach while it waits for a supervisor reply. Reply first, then call subagent_wait({ id: runId }). While that wait blocks, it streams the detached child's current tool and recent transcript activity into the pending tool row when transcript artifacts are available. The remembered run stays pending until the child exits, then emits a session-scoped completion notification with recovered output and remains inspectable through subagent({ action: "status", id: runId }). Do not call resume or launch a replacement while the child remains detached.

Headless sessions also auto-drain current-session subagent and registered provider work at agent_end, using one absolute timeout and continuing through attention states. This is a final lifecycle safeguard rather than a replacement for explicit orchestration: subagent_wait still lets a model react to each result during the turn. Provider, reconciliation, timeout, and malformed-state failures remain visible errors instead of being treated as successful drains.

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

Clarify and launch UI

Tool calls launch directly by default. Set clarify: true on single, parallel, or chain runs when you want to preview and edit the workflow before it runs; 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 @rotart/pi-sub.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 {"@rotart/pi-sub":{"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.defaultModel or subagents.agentOverrides.<name>.model. oracle is an advisory reviewer that critiques direction and proposes an execution prompt without editing files; advisor is the same bundled role under the Claude Code-compatible name. 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, acceptanceRole, disabled, skills, tools, and systemPrompt. Use defaultContext: false or acceptanceRole: false to clear an inherited override. Project overrides beat user overrides.

Set subagents.defaultModel to give all subagents without an explicit model their own default model, separate from the parent session model. Per-agent model overrides and agent frontmatter still win.

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. You can also toggle a single agent without editing settings by hand: subagent({ action: "disable", agent: "reviewer" }) writes that override, and subagent({ action: "enable", agent: "reviewer" }) removes it.

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, review-checklist
skillPath: ./skills, ../shared-skills
output: context.md
defaultReads: context.md
defaultProgress: true
async: true
timeoutMs: 900000
turnBudget: {"maxTurns":20,"graceTurns":2}
acceptance: {"level":"none","reason":"lightweight lookup"}
acceptanceRole: read-only
completionGuard: false
interactive: true
maxSubagentDepth: 1
---

Your system prompt goes here.

Simple-scalar list fields accept either the existing comma-separated form or a newline block list with one - item per line. This applies to tools, defaultReads, skill/skills, skillPath, fallbackModels, extensions, and subagentOnlyExtensions; for example:

tools:
  - read
  - mcp:github/search_repositories
fallbackModels:
  - openai/gpt-5-mini
  - anthropic/claude-sonnet-4

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.
toolsStrict child tool allowlist. Named extension tools must also have their provider loaded. mcp: entries select direct MCP tools when pi-mcp-adapter is installed.
extensionsOmitted means normal extensions; empty means no extensions; list values allowlist specific extensions.
subagentOnlyExtensionsExtension 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.
skillsSelects specific skills for the child, regardless of inheritSkills.
skillPathInvocation-private skill files or discovery directories. Relative paths resolve from the agent definition file. Local matches take precedence, while unresolved or unreadable matches fall back to normal skill discovery. This field discovers candidates only; skills still selects what the child receives.
outputDefault single-agent output file.
defaultReadsFiles to read before running in chain/parallel behavior.
defaultProgressMaintain progress.md.
asyncDefault a single-agent launch to background (true) or foreground (false) when the call omits async. Explicit call values and forceTopLevelAsync win.
timeoutMsPositive integer default runtime deadline in milliseconds for single-agent launches. An explicit timeoutMs or maxRuntimeMs wins.
turnBudgetJSON object default such as {"maxTurns":20,"graceTurns":2} for single-agent launches. An explicit call value wins, followed by this agent default, then global turnBudget config.
acceptanceAcceptance default for single-agent launches. Use a scalar level such as checked or an inline/block YAML map such as { level: "none", reason: "lightweight lookup" }. Explicit call values win; chain and parallel acceptance remains task/step configuration.
acceptanceRoleOptional read-only or writer role for automatic acceptance inference. Explicit task mutation or no-edit intent wins; otherwise the declared role replaces agent-name guessing. This does not grant or revoke tools.
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.
memoryOpt-in role-specific persistent memory. memory: { scope: "project" | "user", path: "<name>" } injects the first lines of a MEMORY.md from a dedicated agent-memory/ directory into the child system prompt. Agents with write tools (edit/write/bash) get a read-write block; read-only agents get a read-only fallback. Project scope resolves under <project>/.pi/agent-memory/, user scope under ~/.pi/agent/agent-memory/. Paths are validated against traversal and symlink escape.

Agent-local skillPath candidates never enter Pi's parent/global skills catalog. Pair inheritSkills: false with explicit skills and skillPath when a child should receive only its selected private skills.

Per-agent persistent memory

A recurring custom agent can opt into a durable, role-specific memory scope with the memory frontmatter field. This is independent of Pi's own parent/session/project memory system and writes nothing to it; memory lives under a dedicated agent-memory/ namespace so the two never collide.

memory:
  scope: project
  path: security-reviewer

On each run, the first 200 lines of MEMORY.md in the resolved memory directory are injected into the child system prompt so the agent can recall accumulated role notes such as threat-model entries, release gotchas, or verified commands. Agents that have write tools (edit, write, or bash, or no tools allowlist at all) are told they may append concise dated entries to the file. Agents without write tools receive a read-only memory block and are not instructed to edit it, so a read-only reviewer can still recall prior notes without being granted write capability. The memory directory is never created eagerly; the agent's own write tool creates it (and MEMORY.md) on the first persist. Memory paths are validated against ./.. traversal and symlink escape, and an unsafe or unresolvable scope is silently skipped rather than breaking the run.

Project-scoped memory resolves under <project>/.pi/agent-memory/<path> and travels with the repo. User-scoped memory resolves under ~/.pi/agent/agent-memory/<path> and is shared across projects for that agent.

Tool and extension selection

If tools is omitted, @rotart/pi-sub does not pass --tools, so the child gets Pi's normal builtin tools. If tools is present, regular tool names become an explicit allowlist. An allowlisted name does not load the extension that registers it: load that provider through normal Pi extension discovery, extensions, subagentOnlyExtensions, or a path-like tools entry. 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 tool names. Internal runtime tools such as structured_output are added to an explicit allowlist only when their contract is active. 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.
  • tools: read, fixture_search plus subagentOnlyExtensions: ./tools/fixture-search.ts: the provider loads only in this agent's child process, and the registered fixture_search name survives the strict allowlist.

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, normal discovered extensions are disabled; the listed extensions, path-like tools entries, required @rotart/pi-sub runtime extensions, and subagentOnlyExtensions still load.

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.

Before the first model turn, the child runtime compares every explicit tool name with Pi's final filtered registry. A missing provider now fails the run with the unavailable names and concrete subagentOnlyExtensions/extensions guidance instead of letting a direct or chained child silently continue without its requested tools.

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 @rotart/pi-sub.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 {"@rotart/pi-sub":{"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 @rotart/pi-sub 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 supervisor/result delivery works through the native channel
  • 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.

Extension delegation API

Pi extensions can request one configured foreground agent through the typed v1 event contract:

import {
  SUBAGENT_DELEGATION_REQUEST_EVENT,
  SUBAGENT_DELEGATION_RESPONSE_EVENT,
  type SubagentDelegationRequest,
  type SubagentDelegationResponse,
} from "@rotart/pi-sub/delegation";

const request: SubagentDelegationRequest = {
  version: 1,
  requestId: crypto.randomUUID(),
  agent: "reviewer",
  task: "Review the supplied evidence.",
  context: "fresh",
  cwd: ctx.cwd,
  timeoutMs: 120_000,
  toolBudget: { soft: 10, hard: 16, block: "*" },
};

const unsubscribe = pi.events.on(SUBAGENT_DELEGATION_RESPONSE_EVENT, (payload) => {
  const response = payload as SubagentDelegationResponse;
  if (response.requestId !== request.requestId) return;
  unsubscribe();
  // Inspect response.status and the metadata present for this run.
});
pi.events.emit(SUBAGENT_DELEGATION_REQUEST_EVENT, request);

The contract uses the established prompt-template:subagent:* event transport and the same executor as the subagent tool; it does not add another launcher. New integrations must send version: 1. Requests are strict and single-agent only. They can set fresh or fork context, model, cwd, timeout, turn and tool-call budgets, skills, output behavior, acceptance, and artifact capture. Unknown or malformed fields return invalid_request before execution.

Responses distinguish completion, failure, timeout, cancellation, interruption, turn or tool-budget exhaustion, explicit acceptance failure, invalid requests, and unavailable active context. Optional run, model, output, session, acceptance, usage, progress, and warning fields are omitted when unavailable. Request IDs must be unique while active; duplicate active IDs are ignored so the original request keeps ownership of its terminal response. Emit SUBAGENT_DELEGATION_CANCEL_EVENT with the same version and request ID to cancel queued or active work.

Delegation requires an active extension context. Emit requests from a supported event callback or queued application step, not by recursively invoking the subagent tool inside another tool's tool_call hook. The caller selects a configured agent, but agent discovery and effective tools remain package-owned. A request cannot grant arbitrary tools, and tool restrictions are not an operating-system sandbox. The detached RPC remains async-only; this API is foreground-only.

Existing prompt-template payloads continue over the same event family, including their parallel-only adapter. @rotart/pi-sub/delegation is the canonical contract for new extension integrations.

Background-work provider API

Other Pi extensions can make their current-session jobs visible to subagent_wait through the versioned process-local provider contract:

import { registerBackgroundWorkProvider } from "@rotart/pi-sub/background-work";

const dispose = registerBackgroundWorkProvider({
  name: "my-background-extension",
  wakeChannels: ["my-extension:job-finished"],
  listActiveWork: () => jobs
    .filter((job) => job.status === "running")
    .map((job) => ({ id: job.id, sessionId: job.ownerSessionId })),
  reconcile: ({ sessionId, nowMs }) => reconcileJobs(sessionId, nowMs),
});

Each