pi-subagents 0.50.0 → 0.51.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 (92) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/agents/gpt-pro.md +17 -0
  3. package/async-retention-discovery-worker.mjs +180 -0
  4. package/docs/agents.md +35 -2
  5. package/docs/configuration.md +30 -12
  6. package/docs/extension-api.md +42 -1
  7. package/docs/observability.md +4 -4
  8. package/docs/tool-reference.md +38 -39
  9. package/docs/workflows.md +169 -3
  10. package/package.json +4 -2
  11. package/skills/pi-subagents/SKILL.md +5 -4
  12. package/skills/pi-subagents/references/constraints-and-recipes.md +6 -4
  13. package/skills/pi-subagents/references/execution-controls.md +18 -15
  14. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  15. package/skills/pi-subagents/references/prompting-and-roles.md +2 -2
  16. package/src/agents/agent-management.ts +100 -345
  17. package/src/agents/agents.ts +125 -25
  18. package/src/api/external-job-provider.ts +185 -0
  19. package/src/api/preflight.ts +31 -6
  20. package/src/api/shared-types.ts +2 -0
  21. package/src/extension/config.ts +3 -3
  22. package/src/extension/doctor.ts +3 -6
  23. package/src/extension/fanout-child.ts +2 -2
  24. package/src/extension/index.ts +165 -88
  25. package/src/extension/public-execution.ts +28 -1
  26. package/src/extension/schemas.ts +12 -35
  27. package/src/extension/tool-description.ts +35 -24
  28. package/src/inspectors/herdr/actions.ts +2 -2
  29. package/src/inspectors/herdr/inspector-runner.ts +2 -1
  30. package/src/inspectors/herdr/project-panes.ts +2 -2
  31. package/src/intercom/native-supervisor-channel.ts +30 -9
  32. package/src/missions/lifecycle.ts +6 -1
  33. package/src/missions/store.ts +4 -9
  34. package/src/profiles/profiles.ts +3 -1
  35. package/src/runs/background/active-run-index.ts +31 -8
  36. package/src/runs/background/async-execution.ts +49 -31
  37. package/src/runs/background/async-job-tracker.ts +20 -4
  38. package/src/runs/background/async-resume.ts +28 -13
  39. package/src/runs/background/async-retention.ts +888 -0
  40. package/src/runs/background/async-status.ts +39 -53
  41. package/src/runs/background/chain-append.ts +3 -33
  42. package/src/runs/background/control-channel.ts +14 -68
  43. package/src/runs/background/index-segment.ts +59 -0
  44. package/src/runs/background/notify.ts +3 -1
  45. package/src/runs/background/result-files.ts +158 -90
  46. package/src/runs/background/result-watcher.ts +72 -20
  47. package/src/runs/background/retained-children.ts +13 -3
  48. package/src/runs/background/run-id-query.ts +7 -0
  49. package/src/runs/background/run-id-resolver.ts +11 -9
  50. package/src/runs/background/run-status.ts +27 -18
  51. package/src/runs/background/scheduled-runs.ts +22 -4
  52. package/src/runs/background/stale-run-reconciler.ts +6 -3
  53. package/src/runs/background/steering.ts +11 -1
  54. package/src/runs/background/subagent-runner.ts +250 -138
  55. package/src/runs/background/subagent-wait.ts +7 -7
  56. package/src/runs/background/terminal-run-index.ts +129 -0
  57. package/src/runs/background/wait-completions.ts +21 -4
  58. package/src/runs/background/wait-subscriptions.ts +80 -1
  59. package/src/runs/foreground/async-steering-action.ts +21 -14
  60. package/src/runs/foreground/execution.ts +2 -0
  61. package/src/runs/foreground/subagent-executor.ts +460 -1536
  62. package/src/runs/foreground/workflow-foreground-steering.ts +6 -5
  63. package/src/runs/shared/chain-outputs.ts +1 -3
  64. package/src/runs/shared/external-job-bridge.ts +450 -0
  65. package/src/runs/shared/external-job-runner.ts +286 -0
  66. package/src/runs/shared/mcp-direct-tool-allowlist.ts +14 -0
  67. package/src/runs/shared/model-fallback.ts +22 -5
  68. package/src/runs/shared/orca-progress-tabs.ts +84 -22
  69. package/src/runs/shared/parallel-handoff.ts +46 -4
  70. package/src/runs/shared/parallel-utils.ts +4 -15
  71. package/src/runs/shared/permissions.ts +5 -1
  72. package/src/runs/shared/pi-args.ts +8 -1
  73. package/src/runs/shared/subagent-control.ts +26 -4
  74. package/src/runs/shared/subagent-prompt-runtime.ts +12 -6
  75. package/src/runs/shared/workflow-graph.ts +1 -23
  76. package/src/runs/shared/worktree.ts +12 -1
  77. package/src/shared/atomic-json.ts +22 -2
  78. package/src/shared/capacity-resilient-json.ts +102 -0
  79. package/src/shared/completion-owner.ts +14 -0
  80. package/src/shared/file-system-retry.ts +49 -1
  81. package/src/shared/fork-context.ts +42 -0
  82. package/src/shared/prompt-resources.ts +0 -40
  83. package/src/shared/settings.ts +3 -27
  84. package/src/shared/types.ts +60 -26
  85. package/src/shared/utils.ts +8 -0
  86. package/src/shared/watch-strategy.ts +10 -0
  87. package/src/slash/slash-commands.ts +11 -3
  88. package/src/tui/fleet.ts +63 -15
  89. package/src/workflows/chat-progress.ts +1 -1
  90. package/src/workflows/scripted-workflow.ts +207 -65
  91. package/src/runs/foreground/chain-clarify.ts +0 -1354
  92. package/src/runs/foreground/chain-execution.ts +0 -1581
