@vicary/pi-subagents 0.84.0-1 → 0.85.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 (204) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-F4ASL6OV.js → chunk-7MAE3DJV.js} +1 -1
  5. package/bundle/{chunk-4MDR6V46.js → chunk-A7VJ5XXE.js} +190 -1177
  6. package/bundle/{chunk-LGLEH7B6.js → chunk-B3OOJJA6.js} +231 -182
  7. package/bundle/{chunk-4E7BKDTX.js → chunk-CS4O36CZ.js} +11 -156
  8. package/bundle/{chunk-G2Z6ZH26.js → chunk-GCSLVFCX.js} +1 -1
  9. package/bundle/{chunk-2S4K53MV.js → chunk-H2NLFTC5.js} +1 -1
  10. package/bundle/{chunk-T44HVL5U.js → chunk-HFTBF7SG.js} +2 -1
  11. package/bundle/{chunk-F4AMYP5N.js → chunk-HS4WPO6B.js} +15 -6
  12. package/bundle/chunk-HXRB42AF.js +108 -0
  13. package/bundle/{chunk-4NIY3BE6.js → chunk-JHBQ7N2L.js} +2 -2
  14. package/bundle/{chunk-HKJLSMXV.js → chunk-JO67XSKD.js} +59 -27
  15. package/bundle/{chunk-C5P5CHYK.js → chunk-KDMFBYFM.js} +1 -1
  16. package/bundle/{chunk-V2BZYLEP.js → chunk-KEY3UQMQ.js} +7 -2
  17. package/bundle/{chunk-NENDSQUY.js → chunk-KZ34KQQH.js} +9 -6
  18. package/bundle/{chunk-AKOIVLA5.js → chunk-L2ENOFVZ.js} +76 -58
  19. package/bundle/{chunk-CGN2TVE7.js → chunk-LGMILZNE.js} +322 -18
  20. package/bundle/{chunk-L3WFKBEI.js → chunk-LTPH2DXH.js} +247 -153
  21. package/bundle/{chunk-2D52JFLF.js → chunk-N7B2KD74.js} +41 -117
  22. package/bundle/{chunk-PV63UFUR.js → chunk-O7CPL6H4.js} +183 -28
  23. package/bundle/{chunk-D3JAFGMO.js → chunk-PHZP3KHB.js} +1 -1
  24. package/bundle/{chunk-2DHZTCOL.js → chunk-PVIVCDG2.js} +2 -2
  25. package/bundle/{chunk-LFDBD4PW.js → chunk-QO75KJBT.js} +2 -2
  26. package/bundle/{chunk-67ENPDDA.js → chunk-QZL2ZZPM.js} +22 -11
  27. package/bundle/{chunk-PALJGGYC.js → chunk-RV5OGHLO.js} +6 -3
  28. package/bundle/chunk-T5V5BRCL.js +1067 -0
  29. package/bundle/{chunk-LNRJCP2Y.js → chunk-UX4SCV5N.js} +337 -207
  30. package/bundle/{chunk-TE4LHYHN.js → chunk-VEZMZDTW.js} +209 -93
  31. package/bundle/{chunk-X2MXCSA5.js → chunk-YZBCREP5.js} +310 -101
  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 +8 -8
  36. package/bundle/project-panes.js +3 -3
  37. package/docs/agents.md +17 -2
  38. package/docs/configuration.md +2 -2
  39. package/docs/extension-api.md +16 -1
  40. package/docs/workflows.md +30 -2
  41. package/package.json +2 -2
  42. package/src/agents/agent-management.js +27 -11
  43. package/src/agents/agent-memory.d.ts +1 -4
  44. package/src/agents/agent-memory.js +1 -4
  45. package/src/agents/agents.d.ts +1 -3
  46. package/src/agents/agents.js +7 -6
  47. package/src/agents/frontmatter.js +1 -8
  48. package/src/agents/global-npm-root.d.ts +1 -0
  49. package/src/agents/global-npm-root.js +11 -3
  50. package/src/agents/skills.d.ts +0 -3
  51. package/src/agents/skills.js +0 -3
  52. package/src/extension/config.js +7 -1
  53. package/src/extension/herdr-pi-bridge.js +10 -2
  54. package/src/extension/index.d.ts +0 -13
  55. package/src/extension/index.js +43 -32
  56. package/src/extension/public-execution.d.ts +1 -0
  57. package/src/extension/public-execution.js +4 -0
  58. package/src/extension/reply-workflow-script.js +24 -4
  59. package/src/extension/schemas.d.ts +8 -3
  60. package/src/extension/schemas.js +5 -3
  61. package/src/extension/session-switch.d.ts +25 -0
  62. package/src/extension/session-switch.js +138 -0
  63. package/src/extension/subagent-guide.d.ts +1 -1
  64. package/src/extension/subagent-guide.js +1 -1
  65. package/src/extension/subagent-launch-tool.d.ts +25 -0
  66. package/src/extension/subagent-launch-tool.js +48 -0
  67. package/src/extension/tool-activation.js +25 -11
  68. package/src/extension/tool-description.js +6 -0
  69. package/src/inspectors/herdr/actions.d.ts +0 -1
  70. package/src/inspectors/herdr/actions.js +0 -1
  71. package/src/inspectors/session-roots-codec.d.ts +0 -1
  72. package/src/inspectors/session-roots-codec.js +0 -1
  73. package/src/inspectors/tmux/actions.d.ts +0 -1
  74. package/src/inspectors/tmux/actions.js +0 -1
  75. package/src/integrations/herdr-status.js +3 -8
  76. package/src/intercom/native-supervisor-channel.js +65 -9
  77. package/src/runs/background/async-execution.d.ts +5 -9
  78. package/src/runs/background/async-execution.js +62 -27
  79. package/src/runs/background/async-job-tracker.js +12 -0
  80. package/src/runs/background/async-resume.d.ts +2 -1
  81. package/src/runs/background/async-resume.js +112 -39
  82. package/src/runs/background/async-retention.js +6 -1
  83. package/src/runs/background/auto-drain.js +2 -1
  84. package/src/runs/background/boot-id.d.ts +1 -3
  85. package/src/runs/background/boot-id.js +1 -3
  86. package/src/runs/background/completion-batcher.d.ts +3 -4
  87. package/src/runs/background/completion-batcher.js +2 -3
  88. package/src/runs/background/control-channel.d.ts +0 -6
  89. package/src/runs/background/control-channel.js +0 -6
  90. package/src/runs/background/fleet-view.js +2 -3
  91. package/src/runs/background/notify.d.ts +0 -2
  92. package/src/runs/background/notify.js +0 -2
  93. package/src/runs/background/result-watcher.d.ts +1 -0
  94. package/src/runs/background/result-watcher.js +59 -29
  95. package/src/runs/background/resume-guidance.js +4 -2
  96. package/src/runs/background/retained-children.js +2 -1
  97. package/src/runs/background/run-child-session.d.ts +0 -1
  98. package/src/runs/background/run-child-session.js +1 -1
  99. package/src/runs/background/run-status.js +4 -3
  100. package/src/runs/background/scheduled-runs.d.ts +3 -1
  101. package/src/runs/background/scheduled-runs.js +13 -16
  102. package/src/runs/background/subagent-runner.d.ts +2 -4
  103. package/src/runs/background/subagent-runner.js +9 -6
  104. package/src/runs/background/subagent-wait.js +12 -15
  105. package/src/runs/background/wait-config.d.ts +2 -0
  106. package/src/runs/background/wait-config.js +17 -3
  107. package/src/runs/background/wait-tool.js +4 -2
  108. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  109. package/src/runs/background/workflow-terminal-proof.js +0 -1
  110. package/src/runs/foreground/execution.d.ts +0 -3
  111. package/src/runs/foreground/execution.js +17 -9
  112. package/src/runs/foreground/subagent-executor.d.ts +3 -2
  113. package/src/runs/foreground/subagent-executor.js +107 -26
  114. package/src/runs/shared/child-commands.js +15 -2
  115. package/src/runs/shared/child-hooks.d.ts +1 -7
  116. package/src/runs/shared/child-hooks.js +13 -5
  117. package/src/runs/shared/child-launch.js +6 -2
  118. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  119. package/src/runs/shared/child-session.d.ts +1 -1
  120. package/src/runs/shared/child-session.js +21 -2
  121. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  122. package/src/runs/shared/child-tool-plan.js +0 -1
  123. package/src/runs/shared/claude-code-adapter.js +11 -0
  124. package/src/runs/shared/external-cli-runner.js +26 -6
  125. package/src/runs/shared/herdr-connection.js +2 -1
  126. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  127. package/src/runs/shared/herdr-pane-host.js +17 -1
  128. package/src/runs/shared/herdr-placed-run.js +48 -22
  129. package/src/runs/shared/lane-metadata.d.ts +0 -1
  130. package/src/runs/shared/lane-metadata.js +0 -1
  131. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  132. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  133. package/src/runs/shared/model-resolution.d.ts +2 -2
  134. package/src/runs/shared/model-resolution.js +7 -1
  135. package/src/runs/shared/model-scope.d.ts +1 -5
  136. package/src/runs/shared/model-scope.js +1 -5
  137. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  138. package/src/runs/shared/mutation-evidence.js +52 -7
  139. package/src/runs/shared/nested-events.d.ts +1 -0
  140. package/src/runs/shared/nested-events.js +1 -1
  141. package/src/runs/shared/parallel-utils.d.ts +0 -1
  142. package/src/runs/shared/permissions.js +5 -3
  143. package/src/runs/shared/placement-host.d.ts +5 -1
  144. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  145. package/src/runs/shared/rex-pane-host.js +0 -2
  146. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  147. package/src/runs/shared/run-launch-folder.js +21 -0
  148. package/src/runs/shared/runner-launcher.d.ts +12 -1
  149. package/src/runs/shared/runner-launcher.js +16 -0
  150. package/src/runs/shared/single-output.d.ts +3 -3
  151. package/src/runs/shared/single-output.js +5 -3
  152. package/src/runs/shared/structured-output.d.ts +8 -0
  153. package/src/runs/shared/structured-output.js +30 -2
  154. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  155. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  156. package/src/runs/shared/tool-timeout.js +2 -1
  157. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  158. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  159. package/src/runs/shared/worktree.d.ts +3 -0
  160. package/src/runs/shared/worktree.js +20 -0
  161. package/src/shared/capacity-resilient-json.d.ts +1 -1
  162. package/src/shared/child-cache-retention.d.ts +1 -2
  163. package/src/shared/child-cache-retention.js +1 -2
  164. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  165. package/src/shared/fleet-transcript-reader.js +333 -0
  166. package/src/shared/formatters.d.ts +0 -18
  167. package/src/shared/formatters.js +0 -18
  168. package/src/shared/session-succession.d.ts +16 -1
  169. package/src/shared/session-succession.js +41 -2
  170. package/src/shared/session-warnings.d.ts +7 -0
  171. package/src/shared/session-warnings.js +26 -0
  172. package/src/shared/settings.d.ts +0 -23
  173. package/src/shared/settings.js +3 -35
  174. package/src/shared/types.d.ts +28 -11
  175. package/src/shared/types.js +0 -12
  176. package/src/shared/utils.d.ts +0 -14
  177. package/src/shared/utils.js +0 -22
  178. package/src/shared/wait-tool-name.d.ts +8 -0
  179. package/src/shared/wait-tool-name.js +13 -0
  180. package/src/slash/slash-commands.js +2 -1
  181. package/src/slash/subagent-cost.d.ts +3 -2
  182. package/src/slash/subagent-cost.js +22 -3
  183. package/src/slash/subagents-admin.js +0 -1
  184. package/src/tui/fleet-status.d.ts +0 -5
  185. package/src/tui/fleet-status.js +4 -24
  186. package/src/tui/fleet-transcript.d.ts +1 -44
  187. package/src/tui/fleet-transcript.js +1 -327
  188. package/src/tui/fleet.js +6 -4
  189. package/src/tui/render.d.ts +0 -9
  190. package/src/tui/render.js +81 -47
  191. package/src/tui/subagent-messages.js +3 -2
  192. package/src/watchdog/register-child.d.ts +2 -3
  193. package/src/watchdog/register-child.js +2 -3
  194. package/src/watchdog/turn-delta.js +2 -1
  195. package/src/workflows/scripted-workflow.js +241 -20
  196. package/src/workflows/workflow-launch-record.d.ts +15 -6
  197. package/src/workflows/workflow-launch-record.js +30 -12
  198. package/src/workflows/workflow-resume-claim.js +2 -2
  199. package/src/workflows/workflow-resume.d.ts +1 -1
  200. package/src/workflows/workflow-resume.js +11 -8
  201. package/src/workflows/workflow-script-worker.d.ts +13 -0
  202. package/src/workflows/workflow-script-worker.js +79 -0
  203. package/workflow-script-process.cjs +36 -0
  204. package/workflow-script-worker.cjs +4 -1
