@vicary/pi-subagents 0.87.0 → 0.88.1

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 (108) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +3 -3
  4. package/bundle/{chunk-3CVOAS77.js → chunk-2DIEL4WG.js} +2 -2
  5. package/bundle/{chunk-75LVXBSA.js → chunk-2HKPEANZ.js} +114 -49
  6. package/bundle/{chunk-ESWW6XSX.js → chunk-47ZN7NKR.js} +1 -1
  7. package/bundle/{chunk-C3KWLXDH.js → chunk-4MVDMA5C.js} +9 -1
  8. package/bundle/{chunk-XV7RTWTS.js → chunk-4ZQBZDF3.js} +21 -6
  9. package/bundle/{chunk-LZKVUWIY.js → chunk-5EMPFFO4.js} +30 -5
  10. package/bundle/{chunk-OOE3R7IQ.js → chunk-6CG2VAG4.js} +2 -2
  11. package/bundle/{chunk-HDICKROY.js → chunk-7OX6O7DQ.js} +31 -14
  12. package/bundle/{chunk-Z4TR7MK6.js → chunk-AZPP3G4N.js} +14 -5
  13. package/bundle/{chunk-PUSTU4Q7.js → chunk-BKISQ5CJ.js} +130 -49
  14. package/bundle/{chunk-NMYBVCGP.js → chunk-CGWNA6EJ.js} +75 -44
  15. package/bundle/{chunk-PGU4TZV3.js → chunk-CPSUJHZE.js} +417 -455
  16. package/bundle/{chunk-W52LJANO.js → chunk-CYKNHFXB.js} +1 -1
  17. package/bundle/{chunk-SIAQXPJ4.js → chunk-D32H53HM.js} +21 -9
  18. package/bundle/{chunk-YEXKJJVS.js → chunk-DSHQWGHO.js} +4 -4
  19. package/bundle/{chunk-6O7YH2QV.js → chunk-GDR2ILWY.js} +1 -1
  20. package/bundle/{chunk-O7A26O6B.js → chunk-IYT7X46U.js} +6 -4
  21. package/bundle/{chunk-NJTSXIMG.js → chunk-JQTHG2ID.js} +12 -12
  22. package/bundle/{chunk-C5QWQSSM.js → chunk-KXW62VBU.js} +1 -1
  23. package/bundle/{chunk-BFF6YDK6.js → chunk-L4YY2TOE.js} +1 -1
  24. package/bundle/{chunk-2NY5PCKQ.js → chunk-LV3CPYXJ.js} +4 -4
  25. package/bundle/{chunk-2D2DQGC2.js → chunk-PYKBTBY6.js} +27 -10
  26. package/bundle/{chunk-M2VBGET6.js → chunk-RMZAAXIR.js} +7 -2
  27. package/bundle/{chunk-HTI7DD5D.js → chunk-V7SZMS6W.js} +2 -2
  28. package/bundle/{chunk-VFUFOZBU.js → chunk-W6HIYD2Z.js} +1 -1
  29. package/bundle/{chunk-USRX7QXD.js → chunk-XIA5GSEU.js} +2 -2
  30. package/bundle/{chunk-CTPAE36Y.js → chunk-YARY7JWU.js} +22 -0
  31. package/bundle/chunk-YDZ7BZD5.js +523 -0
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +9 -9
  36. package/bundle/project-panes.js +3 -3
  37. package/bundle/required-child-extensions.js +1 -1
  38. package/docs/agents.md +4 -2
  39. package/docs/configuration.md +4 -2
  40. package/docs/observability.md +2 -0
  41. package/docs/tool-reference.md +4 -1
  42. package/docs/workflows.md +3 -1
  43. package/package.json +3 -3
  44. package/skills/pi-subagents/SKILL.md +8 -2
  45. package/src/agents/agent-management.d.ts +1 -0
  46. package/src/agents/agent-management.js +12 -4
  47. package/src/agents/agents.d.ts +1 -0
  48. package/src/agents/agents.js +2 -2
  49. package/src/extension/config.d.ts +9 -0
  50. package/src/extension/config.js +13 -0
  51. package/src/extension/index.d.ts +1 -1
  52. package/src/extension/index.js +47 -23
  53. package/src/extension/schemas.d.ts +2 -0
  54. package/src/extension/schemas.js +1 -0
  55. package/src/extension/subagent-launch-tool.d.ts +6 -2
  56. package/src/extension/subagent-launch-tool.js +13 -9
  57. package/src/extension/tool-activation.js +20 -3
  58. package/src/runs/background/async-resume.js +2 -1
  59. package/src/runs/background/async-retention.d.ts +0 -2
  60. package/src/runs/background/async-retention.js +11 -5
  61. package/src/runs/background/async-status.d.ts +2 -0
  62. package/src/runs/background/async-status.js +4 -0
  63. package/src/runs/background/run-child-session.d.ts +2 -2
  64. package/src/runs/background/run-child-session.js +4 -7
  65. package/src/runs/background/stale-run-reconciler.js +17 -8
  66. package/src/runs/background/steering.d.ts +2 -11
  67. package/src/runs/background/steering.js +11 -6
  68. package/src/runs/background/subagent-runner.d.ts +0 -2
  69. package/src/runs/background/subagent-runner.js +73 -58
  70. package/src/runs/foreground/async-steering-action.js +24 -9
  71. package/src/runs/foreground/execution.js +32 -15
  72. package/src/runs/foreground/prompt-audit.js +1 -0
  73. package/src/runs/foreground/subagent-executor.d.ts +1 -8
  74. package/src/runs/foreground/subagent-executor.js +17 -21
  75. package/src/runs/shared/async-status-projection.d.ts +2 -0
  76. package/src/runs/shared/async-status-projection.js +10 -0
  77. package/src/runs/shared/child-launch.js +6 -3
  78. package/src/runs/shared/child-session.d.ts +1 -1
  79. package/src/runs/shared/child-session.js +24 -30
  80. package/src/runs/shared/mcp-config-sources.d.ts +2 -0
  81. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +5 -5
  82. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -15
  83. package/src/runs/shared/subagent-prompt-runtime.js +14 -2
  84. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  85. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  86. package/src/shared/artifacts.d.ts +1 -0
  87. package/src/shared/artifacts.js +107 -9
  88. package/src/shared/compaction-interruption.d.ts +9 -0
  89. package/src/shared/compaction-interruption.js +47 -0
  90. package/src/shared/parent-wake.d.ts +3 -2
  91. package/src/shared/parent-wake.js +14 -3
  92. package/src/shared/reported-progress.d.ts +1 -0
  93. package/src/shared/reported-progress.js +12 -0
  94. package/src/shared/required-child-extensions.d.ts +2 -0
  95. package/src/shared/required-child-extensions.js +27 -0
  96. package/src/shared/status-format.d.ts +1 -0
  97. package/src/shared/status-format.js +1 -1
  98. package/src/shared/types.d.ts +9 -0
  99. package/src/shared/utils.d.ts +3 -1
  100. package/src/shared/utils.js +4 -0
  101. package/src/tui/fleet.d.ts +7 -2
  102. package/src/tui/fleet.js +22 -0
  103. package/src/tui/render.js +33 -2
  104. package/src/watchdog/permission-arbiter.js +1 -0
  105. package/src/watchdog/review.d.ts +0 -5
  106. package/src/watchdog/review.js +2 -1
  107. package/src/workflows/workflow-script-worker.js +3 -1
  108. package/bundle/chunk-XSDYTXHF.js +0 -242
