Pi subagents
Delegate work to named Pi agents in isolated child processes. The extension provides synchronous execution for a result the parent needs immediately and asynchronous jobs for work the parent can retrieve later.
Distributed as a Pi package: the pi manifest in package.json exposes the extension entry at src/index.ts, with host packages (@earendil-works/*, typebox) declared as peer dependencies.
Install
pi install git:git.rwiesner.com/alex/pi-subagent
Or from a local checkout:
pi install /path/to/pi-subagent
Tools
subagent — synchronous
Preserves the original blocking interface. Exactly one invocation shape is required:
{ "agent": "scout", "task": "Inspect the extension lifecycle" }
{
"tasks": [
{ "agent": "scout", "task": "Inspect lifecycle" },
{ "agent": "reviewer", "task": "Review the result", "cwd": "../project" }
]
}
{
"chain": [
{ "agent": "scout", "task": "Investigate the design" },
{ "agent": "reviewer", "task": "Review this report: {previous}" }
]
}
Parallel accepts at most eight tasks. Chain replaces every {previous} placeholder with the preceding step’s final output and stops at the first failure.
subagent_async — start without waiting
Accepts the same invocation fields as subagent, validates the complete invocation, and returns a job ID immediately. Available in TUI and RPC sessions. Print/JSON calls return an error directing the caller to subagent.
{ "tasks": [{ "agent": "scout", "task": "Research storage" }] }
Async jobs survive the current tool call and model turn. Completion does not inject a message or start a model turn automatically.
subagent_jobs — inspect and control
{ "action": "list", "activeOnly": true }
{ "action": "get", "jobId": "job_0001" }
{ "action": "wait", "jobId": "job_0001", "timeoutSeconds": 30 }
{ "action": "cancel", "jobId": "job_0001" }
waitdefaults to 30 seconds and accepts values greater than zero up to 300 seconds. Timeout returnstimedOut: truewithout changing the job.- Aborting a wait stops only that wait. Aborting a synchronous invocation cancels that invocation.
cancelis idempotent for terminal jobs. It prevents queued tasks from starting and terminates running process trees.- Unknown or evicted IDs and malformed requests are management errors. A successfully retrieved
failed,cancelled, orinterruptedjob is not a management-tool error.
Avoid tight polling: use wait when the parent cannot proceed without the result.
Human inspection
/subagents
/subagents job_0001
/subagents cancel job_0001
The footer shows the number of active jobs. /subagents lists active and retained terminal jobs; the detailed view includes tasks, diagnostics, output, timing, and usage.
Scheduling and admission
Synchronous and asynchronous work share one FIFO scheduler. At most four child processes run globally by default.
export PI_SUBAGENT_MAX_WORKERS=8
Valid worker values are integers from 1 through 32. Invalid values fall back to four with a warning. A session accepts at most 64 nonterminal async jobs; excess admission fails atomically without spawning work. Cancelling or finishing jobs frees admission capacity.
Before admission, the extension validates all agents and directories. Relative cwd values resolve against the caller’s ctx.cwd. Agent discovery is performed separately at each task’s resolved directory, so project-local agents follow the task rather than the parent process’s incidental directory.
agentScope is user by default. Use project or both for project agents. In an untrusted interactive project, every distinct project-agent source requires confirmation; a trusted session exempts only its own project-agent directory, not foreign directories selected through task cwd. confirmProjectAgents: false bypasses prompts and should be used only for trusted projects. Noninteractive print/JSON sessions cannot display confirmation prompts and retain the existing no-prompt behavior.
States and outcomes
Jobs use:
queued → running → succeeded | failed | cancelled | interrupted
↘ cancelling → cancelled
Tasks use queued, running, succeeded, failed, cancelled, and interrupted.
- Single mirrors its task outcome.
- Parallel runs all admitted tasks unless cancelled. Any failed task fails the job, while successful results remain available.
- Chain records only executed steps and stops on failure.
- Spawn errors, nonzero exits, error/aborted stop reasons, and termination signals are failures.
- Once cancellation is processed, a later successful process exit cannot change the outcome.
On reload, quit, /new, resume, or fork, unfinished jobs become interrupted; the extension stops admission and awaits process-tree cleanup. It sends SIGTERM, then SIGKILL after five seconds when necessary. Normal Pi shutdown awaits this handler. Hard crashes, SIGKILL, and forced exits cannot guarantee cleanup.
There is no per-task execution timeout. Work runs until completion, explicit cancellation, or session shutdown.
Results, history, and usage
Async snapshots retain per-task final output up to 50 KiB and a valid-UTF-8 stderr tail up to 64 KiB, with explicit truncation metadata. Raw message/tool transcripts are retained for synchronous rendering but not for async history.
Pi custom entries persist bounded job snapshots outside model context. Reload/resume restores them for inspection; restored unfinished jobs become interrupted, never runnable. /new starts empty. /tree navigation replaces terminal history from the active branch without disturbing live jobs. Active jobs plus the 50 most recent terminal jobs are retained; oldest terminal history evicts first.
Child token/cost usage is aggregated in snapshots for inspection. It is not automatically added to the parent tool’s usage because repeated get and wait calls could otherwise double-count it.
Child runtime
Each task remains a real pi --mode json -p --no-session process and inherits the existing model, thinking, tool, context-file, skill, extension, and MCP behavior. Agent markdown bodies are passed as appended system prompts.
Children always receive --exclude-tools subagent*, preventing recursive dispatch and worker-pool deadlocks. Other startup isolation is unchanged.
Development
npm install --ignore-scripts
npm run check
npm test
npm run modelcheck
npm run smoke
spec/SubagentJobs.tla models the bounded scheduler, the lifecycle, and the workflow state machine: needs sets instead of a chain predecessor, the skipped status with its transitive cascade, each-step items (fail-soft, zero items fail the step), and a per-run reservation of min(maxWorkers - 1, 4) steps inside the shared pool. TLC checks worker and per-run bounds, needs ordering, skip propagation, run outcomes, terminal stability, and cancellation/shutdown behavior. Set TLA2_TOOLS_JAR if tla2tools.jar is not at the local development fallback path.
Tests exercise the manager interface, tool schemas/adapters, real subprocess behavior with a fake Pi executable, generated transition sequences, UTF-8 properties, and persistence. .pi/verify.json wires the deterministic gates.
pi-durable evaluation
This implementation intentionally uses Pi-native subprocesses and custom entries, not @earendil-works/pi-durable. The pinned comparison and rationale are in research/pi-durable-async-subagents.md.