@@ -0,0 +1,138 @@
1
+ import { isActiveAsyncState } from "../runs/background/active-run-index.js";
2
+ import { listAsyncRuns } from "../runs/background/async-status.js";
3
+ import { reconcileNestedAsyncDescendants } from "../runs/background/stale-run-reconciler.js";
4
+ import { ownsRun } from "../runs/shared/run-ownership.js";
5
+ import { collectNestedRuns, projectNestedEvents } from "../runs/shared/nested-events.js";
6
+ import { keepSessionWork, releaseSessionWork } from "../shared/session-succession.js";
7
+ import { readStatus } from "../shared/utils.js";
8
+ const STAY = "Stay here";
9
+ const TAKE = "Switch and take the work";
10
+ const LEAVE = "Switch and leave the work here";
11
+ const RPC_PROMPT_TIMEOUT_MS = 60_000;
12
+ /**
13
+ * Asks what happens to this session's outstanding background work when a UI session switches away. Without a UI or
14
+ * outstanding work the switch proceeds and the next session inherits the work. The prompt never enters model history.
15
+ */
16
+ export function createSessionSwitchGuard(deps) {
17
+ let leave;
18
+ let checking = false;
19
+ const lifetime = new AbortController();
20
+ const activeRunCount = (sessionId) => {
21
+ const runs = new Set(listAsyncRuns(deps.asyncDirRoot, {
22
+ sessionId, states: ["queued", "running"], resultsDir: deps.resultsDir, includeNested: false,
23
+ }).map((run) => run.id));
24
+ // Include launch receipts whose active-index marker has not landed yet.
25
+ for (const job of deps.state.asyncJobs.values()) {
26
+ if (runs.has(job.asyncId) || !ownsRun(sessionId, job.sessionId) || !isActiveAsyncState(job.status))
27
+ continue;
28
+ let active = true;
29
+ // An unreadable status could be a live run, so it counts as outstanding instead of refusing every switch.
30
+ try {
31
+ const status = readStatus(job.asyncDir);
32
+ active = !status || isActiveAsyncState(status.state);
33
+ }
34
+ catch { /* active */ }
35
+ if (active)
36
+ runs.add(job.asyncId);
37
+ }
38
+ for (const id of deps.state.workflowControllers?.keys() ?? [])
39
+ runs.add(id);
40
+ return runs.size;
41
+ };
42
+ const hasNestedWork = (sessionId) => {
43
+ const routes = new Map();
44
+ for (const job of deps.state.asyncJobs.values()) {
45
+ if (!ownsRun(sessionId, job.sessionId))
46
+ continue;
47
+ if (job.nestedRoute)
48
+ routes.set(job.nestedRoute.rootRunId, job.nestedRoute);
49
+ else if (collectNestedRuns(job.nestedChildren).some((run) => isActiveAsyncState(run.state)))
50
+ return true;
51
+ }
52
+ for (const control of deps.state.foregroundControls.values()) {
53
+ if (control.sessionId && !ownsRun(sessionId, control.sessionId))
54
+ continue;
55
+ if (control.nestedRoute)
56
+ routes.set(control.nestedRoute.rootRunId, control.nestedRoute);
57
+ }
58
+ for (const route of deps.state.retainedForegroundNestedRoutes?.values() ?? [])
59
+ routes.set(route.rootRunId, route);
60
+ if (deps.state.retainedNestedLookupRoutes?.sessionId === sessionId) {
61
+ for (const route of deps.state.retainedNestedLookupRoutes.routes.values())
62
+ routes.set(route.rootRunId, route);
63
+ }
64
+ return [...routes.values()].some((route) => {
65
+ reconcileNestedAsyncDescendants(route, { resultsDir: deps.resultsDir });
66
+ return collectNestedRuns(projectNestedEvents(route).children).some((run) => isActiveAsyncState(run.state));
67
+ });
68
+ };
69
+ return {
70
+ async beforeSwitch(reason, ctx) {
71
+ if (lifetime.signal.aborted || checking)
72
+ return { cancel: true };
73
+ leave = undefined; // A choice belongs to this switch attempt only.
74
+ if (!ctx.hasUI)
75
+ return;
76
+ checking = true;
77
+ try {
78
+ const sessionId = deps.state.currentSessionId;
79
+ if (!sessionId)
80
+ throw new Error("The current session identity is unavailable.");
81
+ const runs = activeRunCount(sessionId);
82
+ const nested = hasNestedWork(sessionId);
83
+ const results = deps.hasPendingResults();
84
+ const questions = deps.hasPendingSupervisorRequest();
85
+ if (runs === 0 && !nested && !results && !questions)
86
+ return;
87
+ const title = [
88
+ "pi-subagents: switch sessions?",
89
+ "",
90
+ "Background subagent work in this session:",
91
+ ...(runs > 0 ? [` ${runs} run${runs === 1 ? "" : "s"} queued or running`] : []),
92
+ ...(nested ? [" Nested subagents still running"] : []),
93
+ ...(results ? [" Undelivered results"] : []),
94
+ ...(questions ? [" Questions awaiting a reply"] : []),
95
+ ].join("\n");
96
+ const choice = await ctx.ui.select(title, [STAY, TAKE, LEAVE], { signal: lifetime.signal, timeout: ctx.mode === "rpc" ? RPC_PROMPT_TIMEOUT_MS : undefined });
97
+ if (lifetime.signal.aborted || deps.state.currentSessionId !== sessionId)
98
+ return { cancel: true };
99
+ if (choice === TAKE)
100
+ return;
101
+ if (choice === LEAVE) {
102
+ leave = { sessionId, reason };
103
+ return;
104
+ }
105
+ return { cancel: true };
106
+ }
107
+ catch (error) {
108
+ const message = error instanceof Error ? error.message : String(error);
109
+ // Pi ignores thrown switch hooks; always return cancel, even if the UI is stale.
110
+ try {
111
+ if (!lifetime.signal.aborted)
112
+ ctx.ui.notify(`Session switch cancelled: ${message}`, "warning");
113
+ }
114
+ catch { /* The context may already be stale. */ }
115
+ return { cancel: true };
116
+ }
117
+ finally {
118
+ checking = false;
119
+ }
120
+ },
121
+ // Recorded only once the switch commits, so a switch another extension cancels keeps the default handoff.
122
+ sessionShutdown(event) {
123
+ const left = leave;
124
+ leave = undefined;
125
+ const sessionId = deps.state.currentSessionId;
126
+ if (!sessionId)
127
+ return;
128
+ if (left && left.sessionId === sessionId && left.reason === event.reason)
129
+ keepSessionWork(sessionId);
130
+ else
131
+ releaseSessionWork(sessionId);
132
+ },
133
+ dispose() {
134
+ leave = undefined;
135
+ lifetime.abort();
136
+ },
137
+ };
138
+ }
@@ -1,4 +1,4 @@
1
1
  export declare const SUBAGENT_GUIDE_TOPICS: readonly ["overview", "workflows", "agents", "missions", "observability", "tool-reference", "configuration", "models", "watchdog", "extension-api", "council"];
