@xzzpig/pi-subagents 0.1.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 (196) hide show
  1. package/CHANGELOG.md +1621 -0
  2. package/LICENSE +21 -0
  3. package/README.md +118 -0
  4. package/agents/delegate.md +14 -0
  5. package/agents/oracle.md +74 -0
  6. package/agents/researcher.md +52 -0
  7. package/agents/reviewer.md +79 -0
  8. package/agents/scout.md +50 -0
  9. package/agents/worker.md +58 -0
  10. package/index.ts +1 -0
  11. package/inspector-runner.mjs +11 -0
  12. package/install.mjs +93 -0
  13. package/package.json +105 -0
  14. package/prompts/gather-context-and-clarify.md +13 -0
  15. package/prompts/parallel-cleanup.md +59 -0
  16. package/prompts/parallel-research.md +50 -0
  17. package/prompts/parallel-review.md +54 -0
  18. package/prompts/review-loop.md +43 -0
  19. package/skills/pi-subagents/SKILL.md +41 -0
  20. package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
  21. package/skills/pi-subagents/references/execution-controls.md +428 -0
  22. package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
  24. package/src/agents/agent-management.ts +1256 -0
  25. package/src/agents/agent-memory.ts +254 -0
  26. package/src/agents/agent-refinements.ts +624 -0
  27. package/src/agents/agent-scope.ts +6 -0
  28. package/src/agents/agent-selection.ts +25 -0
  29. package/src/agents/agent-serializer.ts +163 -0
  30. package/src/agents/agents.ts +1889 -0
  31. package/src/agents/chain-serializer.ts +280 -0
  32. package/src/agents/frontmatter.ts +149 -0
  33. package/src/agents/identity.ts +30 -0
  34. package/src/agents/proactive-skills.ts +194 -0
  35. package/src/agents/skills.ts +761 -0
  36. package/src/api/background-work.ts +197 -0
  37. package/src/api/capability-ceiling.ts +17 -0
  38. package/src/api/control-channel.ts +4 -0
  39. package/src/api/delegation.ts +119 -0
  40. package/src/api/external-runs.ts +129 -0
  41. package/src/api/intercom-bridge.ts +3 -0
  42. package/src/api/pi-args.ts +5 -0
  43. package/src/api/preflight.ts +403 -0
  44. package/src/api/shared-types.ts +19 -0
  45. package/src/extension/config.ts +76 -0
  46. package/src/extension/control-notices.ts +58 -0
  47. package/src/extension/doctor.ts +230 -0
  48. package/src/extension/fanout-child.ts +201 -0
  49. package/src/extension/index.ts +805 -0
  50. package/src/extension/public-execution.ts +71 -0
  51. package/src/extension/rpc.ts +653 -0
  52. package/src/extension/schemas.ts +375 -0
  53. package/src/extension/steering-notices.ts +35 -0
  54. package/src/extension/tool-description.ts +164 -0
  55. package/src/inspectors/herdr/actions.ts +229 -0
  56. package/src/inspectors/herdr/client.ts +130 -0
  57. package/src/inspectors/herdr/inspector-runner.ts +141 -0
  58. package/src/inspectors/herdr/project-panes.ts +154 -0
  59. package/src/integrations/herdr-status.ts +330 -0
  60. package/src/intercom/intercom-bridge.ts +187 -0
  61. package/src/intercom/native-supervisor-channel.ts +715 -0
  62. package/src/intercom/result-intercom.ts +421 -0
  63. package/src/missions/actions.ts +410 -0
  64. package/src/missions/goal-driver.ts +162 -0
  65. package/src/missions/lifecycle.ts +346 -0
  66. package/src/missions/store.ts +507 -0
  67. package/src/missions/types.ts +157 -0
  68. package/src/missions/workflow-state.ts +250 -0
  69. package/src/policy/authority.ts +46 -0
  70. package/src/profiles/profiles.ts +661 -0
  71. package/src/runs/background/async-execution.ts +1574 -0
  72. package/src/runs/background/async-job-tracker.ts +511 -0
  73. package/src/runs/background/async-resume.ts +539 -0
  74. package/src/runs/background/async-status.ts +542 -0
  75. package/src/runs/background/auto-drain.ts +67 -0
  76. package/src/runs/background/chain-append.ts +328 -0
  77. package/src/runs/background/chain-root-attachment.ts +199 -0
  78. package/src/runs/background/completion-batcher.ts +168 -0
  79. package/src/runs/background/completion-dedupe.ts +54 -0
  80. package/src/runs/background/control-channel.ts +692 -0
  81. package/src/runs/background/fleet-view.ts +540 -0
  82. package/src/runs/background/notify.ts +332 -0
  83. package/src/runs/background/parallel-groups.ts +45 -0
  84. package/src/runs/background/process-terminal.ts +280 -0
  85. package/src/runs/background/result-watcher.ts +414 -0
  86. package/src/runs/background/retained-children.ts +68 -0
  87. package/src/runs/background/run-id-resolver.ts +167 -0
  88. package/src/runs/background/run-status.ts +504 -0
  89. package/src/runs/background/scheduled-runs.ts +753 -0
  90. package/src/runs/background/stale-run-reconciler.ts +396 -0
  91. package/src/runs/background/steering.ts +239 -0
  92. package/src/runs/background/subagent-runner.ts +4718 -0
  93. package/src/runs/background/subagent-wait.ts +661 -0
  94. package/src/runs/background/top-level-async.ts +14 -0
  95. package/src/runs/background/wait-completions.ts +112 -0
  96. package/src/runs/background/wait-config.ts +36 -0
  97. package/src/runs/background/wait-subscriptions.ts +253 -0
  98. package/src/runs/background/wait-tool.ts +34 -0
  99. package/src/runs/foreground/async-steering-action.ts +256 -0
  100. package/src/runs/foreground/async-stop-action.ts +65 -0
  101. package/src/runs/foreground/chain-clarify.ts +1354 -0
  102. package/src/runs/foreground/chain-execution.ts +1527 -0
  103. package/src/runs/foreground/execution.ts +1868 -0
  104. package/src/runs/foreground/foreground-control.ts +132 -0
  105. package/src/runs/foreground/subagent-executor.ts +5532 -0
  106. package/src/runs/shared/acceptance.ts +1365 -0
  107. package/src/runs/shared/agent-contract.ts +38 -0
  108. package/src/runs/shared/capability-ceiling.ts +209 -0
  109. package/src/runs/shared/chain-outputs.ts +118 -0
  110. package/src/runs/shared/child-protocol.ts +401 -0
  111. package/src/runs/shared/completion-guard.ts +95 -0
  112. package/src/runs/shared/context-mode.ts +44 -0
  113. package/src/runs/shared/dynamic-fanout.ts +297 -0
  114. package/src/runs/shared/external-cli-runner.ts +130 -0
  115. package/src/runs/shared/long-running-guard.ts +220 -0
  116. package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
  117. package/src/runs/shared/model-fallback.ts +336 -0
  118. package/src/runs/shared/model-scope.ts +128 -0
  119. package/src/runs/shared/nested-events.ts +1076 -0
  120. package/src/runs/shared/nested-path.ts +52 -0
  121. package/src/runs/shared/nested-render.ts +123 -0
  122. package/src/runs/shared/parallel-handoff.ts +238 -0
  123. package/src/runs/shared/parallel-utils.ts +256 -0
  124. package/src/runs/shared/permissions.ts +95 -0
  125. package/src/runs/shared/pi-args.ts +808 -0
  126. package/src/runs/shared/pi-spawn.ts +163 -0
  127. package/src/runs/shared/process-signal.ts +19 -0
  128. package/src/runs/shared/run-history.ts +181 -0
  129. package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
  130. package/src/runs/shared/session-lease.ts +299 -0
  131. package/src/runs/shared/single-output.ts +235 -0
  132. package/src/runs/shared/spawn-budget.ts +128 -0
  133. package/src/runs/shared/structured-output.ts +182 -0
  134. package/src/runs/shared/subagent-control.ts +231 -0
  135. package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
  136. package/src/runs/shared/subagent-startup-retry.ts +104 -0
  137. package/src/runs/shared/task-intent.ts +181 -0
  138. package/src/runs/shared/tool-availability.ts +83 -0
  139. package/src/runs/shared/tool-budget.ts +80 -0
  140. package/src/runs/shared/turn-budget.ts +98 -0
  141. package/src/runs/shared/usage-budget.ts +65 -0
  142. package/src/runs/shared/workflow-graph.ts +231 -0
  143. package/src/runs/shared/worktree.ts +759 -0
  144. package/src/shared/accessible-dir.ts +47 -0
  145. package/src/shared/artifacts.ts +285 -0
  146. package/src/shared/atomic-json.ts +61 -0
  147. package/src/shared/child-transcript.ts +264 -0
  148. package/src/shared/file-coalescer.ts +40 -0
  149. package/src/shared/file-system-retry.ts +47 -0
  150. package/src/shared/fork-context.ts +213 -0
  151. package/src/shared/formatters.ts +133 -0
  152. package/src/shared/jsonl-writer.ts +81 -0
  153. package/src/shared/launch-contract.ts +124 -0
  154. package/src/shared/model-info.ts +81 -0
  155. package/src/shared/post-exit-stdio-guard.ts +85 -0
  156. package/src/shared/session-identity.ts +10 -0
  157. package/src/shared/session-tokens.ts +44 -0
  158. package/src/shared/settings.ts +501 -0
  159. package/src/shared/status-format.ts +55 -0
  160. package/src/shared/types.ts +2069 -0
  161. package/src/shared/utils.ts +613 -0
  162. package/src/slash/delegation-adapters.ts +434 -0
  163. package/src/slash/delegation-json.ts +108 -0
  164. package/src/slash/delegation-request.ts +166 -0
  165. package/src/slash/prompt-template-bridge.ts +383 -0
  166. package/src/slash/prompt-workflows.ts +300 -0
  167. package/src/slash/selector.ts +147 -0
  168. package/src/slash/slash-bridge.ts +192 -0
  169. package/src/slash/slash-commands.ts +994 -0
  170. package/src/slash/slash-live-state.ts +296 -0
  171. package/src/slash/subagents-admin.ts +432 -0
  172. package/src/tui/fleet-status.ts +564 -0
  173. package/src/tui/fleet-transcript.ts +577 -0
  174. package/src/tui/fleet.ts +879 -0
  175. package/src/tui/render-helpers.ts +80 -0
  176. package/src/tui/render.ts +2029 -0
  177. package/src/types/pi-runtime-compat.d.ts +8 -0
  178. package/src/watchdog/change-signature.ts +220 -0
  179. package/src/watchdog/child-status.ts +205 -0
  180. package/src/watchdog/emission-guard.ts +123 -0
  181. package/src/watchdog/lsp-diagnostics.ts +537 -0
  182. package/src/watchdog/model-selection.ts +167 -0
  183. package/src/watchdog/permission-arbiter.ts +145 -0
  184. package/src/watchdog/register-child.ts +117 -0
  185. package/src/watchdog/register-main.ts +440 -0
  186. package/src/watchdog/render.ts +54 -0
  187. package/src/watchdog/review.ts +302 -0
  188. package/src/watchdog/runtime.ts +868 -0
  189. package/src/watchdog/scope.ts +62 -0
  190. package/src/watchdog/settings.ts +568 -0
  191. package/src/watchdog/tool-actions.ts +155 -0
  192. package/src/watchdog/turn-delta.ts +161 -0
  193. package/src/watchdog/types.ts +198 -0
  194. package/src/watchdog/warning-format.ts +73 -0
  195. package/src/workflows/chat-progress.ts +140 -0
  196. package/src/workflows/scripted-workflow.ts +506 -0
