@xzzpig/pi-subagents 0.4.2 → 0.5.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 +168 -0
- package/README.md +4 -0
- package/agents/oracle.md +3 -1
- package/agents/reviewer.md +1 -0
- package/agents/scout.md +2 -2
- package/agents/worker.md +2 -1
- package/async-retention-discovery-worker.mjs +180 -0
- package/docs/agents.md +40 -2
- package/docs/configuration.md +41 -13
- package/docs/extension-api.md +45 -2
- package/docs/models.md +2 -0
- package/docs/observability.md +41 -5
- package/docs/tool-reference.md +38 -39
- package/docs/workflows.md +173 -3
- package/package.json +13 -10
- package/prompts/council.md +48 -0
- package/skills/council-mode/SKILL.md +230 -0
- package/skills/pi-subagents/SKILL.md +8 -4
- package/skills/pi-subagents/references/constraints-and-recipes.md +13 -6
- package/skills/pi-subagents/references/execution-controls.md +40 -15
- package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
- package/skills/pi-subagents/references/multi-lane-orchestration.md +39 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +4 -2
- package/src/agents/agent-management.ts +158 -357
- package/src/agents/agent-serializer.ts +2 -0
- package/src/agents/agents.ts +186 -44
- package/src/agents/builtin-names.ts +9 -0
- package/src/agents/runtime-agent-registry.ts +418 -0
- package/src/agents/skills.ts +1 -1
- package/src/api/agents.ts +7 -0
- package/src/api/external-job-provider.ts +186 -0
- package/src/api/preflight.ts +37 -9
- package/src/api/shared-types.ts +2 -0
- package/src/extension/config.ts +6 -3
- package/src/extension/doctor.ts +4 -6
- package/src/extension/fanout-child.ts +2 -2
- package/src/extension/index.ts +183 -90
- package/src/extension/public-execution.ts +31 -2
- package/src/extension/rpc.ts +41 -1
- package/src/extension/schemas.ts +17 -37
- package/src/extension/tool-description.ts +35 -24
- package/src/inspectors/herdr/actions.ts +2 -2
- package/src/inspectors/herdr/inspector-runner.ts +2 -1
- package/src/inspectors/herdr/project-panes.ts +2 -2
- package/src/intercom/native-supervisor-channel.ts +32 -10
- package/src/missions/lifecycle.ts +6 -1
- package/src/missions/store.ts +4 -9
- package/src/missions/workflow-state.ts +2 -2
- package/src/profiles/profiles.ts +3 -1
- package/src/runs/background/active-run-index.ts +31 -8
- package/src/runs/background/async-execution.ts +70 -41
- package/src/runs/background/async-job-tracker.ts +24 -7
- package/src/runs/background/async-resume.ts +49 -16
- package/src/runs/background/async-retention.ts +886 -0
- package/src/runs/background/async-status-snapshot.ts +14 -5
- package/src/runs/background/async-status.ts +39 -53
- package/src/runs/background/auto-drain.ts +1 -0
- package/src/runs/background/chain-append.ts +3 -33
- package/src/runs/background/completion-dedupe.ts +5 -1
- package/src/runs/background/completion-replay.ts +22 -12
- package/src/runs/background/control-channel.ts +14 -68
- package/src/runs/background/fleet-view.ts +68 -19
- package/src/runs/background/index-segment.ts +59 -0
- package/src/runs/background/inspect-rpc.ts +443 -0
- package/src/runs/background/notify.ts +31 -5
- package/src/runs/background/result-files.ts +158 -90
- package/src/runs/background/result-watcher.ts +124 -20
- package/src/runs/background/resume-guidance.ts +8 -5
- package/src/runs/background/retained-children.ts +13 -3
- package/src/runs/background/run-id-query.ts +7 -0
- package/src/runs/background/run-id-resolver.ts +11 -9
- package/src/runs/background/run-status.ts +27 -18
- package/src/runs/background/scheduled-runs.ts +24 -4
- package/src/runs/background/stale-run-reconciler.ts +6 -3
- package/src/runs/background/steering.ts +11 -1
- package/src/runs/background/subagent-runner.ts +260 -144
- package/src/runs/background/subagent-wait.ts +17 -13
- package/src/runs/background/terminal-run-index.ts +138 -0
- package/src/runs/background/wait-completions.ts +21 -4
- package/src/runs/background/wait-subscriptions.ts +81 -2
- package/src/runs/background/wait-tool.ts +1 -0
- package/src/runs/foreground/async-steering-action.ts +21 -14
- package/src/runs/foreground/execution.ts +8 -2
- package/src/runs/foreground/subagent-executor.ts +816 -1593
- package/src/runs/foreground/workflow-detach-reconcile.ts +262 -0
- package/src/runs/foreground/workflow-foreground-steering.ts +6 -5
- package/src/runs/shared/acceptance.ts +48 -5
- package/src/runs/shared/chain-outputs.ts +1 -3
- package/src/runs/shared/external-job-bridge.ts +444 -0
- package/src/runs/shared/external-job-runner.ts +286 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +14 -0
- package/src/runs/shared/model-exclusions.ts +242 -0
- package/src/runs/shared/model-fallback.ts +153 -40
- package/src/runs/shared/orca-progress-tabs.ts +84 -22
- package/src/runs/shared/parallel-handoff.ts +46 -4
- package/src/runs/shared/parallel-utils.ts +4 -15
- package/src/runs/shared/permissions.ts +5 -1
- package/src/runs/shared/pi-args.ts +8 -1
- package/src/runs/shared/session-lease.ts +0 -6
- package/src/runs/shared/subagent-control.ts +51 -7
- package/src/runs/shared/subagent-prompt-runtime.ts +12 -6
- package/src/runs/shared/workflow-graph.ts +1 -23
- package/src/runs/shared/worktree.ts +14 -2
- package/src/shared/atomic-json.ts +22 -2
- package/src/shared/capacity-resilient-json.ts +102 -0
- package/src/shared/completion-owner.ts +14 -0
- package/src/shared/file-system-retry.ts +49 -1
- package/src/shared/fork-context.ts +59 -1
- package/src/shared/model-info.ts +20 -0
- package/src/shared/prompt-resources.ts +0 -40
- package/src/shared/settings.ts +5 -29
- package/src/shared/types.ts +106 -26
- package/src/shared/utils.ts +8 -0
- package/src/shared/watch-strategy.ts +10 -0
- package/src/slash/slash-bridge.ts +2 -1
- package/src/slash/slash-commands.ts +47 -7
- package/src/slash/slash-live-state.ts +3 -3
- package/src/tui/fleet-status.ts +86 -1
- package/src/tui/fleet.ts +117 -16
- package/src/tui/render.ts +73 -3
- package/src/watchdog/change-signature.ts +1 -1
- package/src/watchdog/lsp-diagnostics.ts +1 -0
- package/src/workflows/chat-progress.ts +2 -2
- package/src/workflows/scripted-workflow.ts +320 -79
- package/src/workflows/workflow-receipt.ts +140 -0
- package/src/runs/foreground/chain-clarify.ts +0 -1354
- package/src/runs/foreground/chain-execution.ts +0 -1581
package/docs/extension-api.md
CHANGED
|
@@ -23,10 +23,11 @@ pi.events.emit("subagents:rpc:v1:request", {
|
|
|
23
23
|
});
|
|
24
24
|
```
|
|
25
25
|
|
|
26
|
-
The RPC methods are `ping`, `status`, `spawn`, `steer`, `interrupt`, `stop`, and `resume`. `status`, `steer`, `interrupt`, and `resume` reuse
|
|
26
|
+
The RPC methods are `ping`, `status`, `manage`, `spawn`, `steer`, `interrupt`, `stop`, and `resume`. `status`, `manage`, `steer`, `interrupt`, and `resume` reuse normal package-owned actions.
|
|
27
27
|
|
|
28
28
|
Method notes:
|
|
29
29
|
|
|
30
|
+
- `manage` exposes a narrow schedule-only allowlist: `schedule.list`, `schedule.show`, `schedule.history`, `schedule.pause`, `schedule.resume`, `schedule.run`, and `schedule.delete`. All actions except `schedule.list` require `id`. Mission, agent, config, worktree, and arbitrary management actions are rejected before executor dispatch. `ping.capabilities.managementActions` advertises the exact allowlist.
|
|
30
31
|
- `spawn` requires `workflowScript` and is async-only: omit `async` or set `async: true`, omit `clarify`, and do not pass management `action` values. It goes through the same executor as the `subagent` tool, so agent discovery, validation, session attribution, configured spawn caps, child-safety depth, artifacts, and async status all behave the same.
|
|
31
32
|
- `steer` requires an async run `id` (plus optional child `index`) and a non-empty `message`; its reply preserves the normal acknowledged-delivery result. Optional `mode` values are `steer` (default), `follow_up`, and `auto`, and receipts include `deliveryStatus: "delivered" | "queued"`. RPC steering disables the direct tool's pause-and-revive recovery in every mode so an extension keeps authority over the exact child it spawned; `ping.capabilities.nonRecoveringSteer` advertises this guarantee.
|
|
32
33
|
- `resume` requires a run target and non-empty `message`. It delegates to the existing revival path, which validates current-session ownership, persisted session/recovery metadata, stopped/live state, capability ceilings, and the exclusive session lease before returning the new async run details. Callers may request a `file-only` output path for the revived result without overriding its model, tools, or budgets. `ping.capabilities.resume` advertises this seam.
|
|
@@ -35,6 +36,7 @@ Method notes:
|
|
|
35
36
|
Capability advertisements on `ping`:
|
|
36
37
|
|
|
37
38
|
- `events.asyncComplete` — exact process-local completion correlation after RPC `spawn`.
|
|
39
|
+
- `managementActions` — exact schedule management actions accepted by RPC `manage`.
|
|
38
40
|
- `launchResolvedExtensions` — the optional launch-resolved extension projection in status details.
|
|
39
41
|
- `runtimeAcknowledgedExtensions` — the optional child-runtime acknowledgement projection and event name.
|
|
40
42
|
- `processTerminalProof` — the process-terminal proof status (see [observability.md](observability.md#process-terminal-proof)).
|
|
@@ -132,6 +134,7 @@ Boundaries:
|
|
|
132
134
|
- Raw prompts are not exposed in public contract output.
|
|
133
135
|
- It is side-effect-free for launch state: it does not create child sessions, temp prompt files, structured-output runtimes, tool-diagnostic files, or run artifacts.
|
|
134
136
|
- Some host-owned facts, such as exact fork snapshots, nested async roots, and live model registries, can only be proven by the Pi host; those appear as `host_required` diagnostics instead of silently pretending to be exact.
|
|
137
|
+
- Preflight reads the extension config, so `defaultSubagentContext: "fresh"` or `"fork"` affects omitted context in the same way as execution. Explicit `context` still wins.
|
|
135
138
|
|
|
136
139
|
## Agent ejection API
|
|
137
140
|
|
|
@@ -282,6 +285,26 @@ Semantics:
|
|
|
282
285
|
|
|
283
286
|
Child processes do not gain provider tools or extensions automatically. Add `subagent_wait` to the child agent's `tools` allowlist and load each provider through `extensions` or `subagentOnlyExtensions`. The parent's effective `waitTool` setting is serialized through foreground, async, resume, chain, parallel, and fanout launch paths; `PI_SUBAGENT_WAIT_TOOL_ENABLED` keeps precedence.
|
|
284
287
|
|
|
288
|
+
## External job provider bridge
|
|
289
|
+
|
|
290
|
+
Extensions that own long-running advisor jobs can register a process-local provider for `runner.type: external-job` agents:
|
|
291
|
+
|
|
292
|
+
```ts
|
|
293
|
+
import { registerExternalJobProvider } from "pi-subagents/external-job-provider";
|
|
294
|
+
|
|
295
|
+
const dispose = registerExternalJobProvider({
|
|
296
|
+
name: "surf-oracle",
|
|
297
|
+
start: ({ prompt, promptDigest, cwd, runId, stepIndex, agent, options }) => startSurfJob({ prompt, promptDigest, cwd, runId, stepIndex, agent, options }),
|
|
298
|
+
status: (providerJobId) => getSurfJobStatus(providerJobId),
|
|
299
|
+
result: (providerJobId) => getSurfJobResult(providerJobId),
|
|
300
|
+
reattach: (providerJobId) => reattachSurfJob(providerJobId),
|
|
301
|
+
});
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
The provider returns handles with `providerJobId`, `state`, optional `handleUrl`/`conversationUrl`, optional `failureCode`/`failureMessage`, and optional `blockingJobId` for capacity conflicts. `result` can also return `output` and/or `artifactPath`.
|
|
305
|
+
|
|
306
|
+
The async runner process does not import provider internals. It writes operation requests into its async run directory. The parent Pi process services those requests against the registered provider and writes operation responses. If the provider is not registered, the bridge fails closed with an actionable error. If a run is recovered after provider job metadata exists, the runner calls `reattach` and `result`; it does not call `start` again.
|
|
307
|
+
|
|
285
308
|
## Herdr integration
|
|
286
309
|
|
|
287
310
|
When Pi runs inside [Herdr](https://herdr.dev), pi-subagents automatically reports active async-run counts through Herdr pane metadata.
|
|
@@ -343,6 +366,26 @@ const closed = await closeProjectPane({ cwd: "/path/to/repo", requireIdle: true
|
|
|
343
366
|
|
|
344
367
|
The API returns discriminated structured results with canonical project root, binding path, pane identity, bounded Herdr runtime fields, and stable error codes. `requireIdle: true` fails closed unless Herdr explicitly reports `agent_status: "idle"`; use it when an owning extension must not close a working or blocked pane. The API deliberately reports `trust: "human-verification-required"`: it never bypasses or claims to attest Pi's project-trust prompt. `PROJECT_PANES_API_VERSION` is currently `1`.
|
|
345
368
|
|
|
369
|
+
## Host session lifetime and completion wakes
|
|
370
|
+
|
|
371
|
+
A host that embeds this extension owns whether completion wakes can be delivered at all.
|
|
372
|
+
|
|
373
|
+
Ordinary async and foreground completion wakes use `registerSubagentNotify` and `sendCompletion`. They listen for completion events and deliver through `pi.sendMessage(..., { triggerTurn })`. Session shutdown stops the result watcher and disposes this completion notifier. `createWaitSubscriptionManager` is separate: it is the explicit non-blocking `subagent_wait` subscription path, not the ordinary completion wake path.
|
|
374
|
+
|
|
375
|
+
Detached children do not stop when the session does. They are the host process's children, not the session's, so the run keeps going, completes, and notifies nobody. What is lost is the notification, not the work.
|
|
376
|
+
|
|
377
|
+
This matters because "is the parent busy?" is the wrong idle signal. A parent that launches a detached run and hands control back — which is what the async launch output tells it to do — is not prompting, streaming, compacting, or running a shell command. A host that reaps sessions on those signals alone will dispose exactly the session that was waiting to be woken.
|
|
378
|
+
|
|
379
|
+
If your host reclaims idle sessions, keep a session alive while it still has live detached work:
|
|
380
|
+
|
|
381
|
+
- Read run state from the status files under the async run directory rather than from event traffic. A long, quiet workflow sends almost nothing to the parent, so recent-activity heuristics conclude the wrong thing.
|
|
382
|
+
- Treat `queued` and `running` as live, matching `isActiveAsyncState`. An interrupted run that is `paused` is finalized. A workflow that paused because a child used `contact_supervisor` still has a live child; keep that parent session until reconcile writes `complete` or `failed`.
|
|
383
|
+
- Do not treat `lastUpdate` as a heartbeat. The runner advances it in memory every second but only rewrites `status.json` when the activity classification changes, so a live run inside one long quiet tool call leaves a stale file behind. Judging liveness by file age will reap exactly the run you meant to protect.
|
|
384
|
+
- Prefer the recorded runner `pid`, which stays true through a silent tool call and goes false when the runner dies. Keep file age only as a fallback for runs that record no pid, and give it a wide window.
|
|
385
|
+
- Match `sessionId` in `status.json` against both forms. It is resolved as `getSessionFile() ?? getSessionId()`, so it is normally the parent's session *file path*, but a session that is not persisted records a bare session id instead.
|
|
386
|
+
|
|
387
|
+
The symptom when this is missed is quiet and easy to misattribute: subagents appear never to report back, which looks like a fault in this extension rather than in the host that disposed the listener.
|
|
388
|
+
|
|
346
389
|
## Runtime files
|
|
347
390
|
|
|
348
391
|
The main runtime files in this repository:
|
|
@@ -356,7 +399,7 @@ The main runtime files in this repository:
|
|
|
356
399
|
| `src/runs/background/subagent-runner.ts` | Detached async runner. |
|
|
357
400
|
| `src/runs/background/async-execution.ts` | Background launch support. |
|
|
358
401
|
| `src/runs/background/async-status.ts` | Status discovery and formatting for async runs. |
|
|
359
|
-
| `src/
|
|
402
|
+
| `src/workflows/scripted-workflow.ts` / `src/runs/foreground/subagent-executor.ts` | Scripted workflow orchestration and child launch routing. |
|
|
360
403
|
| `src/shared/settings.ts` | Chain behavior, instructions, and config helpers. |
|
|
361
404
|
| `src/runs/shared/worktree.ts` | Git worktree isolation. |
|
|
362
405
|
| `src/intercom/intercom-bridge.ts` | Runtime intercom bridge instructions and diagnostics. |
|
package/docs/models.md
CHANGED
|
@@ -141,6 +141,8 @@ You do not have to spell a model exactly. Model ids are matched fuzzily against
|
|
|
141
141
|
|
|
142
142
|
Exact `provider/id` matches still win, and a qualified provider query never silently switches providers — it only matches within the named provider. Ambiguous bare ids that exist under multiple providers still require a provider prefix or the current session's provider to disambiguate.
|
|
143
143
|
|
|
144
|
+
Registry ids that themselves contain `/` (Hugging Face `owner/name`) resolve the same way as Pi's main agent: `thinkingmachines/Inkling` becomes `huggingface/thinkingmachines/Inkling` when that id is unique or offered by the current session provider. A first path segment that matches a registered provider still means `provider/id`.
|
|
145
|
+
|
|
144
146
|
## Model scope enforcement
|
|
145
147
|
|
|
146
148
|
To keep subagents inside a budget or compliance profile, enforce a model scope. Put `subagents.modelScope` in user or project settings (project overrides user):
|
package/docs/observability.md
CHANGED
|
@@ -99,6 +99,42 @@ Pi binds `Ctrl+B` to editor cursor-left by default. The extension shortcut takes
|
|
|
99
99
|
|
|
100
100
|
If something feels misconfigured, run `/subagents-doctor` or ask: "Check whether subagents and intercom are set up correctly."
|
|
101
101
|
|
|
102
|
+
## Host inspection protocol (RPC)
|
|
103
|
+
|
|
104
|
+
RPC hosts receive live async status through the bounded `subagent-async` widget
|
|
105
|
+
(`PI_SUBAGENT_ASYNC_JSON:` payload). For on-demand detail — a child's delegated
|
|
106
|
+
task, transcript window, or final output — hosts can invoke the extension
|
|
107
|
+
command:
|
|
108
|
+
|
|
109
|
+
```text
|
|
110
|
+
/subagents-inspect-rpc <requestId> <asyncId> [childId] [--lines N]
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Extension commands execute inline over Pi RPC without a model turn. The reply
|
|
114
|
+
arrives as a single emit-then-retract update on the dedicated `subagent-inspect`
|
|
115
|
+
widget key: the first (and only) line is `PI_SUBAGENT_INSPECT_JSON:<JSON>` with a
|
|
116
|
+
versioned `pi-subagents.inspect-reply` payload correlated by `requestId`. Hosts
|
|
117
|
+
must not render this widget; they should buffer the payload by `requestId` and
|
|
118
|
+
drop unmatched replies.
|
|
119
|
+
|
|
120
|
+
Inspection properties:
|
|
121
|
+
|
|
122
|
+
- Read-only and on demand: nothing is persisted, broadcast, or added to
|
|
123
|
+
notification details; every request re-reads canonical run artifacts after
|
|
124
|
+
the same reconciliation the status action performs.
|
|
125
|
+
- Session-scoped: runs owned by another session fail with `foreign_session`;
|
|
126
|
+
unknown ids fail with `not_found`; cleaned-up artifacts fail with `stale`.
|
|
127
|
+
- Bounded: per-field string caps, a message-count cap (`--lines`, max 200), and
|
|
128
|
+
a hard 64 KB serialized budget with explicit `truncated` markers.
|
|
129
|
+
- No filesystem paths appear in the reply.
|
|
130
|
+
- `task` is the child session's first user message and is only populated when
|
|
131
|
+
it is genuinely attributable (fresh-context child whose session file fits the
|
|
132
|
+
read window); forked children omit it.
|
|
133
|
+
- `childId` is exactly the node id the host received in the status snapshot
|
|
134
|
+
(step `workflowKey`/`runId`/`step:<index>`, or a nested run id).
|
|
135
|
+
|
|
136
|
+
In TUI mode the command only points at the interactive `/subagents` inspector.
|
|
137
|
+
|
|
102
138
|
## Async run artifacts
|
|
103
139
|
|
|
104
140
|
Async runs write machine-readable lifecycle artifacts for observability and workflow gates:
|
|
@@ -122,7 +158,7 @@ The result file is consumed and deleted once its completion notice is delivered.
|
|
|
122
158
|
|
|
123
159
|
`subagent_wait` surfaces a slim projection of each terminal payload it covered in its own tool-result `details.completions` — run identity, per-child agent/`runId`/success, artifact paths, and the bounded `archivePath`, without duplicating output text. It reads the replay when watcher delivery or a watcher restart has removed the one-shot result file and in-memory completion state is unavailable. Durable non-blocking wait subscriptions use the same replay in their delivered details. Workflow result files record each child's `runId` explicitly, since a workflow child's `artifactPaths` entry points at its saved output rather than the artifact files keyed by the id. Extensions observing `tool_result` events can read run and artifact identity from there instead of parsing the text summary.
|
|
124
160
|
|
|
125
|
-
Output archives reference an existing child output artifact or session file when one is available. For children without either file, the archive stores
|
|
161
|
+
Output archives reference an existing child output artifact or session file when one is available. For children without either file, the archive stores a per-child `result-tail` entry with `resultIndex`, bounded to 64 KiB per child, and records whether it was truncated. Replay and archive JSON use `version: 1`; consumers must ignore unknown fields.
|
|
126
162
|
|
|
127
163
|
Nested fanout status is stored as compact sidecar event/registry metadata and merged into parent status views and result/intercom payloads; full recursive status snapshots are not embedded in parent result files.
|
|
128
164
|
|
|
@@ -164,15 +200,15 @@ Foreground and async runners share bounded child-protocol handling:
|
|
|
164
200
|
- `agent_end.willRetry` defers completion until the child settles.
|
|
165
201
|
- Current Pi builds use `agent_settled` as the terminal watermark; older builds retain the bounded terminal-message fallback.
|
|
166
202
|
|
|
167
|
-
##
|
|
203
|
+
## Workflow and debug artifacts
|
|
168
204
|
|
|
169
|
-
Each
|
|
205
|
+
Each scripted workflow stores runtime artifacts under a workflow artifact directory. The on-disk directory is still named `chain-runs` for compatibility. With the default `artifactDir: "session"` or with `"temp"`, it is user-scoped temp storage. With `artifactDir: "project"`, the root is `<cwd>/.pi/subagents/chain-runs/`:
|
|
170
206
|
|
|
171
207
|
```text
|
|
172
208
|
<tmpdir>/pi-subagents-<scope>/chain-runs/{runId}/
|
|
173
209
|
```
|
|
174
210
|
|
|
175
|
-
A run directory may contain files such as `context.md`, `plan.md`, `progress.md`, and `parallel-{stepIndex}/.../output.md`. User-scoped temp
|
|
211
|
+
A run directory may contain files such as `context.md`, `plan.md`, `progress.md`, and `parallel-{stepIndex}/.../output.md`. User-scoped temp workflow artifact directories older than 24 hours are cleaned up on extension startup; project-local and explicit persistent roots are not age-scanned.
|
|
176
212
|
|
|
177
213
|
Debug artifacts live under `{sessionDir}/subagent-artifacts/`, `.pi/subagents/artifacts/` for project-scoped runs, or a user-scoped temp artifact directory. Single-run relative `output` files are saved under `{artifactsDir}/outputs/{runId}/` unless `singleRunOutputBaseDir` is configured. Per task you may see:
|
|
178
214
|
|
|
@@ -187,7 +223,7 @@ For npm package projects, project-scoped artifacts need a `.npmignore` rule (or
|
|
|
187
223
|
|
|
188
224
|
## Sessions
|
|
189
225
|
|
|
190
|
-
Session files are stored under a per-run session directory. With `context: "fork"`, each child starts with `--session <branched-session-file>` produced from the parent's current leaf. That is a real session fork, not an injected summary.
|
|
226
|
+
Session files are stored under a per-run session directory. With `context: "fork"`, each child starts with `--session <branched-session-file>` produced from the parent's current leaf. That is a real session fork, not an injected summary. An omitted launch `context` that resolves through `defaultContext: fork` uses the same branch when the parent session file and current leaf exist, and otherwise starts fresh.
|
|
191
227
|
|
|
192
228
|
## Completion notifications
|
|
193
229
|
|
package/docs/tool-reference.md
CHANGED
|
@@ -4,6 +4,8 @@ Parameters and actions for the `subagent` tool. These are what the LLM passes wh
|
|
|
4
4
|
|
|
5
5
|
## Execution examples
|
|
6
6
|
|
|
7
|
+
Chaining is code-driven through `workflowScript`. Use `await runs.run(...)` for sequential steps and `await runs.all([{ key, agent, task }, ...])` for ordinary parallel fanout. Do not read `.output` from an unawaited `runs.run` launch. Stored `runs.run` promises are only for the advanced rolling fanout pattern under [Workflow steering](#workflow-steering), where every promise is later observed with direct `await`, `Promise.race`, or `Promise.all`. Legacy top-level `chain`, `tasks`, and `parallel` inputs are not supported. Helper functions must be plain functions or explicit Promise chains. Nested `async function` helpers, async arrows, and async methods are rejected so child-launch tracking stays portable across Node and Bun.
|
|
8
|
+
|
|
7
9
|
```js
|
|
8
10
|
// One child; return the child promise explicitly
|
|
9
11
|
{ workflowScript: `return runs.run("main", { agent: "scout", task: "Analyze the auth flow" })` }
|
|
@@ -31,18 +33,18 @@ Parameters and actions for the `subagent` tool. These are what the LLM passes wh
|
|
|
31
33
|
| `agent` | string | - | Agent target for management actions. Workflow child agents are set inside `runs.run` or `runs.all`. |
|
|
32
34
|
| `action` | string | - | Agent management (including `guide`, `children.list`, and `refine`/`refine.show`/`refine.rollback`), mission (`mission.create/list/show/update/resolve-decision/attach-run/close`), Herdr inspector (`inspector.open/status/close`), status/control, schedule, watchdog, or doctor action. |
|
|
33
35
|
| `topic` | `overview \| workflows \| agents \| missions \| observability \| tool-reference \| configuration \| models \| watchdog \| extension-api` | `overview` | Packaged guide topic for `action: "guide"`. |
|
|
34
|
-
| `
|
|
35
|
-
| `
|
|
36
|
-
| `context` | `fresh \| fork` | per-agent default or `fresh` | Explicit `fresh` or `fork` overrides every workflow child. When omitted, each child agent uses its own `defaultContext`; `fork` creates real branched sessions from the parent leaf. Packaged `worker`, `oracle`, and `advisor` default to `fork`. |
|
|
36
|
+
| `config` | object/string | - | Agent config for management create/update. |
|
|
37
|
+
| `context` | `fresh \| fork` | global or per-agent default, else `fresh` | Explicit `fresh` or `fork` overrides every workflow child. When omitted, [`defaultSubagentContext`](configuration.md#defaultsubagentcontext) wins over each agent's `defaultContext`; `"fork"` creates a real branched session when the parent session file and current leaf exist, otherwise it falls back to `fresh`. Packaged `worker`, `oracle`, and `advisor` default to `fork`. |
|
|
37
38
|
| `missionId` | string | - | Attach a workflow to an existing project mission instead of creating its default enclosing mission. |
|
|
38
39
|
| `mission` | object/false | auto-create | Override the default enclosing mission with `{ title \| summary, objective?, goal?, budget?, labels? }`. Set exactly one non-empty `title` or `summary`; `objective` and `labels` are optional. `goal` may only be `true`, requires `budget.tokens`, and enables continuation notices. Pass `false` for an intentionally ephemeral workflow with no mission for it or its children and no `state` global. Explicit mission persistence failures are strict. |
|
|
39
40
|
| `handoffPath` | string | - | Aggregate handoff manifest required by `action: "worktree.discard"`. |
|
|
40
|
-
| `focus` | boolean |
|
|
41
|
+
| `focus` | boolean | false | Focus the newly split pane for `action: "inspector.open"` or `action: "project.open"`; not a standalone action. Panes open in the background unless you set `focus: true`. |
|
|
41
42
|
| `view` | `fleet \| transcript` | - | Optional `status` view for the active fleet surface or transcript tail inspection. |
|
|
42
43
|
| `lines` | number | `80` | Maximum transcript lines for `action: "status", view: "transcript"`; capped at 500. |
|
|
43
44
|
| `agentScope` | `user \| project \| both` | `both` | Agent discovery scope. Project wins on collisions. |
|
|
44
|
-
| `async` | boolean | default-on | Background execution. Workflows default to background
|
|
45
|
-
| `chatProgress` | `auto \| off \| live-card` | `auto` | WorkflowScript chat projection. `auto` renders a live in-chat card only for watched foreground workflows in the same Git repository, including managed worktrees; it is off otherwise. Explicit `live-card` requires `async:false` and the same Git repository. |
|
|
45
|
+
| `async` | boolean | default-on | Background execution. Workflows default to background. `async:false` blocks the parent until completion. |
|
|
46
|
+
| `chatProgress` | `auto \| off \| live-card` | `auto` | WorkflowScript chat projection. `auto` renders a live in-chat card only for watched foreground workflows in the same Git repository, including managed worktrees; it is off otherwise. Explicit `live-card` requires `async:false` and the same Git repository. Async workflows have no inline live card, so omit `chatProgress` or use `auto`/`off`; use `async:false` only when the parent must block. |
|
|
47
|
+
| `isolation` | `none \| worktree` | - | Workflow child isolation. `none` runs in the shared cwd and does not need Git. `worktree` requires a managed Git worktree. Do not combine it with a contradictory `worktree` value. |
|
|
46
48
|
| `timeoutMs` / `maxRuntimeMs` | number | config `timeoutMs`, else 30 min foreground / single-agent async | Optional run-level max runtime in milliseconds. When omitted, the global [`timeoutMs`](configuration.md#timeoutms) config provides the default; absent that, foreground and plain single-agent async runs fall back to 30 minutes, while composite async runs (chains, parallel tasks, workflows) stay unbounded at the top level. |
|
|
47
49
|
| `toolTimeoutMs` | number | fast-tool default | Optional positive hard per-tool-call deadline in milliseconds. Precedence: call value → agent frontmatter → config → `PI_SUBAGENT_TOOL_TIMEOUT_MS`. The timer starts on `tool_execution_start`, clears on the matching `tool_execution_end`, and terminates the run with `timedOut: true` if the tool remains open. When omitted, known-fast built-in tools get a five-minute default; long-running tools get attention notices but no hard default. It never extends the run deadline; `contact_supervisor`, `intercom`, and `subagent_wait` are exempt. |
|
|
48
50
|
| `turnBudget` | object | none | Optional assistant-turn budget `{ maxTurns, graceTurns }`. At `maxTurns` the child is warned to wrap up. After the grace window (default 1), termination occurs at the next assistant boundary; a response that starts tool work records `termination-deferred` until a later boundary. Partial output is returned on abort. |
|
|
@@ -65,11 +67,34 @@ Bound writer work with a narrow task and an outer `timeoutMs` or `maxRuntimeMs`
|
|
|
65
67
|
|
|
66
68
|
### Fork context details
|
|
67
69
|
|
|
68
|
-
`context: "fork"` fails fast when the parent session is not persisted, the current leaf is missing, or the branched child session cannot be created.
|
|
70
|
+
Explicit `context: "fork"` fails fast when the parent session is not persisted, the current leaf is missing, or the branched child session cannot be created. By contrast, global `defaultSubagentContext: "fork"` and agent-level `defaultContext: fork` are preferences: when the parent has no persisted session file or current leaf yet, the launch uses `fresh` immediately instead of failing and requiring a retry. Global `defaultSubagentContext: "fresh"` starts fresh. Explicit `context: "fresh"` always wins over both preferences.
|
|
71
|
+
|
|
72
|
+
When the inherited transcript contains signed Anthropic `thinking` / `redacted_thinking` blocks, `pi-subagents` strips those provider-private blocks from the forked child session. It forces thinking `off` only when the child's effective primary or fallback model resolves through the model registry to the Anthropic provider or `anthropic-messages` API; unresolved models are treated conservatively. The result reports every affected child, including on failed runs. Use `context: "fresh"` when an Anthropic child needs thinking. Explicit `context: "fork"` never silently downgrades to `fresh`.
|
|
73
|
+
|
|
74
|
+
In workflow runs that omit `context`, each `runs.run` child follows the global `defaultSubagentContext` when set, then its own `defaultContext`. Without the global setting, a fresh-default scout can run fresh beside a fork-default worker. If the parent session file or current leaf is not available yet, implicit fork-default children run fresh. Pass explicit `context: "fork"` or `context: "fresh"` when you intentionally want one context for every child.
|
|
75
|
+
|
|
76
|
+
### Workflow steering
|
|
77
|
+
|
|
78
|
+
`runs.steer(key, message, options?)` targets a stable key already launched by `runs.run` or `runs.all`. It does not accept a raw run id. Options are `mode?: "steer" | "follow_up" | "auto"`, `index?: number`, and `ackTimeoutMs?: number`. The promise returns `{ key, state, requestId?, deliveryStatus?, targets?, error? }`, where `state` is `queued`, `delivered`, `missed`, or `failed`.
|
|
69
79
|
|
|
70
|
-
|
|
80
|
+
The workflow trace records the attempt and receipt. Always await, return, or include the promise in an awaited standard Promise combinator. Unawaited steering calls reject workflow completion after the side effect settles. `Promise.race` remains the rolling primitive. This slice reuses the foreground and async steering transports and disables steering recovery.
|
|
71
81
|
|
|
72
|
-
|
|
82
|
+
For advanced rolling fanout, keep the launched `runs.run` promises in ordinary JavaScript data only when every promise is later observed with direct `await`, `Promise.race`, or `Promise.all`. `Promise.race` gives the next completed child, `runs.steer` can challenge a still-running keyed sibling, and `Promise.all` collects the rest. No separate `runs.start`, `runs.next`, or `runs.collect` API is exposed.
|
|
83
|
+
|
|
84
|
+
```js
|
|
85
|
+
{ workflowScript: `
|
|
86
|
+
let pending = [
|
|
87
|
+
{ key: "writer", promise: runs.run("writer", { agent: "worker", task: "Draft the fix" }).then((result) => ({ key: "writer", result })) },
|
|
88
|
+
{ key: "reviewer", promise: runs.run("reviewer", { agent: "reviewer", task: "Review likely risks" }).then((result) => ({ key: "reviewer", result })) }
|
|
89
|
+
];
|
|
90
|
+
const first = await Promise.race(pending.map((child) => child.promise));
|
|
91
|
+
pending = pending.filter((child) => child.key !== first.key);
|
|
92
|
+
const target = pending[0];
|
|
93
|
+
const receipt = await runs.steer(target.key, "Use this early review:\n" + first.result.output, { mode: "auto" });
|
|
94
|
+
const rest = await Promise.all(pending.map((child) => child.promise));
|
|
95
|
+
return { first: first.key, rest: rest.map((child) => child.key), receipt };
|
|
96
|
+
` }
|
|
97
|
+
```
|
|
73
98
|
|
|
74
99
|
### Output mode details
|
|
75
100
|
|
|
@@ -79,12 +104,6 @@ In workflowScript, give each child an explicit output path when later script ste
|
|
|
79
104
|
|
|
80
105
|
Workflows get `await state.get(key)` and `await state.set(key, value)` through their default or explicit mission. Use them to share durable JSON values across later workflows attached with the same `missionId`. Each `set` takes the state-file lock and merges its key with the latest on-disk state. Missing keys return `undefined`, and the complete state file has a strict 256 KiB limit. `mission:false` workflows have no `state` global.
|
|
81
106
|
|
|
82
|
-
### Prompt fragments
|
|
83
|
-
|
|
84
|
-
Use `await prompts.render(ref, vars?)` to render reusable plain task text. Refs require an explicit scope: `package:<name>` reads the installed package `prompts/` directory, `user:<name>` reads the Pi agent `prompts/` directory, and `project:<name>` reads the current workflow project's config `prompts/` directory. Each ref names a top-level `<name>.md` file. Frontmatter is removed. Scalar string, number, and boolean variables replace matching `{{name}}` placeholders. Unknown placeholders stay unchanged.
|
|
85
|
-
|
|
86
|
-
Rendering only returns text to the sandbox. It does not give the script filesystem access and does not change child launch parameters, worktree capture, or cleanup. Pass the rendered result explicitly as `task`.
|
|
87
|
-
|
|
88
107
|
### Retained children
|
|
89
108
|
|
|
90
109
|
Completed workflow children from the current parent session stay addressable as retained children. `{ action: "children.list" }` lists up to the last 10 with their run ids and explicit `resumable` or `not resumable` state. Resume only rows reported `resumable`; if no row is resumable, start a same-role fallback challenge and label it as fallback. A later workflow continues a resumable child by passing `resume` instead of `agent`:
|
|
@@ -94,8 +113,7 @@ Completed workflow children from the current parent session stay addressable as
|
|
|
94
113
|
let writer = await runs.run("implement", { agent: "worker", task: "Implement the accepted contract" });
|
|
95
114
|
for (const pass of [1, 2]) {
|
|
96
115
|
if (!writer.runId) throw new Error("writer did not return a retained run id");
|
|
97
|
-
|
|
98
|
-
writer = await runs.run("followup-" + pass, { resume: writer.runId, task });
|
|
116
|
+
writer = await runs.run("followup-" + pass, { resume: writer.runId, task: "Revisit pass " + pass + ": " + writer.output });
|
|
99
117
|
}
|
|
100
118
|
return writer;
|
|
101
119
|
` }
|
|
@@ -113,7 +131,7 @@ For a simple implementation challenge outside a workflow script, send the challe
|
|
|
113
131
|
|
|
114
132
|
`{ action: "guide" }` reads the packaged `README.md` from the installed version. Pass `topic` to read its packaged `docs/<topic>.md` file instead. Valid topics are `overview`, `workflows`, `agents`, `missions`, `observability`, `tool-reference`, `configuration`, `models`, `watchdog`, and `extension-api`. Unknown topics list the valid values and do not change files. Use `/subagents-guide [topic]` for the slash equivalent.
|
|
115
133
|
|
|
116
|
-
Agent definitions are not loaded into context by default. Management actions let the LLM discover, inspect, create, update, and delete agents
|
|
134
|
+
Agent definitions are not loaded into context by default. Management actions let the LLM discover, inspect, create, update, and delete agents at runtime. An unknown action returns safe next steps (`status` and `list`) and may suggest a close non-destructive action. Destructive actions are only named for a near-complete one-character typo, and suggestions never execute an action.
|
|
117
135
|
|
|
118
136
|
```ts
|
|
119
137
|
{ action: "list" }
|
|
@@ -122,7 +140,6 @@ Agent definitions are not loaded into context by default. Management actions let
|
|
|
122
140
|
{ action: "models" }
|
|
123
141
|
{ action: "models", agent: "reviewer" }
|
|
124
142
|
{ action: "get", agent: "code-analysis.scout" }
|
|
125
|
-
{ action: "get", chainName: "review-pipeline" }
|
|
126
143
|
|
|
127
144
|
{ action: "create", config: {
|
|
128
145
|
name: "Code Scout",
|
|
@@ -146,22 +163,11 @@ Agent definitions are not loaded into context by default. Management actions let
|
|
|
146
163
|
progress: true
|
|
147
164
|
}}
|
|
148
165
|
|
|
149
|
-
{ action: "create", config: {
|
|
150
|
-
name: "review-pipeline",
|
|
151
|
-
description: "Scout then review",
|
|
152
|
-
scope: "project",
|
|
153
|
-
steps: [
|
|
154
|
-
{ agent: "scout", task: "Scan {task}", output: "context.md" },
|
|
155
|
-
{ agent: "reviewer", task: "Review {previous}", reads: ["context.md"] }
|
|
156
|
-
]
|
|
157
|
-
}}
|
|
158
166
|
|
|
159
167
|
{ action: "update", agent: "code-analysis.scout", config: { model: "openai/gpt-4o" } }
|
|
160
168
|
{ action: "update", agent: "code-analysis.scout", config: { acceptance: "" } } // clear the frontmatter default
|
|
161
169
|
{ action: "update", agent: "code-analysis.scout", config: { acceptanceRole: false } } // restore inferred name fallback
|
|
162
|
-
{ action: "update", chainName: "review-pipeline", config: { steps: [...] } }
|
|
163
170
|
{ action: "delete", agent: "scout" }
|
|
164
|
-
{ action: "delete", chainName: "review-pipeline" }
|
|
165
171
|
|
|
166
172
|
{ action: "eject", agent: "reviewer" }
|
|
167
173
|
{ action: "eject", agent: "reviewer", agentScope: "project" }
|
|
@@ -201,9 +207,6 @@ subagent({ action: "resume", id: "<nested-run-id>", message: "follow-up for a ne
|
|
|
201
207
|
subagent({ action: "steer", id: "<run-id>", message: "guidance for the running child" })
|
|
202
208
|
subagent({ action: "steer", id: "<run-id>", mode: "follow_up", message: "check this after the current turn" })
|
|
203
209
|
subagent({ action: "steer", id: "<run-id>", index: 1, mode: "auto", message: "guidance for child 2" })
|
|
204
|
-
subagent({ action: "append-step", id: "<run-id>", step: { agent: "worker", task: "Continue from {previous}" } })
|
|
205
|
-
subagent({ action: "approve-checkpoint", id: "<run-id>" })
|
|
206
|
-
subagent({ action: "reject-checkpoint", id: "<run-id>" })
|
|
207
210
|
subagent({ action: "doctor" })
|
|
208
211
|
```
|
|
209
212
|
|
|
@@ -247,10 +250,6 @@ Only a top-level single run may interrupt after the acknowledgment deadline and
|
|
|
247
250
|
|
|
248
251
|
The persisted `steering` ledger retains 20 requests and replaces the old `steerCount`/`lastSteerAt` fields.
|
|
249
252
|
|
|
250
|
-
### append-step
|
|
251
|
-
|
|
252
|
-
`append-step` requires `legacyChainControls: true`. The default registered model-facing schema omits this legacy control surface. When enabled, it accepts exactly one `step` object for an existing durable chain for a top-level async chain whose status is still `running`. The step is persisted in the run directory and becomes eligible only after the chain's already-queued steps finish. Completed, failed, rejected, paused, foreground, single, and non-chain runs reject appends.
|
|
253
|
-
|
|
254
253
|
## Acceptance gates
|
|
255
254
|
|
|
256
255
|
Every run resolves an effective acceptance policy. Callers may omit `acceptance` for the inferred default, or set it on single runs, top-level parallel task items, chain steps, static parallel tasks, and dynamic fanout templates.
|
|
@@ -326,11 +325,11 @@ Orca progress tabs are a global, opt-in observer, not an agent runner. Enable th
|
|
|
326
325
|
{ "orcaProgressTabs": { "enabled": true } }
|
|
327
326
|
```
|
|
328
327
|
|
|
329
|
-
Every foreground or background child keeps running through its normal native Pi or `external-cli` path. For each logical child, the observer asks Orca to create a background terminal tab in that child's current worktree and mirrors progress into it. Titles receive a persistent worktree-local sequence number, including across separate workflow calls. Model/startup retries reuse the same tab. Parallel and chain children each receive their own tab; attaching an already-running async root does not create a duplicate. Terminal control sequences are removed at the viewer sink across read boundaries. Each mirror is capped at 1 MiB and truncates when the cap or stream backpressure is reached. After the child finishes, its viewer returns to the terminal shell instead of ending the terminal session, so the tab and scrollback remain until the user closes them. Successful native Pi children with a known session append a safely quoted removal command for the exact verified session path; unsuccessful and sessionless children append only their terminal status.
|
|
328
|
+
Every foreground or background child keeps running through its normal native Pi or `external-cli` path. For each logical child, the observer asks Orca to create a background terminal tab in that child's current worktree and mirrors progress into it. Titles receive a persistent worktree-local sequence number, including across separate workflow calls. Creates for the same worktree are serialized in that sequence so tabs appear to the right in order (`1`, then `2`, then `3`) instead of racing. Model/startup retries reuse the same tab. Parallel and chain children each receive their own tab; attaching an already-running async root does not create a duplicate. Terminal control sequences are removed at the viewer sink across read boundaries. Each mirror is capped at 1 MiB and truncates when the cap or stream backpressure is reached. After the child finishes, its viewer returns to the terminal shell instead of ending the terminal session, so the tab and scrollback remain until the user closes them. Successful native Pi children with a known session append a safely quoted removal command for the exact verified session path; unsuccessful and sessionless children append only their terminal status.
|
|
330
329
|
|
|
331
330
|
The observer supports macOS and Linux and is disabled on Windows. It requires executable `orca` on `PATH` (or `PI_SUBAGENT_ORCA_BINARY`) and a running Orca runtime that recognizes the child cwd. Availability and tab creation are best-effort: failures never fail, stop, or delay the subagent. Set `orcaProgressTabs.enabled` to `false` to guarantee that no Orca command or tab is created.
|
|
332
331
|
|
|
333
|
-
Agent profile `runner.type`
|
|
332
|
+
Agent profile `runner.type` supports native Pi (the default), `external-cli`, and `external-job`. Orca is intentionally not a profile runner and does not own subagent execution, completion, cancellation, artifacts, or result delivery.
|
|
334
333
|
|
|
335
334
|
## External CLI agent profiles
|
|
336
335
|
|
package/docs/workflows.md
CHANGED
|
@@ -10,7 +10,7 @@ Use orchestration as parent-agent guidance, not as a runtime workflow mode. For
|
|
|
10
10
|
clarify → scout → worker → fresh reviewers → worker
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
Packaged `worker`, `oracle`, and `advisor` default to forked context when a launch omits `context
|
|
13
|
+
Packaged `worker`, `oracle`, and `advisor` default to forked context when a launch omits `context`. If the parent has no persisted session file or current leaf yet, that implicit default falls back to `fresh`. Pass `context: "fresh"` when you intentionally want a fresh child run, or `context: "fork"` when fork must remain strict.
|
|
14
14
|
|
|
15
15
|
Child-safety boundaries are enforced at runtime:
|
|
16
16
|
|
|
@@ -35,7 +35,9 @@ Add `autofix` to `/parallel-review` or `/parallel-cleanup` to apply only the syn
|
|
|
35
35
|
|
|
36
36
|
## Scripted workflows (workflowScript)
|
|
37
37
|
|
|
38
|
-
All model-facing subagent execution is expressed through `workflowScript` in the `subagent` tool. Use stable keys and ordinary JavaScript for one child, sequence, and parallelism. Scripts are ordinary JavaScript statement bodies. Use an explicit `return` for a useful result:
|
|
38
|
+
All model-facing subagent execution is expressed through `workflowScript` in the `subagent` tool. Use stable keys and ordinary JavaScript for one child, sequence, and parallelism. For ordinary parallel fanout, use `await runs.all([{ key, agent, task }, ...])`; do not read `.output` from unawaited `runs.run` launches. Store a `runs.run` promise only when the script later observes it with `await`, `Promise.race`, or `Promise.all`, such as steering a live child before awaiting its result. Scripts are ordinary JavaScript statement bodies. Use an explicit `return` for a useful result:
|
|
39
|
+
|
|
40
|
+
Child results cross into the script as plain JSON data. Non-JSON host metadata is omitted, so use returned fields such as `runId`, `ok`, `output`, and `structuredOutput` for workflow control.
|
|
39
41
|
|
|
40
42
|
```js
|
|
41
43
|
subagent({ workflowScript: `
|
|
@@ -48,6 +50,153 @@ subagent({ workflowScript: `
|
|
|
48
50
|
` });
|
|
49
51
|
```
|
|
50
52
|
|
|
53
|
+
Keep helper functions portable across Node and Bun. Use top-level `await`, plain helper functions that return `runs.run(...)`, or explicit Promise chains. Do not define nested `async function` helpers, async arrows, or async methods inside `workflowScript`; native async helpers hide child-launch observation in Bun and are rejected.
|
|
54
|
+
|
|
55
|
+
```js
|
|
56
|
+
subagent({ workflowScript: `
|
|
57
|
+
function scan() {
|
|
58
|
+
return runs.run("scan", { agent: "scout", task: "Scan the codebase" });
|
|
59
|
+
}
|
|
60
|
+
const result = await scan();
|
|
61
|
+
return result.output;
|
|
62
|
+
` });
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Chaining is still supported. The supported form is scripted chaining: await one `runs.run(...)` result, then pass its output into the next step. Parallel fanout uses `runs.all(...)` inside the same script.
|
|
66
|
+
|
|
67
|
+
```js
|
|
68
|
+
subagent({ workflowScript: `
|
|
69
|
+
const plan = await runs.run("plan", { agent: "scout", task: "Plan the migration" });
|
|
70
|
+
const patch = await runs.run("patch", { agent: "worker", task: "Implement this plan:\n" + plan.output });
|
|
71
|
+
return patch.output;
|
|
72
|
+
` });
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### Steering a workflow child
|
|
76
|
+
|
|
77
|
+
Use `await runs.steer(key, message, options?)` after `runs.run` or `runs.all` has launched that stable key. Scripts do not target raw run ids. The optional fields are `mode: "steer" | "follow_up" | "auto"`, a non-negative child `index`, and a positive `ackTimeoutMs`.
|
|
78
|
+
|
|
79
|
+
```js
|
|
80
|
+
subagent({ workflowScript: `
|
|
81
|
+
const writer = runs.run("writer", { agent: "worker", task: "Implement the change" });
|
|
82
|
+
const evidence = await runs.run("evidence", { agent: "scout", task: "Find the exact contract" });
|
|
83
|
+
const receipt = await runs.steer("writer", "Also check: " + evidence.output, { mode: "follow_up" });
|
|
84
|
+
return { writer: await writer, receipt };
|
|
85
|
+
` });
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The receipt state is `queued`, `delivered`, `missed`, or `failed`. `delivered` means the child Pi session accepted the input. It does not mean the model followed it. `missed` means the keyed child became terminal or had no live route before delivery. This first slice uses the existing foreground and async steering transports but does not start steering recovery. Workflow traces include one steering attempt entry and one receipt entry.
|
|
89
|
+
|
|
90
|
+
Always await or return a `runs.steer` promise. The workflow waits for an observed steering side effect to settle before it exits and rejects fire-and-forget calls. Use ordinary `Promise.race` when the first child or steering receipt should advance the script. There is no callback API or child inbox access.
|
|
91
|
+
|
|
92
|
+
### Advanced rolling child runs
|
|
93
|
+
|
|
94
|
+
`runs.run` starts a keyed child when you call it. You do not need separate `runs.start`, `runs.next`, or `runs.collect` helpers for rolling councils or staged reviews. This is the advanced exception to ordinary `runs.all` fanout: keep launched promises only when the script later observes each one with direct `await`, `Promise.race`, or `Promise.all`. Use `Promise.race` to wait for the next completed child, steer a still-running sibling by its stable key, and use `Promise.all` to collect the remaining children.
|
|
95
|
+
|
|
96
|
+
```js
|
|
97
|
+
subagent({ workflowScript: `
|
|
98
|
+
let pending = [
|
|
99
|
+
{ key: "analysis-a", promise: runs.run("analysis-a", { agent: "reviewer", task: "Analyze option A" }).then((result) => ({ key: "analysis-a", result })) },
|
|
100
|
+
{ key: "analysis-b", promise: runs.run("analysis-b", { agent: "reviewer", task: "Analyze option B" }).then((result) => ({ key: "analysis-b", result })) },
|
|
101
|
+
{ key: "critic", promise: runs.run("critic", { agent: "reviewer", task: "Find the strongest objection" }).then((result) => ({ key: "critic", result })) }
|
|
102
|
+
];
|
|
103
|
+
|
|
104
|
+
const first = await Promise.race(pending.map((child) => child.promise));
|
|
105
|
+
pending = pending.filter((child) => child.key !== first.key);
|
|
106
|
+
|
|
107
|
+
const target = pending.find((child) => child.key === "critic") ?? pending[0];
|
|
108
|
+
const receipt = await runs.steer(target.key, "Challenge this early result:\n" + first.result.output, { mode: "auto" });
|
|
109
|
+
const rest = await Promise.all(pending.map((child) => child.promise));
|
|
110
|
+
|
|
111
|
+
return { first: first.result.output, rest: rest.map((child) => child.result.output), receipt };
|
|
112
|
+
` });
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
The workflow trace records the run completions and steering receipt. Scripts still never see raw async directories, inbox paths, or session files. If the keyed child is terminal, stale, or has no live route when `runs.steer` runs, the receipt reports `missed` or `failed` and the script can decide whether to continue.
|
|
116
|
+
|
|
117
|
+
Use named outputs when later workflow steps need structured data or durable references:
|
|
118
|
+
|
|
119
|
+
```js
|
|
120
|
+
subagent({ workflowScript: `
|
|
121
|
+
const inventory = await runs.run("inventory", {
|
|
122
|
+
agent: "scout",
|
|
123
|
+
task: "List the files that need review.",
|
|
124
|
+
outputSchema: {
|
|
125
|
+
type: "object",
|
|
126
|
+
properties: { files: { type: "array", items: { type: "string" } } },
|
|
127
|
+
required: ["files"],
|
|
128
|
+
additionalProperties: false
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
return runs.run("review", {
|
|
132
|
+
agent: "reviewer",
|
|
133
|
+
task: "Review these files: " + inventory.structuredOutput.files.join(", ")
|
|
134
|
+
});
|
|
135
|
+
` });
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
For dynamic fanout, have one step return a structured list, check it in JavaScript, then map the bounded entries into `runs.all(...)`:
|
|
139
|
+
|
|
140
|
+
```js
|
|
141
|
+
subagent({ workflowScript: `
|
|
142
|
+
const targets = await runs.run("targets", {
|
|
143
|
+
agent: "scout",
|
|
144
|
+
task: "Return up to five source files that need review.",
|
|
145
|
+
outputSchema: {
|
|
146
|
+
type: "object",
|
|
147
|
+
properties: { files: { type: "array", items: { type: "string" }, maxItems: 5 } },
|
|
148
|
+
required: ["files"],
|
|
149
|
+
additionalProperties: false
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
const files = targets.structuredOutput.files.slice(0, 5);
|
|
153
|
+
return runs.all(files.map((file, index) => ({
|
|
154
|
+
key: "review-" + index,
|
|
155
|
+
agent: "reviewer",
|
|
156
|
+
task: "Review " + file
|
|
157
|
+
})));
|
|
158
|
+
` });
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
For intermediate data that only later steps need, prefer the prior child's returned output or `structuredOutput` instead of writing shared files:
|
|
162
|
+
|
|
163
|
+
```js
|
|
164
|
+
subagent({ workflowScript: `
|
|
165
|
+
const scan = await runs.run("scan", { agent: "scout", task: "Find the files that need fixes." });
|
|
166
|
+
return runs.run("fix", { agent: "worker", task: "Implement these findings:\n" + scan.output });
|
|
167
|
+
` });
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
`{chain_dir}` remains available inside scripted workflow step templates for legacy-compatible path templates. It expands to the workflow cwd, not to private temporary storage.
|
|
171
|
+
|
|
172
|
+
### Migrating old chain shapes
|
|
173
|
+
|
|
174
|
+
Legacy top-level `chain`, `tasks`, `parallel`, `chainDir`, `/chain`, `/parallel`, `/run-chain`, and durable `.chain.md` execution are no longer the public workflow API. Rewrite them as JavaScript:
|
|
175
|
+
|
|
176
|
+
```js
|
|
177
|
+
// Old shape, no longer supported:
|
|
178
|
+
// { chain: [{ agent: "scout", task: "Scan" }, { agent: "worker", task: "Fix from {previous}" }] }
|
|
179
|
+
|
|
180
|
+
// Current shape:
|
|
181
|
+
{ workflowScript: `
|
|
182
|
+
const scan = await runs.run("scan", { agent: "scout", task: "Scan" });
|
|
183
|
+
return runs.run("fix", { agent: "worker", task: "Fix from: " + scan.output });
|
|
184
|
+
` }
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
```js
|
|
188
|
+
// Old shape, no longer supported:
|
|
189
|
+
// { tasks: [{ agent: "reviewer", task: "Review API" }, { agent: "reviewer", task: "Review UI" }] }
|
|
190
|
+
|
|
191
|
+
// Current shape:
|
|
192
|
+
{ workflowScript: `
|
|
193
|
+
return runs.all([
|
|
194
|
+
{ key: "api", agent: "reviewer", task: "Review API" },
|
|
195
|
+
{ key: "ui", agent: "reviewer", task: "Review UI" }
|
|
196
|
+
]);
|
|
197
|
+
` }
|
|
198
|
+
```
|
|
199
|
+
|
|
51
200
|
For long task text with Markdown fences or shell blocks, use quoted lines instead of a raw template literal:
|
|
52
201
|
|
|
53
202
|
````js
|
|
@@ -62,7 +211,26 @@ return runs.run("test", { agent: "worker", task });
|
|
|
62
211
|
|
|
63
212
|
A plain workflow creates one enclosing mission by default. Its children do not create separate missions. The result exposes the id as `details.missionId`, and human-readable output ends with `Mission: <id> (<status>)`. Pass `mission:false` for an ephemeral workflow with no mission or durable `state` global.
|
|
64
213
|
|
|
65
|
-
|
|
214
|
+
### Repeatable workflows
|
|
215
|
+
|
|
216
|
+
Use stable child keys and keep process logic in ordinary JavaScript. `runs.run` launches one child, `runs.all` launches independent children together, and later steps can use each completed child's `output`. Put long task text in arrays joined with `"\n"` so Markdown fences do not conflict with the script string.
|
|
217
|
+
|
|
218
|
+
For a process you run often, save the task as a prompt template under `.pi/prompts/` or `~/.pi/agent/prompts/` and launch it with `/prompt-workflow`. The adapter compiles prompt steps into `workflowScript`, so templates describe the work instead of embedding raw `subagent` tool-call JSON. You can ask the parent agent to create or update these prompt files from a process described in natural language.
|
|
219
|
+
|
|
220
|
+
```md
|
|
221
|
+
---
|
|
222
|
+
description: Review a release candidate
|
|
223
|
+
subagent: reviewer
|
|
224
|
+
fresh: true
|
|
225
|
+
---
|
|
226
|
+
Review $@. Return concrete findings with source proof, or state that no issue was found.
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
```text
|
|
230
|
+
/prompt-workflow review-release-candidate v0.51.0
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
For watched same-repo workflows, pass `async:false` only when the parent must block until completion. That blocking mode also shows the live in-chat workflow card. `chatProgress` can force `off` or `live-card` when the automatic policy is not what you want. Blocking workflows default to a 30-minute timeout; async workflows have no default timeout. See the [tool reference](tool-reference.md) for the full parameter list.
|
|
66
234
|
|
|
67
235
|
The legacy `/chain`, `/parallel`, and `/run-chain` commands are not registered.
|
|
68
236
|
|
|
@@ -114,6 +282,8 @@ The parent replies with `subagent_supervisor({ action: "reply", replyTo, message
|
|
|
114
282
|
|
|
115
283
|
Child-side routine completion handoffs are not expected. If a child appears stalled, needs-attention notices show up in the parent session with useful next actions, such as checking `subagent({ action: "status" })`, interrupting the run, or nudging the child.
|
|
116
284
|
|
|
285
|
+
If a `workflowScript` child detaches through `contact_supervisor`, the enclosing async workflow stays `paused` until that child exits. Then the extension reconciles it to `complete` or `failed`. Wait on the child until that happens.
|
|
286
|
+
|
|
117
287
|
If messages do not show up, run `/subagents-doctor`. Advanced users can tune the bridge with `intercomBridge` in [configuration.md](configuration.md).
|
|
118
288
|
|
|
119
289
|
## Recursion guard
|