2
2
  export type SubagentGuideTopic = (typeof SUBAGENT_GUIDE_TOPICS)[number];
3
- /** Reads a guide topic. Docs-backed topics return their intro and table of contents; `topic/section` returns one section. */
3
+ /** Docs-backed topics return their intro and table of contents; `topic/section` returns one section. */
4
4
  export declare function readSubagentGuide(topic?: string, root?: string): string;
@@ -88,7 +88,7 @@ function readGuideFiles(topic, files, root) {
88
88
  throw new Error(`Failed to read packaged subagents guide '${topic}': ${message}`, { cause: error instanceof Error ? error : undefined });
89
89
  }
90
90
  }
91
- /** Reads a guide topic. Docs-backed topics return their intro and table of contents; `topic/section` returns one section. */
91
+ /** Docs-backed topics return their intro and table of contents; `topic/section` returns one section. */
92
92
  export function readSubagentGuide(topic = "overview", root = packageRoot) {
93
93
  const separator = topic.indexOf("/");
94
94
  const name = separator === -1 ? topic : topic.slice(0, separator);
@@ -0,0 +1,25 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { Type, type Static } from "typebox";
3
+ declare const parameters: Type.TObject<{
4
+ workflowRunId: Type.TString;
5
+ key: Type.TString;
6
+ agent: Type.TOptional<Type.TString>;
7
+ task: Type.TOptional<Type.TString>;
8
+ cwd: Type.TOptional<Type.TString>;
9
+ model: Type.TOptional<Type.TString>;
10
+ async: Type.TOptional<Type.TBoolean>;
11
+ worktree: Type.TOptional<Type.TBoolean>;
12
+ resume: Type.TOptional<Type.TString>;
13
+ commands: Type.TOptional<Type.TArray<Type.TObject<{
14
+ command: Type.TString;
15
+ cwd: Type.TOptional<Type.TString>;
16
+ env: Type.TOptional<Type.TRecord<"^.*$", Type.TString>>;
17
+ }>>>;
18
+ output: Type.TOptional<Type.TString>;
19
+ }>;
20
+ export type SubagentLaunchArgs = Static<typeof parameters>;
21
+ /** Not declared to the model, so the system prompt and tool list stay unchanged. */
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>;
25
+ export {};
@@ -0,0 +1,48 @@
1
+ import { Type } from "typebox";
2
+ const SUBAGENT_LAUNCH_TOOL = "subagent_launch";
3
+ const parameters = Type.Object({
4
+ workflowRunId: Type.String(),
5
+ key: Type.String(),
6
+ agent: Type.Optional(Type.String()),
7
+ task: Type.Optional(Type.String()),
8
+ cwd: Type.Optional(Type.String()),
9
+ model: Type.Optional(Type.String()),
10
+ async: Type.Optional(Type.Boolean()),
11
+ worktree: Type.Optional(Type.Boolean()),
12
+ resume: Type.Optional(Type.String()),
13
+ commands: Type.Optional(Type.Array(Type.Object({
14
+ command: Type.String(),
15
+ cwd: Type.Optional(Type.String()),
16
+ env: Type.Optional(Type.Record(Type.String(), Type.String())),
17
+ }))),
18
+ output: Type.Optional(Type.String()),
19
+ });
20
+ /** Not declared to the model, so the system prompt and tool list stay unchanged. */
21
+ export function registerSubagentLaunchTool(pi) {
22
+ pi.registerTool({
23
+ name: SUBAGENT_LAUNCH_TOOL,
24
+ label: "Subagent launch",
25
+ description: "A workflow is about to start this subagent. Blocking this call stops that child from starting.",
26
+ parameters,
27
+ exposure: "deferred",
28
+ async execute() {
29
+ return { content: [{ type: "text", text: "Records approval for a workflow child launch; it starts nothing itself." }], details: {} };
30
+ },
31
+ });
32
+ }
33
+ /** Offers a workflow child start to the session's `tool_call` handlers; returns the refusal, if any. */
34
+ export async function approveWorkflowChildLaunch(ctx, describe, signal) {
35
+ // Starts with no tool call behind them (schedule ticks, auto-resume, RPC) have no executeTool, and a tool
36
+ // allowlist that leaves the tool out unregisters it: no handler could see the call in either case.
37
+ if (!("executeTool" in ctx))
38
+ return undefined;
39
+ const toolCtx = ctx;
40
+ if (!toolCtx.tools.some((tool) => tool.name === SUBAGENT_LAUNCH_TOOL))
41
+ return undefined;
42
+ const args = describe();
43
+ const outcome = await toolCtx.executeTool(SUBAGENT_LAUNCH_TOOL, args, { signal });
44
+ if (!outcome.isError)
45
+ return undefined;
46
+ 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}` : "."}`;
48
+ }
@@ -2,28 +2,35 @@ import { Type } from "typebox";
2
2
  import { MODEL_ONLY_TOOL } from "../shared/extension-context.js";