@@ -106,7 +106,7 @@ Controls how a new parent session offers the `subagent` tool. The default is `"a
106
106
  - `"dynamic"`: every new session starts with the loader, whatever the model. This was the behavior before `toolActivation` existed.
107
107
  - `"eager"`: the loader is not registered, and the extension does not change the tool selection. A new session or `/reload` makes `subagent` active; a resumed session whose recorded tools lack `subagent` stays without it until `/reload`. See the recovery steps above.
108
108
 
109
- The choice is made at session start or tree navigation, and only for a session with no messages. If a compaction that kept no tool checkpoint dropped the record of this choice, the session is decided again as a new session would be; tool selections recorded after that compaction (for `bg_wait` or another extension's tools) are not evidence that the choice survived. Under `"auto"`, resumed sessions keep the tools they recorded. `"dynamic"` also adds the loader to recorded sessions that did not have it. Switching models mid-session does not change the selection. `"auto"` avoids only the loader's cache miss; other tool-list or provider changes can still miss the cache. An active `subagent` sends its full schema on every request. An invalid value is a config error, not a fallback to the default. Restart Pi after changing it.
109
+ The choice is made only for a session with no messages, using the model selected before its first prompt. Switching models after that prompt does not change it. If a compaction that kept no tool checkpoint dropped the record of this choice, the session is decided again as a new session would be; tool selections recorded after that compaction (for `bg_wait` or another extension's tools) are not evidence that the choice survived. Under `"auto"`, resumed sessions keep the tools they recorded. `"dynamic"` also adds the loader to recorded sessions that did not have it. `"auto"` avoids only the loader's cache miss; other tool-list or provider changes can still miss the cache. An active `subagent` sends its full schema on every request. An invalid value is a config error, not a fallback to the default. Restart Pi after changing it.
110
110
 
111
111
  ## `toolDescriptionMode`
112
112
 
@@ -444,6 +444,8 @@ Forces depth-0 internal single, parallel, and chain runs into background mode an
444
444
 
445
445
  Global default runtime deadline, in milliseconds, for foreground launches (single, parallel, chain, and workflow scripts) and plain single-agent async runs whenever no call-level `timeoutMs`/`maxRuntimeMs` applies. Without a configured or explicit deadline, these runs have no runtime deadline. For single-agent launches, selected agent frontmatter `timeoutMs` still wins. This only moves the *default*. Expiring this run-level deadline is terminal.
446
446
 
447
+ A run's deadline does not count time a child spends waiting for its supervisor's reply to a `contact_supervisor` decision or interview, or to an `intercom` ask; `progress_update` does not pause it, and the overall deadline of a workflow script stays wall-clock.
448
+
447
449
  This deadline bounds the whole run. The wait for a single model response is bounded separately by Pi's `httpIdleTimeoutMs` setting (default 300000; `0` disables it), which Pi applies both as the SDK request timeout and as the undici header/body idle timeout. Detached async runners read the same setting from `~/.pi/agent/settings.json` and the project `.pi/settings.json` for their own HTTP dispatcher, so a local model that queues or prefills for longer than five minutes needs `httpIdleTimeoutMs` raised or disabled in Pi settings, and any configured run deadline must also allow enough time.
448
450
 
449
451
  Use it when foreground orchestration or plain async single-agent runs need a default deadline. It does not set async composite top-level deadlines, and it does not replace async fan-out child deadlines.
@@ -732,7 +734,7 @@ Controls where subagent artifact files (inputs, outputs, transcripts, metadata)
732
734
 
733
735
  This preference also controls the default workflow artifact directory used by scripted chaining. `"project"` uses `<cwd>/.pi/subagents/chain-runs/`; the directory keeps its legacy name for compatibility. The default `"session"` and `"temp"` use the user-scoped temp workflow artifact directory.
734
736
 
735
- The `"session"` option uses the same directory that `cleanupAllArtifactDirs` already scans for age-based cleanup, so artifacts are still cleaned up automatically: files older than `artifactConfig.cleanupDays` (default 7, `0` turns cleanup off) are removed, including those in nested folders such as workflow `outputs/`. `handoffs/` and `worktree-diffs/` are kept, because they record worktrees that can be kept longer than that. Temporary workflow artifact directories are cleaned up separately after 24 hours.
737
+ The `"session"` option uses the same directory that `cleanupAllArtifactDirs` already scans for age-based cleanup, so artifacts are still cleaned up automatically: files older than `artifactConfig.cleanupDays` (default 7, `0` turns cleanup off) are removed, including those in nested folders such as workflow `outputs/`. `handoffs/` and `worktree-diffs/` are kept, because they record worktrees that can be kept longer than that. Temporary workflow artifact directories are cleaned up separately after 24 hours. The same setting covers forked children: each one writes a copy of the parent's session file to `<parent session file without .jsonl>/forks/<run id>/`, and once a day at extension load a copy is deleted when nothing has written to it for `cleanupDays` and its async run is not queued or running; the forked child's own artifacts, which live in that folder, go with it. Resuming a child after its copy is deleted fails with an error that says so.
736
738
 
737
739
  When a project-scoped launch runs from an npm package directory, pi-subagents warns if package settings can include `.pi/subagents/` in the published package. Add `.pi/subagents/` to `.npmignore` (or `.gitignore` when no `.npmignore` exists), use a `files` allowlist that does not include `.pi/subagents/`, or select `"session"` or `"temp"`.
738
740
 
@@ -16,6 +16,8 @@ Long-open `bash` attention notices identify the exact tool call and include stat
16
16
 
17
17
  Live progress shows compact detail for single, chain, and parallel modes: a bounded one-line task, current tool, recent output, token counts, aggregate cost, duration, activity freshness, current-tool duration, and chain graph metadata when available. Workflow `label` metadata wins over raw task text in compact multi-child cards.
18
18
 
19
+ While a child runs, the first line of its latest successful `contact_supervisor` `progress_update` shows as a `progress:` row under its task, with the time since the report.
20
+
19
21
  Press Pi's configured expand key (`Ctrl+O` by default) to expand the full streaming view with complete output per step.
20
22
 
21
23
  Sequential chains show a flow line like `done scout → running worker`. Chains with parallel steps show per-step cards instead. Chain status uses `label` and `phase` metadata when present, while falling back to agent names for older chains.
@@ -95,6 +95,7 @@ The `subagent` tool schema lists `agent`, `task`, `workflow`, `args`, `async`, `
95
95
  | `options.view` | `fleet \| transcript` | - | Optional `status` view for the active fleet surface or transcript tail inspection. |
