2026-12-01 12:14:48 +00:00
2026-12-01 12:14:48 +00:00

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. Results are pull-based: completion does not inject a message or start a model turn automatically. The one scoped exception is a run started by ultra, which delivers its status and consolidated answer as a message when it finishes (see Ultra); subagent_async and workflow runs stay pull-based.

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" }
  • wait defaults to 30 seconds and accepts values greater than zero up to 300 seconds. Timeout returns timedOut: true without changing the job.
  • Aborting a wait stops only that wait. Aborting a synchronous invocation cancels that invocation.
  • cancel is 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, or interrupted job is not a management-tool error.

Avoid tight polling: use wait when the parent cannot proceed without the result.

Workflows

A workflow is a declarative plan in a markdown file, executed as a DAG of agent steps on the same subagent manager. Reach for one when a delegation has several phases, when named results must fan in, or when the same plan will run more than once: the plan lives in a file — reviewable in a diff, rerunnable — instead of being re-derived in the parent’s context.

Where workflow files live

  • Project: the nearest .pi/workflows/ directory found by walking up from the session cwd. Only *.md files directly inside it are read.
  • User: ~/.pi/agent/workflows/ (or $PI_CODING_AGENT_DIR/workflows).

A project workflow overrides a user workflow with the same name, so a repository can tailor a shared plan. Files are looked up by their frontmatter name, not by file name.

A file is YAML frontmatter — name, description, optional args, and a steps list — plus a free-form body that is ignored at run time. Step fields are id, agent, task, needs, each, model, and cwd. Unquoted each values and scalar values containing {steps...} are accepted via a repair pass, though quoting them is the form that cannot surprise you. Steps form a DAG: a step starts once every step in its needs succeeded; earlier results reach it through {steps.<id>.output}, declared arguments through {args.<name>}, and an each-step’s current line through {item}. An each-step (each: {steps.<id>.output}) fans out over the nonblank lines of a needed step’s output, one child per line.

Starting a run

{ "action": "start", "name": "audit-routes", "args": { "glob": "src/**/*.ts" }, "cwd": "packages/api" }
/workflow audit-routes glob=src/**/*.ts
/workflow audit-routes glob="src/**/*.ts"

Both surfaces validate the file, its arguments, its step-output references, the agents, and the working directories before any child spawns, then return immediately with the run’s job ID and the start plan. The tool accepts an optional cwd for discovery and step resolution; the slash command takes key=value arguments, quoted when a value contains spaces.

A project workflow and its project agents are repo-controlled: an interactive session asks once, naming every untrusted project directory involved in that start, and approving covers each directory for later starts. User workflows and user agents are trusted and never prompt.

Managing runs

A run is a job, so there is no workflow-specific management surface: subagent_jobs (get, wait, list, cancel) and /subagents handle runs alongside other work, with rows reading Step <id> and Step <id> item <n>. One journal entry per run records the plan, per-step and per-item records, and bounded outputs when the run finishes; a run interrupted by reload, quit, /new, resume, or fork is restored as interrupted.

Bounds: 64 steps per workflow; 32 items per each-step (PI_SUBAGENT_WORKFLOW_MAX_ITEMS, valid 1–256); 256 expanded children per run; and at most min(PI_SUBAGENT_MAX_WORKERS − 1, 4) concurrent children of a run, so PI_SUBAGENT_MAX_WORKERS must be at least 2 to start one. A failed step skips its dependents while independent branches continue; a failed item leaves an empty slot without failing its each-step, but the run fails if any step or item failed.

Workflow authoring is documented in the workflow-authoring skill at .agents/skills/workflow-authoring/SKILL.md (load it as /skill:workflow-authoring before writing or editing a workflow file).

Ultra

Ultra is a policy layer over the workflow engine for plans that are one-off. It adds an inline-plan tool, a per-session mode with injected planning guidance, a keyword trigger for a single prompt, and completion notices for the runs it starts. Parsing, validation, caps, the scheduler, the journal, and run management stay the workflow engine’s.

ultra — inline plans

The ultra tool takes { plan, args?, cwd? }. plan is the same markdown document a workflow file is — YAML frontmatter with name, description, optional args, and steps; the body is ignored — parsed by the file parser and validated by the file validator. Structural validation, step-output references, declared arguments, the 64-step cap, and every step agent and cwd happen before any child spawns; the item count is only known when an each-step’s source output exists, so the ≤ 32-items-per-step and ≤ 256-children-per-run caps are re-checked as each fan-out resolves, before any item child spawns. Project agents named by an inline plan still hit the existing project-agent confirmation.

Author inline for a one-off plan, and save it under .pi/workflows/ when it is worth rerunning. There is no save action: the run’s journal records the plan with source "inline", and that entry is the plan’s only persisted copy.

The start call returns the run id, the start plan, the size guideline, and the retrieval hint; the run is an ordinary async job, managed with subagent_jobs and /subagents like any other.