3
3
  import { registerPinnedTool } from "./declaration-pinning.js";
4
4
  import { listBackgroundWorkProviders } from "../api/background-work.js";
5
+ import { DEFAULT_WAIT_TOOL_NAME, waitToolName } from "../shared/wait-tool-name.js";
5
6
  import { CONTACT_SUPERVISOR_TOOL_NAME as SUPERVISOR_NAME, NATIVE_SUPERVISOR_TOOL_NAME as PARENT_SUPERVISOR_NAME } from "../intercom/native-supervisor-channel.js";
6
7
  const LOADER_NAME = "subagents_enable";
7
8
  const SUBAGENT_NAME = "subagent";
8
- // Declared with subagent, or once background-work providers exist (they report work only bg_wait reads).
9
- const WAIT_NAME = "bg_wait";
9
+ // The wait tool (bg_wait unless config.waitTool.name renames it) is declared with subagent, or once
10
+ // background-work providers exist (they report work only the wait tool reads).
10
11
  // SUPERVISOR_NAME is declared with subagent: a fork launched through it then declares exactly this session's tools.
11
12
  // PARENT_SUPERVISOR_NAME (answering this session's children) is declared with subagent too, unless the session already
12
13
  // declared it: a changed tool set would miss the prompt cache. The channel declares it when a child request arrives.
