@ftrdotdev/pi-delegates 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.
Files changed (138) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/LICENSE +21 -0
  3. package/OPERATIONS.md +130 -0
  4. package/README.md +456 -2
  5. package/ROADMAP.md +179 -0
  6. package/TESTING.md +896 -0
  7. package/agents.ts +8 -0
  8. package/examples/README.md +114 -0
  9. package/examples/gated.ts +28 -0
  10. package/index.ts +9 -0
  11. package/package.json +94 -4
  12. package/skills/pi-delegates/SKILL.md +176 -0
  13. package/skills/pi-delegates/references/control.md +159 -0
  14. package/skills/pi-delegates/references/definitions.md +163 -0
  15. package/skills/pi-delegates/references/gates.md +175 -0
  16. package/skills/pi-delegates/references/launch.md +184 -0
  17. package/src/docs-contract.test.ts +106 -0
  18. package/src/domain/definitions.test.ts +41 -0
  19. package/src/domain/definitions.ts +163 -0
  20. package/src/domain/failure.ts +33 -0
  21. package/src/domain/ids.ts +13 -0
  22. package/src/domain/model-source.ts +30 -0
  23. package/src/domain/names.ts +35 -0
  24. package/src/domain/orchestration/admission.ts +78 -0
  25. package/src/domain/orchestration/control.test.ts +1332 -0
  26. package/src/domain/orchestration/control.ts +457 -0
  27. package/src/domain/orchestration/fanout.test.ts +524 -0
  28. package/src/domain/orchestration/fanout.ts +372 -0
  29. package/src/domain/orchestration/gates.test.ts +685 -0
  30. package/src/domain/orchestration/gates.ts +360 -0
  31. package/src/domain/orchestration/launch.test.ts +372 -0
  32. package/src/domain/orchestration/launch.ts +691 -0
  33. package/src/domain/orchestration/requests.test.ts +695 -0
  34. package/src/domain/orchestration/requests.ts +782 -0
  35. package/src/domain/orchestration/review.test.ts +292 -0
  36. package/src/domain/orchestration/review.ts +168 -0
  37. package/src/domain/orchestration/run-wait.test.ts +265 -0
  38. package/src/domain/orchestration/run-wait.ts +256 -0
  39. package/src/domain/orchestration/workflow-section.test.ts +62 -0
  40. package/src/domain/orchestration/workflow-section.ts +99 -0
  41. package/src/domain/orchestration/workflow.test.ts +1566 -0
  42. package/src/domain/orchestration/workflow.ts +778 -0
  43. package/src/domain/run-records.test.ts +27 -0
  44. package/src/domain/run-records.ts +689 -0
  45. package/src/domain/settlement.test.ts +186 -0
  46. package/src/domain/settlement.ts +137 -0
  47. package/src/domain/shapes.test.ts +185 -0
  48. package/src/domain/skills.test.ts +477 -0
  49. package/src/domain/skills.ts +114 -0
  50. package/src/domain/tool-schema.test.ts +46 -0
  51. package/src/domain/tool-schema.ts +20 -0
  52. package/src/domain/toolkit.test.ts +215 -0
  53. package/src/domain/toolkit.ts +374 -0
  54. package/src/domain/turn-budget.test.ts +37 -0
  55. package/src/domain/turn-budget.ts +23 -0
  56. package/src/domain/view.test.ts +803 -0
  57. package/src/domain/view.ts +491 -0
  58. package/src/example.test.ts +15 -0
  59. package/src/extension/commands.test.ts +485 -0
  60. package/src/extension/commands.ts +230 -0
  61. package/src/extension/entry.test.ts +1276 -0
  62. package/src/extension/entry.ts +380 -0
  63. package/src/extension/gate-alerts.test.ts +237 -0
  64. package/src/extension/gate-alerts.ts +143 -0
  65. package/src/extension/guard.test.ts +48 -0
  66. package/src/extension/guard.ts +31 -0
  67. package/src/extension/host-signals.test.ts +20 -0
  68. package/src/extension/host-signals.ts +13 -0
  69. package/src/extension/inspector-command.test.ts +1343 -0
  70. package/src/extension/inspector-command.ts +685 -0
  71. package/src/extension/prompt.test.ts +108 -0
  72. package/src/extension/prompt.ts +50 -0
  73. package/src/extension/request-alerts.test.ts +183 -0
  74. package/src/extension/request-alerts.ts +181 -0
  75. package/src/extension/retry-observer.test.ts +292 -0
  76. package/src/extension/retry-observer.ts +150 -0
  77. package/src/extension/revocation.test.ts +81 -0
  78. package/src/extension/revocation.ts +84 -0
  79. package/src/extension/settle-alerts.test.ts +579 -0
  80. package/src/extension/settle-alerts.ts +175 -0
  81. package/src/extension/shortcut.test.ts +62 -0
  82. package/src/extension/shortcut.ts +105 -0
  83. package/src/extension/tools.test.ts +1294 -0
  84. package/src/extension/tools.ts +553 -0
  85. package/src/extension/version.test.ts +115 -0
  86. package/src/extension/version.ts +97 -0
  87. package/src/goldens.test.ts +294 -0
  88. package/src/harness-policy.test.ts +76 -0
  89. package/src/layers.test.ts +309 -0
  90. package/src/layers.ts +405 -0
  91. package/src/package-manifest.test.ts +170 -0
  92. package/src/presentation/actions.test.ts +221 -0
  93. package/src/presentation/actions.ts +85 -0
  94. package/src/presentation/activity.test.ts +386 -0
  95. package/src/presentation/activity.ts +66 -0
  96. package/src/presentation/close.test.ts +359 -0
  97. package/src/presentation/inspector.test.ts +682 -0
  98. package/src/presentation/inspector.ts +442 -0
  99. package/src/presentation/overlay.test.ts +553 -0
  100. package/src/presentation/overlay.ts +229 -0
  101. package/src/presentation/repaint.test.ts +365 -0
  102. package/src/presentation/shortcut.ts +2 -0
  103. package/src/presentation/snapshot.test.ts +535 -0
  104. package/src/presentation/snapshot.ts +306 -0
  105. package/src/presentation/status.test.ts +43 -0
  106. package/src/presentation/status.ts +30 -0
  107. package/src/presentation/strip.test.ts +203 -0
  108. package/src/presentation/strip.ts +67 -0
  109. package/src/presentation/wording.test.ts +388 -0
  110. package/src/presentation/wording.ts +294 -0
  111. package/src/runtime/bridge.test.ts +131 -0
  112. package/src/runtime/bridge.ts +128 -0
  113. package/src/runtime/clock.test.ts +31 -0
  114. package/src/runtime/clock.ts +31 -0
  115. package/src/runtime/config.test.ts +63 -0
  116. package/src/runtime/config.ts +92 -0
  117. package/src/runtime/context.test.ts +19 -0
  118. package/src/runtime/context.ts +9 -0
  119. package/src/runtime/execution-env.test.ts +33 -0
  120. package/src/runtime/execution-env.ts +15 -0
  121. package/src/runtime/extensions.test.ts +86 -0
  122. package/src/runtime/extensions.ts +152 -0
  123. package/src/runtime/handle.ts +54 -0
  124. package/src/runtime/log.test.ts +140 -0
  125. package/src/runtime/log.ts +91 -0
  126. package/src/runtime/mcp.test.ts +1450 -0
  127. package/src/runtime/mcp.ts +1005 -0
  128. package/src/runtime/models.test.ts +145 -0
  129. package/src/runtime/models.ts +259 -0
  130. package/src/runtime/observe.test.ts +50 -0
  131. package/src/runtime/observe.ts +150 -0
  132. package/src/runtime/runtime-state.test.ts +25 -0
  133. package/src/runtime/runtime-state.ts +36 -0
  134. package/src/runtime/session-tag.ts +11 -0
  135. package/src/runtime/session.test.ts +352 -0
  136. package/src/runtime/session.ts +263 -0
  137. package/src/runtime/storage.ts +29 -0
  138. package/src/test-hygiene.test.ts +97 -0
