@xzzpig/pi-subagents 0.7.0 → 0.9.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 (234) hide show
  1. package/CHANGELOG.md +456 -4
  2. package/README.md +3 -3
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +13 -3
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +154 -42
  12. package/docs/configuration.md +85 -26
  13. package/docs/extension-api.md +81 -16
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +75 -11
  16. package/docs/observability.md +34 -21
  17. package/docs/tool-reference.md +142 -18
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +148 -4
  20. package/index.ts +10 -1
  21. package/install.mjs +1 -1
  22. package/package.json +7 -6
  23. package/prompts/council.md +19 -7
  24. package/prompts/parallel-review.md +5 -1
  25. package/prompts/review-loop.md +11 -7
  26. package/skills/council-mode/SKILL.md +44 -215
  27. package/skills/council-mode/references/pass-contracts.md +150 -0
  28. package/skills/pi-subagents/SKILL.md +90 -32
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
  30. package/skills/pi-subagents/references/execution-controls.md +104 -19
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
  33. package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
  34. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  35. package/src/agents/agent-management.ts +471 -114
  36. package/src/agents/agent-refinements.ts +4 -4
  37. package/src/agents/agent-serializer.ts +16 -4
  38. package/src/agents/agents.ts +1076 -351
  39. package/src/agents/builtin-names.ts +6 -0
  40. package/src/agents/runtime-agent-events.ts +70 -0
  41. package/src/agents/runtime-agent-registry.ts +31 -20
  42. package/src/api/agents.ts +10 -5
  43. package/src/api/background-work.ts +12 -3
  44. package/src/api/capability-ceiling.ts +0 -1
  45. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  46. package/src/api/delegation.ts +0 -7
  47. package/src/api/external-job-provider.ts +10 -1
  48. package/src/api/external-runs.ts +67 -4
  49. package/src/api/preflight.ts +97 -34
  50. package/src/api/project-panes.ts +2 -0
  51. package/src/api/shared-types.ts +6 -0
  52. package/src/extension/config.ts +90 -0
  53. package/src/extension/doctor.ts +15 -13
  54. package/src/extension/fanout-child.ts +17 -16
  55. package/src/extension/index.ts +139 -41
  56. package/src/extension/public-execution.ts +113 -22
  57. package/src/extension/rpc.ts +182 -13
  58. package/src/extension/schemas.ts +63 -21
  59. package/src/extension/tool-description.ts +48 -23
  60. package/src/extension/tool-result.ts +19 -0
  61. package/src/inspectors/herdr/actions.ts +2 -1
  62. package/src/inspectors/herdr/client.ts +3 -3
  63. package/src/inspectors/herdr/focus.ts +55 -0
  64. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  65. package/src/inspectors/herdr/project-panes.ts +228 -44
  66. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  67. package/src/integrations/herdr-status.ts +75 -5
  68. package/src/intercom/native-supervisor-channel.ts +138 -60
  69. package/src/intercom/result-intercom.ts +2 -0
  70. package/src/intercom/supervisor-ui.ts +243 -0
  71. package/src/profiles/profiles.ts +5 -6
  72. package/src/runs/background/active-async-capacity.ts +103 -18
  73. package/src/runs/background/async-execution.ts +492 -125
  74. package/src/runs/background/async-job-tracker.ts +127 -28
  75. package/src/runs/background/async-resume.ts +67 -29
  76. package/src/runs/background/async-retention.ts +21 -4
  77. package/src/runs/background/async-status-snapshot.ts +23 -261
  78. package/src/runs/background/async-status.ts +199 -14
  79. package/src/runs/background/auto-drain.ts +1 -1
  80. package/src/runs/background/chain-append.ts +8 -3
  81. package/src/runs/background/chain-root-attachment.ts +79 -8
  82. package/src/runs/background/control-channel.ts +101 -214
  83. package/src/runs/background/fleet-view.ts +38 -22
  84. package/src/runs/background/inspect-rpc.ts +8 -8
  85. package/src/runs/background/notify.ts +295 -8
  86. package/src/runs/background/process-terminal.ts +16 -0
  87. package/src/runs/background/result-delivery-ownership.ts +45 -0
  88. package/src/runs/background/result-files.ts +28 -14
  89. package/src/runs/background/result-watcher.ts +43 -19
  90. package/src/runs/background/resume-guidance.ts +2 -2
  91. package/src/runs/background/retained-children.ts +1 -1
  92. package/src/runs/background/run-child-session.ts +613 -0
  93. package/src/runs/background/run-status.ts +99 -18
  94. package/src/runs/background/runner-aliases.ts +125 -0
  95. package/src/runs/background/runner-child-sessions.ts +31 -0
  96. package/src/runs/background/scheduled-runs.ts +174 -18
  97. package/src/runs/background/stale-run-reconciler.ts +13 -4
  98. package/src/runs/background/steering.ts +8 -15
  99. package/src/runs/background/subagent-runner.ts +959 -1159
  100. package/src/runs/background/subagent-wait.ts +86 -31
  101. package/src/runs/background/terminal-run-index.ts +1 -1
  102. package/src/runs/background/wait-completions.ts +45 -2
  103. package/src/runs/background/wait-config.ts +23 -9
  104. package/src/runs/background/wait-tool.ts +27 -19
  105. package/src/runs/foreground/async-steering-action.ts +3 -19
  106. package/src/runs/foreground/async-stop-action.ts +23 -2
  107. package/src/runs/foreground/execution.ts +585 -481
  108. package/src/runs/foreground/foreground-control.ts +13 -0
  109. package/src/runs/foreground/foreground-history.ts +26 -3
  110. package/src/runs/foreground/subagent-executor.ts +1549 -410
  111. package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
  112. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  113. package/src/runs/shared/abort-recovery.ts +119 -0
  114. package/src/runs/shared/acceptance.ts +147 -39
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +565 -0
  117. package/src/runs/shared/background-process-options.ts +9 -0
  118. package/src/runs/shared/capability-ceiling.ts +2 -2
  119. package/src/runs/shared/child-hooks.ts +25 -0
  120. package/src/runs/shared/child-identity.ts +62 -0
  121. package/src/runs/shared/child-launch-plan.ts +151 -0
  122. package/src/runs/shared/child-launch.ts +314 -0
  123. package/src/runs/shared/child-lifecycle.ts +25 -0
  124. package/src/runs/shared/child-runtime-config.ts +126 -0
  125. package/src/runs/shared/child-session.ts +342 -0
  126. package/src/runs/shared/child-tool-plan.ts +540 -0
  127. package/src/runs/shared/claude-code-adapter.ts +133 -0
  128. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  129. package/src/runs/shared/completion-evidence.ts +89 -0
  130. package/src/runs/shared/completion-guard.ts +57 -6
  131. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  132. package/src/runs/shared/dynamic-fanout.ts +4 -4
  133. package/src/runs/shared/extension-bindings.ts +78 -0
  134. package/src/runs/shared/external-cli-contract.ts +167 -0
  135. package/src/runs/shared/external-cli-preflight.ts +138 -0
  136. package/src/runs/shared/external-cli-runner.ts +349 -54
  137. package/src/runs/shared/external-job-bridge.ts +53 -37
  138. package/src/runs/shared/external-job-runner.ts +126 -23
  139. package/src/runs/shared/fast-mode-extension.ts +10 -0
  140. package/src/runs/shared/host-step-status.ts +231 -0
  141. package/src/runs/shared/lane-metadata.ts +126 -0
  142. package/src/runs/shared/launch-cwd.ts +16 -0
  143. package/src/runs/shared/long-running-guard.ts +2 -1
  144. package/src/runs/shared/mcp-config-sources.ts +422 -0
  145. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  146. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  147. package/src/runs/shared/model-exclusions.ts +141 -10
  148. package/src/runs/shared/model-fallback.ts +187 -33
  149. package/src/runs/shared/model-scope.ts +106 -39
  150. package/src/runs/shared/mutation-evidence.ts +199 -0
  151. package/src/runs/shared/nested-events.ts +38 -48
  152. package/src/runs/shared/nested-path.ts +0 -14
  153. package/src/runs/shared/nested-render.ts +9 -5
  154. package/src/runs/shared/orca-progress-tabs.ts +83 -16
  155. package/src/runs/shared/parallel-handoff.ts +423 -7
  156. package/src/runs/shared/parallel-utils.ts +28 -5
  157. package/src/runs/shared/permissions.ts +1 -14
  158. package/src/runs/shared/pi-spawn.ts +69 -35
  159. package/src/runs/shared/process-signal.ts +16 -0
  160. package/src/runs/shared/run-fanout-budget.ts +0 -13
  161. package/src/runs/shared/run-history.ts +21 -1
  162. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  163. package/src/runs/shared/single-output.ts +89 -22
  164. package/src/runs/shared/structured-output.ts +61 -7
  165. package/src/runs/shared/subagent-control.ts +6 -2
  166. package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
  167. package/src/runs/shared/task-intent.ts +21 -7
  168. package/src/runs/shared/tool-availability.ts +18 -64
  169. package/src/runs/shared/tool-budget.ts +0 -14
  170. package/src/runs/shared/tool-timeout.ts +1 -1
  171. package/src/runs/shared/workflow-graph.ts +16 -0
  172. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  173. package/src/runs/shared/worktree.ts +571 -62
  174. package/src/shared/atomic-json.ts +3 -1
  175. package/src/shared/child-session-name.ts +46 -0
  176. package/src/shared/extension-context.ts +24 -0
  177. package/src/shared/fork-context.ts +21 -12
  178. package/src/shared/fork-session-cwd.ts +27 -0
  179. package/src/shared/formatters.ts +18 -3
  180. package/src/shared/jsonl-writer.ts +11 -0
  181. package/src/shared/launch-contract.ts +20 -6
  182. package/src/shared/pruned-fork.ts +450 -0
  183. package/src/shared/session-file-trust.ts +19 -0
  184. package/src/shared/session-tokens.ts +14 -3
  185. package/src/shared/settings.ts +21 -102
  186. package/src/shared/shortcuts.ts +17 -0
  187. package/src/shared/thinking-ceiling.ts +46 -0
  188. package/src/shared/types.ts +644 -75
  189. package/src/shared/utils.ts +60 -93
  190. package/src/shared/workflow-child-permit.ts +207 -0
  191. package/src/slash/delegation-adapters.ts +1 -9
  192. package/src/slash/delegation-request.ts +0 -4
  193. package/src/slash/prompt-template-bridge.ts +37 -1
  194. package/src/slash/slash-bridge.ts +1 -2
  195. package/src/slash/slash-commands.ts +383 -116
  196. package/src/slash/slash-live-state.ts +22 -11
  197. package/src/slash/subagents-admin.ts +29 -12
  198. package/src/tui/fleet-native-transcript.ts +4 -0
  199. package/src/tui/fleet-status.ts +278 -90
  200. package/src/tui/fleet-transcript.ts +11 -5
  201. package/src/tui/fleet.ts +54 -28
  202. package/src/tui/render-helpers.ts +31 -0
  203. package/src/tui/render.ts +1433 -166
  204. package/src/watchdog/change-signature.ts +40 -1
  205. package/src/watchdog/child-status.ts +54 -34
  206. package/src/watchdog/diff-tool.ts +77 -0
  207. package/src/watchdog/emission-guard.ts +5 -3
  208. package/src/watchdog/guidance.ts +20 -0
  209. package/src/watchdog/permission-arbiter.ts +59 -52
  210. package/src/watchdog/register-child.ts +28 -25
  211. package/src/watchdog/register-main.ts +10 -9
  212. package/src/watchdog/render.ts +4 -5
  213. package/src/watchdog/review.ts +15 -4
  214. package/src/watchdog/rules.ts +70 -0
  215. package/src/watchdog/runtime.ts +75 -92
  216. package/src/watchdog/scope.ts +0 -11
  217. package/src/watchdog/settings.ts +48 -104
  218. package/src/watchdog/turn-delta.ts +1 -1
  219. package/src/watchdog/types.ts +18 -32
  220. package/src/watchdog/warning-format.ts +0 -1
  221. package/src/workflows/chat-progress.ts +7 -3
  222. package/src/workflows/host-command.ts +235 -0
  223. package/src/workflows/scripted-workflow.ts +1142 -69
  224. package/src/workflows/workflow-checklist.ts +439 -0
  225. package/src/workflows/workflow-child-summary.ts +121 -0
  226. package/src/workflows/workflow-preflight.ts +297 -0
  227. package/src/workflows/workflow-receipt.ts +232 -6
  228. package/src/workflows/workflow-resources.ts +150 -0
  229. package/src/workflows/workflow-settlement.ts +246 -0
  230. package/src/runs/shared/child-protocol.ts +0 -401
  231. package/src/runs/shared/pi-args.ts +0 -858
  232. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  233. package/src/runs/shared/turn-budget.ts +0 -98
  234. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -9,7 +9,7 @@
