pi-goal-delegate 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +212 -0
- package/LICENSE +373 -0
- package/README.md +563 -2
- package/package.json +64 -4
- package/skills/delegate/SKILL.md +74 -0
- package/src/command.ts +487 -0
- package/src/contract.ts +629 -0
- package/src/events.ts +263 -0
- package/src/identity.ts +474 -0
- package/src/index.ts +704 -0
- package/src/registry.ts +1045 -0
- package/src/result-schema.ts +132 -0
- package/src/retention.ts +366 -0
- package/src/run.ts +1148 -0
- package/src/spawn.ts +428 -0
- package/src/supervisor.mjs +339 -0
- package/src/verify.ts +113 -0
- package/src/worker.ts +517 -0
- package/src/worktree.ts +204 -0
package/README.md
CHANGED
|
@@ -1,3 +1,564 @@
|
|
|
1
|
-
#
|
|
1
|
+
# delegate
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
One self-contained goal, handed to a fresh child agent, under a contract that
|
|
4
|
+
says when it is done and what proves it. The parent starts the delegation, gets a
|
|
5
|
+
handle in about a second, and is woken by a completion message.
|
|
6
|
+
|
|
7
|
+
This extension replaces `goal-handoff`. The primitive did not change. The
|
|
8
|
+
lifecycle around it did, and the names now say what the thing is.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
pi install npm:pi-goal-delegate # keep it: the extension and the skill
|
|
14
|
+
pi -e npm:pi-goal-delegate # try it for one session, install nothing
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
`package.json` declares `pi.extensions` and `pi.skills`, so both arrive with the
|
|
18
|
+
package. To work on it directly, add the checkout instead:
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pi -e /path/to/pi-goal-delegate/src/index.ts
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Nothing else is required. The extension has no runtime dependency of its own: it
|
|
25
|
+
starts another `pi` process with the same binary that is running it.
|
|
26
|
+
|
|
27
|
+
## Where this sits
|
|
28
|
+
|
|
29
|
+
| Layer | Owns | Does not own |
|
|
30
|
+
|---|---|---|
|
|
31
|
+
| `codemode` | Control flow over tools: `Promise.all`, loops, filtering, scripting | Processes, budgets, child agents |
|
|
32
|
+
| `pi-async-shell` | OS process supervision for commands: scope, binding, containment, durable logs | Anything about a goal or an agent |
|
|
33
|
+
| `delegate` | The contract with a fresh child agent: goal, done criteria, budget, evidence, lifecycle | Orchestration, fan-out policy, generic shell supervision |
|
|
34
|
+
|
|
35
|
+
A delegation happens to be a process, so this extension supervises one, using the
|
|
36
|
+
model `pi-async-shell` established: a detached owner for the output, a scope that
|
|
37
|
+
says who must reap, an event for completion instead of a poll, and a cancellation
|
|
38
|
+
ladder that proves absence. It borrows the model, not the code.
|
|
39
|
+
|
|
40
|
+
Fan-out belongs to `codemode`, not here:
|
|
41
|
+
|
|
42
|
+
```js
|
|
43
|
+
const handles = await Promise.all(goals.map((g) => tools.delegate_start(g)));
|
|
44
|
+
return handles.map((h) => h.runId);
|
|
45
|
+
// end the turn; the completion message wakes you when they settle
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Layout
|
|
49
|
+
|
|
50
|
+
```text
|
|
51
|
+
src/
|
|
52
|
+
index.ts tool and command registration (the file Pi discovers)
|
|
53
|
+
command.ts /delegate, the human front end for the same registry
|
|
54
|
+
registry.ts handles, claims, admission gate, coalesced completion, /reload handoff
|
|
55
|
+
run.ts admission, live tail, cancellation ladder, sealed outcome
|
|
56
|
+
spawn.ts run directory layout, child argv, detached supervisor spawn, typed reads
|
|
57
|
+
supervisor.mjs detached owner of the child output and of state.json
|
|
58
|
+
identity.ts procfs identity, process-tree fence, containment verdict
|
|
59
|
+
events.ts the child JSON event stream: turns, usage, last text
|
|
60
|
+
worker.ts child-side goal loop (loaded into the child with -e)
|
|
61
|
+
contract.ts statuses, budgets, breakers, prompt text shared by both sides
|
|
62
|
+
verify.ts the parent's own check on a completion claim
|
|
63
|
+
worktree.ts a checkout of its own for a child that asks for one
|
|
64
|
+
retention.ts reclaim run records by age, count and bytes
|
|
65
|
+
skills/
|
|
66
|
+
delegate/ the skill that teaches the workflow to an agent
|
|
67
|
+
tests/ node --test suites, plus the fake child and worker host
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`package.json` declares `pi.extensions` and `pi.skills`, so installing the
|
|
71
|
+
package gives Pi both the extension and the skill.
|
|
72
|
+
|
|
73
|
+
## Tools
|
|
74
|
+
|
|
75
|
+
### `delegate_start`
|
|
76
|
+
|
|
77
|
+
Admits the child and returns its handle. The child keeps running after the call
|
|
78
|
+
returns.
|
|
79
|
+
|
|
80
|
+
| Parameter | Default | Meaning |
|
|
81
|
+
|---|---|---|
|
|
82
|
+
| `goal` | required | The objective, self-contained. |
|
|
83
|
+
| `doneWhen` | child decides | Verifiable completion criteria. Prefer "a command exits 0", not "it works". |
|
|
84
|
+
| `context` | none | Only facts the child cannot discover: decisions, paths, constraints. Capped at 4000 characters. |
|
|
85
|
+
| `verify` | none | A command that gates `delegate_complete` in the child and is independently re-run by the parent (see [Verification](#verification)). |
|
|
86
|
+
| `resultSchema` | none | JSON Schema for the structured `result` returned through `delegate_complete`, suitable for codemode aggregation. A schema no value could satisfy (an unresolved `$ref`, a shape the validator cannot evaluate) is refused at start, because TypeBox fails closed and the child could never complete. |
|
|
87
|
+
| `maxTurns` | 150 | Model turns. One turn is one assistant response plus its tool calls. |
|
|
88
|
+
| `timeoutMinutes` | 60 | Wall-clock cap. The child enforces it too, so a workspace run is still bounded after Pi dies. |
|
|
89
|
+
| `maxCostUsd` | `PI_DELEGATE_MAX_COST_USD` | Cumulative spend cap for this run, from provider usage cost. It bounds one run, not the delegation tree; a child may not exceed its own parent's cap. 0 disables it. |
|
|
90
|
+
| `maxDepth` | 0 | Maximum absolute delegation-tree depth, 0-3. Zero disables nested delegation; children cannot raise depth, cost, or deadline limits. |
|
|
91
|
+
| `model` | parent model | `provider/id`, passed to the child explicitly (see [Model](#model)). |
|
|
92
|
+
| `tools` | inherited | Allowlist for the child. The protocol tools, and `codemode` when the parent has it, are always kept. |
|
|
93
|
+
| `cwd` | session cwd | Working directory. |
|
|
94
|
+
| `scope` | `session` | `session` dies with Pi and survives `/reload`; `workspace` outlives Pi and is re-adopted. |
|
|
95
|
+
| `isolated` | `false` | Drop ambient extensions, skills, MCP servers, and context files. |
|
|
96
|
+
| `worktree` | `false` | Give the child its own `git worktree` and branch. Requires git. |
|
|
97
|
+
| `resumeFrom` | none | Continue a previous child: a run id, or a session file path. |
|
|
98
|
+
| `inlineSettleMs` | 1000 | Hold this call open for an immediate settle, so a broken start fails here. Expiry cancels nothing. |
|
|
99
|
+
|
|
100
|
+
### `delegate_list`
|
|
101
|
+
|
|
102
|
+
Every run this session knows about, live or settled: status, turns, cost, how the
|
|
103
|
+
completion was verified, and where a resume would point. Listing claims nothing,
|
|
104
|
+
so unlike `delegate_await` it never consumes the completion message.
|
|
105
|
+
`includeSettled: false` shows only what is running.
|
|
106
|
+
|
|
107
|
+
### `delegate_send`
|
|
108
|
+
|
|
109
|
+
`delegate_send(runId, text)` hands a running child one message. The parent
|
|
110
|
+
appends it to `inbox.jsonl` in the run directory and the worker reads it at its
|
|
111
|
+
next `turn_start`. The worker immediately queues it with Pi's `deliverAs: "steer"`,
|
|
112
|
+
so Pi delivers it after the current turn's tool calls and before the next model
|
|
113
|
+
call. It works across `/reload` and across processes, and it never interrupts a
|
|
114
|
+
request already in flight. The child treats it as direction for existing work,
|
|
115
|
+
not as a new goal; it is not deferred until `agent_settled`.
|
|
116
|
+
|
|
117
|
+
### `delegate_await`
|
|
118
|
+
|
|
119
|
+
Waits up to `waitMs` (default 30000, max 50000) for one or more delegations. It
|
|
120
|
+
blocks this tool call and never cancels the work. `waitMs: 0` is a snapshot.
|
|
121
|
+
`mode: "any"` returns on the first settle; `"all"` waits for every run.
|
|
122
|
+
|
|
123
|
+
A settle reported by an await is claimed before the wait starts, so it is not
|
|
124
|
+
also announced as a message. Claims are reference counted, and an aborted wait
|
|
125
|
+
hands its settle back to the completion channel.
|
|
126
|
+
|
|
127
|
+
### `delegate_cancel`
|
|
128
|
+
|
|
129
|
+
Graceful signal, grace period (default 3000ms), process-tree fence, then a check
|
|
130
|
+
that the tree is actually gone. `containment` is a measurement, not a promise, and
|
|
131
|
+
it has three values:
|
|
132
|
+
|
|
133
|
+
| `containment` | Meaning |
|
|
134
|
+
|---|---|
|
|
135
|
+
| `gone` | The platform was observed and no process survived. |
|
|
136
|
+
| `leaked` | Some process survived; the pids are in `leakedPids`. |
|
|
137
|
+
| `unproven` | This platform exposes no process table, so absence could not be proven. Report it as unproven, never as gone. |
|
|
138
|
+
|
|
139
|
+
The three-state verdict exists because the old `verifiedGone: boolean` was `true`
|
|
140
|
+
when nothing was observable: an absence of observation read as proof of absence.
|
|
141
|
+
|
|
142
|
+
### Child-side protocol
|
|
143
|
+
|
|
144
|
+
The child gets exactly two tools that end the loop:
|
|
145
|
+
|
|
146
|
+
- `delegate_complete(summary, evidence, result?)` - completion-gated done. Evidence is commands, files, checks; `result` is validated when `resultSchema` is present.
|
|
147
|
+
- `delegate_blocked(reason, needs)` - a decision, credential, or fact the child cannot obtain.
|
|
148
|
+
|
|
149
|
+
Foreign goal tools (`goal_complete`, `goal_blocked`, `goal_wait`, the old
|
|
150
|
+
`goal_handoff_*`) are deactivated in the child. A delegated child has one goal
|
|
151
|
+
protocol.
|
|
152
|
+
|
|
153
|
+
## Waiting: three rules
|
|
154
|
+
|
|
155
|
+
1. **Starting is not waiting.** `delegate_start` waits for admission plus a
|
|
156
|
+
bounded inline window, and then returns. It never waits for the goal.
|
|
157
|
+
2. **A tool-call wait is bounded and narrow.** `delegate_await` blocks at most 50
|
|
158
|
+
seconds, because a `codemode` script has a 60-second budget. Its expiry
|
|
159
|
+
cancels nothing.
|
|
160
|
+
3. **The long wait is ending the turn.** The completion arrives as a
|
|
161
|
+
`delegate-completion` message, coalesced over 150ms and steered in before the
|
|
162
|
+
next model call. One message for twelve runs is one decision, not twelve.
|
|
163
|
+
|
|
164
|
+
The rule exists because a goal takes minutes. Across 42 recorded runs, 100% ran
|
|
165
|
+
longer than 60 seconds: minimum 222s, median 1102s (18 minutes), maximum 6270s
|
|
166
|
+
(104 minutes). A start call that waits for the goal is a start call that times
|
|
167
|
+
out, so the old tool forced every `codemode` caller to override `timeout_ms` into
|
|
168
|
+
the hours and risk aborting a healthy child.
|
|
169
|
+
|
|
170
|
+
## Lifecycle
|
|
171
|
+
|
|
172
|
+
| Status | Who decides | Meaning |
|
|
173
|
+
|---|---|---|
|
|
174
|
+
| `starting` | parent | Admitted, no event seen yet. |
|
|
175
|
+
| `running` | parent, from the child stream | Turns are arriving. |
|
|
176
|
+
| `complete` | child | `delegate_complete`, and the `verify` command, if any, exited 0. |
|
|
177
|
+
| `unverified` | parent | The child said complete, and the parent ran `verify` and it failed. |
|
|
178
|
+
| `blocked` | child | `delegate_blocked`. The outcome carries `needs`, not `evidence`. |
|
|
179
|
+
| `no_progress` | child or parent | Circuit breaker: repeated identical call, consecutive failures, or two identical no-tool turns. |
|
|
180
|
+
| `limit` | child or parent | Turn budget or spend cap reached. The child fences itself before the next request, not at the idle boundary; the parent's copy of the same rule is a runaway net with a two-turn grace. |
|
|
181
|
+
| `timeout` | parent and child | Wall clock. Parent enforces with the ladder; child enforces on its own for `workspace` runs. |
|
|
182
|
+
| `aborted` | parent | `delegate_cancel`. |
|
|
183
|
+
| `error` | parent | Spawn failure, child crash, provider error, or no verdict at all. |
|
|
184
|
+
| `lost` | parent | Adopted workspace record with no exit and no provable liveness. Never reported as complete. |
|
|
185
|
+
|
|
186
|
+
Only `complete` and `blocked` are delegations that delivered what they were
|
|
187
|
+
given. Everything else is a failure, and `isFailure` in `contract.ts` is the one
|
|
188
|
+
definition the tools, the command, and `isError` on a tool result all share: a
|
|
189
|
+
`no_progress` or `limit` run used to be reported with `isError: false`, so an
|
|
190
|
+
orchestrator branching on `isError` read a stalled child as a finished one.
|
|
191
|
+
|
|
192
|
+
## Verification
|
|
193
|
+
|
|
194
|
+
`doneWhen` is prose for the child. `verify` is an executable completion gate for
|
|
195
|
+
both sides:
|
|
196
|
+
|
|
197
|
+
```js
|
|
198
|
+
await tools.delegate_start({
|
|
199
|
+
goal: "Make the parser stream instead of buffering",
|
|
200
|
+
verify: "pnpm test --filter parser"
|
|
201
|
+
});
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
`delegate_complete` first runs the command in the child's directory. A failure
|
|
205
|
+
is returned to the child as a tool error containing the command output, and the
|
|
206
|
+
run continues so the child can repair the cause and retry. Only a passing claim
|
|
207
|
+
terminates the child. The parent then independently runs the same command before
|
|
208
|
+
accepting the outcome, using the same `PI_DELEGATE_ENV_DROP` policy so verification
|
|
209
|
+
cannot regain credentials withheld from the child.
|
|
210
|
+
|
|
211
|
+
The parent's recheck records `verified`:
|
|
212
|
+
|
|
213
|
+
| `verified` | Meaning |
|
|
214
|
+
|---|---|
|
|
215
|
+
| `true` | The command exited 0. |
|
|
216
|
+
| `false` | It exited non-zero, could not start, or timed out (`PI_DELEGATE_VERIFY_TIMEOUT_MS`, default 120000). The status becomes `unverified`. |
|
|
217
|
+
| `"not-run"` | The run carried no verify command, so the evidence is the child's own account and nothing more. |
|
|
218
|
+
|
|
219
|
+
The child's summary and evidence survive a contradiction: the parent records that
|
|
220
|
+
its own check failed, not that the child never spoke. `childVerification` preserves
|
|
221
|
+
the successful child-side gate separately from the parent's `verification` record.
|
|
222
|
+
|
|
223
|
+
## Budgets, and why the defaults are these numbers
|
|
224
|
+
|
|
225
|
+
`maxTurns` counts model turns. Real delegations, measured from the child session
|
|
226
|
+
files of 42 runs: minimum 25, median 110, p90 217, maximum 296. The default is 150
|
|
227
|
+
and the hard maximum is 500. The old default of 20 counted user messages, so it
|
|
228
|
+
recorded `turns: 1` for a 265-turn session and bounded nothing.
|
|
229
|
+
|
|
230
|
+
`timeoutMinutes` defaults to 60. A 30-minute cap would have cut 14 of those 42
|
|
231
|
+
runs; 60 minutes keeps 90% of them.
|
|
232
|
+
|
|
233
|
+
Circuit breakers run in both the child and the parent's compact event observer:
|
|
234
|
+
the third identical tool call is blocked in the child, the sixth ends the run,
|
|
235
|
+
eight consecutive tool errors end the run, and two consecutive turns with the
|
|
236
|
+
same answer and no tool calls end the run. They live in
|
|
237
|
+
`contract.ts` as pure functions over one state record, because the parent reads
|
|
238
|
+
the same rules from the child's event stream and two copies of a threshold is two
|
|
239
|
+
answers to "was this run stuck".
|
|
240
|
+
|
|
241
|
+
### Admission: how many children at once
|
|
242
|
+
|
|
243
|
+
One session may keep `PI_DELEGATE_MAX_LIVE` delegations live, four by default,
|
|
244
|
+
thirty-two at most. A `Promise.all` over fifty goals used to start fifty children,
|
|
245
|
+
each with its own process, model stream, and budget; the fifty-first is now
|
|
246
|
+
refused with the live runs named:
|
|
247
|
+
|
|
248
|
+
```text
|
|
249
|
+
Too many live delegations: 4 of 4 already running.
|
|
250
|
+
- dl_mx38p4q3_e48a8e01 (2m03s, 41/150 turns)
|
|
251
|
+
Wait for one to settle, cancel one with delegate_cancel, or raise
|
|
252
|
+
PI_DELEGATE_MAX_LIVE (currently 4, maximum 32).
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
The gate counts live runs plus starts synchronously reserved during admission,
|
|
256
|
+
not lifetime runs: concurrent starts cannot pass before their handles register,
|
|
257
|
+
and cancelling frees a slot immediately. A malformed value falls back to the default rather than to
|
|
258
|
+
"unlimited".
|
|
259
|
+
|
|
260
|
+
### Cost
|
|
261
|
+
|
|
262
|
+
`maxCostUsd` caps cumulative spend, read from provider usage cost as the run
|
|
263
|
+
streams. The parent checks the same limit the child does, and a run that crosses it
|
|
264
|
+
ends as `limit` with the amount in the summary. It is off by default
|
|
265
|
+
(`PI_DELEGATE_MAX_COST_USD=0`): a cap that kills a healthy run by default is worse
|
|
266
|
+
than no cap.
|
|
267
|
+
|
|
268
|
+
The cap is per run. A nested child may not choose a cap larger than its own
|
|
269
|
+
parent's, but nothing sums a tree: four grandchildren with a $2 cap each can spend
|
|
270
|
+
$8 between them, and the parent's own cap is unaffected. Treat `maxDepth` and
|
|
271
|
+
`maxTurns` as the tree-wide bound and `maxCostUsd` as the per-run ceiling.
|
|
272
|
+
|
|
273
|
+
## Parallel children and worktrees
|
|
274
|
+
|
|
275
|
+
Two children editing one working tree fight over every file: a build in one
|
|
276
|
+
rewrites what the other is reading, and `git status` in either reports the
|
|
277
|
+
other's work. `worktree: true` gives the child its own checkout:
|
|
278
|
+
|
|
279
|
+
```js
|
|
280
|
+
await tools.delegate_start({ goal: "...", worktree: true });
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
The parent runs `git worktree add --no-track -b delegate/<runId>
|
|
284
|
+
<agentDir>/delegate/worktrees/<runId> HEAD` in the session directory and starts
|
|
285
|
+
the child there. The outcome records `worktree: { path, branch, repo, base }` and
|
|
286
|
+
`integration`: HEAD, dirty status, diff statistics, `changes.patch`, and the
|
|
287
|
+
result of `git apply --check` against the original repository. The patch includes
|
|
288
|
+
committed, tracked-uncommitted, and untracked work. Nothing is automatically
|
|
289
|
+
committed or merged; `integration.applyCommand` is the explicit integration path.
|
|
290
|
+
|
|
291
|
+
The checkout is **kept by default**: it holds the only copy of the child's work.
|
|
292
|
+
`PI_DELEGATE_KEEP_WORKTREES=0` opts into cleanup, and even then only a clean tree
|
|
293
|
+
is removed. A worktree inside the record root is removed with its record by
|
|
294
|
+
retention, but only when clean and no other run record references it. A dirty
|
|
295
|
+
worktree and its pointer record are both preserved. A directory that is not a git
|
|
296
|
+
repository, or a repository with no commit, fails the start with git's own message
|
|
297
|
+
rather than silently falling back to the shared tree.
|
|
298
|
+
|
|
299
|
+
## Resuming a run
|
|
300
|
+
|
|
301
|
+
`outcome.sessionFile` is the child's own Pi session. `delegate_start({ resumeFrom:
|
|
302
|
+
runId })` resolves it and passes `--session <path>` to the new child, so a second
|
|
303
|
+
delegation continues the first one's context instead of starting cold. When the
|
|
304
|
+
previous run used a worktree, the resumed run automatically keeps that checkout
|
|
305
|
+
as its cwd instead of moving back to the shared tree. `resumedFrom` records the
|
|
306
|
+
lineage. A session file path or a session id is accepted as-is; an unknown value
|
|
307
|
+
is passed through rather than guessed at. A resume is a new run with a new budget,
|
|
308
|
+
not a reopening of the sealed run record.
|
|
309
|
+
|
|
310
|
+
## Model
|
|
311
|
+
|
|
312
|
+
The parent passes its model to the child explicitly with `--model` and its
|
|
313
|
+
thinking level with `--thinking`. Inheritance by omission does not work: a child
|
|
314
|
+
started without `--model` falls back to `settings.json` `defaultModel`, which is
|
|
315
|
+
not the parent session model. `modelSource` in the outcome records which one ran:
|
|
316
|
+
`explicit`, `inherited`, or `default`.
|
|
317
|
+
|
|
318
|
+
## Accounting
|
|
319
|
+
|
|
320
|
+
Every outcome carries `turns`, `toolCalls`, and `usage` (`input`, `output`,
|
|
321
|
+
`cacheRead`, `cacheWrite`, `totalTokens`, `cost`). The numbers are folded from the
|
|
322
|
+
child's own JSON event stream, and the child writes the same numbers into
|
|
323
|
+
`result.json`, so a killed run still reports what was spent up to the kill. Across
|
|
324
|
+
the recorded runs the cost was $0.08 to $2.42 per delegation.
|
|
325
|
+
|
|
326
|
+
## Supervision
|
|
327
|
+
|
|
328
|
+
`delegate_start` spawns `supervisor.mjs`, a detached Node process in its own
|
|
329
|
+
session. The supervisor owns the child stdout and stderr and writes
|
|
330
|
+
`child.jsonl`, `child.log`, and the compact accounting stream `control.jsonl`. Pi holds no pipe to the child, which is what makes
|
|
331
|
+
the rest possible:
|
|
332
|
+
|
|
333
|
+
- **`/reload` transfers ownership.** The live registry is published to a
|
|
334
|
+
process-global slot keyed by `(pid, sessionId, cwd)`; the next activation claims
|
|
335
|
+
it and rebinds its UI callbacks. Nothing restarts, no byte is lost. A slot that
|
|
336
|
+
nobody claims within 30 seconds expires into cancellation, so a handle is never
|
|
337
|
+
left unowned.
|
|
338
|
+
- **`session_shutdown` reaps session runs.** The supervisor watches fd 3. EOF means
|
|
339
|
+
the owning Pi died, so the tree is torn down. Bytes on fd 3 are not a protocol;
|
|
340
|
+
`/reload` transfers the in-process registry without changing supervisor ownership.
|
|
341
|
+
- **`scope: "workspace"` survives Pi.** No fd 3, no owner watch. On the next
|
|
342
|
+
`session_start` in the same directory, a run whose owner identity is dead is
|
|
343
|
+
re-adopted: the event log is folded, the tail resumes, and the settle is
|
|
344
|
+
delivered here. A run whose owner is alive is read-only. A record with no exit
|
|
345
|
+
and no provable liveness becomes `lost`.
|
|
346
|
+
- **Logs drain past the cap.** 32 MiB per stream by default. Past the cap the
|
|
347
|
+
supervisor stops appending the raw payload and keeps reading, because a reader
|
|
348
|
+
that stops reading turns a logging policy into a hung child. It still writes
|
|
349
|
+
compact turn, usage, cost, and breaker records to `control.jsonl`, so a capped
|
|
350
|
+
payload log cannot blind the parent's budgets or no-progress enforcement.
|
|
351
|
+
- **The fence is the containment guarantee, where a process table exists.**
|
|
352
|
+
Cancellation unions three views: processes tagged `PI_DELEGATE_RUN=<id>`, live
|
|
353
|
+
descendants of the captured `(boot_id, pid, start)` identity, and live members
|
|
354
|
+
of the owned process group. Each pid start time is re-read before signalling, so
|
|
355
|
+
a reused pid is never killed. A process group alone is not containment:
|
|
356
|
+
`setsid(2)` escapes it. Off Linux the group is what is left, and it is enough to
|
|
357
|
+
kill: `spawn(detached: true)` makes the supervisor a session leader, so its pid
|
|
358
|
+
*is* the process group id and `kill(-pgid)` reaches the whole tree without asking
|
|
359
|
+
the kernel anything.
|
|
360
|
+
- **The group handle is not a guess.** `pgidFor()` returns the detached
|
|
361
|
+
supervisor's own pid on POSIX. It used to be read from `/proc/<pid>/stat`, which
|
|
362
|
+
meant every non-Linux platform had an empty group list, so `killGroup` had
|
|
363
|
+
nothing to signal and the cancel still reported success.
|
|
364
|
+
|
|
365
|
+
## Permission asks
|
|
366
|
+
|
|
367
|
+
The child is started with `PI_SUBAGENT_PARENT_SESSION=<session id>`, the
|
|
368
|
+
convention `@gotgenes/pi-permission-system` documents for out-of-process
|
|
369
|
+
subagents. A gated tool call in the child is forwarded to the delegating session,
|
|
370
|
+
so authority stays with the human instead of failing closed with "no interactive
|
|
371
|
+
UI is available". Without a human to answer, the child reports `blocked`. The
|
|
372
|
+
marker is never overwritten when one is already present, so a chain of
|
|
373
|
+
delegations relays through the middle hop.
|
|
374
|
+
|
|
375
|
+
This is a declared dependency on another package's environment convention, not on
|
|
376
|
+
its code. It is why a delegated child is not a security boundary of its own:
|
|
377
|
+
|
|
378
|
+
- **Nothing here reads or writes that extension.** This package sets one
|
|
379
|
+
environment variable and `@gotgenes/pi-permission-system` reads it. If that
|
|
380
|
+
package is not installed, the variable is inert and nothing changes.
|
|
381
|
+
- **The convention can move.** If that package changes the variable name, gated
|
|
382
|
+
calls in the child fall back to whatever that extension does by default
|
|
383
|
+
(usually "deny, no interactive UI"), and the child reports `blocked`. It does
|
|
384
|
+
not become silently permissive.
|
|
385
|
+
- **A different permission extension sees nothing.** Another implementation of
|
|
386
|
+
permission gating will not honour this marker, so an approval ask from a child
|
|
387
|
+
fails closed there. `isolated: true` is the other answer for a host that cannot
|
|
388
|
+
answer asks at all: built-in tools only, no ambient extension, skill, MCP
|
|
389
|
+
server, or AGENTS.md.
|
|
390
|
+
|
|
391
|
+
`isolated: true` is the other answer for a host that cannot answer asks: the child
|
|
392
|
+
runs with built-in tools only, no ambient extension, skill, MCP server, or
|
|
393
|
+
AGENTS.md.
|
|
394
|
+
|
|
395
|
+
## Command
|
|
396
|
+
|
|
397
|
+
```text
|
|
398
|
+
/delegate Fix the login error handling and add a regression test --turns 60
|
|
399
|
+
/delegate Update every caller of parseConfig --done "tests pass" --model mistral/ministral-8b-latest
|
|
400
|
+
/delegate list delegations in this session
|
|
401
|
+
/delegate read <id|prefix> one run in full
|
|
402
|
+
/delegate log <id|prefix> tail the child stderr
|
|
403
|
+
/delegate cancel <id|prefix|all> cancel with the ladder
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
Options may appear anywhere, as `--name value` or `--name=value`: `--model`,
|
|
407
|
+
`--turns`, `--minutes`, `--cost`, `--done`, `--context`, `--verify`,
|
|
408
|
+
`--tools`, `--scope`, `--isolated`, `--worktree`, `--resume`, `--cwd`, `--depth`,
|
|
409
|
+
`--schema`. `--verify` is the same completion gate the tool takes: it runs inside
|
|
410
|
+
the child at `delegate_complete`, and the parent re-runs it with the child's
|
|
411
|
+
dropped-environment policy before the claim is accepted.
|
|
412
|
+
`/delegate send <id> <text>` is the steering path, the same as `delegate_send`.
|
|
413
|
+
The command accepts what the tool schema accepts:
|
|
414
|
+
`--turns` is 1-500, `--minutes` is 1-240, and a relative `--cwd` resolves
|
|
415
|
+
against the session directory rather than the process working directory. A bare
|
|
416
|
+
`--` ends option parsing, so a goal may contain its own `--words`.
|
|
417
|
+
|
|
418
|
+
Outside the TUI the command waits for the outcome and prints it, because nothing
|
|
419
|
+
else keeps a print-mode process alive for a session-scoped child.
|
|
420
|
+
|
|
421
|
+
## Artifacts
|
|
422
|
+
|
|
423
|
+
`~/.pi/agent/delegate/<runId>/` (`PI_DELEGATE_HOME` overrides the root):
|
|
424
|
+
|
|
425
|
+
| File | Written by | Meaning |
|
|
426
|
+
|---|---|---|
|
|
427
|
+
| `spec.json` | parent | The exact contract the child received, including the child command line. Written once, at admission. |
|
|
428
|
+
| `meta.json` | parent | Scope, status, session directory, supervisor identity, owner identity, containment mode. |
|
|
429
|
+
| `state.json` | supervisor | Pid, process group, cap, exit, sealed-at. The one record of the child process, sealed atomically. |
|
|
430
|
+
| `child.jsonl` | supervisor | The raw child JSON event stream, capped at 32 MiB. |
|
|
431
|
+
| `control.jsonl` | supervisor | Compact turn, usage, cost, text, and breaker events. Written even after the raw cap; this is the parent's accounting source. |
|
|
432
|
+
| `child.log` | supervisor | The child stderr. |
|
|
433
|
+
| `result.json` | child | The verdict: status, summary, evidence or needs, turns, usage, session file. |
|
|
434
|
+
| `outcome.json` | parent | The sealed outcome, including structured result and integration metadata, readable after the parent is gone. |
|
|
435
|
+
| `changes.patch` | parent | For worktree runs with changes: committed, tracked, and untracked work exported without an automatic commit. |
|
|
436
|
+
| `inbox.jsonl` | parent | Steering messages, one JSON line each. The child reads the file at `turn_start`. |
|
|
437
|
+
| `owner.lock` | parent | The adoption claim, created with `O_EXCL`. One owner at a time. |
|
|
438
|
+
|
|
439
|
+
Each file has exactly one writer. `state.json` replaced `pid.json`, `exit.json` and
|
|
440
|
+
`log-cap.json`, which described the same process in three files that a reader had
|
|
441
|
+
to merge: two writers of one fact is how they disagree. Records written by a
|
|
442
|
+
previous version are still read.
|
|
443
|
+
|
|
444
|
+
Each run directory is created `0700` and every record inside it is written
|
|
445
|
+
`0600`. The record holds the goal, the context note, and the child's full output
|
|
446
|
+
on a possibly shared machine, so it is private to the user who started it.
|
|
447
|
+
|
|
448
|
+
Nothing reads a directory after its outcome is sealed, and records are reclaimed
|
|
449
|
+
automatically. Retention is bounded three times: a record older than
|
|
450
|
+
`PI_DELEGATE_RETENTION_DAYS` (default 7) is removed, once the count passes
|
|
451
|
+
`PI_DELEGATE_MAX_RUNS` (default 100) the oldest surplus is removed, and once the
|
|
452
|
+
total passes `PI_DELEGATE_MAX_BYTES` (default 512 MiB) the oldest records are
|
|
453
|
+
removed until it fits. The byte cap is the one that bounds the worst case:
|
|
454
|
+
32 MiB of stdout and 32 MiB of stderr per run times a hundred kept runs is 6.4 GB
|
|
455
|
+
that no count or age limit ever reached.
|
|
456
|
+
|
|
457
|
+
A record is never removed while it can still produce a verdict: a run this
|
|
458
|
+
process follows, a record whose supervisor is alive, or one younger than ten
|
|
459
|
+
minutes. Deleting a record removes a worktree inside the record root only through
|
|
460
|
+
`git worktree remove`, only when it is clean, and only when no other run references
|
|
461
|
+
it. A dirty checkout and its record stay in place. Delete old runs whenever you
|
|
462
|
+
like; the next session prunes the rest.
|
|
463
|
+
|
|
464
|
+
Runs recorded before this rename stay in `~/.pi/agent/goal-handoff/`. Nothing
|
|
465
|
+
reads them, and the old extension is retired to
|
|
466
|
+
`~/.pi/agent/retired-extensions/goal-handoff/`.
|
|
467
|
+
|
|
468
|
+
### Environment
|
|
469
|
+
|
|
470
|
+
| Variable | Meaning |
|
|
471
|
+
|---|---|
|
|
472
|
+
| `PI_DELEGATE_HOME` | Run-record root. Default `<agentDir>/delegate`. |
|
|
473
|
+
| `PI_DELEGATE_MAX_RUNS` | Run records kept after pruning. Default 100. |
|
|
474
|
+
| `PI_DELEGATE_RETENTION_DAYS` | Age at which a run record is removed. Default 7; 0 disables the age rule. |
|
|
475
|
+
| `PI_DELEGATE_MAX_BYTES` | Total bytes across every run record. Default 536870912 (512 MiB); 0 disables the size rule. |
|
|
476
|
+
| `PI_DELEGATE_MAX_LIVE` | Concurrent delegations in one session. Default 4, maximum 32. |
|
|
477
|
+
| `PI_DELEGATE_MAX_COST_USD` | Default cumulative spend cap per run, in US dollars. Default 0 (off). |
|
|
478
|
+
| `PI_DELEGATE_VERIFY_TIMEOUT_MS` | Timeout for the `verify` command. Default 120000. |
|
|
479
|
+
| `PI_DELEGATE_KEEP_WORKTREES` | Set to `0` to remove a clean worktree when its run settles. Default: keep. |
|
|
480
|
+
| `PI_DELEGATE_PI_ENTRY` | JavaScript entry for the child, when `process.argv[1]` is not it. |
|
|
481
|
+
| `PI_DELEGATE_PI_COMMAND` | Executable that starts the child, for a launcher that hides its own entry. |
|
|
482
|
+
| `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. |
|
|
483
|
+
| `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. |
|
|
484
|
+
| `PI_SUBAGENT_PARENT_SESSION` | Set for the child unless one is already present. Names the session that answers forwarded permission asks. |
|
|
485
|
+
|
|
486
|
+
## Tests
|
|
487
|
+
|
|
488
|
+
From the repository root:
|
|
489
|
+
|
|
490
|
+
```bash
|
|
491
|
+
pnpm install
|
|
492
|
+
pnpm run typecheck # tsc --noEmit over src/ and tests/
|
|
493
|
+
pnpm test # every suite below
|
|
494
|
+
pnpm run test:coverage
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
| Suite | Covers |
|
|
498
|
+
|---|---|
|
|
499
|
+
| `tests/delegate.test.mjs` | lifecycle, event folding, containment, claims, the cancellation grace period, the status footer, reload |
|
|
500
|
+
| `tests/command.test.mjs` | `/delegate` parsing, quoting, prefix resolution, every cancel form, the TUI and print paths |
|
|
501
|
+
| `tests/worker.test.mjs` | the child's circuit breakers and terminal states, in a real subprocess |
|
|
502
|
+
| `tests/events.test.mjs` | the event stream: unknown records, error carriers, the incremental tailer |
|
|
503
|
+
| `tests/isolation.test.mjs` | directory-scoped workspace adoption, per-session registries |
|
|
504
|
+
| `tests/adoption.test.mjs` | re-adoption against a supervisor that is actually running |
|
|
505
|
+
| `tests/failure.test.mjs` | wall-clock deadlines, a supervisor killed from outside, an exit with no verdict |
|
|
506
|
+
| `tests/retention.test.mjs` | age and count pruning, live-run protection |
|
|
507
|
+
| `tests/supervisor.test.mjs` | sealed exit records, controlled exit, log cap, the owner watch |
|
|
508
|
+
| `tests/tool-e2e.test.mjs` | the real loader, tool schemas, every `delegate_await` and `delegate_cancel` mode, `/reload` |
|
|
509
|
+
| `tests/guard.test.mjs` | the child-side recursion guard, parameter validation, declared bounds |
|
|
510
|
+
| `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. |
|
|
511
|
+
| `tests/gates.test.mjs` | the live-admission gate, the spend cap, verified completion, the adoption claim, steering, worktrees, and typed record reads |
|
|
512
|
+
| `tests/result-schema.test.mjs` | the `resultSchema` admission audit and the instance path a rejected value is told |
|
|
513
|
+
|
|
514
|
+
`tests/support.mjs` holds what every suite needs: temporary directories removed
|
|
515
|
+
when the test ends, the `PI_DELEGATE_*` environment restored after each test, and
|
|
516
|
+
`waitFor` in place of fixed sleeps. 188 tests, no model and no network.
|
|
517
|
+
|
|
518
|
+
CI runs the whole suite on Linux against Node 22, 24 and 26, and runs
|
|
519
|
+
`tests/containment.test.mjs` plus `tests/gates.test.mjs` on `macos-latest`: those
|
|
520
|
+
are the suites that exercise cancellation and adoption where `/proc` does not
|
|
521
|
+
exist, which is exactly the platform where absence used to be reported as proof.
|
|
522
|
+
|
|
523
|
+
No suite needs a model or a network. The lifecycle suites spawn the fake child in
|
|
524
|
+
`tests/fixtures/fake-pi.mjs`, which emits a real JSON event stream and seals a
|
|
525
|
+
real verdict, and which can also refuse SIGTERM so a grace period is observable; the worker suite drives the real `worker.ts` through
|
|
526
|
+
`tests/fixtures/worker-host.mjs`. The e2e suite loads the extension through Pi's
|
|
527
|
+
own loader and resolves Pi's host packages from an explicit `PI_HOST_MODULES`
|
|
528
|
+
override first, then from the project's own `node_modules`, then from the newest
|
|
529
|
+
`~/.pi/agent/managed-runtime/releases` entry, so a clean clone with
|
|
530
|
+
`pnpm install` runs it with no configuration.
|
|
531
|
+
|
|
532
|
+
## Limits
|
|
533
|
+
|
|
534
|
+
- **Containment is platform-dependent, and the verdict says which one ran.**
|
|
535
|
+
Linux gets full observation: procfs identity, the tag scan, the descendant walk,
|
|
536
|
+
and the owned process group. macOS and other POSIX platforms get the process
|
|
537
|
+
group, which the detached supervisor leads, probed with signal 0: cancellation
|
|
538
|
+
works, and the verdict is `gone` or `leaked` on real evidence. Windows gets
|
|
539
|
+
`taskkill /T` and no observation, so its verdict is `unproven` — the tree is
|
|
540
|
+
asked to die and the parent says so instead of claiming proof. A `setsid(2)`
|
|
541
|
+
child that also clears its environment and loses its parent is out of reach on
|
|
542
|
+
any platform.
|
|
543
|
+
- **A delegation is not a sandbox.** The child runs with the parent's authority,
|
|
544
|
+
in the parent's filesystem, with the parent's environment (minus
|
|
545
|
+
`PI_DELEGATE_ENV_DROP`). `tools` and `isolated` bound the surface, not the
|
|
546
|
+
permission.`
|
|
547
|
+
- **A session-scoped run cannot outlive the session.** Use `workspace` for that.
|
|
548
|
+
In print mode a session run is cancelled when the process exits, so a print
|
|
549
|
+
caller should await it.
|
|
550
|
+
- **`isolated: true` also drops provider extensions.** A custom provider that
|
|
551
|
+
lives in an extension is unavailable to an isolated child.
|
|
552
|
+
- **A delegated child inherits the parent filesystem and network permissions.**
|
|
553
|
+
Tool allowlists bound the surface, not the sandbox.
|
|
554
|
+
- **`delegate_await` blocks the tool call.** A tool call cannot be suspended here.
|
|
555
|
+
Waits measured in minutes belong to the completion message.
|
|
556
|
+
- **The workspace adoption scan reads the global run root.** A record is adopted
|
|
557
|
+
only when it was started by this session's directory (its recorded session
|
|
558
|
+
directory, or the child `cwd` for a record written before that field existed;
|
|
559
|
+
both are compared through `realpath`), and its owner is gone. Two sessions in
|
|
560
|
+
different directories never adopt each other's runs, and a record from a deleted
|
|
561
|
+
directory is never adopted.
|
|
562
|
+
- **The no-progress rule is a heuristic.** Two identical answers with no tool call
|
|
563
|
+
end the run in either observer; a child that varies its wording while doing
|
|
564
|
+
nothing can still consume its turn budget.
|
package/package.json
CHANGED
|
@@ -1,6 +1,66 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-goal-delegate",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Bounded delegation for Pi: one self-contained goal, a fresh child agent, and a contract that says when it is done and what proves it.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MPL-2.0",
|
|
7
|
+
"author": "Zhuocheng-Lang <2435060515@st.usst.edu.cn>",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"pi-package",
|
|
10
|
+
"pi-extension",
|
|
11
|
+
"pi-skill",
|
|
12
|
+
"pi",
|
|
13
|
+
"delegate",
|
|
14
|
+
"subagent",
|
|
15
|
+
"orchestration",
|
|
16
|
+
"agent"
|
|
17
|
+
],
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/Zhuocheng-Lang/pi-goal-delegate.git"
|
|
21
|
+
},
|
|
22
|
+
"homepage": "https://github.com/Zhuocheng-Lang/pi-goal-delegate#readme",
|
|
23
|
+
"bugs": {
|
|
24
|
+
"url": "https://github.com/Zhuocheng-Lang/pi-goal-delegate/issues"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"src/",
|
|
31
|
+
"skills/",
|
|
32
|
+
"README.md",
|
|
33
|
+
"CHANGELOG.md",
|
|
34
|
+
"LICENSE"
|
|
35
|
+
],
|
|
36
|
+
"pi": {
|
|
37
|
+
"extensions": [
|
|
38
|
+
"./src/index.ts"
|
|
39
|
+
],
|
|
40
|
+
"skills": [
|
|
41
|
+
"./skills"
|
|
42
|
+
],
|
|
43
|
+
"changelogPath": "./CHANGELOG.md"
|
|
44
|
+
},
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=22.19.0"
|
|
47
|
+
},
|
|
48
|
+
"packageManager": "pnpm@12.23.0",
|
|
49
|
+
"peerDependencies": {
|
|
50
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
51
|
+
"typebox": "*"
|
|
52
|
+
},
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@earendil-works/pi-ai": "^1.6.0",
|
|
55
|
+
"@earendil-works/pi-coding-agent": "^1.6.0",
|
|
56
|
+
"@types/node": "^26.6.7",
|
|
57
|
+
"typebox": "^1.4.7",
|
|
58
|
+
"typescript": "^7.0.2"
|
|
59
|
+
},
|
|
60
|
+
"scripts": {
|
|
61
|
+
"test": "node --test tests/*.test.mjs",
|
|
62
|
+
"test:coverage": "node --test --experimental-test-coverage tests/*.test.mjs",
|
|
63
|
+
"typecheck": "tsc --noEmit && tsc -p tsconfig.tests.json --noEmit",
|
|
64
|
+
"verify": "pnpm run typecheck && pnpm test"
|
|
65
|
+
}
|
|
66
|
+
}
|