@@ -0,0 +1,805 @@
1
+ /**
2
+ * Subagent Tool
3
+ *
4
+ * Full-featured subagent with sync and async modes.
5
+ * - Sync (default): Streams output, renders markdown, tracks usage
6
+ * - Async: Background execution, emits events when done
7
+ *
8
+ * Public execution mode: workflow (workflowScript)
9
+ * Toggle: async parameter (default: true; set asyncByDefault:false in config.json to opt out)
10
+ *
11
+ * Config file: ~/.pi/agent/extensions/subagent/config.json
12
+ * { "asyncByDefault": true, "forceTopLevelAsync": true, "maxSubagentDepth": 1, "intercomBridge": { "mode": "always", "instructionFile": "./intercom-bridge.md" }, "worktreeSetupHook": "./scripts/setup-worktree.mjs" }
13
+ */
14
+
15
+ import { randomUUID } from "node:crypto";
16
+ import * as fs from "node:fs";
17
+ import * as os from "node:os";
18
+ import * as path from "node:path";
19
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
20
+ import { keyText, type ExtensionAPI, type ExtensionContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
21
+ import { Box, Container, Spacer, Text, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
22
+ import { discoverAgents } from "../agents/agents.ts";
23
+ import { ensureAccessibleDir } from "../shared/accessible-dir.ts";
24
+ import { cleanupAllArtifactDirs, cleanupOldArtifacts, getArtifactsDir } from "../shared/artifacts.ts";
25
+ import { resolveCurrentSessionId } from "../shared/session-identity.ts";
26
+ import { cleanupOldChainDirs } from "../shared/settings.ts";
27
+ import { clearLegacyResultAnimationTimer, renderSubagentResult, renderSubagentSummary } from "../tui/render.ts";
28
+ import { openSubagentFleet } from "../tui/fleet.ts";
29
+ import { SubagentFleetStatus, resolveFleetViewPlacement } from "../tui/fleet-status.ts";
30
+ import { SubagentParams } from "./schemas.ts";
31
+ import { createSubagentExecutor, type SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
32
+ import { createAsyncJobTracker } from "../runs/background/async-job-tracker.ts";
33
+ import { createResultWatcher } from "../runs/background/result-watcher.ts";
34
+ import { createScheduledRunManager } from "../runs/background/scheduled-runs.ts";
35
+ import { registerSlashCommands } from "../slash/slash-commands.ts";
36
+ import { registerPromptTemplateDelegationBridge } from "../slash/prompt-template-bridge.ts";
37
+ import { registerMainWatchdog } from "../watchdog/register-main.ts";
38
+ import { registerSlashSubagentBridge } from "../slash/slash-bridge.ts";
39
+ import { createNativeSupervisorChannel } from "../intercom/native-supervisor-channel.ts";
40
+ import { registerHerdrStatusBridge } from "../integrations/herdr-status.ts";
41
+ import { registerSubagentRpcBridge } from "./rpc.ts";
42
+ import { clearSlashSnapshots, getSlashRenderableSnapshot, resolveSlashMessageDetails, restoreSlashFinalSnapshots, type SlashMessageDetails } from "../slash/slash-live-state.ts";
43
+ import { inspectSubagentStatus } from "../runs/background/run-status.ts";
44
+ import { resolveWaitToolConfig } from "../runs/background/subagent-wait.ts";
45
+ import { registerWaitTool } from "../runs/background/wait-tool.ts";
46
+ import { createWaitSubscriptionManager } from "../runs/background/wait-subscriptions.ts";
47
+ import { drainOutstandingWork } from "../runs/background/auto-drain.ts";
48
+ import registerSubagentNotify, { parseSubagentNotifyContent, type SubagentNotifyDetails } from "../runs/background/notify.ts";
49
+ import { formatSteeringNotice, handleSubagentSteeringNotice, SUBAGENT_STEERING_MESSAGE_TYPE, type SubagentSteeringMessageDetails } from "./steering-notices.ts";
50
+ import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "../runs/shared/pi-args.ts";
51
+ import { resolveCurrentSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.ts";
52
+ import { formatDuration, shortenPath } from "../shared/formatters.ts";
53
+ import { loadConfig, resolveAsyncByDefault, resolveScheduledStoreRoot } from "./config.ts";
54
+ import { buildSubagentToolDescription } from "./tool-description.ts";
55
+ import { collectGoalContinuationNotices } from "../missions/goal-driver.ts";
56
+ import { syncMissionFromAsyncCompletion } from "../missions/lifecycle.ts";
57
+ import { resolveMissionStoreLocation } from "../missions/store.ts";
58
+ import { listRetainedChildren } from "../runs/background/retained-children.ts";
59
+ import {
60
+ type Details,
61
+ type SubagentState,
62
+ DIRS,
63
+ DEFAULT_ARTIFACT_CONFIG,
64
+ SLASH_RESULT_TYPE,
65
+ SLASH_TEXT_RESULT_TYPE,
66
+ SUBAGENT_ASYNC_COMPLETE_EVENT,
67
+ SUBAGENT_ASYNC_STARTED_EVENT,
68
+ SUBAGENT_CONTROL_EVENT,
69
+ SUBAGENT_STEERING_NOTICE_EVENT,
70
+ WIDGET_KEY,
71
+ resolveMaxSubagentSpawnsPerSession,
72
+ } from "../shared/types.ts";
73
+ import {
74
+ formatSubagentControlNotice,
75
+ handleSubagentControlNotice,
76
+ SUBAGENT_CONTROL_MESSAGE_TYPE,
77
+ type SubagentControlMessageDetails,
78
+ } from "./control-notices.ts";
79
+
80
+ export { loadConfig, resolveAsyncByDefault } from "./config.ts";
81
+
82
+ function workflowLaneKeys(script: string): string[] {
83
+ const keys: string[] = [];
84
+ const seen = new Set<string>();
85
+ const add = (key: string): void => {
86
+ if (!seen.has(key)) {
87
+ seen.add(key);
88
+ keys.push(key);
89
+ }
90
+ };
91
+ const isIdentifier = (char: string | undefined): boolean => char !== undefined && /[\w$]/.test(char);
92
+ const skipTrivia = (start: number): number => {
93
+ let index = start;
94
+ while (index < script.length) {
95
+ if (/\s/.test(script[index]!)) index += 1;
96
+ else if (script.startsWith("//", index)) {
97
+ const end = script.indexOf("\n", index + 2);
98
+ index = end === -1 ? script.length : end + 1;
99
+ } else if (script.startsWith("/*", index)) {
100
+ const end = script.indexOf("*/", index + 2);
101
+ index = end === -1 ? script.length : end + 2;
102
+ } else break;
103
+ }
104
+ return index;
105
+ };
106
+ const readLiteral = (start: number): { key?: string; end: number } | undefined => {
107
+ const quote = script[start];
108
+ if (quote !== "'" && quote !== '"' && quote !== "`") return undefined;
109
+ let index = start + 1;
110
+ let dynamicTemplate = false;
111
+ while (index < script.length) {
112
+ if (script[index] === "\\") {
113
+ index += 2;
114
+ continue;
115
+ }
116
+ if (quote === "`" && script.startsWith("${", index)) dynamicTemplate = true;
117
+ if (script[index] === quote) return { key: dynamicTemplate ? undefined : script.slice(start + 1, index), end: index + 1 };
118
+ if (quote !== "`" && /[\r\n]/.test(script[index]!)) return { end: index + 1 };
119
+ index += 1;
120
+ }
121
+ return { end: script.length };
122
+ };
123
+
124
+ const collectRunsAllKeys = (start: number): number => {
125
+ let index = skipTrivia(start);
126
+ if (script[index] !== "(") return start;
127
+ index = skipTrivia(index + 1);
128
+ if (script[index] !== "[") return start;
129
+ let arrayDepth = 1;
130
+ let objectDepth = 0;
131
+ let directChildObject = false;
132
+ let expectingElement = true;
133
+ for (index += 1; index < script.length; index += 1) {
134
+ index = skipTrivia(index);
135
+ const literal = readLiteral(index);
136
+ if (literal) {
137
+ index = literal.end - 1;
138
+ continue;
139
+ }
140
+ if (script[index] === "[") {
141
+ arrayDepth += 1;
142
+ expectingElement = false;
143
+ continue;
144
+ }
145
+ if (script[index] === "]") {
146
+ arrayDepth -= 1;
147
+ if (arrayDepth === 0) return index + 1;
148
+ continue;
149
+ }
150
+ if (script[index] === "{") {
151
+ objectDepth += 1;
152
+ if (objectDepth === 1) directChildObject = arrayDepth === 1 && expectingElement;
153
+ expectingElement = false;
154
+ continue;
155
+ }
156
+ if (script[index] === "}") {
157
+ objectDepth -= 1;
158
+ if (objectDepth === 0) directChildObject = false;
159
+ continue;
160
+ }
161
+ if (script[index] === "," && arrayDepth === 1 && objectDepth === 0) {
162
+ expectingElement = true;
163
+ continue;
164
+ }
165
+ if (directChildObject && objectDepth === 1 && !isIdentifier(script[index - 1]) && script.startsWith("key", index) && !isIdentifier(script[index + 3])) {
166
+ const colon = skipTrivia(index + 3);
167
+ const key = script[colon] === ":" ? readLiteral(skipTrivia(colon + 1)) : undefined;
168
+ if (key) {
169
+ const next = skipTrivia(key.end);
170
+ if (key.key !== undefined && (script[next] === "," || script[next] === "}")) add(key.key);
171
+ index = key.end - 1;
172
+ }
173
+ }
174
+ }
175
+ return index;
176
+ };
177
+
178
+ for (let index = 0; index < script.length;) {
179
+ index = skipTrivia(index);
180
+ const literal = readLiteral(index);
181
+ if (literal) {
182
+ index = literal.end;
183
+ continue;
184
+ }
185
+ if (!isIdentifier(script[index - 1]) && script.startsWith("runs.run", index) && !isIdentifier(script[index + 8])) {
186
+ const open = skipTrivia(index + 8);
187
+ const key = script[open] === "(" ? readLiteral(skipTrivia(open + 1)) : undefined;
188
+ if (key) {
189
+ const next = skipTrivia(key.end);
190
+ if (key.key !== undefined && (script[next] === "," || script[next] === ")")) add(key.key);
191
+ index = key.end;
192
+ continue;
193
+ }
194
+ }
195
+ if (!isIdentifier(script[index - 1]) && script.startsWith("runs.all", index) && !isIdentifier(script[index + 8])) {
196
+ index = collectRunsAllKeys(index + 8);
197
+ continue;
198
+ }
199
+ index += 1;
200
+ }
201
+ return keys;
202
+ }
203
+
204
+ function formatWorkflowManifest(script: string, async: unknown, clarify: unknown): string {
205
+ if (clarify === true) return "workflow script · rejected: clarify UI unsupported";
206
+ const keys = workflowLaneKeys(script);
207
+ // The workflow executor starts background work unless callers pass async:false.
208
+ const mode = async === false ? "foreground" : "background";
209
+ if (keys.length === 0) return `workflow script · ${mode}`;
210
+ const visibleKeys = keys.slice(0, 4).join(", ");
211
+ const remainder = keys.length > 4 ? `, +${keys.length - 4}` : "";
212
+ return `workflow · ${mode} · ${keys.length} lane${keys.length === 1 ? "" : "s"}: ${visibleKeys}${remainder}`;
213
+ }
214
+
215
+ /**
216
+ * Derive subagent session base directory from parent session file.
217
+ * If parent session is ~/.pi/agent/sessions/abc123.jsonl,
218
+ * returns ~/.pi/agent/sessions/abc123/ as the base.
219
+ * Callers add runId to create the actual session root: abc123/{runId}/
220
+ * Falls back to a unique temp directory if no parent session.
221
+ */
222
+ function getSubagentSessionRoot(parentSessionFile: string | null): string {
223
+ if (parentSessionFile) {
224
+ const baseName = path.basename(parentSessionFile, ".jsonl");
225
+ const sessionsDir = path.dirname(parentSessionFile);
226
+ return path.join(sessionsDir, baseName);
227
+ }
228
+ return fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-session-"));
229
+ }
230
+
231
+ function expandTilde(p: string): string {
232
+ return p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p;
233
+ }
234
+
235
+ function isSlashResultRunning(result: { details?: Details }): boolean {
236
+ return result.details?.progress?.some((entry) => entry.status === "running")
237
+ || result.details?.results.some((entry) => entry.progress?.status === "running")
238
+ || false;
239
+ }
240
+
241
+ function isSlashResultError(result: { details?: Details }): boolean {
242
+ return result.details?.results.some((entry) => entry.exitCode !== 0 && entry.progress?.status !== "running") || false;
243
+ }
244
+
245
+ function isStaleExtensionContextError(error: unknown): boolean {
246
+ return error instanceof Error && error.message.includes("Extension context no longer active");
247
+ }
248
+
249
+ function rebuildSlashResultContainer(
250
+ container: Container,
251
+ result: AgentToolResult<Details>,
252
+ options: { expanded: boolean },
253
+ theme: ExtensionContext["ui"]["theme"],
254
+ ): void {
255
+ container.clear();
256
+ container.addChild(new Spacer(1));
257
+ const boxTheme = isSlashResultRunning(result) ? "toolPendingBg" : isSlashResultError(result) ? "toolErrorBg" : "toolSuccessBg";
258
+ const box = new Box(1, 1, (text: string) => theme.bg(boxTheme, text));
259
+ box.addChild(renderSubagentResult(result, options, theme));
260
+ container.addChild(box);
261
+ }
262
+
263
+ function createSlashResultComponent(
264
+ details: SlashMessageDetails,
265
+ options: { expanded: boolean },
266
+ theme: ExtensionContext["ui"]["theme"],
267
+ ): Container {
268
+ const container = new Container();
269
+ let lastVersion = -1;
270
+ container.render = (width: number): string[] => {
271
+ const snapshot = getSlashRenderableSnapshot(details);
272
+ if (snapshot.version !== lastVersion || isSlashResultRunning(snapshot.result)) {
273
+ lastVersion = snapshot.version;
274
+ rebuildSlashResultContainer(container, snapshot.result, options, theme);
275
+ }
276
+ return Container.prototype.render.call(container, width);
277
+ };
278
+ return container;
279
+ }
280
+
281
+ class SubagentControlNoticeComponent implements Component {
282
+ private readonly details: SubagentControlMessageDetails;
283
+ private readonly theme: ExtensionContext["ui"]["theme"];
284
+
285
+ constructor(details: SubagentControlMessageDetails, theme: ExtensionContext["ui"]["theme"]) {
286
+ this.details = details;
287
+ this.theme = theme;
288
+ }
289
+
290
+ invalidate(): void {}
291
+
292
+ render(width: number): string[] {
293
+ const eventLabel = this.details.event.type.replaceAll("_", " ");
294
+ if (width < 3) return [truncateToWidth(`Subagent ${eventLabel}`, width)];
295
+ const bodyWidth = Math.max(1, width - 2);
296
+ const borderChar = "─";
297
+ const header = ` ⚠ Subagent ${eventLabel}: ${this.details.event.agent} `;
298
+ const headerText = truncateToWidth(header, bodyWidth, "");
299
+ const headerPadding = Math.max(0, bodyWidth - visibleWidth(headerText));
300
+ const lines = [this.theme.fg("accent", `╭${headerText}${borderChar.repeat(headerPadding)}╮`)];
301
+
302
+ for (const line of wrapTextWithAnsi(formatSubagentControlNotice(this.details), bodyWidth)) {
303
+ const text = truncateToWidth(line, bodyWidth, "");
304
+ const padding = Math.max(0, bodyWidth - visibleWidth(text));
305
+ lines.push(this.theme.fg("accent", `│${text}${" ".repeat(padding)}│`));
306
+ }
307
+ lines.push(this.theme.fg("accent", `╰${borderChar.repeat(bodyWidth)}╯`));
308
+ return lines;
309
+ }
310
+ }
311
+
312
+ export default function registerSubagentExtension(pi: ExtensionAPI): void {
313
+ if (process.env[SUBAGENT_CHILD_ENV] === "1") {
314
+ return;
315
+ }
316
+ const globalStore = globalThis as Record<string, unknown>;
317
+ const runtimeCleanupStoreKey = "__piSubagentRuntimeCleanup";
318
+ const previousRuntimeCleanup = globalStore[runtimeCleanupStoreKey];
319
+ if (typeof previousRuntimeCleanup === "function") {
320
+ try {
321
+ previousRuntimeCleanup();
322
+ } catch {
323
+ // Best effort cleanup for stale timers from an older reload.
324
+ }
325
+ }
326
+
327
+ DIRS.results = ensureAccessibleDir(DIRS.results);
328
+ DIRS.async = ensureAccessibleDir(DIRS.async);
329
+ cleanupOldChainDirs();
330
+
331
+ const config = loadConfig();
332
+ const waitToolConfig = resolveWaitToolConfig(config.waitTool);
333
+ const asyncByDefault = resolveAsyncByDefault(config);
334
+ const fleetViewEnabled = config.fleetView !== false;
335
+ const fleetViewPlacement = resolveFleetViewPlacement(config.fleetViewPlacement);
336
+ const asyncWidgetEnabled = config.asyncWidget !== false;
337
+ const summaryInlineToolDisplay = config.inlineToolDisplay === "summary";
338
+ const tempArtifactsDir = getArtifactsDir(null);
339
+ cleanupAllArtifactDirs(DEFAULT_ARTIFACT_CONFIG.cleanupDays);
340
+
341
+ const state: SubagentState = {
342
+ baseCwd: "",
343
+ currentSessionId: null,
344
+ artifactDirPreference: config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir,
345
+ ...(config.authorityPolicy ? { authorityPolicy: config.authorityPolicy } : {}),
346
+ ...(config.missions ? { missionStoreConfig: config.missions } : {}),
347
+ parentSessionFile: null,
348
+ subagentInProgress: false,
349
+ subagentSpawns: {
350
+ sessionId: null,
351
+ count: 0,
352
+ configuredLimit: resolveMaxSubagentSpawnsPerSession(config.maxSubagentSpawnsPerSession) ?? null,
353
+ granted: 0,
354
+ grantHistory: [],
355
+ },
356
+ asyncJobs: new Map(),
357
+ fleetJobs: new Map(),
358
+ foregroundRuns: new Map(),
359
+ foregroundControls: new Map(),
360
+ lastForegroundControlId: null,
361
+ cleanupTimers: new Map(),
362
+ lastUiContext: null,
363
+ poller: null,
364
+ completionSeen: new Map(),
365
+ watcher: null,
366
+ watcherRestartTimer: null,
367
+ resultFileCoalescer: {
368
+ schedule: () => false,
369
+ clear: () => {},
370
+ },
371
+ };
372
+
373
+ const supervisorChannel = createNativeSupervisorChannel(pi, state);
374
+ const waitSubscriptionManager = createWaitSubscriptionManager(pi, state);
375
+ const mainWatchdog = registerMainWatchdog(pi);
376
+ const completionNotifier = registerSubagentNotify(pi, state, { batchConfig: config.completionBatch });
377
+ const fleetStatus = fleetViewEnabled
378
+ ? new SubagentFleetStatus(state, async (itemKey) => {
379
+ const ctx = state.lastUiContext;
380
+ if (!ctx?.hasUI) return;
381
+ await openSubagentFleet(ctx, state, { initialKey: itemKey, asyncDirRoot: DIRS.async, resultsDir: DIRS.results });
382
+ }, { placement: fleetViewPlacement })
383
+ : undefined;
384
+ let executorScheduled: ((id: string, params: SubagentParamsLike, signal: AbortSignal, ctx: ExtensionContext) => Promise<AgentToolResult<Details>>) | undefined;
385
+ let goalTurnId = 0;
386
+ const scheduledStoreRoot = config.scheduledRuns?.storeRoot === undefined ? undefined : resolveScheduledStoreRoot(config.scheduledRuns.storeRoot);
387
+ const scheduledRunManager = createScheduledRunManager({
388
+ config,
389
+ storeRoot: scheduledStoreRoot,
390
+ launch: (params, ctx, signal) => {
391
+ if (!executorScheduled) {
392
+ return Promise.resolve({
393
+ content: [{ type: "text", text: "Scheduled subagent launch is unavailable (executor not ready)." }],
394
+ isError: true,
395
+ details: { mode: "management" as const, results: [] },
396
+ });
397
+ }
398
+ return executorScheduled(randomUUID(), params, signal, ctx);
399
+ },
400
+ resolveCapabilityCeiling: (sessionId) => resolveCurrentSubagentCapabilityCeiling(sessionId),
401
+ });
402
+ const { startResultWatcher, primeExistingResults, stopResultWatcher } = createResultWatcher(
403
+ pi,
404
+ state,
405
+ DIRS.results,
406
+ 10 * 60 * 1000,
407
+ {
408
+ notifier: completionNotifier,
409
+ observeCompletion: (result) => scheduledRunManager.handleAsyncCompletion(result),
410
+ deliverIntercomResults: config.intercomBridge?.resultDelivery === true,
411
+ },
412
+ );
413
+
414
+ const runtimeCleanup = () => {
415
+ stopResultWatcher();
416
+ state.currentSessionId = null;
417
+ completionNotifier.dispose();
418
+ mainWatchdog.dispose();
419
+ scheduledRunManager.stop();
420
+ supervisorChannel.dispose();
421
+ waitSubscriptionManager.dispose();
422
+ fleetStatus?.dispose();
423
+ if (state.poller) {
424
+ clearInterval(state.poller);
425
+ state.poller = null;
426
+ }
427
+ };
428
+ globalStore[runtimeCleanupStoreKey] = runtimeCleanup;
429
+
430
+ const { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs } = createAsyncJobTracker(pi, state, DIRS.async, {
431
+ widgetEnabled: asyncWidgetEnabled,
432
+ });
433
+ const executor = createSubagentExecutor({
434
+ pi,
435
+ state,
436
+ config,
437
+ asyncByDefault,
438
+ waitToolEnabled: waitToolConfig.enabled,
439
+ handleScheduledRunAction: (params, ctx) => scheduledRunManager.handleToolCall(params, ctx),
440
+ watchdog: mainWatchdog,
441
+ tempArtifactsDir,
442
+ getSubagentSessionRoot,
443
+ expandTilde,
444
+ discoverAgents,
445
+ });
446
+ executorScheduled = executor.executeScheduled;
447
+
448
+ pi.registerMessageRenderer<SlashMessageDetails>(SLASH_RESULT_TYPE, (message, options, theme) => {
449
+ const details = resolveSlashMessageDetails(message.details);
450
+ if (!details) return undefined;
451
+ return createSlashResultComponent(details, options, theme);
452
+ });
453
+
454
+ pi.registerMessageRenderer<undefined>(SLASH_TEXT_RESULT_TYPE, (message, _options, _theme) => {
455
+ const content = typeof message.content === "string"
456
+ ? message.content
457
+ : message.content
458
+ .filter((entry) => entry.type === "text")
459
+ .map((entry) => entry.text)
460
+ .join("\n");
461
+ return new Text(content, 0, 0);
462
+ });
463
+
464
+ pi.registerMessageRenderer<SubagentNotifyDetails>("subagent-notify", (message, options, theme) => {
465
+ const content = typeof message.content === "string" ? message.content : "";
466
+ const details = (message.details as SubagentNotifyDetails | undefined) ?? parseSubagentNotifyContent(content);
467
+ if (!details) return new Text(content, 0, 0);
468
+ const icon = details.status === "completed"
469
+ ? theme.fg("success", "✓")
470
+ : details.status === "paused"
471
+ ? theme.fg("warning", "■")
472
+ : theme.fg("error", "✗");
473
+ const parts: string[] = [];
474
+ if (details.taskInfo) parts.push(details.taskInfo);
475
+ if (details.durationMs !== undefined) parts.push(formatDuration(details.durationMs));
476
+ let text = `${icon} ${theme.bold(details.agent)} ${theme.fg("dim", details.status)}`;
477
+ if (parts.length > 0) text += ` ${theme.fg("dim", "·")} ${parts.map((part) => theme.fg("dim", part)).join(` ${theme.fg("dim", "·")} `)}`;
478
+ const trimmedPreview = details.resultPreview.trim();
479
+ const previewLines = options.expanded
480
+ ? trimmedPreview.split("\n").filter((line) => line.trim())
481
+ : [trimmedPreview.split("\n", 1)[0] ?? ""].filter((line) => line.trim());
482
+ for (const line of previewLines.length > 0 ? previewLines : ["(no output)"]) {
483
+ text += `\n ${theme.fg("dim", `⎿ ${line}`)}`;
484
+ }
485
+ if (!options.expanded && trimmedPreview.includes("\n")) {
486
+ const expandKey = keyText("app.tools.expand");
487
+ text += `\n ${theme.fg("dim", `${expandKey} full notification`)}`;
488
+ }
489
+ if (details.sessionLabel && details.sessionValue) {
490
+ text += `\n ${theme.fg("muted", `${details.sessionLabel}: ${shortenPath(details.sessionValue)}`)}`;
491
+ }
492
+ return new Text(text, 0, 0);
493
+ });
494
+
495
+ pi.registerMessageRenderer<SubagentSteeringMessageDetails>(SUBAGENT_STEERING_MESSAGE_TYPE, (message, _options, theme) => {
496
+ const details = message.details as SubagentSteeringMessageDetails | undefined;
497
+ if (!details) return undefined;
498
+ return new Text(theme.fg(details.state === "recovered" ? "warning" : "error", formatSteeringNotice(details)), 0, 0);
499
+ });
500
+
501
+ pi.registerMessageRenderer<SubagentControlMessageDetails>(SUBAGENT_CONTROL_MESSAGE_TYPE, (message, _options, theme) => {
502
+ const details = message.details as SubagentControlMessageDetails | undefined;
503
+ if (!details?.event) return undefined;
504
+ const content = typeof message.content === "string" ? message.content : undefined;
505
+ return new SubagentControlNoticeComponent({ ...details, noticeText: formatSubagentControlNotice(details, content) }, theme);
506
+ });
507
+
508
+ const executeSubagentCollapsed = (id: string, params: SubagentParamsLike, signal: AbortSignal, onUpdate: ((result: AgentToolResult<Details>) => void) | undefined, ctx: ExtensionContext) => {
509
+ if (ctx.hasUI) ctx.ui.setToolsExpanded(false);
510
+ return executor.executePublic(id, params, signal, onUpdate, ctx);
511
+ };
512
+
513
+ const slashBridge = registerSlashSubagentBridge({
514
+ events: pi.events,
515
+ getContext: () => state.lastUiContext,
516
+ execute: (id, params, signal, onUpdate, ctx) =>
517
+ executeSubagentCollapsed(id, params, signal, onUpdate, ctx),
518
+ });
519
+
520
+ const promptTemplateBridge = registerPromptTemplateDelegationBridge({
521
+ events: pi.events,
522
+ getContext: () => state.lastUiContext,
523
+ execute: (requestId, params, signal, ctx, onUpdate) =>
524
+ executeSubagentCollapsed(requestId, params, signal, onUpdate, ctx),
525
+ executeStructured: (requestId, params, signal, ctx, onUpdate) => {
526
+ if (ctx.hasUI) ctx.ui.setToolsExpanded(false);
527
+ return executor.executeDelegated(requestId, params, signal, onUpdate, ctx);
528
+ },
529
+ });
530
+
531
+ const rpcBridge = registerSubagentRpcBridge({
532
+ events: pi.events,
533
+ getContext: () => state.lastUiContext,
534
+ execute: (id, params, signal, onUpdate, ctx) => executor.executePublic(id, params, signal, onUpdate, ctx),
535
+ state,
536
+ });
537
+
538
+
539
+ const tool: ToolDefinition<typeof SubagentParams, Details> = {
540
+ name: "subagent",
541
+ label: "Subagent",
542
+ description: buildSubagentToolDescription(config),
543
+ parameters: SubagentParams,
544
+
545
+ execute(id, params, signal, onUpdate, ctx) {
546
+ return executeSubagentCollapsed(id, params as SubagentParamsLike, signal ?? new AbortController().signal, onUpdate, ctx);
547
+ },
548
+
549
+ renderCall(args, theme) {
550
+ if (args.action) {
551
+ const target = args.agent || args.chainName || "";
552
+ return new Text(
553
+ `${theme.fg("toolTitle", theme.bold("subagent "))}${args.action}${target ? ` ${theme.fg("accent", target)}` : ""}`,
554
+ 0, 0,
555
+ );
556
+ }
557
+ if (args.workflowScript)
558
+ return new Text(
559
+ `${theme.fg("toolTitle", theme.bold("subagent "))}${formatWorkflowManifest(args.workflowScript, args.async, false)}`,
560
+ 0,
561
+ 0,
562
+ );
563
+ const asyncLabel = args.async === true ? theme.fg("warning", " [async]") : "";
564
+ return new Text(
565
+ `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", args.agent || "?")}${asyncLabel}`,
566
+ 0,
567
+ 0,
568
+ );
569
+ },
570
+
571
+ renderResult(result, options, theme, context) {
572
+ clearLegacyResultAnimationTimer(context);
573
+ const renderedResult = { ...result, isError: context.isError };
574
+ return summaryInlineToolDisplay
575
+ ? renderSubagentSummary(renderedResult, options, theme)
576
+ : renderSubagentResult(renderedResult, options, theme);
577
+ },
578
+
579
+ };
580
+
581
+ pi.registerTool(tool);
582
+
583
+ registerWaitTool(pi, state, waitToolConfig.enabled, waitSubscriptionManager);
584
+
585
+ pi.on("agent_end", async (_event, ctx) => {
586
+ if (!ctx.hasUI) await drainOutstandingWork({ state, events: pi.events });
587
+ const ownerSessionId = state.currentSessionId;
588
+ if (!ownerSessionId) return;
589
+ goalTurnId += 1;
590
+ try {
591
+ const location = resolveMissionStoreLocation({ projectRoot: state.baseCwd, ...(config.missions ? { config: config.missions } : {}) });
592
+ const retainedChildren = listRetainedChildren(DIRS.async, ownerSessionId);
593
+ for (const notice of collectGoalContinuationNotices({ location, ownerSessionId, retainedChildren, turnId: goalTurnId })) {
594
+ handleSubagentControlNotice({
595
+ pi,
596
+ state,
597
+ visibleControlNotices: new Set(),
598
+ details: { source: "goal", event: notice.event, noticeText: notice.message },
599
+ });
600
+ }
601
+ } catch (error) {
602
+ console.error("Failed to evaluate goal missions:", error);
603
+ }
604
+ });
605
+
606
+ registerSlashCommands(pi, state);
607
+
608
+ const eventUnsubscribeStoreKey = "__piSubagentEventUnsubscribes";
609
+ const controlNoticeSeenStoreKey = "__piSubagentVisibleControlNotices";
610
+ const previousEventUnsubscribes = globalStore[eventUnsubscribeStoreKey];
611
+ if (Array.isArray(previousEventUnsubscribes)) {
612
+ for (const unsubscribe of previousEventUnsubscribes) {
613
+ if (typeof unsubscribe !== "function") continue;
614
+ try {
615
+ unsubscribe();
616
+ } catch {
617
+ // Best effort cleanup for stale handlers from an older reload.
618
+ }
619
+ }
620
+ }
621
+ const existingVisibleControlNotices = globalStore[controlNoticeSeenStoreKey];
622
+ const visibleControlNotices = existingVisibleControlNotices instanceof Set ? existingVisibleControlNotices as Set<string> : new Set<string>();
623
+ globalStore[controlNoticeSeenStoreKey] = visibleControlNotices;
624
+ const activeHerdrRuns = () => [...state.asyncJobs.values()]
625
+ .filter((job) => job.status === "queued" || job.status === "running")
626
+ .map((job) => ({
627
+ id: job.asyncId,
628
+ agents: job.agents,
629
+ needsAttention: job.activityState === "needs_attention",
630
+ }));
631
+ const herdrStatusBridge = registerHerdrStatusBridge({
632
+ events: pi.events,
633
+ getRuns: activeHerdrRuns,
634
+ async runHerdr(args) {
635
+ await pi.exec(process.env.HERDR_BIN || "herdr", [...args], { timeout: 5_000 });
636
+ },
637
+ });
638
+ const controlEventHandler = (payload: unknown) => {
639
+ handleSubagentControlNotice({
640
+ pi,
641
+ state,
642
+ visibleControlNotices,
643
+ details: payload as SubagentControlMessageDetails,
644
+ });
645
+ };
646
+ const steeringNoticeHandler = (payload: unknown) => {
647
+ handleSubagentSteeringNotice({ pi, state, details: payload as SubagentSteeringMessageDetails });
648
+ };
649
+ const asyncStartedHandler = (payload: unknown) => {
650
+ handleStarted(payload);
651
+ fleetStatus?.refresh();
652
+ };
653
+ const asyncCompleteHandler = (payload: unknown) => {
654
+ handleComplete(payload);
655
+ scheduledRunManager.handleAsyncCompletion(payload);
656
+ try {
657
+ syncMissionFromAsyncCompletion(payload);
658
+ } catch (error) {
659
+ console.error("Failed to update mission from async completion:", error);
660
+ }
661
+ fleetStatus?.refresh();
662
+ };
663
+ const eventUnsubscribes = [
664
+ pi.events.on(SUBAGENT_ASYNC_STARTED_EVENT, asyncStartedHandler),
665
+ pi.events.on(SUBAGENT_ASYNC_COMPLETE_EVENT, asyncCompleteHandler),
666
+ pi.events.on(SUBAGENT_CONTROL_EVENT, controlEventHandler),
667
+ pi.events.on(SUBAGENT_STEERING_NOTICE_EVENT, steeringNoticeHandler),
668
+ herdrStatusBridge.dispose,
669
+ rpcBridge.dispose,
670
+ ];
671
+ globalStore[eventUnsubscribeStoreKey] = eventUnsubscribes;
672
+
673
+ pi.on("tool_result", (event, ctx) => {
674
+ if (event.toolName !== "subagent") return;
675
+ if (!ctx.hasUI) return;
676
+ state.lastUiContext = ctx;
677
+ restoreActiveJobs(ctx);
678
+ fleetStatus?.setContext(ctx);
679
+ fleetStatus?.refresh();
680
+ if (state.asyncJobs.size > 0) {
681
+ refreshWidget(ctx);
682
+ ensurePoller();
683
+ }
684
+ });
685
+
686
+ const cleanupSessionArtifacts = (ctx: ExtensionContext) => {
687
+ try {
688
+ const sessionFile = ctx.sessionManager.getSessionFile();
689
+ if (sessionFile) {
690
+ cleanupOldArtifacts(getArtifactsDir(sessionFile), DEFAULT_ARTIFACT_CONFIG.cleanupDays);
691
+ }
692
+ } catch {
693
+ // Cleanup failures should not block session lifecycle events.
694
+ }
695
+ };
696
+
697
+ const resetSessionState = (ctx: ExtensionContext, recovering: boolean) => {
698
+ state.baseCwd = ctx.cwd;
699
+ goalTurnId = 0;
700
+ state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
701
+ state.parentSessionFile = ctx.sessionManager.getSessionFile();
702
+ state.subagentSpawns = {
703
+ sessionId: state.currentSessionId,
704
+ count: 0,
705
+ configuredLimit: resolveMaxSubagentSpawnsPerSession(config.maxSubagentSpawnsPerSession) ?? null,
706
+ granted: 0,
707
+ grantHistory: [],
708
+ };
709
+ // Set PI_SUBAGENT_PARENT_SESSION for permission-system forwarding.
710
+ // Only set in the root session (the interactive UI session), not in
711
+ // child subagent processes — children inherit the parent's value
712
+ // through the process environment at spawn time and must not overwrite
713
+ // it with their own session identity.
714
+ if (!process.env[SUBAGENT_CHILD_ENV]) {
715
+ const sessionId = ctx.sessionManager.getSessionId();
716
+ if (sessionId) {
717
+ process.env[SUBAGENT_PARENT_SESSION_ENV] = sessionId;
718
+ }
719
+ }
720
+ state.lastUiContext = ctx;
721
+ cleanupSessionArtifacts(ctx);
722
+ state.foregroundControls.clear();
723
+ state.lastForegroundControlId = null;
724
+ resetJobs(ctx);
725
+ restoreActiveJobs(ctx);
726
+ scheduledRunManager.bindSession(ctx);
727
+ restoreSlashFinalSnapshots(ctx.sessionManager.getEntries());
728
+ waitSubscriptionManager.restore();
729
+ startResultWatcher();
730
+ primeExistingResults({ triggerTurn: !recovering });
731
+ fleetStatus?.setContext(ctx);
732
+ };
733
+
734
+ pi.on("agent_start", () => {
735
+ herdrStatusBridge.agentStarted();
736
+ });
737
+
738
+ pi.on("session_compact", () => {
739
+ const hasActiveAsyncWork = [...state.asyncJobs.values()].some((job) => job.status === "queued" || job.status === "running");
740
+ if (!hasActiveAsyncWork || state.lastUiContext?.hasUI !== true) return;
741
+ pi.sendMessage(
742
+ {
743
+ customType: "subagent-compaction-resume",
744
+ content: "Compaction is complete. Resume the parent task now; background subagent results will arrive separately when ready.",
745
+ display: false,
746
+ },
747
+ { triggerTurn: true },
748
+ );
749
+ });
750
+
751
+ pi.on("session_start", (event, ctx) => {
752
+ const recovering = event.reason === "startup" || event.reason === "reload" || event.reason === "resume";
753
+ resetSessionState(ctx, recovering);
754
+ herdrStatusBridge.sessionStarted({
755
+ hasUI: ctx.hasUI === true,
756
+ runs: activeHerdrRuns(),
757
+ });
758
+ rpcBridge.emitReady(ctx);
759
+ supervisorChannel.start();
760
+ });
761
+
762
+ pi.on("session_shutdown", async () => {
763
+ stopResultWatcher();
764
+ state.currentSessionId = null;
765
+ state.parentSessionFile = null;
766
+ completionNotifier.dispose();
767
+ delete process.env[SUBAGENT_PARENT_SESSION_ENV];
768
+ for (const unsubscribe of eventUnsubscribes) {
769
+ try {
770
+ unsubscribe();
771
+ } catch {
772
+ // Best effort cleanup during shutdown.
773
+ }
774
+ }
775
+ if (globalStore[eventUnsubscribeStoreKey] === eventUnsubscribes) {
776
+ delete globalStore[eventUnsubscribeStoreKey];
777
+ }
778
+ scheduledRunManager.stop();
779
+ if (state.poller) clearInterval(state.poller);
780
+ state.poller = null;
781
+ for (const timer of state.cleanupTimers.values()) {
782
+ clearTimeout(timer);
783
+ }
784
+ state.cleanupTimers.clear();
785
+ state.asyncJobs.clear();
786
+ clearSlashSnapshots();
787
+ slashBridge.cancelAll();
788
+ slashBridge.dispose();
789
+ promptTemplateBridge.cancelAll();
790
+ promptTemplateBridge.dispose();
791
+ supervisorChannel.dispose();
792
+ fleetStatus?.dispose();
793
+ if (globalStore[runtimeCleanupStoreKey] === runtimeCleanup) {
794
+ delete globalStore[runtimeCleanupStoreKey];
795
+ }
796
+ try {
797
+ if (state.lastUiContext?.hasUI) {
798
+ state.lastUiContext.ui.setWidget(WIDGET_KEY, undefined);
799
+ }
800
+ } catch (error) {
801
+ if (!isStaleExtensionContextError(error)) throw error;
802
+ }
803
+ await herdrStatusBridge.flush();
804
+ });
805
+ }