Task-first delegation for Pi. A parent session starts a fresh Pi child over the public RPC protocol, optionally joins it, and keeps working while it runs.
Children run as real pi --mode rpc processes. By default they start without ambient extensions, MCP, or a saved conversation. A review can use built-in read tools without loading the parent's tool stack.
pi install npm:@nijaru/pi-subagentsRequires Pi 1.3.0+ from a Node/npm installation (with the pi CLI) and Node.js 22.19+. Standalone Pi binaries are not supported. Restart Pi or use /reload.
Use subagent to start, inspect, or collect a task:
| Command | Purpose |
|---|---|
run |
Start a child and join it for up to joinTimeoutMs (60 seconds by default). If the join expires, the child continues in the background. |
spawn |
Start a child and return its handle immediately. |
wait |
Join one or more children. Wakes when any selected child finishes. |
status |
Inspect one child or list retained children. Does not consume results. |
stop |
Cancel a child and join its cleanup. |
Every child gets a short session-scoped handle (sa-<n>). wait, status, stop, and steer accept the handle or the full UUID. Optional label on run/spawn gives the task a name in reports and the UI: at most 80 characters, nonblank, on one line. Labels may repeat; they are not control identities.
{"command":"run","label":"parser review","prompt":"Review the parser changes. Report concrete regressions with file/line and evidence. Do not edit files.","tools":["read"]}{"command":"spawn","prompt":"Implement the parser regression test. Own only tests/parser.test.ts and run it.","tools":["read","edit","bash"],"persist":true}
{"command":"wait","ids":["sa-4821"]}run is the synchronous convenience: it starts and joins. spawn is the background form. A run whose join expires returns a running handle; it does not stop the child. Cancelling a run call cancels its child and joins cleanup, even beyond the join budget; cancelling a wait leaves children running.
The tool requests strict JSON-schema argument sampling when the host/provider supports it, including OpenAI and Codex Responses. Other backends can use ordinary tool calls. The advertised schema describes types and enums; the extension enforces resource limits and command-specific requirements before any launch or join, regardless of provider. This does not constrain the child’s final answer to a JSON schema.
Task prompts are wrapped in a Task: envelope and steering messages in a Steering instruction: envelope before they reach RPC. This prevents RPC from interpreting a leading /command, /skill:..., or /template as a child command. The task content itself is otherwise unchanged.
By default, an unread completion requests a continuation once: at the next successful active boundary, or by starting a turn if the TUI or RPC parent is idle. Completions that arrive together share a notice. Use wake: false on spawn or run for manual collection. Print mode does not stay alive waiting for children.
Notices list handles, not reports. Use wait to collect reports. run, wait, and stop collect terminal reports they return; status does not. Collected reports can be cleared or evicted. If a notice is dropped, status and /subagents can still find the result.
/subagents disarm [id] revokes pending wakes without stopping children. An abort or final failure disarms wakes; a successful retry preserves them. Pi does not report Escape pressed after the session is already idle, so use disarm in that case. It cannot recall a turn that already started.
/subagents lists retained children and unread results. /subagents clear drops completed, read handles.
| Budget | Default | Scope |
|---|---|---|
startupTimeoutMs |
30s (PI_SUBAGENT_STARTUP_TIMEOUT_MS) |
RPC process, model selection, tool probe, and readiness |
executionTimeoutMs |
Off; PI_SUBAGENT_TIMEOUT_MS opts in |
Task preflight and model/tool work, starting when the task is submitted |
joinTimeoutMs |
60s (PI_SUBAGENT_FOREGROUND_MS) |
How long one run blocks; at most 10m |
timeoutMs |
5m | How long one wait joins; never changes a child deadline |
Execution deadlines are off by default. Set executionTimeoutMs for a task-specific cutoff, or PI_SUBAGENT_TIMEOUT_MS for an opt-in global default; explicit arguments take precedence. Configured limits must be positive integer milliseconds, at most two hours. Invalid execution-limit environment values fail before task submission; unset the variable to disable that default. Without a limit, a child can keep running, spending, and occupying its admission slot until it finishes, is stopped, or its parent shuts down. Pi/provider request, connection, idle, and retry limits still apply.
joinTimeoutMs is a foreground join budget, not an execution deadline. It is capped at 10 minutes; an out-of-range PI_SUBAGENT_FOREGROUND_MS value falls back to the 60-second default.
status exposes lastActivityAt (parent-observed Unix milliseconds) and, while work is active, activity (model, thinking, text, tool, retry, or compaction) and currentTool (one observed tool-call name; calls can overlap). Model/token, tool, retry, and compaction lifecycle events refresh the timestamp, including thinking before visible text. retry means observed Pi retry backoff, not hidden provider-internal retries; compaction means observed summarization work. Metadata contains no reasoning text, tool arguments, or tool results. Current activity clears when execution stops; the last timestamp survives failure and cleanup. Successful reports omit activity timestamps; running and failed reports retain them. These are observations, not stall detection: a quiet tool or provider can still be working.
Interrupted execution also retains interruption: the observed activity, an activeToolCount of calls with a start but no observed end, and one currentTool name when available. This snapshot is frozen before cleanup; it contains no arguments or results. A start event does not prove a tool executed, and a missing end does not prove its effects failed. Reports warn to reconcile workspace/external state before retrying when this count is nonzero. The count and sampled name are not a complete side-effect ledger. Batch metadata is bounded too: details may omit a session path with omittedFields: ["sessionFile"], never return a truncated resume target. Inspect that child alone with status to retrieve it.
Every armed phase exposes its effective deadline: { phase, startedAt, expiresAt }, with Unix millisecond timestamps after defaults and environment settings are resolved. Startup protection and its metadata clear when a task is submitted without an execution limit. An explicitly configured execution deadline—or a failed-startup deadline—remains in terminal details; running and failed text reports show it too. Activity never extends the cutoff. The library does not automatically retry, extend the budget, or send a wrap-up prompt: queued steering cannot interrupt a long model request or tool call.
At startup/execution expiry the child is stopped and its result retains bounded visible assistant text across messages, including unfinished text. Completed text blocks replace their interim deltas even if the whole assistant message never finishes. Successful results retain completed assistant answers newest-first, including answers before and after steering or follow-ups. Earlier answers follow [Earlier completed answer] separators; tool-use narration is excluded. A later correction gets the first share of the byte budget instead of being crowded out by an older answer. Earlier answers can still contain additional findings; a follow-up is not necessarily a self-contained replacement. Failed/interrupted history remains chronological. Both views retain bounded prefixes with explicit truncation metadata. Join/wait expiry leaves the child running. errorKind distinguishes primary task causes such as startup, provider, protocol, deadline, and cancelled; cleanup uncertainty is separate under cleanup.status and cleanup.error; timeoutPhase names the expired deadline. Reported runtime excludes process-tree cleanup; cleanupMs records the excluded portion.
- Public RPC boundary. The child is spawned as
pi --mode rpc; the parent speaks only the documented JSONL protocol. Nojiti, no SDK bootstrap, and no private Pi module imports. - Startup. One deadline covers any crash guard, RPC setup, model selection, and tool readiness. The parent rejects known unsupported explicit effort before spawning and verifies the effective model and effort in the child. Only configured children need the tool probe; the probe checks exact tools and blocks unselected nested tool calls.
- Task preflight. Pi can compact saved history and run extension hooks before acknowledging a task prompt. This work uses the optional execution deadline, not a separate 30-second control-acknowledgment cutoff.
- Tool setup. Built-in read-only and reasoning-only tasks skip extension and MCP discovery. Mutation or custom tools,
fullConfig: true, andtrustProject: trueload the ordinary configuration so write-policy hooks still run. Model settings and applicable instruction files remain available on the lean path. - Cleanup. POSIX children run in detached process groups. Built-in Bash/Edit/Write, a saved or resumed session, or full configuration require a crash guard before task submission. Ordinary read-only or reasoning-only runs skip that helper. The parent still stops and cleans up every managed child on ordinary cancellation, shutdown, or deadline expiry. Unconfirmed cleanup keeps its admission slot.
- Advanced: steering.
steerqueues an instruction after the current assistant turn and tool calls. An interrupted acknowledgment does not mean the instruction was rejected; do not resend blindly. - Advanced: recovery. Opt in with
persist: trueif a saved conversation will help recovery. Saved sessions under~/.pi/agent/subagents/sessions/can include sensitive data.resumeaccepts a stopped child handle or a saved session path in its original workspace. It does not inherit the old model, tools, or trust options. A saved conversation is not rollback: reconcile mutations before resuming. - Trust. RPC mode cannot show Pi's project-trust prompt. Project-local resources are skipped unless a saved decision applies or the call sets
trustProject: true, which passes--approveto the child. Parent permission state is not inherited.
Children inherit the parent process environment, including credentials and tool configuration. Parent session-identity variables are removed and child identity is set explicitly. This is ordinary subprocess inheritance, not credential filtering.
The child is a full Pi process, so extensions and a child with shell access can produce effects outside the managed process group. Tool allowlists and subprocesses are not sandboxes.
Persisted and resumed sessions have an exclusive, cooperative <sessionFile>.subagent-lock held from before launch through cleanup. Competing subagent parents reject contention rather than queueing. These locks do not protect against an ordinary Pi process opening the same file; do not open a session elsewhere while a child owns it.
Normal completion, cancellation, and failed startup release ownership only after confirmed cleanup; leader exit alone is insufficient. A hard parent crash or unconfirmed cleanup leaves the lock in place. Confirmation covers the managed root group and captured descendants, not all possible external effects. If the leader exits before its descendant tree can be observed, cleanup is unconfirmed rather than assumed safe. Locks never expire automatically: verify that the old child has stopped before manually removing an orphaned lock. The lock records the parent PID and child run ID. This conservative recovery avoids allowing two writers while an old child is still alive.
Terminal reports expose cleanup.status: confirmed or unconfirmed. Unconfirmed cleanup retains the admission slot and any session lease, even after the report is collected. Such handles cannot be resumed, cleared, or evicted in that parent session. state.outcome always describes the task, independently of cleanup. A completed task remains completed and keeps its answer; cleanup does not replace the task’s diagnostics. Unconfirmed cleanup still marks the tool result as an error, including inspection and stop results. Do not rerun completed work solely because of cleanup. Reconcile process and workspace state before recovery; a new parent session clears handle reservations, not orphaned lock files.
Defaults are the parent's active built-in read, grep, find, and ls tools. Request Bash/Edit/Write or custom tools explicitly; tools: [] makes a reasoning-only child.
Explicit tools must be active or callable in the parent. Lean children use the CLI built-in tool selection and have no extension dispatcher. Configured children also deny and verify unselected tools, including nested calls. Neither path is a sandbox. Children cannot delegate again.
model is an exact provider/model-id; otherwise the parent's model is inherited. thinking selects a reasoning effort supported by that model. An explicit unsupported level fails before prompting. A different model uses its own Pi defaults when thinking is omitted.
cwd defaults to the parent cwd, except handle-based resume uses the child's original cwd. A fresh child starts a new conversation; the prompt must carry scope, evidence, constraints, expected output, and checks. Parent history, runtime-only tools, and permission-hook state are not copied.
| Resource | Limit |
|---|---|
| Admission slots | 4 per parent session, including cleanup-unconfirmed children; excess starts are rejected |
| Retained handles | 32; oldest completed, read handles are evicted first; unread results are never evicted |
| Startup | 30 seconds by default, up to 5 minutes |
| Execution deadline | Off by default; optional configured cutoff up to 2 hours |
| One wait | 5 minutes by default, at most 10 |
| Task prompt | 100 KiB |
| Tool response and details | 50 KiB each |
| Child stderr | 50 KiB, keeping both ends |
Child reports remain bounded in memory; they are not spilled to disk. Text, structured results, and renderer details derive from the same budgeted report view. outputTruncation records shortened UTF-8 output. Launch metadata omitted for space is absent and listed in omittedFields, not replaced with empty values. Session paths are whole or absent; inspect one child with status for an omitted path. A persisted session is separate from that report.
Child usage includes assistant calls, completed compaction summaries, and usage reported by child tools. Interrupted calls retain the latest reported cumulative usage; updates are not added repeatedly. Providers that report usage only at finalization can leave interrupted usage unknown.
Usage is available in each child report. It is not carried into the parent's tool-result usage or session ledger.
Children stop on orderly quit, reload, or session replacement. POSIX crash guards also stop protected process groups on hard parent death. Lean in-memory read-only runs do not have that extra guarantee, and Windows only has best-effort process-tree shutdown.
bun install --frozen-lockfile
bun run checkPi loads the TypeScript extension directly; there is no build step. Checks use a fake RPC child for deterministic lifecycle tests and real Pi parent/child processes with local mock Chat Completions, Responses, and Codex Responses endpoints. Integration tests cover strict arguments, optional-null normalization, and a backend without strict-tool support. No live model calls are needed.
RPC preserves the normal Pi CLI runtime while supporting steering and session continuation. Print/JSON mode is simpler for one-shot jobs but cannot steer a running task; an SDK worker would require a separate bootstrap, and an in-process session would share the parent's failure domain. Terminal attachment and independent background survival are outside this tool's scope.
0.0.x is pre-release: tool schema and result shape are not promised across patch releases.
- 0.0.22:
- Request strict tool arguments on supported backends, including Codex/OpenAI, while enforcing resource and command limits for every provider.
- Add optional task labels and keep successful answers newest-first so steering corrections get priority within bounded reports.
- Preserve the primary task outcome independently of cleanup uncertainty, and clarify recovery without blindly rerunning completed work.
- Migration: report ordering and cleanup fields changed; see Migration.
- 0.0.21: simplify snapshot copying and host API integration without changing tool behavior or the Pi 1.3 minimum.
- 0.0.20:
- Execution deadlines are off by default. Set
executionTimeoutMsorPI_SUBAGENT_TIMEOUT_MSto opt in; task preflight follows the same policy. Startup protection and join budgets remain separate. - Resume a saved conversation by handle or path, and retain completed answers across steering. Model and effort are explicitly established and verified before task submission.
- Child execution has one lifecycle owner. Cleanup uncertainty retains admission and session ownership without hiding the task outcome; RPC queues and public reports are bounded.
- Migration: remove
notify,stdout, and syntheticstate.exitCodeusage. Result omissions and cleanup disposition are explicit; see Migration.
- Execution deadlines are off by default. Set
- 0.0.19:
- Migration: children now save recoverable conversations by default, including prompts and tool results; use
persist: falsefor ephemeral work. - Recovery: results expose effective deadlines and interruption observations. Failed reports retain earlier visible work and authoritative completed text blocks, with truthful Unicode/truncation accounting. Activity distinguishes Pi retry backoff and compaction. Oversized batch details may explicitly omit session paths; inspect an individual child with
statusfor its full path. - Compatibility: support Pi 1.5 schemas and host keybindings while retaining Pi 1.3 support; preserve provider-billed usage totals and provenance.
- Hard execution limits are unchanged. No automatic wrap-up, retry, or budget extension is added.
- Migration: children now save recoverable conversations by default, including prompts and tool results; use
- 0.0.13: replace the custom SDK child bootstrap with Pi's public RPC protocol. Add
steer, persisted/resumable child sessions (persist,resume), and opt-intrustProject. Removejiti, private Pi imports, and the custom fd-3 child protocol. Add an active-tool probe so missing tools fail before prompting. Wrap prompts and steering to prevent RPC command expansion, exclude all unselected tools from nested calls, preserve orderly child shutdown hooks, ignore oversizedagent_endhistory, retain the latest partial report, and expose persisted session paths in model-facing text. Notices announce handles without consuming reports. Persisted sessions have exclusive ownership, startup operations share one deadline, and children inherit the ordinary process environment.
- Read-only children with built-in tools now skip ambient extensions and MCP. Mutation and custom tools still load configured hooks. Use
fullConfig: truefor a review that needs configured extensions. Child conversations are now in memory by default; setpersist: trueto save one. - Child usage remains in reports; it is no longer copied into the parent ledger. Unread handles are available via
statusand/subagents, not unrelated tool results. - Background child completions can now resume an idle live parent by default. Set
wake: falseto preserve manual collection without an automatic continuation.
- Successful
outputis now newest-first, with[Earlier completed answer]separators. Do not assume the first answer is the earliest, or that a follow-up repeats all earlier findings. Failed/interrupted history remains chronological. - Read the primary task outcome from
state.outcomeand resource disposition fromcleanup.status.cleanup.taskOutcomeanderrorKind: "cleanup"are removed. Unconfirmed cleanup remains a tool error and retains admission/session ownership, but no longer turns a completed task into a failed one. Do not blindly rerun completed work. - Parameter schemas now express portable structural types for strict-tool backends; resource limits and cross-field requirements remain enforced at runtime. Consumers that previously used the exported schema alone for full validation must also use
validateCommand()fromextensions/pi-subagents/params.ts.
-
Execution deadlines are now opt-in. Omit
executionTimeoutMsand leavePI_SUBAGENT_TIMEOUT_MSunset for no execution cutoff. Valid environment configuration still provides a global default; explicit arguments override it. Invalid execution-limit environment values now fail instead of falling back silently. Startup, foreground handoff, wait, and cleanup budgets are unchanged. -
Initial task preflight no longer has a separate 30-second RPC acknowledgment cutoff; optional execution deadlines govern preflight as well as model/tool work.
-
Result consumers must stop reading synthetic
state.exitCodeand unusedstdout; usestate.outcome,errorKind, andstderr. Optionalcleanupdescribes resource disposition separately from the task outcome. -
Budget-omitted
prompt,cwd, andtoolsare now absent rather than empty placeholders.omittedFieldsidentifies omitted launch metadata or session paths. Model text and structured results use the same report excerpt. -
Cleanup-unconfirmed children retain admission and session ownership even after collection. They are not resumable or eligible for clearing/eviction in that parent session.
-
Remove
notifyfrom calls. All unread completions now use active-boundary announcements with inbox fallback, without waking idle parents. Notices still requirewaitto collect reports. -
Successful
outputmay contain several completed answers from one execution, separated by blank lines, rather than only the last answer after steering. It remains bounded; inspectoutputTruncationfor loss. -
resumeaccepts a retainedsa-Nhandle or an explicit session path. Handle resume creates a new handle in the original workspace by default and leaves the earlier report readable. Explicitpersist(includingfalse) cannot be combined withresume.
PI_SUBAGENT_RUNNER,PI_SUBAGENT_BIN, andPI_BINare no longer used. The child requires the installed Pi CLI.- Children now use a real Pi RPC process. Project trust follows RPC rules; pass
trustProject: truefor a one-shot--approveor save a trust decision. - Child sessions are saved by default;
persist: falseopts out, andresume: "<sessionFile>"continues one. Existing SDK child handles do not migrate. steeris available only while a child is running. After completion, resume its persisted session to continue the conversation.- Tool availability is checked by a public extension probe before the prompt; a missing built-in or MCP tool exhausts startup without starting model work.
- Completion notices no longer embed reports or implicitly acknowledge them. Retrieve reports with
wait;statusremains observational. PI_SUBAGENT_PASSTHROUGH_ENVis retired. Child processes inherit ordinary environment configuration; session-identity variables are replaced, not copied.