9
9
  * Toggle: async parameter (default: true; set asyncByDefault:false in config.json to opt out)
10
10
  *
11
11
  * Config file: ~/.pi/agent/extensions/subagent/config.json
12
- * { "asyncByDefault": true, "defaultSubagentContext": "fork", "forceTopLevelAsync": true, "maxSubagentDepth": 1, "intercomBridge": { "mode": "always", "instructionFile": "./intercom-bridge.md" }, "worktreeSetupHook": "./scripts/setup-worktree.mjs" }
12
+ * { "asyncByDefault": true, "defaultSubagentContext": "fork", "forkContext": { "mode": "pruned", "model": "provider/model" }, "forceTopLevelAsync": true, "maxSubagentDepth": 1, "intercomBridge": { "mode": "always", "instructionFile": "./intercom-bridge.md" }, "worktreeSetupHook": "./scripts/setup-worktree.mjs" }
13
13
  */
14
14
 
15
15
  import { randomUUID } from "node:crypto";
@@ -19,12 +19,15 @@ import * as path from "node:path";
19
19
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
20
20
  import { keyText, type ExtensionAPI, type ExtensionContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
21
21
  import { Box, Container, Spacer, Text, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
22
- import { discoverAgents, discoverAgentsAll, type AgentConfig, type AgentScope } from "../agents/agents.ts";
22
+ import { discoverAgentSnapshot, discoverAgents, discoverAgentsAll, type AgentConfig, type AgentScope } from "../agents/agents.ts";
23
23
  import { mergeAgentsForScope } from "../agents/agent-selection.ts";
24
24
  import { clearRuntimeAgentsForPi, listRuntimeAgentConfigs, mergeRuntimeAgents } from "../agents/runtime-agent-registry.ts";
25
+ import { registerRuntimeAgentEventListener } from "../agents/runtime-agent-events.ts";
25
26
  import { ensureAccessibleDir } from "../shared/accessible-dir.ts";
26
27
  import { cleanupAllArtifactDirs, cleanupOldArtifacts, getArtifactsDir } from "../shared/artifacts.ts";
27
28
  import { resolveCurrentSessionId } from "../shared/session-identity.ts";
29
+ import { getAgentDir } from "../shared/utils.ts";
30
+ import { isStaleExtensionContextError, withCachedUiContext } from "../shared/extension-context.ts";
28
31
  import { currentCompletionOwnerId } from "../shared/completion-owner.ts";
29
32
  import { cleanupOldChainDirs } from "../shared/settings.ts";
30
33
  import { clearLegacyResultAnimationTimer, renderSubagentResult, renderSubagentSummary } from "../tui/render.ts";
@@ -33,32 +36,43 @@ import { SubagentFleetStatus, resolveFleetViewPlacement } from "../tui/fleet-sta
33
36
  import { createSubagentParamsSchema } from "./schemas.ts";
34
37
  import { createSubagentExecutor, type SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
35
38
  import { createAsyncJobTracker } from "../runs/background/async-job-tracker.ts";
36
- import { getActiveAsyncCapacitySnapshot, resolveMaxActiveAsyncRunsPerSession } from "../runs/background/active-async-capacity.ts";
39
+ import { getActiveAsyncCapacitySnapshot, resolveAbandonedSlotReleaseAfterMs, resolveMaxActiveAsyncRunsPerSession } from "../runs/background/active-async-capacity.ts";
37
40
  import { cleanupResultIndexes, missionObserverResultCandidateFiles } from "../runs/background/result-files.ts";
38
41
  import { ASYNC_RETENTION_DELAY_MS, cleanupAsyncRetention } from "../runs/background/async-retention.ts";
39
42
  import { createResultWatcher } from "../runs/background/result-watcher.ts";
43
+ import { createResultDeliveryOwnership } from "../runs/background/result-delivery-ownership.ts";
40
44
  import { createScheduledRunManager } from "../runs/background/scheduled-runs.ts";
41
45
  import { registerSlashCommands } from "../slash/slash-commands.ts";
42
46
  import { registerPromptTemplateDelegationBridge } from "../slash/prompt-template-bridge.ts";
43
47
  import { registerMainWatchdog } from "../watchdog/register-main.ts";
44
48
  import { registerSlashSubagentBridge } from "../slash/slash-bridge.ts";
45
49
  import { createNativeSupervisorChannel } from "../intercom/native-supervisor-channel.ts";
50
+ import {
51
+ renderSupervisorReply,
52
+ renderSupervisorRequest,
53
+ SUPERVISOR_REPLY_ENTRY_TYPE,
54
+ SUPERVISOR_REQUEST_MESSAGE_TYPE,
55
+ type SupervisorRequestMessageDetails,
56
+ } from "../intercom/supervisor-ui.ts";
46
57
  import { registerHerdrStatusBridge, type HerdrStatusRun } from "../integrations/herdr-status.ts";
58
+ import { listHerdrProjectPaneRoots, restoreHerdrProjectPaneSnapshots } from "../inspectors/herdr/project-panes.ts";
47
59
  import { registerSubagentRpcBridge } from "./rpc.ts";
48
60
  import { clearSlashSnapshots, getSlashRenderableSnapshot, resolveSlashMessageDetails, restoreSlashFinalSnapshots, type SlashMessageDetails } from "../slash/slash-live-state.ts";
49
- import { inspectSubagentStatus } from "../runs/background/run-status.ts";
50
61
  import { resolveWaitToolConfig } from "../runs/background/subagent-wait.ts";
51
62
  import { registerWaitTool } from "../runs/background/wait-tool.ts";
52
63
  import { createWaitSubscriptionManager } from "../runs/background/wait-subscriptions.ts";
53
64
  import { drainOutstandingWork } from "../runs/background/auto-drain.ts";
54
65
  import registerSubagentNotify, { parseSubagentNotifyContent, type SubagentNotifyDetails } from "../runs/background/notify.ts";
55
66
  import { formatSteeringNotice, handleSubagentSteeringNotice, SUBAGENT_STEERING_MESSAGE_TYPE, type SubagentSteeringMessageDetails } from "./steering-notices.ts";
56
- import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "../runs/shared/pi-args.ts";
67
+ import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "../runs/shared/child-runtime-config.ts";
68
+ import { disposeChildSessions } from "../runs/shared/child-session.ts";
57
69
  import { resolveCurrentSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.ts";
58
70
  import { formatDuration, shortenPath } from "../shared/formatters.ts";
59
- import { loadConfig, resolveAsyncByDefault, resolveScheduledStoreRoot } from "./config.ts";
71
+ import { applyModelExclusionsConfig, loadConfig, resolveAsyncByDefault, resolveScheduledStoreRoot } from "./config.ts";
60
72
  import { applyInjectionBlock, renderInjectionBlock, resolveInjectableAgents, SUBAGENT_INJECTION_MARKER } from "./context-injection.ts";
61
73
  import { buildSubagentToolDescription, buildSubagentToolPromptMetadata } from "./tool-description.ts";
74
+ import { formatWorkflowPreflightSummary, normalizeWorkflowPreflight } from "../workflows/workflow-preflight.ts";
75
+ import { finalizeToolResult } from "./tool-result.ts";
62
76
  import { collectGoalContinuationNotices } from "../missions/goal-driver.ts";
63
77
  import { restoreForegroundRunHistory } from "../runs/foreground/foreground-history.ts";
64
78
  import { resolveMissionStoreLocation } from "../missions/store.ts";
@@ -248,15 +262,25 @@ function workflowLaneKeys(script: string): string[] {
248
262
  return keys;
249
263
  }
250
264
 
251
- function formatWorkflowManifest(script: string, async: unknown, clarify: unknown): string {
265
+ function formatWorkflowPreflightCall(input: unknown): string {
266
+ if (input === undefined) return "";
267
+ try {
268
+ return formatWorkflowPreflightSummary(normalizeWorkflowPreflight(input));
269
+ } catch (error) {
270
+ return `preflight · rejected: ${error instanceof Error ? error.message : String(error)}`;
271
+ }
272
+ }
273
+
274
+ function formatWorkflowManifest(script: string, async: unknown, clarify: unknown, preflightInput?: unknown): string {
252
275
  if (clarify === true) return "workflow script · rejected: clarify UI unsupported";
253
276
  const keys = workflowLaneKeys(script);
254
277
  // The workflow executor starts background work unless callers pass async:false.
255
278
  const mode = async === false ? "foreground" : "background";
256
- if (keys.length === 0) return `workflow script · ${mode}`;
279
+ const preflight = formatWorkflowPreflightCall(preflightInput);
280
+ if (keys.length === 0) return `workflow script · ${mode}${preflight ? ` · ${preflight}` : ""}`;
257
281
  const visibleKeys = keys.slice(0, 4).join(", ");
258
282
  const remainder = keys.length > 4 ? `, +${keys.length - 4}` : "";
259
- return `workflow · ${mode} · ${keys.length} lane${keys.length === 1 ? "" : "s"}: ${visibleKeys}${remainder}`;
283
+ return `workflow · ${mode} · ${keys.length} lane${keys.length === 1 ? "" : "s"}: ${visibleKeys}${remainder}${preflight ? ` · ${preflight}` : ""}`;
260
284
  }
261
285
 
262
286
  /**
@@ -289,10 +313,6 @@ function isSlashResultError(result: { details?: Details }): boolean {
289
313
  return result.details?.results.some((entry) => entry.exitCode !== 0 && entry.progress?.status !== "running") || false;
290
314
  }
291
315
 
292
- function isStaleExtensionContextError(error: unknown): boolean {
293
- return error instanceof Error && error.message.includes("Extension context no longer active");
294
- }
295
-
296
316
  function rebuildSlashResultContainer(
297
317
  container: Container,
298
318
  result: AgentToolResult<Details>,
@@ -382,9 +402,13 @@ export function projectActiveHerdrRuns(state: SubagentState): HerdrStatusRun[] {
382
402
  .filter((job) => active(job.status))
383
403
  .map((job) => {
384
404
  const children = job.mode === "workflow" ? foregroundChildrenByWorkflow.get(job.asyncId) : undefined;
405
+ const currentStep = job.steps?.find((step) => step.status === "running")
406
+ ?? (job.currentStep !== undefined ? job.steps?.[job.currentStep] : undefined)
407
+ ?? job.steps?.find((step) => step.status === "pending");
385
408
  return {
386
409
  id: job.asyncId,
387
410
  agents: children?.length ? children.map((child) => child.agent) : job.agents,
411
+ ...(currentStep?.label ? { taskLabel: currentStep.label } : {}),
388
412
  needsAttention: job.activityState === "needs_attention" || children?.some((child) => child.needsAttention),
389
413
  };
390
414
  });
@@ -401,6 +425,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
401
425
  cleanupOldChainDirs();
402
426
 
403
427
  const config = loadConfig();
428
+ // Apply the process-wide exclusion TTL before any child launch can record a model failure.
429
+ applyModelExclusionsConfig(config);
404
430
  const waitToolConfig = resolveWaitToolConfig(config.waitTool);
405
431
  const asyncByDefault = resolveAsyncByDefault(config);
406
432
  const fleetViewEnabled = config.fleetView !== false;
@@ -422,6 +448,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
422
448
  const state: SubagentState = {
423
449
  baseCwd: "",
424
450
  currentSessionId: null,
451
+ statusProjectionSessionId: null,
425
452
  completionOwnerId: currentCompletionOwnerId(),
426
453
  artifactDirPreference: config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir,
427
454
  ...(config.authorityPolicy ? { authorityPolicy: config.authorityPolicy } : {}),
@@ -437,6 +464,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
437
464
  grantHistory: [],
438
465
  },
439
466
  activeAsyncCapacity: { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession) ?? 0 },
467
+ herdrProjectPanes: new Map(),
440
468
  asyncJobs: new Map(),
441
469
  fleetJobs: new Map(),
442
470
  foregroundRuns: new Map(),
@@ -454,16 +482,31 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
454
482
  clear: () => {},
455
483
  },
456
484
  };
485
+ const withLastUiContext = <T>(run: (ctx: ExtensionContext) => T): T | undefined => {
486
+ const cached = state.lastUiContext;
487
+ return withCachedUiContext(cached, () => {
488
+ if (state.lastUiContext === cached) state.lastUiContext = null;
489
+ }, run);
490
+ };
457
491
 
458
492
  const supervisorChannel = createNativeSupervisorChannel(pi, state);
459
493
  const waitSubscriptionManager = createWaitSubscriptionManager(pi, state);
460
494
  const mainWatchdog = registerMainWatchdog(pi);
461
- const completionNotifier = registerSubagentNotify(pi, state, { batchConfig: config.completionBatch });
495
+ const resultDeliveryOwnership = createResultDeliveryOwnership(state);
496
+ const completionNotifier = registerSubagentNotify(pi, state, { batchConfig: config.completionBatch, ownership: resultDeliveryOwnership });
462
497
  const fleetStatus = fleetViewEnabled
463
498
  ? new SubagentFleetStatus(state, async (itemKey) => {
464
- const ctx = state.lastUiContext;
465
- if (!ctx?.hasUI) return;
466
- await openSubagentFleet(ctx, state, { initialKey: itemKey, asyncDirRoot: DIRS.async, resultsDir: DIRS.results, fleetKeybindings: config.fleetKeybindings });
499
+ const ctx = withLastUiContext((current) => current);
500
+ if (!ctx) return;
501
+ try {
502
+ await openSubagentFleet(ctx, state, { initialKey: itemKey, asyncDirRoot: DIRS.async, resultsDir: DIRS.results, fleetKeybindings: config.fleetKeybindings });
503
+ } catch (error) {
504
+ if (isStaleExtensionContextError(error)) {
505
+ if (state.lastUiContext === ctx) state.lastUiContext = null;
506
+ return;
507
+ }
508
+ throw error;
509
+ }
467
510
  }, { placement: fleetViewPlacement })
468
511
  : undefined;
469
512
  let executorScheduled: ((id: string, params: SubagentParamsLike, signal: AbortSignal, ctx: ExtensionContext) => Promise<AgentToolResult<Details>>) | undefined;
@@ -492,21 +535,28 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
492
535
  if (scheduledRunManager.observedCompletionRunIds().size > 0) return true;
493
536
  return missionObserverResultCandidateFiles(DIRS.results).length > 0;
494
537
  };
495
- const discoverAgentsForRuntime = (cwd: string, scope: AgentScope) => {
496
- const discovered = discoverAgents(cwd, scope);
497
- if (listRuntimeAgentConfigs(pi).length === 0) return discovered;
498
- const all = discoverAgentsAll(cwd);
538
+ const discoverAgentsForRuntime = (cwd: string, scope: AgentScope, preferredModelProvider?: string) => {
539
+ if (listRuntimeAgentConfigs(pi).length === 0) return discoverAgents(cwd, scope, preferredModelProvider);
540
+ const snapshot = discoverAgentSnapshot(cwd, scope, preferredModelProvider, { includeChains: false });
541
+ const discovered = snapshot.effective;
542
+ const all = snapshot.all;
499
543
  const configuredAgents: AgentConfig[] = [
500
544
  ...all.builtin,
501
545
  ...all.package,
502
546
  ...all.user,
503
547
  ...all.project,
504
548
  ];
505
- return mergeRuntimeAgents(pi, discovered, configuredAgents);
549
+ const merged = mergeRuntimeAgents(pi, discovered, configuredAgents);
550
+ if (discovered.maxThinking === undefined) return merged;
551
+ return {
552
+ ...merged,
553
+ agents: merged.agents.map((agent) => agent.maxThinking === discovered.maxThinking ? agent : { ...agent, maxThinking: discovered.maxThinking }),
554
+ };
506
555
  };
507
556
  const { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs, dispose: disposeAsyncJobTracker } = createAsyncJobTracker(pi, state, DIRS.async, {
508
557
  widgetEnabled: asyncWidgetEnabled,
509
558
  onJobTerminal: () => refreshResultDelivery(),
559
+ supervisorRequestState: supervisorChannel.getSupervisorRequestState,
510
560
  });
511
561
  const resultWatcher = createResultWatcher(
512
562
  pi,
@@ -515,14 +565,15 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
515
565
  10 * 60 * 1000,
516
566
  {
517
567
  notifier: completionNotifier,
568
+ ownership: resultDeliveryOwnership,
518
569
  observeCompletion: (result) => scheduledRunManager.handleAsyncCompletion(result),
519
570
  observedCompletionRunIds: () => scheduledRunManager.observedCompletionRunIds(),
520
571
  hasDeliveryDemand: hasResultDeliveryDemand,
521
572
  deliverIntercomResults: config.intercomBridge?.resultDelivery === true,
522
- resultScanLogging: config.resultScanLogging ?? "all",
573
+ resultScanLogging: config.resultScanLogging,
523
574
  },
524
575
  );
525
- const { startResultWatcher, primeExistingResults, stopResultWatcher } = resultWatcher;
576
+ const { startResultWatcher, transitionResultDelivery, primeExistingResults, stopResultWatcher } = resultWatcher;
526
577
  refreshResultDelivery = resultWatcher.refreshResultDelivery;
527
578
  const asyncRetentionAbort = new AbortController();
528
579
  const asyncRetentionTimer = setTimeout(async () => {
@@ -549,6 +600,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
549
600
  config,
550
601
  asyncByDefault,
551
602
  waitToolEnabled: waitToolConfig.enabled,
603
+ waitToolDefaultTimeoutMs: waitToolConfig.defaultTimeoutMs,
552
604
  handleScheduledRunAction: (params, ctx) => scheduledRunManager.handleToolCall(params, ctx),
553
605
  watchdog: mainWatchdog,
554
606
  tempArtifactsDir,
@@ -560,6 +612,14 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
560
612
  });
561
613
  executorScheduled = executor.executeScheduled;
562
614
 
615
+ pi.registerMessageRenderer<SupervisorRequestMessageDetails>(SUPERVISOR_REQUEST_MESSAGE_TYPE, renderSupervisorRequest);
616
+ const registerEntryRenderer = (pi as unknown as {
617
+ registerEntryRenderer?: (customType: string, renderer: (entry: { data?: unknown }, options: { expanded: boolean }, theme: ExtensionContext["ui"]["theme"]) => Component | undefined) => void;
618
+ }).registerEntryRenderer;
619
+ if (typeof registerEntryRenderer === "function") {
620
+ registerEntryRenderer.call(pi, SUPERVISOR_REPLY_ENTRY_TYPE, renderSupervisorReply);
621
+ }
622
+
563
623
  pi.registerMessageRenderer<SlashMessageDetails>(SLASH_RESULT_TYPE, (message, options, theme) => {
564
624
  const details = resolveSlashMessageDetails(message.details);
565
625
  if (!details) return undefined;
@@ -601,6 +661,15 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
601
661
  const expandKey = keyText("app.tools.expand");
602
662
  text += `\n ${theme.fg("dim", `${expandKey} full notification`)}`;
603
663
  }
664
+ if (details.workflowRunId) {
665
+ text += `\n ${theme.fg("muted", `workflow: ${details.workflowRunId}`)}`;
666
+ }
667
+ if (details.childRuns?.length) {
668
+ text += `\n ${theme.fg("muted", `children: ${details.childRuns.map((child) => `${child.workflowKey ?? child.agent ?? "child"}=${child.runId}`).join(", ")}`)}`;
669
+ }
670
+ if (details.reconciledFromDetachedChild) {
671
+ text += `\n ${theme.fg("muted", `reconciled child: ${details.reconciledFromDetachedChild}`)}`;
672
+ }
604
673
  if (details.sessionLabel && details.sessionValue) {
605
674
  text += `\n ${theme.fg("muted", `${details.sessionLabel}: ${shortenPath(details.sessionValue)}`)}`;
606
675
  }
@@ -627,7 +696,6 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
627
696
 
628
697
  const slashBridge = registerSlashSubagentBridge({
629
698
  events: pi.events,
630
- asyncByDefault,
631
699
  getContext: () => state.lastUiContext,
632
700
  execute: (id, params, signal, onUpdate, ctx) =>
633
701
  executeSubagentCollapsed(id, params, signal, onUpdate, ctx),
@@ -660,8 +728,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
660
728
  ...buildSubagentToolPromptMetadata(config),
661
729
  parameters,
662
730
 
663
- execute(id, params, signal, onUpdate, ctx) {
664
- return executeSubagentCollapsed(id, params as SubagentParamsLike, signal ?? new AbortController().signal, onUpdate, ctx);
731
+ async execute(id, params, signal, onUpdate, ctx) {
732
+ return finalizeToolResult(await executeSubagentCollapsed(id, params as SubagentParamsLike, signal ?? new AbortController().signal, onUpdate, ctx));
665
733
  },
666
734
 
667
735
  renderCall(args, theme) {
@@ -676,7 +744,13 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
676
744
  }
677
745
  if (args.workflowScript)
678
746
  return new Text(
679
- `${title}${gap}${formatWorkflowManifest(args.workflowScript, args.async, false)}`,
747
+ `${title}${gap}${formatWorkflowManifest(args.workflowScript, args.async, false, args.preflight)}`,
748
+ 0,
749
+ 0,
750
+ );
751
+ if (args.workflowScriptPath)
752
+ return new Text(
753
+ `${title}${gap}${theme.fg("accent", args.workflowScriptPath)}${args.async === true ? `${gap}${theme.fg("warning", "[async]")}` : ""}${args.preflight !== undefined ? `${gap}${theme.fg("dim", formatWorkflowPreflightCall(args.preflight))}` : ""}`,
680
754
  0,
681
755
  0,
682
756
  );
@@ -700,7 +774,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
700
774
 
701
775
  pi.registerTool(tool);
702
776
 
703
- registerWaitTool(pi, state, waitToolConfig.enabled, waitSubscriptionManager);
777
+ registerWaitTool(pi, state, waitToolConfig.enabled, waitSubscriptionManager, waitToolConfig.defaultTimeoutMs);
704
778
 
705
779
  pi.on("agent_end", async (_event, ctx) => {
706
780
  if (!ctx.hasUI) await drainOutstandingWork({ state, events: pi.events });
@@ -723,7 +797,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
723
797
  }
724
798
  });
725
799
 
726
- registerSlashCommands(pi, state, {
800
+ const disposeSlashCommands = registerSlashCommands(pi, state, {
727
801
  fleetKeybindings: config.fleetKeybindings,
728
802
  foregroundDetachShortcut: config.foregroundDetachShortcut,
729
803
  });
@@ -733,6 +807,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
733
807
  const herdrStatusBridge = registerHerdrStatusBridge({
734
808
  events: pi.events,
735
809
  getRuns: activeHerdrRuns,
810
+ getProjectPaneCount: () => [...(state.herdrProjectPanes?.values() ?? [])].filter((pane) => pane.state === "open").length,
736
811
  async runHerdr(args) {
737
812
  await pi.exec(process.env.HERDR_BIN || "herdr", [...args], { timeout: 5_000 });
738
813
  },
@@ -762,6 +837,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
762
837
  fleetStatus?.refresh();
763
838
  };
764
839
  const eventUnsubscribes = [
840
+ registerRuntimeAgentEventListener(pi),
765
841
  pi.events.on(SUBAGENT_ASYNC_STARTED_EVENT, asyncStartedHandler),
766
842
  pi.events.on(SUBAGENT_ASYNC_COMPLETE_EVENT, asyncCompleteHandler),
767
843
  pi.events.on(SUBAGENT_PROCESS_TERMINAL_EVENT, () => {
@@ -778,7 +854,9 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
778
854
  if (event.toolName !== "subagent") return;
779
855
  if (!ctx.hasUI) return;
780
856
  state.lastUiContext = ctx;
857
+ const activeJobCount = state.asyncJobs.size;
781
858
  restoreActiveJobs(ctx);
859
+ if (state.asyncJobs.size > activeJobCount) herdrStatusBridge.syncRuns();
782
860
  fleetStatus?.setContext(ctx);
783
861
  fleetStatus?.refresh();
784
862
  if (state.asyncJobs.size > 0) {
@@ -801,14 +879,13 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
801
879
  const suspendWidgetsForCompaction = () => {
802
880
  if (state.widgetsSuspended) return;
803
881
  state.widgetsSuspended = true;
804
- if (state.lastUiContext?.hasUI) state.lastUiContext.ui.setWidget(WIDGET_KEY, undefined);
882
+ withLastUiContext((ctx) => ctx.ui.setWidget(WIDGET_KEY, undefined));
805
883
  fleetStatus?.refresh();
806
884
  };
807
885
  const resumeWidgetsAfterCompaction = () => {
808
886
  if (!state.widgetsSuspended) return;
809
887
  state.widgetsSuspended = false;
810
- const ctx = state.lastUiContext;
811
- if (ctx?.hasUI) refreshWidget(ctx);
888
+ withLastUiContext((ctx) => refreshWidget(ctx));
812
889
  fleetStatus?.refresh();
813
890
  };
814
891
 
@@ -820,16 +897,20 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
820
897
  state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(
821
898
  state.currentSessionId,
822
899
  resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession),
823
- { liveWorkflowRunIds: new Set(state.workflowControllers?.keys() ?? []) },
900
+ { liveWorkflowRunIds: new Set(state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(config.capacity?.abandonedSlotReleaseAfterMs) },
824
901
  );
825
902
  };
826
903
 
827
- const resetSessionState = (ctx: ExtensionContext, recovering: boolean) => {
904
+ const resetSessionState = (ctx: ExtensionContext, recovering: boolean, previousSessionFile?: string) => {
828
905
  state.widgetsSuspended = false;
829
906
  state.baseCwd = ctx.cwd;
830
907
  goalTurnId = 0;
908
+ const previousRuntimeSessionId = state.currentSessionId;
909
+ resultDeliveryOwnership.claimPredecessor(previousSessionFile, previousRuntimeSessionId);
831
910
  state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
911
+ transitionResultDelivery();
832
912
  state.parentSessionFile = ctx.sessionManager.getSessionFile();
913
+ state.trustedSessionFileRoot = state.parentSessionFile ? path.join(getAgentDir(), "sessions") : undefined;
833
914
  state.trustedSessionRoots = [...new Set([
834
915
  ...(config.defaultSessionDir ? [path.resolve(expandTilde(config.defaultSessionDir))] : []),
835
916
  ...(state.parentSessionFile ? [getSubagentSessionRoot(state.parentSessionFile)] : []),
@@ -841,11 +922,13 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
841
922
  granted: 0,
842
923
  grantHistory: [],
843
924
  };
925
+ const projectPaneOwnerRoot = path.resolve(ctx.cwd);
926
+ restoreHerdrProjectPaneSnapshots(state, [...new Set([...(state.herdrProjectPanes?.keys() ?? []), ...listHerdrProjectPaneRoots(projectPaneOwnerRoot), projectPaneOwnerRoot])]);
844
927
  // Set PI_SUBAGENT_PARENT_SESSION for permission-system forwarding.
845
- // Only set in the root session (the interactive UI session), not in
846
- // child subagent processes — children inherit the parent's value
847
- // through the process environment at spawn time and must not overwrite
848
- // it with their own session identity.
928
+ // Only set in the root session (the interactive UI session), not in a
929
+ // child host: the runner process inherits the parent's value through
930
+ // its environment at spawn time and must not overwrite it with a child
931
+ // session's identity.
849
932
  if (!process.env[SUBAGENT_CHILD_ENV]) {
850
933
  const sessionId = ctx.sessionManager.getSessionId();
851
934
  if (sessionId) {
@@ -926,11 +1009,19 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
926
1009
  if (runtimeCleaned) return;
927
1010
  runtimeCleaned = true;
928
1011
  const shuttingDownParentSession = parentSessionEnvValue;
1012
+ // Workflow continuations retain their launch context; abort them before
1013
+ // teardown so a reload cannot launch through a stale context.
1014
+ for (const controller of state.workflowControllers?.values() ?? []) {
1015
+ if (!controller.signal.aborted) controller.abort(new Error("Workflow stopped because the extension session was replaced or reloaded."));
1016
+ }
1017
+ state.workflowControllers?.clear();
1018
+ state.workflowChildStops?.clear();
929
1019
  clearRuntimeAgentsForPi(pi);
930
1020
  clearTimeout(resultIndexCleanupTimer);
931
1021
  clearTimeout(asyncRetentionTimer);
932
1022
  asyncRetentionAbort.abort();
933
1023
  stopResultWatcher();
1024
+ resultDeliveryOwnership.clear();
934
1025
  completionNotifier.dispose();
935
1026
  mainWatchdog.dispose();
936
1027
  scheduledRunManager.stop();
@@ -948,12 +1039,14 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
948
1039
  // Best effort cleanup during shutdown or reload.
949
1040
  }
950
1041
  }
1042
+ disposeSlashCommands.dispose();
951
1043
  slashBridge.cancelAll();
952
1044
  slashBridge.dispose();
953
1045
  promptTemplateBridge.cancelAll();
954
1046
  promptTemplateBridge.dispose();
955
1047
  state.widgetsSuspended = false;
956
1048
  state.currentSessionId = null;
1049
+ state.statusProjectionSessionId = null;
957
1050
  state.parentSessionFile = null;
958
1051
  parentSessionEnvValue = null;
959
1052
  if (shuttingDownParentSession && process.env[SUBAGENT_PARENT_SESSION_ENV] === shuttingDownParentSession) {
@@ -1017,7 +1110,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1017
1110
 
1018
1111
  pi.on("session_compact", () => {
1019
1112
  const hasActiveAsyncWork = [...state.asyncJobs.values()].some((job) => job.status === "queued" || job.status === "running");
1020
- if (!hasActiveAsyncWork || state.lastUiContext?.hasUI !== true) return;
1113
+ if (!hasActiveAsyncWork || !withLastUiContext(() => true)) return;
1021
1114
  pi.sendMessage(
1022
1115
  {
1023
1116
  customType: "subagent-compaction-resume",
@@ -1031,7 +1124,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1031
1124
  pi.on("session_start", (event, ctx) => {
1032
1125
  installRuntime(ctx);
1033
1126
  const recovering = event.reason === "startup" || event.reason === "reload" || event.reason === "resume";
1034
- resetSessionState(ctx, recovering);
1127
+ resetSessionState(ctx, recovering, event.previousSessionFile);
1035
1128
  refreshContextInjectionSnapshot(ctx);
1036
1129
  herdrStatusBridge.sessionStarted({
1037
1130
  hasUI: ctx.hasUI === true,
@@ -1053,6 +1146,11 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1053
1146
 
1054
1147
  pi.on("session_shutdown", async () => {
1055
1148
  runtimeEntry.cleanup();
1149
+ try {
1150
+ await disposeChildSessions();
1151
+ } catch (error) {
1152
+ console.error("Failed to dispose in-process child sessions:", error);
1153
+ }
1056
1154
  await herdrStatusBridge.flush();
1057
1155
  });
1058
1156
  }