96
96
  | `options.lines` | number | `80` | Maximum transcript lines for `action: "status"` with `options.view: "transcript"`; capped at 500. |
97
97
  | `options.agentScope` | `user \| project \| both` | `both` | Agent discovery scope. Project wins on collisions. |
98
+ | `options.search` | string | - | With `action: "list"`, show only agents whose name, alias, or description contains this text (case-insensitive). |
98
99
  | `options.capabilities` | boolean | `false` | With `action: "list"`, return compact prompt-free rows and `details.agentCapabilities` machine-readable records for each agent's declared/default routing capabilities. External CLI rows also include their command and passive local availability. |
99
100
 
100
101
  ### Execution parameters
@@ -105,7 +106,7 @@ The `subagent` tool schema lists `agent`, `task`, `workflow`, `args`, `async`, `
105
106
  | `options.chatProgress` | `auto \| off \| live-card` | `auto` | Workflow 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. |
106
107
  | `isolation` | `none \| worktree` | - | Alias kept at the top level; prefer `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. |
107
108
  | `options.baseRef` | string | `HEAD` | `HEAD` or a supported named ref such as `refs/heads/release`, `refs/tags/v1`, or `origin/main`. Full 40/64-character commit IDs and revision expressions such as `HEAD~1` are unsupported. The ref must resolve to a commit at worktree allocation; omitted values default to `HEAD` resolved at that time. Source-checkout cleanliness is still checked. For a workflow script, set it on the outer request as a default or on an individual `runs.run`/`runs.all` child to override it. |
