@ftrdotdev/pi-delegates0.2.1
Durable agent delegation for Pi
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
pi-delegates
pi-delegates is a Pi extension for durable agent delegation. A delegated agent is a child conversation. Its toolkit (model, thinking level, tools, extensions, instructions, working directory and approval rules) is committed when the run starts. Close Pi, reopen the session, and the runs, conversations, checkpoints, gate decisions and dispositions are still there.
Package: @ftrdotdev/pi-delegates · MIT

The inspector overlay (ctrl+space): one fanout run, its three children, the
gate one child is parked on, and the lane counts. Every row is live.
Installation
pi install npm:@ftrdotdev/pi-delegates
Requirements
- Pi
1.6.0with a matching@earendil-works/pi-ai, the versionpi-durablepins. On load the package compares the two; when they differ it refuses to start and prints both versions. - Node
22.19.0or newer. The store usesnode:sqlite.
Inspector shortcut
ctrl+space opens the inspector overlay while the inspector is active. Change
it in ~/.pi/agent/delegates.json:
{ "inspectorShortcut": "ctrl+alt+i" }
Or set PI_DELEGATES_INSPECTOR_SHORTCUT=ctrl+alt+i for one run. ctrl+i is
not used: legacy terminals send it as Tab. ctrl+shift+... bindings need a
terminal with Kitty keyboard protocol support. If the OS reserves
ctrl+space (macOS input switching, for example), use ctrl+alt+i or f2.
Run /reload after editing the file.
In the overlay, enter or i expands the selected row. On a fanout or
review parent it shows the child rows; the Gates section stays visible below the
tree. enter or i on a child shows its details. s stops a run, a
approves a gate, d denies one, and escape closes. A waiting child with one
gate also accepts a or d: the write goes to the parent run that owns the
gate. Finished rows show took <duration>; live rows show their current
activity or age. An expanded row keeps its details indented beneath it.
ctrl+space only opens the overlay; it never acts on a row. While the
inspector is off, the key prints a hint that names /delegates, the same notice
/delegates:overlay prints, instead of doing nothing. The footer carries the
state in one line: delegates off · /delegates when off, delegates idle · ctrl+space when on and quiet, and the live counters (delegates running 2 · gates 1 · ctrl+space) while work is pending. A session that never enabled the
inspector shows no footer line. The Delegates box above the editor stays
mounted from activation to teardown: idle — ctrl+space when nothing is
running, then the non-zero counters and up to two live child lines while work
runs.
When a gate becomes pending, one warning notice names the gate and any waiting
child, and one message enters the parent session. The message tells the agent to
ask you for the decision; it does not approve or deny the gate. These alerts run
with the session, not with the inspector: turning /delegates off does not
silence them. An alert is not repeated after an inspector toggle or a reload.
The same alert path announces a delegate's question with one warning and one
parent message. See Questions from a delegate.
/delegates toggles the inspector. The first delegate launch in a TUI session
turns it on automatically. An explicit off stays off for later launches, and
reload, resume and branch switch restore an active inspector.
Agent skill
The package ships a skill for agents. It covers when to delegate, launch
shapes, definition fields, run status, control, gates and gate automation. Pi
loads it when a task matches, or run /skill:pi-delegates.
Tools
| Tool | Purpose |
|---|---|
delegate_launch |
Start a single agent, a fanout in a lane, or a panel of reviewers |
delegate_control |
steer, stop, resume, approve, deny, answer or decline a run |
delegate_status |
Show runs, lanes, pending gates and requests; with no argument, newest 50 |
delegate_status accepts run or lane to narrow the view. With run it
reads only that run, prints what it waits on and its review rows, and prints no
lane line. Without run it returns the newest 50 runs, prints how many older
runs it left out, and lists what needs a person first.
A launch needs a host model. When the session has no model and the definition
sets none, the launch fails with HostModelMissing before a task or a run is
written. The error names the definition, model.provider and model.modelId.
A launch waits up to defaults.launchWaitMs, which is 10 minutes by default.
It returns the answer for a single run, or the group summary for a fanout or
review. The result names the run id. When the child parks on an approval gate,
it returns waiting with the gate names. When the deadline passes, it returns
running or queued with the run id, and the run keeps working.
The prompt section lists the built-in presets:
| Preset | Tools |
|---|---|
scout |
read |
builder |
read, bash, write, edit |
reviewer |
read |
Presets use the host session's model and thinking level at launch. They carry no approval rules. Gates are opt-in and belong to the user who registers the definition. See Register an agent with a gate.
MCP servers
The package reads mcp.json from the agent directory and, when Pi marks the
project trusted, <project>/.pi/mcp.json. Project entries replace global
entries with the same name. A project entry without command, url or type
overrides only enabled, exposure and toolExposure of the global server. A
project entry may not set auth beside url: a repository cannot choose where
a credential goes.
{
"mcpServers": {
"demo": { "command": "node", "args": ["server.js"] },
"docs": {
"url": "https://example.test/mcp",
"headers": { "Authorization": "Bearer ${DOCS_TOKEN}" }
}
}
}
${NAME} in env and headers expands from the process environment. A
missing variable keeps its literal and writes mcp.env_missing. A value that
starts with ! writes mcp.env_unsupported, and the server is skipped: the
package never runs a command to build a server environment.
Only a server that a registered definition references connects: a tools entry
under mcp__<server>__, or an extensions entry mcp:<server>. References are
read at session start, so an inline definition can use a connected server's
tools but cannot bring in a server that no registered definition references.
Each connected server registers one extension mcp:<server> with the namespace
mcp__<server> and one tool per visible server tool, named
mcp__<server>__<tool>.
A definition selects those tools by exact name or by a pattern that names its server:
{ "tools": ["read", "mcp__demo__*"] }
mcp__<server>__* and mcp__<server>__<prefix>* are the only accepted shapes;
mcp__* and a partial namespace are refused with a message that states the
grammar. An unknown namespace fails the launch with ToolkitUnresolved, which
lists the available namespaces and the configured servers that are not
connected.
exposure picks how a server's tools reach the child: codemode (default,
scripts only), direct (the model and scripts), deferred (the model after
tool_search, and scripts), or hidden (no tool is registered unless
toolExposure re-exposes it). A toolExposure entry overrides one tool name
or * pattern. A selected codemode tool also selects the codemode
extension; a selected deferred tool selects tool-search.
A server that cannot connect degrades: no tools, one mcp.connect_failed,
mcp.connect_timeout or mcp.list_tools_failed line in delegates.log, one
aggregated warning at session start, and the launch continues. A connect waits
at most 10 seconds. A tool call is bounded by the server's timeout (default 60
seconds) and by the run's cancellation; a timeout returns an error naming the
server. A result over 20 KiB is cut, and the full text is saved under the
session directory.
Workflows
A registered definition may set codemode: "runs". Such a definition runs
workflows only: a single, fanout or review launch of it fails with
WorkflowOnly, and a workflow launch of a definition without the field fails
with WorkflowNotEnabled, both before a run exists. The model-authored inline
definition cannot set the field.
const composer = defineAgent({
name: "composer",
role: "Workflow composer",
prompt: { role: "You compose workflows from delegated runs." },
tools: ["read"],
extensions: ["coding-tools"],
approval: { gates: [] },
codemode: "runs",
});
Launch it with kind: "workflow". The script is JavaScript that the child's
model passes verbatim to durable's codemode tool:
{
"kind": "workflow",
"agent": "composer",
"script": "const a = await tools.launch({ agent: 'scout', task: 'a' }); return a.answer"
}
A script may be at most 65536 UTF-8 bytes; a larger one fails with
WorkflowTooLarge before a run is claimed. The run records mode workflow, and
its lane defaults to workflow. The child conversation selects codemode and
runs beside the definition's own tools and extensions, so the model sees
codemode and none of the run tools.
The script reaches eight tools under the runs namespace:
| Tool | Purpose |
|---|---|
launch |
Start one child in the workflow's lane, wait for it, return { run, answer, status } |
launch_many |
Start a group in one lane, wait for all, return one outcome per child |
lane |
Read { name, running, queued, answered } for one lane |
status |
Read every run of the session as { run, definition, lane, status } |
ref |
Read { run, conversationId, gateRunId } for one run |
steer |
Send a message to a child |
stop |
Stop a child |
gate |
Ask a person to approve or deny script:<name>, then return the decision |
A child run is owned by the workflow run task, inherits the workflow's lane, and
records parentRunId, so it appears nested under the workflow. A launch_many
child records the workflow as its parent and gate run too, so its approval gate
is listed under the workflow, not under the group. A script cannot stop or steer
its own run; that call returns an error result naming the run. A refused control
call returns an error result that names the reason; the script catches it to
branch. An unknown agent or a missing host model fails the call, so the script
raises.
The lane cap bounds a launch_many group. tools.launch claims its child
without admission, like kind: "single"; a script that wants parallel children
calls launch_many. The script the model passes is trusted: the toolkit does
not compare the codemode code with the launch script, so the workflow-script
section and the definition prompt are the only instruction.
A restart resumes the script from durable's journal: each nested call reattaches
by key, so an answered child is not started again. delegate_control resume
refuses a workflow run; reopen the session instead. tools.gate parks the
workflow on script:<name> until delegate_control approve or deny releases
it.
Questions from a delegate
A delegate can put one question to you. The child needs the questions
extension and the ask tool in its definition:
const envScout = defineAgent({
name: "env-scout",
role: "Environment scout",
prompt: { role: "Ask which environment to inspect, then inspect it." },
tools: ["read", "ask"],
extensions: ["coding-tools", "questions"],
approval: { gates: [] },
});
ask takes { prompt, options?, allowOther? }. With two to five options it
asks for a choice; with none it asks for free text. allowOther defaults to
true, and a request with no options must allow free text, so allowOther: false
needs at least two options. A prompt is at most 4 KiB, a label at most 128
characters, a description at most 1 KiB, and an answer at most 4 KiB; a refusal
names the field and its bound. At most one option may be recommended.
The child commits the request and parks its tool call. The child never opens a socket or runs a command for IPC: the durable store is the channel, as it is for gates, so an answer survives a restart.
In Pi, one warning reads request <id> asks: <prompt>, truncated to 120
characters, and one message enters the parent session with the exact questions
parameter. The message tells the model to ask you with the question tool when
that tool exists, and in plain text otherwise; there is no dependency on
@ftrdotdev/pi-inquiry. The model answers with:
{ "action": "answer", "run": "<run id>", "request": "<request id>", "answer": "staging" },
and declines a cancelled dialog with:
{ "action": "decline", "run": "<run id>", "request": "<request id>" }
answer accepts either the run id or a fanout child's run id. The answer is
normalized before it is stored: ignore case, trim, strip a leading N. , accept
an in-range option number, and store the canonical label. An answer outside the
options is refused and names the labels. A second answer, an unknown request, a
wrong run, a declined request and an expired request are refused. decline
cancels the request with reason declined; the child gets an error naming the
reason. A declined request settles the run denied, not answered: the row and
the lane counts read denied, and the wait text names it, Run <id> was denied: request <request id> was declined.
After an answer the verb waits like a launch: the run settles, or it asks its
next request. delegate_launch and delegate_control answer return at a
request instead of blocking. approve and deny still wait for the task, so a
question that follows a decision reaches you through the alert or
/delegates:answer. A run that waits on a gate and a request names both: Run <id> waits for gate <gates> and request <requests>.
/delegates:answer answers without the model. With no arguments it lists the
pending requests, then asks for a label or free text; cancelling the answer
dialog declines the request, and cancelling the request picker leaves every
request pending. With <run> <request> <answer…> it answers directly. A
request that is no longer pending is refused.
The deadline is 24 hours from the first call. A record past its deadline reads
as expired without a write, the child's ask returns an error, and a late
answer is refused. stop cancels the run's pending requests with reason
stopped; a resume does not resurrect one. Seven days after a request is
made, the next live start retires the record and its index row. A read-only
viewer lists pending requests and never announces, answers or prunes.
A headless or sandboxed host starts startRequestAlerts with its own
RequestAlertHost, or reads the same records with requestRecords from the
store. Without that watcher a request stays pending and the store still lists
it. The package default, logOnlyRequestHost, writes one id-only log line per
request; the prompt and the answer never enter the log.
/delegates
/delegates toggles the live inspector in a TUI session. /delegates:list
prints the registered agents, the session's runs, the lane counts, the pending
gates and the pending requests. Each agent line names its tools and gates.
/delegates and /delegates:list only read. The three tools and
/delegates:answer are the writers.
Register an agent with a gate
Presets carry no gates. To gate a tool, register your own definition from a Pi extension. From a checkout, examples/gated.ts is a one-file version of this recipe; see examples/README.md.
Create a local package with a manifest at ./delegates-local/package.json:
{
"name": "delegates-local",
"private": true,
"keywords": ["pi-package"],
"dependencies": {
"@ftrdotdev/pi-delegates": "^0.1.0"
},
"pi": {
"extensions": ["./deployer.ts"]
}
}
The pi.extensions field lists ./deployer.ts. Pi loads that file.
Build the definition and pass it to createDelegatesExtension:
import { createDelegatesExtension } from "@ftrdotdev/pi-delegates";
import { defineAgent } from "@ftrdotdev/pi-delegates/agents";
const deployer = defineAgent({
name: "deployer",
role: "Deploy agent",
prompt: { role: "You deploy the service and report the result." },
tools: ["read", "bash"],
extensions: ["coding-tools"],
approval: {
gates: [{ name: "deploy", tools: ["bash"], match: "deploy" }],
},
});
export default createDelegatesExtension({ definitions: [deployer] });
Install the checkout as the local package's dependency. Before the first release, the npm name does not resolve. After the release, install the npm name:
cd ./delegates-local
# Before the release is published:
npm install <checkout>/packages/delegates
# After the release:
# npm install @ftrdotdev/pi-delegates
pi install ./delegates-local
Do not also install the checkout as a Pi package. The local extension registers the delegate tools, so a second copy registers them twice.
Call delegate_launch:
{ "request": { "kind": "single", "agent": "deployer", "task": "deploy the service" } }
Repeating the same request in one session returns the run that request already started. The run id covers the session and the request content, so a retried tool call never spawns a second run. Change the task text to launch again.
match is a case-sensitive substring of the raw bash command and applies to
bash only. A rule with match on read never parks; omit match to park
every call of a listed tool. The gate name is scoped to the run, so one
decision covers every child that parks on that name.
A matching bash command parks the run. Decide the run with the run id that
the launch returned. Call delegate_control:
{ "action": "approve", "run": "<run id>", "gate": "deploy" }
coding-tools is the built-in coding extension. The package adds the
gate-guard extension when the definition has rules. A gate belongs to the
registered definition. An inline definition of the same name can narrow the
tools, but it cannot remove the rule.
Configuration
delegates.json in the Pi agent directory overrides the defaults. A missing
file uses the defaults. An invalid value falls back to its default and adds a
diagnostic.
{
"caps": { "laneCap": 4, "sessionCeiling": 8, "maxTurns": 400 },
"defaults": { "maxTurns": 120, "launchWaitMs": 600000 }
}
defaults.maxTurns is the budget a child gets when no request or definition
names one. caps.maxTurns is the ceiling every resolved budget is clamped to,
and no budget goes below one round.
Failure log
The package writes <sessionDir>/delegates.log, one JSON object per line. It
records harness reports, config diagnostics, version notes, swallowed errors and
wait outcomes that are not settled. It never holds the request, the task text,
an answer, a prompt or a command. A broken log path never fails a call.
See OPERATIONS.md for the fields and stable codes.
Session store
The Pi process that owns a session is its only writer. Do not open its SQLite store yourself. See OPERATIONS.md for the path and read-only rules.
Development
See TESTING.md to run the extension from a checkout, and ROADMAP.md for deferred work.