pi-subagents 0.59.0 → 0.60.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 (43) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/docs/tool-reference.md +4 -1
  3. package/docs/workflows.md +2 -2
  4. package/package.json +1 -1
  5. package/skills/council-mode/SKILL.md +48 -243
  6. package/skills/council-mode/references/pass-contracts.md +150 -0
  7. package/skills/pi-subagents/SKILL.md +87 -37
  8. package/skills/pi-subagents/references/constraints-and-recipes.md +29 -233
  9. package/skills/pi-subagents/references/execution-controls.md +47 -6
  10. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  11. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  12. package/skills/pi-subagents/references/prompting-and-roles.md +34 -27
  13. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  14. package/src/agents/agent-management.ts +154 -25
  15. package/src/api/shared-types.ts +2 -0
  16. package/src/extension/public-execution.ts +1 -0
  17. package/src/extension/schemas.ts +1 -0
  18. package/src/extension/tool-description.ts +8 -4
  19. package/src/runs/background/async-execution.ts +2 -2
  20. package/src/runs/background/async-job-tracker.ts +3 -0
  21. package/src/runs/background/async-status.ts +45 -2
  22. package/src/runs/background/control-channel.ts +3 -2
  23. package/src/runs/background/run-status.ts +13 -2
  24. package/src/runs/background/subagent-runner.ts +5 -1
  25. package/src/runs/background/subagent-wait.ts +10 -2
  26. package/src/runs/background/wait-completions.ts +3 -0
  27. package/src/runs/foreground/execution.ts +11 -2
  28. package/src/runs/foreground/subagent-executor.ts +98 -1
  29. package/src/runs/shared/async-status-projection.ts +138 -4
  30. package/src/runs/shared/background-process-options.ts +9 -0
  31. package/src/runs/shared/mcp-direct-tool-grant.ts +2 -5
  32. package/src/runs/shared/mutation-evidence.ts +52 -3
  33. package/src/runs/shared/pi-args.ts +47 -1
  34. package/src/runs/shared/single-output.ts +45 -18
  35. package/src/runs/shared/subagent-prompt-runtime.ts +20 -2
  36. package/src/runs/shared/workflow-graph.ts +15 -0
  37. package/src/shared/types.ts +34 -1
  38. package/src/tui/fleet-status.ts +11 -3
  39. package/src/tui/render-helpers.ts +31 -0
  40. package/src/tui/render.ts +597 -112
  41. package/src/watchdog/change-signature.ts +40 -1
  42. package/src/workflows/host-command.ts +6 -1
  43. package/src/workflows/scripted-workflow.ts +53 -2
@@ -1,51 +1,101 @@
1
1
  ---
2
2
  name: pi-subagents
3
3
  description: |
4
- Delegate work to builtin or custom subagents with single-agent, parallel,
5
- scripted-chaining, async, forked-context, and coordinated workflows. Use
6
- for advisory review, implementation handoffs, and multi-step tasks where a
7
- single agent should stay in control while other agents contribute context,
8
- planning, or execution.
4
+ Delegate to builtin or custom subagents for single-agent handoffs, parallel
5
+ review, scripted chaining, async work, forked context, and coordinated
6
+ workflows. Use when one parent agent should stay in control while children
7
+ supply focused context, planning, review, or execution.
9
8
  ---
10
9
 
11
10
  # Pi Subagents
12
11
 
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.
12
+ Choose a mode:
14
13
 
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.
14
+ - **Direct mode:** For tiny or focused work, the parent handles the task
15
+ directly; a single bounded child handoff is fine. Skip workflow ceremony.
16
+ - **Orchestrator mode:** For substantial or delegated work, the parent is the
17
+ supervisor, arbiter, and authority holder—not the routine primary doer.
18
+ Subagents may own planning/design, scouting, implementation,
19
+ simplification/challenge, validation, and review as useful. The parent keeps
20
+ user intent, constraints, authority, routing, arbitration, final acceptance,
21
+ and publication.
22
+ - A useful loop for substantial work is **writer → challenge/simplify → review**;
23
+ the parent arbitrates between steps, and tiny tasks can skip it.
24
+ - Direct parent edits during orchestrator mode should be intentional, small
25
+ interventions with a brief reason.
16
26
 
17
- Package-installed agents appear in `subagent({ action: "list" })` with builtin, user, and project agents. If `surf-cli` is installed as a Pi package, the Surf browser extension is loaded, and Chrome is logged into a ChatGPT Pro account, Surf can expose `gpt-pro`: a read-only async advisor that reaches ChatGPT web through Surf Oracle. Check it with `subagent({ action: "get", agent: "gpt-pro" })` and run it with `subagent({ agent: "gpt-pro", task: "Review this plan and identify release risks." })`.
27
+ Children do not spawn subagents unless the parent explicitly delegated fanout
28
+ and their resolved `tools` allow `subagent`.
18
29
 
19
- ## How to use this router
30
+ ## Launch shape
20
31
 