Review card. With a UI and ultra mode off, every ultra start shows one review card after validation and before the run: the plan, each step with its needs and fan-out source, the child-count estimate against the caps, and every named agent with its user or project source. Declining spawns nothing. With ultra mode on, the mode is the consent and no card appears, though the start result still shows the plan. Print/JSON sessions have no UI and never prompt; they start directly. The review policy lives in the extension — there is no tool parameter for it.

/ultra mode

/ultra or /ultra status reports the mode; /ultra on and /ultra off set it, and anything else prints usage. The setting is in memory for the session, and the next session starts from PI_SUBAGENT_ULTRACODE (default off). While the mode is on, before_agent_start adds an ultracode system-prompt section — cache-diffed by Pi, never a per-run message — with the decision heuristics (a task larger than one agent can hold in context; the same step across many items; findings that should be cross-checked before the user sees them), the pattern menu and its declarative mapping (fan-out and synthesize → each-step plus fan-in; adversarial verification → a verify step that needs the producer; generate and filter; tournament via pre-expanded brackets; classify-and-act and loop-until-done not expressible in one plan), the current size guideline, and the wait-before-continuing instruction. Turning the mode off removes the section.

The ultracode keyword

Typed interactive input containing the lowercase, word-bounded ultracode has the word stripped and arms a one-shot flag. The next run receives an instruction to author an inline plan for the task and start it before doing the work. Matching is case-sensitive (Ultracode does not trigger) and word-bounded (ultracodes and myultracode do not). Only input whose source is interactive arms it; RPC or extension text cannot. The flag is consumed by the next run whether or not that run starts a plan, and it is independent of ultra mode. PI_SUBAGENT_ULTRA_KEYWORD=off disables the trigger.

Completion notices

When a run started by ultra reaches a terminal state, the extension sends a pi-subagent-ultra-done message with the run’s status and the bounded consolidated answer — the journal output of the last succeeded step, within its 50 KiB output budget — as a message that may start a model turn. A run with no succeeded step reports its status and error instead of partial output. This is the scoped exception to pull-based results: subagent_async and workflow starts still never start an automatic model turn. PI_SUBAGENT_ULTRA_NOTIFY=off restores pure pull for ultra runs; PI_SUBAGENT_ULTRA=off removes notices with the rest of the layer.

Switches

All five variables are read when the extension loads; an invalid value falls back to its default and the session shows a warning at start.

  • PI_SUBAGENT_ULTRA=on|off (default on): off removes the whole layer — the ultra tool, /ultra, guidance injection, the keyword trigger, and completion notices.
  • PI_SUBAGENT_ULTRACODE=on|off (default off): the session’s starting ultra mode; /ultra on|off overrides it.
  • PI_SUBAGENT_ULTRA_GUIDELINE=small|medium|large|unrestricted (default medium): advice only — aim for fewer than 5 / 10 / 50 children, or no child-count advice. Injected into the guidance and shown at start, never enforced.
  • PI_SUBAGENT_ULTRA_KEYWORD=on|off (default on): the ultracode trigger.
  • PI_SUBAGENT_ULTRA_NOTIFY=on|off (default on): completion notices for ultra runs.

Bounds

The hard caps are the workflow engine’s and unchanged: 64 steps per plan, 32 items per each-step (PI_SUBAGENT_WORKFLOW_MAX_ITEMS, valid 1–256), 256 expanded children per run, and at most min(PI_SUBAGENT_MAX_WORKERS − 1, 4) concurrent children of a run. The size guideline is advice, not a cap. Children of an ultra run — like every child — are started with --exclude-tools subagent*,workflow,ultra, so they cannot dispatch further agents, workflows, or ultra runs.

Human inspection

/subagents
/subagents job_0001
/subagents cancel job_0001

The footer shows the number of active jobs. In the TUI, /subagents opens a live dashboard with active jobs first. /subagents job_0001 selects that job directly; /subagents cancel job_0001 remains a noninteractive cancellation shortcut. Outside the TUI, list and detail commands retain their text output.

Dashboard controls:

  • up/down or j/k: select a job; left/right or h/l: select a task or workflow step.
  • Enter: expand or collapse the selected task's brief, activity, and output.
  • f: switch between all jobs and active jobs only.
  • c, then y: confirm cancellation of an active job; n or Esc abandons the confirmation.
  • Esc: close the dashboard.

The selected task shows its status, elapsed time, recent tool and assistant activity, bounded output, errors, model, and usage. The default synchronous subagent view is also compact: each agent reports its current status and latest activity, with full task and output details available through tool expansion (Ctrl+O).

Scheduling and admission

Synchronous and asynchronous work share one FIFO scheduler. At most sixteen 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 sixteen 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; workflow steps additionally use skipped.

  • 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. Each task also retains its 20 most recent display-safe activity summaries, capped at 512 bytes each. Live message updates refresh an open dashboard without appending a session entry per message; the latest bounded activity is persisted at job and task transitions. 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*,workflow,ultra, 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.

S
Description
No description provided
Readme
788 KiB
0 Stars 1 Watchers 0 Forks
Languages
TypeScript 88.9%
HTML 8.4%
TLA 2.7%