@@ -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
- | `chainName` | string | - | Chain name for management actions. |
35
- | `config` | object/string | - | Agent or existing durable chain config for management create/update. |
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 | true | Focus the newly split pane for `action: "inspector.open"` or `action: "project.open"`; not a standalone action. |
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 and accept `async:false` as an explicit foreground escape hatch. |
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
- 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. Forking never silently downgrades to `fresh`.
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
- In workflow runs that omit `context`, each `runs.run` child follows its own `defaultContext`, so a fresh-default scout can run fresh beside a fork-default worker. Pass explicit `context: "fork"` or `context: "fresh"` when you intentionally want one context for every child.
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
- const task = await prompts.render("project:writer-followup", { pass, previous: writer.output });
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 and chains 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.
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` remains unchanged: supported values are native Pi (the default) and `external-cli`. Orca is intentionally not a profile runner and does not own subagent execution, completion, cancellation, artifacts, or result delivery.
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`; pass `context: "fresh"` when you intentionally want a fresh child run.
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,7 @@ 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
39
 
40
40
  ```js
41
41
  subagent({ workflowScript: `
@@ -48,6 +48,153 @@ subagent({ workflowScript: `
48
48
  ` });
49
49
  ```
50
50
 
51
+ 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.
52
+
53
+ ```js
54
+ subagent({ workflowScript: `
55
+ function scan() {
56
+ return runs.run("scan", { agent: "scout", task: "Scan the codebase" });
57
+ }
58
+ const result = await scan();
59
+ return result.output;
60
+ ` });
61
+ ```
62
+
63
+ 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.
64
+
65
+ ```js
66
+ subagent({ workflowScript: `
67
+ const plan = await runs.run("plan", { agent: "scout", task: "Plan the migration" });
68
+ const patch = await runs.run("patch", { agent: "worker", task: "Implement this plan:\n" + plan.output });
69
+ return patch.output;
70
+ ` });
71
+ ```
72
+
73
+ ### Steering a workflow child
74
+
75
+ 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`.
76
+
77
+ ```js
78
+ subagent({ workflowScript: `
79
+ const writer = runs.run("writer", { agent: "worker", task: "Implement the change" });
80
+ const evidence = await runs.run("evidence", { agent: "scout", task: "Find the exact contract" });
81
+ const receipt = await runs.steer("writer", "Also check: " + evidence.output, { mode: "follow_up" });
82
+ return { writer: await writer, receipt };
83
+ ` });
84
+ ```
85
+
86
+ 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.
87
+
88
+ 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.
89
+
90
+ ### Advanced rolling child runs
91
+
92
+ `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.
93
+
94
+ ```js
95
+ subagent({ workflowScript: `
96
+ let pending = [
97
+ { key: "analysis-a", promise: runs.run("analysis-a", { agent: "reviewer", task: "Analyze option A" }).then((result) => ({ key: "analysis-a", result })) },
98
+ { key: "analysis-b", promise: runs.run("analysis-b", { agent: "reviewer", task: "Analyze option B" }).then((result) => ({ key: "analysis-b", result })) },
99
+ { key: "critic", promise: runs.run("critic", { agent: "reviewer", task: "Find the strongest objection" }).then((result) => ({ key: "critic", result })) }
100
+ ];
101
+
102
+ const first = await Promise.race(pending.map((child) => child.promise));
103
+ pending = pending.filter((child) => child.key !== first.key);
104
+
105
+ const target = pending.find((child) => child.key === "critic") ?? pending[0];
106
+ const receipt = await runs.steer(target.key, "Challenge this early result:\n" + first.result.output, { mode: "auto" });
107
+ const rest = await Promise.all(pending.map((child) => child.promise));
108
+
109
+ return { first: first.result.output, rest: rest.map((child) => child.result.output), receipt };
110
+ ` });
111
+ ```
112
+
113
+ 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.
114
+
115
+ Use named outputs when later workflow steps need structured data or durable references:
116
+
117
+ ```js
118
+ subagent({ workflowScript: `
119
+ const inventory = await runs.run("inventory", {
120
+ agent: "scout",
121
+ task: "List the files that need review.",
122
+ outputSchema: {
123
+ type: "object",
124
+ properties: { files: { type: "array", items: { type: "string" } } },
125
+ required: ["files"],
126
+ additionalProperties: false
127
+ }
128
+ });
129
+ return runs.run("review", {
130
+ agent: "reviewer",
131
+ task: "Review these files: " + inventory.structuredOutput.files.join(", ")
132
+ });
133
+ ` });
134
+ ```
135
+
136
+ For dynamic fanout, have one step return a structured list, check it in JavaScript, then map the bounded entries into `runs.all(...)`:
137
+
138
+ ```js
139
+ subagent({ workflowScript: `
140
+ const targets = await runs.run("targets", {
141
+ agent: "scout",
142
+ task: "Return up to five source files that need review.",
143
+ outputSchema: {
144
+ type: "object",
145
+ properties: { files: { type: "array", items: { type: "string" }, maxItems: 5 } },
146
+ required: ["files"],
147
+ additionalProperties: false
148
+ }
149
+ });
150
+ const files = targets.structuredOutput.files.slice(0, 5);
151
+ return runs.all(files.map((file, index) => ({
152
+ key: "review-" + index,
153
+ agent: "reviewer",
154
+ task: "Review " + file
155
+ })));
156
+ ` });
157
+ ```
158
+
159
+ For intermediate data that only later steps need, prefer the prior child's returned output or `structuredOutput` instead of writing shared files:
160
+
161
+ ```js
162
+ subagent({ workflowScript: `
163
+ const scan = await runs.run("scan", { agent: "scout", task: "Find the files that need fixes." });
164
+ return runs.run("fix", { agent: "worker", task: "Implement these findings:\n" + scan.output });
165
+ ` });
166
+ ```
167
+
168
+ `{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.
169
+
170
+ ### Migrating old chain shapes
171
+
172
+ 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:
173
+
174
+ ```js
175
+ // Old shape, no longer supported:
176
+ // { chain: [{ agent: "scout", task: "Scan" }, { agent: "worker", task: "Fix from {previous}" }] }
177
+
178
+ // Current shape:
179
+ { workflowScript: `
180
+ const scan = await runs.run("scan", { agent: "scout", task: "Scan" });
181
+ return runs.run("fix", { agent: "worker", task: "Fix from: " + scan.output });
182
+ ` }
183
+ ```
184
+
185
+ ```js
186
+ // Old shape, no longer supported:
187
+ // { tasks: [{ agent: "reviewer", task: "Review API" }, { agent: "reviewer", task: "Review UI" }] }
188
+
189
+ // Current shape:
190
+ { workflowScript: `
191
+ return runs.all([
192
+ { key: "api", agent: "reviewer", task: "Review API" },
193
+ { key: "ui", agent: "reviewer", task: "Review UI" }
194
+ ]);
195
+ ` }
196
+ ```
197
+
51
198
  For long task text with Markdown fences or shell blocks, use quoted lines instead of a raw template literal:
52
199
 
53
200
  ````js
@@ -62,7 +209,26 @@ return runs.run("test", { agent: "worker", task });
62
209
 
63
210
  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
211
 
65
- For watched same-repo workflows, pass `async:false` to show the live in-chat workflow card. `chatProgress` can force `off` or `live-card` when the automatic policy is not what you want. Foreground 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.
212
+ ### Repeatable workflows
213
+
214
+ 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.
215
+
216
+ 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.
217
+
218
+ ```md
219
+ ---
220
+ description: Review a release candidate
221
+ subagent: reviewer
222
+ fresh: true
223
+ ---
224
+ Review $@. Return concrete findings with source proof, or state that no issue was found.
225
+ ```
226
+
227
+ ```text
228
+ /prompt-workflow review-release-candidate v0.51.0
229
+ ```
230
+
231
+ 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
232
 
67
233
  The legacy `/chain`, `/parallel`, and `/run-chain` commands are not registered.
68
234
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagents",
3
- "version": "0.50.0",
3
+ "version": "0.51.0",
4
4
  "description": "Pi extension for single-agent delegation and scripted multi-agent workflows",
5
5
  "author": "Nico Bailon",
6
6
  "license": "MIT",
@@ -8,6 +8,7 @@
8
8
  "exports": {
9
9
  ".": "./index.ts",
10
10
  "./background-work": "./src/api/background-work.ts",
11
+ "./external-job-provider": "./src/api/external-job-provider.ts",
11
12
  "./external-runs": "./src/api/external-runs.ts",
12
13
  "./delegation": "./src/api/delegation.ts",
13
14
  "./capability-ceiling": "./src/api/capability-ceiling.ts",
@@ -52,7 +53,7 @@
52
53
  "scripts": {
53
54
  "typecheck": "tsc --noEmit",
54
55
  "test": "npm run test:unit",
55
- "test:unit": "node --experimental-strip-types --test test/unit/*.test.ts",
56
+ "test:unit": "node --experimental-strip-types --import ./test/support/isolated-temp-root.mjs --test test/unit/*.test.ts",
56
57
  "test:integration": "node --experimental-strip-types --import ./test/support/register-loader.mjs --test test/integration/*.test.ts",
57
58
  "test:e2e": "node --experimental-strip-types --import ./test/support/register-loader.mjs --test test/e2e/*.test.ts",
58
59
  "test:all": "npm run test:unit && npm run test:integration && npm run test:e2e"
@@ -89,6 +90,7 @@
89
90
  }
90
91
  },
91
92
  "dependencies": {
93
+ "acorn": "8.18.0",
92
94
  "jiti": "2.7.0",
93
95
  "typebox": "1.1.38",
94
96
  "yaml": "2.8.3"
@@ -2,7 +2,7 @@
2
2
  name: pi-subagents
3
3
  description: |
4
4
  Delegate work to builtin or custom subagents with single-agent, parallel,
5
- scripted, compatibility-chain, async, forked-context, and coordinated workflows. Use
5
+ scripted-chaining, async, forked-context, and coordinated workflows. Use
6
6
  for advisory review, implementation handoffs, and multi-step tasks where a
7
7
  single agent should stay in control while other agents contribute context,
8
8
  planning, or execution.
@@ -12,7 +12,7 @@ description: |
12
12
 
13
13
  This skill is for the main parent orchestrator only. Do not inject or follow it inside spawned child subagents. The parent session owns delegation, orchestration, review fanout, and final fix-worker launches. Ordinary children should not run their own subagent workflows; the explicit exception is a delegated fanout child whose resolved builtin `tools` includes `subagent`, and that child may use `subagent` only for the fanout work the parent assigned.
14
14
 
15
- Use this skill when the parent orchestrator needs one specialized child or composed orchestration. Use `workflowScript` for all execution, including one isolated child. Use `return runs.run("main", { agent, task })` for one child and `runs.all([...])` for coordinated waves: sequence, parallelism, branching, retries, gate monitors, and aggregation. Scripted workflows start asynchronously by default; pass `async:false` only for a small foreground run.
15
+ Use this skill when the parent orchestrator needs one specialized child or composed orchestration. Use `workflowScript` for all execution, including one isolated child. Chaining is still supported, but it is code-driven: use `await runs.run(...)` for sequential steps, `runs.all([...])` for parallel fanout, and ordinary JavaScript for branching, retries, gate monitors, and aggregation. Keep workflow helpers portable: use plain helper functions or explicit Promise chains, not nested `async function` helpers, async arrows, or async methods. Do not use legacy top-level `chain` / `tasks` inputs or durable `.chain.md` execution. Scripted workflows normally start asynchronously unless config sets `asyncByDefault:false`; set `async:true` explicitly when async behavior matters. Pass `async:false` only when the parent must block until completion. Async mode still shows progress. Do not use `async:false` for final reviews, backlog gates, run-to-completion convenience, or because no other work is available.
16
16
 
17
17
  ## How to use this router
18
18
 
@@ -22,7 +22,7 @@ Read the matching reference file before acting. Paths are relative to this `SKIL
22
22
  | --- | --- |
23
23
  | Decide whether to delegate, choose agents, compare tool versus slash commands, apply prompt techniques, or understand builtin roles | `references/prompting-and-roles.md` |
24
24
  | Run one-child, scripted, async, scheduled, mission-backed, forked, watchdog, oracle, or intercom-coordinated workflows | `references/execution-controls.md` |
25
- | List/create/update/delete/eject/disable agents or chains, edit agent files, use prompt-template integration, or expose extension RPC | `references/management-authoring-rpc.md` |
25
+ | List/create/update/delete/eject/disable agents, inspect legacy chain records, edit agent files, use prompt-template integration, or expose extension RPC | `references/management-authoring-rpc.md` |
26
26
  | Check safety constraints, best practices, standard workflows, or error handling | `references/constraints-and-recipes.md` |
27
27
 
28
28
  For broad or uncertain requests, read more than one reference. For complex work, start with `references/prompting-and-roles.md` and `references/execution-controls.md`, then consult `references/constraints-and-recipes.md` before launching or reviewing child work.
@@ -34,7 +34,8 @@ For broad or uncertain requests, read more than one reference. For complex work,
34
34
  - For cross-codebase work, record the target repo, explicit `cwd`, authority boundary, and expected output before launch. Do not assume the parent session cwd is the child repo.
35
35
  - For parallel fanout, compare child prompts before launch. Do not send clone prompts with only issue numbers, titles, or broad file globs swapped; each child needs a lane-specific task, source seam, prior evidence, and decision that remains distinct without the item number. Launch that fanout as one async `workflowScript` with stable keys and aggregate output unless there is truly only one child.
36
36
  - Prefer fresh-context review/validation fanout, then synthesize and apply fixes in the parent.
37
- - Use async/background by default when work can proceed independently; do not poll just to wait. For adaptive gates, branch in `workflowScript`. Approval controls remain available only for already-running durable legacy chains.
37
+ - Use async/background by default. Final reviews, gate checks, oracle checks, and backlog lanes stay async. Use `async:false` only when the parent must block until completion. Do not poll just to wait. For adaptive gates, branch in `workflowScript`.
38
+ - For Pi extension repos whose canonical checkout is under `~/.pi/agent/extensions`, never create lane worktrees as sibling directories there. Pi auto-loads `~/.pi/agent/extensions/*/index.ts`, so sibling worktrees can register duplicate tools. Put lanes under `~/.pi/agent/worktrees`, another worktree base outside auto-discovery, or a temporary clone. If a lane must run the modified extension itself, use an isolated Pi config home with `PI_CODING_AGENT_DIR=<lane-config> pi --no-extensions -e <lane>/index.ts`. Use full containers only when path and config isolation are insufficient.
38
39
  - Preserve capability ceilings, including child tool restrictions and session-scoped allowed-agent restrictions.
39
40
  - Escalate unresolved product, architecture, authority, release, merge, or safety decisions upward instead of letting a child decide silently.
40
41
  - Treat receipts, CI, review bots, and external-run records as evidence, not authority to merge, close, comment, publish, or release.
@@ -4,10 +4,12 @@ This file is a detailed reference loaded from `skills/pi-subagents/SKILL.md`.
4
4
 
5
5
  ## Important Constraints
6
6
 
7
- - **Forking requires a persisted parent session.** If the current session does not
8
- have a persisted session file, forked runs fail. Packaged `worker`, `oracle`,
9
- and `advisor` default to forked context, so use `context: "fresh"` explicitly
10
- when that is not available or not wanted.
7
+ - **Explicit forking requires a persisted parent session.** If the current session
8
+ does not have a persisted session file or current leaf, explicit `context: "fork"`
9
+ fails. An agent-level `defaultContext: fork` is a preference: packaged `worker`,
10
+ `oracle`, and `advisor` fall back to `fresh` when those fork preconditions are not
11
+ met yet. Use `context: "fresh"` when you do not want a fork even after the parent
12
+ session exists.
11
13
  - **Forked runs inherit parent history.** They are branched threads, not fresh
12
14
  filtered contexts. Use fresh context for adversarial reviewers unless the user explicitly asks for forked context.
13
15
  - **Default subagent nesting depth is 2.** Deeper recursive delegation is blocked
@@ -26,6 +26,14 @@ An agent may set `runner.type: external-cli` with a non-empty `command`, optiona
26
26
 
27
27
  External CLI profiles are async-only and one-shot. They support lifecycle artifacts, stdout/stderr logs, timeout, and stop. Full stdout and stderr are retained in their log files, while the final stdout response and stderr error kept in memory are each limited to their last 64 KiB. They do not support foreground/clarify, steer/resume/interrupt-as-pause, Pi models/tools/extensions/skills, tool or turn budgets, structured output, nested subagents, fallbacks, or sessions.
28
28
 
29
+ ### External job profiles
30
+
31
+ An agent may set `runner.type: external-job` with a non-empty `provider` and optional JSON `options`. The bundled `gpt-pro` agent uses provider `surf-oracle`. The provider must be registered in the host Pi process through `pi-subagents/external-job-provider`; the async runner talks to that parent-owned registry through a local operation bridge.
32
+
33
+ External job profiles are async-only. The provider owns the remote job and Pi owns the async run record. Status persists provider name, provider job id, prompt digest, provider options, handle/conversation URLs when supplied, result artifact path, last known state, and provider failure code/message. Recovery uses existing provider job metadata to call `reattach` and `result`; it refuses to redispatch a prompt when the persisted provider job does not match the prompt digest.
34
+
35
+ External job profiles do not support foreground/clarify, steer/resume, Pi models/tools/extensions/skills, tool or turn budgets, structured output, native child permissions, fallbacks, or Pi child sessions. Capacity conflicts fail closed and include the blocking provider job id when the provider supplies it.
36
+
29
37
  ### Single agent
30
38
 
31
39
  ```typescript
@@ -53,7 +61,7 @@ its resolved launch context as `[fresh]` or `[fork]`. Aggregate headers show
53
61
 
54
62
  ### Scripted workflows
55
63
 
56
- `workflowScript` is the sole public execution surface. Use `runs.run(key, { agent, task, ... })` for one child, `runs.all([...])` for parallel children, and ordinary JavaScript for sequence, branching, filtering, retries, and aggregation. Scripts are ordinary JavaScript statement bodies, so use an explicit return such as `workflowScript: "return runs.run('main', { agent: 'worker', task: '...' })"` for a useful one-child result. Prefer a single scripted workflow whenever the parent is starting a coordinated wave, such as multiple reviews, review plus gate monitor, worker then monitor setup, cross-repo prep lanes, or a fanout that the parent will consume together.
64
+ `workflowScript` is the sole public execution surface. Use `runs.run(key, { agent, task, ... })` for one child, `runs.all([...])` for parallel children, and ordinary JavaScript for sequence, branching, filtering, retries, and aggregation. Scripts are ordinary JavaScript statement bodies, so use an explicit return such as `workflowScript: "return runs.run('main', { agent: 'worker', task: '...' })"` for a useful one-child result. Use top-level `await`, plain helper functions, or explicit Promise chains; nested `async function` helpers, async arrows, and async methods are rejected. Prefer a single scripted workflow whenever the parent is starting a coordinated wave, such as multiple reviews, review plus gate monitor, worker then monitor setup, cross-repo prep lanes, or a fanout that the parent will consume together.
57
65
 
58
66
  ```js
59
67
  subagent({
@@ -68,21 +76,23 @@ subagent({
68
76
  })
69
77
  ```
70
78
 
71
- Scripts run in a timed worker with only `runs.run`, `runs.all`, `runs.status`, `runs.ref/refs`, `prompts.render`, `emit`, captured `console`, and standard JavaScript. `await prompts.render("package:<name>" | "user:<name>" | "project:<name>", vars?)` reads a named Markdown fragment through the host resolver, applies simple scalar `{{name}}` interpolation, and returns plain task text. It does not give the script filesystem access. Pass the rendered text explicitly as `task` to `runs.run`. Mission-attached workflows also get `await state.get(key)` and `await state.set(key, value)` for durable JSON state shared across workflows on the same mission; `mission: false` workflows have no `state` global. Stable keys are required. Child launches follow ordinary single-agent execution controls. Give each child a distinct decision and output path when reports must outlive the workflow, then consume the aggregate workflow result before opening individual reports.
79
+ Scripts run in a timed worker with only `runs.run`, `runs.all`, `runs.status`, `runs.ref/refs`, `emit`, captured `console`, and standard JavaScript. Pass explicit task text to `runs.run`. Mission-attached workflows also get `await state.get(key)` and `await state.set(key, value)` for durable JSON state shared across workflows on the same mission; `mission: false` workflows have no `state` global. Stable keys are required. Child launches follow ordinary single-agent execution controls. Give each child a distinct decision and output path when reports must outlive the workflow, then consume the aggregate workflow result before opening individual reports.
72
80
 
73
81
  For one host-run verification command, pass `gate: "npm test"` on a `runs.run`/`runs.all` item (or at the top level as a workflow default). It is shorthand for verified acceptance with that single command: the runtime executes it on the host, records the result as evidence, and memoizes it per tracked workspace state and effective environment. `gate` cannot be combined with `acceptance`; use explicit `acceptance.verify` for multiple commands or custom criteria.
74
82
 
75
- Completed workflow children from this parent session stay addressable as retained children. `subagent({ action: "children.list" })` lists up to the last 10 with run ids and reports each row as `resumable` or `not resumable` with a reason. Resume only rows reported `resumable`. For a retained-child challenge, use `resume` instead of `steer` when the child is complete. If no retained child is resumable, launch a same-role fallback challenge and label it as fallback. A later workflow continues a resumable child with `runs.run(key, { resume: "<run-id>", task: "follow-up" })`. Inside `workflowScript`, awaiting that call waits for the revived child to finish and returns its completed output and new `runId`; top-level `{ action: "resume" }` remains detached. A follow-up loop can render each task with `await prompts.render(...)`. Assign each returned child result back to the loop variable because every resume can return a new retained `runId`; always resume the latest returned id. `resume` and `agent` are mutually exclusive, the revived child keeps its stored agent/model/tool contract, and `gate` is rejected on retained resume items.
83
+ Completed workflow children from this parent session stay addressable as retained children. `subagent({ action: "children.list" })` lists up to the last 10 with run ids and reports each row as `resumable` or `not resumable` with a reason. Resume only rows reported `resumable`. For a retained-child challenge, use `resume` instead of `steer` when the child is complete. If no retained child is resumable, launch a same-role fallback challenge and label it as fallback. A later workflow continues a resumable child with `runs.run(key, { resume: "<run-id>", task: "follow-up" })`. Inside `workflowScript`, awaiting that call waits for the revived child to finish and returns its completed output and new `runId`; top-level `{ action: "resume" }` remains detached. Pass explicit follow-up task text. Assign each returned child result back to the loop variable because every resume can return a new retained `runId`; always resume the latest returned id. `resume` and `agent` are mutually exclusive, the revived child keeps its stored agent/model/tool contract, and `gate` is rejected on retained resume items.
76
84
 
77
85
  ### Async/background
78
86
 
79
- Prefer async mode for every subagent launch. Set `async: true` no matter the task unless there is a specific reason to opt into a foreground/blocking run. This applies to scouts, researchers, workers, reviewers, validators, oracle checks, one-off delegates, and scripted workflows. Keep the write path single-threaded even when the run is async.
87
+ Prefer async mode for every subagent launch. Set `async: true` no matter the task unless the parent must block until completion. This applies to scouts, researchers, workers, reviewers, validators, oracle checks, one-off delegates, final review gates, backlog gates, and scripted workflows. Keep the write path single-threaded even when the run is async.
88
+
89
+ Use `async:false` only when the parent must block until completion. Async mode still shows progress. Do not use `async:false` because a task is short, because it is the last gate, because no other work is ready, because the user asked to finish the overall job, or because blocking is convenient.
80
90
 
81
91
  Async does not mean parallel writes. Do not edit the same active worktree while an async worker is changing it. Parent-side overlap should be reading, validation prep, synthesis, command planning, or review of unaffected context unless the writer is isolated in a separate worktree.
82
92
 
83
- Do not end your turn immediately after launching an async child if you promised to keep working. Continue the local inspection, synthesis, or validation prep, then check the async run when its result is needed.
93
+ Do not end your turn immediately after launching an async child if you promised to keep working. Continue the local inspection, synthesis, or validation prep, then check the async run when its result is needed. If no safe independent work remains, return control and let Pi wake the session; do not convert the child to foreground.
84
94
 
85
- In an interactive chat, normally return control when ready to yield and let Pi wake the session on completion; do not call `subagent_wait()` merely to wait. Override that default and call it when the current request is run-to-completion — for example, the user asked you to report results back before continuing or a skill cannot return before its background work finishes. Headless sessions auto-drain exact current-session work at `agent_end`; call `subagent_wait()` when this turn must receive results before it ends. Never substitute sleep or status-polling loops.
95
+ In an interactive chat, normally return control when ready to yield and let Pi wake the session on completion; do not call `subagent_wait()` merely to wait. A run-to-completion user request is not by itself a reason to use foreground children. Override the normal yield-and-wake flow only when this exact turn cannot safely end without the result, such as a headless provider flow or a skill contract that must produce a same-turn artifact. Use `subagent_wait()`, not `async:false`, for that current-turn dependency. Never substitute sleep or status-polling loops.
86
96
 
87
97
  `subagent_wait()` returns when the next initially active async run or registered provider item finishes or a subagent needs attention. Use `subagent_wait({ all: true })` for all work active at call time, `subagent_wait({ id: "..." })` for one async or remembered detached foreground run, and `subagent_wait({ timeoutMs })` to cap the block. In a long-lived interactive parent session, use `subagent_wait({ id: "...", nonBlocking: true })` to resolve the prefix to one exact run, persist an armed subscription, return immediately, and wake later on completion, failure, attention, reconciliation failure, or timeout. Ordinary status lists armed subscriptions separately from active children. This differs from disabling `waitTool`, which returns immediately without arming a future wake. If a foreground child detaches for supervisor coordination, reply first, then wait on its id; do not resume or launch a replacement while it remains detached. Headless sessions also auto-drain exact current-session work at `agent_end` as a final safeguard.
88
98
 
@@ -110,17 +120,10 @@ While children run, the persistent FleetView and the collapsed foreground tool-r
110
120
 
111
121
  Inspect async runs with `subagent({ action: "status", id: "..." })` or `subagent({ action: "status" })` for active runs. Use `subagent({ action: "status", view: "fleet" })` when supervising several active foreground/background runs and `subagent({ action: "status", id: "...", view: "transcript", index: 0 })` when you need the latest child output without digging through artifacts. If a delegated fanout child launches nested runs, the parent status view shows them as a tree and you can target a nested run directly with its nested id.
112
122
 
113
- Stop a current-session top-level async run with `stop` (or `/subagents-stop`). Stopped runs finish as `stopped`/cancelled and are not resumable. For an active foreground single-subagent run, `/subagents-detach [run-id]` leaves the child running without terminating it and returns the eventual result through status/wait. Append one more step to the tail of a still-running durable chain with `append-step` (`step` must contain exactly one step object). Use checkpoint steps for planned human gates; they pause without launching a child and are approved or rejected through current-session control actions:
123
+ Stop a current-session top-level async run with `stop` (or `/subagents-stop`). Stopped runs finish as `stopped`/cancelled and are not resumable. For an active foreground single-subagent run, `/subagents-detach [run-id]` leaves the child running without terminating it and returns the eventual result through status/wait.
114
124
 
115
125
  ```typescript
116
126
  subagent({ action: "stop", id: "run-id" })
117
- subagent({
118
- action: "append-step",
119
- id: "run-id",
120
- step: { checkpoint: "review", message: "Approve the next implementation step?" }
121
- })
122
- subagent({ action: "approve-checkpoint", id: "run-id" })
123
- subagent({ action: "reject-checkpoint", id: "run-id" })
124
127
  ```
125
128
 
126
129
  Use `steer` for top-level live async guidance and `resume` after a delegated run pauses or finishes. Routed nested runs retain their existing non-destructive live follow-up path:
@@ -183,7 +186,7 @@ Humans can use `/subagents-doctor` for the same read-only report. It checks runt
183
186
 
184
187
  ### Subagent control
185
188
 
186
- Subagent control is the runtime visibility and intervention layer for delegated runs. It is separate from lifecycle status. Lifecycle status says whether a child is `queued`, `running`, `paused`, `complete`, `stopped`, `failed`, or `rejected`. Activity reporting is factual: it tracks the last observed activity time and the current tool when known. It does not pretend to know that a child is truly stuck. Manual top-level async cancellation uses `stop` / `/subagents-stop`; a live async chain can gain one more tail step via `append-step`, and a paused async chain checkpoint can be decided with `approve-checkpoint` or `reject-checkpoint`.
189
+ Subagent control is the runtime visibility and intervention layer for delegated runs. It is separate from lifecycle status. Lifecycle status says whether a child is `queued`, `running`, `paused`, `complete`, `stopped`, `failed`, or `rejected`. Activity reporting is factual: it tracks the last observed activity time and the current tool when known. It does not pretend to know that a child is truly stuck. Manual top-level async cancellation uses `stop` / `/subagents-stop`.
187
190
 
188
191
  Default behavior is intentionally conservative. When no activity has been observed past the configured threshold, the run emits a `needs_attention` control event. Foreground runs can push this as a `subagent:control-event` event, and async runs persist it to `events.jsonl` so the parent tracker can surface it without constant manual polling. Notification-worthy control events are also inserted into the visible transcript so both the user and the parent agent can see them, with a proactive hint plus concrete `nudge`, `status`, and `interrupt` options. Visible notifications fire once per child run and attention state.
189
192
 
@@ -6,7 +6,7 @@ This file is a detailed reference loaded from `skills/pi-subagents/SKILL.md`.
6
6
 
7
7
  The `subagent(...)` tool also supports management actions.
8
8
 
9
- ### List available agents and chains
9
+ ### List available agents and legacy chain records
10
10
 
11
11
  ```typescript
12
12
  subagent({ action: "list" })
@@ -85,7 +85,7 @@ subagent({ action: "reset", agent: "reviewer" })
85
85
  Use management actions when the system needs to create or edit subagents on
86
86
  demand without dropping into raw file editing.
87
87
 
88
- Management actions create or update user/project agent files. `config.name` is the local frontmatter name; optional `config.package` registers and looks up the runtime name as `{package}.{name}`. Use the dotted runtime name for `get`, `update`, `delete`, slash commands, and chain steps. For small builtin changes such as a model swap, prefer `subagents.agentOverrides` in settings.
88
+ Management actions create or update user/project agent files. `config.name` is the local frontmatter name; optional `config.package` registers and looks up the runtime name as `{package}.{name}`. Use the dotted runtime name for `get`, `update`, `delete`, slash commands, and scripted workflow steps. For small builtin changes such as a model swap, prefer `subagents.agentOverrides` in settings. Durable `.chain.md` definitions are legacy records, not a current authoring target; use `workflowScript` or `/prompt-workflow` for repeatable orchestration.
89
89
 
90
90
  ## Creating and Editing Agents by File
91
91
 
@@ -129,7 +129,7 @@ That is only a starting point. Omit `package` for the traditional unqualified ru
129
129
 
130
130
  `aliases` is an optional comma-separated or block-list set of alternate names for selecting an agent. Aliases resolve to the canonical `name` for execution, status, persistence, and config. Exact canonical names take precedence over aliases, and alias collisions between distinct canonical agents fail as ambiguous. Management create/update accepts a comma-separated string, string array, or `false`/empty string to clear aliases.
131
131
 
132
- `acceptance` is a single-agent launch default. Use a scalar level such as `checked` or an inline/block YAML map such as `{ level: "none", reason: "lightweight lookup" }`. An explicit tool-call value wins; chain and parallel acceptance remains configured on the task or step. Management create/update accepts the same policy object, and `acceptance: ""` clears the frontmatter default (`false` remains the deprecated disabled-policy shorthand).
132
+ `acceptance` is a single-agent launch default. Use a scalar level such as `checked` or an inline/block YAML map such as `{ level: "none", reason: "lightweight lookup" }`. An explicit tool-call value wins; scripted workflow child acceptance remains configured on the `runs.run` or `runs.all` item. Management create/update accepts the same policy object, and `acceptance: ""` clears the frontmatter default (`false` remains the deprecated disabled-policy shorthand).
133
133
 
134
134
  `acceptanceRole` is `read-only` or `writer` and controls automatic acceptance inference only. Explicit task mutation or no-edit intent wins; otherwise the role replaces agent-name guessing. Omission preserves the current name heuristics. The field does not grant or revoke tools. Management accepts `false` or an empty string to clear it.
135
135