108
- | `options.timeoutMs` | number | config `timeoutMs`, else none | Optional run-level max runtime in milliseconds. The top-level alias `maxRuntimeMs` is also accepted; both must agree. When omitted, the global [`timeoutMs`](configuration.md#timeoutms) config provides the default for foreground and plain single-agent async runs; otherwise no run-level deadline applies. Composite async runs (chains, parallel tasks, workflows) stay unbounded at the top level unless explicitly bounded. Expiration of a run-level deadline is terminal. |
109
+ | `options.timeoutMs` | number | config `timeoutMs`, else none | Optional run-level max runtime in milliseconds; time a child spends waiting for a supervisor reply (`contact_supervisor` decision or interview, `intercom` ask) does not count. The top-level alias `maxRuntimeMs` is also accepted; both must agree. When omitted, the global [`timeoutMs`](configuration.md#timeoutms) config provides the default for foreground and plain single-agent async runs; otherwise no run-level deadline applies. Composite async runs (chains, parallel tasks, workflows) stay unbounded at the top level unless explicitly bounded. Expiration of a run-level deadline is terminal. |
109
110
  | `options.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 `bg_wait` are exempt. |
110
111
  | `options.checkpointBeforeDeadlineMs` | number | none | Async single-agent runs only. The runner requests that the child "checkpoint and stop" this many milliseconds before the run deadline (finish the current tool call, report changed files, build/test state, remaining work, commit/PR state; start no new work). This best-effort steer uses the normal steering lifecycle at the next tool boundary, so the receipt is visible in status and events; the ordinary deadline kill still applies. Precedence: call value → config `checkpointBeforeDeadlineMs`. Disarmed when the deadline leaves under one second before the checkpoint. |
111
112
  | `options.toolBudget` | object | none | Optional child tool-call budget `{ soft?, hard, block? }`: `hard` is a positive integer and `soft`, if set, is a positive integer no greater than `hard`. At `soft` the child is nudged to finalize. After `hard`, configured tools are blocked; `block` defaults to `read`, `grep`, `find`, and `ls`, and accepts either a nonempty array of tool names or `"*"` for every tool call. Final assistant text is never blocked. |
@@ -210,6 +211,7 @@ Agent definitions are not loaded into context by default. Management actions let
210
211
  { action: "list" }
211
212
  { action: "list", options: { agentScope: "project" } }
212
213
  { action: "list", options: { capabilities: true } }
214
+ { action: "list", options: { search: "review" } }
213
215
  { action: "get", agent: "scout" }
214
216
  { action: "models" }
215
217
  { action: "models", agent: "reviewer" }
@@ -252,6 +254,7 @@ Agent definitions are not loaded into context by default. Management actions let
252
254
 
253
255
  Rules:
254
256
 
257
+ - `action: "list"` shows at most 30 agents, then a `+N more` line pointing at `options.search`; `details.agentCapabilities` still covers every match.
255
258
  - `options.capabilities: true` changes `action: "list"` to compact one-line rows and adds `details.agentCapabilities: { agents, restrictedCount, capabilityCeilingSources? }`. Each agent row includes source, aliases, runner type/capabilities, tools, MCP direct tools, mutation tools, model/thinking, default async/timeout, declared acceptance policy/role, output path/mode, skills/extensions, and whether the current capability ceiling allows execution. External CLI rows include `runner.command`, `runner.available`, and a bounded `runner.unavailableReason` when passive PATH/PATHEXT/X_OK lookup cannot find the command. It never includes an agent's system prompt. Rows show declared/default capabilities and command discoverability, not authentication, version compatibility, or successful launch; launch preflight remains authoritative.
256
259
  - `create` uses `config.scope`, not `agentScope`.
257
260
  - `config.name` is the local frontmatter name; optional `config.package` registers the runtime name as `{package}.{name}` and is saved as separate `name` and `package` frontmatter.
package/docs/workflows.md CHANGED
@@ -149,7 +149,9 @@ The host resolves the name and validates bounded plain-JSON `args` before starti
149
149
 
150
150
  ### Approving workflow children in permission extensions
151
151
 
152
- Before a workflow starts a child, pi-subagents makes a nested `subagent_launch` tool call, so permission extensions see it in their `tool_call` handler like any other tool call. This covers reply-block, file and named workflows, and `chain` and `tasks`. The call's input is `{ workflowRunId, key, agent?, task?, cwd?, model?, async?, worktree?, resume?, commands?, output? }`. `cwd` is the absolute directory the child starts in. It is left out for a resumed child, which keeps its earlier directory, and for a child placed on another machine. `commands` lists, in run order, the shell commands the child's `gate`, `acceptance.verify` or agent `acceptance` will run on this machine after the child finishes, each `{ command, cwd?, env? }`. A command's `cwd` is absolute and is left out when the child's is; for a `worktree: true` child it names the source directory, because the worktree does not exist yet. `env` lists only the variables the command sets on top of the parent's environment. `output` is the absolute path of the file the child's `output` writes. The other optional fields appear when the child request sets them. A blocked or failed call stops that child, so its commands never run and its output file is never written; it fails with `Workflow child '<key>' was not started: …` and the block reason. Allowed calls do nothing else. The tool is not declared to the model.
152
+ Before a workflow starts a child, pi-subagents makes a nested `subagent_launch` tool call, so permission extensions see it in their `tool_call` handler like any other tool call. This covers reply-block, file and named workflows, and `chain` and `tasks`. The call's input is `{ workflowRunId, key, agent?, task?, cwd?, model?, async?, worktree?, resume?, commands?, output? }`. `cwd` is the absolute directory the child starts in. It is left out for a resumed child, which keeps its earlier directory, and for a child placed on another machine. `commands` lists, in run order, the shell commands the child's `gate`, `acceptance.verify` or agent `acceptance` will run on this machine after the child finishes, each `{ command, cwd?, env? }`. A command's `cwd` is absolute and is left out when the child's is; for a `worktree: true` child it names the source directory, because the worktree does not exist yet. `env` lists only the variables the command sets on top of the parent's environment. `output` is the absolute path of the file the child's `output` writes. The other optional fields appear when the child request sets them. A blocked or failed call stops that child, so its commands never run and its output file is never written; it fails with `Workflow child '<key>' was not started: …` and the block reason. The tool is not declared to the model.
153
+
154
+ A handler may also change `task` in place (`event.input.task = …`). A freshly launched child then receives the changed text, after `{previous}` is filled in and before any fork preamble is added. Changes to any other field, and to a resumed child's message, are ignored. Handlers run in registration order, so one registered earlier sees the original text.
153
155
 
154
156
  Extensions that ask about tools they have no rule for ask once per workflow child until you allow `subagent_launch`. Ones that deny unknown tools without a UI, as in `pi -p`, refuse every workflow child until you allow it.
155
157
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@vicary/pi-subagents",
4
- "version": "0.87.0",
4
+ "version": "0.88.1",
5
5
  "description": "Pi extension for single-agent delegation and scripted multi-agent workflows",
6
6
  "author": "Nico Bailon",
7
7
  "license": "MIT",
@@ -20,7 +20,7 @@
20
20
  "@js-temporal/polyfill": "0.5.1",
21
21
  "acorn": "8.18.0",
22
22
  "jiti": "2.7.0",
23
- "undici": "8.12.3",
23
+ "undici": "8.12.4",
24
24
  "yaml": "2.8.3"
25
25
  },
26
26
  "peerDependencies": {
@@ -135,5 +135,5 @@
135
135
  "./prompts"
136
136
  ]
137
137
  },
138
- "gitHead": "207fb43a2eea3abb55f3dbb57ed5f027edd6db85"
138
+ "gitHead": "5091dc4108789ed257c421b927e7c7b960af5f4b"
139
139
  }
@@ -104,7 +104,13 @@ number.
104
104
  `.pi/subagents/` does not). For Pi extension repos, put lane worktrees
105
105
  outside `~/.pi/agent/extensions`, for example `~/.pi/agent/worktrees`.
106
106
  - Reviewers use fresh context. Use `context: "fork"` only when the child needs
107
- the parent's history; it requires a persisted parent session.
107
+ the parent's history; it requires a persisted parent session. Each fork
108
+ copies the parent's session file to
109
+ `<parent session file without .jsonl>/forks/<run id>/`:
110
+ before forking from a session file of hundreds of MB, run `df -h` on that
111
+ file's folder. Once a forked child is accepted or dropped and won't be
112
+ resumed, delete its `forks/<run id>/` folder; never one whose run is still
113
+ active.
108
114
  - Children do not spawn subagents unless the parent delegated fanout and their
109
115
  resolved `tools` include `subagent`.
110
116
  - A failed workflow, launch, prompt runtime, extension load, or child tool
@@ -112,7 +118,7 @@ number.
112
118
  verify a clean worktree or capture the partial diff, then retry the same way
113
119
  once. Switching to `interactive_shell`, `pi -ne`, or another CLI needs owner
114
120
  approval.
115
- - 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.
121
+ - 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.
116
122
  - Route workers and scouts to a fast capable tier, serious reviews to a strong
117
123
  tier, and top reasoning only to bounded read-only critique. Exact model names
118
124
  belong in user or project settings, not here. When neither the user nor
@@ -17,6 +17,7 @@ interface ManagementParams {
17
17
  agentScope?: unknown;
18
18
  capabilities?: unknown;
19
19
  config?: unknown;
20
+ search?: unknown;
20
21
  }
21
22
  export declare function editableAgentConfig(agent: AgentConfig): AgentConfig;
22
23
  export declare function preservedAgentFrontmatterFields(agent: AgentConfig, cfg: Record<string, unknown>): Set<string>;
@@ -1,6 +1,6 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
- import { defaultInheritProjectContext, defaultInheritSkills, defaultSystemPromptMode, discoverAgentsAll, buildRuntimeName, findBlockingAgentDiagnostic, frontmatterNameForConfig, parsePackageName, mergeBuiltinAgentOverride, removeBuiltinAgentOverride, removeBuiltinAgentOverrideFields, resolveAgentName, } from "./agents.js";
3
+ import { defaultInheritProjectContext, defaultInheritSkills, defaultSystemPromptMode, discoverAgentsAll, buildRuntimeName, findBlockingAgentDiagnostic, frontmatterNameForConfig, MAX_LISTED_AGENTS, parsePackageName, mergeBuiltinAgentOverride, removeBuiltinAgentOverride, removeBuiltinAgentOverrideFields, resolveAgentName, } from "./agents.js";
4
4
  import { serializeAgent } from "./agent-serializer.js";
5
5
  import { mergeAgentsForScope } from "./agent-selection.js";
6
6
  import { discoverAvailableSkills, resolveSkills } from "./skills.js";
@@ -1030,7 +1030,9 @@ export function handleList(params, ctx) {
1030
1030
  scopedAgents = scopedAgents
1031
1031
  .sort((a, b) => a.name.localeCompare(b.name));
1032
1032
  const capabilityCeiling = resolveCurrentSubagentCapabilityCeiling(ctx.piSessionId);
1033
- const visibleAgents = scopedAgents.filter((a) => !a.disabled);
1033
+ const search = typeof params.search === "string" ? params.search.trim().toLowerCase() : "";
1034
+ const visibleAgents = scopedAgents.filter((a) => !a.disabled
1035
+ && (!search || [a.name, a.description, ...(a.aliases ?? [])].some((text) => text.toLowerCase().includes(search))));
1034
1036
  const agents = visibleAgents.filter((a) => isAgentAllowedByCapabilityCeiling(a.name, capabilityCeiling));
1035
1037
  const restrictedAgents = visibleAgents.filter((a) => !isAgentAllowedByCapabilityCeiling(a.name, capabilityCeiling));
1036
1038
  const restrictedSources = capabilityCeilingAgentRestrictionSources(capabilityCeiling);
@@ -1050,11 +1052,17 @@ export function handleList(params, ctx) {
1050
1052
  const formatLine = capabilityMode
1051
1053
  ? (agent, names) => formatAgentCapabilitiesLine(agent, names, externalCliAvailability, unavailableModels)
1052
1054
  : formatAgentListLine;
1055
+ // A large catalog would otherwise put every agent's description into the model's context at once.
1056
+ const shownAgents = agents.slice(0, MAX_LISTED_AGENTS);
1057
+ const shownRestrictedAgents = restrictedAgents.slice(0, MAX_LISTED_AGENTS - shownAgents.length);
1058
+ const omittedCount = Math.max(0, agents.length + restrictedAgents.length - MAX_LISTED_AGENTS);
1053
1059
  const lines = [
1054
1060
  capabilityMode ? "Executable agents (capabilities):" : "Executable agents:",
1055
- ...formatAgentListSections(agents, providerNameSet, formatLine),
1061
+ ...formatAgentListSections(shownAgents, providerNameSet, formatLine),
1056
1062
  ];
1057
- appendRestrictedAgentLines({ lines, agents: restrictedAgents, sources: restrictedSources, providerNames: providerNameSet, formatLine });
1063
+ appendRestrictedAgentLines({ lines, agents: shownRestrictedAgents, sources: restrictedSources, providerNames: providerNameSet, formatLine });
1064
+ if (omittedCount > 0)
1065
+ lines.push("", `+${omittedCount} more; narrow with {action:"list", options:{search:"<term>"}}`);
1058
1066
  appendExternalJobRegistryLine(lines, [...agents, ...restrictedAgents], providerStatus);
1059
1067
  appendAgentDiagnosticLines(lines, d.agentDiagnostics);
1060
1068
  if (proactiveSuggestions.length)
@@ -235,6 +235,7 @@ export interface AgentDiscoveryResult {
235
235
  }
236
236
  /** Create formatter input from the exact discovery operation used for resolution. */
237
237
  export declare function unknownAgentDiagnosticContext(discovered: Pick<AgentDiscoveryResult, "cwd" | "scope" | "directories" | "agents" | "disabledAgents">): UnknownAgentDiagnosticContext;
238
+ export declare const MAX_LISTED_AGENTS = 30;
238
239
  /** One line per agent the caller can launch instead, so a wrong name needs no separate list call. */
239
240
  export declare function formatAvailableAgentLines(agents: readonly AgentConfig[]): string[];
240
241
  /** The closest agent name or alias when `name` looks like a typo of one. */
@@ -84,7 +84,7 @@ export function unknownAgentDiagnosticContext(discovered) {
84
84
  ...(discovered.disabledAgents?.length ? { disabledAgents: discovered.disabledAgents } : {}),
85
85
  };
86
86
  }
87
- const MAX_LISTED_AGENTS = 30;
87
+ export const MAX_LISTED_AGENTS = 30;
88
88
  const MAX_LISTED_DESCRIPTION_CHARS = 80;
89
89
  /** One line per agent the caller can launch instead, so a wrong name needs no separate list call. */
90
90
  export function formatAvailableAgentLines(agents) {
@@ -95,7 +95,7 @@ export function formatAvailableAgentLines(agents) {
95
95
  return `- ${agent.name} (${agent.source})${short ? ` — ${short}` : ""}`;
96
96
  });
97
97
  if (sorted.length > MAX_LISTED_AGENTS)
98
- lines.push(`+${sorted.length - MAX_LISTED_AGENTS} more; {action:"list"}`);
98
+ lines.push(`+${sorted.length - MAX_LISTED_AGENTS} more; {action:"list", options:{search:"<term>"}}`);
99
99
  return lines.length ? lines : ["- (none)"];
100
100
  }
101
101
  /** The closest agent name or alias when `name` looks like a typo of one. */
@@ -1,5 +1,14 @@
1
1
  import { type ExtensionConfig } from "../shared/types.ts";
2
2
  export declare function resolveScheduledStoreRoot(value: string): string;
3
+ /**
4
+ * Resolve the optional global default runtime deadline from extension config
5
+ * (`config.timeoutMs`). Returns undefined for unset or invalid values so callers
6
+ * use no configured deadline. "Invalid" covers non-positive-integer values and
7
+ * values above the Node.js timer ceiling; an invalid value counts as unset, and
8
+ * above that ceiling a timer fires almost at once, expiring the run instead of
9
+ * running long.
10
+ */
11
+ export declare function resolveConfigDefaultTimeoutMs(raw: unknown): number | undefined;
3
12
  export declare function getConfigPath(): string;
4
13
  export declare function saveConfig(config: ExtensionConfig, configPath?: string): void;
5
14
  export declare function updateConfig(updater: (config: ExtensionConfig) => ExtensionConfig): ExtensionConfig;
@@ -244,6 +244,19 @@ function validateConfig(config) {
244
244
  validateOrcaProgressTabsConfig(config.orcaProgressTabs);
245
245
  validateRunnerLaunchersConfig(config.runnerLaunchers);
246
246
  }
247
+ /**
248
+ * Resolve the optional global default runtime deadline from extension config
249
+ * (`config.timeoutMs`). Returns undefined for unset or invalid values so callers
250
+ * use no configured deadline. "Invalid" covers non-positive-integer values and
251
+ * values above the Node.js timer ceiling; an invalid value counts as unset, and
252
+ * above that ceiling a timer fires almost at once, expiring the run instead of
253
+ * running long.
254
+ */
255
+ export function resolveConfigDefaultTimeoutMs(raw) {
256
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw <= 0 || raw > 2_147_483_647)
257
+ return undefined;
258
+ return raw;
259
+ }
247
260
  export function getConfigPath() {
248
261
  return path.join(getAgentDir(), "extensions", "subagent", "config.json");
249
262
  }
@@ -1,4 +1,4 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
1
+ import { type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { type HerdrStatusRun } from "../integrations/herdr-status.ts";
3
3
  import { type SubagentState } from "../shared/types.ts";
4
4
  export declare function projectActiveHerdrRuns(state: SubagentState): HerdrStatusRun[];
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import * as fs from "node:fs";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
5
+ import { AgentSession } from "@earendil-works/pi-coding-agent";
5
6
  import { Box, Container, Spacer, Text } from "@earendil-works/pi-tui";
6
7
  import { clearAgentDiscoveryCache, discoverAgentSnapshot, discoverAgents, discoverAgentsAll } from "../agents/agents.js";
7
8
  import { resolveGlobalNpmRoot } from "../agents/global-npm-root.js";
@@ -13,6 +14,7 @@ import { cleanupAllArtifactDirs, cleanupOldArtifacts, getArtifactsDir } from "..
13
14
  import { resolveCurrentSessionId } from "../shared/session-identity.js";
14
15
  import { recordSessionReplacement, recordSessionStart } from "../shared/session-succession.js";
15
16
  import { createSessionSwitchGuard } from "./session-switch.js";
17
+ import { compactionInProgress, compactionInterruptedRun, installCompactionInterruptionCapture, takeCompactionAbort } from "../shared/compaction-interruption.js";
16
18
  import { reportSessionWarning } from "../shared/session-warnings.js";
17
19
  import { getAgentDir } from "../shared/utils.js";
18
20
  import { isStaleExtensionContextError, MODEL_ONLY_TOOL, withCachedUiContext } from "../shared/extension-context.js";
@@ -59,7 +61,7 @@ import { handleSubagentSteeringNotice } from "./steering-notices.js";
59
61
  import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "../runs/shared/child-runtime-config.js";
60
62
  import { disposeChildSessionsForParent } from "../runs/shared/child-session.js";
61
63
  import { resolveCurrentSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.js";
62
- import { loadConfig, resolveAsyncByDefault, resolveScheduledStoreRoot } from "./config.js";
64
+ import { loadConfig, resolveAsyncByDefault, resolveConfigDefaultTimeoutMs, resolveScheduledStoreRoot } from "./config.js";
63
65
  import { buildSubagentToolDescription, buildSubagentToolPromptMetadata } from "./tool-description.js";
64
66
  import { formatWorkflowPreflightSummary, normalizeWorkflowPreflight } from "../workflows/workflow-preflight.js";
65
67
  import { runtimeReplacedAbortReason } from "../workflows/workflow-reuse.js";
@@ -215,6 +217,7 @@ export default function registerSubagentExtension(pi) {
215
217
  if (process.env[SUBAGENT_CHILD_ENV] === "1") {
216
218
  return;
217
219
  }
220
+ installCompactionInterruptionCapture(AgentSession);
218
221
  const runtimeRegistry = getRuntimeRegistry();
219
222
  setMainThinkingLevelSource(() => readMainThinkingLevel(() => pi.getThinkingLevel()));
220
223
  DIRS.results = ensureAccessibleDir(DIRS.results);
@@ -490,7 +493,7 @@ export default function registerSubagentExtension(pi) {
490
493
  });
491
494
  }
492
495
  catch (error) {
493
- console.error("Failed to clean retained async subagent state:", error);
496
+ reportSessionWarning(state, `Failed to clean retained async subagent state: ${error instanceof Error ? error.message : String(error)}`, "async-retention-cleanup");
494
497
  }
495
498
  }, ASYNC_RETENTION_DELAY_MS);
496
499
  asyncRetentionTimer.unref?.();
@@ -747,7 +750,7 @@ export default function registerSubagentExtension(pi) {
747
750
  try {
748
751
  // The run is still active here, so its signal tells a user stop (Esc) apart from a finished or failed run.
749
752
  // Pi skips agent_before_settle after an abort. Background runs keep going, but they must not restart the parent.
750
- if (ctx.hasUI && ctx.signal?.aborted) {
753
+ if (ctx.hasUI && ctx.signal?.aborted && !takeCompactionAbort(ctx.sessionManager)) {
751
754
  parentWake.userAborted();
752
755
  const active = activeAsyncJobCount();
753
756
  if (active > 0)
@@ -756,8 +759,9 @@ export default function registerSubagentExtension(pi) {
756
759
  // A headless host may dispose the session as soon as this turn settles, so hand
757
760
  // finished results to Pi now; Pi runs the queued completion turn after agent_end.
758
761
  // A failed drain rejects without this step so its deadline stays exact.
762
+ // The parent ended its turn to wait for the wake, so the drain lasts as long as a run may.
759
763
  if (!ctx.hasUI)
760
- await drainOutstandingWork({ state, events: pi.events, hasPendingSupervisorRequest: supervisorChannel.hasPendingRequests }).then(resultWatcher.deliverPendingResults);
764
+ await drainOutstandingWork({ state, events: pi.events, hasPendingSupervisorRequest: supervisorChannel.hasPendingRequests, timeoutMs: resolveConfigDefaultTimeoutMs(config.timeoutMs) }).then(resultWatcher.deliverPendingResults);
761
765
  }
762
766
  finally {
763
767
  // Deliver notices after a failed drain without suppressing its rejection.
@@ -1109,7 +1113,12 @@ export default function registerSubagentExtension(pi) {
1109
1113
  }
1110
1114
  };
1111
1115
  let compactionResumeTimer;
1112
- const cancelCompactionResume = () => { clearTimeout(compactionResumeTimer); compactionResumeTimer = undefined; };
1116
+ let compactionInterruptedParent = false;
1117
+ const cancelCompactionResume = () => {
1118
+ clearTimeout(compactionResumeTimer);
1119
+ compactionResumeTimer = undefined;
1120
+ compactionInterruptedParent = false;
1121
+ };
1113
1122
  pi.on("agent_start", () => {
1114
1123
  cancelCompactionResume();
1115
1124
  parentWake.agentStarted();
@@ -1131,38 +1140,53 @@ export default function registerSubagentExtension(pi) {
1131
1140
  if (event.reason !== "manual")
1132
1141
  suspendWidgetsForCompaction();
1133
1142
  });
1134
- // Pi emits session_compact before it clears its compaction state. sendMessage's run path has no
1135
- // compaction guard (only prompt() refuses), so wait for the parent to go idle before the resume notice
1136
- // starts a run. A run that starts first cancels the pending resume.
1137
- pi.on("session_compact", (event) => {
1143
+ // parentWake only appends wakes during a manual compaction. Once every overlapping compaction has ended, wake
1144
+ // the parent once if a wake was deferred, or if a successful compaction cut off a working parent with
1145
+ // background work (Pi never continues that run). Pi emits session_compact before it clears its compaction
1146
+ // state, so wait until the session is idle and compact() has returned. A run that starts first cancels it.
1147
+ const wakeAfterCompaction = (completed) => (event, ctx) => {
1138
1148
  if (event.reason !== "manual")
1139
1149
  return;
1140
- if (activeAsyncJobCount() === 0 || !withLastUiContext(() => true))
1150
+ const sessionManager = ctx.sessionManager;
1151
+ if (completed && compactionInterruptedRun(sessionManager))
1152
+ compactionInterruptedParent = true;
1153
+ if (compactionResumeTimer)
1141
1154
  return;
1142
- cancelCompactionResume();
1143
1155
  const sessionId = state.currentSessionId;
1144
1156
  const deadline = Date.now() + COMPACTION_RESUME_DEADLINE_MS;
1145
- const resumeWhenIdle = () => {
1146
- if (state.currentSessionId !== sessionId || activeAsyncJobCount() === 0)
1157
+ const wakeWhenIdle = () => {
1158
+ compactionResumeTimer = undefined;
1159
+ if (state.currentSessionId !== sessionId)
1147
1160
  return;
1148
- const idle = withLastUiContext((ctx) => ctx.isIdle());
1149
- if (idle === undefined)
1150
- return;
1151
- if (!idle) {
1161
+ let idle;
1162
+ try {
1163
+ idle = ctx.isIdle();
1164
+ }
1165
+ catch {
1166
+ return; // Replaced or reloaded: the new session's runtime owns its notices.
1167
+ }
1168
+ // Past the deadline the next compaction event polls again.
1169
+ if (!idle || compactionInProgress(sessionManager)) {
1152
1170
  if (Date.now() < deadline)
1153
- compactionResumeTimer = setTimeout(resumeWhenIdle, COMPACTION_RESUME_POLL_MS);
1171
+ compactionResumeTimer = setTimeout(wakeWhenIdle, COMPACTION_RESUME_POLL_MS);
1154
1172
  return;
1155
1173
  }
1156
- // Pi's compact() aborts a live run first, which set the user-abort hold; this resume is deliberate.
1157
- parentWake.releaseHold();
1174
+ const interrupted = compactionInterruptedParent && activeAsyncJobCount() > 0 && withLastUiContext(() => true) === true;
1175
+ compactionInterruptedParent = false;
1176
+ if (!parentWake.takeDeferredWake() && !interrupted)
1177
+ return;
1158
1178
  parentWake.sendMessage({
1159
1179
  customType: "subagent-compaction-resume",
1160
- content: "Compaction is complete. Resume the parent task now; background subagent results will arrive separately when ready.",
1180
+ content: interrupted
1181
+ ? "Compaction is complete. Resume the parent task now; background subagent results will arrive separately when ready."
1182
+ : "Compaction is complete. Act on the background subagent notices above.",
1161
1183
  display: false,
1162
1184
  }, { triggerTurn: true });
1163
1185
  };
1164
- compactionResumeTimer = setTimeout(resumeWhenIdle, COMPACTION_RESUME_POLL_MS);
1165
- });
1186
+ compactionResumeTimer = setTimeout(wakeWhenIdle, COMPACTION_RESUME_POLL_MS);
1187
+ };
1188
+ pi.on("session_compact", wakeAfterCompaction(true));
1189
+ pi.on("session_compact_failed", wakeAfterCompaction(false));
1166
1190
  pi.on("session_start", (event, ctx) => {
1167
1191
  parentWake.bindSession(ctx);
1168
1192
  completionNotifier.bindSession(ctx.sessionManager);
@@ -7,6 +7,7 @@ export declare const SubagentFlatParams: Type.TObject<{
7
7
  extensionBindings: Type.TOptional<Type.TUnsafe<unknown>>;
8
8
  action: Type.TOptional<Type.TString>;
9
9
  capabilities: Type.TOptional<Type.TBoolean>;
10
+ search: Type.TOptional<Type.TString>;
10
11
  name: Type.TOptional<Type.TString>;
11
12
  id: Type.TOptional<Type.TString>;
12
13
  runId: Type.TOptional<Type.TString>;
@@ -141,6 +142,7 @@ export declare const SUBAGENT_OPTION_KEYS: readonly string[];
141
142
  export declare const SubagentOptionParams: Type.TObject<{
142
143
  extensionBindings: Type.TOptional<Type.TUnsafe<unknown>>;
143
144
  capabilities: Type.TOptional<Type.TBoolean>;
145
+ search: Type.TOptional<Type.TString>;
144
146
  name: Type.TOptional<Type.TString>;
145
147
  dir: Type.TOptional<Type.TString>;
146
148
  handoffPath: Type.TOptional<Type.TString>;
@@ -141,6 +141,7 @@ const SubagentParamProperties = {
141
141
  description: "Management/control only; omit for execution. validate accepts workflow: true or a script path. Discover actions with {action:\"guide\",options:{topic:\"tool-reference\"}}."
142
142
  })),
143
143
  capabilities: Type.Optional(Type.Boolean({ description: "list: compact capability rows/details without system prompts." })),
144
+ search: Type.Optional(Type.String({ minLength: 1, description: "list: case-insensitive match on agent name, alias, or description." })),
144
145
  name: Type.Optional(Type.String({ description: "schedule.create name." })),
145
146
  id: Type.Optional(Type.String({
146
147
  description: "Run id/prefix for status/control."
@@ -20,6 +20,10 @@ declare const parameters: Type.TObject<{
20
20
  export type SubagentLaunchArgs = Static<typeof parameters>;
21
21
  /** Not declared to the model, so the system prompt and tool list stay unchanged. */
22
22
  export declare function registerSubagentLaunchTool(pi: ExtensionAPI): void;
23
- /** Offers a workflow child start to the session's `tool_call` handlers; returns the refusal, if any. */
24
- export declare function approveWorkflowChildLaunch(ctx: ExtensionContext, describe: () => SubagentLaunchArgs, signal: AbortSignal): Promise<string | undefined>;
23
+ /** Offers a workflow child start to the session's `tool_call` handlers; returns the refusal, or the task the handlers left. */
24
+ export declare function approveWorkflowChildLaunch(ctx: ExtensionContext, describe: () => SubagentLaunchArgs, signal: AbortSignal): Promise<{
25
+ refusal: string;
26
+ } | {
27
+ task?: string;
28
+ }>;
25
29
  export {};
@@ -22,27 +22,31 @@ export function registerSubagentLaunchTool(pi) {
22
22
  pi.registerTool({
23
23
  name: SUBAGENT_LAUNCH_TOOL,
24
24
  label: "Subagent launch",
25
- description: "A workflow is about to start this subagent. Blocking this call stops that child from starting.",
25
+ description: "A workflow is about to start this subagent. Blocking this call stops that child from starting; changing its task changes what the child is told.",
26
26
  parameters,
27
27
  exposure: "deferred",
28
- async execute() {
29
- return { content: [{ type: "text", text: "Records approval for a workflow child launch; it starts nothing itself." }], details: {} };
28
+ // Pi hands execute the input after every tool_call handler ran, so a handler's change to task arrives here.
29
+ async execute(_toolCallId, params) {
30
+ return { content: [{ type: "text", text: "Records approval for a workflow child launch; it starts nothing itself." }], details: { task: params.task } };
30
31
  },
31
32
  });
32
33
  }
33
- /** Offers a workflow child start to the session's `tool_call` handlers; returns the refusal, if any. */
34
+ /** Offers a workflow child start to the session's `tool_call` handlers; returns the refusal, or the task the handlers left. */
34
35
  export async function approveWorkflowChildLaunch(ctx, describe, signal) {
35
36
  // Starts with no tool call behind them (schedule ticks, auto-resume, RPC) have no executeTool, and a tool
36
37
  // allowlist that leaves the tool out unregisters it: no handler could see the call in either case.
37
38
  if (!("executeTool" in ctx))
38
- return undefined;
39
+ return {};
39
40
  const toolCtx = ctx;
40
41
  if (!toolCtx.tools.some((tool) => tool.name === SUBAGENT_LAUNCH_TOOL))
41
- return undefined;
42
+ return {};
42
43
  const args = describe();
43
44
  const outcome = await toolCtx.executeTool(SUBAGENT_LAUNCH_TOOL, args, { signal });
44
- if (!outcome.isError)
45
- return undefined;
45
+ if (!outcome.isError) {
46
+ // Pi doesn't validate the input again after a handler changes it.
47
+ const task = outcome.result.details?.task;
48
+ return { task: typeof task === "string" ? task : undefined };
49
+ }
46
50
  const reason = outcome.result.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n").trim();
47
- return `Workflow child '${args.key}' was not started: the ${SUBAGENT_LAUNCH_TOOL} call was refused${reason ? `: ${reason}` : "."}`;
51
+ return { refusal: `Workflow child '${args.key}' was not started: the ${SUBAGENT_LAUNCH_TOOL} call was refused${reason ? `: ${reason}` : "."}` };
48
52
  }
@@ -182,11 +182,28 @@ export function registerSubagentToolActivation(pi, options) {
182
182
  },
183
183
  };
184
184
  registerPinnedTool(pi, loader);
185
- // Decided at session start and tree navigation only; switching models keeps the session's tools.
185
+ // Decided at session start and tree navigation. Pi declares a session's first tools only with its first request, so a
186
+ // model switch before then decides again; later switches keep the session's tools.
186
187
  let loaderSelected = true;
188
+ // The loader and subagent state the last decision left, until the first request (agent_start). A different live
189
+ // state is a choice made since, and stands.
190
+ let undeclared;
191
+ const activationState = () => [LOADER_NAME, SUBAGENT_NAME].map((name) => pi.getActiveTools().includes(name)).join();
187
192
  const replyOwed = () => options.hasPendingSupervisorRequest?.() === true;
188
- pi.on("session_start", (_event, ctx) => { loaderSelected = applyRecordedSelection(pi, ctx, mode, replyOwed()); });
189
- pi.on("session_tree", (_event, ctx) => { loaderSelected = applyRecordedSelection(pi, ctx, mode, replyOwed()); });
193
+ const decide = (ctx) => {
194
+ loaderSelected = applyRecordedSelection(pi, ctx, mode, replyOwed());
195
+ undeclared = Array.isArray(pi.getActiveTools()) ? activationState() : undefined;
196
+ };
197
+ pi.on("session_start", (_event, ctx) => decide(ctx));
198
+ pi.on("session_tree", (_event, ctx) => decide(ctx));
199
+ pi.on("agent_start", () => { undeclared = undefined; });
200
+ // Only while idle: a run being prepared or started may already have fixed its first tools.
201
+ pi.on("model_select", (_event, ctx) => {
202
+ if (mode === "auto" && ctx.isIdle() && undeclared === activationState() && loaderSelected !== addsToolsWithoutCheckpoint(ctx.model)
203
+ // SAFETY: as in applyRecordedSelection.
204
+ && ctx.sessionManager.buildSessionContext().messages.length === 0)
205
+ decide(ctx);
206
+ });
190
207
  pi.on("before_agent_start", (event) => {
191
208
  const available = pi.getAllTools();
192
209
  if (!Array.isArray(available) || !available.some((tool) => tool.name === LOADER_NAME))
@@ -20,6 +20,7 @@ import { validateIntercomBridgeConfig } from "../../intercom/intercom-bridge.js"
20
20
  import { validateModelResponseAliases } from "../../shared/model-response-aliases.js";
21
21
  import { readWorkflowLaunchRecord } from "../../workflows/workflow-launch-record.js";
22
22
  import { recoveryDescriptorPath } from "../shared/run-launch-folder.js";
23
+ import { missingForkCopyNote } from "../../shared/artifacts.js";
23
24
  function getErrorMessage(error) {
24
25
  return error instanceof Error ? error.message : String(error);
25
26
  }
@@ -499,7 +500,7 @@ function validateResumeSessionFile(runId, sessionFile) {
499
500
  throw new Error(`Async run '${runId}' session file must be a .jsonl file: ${sessionFile}`);
500
501
  const resolved = path.resolve(sessionFile);
501
502
  if (!fs.existsSync(resolved))
502
- throw new Error(`Async run '${runId}' session file does not exist: ${sessionFile}`);
503
+ throw new Error(`Async run '${runId}' session file does not exist: ${sessionFile}${missingForkCopyNote(resolved)}`);
503
504
  return resolved;
504
505
  }
505
506
  function validateResumeCwd(runId, cwd) {
@@ -1,8 +1,6 @@
1
1
  import * as fs from "node:fs";
2
- export declare const ASYNC_RETENTION_DAYS = 30;
3
2
  export declare const ASYNC_RETENTION_BATCH_SIZE = 100;
4
3
  export declare const ASYNC_RETENTION_DELAY_MS = 60000;
5
- export declare const ASYNC_RETENTION_TOMBSTONE_GRACE_MS: number;
6
4
  export declare const RESUMABLE_RETENTION_DAYS = 90;
7
5
  export interface AsyncRetentionOptions {
8
6
  asyncDirRoot: string;
@@ -12,10 +12,10 @@ import { ACTIVE_RUN_INDEX_DIR } from "./active-run-index.js";
12
12
  import { encodeIndexSegment } from "./index-segment.js";
13
13
  import { reconcileAsyncRun } from "./stale-run-reconciler.js";
14
14
  import { recoveryDescriptorPath, runLaunchDir } from "../shared/run-launch-folder.js";
15
- export const ASYNC_RETENTION_DAYS = 30;
15
+ const ASYNC_RETENTION_DAYS = 30;
16
16
  export const ASYNC_RETENTION_BATCH_SIZE = 100;
17
17
  export const ASYNC_RETENTION_DELAY_MS = 60_000;
18
- export const ASYNC_RETENTION_TOMBSTONE_GRACE_MS = 24 * 60 * 60 * 1000;
18
+ const ASYNC_RETENTION_TOMBSTONE_GRACE_MS = 24 * 60 * 60 * 1000;
19
19
  // A run or result whose session file still exists can be resumed, so it is kept this long
20
20
  // instead of ASYNC_RETENTION_DAYS. Session files outlive run dirs, so without a ceiling it is kept forever.
21
21
  export const RESUMABLE_RETENTION_DAYS = 90;
@@ -296,9 +296,15 @@ async function computeProcessStartIdentity(pid) {
296
296
  if (process.platform === "win32") {
297
297
  // PowerShell takes ~0.5 s to start; a synchronous spawn would freeze the TUI.
298
298
  const started = await new Promise((resolve) => {
299
- execFile("powershell.exe", ["-NoProfile", "-Command", `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CreationDate`], { encoding: "utf-8", windowsHide: true, timeout: 5_000 }, (error, stdout) => {
300
- resolve(error ? "" : stdout.trim());
301
- });
299
+ // Node throws instead of calling back when the executable cannot be spawned at all (spawn UNKNOWN when policy blocks PowerShell).
300
+ try {
301
+ execFile("powershell.exe", ["-NoProfile", "-Command", `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CreationDate`], { encoding: "utf-8", windowsHide: true, timeout: 5_000 }, (error, stdout) => {
302
+ resolve(error ? "" : stdout.trim());
303
+ });
304
+ }
305
+ catch {
306
+ resolve("");
307
+ }
302
308
  });
303
309
  return started ? `win:${started}` : undefined;
304
310
  }
@@ -36,6 +36,8 @@ interface AsyncRunStepSummary {
36
36
  endMs: number;
37
37
  }>;
38
38
  recentOutput?: string[];
39
+ progressText?: string;
40
+ progressUpdatedAt?: number;
39
41
  turnCount?: number;
40
42
  toolCount?: number;
41
43
  steering?: SteeringStatus;