package/README.md CHANGED
@@ -1,3 +1,457 @@
1
- # Temporary Holding Version
1
+ # pi-delegates
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ pi-delegates is a Pi extension for durable agent delegation. A delegated agent
4
+ is a child conversation. Its toolkit (model, thinking level, tools, extensions,
5
+ instructions, working directory and approval rules) is committed when the run
6
+ starts. Close Pi, reopen the session, and the runs, conversations, checkpoints,
7
+ gate decisions and dispositions are still there.
8
+
9
+ Package: `@ftrdotdev/pi-delegates` · [MIT](LICENSE)
10
+
11
+ ![The Delegates inspector overlay: a fanout run with three children, one vault-scout waiting on the vault-access gate and two scouts answered after 5 and 12 seconds, the gate row, the lane counts, and the key line](https://raw.githubusercontent.com/felixnorden/pi-mono/main/docs/images/pi-delegates.png)
12
+
13
+ The inspector overlay (`ctrl+space`): one fanout run, its three children, the
14
+ gate one child is parked on, and the lane counts. Every row is live.
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ pi install npm:@ftrdotdev/pi-delegates
20
+ ```
21
+
22
+ ## Requirements
23
+
24
+ - Pi `1.6.0` with a matching `@earendil-works/pi-ai`, the version `pi-durable`
25
+ pins. On load the package compares the two; when they differ it refuses to
26
+ start and prints both versions.
27
+ - Node `22.19.0` or newer. The store uses `node:sqlite`.
28
+
29
+ ## Inspector shortcut
30
+
31
+ `ctrl+space` opens the inspector overlay while the inspector is active. Change
32
+ it in `~/.pi/agent/delegates.json`:
33
+
34
+ ```json
35
+ { "inspectorShortcut": "ctrl+alt+i" }
36
+ ```
37
+
38
+ Or set `PI_DELEGATES_INSPECTOR_SHORTCUT=ctrl+alt+i` for one run. `ctrl+i` is
39
+ not used: legacy terminals send it as Tab. `ctrl+shift+...` bindings need a
40
+ terminal with Kitty keyboard protocol support. If the OS reserves
41
+ `ctrl+space` (macOS input switching, for example), use `ctrl+alt+i` or `f2`.
42
+ Run `/reload` after editing the file.
43
+
44
+ In the overlay, `enter` or `i` expands the selected row. On a `fanout` or
45
+ review parent it shows the child rows; the Gates section stays visible below the
46
+ tree. `enter` or `i` on a child shows its details. `s` stops a run, `a`
47
+ approves a gate, `d` denies one, and `escape` closes. A waiting child with one
48
+ gate also accepts `a` or `d`: the write goes to the parent run that owns the
49
+ gate. Finished rows show `took <duration>`; live rows show their current
50
+ activity or age. An expanded row keeps its details indented beneath it.
51
+ `ctrl+space` only opens the overlay; it never acts on a row. While the
52
+ inspector is off, the key prints a hint that names `/delegates`, the same notice
53
+ `/delegates:overlay` prints, instead of doing nothing. The footer carries the
54
+ state in one line: `delegates off · /delegates` when off, `delegates idle ·
55
+ ctrl+space` when on and quiet, and the live counters (`delegates running 2 ·
56
+ gates 1 · ctrl+space`) while work is pending. A session that never enabled the
57
+ inspector shows no footer line. The `Delegates` box above the editor stays
58
+ mounted from activation to teardown: `idle — ctrl+space` when nothing is
59
+ running, then the non-zero counters and up to two live child lines while work
60
+ runs.
61
+
62
+ When a gate becomes pending, one warning notice names the gate and any waiting
63
+ child, and one message enters the parent session. The message tells the agent to
64
+ ask you for the decision; it does not approve or deny the gate. These alerts run
65
+ with the session, not with the inspector: turning `/delegates` off does not
66
+ silence them. An alert is not repeated after an inspector toggle or a reload.
67
+ The same alert path announces a delegate's question with one warning and one
68
+ parent message. See [Questions from a delegate](#questions-from-a-delegate).
69
+
70
+ `/delegates` toggles the inspector. The first delegate launch in a TUI session
71
+ turns it on automatically. An explicit off stays off for later launches, and
72
+ reload, resume and branch switch restore an active inspector.
73
+
74
+ ## Agent skill
75
+
76
+ The package ships a skill for agents. It covers when to delegate, launch
77
+ shapes, definition fields, run status, control, gates and gate automation. Pi
78
+ loads it when a task matches, or run `/skill:pi-delegates`.
79
+
80
+ ## Tools
81
+
82
+ | Tool | Purpose |
83
+ | ------------------ | ------------------------------------------------------------------------- |
84
+ | `delegate_launch` | Start a single agent, a fanout in a lane, or a panel of reviewers |
85
+ | `delegate_control` | `steer`, `stop`, `resume`, `approve`, `deny`, `answer` or `decline` a run |
86
+ | `delegate_status` | Show runs, lanes, pending gates and requests; with no argument, newest 50 |
87
+
88
+ `delegate_status` accepts `run` or `lane` to narrow the view. With `run` it
89
+ reads only that run, prints what it waits on and its review rows, and prints no
90
+ lane line. Without `run` it returns the newest 50 runs, prints how many older
91
+ runs it left out, and lists what needs a person first.
92
+
93
+ A launch needs a host model. When the session has no model and the definition
94
+ sets none, the launch fails with `HostModelMissing` before a task or a run is
95
+ written. The error names the definition, `model.provider` and `model.modelId`.
96
+
97
+ A launch waits up to `defaults.launchWaitMs`, which is 10 minutes by default.
98
+ It returns the answer for a single run, or the group summary for a fanout or
99
+ review. The result names the run id. When the child parks on an approval gate,
100
+ it returns `waiting` with the gate names. When the deadline passes, it returns
101
+ `running` or `queued` with the run id, and the run keeps working.
102
+
103
+ The prompt section lists the built-in presets:
104
+
105
+ | Preset | Tools |
106
+ | ---------- | ------------------------------- |
107
+ | `scout` | `read` |
108
+ | `builder` | `read`, `bash`, `write`, `edit` |
109
+ | `reviewer` | `read` |
110
+
111
+ Presets use the host session's model and thinking level at launch. They carry
112
+ no approval rules. Gates are opt-in and belong to the user who registers the
113
+ definition. See [Register an agent with a gate](#register-an-agent-with-a-gate).
114
+
115
+ ## MCP servers
116
+
117
+ The package reads `mcp.json` from the agent directory and, when Pi marks the
118
+ project trusted, `<project>/.pi/mcp.json`. Project entries replace global
119
+ entries with the same name. A project entry without `command`, `url` or `type`
120
+ overrides only `enabled`, `exposure` and `toolExposure` of the global server. A
121
+ project entry may not set `auth` beside `url`: a repository cannot choose where
122
+ a credential goes.
123
+
124
+ ```json
125
+ {
126
+ "mcpServers": {
127
+ "demo": { "command": "node", "args": ["server.js"] },
128
+ "docs": {
129
+ "url": "https://example.test/mcp",
130
+ "headers": { "Authorization": "Bearer ${DOCS_TOKEN}" }
131
+ }
132
+ }
133
+ }
134
+ ```
135
+
136
+ `${NAME}` in `env` and `headers` expands from the process environment. A
137
+ missing variable keeps its literal and writes `mcp.env_missing`. A value that
138
+ starts with `!` writes `mcp.env_unsupported`, and the server is skipped: the
139
+ package never runs a command to build a server environment.
140
+
141
+ Only a server that a registered definition references connects: a `tools` entry
142
+ under `mcp__<server>__`, or an `extensions` entry `mcp:<server>`. References are
143
+ read at session start, so an inline definition can use a connected server's
144
+ tools but cannot bring in a server that no registered definition references.
145
+ Each connected server registers one extension `mcp:<server>` with the namespace
146
+ `mcp__<server>` and one tool per visible server tool, named
147
+ `mcp__<server>__<tool>`.
148
+
149
+ A definition selects those tools by exact name or by a pattern that names its
150
+ server:
151
+
152
+ ```json
153
+ { "tools": ["read", "mcp__demo__*"] }
154
+ ```
155
+
156
+ `mcp__<server>__*` and `mcp__<server>__<prefix>*` are the only accepted shapes;
157
+ `mcp__*` and a partial namespace are refused with a message that states the
158
+ grammar. An unknown namespace fails the launch with `ToolkitUnresolved`, which
159
+ lists the available namespaces and the configured servers that are not
160
+ connected.
161
+
162
+ `exposure` picks how a server's tools reach the child: `codemode` (default,
163
+ scripts only), `direct` (the model and scripts), `deferred` (the model after
164
+ `tool_search`, and scripts), or `hidden` (no tool is registered unless
165
+ `toolExposure` re-exposes it). A `toolExposure` entry overrides one tool name
166
+ or `*` pattern. A selected codemode tool also selects the `codemode`
167
+ extension; a selected deferred tool selects `tool-search`.
168
+
169
+ A server that cannot connect degrades: no tools, one `mcp.connect_failed`,
170
+ `mcp.connect_timeout` or `mcp.list_tools_failed` line in `delegates.log`, one
171
+ aggregated warning at session start, and the launch continues. A connect waits
172
+ at most 10 seconds. A tool call is bounded by the server's `timeout` (default 60
173
+ seconds) and by the run's cancellation; a timeout returns an error naming the
174
+ server. A result over 20 KiB is cut, and the full text is saved under the
175
+ session directory.
176
+
177
+ ## Workflows
178
+
179
+ A registered definition may set `codemode: "runs"`. Such a definition runs
180
+ workflows only: a `single`, `fanout` or `review` launch of it fails with
181
+ `WorkflowOnly`, and a workflow launch of a definition without the field fails
182
+ with `WorkflowNotEnabled`, both before a run exists. The model-authored inline
183
+ definition cannot set the field.
184
+
185
+ ```ts
186
+ const composer = defineAgent({
187
+ name: "composer",
188
+ role: "Workflow composer",
189
+ prompt: { role: "You compose workflows from delegated runs." },
190
+ tools: ["read"],
191
+ extensions: ["coding-tools"],
192
+ approval: { gates: [] },
193
+ codemode: "runs",
194
+ });
195
+ ```
196
+
197
+ Launch it with `kind: "workflow"`. The `script` is JavaScript that the child's
198
+ model passes verbatim to durable's `codemode` tool:
199
+
200
+ ```json
201
+ {
202
+ "kind": "workflow",
203
+ "agent": "composer",
204
+ "script": "const a = await tools.launch({ agent: 'scout', task: 'a' }); return a.answer"
205
+ }
206
+ ```
207
+
208
+ A script may be at most 65536 UTF-8 bytes; a larger one fails with
209
+ `WorkflowTooLarge` before a run is claimed. The run records mode `workflow`, and
210
+ its lane defaults to `workflow`. The child conversation selects `codemode` and
211
+ `runs` beside the definition's own tools and extensions, so the model sees
212
+ `codemode` and none of the run tools.
213
+
214
+ The script reaches eight tools under the `runs` namespace:
215
+
216
+ | Tool | Purpose |
217
+ | ------------- | ------------------------------------------------------------------------------------- |
218
+ | `launch` | Start one child in the workflow's lane, wait for it, return `{ run, answer, status }` |
219
+ | `launch_many` | Start a group in one lane, wait for all, return one outcome per child |
220
+ | `lane` | Read `{ name, running, queued, answered }` for one lane |
221
+ | `status` | Read every run of the session as `{ run, definition, lane, status }` |
222
+ | `ref` | Read `{ run, conversationId, gateRunId }` for one run |
223
+ | `steer` | Send a message to a child |
224
+ | `stop` | Stop a child |
225
+ | `gate` | Ask a person to approve or deny `script:<name>`, then return the decision |
226
+
227
+ A child run is owned by the workflow run task, inherits the workflow's lane, and
228
+ records `parentRunId`, so it appears nested under the workflow. A `launch_many`
229
+ child records the workflow as its parent and gate run too, so its approval gate
230
+ is listed under the workflow, not under the group. A script cannot stop or steer
231
+ its own run; that call returns an error result naming the run. A refused control
232
+ call returns an error result that names the reason; the script catches it to
233
+ branch. An unknown agent or a missing host model fails the call, so the script
234
+ raises.
235
+
236
+ The lane cap bounds a `launch_many` group. `tools.launch` claims its child
237
+ without admission, like `kind: "single"`; a script that wants parallel children
238
+ calls `launch_many`. The script the model passes is trusted: the toolkit does
239
+ not compare the `codemode` code with the launch script, so the `workflow-script`
240
+ section and the definition prompt are the only instruction.
241
+
242
+ A restart resumes the script from durable's journal: each nested call reattaches
243
+ by key, so an answered child is not started again. `delegate_control resume`
244
+ refuses a workflow run; reopen the session instead. `tools.gate` parks the
245
+ workflow on `script:<name>` until `delegate_control approve` or `deny` releases
246
+ it.
247
+
248
+ ## Questions from a delegate
249
+
250
+ A delegate can put one question to you. The child needs the `questions`
251
+ extension and the `ask` tool in its definition:
252
+
253
+ ```ts
254
+ const envScout = defineAgent({
255
+ name: "env-scout",
256
+ role: "Environment scout",
257
+ prompt: { role: "Ask which environment to inspect, then inspect it." },
258
+ tools: ["read", "ask"],
259
+ extensions: ["coding-tools", "questions"],
260
+ approval: { gates: [] },
261
+ });
262
+ ```
263
+
264
+ `ask` takes `{ prompt, options?, allowOther? }`. With two to five options it
265
+ asks for a choice; with none it asks for free text. `allowOther` defaults to
266
+ true, and a request with no options must allow free text, so `allowOther: false`
267
+ needs at least two options. A prompt is at most 4 KiB, a label at most 128
268
+ characters, a description at most 1 KiB, and an answer at most 4 KiB; a refusal
269
+ names the field and its bound. At most one option may be recommended.
270
+
271
+ The child commits the request and parks its tool call. The child never opens a
272
+ socket or runs a command for IPC: the durable store is the channel, as it is for
273
+ gates, so an answer survives a restart.
274
+
275
+ In Pi, one warning reads `request <id> asks: <prompt>`, truncated to 120
276
+ characters, and one message enters the parent session with the exact `questions`
277
+ parameter. The message tells the model to ask you with the `question` tool when
278
+ that tool exists, and in plain text otherwise; there is no dependency on
279
+ `@ftrdotdev/pi-inquiry`. The model answers with:
280
+
281
+ ```json
282
+ { "action": "answer", "run": "<run id>", "request": "<request id>", "answer": "staging" },
283
+ ```
284
+
285
+ and declines a cancelled dialog with:
286
+
287
+ ```json
288
+ { "action": "decline", "run": "<run id>", "request": "<request id>" }
289
+ ```
290
+
291
+ `answer` accepts either the run id or a fanout child's run id. The answer is
292
+ normalized before it is stored: ignore case, trim, strip a leading `N. `, accept
293
+ an in-range option number, and store the canonical label. An answer outside the
294
+ options is refused and names the labels. A second answer, an unknown request, a
295
+ wrong run, a declined request and an expired request are refused. `decline`
296
+ cancels the request with reason `declined`; the child gets an error naming the
297
+ reason. A declined request settles the run `denied`, not `answered`: the row and
298
+ the lane counts read denied, and the wait text names it, `Run <id> was denied:
299
+ request <request id> was declined.`
300
+
301
+ After an answer the verb waits like a launch: the run settles, or it asks its
302
+ next request. `delegate_launch` and `delegate_control answer` return at a
303
+ request instead of blocking. `approve` and `deny` still wait for the task, so a
304
+ question that follows a decision reaches you through the alert or
305
+ `/delegates:answer`. A run that waits on a gate and a request names both: `Run
306
+ <id> waits for gate <gates> and request <requests>.`
307
+
308
+ `/delegates:answer` answers without the model. With no arguments it lists the
309
+ pending requests, then asks for a label or free text; cancelling the answer
310
+ dialog declines the request, and cancelling the request picker leaves every
311
+ request pending. With `<run> <request> <answer…>` it answers directly. A
312
+ request that is no longer pending is refused.
313
+
314
+ The deadline is 24 hours from the first call. A record past its deadline reads
315
+ as `expired` without a write, the child's `ask` returns an error, and a late
316
+ answer is refused. `stop` cancels the run's pending requests with reason
317
+ `stopped`; a resume does not resurrect one. Seven days after a request is
318
+ made, the next live start retires the record and its index row. A read-only
319
+ viewer lists pending requests and never announces, answers or prunes.
320
+
321
+ A headless or sandboxed host starts `startRequestAlerts` with its own
322
+ `RequestAlertHost`, or reads the same records with `requestRecords` from the
323
+ store. Without that watcher a request stays pending and the store still lists
324
+ it. The package default, `logOnlyRequestHost`, writes one id-only log line per
325
+ request; the prompt and the answer never enter the log.
326
+
327
+ ## `/delegates`
328
+
329
+ `/delegates` toggles the live inspector in a TUI session. `/delegates:list`
330
+ prints the registered agents, the session's runs, the lane counts, the pending
331
+ gates and the pending requests. Each agent line names its tools and gates.
332
+ `/delegates` and `/delegates:list` only read. The three tools and
333
+ `/delegates:answer` are the writers.
334
+
335
+ ## Register an agent with a gate
336
+
337
+ Presets carry no gates. To gate a tool, register your own definition from a Pi
338
+ extension. From a checkout, [examples/gated.ts](./examples/gated.ts) is a
339
+ one-file version of this recipe; see [examples/README.md](./examples/README.md).
340
+
341
+ Create a local package with a manifest at `./delegates-local/package.json`:
342
+
343
+ ```json
344
+ {
345
+ "name": "delegates-local",
346
+ "private": true,
347
+ "keywords": ["pi-package"],
348
+ "dependencies": {
349
+ "@ftrdotdev/pi-delegates": "^0.1.0"
350
+ },
351
+ "pi": {
352
+ "extensions": ["./deployer.ts"]
353
+ }
354
+ }
355
+ ```
356
+
357
+ The `pi.extensions` field lists `./deployer.ts`. Pi loads that file.
358
+
359
+ Build the definition and pass it to `createDelegatesExtension`:
360
+
361
+ ```ts
362
+ import { createDelegatesExtension } from "@ftrdotdev/pi-delegates";
363
+ import { defineAgent } from "@ftrdotdev/pi-delegates/agents";
364
+
365
+ const deployer = defineAgent({
366
+ name: "deployer",
367
+ role: "Deploy agent",
368
+ prompt: { role: "You deploy the service and report the result." },
369
+ tools: ["read", "bash"],
370
+ extensions: ["coding-tools"],
371
+ approval: {
372
+ gates: [{ name: "deploy", tools: ["bash"], match: "deploy" }],
373
+ },
374
+ });
375
+
376
+ export default createDelegatesExtension({ definitions: [deployer] });
377
+ ```
378
+
379
+ Install the checkout as the local package's dependency. Before the first
380
+ release, the npm name does not resolve. After the release, install the npm
381
+ name:
382
+
383
+ ```bash
384
+ cd ./delegates-local
385
+ # Before the release is published:
386
+ npm install <checkout>/packages/delegates
387
+ # After the release:
388
+ # npm install @ftrdotdev/pi-delegates
389
+ pi install ./delegates-local
390
+ ```
391
+
392
+ Do not also install the checkout as a Pi package. The local extension registers
393
+ the delegate tools, so a second copy registers them twice.
394
+
395
+ Call `delegate_launch`:
396
+
397
+ ```json
398
+ { "request": { "kind": "single", "agent": "deployer", "task": "deploy the service" } }
399
+ ```
400
+
401
+ Repeating the same request in one session returns the run that request already
402
+ started. The run id covers the session and the request content, so a retried
403
+ tool call never spawns a second run. Change the task text to launch again.
404
+
405
+ `match` is a case-sensitive substring of the raw `bash` command and applies to
406
+ `bash` only. A rule with `match` on `read` never parks; omit `match` to park
407
+ every call of a listed tool. The gate name is scoped to the run, so one
408
+ decision covers every child that parks on that name.
409
+
410
+ A matching `bash` command parks the run. Decide the run with the run id that
411
+ the launch returned. Call `delegate_control`:
412
+
413
+ ```json
414
+ { "action": "approve", "run": "<run id>", "gate": "deploy" }
415
+ ```
416
+
417
+ `coding-tools` is the built-in coding extension. The package adds the
418
+ `gate-guard` extension when the definition has rules. A gate belongs to the
419
+ registered definition. An inline definition of the same name can narrow the
420
+ tools, but it cannot remove the rule.
421
+
422
+ ## Configuration
423
+
424
+ `delegates.json` in the Pi agent directory overrides the defaults. A missing
425
+ file uses the defaults. An invalid value falls back to its default and adds a
426
+ diagnostic.
427
+
428
+ ```json
429
+ {
430
+ "caps": { "laneCap": 4, "sessionCeiling": 8, "maxTurns": 400 },
431
+ "defaults": { "maxTurns": 120, "launchWaitMs": 600000 }
432
+ }
433
+ ```
434
+
435
+ `defaults.maxTurns` is the budget a child gets when no request or definition
436
+ names one. `caps.maxTurns` is the ceiling every resolved budget is clamped to,
437
+ and no budget goes below one round.
438
+
439
+ ## Failure log
440
+
441
+ The package writes `<sessionDir>/delegates.log`, one JSON object per line. It
442
+ records harness reports, config diagnostics, version notes, swallowed errors and
443
+ wait outcomes that are not `settled`. It never holds the request, the task text,
444
+ an answer, a prompt or a command. A broken log path never fails a call.
445
+
446
+ See [OPERATIONS.md](./OPERATIONS.md) for the fields and stable codes.
447
+
448
+ ## Session store
449
+
450
+ The Pi process that owns a session is its only writer. Do not open its SQLite
451
+ store yourself. See [OPERATIONS.md](./OPERATIONS.md) for the path and read-only
452
+ rules.
453
+
454
+ ## Development
455
+
456
+ See [TESTING.md](./TESTING.md) to run the extension from a checkout, and
457
+ [ROADMAP.md](./ROADMAP.md) for deferred work.
package/ROADMAP.md ADDED
@@ -0,0 +1,179 @@
1
+ # pi-delegates roadmap
2
+
3
+ The first release ships durable delegation: three in-session tools, one prompt
4
+ section, `/delegates`, single launch, fanout, review, control, gates, skills,
5
+ scripted workflows, MCP servers and the inspector. Each section below names
6
+ deferred work and why it waits. The last section names what the design rejects;
7
+ that work is not deferred.
8
+
9
+ ## Shipped
10
+
11
+ - **MCP servers.** The package reads `mcp.json` and, when the project is
12
+ trusted, `.pi/mcp.json`, with the host's override rules. Only servers a
13
+ registered definition references connect; an inline definition can use them
14
+ but cannot bring one in. Each connection registers one extension
15
+ `mcp:<server>` with the namespace `mcp__<server>` and one durable tool per
16
+ visible server tool. A definition selects them by exact name or by a
17
+ `mcp__<server>__<prefix>*` pattern; an unknown namespace fails the launch.
18
+ `exposure` and `toolExposure` map to `callers` and `deferred`, and a selected
19
+ tool auto-selects `codemode` or `tool-search`. A server that cannot connect
20
+ degrades with one diagnostic and one aggregated warning; connects race a 10 s
21
+ deadline and calls race the server's `timeout` and the run's cancellation.
22
+ Bounded results are saved under the session directory. Remaining gaps: OAuth
23
+ sign-in, resource tools, a per-run reconnect, config writes, and servers that
24
+ other extensions register with `pi.registerMcpServer()`. Also open: an inline
25
+ definition cannot reference a server that no registered definition does,
26
+ because the referenced set is read at session start. Re-read
27
+ `pi-coding-agent/dist/extensions/mcp/config.js` before trusting the merge.
28
+ - **Delegated-agent skills.** A definition declares `skills` by name; the binder
29
+ adds the `skills` extension, the toolkit document records the names (version
30
+ 2), and the prompt section lists only the declared skills. A name that does
31
+ not resolve fails the launch, and a stored name that stops resolving is
32
+ refused with the missing list.
33
+ - **Questions from a delegate.** A child whose definition selects `questions`
34
+ and `ask` can put one question to the user and park on the answer. The record
35
+ is a session document keyed by conversation and call, with one index row
36
+ written in the same commit. A wait attaches to both indexes and resolves on
37
+ the commit, so the parent turn ends at the question. `delegate_control`
38
+ `answer` and `decline`, and `/delegates:answer`, are the writes. A request
39
+ expires after 24 hours, and a decided record is pruned 7 days after it was
40
+ requested. What remains: a web control plane, `tools.ask` for workflow
41
+ scripts, multi-question calls and multi-select answers. `gatedTool` still has
42
+ the commit/park window that `ask` closes: a decision that lands between the
43
+ gate's read and `requestGate`'s commit is lost for that call. The fanout
44
+ admission loop still polls at 1000 ms; `docs/issues/fanout-latency.md`
45
+ records it and it is unrelated to the wait.
46
+
47
+ ## Durability and hosts
48
+
49
+ - **Store retention and cleanup.** Stores live beside the session file and are
50
+ never pruned. A later changeset adds a retention command.
51
+ - **A project-local store.** `storePathFor` puts the SQLite file under the Pi
52
+ sessions directory (`<sessionDir>/delegates-<sessionId>.sqlite`), a hashed
53
+ slug away from the checkout it describes, while the sibling package keeps
54
+ `.pi/subagents/` inside the project. Moving the store to
55
+ `<cwd>/.pi/delegates/<sessionId>.sqlite` needs the `.pi/mcp.json` trust gate,
56
+ a fallback open of the old path for a session that is mid-upgrade, a
57
+ documented `.gitignore` line, and the failure log and MCP result files moved
58
+ with it. `docs/issues/project-local-store.md` records the details.
59
+ - **Store migration between package versions.** Durable task and document
60
+ migrations are supported today. A store migration between
61
+ `@ftrdotdev/pi-delegates` versions is not.
62
+ - **A second writer.** One Pi process owns a store. Read-only open is
63
+ supported. Multi-process writing, leases and store takeover wait for a
64
+ durable coordination primitive.
65
+ - **Progress without an open Pi process.** Closing Pi pauses delegated work.
66
+ A daemon needs the cooperation of the session file, which Pi owns.
67
+ - **Scheduled launches (cron and one-shot).** Nothing starts a run without a
68
+ tool call. A timer surface needs a process that runs while Pi is closed, so
69
+ it depends on the daemon item above.
70
+
71
+ ## Work items and authorization
72
+
73
+ - **Gate revocation after launch.** A committed toolkit cannot change. Removing
74
+ a gate later is not supported, because the child's conversation already runs
75
+ with the old rules.
76
+ - **Spend enforcement.** The package reports no spend. Budgets and goal limits
77
+ are not enforced.
78
+ - **A turn budget the task chooses.** `maxTurns` is one global value from
79
+ `delegates.json` (40 by default), applied to every child. Neither the launch
80
+ request nor the agent definition can raise it, and the skill says nothing
81
+ about sizing a task to it, so a child that reads a long guide, edits a
82
+ package and verifies the result ends `turn_limit` with its report unwritten.
83
+ What it needs: a higher default, `maxTurns` on the request and the
84
+ definition, the resolved value in the run record, and a `Turn budget`
85
+ section in the skill. `docs/issues/turn-budget.md` records the details.
86
+ - **A live approval dialog.** Gates are committed records and parked calls.
87
+ They are not interactive prompts inside a running delegate.
88
+
89
+ ## Surfaces and observability
90
+
91
+ - **A wider failure log.** Version 1 writes one JSONL file per session, with a
92
+ stable `code` and a 200-character `detail`. It adds no telemetry context, no
93
+ trace links and no counters, because one sink has one reader. Log rotation
94
+ waits until a session log reaches 5 MB.
95
+ - **A failed run's reason without its detail.** `delegate_status` prints
96
+ `failed (model_error)` and drops the provider text that the store keeps in
97
+ `RunFailure.detail`, and no log code covers a run failure at all, so a 429
98
+ reads exactly like a malformed request. `docs/issues/failure-detail.md`
99
+ records the details.
100
+ - **Telemetry, metrics and trace links.** Version 1 writes the JSONL file and
101
+ nothing else: no Effect logger, no `pi-telemetry` context, no counters and no
102
+ span links. A second reader or a trace view is the trigger; until then it
103
+ adds a failure mode without an audience.
104
+ - **A bounded status read.** A session status returns the newest 50 runs and
105
+ prints how many it left out. A paging cursor, a wider bound and concurrent
106
+ reads wait until sessions routinely exceed 50 runs.
107
+ - **Progress inside the parent conversation.** A delegate reports a final
108
+ answer or a status row, and the parent polls. Streaming partial text into the
109
+ parent turn needs an event path from a child conversation to the host, which
110
+ the durable task model does not carry today.
111
+ - **A setup check.** `/delegates` lists runs and nothing else. No command
112
+ reports the resolved registry, the config diagnostics, the store path and the
113
+ version verdict together, though the runtime records each part.
114
+ - **The CLI.** `pi delegates runs|lanes|gates|reviews|spend|diagnostics` would
115
+ open a store read-only, aggregate sessions and reject writes.
116
+ - **Cross-session aggregation.** Every view reads one session's store. A merge
117
+ across stores must decide its order, its bound, and where it finds the stores;
118
+ run ids already carry the session id, so they do not collide.
119
+ - **The panel.** A read-only local page over the same view model, refreshed on
120
+ an interval.
121
+ - **A live inspector.** Transcript paging and per-turn evidence are not in the
122
+ first release.
123
+
124
+ ## Agent definitions and toolkits
125
+
126
+ - **Scripted workflows inside a delegate.** A registered definition with
127
+ `codemode: "runs"` runs a workflow launch: the child's model passes the
128
+ script to durable's `codemode` tool, and a script gate parks the workflow on
129
+ `script:<name>`. The lane cap binds `launch_many` groups only; `tools.launch`
130
+ claims its child without admission. The script the model passes is trusted:
131
+ the toolkit does not compare it with the launch script. What remains: a
132
+ workflow language of the package's own, nested workflows (code mode is
133
+ model-only), retry policies for a failed script, and a UI for script progress
134
+ beyond `pi.live.nestedTools`.
135
+ - **Declarative definition files.** Definitions are exported objects passed to
136
+ the factory. Version 1 has no definition file format and no reload command.
137
+ - **Loading Pi extension files per agent.** Agents select installed durable
138
+ extensions by name. The package does not use jiti or package-manifest
139
+ discovery.
140
+
141
+ ## Isolation and execution
142
+
143
+ - **One session runtime with logger, tracer, metrics and clock layers.** No
144
+ domain code consumes Effect services, so a session `ManagedRuntime` would
145
+ add a layer without a consumer. Cancellation needs a signal, not a runtime.
146
+ - **A live task-graph watch.** The wait attaches to the gate index and the
147
+ request index and resolves on a commit; a 5 s backstop re-checks after a
148
+ missed push. A stream lifecycle replaces it only when a measured need
149
+ appears.
150
+ - **`Effect.Semaphore` admission.** The durable task count is the correct
151
+ source across restarts; a semaphore is process-local. Do not add it.
152
+ - **A cumulative spawn budget.** The admission caps bound live runs per lane
153
+ and per session, not the total. A resumed run creates a new task each time,
154
+ so one run can spawn without a counter. A per-run-tree cap needs a durable
155
+ count beside the launch index.
156
+ - **Per-part health entries.** One `RuntimeState` covers the whole runtime. The
157
+ log carries config diagnostics; a per-part health surface needs its own
158
+ reader.
159
+ - **Worktrees per child.** Every child in a run shares one working directory.
160
+ The package records no lane merge evidence.
161
+ - **Multi-repo runs.** A run uses one repository. Runs across several
162
+ repositories are not supported.
163
+ - **Nested delegation.** `delegates-control` is not installed in the first
164
+ release, so a definition that names it fails as an unresolved name.
165
+ - **A non-blocking launch.** `delegate_launch` waits up to `launchWaitMs` and
166
+ returns a run id at the deadline. Returning at once and reading the run with
167
+ `delegate_status` is a UX change that needs evidence; the inline wait exists
168
+ because a person asked for the result.
169
+
170
+ ## Rejected by design
171
+
172
+ The design concept rejects this work, so it is not deferred and needs a new
173
+ design concept before it becomes a ticket.
174
+
175
+ - **Mandate, Policy and an authorization layer.** Authority is the agent
176
+ definition plus its gate rules. There is no admission table, no mandate
177
+ revalidation, and no policy version separate from the committed toolkit.
178
+ - **Source intake and work-item Tickets.** A run starts from a tool call, not
179
+ from a Source admitted through a Trigger.