pi-goal-delegate0.3.2
Bounded delegation for Pi: one goal, a fresh child agent, and a return value that says verified or not. Waits inline by default; wait: false returns a live handle.
Untested on omp
This is a pi package. No one has reported whether it works on omp yet. If you try it, add your result below.
Reports 0
No reports yet.
Readme
delegate
A delegation hands one goal to a fresh Pi child process with its own context
window, budget, and completion contract. delegate_start waits for the
verified outcome by default, so a codemode script collects results the way
it collects any other tool result: inline, in order, with no cross-turn
bookkeeping. wait: false returns a live handle in about a second and lets a
completion message wake the session later.
This package replaces goal-handoff. The primitive is the same: one goal, one
child, one verifiable ending.
Install
pi install npm:pi-goal-delegate # keep it: the extension and the skill
pi -e npm:pi-goal-delegate # try it for one session, install nothing
package.json declares pi.extensions and pi.skills, so both arrive with the
package. To work on it directly, add the checkout instead:
pi -e /path/to/pi-goal-delegate/src/index.ts
The extension has no runtime dependency of its own: it starts another pi
process with the same binary that is running it.
When to delegate
Delegate when at least one of these is true before any work starts. Each one is decidable from the request itself, in seconds:
- The task splits into two or more independent workstreams. Rewriting
several documents or modules, auditing separate subsystems, fixing unrelated
test suites. Two or more workstreams means a fan-out, and a fan-out is one
script with
Promise.all. - The work is a long loop you do not want in this context. Exploration, reverse engineering, build-and-fix iteration, or verification that will take more than about fifteen tool calls. The child absorbs the search noise and returns the verdict.
- A mechanical job can run on a cheaper or different model under a command
gate. Renames, migrations, doc rewrites, test backfills: pass
modelandverifyand let the gate decide whether the work counts.
Work inline when the change is a direct edit of one to five calls, when it needs back-and-forth with the user, or when it shares tight uncommitted state with this session. A single delegation of one small task is slower than doing it, so one workstream is not a reason to delegate.
Two ways to wait, and which is the default
| Mode | How | When |
|---|---|---|
Inline (default, wait: true) |
delegate_start holds the call open until the child settles and returns the outcome. |
Inside codemode, in a fan-out, or in an active /goal. |
Handle (wait: false) |
The call returns a live handle as soon as the run is admitted; the settle later arrives as a delegate-completion message. |
When the parent has other work to do, or the session should go idle while the child runs. |
The inline wait is bounded by the run's own budget, so no call can outlive the delegation it waits for. Two things can still end the wait early, and neither one touches the child:
- The caller aborts the tool call, for example when a
codemodescript reaches itstimeout_msdeadline. - The run's own
timeoutMinutesexpires and the parent stops the child.
In both cases delegate_start returns the live handle, the claim on the settle is
released, and the completion is delivered as a message when the child ends.
Raising the script deadline
A codemode script has no deadline unless its header sets one, and a host that
sets a short default (60 seconds, say) will cut an inline wait long before a
typical delegation ends. Set the deadline for the whole script whenever the work
is longer than a minute:
// @options: {"timeout_ms": 1800000}
// goal: fan out three verified delegations and return their outcomes
const goals = [
{ goal: "Make pnpm test pass in packages/api", verify: "pnpm --dir packages/api test", worktree: true },
{ goal: "Make pnpm test pass in packages/web", verify: "pnpm --dir packages/web test", worktree: true },
];
const outcomes = await Promise.all(goals.map((g) => tools.delegate_start(g)));
return outcomes.map(({ runId, status, verified, summary, integration }) => ({
runId, status, verified, summary, patch: integration?.patchPath,
}));
Yielding the turn instead
With wait: false, the completion arrives as a delegate-completion message: one
coalesced message for a whole wave of runs, steered in before the next model call.
In an ordinary session, end the turn and let it wake you.
Under /goal (@narumitw/pi-goal), ending a turn without goal_wait triggers
immediate automatic continuation while the child is still running. Do one of these
instead:
- keep
wait: true(the default), so the child is done before the turn can end; - or call
goal_wait({ goal_id, reason })alone, which pauses Goal mode until thedelegate-completionmessage wakes it.
delegate_start reads the active goal id from the session and prints the exact
goal_wait call when it returns a live handle under Goal mode.
Where this sits
| Layer | Owns | Does not own |
|---|---|---|
codemode |
Control flow over tools: Promise.all, loops, filtering, scripting |
Processes, budgets, child agents |
pi-async-shell |
OS process supervision for commands: scope, binding, containment, durable logs | Anything about a goal or an agent |
delegate |
The contract with a fresh child agent: goal, done criteria, budget, evidence, lifecycle | Orchestration, fan-out policy, generic shell supervision |
A delegation is a process, so this extension supervises one with the model
pi-async-shell established: a detached owner for the output, a scope that says
who must reap, an event for completion instead of a poll, and a cancellation ladder
that proves absence. It borrows the model, not the code.
Tools
Four tools, one seam: start a run, inspect or wait for runs, steer a run, stop a run.
delegate_start
| Parameter | Default | Meaning |
|---|---|---|
goal |
required | The objective, stated so it stands without this conversation. |
doneWhen |
child decides | Verifiable completion criteria. Prefer "a command exits 0" over "it works". |
verify |
none | A shell command that gates delegate_complete in the child and is re-run by the parent (see Verification). |
context |
none | Facts the child cannot discover: decisions, paths, constraints. Capped at 4000 characters. |
wait |
true |
Hold the call until the child settles and return its outcome. false returns a live handle as soon as the run is admitted. |
worktree |
false |
Give the child its own git worktree and branch. Requires git. |
options |
none | Everything else, below. |
options field |
Default | Meaning |
|---|---|---|
maxTurns |
150 | Model turns. One turn is one assistant response plus its tool calls. |
timeoutMinutes |
60 | Wall-clock cap, and therefore the ceiling on an inline wait. The child enforces it too. |
maxCostUsd |
PI_DELEGATE_MAX_COST_USD |
Cumulative spend cap for this run, from provider usage cost. 0 disables it. |
maxDepth |
0 | Maximum absolute delegation-tree depth, 0-3. Zero disables nested delegation. |
model |
parent model | provider/id, passed to the child explicitly (see Model). |
tools |
inherited | Allowlist for the child. The protocol tools, and codemode when the parent has it, are always kept. |
cwd |
session cwd | Working directory for the child. |
scope |
session |
session dies with Pi and survives /reload; workspace outlives Pi and is re-adopted. |
isolated |
false |
Drop ambient extensions, skills, MCP servers, and context files. |
resumeFrom |
none | Continue a previous child: a run id, or a session file path. |
resultSchema |
none | JSON Schema for the structured result returned through delegate_complete. A schema no value could satisfy is refused at start, because the child could then never complete. |
A known option name written at the top level instead of inside options is lifted
into options before validation, so a near-miss argument starts the run the caller
meant instead of failing the schema.
// Default: wait for the verified outcome.
const outcome = await tools.delegate_start({
goal: "Make the parser stream instead of buffering",
verify: "pnpm test --filter parser",
context: "parse() is used by cli/scan.ts; keep its signature",
});
if (outcome.verified === true) return outcome.summary;
// Background: a handle now, a message later.
const handle = await tools.delegate_start({ goal: "...", wait: false });
delegate_status
Inspects runs, and waits for them when asked.
| Parameter | Default | Meaning |
|---|---|---|
runIds |
every run in this session | One run id, an array of run ids, or "all". |
waitMs |
0 | 0 is a snapshot. Above 0, the call waits up to this many milliseconds for the runs to settle. |
mode |
all |
all waits for every named run; any returns when the first one settles. |
A call that names run ids claims the settles it reports, so the same settle is not
also announced as a message. A call with no runIds is a read: it lists what
exists and claims nothing.
delegate_send
delegate_send(runId, text) hands a running child one message. The parent appends
it to inbox.jsonl in the run directory and the worker reads it at its next
turn_start, immediately queuing it with Pi's deliverAs: "steer" so it lands
after the current turn's tool calls and before the next model call. It works across
/reload and across processes and never interrupts a request in flight. Use it to
correct course; that costs one call, where a restart costs the whole budget and the
context.
delegate_cancel
Graceful signal, grace period (default 3000 ms), process-tree fence, then a check
that the tree is actually gone. containment is a measurement:
containment |
Meaning |
|---|---|
gone |
The platform was observed and no process survived. |
leaked |
Some process survived; the pids are in leakedPids. |
unproven |
This platform exposes no process table, so absence could not be proven. Report it as unproven, never as gone. |
The three-state verdict exists because a two-state verifiedGone was true when
nothing was observable: an absence of observation read as proof of absence.
Child-side protocol
The child gets exactly two tools that end the loop:
delegate_complete(summary, evidence, result?)— completion-gated done. Evidence is commands, files, checks;resultis validated whenresultSchemais present.delegate_blocked(reason, needs)— a decision, credential, or fact the child cannot obtain.
Foreign goal tools (goal_complete, goal_blocked, goal_wait, the old
goal_handoff_*) are deactivated in the child. A delegated child has one goal
protocol.
Lifecycle
| Status | Who decides | Meaning |
|---|---|---|
starting |
parent | Admitted, no event seen yet. |
running |
parent, from the child stream | Turns are arriving. |
complete |
child | delegate_complete, and the verify command, if any, exited 0. |
unverified |
parent | The child said complete, and the parent ran verify and it failed. |
blocked |
child | delegate_blocked. The outcome carries needs, not evidence. |
no_progress |
child or parent | Circuit breaker: repeated identical call, consecutive failures, or two identical no-tool turns. |
limit |
child or parent | Turn budget or spend cap reached. The child fences itself before the next request; the parent's copy of the rule is a runaway net with a two-turn grace. |
timeout |
parent and child | Wall clock. The parent enforces it with the ladder; the child enforces it on its own for workspace runs. |
aborted |
parent | delegate_cancel. |
error |
parent | Spawn failure, child crash, provider error, or no verdict at all. |
lost |
parent | An adopted workspace record with no exit and no provable liveness. Never reported as complete. |
Only complete and blocked delivered what they were given. Everything else is a
failure, and isFailure in contract.ts is the one definition the tools, the
command, and isError on a tool result all share: a no_progress or limit run
reported with isError: false is a stalled child an orchestrator reads as a
finished one.
Verification
doneWhen is prose for the child. verify is an executable completion gate for
both sides:
await tools.delegate_start({
goal: "Make the parser stream instead of buffering",
verify: "pnpm test --filter parser",
});
delegate_complete first runs the command in the child's directory. A failure is
returned to the child as a tool error containing the command output, and the run
continues so the child can repair the cause and retry. Only a passing claim
terminates the child. The parent then independently runs the same command before
accepting the outcome, using the same PI_DELEGATE_ENV_DROP policy so verification
cannot regain credentials withheld from the child.
verified |
Meaning |
|---|---|
true |
The command exited 0. |
false |
It exited non-zero, could not start, or timed out (PI_DELEGATE_VERIFY_TIMEOUT_MS, default 120000). The status becomes unverified. |
"not-run" |
The run carried no verify command, so the evidence is the child's own account and nothing more. |
The child's summary and evidence survive a contradiction: the parent records that
its own check failed, not that the child never spoke. childVerification preserves
the successful child-side gate separately from the parent's verification record.
Budgets
maxTurns counts model turns. Recorded delegations measure from 25 to 296 turns,
with a median of 110, so the default is 150 and the hard maximum is 500.
timeoutMinutes defaults to 60, which keeps about 90% of recorded runs inside the
cap. It bounds the inline wait as well, so one number answers both questions.
Circuit breakers run in the child and in the parent's compact event observer: the
third identical tool call is blocked in the child, the sixth ends the run, eight
consecutive tool errors end the run, and two consecutive turns with the same answer
and no tool calls end the run. They live in contract.ts as pure functions over
one state record, because the parent reads the same rules from the child's event
stream and two copies of a threshold is two answers to "was this run stuck".
Admission: how many children at once
One session may keep PI_DELEGATE_MAX_LIVE delegations live, four by default,
thirty-two at most. A Promise.all over fifty goals is refused at the fifth with
the live runs named:
Too many live delegations: 4 of 4 already running.
- dl_mx38p4q3_e48a8e01 (2m03s, 41/150 turns)
Wait for one to settle, cancel one with delegate_cancel, or raise
PI_DELEGATE_MAX_LIVE (currently 4, maximum 32).
The gate counts live runs plus starts reserved during admission, not lifetime runs: concurrent starts cannot pass before their handles register, and cancelling frees a slot immediately. A malformed value falls back to the default rather than to "unlimited".
Cost
maxCostUsd caps cumulative spend, read from provider usage cost as the run
streams. The parent checks the same limit the child does, and a run that crosses it
ends as limit with the amount in the summary. It is off by default
(PI_DELEGATE_MAX_COST_USD=0): a cap that kills a healthy run by default is worse
than no cap.
The cap is per run. A nested child may not choose a cap larger than its parent's,
but nothing sums a tree: four grandchildren with a $2 cap each can spend $8 between
them. Treat maxDepth and maxTurns as the tree-wide bound and maxCostUsd as the
per-run ceiling.
Parallel children and worktrees
Two children editing one working tree fight over every file. worktree: true gives
the child its own checkout:
await tools.delegate_start({ goal: "...", worktree: true });
The parent runs git worktree add --no-track -b delegate/<runId> <agentDir>/delegate/worktrees/<runId> HEAD in the session directory and starts the
child there. The outcome records worktree: { path, branch, repo, base } and
integration: HEAD, dirty status, diff statistics, changes.patch, and the result
of git apply --check against the original repository. The patch includes
committed, tracked-uncommitted, and untracked work. Nothing is automatically
committed or merged; integration.applyCommand is the explicit integration path.
The checkout is kept by default: it holds the only copy of the child's work.
PI_DELEGATE_KEEP_WORKTREES=0 opts into cleanup, and even then only a clean tree is
removed. A directory that is not a git repository, or a repository with no commit,
fails the start with git's own message rather than silently falling back to the
shared tree.
Resuming a run
outcome.sessionFile is the child's own Pi session. options.resumeFrom: runId
resolves it and passes --session <path> to the new child, so a second delegation
continues the first one's context instead of starting cold. When the previous run
used a worktree, the resumed run keeps that checkout as its cwd. resumedFrom
records the lineage. A session file path or a session id is accepted as-is; an
unknown value is passed through rather than guessed at. A resume is a new run with a
new budget, not a reopening of the sealed record.
Model
The parent passes its model to the child explicitly with --model and its thinking
level with --thinking. Inheritance by omission does not work: a child started
without --model falls back to settings.json defaultModel, which is not the
parent session model. modelSource in the outcome records which one ran:
explicit, inherited, or default.
Accounting
Every outcome carries turns, toolCalls, and usage (input, output,
cacheRead, cacheWrite, totalTokens, cost). The numbers are folded from the
child's own JSON event stream, and the child writes the same numbers into
result.json, so a killed run still reports what was spent up to the kill.
Supervision
delegate_start spawns supervisor.mjs, a detached Node process in its own
session. The supervisor owns the child stdout and stderr and writes child.jsonl,
child.log, and the compact accounting stream control.jsonl. Pi holds no pipe to
the child, which is what makes the rest possible:
- An interrupted wait does not interrupt the child. A tool call that is aborted or times out ends only the wait. The supervisor is detached, the run keeps going, the claim on its settle is released, and the completion is delivered as a message. Synchronous orchestration and background orchestration are therefore one mechanism with a different amount of patience.
/reloadtransfers ownership. The live registry is published to a process-global slot keyed by(pid, sessionId, cwd); the next activation claims it and rebinds its UI callbacks. Nothing restarts, no byte is lost. A slot nobody claims within 30 seconds expires into cancellation.session_shutdownreaps session runs. The supervisor watches fd 3. EOF means the owning Pi died, so the tree is torn down. Bytes on fd 3 are not a protocol;/reloadtransfers the in-process registry without changing supervisor ownership.scope: "workspace"survives Pi. No fd 3, no owner watch. On the nextsession_startin the same directory, a run whose owner identity is dead is re-adopted: the event log is folded, the tail resumes, and the settle is delivered here. A run whose owner is alive is read-only. A record with no exit and no provable liveness becomeslost.- Logs drain past the cap. 32 MiB per stream by default. Past the cap the
supervisor stops appending the raw payload and keeps reading, because a reader that
stops reading turns a logging policy into a hung child. It still writes compact
turn, usage, cost, and breaker records to
control.jsonl, so a capped payload log cannot blind the parent's budgets or no-progress enforcement. - The fence is the containment guarantee, where a process table exists.
Cancellation unions three views: processes tagged
PI_DELEGATE_RUN=<id>, live descendants of the captured(boot_id, pid, start)identity, and live members of the owned process group. Each pid start time is re-read before signalling, so a reused pid is never killed. Off Linux the group is what is left, and it is enough to kill:spawn(detached: true)makes the supervisor a session leader, so its pid is the process group id andkill(-pgid)reaches the whole tree.
Permission asks
The child is started with PI_SUBAGENT_PARENT_SESSION=<session id>, the convention
@gotgenes/pi-permission-system documents for out-of-process subagents. A gated
tool call in the child is forwarded to the delegating session, so authority stays
with the human instead of failing closed with "no interactive UI is available".
Without a human to answer, the child reports blocked. The marker is never
overwritten when one is already present, so a chain of delegations relays through
the middle hop.
This is a declared dependency on another package's environment convention, not on
its code: if that package is not installed, the variable is inert. If it changes the
variable name, gated calls in the child fall back to that extension's default
(usually "deny, no interactive UI") and the child reports blocked; it does not
become silently permissive. isolated: true is the answer for a host that cannot
answer asks at all: built-in tools only, no ambient extension, skill, MCP server, or
AGENTS.md.
Command
/delegate Fix the login error handling and add a regression test --turns 60
/delegate Update every caller of parseConfig --done "tests pass" --model mistral/ministral-8b-latest
/delegate list delegations in this session
/delegate read <id|prefix> one run in full
/delegate log <id|prefix> tail the child stderr
/delegate send <id> <text> steer a running child
/delegate cancel <id|prefix|all> cancel with the ladder
/delegate doctor check this installation
Options may appear anywhere, as --name value or --name=value: --model,
--turns, --minutes, --cost, --done, --context, --verify, --tools,
--scope, --isolated, --worktree, --resume, --cwd, --depth, --schema,
--wait, --background. The command accepts what the tool schema accepts:
--turns is 1-500, --minutes is 1-240, and a relative --cwd resolves against the
session directory rather than the process working directory. A bare -- ends option
parsing, so a goal may contain its own --words.
In the TUI the command returns as soon as the run is admitted and the settle arrives
as a completion message; --wait holds it open instead. In print mode it waits for
the outcome and prints it, because nothing else keeps a print-mode process alive for
a session-scoped child; --background returns immediately.
Doctor
/delegate doctor checks the parts that fail silently:
delegate doctor
manifest ok pi-goal-delegate 0.3.0 · 1 extension, 1 skill path
run root ok ~/.pi/agent/delegate · 12 records · 41.2 MiB
git ok available · worktree: true usable
launcher ok /usr/bin/node /usr/lib/pi/cli.js · child runs in --mode json
live ok 1 live of 4 · dl_mx38p4q3_e48a8e01
retention warn 3 of 14 records would be removed by the next prune: dl_1, dl_2, dl_3
PI_DELEGATE_MAX_RUNS, PI_DELEGATE_RETENTION_DAYS and PI_DELEGATE_MAX_BYTES set the policy
limits ok max live 4 of 32 · spend cap off · verify timeout 120s · run cap 240 minutes
session ok s_abc123 in /repo · top-level session
containment ok linux: procfs identity, tag scan, group fence
Each line is ok, warn, or fail, and a check that cannot answer says so instead of
throwing. A fail is an installation that will not work, and the reason is on the
line: a run root that cannot be written, a launcher that does not exist, a manifest
entry that no longer resolves. A warn is a working installation with
something to know.
The same checks run at session_start for the one failure that used to be
invisible: an unwritable record root. A missing root is checked through its
nearest existing ancestor, and a symlink to a writable directory is accepted.
The probe uses a unique exclusive file and reports create, write, close or
unlink failures, so it neither clobbers an existing file nor passes a read-only
root. It produces a warning in the session instead of a delegation that fails
six days later.
delegate_status with no runs reports the run root and the record count as well, so
an agent can tell "nothing has run" from "the record root moved".
Artifacts
~/.pi/agent/delegate/<runId>/ (PI_DELEGATE_HOME overrides the root):
| File | Written by | Meaning |
|---|---|---|
spec.json |
parent | The exact contract the child received, including the child command line. Written once, at admission. |
meta.json |
parent | Scope, status, session directory, supervisor identity, owner identity, containment mode. |
state.json |
supervisor | Pid, process group, cap, exit, sealed-at. The one record of the child process, sealed atomically. |
child.jsonl |
supervisor | The raw child JSON event stream, capped at 32 MiB. |
control.jsonl |
supervisor | Compact turn, usage, cost, text, and breaker events. Written even after the raw cap; this is the parent's accounting source. |
child.log |
supervisor | The child stderr. |
result.json |
child | The verdict: status, summary, evidence or needs, turns, usage, session file. |
outcome.json |
parent | The sealed outcome, including structured result and integration metadata, readable after the parent is gone. |
changes.patch |
parent | For worktree runs with changes: committed, tracked, and untracked work exported without an automatic commit. |
inbox.jsonl |
parent | Steering messages, one JSON line each. The child reads the file at turn_start. |
owner.lock |
parent | The adoption claim, created with O_EXCL. One owner at a time. |
Each file has exactly one writer. state.json replaced pid.json, exit.json and
log-cap.json, which described the same process in three files a reader had to merge.
Records written by a previous version are still read.
Each run directory is created 0700 and every record inside it is written 0600.
The record holds the goal, the context note, and the child's full output on a
possibly shared machine, so it is private to the user who started it.
Retention
Records are reclaimed automatically, bounded three times: a record older than
PI_DELEGATE_RETENTION_DAYS (default 7) is removed, once the count passes
PI_DELEGATE_MAX_RUNS (default 100) the oldest surplus is removed, and once the
total passes PI_DELEGATE_MAX_BYTES (default 512 MiB) the oldest records are removed
until it fits. The byte cap bounds the worst case: 32 MiB of stdout and 32 MiB of
stderr per run times a hundred kept runs is 6.4 GB that no count or age limit ever
reached.
A record is never removed while it can still produce a verdict: a run this process
follows, a record whose supervisor is alive, or one younger than ten minutes.
Deleting a record removes a worktree inside the record root only through
git worktree remove, only when it is clean, and only when no other run references
it. /delegate doctor reports the plan before the next prune runs it, so retention
is predictable rather than a surprise.
Environment
| Variable | Meaning |
|---|---|
PI_DELEGATE_HOME |
Run-record root. Default <agentDir>/delegate. |
PI_DELEGATE_MAX_RUNS |
Run records kept after pruning. Default 100. |
PI_DELEGATE_RETENTION_DAYS |
Age at which a run record is removed. Default 7; 0 disables the age rule. |
PI_DELEGATE_MAX_BYTES |
Total bytes across every run record. Default 536870912 (512 MiB); 0 disables the size rule. |
PI_DELEGATE_MAX_LIVE |
Concurrent delegations in one session. Default 4, maximum 32. |
PI_DELEGATE_MAX_COST_USD |
Default cumulative spend cap per run, in US dollars. Default 0 (off). |
PI_DELEGATE_VERIFY_TIMEOUT_MS |
Timeout for the verify command. Default 120000. |
PI_DELEGATE_KEEP_WORKTREES |
Set to 0 to remove a clean worktree when its run settles. Default: keep. |
PI_DELEGATE_PI_ENTRY |
JavaScript entry for the child, when process.argv[1] is not it. |
PI_DELEGATE_PI_COMMAND |
Executable that starts the child, for a launcher that hides its own entry. |
PI_DELEGATE_ENV_DROP |
Comma-separated variable names removed from the child's environment. The child inherits the environment by default, because that is how it authenticates; name what must not travel when the goal covers content you do not control. |
PI_DELEGATE_RUN / PI_DELEGATE_DIR / PI_DELEGATE_SPEC |
Set by the parent on the supervisor and inherited by the child: the containment tag, the run directory, and the contract path. |
PI_SUBAGENT_PARENT_SESSION |
Set for the child unless one is already present. Names the session that answers forwarded permission asks. |
Layout
src/
index.ts tool and command registration (the file Pi discovers)
command.ts /delegate, the human front end for the same registry
doctor.ts the installation and health self-check
registry.ts handles, claims, admission gate, coalesced completion, /reload handoff
run.ts admission, live tail, cancellation ladder, sealed outcome
spawn.ts run directory layout, child argv, detached supervisor spawn, typed reads
supervisor.mjs detached owner of the child output and of state.json
identity.ts procfs identity, process-tree fence, containment verdict
events.ts the child JSON event stream: turns, usage, last text
worker.ts child-side goal loop (loaded into the child with -e)
contract.ts statuses, budgets, breakers, prompt text shared by both sides
verify.ts the parent's own check on a completion claim
worktree.ts a checkout of its own for a child that asks for one
retention.ts reclaim run records by age, count and bytes, and report the plan
skills/
delegate/ the skill that teaches the workflow to an agent
tests/ node --test suites, plus the fake child and worker host
Tests
From the repository root:
pnpm install
pnpm run typecheck # tsc --noEmit over src/ and tests/
pnpm test # every suite below
pnpm run test:coverage
| Suite | Covers |
|---|---|
tests/delegate.test.mjs |
lifecycle, event folding, containment, claims, the cancellation grace period, the status footer, reload |
tests/command.test.mjs |
/delegate parsing, quoting, prefix resolution, every cancel form, doctor, the TUI and print paths |
tests/surface.test.mjs |
the four-tool surface, the lean schema budget, option hoisting, the inline default, the goal_wait guidance, and the onProgress contract |
tests/doctor.test.mjs |
real run-root probes: missing ancestors, read-only directories, exclusive cleanup, and symlinked roots |
tests/worker.test.mjs |
the child's circuit breakers and terminal states, in a real subprocess |
tests/events.test.mjs |
the event stream: unknown records, error carriers, the incremental tailer |
tests/isolation.test.mjs |
directory-scoped workspace adoption, per-session registries |
tests/adoption.test.mjs |
re-adoption against a supervisor that is actually running |
tests/failure.test.mjs |
wall-clock deadlines, a supervisor killed from outside, an exit with no verdict |
tests/retention.test.mjs |
age and count pruning, the reported plan, live-run protection |
tests/supervisor.test.mjs |
sealed exit records, controlled exit, log cap, the owner watch |
tests/tool-e2e.test.mjs |
the real loader, tool schemas, inline and background starts, every delegate_status and delegate_cancel mode, /reload |
tests/guard.test.mjs |
the child-side recursion guard, parameter validation, declared bounds |
tests/containment.test.mjs |
the containment verdict model, signal-0 probing, a real cancel that must prove the tree gone, isFailure. Portable: this is the suite the macOS CI job runs. |
tests/gates.test.mjs |
the live-admission gate, the spend cap, verified completion, the adoption claim, steering, worktrees, and typed record reads |
tests/result-schema.test.mjs |
the resultSchema admission audit and the instance path a rejected value is told |
tests/support.mjs holds what every suite needs: temporary directories removed when
the test ends, the PI_DELEGATE_* environment restored after each test, and
waitFor in place of fixed sleeps. No suite replaces process.stdout: the
command takes its output sink as a dependency, because a test that swaps the
process stream also swaps the channel the test runner reports on, and the results
it swallows are the ones nobody notices are missing.
CI runs the whole suite on Linux against Node 22, 24 and 26, and runs
tests/containment.test.mjs plus tests/gates.test.mjs on macos-latest: those are
the suites that exercise cancellation and adoption where /proc does not exist,
which is exactly the platform where absence used to be reported as proof.
No suite needs a model or a network. The lifecycle suites spawn the fake child in
tests/fixtures/fake-pi.mjs, which emits a real JSON event stream and seals a real
verdict, and which can also refuse SIGTERM so a grace period is observable. The
worker suite drives the real worker.ts through tests/fixtures/worker-host.mjs.
The e2e suite loads the extension through Pi's own loader and resolves Pi's host
packages from an explicit PI_HOST_MODULES override first, then from the project's
own node_modules, then from the newest ~/.pi/agent/managed-runtime/releases
entry.
Limits
- Containment is platform-dependent, and the verdict says which one ran. Linux
gets procfs identity, the tag scan, the descendant walk, and the owned process
group. macOS and other POSIX platforms get the process group, probed with signal 0:
cancellation works, and the verdict is
goneorleakedon real evidence. Windows getstaskkill /Tand no observation, so its verdict isunproven. Asetsid(2)child that also clears its environment and loses its parent is out of reach on any platform. - A delegation is not a sandbox. The child runs with the parent's authority, in
the parent's filesystem, with the parent's environment (minus
PI_DELEGATE_ENV_DROP).toolsandisolatedbound the surface, not the permission. - A session-scoped run cannot outlive the session. Use
workspacefor that. In print mode a session run is cancelled when the process exits, so a print caller should use the default inline wait. isolated: truealso drops provider extensions. A custom provider that lives in an extension is unavailable to an isolated child.- The workspace adoption scan reads the global run root. A record is adopted only when it was started by this session's directory and its owner is gone. Two sessions in different directories never adopt each other's runs, and a record from a deleted directory is never adopted.
- The no-progress rule is a heuristic. Two identical answers with no tool call end the run in either observer; a child that varies its wording while doing nothing can still consume its turn budget.
Design notes
Three decisions are load-bearing, and each one replaced a rule that measured wrong in practice.
The wait is inline, and its ceiling is the run's own budget. Every recorded
delegation ran longer than 60 seconds (minimum 222 s, median 1102 s, maximum 6270 s),
so a tool-call wait capped in tens of seconds could never report a result. A capped
wait pushed callers into cross-turn bookkeeping, and under /goal that bookkeeping
was a live loop: end the turn, get continuation, poll, repeat. Waiting for the
outcome the run already promises costs nothing extra and removes the loop.
The tool surface is four calls with one required argument. A delegation is decided
in the second before the first call. Seventeen flat optional parameters and a tutorial
in the description answer questions the caller has not asked yet; a required goal,
six sparse inputs, and a nested options bag answer the one that matters.
The completion is an event, never a poll. A settle that nothing awaited is delivered as one coalesced message. A settle an await reported is claimed and never announced twice.