21
- Read the matching reference file before acting. Paths are relative to this `SKILL.md`; resolve them against `skills/pi-subagents/` and load them with the read tool.
32
+ | Need | Use |
33
+ | --- | --- |
34
+ | One bounded task for one child | direct `{ agent, task }` |
35
+ | JavaScript control flow or data-dependent branching; sequence, fanout, retry, rolling fanout, or aggregation | `workflowScript` with `runs.run(...)` / `runs.all(...)` |
36
+ | A broad plan split into visible narrow stages per lane | `workflowScript` with `runs.lanes([{ key, stages: [...] }])` |
37
+ | Independent worktree or repository lanes | `references/multi-lane-orchestration.md` |
38
+ | Council of advisors | `../council-mode/SKILL.md` |
39
+ | Management, status, steering, authoring, or inspection | `action` |
40
+
41
+ `workflowScript` is code-driven: `runs.run(...)` for keyed steps,
42
+ `runs.all([...])` for fanout, plain JavaScript for branching and aggregation.
43
+ Keep scripts portable: use top-level `await`, plain helpers, or explicit Promise
44
+ chains, not nested async helpers. Legacy top-level `chain` / `tasks` inputs and
45
+ durable `.chain.md` execution are inspection or migration material only.
46
+
47
+ Use `runs.lanes(...)` only inside a `workflowScript`, not as a top-level mode,
48
+ when a broad, predeclared plan benefits from visible per-lane stages; otherwise
49
+ use ordinary `runs.run(...)` / `runs.all(...)`. See the [canonical staged-lane
50
+ example](../../docs/workflows.md#parallel-sequential-lanes). Keep assignments
51
+ bounded, but do not add stages or ceremony just to satisfy this skill.
52
+
53
+ Use async/background by default. Set `async:false` only when the parent must
54
+ block. Final reviews, validation gates, oracle checks, and publication checks
55
+ stay async.
56
+
57
+ In an ordinary interactive session, yield after launching or triaging useful
58
+ async lanes and let Pi wake the parent on completion; do not call blocking
59
+ `subagent_wait()` merely because a child is active. Use blocking
60
+ `subagent_wait()` only when a headless/run-to-completion contract or a required
61
+ same-turn artifact makes the result necessary before this turn ends. For
62
+ “continue/orchestrate/work until done,” keep the lane board moving while a safe
63
+ immediate action remains; if only async lanes are running, record the revisit
64
+ trigger and yield.
22
65
 
23
- | Task | Read |
66
+ Package agents appear in `subagent({ action: "list" })`. External CLI/job agents
67
+ use their own runner contract. Do not pass native Pi child options to them unless
68
+ that runner explicitly supports the option.
69
+
70
+ ## Read the reference for the branch
71
+
72
+ | Branch | Read |
24
73
  | --- | --- |
25
- | Decide whether to delegate, choose agents, compare tool versus slash commands, apply prompt techniques, or understand builtin roles | `references/prompting-and-roles.md` |
26
- | Use council mode, convene several advisors, debate a decision, cross-examine recommendations, critique or improve a plan with multiple model perspectives, or run `/council` | `../council-mode/SKILL.md` |
27
- | Run one-child, scripted, async, scheduled, mission-backed, forked, watchdog, oracle, or intercom-coordinated workflows | `references/execution-controls.md` |
28
- | Coordinate several independent tasks, worktrees, repositories, or writer lanes | `references/multi-lane-orchestration.md` |
29
- | 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` |
30
- | Check safety constraints, best practices, standard workflows, or error handling | `references/constraints-and-recipes.md` |
31
-
32
- 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.
33
-
34
- External CLI agents such as `codex-exec`, `codex-exec-writer`, `claude-code`, and `cursor-agent` use their own runner contract. Do not pass native Pi child options such as model override, structured output, acceptance/agent contract, tool budgets, fast mode, fork context, skills, or native Pi tools unless that runner explicitly implements them.
35
-
36
- ## Always-on constraints
37
-
38
- - Keep the parent as orchestrator and final decision-maker.
39
- - Before multiple mutation-capable lanes, record a lane board and each lane's isolation path.
40
- - For plan, design, or architecture advice that asks for council mode, asks to convene several advisors, compare model perspectives, debate a decision, cross-examine recommendations, or critique and improve a plan, read `../council-mode/SKILL.md` and use Council Mode instead of ad hoc parallel oracle calls.
41
- - For plan, design, or architecture advice that asks to consult, discuss with, or come to agreement with one `oracle`, use a short same-session consultation loop: read the first result, resume once with a targeted challenge when material tradeoffs remain, then synthesize the parent decision. Keep explicit one-shot, trivial, and fully settled consultations one-shot.
42
- - Use one writer per cwd/worktree unless isolated worktrees are intentional.
43
- - 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.
44
- - 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.
74
+ | Delegate or choose roles, prompts, models, or slash commands | `references/prompting-and-roles.md` |
75
+ | Execute single, scripted, async, scheduled, mission, forked, watchdog, oracle, or intercom workflows | `references/execution-controls.md` |
76
+ | Review, validate, triage gate failures, or prepare delivery | `references/review-and-validation.md` |
77
+ | Coordinate lanes, worktrees, repositories, or writer waves | `references/multi-lane-orchestration.md` |
78
+ | List, create, edit, disable, eject, or expose agents/RPC | `references/management-authoring-rpc.md` |
79
+ | Check safety constraints, recipes, or error handling | `references/constraints-and-recipes.md` |
80
+
81
+ For complex work, read `prompting-and-roles.md` and `execution-controls.md`, then
82
+ load `review-and-validation.md` and `constraints-and-recipes.md` before launch or
83
+ review.
84
+
85
+ ## Operating rules
86
+
87
+ - Avoid duplicate scouts, overlapping writers, and vague prompts without a concrete deliverable.
88
+ - Keep the parent on the ordinary strong default model. Route workers/scouts to a fast capable tier, serious reviews to a strong tier, and top reasoning to bounded read-only critique.
89
+ - Exact model names are deployment policy. Put them in user/project settings or profiles, not package guidance.
90
+ - Give every child a compact meta-prompt checklist: objective; repo/cwd/ref; authority/edit boundary; relevant files/contracts and constraints; success/acceptance criteria; validation; expected output/report; and stop/ask conditions. See `references/prompting-and-roles.md`.
91
+ - For mutation work, use an isolated lane/worktree when isolation, overlap, or concurrent juggling matters; keep one writer per cwd/worktree. See `references/multi-lane-orchestration.md` for lane mechanics.
92
+ - Keep long/high-output validation out of chat: prefer `interactive_shell` dispatch/background monitors, bounded logs, or subagent-owned reports; return a concise summary plus report path unless same-turn output is required. See `references/execution-controls.md`.
93
+ - For cross-codebase work, record the repo, explicit `cwd`, authority boundary, and expected output before launch.
94
+ - Make parallel prompts distinct by source seam, evidence, and decision. Do not clone prompts with only item numbers swapped.
45
95
  - Prefer fresh-context review/validation fanout, then synthesize and apply fixes in the parent.
46
- - 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`.
47
- - 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.
48
- - Preserve capability ceilings, including child tool restrictions and session-scoped allowed-agent restrictions.
49
- - Escalate unresolved product, architecture, authority, release, merge, or safety decisions upward instead of letting a child decide silently.
50
- - Treat receipts, CI, review bots, and external-run records as evidence, not authority to merge, close, comment, publish, or release.
51
- - As a conservative orchestration policy, do not pass a hard `toolBudget` or tight `usageBudget` to mutation-capable workers. The default tool budget blocks read/search tools rather than mutation tools, and reported usage has no reservation model. If a worker is interrupted after a tool call starts, checkpoint after the current tool returns with changed files, build/test state, and commit or PR state.
96
+ - For Pi extension repos under `~/.pi/agent/extensions`, put lane worktrees outside extension auto-discovery, such as `~/.pi/agent/worktrees`.
97
+ - Preserve capability ceilings, including child tool limits and allowed-agent restrictions.
98
+ - Preserve parent authority and escalate unresolved choices.
99
+ - Treat receipts, CI, review bots, and external-run records as evidence, not authority.
100
+ - For backlog maintenance, releases, merge queues, or other public-repo mutation policy, load the matching user/project skill. This package defines delegation primitives, not private policy.
101
+ - As a conservative orchestration policy, do not pass a hard `toolBudget` or tight `usageBudget` to mutation-capable workers. The default tool budget blocks read/search tools rather than mutation tools. If interrupted after a tool call starts, checkpoint after the current tool returns with changed files, build/test state, and commit or PR state.
@@ -31,244 +31,40 @@ For durable evidence, copy only the final summary to session memory, a PR body/c
31
31
 
32
32
  ## Best Practices
33
33
 
34
- ### Prefer async orchestration
34
+ - Run subagents asynchronously by default; direct one-child execution is enough for one bounded task, while `workflowScript` is the composition surface for JavaScript control flow and data-dependent branching. Use `async: false` only when the parent must block. See `references/execution-controls.md` → Async/background for wait semantics.
35
+ - For a predeclared broad plan split into visible narrow stages, use `runs.lanes([...])` inside `workflowScript`; use raw `runs.run(...)`/`runs.all(...)` for conditional or rolling flows. See [`execution-controls.md`](execution-controls.md#parallel-sequential-lanes).
36
+ - Keep one writer per cwd/worktree. Parallelize reading, review, and validation; concurrent writers need isolated worktrees. Give every child a cold-start packet with its goal, target/ref, authority, context, success criteria, validation, output, and stop rules.
37
+ - Keep tasks narrow and standalone; do not rely on issue numbers, broad globs, or supervisor round-trips to supply missing context.
38
+ - Keep authority with the parent. Escalate unapproved product, scope, architecture, merge, credential, or release decisions; checks, receipts, and review bots are evidence, not authority.
39
+ - Use `fresh` context for adversarial review. `fork` is a persisted, history-inheriting branch; see `references/execution-controls.md` for its preconditions.
40
+ - Use a same-session oracle follow-up only when its first answer leaves a material tradeoff. Treat `needs_attention` as a control signal, not failure, and do not interrupt a child merely because it is quiet during tools, tests, or reasoning.
41
+ - Use `/name` when intercom targeting needs a stable session name.
35
42
 
36
- Launch every subagent asynchronously by default. Use `async: true` for scouts, researchers, workers, reviewers, validators, oracle checks, one-off delegates, and scripted workflows unless you intentionally need a foreground/blocking run. Launch all execution through `workflowScript`; use `return runs.run("main", { agent, task })` for one isolated child and `runs.all([...])` when two or more child lanes, monitors, or dependent steps should move together. The parent should keep moving: inspect code while scouts run, prepare validation while a worker implements, do a local diff pass while reviewers review, and synthesize or verify while a fix worker applies accepted feedback. Async is the default orchestration posture; foreground runs are the explicit opt-out.
43
+ ## Workflow selection
37
44
 
38
- ### Use subagent_wait() to block until async runs finish
45
+ This reference keeps cross-cutting policy and failure handling. Load the matching domain reference for detail:
39
46
 
40
- In an interactive chat, do not call `subagent_wait()` merely to wait after launching background work; return control to the user and Pi will wake the session on completion. Override that default when the current request is run-to-completion — for example, the user asked you to stay with the task and report results back this turn or a skill must finish in one turn. In a headless run, Pi auto-drains exact current-session work at `agent_end`; call `subagent_wait()` when this turn must receive results before it ends. In either case, `subagent_wait()` blocks the current turn until the next run completes or needs attention, keeps the turn alive for normal notification delivery, then returns.
47
+ | Need | Read |
48
+ | --- | --- |
49
+ | Execution syntax, lifecycle, async/wait, missions, controls, watchdog, or worktrees | [`references/execution-controls.md`](execution-controls.md) |
50
+ | Role choice, prompt contracts, review/research/cleanup techniques, or model tiering | [`references/prompting-and-roles.md`](prompting-and-roles.md) |
51
+ | Fresh review, validation, gate failures, finding disposition, and final delivery checks | [`references/review-and-validation.md`](review-and-validation.md) |
52
+ | Independent lanes, repositories, worktrees, and handoffs | [`references/multi-lane-orchestration.md`](multi-lane-orchestration.md) |
53
+ | Agent management, file authoring, prompt integration, or RPC | [`references/management-authoring-rpc.md`](management-authoring-rpc.md) |
41
54
 
42
- - `subagent_wait()` — return when the next initially active async run or registered provider item finishes, or a subagent needs attention.
43
- - `subagent_wait({ all: true })` — block until every async run and provider item active at call time finishes, or a subagent needs attention.
44
- - `subagent_wait({ id: "..." })` — block on one async or remembered detached foreground run (id or prefix). Provider items are not selected through this parameter.
45
- - `subagent_wait({ stopOnAttention: false })` — for blocking waits only, keep waiting through idle or long-thinking attention; supervisor/contact requests still stop the wait.
46
- - `subagent_wait({ timeoutMs })` — cap the block; active work keeps running if it elapses.
55
+ Choose the smallest recipe that fits:
47
56
 
48
- Providers are discovered through the `pi-subagents/background-work` registry and must return stable item IDs with exact owning session IDs. Child agents receive no provider automatically: keep `subagent_wait` in the child `tools` allowlist and load provider extensions through `extensions` or `subagentOnlyExtensions`.
49
-
50
- For non-interactive fleet orchestration, `subagent_wait()` can keep N workers in flight: launch N, wait for the next completion, react to the result, launch a replacement if needed, then wait again. Use `subagent_wait({ all: true })` only when you intentionally want to drain the fleet to zero. If the turn ends first, headless `agent_end` auto-drain still waits for exact current-session work. In an interactive session, return to the user instead of holding the turn open just to await completion.
51
-
52
- If config or `PI_SUBAGENT_WAIT_TOOL_ENABLED` disables blocking behavior, direct `subagent_wait` calls return immediately. Headless `agent_end` auto-drain remains active as a lifecycle safeguard and surfaces provider, reconciliation, or timeout failures.
53
-
54
- ### Keep writes single-threaded by default
55
-
56
- A strong pattern is one main decision-maker plus advisory/research/review/validation subagents around it. Use `oracle` for advice and `worker` for the actual write path. Parallelize reading, review, validation, and synthesis support, not normal writes, unless you deliberately isolate writers with worktrees. Across repositories, each repo/worktree still gets at most one writer, with explicit `cwd` and authority in the child prompt. A child that writes should report what changed, what was left undone, commands run with exit codes, validation evidence, surprises, and any decisions that need parent approval.
57
-
58
- ### Use fork for branched advisory or execution threads
59
-
60
- Forked runs are useful when the child should reason in a separate thread while
61
- still inheriting the parent’s accumulated context. They are especially useful for
62
- `oracle`, which audits inherited decisions and drift. For adversarial code review,
63
- prefer fresh-context reviewers that inspect the repo and diff directly unless the
64
- user explicitly requests forked context.
65
-
66
- ### Prefer narrow tasks
67
-
68
- Give subagents specific tasks rather than vague mandates.
69
- `Review auth.ts for null-check gaps` works better than `Review everything`.
70
-
71
- Before fanout, assign each child a lightweight task profile in the parent prompt:
72
- work kind, required input, expected output, acceptance check, and context mode.
73
- Keep the profile prose-only; do not invent runtime fields. Use coarse kinds such
74
- as `code-write`, `code-read`, `transform`, `summarize`, and `search` only to
75
- shape the task and choose an existing agent/model setting. If a child task is not
76
- standalone enough for fresh context, add the missing facts to the prompt, switch
77
- to forked context, or ask the user. Do not launch vague tasks and rely on
78
- supervisor round-trips to recover missing context.
79
-
80
- ### Escalate decisions upward
81
-
82
- If a subagent encounters an unapproved product, architecture, scope, merge, release, credential, or authority choice, it should use `contact_supervisor` and wait for the reply instead of deciding alone. Generic `intercom` is external or provider-supplied only. Use it only when external bridge instructions provide an explicit safe target. External checks, receipts, and review bots provide evidence only; they do not grant authority.
83
-
84
- ### Use a short oracle consultation for material advice
85
-
86
- When a user asks to ask, consult, discuss with, or come to agreement with `oracle` about a plan, design, or architecture decision, do not treat the first advisory report as final when it raises a material challenge or tradeoff. Read it, resume the same oracle session once with a targeted question, then make the parent decision. An explicit one-shot request, a trivial question, or a fully settled first answer does not need a follow-up.
87
-
88
- ### Intervene only on clear control signals
89
-
90
- Use subagent control proactively when a delegated run emits `needs_attention`, or when a human asks you to regain control. Do not interrupt just because a child has briefly produced no output. Silence can be normal during long tool calls, test runs, or model reasoning.
91
-
92
- ### Name sessions meaningfully
93
-
94
- Use `/name` so intercom targeting stays stable.
95
-
96
- ## Common Workflows
97
-
98
- ### Recon → Plan → Implement
99
-
100
- ```js
101
- subagent({ workflowScript: `
102
- const context = await runs.run("recon", { agent: "scout", task: "Start from the named source roots, paths, and symbols. Identify the implementation seam before broad search." });
103
- return (await runs.run("implement", { agent: "worker", task: "Read the scout output, plan paths, and named files/seams first. Implement from: " + context.output })).output;
104
- ` })
105
- ```
106
-
107
- ### Fable mode for complex work
108
-
109
- Fable mode is the default orchestration posture for complex work. It is not a separate runtime mode; it is how the parent session uses `subagent`, `interview`, `subagent_wait`, acceptance contracts, artifacts, and fresh-context review when the work has real complexity. Use it for complex features, broad refactors, migrations, ambiguous goals, multi-system changes, expensive validation, user-visible behavior changes, or any request to plan/orchestrate end to end. Do not force it onto tiny one-shot delegation.
110
-
111
- Run the work through seven gated phases:
112
-
113
- 1. **Understand** — use `scout` fanout for breadth, but the parent personally reads the load-bearing files and lets direct source reading decide disagreements. Gate: the parent can quote the exact code or behavior being changed and knows the repo's verification harness.
114
- 2. **Decide** — separate user-owned decisions from implementation judgments. Use `interview` for product, naming, cost, taste, risk, release, merge, or authority decisions; decide routine engineering details in the parent and state them. Gate: every user-owned decision needed for design is answered or recorded as a blocked follow-up.
115
- 3. **Design** — use read-only design/review children for parallel perspectives. Before parallel workstreams, write seam contracts: ownership boundaries, composition points, assumptions, and validation handoffs. Gate: one parent-synthesized plan and written seams for parallel work.
116
- 4. **Implement** — capture a baseline first, then launch one async `worker` as the sole writer for the active worktree unless isolated worktrees were intentionally requested. For cross-codebase work, launch separate async workers only when each has its own repo/worktree, explicit `cwd`, and non-overlapping authority. Break large work into serial milestones instead of concurrent writes. Gate: build/typecheck is green and every output or diff delta is characterized as intended or fixed.
117
- 5. **Verify** — climb the spend ladder: static checks, free end-to-end/dry-run, cheapest live probe, targeted changed-path live test, then full realistic run when warranted. Observe the artifact itself, not only exit codes or scores, and confirm the changed code actually executed. Gate: the highest necessary rung has directly observed evidence matching intent.
118
- 6. **Iterate** — when a gate or reviewer finds a defect, the parent names the failure class, searches for siblings, synthesizes fixes, and sends exactly one fix worker for accepted changes. For LLM judges, gates, or detectors, trigger on concrete findings rather than scores, record pass/violations/error verdicts, cache nondeterministic verdicts by input hash, budget enough output tokens, and sanitize judge text before reusing it downstream. Gate: the class is fixed or explicitly bounded, and recurrence detection exists when feasible.
119
- 7. **Ship** — run adversarial fresh-context review/validation outside the implementation path, disposition every finding, rerun affected gates, then have the parent inspect the final diff. Commit, push, comment, close, merge, release, or open PRs only inside user-approved boundaries for that repo. Gate: findings are dispositioned, gates re-pass, and the final summary names evidence, artifacts, residual risks, and output paths.
120
-
121
- ### Clarify → Plan → Implement → Review (self-orchestrated workflow)
122
-
123
- For straightforward non-trivial work, this sequence is the lightweight version of the parent-owned loop. When the task is complex, use Fable mode above. In either case, factor in the packaged prompt workflows without literally invoking slash commands. Use the same patterns through tools and subagents.
124
-
125
- Keep builtin agent defaults unless the user explicitly asks for a different model, thinking level, skills, output behavior, context mode, or other override. Do not add overrides just because you are orchestrating; the defaults encode the intended role behavior. In particular, packaged `worker`, `oracle`, and `advisor` default to forked context.
126
-
127
- When the user approves launching a subagent to carry out a plan or workflow, treat that as approval to generate a proper role-specific meta prompt for that subagent. Include the approved plan path or summary, clarified requirements, non-goals, relevant context, role boundaries, files or areas to inspect, acceptance criteria, expected output, and validation expectations. Do not pass vague instructions like “implement the plan fully” or “review this” by themselves.
128
-
129
- - `/gather-context-and-clarify` maps to: launch `scout` and, when needed, `researcher`; synthesize findings; then use `interview` to ask every clarification question needed for shared understanding.
130
- - `/parallel-review` maps to: launch fresh-context `reviewer` agents with distinct review angles; synthesize the feedback before applying anything.
131
- - `/review-loop` maps to: keep the parent in charge of worker → fresh reviewers → synthesized fix worker cycles until no fixes worth doing now remain, an unapproved decision appears, or the review-round cap is reached.
132
- - `/parallel-research` maps to: combine local `scout` context with external `researcher` evidence when current docs, ecosystem behavior, or API details matter.
133
- - `/parallel-cleanup` maps to: use review-only cleanup passes after implementation, especially for simplicity, verbosity, and redundant tests.
134
-
135
- For feature work, use this sequence as scaffolding for parent-agent behavior:
136
-
137
- ```text
138
- clarify → validation contract → scout → async worker → parallel async fresh-context reviewers/validators → async fix worker → follow-up review when warranted → parent review
139
- ```
140
-
141
- The validation contract defines acceptance before code is written: expected behavior, acceptance checks, commands or user flows to exercise, and evidence the worker should return. Keep it lightweight for small tasks, but make it explicit enough that reviewers and validators are checking the intended outcome rather than the worker’s own assumptions.
142
-
143
- For one host-run verification command, `gate: "npm test"` on the child is shorthand for verified acceptance with that command; it cannot be combined with `acceptance` and is rejected on retained resume items. Use the structured `acceptance` field when the run should carry an explicit acceptance contract. If omitted, subagents infer an effective policy from role, mode, and risk. Evidence levels end at `verified`: use `level: "checked"` for ordinary writer evidence and `level: "verified"` when the runtime should run explicit validation commands. Independent review is orthogonal; use `review: { required: true, agent: "reviewer" }` and orchestrate the reviewer separately. `review-required` means evidence passed but review is pending, while `reviewed` means a real independent result found no blockers. For reviewer/read-only calls, omit `acceptance`. Never explicitly request `level: "reviewed"`; that value remains recognized only so preflight can return an actionable correction. To disable gates, use `{ level: "none", reason: "..." }`; the bare string `"none"` is rejected, and `false` is accepted only as a deprecated shorthand. Child-reported command success is evidence, not runtime verification.
144
-
145
- The first `worker` implements the approved plan. The parent continues with independent inspection or validation prep while it runs, not parallel edits to the same worktree. When the async worker completes, treat its handoff as the transition into review, not as final completion, unless the user explicitly asked for worker-only work, review-only output, or to stop after implementation. Parallel reviewers inspect the resulting diff from fresh context. Validators check behavior with the best available evidence: commands, tests, browser/CLI interaction, screenshots, logs, or manual reproduction notes. The final `worker` applies synthesized review fixes in forked context, then the parent looks over the final diff before completing. The parent may launch these steps as an initial async `workflowScript` when the workflow is already clear, or as follow-up workflowScript runs after each async completion. Initial workflows should pass `async: true` so the main chat is unblocked. Do not stop after parallel review unless the user explicitly asked for review-only output or the review surfaced a decision that needs approval first.
146
-
147
- For complex work, risky changes, broad refactors, or many changed lines, increase review and validation fanout rather than trusting one reviewer. Use distinct angles such as correctness/regressions, tests/validation, simplicity/maintainability, security/privacy, performance, docs/API contracts, and user-flow behavior. When reviewers find non-trivial issues or the fix worker touches many lines, run another focused review round before final validation.
148
-
149
- When review has already produced concrete findings across several independent areas, use staged fix orchestration: parallel read-only reviewers for each issue cluster, one sole writer worker for the active worktree, then parallel fresh-context validators. This is the safest way to handle a dirty worktree with many prior changes because it parallelizes judgment without parallelizing writes. Non-blocking suggestions may go into the writer prompt only if they are small, safe, and inside the approved scope; otherwise defer them explicitly.
150
-
151
- For very large work, split into serial milestones instead of launching a swarm of writers. Each milestone gets one writer, a validation contract, fresh-context review/validation, a fix pass, and parent acceptance before the next milestone starts. Use parallel subagents inside a milestone for read-only context, research, review, and validation only.
152
-
153
- Keep orchestration authority in the parent session. Child subagents should not launch more subagents, read this skill, or run their own orchestration loops unless the parent intentionally selected a fanout agent whose builtin `tools` includes `subagent`. Spawned subagents do not receive the `pi-subagents` skill, parent-only status/control/slash messages, or prior parent `subagent` tool-call/tool-result artifacts. Ordinary children also do not receive the `subagent` extension tool. Child context filtering strips old hidden orchestration-instruction messages when they appear in inherited history. Every child receives a boundary instruction: ordinary children are told the parent owns orchestration and they must not propose or run subagents; explicit fanout children are told to use `subagent` only for the assigned fanout work, with `maxSubagentDepth` still enforced. Implementation children must call real edit/write tools instead of printing pseudo tool calls. Pass children concrete role-specific work instead.
154
-
155
- 1. Clarify first. This is mandatory. Gather code context with `scout`, add `researcher` only when external evidence matters, then ask the user clarifying questions with `interview` until scope, acceptance criteria, constraints, and non-goals are clear.
156
- 2. Define the validation contract. State acceptance before implementation: expected behavior, checks to run, user flows to exercise, and evidence required in the worker handoff. For UI, CLI, integration, or workflow changes, include at least one validator angle that uses the product the way a user would rather than only reading code.
157
- 3. Plan when useful. For complex work, write a plan doc yourself and get approval before implementation. For simple work, confirm shared understanding and explicitly note why planning is skipped.
158
- 4. Implement with one writer. After approval, launch `worker` asynchronously with a proper meta prompt that includes clarified requirements, relevant context, plan path or summary, the validation contract, and output expectations. Packaged `worker` defaults to forked context; pass `context: "fresh"` only when you intentionally want a fresh child. While it runs, prepare validation or inspect adjacent code instead of editing the same worktree.
159
- 5. Require a useful worker handoff. Ask the worker to report changed files, what was implemented, what was left undone, commands run with exit codes, validation evidence, surprises or new risks, decisions made inside approved scope, and decisions needing parent approval.
160
- 6. Review after implementation. After the worker completes, launch parallel async fresh-context `reviewer` agents for correctness/regressions, tests/validation, and simplicity/maintainability. Add security, performance, docs/API, domain-specific, or user-flow validators for complex work, risky changes, broad refactors, or many changed lines. Use `output: false` unless review artifacts are explicitly needed.
161
- 7. Synthesize, then run the fix worker. Separate blockers, fixes worth doing now, optional improvements, and feedback to ignore/defer, then launch an async forked `worker` to apply fixes worth doing now when the workflow is implementation-authorized. If reviewers found scope/product/architecture choices that were not approved, ask the user first instead of applying them.
162
- 8. Review again when warranted. If the fix worker made substantial changes or addressed non-trivial findings, run another focused parallel review round before final validation.
163
- 9. Validate and complete. After the fix worker and any follow-up review return, inspect the final diff yourself, run or confirm focused validation, update docs/changelog when relevant, and summarize what changed and why.
164
-
165
- Example implementation handoff after clarification and optional planning:
166
-
167
- ```typescript
168
- subagent({
169
- workflowScript: `return runs.run("implementation", {
170
- agent: "worker",
171
- task: "Implement the approved feature.\n\nClarified requirements:\n- ...\n\nPlan: see ~/Documents/docs/...-plan.md\n\nValidation contract:\n- ...\n\nReturn a handoff with changed files, what was implemented, what was left undone, commands run with exit codes, validation evidence, surprises/new risks, and decisions needing parent approval.",
172
- acceptance: {
173
- level: "checked",
174
- evidence: ["changed-files", "tests-added", "commands-run", "residual-risks", "no-staged-files"]
175
- }
176
- })`,
177
- async: true
178
- })
179
- ```
180
-
181
- Example review pass after implementation:
182
-
183
- ```typescript
184
- subagent({
185
- workflowScript: `
186
- const results = await runs.all([
187
- { key: "correctness", agent: "reviewer", task: "Review the current diff for correctness and regressions. Inspect changed files directly; do not rely on the worker's reasoning.", output: false },
188
- { key: "tests", agent: "reviewer", task: "Review the current diff for tests and validation quality against the validation contract. Inspect changed files directly.", output: false },
189
- { key: "simplicity", agent: "reviewer", task: "Review the current diff for simplicity and maintainability. Inspect changed files directly.", output: false }
190
- ]);
191
- return results.map(result => result.output);
192
- `,
193
- context: "fresh",
194
- async: true
195
- })
196
- ```
197
-
198
- Example fix worker after parallel reviews:
199
-
200
- ```typescript
201
- subagent({
202
- workflowScript: `return runs.run("fix", {
203
- agent: "worker",
204
- task: "Apply the synthesized reviewer feedback below. Only apply fixes worth doing now; preserve user-approved scope; ask before unapproved product or architecture changes. Run focused validation and summarize what changed.\n\nReviewer synthesis:\n..."
205
- })`,
206
- async: true
207
- })
208
- ```
209
-
210
- ### Review loop
211
-
212
- Do not treat review as the final step for implementation work. Run reviewers and validators, synthesize their findings against user scope and the validation contract, then launch one `worker` for accepted fixes when implementation is authorized.
213
-
214
- When an async implementation worker completes, treat the worker handoff as an intermediate state. The next parent action is review fanout, then synthesis, then a fix worker if reviewers found fixes worth doing now. This can be planned as an initial async `workflowScript` when the whole workflow is known, or continued as follow-up workflowScript runs when the parent only launched the first worker initially. Initial workflows should pass `async: true` so the main chat is unblocked.
215
-
216
- For explicit review-loop requests, repeat worker → fresh-reviewer → synthesized-fix-worker cycles until reviewers find no blockers or fixes worth doing now, remaining feedback is optional or intentionally deferred, an unapproved product/scope/architecture decision needs the user, or the max review-round cap is reached. Default to 3 review rounds unless the user sets a different cap. For complex work, many changed lines, or any fix pass that materially changes the diff, run another focused review round before the parent’s final look; otherwise stop instead of chasing optional polish.
217
-
218
- ### Parallel non-conflicting analysis
219
-
220
- ```js
221
- subagent({ workflowScript: `
222
- return await runs.all([
223
- { key: "frontend", agent: "scout", task: "Inspect the frontend" },
224
- { key: "backend", agent: "scout", task: "Inspect the backend" }
225
- ]);
226
- ` })
227
- ```
228
-
229
- Use distinct keys, prompts, and output paths. Do not launch parallel writers into the same checkout.
57
+ - **Recon → plan → implement:** run one focused `scout`, then one `worker` that consumes its findings.
58
+ - **Non-trivial implementation:** clarify scope and acceptance, record user-owned decisions and seam/validation contracts, scout load-bearing code, plan when useful, use one writer, run fresh review/validation, apply only accepted fixes with one writer, then inspect direct evidence and the final diff before parent acceptance. Split large work into serial milestones instead of a writer swarm; do not stop at review without disposition.
59
+ - **Parallel analysis:** fan out only independent read/review/validation work, or isolate each writer in its own worktree. Never run concurrent writers in one checkout.
230
60
 
231
61
  ## Error Handling
232
62
 
233
- **"Unknown agent"**
234
- ```typescript
235
- subagent({ action: "list" })
236
- // Check available agents, then confirm scope/precedence. Saved chains are not a
237
- // public execution surface; author orchestration with workflowScript.
238
- ```
239
-
240
- **Setup, discovery, or intercom confusion**
241
- ```typescript
242
- subagent({ action: "doctor" })
243
- // Check runtime paths, async support, discovery counts, current session, and intercom bridge state.
244
- ```
245
-
246
- **"Max subagent depth exceeded"**
247
- ```typescript
248
- // Flatten the workflow or raise maxSubagentDepth in config.
249
- ```
250
-
251
- **"Session manager did not return a session file"**
252
- ```typescript
253
- // Persist the current session before using context: "fork".
254
- ```
255
-
256
- **Intercom "Already waiting for a reply"**
257
- ```typescript
258
- // Resolve the current outbound ask before starting another one.
259
- ```
260
-
261
- **Parallel output-path conflict**
262
- ```typescript
263
- // Give each parallel task a distinct output path, or disable output for tasks that do not need it.
264
- ```
265
-
266
- **Worktree launch fails**
267
- ```typescript
268
- // Ensure the git working tree is clean and task cwd overrides match the shared cwd.
269
- ```
270
-
271
- **Child fails before starting**
272
- ```typescript
273
- // Inspect `subagent({ action: "status", id: "..." })`, artifact metadata/output logs, and run doctor. Extension loader errors usually appear in child output logs.
274
- ```
63
+ - **Unknown agent:** run `subagent({ action: "list" })`; check scope/precedence and author new orchestration with `workflowScript`, not legacy chains.
64
+ - **Setup, discovery, or intercom confusion:** run `subagent({ action: "doctor" })`.
65
+ - **Max subagent depth exceeded:** flatten the workflow or raise `maxSubagentDepth` in config.
66
+ - **Missing session file for a fork:** persist the parent session before using `context: "fork"`.
67
+ - **Intercom already waiting for a reply:** resolve the pending ask before starting another.
68
+ - **Parallel output-path conflict:** give each task a distinct output path, or disable output where no artifact is needed.
69
+ - **Worktree launch failure:** ensure the git tree is clean and task cwd overrides match the shared cwd.
70
+ - **Child fails before starting:** inspect `subagent({ action: "status", id: "..." })`, artifact metadata, output logs, and `doctor`; loader errors usually appear in child logs.
@@ -28,7 +28,7 @@ External CLI profiles are async-only and one-shot. They support lifecycle artifa
28
28
 
29
29
  ### External job profiles
30
30
 
31
- An agent may set `runner.type: external-job` with a non-empty `provider` and optional JSON `options`. When `surf-cli` is installed and loaded, Surf can optionally expose a `gpt-pro` package agent through provider `surf-oracle`. Surf maps `model: pro` to ChatGPT GPT-5.6 Sol Pro web mode. pi-subagents does not own that package agent or model mapping. Remove any old `agentOverrides.gpt-pro.disabled` workaround before using Surf's package agent. 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.
31
+ An agent may set `runner.type: external-job` with a non-empty `provider` and optional JSON `options`. When `surf-cli` is installed and loaded, Surf can optionally expose a `gpt-pro` package agent through provider `surf-oracle`. Surf maps `model: pro` to its configured pro web mode. pi-subagents does not own that package agent or model mapping. Remove any old `agentOverrides.gpt-pro.disabled` workaround before using Surf's package agent. 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
32
 
33
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
34
 
@@ -38,10 +38,17 @@ External job profiles do not support foreground/clarify, steer/resume, Pi models
38
38
 
39
39
  ```typescript
40
40
  subagent({
41
- workflowScript: `return runs.run("oracle-check", { agent: "oracle", task: "Review my current direction and challenge assumptions." })`
41
+ agent: "oracle",
42
+ task: "Review my current direction and challenge assumptions."
42
43
  })
43
44
  ```
44
45
 
46
+ Use direct single-agent execution for one bounded task when no stable key,
47
+ branching, retained-child lookup, or aggregate workflow result is needed. Use a
48
+ `workflowScript` when the parent needs JavaScript control flow or data-dependent
49
+ branching, or when the run is part of a larger coordinated wave or a later step
50
+ must resume it by key.
51
+
45
52
  ### Forked context
46
53
 
47
54
  ```typescript
@@ -61,7 +68,17 @@ its resolved launch context as `[fresh]` or `[fork]`. Aggregate headers show
61
68
 
62
69
  ### Scripted workflows
63
70
 
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.
71
+ `workflowScript` is the public composition surface when the parent needs
72
+ JavaScript control flow or data-dependent branching. Use
73
+ `runs.run(key, { agent, task, ... })` for keyed children, `runs.all([...])` for
74
+ parallel children, and ordinary JavaScript for sequence, filtering, retries,
75
+ and aggregation. Scripts are ordinary JavaScript statement bodies, so use an
76
+ explicit return such as `return runs.run("main", { agent: "worker", task: "..." })` for a useful one-child result. Use top-level `await`,
77
+ plain helper functions, or explicit Promise chains; nested `async function`
78
+ helpers, async arrows, and async methods are rejected. Prefer a single scripted
79
+ workflow whenever the parent is starting a coordinated wave, such as multiple
80
+ reviews, review plus gate monitor, worker then monitor setup, cross-repo prep
81
+ lanes, or a fanout that the parent will consume together.
65
82
 
66
83
  ```js
67
84
  subagent({
@@ -82,6 +99,8 @@ If `runs.all` is missing in a running session, reload or update `pi-subagents` b
82
99
 
83
100
  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.
84
101
 
102
+ If omitted, acceptance is inferred from role, mode, and risk. Use `level: "checked"` for ordinary writer evidence and `level: "verified"` when the runtime should run explicit validation commands. Independent review is orthogonal: use `review: { required: true, agent: "reviewer" }`; reviewer/read-only calls omit `acceptance`. `review-required` means evidence passed but review is pending; `reviewed` means an independent review found no blockers. Never request `level: "reviewed"`; it is recognized only so preflight can return an actionable correction. Disable gates with `{ level: "none", reason: "..." }`; bare `"none"` is rejected and `false` is only a deprecated shorthand. Child-reported command success is evidence, not runtime verification.
103
+
85
104
  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.
86
105
 
87
106
  Each workflow key identifies one result lane: use a new stable workflow key for every distinct retained resume pass; same-key calls are reused only when launch parameters are identical, and incompatible parameters are rejected.
@@ -97,9 +116,22 @@ return runs.run("cross-oracle", {
97
116
 
98
117
  Keyed resume reads that one exact receipt and revalidates the retained run at launch. It fails when the workflow or key is missing, the receipt is stale, `latest` is not `true`, or the recorded child is no longer resumable. The receipt is terminal-only: if `status.json` or `events.jsonl` exists without it, the workflow may still be active or terminal receipt writing may have failed. Use direct child run IDs from status/events for direct resume after the normal retained-child checks; do not reconstruct keyed entries from those files. Foreground workflow results expose the same receipt in `details.workflow.receipt`, but cross-workflow keyed lookup requires the durable receipt from an async workflow.
99
118
 
119
+ ### Parallel sequential lanes
120
+
121
+ For a broad plan with a known set of narrow, visible stages per lane, use
122
+ `runs.lanes(...)` inside a `workflowScript`; it is a nested helper, not a
123
+ top-level `subagent` mode. Give each lane and stage a stable key. The first
124
+ stage from every lane is launched together, then later stages sequence per lane.
125
+ `resume: "previous"` requires the retained predecessor, and a failed or blocked
126
+ stage blocks only that lane. The returned board exposes lane/stage results for
127
+ the parent. See the [canonical staged-lane example](../../../docs/workflows.md#parallel-sequential-lanes).
128
+
129
+ Use raw `runs.run(...)`/`runs.all(...)` instead when branching or rolling fanout
130
+ depends on runtime data rather than a predeclared stage plan.
131
+
100
132
  ### Async/background
101
133
 
102
- 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.
134
+ 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, publication gates, and scripted workflows. Keep the write path single-threaded even when the run is async.
103
135
 
104
136
  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.
105
137
 
@@ -107,9 +139,18 @@ Async does not mean parallel writes. Do not edit the same active worktree while
107
139
 
108
140
  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.
109
141
 
110
- 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.
142
+ In an ordinary interactive chat, normally return control after launching or
143
+ triaging useful async work and let Pi wake the session on completion; do not
144
+ call `subagent_wait()` merely to wait. A run-to-completion user request is not
145
+ by itself a reason to use foreground children. Override the normal yield-and-
146
+ wake flow only when this exact turn cannot safely end without the result, such
147
+ as a headless provider flow or a skill contract that must produce a same-turn
148
+ artifact. Use `subagent_wait()`, not `async:false`, for that current-turn
149
+ dependency. Never substitute sleep or status-polling loops.
150
+
151
+ `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; active work keeps running if it elapses. `subagent_wait({ stopOnAttention: false })` keeps a blocking wait through idle or long-thinking attention, but supervisor/contact requests still stop it. 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.
111
152
 
112
- `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.
153
+ Providers are discovered through the `pi-subagents/background-work` registry and must expose a stable item id and owning session id. Load a provider through the child’s `extensions` or `subagentOnlyExtensions` and allow `subagent_wait` in its tools. For non-interactive fleets, launch N workers, wait for the next completion, react, and replace as needed; use `all: true` only when intentionally draining the fleet. If `PI_SUBAGENT_WAIT_TOOL_ENABLED` disables blocking, direct waits return immediately, but headless `agent_end` auto-drain still surfaces provider, reconciliation, or timeout failures.
113
154
 
114
155
  ```typescript
115
156
  subagent({
@@ -41,7 +41,7 @@ subagent({
41
41
  description: "Project-specific implementation helper",
42
42
  systemPrompt: "Your system prompt here.",
43
43
  systemPromptMode: "replace",
44
- model: "openai-codex/gpt-5.4",
44
+ model: "provider/model-id",
45
45
  tools: "read,grep,find,ls,bash"
46
46
  }
47
47
  })
@@ -97,7 +97,7 @@ name: my-agent
97
97
  package: code-analysis
98
98
  description: What this agent does
99
99
  aliases: developer, coder
100
- model: openai-codex/gpt-5.4
100
+ model: provider/model-id
101
101
  thinking: high
102
102
  tools: read, grep, find, ls, bash
103
103
  systemPromptMode: replace