@cr1ms0n/pi-subagent
Community fork of Luke Parke's pi-subagent with Jev model/tool routing and verified Pi child capabilities
Package details
Install @cr1ms0n/pi-subagent from npm and Pi will load the resources declared by the package manifest.
$ pi install npm:@cr1ms0n/pi-subagent- Package
@cr1ms0n/pi-subagent- Version
0.9.0- Published
- Sep 21, 2026
- Downloads
- 1,356/mo · 712/wk
- Author
- cr1ms0n
- License
- MIT
- Types
- extension, skill
- Size
- 739.2 KB
- Dependencies
- 0 dependencies · 4 peers
Pi manifest JSON
{
"skills": [
"./skills"
],
"extensions": [
"./extensions/subagent.ts"
]
}Security note
Pi packages can execute code and influence agent behavior. Review the source before installing third-party packages.
README
@cr1ms0n/pi-subagent
This is an independent community fork of @parke.dev/pi-subagent 0.8.0, originally by Luke Parke. It is not an official upstream release. The original MIT license and copyright are preserved. Upstream source: LukasParke/pi-extensions.
This fork replaces the upstream fixed model route with mandatory Jev routing. New subagent dispatches require a jevRouting block in ~/.pi/subagent.json (a dedicated candidate-model list plus the name of the environment variable holding your TypeSafe credential), and the TUI shows the selected execution model and tools.
Production-grade isolated subagents for Pi.
Delegate research, parallel exploration, and clean-context review to child Pi processes. Named agent personas, Jev-selected execution models and individual tools, cancellable background runs with completion notifications and a live widget, mid-run steering, graceful budget wrap-ups, bounded same-model retry, a stall watchdog, session resume and context forking, worktree isolation with a diff/apply/discard loop, capability profiles, a root/subagent/combined cost ledger, and a TUI inspector.
Install
Pi packages install from npm, git, or a local path:
# npm (scoped; surfaces on the pi.dev gallery via the pi-package keyword)
# Note: unscoped "pi-subagent" is rejected by npm as too similar to "pi-sub-agent".
pi install npm:@cr1ms0n/pi-subagent@0.8.1
# latest npm
pi install npm:@cr1ms0n/pi-subagent
# npm is the supported package install path from the monorepo.
# For local development, install this workspace directly:
pi install /absolute/path/to/pi-extensions/packages/pi-subagent
# local checkout
pi install /absolute/path/to/pi-subagent
Then start Pi normally. The package registers:
- tool:
subagent - command:
/subagents(run inspector overlay) - command:
/subagent-cost(parent / subagent / combined usage on demand)
This fork is published manually after pack-content and offline checks — see docs/RELEASING.md.
Quick usage
// Single foreground task (default profile: general). Omit model and
// fallback_models: Jev selects the execution model from your configured list.
{ task: "Find all call sites of parseConfig and summarize patterns.", description: "Map parseConfig usage" }
// Named agent: persona prompt from .pi/agents/reviewer.md. Jev still picks the model.
{ task: "Review this diff for security issues", agent: "reviewer" }
// Parallel read-only explorers (default profile for tasks[]: explore).
{
tasks: [
{ task: "Map auth middleware flow", description: "Auth flow map" },
{ task: "List all env vars used in server/", description: "Env var inventory" }
]
}
// Parallel research with automatic fan-in: one read-only child folds all
// outputs into a single brief, delivered first.
{
tasks: [
{ task: "Audit backend error handling", description: "Backend audit" },
{ task: "Audit frontend error handling", description: "Frontend audit" }
],
synthesis: "Merge both audits into one prioritized findings list"
}
// Background run: the widget shows the selected model; expanded results include tools.
{ task: "Audit dependency licenses", async: true }
// later
{ action: "status", id: "abc123" }
{ action: "wait", id: "abc123" } // interruptible; does not cancel
{ action: "cancel", id: "abc123" }
// Collecting a background run also has its own tool, for reflexive mid-flow
// use. Identical semantics to action:"wait" (same handler underneath).
// A timeout returns a still-running notice WITHOUT cancelling or consuming
// the run, so it stays collectable.
subagent_wait { id: "abc123" }
subagent_wait { id: "abc123", timeout_ms: 30000 }
// Dry-run a spawn request: full validation, Jev selection and local preflights
// (git repo, fork session, output paths). Returns the resolved per-task plan
// (model, tools, budgets, isolation) and its selector usage without spawning.
// Selector fees apply, and a later dispatch selects again.
{ action: "plan", tasks: [{ task: "Implement feature A", profile: "general", isolation: "worktree" }] }
// Structured output: the child must end with a fenced json:result block
// matching the schema. Invalid output gets one automatic repair round;
// delivery is the clean JSON and details carry the parsed object.
{
task: "Audit the auth module",
output_schema: {
type: "object",
required: ["findings", "risk"],
properties: {
findings: { type: "array", items: { type: "string" } },
risk: { type: "string", enum: ["low", "medium", "high"] }
}
}
}
// Fork the parent conversation into the child (needs a persisted session).
// The child starts from a branched copy of everything discussed so far.
{ task: "Implement the plan we agreed on", context: "fork", profile: "general" }
// Budgets with graceful wrap-up: at the limit the child is steered to produce
// a final answer and given grace turns before any hard stop.
{ task: "Audit deps", max_turns: 15, grace_turns: 2 }
// Transient child failures retry the already selected model and tool set, up to
// max_retries. There are no emergency or fallback models.
{ task: "Research X", max_retries: 1 }
// Steer a running child mid-run instead of cancel + retry. The message is
// delivered after the current assistant turn, before the next LLM call.
{ action: "steer", id: "abc123", message: "Skip the tests directory; focus on src/" }
// Parallel runs: pass index to pick one live task.
{ action: "steer", id: "abc123", index: 1, message: "Wrap up now" }
// Resume a child session. The new invocation selects again.
{ task: "Continue from your findings and propose a fix plan", resume: "<session-id>" }
// Isolated writers
{
tasks: [
{ task: "Implement feature A", profile: "general", isolation: "worktree" },
{ task: "Implement feature B", profile: "general", isolation: "worktree" }
]
}
// Close the worktree loop after the run finishes:
{ action: "diff", id: "abc123", index: 0 } // inspect the patch
{ action: "apply", id: "abc123", index: 0 } // land as uncommitted changes in your checkout
{ action: "discard", id: "abc123", index: 1 } // drop worktree + branch
The /subagents overlay mirrors the worktree loop interactively: s steer,
a apply, x discard on the selected run.
Side questions (/btw)
/btw does this repo have a rate limiter?
/btw # prompts for the question
/btw runs a one-off read-only subagent for you, not for the model. It uses
the same policy, budget, semaphore and process-lock machinery as any run, but
delivers its answer as a custom session entry, which does not participate in
LLM context. The main agent keeps working and never sees the question or the
answer — useful for checking something mid-task without derailing the
conversation or polluting the context window.
Backends
Jev routing manages Pi-backed new dispatch only. A backend: "codex" or
backend: "claude" new task is refused before any selector or provider work,
including a backend inherited from agent frontmatter; the extension never
silently switches it to Pi. Existing Codex/Claude runs stay manageable:
status, wait, cancel, steer, diff, apply and discard all still
work. Provider diversity is not lost, because another provider's execution
model stays eligible through Pi once it is in your configured candidate list.
// Refused on new work. Use the Pi-backed path so Jev can route it.
{ task: "Summarize this module", backend: "codex", profile: "explore" }
The low-level SDK is a different contract: runTasks/runSubagent execute the
explicit TaskSpec you hand them, so embedding code can still select a backend
directly. Everything else (worktrees, process locks, depth limits, budgets,
orphan reclaim) is backend-agnostic and applies unchanged.
Capabilities differ, and unsupported combinations are refused with an
explanation rather than silently ignored: a dropped max_cost or unenforced
read-only profile would be a safety regression, not a minor degradation.
pi (default) |
codex |
claude |
|
|---|---|---|---|
max_cost |
yes | refused (reports tokens, no cost) | yes (total_cost_usd) |
| read-only profile | tool allowlist | --sandbox read-only (OS-level) |
--allowedTools |
| steering / graceful wrap-up | yes | no (no stdin channel) | no (one-shot) |
resume |
yes | yes | yes |
context:'fork', fork_resume |
yes | refused | yes |
thinking |
yes | no | no |
output_schema |
yes | yes | yes |
A budget breach on a backend without steering hard-stops instead of asking the child to wrap up. Codex's read-only sandbox is enforced by the OS, which is stronger than a tool allowlist.
Agent frontmatter backend: remains a default. New extension-managed work rejects
any effective backend other than Pi, including a native backend inherited from an agent.
Direct SDK specs retain the backend capabilities listed above.
Profiles
| Profile | Tools | Writes |
|---|---|---|
explore (parallel default) |
locally permitted read-only tools + Pi context tools | no project-file writes |
review |
same as explore | no project-file writes |
general |
Jev chooses from the full available locally permitted catalog + Pi context tools | yes for selected write-capable tools; unknown custom tools count as writable |
Jev chooses individual tool names, not a capability bundle. Candidates come
from the full available locally permitted catalog, not from the agent file's
tools defaults and not from the parent's currently active tools. An explicit
task tools list is a ceiling, and explore/review keep their read-only rule
regardless of what the selector returns. An empty selection never means "all
tools".
For the Pi backend, the context-management tools new_context,
get_context_remaining, history, and notes are added locally when the
parent exposes them, so they are never a selector question. They are
control-plane tools: they may update continuity notes or the remote context
window, but cannot modify the child checkout or run a shell command. This
exception also applies when a task supplies a narrower tool list, so Pi's
contextManagement remains usable for configured gateway models. Locally added
controls are reported in the route metadata.
The finalized tool set is passed to the child as Pi's --tools allowlist
(--no-tools for a true empty set). Pi 0.86.0 is the verified baseline for
built-in, extension and late-registered tool enforcement; a host that cannot
honor that allowlist is refused rather than silently weakened, and the extension
does not claim identical behavior on untested older releases. Before the real
task prompt is sent, the child is also asked to confirm the selected model and
the finalized tool names through a verified private startup command; if the host
cannot verify that command or the child cannot confirm both, the launch aborts
with a startup diagnostic instead of running with a broader tool set.
Parallel write-capable tasks sharing one checkout are rejected unless each uses
isolation: "worktree", distinct cwd, or explicit allow_shared_writes: true.
Configuration
Defaults can be overridden in ~/.pi/subagent.json and per-field via env vars
(env wins over file):
| Setting | Env var | Default |
|---|---|---|
maxTasksPerRun |
PI_SUBAGENT_MAX_TASKS |
8 |
maxActiveProcesses |
PI_SUBAGENT_MAX_ACTIVE |
4 |
maxQueuedTasks |
PI_SUBAGENT_MAX_QUEUED |
32 |
maxGlobalActive |
PI_SUBAGENT_MAX_GLOBAL_ACTIVE |
16 |
defaultTimeoutMs |
PI_SUBAGENT_TIMEOUT_MS |
900000 |
maxDepth |
PI_SUBAGENT_MAX_DEPTH |
2 |
killGraceMs |
PI_SUBAGENT_KILL_GRACE_MS |
3000 |
sessionDir |
PI_SUBAGENT_SESSION_DIR |
~/.pi/subagent-sessions |
worktreeDir |
PI_SUBAGENT_WORKTREE_DIR |
~/.pi/subagent-worktrees |
lockDir |
PI_SUBAGENT_LOCK_DIR |
~/.pi/subagent-locks |
worktreeRetentionDays |
PI_SUBAGENT_WORKTREE_RETENTION_DAYS |
unused (lifecycle GC) |
sessionRetentionDays |
PI_SUBAGENT_SESSION_RETENTION_DAYS |
unused (lifecycle GC) |
lockRetentionDays |
PI_SUBAGENT_LOCK_RETENTION_DAYS |
7 |
taskDefaults |
— | none |
jevRouting |
- | required for new dispatch (see below) |
graceTurns |
PI_SUBAGENT_GRACE_TURNS |
2 |
stallAfterMs |
PI_SUBAGENT_STALL_AFTER_MS |
90000 |
stallKillAfterMs |
PI_SUBAGENT_STALL_KILL_AFTER_MS |
90000 |
maxRetries |
PI_SUBAGENT_MAX_RETRIES |
1 |
widget |
PI_SUBAGENT_WIDGET |
background (off disables) |
notifications |
PI_SUBAGENT_NOTIFICATIONS |
batched (off disables) |
| (bin) | PI_SUBAGENT_BIN |
auto (process.execPath + CLI entry) |
Jev routing
New subagent dispatches are selected by Jev, TypeSafe's structured-decision API,
against a dedicated candidate list you maintain in ~/.pi/subagent.json. Fixed
routing is gone: a modelPolicy block produces a migration error, and an
explicit model or fallback_models on new work is rejected rather than
bypassing selection. Management actions (status, wait, cancel, steer,
diff, apply, discard) never call the selector and need no credential.
{
"jevRouting": {
"selectorModel": "jev-latest",
"apiKeyEnv": "TYPESAFE_API_KEY",
"timeoutMs": 15000,
"models": [
{
"model": "<provider/model-id>",
"description": "<your characteristics notes, Chinese allowed>",
"thinking": "<optional opaque Pi thinking default>"
}
]
}
}
selectorModeldefaults to the stable aliasjev-latest. Pin an exact version to control which selector version is requested. This does not guarantee deterministic choices; the extension records the version that actually answered.apiKeyEnvdefaults toTYPESAFE_API_KEY. Only the variable name lives in the file. Set the credential in your local environment; the extension reads it at request time and never writes it to config, prompts, argv, logs or results.timeoutMsdefaults to 15000 and must be an integer between 100 and 600000. It bounds one logical task selection, including all its HTTP requests and queue waits. Parallel workers each have a selection allowance, still capped by their absolute tasktimeout_msdeadline. Deferred synthesis has a separate allowance.modelsholds 1 to 255 entries, each with an exactprovider/model-idand a non-blank description. Those descriptions are what Jev matches against your task, so write them the way you would explain the model to a colleague.thinkingis optional.
Plan and background-start native usage attachments are limited to 1024 selector HTTP receipts per invocation. Larger requests fail with a request-splitting error; background work has not started at that point. Previously incurred selector tokens remain in the ledger. This bounds an atomic delivery record, not the number of tools Jev may consider within each task.
The candidate list is intersected with the models the local Pi registry reports
as available. A configured model Pi cannot resolve is not eligible, and an empty
eligible pool fails before any request. Adding a model anywhere else in Pi does
not authorize it, and legacy modelPolicy entries are never imported
automatically. An unknown jevRouting field is an error, not a silent default.
Jev receives only the current delegated task text, your model IDs and descriptions, candidate tool names and descriptions, and the permission/output requirements it needs to choose. It does not receive repository files, conversation history, full system prompts, persona text or tool parameter schemas. Task text and descriptions are user content and may contain sensitive material, so treat what you delegate as disclosure to TypeSafe.
Every new extension-managed dispatch routes through Jev: task/tasks[],
action:"plan", /btw, resume, fork, locally permitted nested dispatch and the
optional synthesis child. action:"plan" calls Jev and runs the same local
preflights, returns the resolved model/tool plan and the selector usage, and
creates no child or run entry. A later dispatch selects again; there is no cached
decision to reuse. If optional synthesis selection fails, the worker plan and its
usage stay valid and synthesis is reported as blocked with its diagnostic.
thinking is optional and is an opaque Pi thinking-level string. Common values
include off, minimal, low, medium, high, xhigh, and max, but the
package does not remap or restrict model-specific values. Pi receives the value
unchanged and decides whether the active model supports it. Resolution order is:
explicit task thinking > agent frontmatter thinking > profile
taskDefaults.<profile>.thinking > the selected candidate's optional thinking
the parent session's thinking level. Jev never chooses a thinking level.
The extension re-reads jevRouting on each dispatch and injects the current
routing guidance into the parent prompt, so configuration edits reach the next
decision without a code change. Missing or invalid jevRouting, or a missing
credential environment variable, rejects new dispatch and plan with a remedy;
management stays available.
The mandatory routing above is the Extension dispatch contract. The stable SDK
exports (runTasks and runSubagent) are trusted low-level library APIs: they
execute the explicit TaskSpec you pass and perform no implicit routing, config
discovery or network call. Library callers own model and tool choice, and must not
read these SDK calls as Jev enforcement.
Named agent files
Define reusable subagent personas as markdown files, discovered from the same conventional roots skills use (higher root wins name conflicts):
| Priority | Location | Scope |
|---|---|---|
| 1 | .pi/agents/<name>.md |
project (authoritative) |
| 2 | .agents/agents/<name>.md |
shared cross-tool workspace |
| 3 | $PI_CODING_AGENT_DIR/agents/<name>.md (default ~/.pi/agent/agents/) |
global |
The markdown body becomes the child's appended system prompt; frontmatter supplies defaults using the same snake_case names as the tool parameters:
---
description: Security-focused code reviewer
# Legacy model/fallback fields are ignored; Jev routing owns model/tool choice.
thinking: high
profile: review
max_turns: 20
spawns: false # or "*", "scout", "[reviewer, scout]"
---
You are a security auditor. Review code for injection flaws, auth issues,
and sensitive data exposure. Report findings with file:line evidence and
severity ratings.
@include shared/review-checklist.md
Agent files may also pin a structured contract with
output_schema: {"type": "object", …} (single-line inline JSON) or
output_schema: @contract.json (path relative to the agent file).
spawns: controls which agents a child of this persona may spawn:
false disables further nesting (no tool registered in that child),
"*" (or omit) is unrestricted, and a comma/bracket list is an allowlist
(agentless tasks are rejected under an allowlist). The policy is passed to
the child via PI_SUBAGENT_SPAWNS and enforced on each subsequent spawn.
Body lines that consist solely of @include relative/path.md expand that
file one level deep (relative to the agent file, same 64KB/symlink guards
as @contract.json). Missing or rejected includes leave the line verbatim;
includes do not recurse.
Invoke with { task: "…", agent: "reviewer" }. The agent file supplies
persona, capability, thinking and budget defaults only: model and tool selection
stay with Jev routing, and a legacy model/fallback_models in frontmatter is
ignored. An explicit system_prompt appends after the persona body.
Profiles still enforce capability: profile: review filters candidates to read-only
tools. Legacy agent tools defaults are ignored; an explicit task tools list
requesting write tools under review fails closed. The agent catalog is advertised in the tool's
system-prompt guidelines (session start) and in bare status output (live),
and file changes are picked up within seconds — no restart needed.
Per-profile task defaults
taskDefaults in ~/.pi/subagent.json remains available for non-model
fields such as thinking, budgets, and retry counts. Its legacy model and
fallbackModels fields are ignored; model and tool routing belong only to
jevRouting. A profile thinking value overrides the selected candidate's
optional thinking default. Invalid fields are dropped field-by-field.
Notes on behavior:
timeout_msis the absolute task deadline: local preflight, Jev selection, setup, queue time and runtime all count against it, and selection cannot reset it. Timed-out tasks reportstate: "timeout"withtimeoutPhase: "queued"|"starting"|"running"so agents can retry capacity issues without confusing them for task failures.- Budget stops (
max_turns,max_cost) trigger a graceful wrap-up: the child is steered to produce its final answer NOW and allowedgraceTurnsmore turns before SIGTERM. Results end aspartialwithwrappedUp: truewhen the child concluded in time.graceTurns: 0restores immediate stops. - A stall watchdog flags children with no protocol activity for
stallAfterMs(a liveness probe distinguishes quiet-but-thinking from dead), then kills afterstallKillAfterMsmore silence — feeding automatic retry instead of burning the whole timeout. - Transient failures retry automatically (queue timeouts, stalls, spawn
errors, provider errors) up to
maxRetriesextra attempts on the already selected model and tool set. There are no emergency or fallback models, and a quality or budget failure never reselects. Usage accumulates across attempts; results recordattempts. Task-quality failures (nonzero exit with complete protocol, cancellations, budget stops, running timeouts) never retry. context: "fork"starts a single child from a real branched copy of the parent conversation (--forkon the parent's session file). It requires a persisted parent session, cannot combine withresume, and is rejected for parallel fanout (context duplication × N is a cost bug, not a feature).- Structured output (
output_schema): the contract is appended to the child's system prompt; the final message must end with a fencedjson:resultblock. Validation runs parent-side against a dependency-free JSON-Schema subset (type/properties/required/items/enum/const — unknown keywords are ignored, never rejected). Invalid output triggers one steer-based repair round; still-invalid results endpartialwithstructuredErrorset and the raw text delivered — paid work is never discarded. Validated parallel results feed thesynthesischild as clean JSON instead of prose. - Arg repair: double-encoded task text (literal
\n/\"escapes from LLM re-encoding) is conservatively de-mangled once at validation time. Identifier fields and paths are never touched. Protocol streams truncated after useful assistant output also end aspartial. - Aborting a
waitreturns immediately without cancelling the background run. - Child processes are launched via the same Node runtime + CLI entry as the
parent when possible (
PI_SUBAGENT_BINoverrides). Barepion PATH is only a logged last resort. - Direct resume is exclusive across processes via durable locks under
lockDir. Lost runs block resume until startup orphan reconciliation kills (or confirms dead) the recorded child process group. maxGlobalActivebounds concurrent children across every Pi parent process on the machine (in addition to the per-session semaphore).- Nested children at the depth ceiling do not re-register the subagent tool; only top-level parents run maintenance/orphan reclaim/worktree GC.
- Preserved worktrees live under
worktreeDir(durable, not/tmp) and are garbage-collected on startup by lifecycle, not wall-clock retention: once a run is over (not live, past a 1h concurrency race guard), the worktree's unique work is archived as one applyable patch under<repo-container>/_patches/and the directory is reclaimed immediately. Branches holding commits that exist on no other ref are never deleted.diff/apply/discardtransparently fall back to the archived patch when the directory is already gone. Live runs are never swept: the current session's live worktrees plus any worktree recorded on a running run record (concurrent Pi processes) are shielded machine-wide. - Startup GC sweeps every repo container under
worktreeDir, not just the current checkout's, so repos you stop visiting are still reclaimed. A container whose base repo no longer exists is kept and reported, never deleted — its worktrees' object stores lived inside the deleted repo, so unique work cannot be distinguished from a pristine checkout, let alone archived. Empty containers (no worktrees, no archived patches) are removed. - Child session transcripts are likewise distilled on lifecycle: when a run is
over and nothing on the parent branch references its session, the transcript
is reduced to a small
.digest.json(task, final output, model, usage, turn/tool/error counts) and the raw.jsonlis deleted. Resume needs the transcript, so anything referenced or busy machine-wide is kept. keep_background: trueon a task keeps processes the child intentionally backgrounded (e.g. dev servers) alive after a clean exit.include_wip: true(withisolation: "worktree") seeds the worktree with the parent checkout's uncommitted changes so the child sees your dirty baseline.diff/applysubtract that baseline when clean, else report the combined delta with an explicit[includes parent WIP]warning.
Using the runner as a library
Import the stable public SDK from the package root or the explicit /sdk
subpath — do not reach into src/* internals (those paths are not part of the
supported contract):
import {
runTasks,
runSubagent,
ChildRunner,
WorktreeManager,
Semaphore,
ProcessLockManager,
addUsage,
normalizeUsage,
emptyUsage,
type TaskSpec,
type TaskResult,
type RunState,
type UsageStats,
} from "@cr1ms0n/pi-subagent/sdk";
The package root is an alias for the same SDK:
import { runTasks } from "@cr1ms0n/pi-subagent".
The Extension dispatch path routes every new task through Jev, so callers never pass a model to it. The low-level SDK is the opposite contract: it is explicit-spec and performs no implicit routing, config discovery or network call, so embedding code supplies the model (and tool list) it resolved itself. This placeholder is illustrative only and configures nothing:
const task: TaskSpec = {
task: "Audit src/ for unsafe parsing",
profile: "explore",
model: "<provider/model-id resolved by your embedding code>",
timeoutMs: 10 * 60_000,
};
Prefer runTasks() for multi-task / worktree orchestration (same path the
extension and pi-workflows use). runSubagent() runs a single child process
directly without the extension host, but durable coordination is opt-in.
Pass both locks (a ProcessLockManager) and a stable runId if you want
global concurrency slots and orphan reclaim to see the child. Without those
options no durable run record is written, so a parent restart cannot reclassify
the process and nested children vanish from reconcile. There is intentionally
no implicit default lock manager — embedding code that needs durability must
construct and share one.
The Pi extension entry is unchanged: package pi.extensions still points at
./extensions/subagent.ts.
Design invariants
- A run belongs to one parent session and cannot update another session.
- Per-session + machine-wide process caps and nesting depth limits prevent process storms.
- Cancellation prevents queued tasks from spawning.
- Direct resume of a child session is exclusive across processes via durable locks.
- Tool responses are capped to ~50KB/2000 lines; full output lives in
artifacts and
~/.pi/subagent-sessions. - Status is compact; wait is the one-shot deliverable.
- On parent session shutdown, live children are aborted and awaited briefly.
- On parent (re)start, orphan process groups recorded under
lockDirare reaped before any resume is allowed for the matching child session. - Provider-reported usage is counted once per root message and terminal child run; selector usage is a separate category counted once per selector request ID.
- Protocol completion prefers
agent_settled(falls back to non-retryingagent_end). - Jev selection precedes every new extension-managed launch, and the selected tool subset is enforced by Pi's CLI allowlist; empty selection never means all tools.
Layout
src/
index.ts # stable public SDK entry (@cr1ms0n/pi-subagent)
extension.ts # Pi wiring only
schema.ts # request schemas (subagent + subagent_wait)
btw.ts # /btw side questions (model-hidden entries)
backend.ts # backend adapter seam + capability gate
backends/ # pi | codex | claude adapters (invocation + parser)
policy.ts # profiles, normalization, write guards, agent resolution
routing-types.ts # selector DTOs, decisions, receipts, local resource limits
routing-policy.ts# strict jevRouting parser, candidate list, routing guidance
jev-router.ts # injectable Jev transport, response validation, receipts
dispatch-preflight.ts # bounded read-only checks before selector work
startup-check.ts / child-preflight.ts # private child model/tool verification
dispatch-routing.ts # prepare -> select -> finalize for one or many tasks
agents.ts # named agent files (.pi/agents/, .agents/agents/, global)
launch.ts # resolve child pi via execPath / PI_SUBAGENT_BIN
process-lock.ts # durable session locks, global slots, orphan records
worktree.ts # git worktree isolation + diff/apply/discard
orchestrator.ts # multi-task execution, worktree prep, bounded same-model retry
runner.ts # child process lifecycle, RPC channel, steering,
# graceful budget wrap-up, stall watchdog
protocol.ts # Pi RPC/JSON event parser (agent_settled-aware)
semaphore.ts # per-session concurrency limit
registry.ts # session-scoped run state + durable resume locks
persistence.ts # parent-session event folding
usage.ts # root/subagent/combined usage ledger
output.ts # exact global output caps
notifications.ts # batched background-run completion notifications
format.ts / ui.ts# renderers, ambient widget, /subagents overlay
Develop
This checkout has no scripts, no devDependencies, no tsconfig.json and no
test runner, so npm install, npm run typecheck, npm test and
npm run pack:check are not defined here. The checks that do run locally are
offline:
npm pack --dry-run --json
That verifies the publishable file list matches package.json files and leaks
no backup, transcript, session data, research output or generated bundle. Source
changes are parse/type-strip checked by running the global Pi install's bundled
esbuild over every src/ and extensions/ file; that catches malformed
TypeScript only, not type errors or peer API mismatches. Provider-free fixtures
and an injected fake selector transport, run with the already installed Pi runtime
rather than a repository test framework, exercise routing behavior without any
model call. See .trellis/spec/backend/quality-guidelines.md
for the exact commands and what each check does and does not prove.
Cost accounting
status, /subagent-cost, and the /subagents overlay header show separate
root, subagent, and combined totals based on provider-reported
usage. On Pi builds after v0.80.10, delivered runs also report their total
usage natively on the tool result
(pi#6671), so Pi's own
footer, /session, and RPC totals include subagent spend — exactly once per
run; older Pi hosts ignore the field. Nested usage reported by a child's tool
results (e.g. grandchild subagents) folds into the run's totals and budgets.
The extension footer stays terse (running/ready counts only). Delivery and
replay do not double count runs. See
docs/COST-ACCOUNTING.md.
Jev selection is billed separately from execution. TypeSafe reports tokens, not
currency, so the ledger shows routing tokens as their own category, counts each
selector request once by its request ID (including plan and pre-spawn failures),
and marks routing cost as unreported rather than free. Numeric dollar totals
exclude unreported routing spend, and max_cost caps provider-reported execution
cost only; it does not cap TypeSafe charges. Route metadata (selected model,
selected tools, locally added controls, selector version, confidence, outcome,
latency) travels with the run alongside usage.
Roadmap
Planned work — agent spawn policies, dry-run validation, engine hardening, live transcripts — lives in docs/ROADMAP.md (rationale and design sketches) and docs/PLAN.md (execution contract: work breakdown, acceptance criteria, test plans, and release gates per phase).
Security
See docs/SECURITY.md. Pi packages run with full system access—review source before installing third-party packages.
Status
v0.1 focuses on the correct lifecycle engine:
- process + session ownership
- budgets, caps, profiles
- persistence + inspector
- worktree isolation helpers
Named agent catalogs and automatic chain workflows are intentionally deferred until the core is battle-tested.