13
- const UNLOAD_SENTINELS = new Set([LOADER_NAME, SUBAGENT_NAME, WAIT_NAME]);
14
+ const isUnloadSentinel = (name) => name === LOADER_NAME || name === SUBAGENT_NAME || name === waitToolName();
15
+ // Every bg_wait pi-subagents has registered (since 0.61.0) takes nonBlocking and stopOnAttention; another extension's
16
+ // bg_wait (@99percentpeople/pi-background-tasks takes id and timeout) does not.
17
+ function isOwnWaitDefinition(tool) {
18
+ const properties = tool.parameters?.properties;
19
+ return typeof properties === "object" && properties !== null && Object.hasOwn(properties, "nonBlocking") && Object.hasOwn(properties, "stopOnAttention");
20
+ }
14
21
  function hasNativeToolSelection(messages) {
15
22
  return messages.some((message) => message.role === "system"
16
23
  && (Object.hasOwn(message, "toolsAdded") || Object.hasOwn(message, "toolsRemoved")));
17
24
  }
18
25
  function setSelection(pi, includeSubagent, includeLoader, includeWait, restore = [], keepParentSupervisor = false) {
19
26
  const next = [...pi.getActiveTools(), ...restore].filter((name) => (includeSubagent || (name !== SUBAGENT_NAME && name !== SUPERVISOR_NAME && (keepParentSupervisor || name !== PARENT_SUPERVISOR_NAME)))
20
- && (includeLoader || name !== LOADER_NAME) && (includeWait || name !== WAIT_NAME));
27
+ && (includeLoader || name !== LOADER_NAME) && (includeWait || name !== waitToolName()));
21
28
  if (includeSubagent)
22
29
  next.push(SUBAGENT_NAME, SUPERVISOR_NAME, PARENT_SUPERVISOR_NAME);
23
30
  if (includeLoader)
24
31
  next.push(LOADER_NAME);
25
32
  if (includeWait)
26
- next.push(WAIT_NAME);
33
+ next.push(waitToolName());
27
34
  pi.setActiveTools([...new Set(next)]);
28
35
  }
29
36
  // Mirrors pi-ai's per-API transcript handling: without these flags, a mid-conversation tool change
@@ -60,6 +67,8 @@ function applyRecordedSelection(pi, ctx, mode, replyOwed) {
60
67
  const declaredSentinels = new Set();
61
68
  // Tools the surviving transcript says something about: an addition, or a removal that is not an unload.
62
69
  const evidenced = new Set();
70
+ // Whether the latest bg_wait declaration was this extension's wait tool, from before a waitTool.name rename.
71
+ let legacyWaitIsOwn = false;
63
72
  for (const message of messages) {
64
73
  if (message.role !== "system")
65
74
  continue;
@@ -67,12 +76,12 @@ function applyRecordedSelection(pi, ctx, mode, replyOwed) {
67
76
  // While this extension is loaded, the loader, subagent or bg_wait stays declared, so a removal of declared
68
77
  // sentinels that leaves none of them is that unload, not a choice, and the selection from before it stands.
69
78
  // Pi removes only declared tools, so a removal naming an undeclared sentinel is a choice.
70
- const removedSentinels = (message.toolsRemoved ?? []).filter((tool) => UNLOAD_SENTINELS.has(tool.name));
79
+ const removedSentinels = (message.toolsRemoved ?? []).filter((tool) => isUnloadSentinel(tool.name));
71
80
  const allDeclared = removedSentinels.every((tool) => declaredSentinels.has(tool.name));
72
81
  for (const tool of message.toolsRemoved ?? [])
73
82
  declaredSentinels.delete(tool.name);
74
83
  for (const tool of message.toolsAdded ?? [])
75
- if (UNLOAD_SENTINELS.has(tool.name))
84
+ if (isUnloadSentinel(tool.name))
76
85
  declaredSentinels.add(tool.name);
77
86
  const unloaded = removedSentinels.length > 0 && allDeclared && declaredSentinels.size === 0;
78
87
  for (const tool of message.toolsRemoved ?? []) {
@@ -86,6 +95,8 @@ function applyRecordedSelection(pi, ctx, mode, replyOwed) {
86
95
  for (const tool of message.toolsAdded ?? []) {
87
96
  recorded.add(tool.name);
88
97
  evidenced.add(tool.name);
98
+ if (tool.name === DEFAULT_WAIT_TOOL_NAME)
99
+ legacyWaitIsOwn = isOwnWaitDefinition(tool);
89
100
  }
90
101
  }
91
102
  // The loader and subagent record one activation state (cold, warm, eager); bg_wait and subagent_supervisor
@@ -101,17 +112,20 @@ function applyRecordedSelection(pi, ctx, mode, replyOwed) {
101
112
  // A new process restores the transcript's tools, where the unload left this extension's tools inactive; only
102
113
  // /reload re-adds them. Restoring them keeps a sentinel declared, so a later unload is recognised too. Tools of
103
114
  // other extensions, and tools excluded for this process (not registered, so not in getAllTools), stay as they are.
115
+ // A transcript from before a waitTool.name rename records the wait tool as bg_wait; that record stands for the
116
+ // renamed tool while the transcript says nothing about the new name and its latest bg_wait was this extension's.
117
+ const waitRecord = waitToolName() !== DEFAULT_WAIT_TOOL_NAME && !evidenced.has(waitToolName()) && legacyWaitIsOwn ? DEFAULT_WAIT_TOOL_NAME : waitToolName();
104
118
  const source = unloadedNames.size > 0 ? available.find((tool) => tool.name === LOADER_NAME)?.sourceInfo.path : undefined;
105
119
  const restore = source === undefined ? [] : available
106
120
  .filter((tool) => unloadedNames.has(tool.name) && recorded.has(tool.name) && tool.sourceInfo.path === source)
107
121
  .map((tool) => tool.name);
108
- setSelection(pi, recorded.has(SUBAGENT_NAME) || startsEager, loaderSelected, recorded.has(WAIT_NAME) || (!evidenced.has(WAIT_NAME) && startsEager), replyOwed ? [...restore, PARENT_SUPERVISOR_NAME] : restore, replyOwed || recorded.has(PARENT_SUPERVISOR_NAME));
122
+ setSelection(pi, recorded.has(SUBAGENT_NAME) || startsEager, loaderSelected, recorded.has(waitRecord) || (!evidenced.has(waitRecord) && startsEager), replyOwed ? [...restore, PARENT_SUPERVISOR_NAME] : restore, replyOwed || recorded.has(PARENT_SUPERVISOR_NAME));
109
123
  return loaderSelected;
110
124
  }
111
125
  // "auto" goes eager only for an empty session; any history keeps the tools it already sent.
112
126
  const eager = mode === "auto" && messages.length === 0 && !addsToolsWithoutCheckpoint(ctx.model);
113
127
  const kept = (name) => eager || (messages.length > 0 && pi.getActiveTools().includes(name));
114
- setSelection(pi, kept(SUBAGENT_NAME), !eager, kept(WAIT_NAME), replyOwed ? [PARENT_SUPERVISOR_NAME] : [], replyOwed || messages.length > 0);
128
+ setSelection(pi, kept(SUBAGENT_NAME), !eager, kept(waitToolName()), replyOwed ? [PARENT_SUPERVISOR_NAME] : [], replyOwed || messages.length > 0);
115
129
  return !eager;
116
130
  }
117
131
  export function registerSubagentToolActivation(pi, options) {
@@ -170,8 +184,8 @@ export function registerSubagentToolActivation(pi, options) {
170
184
  return;
171
185
  // Another extension's background-work provider reports work only bg_wait can wait for, so a session with one
172
186
  // declares bg_wait without enabling subagent, including when the provider registered after session start.
173
- const providedWait = available.some((tool) => tool.name === WAIT_NAME) && listBackgroundWorkProviders().length > 0;
174
- const names = [...(loaderSelected ? [LOADER_NAME] : []), ...(providedWait ? [WAIT_NAME] : [])];
187
+ const providedWait = available.some((tool) => tool.name === waitToolName()) && listBackgroundWorkProviders().length > 0;
188
+ const names = [...(loaderSelected ? [LOADER_NAME] : []), ...(providedWait ? [waitToolName()] : [])];
175
189
  if (names.length === 0)
176
190
  return;
177
191
  const selectedTools = event.systemPromptOptions.selectedTools ??= [...pi.getActiveTools()];
@@ -2,6 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { getAgentDir, getProjectConfigDir } from "../shared/utils.js";
4
4
  import { resolveDisabledFeatureSurface } from "../shared/disabled-features.js";
5
+ import { DEFAULT_WAIT_TOOL_NAME, waitToolName } from "../shared/wait-tool-name.js";
5
6
  const CUSTOM_TOOL_DESCRIPTION_FILE = "subagent-tool-description.md";
6
7
  const CUSTOM_TOOL_DESCRIPTION_MAX_BYTES = 50 * 1024;
7
8
  function featureText(disabled) {
@@ -153,6 +154,11 @@ function withMandatorySafetyGuidance(description) {
153
154
  : SUBAGENT_SAFETY_GUIDANCE;
154
155
  }
155
156
  export function buildSubagentToolDescription(config = {}, options) {
157
+ const description = describeSubagentTool(config, options);
158
+ const name = waitToolName();
159
+ return name === DEFAULT_WAIT_TOOL_NAME ? description : description.replace(/\bbg_wait\b/g, name);
160
+ }
161
+ function describeSubagentTool(config, options) {
156
162
  const on = options?.disabledFeatures ? featureText(options.disabledFeatures) : allEnabled;
157
163
  if (config.toolDescriptionMode === undefined)
158
164
  return essentials(on);
@@ -18,7 +18,6 @@ export interface HerdrInspectorBinding {
18
18
  }
19
19
  export declare function bindingPath(asyncDir: string, index?: number): string;
20
20
  export declare function readHerdrInspectorBinding(asyncDir: string, index?: number): HerdrInspectorBinding | undefined;
21
- /** Read a binding only when it belongs to the requested inspector target. */
22
21
  export declare function readHerdrInspectorBindingForTarget(target: InspectorTarget): HerdrInspectorBinding | undefined;
23
22
  export declare function openHerdrInspector(context: InspectorContext, launch: InspectorLaunch, params: InspectorParams, client: HerdrClient): Promise<AgentToolResult<Details>>;
24
23
  export declare function statusHerdrInspector(context: InspectorContext, client: HerdrClient): Promise<AgentToolResult<Details>>;
@@ -28,7 +28,6 @@ export function readHerdrInspectorBinding(asyncDir, index) {
28
28
  return undefined;
29
29
  }
30
30
  }
31
- /** Read a binding only when it belongs to the requested inspector target. */
32
31
  export function readHerdrInspectorBindingForTarget(target) {
33
32
  const binding = readHerdrInspectorBinding(target.asyncDir, target.index);
34
33
  if (!binding || binding.runId !== target.runId || binding.childIndex !== target.index)
@@ -11,5 +11,4 @@
11
11
  * a way that could still fail as new characters are added upstream.
12
12
  */
13
13
  export declare function encodeSessionRoots(roots: readonly string[]): string;
14
- /** Decodes a `--session-roots` argument produced by {@link encodeSessionRoots}. */
15
14
  export declare function decodeSessionRoots(raw: string): string[];
@@ -18,7 +18,6 @@ function parseStringArray(value) {
18
18
  return undefined;
19
19
  return value;
20
20
  }
21
- /** Decodes a `--session-roots` argument produced by {@link encodeSessionRoots}. */
22
21
  export function decodeSessionRoots(raw) {
23
22
  try {
24
23
  const decoded = parseStringArray(JSON.parse(Buffer.from(raw, "base64").toString("utf-8")));
@@ -18,7 +18,6 @@ export interface TmuxInspectorBinding {
18
18
  }
19
19
  export declare function bindingPath(asyncDir: string, index?: number): string;
20
20
  export declare function readTmuxInspectorBinding(asyncDir: string, index?: number): TmuxInspectorBinding | undefined;
21
- /** Read a binding only when it belongs to the requested inspector target. */
22
21
  export declare function readTmuxInspectorBindingForTarget(target: InspectorTarget): TmuxInspectorBinding | undefined;
23
22
  export declare function openTmuxInspector(context: InspectorContext, launch: InspectorLaunch, focus: boolean, client: TmuxClient): Promise<AgentToolResult<Details>>;
24
23
  export declare function statusTmuxInspector(context: InspectorContext, client: TmuxClient): Promise<AgentToolResult<Details>>;
@@ -28,7 +28,6 @@ export function readTmuxInspectorBinding(asyncDir, index) {
28
28
  return undefined;
29
29
  }
30
30
  }
31
- /** Read a binding only when it belongs to the requested inspector target. */
32
31
  export function readTmuxInspectorBindingForTarget(target) {
33
32
  const binding = readTmuxInspectorBinding(target.asyncDir, target.index);
34
33
  if (!binding || binding.runId !== target.runId || binding.childIndex !== target.index)
@@ -5,7 +5,6 @@ const DEFAULT_SOURCE = "pi-subagents:herdr";
5
5
  const DEFAULT_TTL_MS = 120_000;
6
6
  const DEFAULT_REFRESH_MS = 45_000;
7
7
  const MAX_TASK_LABEL_CHARS = 80;
8
- const MAX_TITLE_TASK_CHARS = 42;
9
8
  const MAX_WORKFLOW_LABEL_NODES = 128;
10
9
  const MAX_WORKFLOW_LABEL_DEPTH = 8;
11
10
  let metadataReportSeq = Date.now() * 1000;
@@ -16,13 +15,13 @@ function nextMetadataReportSeq() {
16
15
  function isRecord(value) {
17
16
  return typeof value === "object" && value !== null && !Array.isArray(value);
18
17
  }
19
- function boundedTaskLabel(value, maxChars = MAX_TASK_LABEL_CHARS) {
18
+ function boundedTaskLabel(value) {
20
19
  if (typeof value !== "string")
21
20
  return undefined;
22
21
  const normalized = sanitizeDisplayText(value).trim();
23
22
  if (!normalized)
24
23
  return undefined;
25
- return previewDisplayText(normalized, maxChars);
24
+ return previewDisplayText(normalized, MAX_TASK_LABEL_CHARS);
26
25
  }
27
26
  function workflowTaskLabel(data) {
28
27
  const explicit = boundedTaskLabel(data.taskLabel);
@@ -125,11 +124,7 @@ export function registerHerdrStatusBridge(options) {
125
124
  const titleSuffix = () => {
126
125
  if (runs.size === 0)
127
126
  return undefined;
128
- const agentNames = activeAgentNames();
129
- const activeCount = activeSubagentCount();
130
- const task = boundedTaskLabel(activeTaskLabel(), MAX_TITLE_TASK_CHARS);
131
- const target = task ?? (activeCount === 1 && agentNames.length === 1 ? agentNames[0] : String(activeCount));
132
- return `⏳${target}${attentionRuns.size > 0 ? "⚠" : ""}`;
127
+ return `⏳${activeSubagentCount()}${attentionRuns.size > 0 ? "⚠" : ""}`;
133
128
  };
134
129
  const enqueue = (args) => {
135
130
  pendingReport = args;
@@ -9,6 +9,7 @@ import { ownsRun } from "../runs/shared/run-ownership.js";
9
9
  import { writeAtomicJson, writePrivateAtomicJson } from "../shared/atomic-json.js";
10
10
  import { shouldUseNativeFsWatch } from "../shared/watch-strategy.js";
11
11
  import { MODEL_ONLY_TOOL } from "../shared/extension-context.js";
12
+ import { reportSessionWarning } from "../shared/session-warnings.js";
12
13
  import { SUPERVISOR_REQUEST_MESSAGE_TYPE, SUPERVISOR_REPLY_ENTRY_TYPE, supervisorReplyHint, } from "./supervisor-ui.js";
13
14
  const SUPERVISOR_CHANNEL_ROOT = path.join(TEMP_ROOT_DIR, "supervisor-channels");
14
15
  const REQUESTS_DIR = "requests";
@@ -533,7 +534,22 @@ function appendSupervisorReplyEntry(pi, request, reply) {
533
534
  console.error("Failed to journal native supervisor reply:", error);
534
535
  }
535
536
  }
536
- function resolvePendingRequest(pending, params) {
537
+ function endedRequestText(ended, runState) {
538
+ const { request } = ended;
539
+ const iso = (time) => new Date(time).toISOString();
540
+ const when = ended.eventAt !== undefined ? ` at ${iso(ended.eventAt)}` : ` (noticed at ${iso(ended.endedAt)})`;
541
+ const subject = `Supervisor request '${request.id}' from ${request.agent} [${request.runId}#${request.childIndex}]`;
542
+ const runStatus = runState.asyncJobs.get(request.runId)?.status;
543
+ const runNow = runStatus && runStatus !== "queued" && runStatus !== "running" ? ` Run ${request.runId} is now ${runStatus}.` : "";
544
+ switch (ended.lifecycle) {
545
+ case "resolved": return `${subject} was already answered${when}.`;
546
+ case "expired": return `${subject} expired${when}: no reply arrived before the child's ask timeout.`;
547
+ case "deadline": return `${subject} ended around its ask deadline${when}: either no reply arrived before the child's ask timeout, or its run was stopped just before then.${runNow}`;
548
+ case "inactive": return `${subject} was closed because its child run ended${when}.${runNow}`;
549
+ case "missing": return `${subject} was withdrawn by the child before its ask deadline${when}. A child withdraws its request when its run is stopped, interrupted or times out, for example when a workflow aborts its other children after one fails.${runNow}`;
550
+ }
551
+ }
552
+ function resolvePendingRequest(pending, params, ended, runState) {
537
553
  const requests = [...pending.values()].filter((request) => request.expectsReply);
538
554
  if (params.replyTo) {
539
555
  const request = pending.get(params.replyTo);
@@ -541,6 +557,9 @@ function resolvePendingRequest(pending, params) {
541
557
  // A child stops waiting after its ask timeout and may ask again under a new id. Its first
542
558
  // notice can reach a busy parent after that, so name what can still be answered.
543
559
  const current = requests.length ? `Pending now:\n${requests.map(pendingHeader).join("\n")}` : "No pending supervisor requests.";
560
+ const endedRequest = ended.get(params.replyTo);
561
+ if (endedRequest)
562
+ throw new Error(`${endedRequestText(endedRequest, runState(endedRequest.request))} ${current}`);
544
563
  throw new Error(`No pending supervisor request found for replyTo '${params.replyTo}'. It was answered, expired or withdrawn. ${current}`);
545
564
  }
546
565
  return request;
@@ -572,7 +591,7 @@ function publicPendingRequests(pending) {
572
591
  expectsReply: request.expectsReply,
573
592
  }));
574
593
  }
575
- function buildParentSupervisorTool(pi, pending, state, onLifecycle, discover, runState) {
594
+ function buildParentSupervisorTool(pi, pending, state, onLifecycle, discover, runState, ended) {
576
595
  return {
577
596
  name: NATIVE_SUPERVISOR_TOOL_NAME,
578
597
  ...MODEL_ONLY_TOOL,
@@ -592,11 +611,11 @@ function buildParentSupervisorTool(pi, pending, state, onLifecycle, discover, ru
592
611
  return { content: [{ type: "text", text: lines.length ? lines.join("\n") : "No pending supervisor requests." }], details: { pending: publicPendingRequests(pending) } };
593
612
  }
594
613
  if (input.action === "reply") {
595
- const request = resolvePendingRequest(pending, input);
614
+ const request = resolvePendingRequest(pending, input, ended, runState);
596
615
  const reply = writeReply(request, input.message ?? "");
597
616
  appendSupervisorReplyEntry(pi, request, reply);
598
617
  pending.delete(request.id);
599
- onLifecycle(request, "resolved");
618
+ onLifecycle(request, "resolved", reply.createdAt);
600
619
  clearForegroundSupervisorAttention(request, pending, state);
601
620
  return { content: [{ type: "text", text: `Replied to supervisor request ${request.id}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent } };
602
621
  }
@@ -654,12 +673,37 @@ export function createNativeSupervisorChannel(pi, state, deps = {}) {
654
673
  requestCorrelations.set(key, { request, state: "resolved", updatedAt: Date.now() });
655
674
  pruneRequestCorrelations();
656
675
  };
657
- const observeRequestLifecycle = (request, lifecycle) => {
676
+ // How each request ended, so a late reply can say why it is gone instead of a generic miss.
677
+ const endedRequests = new Map();
678
+ const rememberEndedRequest = (request, lifecycle, eventAt) => {
679
+ if (!request.expectsReply)
680
+ return;
681
+ const now = Date.now();
682
+ endedRequests.delete(request.id);
683
+ endedRequests.set(request.id, { request, lifecycle, endedAt: now, ...(eventAt !== undefined ? { eventAt } : {}) });
684
+ for (const [id, ended] of endedRequests) {
685
+ if (now - ended.endedAt <= SUPERVISOR_REQUEST_CORRELATION_RETENTION_MS && endedRequests.size <= MAX_SUPERVISOR_REQUEST_CORRELATIONS)
686
+ break;
687
+ endedRequests.delete(id);
688
+ }
689
+ };
690
+ const observeRequestLifecycle = (request, lifecycle, eventAt) => {
658
691
  settleNotices.delete(request.id);
659
692
  if (queuedNotices.delete(request.id))
660
693
  updateDeliverySubscription();
661
694
  if (lifecycle !== "wrong-session")
662
695
  rememberResolvedRequest(request);
696
+ // A child that hits its ask deadline deletes its own request file, so a missing file past the deadline can be
697
+ // that timeout or a stop just before it. The parent extends a queued ask's expiresAt in memory too, so a live
698
+ // ask never reads as past it.
699
+ if (lifecycle !== "wrong-session" && lifecycle !== "pending") {
700
+ const now = Date.now();
701
+ const expiresAt = requestExpiresAt(request, now);
702
+ if (lifecycle === "missing" && now > expiresAt)
703
+ rememberEndedRequest(request, "deadline", expiresAt);
704
+ else
705
+ rememberEndedRequest(request, lifecycle, lifecycle === "expired" ? expiresAt : eventAt);
706
+ }
663
707
  updateSettleSubscription();
664
708
  };
665
709
  const getSupervisorRequestState = (event) => {
@@ -716,7 +760,7 @@ export function createNativeSupervisorChannel(pi, state, deps = {}) {
716
760
  };
717
761
  const registerParentTools = () => {
718
762
  if (!hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME))
719
- pi.registerTool(buildParentSupervisorTool(pi, pending, state, observeRequestLifecycle, () => poll(), runState));
763
+ pi.registerTool(buildParentSupervisorTool(pi, pending, state, observeRequestLifecycle, () => pollOnce(), runState, endedRequests));
720
764
  };
721
765
  // A session that never delegated through `subagent` does not declare the reply tool (scheduled runs, runs
722
766
  // adopted after a resume), so declare it before the model is asked to use it.
@@ -742,7 +786,7 @@ export function createNativeSupervisorChannel(pi, state, deps = {}) {
742
786
  // Supervisor delivery must not fail because best-effort temp cleanup failed.
743
787
  }
744
788
  };
745
- const poll = () => {
789
+ const pollOnce = () => {
746
790
  cleanupStaleChannelsIfDue();
747
791
  // Only display notifications require a live UI context, not request registration.
748
792
  refreshPendingRequests(pending, state, observeRequestLifecycle, runState);
@@ -777,7 +821,7 @@ export function createNativeSupervisorChannel(pi, state, deps = {}) {
777
821
  continue;
778
822
  }
779
823
  seenFiles.add(file);
780
- observeRequestLifecycle(request, "resolved");
824
+ observeRequestLifecycle(request, "resolved", now);
781
825
  cleanupRequestLifecycle(request, "resolved");
782
826
  continue;
783
827
  }
@@ -835,6 +879,17 @@ export function createNativeSupervisorChannel(pi, state, deps = {}) {
835
879
  channels?.retire?.();
836
880
  updateSettleSubscription();
837
881
  };
882
+ // Never throws: this runs from timers, watchers, setImmediate and event handlers, and Pi exits the process on an
883
+ // uncaught exception, so one unreadable temp directory must not end the session. Callers whose answer a model or a
884
+ // drain decision reads use pollOnce, so a failed scan is not mistaken for "no pending requests".
885
+ const poll = () => {
886
+ try {
887
+ pollOnce();
888
+ }
889
+ catch (error) {
890
+ reportSessionWarning(state, `Supervisor channel poll failed: ${error instanceof Error ? error.message : String(error)}`, "supervisor-channel-poll");
891
+ }
892
+ };
838
893
  const handleBeforeSettle = (event) => {
839
894
  if (!started || event.outcome !== "completed")
840
895
  return;
@@ -1048,7 +1103,7 @@ export function createNativeSupervisorChannel(pi, state, deps = {}) {
1048
1103
  hasPendingRequests: () => {
1049
1104
  if (!started)
1050
1105
  return false;
1051
- poll();
1106
+ pollOnce();
1052
1107
  return pending.size > 0;
1053
1108
  },
1054
1109
  start: () => {
@@ -1111,6 +1166,7 @@ export function createNativeSupervisorChannel(pi, state, deps = {}) {
1111
1166
  pending.clear();
1112
1167
  settleNotices.clear();
1113
1168
  requestCorrelations.clear();
1169
+ endedRequests.clear();
1114
1170
  seenFiles.clear();
1115
1171
  },
1116
1172
  pending,