@timmyjl12/pi-subagents 0.20.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/CHANGELOG.md +862 -827
  2. package/README.md +1125 -1080
  3. package/dist/active-agents-prompt.d.ts +31 -9
  4. package/dist/active-agents-prompt.js +73 -9
  5. package/dist/agent-color.js +9 -1
  6. package/dist/agent-file-toggle.d.ts +1 -1
  7. package/dist/agent-manager.d.ts +405 -18
  8. package/dist/agent-manager.js +1661 -131
  9. package/dist/agent-runner.d.ts +45 -6
  10. package/dist/agent-runner.js +109 -18
  11. package/dist/agent-types.d.ts +30 -7
  12. package/dist/agent-types.js +38 -9
  13. package/dist/awaited-result.d.ts +37 -0
  14. package/dist/awaited-result.js +150 -0
  15. package/dist/child-session-shutdown.d.ts +19 -1
  16. package/dist/child-session-shutdown.js +60 -11
  17. package/dist/cleanup-plans.d.ts +10 -0
  18. package/dist/cleanup-plans.js +112 -0
  19. package/dist/cross-extension-rpc.d.ts +8 -1
  20. package/dist/cross-extension-rpc.js +59 -5
  21. package/dist/custom-agents.d.ts +34 -9
  22. package/dist/custom-agents.js +308 -111
  23. package/dist/default-agents.d.ts +1 -1
  24. package/dist/env.d.ts +1 -1
  25. package/dist/error-log.d.ts +6 -0
  26. package/dist/error-log.js +8 -0
  27. package/dist/force-main-model.d.ts +21 -0
  28. package/dist/force-main-model.js +28 -0
  29. package/dist/goal-bridge.d.ts +155 -0
  30. package/dist/goal-bridge.js +305 -0
  31. package/dist/group-join.d.ts +5 -1
  32. package/dist/group-join.js +52 -7
  33. package/dist/index.d.ts +5 -5
  34. package/dist/index.js +2827 -333
  35. package/dist/invocation-config.d.ts +30 -3
  36. package/dist/invocation-config.js +30 -1
  37. package/dist/memory.d.ts +1 -1
  38. package/dist/mention-clone.d.ts +1 -1
  39. package/dist/model-scope.d.ts +1 -1
  40. package/dist/nested-tools.d.ts +22 -1
  41. package/dist/nested-tools.js +120 -26
  42. package/dist/output-file.d.ts +15 -4
  43. package/dist/output-file.js +146 -43
  44. package/dist/prompts.d.ts +1 -1
  45. package/dist/recovery.d.ts +1 -1
  46. package/dist/report-cleanup.d.ts +204 -0
  47. package/dist/report-cleanup.js +1632 -0
  48. package/dist/report-store.d.ts +738 -0
  49. package/dist/report-store.js +3616 -0
  50. package/dist/schedule-store.d.ts +14 -6
  51. package/dist/schedule-store.js +88 -58
  52. package/dist/schedule.d.ts +20 -8
  53. package/dist/schedule.js +135 -74
  54. package/dist/settings.d.ts +39 -11
  55. package/dist/settings.js +22 -5
  56. package/dist/status-note.d.ts +1 -1
  57. package/dist/structured-output.d.ts +1 -1
  58. package/dist/types.d.ts +32 -3
  59. package/dist/ui/agent-mention.d.ts +2 -2
  60. package/dist/ui/agent-widget.d.ts +82 -13
  61. package/dist/ui/agent-widget.js +155 -37
  62. package/dist/ui/cleanup-preview.d.ts +59 -0
  63. package/dist/ui/cleanup-preview.js +466 -0
  64. package/dist/ui/conversation-viewer.d.ts +4 -4
  65. package/dist/ui/conversation-viewer.js +10 -6
  66. package/dist/ui/fleet-list.d.ts +3 -3
  67. package/dist/ui/fleet-list.js +3 -3
  68. package/dist/ui/fleet-overlay.d.ts +37 -6
  69. package/dist/ui/fleet-overlay.js +214 -18
  70. package/dist/ui/hub-feed.d.ts +52 -0
  71. package/dist/ui/hub-feed.js +148 -0
  72. package/dist/ui/native-transcript.js +5 -1
  73. package/dist/ui/schedule-menu.d.ts +1 -1
  74. package/dist/ui/schedule-menu.js +1 -1
  75. package/dist/ui/workflow-card.d.ts +4 -4
  76. package/dist/ui/workflow-dialog.d.ts +4 -4
  77. package/dist/ui/workflow-dialog.js +8 -3
  78. package/dist/ui/workflow-menu.d.ts +2 -2
  79. package/dist/usage.d.ts +12 -0
  80. package/dist/usage.js +28 -1
  81. package/dist/workflow/entry.d.ts +3 -3
  82. package/dist/workflow/host.d.ts +7 -4
  83. package/dist/workflow/host.js +162 -48
  84. package/dist/workflow/journal.d.ts +23 -7
  85. package/dist/workflow/journal.js +80 -23
  86. package/dist/workflow/progress.d.ts +1 -1
  87. package/dist/workflow/runtime.d.ts +45 -6
  88. package/dist/workflow/runtime.js +105 -16
  89. package/dist/workflow/task.d.ts +13 -4
  90. package/dist/workflow/task.js +7 -1
  91. package/dist/workflow/tool-description.d.ts +7 -2
  92. package/dist/workflow/tool-description.js +10 -5
  93. package/docs/{FORK.md → DEVELOPMENT.md} +4 -4
  94. package/docs/artifacts.md +93 -0
  95. package/docs/rpc.md +252 -189
  96. package/docs/runtime-performance.md +53 -0
  97. package/docs/workflows.md +48 -18
  98. package/examples/agent-tool-description.md +2 -2
  99. package/examples/workflows/review-panel.js +6 -3
  100. package/package.json +5 -5
  101. package/src/active-agents-prompt.ts +115 -39
  102. package/src/agent-color.ts +10 -2
  103. package/src/agent-file-toggle.ts +2 -2
  104. package/src/agent-manager.ts +3312 -1601
  105. package/src/agent-runner.ts +164 -36
  106. package/src/agent-types.ts +56 -11
  107. package/src/awaited-result.ts +187 -0
  108. package/src/child-session-shutdown.ts +114 -46
  109. package/src/cleanup-plans.ts +112 -0
  110. package/src/cross-extension-rpc.ts +68 -9
  111. package/src/custom-agents.ts +384 -112
  112. package/src/default-agents.ts +1 -1
  113. package/src/enabled-models.ts +1 -1
  114. package/src/env.ts +1 -1
  115. package/src/error-log.ts +10 -1
  116. package/src/force-main-model.ts +29 -0
  117. package/src/goal-bridge.ts +468 -0
  118. package/src/group-join.ts +56 -9
  119. package/src/index.ts +2987 -349
  120. package/src/invocation-config.ts +50 -4
  121. package/src/memory.ts +1 -1
  122. package/src/mention-clone.ts +3 -3
  123. package/src/model-scope.ts +1 -1
  124. package/src/nested-tools.ts +164 -33
  125. package/src/output-file.ts +168 -46
  126. package/src/prompts.ts +1 -1
  127. package/src/recovery.ts +2 -2
  128. package/src/report-cleanup.ts +2044 -0
  129. package/src/report-store.ts +4133 -0
  130. package/src/schedule-store.ts +244 -201
  131. package/src/schedule.ts +144 -80
  132. package/src/settings.ts +61 -16
  133. package/src/skill-loader.ts +1 -1
  134. package/src/standalone-fallback.ts +2 -2
  135. package/src/status-note.ts +1 -1
  136. package/src/structured-output.ts +1 -1
  137. package/src/types.ts +33 -3
  138. package/src/ui/agent-mention.ts +3 -3
  139. package/src/ui/agent-widget.ts +179 -45
  140. package/src/ui/cleanup-preview.ts +518 -0
  141. package/src/ui/conversation-viewer.ts +19 -15
  142. package/src/ui/fleet-list.ts +7 -7
  143. package/src/ui/fleet-overlay.ts +1048 -847
  144. package/src/ui/hub-feed.ts +179 -0
  145. package/src/ui/native-transcript.ts +7 -3
  146. package/src/ui/schedule-menu.ts +4 -4
  147. package/src/ui/workflow-card.ts +4 -4
  148. package/src/ui/workflow-dialog.ts +10 -6
  149. package/src/ui/workflow-menu.ts +4 -4
  150. package/src/usage.ts +53 -3
  151. package/src/workflow/collisions.ts +1 -1
  152. package/src/workflow/entry.ts +3 -3
  153. package/src/workflow/host.ts +174 -54
  154. package/src/workflow/journal.ts +80 -23
  155. package/src/workflow/progress.ts +1 -1
  156. package/src/workflow/runtime.ts +146 -23
  157. package/src/workflow/saved.ts +3 -3
  158. package/src/workflow/task.ts +18 -7
  159. package/src/workflow/tool-description.ts +10 -5
package/src/index.ts CHANGED
@@ -12,37 +12,62 @@
12
12
  */
13
13
 
14
14
  import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
15
- import { isAbsolute, join } from "node:path";
15
+ import { dirname, isAbsolute, join, resolve } from "node:path";
16
16
  import { defineTool, type ExtensionAPI, type ExtensionCommandContext, type ExtensionContext, getAgentDir, getSettingsListTheme } from "@earendil-works/pi-coding-agent";
17
- import { Container, Key, matchesKey, type SettingItem, SettingsList, Spacer, Text, TruncatedText } from "@earendil-works/pi-tui";
17
+ import { Container, Key, matchesKey, type OverlayHandle, type SettingItem, SettingsList, Spacer, Text, TruncatedText } from "@earendil-works/pi-tui";
18
18
  import { Type } from "@sinclair/typebox";
19
- import { abortable } from "./abortable.js";
20
- import { ACTIVE_AGENTS_SECTION, buildActiveAgentsSection } from "./active-agents-prompt.js";
21
- import { type AdvisorStatus, formatAdvisorStatus } from "./advisor-status.js";
22
- import { hasAgentBadge, renderAgentName } from "./agent-color.js";
23
- import { buildNewAgentFile, disableInContent, enableInContent, isEmptyStub, locateAgentFile, personalAgentsDir, projectAgentsDir, serializeAgentFile } from "./agent-file-toggle.js";
24
- import { AgentManager, isTopLevelAgent, sessionAcceptsSteer } from "./agent-manager.js";
25
- import { getAgentConversation, getDefaultMaxTurns, getGraceTurns, getRememberAgents, normalizeMaxTurns, resolveEffectiveMaxTurns, SUBAGENT_TOOL_NAMES, setDefaultMaxTurns, setGraceTurns, setRememberAgents, steerAgent } from "./agent-runner.js";
26
- import { BUILTIN_TOOL_NAMES, getAgentConfig, getAllTypes, getAvailableTypes, getConfig, getFallbackSubagent, isDefaultsDisabled, NO_FALLBACK, registerAgents, resolveSpawnType, resolveType, setDefaultsDisabled, setFallbackSubagent } from "./agent-types.js";
27
- import { inChildSessionContext } from "./child-context.js";
28
- import { type RpcHandle, registerRpcHandlers } from "./cross-extension-rpc.js";
29
- import { loadCustomAgents } from "./custom-agents.js";
30
- import { logSubagentIssue } from "./error-log.js";
31
- import { GroupJoinManager } from "./group-join.js";
32
- import { isolationParam, isPinFallback, resolveAgentInvocationConfig, resolveJoinMode, resolvePinnedModel } from "./invocation-config.js";
33
- import { describeMention, handleBase, isReservedHandle, parseMention, resolveHandleToType, stripAgentPrefix } from "./mention.js";
34
- import { runMentionClone } from "./mention-clone.js";
35
- import { describeModel, type ModelRegistry, resolveModel } from "./model-resolver.js";
36
- import { checkModelScope, isScopeModelsEnabled, setScopeModelsEnabled } from "./model-scope.js";
37
- import { getMaxSubagentDepth, setMaxSubagentDepth } from "./nested-tools.js";
38
- import { createOutputFilePath, ensureOutputFile, getOutputTranscriptDefault, sessionTaskDir, setOutputTranscriptDefault, streamToOutputFile, writeInitialEntry } from "./output-file.js";
39
- import { SubagentScheduler } from "./schedule.js";
40
- import { resolveStorePath, ScheduleStore } from "./schedule-store.js";
41
- import { applyAndEmitLoaded, loadSettings, type SubagentsSettings, saveAndEmitChanged, type ToolDescriptionMode } from "./settings.js";
42
- import { getForegroundOutcomeNote, getStatusNote, partialOutputSuffix } from "./status-note.js";
43
- import { readShowTerminalProgress, TerminalProgressTracker } from "./terminal-progress.js";
44
- import { type AgentConfig, type AgentInvocation, type AgentMentionMode, type AgentRecord, type JoinMode, type NotificationDetails, type SubagentType, type ViewerMarkdownMode, type WidgetMode } from "./types.js";
45
- import { createMentionProvider, mentionRoster, type TypeInfo } from "./ui/agent-mention.js";
19
+ import { abortable } from "./abortable.ts";
20
+ import { ACTIVE_AGENTS_MESSAGE_TYPE, nextActiveAgentsMessage } from "./active-agents-prompt.ts";
21
+ import { type AdvisorStatus, formatAdvisorStatus } from "./advisor-status.ts";
22
+ import { hasAgentBadge, renderAgentName } from "./agent-color.ts";
23
+ import { buildNewAgentFile, disableInContent, enableInContent, isEmptyStub, locateAgentFile, personalAgentsDir, projectAgentsDir, serializeAgentFile } from "./agent-file-toggle.ts";
24
+ import { AgentManager, isTopLevelAgent, sessionAcceptsSteer } from "./agent-manager.ts";
25
+ import { getAgentConversation, getAllowPerCallTurnLimits, getDefaultMaxTurns, getGraceTurns, getRememberAgents, normalizeMaxTurns, resolveEffectiveMaxTurns, SUBAGENT_TOOL_NAMES, setAllowPerCallTurnLimits, setDefaultMaxTurns, setGraceTurns, setRememberAgents, steerAgent } from "./agent-runner.ts";
26
+ import { BUILTIN_TOOL_NAMES, buildAgentRegistry, cloneAgentDefinition, getAgentConfig, getAgentConfigIn, getAllTypes, getAvailableTypes, getConfig, getFallbackSubagent, isDefaultsDisabled, NO_FALLBACK, registerAgents, resolveSpawnType, resolveSpawnTypeIn, setDefaultsDisabled, setFallbackSubagent } from "./agent-types.ts";
27
+ import { type FinalReportRequest, formatArchivedReportLookup, formatFinalReport } from "./awaited-result.ts";
28
+ import { inChildSessionContext } from "./child-context.ts";
29
+ import { mergeCleanupPlans, partitionCleanupPlan } from "./cleanup-plans.ts";
30
+ import { type RpcHandle, registerRpcHandlers } from "./cross-extension-rpc.ts";
31
+ import { loadCustomAgents, loadCustomAgentsAsync } from "./custom-agents.ts";
32
+ import { logSubagentIssue } from "./error-log.ts";
33
+ import { isForceMainModel, setForceMainModel } from "./force-main-model.ts";
34
+ import { SubagentsGoalBridge } from "./goal-bridge.ts";
35
+ import { GroupJoinManager } from "./group-join.ts";
36
+ import { isolationParam, isPinFallback, maxTurnsParam, resolveAgentInvocationConfig, resolveJoinMode, resolvePinnedModel } from "./invocation-config.ts";
37
+ import { describeMention, handleBase, isReservedHandle, parseMention, resolveHandleToType, stripAgentPrefix } from "./mention.ts";
38
+ import { runMentionClone } from "./mention-clone.ts";
39
+ import { describeModel, type ModelRegistry, resolveModel } from "./model-resolver.ts";
40
+ import { checkModelScope, isScopeModelsEnabled, setScopeModelsEnabled } from "./model-scope.ts";
41
+ import { getMaxSubagentDepth, setMaxSubagentDepth } from "./nested-tools.ts";
42
+ import { createOutputFilePath, ensureOutputFile, getOutputTranscriptDefault, sessionTaskDir, setOutputTranscriptDefault, streamToOutputFile, writeInitialEntry } from "./output-file.ts";
43
+ import {
44
+ applyCleanup,
45
+ CleanupApplyError,
46
+ type CleanupFileInventory,
47
+ type CleanupLiveState,
48
+ type CleanupPlan,
49
+ type CleanupPreparation,
50
+ type CleanupPrepareRequest,
51
+ type CleanupResult,
52
+ type CleanupSkip,
53
+ cleanupReadStateLabel,
54
+ planCleanup,
55
+ } from "./report-cleanup.ts";
56
+ import {
57
+ normalizeReportPath,
58
+ type ReportContext,
59
+ type ReportLookup,
60
+ type ReportSaveResult,
61
+ ReportStore,
62
+ ReportUnavailableError,
63
+ } from "./report-store.ts";
64
+ import { SubagentScheduler } from "./schedule.ts";
65
+ import { resolveStorePath, ScheduleStore } from "./schedule-store.ts";
66
+ import { applyAndEmitLoaded, loadSettings, type SubagentsSettings, saveAndEmitChanged, type ToolDescriptionMode } from "./settings.ts";
67
+ import { getForegroundOutcomeNote, getStatusNote, partialOutputSuffix } from "./status-note.ts";
68
+ import { readShowTerminalProgress, TerminalProgressTracker } from "./terminal-progress.ts";
69
+ import { type AgentConfig, type AgentInvocation, type AgentMentionMode, type AgentRecord, type JoinMode, type NotificationDetails, type SubagentType, type ViewerMarkdownMode, type WidgetMode, type WidgetPlacement } from "./types.ts";
70
+ import { createMentionProvider, mentionRoster, type TypeInfo } from "./ui/agent-mention.ts";
46
71
  import {
47
72
  type AgentActivity,
48
73
  type AgentDetails,
@@ -58,28 +83,30 @@ import {
58
83
  getDisplayName,
59
84
  getPromptModeLabel,
60
85
  SPINNER,
86
+ sanitizeRowText,
61
87
  type Theme,
62
88
  type UICtx,
63
- } from "./ui/agent-widget.js";
64
- import { ConversationViewer } from "./ui/conversation-viewer.js";
65
- import { FleetList, type FleetUICtx, type FleetWorkflow } from "./ui/fleet-list.js";
66
- import { FleetOverlay } from "./ui/fleet-overlay.js";
67
- import { showSchedulesMenu } from "./ui/schedule-menu.js";
68
- import { renderWorkflowCard, renderWorkflowEntryCard } from "./ui/workflow-card.js";
69
- import { openWorkflowFromFleet, showWorkflowsMenu, type WorkflowMenuDeps } from "./ui/workflow-menu.js";
70
- import { getLifetimeCost, getLifetimeTotal, getSessionContextPercent, type LifetimeUsage, PendingUsagePool, toReportedUsage } from "./usage.js";
71
- import { decideWorkflowCollision, FOREIGN_WORKFLOW_TOOL_NAMES } from "./workflow/collisions.js";
72
- import { WORKFLOW_ENTRY_TYPE, type WorkflowEntryData, workflowEntryData } from "./workflow/entry.js";
73
- import { createWorkflowHost } from "./workflow/host.js";
74
- import { appendJournal, readJournal, type WorkflowJournalEntry } from "./workflow/journal.js";
75
- import { extractMeta, type WorkflowMeta, workflowCallName } from "./workflow/meta.js";
76
- import { elapsedMs } from "./workflow/progress.js";
77
- import { runWorkflow } from "./workflow/runtime.js";
78
- import { resolveWorkflowScript } from "./workflow/saved.js";
79
- import { completeWorkflowTask, createWorkflowTask, failWorkflowTask, formatWorkflowNotification, resolveResumeTarget, updateWorkflowProgressBatch, type WorkflowTask, workflowResultText, workflowRunId } from "./workflow/task.js";
80
- import { fullWorkflowToolDescription } from "./workflow/tool-description.js";
81
- import { isWorktreeIsolationEnabled, setWorktreeIsolationEnabled } from "./worktree.js";
82
- import { escapeXml } from "./xml.js";
89
+ } from "./ui/agent-widget.ts";
90
+ import { formatCleanupPreview, showCleanupPreview } from "./ui/cleanup-preview.ts";
91
+ import { ConversationViewer } from "./ui/conversation-viewer.ts";
92
+ import type { FleetWorkflow } from "./ui/fleet-list.ts";
93
+ import { FleetOverlay } from "./ui/fleet-overlay.ts";
94
+ import { showSchedulesMenu } from "./ui/schedule-menu.ts";
95
+ import { renderWorkflowCard, renderWorkflowEntryCard } from "./ui/workflow-card.ts";
96
+ import { openWorkflowFromFleet, showWorkflowsMenu, type WorkflowMenuDeps } from "./ui/workflow-menu.ts";
97
+ import { getLifetimeCost, getLifetimeTotal, getSessionContextPercent, type LifetimeUsage, PendingUsagePool, toReportedUsage } from "./usage.ts";
98
+ import { decideWorkflowCollision, FOREIGN_WORKFLOW_TOOL_NAMES } from "./workflow/collisions.ts";
99
+ import { WORKFLOW_ENTRY_TYPE, type WorkflowEntryData, workflowEntryData } from "./workflow/entry.ts";
100
+ import { createWorkflowHost } from "./workflow/host.ts";
101
+ import { appendJournal, readJournal, type WorkflowJournalEntry } from "./workflow/journal.ts";
102
+ import { extractMeta, type WorkflowMeta, workflowCallName } from "./workflow/meta.ts";
103
+ import { elapsedMs } from "./workflow/progress.ts";
104
+ import { DEFAULT_WORKFLOW_AGENT_TYPE, runWorkflow } from "./workflow/runtime.ts";
105
+ import { resolveWorkflowScript } from "./workflow/saved.ts";
106
+ import { completeWorkflowTask, createWorkflowTask, failWorkflowTask, formatWorkflowNotification, resolveResumeTarget, updateWorkflowProgressBatch, type WorkflowTask, workflowResultText, workflowRunId } from "./workflow/task.ts";
107
+ import { fullWorkflowToolDescription } from "./workflow/tool-description.ts";
108
+ import { isWorktreeIsolationEnabled, setWorktreeIsolationEnabled } from "./worktree.ts";
109
+ import { escapeXml } from "./xml.ts";
83
110
 
84
111
  // ---- Shared helpers ----
85
112
 
@@ -97,8 +124,11 @@ export function renderRunningAgentStatus(
97
124
  ): Container {
98
125
  const container = new Container();
99
126
  container.addChild(new Text(theme.fg("accent", frame) + (statsText ? " " + statsText : ""), 0, 0));
100
- container.addChild(new Text(theme.fg("dim", ` ⎿ ${activity}`), 0, 0));
101
- container.addChild(new TruncatedText(theme.fg("dim", ` ⎿ ${formatAdvisorStatus(advisorStatus)}`), 0, 0));
127
+ // `statsText` arrives already styled, so only the plain fragments are
128
+ // flattened here: a control byte in either would make one rendered row
129
+ // occupy two terminal rows and desynchronise the host's line diff.
130
+ container.addChild(new Text(theme.fg("dim", ` ⎿ ${sanitizeRowText(activity)}`), 0, 0));
131
+ container.addChild(new TruncatedText(theme.fg("dim", ` ⎿ ${sanitizeRowText(formatAdvisorStatus(advisorStatus))}`), 0, 0));
102
132
  return container;
103
133
  }
104
134
 
@@ -176,7 +206,7 @@ function getStatusLabel(status: string, error?: string): string {
176
206
  }
177
207
 
178
208
  /** Format a structured task notification matching Claude Code's <task-notification> XML. */
179
- function formatTaskNotification(record: AgentRecord, resultMaxLen: number, showCost = false): string {
209
+ function formatTaskNotification(record: AgentRecord, request: FinalReportRequest, showCost = false): string {
180
210
  const status = getStatusLabel(record.status, record.error);
181
211
  const durationMs = record.completedAt ? record.completedAt - record.startedAt : 0;
182
212
  const totalTokens = getLifetimeTotal(record.lifetimeUsage);
@@ -188,11 +218,10 @@ function formatTaskNotification(record: AgentRecord, resultMaxLen: number, showC
188
218
  const cost = showCost ? getLifetimeCost(record.lifetimeUsage) : 0;
189
219
  const costXml = cost > 0 ? `<estimated_cost_usd>${cost.toFixed(4)}</estimated_cost_usd>` : "";
190
220
 
191
- const resultPreview = record.result
192
- ? record.result.length > resultMaxLen
193
- ? record.result.slice(0, resultMaxLen) + "\n...(truncated, use get_subagent_result for full output)"
194
- : record.result
195
- : "No output.";
221
+ // Never a preview and never capped: the completion notification is where the
222
+ // parent actually reads the worker's answer. The rendered notification keeps
223
+ // its own compact 500/300-character preview in `buildNotificationDetails`.
224
+ const report = formatFinalReport(record, request);
196
225
 
197
226
  return [
198
227
  `<task-notification>`,
@@ -201,7 +230,7 @@ function formatTaskNotification(record: AgentRecord, resultMaxLen: number, showC
201
230
  record.outputFile ? `<output-file>${escapeXml(record.outputFile)}</output-file>` : null,
202
231
  `<status>${escapeXml(status)}</status>`,
203
232
  `<summary>Agent "${escapeXml(record.description)}" ${record.status}${getStatusNote(record.status)}</summary>`,
204
- `<result>${escapeXml(resultPreview)}</result>`,
233
+ `<result>${escapeXml(report)}</result>`,
205
234
  `<usage><total_tokens>${totalTokens}</total_tokens><tool_uses>${record.toolUses}</tool_uses>${ctxXml}${compactXml}${costXml}<duration_ms>${durationMs}</duration_ms></usage>`,
206
235
  `</task-notification>`,
207
236
  ].filter(Boolean).join('\n');
@@ -316,7 +345,7 @@ export default function (pi: ExtensionAPI) {
316
345
  // ---- Register custom notification renderer ----
317
346
  pi.registerMessageRenderer<NotificationDetails>(
318
347
  "subagent-notification",
319
- (message, { expanded }, theme) => {
348
+ (message, { expanded, outputPad }, theme) => {
320
349
  const d = message.details;
321
350
  if (!d) return undefined;
322
351
 
@@ -328,7 +357,7 @@ export default function (pi: ExtensionAPI) {
328
357
  : "completed";
329
358
 
330
359
  // Line 1: icon + agent description + status
331
- let line = `${icon} ${theme.bold(d.description)} ${theme.fg("dim", statusText)}`;
360
+ let line = `${icon} ${theme.bold(sanitizeRowText(d.description))} ${theme.fg("dim", statusText)}`;
332
361
 
333
362
  // Line 2: stats
334
363
  const parts: string[] = [];
@@ -374,7 +403,8 @@ export default function (pi: ExtensionAPI) {
374
403
  rendered.unshift(theme.fg("dim", `${all.length} agents · ${formatTokens(tokens)} · ${total}`));
375
404
  }
376
405
  }
377
- return new Text(rendered.join("\n"), 0, 0);
406
+ // pi adds no padding around a custom renderer; match the transcript's.
407
+ return new Text(rendered.join("\n"), outputPad, 0);
378
408
  }
379
409
  );
380
410
 
@@ -407,6 +437,23 @@ export default function (pi: ExtensionAPI) {
407
437
  registerAgents(userAgents);
408
438
  };
409
439
 
440
+ /**
441
+ * Awaitable refresh for paths that can suspend (Agent tool, resumes,
442
+ * session_start and the menu). It keeps the process registry fresh for the
443
+ * genuinely synchronous callers, but RETURNS the registry built from THIS
444
+ * load: another root may re-register the global registry while this caller is
445
+ * suspended, and resolving from the global after the await would admit a
446
+ * definition this call never read.
447
+ */
448
+ const reloadCustomAgentsAsync = async (strict = false): Promise<Map<string, AgentConfig>> => {
449
+ const userAgents = await loadCustomAgentsAsync(process.cwd(), strict);
450
+ // One synchronous block: no reload can interleave between the scoped map
451
+ // and the global re-registration.
452
+ const registry = buildAgentRegistry(userAgents);
453
+ registerAgents(userAgents);
454
+ return registry;
455
+ };
456
+
410
457
  // Initial load — the only strict one. A bad edit mid-session must not kill the
411
458
  // session on the next unrelated spawn, so every later reload keeps warning.
412
459
  reloadCustomAgents(strictAgentFiles);
@@ -428,7 +475,7 @@ export default function (pi: ExtensionAPI) {
428
475
  /** Show `~$X` next to token counts in the subagent surfaces. */
429
476
  let showCost = false;
430
477
  function isShowCostEnabled(): boolean { return showCost; }
431
- function setShowCost(b: boolean): void { showCost = b; widget.update(); fleet.update(); }
478
+ function setShowCost(b: boolean): void { showCost = b; widget.update(); }
432
479
  /** Name the model and thinking level on the widget's running rows. */
433
480
  let showModel = false;
434
481
  function isShowModelEnabled(): boolean { return showModel; }
@@ -444,8 +491,7 @@ export default function (pi: ExtensionAPI) {
444
491
  /**
445
492
  * The viewer's Ctrl+R shortcut, from any entry point: set the mode and persist it,
446
493
  * so the key and `/agents → Settings` stay one setting rather than one per
447
- * entry point. `ctx` carries only the warning a failed write notifies with,
448
- * and the fleet list may be acting without one.
494
+ * entry point. `ctx` carries only the warning a failed write notifies with.
449
495
  */
450
496
  function chooseViewerMarkdown(mode: ViewerMarkdownMode, ctx?: ExtensionContext): void {
451
497
  setViewerMarkdown(mode);
@@ -455,8 +501,10 @@ export default function (pi: ExtensionAPI) {
455
501
 
456
502
  // ---- Cancellable pending notifications ----
457
503
  // Holds notifications briefly so get_subagent_result can cancel them
458
- // before they reach pi.sendMessage (fire-and-forget).
459
- const pendingNudges = new Map<string, ReturnType<typeof setTimeout>>();
504
+ // before they reach pi.sendMessage (fire-and-forget). The send is retained
505
+ // with its timer so shutdown can deliver a workflow notice the run just
506
+ // settled synchronously instead of dropping it with the timer.
507
+ const pendingNudges = new Map<string, { timer: ReturnType<typeof setTimeout>; send: () => void }>();
460
508
  const NUDGE_HOLD_MS = 200;
461
509
  // A queued result wait must observe completion before its held notification
462
510
  // can fire, so successful waits can still suppress that redundant nudge.
@@ -464,25 +512,73 @@ export default function (pi: ExtensionAPI) {
464
512
 
465
513
  function scheduleNudge(key: string, send: () => void, delay = NUDGE_HOLD_MS) {
466
514
  cancelNudge(key);
467
- pendingNudges.set(key, setTimeout(() => {
515
+ const timer = setTimeout(() => {
468
516
  pendingNudges.delete(key);
469
517
  try { send(); } catch { /* ignore stale completion side-effect errors */ }
470
- }, delay));
518
+ }, delay);
519
+ pendingNudges.set(key, { timer, send });
471
520
  }
472
521
 
473
522
  function cancelNudge(key: string) {
474
- const timer = pendingNudges.get(key);
475
- if (timer != null) {
476
- clearTimeout(timer);
523
+ const entry = pendingNudges.get(key);
524
+ if (entry != null) {
525
+ clearTimeout(entry.timer);
477
526
  pendingNudges.delete(key);
478
527
  }
479
528
  }
480
529
 
481
- // ---- Individual nudge helper (async join mode) ----
482
- function emitIndividualNudge(record: AgentRecord) {
483
- if (record.resultConsumed) return; // re-check at send time
530
+ // ---- Deferred result interest ----
531
+ // An interactive `get_subagent_result(wait: true)` no longer blocks: it
532
+ // returns, ending the main turn, and registers here what that wait asked the
533
+ // completion notification to carry. Keyed by canonical record id and pinned
534
+ // to the run generation, so a completion from a superseded run can neither
535
+ // deliver the old result nor spend the new run's request.
536
+ interface DeferredResultInterest extends FinalReportRequest {
537
+ runGeneration: number;
538
+ }
539
+ const deferredResultInterest = new Map<string, DeferredResultInterest>();
540
+
541
+ /** Remember (or upgrade, within one run) that a completion must carry this result. */
542
+ function deferResultDelivery(record: AgentRecord, request: FinalReportRequest): void {
543
+ const runGeneration = record.runGeneration ?? 0;
544
+ const prior = deferredResultInterest.get(record.id);
545
+ const sameRun = prior?.runGeneration === runGeneration;
546
+ deferredResultInterest.set(record.id, {
547
+ runGeneration,
548
+ verbose: sameRun && prior.verbose ? true : request.verbose,
549
+ });
550
+ }
551
+
552
+ /** The interest for the run this record is on now, if any. */
553
+ function currentResultInterest(record: AgentRecord): DeferredResultInterest | undefined {
554
+ const interest = deferredResultInterest.get(record.id);
555
+ return interest?.runGeneration === (record.runGeneration ?? 0) ? interest : undefined;
556
+ }
557
+
558
+ /**
559
+ * Drop interest a terminal delivery has made inert.
560
+ *
561
+ * A completion pinned to `deliveryGeneration` spends any request for that run
562
+ * (it was carried, or the run produced no interest of its own) and any older
563
+ * one (a resume superseded it, so that wait's agent run is gone for good —
564
+ * leaving it behind would only enrich some later, unrelated run). A NEWER
565
+ * request is for a run this delivery cannot speak for, so it is kept.
566
+ */
567
+ function clearSpentResultInterest(record: AgentRecord, deliveryGeneration: number): void {
568
+ const interest = deferredResultInterest.get(record.id);
569
+ if (interest && interest.runGeneration <= deliveryGeneration) deferredResultInterest.delete(record.id);
570
+ }
484
571
 
485
- const notification = formatTaskNotification(record, 500, showCost);
572
+ // ---- Individual nudge helper (async join mode) ----
573
+ function emitIndividualNudge(record: AgentRecord, runGeneration: number) {
574
+ // Re-check at send time: a resume inside the hold made this completion stale.
575
+ if ((record.runGeneration ?? 0) !== runGeneration) return;
576
+ if (record.resultConsumed) return;
577
+
578
+ const awaited = currentResultInterest(record);
579
+ // EVERY ordinary completion carries the complete final report — awaited or
580
+ // not. `verbose` is the only thing a wait can add, and it is opt-in.
581
+ const notification = formatTaskNotification(record, awaited ?? { verbose: false }, showCost);
486
582
  const footer = record.outputFile ? `\nFull transcript available at: ${record.outputFile}` : '';
487
583
 
488
584
  pi.sendMessage<NotificationDetails>({
@@ -491,28 +587,43 @@ export default function (pi: ExtensionAPI) {
491
587
  display: true,
492
588
  details: buildNotificationDetails(record, 500, agentActivity.get(record.id)),
493
589
  }, { deliverAs: "followUp", triggerTurn: true });
590
+ // Spent: one wakeup per completion, never a supplement. Any older interest
591
+ // for this record is inert now that this run's terminal report went out.
592
+ clearSpentResultInterest(record, runGeneration);
494
593
  }
495
594
 
496
595
  function sendIndividualNudge(record: AgentRecord) {
596
+ // Captured at schedule time; re-checked when the hold expires.
597
+ const runGeneration = record.runGeneration ?? 0;
497
598
  agentActivity.delete(record.id);
498
599
  widget.markFinished(record.id);
499
- fleet.onAgentFinished(record.id);
500
- scheduleNudge(record.id, () => emitIndividualNudge(record));
600
+ scheduleNudge(record.id, () => emitIndividualNudge(record, runGeneration));
501
601
  widget.update();
502
602
  }
503
603
 
504
604
  // ---- Group join manager ----
505
605
  const groupJoin = new GroupJoinManager(
506
606
  (records, partial) => {
507
- for (const r of records) { agentActivity.delete(r.id); widget.markFinished(r.id); fleet.onAgentFinished(r.id); }
607
+ for (const r of records) { agentActivity.delete(r.id); widget.markFinished(r.id); }
508
608
 
609
+ // Pin each record's run at schedule time; the hold is 200 ms, and a
610
+ // resume inside it must not inherit this completion.
611
+ const completions = records.map(record => ({ record, runGeneration: record.runGeneration ?? 0 }));
509
612
  const groupKey = `group:${records.map(r => r.id).join(",")}`;
510
613
  scheduleNudge(groupKey, () => {
511
- // Re-check at send time
512
- const unconsumed = records.filter(r => !r.resultConsumed);
614
+ const unconsumed = completions
615
+ .filter(entry => (entry.record.runGeneration ?? 0) === entry.runGeneration && !entry.record.resultConsumed)
616
+ .map(entry => entry.record);
513
617
  if (unconsumed.length === 0) { widget.update(); return; }
514
618
 
515
- const notifications = unconsumed.map(r => formatTaskNotification(r, 300, showCost)).join('\n\n');
619
+ // Every member carries its complete final report. A wait's `verbose`
620
+ // adds its own opt-in transcript excerpt; nothing here is budgeted
621
+ // against the group, because the report itself is never truncated.
622
+ const awaited = unconsumed.filter(r => currentResultInterest(r) !== undefined);
623
+
624
+ const notifications = unconsumed.map(r =>
625
+ formatTaskNotification(r, currentResultInterest(r) ?? { verbose: false }, showCost),
626
+ ).join('\n\n');
516
627
  const label = partial
517
628
  ? `${unconsumed.length} agent(s) finished (partial — others still running)`
518
629
  : `${unconsumed.length} agent(s) finished`;
@@ -525,10 +636,17 @@ export default function (pi: ExtensionAPI) {
525
636
 
526
637
  pi.sendMessage<NotificationDetails>({
527
638
  customType: "subagent-notification",
528
- content: `Background agent group completed: ${label}\n\n${notifications}\n\nUse get_subagent_result for full output.`,
639
+ content: `Background agent group completed: ${label}\n\n${notifications}\n\n` +
640
+ `Each agent's complete final report is included above — do not re-request one. ` +
641
+ (awaited.length > 0
642
+ ? "A requested wait additionally carries its full conversation as an opt-in transcript excerpt; get_subagent_result(verbose: true) returns a full transcript."
643
+ : "Use get_subagent_result only for a status detail or an explicit raw transcript."),
529
644
  display: true,
530
645
  details,
531
646
  }, { deliverAs: "followUp", triggerTurn: true });
647
+ // One group wakeup spends every request it could speak for — including
648
+ // an older run's request that a resume has already superseded.
649
+ for (const entry of completions) clearSpentResultInterest(entry.record, entry.runGeneration);
532
650
  });
533
651
  widget.update();
534
652
  },
@@ -573,6 +691,380 @@ export default function (pi: ExtensionAPI) {
573
691
  };
574
692
  }
575
693
 
694
+ // Durable completed reports. Bound lazily from the root session's plain
695
+ // metadata (cwd/id/file) and never from a captured ExtensionContext: async
696
+ // filesystem continuations outlive the context that started them.
697
+ /**
698
+ * Default session roots plus the root session file's own directory. The SDK
699
+ * allows a custom sessionDir beyond PI_CODING_AGENT_SESSION_DIR/<agentDir>/
700
+ * sessions; including it lets legacy raw reads/cleanup validation resolve the
701
+ * real parent file. Later session switches to a DIFFERENT custom dir are a
702
+ * known bounded gap of this single-store binding (T3 cleanup must recheck).
703
+ */
704
+ function createReportStore(extraSessionRoots: readonly string[] = []): ReportStore {
705
+ const roots = new Set<string>();
706
+ const envDir = process.env.PI_CODING_AGENT_SESSION_DIR?.trim();
707
+ if (envDir) roots.add(resolve(envDir));
708
+ roots.add(resolve(join(getAgentDir(), "sessions")));
709
+ for (const root of extraSessionRoots) roots.add(resolve(root));
710
+ return new ReportStore({ sessionRoots: [...roots] });
711
+ }
712
+
713
+ /** One live store per root; inactive roots are retired after their writes drain. */
714
+ const reportStores = new Map<string, ReportStore>();
715
+ const reportActiveRoots = new Set<string>();
716
+ let reportStore = createReportStore();
717
+ let reportBoundRoot: string | undefined;
718
+ let reportBindChain: Promise<void> = Promise.resolve();
719
+ /**
720
+ * Settled generations that occurred before the first bind (harnesses without
721
+ * session_start). Plain clones only — never a live record/session — and one
722
+ * entry per id, since only the latest generation is a durable report.
723
+ */
724
+ const pendingArchivedRecords = new Map<string, AgentRecord>();
725
+ const archiveRetryAttempts = new Map<string, number>();
726
+ let archiveDrainTimer: ReturnType<typeof setTimeout> | undefined;
727
+ const MAX_ARCHIVE_RETRIES = 5;
728
+
729
+ /**
730
+ * Cleanup state is command-local but the artifact guard installed on the
731
+ * manager is permanent. It consults only the operation that currently owns
732
+ * reservations, so ordinary spawns/resumes keep the original behavior.
733
+ */
734
+ interface CleanupOperation {
735
+ epoch: number;
736
+ rootSessionId: string;
737
+ readRoot: () => string | undefined;
738
+ candidateRoots: Set<string>;
739
+ frozenRoots: Set<string>;
740
+ reservedRoots: Set<string>;
741
+ selectedAgentIds: Set<string>;
742
+ selectedSessionFiles: Set<string>;
743
+ selectedPaths: Set<string>;
744
+ selectedWorkflowIds: Set<string>;
745
+ /** Planned agent id → the root whose reservation governs that selection. */
746
+ planAgentRoots: Map<string, string>;
747
+ /** Planned path (and child-session file) → the same governing root. */
748
+ planPathRoots: Map<string, string>;
749
+ }
750
+
751
+ interface CleanupRuntimeSnapshot {
752
+ activeAgentIds: Set<string>;
753
+ activeWorkflowIds: Set<string>;
754
+ protectedPaths: Set<string>;
755
+ unreadAgentIds: Set<string>;
756
+ protectedRoots: Set<string>;
757
+ unknownRootActivity: boolean;
758
+ hasActiveWork: boolean;
759
+ }
760
+
761
+ interface CleanupPreviewRecord {
762
+ record: AgentRecord;
763
+ runGeneration: number;
764
+ rootSessionId: string | undefined;
765
+ }
766
+
767
+ interface WorkflowCleanupProof {
768
+ rootSessionId?: string;
769
+ generatedPaths: string[];
770
+ externalPaths: string[];
771
+ persistenceUncertainty?: string;
772
+ }
773
+
774
+ let sessionEpoch = 0;
775
+ let shuttingDown = false;
776
+ let cleanupOperation: CleanupOperation | undefined;
777
+ /**
778
+ * Per-root read-invalidation counter. Bumped when a cleanup operation takes
779
+ * ownership of a root, and again when it releases it — never pruned, because
780
+ * the counter's only job is to differ between two points in time. An archived
781
+ * read that resumes across either edge re-resolves instead of returning the
782
+ * body it captured before the root changed.
783
+ */
784
+ const cleanupReadInvalidations = new Map<string, number>();
785
+ /**
786
+ * Selected reports whose durable deletion receipt may already be committed but
787
+ * could not be read back. `writeDeletionReceipt` publishes the receipt before
788
+ * it bumps the root generation, so a rejected call is NOT proof that the body
789
+ * survived — and an unreadable entry is not proof either. Such an id is a
790
+ * reported FAILURE (never a deletion), and the in-memory live body must not
791
+ * then be served as if the durable entry were still intact: that is handing
792
+ * back a report this command deleted. Ids only — no bodies, no paths — dropped
793
+ * when a new generation of that agent starts or when the session ends.
794
+ */
795
+ const cleanupUnprovenReports = new Set<string>();
796
+ const workflowCleanupProofs = new Map<string, WorkflowCleanupProof>();
797
+ const workflowArtifactStores = new Map<string, ReportStore>();
798
+ const discardedWorkflowNotifications = new Set<string>();
799
+
800
+ /**
801
+ * Copy every plain field a report snapshot needs, synchronously, so a later
802
+ * resume cannot rewrite the generation being archived. Live SDK handles are
803
+ * deliberately excluded; the snapshot only needs `session.sessionId`.
804
+ */
805
+ function cloneRecordForArchive(record: AgentRecord): AgentRecord {
806
+ const sessionId = record.session?.sessionId ?? record.sessionId;
807
+ return {
808
+ id: record.id,
809
+ type: record.type,
810
+ description: record.description,
811
+ status: record.status,
812
+ ...(record.result === undefined ? {} : { result: record.result }),
813
+ ...(record.error === undefined ? {} : { error: record.error }),
814
+ toolUses: record.toolUses,
815
+ startedAt: record.startedAt,
816
+ ...(record.completedAt === undefined ? {} : { completedAt: record.completedAt }),
817
+ ...(sessionId === undefined
818
+ ? {}
819
+ : { sessionId }),
820
+ ...(record.sessionFile === undefined ? {} : { sessionFile: record.sessionFile }),
821
+ ...(record.outputFile === undefined ? {} : { outputFile: record.outputFile }),
822
+ ...(record.invocation === undefined ? {} : { invocation: { ...record.invocation } }),
823
+ lifetimeUsage: { ...record.lifetimeUsage },
824
+ compactionCount: record.compactionCount,
825
+ ...(record.isBackground === undefined ? {} : { isBackground: record.isBackground }),
826
+ ...(record.depth === undefined ? {} : { depth: record.depth }),
827
+ ...(record.handle === undefined ? {} : { handle: record.handle }),
828
+ ...(record.alias === undefined ? {} : { alias: record.alias }),
829
+ ...(record.groupId === undefined ? {} : { groupId: record.groupId }),
830
+ ...(record.runGeneration === undefined ? {} : { runGeneration: record.runGeneration }),
831
+ ...(record.structuredJson === undefined ? {} : { structuredJson: record.structuredJson }),
832
+ ...(record.structuredRetried === undefined ? {} : { structuredRetried: record.structuredRetried }),
833
+ ...(record.droppedSteers === undefined ? {} : { droppedSteers: record.droppedSteers }),
834
+ ...(record.resultConsumed === undefined ? {} : { resultConsumed: record.resultConsumed }),
835
+ ...(record.parentAgentId === undefined ? {} : { parentAgentId: record.parentAgentId }),
836
+ ...(record.workflowId === undefined ? {} : { workflowId: record.workflowId }),
837
+ ...(record.ownerIds === undefined ? {} : { ownerIds: [...record.ownerIds] }),
838
+ ...(record.rootSessionId === undefined ? {} : { rootSessionId: record.rootSessionId }),
839
+ ...(record.rootCwd === undefined ? {} : { rootCwd: record.rootCwd }),
840
+ ...(record.rootSessionFile === undefined ? {} : { rootSessionFile: record.rootSessionFile }),
841
+ ...(record.pendingSteers === undefined ? {} : { pendingSteers: [...record.pendingSteers] }),
842
+ };
843
+ }
844
+
845
+ /** The store already bound for a record's own root, if that root has one. */
846
+ function storeForRecord(record: AgentRecord): ReportStore | undefined {
847
+ if (record.rootSessionId !== undefined) return reportStores.get(record.rootSessionId);
848
+ return reportBoundRoot === undefined ? undefined : reportStore;
849
+ }
850
+
851
+ function saveArchivedRecord(record: AgentRecord): void {
852
+ const target = storeForRecord(record);
853
+ if (target === undefined) {
854
+ pendingArchivedRecords.set(record.id, cloneRecordForArchive(record));
855
+ return;
856
+ }
857
+ const saving = target.save(record);
858
+ void saving.then((result) => {
859
+ // A saved FULL entry (which `save` only writes when no deletion receipt is
860
+ // present) is the one durable proof that replaces an unprovable receipt.
861
+ // Starting/resuming a run is not proof: `save` refuses to overwrite the
862
+ // receipt on its own, so the id stays refused until this lands.
863
+ if (result.saved === true) {
864
+ archiveRetryAttempts.delete(record.id);
865
+ cleanupUnprovenReports.delete(record.id);
866
+ return;
867
+ }
868
+ const transient = result.reason === "cleanup-lock" || result.reason === "cleanup-lock-unreadable"
869
+ || result.reason === "store-closed" || result.reason === "not-bound";
870
+ if (transient) {
871
+ // The pending archive must not be dropped just because the store that
872
+ // accepted the drain later refused a save. Keep the record queued for
873
+ // the next binding/retry while the reason is transient.
874
+ pendingArchivedRecords.set(record.id, cloneRecordForArchive(record));
875
+ schedulePendingArchiveDrain(record.id);
876
+ } else {
877
+ archiveRetryAttempts.delete(record.id);
878
+ if (result.reason !== "persist-disabled") {
879
+ console.warn(`[pi-subagents] durable report save refused for ${record.id}: ${result.reason}`);
880
+ }
881
+ }
882
+ }).catch((error: unknown) => {
883
+ console.warn("[pi-subagents] durable report save failed:", error);
884
+ });
885
+ }
886
+
887
+ function drainPendingArchivedRecords(): void {
888
+ const pending = [...pendingArchivedRecords.values()];
889
+ pendingArchivedRecords.clear();
890
+ for (const record of pending) saveArchivedRecord(record);
891
+ }
892
+
893
+ function schedulePendingArchiveDrain(recordId: string): void {
894
+ const attempts = archiveRetryAttempts.get(recordId) ?? 0;
895
+ if (attempts >= MAX_ARCHIVE_RETRIES) {
896
+ console.warn(`[pi-subagents] durable report retry limit reached for ${recordId}`);
897
+ return;
898
+ }
899
+ archiveRetryAttempts.set(recordId, attempts + 1);
900
+ if (archiveDrainTimer !== undefined) return;
901
+ const delay = Math.min(100 * 2 ** Math.max(0, attempts - 1), 1000);
902
+ archiveDrainTimer = setTimeout(() => {
903
+ archiveDrainTimer = undefined;
904
+ drainPendingArchivedRecords();
905
+ }, delay);
906
+ archiveDrainTimer.unref?.();
907
+ }
908
+
909
+ function reportContextFor(ctx: ExtensionContext): ReportContext | undefined {
910
+ const rootSessionId = ctx.sessionManager?.getSessionId?.();
911
+ if (!rootSessionId) return undefined;
912
+ const rootSessionFile = ctx.sessionManager?.getSessionFile?.();
913
+ return {
914
+ cwd: ctx.cwd,
915
+ rootSessionId,
916
+ ...(rootSessionFile === undefined ? {} : { rootSessionFile }),
917
+ persistReports: rootSessionFile !== undefined,
918
+ };
919
+ }
920
+
921
+ /** A root with live/finalizing work keeps its store until a later boundary. */
922
+ function reportRootHasLiveWork(rootSessionId: string): boolean {
923
+ if (manager.listAgents().some(record =>
924
+ (record.rootSessionId ?? reportBoundRoot) === rootSessionId)) return true;
925
+ for (const [id, task] of workflowTasks) {
926
+ if (workflowArtifactRoots.get(id) !== rootSessionId) continue;
927
+ if (task.status === "running" || task.status === "paused"
928
+ || workflowRunPromises.has(id) || workflowJournalDrains.has(id)) return true;
929
+ }
930
+ return false;
931
+ }
932
+
933
+ /**
934
+ * Close together so every store stops write admission before any await. An
935
+ * incomplete close is explicit and retains that store's lease; it is never
936
+ * logged or treated as a successful durable drain.
937
+ */
938
+ async function closeReportStores(stores: ReadonlySet<ReportStore>, quiescent: boolean): Promise<void> {
939
+ await Promise.all([...stores].map(async store => {
940
+ try {
941
+ const drained = await store.close({ quiescent });
942
+ if (drained.status !== "flushed") {
943
+ console.warn(`[pi-subagents] durable report flush incomplete (${drained.reason}); lease retained`);
944
+ }
945
+ } catch (error) {
946
+ console.warn("[pi-subagents] durable report close failed:", error);
947
+ }
948
+ }));
949
+ }
950
+
951
+ /**
952
+ * Replacement prunes only roots with no live records/runs. Their accepted
953
+ * writes and maintenance drain inside close; roots still producing reports
954
+ * keep the exact store pinned to that work.
955
+ */
956
+ async function pruneReportStores(nextRoot: string): Promise<void> {
957
+ drainPendingArchivedRecords();
958
+ const candidates = [...reportStores.entries()].filter(([root]) =>
959
+ root !== nextRoot && !reportRootHasLiveWork(root));
960
+ if (candidates.length === 0) return;
961
+ const retired = new Set(candidates.map(([, store]) => store));
962
+ if (candidates.some(([root]) => root === reportBoundRoot)) reportBoundRoot = undefined;
963
+ await closeReportStores(retired, true);
964
+ for (const [root, store] of candidates) {
965
+ if (reportStores.get(root) === store) reportStores.delete(root);
966
+ reportActiveRoots.delete(root);
967
+ }
968
+ for (const [id, store] of workflowArtifactStores) {
969
+ if (retired.has(store)) workflowArtifactStores.delete(id);
970
+ }
971
+ }
972
+
973
+ /**
974
+ * Bind the store to the current ROOT session, lazily for callers that enter
975
+ * without a `session_start` (tests, RPC-only harnesses). Serialized so a
976
+ * late bind can never overwrite a newer root's binding, and plain-data only.
977
+ */
978
+ function ensureReportBinding(ctx: ExtensionContext): Promise<void> {
979
+ const context = reportContextFor(ctx);
980
+ if (!context) return Promise.resolve();
981
+ if (reportBoundRoot === context.rootSessionId && reportActiveRoots.has(context.rootSessionId)) return Promise.resolve();
982
+ const next = reportBindChain
983
+ .then(async () => {
984
+ if (reportBoundRoot === context.rootSessionId && reportActiveRoots.has(context.rootSessionId)) return;
985
+ await pruneReportStores(context.rootSessionId);
986
+ let target = reportStores.get(context.rootSessionId);
987
+ if (target?.isClosed) {
988
+ // A closed/closing store is never a candidate for a new activation,
989
+ // even when the root id is reused by a later session.
990
+ reportStores.delete(context.rootSessionId);
991
+ reportActiveRoots.delete(context.rootSessionId);
992
+ target = undefined;
993
+ }
994
+ if (target === undefined) {
995
+ const extra: string[] = [];
996
+ if (context.rootSessionFile !== undefined) extra.push(dirname(context.rootSessionFile));
997
+ target = createReportStore(extra);
998
+ } else if (reportActiveRoots.has(context.rootSessionId)) {
999
+ // Switching back to a still-bound root: keep its lease/context.
1000
+ reportStore = target;
1001
+ reportBoundRoot = context.rootSessionId;
1002
+ drainPendingArchivedRecords();
1003
+ return;
1004
+ }
1005
+ const binding = await target.bind(context);
1006
+ if (binding.active) reportActiveRoots.add(context.rootSessionId);
1007
+ else {
1008
+ reportActiveRoots.delete(context.rootSessionId);
1009
+ console.warn(`[pi-subagents] durable report binding refused for ${context.rootSessionId}: ${binding.reason}`);
1010
+ }
1011
+ reportStores.set(context.rootSessionId, target);
1012
+ reportStore = target;
1013
+ // An inactive store still supports reads, but the next operation retries
1014
+ // activation: a transient cleanup lock must not strand this root forever.
1015
+ reportBoundRoot = context.rootSessionId;
1016
+ drainPendingArchivedRecords();
1017
+ })
1018
+ .catch((error: unknown) => {
1019
+ console.warn("[pi-subagents] durable report store unavailable:", error);
1020
+ });
1021
+ reportBindChain = next;
1022
+ return next;
1023
+ }
1024
+
1025
+ /**
1026
+ * Await a root's own binding admission before an Agent run may create a
1027
+ * session, transcript or worktree.
1028
+ *
1029
+ * A supported SDK host can create a session and call `prompt()` without
1030
+ * `bindExtensions()` (installed docs/sdk.md and examples/sdk/06-extensions.ts),
1031
+ * so `session_start` — the only startup bind — never fires. The lazy bind the
1032
+ * tool starts is then the FIRST activation of that root, and an absent store
1033
+ * is not permission to spawn: a cleanup lock or a refused activation must be
1034
+ * seen before the first artifact exists. `reportBindChain` already serializes
1035
+ * that bind, so awaiting it adds nothing but the proof.
1036
+ *
1037
+ * An already-active root returns without yielding, preserving the same-tick
1038
+ * foreground batch; an intentionally ephemeral context keeps its historical
1039
+ * synchronous deferred-bind contract.
1040
+ */
1041
+ function reportBindingAdmission(ctx: ExtensionContext): Promise<void> | undefined {
1042
+ const context = reportContextFor(ctx);
1043
+ if (context === undefined || context.persistReports !== true) return undefined;
1044
+ const root = context.rootSessionId;
1045
+ // Already active / intentional ephemeral / reserved: no promise at all, so
1046
+ // the caller does not even yield a microtask (same-tick batch + no widened
1047
+ // window against a transient maintenance lock).
1048
+ if (reportActiveRoots.has(root)) return undefined;
1049
+ // A root this operation is about to delete is never bound: binding publishes
1050
+ // a lease and runs maintenance. The acquisition guard below refuses it.
1051
+ if (cleanupRootReserved(root)) return undefined;
1052
+ return ensureReportBinding(ctx);
1053
+ }
1054
+
1055
+ /**
1056
+ * Synchronous half of the same boundary for entry points that cannot await
1057
+ * (the cross-package registry and the bus RPC handlers, both synchronous by
1058
+ * contract). A persistent root with no proven-active store refuses before a
1059
+ * new id or SDK history exists; an ephemeral context keeps its behavior.
1060
+ */
1061
+ function assertReportBindingAdmission(ctx: ExtensionContext): void {
1062
+ const context = reportContextFor(ctx);
1063
+ if (context === undefined || context.persistReports !== true) return;
1064
+ if (reportActiveRoots.has(context.rootSessionId)) return;
1065
+ throw new ReportUnavailableError("report-binding-not-active");
1066
+ }
1067
+
576
1068
  // Background completion: route through group join or send individual nudge
577
1069
  const manager = new AgentManager((record) => {
578
1070
  // Every settle changes whether subagent work remains, which is what the
@@ -605,7 +1097,6 @@ export default function (pi: ExtensionAPI) {
605
1097
  if (record.resultConsumed) {
606
1098
  agentActivity.delete(record.id);
607
1099
  widget.markFinished(record.id);
608
- fleet.onAgentFinished(record.id);
609
1100
  widget.update();
610
1101
  return;
611
1102
  }
@@ -634,8 +1125,6 @@ export default function (pi: ExtensionAPI) {
634
1125
  if (currentCtx?.hasUI) {
635
1126
  widget.ensureTimer();
636
1127
  widget.update();
637
- fleet.ensureTimer();
638
- fleet.update();
639
1128
  }
640
1129
  // Emit started event when agent transitions to running (including from queue)
641
1130
  pi.events.emit("subagents:started", {
@@ -662,6 +1151,1085 @@ export default function (pi: ExtensionAPI) {
662
1151
  if (reportUsage) pendingUsage.add(usage);
663
1152
  });
664
1153
 
1154
+ // Every terminal generation reaches the archiver, including the foreground
1155
+ // resumes and queued stops that never call onComplete.
1156
+ manager.setReportArchiver({ save: record => saveArchivedRecord(record) });
1157
+ // Acquire-side cleanup barrier: reserved roots and selected ids/paths refuse
1158
+ // new artifact work before a session, output or worktree is written.
1159
+ manager.setArtifactAccessGuard(record => assertCleanupArtifactAccessAsync(record));
1160
+ // Injected into nested tools via the runner so an owner can read its own
1161
+ // archived child after eviction; `findOwned` enforces exact parentAgentId.
1162
+ manager.setArchivedReportReader({
1163
+ findOwned: async (ref, owner) => {
1164
+ // A live record can be evicted in the same tick its snapshot was queued;
1165
+ // flush before the durable read so it observes its own completed write.
1166
+ const parent = manager.getRecord(owner.id);
1167
+ const target = (parent === undefined ? undefined : storeForRecord(parent)) ?? reportStore;
1168
+ const ownerRoot = parent?.rootSessionId;
1169
+ // The lookup below re-reads the durable entry after every await, so it is
1170
+ // never a cached body. The token only has to catch a cleanup that took or
1171
+ // released the owner's root while this call was in flight.
1172
+ const token = cleanupReadTokenFor(ownerRoot);
1173
+ const drained = await target.flush();
1174
+ if (drained.status !== "flushed") {
1175
+ return { status: "missing", ref, reason: `report-writes-not-flushed:${drained.reason}` } as const;
1176
+ }
1177
+ const lookup = await target.findOwned(ref, owner.id, owner);
1178
+ if (lookup.status === "found") {
1179
+ const refusal = cleanupReadRefusal({
1180
+ agentId: lookup.report.id,
1181
+ sessionFile: lookup.report.sessionFile,
1182
+ rootSessionId: lookup.report.rootSessionId,
1183
+ });
1184
+ if (refusal !== undefined) {
1185
+ return { status: "missing", ref, reason: refusal } as const;
1186
+ }
1187
+ if (cleanupReadTokenFor(ownerRoot) !== token) {
1188
+ return { status: "missing", ref, reason: "cleanup-changed-owner-root" } as const;
1189
+ }
1190
+ }
1191
+ return lookup;
1192
+ },
1193
+ });
1194
+
1195
+ // ---- Cleanup command, read/producer barriers and reservations ----
1196
+
1197
+ interface ParsedCleanupArgs {
1198
+ scope: "session" | "global";
1199
+ dryRun: boolean;
1200
+ includeLegacy: boolean;
1201
+ }
1202
+
1203
+ function parseCleanupArgs(tokens: readonly string[]): ParsedCleanupArgs | undefined {
1204
+ let scope: "session" | "global" = "session";
1205
+ let scopeSeen = false;
1206
+ let dryRun = false;
1207
+ let includeLegacy = false;
1208
+ for (const raw of tokens) {
1209
+ const token = raw.toLowerCase();
1210
+ if (token === "session" || token === "global") {
1211
+ if (scopeSeen) return undefined;
1212
+ scope = token;
1213
+ scopeSeen = true;
1214
+ continue;
1215
+ }
1216
+ if (token === "--dry-run") {
1217
+ if (dryRun) return undefined;
1218
+ dryRun = true;
1219
+ continue;
1220
+ }
1221
+ if (token === "--include-legacy") {
1222
+ if (includeLegacy) return undefined;
1223
+ includeLegacy = true;
1224
+ continue;
1225
+ }
1226
+ // Includes on/off, --yes/-y/--force and any unknown flag: cleanup never
1227
+ // toggles or bypasses its explicit confirmation.
1228
+ return undefined;
1229
+ }
1230
+ return { scope, dryRun, includeLegacy };
1231
+ }
1232
+
1233
+ function cleanupUsage(): string {
1234
+ return "Usage: /subagents cleanup [session|global] [--dry-run] [--include-legacy] — nothing is deleted without an explicit preview and confirmation. Use /subagents on|off for the model policy toggle.";
1235
+ }
1236
+
1237
+ function safeCleanupText(value: string): string {
1238
+ // JSON escaping covers quotes, backslashes and C0; C1/DEL are not escaped by
1239
+ // JSON.stringify and are the remaining terminal-control injection surface.
1240
+ return JSON.stringify(value).replace(/[\u007f-\u009f]/g, ch =>
1241
+ `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`);
1242
+ }
1243
+
1244
+ function cleanupOperationCurrent(op: CleanupOperation): boolean {
1245
+ return op.epoch === sessionEpoch && op.readRoot() === op.rootSessionId;
1246
+ }
1247
+
1248
+ function cleanupPathKey(path: string): string {
1249
+ return normalizeReportPath(path);
1250
+ }
1251
+
1252
+ function cleanupSelectionPaths(...paths: readonly (string | undefined)[]): string[] {
1253
+ return paths.filter((path): path is string => path !== undefined).map(cleanupPathKey);
1254
+ }
1255
+
1256
+ /** The store that actually owns this root — i.e. one whose bind was attempted. */
1257
+ function owningReportStore(rootSessionId: string | undefined): ReportStore | undefined {
1258
+ if (rootSessionId === undefined) return undefined;
1259
+ const store = reportStores.get(rootSessionId);
1260
+ return store?.bindingContext?.rootSessionId === rootSessionId ? store : undefined;
1261
+ }
1262
+
1263
+ /** Whether this command has an operation that is about to delete this root. */
1264
+ function cleanupRootReserved(rootSessionId: string | undefined): boolean {
1265
+ const op = cleanupOperation;
1266
+ return rootSessionId !== undefined
1267
+ && op !== undefined
1268
+ && cleanupOperationCurrent(op)
1269
+ && op.reservedRoots.has(rootSessionId);
1270
+ }
1271
+
1272
+ /**
1273
+ * Whether a planned id is still operation-LOCALLY selected. The answer is
1274
+ * deliberately conditioned on the entry's root still being reserved: a root
1275
+ * that froze as busy or whose generation was superseded keeps its work, so it
1276
+ * must not carry an id/path barrier cleanup will never act on. Real store
1277
+ * locks are enforced separately and always.
1278
+ */
1279
+ function cleanupAgentSelected(op: CleanupOperation, agentId: string): boolean {
1280
+ const root = op.planAgentRoots.get(agentId);
1281
+ return root !== undefined && op.reservedRoots.has(root);
1282
+ }
1283
+
1284
+ function cleanupPathSelected(op: CleanupOperation, path: string): boolean {
1285
+ const root = op.planPathRoots.get(path);
1286
+ return root !== undefined && op.reservedRoots.has(root);
1287
+ }
1288
+
1289
+ /**
1290
+ * Index-local reservations, re-run synchronously after the last store I/O.
1291
+ * A cleanup command's selection is command-local state, not filesystem truth:
1292
+ * it must be checked in the same tick as the admission it protects, or a
1293
+ * cleanup that began while an async guard was suspended could slip through.
1294
+ */
1295
+ function assertCleanupLocalAccess(
1296
+ rootSessionId: string | undefined,
1297
+ paths: readonly (string | undefined)[],
1298
+ agentId?: string,
1299
+ ): void {
1300
+ const op = cleanupOperation;
1301
+ if (op === undefined || !cleanupOperationCurrent(op)) return;
1302
+ for (const path of cleanupSelectionPaths(...paths)) {
1303
+ if (cleanupPathSelected(op, path)) throw new ReportUnavailableError("cleanup-selected-path");
1304
+ }
1305
+ if (agentId !== undefined && cleanupAgentSelected(op, agentId)) {
1306
+ throw new ReportUnavailableError("cleanup-selected-agent");
1307
+ }
1308
+ if (rootSessionId === undefined) throw new ReportUnavailableError("cleanup-unknown-root");
1309
+ if (op.reservedRoots.has(rootSessionId)) throw new ReportUnavailableError("cleanup-reserved-root");
1310
+ }
1311
+
1312
+ /**
1313
+ * Acquire-side barrier.
1314
+ *
1315
+ * The owning store's REAL activation/root availability is enforced
1316
+ * unconditionally: a valid foreign lock that was already held when this
1317
+ * activation first met the root leaves the store inactive, and "no local
1318
+ * cleanup operation" is not permission to start a session, transcript,
1319
+ * worktree or workflow on top of it. Only the command-local reservations and
1320
+ * selections are conditional, because they exist only while a command is
1321
+ * applying.
1322
+ */
1323
+ function assertCleanupRootAccess(rootSessionId: string | undefined, paths: readonly (string | undefined)[] = []): void {
1324
+ const store = owningReportStore(rootSessionId);
1325
+ // Inactive activation, closed store, or a live/uncertain lock of its own
1326
+ // root. Reads deliberately do NOT come through here (see cleanupReadRefusal).
1327
+ store?.assertAvailable();
1328
+ assertCleanupLocalAccess(rootSessionId, paths);
1329
+ if (rootSessionId === undefined) return;
1330
+ // Canonical selection of exactly these artifacts by any lock, local or
1331
+ // foreign, is enforced even with no operation of ours running. One combined
1332
+ // scan, not one full listing per path.
1333
+ const scan = store ?? reportStore;
1334
+ const sessionFiles = cleanupSelectionPaths(...paths);
1335
+ if (sessionFiles.length > 0) scan.assertAvailableAny({ sessionFiles });
1336
+ }
1337
+
1338
+ /**
1339
+ * Awaitable twin of {@link assertCleanupRootAccess} for paths that have
1340
+ * already suspended. Store I/O comes first; the command-local reservations
1341
+ * are re-checked synchronously afterwards, so no await sits between that
1342
+ * final check and admission.
1343
+ */
1344
+ async function assertCleanupRootAccessAsync(
1345
+ rootSessionId: string | undefined,
1346
+ paths: readonly (string | undefined)[] = [],
1347
+ ): Promise<void> {
1348
+ const store = owningReportStore(rootSessionId);
1349
+ if (store !== undefined) await store.assertAvailableAsync();
1350
+ if (rootSessionId !== undefined) {
1351
+ const scan = store ?? reportStore;
1352
+ const sessionFiles = cleanupSelectionPaths(...paths);
1353
+ if (sessionFiles.length > 0) await scan.assertAvailableAnyAsync({ sessionFiles });
1354
+ }
1355
+ // LAST: no await after the local reservation check.
1356
+ assertCleanupLocalAccess(rootSessionId, paths);
1357
+ }
1358
+
1359
+ /**
1360
+ * Awaitable artifact barrier for the manager's acquire-side guard and for
1361
+ * resume paths. One combined async scan covers the agent id, its session and
1362
+ * its transcript; the index-local reservations are re-checked last.
1363
+ */
1364
+ async function assertCleanupArtifactAccessAsync(record: AgentRecord): Promise<void> {
1365
+ // An unproven deletion receipt is an ids-only barrier that outlives its
1366
+ // operation: a live resume keeps this agent's id, so it must not reopen
1367
+ // work or write a transcript over a body cleanup may already have removed.
1368
+ if (cleanupUnprovenReports.has(record.id)) throw new ReportUnavailableError("cleanup-receipt-unproven");
1369
+ const owning = owningReportStore(record.rootSessionId);
1370
+ if (owning !== undefined) await owning.assertAvailableAsync();
1371
+ const store = (record.rootSessionId === undefined ? undefined : reportStores.get(record.rootSessionId)) ?? reportStore;
1372
+ await store.assertAvailableAnyAsync({
1373
+ agentId: record.id,
1374
+ sessionFiles: cleanupSelectionPaths(record.sessionFile, record.outputFile),
1375
+ });
1376
+ // LAST: no await after the local reservation check.
1377
+ assertCleanupLocalAccess(
1378
+ record.rootSessionId,
1379
+ [record.sessionFile, record.outputFile],
1380
+ record.id,
1381
+ );
1382
+ }
1383
+
1384
+ /**
1385
+ * Why an exact report/session read must not continue, or undefined.
1386
+ *
1387
+ * Cleanup state is consulted when an operation is applying (and only for the
1388
+ * roots it actually reserved); the store's own lock view is consulted ALWAYS,
1389
+ * so a foreign cleanup deleting this exact agent/session is refused even
1390
+ * though this process never ran the command.
1391
+ */
1392
+ function cleanupReadRefusal(ref: {
1393
+ agentId?: string;
1394
+ sessionFile?: string;
1395
+ path?: string;
1396
+ rootSessionId?: string;
1397
+ }): string | undefined {
1398
+ // Unprovable receipt state outlives the operation: the barrier is gone, but
1399
+ // the durable entry may already be a deletion receipt.
1400
+ if (ref.agentId !== undefined && cleanupUnprovenReports.has(ref.agentId)) return "cleanup-receipt-unproven";
1401
+ const op = cleanupOperation;
1402
+ if (op !== undefined && cleanupOperationCurrent(op)) {
1403
+ if (ref.agentId !== undefined && cleanupAgentSelected(op, ref.agentId)) return "cleanup-in-progress";
1404
+ const paths = cleanupSelectionPaths(ref.sessionFile, ref.path);
1405
+ if (paths.some(path => cleanupPathSelected(op, path))) return "cleanup-in-progress";
1406
+ }
1407
+ const store = (ref.rootSessionId === undefined ? undefined : reportStores.get(ref.rootSessionId)) ?? reportStore;
1408
+ try {
1409
+ store.assertAvailable(ref.agentId, ref.sessionFile);
1410
+ } catch (error) {
1411
+ if (error instanceof ReportUnavailableError) return `cleanup-in-progress:${error.message}`;
1412
+ throw error;
1413
+ }
1414
+ return undefined;
1415
+ }
1416
+
1417
+ function cleanupReadTokenFor(rootSessionId: string | undefined): number {
1418
+ return rootSessionId === undefined ? 0 : (cleanupReadInvalidations.get(rootSessionId) ?? 0);
1419
+ }
1420
+
1421
+ /**
1422
+ * Record every selected report whose receipt state cleanup could not prove.
1423
+ *
1424
+ * The backend answers a report candidate in exactly one of three ways: marked
1425
+ * deleted (a durable deleted entry was read back), failed with
1426
+ * `receipt-state-uncertain` (the entry could not be read at all), or failed
1427
+ * with `receipt-failed` (the mutator rejected and the entry did not read back
1428
+ * as a deletion — which includes the entry being absent/unparseable). The last
1429
+ * two cannot prove the body survived, so they fail closed here rather than
1430
+ * leaving the cached live report readable after the barrier is released.
1431
+ */
1432
+ function markUnprovenCleanupReports(result: CleanupResult): void {
1433
+ for (const failure of result.failed) {
1434
+ if (failure.agentId === undefined || failure.kind !== "report-entry") continue;
1435
+ if (!failure.reason.startsWith("receipt-")) continue;
1436
+ if (result.deletedAgentIds.includes(failure.agentId)) continue;
1437
+ cleanupUnprovenReports.add(failure.agentId);
1438
+ }
1439
+ }
1440
+
1441
+ /** Bump every root an operation will touch, at both edges of that operation. */
1442
+ function invalidateCleanupReads(roots: Iterable<string>): void {
1443
+ for (const root of roots) cleanupReadInvalidations.set(root, cleanupReadTokenFor(root) + 1);
1444
+ }
1445
+
1446
+ function addCleanupPaths(target: Set<string>, ...paths: readonly (string | undefined)[]): void {
1447
+ for (const path of paths) {
1448
+ if (path === undefined) continue;
1449
+ target.add(cleanupPathKey(path));
1450
+ let parent = dirname(path);
1451
+ while (parent.length > 1 && parent !== dirname(parent)) {
1452
+ target.add(cleanupPathKey(parent));
1453
+ parent = dirname(parent);
1454
+ }
1455
+ }
1456
+ }
1457
+
1458
+ /** Synchronous runtime proof used by preview, reservations and every unlink gate. */
1459
+ function collectCleanupRuntime(): CleanupRuntimeSnapshot {
1460
+ const activeAgentIds = new Set<string>();
1461
+ const activeWorkflowIds = new Set<string>();
1462
+ const protectedPaths = new Set<string>();
1463
+ const unreadAgentIds = new Set<string>();
1464
+ const protectedRoots = new Set<string>();
1465
+ let unknownRootActivity = false;
1466
+
1467
+ const addRoot = (rootSessionId: string | undefined): void => {
1468
+ if (rootSessionId !== undefined && rootSessionId.length > 0) protectedRoots.add(rootSessionId);
1469
+ else unknownRootActivity = true;
1470
+ };
1471
+ const visited = new Set<AgentRecord>();
1472
+ const addRecord = (record: AgentRecord): void => {
1473
+ const stack = [record];
1474
+ while (stack.length > 0) {
1475
+ const current = stack.pop();
1476
+ if (current === undefined || visited.has(current)) continue;
1477
+ visited.add(current);
1478
+ activeAgentIds.add(current.id);
1479
+ addRoot(current.rootSessionId);
1480
+ addCleanupPaths(protectedPaths, current.sessionFile, current.outputFile);
1481
+ for (const ownerId of current.ownerIds ?? []) {
1482
+ activeAgentIds.add(ownerId);
1483
+ const owner = manager.getRecord(ownerId);
1484
+ if (owner === undefined) unknownRootActivity = true;
1485
+ else stack.push(owner);
1486
+ }
1487
+ if (current.parentAgentId !== undefined) {
1488
+ activeAgentIds.add(current.parentAgentId);
1489
+ const parent = manager.getRecord(current.parentAgentId);
1490
+ if (parent === undefined) unknownRootActivity = true;
1491
+ else stack.push(parent);
1492
+ }
1493
+ }
1494
+ };
1495
+
1496
+ for (const id of manager.getBusyAgentIds()) {
1497
+ const record = manager.getRecord(id);
1498
+ if (record === undefined) {
1499
+ activeAgentIds.add(id);
1500
+ unknownRootActivity = true;
1501
+ } else {
1502
+ addRecord(record);
1503
+ }
1504
+ }
1505
+ for (const row of manager.listUncertainTeardowns()) {
1506
+ activeAgentIds.add(row.agentId);
1507
+ addRoot(row.rootSessionId);
1508
+ addCleanupPaths(protectedPaths, row.sessionFile, row.rootSessionFile);
1509
+ }
1510
+ for (const record of manager.listAgents()) {
1511
+ if (record.resultConsumed !== true) unreadAgentIds.add(record.id);
1512
+ }
1513
+ for (const task of workflowTasks.values()) {
1514
+ const proof = workflowCleanupProofs.get(task.id);
1515
+ const active = proof !== undefined || task.status === "running" || task.status === "paused";
1516
+ if (!active) continue;
1517
+ activeWorkflowIds.add(task.id);
1518
+ addRoot(proof?.rootSessionId ?? workflowArtifactRoots.get(task.id));
1519
+ const paths = workflowArtifactPaths.get(task.id);
1520
+ addCleanupPaths(protectedPaths, ...(paths?.generatedPaths ?? []), ...(paths?.externalPaths ?? []));
1521
+ addCleanupPaths(protectedPaths, ...(proof?.generatedPaths ?? []), ...(proof?.externalPaths ?? []));
1522
+ }
1523
+ for (const [id, proof] of workflowCleanupProofs) {
1524
+ activeWorkflowIds.add(id);
1525
+ addRoot(proof.rootSessionId);
1526
+ addCleanupPaths(protectedPaths, ...proof.generatedPaths, ...proof.externalPaths);
1527
+ }
1528
+
1529
+ return {
1530
+ activeAgentIds,
1531
+ activeWorkflowIds,
1532
+ protectedPaths,
1533
+ unreadAgentIds,
1534
+ protectedRoots,
1535
+ unknownRootActivity,
1536
+ hasActiveWork: activeAgentIds.size > 0 || activeWorkflowIds.size > 0 || unknownRootActivity,
1537
+ };
1538
+ }
1539
+
1540
+ function cleanupLiveStateForRuntime(
1541
+ runtime: CleanupRuntimeSnapshot,
1542
+ protectAllCandidates?: ReadonlySet<string>,
1543
+ ): CleanupLiveState {
1544
+ const protectedRoots = new Set(runtime.protectedRoots);
1545
+ if (runtime.unknownRootActivity) {
1546
+ for (const root of protectAllCandidates ?? []) protectedRoots.add(root);
1547
+ }
1548
+ return {
1549
+ activeAgentIds: runtime.activeAgentIds,
1550
+ activeWorkflowIds: runtime.activeWorkflowIds,
1551
+ protectedPaths: runtime.protectedPaths,
1552
+ unreadAgentIds: runtime.unreadAgentIds,
1553
+ diagnosticsBusy: runtime.hasActiveWork,
1554
+ protectedRootSessionIds: protectedRoots,
1555
+ };
1556
+ }
1557
+
1558
+ /** Build the preview without ever acquiring a cleanup lock or touching a file. */
1559
+ async function buildCleanupPreviewPlan(
1560
+ baseStore: ReportStore,
1561
+ scope: "session" | "global",
1562
+ includeLegacy: boolean,
1563
+ runtime: CleanupRuntimeSnapshot,
1564
+ stores: ReadonlyMap<string, ReportStore>,
1565
+ previewRootSessionId?: string,
1566
+ ): Promise<CleanupPlan> {
1567
+ const build = async (protectAllCandidates?: ReadonlySet<string>): Promise<CleanupPlan> => {
1568
+ const liveState = () => cleanupLiveStateForRuntime(runtime, protectAllCandidates);
1569
+ const base = await planCleanup(baseStore, scope, liveState, { includeLegacy, previewRootSessionId });
1570
+ if (scope !== "global") return base;
1571
+ const overrides = new Map<string, CleanupPlan>();
1572
+ for (const [rootSessionId, store] of stores) {
1573
+ if (store.bindingContext?.rootSessionId !== rootSessionId) continue;
1574
+ overrides.set(rootSessionId, await planCleanup(store, "session", liveState, { includeLegacy }));
1575
+ }
1576
+ return mergeCleanupPlans(base, overrides);
1577
+ };
1578
+ let plan = await build();
1579
+ if (runtime.unknownRootActivity) {
1580
+ const roots = new Set(
1581
+ plan.files.map(file => file.rootSessionId).filter(root => root.length > 0),
1582
+ );
1583
+ if (roots.size > 0) plan = await build(roots);
1584
+ }
1585
+ return plan;
1586
+ }
1587
+
1588
+ /**
1589
+ * Snapshot every live record the preview could select, BEFORE planning or any
1590
+ * UI wait. Plain object identity + the numeric run generation only: a resume
1591
+ * that lands while the preview/confirmation is open must remain a NEW
1592
+ * generation this cleanup never selected.
1593
+ */
1594
+ function snapshotLiveRecords(): Map<string, { record: AgentRecord; runGeneration: number }> {
1595
+ const result = new Map<string, { record: AgentRecord; runGeneration: number }>();
1596
+ for (const record of manager.listAgents()) {
1597
+ result.set(record.id, { record, runGeneration: record.runGeneration ?? 0 });
1598
+ }
1599
+ return result;
1600
+ }
1601
+
1602
+ /**
1603
+ * Planned ids that had a live record when the pre-plan snapshot was taken.
1604
+ * A planned id absent from that snapshot is not previewed as live: if a record
1605
+ * exists for it later, it is a NEW live id and its root is conservatively
1606
+ * changed (see the post-confirmation freeze below).
1607
+ */
1608
+ function selectPreviewRecords(
1609
+ plan: CleanupPlan,
1610
+ snapshot: ReadonlyMap<string, { record: AgentRecord; runGeneration: number }>,
1611
+ ): Map<string, CleanupPreviewRecord> {
1612
+ const result = new Map<string, CleanupPreviewRecord>();
1613
+ for (const file of plan.files) {
1614
+ if (file.agentId === undefined || result.has(file.agentId)) continue;
1615
+ const captured = snapshot.get(file.agentId);
1616
+ if (captured === undefined) continue;
1617
+ result.set(file.agentId, {
1618
+ record: captured.record,
1619
+ runGeneration: captured.runGeneration,
1620
+ rootSessionId: file.rootSessionId.length > 0 ? file.rootSessionId : captured.record.rootSessionId,
1621
+ });
1622
+ }
1623
+ return result;
1624
+ }
1625
+
1626
+ function isSelectedLiveRecord(
1627
+ record: AgentRecord,
1628
+ preview: ReadonlyMap<string, CleanupPreviewRecord>,
1629
+ ): boolean {
1630
+ const snapshot = preview.get(record.id);
1631
+ return snapshot !== undefined
1632
+ && snapshot.record === record
1633
+ && snapshot.runGeneration === (record.runGeneration ?? 0)
1634
+ && record.status !== "running"
1635
+ && record.status !== "queued";
1636
+ }
1637
+
1638
+ /**
1639
+ * Count the delivery windows confirmation will actually discard — and only
1640
+ * those. Three separate truths are reported separately: unread artifact files
1641
+ * (`counts.unread`), unread LIVE reports (`countSelectedUnreadReports`) and
1642
+ * pending deliveries (here). A workflow's held notice is one window under the
1643
+ * run id, not an agent id; a member whose result was already consumed, or
1644
+ * whose record moved to a newer run, cannot deliver at all and is not counted.
1645
+ */
1646
+ function countPendingSelectedDeliveries(
1647
+ plan: CleanupPlan,
1648
+ preview: ReadonlyMap<string, CleanupPreviewRecord>,
1649
+ ): number {
1650
+ const selected = new Set(plan.agentIds);
1651
+ const pending = new Set<string>();
1652
+ const eligible = (id: string): boolean => {
1653
+ if (!selected.has(id)) return false;
1654
+ const snapshot = preview.get(id);
1655
+ if (snapshot === undefined) return false;
1656
+ const record = snapshot.record;
1657
+ // Same record object AND same run generation: a resume makes this a newer
1658
+ // run whose own notification is none of this cleanup's business.
1659
+ if (manager.getRecord(id) !== record) return false;
1660
+ if ((record.runGeneration ?? 0) !== snapshot.runGeneration) return false;
1661
+ if (record.resultConsumed === true) return false;
1662
+ return record.status !== "running" && record.status !== "queued";
1663
+ };
1664
+ const addKeys = (key: string): void => {
1665
+ const ids = key.startsWith("group:") ? key.slice("group:".length).split(",") : [key];
1666
+ for (const id of ids) if (eligible(id)) pending.add(id);
1667
+ };
1668
+ for (const key of pendingNudges.keys()) addKeys(key);
1669
+ for (const entry of currentBatchAgents) if (eligible(entry.id)) pending.add(entry.id);
1670
+ for (const id of selected) if (eligible(id) && groupJoin.isGrouped(id)) pending.add(id);
1671
+ for (const file of plan.files) {
1672
+ if (file.workflowId === undefined || !pendingNudges.has(file.workflowId)) continue;
1673
+ // Namespaced so a workflow id can never collide with an agent id.
1674
+ pending.add(`workflow:${file.workflowId}`);
1675
+ }
1676
+ return pending.size;
1677
+ }
1678
+
1679
+ function countSelectedUnreadReports(preview: ReadonlyMap<string, CleanupPreviewRecord>): number {
1680
+ let count = 0;
1681
+ for (const snapshot of preview.values()) {
1682
+ if (snapshot.record.resultConsumed !== true) count++;
1683
+ }
1684
+ return count;
1685
+ }
1686
+
1687
+ function buildCleanupConfirmation(
1688
+ plan: CleanupPlan,
1689
+ preview: ReadonlyMap<string, CleanupPreviewRecord>,
1690
+ ): string {
1691
+ const unreadReports = countSelectedUnreadReports(preview);
1692
+ const pending = countPendingSelectedDeliveries(plan, preview);
1693
+ const counts = plan.counts;
1694
+ const lines = [
1695
+ `Permanently delete ${counts.files} file(s) (${counts.bytes} bytes) from ${plan.roots.length} root session(s)?`,
1696
+ `${counts.reports} report entries · ${counts.taskOutputs} task outputs · ${counts.workflowFiles} workflow files · ${counts.childSessions} child sessions · ${counts.legacy} legacy outputs · ${counts.diagnostics} diagnostics logs.`,
1697
+ `${counts.unread} unread artifact file(s) are not marked as read; ${unreadReports} live report(s) are not marked as read.`,
1698
+ `${pending} selected completion notification(s) are still pending and will be discarded.`,
1699
+ ];
1700
+ if (plan.identityUncertainty !== undefined) {
1701
+ lines.push(`Identity uncertainty: ${plan.identityUncertainty}. Identity-sensitive deletions will be refused.`);
1702
+ }
1703
+ lines.push("This cannot be undone. Your own session history is never a cleanup candidate.");
1704
+ return lines.join("\n");
1705
+ }
1706
+
1707
+ function beginWorkflowCleanupProof(id: string, rootSessionId: string | undefined): void {
1708
+ workflowCleanupProofs.set(id, {
1709
+ ...(rootSessionId === undefined ? {} : { rootSessionId }),
1710
+ generatedPaths: [],
1711
+ externalPaths: [],
1712
+ });
1713
+ }
1714
+
1715
+ function updateWorkflowCleanupProof(id: string, generatedPaths: readonly string[], externalPaths: readonly string[]): void {
1716
+ const proof = workflowCleanupProofs.get(id);
1717
+ if (proof === undefined) return;
1718
+ proof.generatedPaths = [...generatedPaths];
1719
+ proof.externalPaths = [...externalPaths];
1720
+ }
1721
+
1722
+ function recordWorkflowPersistenceResult(id: string, result: ReportSaveResult | undefined): void {
1723
+ const proof = workflowCleanupProofs.get(id);
1724
+ if (proof === undefined) return;
1725
+ if (result?.saved === false && result.reason !== "persist-disabled") {
1726
+ proof.persistenceUncertainty ??= result.reason;
1727
+ } else if (result?.saved === true) {
1728
+ proof.persistenceUncertainty = undefined;
1729
+ }
1730
+ }
1731
+
1732
+ function settleWorkflowCleanupProof(id: string, result: ReportSaveResult | undefined): void {
1733
+ const proof = workflowCleanupProofs.get(id);
1734
+ if (proof === undefined) return;
1735
+ if (result === undefined || result.saved === true || result.reason === "persist-disabled") {
1736
+ workflowCleanupProofs.delete(id);
1737
+ return;
1738
+ }
1739
+ proof.persistenceUncertainty ??= result.reason;
1740
+ }
1741
+
1742
+ function cleanupOperationLiveState(op: CleanupOperation): CleanupLiveState {
1743
+ if (!cleanupOperationCurrent(op)) {
1744
+ return { protectedRootSessionIds: [...op.candidateRoots], diagnosticsBusy: true };
1745
+ }
1746
+ const runtime = collectCleanupRuntime();
1747
+ const protectedRoots = new Set([...op.frozenRoots, ...runtime.protectedRoots]);
1748
+ if (runtime.unknownRootActivity) {
1749
+ for (const root of op.candidateRoots) protectedRoots.add(root);
1750
+ }
1751
+ return {
1752
+ activeAgentIds: runtime.activeAgentIds,
1753
+ activeWorkflowIds: runtime.activeWorkflowIds,
1754
+ protectedPaths: runtime.protectedPaths,
1755
+ unreadAgentIds: runtime.unreadAgentIds,
1756
+ diagnosticsBusy: runtime.hasActiveWork,
1757
+ protectedRootSessionIds: protectedRoots,
1758
+ };
1759
+ }
1760
+
1761
+ /**
1762
+ * Diagnostics is the one shared global candidate, so it has no per-root
1763
+ * selection to protect it. Its final gate asks each root's OWNING store what
1764
+ * that store really sees: activation/lease/lock liveness and readability,
1765
+ * through the public `rootProtectionReason` view — the same backend policy
1766
+ * that refuses a bind or a cleanup lock. Counting local bindings or comparing
1767
+ * lease counts guesses at ownership: a foreign writer can hold the only active
1768
+ * lease of a root this process merely has a refused context for.
1769
+ *
1770
+ * Own idle roots allow. A live/uncertain lock, an unreadable lease metadata
1771
+ * set, a live foreign lease, or a root that vanished under us all protect.
1772
+ */
1773
+ async function cleanupForeignDiagnosticsActivity(baseStore: ReportStore): Promise<{ busy: boolean; roots: string[] }> {
1774
+ try {
1775
+ // Strict inventory, never a best-effort list: an unreadable, unsafe or
1776
+ // vanished root is uncertainty, and a partial inventory must protect the
1777
+ // shared aggregate rather than silently shrinking to the readable roots.
1778
+ const scan = await baseStore.scanRootIdentities();
1779
+ const roots: string[] = [];
1780
+ let busy = scan.uncertainty !== undefined;
1781
+ for (const state of scan.states) {
1782
+ // The owning store must answer, or its own lease reads as foreign; roots
1783
+ // without one are answered by any store, since all share the same root.
1784
+ const owner = reportStores.get(state.rootSessionId);
1785
+ const store = owner?.bindingContext?.rootSessionId === state.rootSessionId ? owner : baseStore;
1786
+ const reason = await store.rootProtectionReason(state.rootSessionId);
1787
+ if (reason === undefined) continue;
1788
+ busy = true;
1789
+ roots.push(state.rootSessionId);
1790
+ }
1791
+ return { busy, roots };
1792
+ } catch {
1793
+ // Unreadable inventory is itself uncertainty: keep the shared aggregate.
1794
+ return { busy: true, roots: [] };
1795
+ }
1796
+ }
1797
+
1798
+ async function diagnosticsCleanupLiveState(op: CleanupOperation): Promise<CleanupLiveState> {
1799
+ const live = cleanupOperationLiveState(op);
1800
+ if (!cleanupOperationCurrent(op)) return live;
1801
+ const foreign = await cleanupForeignDiagnosticsActivity(reportStores.get(op.rootSessionId) ?? reportStore);
1802
+ const protectedRoots = new Set(live.protectedRootSessionIds ?? []);
1803
+ for (const root of foreign.roots) protectedRoots.add(root);
1804
+ return {
1805
+ ...live,
1806
+ diagnosticsBusy: live.diagnosticsBusy === true || foreign.busy,
1807
+ protectedRootSessionIds: protectedRoots,
1808
+ };
1809
+ }
1810
+
1811
+ async function prepareCleanupPartition(
1812
+ op: CleanupOperation,
1813
+ request: CleanupPrepareRequest,
1814
+ ): Promise<CleanupPreparation> {
1815
+ if (!cleanupOperationCurrent(op)) throw new Error("cleanup-session-changed");
1816
+ const runtime = collectCleanupRuntime();
1817
+ const allowed = new Set<string>();
1818
+ if (!runtime.unknownRootActivity) {
1819
+ for (const root of request.rootSessionIds) {
1820
+ if (op.reservedRoots.has(root) && !runtime.protectedRoots.has(root) && !op.frozenRoots.has(root)) {
1821
+ allowed.add(root);
1822
+ }
1823
+ }
1824
+ }
1825
+ const agentIds = request.agentIds.filter(id => {
1826
+ const root = op.planAgentRoots.get(id);
1827
+ return root !== undefined && allowed.has(root);
1828
+ });
1829
+ const sessionFiles = request.sessionFiles.filter(path => {
1830
+ const root = op.planPathRoots.get(cleanupPathKey(path));
1831
+ return root !== undefined && allowed.has(root);
1832
+ });
1833
+ const readyRootSessionIds = request.rootSessionIds.filter(root => allowed.has(root));
1834
+ if (agentIds.length === 0 && sessionFiles.length === 0) {
1835
+ return {
1836
+ readyAgentIds: [],
1837
+ readySessionFiles: [],
1838
+ readyRootSessionIds,
1839
+ ...(request.rootSessionIds.some(root => !allowed.has(root))
1840
+ ? { blockedRootSessionIds: Object.fromEntries(request.rootSessionIds.filter(root => !allowed.has(root)).map(root => [root, "cleanup-root-not-eligible"])) }
1841
+ : {}),
1842
+ };
1843
+ }
1844
+ const prepared = await manager.prepareCleanup(agentIds, sessionFiles);
1845
+ return { ...prepared, readyRootSessionIds };
1846
+ }
1847
+
1848
+ function combineCleanupResults(plan: CleanupPlan, results: readonly CleanupResult[]): CleanupResult {
1849
+ const deleted = results.flatMap(result => result.deleted);
1850
+ const failed = results.flatMap(result => result.failed);
1851
+ const skipped: CleanupSkip[] = [
1852
+ ...plan.skipped.map(item => ({ ...item })),
1853
+ ...results.flatMap(result => result.skipped),
1854
+ ];
1855
+ const deletedAgentIds = new Set<string>();
1856
+ let bytesDeleted = 0;
1857
+ for (const result of results) {
1858
+ for (const id of result.deletedAgentIds) deletedAgentIds.add(id);
1859
+ bytesDeleted += result.bytesDeleted;
1860
+ }
1861
+ return {
1862
+ scope: plan.scope,
1863
+ deleted,
1864
+ failed,
1865
+ skipped,
1866
+ deletedAgentIds: [...deletedAgentIds].sort(),
1867
+ bytesDeleted,
1868
+ };
1869
+ }
1870
+
1871
+ function formatCleanupResult(result: CleanupResult): string {
1872
+ const lines = [
1873
+ `Cleanup ${result.scope} finished — ${result.deleted.length} deleted (${result.bytesDeleted} bytes), ${result.failed.length} failed, ${result.skipped.length} skipped.`,
1874
+ ];
1875
+ if (result.deleted.length > 0) {
1876
+ lines.push("Deleted:");
1877
+ for (const item of result.deleted) {
1878
+ lines.push(`- ${safeCleanupText(item.path)} (${item.kind}, ${item.bytes} bytes, ${cleanupReadStateLabel(item.readState)})`);
1879
+ }
1880
+ }
1881
+ if (result.failed.length > 0) {
1882
+ lines.push("Failed:");
1883
+ for (const item of result.failed) {
1884
+ lines.push(`- ${item.path === undefined ? `(${item.kind ?? "unknown"})` : safeCleanupText(item.path)}: ${safeCleanupText(item.reason)}`);
1885
+ }
1886
+ }
1887
+ if (result.skipped.length > 0) {
1888
+ lines.push("Skipped:");
1889
+ for (const item of result.skipped) {
1890
+ const where = item.path === undefined
1891
+ ? `(${item.kind ?? "unknown"}${item.rootSessionId === undefined ? "" : `, root ${item.rootSessionId}`}${item.agentId === undefined ? "" : `, agent ${item.agentId}`})`
1892
+ : `${safeCleanupText(item.path)} (${item.kind ?? "unknown"})`;
1893
+ lines.push(`- ${where}: ${safeCleanupText(item.reason)}`);
1894
+ }
1895
+ }
1896
+ return lines.join("\n");
1897
+ }
1898
+
1899
+ function discardSelectedDeliveries(
1900
+ op: CleanupOperation,
1901
+ plan: CleanupPlan,
1902
+ preview: ReadonlyMap<string, CleanupPreviewRecord>,
1903
+ ): void {
1904
+ const allowed = new Set(op.reservedRoots);
1905
+ const selected = new Set<string>();
1906
+ for (const file of plan.files) {
1907
+ if (file.agentId === undefined || !allowed.has(file.rootSessionId)) continue;
1908
+ const snapshot = preview.get(file.agentId);
1909
+ if (snapshot === undefined || !isSelectedLiveRecord(snapshot.record, preview)) continue;
1910
+ selected.add(file.agentId);
1911
+ }
1912
+ for (const id of selected) {
1913
+ const record = manager.getRecord(id);
1914
+ if (record === undefined) continue;
1915
+ record.resultConsumed = true;
1916
+ cancelNudge(id);
1917
+ deferredResultInterest.delete(id);
1918
+ }
1919
+ const remainingBatch = currentBatchAgents.filter(entry => !selected.has(entry.id));
1920
+ if (remainingBatch.length !== currentBatchAgents.length) {
1921
+ currentBatchAgents = remainingBatch;
1922
+ if (currentBatchAgents.length === 0 && batchFinalizeTimer !== undefined) {
1923
+ clearTimeout(batchFinalizeTimer);
1924
+ batchFinalizeTimer = undefined;
1925
+ }
1926
+ }
1927
+ for (const workflowId of plan.files
1928
+ .filter(file => workflowIdOf(file) !== undefined && allowed.has(file.rootSessionId))
1929
+ .map(file => workflowIdOf(file))
1930
+ .filter((id): id is string => id !== undefined)) {
1931
+ op.selectedWorkflowIds.add(workflowId);
1932
+ discardedWorkflowNotifications.add(workflowId);
1933
+ cancelNudge(workflowId);
1934
+ }
1935
+ groupJoin.discard(selected);
1936
+ }
1937
+
1938
+ function workflowIdOf(file: CleanupFileInventory): string | undefined {
1939
+ return file.workflowId;
1940
+ }
1941
+
1942
+ function forgetDeletedWorkflowPointers(result: CleanupResult): void {
1943
+ for (const file of result.deleted) {
1944
+ if (file.kind !== "workflow-registration" || file.workflowId === undefined) continue;
1945
+ const ownedRoot = workflowArtifactRoots.get(file.workflowId);
1946
+ if (ownedRoot !== undefined && ownedRoot !== file.rootSessionId) continue;
1947
+ workflowTasks.delete(file.workflowId);
1948
+ workflowArtifactPaths.delete(file.workflowId);
1949
+ workflowArtifactRoots.delete(file.workflowId);
1950
+ workflowArtifactStores.delete(file.workflowId);
1951
+ workflowCleanupProofs.delete(file.workflowId);
1952
+ // The run promise and its journal drain are deliberately NOT dropped
1953
+ // here: a deleted registration is not proof that the run stopped writing,
1954
+ // and shutdown must still await whatever it accepted. Those handles are
1955
+ // removed by the run settling, never by pointer forgetting.
1956
+ // The send-time invalidation deliberately OUTLIVES pointer forgetting. A
1957
+ // hold callback can already be sitting in the timer queue when cleanup
1958
+ // finishes, and it rechecks this set on entry: dropping the flag together
1959
+ // with the pointers would let that queued callback announce a run whose
1960
+ // registration this cleanup just deleted.
1961
+ }
1962
+ for (const file of result.deleted) {
1963
+ if (file.kind === "workflow-generated") knownGeneratedWorkflowPaths.delete(resolve(file.path));
1964
+ }
1965
+ }
1966
+
1967
+ async function handleCleanupCommand(tokens: readonly string[], ctx: ExtensionCommandContext): Promise<void> {
1968
+ const parsed = parseCleanupArgs(tokens);
1969
+ if (parsed === undefined) {
1970
+ ctx.ui.notify(cleanupUsage(), "warning");
1971
+ return;
1972
+ }
1973
+ const rootSessionId = ctx.sessionManager?.getSessionId?.();
1974
+ if (rootSessionId === undefined) {
1975
+ ctx.ui.notify("Cleanup is unavailable without a bound session.", "warning");
1976
+ return;
1977
+ }
1978
+ const epoch = sessionEpoch;
1979
+ const readRoot = () => ctx.sessionManager?.getSessionId?.();
1980
+ // Dry-run is strictly read-only: never rebind a root, retire another
1981
+ // store's lease, or drain deferred archive writes just to render a preview.
1982
+ if (!parsed.dryRun) await ensureReportBinding(ctx);
1983
+ if (epoch !== sessionEpoch || readRoot() !== rootSessionId) {
1984
+ ctx.ui.notify("Cleanup cancelled — the session changed before preview.", "warning");
1985
+ return;
1986
+ }
1987
+ const baseStore = reportStores.get(rootSessionId) ?? reportStore;
1988
+ if (!parsed.dryRun && baseStore.bindingContext?.rootSessionId !== rootSessionId) {
1989
+ ctx.ui.notify("Cleanup refused — the bound report store does not belong to this session.", "warning");
1990
+ return;
1991
+ }
1992
+ const stores = new Map(reportStores);
1993
+ if (!parsed.dryRun && !stores.has(rootSessionId)) stores.set(rootSessionId, baseStore);
1994
+ // Taken BEFORE every planning/UI await: the preview must describe the
1995
+ // generations that existed when it opened, not whatever a resume leaves
1996
+ // behind by the time confirmation arrives.
1997
+ const initialPreviewRecords = snapshotLiveRecords();
1998
+ if (!parsed.dryRun) drainPendingArchivedRecords();
1999
+ try {
2000
+ const drained = await Promise.all([...new Set([...stores.values(), baseStore])].map(store => store.flush()));
2001
+ if (drained.some(result => result.status !== "flushed")) throw new Error("incomplete report flush");
2002
+ } catch {
2003
+ ctx.ui.notify("Cleanup refused — pending report writes could not be flushed.", "warning");
2004
+ return;
2005
+ }
2006
+
2007
+ const runtime = collectCleanupRuntime();
2008
+ let plan: CleanupPlan;
2009
+ try {
2010
+ plan = await buildCleanupPreviewPlan(
2011
+ baseStore,
2012
+ parsed.scope,
2013
+ parsed.includeLegacy,
2014
+ runtime,
2015
+ stores,
2016
+ parsed.dryRun && parsed.scope === "session" ? rootSessionId : undefined,
2017
+ );
2018
+ } catch (error) {
2019
+ ctx.ui.notify(`Cleanup preview failed: ${error instanceof Error ? error.message : String(error)}`, "warning");
2020
+ return;
2021
+ }
2022
+ if (epoch !== sessionEpoch || readRoot() !== rootSessionId) {
2023
+ ctx.ui.notify("Cleanup cancelled — the session changed before preview.", "warning");
2024
+ return;
2025
+ }
2026
+
2027
+ const previewText = formatCleanupPreview(plan);
2028
+ if (ctx.mode !== "tui" || !ctx.hasUI) {
2029
+ ctx.ui.notify(
2030
+ `${previewText}\n\nCleanup needs the native terminal UI for its review and confirmation; nothing was deleted. Run it interactively, or use --dry-run here to inspect this inventory.`,
2031
+ parsed.dryRun ? "info" : "warning",
2032
+ );
2033
+ return;
2034
+ }
2035
+ let reviewed = false;
2036
+ try {
2037
+ reviewed = await showCleanupPreview(ctx, plan, parsed.dryRun);
2038
+ } catch {
2039
+ reviewed = false;
2040
+ }
2041
+ if (epoch !== sessionEpoch || readRoot() !== rootSessionId) {
2042
+ ctx.ui.notify("Cleanup cancelled — the session changed during preview.", "warning");
2043
+ return;
2044
+ }
2045
+ if (!reviewed) {
2046
+ ctx.ui.notify(parsed.dryRun ? "Dry run closed — nothing was deleted." : "Cleanup cancelled — nothing was deleted.", "info");
2047
+ return;
2048
+ }
2049
+ if (parsed.dryRun) {
2050
+ ctx.ui.notify("Dry run complete — nothing was deleted.", "info");
2051
+ return;
2052
+ }
2053
+ if (plan.files.length === 0) {
2054
+ ctx.ui.notify("Nothing is eligible for cleanup.", "info");
2055
+ return;
2056
+ }
2057
+
2058
+ const previewRecords = selectPreviewRecords(plan, initialPreviewRecords);
2059
+ const confirmed = await ctx.ui.confirm("Confirm cleanup", buildCleanupConfirmation(plan, previewRecords));
2060
+ if (!confirmed) {
2061
+ ctx.ui.notify("Cleanup cancelled — nothing was deleted.", "info");
2062
+ return;
2063
+ }
2064
+ if (epoch !== sessionEpoch || readRoot() !== rootSessionId) {
2065
+ ctx.ui.notify("Cleanup cancelled — the session changed before deletion.", "warning");
2066
+ return;
2067
+ }
2068
+ let legacyConfirmed = false;
2069
+ if (plan.files.some(file => file.kind === "legacy-output")) {
2070
+ const legacyCount = plan.files.filter(file => file.kind === "legacy-output").length;
2071
+ legacyConfirmed = await ctx.ui.confirm(
2072
+ "Confirm legacy cleanup",
2073
+ `Delete ${legacyCount} legacy .output file(s)? Older pi instances must be closed first; a live instance may still hold these files.`,
2074
+ );
2075
+ if (!legacyConfirmed) {
2076
+ ctx.ui.notify("Cleanup cancelled — nothing was deleted.", "info");
2077
+ return;
2078
+ }
2079
+ if (epoch !== sessionEpoch || readRoot() !== rootSessionId) {
2080
+ ctx.ui.notify("Cleanup cancelled — the session changed before deletion.", "warning");
2081
+ return;
2082
+ }
2083
+ }
2084
+
2085
+ const after = collectCleanupRuntime();
2086
+ const candidateRoots = new Set(
2087
+ plan.files.map(file => file.rootSessionId).filter(root => root.length > 0),
2088
+ );
2089
+ const frozenRoots = new Set(after.protectedRoots);
2090
+ if (after.unknownRootActivity) {
2091
+ for (const root of candidateRoots) frozenRoots.add(root);
2092
+ }
2093
+ const plannedAgentRoots = new Map<string, string>();
2094
+ for (const file of plan.files) {
2095
+ if (file.agentId !== undefined && !plannedAgentRoots.has(file.agentId)) {
2096
+ plannedAgentRoots.set(file.agentId, file.rootSessionId);
2097
+ }
2098
+ }
2099
+ const freezeChangedRoot = (root: string | undefined): void => {
2100
+ if (root !== undefined && root.length > 0) frozenRoots.add(root);
2101
+ else for (const candidate of candidateRoots) frozenRoots.add(candidate);
2102
+ };
2103
+ // Every planned agent id, not only the ones the snapshot happened to hold:
2104
+ // an id with no record at preview time that has one now is a live id this
2105
+ // preview never selected, so its root is conservatively changed. A record
2106
+ // that vanished with no new run leaves no writer and no notice to protect.
2107
+ for (const [id, plannedRoot] of plannedAgentRoots) {
2108
+ const snapshot = initialPreviewRecords.get(id);
2109
+ const current = manager.getRecord(id);
2110
+ if (snapshot === undefined) {
2111
+ if (current !== undefined) freezeChangedRoot(current.rootSessionId ?? plannedRoot);
2112
+ continue;
2113
+ }
2114
+ if (current === undefined) continue;
2115
+ if (current === snapshot.record && (current.runGeneration ?? 0) === snapshot.runGeneration) continue;
2116
+ freezeChangedRoot(snapshot.record.rootSessionId ?? plannedRoot);
2117
+ }
2118
+ const reservedRoots = new Set([...candidateRoots].filter(root => !frozenRoots.has(root)));
2119
+ const op: CleanupOperation = {
2120
+ epoch,
2121
+ rootSessionId,
2122
+ readRoot,
2123
+ candidateRoots,
2124
+ frozenRoots,
2125
+ reservedRoots,
2126
+ selectedAgentIds: new Set(plan.agentIds),
2127
+ selectedSessionFiles: new Set(plan.sessionFiles.map(cleanupPathKey)),
2128
+ selectedPaths: new Set(plan.files.map(file => cleanupPathKey(file.path))),
2129
+ selectedWorkflowIds: new Set(),
2130
+ planAgentRoots: new Map(plannedAgentRoots),
2131
+ planPathRoots: new Map<string, string>(),
2132
+ };
2133
+ for (const file of plan.files) {
2134
+ op.planPathRoots.set(cleanupPathKey(file.path), file.rootSessionId);
2135
+ if (file.kind === "child-session" && file.sessionFile !== undefined) {
2136
+ op.planPathRoots.set(cleanupPathKey(file.sessionFile), file.rootSessionId);
2137
+ }
2138
+ }
2139
+ // Exactly one operation owns the reservations: a second confirmed cleanup
2140
+ // must not overwrite this owner, or its release would clear barriers the
2141
+ // first pass is still relying on.
2142
+ if (cleanupOperation !== undefined && cleanupOperationCurrent(cleanupOperation)) {
2143
+ ctx.ui.notify("Another cleanup is already applying in this session; nothing was deleted.", "warning");
2144
+ return;
2145
+ }
2146
+ cleanupOperation = op;
2147
+ // From here every archived read of a candidate root is suspect, including
2148
+ // one that resumes after this operation has already released.
2149
+ invalidateCleanupReads(op.candidateRoots);
2150
+ const results: CleanupResult[] = [];
2151
+ let interrupted = false;
2152
+ try {
2153
+ // Consume the eligible selected deliveries SYNCHRONOUSLY, before this
2154
+ // operation's first await. A held individual/group/workflow notice can
2155
+ // reach its deadline during the root-generation reads below, and cleanup
2156
+ // cannot withdraw a message that was already sent. A later generation or
2157
+ // deletion failure does not roll this back: the discard is deliberate.
2158
+ discardSelectedDeliveries(op, plan, previewRecords);
2159
+ if (!cleanupOperationCurrent(op)) interrupted = true;
2160
+ // Recheck the confirmed root generations ONLY after every idle candidate
2161
+ // root is reserved, so no producer can slip into the gap. This still
2162
+ // precedes every deletion.
2163
+ const changedRoots = new Set<string>();
2164
+ await Promise.all([...reservedRoots].map(async root => {
2165
+ const planned = plan.roots.find(item => item.rootSessionId === root);
2166
+ if (planned === undefined) return;
2167
+ const store = stores.get(root) ?? baseStore;
2168
+ const current = await store.getRootGeneration(root);
2169
+ if ((current ?? 0) !== planned.generation) changedRoots.add(root);
2170
+ }));
2171
+ for (const root of changedRoots) {
2172
+ op.reservedRoots.delete(root);
2173
+ op.frozenRoots.add(root);
2174
+ }
2175
+ if (!cleanupOperationCurrent(op)) interrupted = true;
2176
+
2177
+ const parts = partitionCleanupPlan(plan);
2178
+ for (const part of parts) {
2179
+ const root = part.files[0]?.rootSessionId ?? "";
2180
+ const store = root === "" || !stores.has(root) ? baseStore : stores.get(root)!;
2181
+ const result = await applyCleanup(store, part, {
2182
+ confirmed: true,
2183
+ confirmedLegacy: legacyConfirmed,
2184
+ liveStateGetter: () => root === "" ? diagnosticsCleanupLiveState(op) : Promise.resolve(cleanupOperationLiveState(op)),
2185
+ prepare: request => prepareCleanupPartition(op, request),
2186
+ });
2187
+ results.push(result);
2188
+ if (!cleanupOperationCurrent(op)) interrupted = true;
2189
+ }
2190
+
2191
+ const combined = combineCleanupResults(plan, results);
2192
+ markUnprovenCleanupReports(combined);
2193
+ const deletedSessionFiles = combined.deleted
2194
+ .filter(item => item.kind === "child-session")
2195
+ .map(item => item.path);
2196
+ manager.forgetCleanup(combined.deletedAgentIds, deletedSessionFiles);
2197
+ forgetDeletedWorkflowPointers(combined);
2198
+ const text = formatCleanupResult(combined)
2199
+ + (interrupted ? "\nCleanup interrupted — the session changed; any remaining candidates were not deleted." : "");
2200
+ ctx.ui.notify(text, combined.failed.length > 0 || interrupted ? "warning" : "info");
2201
+ } catch (error) {
2202
+ // A thrown store/diagnostic error can follow a partially applied plan, and
2203
+ // the partition that rejected has usually committed work of its own. Its
2204
+ // handoff carries that exact progress, so the deletions are reported and
2205
+ // forgotten instead of leaving live reports readable whose durable entries
2206
+ // are already deletion receipts. Never retry or freshen the confirmed plan
2207
+ // here.
2208
+ if (error instanceof CleanupApplyError) results.push(error.result);
2209
+ const partial = combineCleanupResults(plan, results);
2210
+ // A rejected receipt write may already have committed: report it as a
2211
+ // failure AND refuse the cached live body, never as a deletion.
2212
+ markUnprovenCleanupReports(partial);
2213
+ const deletedSessionFiles = partial.deleted
2214
+ .filter(item => item.kind === "child-session")
2215
+ .map(item => item.path);
2216
+ manager.forgetCleanup(partial.deletedAgentIds, deletedSessionFiles);
2217
+ forgetDeletedWorkflowPointers(partial);
2218
+ ctx.ui.notify(
2219
+ `${formatCleanupResult(partial)}\nCleanup failed: ${safeCleanupText(error instanceof Error ? error.message : String(error))}`,
2220
+ "warning",
2221
+ );
2222
+ } finally {
2223
+ // Only the owner releases the operation; a second command's reservations
2224
+ // are never cleared by this one's exit.
2225
+ if (cleanupOperation === op) cleanupOperation = undefined;
2226
+ // Closing edge of the read-invalidation interval: a read still holding a
2227
+ // body from before this operation must re-resolve even now that the
2228
+ // barriers are gone.
2229
+ invalidateCleanupReads(op.candidateRoots);
2230
+ }
2231
+ }
2232
+
665
2233
  // Expose manager via Symbol.for() global registry for cross-package access.
666
2234
  // Standard Node.js pattern for cross-package singletons (used by OpenTelemetry, etc.).
667
2235
  // Documented for callers in docs/rpc.md ("The manager registry").
@@ -679,22 +2247,47 @@ export default function (pi: ExtensionAPI) {
679
2247
  * Resolve the agent type and spawn. Trusts its options — every caller must
680
2248
  * either be in-process or have gone through `spawnTopLevel` first.
681
2249
  */
682
- const spawnResolved = (piRef: any, ctxRef: any, type: string, prompt: string, options: any) => {
683
- // Cross-extension callers get the same dispatch contract as the LLM (#183).
684
- // The RPC layer already throws for an unresolvable model rather than falling
685
- // back silently; a bad agent type should not be quieter. Throws become error
686
- // envelopes at the RPC boundary. Reload first so an agent file added mid
687
- // session is spawnable here too, not only through the Agent tool.
688
- reloadCustomAgents();
689
- const dispatch = resolveSpawnType(type);
690
- if (!dispatch.ok) {
691
- logSubagentIssue({ kind: "spawn_rejected", requestedType: String(type), reason: dispatch.message });
692
- throw new Error(dispatch.message);
2250
+ const spawnResolved = (piRef: any, ctxRef: any, type: string, prompt: string, options: any, cleanupPrepared = false) => {
2251
+ // Only private callers that awaited the store barrier skip synchronous I/O.
2252
+ // Recheck local reservations in this same tick; the manager still guards
2253
+ // the actual start. The public synchronous registry keeps its fresh guard.
2254
+ const rootSessionId = ctxRef?.sessionManager?.getSessionId?.();
2255
+ const paths = [options?.resumeSessionFile];
2256
+ if (cleanupPrepared) assertCleanupLocalAccess(rootSessionId, paths);
2257
+ else assertCleanupRootAccess(rootSessionId, paths);
2258
+ // A prepared caller (the RPC `prepare` registry) already resolved its type
2259
+ // and froze its definition before this synchronous hand-off. Re-resolving
2260
+ // against this process's global registry would discard that snapshot and
2261
+ // could admit a different same-name definition. Unprepared callers keep the
2262
+ // deliberate fresh synchronous reload/resolution below.
2263
+ const admittedDefinition = options?.agentDefinition === undefined
2264
+ ? undefined
2265
+ : cloneAgentDefinition(options.agentDefinition);
2266
+ let spawnType = type;
2267
+ if (admittedDefinition === undefined) {
2268
+ // Cross-extension callers get the same dispatch contract as the LLM (#183).
2269
+ // The RPC layer already throws for an unresolvable model rather than falling
2270
+ // back silently; a bad agent type should not be quieter. Throws become error
2271
+ // envelopes at the RPC boundary. Reload first so an agent file added mid
2272
+ // session is spawnable here too, not only through the Agent tool.
2273
+ reloadCustomAgents();
2274
+ const dispatch = resolveSpawnType(type);
2275
+ if (!dispatch.ok) {
2276
+ logSubagentIssue({ kind: "spawn_rejected", requestedType: String(type), reason: dispatch.message });
2277
+ throw new Error(dispatch.message);
2278
+ }
2279
+ spawnType = dispatch.type;
693
2280
  }
2281
+ // Bus RPC and the cross-package registry land here synchronously, without
2282
+ // the Agent tool's awaited admission. A persistent root with no proven-active
2283
+ // store must not open a new id or SDK history: the cleanup root guard above
2284
+ // cannot see an absent store, and a foreign lock's selection names OLDER ids,
2285
+ // never the id about to be created. Ephemeral contexts keep their behavior.
2286
+ assertReportBindingAdmission(ctxRef as ExtensionContext);
694
2287
  // Every programmatic spawn lands here — cross-extension RPC, both `@handle`
695
2288
  // mention paths, and the `Symbol.for("pi-subagents:manager")` registry — and
696
2289
  // none came through the Agent tool, which is where the UI activity tracker is
697
- // otherwise created. Without one the widget and FleetView have no tool name
2290
+ // otherwise created. Without one the widget has no tool name
698
2291
  // and no turn count, so the row reads `thinking…` for the agent's whole life
699
2292
  // while the header's tool-use count climbs beside it (#181). Double-tracking
700
2293
  // is not possible: the Agent tool calls `manager.spawn` directly. The tracker
@@ -706,15 +2299,24 @@ export default function (pi: ExtensionAPI) {
706
2299
  // built with `undefined` renders `↻3` where the Agent tool renders `↻3≤20`.
707
2300
  // Like the tool's own, it is a prediction — editing the agent file mid-run
708
2301
  // leaves the displayed ceiling stale.
709
- const { state, callbacks } = createActivityTracker(resolveEffectiveMaxTurns(dispatch.type, options?.maxTurns));
2302
+ const { state, callbacks } = createActivityTracker(resolveEffectiveMaxTurns(spawnType, options?.maxTurns));
710
2303
  // Repaints are left to the manager's `onStart` callback, which already starts
711
- // the widget/fleet timers for agents that enter this way.
712
- const id = manager.spawn(piRef, ctxRef, dispatch.type, prompt, { ...options, ...callbacks });
2304
+ // the widget timer for agents that enter this way.
2305
+ const id = manager.spawn(piRef, ctxRef, spawnType, prompt, {
2306
+ ...options,
2307
+ ...(admittedDefinition === undefined ? {} : { agentDefinition: admittedDefinition }),
2308
+ ...callbacks,
2309
+ });
713
2310
  agentActivity.set(id, state);
714
2311
  return id;
715
2312
  };
716
2313
 
717
- const spawnTopLevel = (piRef: any, ctxRef: any, type: string, prompt: string, options: any) => {
2314
+ /**
2315
+ * Strip internals a process-external caller must never supply. A trusted
2316
+ * prepared definition is kept only for the RPC boundary below, which attaches
2317
+ * it AFTER deleting any caller-supplied value.
2318
+ */
2319
+ const sanitizeTopLevelOptions = (options: any, keepAgentDefinition = false) => {
718
2320
  const safeOptions = { ...(options ?? {}) };
719
2321
  delete safeOptions.parentAgentId;
720
2322
  // Internal too: a forged value would hide an RPC-spawned agent inside
@@ -726,6 +2328,11 @@ export default function (pi: ExtensionAPI) {
726
2328
  // Also internal: it names a transcript directory, so a forged value would
727
2329
  // be a path-traversal primitive.
728
2330
  delete safeOptions.rootSessionId;
2331
+ // Root provenance and owner lineage are pinned by the manager from the
2332
+ // live parent chain/context; a caller must not forge either.
2333
+ delete safeOptions.rootCwd;
2334
+ delete safeOptions.rootSessionFile;
2335
+ delete safeOptions.ownerIds;
729
2336
  // Worse than rootSessionId: this one names a file to OPEN and replay as a
730
2337
  // conversation. Only the mention dispatcher may set it, and only from a
731
2338
  // path this extension itself recorded — never from anything a caller sent.
@@ -737,9 +2344,24 @@ export default function (pi: ExtensionAPI) {
737
2344
  // awaits nothing. A forged `blocking` would charge it to the foreground
738
2345
  // pool and could defer it behind a queue whose gate nobody is holding.
739
2346
  delete safeOptions.blocking;
740
- return spawnResolved(piRef, ctxRef, type, prompt, safeOptions);
2347
+ // A definition snapshot is an admission capability: it decides prompt, tool
2348
+ // permissions, model and nesting policy. Only the RPC handler may forward
2349
+ // the one it resolved from its own scoped `prepare` registry.
2350
+ if (!keepAgentDefinition) delete safeOptions.agentDefinition;
2351
+ return safeOptions;
741
2352
  };
742
2353
 
2354
+ const spawnTopLevel = (piRef: any, ctxRef: any, type: string, prompt: string, options: any) =>
2355
+ spawnResolved(piRef, ctxRef, type, prompt, sanitizeTopLevelOptions(options));
2356
+
2357
+ /**
2358
+ * RPC spawns arrive through `registerRpcHandlers`, which deletes any
2359
+ * caller-supplied definition and attaches the one resolved from the scoped
2360
+ * `prepare` registry. Preserve exactly that snapshot across sanitization.
2361
+ */
2362
+ const spawnRpcPrepared = (piRef: any, ctxRef: any, type: string, prompt: string, options: any) =>
2363
+ spawnResolved(piRef, ctxRef, type, prompt, sanitizeTopLevelOptions(options, true), true);
2364
+
743
2365
  /**
744
2366
  * Resolve a tool's `agent_id` as an id OR a handle, so the model addresses
745
2367
  * agents by the same names the user types. Ids are tried first, keeping the
@@ -763,11 +2385,25 @@ export default function (pi: ExtensionAPI) {
763
2385
  return record !== undefined && isTopLevelAgent(record) ? record : undefined;
764
2386
  },
765
2387
  };
766
- const ownsManagerRegistry = (globalThis as any)[MANAGER_KEY] === undefined;
2388
+ const managerRegistryHost = globalThis as typeof globalThis & Record<symbol, unknown>;
2389
+ const ownsManagerRegistry = managerRegistryHost[MANAGER_KEY] === undefined;
767
2390
  if (ownsManagerRegistry) {
768
- (globalThis as any)[MANAGER_KEY] = registryEntry;
2391
+ managerRegistryHost[MANAGER_KEY] = registryEntry;
769
2392
  }
770
2393
 
2394
+ // --- Goal-orchestration bridge (optional, additive) ---
2395
+ // Constructed at the factory but bound only in session_start; it reads the
2396
+ // manager this activation owns, never the process-global registry, and adds
2397
+ // no lifecycle broadcast of its own beyond the session-scoped ready hint.
2398
+ const goalBridge = new SubagentsGoalBridge({
2399
+ events: pi.events,
2400
+ source: {
2401
+ listAgents: () => manager.listAgents(),
2402
+ getRecord: (id) => manager.getRecord(id),
2403
+ steerAcknowledged: (id, message) => manager.steerAcknowledged(id, message),
2404
+ },
2405
+ });
2406
+
771
2407
  // --- Cross-extension RPC via pi.events ---
772
2408
  let currentCtx: ExtensionContext | undefined;
773
2409
  // RPC handlers + the `subagents:ready` broadcast are wired on `session_start`
@@ -806,6 +2442,8 @@ export default function (pi: ExtensionAPI) {
806
2442
  // This also wires the RPC handlers and broadcasts readiness — on the first
807
2443
  // bound session_start, so a filtered-out activation never advertises (#142).
808
2444
  pi.on("session_start", async (_event, ctx) => {
2445
+ sessionEpoch++;
2446
+ shuttingDown = false;
809
2447
  currentCtx = ctx;
810
2448
  // pi's own spinner gate: we mirror terminal.showTerminalProgress so a
811
2449
  // user who opted out of terminal progress doesn't get a subagent-driven
@@ -815,9 +2453,29 @@ export default function (pi: ExtensionAPI) {
815
2453
  terminalProgress.refresh();
816
2454
  if (ctx.hasUI) {
817
2455
  widget.setUICtx(ctx.ui);
818
- fleet.setUICtx(ctx.ui as any);
819
2456
  }
2457
+ // Awaitable refresh for this session's start. The factory load above stays
2458
+ // authoritative for the initial registration; this only picks up files that
2459
+ // changed since. It is NOT fire-and-forget: RPC/mention consumers wired
2460
+ // below must see the fresh global registry until their own scoped reload.
2461
+ await reloadCustomAgentsAsync();
2462
+ // Bind the durable report root before the session yields to any tool.
2463
+ // Deliberately after the synchronous UI capture above: a session_start
2464
+ // caller that does not await must still see the widget bound in the same
2465
+ // tick. Plain metadata is pinned here; no async continuation closes over
2466
+ // the ExtensionContext.
2467
+ // Evict first: roots whose records are all gone can then be drained,
2468
+ // closed and removed instead of accumulating for the process lifetime.
820
2469
  manager.clearCompleted(true);
2470
+ await ensureReportBinding(ctx);
2471
+ // Bind the goal bridge only now: manager and session id are live. A repeat
2472
+ // session_start for the same id keeps the existing listener/ledger; a new
2473
+ // id rebinds (releasing the previous listeners first).
2474
+ const goalSessionId = ctx.sessionManager?.getSessionId?.();
2475
+ if (goalSessionId && goalBridge.sessionId !== goalSessionId) goalBridge.bind(goalSessionId);
2476
+ // A new session inherits no deferred wait: its owner was a turn in the last
2477
+ // one, and its wakeup channel died with it.
2478
+ deferredResultInterest.clear();
821
2479
  // Guard mirrors the `!scheduler.isActive()` pattern below: session_start
822
2480
  // fires once per activation, but a double-bind must not leak listeners.
823
2481
  if (!rpcHandle) {
@@ -825,8 +2483,24 @@ export default function (pi: ExtensionAPI) {
825
2483
  events: pi.events,
826
2484
  pi,
827
2485
  getCtx: () => currentCtx,
2486
+ /** Resolve definitions and await root admission before a new id exists. */
2487
+ prepare: async () => {
2488
+ const admissionCtx = currentCtx;
2489
+ const admissionEpoch = sessionEpoch;
2490
+ const rootSessionId = admissionCtx?.sessionManager?.getSessionId?.();
2491
+ const registry = await reloadCustomAgentsAsync();
2492
+ await assertCleanupRootAccessAsync(rootSessionId);
2493
+ if (currentCtx === undefined || sessionEpoch !== admissionEpoch
2494
+ || admissionCtx?.sessionManager?.getSessionId?.() !== rootSessionId
2495
+ || currentCtx.sessionManager?.getSessionId?.() !== rootSessionId) {
2496
+ throw new ReportUnavailableError("inactive-activation");
2497
+ }
2498
+ return registry;
2499
+ },
828
2500
  manager: {
829
- spawn: spawnTopLevel,
2501
+ // The handler has already stripped a caller-supplied definition and
2502
+ // attached the one resolved from `prepare`; preserve that snapshot.
2503
+ spawn: spawnRpcPrepared,
830
2504
  awaitStartup: (id) => manager.awaitStartup(id),
831
2505
  getRecord: (id) => manager.getRecord(id),
832
2506
  // Unguarded on purpose: the stop handler now runs the top-level check
@@ -842,6 +2516,9 @@ export default function (pi: ExtensionAPI) {
842
2516
  if (record.status === "running" || record.status === "queued") return false;
843
2517
  record.resultConsumed = true;
844
2518
  cancelNudge(record.id);
2519
+ // Consumed is consumed: no deferred enrichment may ride the next
2520
+ // notification this record produces after a resume.
2521
+ deferredResultInterest.delete(record.id);
845
2522
  return true;
846
2523
  },
847
2524
  },
@@ -861,8 +2538,8 @@ export default function (pi: ExtensionAPI) {
861
2538
  ctx.ui.addAutocompleteProvider(current =>
862
2539
  createMentionProvider(
863
2540
  current,
864
- // Plain text, not renderAgentName: the same label FleetView and the
865
- // widget show, but the autocomplete description cannot carry ANSI.
2541
+ // Plain text, not renderAgentName: the widget's label, but autocomplete
2542
+ // descriptions cannot carry ANSI.
866
2543
  () => mentionRoster(manager, mentionTypes(), type => getConfig(type).displayName),
867
2544
  isAgentMentionsEnabled,
868
2545
  ),
@@ -872,7 +2549,7 @@ export default function (pi: ExtensionAPI) {
872
2549
  // extension factory has run, so this is the earliest point the real value
873
2550
  // exists. Detached inside — a workflow must not hold up session startup.
874
2551
  resolveWorkflowCollisions(ctx);
875
- runWorkflowFlag(ctx);
2552
+ await runWorkflowFlag(ctx);
876
2553
  });
877
2554
 
878
2555
  /** Agent types `@` can start, in the shape the roster wants. */
@@ -954,7 +2631,10 @@ export default function (pi: ExtensionAPI) {
954
2631
  // agent, so its frontmatter is what governs — `output_transcript: false`
955
2632
  // must keep holding, since record.outputFile is the sole gate every
956
2633
  // downstream consumer keys off and a resume must not re-open it.
957
- const config = getAgentConfig(record.type);
2634
+ // Resolve from THIS refresh's registry, not the process-global one a
2635
+ // concurrent root may re-register while this hook is suspended.
2636
+ const registry = await reloadCustomAgentsAsync();
2637
+ const config = getAgentConfigIn(registry, record.type);
958
2638
  const resumedRecord = await startBackgroundResume(ctx, record, mention.message, {
959
2639
  outputTranscript: config?.outputTranscript ?? getOutputTranscriptDefault(),
960
2640
  maxTurns: normalizeMaxTurns(config?.maxTurns ?? getDefaultMaxTurns()),
@@ -972,12 +2652,26 @@ export default function (pi: ExtensionAPI) {
972
2652
 
973
2653
  // Evicted, but its conversation is still on disk: reopen it. This is an
974
2654
  // ordinary spawn carrying a session file, so the new record picks up the
975
- // widget, fleet row, transcript and completion notification unchanged —
2655
+ // widget, transcript and completion notification unchanged —
976
2656
  // and `reclaim` hands it back the names the tombstone was holding.
977
2657
  if (resolved?.kind === "tombstone") {
978
2658
  const entry = resolved.entry;
979
2659
  const target = `@${entry.alias ?? entry.handle}`;
980
2660
 
2661
+ // The original id's cleanup receipt may be unproven: the durable entry is
2662
+ // then neither a proven deletion nor a proven survivor. Reopening this
2663
+ // history under a NEW id would bypass the ids-only read barrier and could
2664
+ // replay a conversation whose saved report cleanup may already have
2665
+ // removed. Refuse before any new id, SDK session or history mutation —
2666
+ // including the drop-tombstone path below, which would forget it.
2667
+ if (cleanupUnprovenReports.has(entry.id)) {
2668
+ ctx.ui.notify(
2669
+ `Could not resume ${target} — cleanup removed this agent's previous report but could not verify the removal, so its saved history stays untouched until that receipt resolves.`,
2670
+ "warning",
2671
+ );
2672
+ return { action: "handled" };
2673
+ }
2674
+
981
2675
  // Checked here rather than left to SessionManager.open: that runs inside
982
2676
  // runAgent, whose rejection lands on the record as an agent error, not in
983
2677
  // the catch below. A `/new` in another pi window or a manual delete makes
@@ -994,9 +2688,10 @@ export default function (pi: ExtensionAPI) {
994
2688
  // disabled type. A resume must not inherit that: reopening this
995
2689
  // conversation under a different agent's prompt and tools is not
996
2690
  // continuing it, and the new record would re-tombstone under the
997
- // substitute, so the handle would never find its way back.
998
- reloadCustomAgents();
999
- const dispatch = resolveSpawnType(entry.type);
2691
+ // substitute, so the handle would never find its way back. Resolve from
2692
+ // THIS refresh's registry; a concurrent root may re-register the global.
2693
+ const scopedRegistry = await reloadCustomAgentsAsync();
2694
+ const dispatch = resolveSpawnTypeIn(scopedRegistry, entry.type);
1000
2695
  if (!dispatch.ok || dispatch.fellBackFrom !== undefined) {
1001
2696
  logSubagentIssue({ kind: "spawn_rejected", requestedType: entry.type,
1002
2697
  reason: dispatch.ok ? "Type now resolves only through fallbackSubagent; resume refused." : dispatch.message });
@@ -1006,7 +2701,17 @@ export default function (pi: ExtensionAPI) {
1006
2701
  return { action: "handled" };
1007
2702
  }
1008
2703
 
2704
+ // Freeze the definition before the admission await: the conversation this
2705
+ // reopens must keep the prompt/tools/pins of the type that resolved here.
2706
+ const admittedDefinition = cloneAgentDefinition(getAgentConfigIn(scopedRegistry, dispatch.type));
2707
+
1009
2708
  try {
2709
+ // A supported SDK host reaches this path without session_start, so the
2710
+ // root's lazy bind is its FIRST activation. Await that admission before
2711
+ // any new id or SDK history exists (spawnResolved re-proves it).
2712
+ const pendingAdmission = reportBindingAdmission(ctx);
2713
+ if (pendingAdmission !== undefined) await pendingAdmission;
2714
+ await assertCleanupRootAccessAsync(ctx.sessionManager?.getSessionId?.(), [entry.sessionFile]);
1010
2715
  // spawnResolved, not spawnTopLevel: the latter strips
1011
2716
  // `resumeSessionFile` and `reclaim` as untrusted. This path is the
1012
2717
  // exception — both come from a tombstone this extension wrote.
@@ -1015,7 +2720,8 @@ export default function (pi: ExtensionAPI) {
1015
2720
  reclaim: { handle: entry.handle, alias: entry.alias },
1016
2721
  resumeSessionFile: entry.sessionFile,
1017
2722
  isBackground: true,
1018
- });
2723
+ ...(admittedDefinition === undefined ? {} : { agentDefinition: admittedDefinition }),
2724
+ }, true);
1019
2725
  // The agent may still be starting — wait, so a startup failure lands in
1020
2726
  // the catch below instead of being announced as a resume.
1021
2727
  await manager.awaitStartup(id);
@@ -1044,6 +2750,20 @@ export default function (pi: ExtensionAPI) {
1044
2750
  ?? (alias ? resolveHandleToType(alias, getAvailableTypes()) : undefined);
1045
2751
  if (!type) return { action: "continue" };
1046
2752
 
2753
+ /**
2754
+ * Fresh scoped resolution and a frozen definition for a mention-started
2755
+ * type. The roster above is synchronous and may be stale; this refresh is
2756
+ * what the spawn is actually admitted with. FallbackSubagent is allowed
2757
+ * here, exactly as a model-initiated Agent call at the same moment would be.
2758
+ */
2759
+ const admitMentionType = async (): Promise<{ type: string; agentDefinition?: AgentConfig }> => {
2760
+ const registry = await reloadCustomAgentsAsync();
2761
+ const dispatch = resolveSpawnTypeIn(registry, type);
2762
+ if (!dispatch.ok) throw new Error(dispatch.message);
2763
+ const definition = cloneAgentDefinition(getAgentConfigIn(registry, dispatch.type));
2764
+ return { type: dispatch.type, ...(definition === undefined ? {} : { agentDefinition: definition }) };
2765
+ };
2766
+
1047
2767
  // Claude Code never starts the agent itself: `@agent-<type>` becomes an
1048
2768
  // attachment asking the main model to do it, and the model writes the
1049
2769
  // agent's prompt from the conversation rather than forwarding the typed
@@ -1074,10 +2794,18 @@ export default function (pi: ExtensionAPI) {
1074
2794
  // agent the direct way rather than leaving the user with a toast and
1075
2795
  // nothing running.
1076
2796
  try {
1077
- const id = spawnTopLevel(pi, ctx, type, mention.message, {
2797
+ // Same first-activation admission as the direct path below. The
2798
+ // definition is frozen from this refresh before that await, so a
2799
+ // registry mutation while admission is pending cannot change it.
2800
+ const admitted = await admitMentionType();
2801
+ const pendingAdmission = reportBindingAdmission(ctx);
2802
+ if (pendingAdmission !== undefined) await pendingAdmission;
2803
+ await assertCleanupRootAccessAsync(ctx.sessionManager?.getSessionId?.());
2804
+ const id = spawnResolved(pi, ctx, admitted.type, mention.message, {
1078
2805
  description: describeMention(mention.message),
1079
2806
  isBackground: true,
1080
- });
2807
+ ...(admitted.agentDefinition === undefined ? {} : { agentDefinition: admitted.agentDefinition }),
2808
+ }, true);
1081
2809
  // Same reason as the direct path below: the agent may still be
1082
2810
  // starting, and a failure there must reach this catch.
1083
2811
  await manager.awaitStartup(id);
@@ -1088,20 +2816,29 @@ export default function (pi: ExtensionAPI) {
1088
2816
  "error",
1089
2817
  );
1090
2818
  }
1091
- });
2819
+ })
2820
+ // Last resort for the notify itself throwing (ctx gone stale): never an unhandled rejection.
2821
+ .catch((error: unknown) => console.warn("[pi-subagents] mention start failed:", error));
1092
2822
  return { action: "handled" };
1093
2823
  }
1094
2824
 
1095
2825
  try {
1096
- // Nothing else to pass: runAgent resolves model, thinking and max turns
1097
- // from the agent's own config when the spawn omits them, and the
1098
- // manager's onStart/onComplete callbacks own the widget, the fleet list
1099
- // and the completion notification — the same contract the scheduler and
1100
- // cross-extension RPC spawns run under.
1101
- const id = spawnTopLevel(pi, ctx, type, mention.message, {
2826
+ // A supported SDK host can reach this start without session_start; the
2827
+ // root's first activation must be proven active before a new id exists.
2828
+ // The definition is frozen from this refresh BEFORE that await.
2829
+ const admitted = await admitMentionType();
2830
+ const pendingAdmission = reportBindingAdmission(ctx);
2831
+ if (pendingAdmission !== undefined) await pendingAdmission;
2832
+ await assertCleanupRootAccessAsync(ctx.sessionManager?.getSessionId?.());
2833
+ // Nothing else to pass: runAgent derives model, thinking and max turns
2834
+ // from the admitted definition, and the manager's onStart/onComplete
2835
+ // callbacks own the widget and completion notification — the same contract
2836
+ // the scheduler and cross-extension RPC spawns run under.
2837
+ const id = spawnResolved(pi, ctx, admitted.type, mention.message, {
1102
2838
  description: describeMention(mention.message),
1103
2839
  isBackground: true,
1104
- });
2840
+ ...(admitted.agentDefinition === undefined ? {} : { agentDefinition: admitted.agentDefinition }),
2841
+ }, true);
1105
2842
  // The agent may still be starting (a worktree copy is an awaited git
1106
2843
  // call) — report a failure that lands there as a failed start, not as a
1107
2844
  // "Started" toast for an agent that never ran.
@@ -1114,7 +2851,9 @@ export default function (pi: ExtensionAPI) {
1114
2851
  });
1115
2852
 
1116
2853
  pi.on("session_before_switch", () => {
2854
+ sessionEpoch++;
1117
2855
  manager.clearCompleted(true);
2856
+ deferredResultInterest.clear();
1118
2857
  scheduler.stop();
1119
2858
  });
1120
2859
 
@@ -1142,6 +2881,11 @@ export default function (pi: ExtensionAPI) {
1142
2881
  // On shutdown, abort all agents immediately and clean up.
1143
2882
  // If the session is going down, there's nothing left to consume agent results.
1144
2883
  pi.on("session_shutdown", async () => {
2884
+ shuttingDown = true;
2885
+ sessionEpoch++;
2886
+ // Synchronous, before any await: no bus listener or steering ledger from
2887
+ // this binding may survive shutdown.
2888
+ goalBridge.unbind();
1145
2889
  rpcHandle?.unsubSpawn();
1146
2890
  rpcHandle?.unsubStop();
1147
2891
  rpcHandle?.unsubPing();
@@ -1150,18 +2894,42 @@ export default function (pi: ExtensionAPI) {
1150
2894
  currentCtx = undefined;
1151
2895
  // Only release the global slot if this activation claimed it — a child
1152
2896
  // session's shutdown must not delete the root session's registry entry.
1153
- if (ownsManagerRegistry && (globalThis as any)[MANAGER_KEY] === registryEntry) {
1154
- delete (globalThis as any)[MANAGER_KEY];
2897
+ if (ownsManagerRegistry && managerRegistryHost[MANAGER_KEY] === registryEntry) {
2898
+ delete managerRegistryHost[MANAGER_KEY];
1155
2899
  }
1156
2900
  scheduler.stop();
1157
2901
  // Before abortAll, and not folded into it: a workflow owns a worker thread
1158
- // as well as its children, and only its own signal terminates that.
2902
+ // as well as its children, and only its own signal terminates that. Maps and
2903
+ // creation/settlement proofs stay until quiescence is decided below: abort
2904
+ // is not proof that a workflow cannot still write.
1159
2905
  for (const task of workflowTasks.values()) task.abortController.abort();
1160
- workflowTasks.clear();
1161
2906
  manager.abortAll();
1162
- for (const timer of pendingNudges.values()) clearTimeout(timer);
2907
+ // Aborting stops a producer; it does NOT undo records the runtime already
2908
+ // accepted into its ordered write chain, nor the final artifact
2909
+ // registration and completion notification a settled run still owns. Wait
2910
+ // for the actual run promises and their accepted-journal tails, so a normal
2911
+ // process exit cannot drop resume history. The handles are re-read until
2912
+ // none remain: a launch already in flight can register after the first
2913
+ // pass. Bounded by the runs themselves (worker termination + accepted
2914
+ // appends), never by an arbitrary deadline.
2915
+ await awaitWorkflowQuiescence();
2916
+ // A workflow this shutdown stopped settled INSIDE the wait above, so its
2917
+ // completion is still held. Deliver that one notice now, synchronously:
2918
+ // its run is over and a held timer would only be cleared below. Nothing
2919
+ // can be scheduled AFTER the handler returns — every workflow id is marked
2920
+ // discarded here, and the remaining holds are agent notices, which have
2921
+ // never survived shutdown.
2922
+ flushStoppedWorkflowNudges();
2923
+ for (const id of new Set([
2924
+ ...workflowTasks.keys(),
2925
+ ...workflowRunPromises.keys(),
2926
+ ...workflowJournalDrains.keys(),
2927
+ ])) {
2928
+ discardedWorkflowNotifications.add(id);
2929
+ }
2930
+ for (const entry of pendingNudges.values()) clearTimeout(entry.timer);
1163
2931
  pendingNudges.clear();
1164
- fleet.dispose();
2932
+ deferredResultInterest.clear();
1165
2933
  widget.dispose();
1166
2934
  // Clear the terminal spinner before pi restores the terminal — nothing
1167
2935
  // else writes the clear for work we asserted while the main session was
@@ -1171,32 +2939,80 @@ export default function (pi: ExtensionAPI) {
1171
2939
  // extensions bound there can release what they armed in `session_start` (#242).
1172
2940
  // pi awaits this handler, and the process exits right after — unawaited, those
1173
2941
  // handlers would never run. Internally bounded, so a hung one can't strand quit.
1174
- await manager.dispose(pi);
2942
+ const shutdown = await manager.dispose(pi);
2943
+ // Lazy tool-only binding may still be creating a store not yet in the map.
2944
+ // Finish it before collecting stores, so its pending reports are flushed
2945
+ // and its activation cannot outlive this root's shutdown.
2946
+ await reportBindChain;
2947
+ // The manager has already handed every terminal/partial generation to its
2948
+ // root's store. Close EVERY bound root (a session switch may have left one
2949
+ // serving in-flight work): each close stops new saves, then drains accepted
2950
+ // writes/maintenance. Leases are released only for proven-quiescent stores
2951
+ // whose bounded drain completed; every uncertain root stays protected.
2952
+ const workflowWorkRemains = workflowCleanupProofs.size > 0
2953
+ || [...workflowTasks.values()].some(task => task.status === "running" || task.status === "paused");
2954
+ const quiescent = shutdown.status === "completed" && !workflowWorkRemains;
2955
+ const stores = new Set<ReportStore>([...reportStores.values(), reportStore]);
2956
+ await closeReportStores(stores, quiescent);
2957
+ // The lease decision above is final, and every workflow run/drain handle
2958
+ // was awaited above, so the maps are empty of live work by now. Clearing
2959
+ // them drops pointers, not work: nothing here is a substitute for the
2960
+ // drain. On an uncertain shutdown the proofs stay, exactly as before.
2961
+ workflowTasks.clear();
2962
+ workflowArtifactPaths.clear();
2963
+ workflowArtifactRoots.clear();
2964
+ workflowArtifactStores.clear();
2965
+ workflowCleanupProofs.clear();
2966
+ workflowRunPromises.clear();
2967
+ workflowJournalDrains.clear();
2968
+ knownGeneratedWorkflowPaths.clear();
2969
+ discardedWorkflowNotifications.clear();
2970
+ cleanupUnprovenReports.clear();
2971
+ // A later activation may reuse the same root id, but never its closed store.
2972
+ // Incomplete closes have already retained their leases above, so dropping
2973
+ // these object references cannot make an uncertain root look unprotected.
2974
+ reportStores.clear();
2975
+ reportActiveRoots.clear();
2976
+ if (archiveDrainTimer !== undefined) {
2977
+ clearTimeout(archiveDrainTimer);
2978
+ archiveDrainTimer = undefined;
2979
+ }
2980
+ archiveRetryAttempts.clear();
2981
+ pendingArchivedRecords.clear();
2982
+ reportBoundRoot = undefined;
2983
+ reportStore = createReportStore();
2984
+ reportBindChain = Promise.resolve();
1175
2985
  });
1176
2986
 
1177
- // Live widget: show running agents above editor.
1178
- // widgetMode (default "background") selects what the widget shows: "all" =
2987
+ // Live compact widget; placement is independent of agent filtering.
2988
+ // widgetMode (default "all") selects what the widget shows: "all" =
1179
2989
  // every agent; "background" = hide foreground (they already render inline as
1180
2990
  // the Agent tool result, so showing them here too is a duplicate, #118), keep
1181
2991
  // everything else; "off" = hide the widget entirely. Read live at render time.
1182
- let widgetMode: WidgetMode = "background";
2992
+ let widgetMode: WidgetMode = "all";
1183
2993
  function getWidgetMode(): WidgetMode { return widgetMode; }
1184
- const widget = new AgentWidget(manager, agentActivity, getWidgetMode, isShowCostEnabled, isShowModelEnabled);
2994
+ let widgetPlacement: WidgetPlacement = "above";
2995
+ function getWidgetPlacement(): WidgetPlacement { return widgetPlacement; }
2996
+ const widget = new AgentWidget(manager, agentActivity, getWidgetMode, isShowCostEnabled, isShowModelEnabled, getWidgetPlacement);
1185
2997
  function setWidgetMode(m: WidgetMode): void { widgetMode = m; widget.update(); }
1186
-
1187
- // Claude Code-style FleetView: navigable list of main + subagents below the editor.
1188
- const fleet = new FleetList(manager, agentActivity, isShowCostEnabled);
1189
- fleet.setAgentOpener(async (record, onCloseReady) => {
1190
- if (!currentCtx) throw new Error("No active parent session.");
1191
- await viewAgentConversation(currentCtx, record, onCloseReady);
2998
+ function setWidgetPlacement(placement: WidgetPlacement): void { widgetPlacement = placement; widget.update(); }
2999
+ // ← opens the Hub whenever it would have rows: any top-level agent (running,
3000
+ // queued, or settled history awaiting the sweep) or a workflow run from this
3001
+ // session — regardless of what the widgetMode filter leaves visible in the
3002
+ // compact list. While the Hub is open it owns the keyboard (isOpen), so ←
3003
+ // can never stack a second overlay on top of it.
3004
+ let hubOpen = false;
3005
+ widget.setHubOpener({
3006
+ open: () => {
3007
+ if (!currentCtx) return;
3008
+ // Fire-and-forget from a key handler: a rejection here (for example a ctx gone stale) would end pi.
3009
+ void showFleetOverlay(currentCtx).catch((error: unknown) => {
3010
+ console.warn("[pi-subagents] could not open the agent hub:", error);
3011
+ });
3012
+ },
3013
+ hasContent: () => manager.listAgents().some(isTopLevelAgent) || (isWorkflowsEnabled() && fleetWorkflows().length > 0),
3014
+ isOpen: () => hubOpen,
1192
3015
  });
1193
- // ← at an empty prompt: the two-pane overlay (canonical roster surface — the
1194
- // compact list stays the glanceable one). Between sessions there is no ctx to
1195
- // open it against, and the key then stays with the editor.
1196
- fleet.setOverlayOpener(() => { if (currentCtx) void showFleetOverlay(currentCtx); });
1197
- let fleetViewEnabled = true;
1198
- function isFleetViewEnabled(): boolean { return fleetViewEnabled; }
1199
- function setFleetViewEnabled(b: boolean): void { fleetViewEnabled = b; fleet.setEnabled(b); }
1200
3016
 
1201
3017
  // Terminal spinner for background subagent work — the tab/taskbar progress
1202
3018
  // pi clears at agent_end even when subagents keep running. See
@@ -1271,6 +3087,23 @@ export default function (pi: ExtensionAPI) {
1271
3087
  workflowsPinned = true;
1272
3088
  }
1273
3089
 
3090
+ // Agent type a workflow's `agent()` call uses when it names none. `task` is
3091
+ // the economical default (DEFAULT_WORKFLOW_AGENT_TYPE in runtime.ts); this
3092
+ // setting pins a different role per project. Precedence is per-run: an
3093
+ // explicit `SubagentWorkflow(agentType)` outranks it, a resume inherits the
3094
+ // original run's frozen choice, and a script's per-call `opts.agentType`
3095
+ // outranks all three. Read live when a run is created — existing tasks keep
3096
+ // the role they started with, so changing the setting never re-roles a run
3097
+ // already in flight.
3098
+ //
3099
+ // Deliberately not validated against the registry here: a role can be renamed
3100
+ // or temporarily disabled, and silently substituting a different (possibly
3101
+ // expensive) role would hide that. Resolution stays at spawn time, where an
3102
+ // unavailable workflow default is refused rather than sent to a fallback.
3103
+ let workflowDefaultAgentType = DEFAULT_WORKFLOW_AGENT_TYPE;
3104
+ function getWorkflowDefaultAgentType(): string { return workflowDefaultAgentType; }
3105
+ function setWorkflowDefaultAgentType(agentType: string) { workflowDefaultAgentType = agentType; }
3106
+
1274
3107
  // ---- Disable default agents configuration ----
1275
3108
  // When enabled, the three hardcoded default agents (general-purpose, Explore,
1276
3109
  // Plan) are not registered. User-defined agents from project/global custom
@@ -1337,7 +3170,7 @@ export default function (pi: ExtensionAPI) {
1337
3170
  /**
1338
3171
  * Launch a detached resume of an existing agent and wire everything a
1339
3172
  * re-running agent needs: transcript anchoring, activity tracking, join-mode
1340
- * batching, the widget/fleet refresh, and the `subagents:created` event.
3173
+ * batching, the widget refresh, and the `subagents:created` event.
1341
3174
  *
1342
3175
  * Shared by the Agent tool's `resume` + `run_in_background` branch and the
1343
3176
  * `@handle message` prompt mention — they differ only in how they report the
@@ -1352,30 +3185,28 @@ export default function (pi: ExtensionAPI) {
1352
3185
  prompt: string,
1353
3186
  opts: { outputTranscript: boolean; maxTurns?: number; toolCallId?: string },
1354
3187
  ): Promise<AgentRecord | undefined> {
3188
+ // Before the first record/transcript mutation: a selected id/session or a
3189
+ // root reserved by cleanup must never reopen work on the artifact set. The
3190
+ // combined async scope covers the agent, its session and its transcript;
3191
+ // the entering root is proved separately when it is not the record's own.
3192
+ await assertCleanupArtifactAccessAsync(existing);
3193
+ const enteringRoot = ctx.sessionManager.getSessionId();
3194
+ if (existing.rootSessionId === undefined || existing.rootSessionId !== enteringRoot) {
3195
+ await assertCleanupRootAccessAsync(enteringRoot, [existing.sessionFile]);
3196
+ }
1355
3197
  const id = existing.id;
1356
3198
  const joinMode = resolveJoinMode(defaultJoinMode, true);
1357
- // Assigned unconditionally: the completion notification carries this as
1358
- // `<tool-use-id>`, so a mention-resume (which passes none) has to CLEAR the
1359
- // id left by the spawn that created the record. Keeping it would point the
1360
- // orchestrator's new result at a tool call that was answered runs ago.
1361
- existing.toolCallId = opts.toolCallId;
1362
- if (joinMode) existing.joinMode = joinMode;
1363
- // Reuse the agent's transcript rather than starting a fresh one: the
1364
- // path is deterministic per agent+session, so writing an initial entry
1365
- // would truncate the previous run's turns (see ensureOutputFile).
1366
- if (opts.outputTranscript) {
1367
- existing.outputFile = createOutputFilePath(ctx.cwd, id, ctx.sessionManager.getSessionId());
1368
- ensureOutputFile(existing.outputFile);
1369
- }
1370
- // Anchor streaming past the turns already on disk, captured BEFORE the
1371
- // run starts. The resumed prompt lands as an ordinary user message at
1372
- // this index, so it is written exactly once.
1373
- const transcriptAnchor = existing.session?.messages.length ?? 0;
3199
+ const outputSessionId = ctx.sessionManager.getSessionId();
1374
3200
 
3201
+ // Pure locals only: nothing shared is touched until the manager says this
3202
+ // caller won admission. The tracker is created here so the synchronous
3203
+ // `onAdmitted` hook allocates nothing that could throw mid-transition; the
3204
+ // anchor is captured by the hook, from the record the accepted run owns.
1375
3205
  const { state: bgState, callbacks: bgCallbacks } = createActivityTracker(opts.maxTurns);
1376
3206
  // resumeAgent has no onSessionCreated — the session predates this run —
1377
3207
  // so seed it directly, or the widget shows no context % for the agent.
1378
3208
  bgState.session = existing.session;
3209
+ let transcriptAnchor = 0;
1379
3210
 
1380
3211
  // No `signal`: a background spawn deliberately omits it, and a detached
1381
3212
  // resume must behave the same. Passing it would abort this agent when
@@ -1385,10 +3216,36 @@ export default function (pi: ExtensionAPI) {
1385
3216
  isBackground: true,
1386
3217
  onToolActivity: bgCallbacks.onToolActivity,
1387
3218
  onAssistantUsage: bgCallbacks.onAssistantUsage,
3219
+ // The ownership boundary. The manager runs this synchronously only for
3220
+ // the WINNING resume, after its last guarded identity check and before
3221
+ // any generation/terminal/start bookkeeping. Everything shared and
3222
+ // caller-visible is mutated here, so a refused concurrent caller cannot
3223
+ // rewrite the winner's tool-call correlation, join mode, output wiring
3224
+ // or anchor. Only accepted ownership can reach the record's own fields.
3225
+ onAdmitted: admitted => {
3226
+ // Assigned unconditionally: the completion notification carries this as
3227
+ // `<tool-use-id>`, so a mention-resume (which passes none) has to CLEAR
3228
+ // the id left by the spawn that created the record. Keeping it would
3229
+ // point the orchestrator's new result at a tool call that was answered
3230
+ // runs ago.
3231
+ admitted.toolCallId = opts.toolCallId;
3232
+ if (joinMode) admitted.joinMode = joinMode;
3233
+ // Reuse the agent's transcript rather than starting a fresh one: the
3234
+ // path is deterministic per agent+session, so writing an initial entry
3235
+ // would truncate the previous run's turns (see ensureOutputFile).
3236
+ if (opts.outputTranscript) {
3237
+ admitted.outputFile = createOutputFilePath(ctx.cwd, id, outputSessionId);
3238
+ ensureOutputFile(admitted.outputFile);
3239
+ }
3240
+ // Anchor streaming past the turns already on disk, captured BEFORE the
3241
+ // run starts. The resumed prompt lands as an ordinary user message at
3242
+ // this index, so it is written exactly once.
3243
+ transcriptAnchor = admitted.session?.messages.length ?? 0;
3244
+ },
1388
3245
  // Fires when the run actually starts — immediately, or on queue
1389
3246
  // drain. Wiring it here (rather than after resume() returns) means a
1390
- // resume stopped while still queued never started streaming, so
1391
- // there is no subscription left behind for a later run to trip over.
3247
+ // resume stopped while still queued never started streaming, so there
3248
+ // is no subscription left behind for a later run to trip over.
1392
3249
  onStarted: () => {
1393
3250
  const rec = manager.getRecord(id);
1394
3251
  if (rec?.session && rec.outputFile) {
@@ -1397,6 +3254,9 @@ export default function (pi: ExtensionAPI) {
1397
3254
  },
1398
3255
  });
1399
3256
  if (!record) return undefined;
3257
+ // Deliberately NOT cleared here: `store.save` refuses to replace an existing
3258
+ // deletion receipt, so a resume starting proves nothing about the durable
3259
+ // body. Only a durably saved full entry clears the barrier (saveArchivedRecord).
1400
3260
 
1401
3261
  if (joinMode != null && joinMode !== 'async') {
1402
3262
  currentBatchAgents.push({ id, joinMode });
@@ -1411,8 +3271,6 @@ export default function (pi: ExtensionAPI) {
1411
3271
  widget.markRunning(id);
1412
3272
  widget.ensureTimer();
1413
3273
  widget.update();
1414
- fleet.ensureTimer();
1415
- fleet.update();
1416
3274
 
1417
3275
  // Resume ignores subagent_type (the record keeps the type it was
1418
3276
  // spawned with), so report the record's own identity — a "created"
@@ -1431,7 +3289,6 @@ export default function (pi: ExtensionAPI) {
1431
3289
  // Grab UI context from first tool execution + clear lingering widget on new turn
1432
3290
  pi.on("tool_execution_start", async (_event, ctx) => {
1433
3291
  widget.setUICtx(ctx.ui as UICtx);
1434
- fleet.setUICtx(ctx.ui as unknown as FleetUICtx);
1435
3292
  widget.onTurnStart();
1436
3293
  });
1437
3294
 
@@ -1478,6 +3335,9 @@ export default function (pi: ExtensionAPI) {
1478
3335
  setMaxConcurrentForeground: (n) => manager.setMaxConcurrentForeground(n),
1479
3336
  setDefaultMaxTurns,
1480
3337
  setGraceTurns,
3338
+ // Caller turn caps are a policy, so this one is not merely persisted: a
3339
+ // project/session that omits the key must not inherit another's `true`.
3340
+ setAllowPerCallTurnLimits,
1481
3341
  setDefaultJoinMode,
1482
3342
  setBackgroundByDefault,
1483
3343
  setSchedulingEnabled,
@@ -1485,13 +3345,14 @@ export default function (pi: ExtensionAPI) {
1485
3345
  setStrictAgentFiles: (b) => { strictAgentFiles = b; },
1486
3346
  setDisableDefaultAgents: setDisableDefaultAgents,
1487
3347
  setToolDescriptionMode: setToolDescriptionMode,
1488
- setFleetView: setFleetViewEnabled,
1489
3348
  setAgentMentions: setAgentMentionMode,
1490
3349
  setRememberAgents,
1491
3350
  setWidgetMode: setWidgetMode,
3351
+ setWidgetPlacement,
1492
3352
  setOutputTranscript: setOutputTranscriptDefault,
1493
3353
  setWorktreeIsolation: setWorktreeIsolationEnabled,
1494
3354
  setWorkflowsEnabled: setWorkflowsEnabled,
3355
+ setWorkflowDefaultAgentType: setWorkflowDefaultAgentType,
1495
3356
  setMaxSubagentDepth: setMaxSubagentDepth,
1496
3357
  setFallbackSubagent: setFallbackSubagent,
1497
3358
  setReportUsage,
@@ -1557,15 +3418,15 @@ export default function (pi: ExtensionAPI) {
1557
3418
  // Compact Agent tool description (#91, `toolDescriptionMode: "compact"`) —
1558
3419
  // the same load-bearing facts as the full version at ~75% fewer tokens, for
1559
3420
  // small/local models. Per-option details live in the param descriptions.
1560
- const compactAgentToolDescription = `Launch an autonomous agent for complex, multi-step tasks. Agent types:
3421
+ const compactAgentToolDescription = `Launch an autonomous agent. Types:
1561
3422
  ${buildCompactTypeListText()}
1562
3423
 
1563
- Custom agents: .pi/agents/<name>.md (project) or ${getAgentDir()}/agents/<name>.md (global).
3424
+ Custom agents: .pi/agents/<name>.md (project), or agents/<name>.md under the configured pi agent directory (global).
1564
3425
 
1565
3426
  Notes:
1566
- - description: 3-5 words (shown in UI). Prompts must be self-contained — the agent has not seen this conversation.
3427
+ - description: 3-5 UI words. Prompts must be self-contained; the agent hasn't seen this conversation.
1567
3428
  - Parallel work: one message, multiple Agent calls — they run concurrently.
1568
- - Subagents run in the background by default; you'll be notified when one completes. Pass run_in_background: false only when your very next action depends on the result and nothing else could usefully happen while it runs. Never fabricate or predict a pending agent's results — if the user asks before the notification arrives, say it's still running.
3429
+ - Subagents run in the background by default; you'll be notified when one completes. Pass run_in_background: false when your very next action depends on the result. In the terminal UI that is a PENDING logical await — your turn is released and the report arrives in a later turn; headless/print runs block inline. Never poll for, fabricate, or predict a pending agent's result.
1569
3430
  - The result is not shown to the user — summarize it for them. Verify an agent's claimed code changes before reporting work done.
1570
3431
  - resume continues a previous agent by ID. If the user asks to cancel/stop an agent, call stop_subagent; to redirect it, call steer_subagent.${isolationCompactGuideline}`;
1571
3432
 
@@ -1588,8 +3449,8 @@ If the target is already known, use a direct tool — \`read\` for a known path,
1588
3449
  - When you launch multiple agents for independent work, send them in a single message with multiple tool uses so they run concurrently. If the user specifies that they want you to run agents "in parallel", you MUST send a single message with multiple Agent tool use content blocks.
1589
3450
  - When the agent is done, it returns a single message back to you. The result is not visible to the user — to show the user, send a text message with a concise summary.
1590
3451
  - Trust but verify: an agent's summary describes what it intended to do, not necessarily what it did. When an agent writes or edits code, check the actual changes before reporting the work as done.
1591
- - Agents run in the background by default. When an agent runs in the background, you will be automatically notified when it completes — do NOT sleep, poll, or proactively check on its progress. Continue with other work or respond to the user instead.
1592
- - **Foreground vs background**: Pass \`run_in_background: false\` only when your very next action depends on the agent's result and nothing else could usefully happen while it runs — e.g., a research agent whose finding gates the edit you're about to make. Otherwise let it run in the background (the default) — this includes fire-and-forget work, independent investigations, and anything where the user might hand you something else in the meantime. Wanting the result "next" is not enough on its own.
3452
+ - Agents run in the background by default. When an agent runs in the background, you will be automatically notified when it completes, and that notification carries the agent's complete final report — do NOT sleep, poll, or proactively check on its progress. Continue with other work or respond to the user instead.
3453
+ - **Foreground vs background**: Pass \`run_in_background: false\` only when your very next action depends on the agent's result and nothing else could usefully happen while it runs — e.g., a research agent whose finding gates the edit you're about to make. Otherwise let it run in the background (the default) — this includes fire-and-forget work, independent investigations, and anything where the user might hand you something else in the meantime. Wanting the result "next" is not enough on its own. In the terminal UI a foreground request is a logical await anyway: it returns PENDING immediately and releases your turn, and the agent's complete final report arrives automatically in a later turn (headless/print runs still block inline).
1593
3454
  - **Don't race**: after launching a background agent, you know nothing about its results. Never fabricate or predict them in any format — not as prose, summary, or structured output. The completion notification arrives in a later turn; it is never something you write yourself. If the user asks before it lands, say the agent is still running — give status, not a guess.
1594
3455
  - Use resume with an agent ID to continue a previous agent's work. A new (non-resume) Agent call starts a fresh agent with no memory of prior runs, so the prompt must be self-contained.
1595
3456
  - Use steer_subagent to send mid-run messages to a running background agent.
@@ -1674,7 +3535,7 @@ Terse command-style prompts produce shallow, generic work.
1674
3535
  "Use Agent with specialized agents when the task matches an agent type's description. Subagents are valuable for parallelizing independent queries or for protecting the main context window from excessive results, but should not be used excessively when not needed. Importantly, avoid duplicating work that subagents are already doing — if you delegate research to a subagent, do not also perform the same searches yourself.",
1675
3536
  `Use Agent by choosing the required subagent_type from the enabled roles and their descriptions.${rolePreferences.length ? ` Prefer ${rolePreferences.join("; ")}.` : ""} Use exact names, including case. Explicit valid choices remain authoritative; there is no automatic task classifier or forced remapping. For a known target, use direct tools (read, grep, find).`,
1676
3537
  "Agent model and thinking pins take precedence over call parameters. Unpinned fields use caller parameters, otherwise inherit the live parent model and thinking level. inherit_context controls conversation history, not model selection.",
1677
- "When an agent runs in the background, you will be notified on completion — do not poll or sleep waiting for it. Continue with other work instead.",
3538
+ "When an agent runs in the background — including a run_in_background: false request in the terminal UI, which returns PENDING at once and releases your turn — you will be notified on completion, and that notification carries the agent's complete final report. Do not poll or sleep waiting for it, never fabricate a pending result, and keep continuing with useful work instead. A sibling tool in the same batch may proceed without the dependency's result; it is not complete yet.",
1678
3539
  "Trust but verify: an agent's summary describes intent, not outcome. When an agent writes or edits code, check the actual changes before reporting work as done.",
1679
3540
  ],
1680
3541
  parameters: Type.Object({
@@ -1704,20 +3565,19 @@ Terse command-style prompts produce shallow, generic work.
1704
3565
  description: `Thinking level: ${THINKING_LEVELS.join(", ")}. Agent thinking pin wins; this parameter only fills an unspecified field. Omit to inherit live parent thinking when unpinned.`,
1705
3566
  }),
1706
3567
  ),
1707
- max_turns: Type.Optional(
1708
- Type.Number({
1709
- description: "Maximum number of agentic turns before stopping. Omit for unlimited (default).",
1710
- minimum: 1,
1711
- }),
1712
- ),
3568
+ // Caller turn caps are a configurable policy (off by default): when
3569
+ // disabled the parameter is absent from the schema entirely, so the model
3570
+ // is never offered a knob the resolver would drop. Runtime filtering
3571
+ // still covers calls that bypass schema validation.
3572
+ ...maxTurnsParam(getAllowPerCallTurnLimits()),
1713
3573
  run_in_background: Type.Optional(
1714
3574
  Type.Boolean({
1715
- description: "Defaults to true — the agent runs detached, returning its ID immediately, and you are notified on completion. Set false only when your very next action depends on the result; the call then blocks and returns the agent's full output inline.",
3575
+ description: "Defaults to true — the agent runs detached, returning its ID immediately, and you are notified on completion. Set false when your very next action depends on the result. In the terminal UI (interactive mode), false is a logical await: the call returns PENDING immediately and releases your turn, the agent keeps running in the background, and its complete final report arrives automatically in a later turn — do not poll or fabricate it. In headless/print runs, false keeps the historical inline contract: the call blocks and returns the agent's full output inline.",
1716
3576
  }),
1717
3577
  ),
1718
3578
  resume: Type.Optional(
1719
3579
  Type.String({
1720
- description: "Optional agent ID to resume from. Continues from previous context. Resumes detached like any other spawn; pass run_in_background: false to block and get the result inline. An agent can only be resumed once its current run has finished — use steer_subagent to reach one mid-run.",
3580
+ description: "Optional agent ID to resume from. Continues from previous context. Resumes detached like any other spawn; pass run_in_background: false to request foreground — in the terminal UI that returns PENDING at once and the complete report arrives in a later turn, while headless/print runs block and return it inline. An agent can only be resumed once its current run has finished — use steer_subagent to reach one mid-run.",
1721
3581
  }),
1722
3582
  ),
1723
3583
  isolated: Type.Optional(
@@ -1854,11 +3714,25 @@ Terse command-style prompts produce shallow, generic work.
1854
3714
  // ---- Execute ----
1855
3715
 
1856
3716
  execute: async (toolCallId, params, signal, onUpdate, ctx) => {
3717
+ // First tool may run without a prior session_start (older harnesses).
3718
+ // Start the bind but do not await it here: the Agent tool's dispatch must
3719
+ // stay synchronous so two blocking calls in one pi batch still reach the
3720
+ // foreground queue in the same tick. session_start has already bound the
3721
+ // real session before any tool runs. A root this command is about to
3722
+ // delete is not bound at all — binding publishes a lease and runs
3723
+ // maintenance — so only that case skips the eager bind; an inactive
3724
+ // (refused) binding still retries, which is how it recovers a released
3725
+ // foreign lock, and the artifact guard below refuses work until it has.
3726
+ const initialAgentRoot = ctx.sessionManager?.getSessionId?.();
3727
+ if (!cleanupRootReserved(initialAgentRoot)) void ensureReportBinding(ctx);
1857
3728
  // Ensure we have UI context for widget rendering
1858
3729
  widget.setUICtx(ctx.ui as UICtx);
1859
3730
 
1860
- // Reload custom agents so new project/global .md files are picked up without restart
1861
- reloadCustomAgents();
3731
+ // Awaitable refresh: new project/global .md files are picked up without a
3732
+ // restart, and dispatch resolves against THIS load's registry. The
3733
+ // process-global registry can be re-registered by a concurrent root while
3734
+ // this call suspends, so it is not consulted after the await.
3735
+ const registry = await reloadCustomAgentsAsync();
1862
3736
 
1863
3737
  const rawType = params.subagent_type as SubagentType;
1864
3738
  // Single decision point for dispatch (#183): unknown, disabled and
@@ -1866,7 +3740,7 @@ Terse command-style prompts produce shallow, generic work.
1866
3740
  // background or scheduled call can't start running the wrong agent while
1867
3741
  // the caller is still unaware. `fallbackSubagent` decides whether an
1868
3742
  // unresolvable type falls back or fails closed.
1869
- const dispatch = resolveSpawnType(rawType);
3743
+ const dispatch = resolveSpawnTypeIn(registry, rawType);
1870
3744
  // `resume` replays a stored session and ignores `subagent_type` entirely,
1871
3745
  // but the parameter is required by the schema — so gating it here would
1872
3746
  // make a live agent unresumable the moment its type is deleted, disabled,
@@ -1886,19 +3760,32 @@ Terse command-style prompts produce shallow, generic work.
1886
3760
  // session and ignores `subagent_type` entirely, so a note about type
1887
3761
  // substitution would be describing something that didn't happen.
1888
3762
  const fallbackNote = dispatch.ok && dispatch.fellBackFrom !== undefined
1889
- ? `Note: Unknown agent type "${dispatch.fellBackFrom}" — using ${resolveType(subagentType) ? subagentType : "the fallback agent config"}.\n\n`
3763
+ ? `Note: Unknown agent type "${dispatch.fellBackFrom}" — using ${getAgentConfigIn(registry, subagentType) ? subagentType : "the fallback agent config"}.\n\n`
1890
3764
  : "";
1891
3765
 
1892
3766
  const displayName = getDisplayName(subagentType);
1893
3767
 
1894
- // Get agent config (if any)
1895
- const customConfig = getAgentConfig(subagentType);
3768
+ // Get agent config from the SAME registry that resolved the type, then
3769
+ // freeze it before any report-admission/worktree await. Queueing, a slow
3770
+ // guard or a reload in another root must not change the prompt, tool
3771
+ // permissions, model or nesting policy this call was admitted with.
3772
+ const customConfig = getAgentConfigIn(registry, subagentType);
3773
+ const admittedDefinition = cloneAgentDefinition(customConfig);
1896
3774
 
1897
3775
  const resolvedConfig = resolveAgentInvocationConfig(customConfig, params, {
1898
3776
  worktreeAllowed: isWorktreeIsolationEnabled(),
1899
3777
  defaultRunInBackground: getBackgroundByDefault(),
3778
+ // Caller caps are opt-in: with the policy off, a `max_turns` parameter
3779
+ // is dropped here (the schema also omits it), while an agent-file pin
3780
+ // and the configured default keep deciding the real budget.
3781
+ allowPerCallTurnLimits: getAllowPerCallTurnLimits(),
1900
3782
  });
1901
3783
 
3784
+ // `/subagents off`: the spawn twins the main model — pins and caller
3785
+ // overrides give way, and a scope check against the model the session is
3786
+ // already running can only produce a spurious refusal. Resume is left
3787
+ // alone either way: it replays the stored session, model included.
3788
+ const twinForced = isForceMainModel();
1902
3789
  // Resume keeps the existing session's model; validate only new spawns.
1903
3790
  // Caller shorthand retains resolveModel's policy. A qualified agent pin
1904
3791
  // resolves exactly, then to the same id on another available provider;
@@ -1906,7 +3793,7 @@ Terse command-style prompts produce shallow, generic work.
1906
3793
  // visible notice, while user-authored pins stay strict and throw.
1907
3794
  let model = ctx.model;
1908
3795
  let pinFallbackNotice: string | undefined;
1909
- if (!params.resume && resolvedConfig.modelInput !== undefined) {
3796
+ if (!twinForced && !params.resume && resolvedConfig.modelInput !== undefined) {
1910
3797
  const resolved = resolvedConfig.modelFromParams
1911
3798
  ? resolveModel(resolvedConfig.modelInput, ctx.modelRegistry)
1912
3799
  : resolvePinnedModel(resolvedConfig.modelInput, ctx.modelRegistry, {
@@ -1930,19 +3817,21 @@ Terse command-style prompts produce shallow, generic work.
1930
3817
  // Scope validation: the effective resolved model is checked against the
1931
3818
  // user's enabledModels list. Policy (hard error vs warn-and-proceed) lives
1932
3819
  // in model-scope.ts so the nested delegation tools apply the same rule.
1933
- const scopeVerdict = checkModelScope({
1934
- model,
1935
- cwd: ctx.cwd,
1936
- modelRegistry: ctx.modelRegistry,
1937
- callerSupplied: resolvedConfig.modelFromParams,
1938
- agentLabel: customConfig?.displayName ?? subagentType,
1939
- modelInput: resolvedConfig.modelInput,
1940
- });
1941
- if (!params.resume && scopeVerdict.kind === "error") {
1942
- logSubagentIssue({ kind: "spawn_rejected", requestedType: subagentType, reason: scopeVerdict.message });
1943
- return textResult(scopeVerdict.message);
3820
+ if (!twinForced) {
3821
+ const scopeVerdict = checkModelScope({
3822
+ model,
3823
+ cwd: ctx.cwd,
3824
+ modelRegistry: ctx.modelRegistry,
3825
+ callerSupplied: resolvedConfig.modelFromParams,
3826
+ agentLabel: customConfig?.displayName ?? subagentType,
3827
+ modelInput: resolvedConfig.modelInput,
3828
+ });
3829
+ if (!params.resume && scopeVerdict.kind === "error") {
3830
+ logSubagentIssue({ kind: "spawn_rejected", requestedType: subagentType, reason: scopeVerdict.message });
3831
+ return textResult(scopeVerdict.message);
3832
+ }
3833
+ if (!params.resume && scopeVerdict.kind === "warn") ctx.ui.notify(scopeVerdict.message, "warning");
1944
3834
  }
1945
- if (!params.resume && scopeVerdict.kind === "warn") ctx.ui.notify(scopeVerdict.message, "warning");
1946
3835
 
1947
3836
  const thinking = resolvedConfig.thinking;
1948
3837
  const inheritContext = resolvedConfig.inheritContext;
@@ -1967,7 +3856,8 @@ Terse command-style prompts produce shallow, generic work.
1967
3856
  // This is the pre-session snapshot — agent-manager overwrites it with the
1968
3857
  // effective values the moment a session reports them.
1969
3858
  const { modelName, modelId } = model ? describeModel(model) : { modelName: undefined, modelId: undefined };
1970
- const modelSource = resolvedConfig.modelInput === undefined ? "parent inheritance; unpinned"
3859
+ const modelSource = twinForced ? `forced to the main model (/subagents off)${resolvedConfig.modelInput !== undefined ? `; "${resolvedConfig.modelInput}" ignored` : ""}`
3860
+ : resolvedConfig.modelInput === undefined ? "parent inheritance; unpinned"
1971
3861
  : pinFallbackNotice !== undefined ? `agent pin "${resolvedConfig.modelInput}" unavailable; parent model substituted`
1972
3862
  : `${resolvedConfig.modelFromParams ? "caller" : "agent pin"}: "${resolvedConfig.modelInput}"`;
1973
3863
  const thinkingSource = customConfig?.thinking !== undefined ? `agent pin: "${customConfig.thinking}"`
@@ -2067,7 +3957,7 @@ Terse command-style prompts produce shallow, generic work.
2067
3957
  return textResult("Scheduler is not active in this session yet. Try again after the session has fully started.");
2068
3958
  }
2069
3959
  try {
2070
- const job = scheduler.addJob({
3960
+ const job = await scheduler.addJob({
2071
3961
  name: params.description as string,
2072
3962
  description: params.description as string,
2073
3963
  schedule: params.schedule as string,
@@ -2092,6 +3982,26 @@ Terse command-style prompts produce shallow, generic work.
2092
3982
  }
2093
3983
  }
2094
3984
 
3985
+ // Schedule definitions and settings are not cleanup artifacts. Every
3986
+ // path below can create a session/output/artifact, so guard it here.
3987
+ const agentRootSessionId = ctx.sessionManager.getSessionId();
3988
+ // Await this root's own binding admission — including the FIRST persistent
3989
+ // activation a supported SDK host reaches without session_start — and then
3990
+ // prove it is active before any session/output/worktree exists. An active
3991
+ // root returns without yielding (same-tick batch); an intentional
3992
+ // ephemeral context keeps its deferred-bind contract.
3993
+ const pendingAdmission = reportBindingAdmission(ctx);
3994
+ if (pendingAdmission !== undefined) await pendingAdmission;
3995
+ // Await the owning store's activation/root lock and any selected-path
3996
+ // lock through the async scan, then re-check this command's reservations
3997
+ // synchronously as the last step. Previously this was a synchronous full
3998
+ // scan; an SDK host that reaches this point through an await must not
3999
+ // block the main thread on every foreign root's lock metadata.
4000
+ await assertCleanupRootAccessAsync(agentRootSessionId);
4001
+ // Fail closed when the awaited bind threw or was refused: an absent store
4002
+ // makes the acquisition guard above a no-op, and that is not permission.
4003
+ assertReportBindingAdmission(ctx);
4004
+
2095
4005
  // Resume existing agent
2096
4006
  if (params.resume) {
2097
4007
  const existing = manager.getRecord(params.resume);
@@ -2102,11 +4012,13 @@ Terse command-style prompts produce shallow, generic work.
2102
4012
  return textResult(`Agent "${params.resume}" has no active session to resume.`);
2103
4013
  }
2104
4014
 
2105
- // Background resume: detached run that notifies on completion, mirroring
2106
- // a background spawn. Previously run_in_background was silently ignored
2107
- // on resume (this branch returned before the background branch below),
2108
- // so a resumed agent always blocked the main loop until it finished.
2109
- if (runInBackground) {
4015
+ // A resume that hands control back: either an explicit background
4016
+ // call, or an interactive foreground request, which is a logical await
4017
+ // in the TUI. Previously run_in_background was silently ignored on
4018
+ // resume (this branch returned before the background branch below), so
4019
+ // a resumed agent always blocked the main loop until it finished.
4020
+ const detachedResume = runInBackground || ctx.mode === "tui";
4021
+ if (detachedResume) {
2110
4022
  const id = existing.id;
2111
4023
  // A detached resume hands control back while the record stays
2112
4024
  // "running", so nothing stops the model from resuming the same agent
@@ -2129,19 +4041,42 @@ Terse command-style prompts produce shallow, generic work.
2129
4041
  return textResult(`Failed to resume agent "${params.resume}".`);
2130
4042
  }
2131
4043
 
2132
- const isQueued = record.status === "queued";
2133
- return textResult(
2134
- `Agent ${isQueued ? "queued" : "resumed"} in background.\n` +
2135
- `Agent ID: ${id}\n` +
2136
- `Type: ${existing.type}\n` +
2137
- (record.outputFile ? `Output file: ${record.outputFile}\n` : "") +
2138
- (isQueued ? `Position: queued (max ${manager.getMaxConcurrent()} concurrent)\n` : "") +
2139
- `\nYou will be notified when this agent completes.\n` +
2140
- `Use get_subagent_result to retrieve full results, or steer_subagent to send it messages.`,
2141
- { ...detailBaseFor(record), toolUses: record.toolUses, tokens: "", durationMs: 0, status: "background" as const, agentId: id },
2142
- );
4044
+ const isQueued = manager.isQueued(id);
4045
+ const details = { ...detailBaseFor(record), toolUses: record.toolUses, tokens: "", durationMs: 0, status: "background" as const, agentId: id };
4046
+ if (runInBackground) {
4047
+ return textResult(
4048
+ `Agent ${isQueued ? "queued" : "resumed"} in background.\n` +
4049
+ `Agent ID: ${id}\n` +
4050
+ `Type: ${existing.type}\n` +
4051
+ (record.outputFile ? `Output file: ${record.outputFile}\n` : "") +
4052
+ (isQueued ? `Position: queued (max ${manager.getMaxConcurrent()} concurrent)\n` : "") +
4053
+ `\nYou will be notified when this agent completes, and that notification carries its complete final report.\n` +
4054
+ `Do not poll for it and do not fabricate its result. Use get_subagent_result only to check status, steer_subagent to send it messages, or stop_subagent to stop it.`,
4055
+ details,
4056
+ );
4057
+ }
4058
+
4059
+ // Interactive foreground resume: startBackgroundResume already passes
4060
+ // `isBackground: true` to the manager, so this returns at once — never
4061
+ // a child promise. Same pending contract as a foreground spawn.
4062
+ return {
4063
+ ...textResult(
4064
+ `PENDING — Agent ${isQueued ? "queued" : "resumed"} as a background-managed logical await.\n` +
4065
+ `Agent ID: ${id}\n` +
4066
+ `Type: ${existing.type}\n` +
4067
+ (record.outputFile ? `Output file: ${record.outputFile}\n` : "") +
4068
+ (isQueued ? `Position: queued (max ${manager.getMaxConcurrent()} concurrent)\n` : "") +
4069
+ `\nThere is no result yet. The main turn is released and the agent continues in background; ` +
4070
+ `its complete final report will arrive automatically in a later turn — do not poll or wait for it, ` +
4071
+ `and do not fabricate its result.\n` +
4072
+ `Other tools in this batch may carry on without this agent's result — it is not complete yet.`,
4073
+ details,
4074
+ ),
4075
+ terminate: true,
4076
+ };
2143
4077
  }
2144
4078
 
4079
+ await assertCleanupArtifactAccessAsync(existing);
2145
4080
  const record = await manager.resume(params.resume, params.prompt, signal);
2146
4081
  if (!record) {
2147
4082
  return textResult(`Failed to resume agent "${params.resume}".`);
@@ -2157,8 +4092,21 @@ Terse command-style prompts produce shallow, generic work.
2157
4092
  );
2158
4093
  }
2159
4094
 
2160
- // Background execution
2161
- if (runInBackground) {
4095
+ // ---- Detached spawn (background call or interactive logical await) ----
4096
+ /**
4097
+ * Spawn this call's agent as a detached, manager-owned run — background
4098
+ * pool slot, no parent-abort wiring, completion notification on settle —
4099
+ * and return as soon as it is registered.
4100
+ *
4101
+ * `startupDeferred` is the interactive half of the contract. A worktree
4102
+ * copy is an awaited git call that can take seconds, and an interactive
4103
+ * call must never hold its receipt open for it, so a TUI call returns
4104
+ * first and observes startup failure through the ordinary completion
4105
+ * channel instead of a throw. Every other path keeps the inline strict
4106
+ * startup error (#179): a returned message would read as a subagent that
4107
+ * ran.
4108
+ */
4109
+ const spawnDetached = async (startupDeferred: boolean) => {
2162
4110
  const { state: bgState, callbacks: bgCallbacks } = createActivityTracker(effectiveMaxTurns);
2163
4111
 
2164
4112
  // Wrap onSessionCreated to wire output file streaming.
@@ -2188,7 +4136,8 @@ Terse command-style prompts produce shallow, generic work.
2188
4136
  isBackground: true,
2189
4137
  isolation,
2190
4138
  invocation: agentInvocation,
2191
- rootSessionId: ctx.sessionManager.getSessionId(),
4139
+ ...(admittedDefinition === undefined ? {} : { agentDefinition: admittedDefinition }),
4140
+ rootSessionId: agentRootSessionId,
2192
4141
  ...bgCallbacks,
2193
4142
  });
2194
4143
 
@@ -2202,11 +4151,16 @@ Terse command-style prompts produce shallow, generic work.
2202
4151
  attachTranscript(record, id);
2203
4152
  }
2204
4153
 
2205
- // With isolation: "worktree" the agent isn't running yet — the repo
2206
- // copy is an awaited git call. Wait for it here, after the synchronous
2207
- // wiring above, so a strict-isolation failure still fails THIS tool
2208
- // call instead of being reported as a subagent that ran (#179).
2209
- await manager.awaitStartup(id);
4154
+ if (!startupDeferred) {
4155
+ // Headless callers receive this error inline, not as another wakeup.
4156
+ try {
4157
+ await manager.awaitStartup(id);
4158
+ } catch (error) {
4159
+ if (record) record.resultConsumed = true;
4160
+ cancelNudge(id);
4161
+ throw error;
4162
+ }
4163
+ }
2210
4164
 
2211
4165
  if (joinMode == null || joinMode === 'async') {
2212
4166
  // Foreground/no join mode or explicit async — not part of any batch
@@ -2222,8 +4176,6 @@ Terse command-style prompts produce shallow, generic work.
2222
4176
  agentActivity.set(id, bgState);
2223
4177
  widget.ensureTimer();
2224
4178
  widget.update();
2225
- fleet.ensureTimer();
2226
- fleet.update();
2227
4179
 
2228
4180
  // Emit created event
2229
4181
  pi.events.emit("subagents:created", {
@@ -2233,7 +4185,16 @@ Terse command-style prompts produce shallow, generic work.
2233
4185
  isBackground: true,
2234
4186
  });
2235
4187
 
2236
- const isQueued = record?.status === "queued";
4188
+ return { id, record };
4189
+ };
4190
+
4191
+ // Background execution
4192
+ if (runInBackground) {
4193
+ // Interactive callers get their receipt before a worktree copy finishes;
4194
+ // headless/print and nested-free programmatic runs keep inline startup
4195
+ // errors because they are not holding a human's turn.
4196
+ const { id, record } = await spawnDetached(ctx.mode === "tui");
4197
+ const isQueued = manager.isQueued(id);
2237
4198
  return textResult(
2238
4199
  `${fallbackNote}Agent ${isQueued ? "queued" : "started"} in background.\n` +
2239
4200
  `Agent ID: ${id}\n` +
@@ -2242,13 +4203,45 @@ Terse command-style prompts produce shallow, generic work.
2242
4203
  (record ? selectionNoteFor(record) : "") +
2243
4204
  (record?.outputFile ? `Output file: ${record.outputFile}\n` : "") +
2244
4205
  (isQueued ? `Position: queued (max ${manager.getMaxConcurrent()} concurrent)\n` : "") +
2245
- `\nYou will be notified when this agent completes.\n` +
2246
- `Use get_subagent_result to retrieve full results, or steer_subagent to send it messages.\n` +
4206
+ `\nYou will be notified when this agent completes, and that notification carries its complete final report.\n` +
4207
+ `Do not poll for it and do not fabricate its result. Use get_subagent_result only to check status, steer_subagent to send it messages, or stop_subagent to stop it.\n` +
2247
4208
  `Do not duplicate this agent's work.`,
2248
4209
  { ...detailBaseFor(record), toolUses: 0, tokens: "", durationMs: 0, status: "background" as const, agentId: id },
2249
4210
  );
2250
4211
  }
2251
4212
 
4213
+ // Interactive foreground: a LOGICAL await, not a blocking call.
4214
+ //
4215
+ // The caller asked for a dependency, so it gets one — but in the TUI the
4216
+ // main turn must not sit on a child promise. The agent is background-
4217
+ // managed (pool slot, no parent-abort wiring), the receipt says PENDING,
4218
+ // and `terminate` releases the turn. `terminate` is honored only when
4219
+ // EVERY result in the batch asks for it, so a sibling tool that still
4220
+ // needs its own continuation keeps the turn alive — it must simply treat
4221
+ // this dependency as unfinished. Headless/RPC/print and nested callers
4222
+ // keep the historical inline contract below.
4223
+ if (ctx.mode === "tui") {
4224
+ const { id, record } = await spawnDetached(true);
4225
+ const isQueued = manager.isQueued(id);
4226
+ return {
4227
+ ...textResult(
4228
+ `${fallbackNote}PENDING — Agent ${isQueued ? "queued" : "started"} as a background-managed logical await.\n` +
4229
+ `Agent ID: ${id}\n` +
4230
+ `Type: ${displayName}\n` +
4231
+ `Description: ${params.description}\n` +
4232
+ (record ? selectionNoteFor(record) : "") +
4233
+ (record?.outputFile ? `Output file: ${record.outputFile}\n` : "") +
4234
+ (isQueued ? `Position: queued (max ${manager.getMaxConcurrent()} concurrent)\n` : "") +
4235
+ `\nThere is no result yet. The main turn is released and the agent continues in background; ` +
4236
+ `its complete final report will arrive automatically in a later turn — do not poll or wait for it, ` +
4237
+ `and do not fabricate its result.\n` +
4238
+ `Other tools in this batch may carry on without this agent's result — it is not complete yet.`,
4239
+ { ...detailBaseFor(record), toolUses: 0, tokens: "", durationMs: 0, status: "background" as const, agentId: id },
4240
+ ),
4241
+ terminate: true,
4242
+ };
4243
+ }
4244
+
2252
4245
  // Foreground (synchronous) execution — stream progress via onUpdate
2253
4246
  let spinnerFrame = 0;
2254
4247
  const startedAt = Date.now();
@@ -2308,8 +4301,6 @@ Terse command-style prompts produce shallow, generic work.
2308
4301
  fgId = a.id;
2309
4302
  agentActivity.set(a.id, fgState);
2310
4303
  widget.ensureTimer();
2311
- fleet.ensureTimer();
2312
- fleet.update();
2313
4304
  break;
2314
4305
  }
2315
4306
  }
@@ -2344,8 +4335,9 @@ Terse command-style prompts produce shallow, generic work.
2344
4335
  thinkingLevel: thinking,
2345
4336
  isolation,
2346
4337
  invocation: agentInvocation,
4338
+ ...(admittedDefinition === undefined ? {} : { agentDefinition: admittedDefinition }),
2347
4339
  signal,
2348
- rootSessionId: ctx.sessionManager.getSessionId(),
4340
+ rootSessionId: agentRootSessionId,
2349
4341
  // Deliberately does NOT set fgId: that drives agentActivity, the
2350
4342
  // widget and the `finally` cleanup below, none of which should see an
2351
4343
  // agent that has no session and may never get one.
@@ -2366,7 +4358,6 @@ Terse command-style prompts produce shallow, generic work.
2366
4358
  if (fgId) {
2367
4359
  agentActivity.delete(fgId);
2368
4360
  widget.markFinished(fgId);
2369
- fleet.onAgentFinished(fgId);
2370
4361
  }
2371
4362
  }
2372
4363
 
@@ -2438,19 +4429,150 @@ Terse command-style prompts produce shallow, generic work.
2438
4429
  * background run.
2439
4430
  */
2440
4431
  const workflowTasks = new Map<string, WorkflowTask>();
4432
+ /**
4433
+ * The ACTUAL detached run, by task id, and the runtime's accepted-journal
4434
+ * drain. Both are registered synchronously before a launcher returns: the
4435
+ * tool and the CLI flag hand control back while the run keeps writing, so
4436
+ * aborting its task is not proof that either has finished. Shutdown awaits
4437
+ * both; see {@link awaitWorkflowQuiescence}.
4438
+ *
4439
+ * Deliberately independent of `workflowTasks`: cleanup may forget a deleted
4440
+ * run's pointers, but it cannot disprove that the run is still live, and
4441
+ * dropping its handle would make shutdown return with accepted writes still
4442
+ * in flight. It is cleared by the run settling, not by pointer forgetting.
4443
+ */
4444
+ const workflowRunPromises = new Map<string, Promise<void>>();
4445
+ const workflowJournalDrains = new Map<string, () => Promise<void>>();
4446
+
4447
+ /**
4448
+ * Launch a detached workflow run and remember the work it owns.
4449
+ *
4450
+ * `runWorkflowTask` starts the runtime synchronously up to its first await,
4451
+ * so `onJournalDrain` has already registered by the time it returns. The
4452
+ * promise is stored in the same synchronous block, before this function
4453
+ * returns to the tool or the CLI flag.
4454
+ */
4455
+ function launchWorkflowRun(ctx: ExtensionContext, task: WorkflowTask, onSettled: () => void): void {
4456
+ const run = runWorkflowTask(ctx, task).then(onSettled);
4457
+ workflowRunPromises.set(task.id, run);
4458
+ const forget = () => {
4459
+ if (workflowRunPromises.get(task.id) === run) workflowRunPromises.delete(task.id);
4460
+ // Only now: `finish` drained the accepted writes before the run's own
4461
+ // promise resolved, so the handle cannot be needed again.
4462
+ if (!workflowRunPromises.has(task.id)) workflowJournalDrains.delete(task.id);
4463
+ };
4464
+ // Both arms: a throwing notification must not leave the handle behind (or
4465
+ // surface as an unhandled rejection). The run itself never rejects.
4466
+ void run.then(forget, forget);
4467
+ }
4468
+
4469
+ /** Last admission check after artifact persistence yields; no worker exists yet. */
4470
+ function workflowLaunchRefusal(ctx: ExtensionContext, epoch: number, rootSessionId: string | undefined): string | undefined {
4471
+ if (shuttingDown) return "the session is shutting down";
4472
+ if (sessionEpoch !== epoch || ctx.sessionManager.getSessionId() !== rootSessionId) {
4473
+ return "the session changed while workflow artifacts were persisted";
4474
+ }
4475
+ try {
4476
+ assertCleanupRootAccess(rootSessionId);
4477
+ } catch (error) {
4478
+ return error instanceof Error ? error.message : String(error);
4479
+ }
4480
+ return undefined;
4481
+ }
4482
+
4483
+ /**
4484
+ * Wait for every detached workflow producer and its accepted journal tail.
4485
+ *
4486
+ * Called after the producers are aborted. Re-reads the handles on every pass
4487
+ * because a launch already in flight can register while the first snapshot is
4488
+ * being awaited; returning on that snapshot would leave that run's accepted
4489
+ * records unwritten. A run promise settles only after the runtime drained its
4490
+ * accepted queue and terminated its worker, and `runWorkflowTask` settles its
4491
+ * final artifact registration before resolving.
4492
+ */
4493
+ async function awaitWorkflowQuiescence(): Promise<void> {
4494
+ for (;;) {
4495
+ const drains = [...workflowJournalDrains.values()];
4496
+ const runs = [...workflowRunPromises.values()];
4497
+ if (drains.length === 0 && runs.length === 0) return;
4498
+ await Promise.allSettled([...drains.map(drain => drain()), ...runs]);
4499
+ }
4500
+ }
2441
4501
 
2442
4502
  /**
2443
- * Workflow runs as the fleet list wants them.
4503
+ * Deliver the held completion of a workflow that settled during shutdown.
2444
4504
  *
2445
- * Mapped here rather than handing `WorkflowTask` over the seam: the list is
2446
- * deliberately ignorant of the workflow engine, and a run's counters live in
2447
- * the progress log rather than on the record, so they are derived per call
2448
- * the same way the card derives them.
4505
+ * Called after the run promises and journal tails are awaited, so the notice
4506
+ * already exists in `pendingNudges` and no timer can be left to fire after
4507
+ * the handler returns. Agent notices are not touched: only keys that belong
4508
+ * to a workflow run are delivered here, and an explicitly discarded run is
4509
+ * dropped instead. A throw is swallowed like every other shutdown-time send.
4510
+ */
4511
+ function flushStoppedWorkflowNudges(): void {
4512
+ for (const [key, entry] of [...pendingNudges]) {
4513
+ if (!workflowTasks.has(key) && !workflowRunPromises.has(key) && !workflowJournalDrains.has(key)) continue;
4514
+ if (discardedWorkflowNotifications.has(key)) {
4515
+ cancelNudge(key);
4516
+ continue;
4517
+ }
4518
+ pendingNudges.delete(key);
4519
+ clearTimeout(entry.timer);
4520
+ try {
4521
+ entry.send();
4522
+ } catch {
4523
+ // A delivery during shutdown must not fail the shutdown itself.
4524
+ }
4525
+ }
4526
+ }
4527
+
4528
+ interface WorkflowArtifactPaths {
4529
+ /** Exact generated inline copy/journal written by this extension. */
4530
+ generatedPaths: string[];
4531
+ /** Caller/saved source files; provenance only, never cleanup candidates. */
4532
+ externalPaths: string[];
4533
+ }
4534
+
4535
+ /**
4536
+ * Ownership for cleanup, independent of how many agents the run spawns.
4537
+ * Registration happens at creation and settlement even for a zero-agent
4538
+ * workflow, and the generated paths are the copies THIS run wrote — never a
4539
+ * saved/external source the caller supplied.
2449
4540
  */
4541
+ const workflowArtifactPaths = new Map<string, WorkflowArtifactPaths>();
4542
+ /** Root a run was created under; settlement must update THAT store. */
4543
+ const workflowArtifactRoots = new Map<string, string>();
4544
+ const knownGeneratedWorkflowPaths = new Set<string>();
4545
+
4546
+ function rememberWorkflowArtifacts(
4547
+ id: string,
4548
+ paths: WorkflowArtifactPaths,
4549
+ provenance: { rootSessionId: string | undefined; store: ReportStore },
4550
+ ): void {
4551
+ workflowArtifactPaths.set(id, paths);
4552
+ if (provenance.rootSessionId !== undefined) workflowArtifactRoots.set(id, provenance.rootSessionId);
4553
+ workflowArtifactStores.set(id, provenance.store);
4554
+ for (const path of paths.generatedPaths) knownGeneratedWorkflowPaths.add(resolve(path));
4555
+ }
4556
+
4557
+ async function persistWorkflowArtifactStatus(task: WorkflowTask): Promise<ReportSaveResult | undefined> {
4558
+ const paths = workflowArtifactPaths.get(task.id);
4559
+ if (!paths) return undefined;
4560
+ // Pinned at creation: an old run's settlement must never be retargeted to
4561
+ // whatever root happens to be current when its final write is ready.
4562
+ const target = workflowArtifactStores.get(task.id);
4563
+ if (target === undefined) return { saved: false, reason: "workflow-store-missing" };
4564
+ return target.registerWorkflow({
4565
+ id: task.id,
4566
+ generatedPaths: paths.generatedPaths,
4567
+ externalPaths: paths.externalPaths,
4568
+ status: task.status,
4569
+ startedAt: task.startTime,
4570
+ ...(task.endTime === undefined ? {} : { completedAt: task.endTime }),
4571
+ });
4572
+ }
4573
+
4574
+ /** Workflow rows for Agent Hub, using cached counters rather than walking the progress log on render. */
2450
4575
  function fleetWorkflows(): FleetWorkflow[] {
2451
- // Cached counters only, no derivation: the fleet list calls this on a
2452
- // 200ms tick and reads the roster several times per update, so walking a
2453
- // run's progress log here would put O(log) work in the render loop.
2454
4576
  return [...workflowTasks.values()].map(task => ({
2455
4577
  id: task.id,
2456
4578
  name: task.meta?.name ?? task.workflowName ?? task.id,
@@ -2474,6 +4596,8 @@ Terse command-style prompts produce shallow, generic work.
2474
4596
  const result = await runWorkflow({
2475
4597
  script: task.script,
2476
4598
  args: task.args,
4599
+ defaultAgentType: task.defaultAgentType,
4600
+ defaultAgentTypeExplicit: task.defaultAgentTypeExplicit,
2477
4601
  signal: task.abortController.signal,
2478
4602
  host: createWorkflowHost({
2479
4603
  pi,
@@ -2487,6 +4611,10 @@ Terse command-style prompts produce shallow, generic work.
2487
4611
  // The dialog's pause / skip / retry keys run through this; it is dropped
2488
4612
  // again when the task settles.
2489
4613
  onControl: control => { task.control = control; },
4614
+ // Registered by the runtime before its worker exists. The accepted
4615
+ // records behind a slow append are invisible to the journal module's
4616
+ // own per-path queue, so shutdown and a paused resume need this tail.
4617
+ onJournalDrain: drain => { workflowJournalDrains.set(task.id, drain); },
2490
4618
  journal: {
2491
4619
  ...(task.replay !== undefined ? { entries: task.replay } : {}),
2492
4620
  ...(task.journalPath !== undefined
@@ -2497,6 +4625,17 @@ Terse command-style prompts produce shallow, generic work.
2497
4625
  completeWorkflowTask(task, result);
2498
4626
  } catch (err) {
2499
4627
  failWorkflowTask(task, err instanceof Error ? err.message : String(err));
4628
+ } finally {
4629
+ // Settlement is registered before the result notification, so cleanup
4630
+ // sees a completed/failed run rather than a forever-running one. The
4631
+ // proof added before creation stays active through this final write.
4632
+ try {
4633
+ const persisted = await persistWorkflowArtifactStatus(task);
4634
+ settleWorkflowCleanupProof(task.id, persisted);
4635
+ } catch {
4636
+ const proof = workflowCleanupProofs.get(task.id);
4637
+ if (proof !== undefined) proof.persistenceUncertainty ??= "settlement-registration-threw";
4638
+ }
2500
4639
  }
2501
4640
  }
2502
4641
 
@@ -2507,9 +4646,10 @@ Terse command-style prompts produce shallow, generic work.
2507
4646
  */
2508
4647
  function notifyWorkflowFinished(task: WorkflowTask) {
2509
4648
  widget.update();
2510
- fleet.update();
4649
+ if (discardedWorkflowNotifications.has(task.id)) return;
2511
4650
  const result = workflowResultText(task);
2512
4651
  scheduleNudge(task.id, () => {
4652
+ if (discardedWorkflowNotifications.has(task.id)) return;
2513
4653
  pi.sendMessage<NotificationDetails>({
2514
4654
  customType: "subagent-notification",
2515
4655
  content: formatWorkflowNotification(task),
@@ -2541,6 +4681,7 @@ Terse command-style prompts produce shallow, generic work.
2541
4681
  promptGuidelines: [
2542
4682
  "Use SubagentWorkflow when the number of agents depends on something discovered at runtime, when work flows through stages, or when findings should be independently verified. Use Agent for one delegated task or a handful you can name up front.",
2543
4683
  "Prefer `pipeline` over `parallel` — a barrier costs wall-clock whenever the stages are unevenly sized.",
4684
+ "Before calling SubagentWorkflow with a scriptPath that depends on a file you just wrote or edited, wait for that Edit/Write call to complete. Never launch the edit and the workflow in the same parallel tool batch — the run can otherwise read the old file.",
2544
4685
  "A workflow runs in the background and notifies you when it finishes — do not poll or sleep waiting for it.",
2545
4686
  ],
2546
4687
  parameters: Type.Object({
@@ -2564,7 +4705,15 @@ Terse command-style prompts produce shallow, generic work.
2564
4705
  ),
2565
4706
  args: Type.Optional(
2566
4707
  Type.Any({
2567
- description: "Exposed to the script as the global `args`, verbatim. Must be JSON-shaped.",
4708
+ description:
4709
+ "Exposed to the script as the global `args`, verbatim. Pass the actual object or array — not a JSON-encoded string, which would reach the script as a string rather than the structure it describes.",
4710
+ }),
4711
+ ),
4712
+ agentType: Type.Optional(
4713
+ Type.String({
4714
+ minLength: 1,
4715
+ description:
4716
+ 'Default agent type for this run\'s agent() calls that do not name one. Outranks the project\'s workflow default (the "task" role unless configured); a script\'s per-call opts.agentType still outranks this. Resolved from the same registry as the Agent tool.',
2568
4717
  }),
2569
4718
  ),
2570
4719
  resumeFromRunId: Type.Optional(
@@ -2620,6 +4769,14 @@ Terse command-style prompts produce shallow, generic work.
2620
4769
  },
2621
4770
 
2622
4771
  execute: async (toolCallId, params, _signal, _onUpdate, ctx) => {
4772
+ // Captured before the first await: a session switch or shutdown during a
4773
+ // resumed run's journal wait must be recognisable as a change that
4774
+ // happened AFTER this call was admitted, so no new run is published into
4775
+ // a session that has already moved on.
4776
+ if (shuttingDown) return textResult("Workflow not started: the session is shutting down.");
4777
+ const admitEpoch = sessionEpoch;
4778
+ const requestedAgentType = params.agentType?.trim();
4779
+ if (requestedAgentType === "") return textResult("agentType must be a non-empty agent name.");
2623
4780
  const resumeFrom = resolveResumeTarget(params.resumeFromRunId, workflowTasks);
2624
4781
  if (resumeFrom !== undefined && !resumeFrom.ok) return textResult(resumeFrom.message);
2625
4782
 
@@ -2635,6 +4792,18 @@ Terse command-style prompts produce shallow, generic work.
2635
4792
  );
2636
4793
  if (!resolved.ok) return textResult(resolved.message);
2637
4794
 
4795
+ // Registering generated artifacts requires a bound root; a workflow with
4796
+ // zero agents still owns the script copy and journal it writes below.
4797
+ // Refuse a cleanup-reserved root before binding publishes a lease or runs
4798
+ // maintenance, not only before the generated copy is written.
4799
+ const workflowRootSessionId = ctx.sessionManager.getSessionId();
4800
+ try {
4801
+ assertCleanupRootAccess(workflowRootSessionId);
4802
+ } catch (error) {
4803
+ return textResult(`Workflow not started: ${error instanceof Error ? error.message : String(error)}.`);
4804
+ }
4805
+ await ensureReportBinding(ctx);
4806
+
2638
4807
  // Parsed before anything is scheduled: a bad `meta` is an authoring error
2639
4808
  // the model can fix immediately, and reporting it as a background run
2640
4809
  // that failed a second later would just cost a turn.
@@ -2646,10 +4815,67 @@ Terse command-style prompts produce shallow, generic work.
2646
4815
  }
2647
4816
 
2648
4817
  const runId = workflowRunId();
4818
+ // Pin root/store before any await or copy. The proof starts before the
4819
+ // generated script copy exists and remains through final registration, so
4820
+ // a zero-agent run is never mistaken for an idle namespace.
4821
+ const workflowStore = (workflowRootSessionId === undefined ? undefined : reportStores.get(workflowRootSessionId)) ?? reportStore;
4822
+ try {
4823
+ assertCleanupRootAccess(workflowRootSessionId);
4824
+ } catch (error) {
4825
+ return textResult(`Workflow not started: ${error instanceof Error ? error.message : String(error)}.`);
4826
+ }
4827
+
4828
+ // A paused run may still have ACCEPTED journal records behind a slow
4829
+ // append: the runtime serializes them in its own chain, which the journal
4830
+ // module's per-path queue only sees one record at a time. Reading before
4831
+ // that tail settles replays a prefix missing calls the earlier run already
4832
+ // completed, so the resume pays for them again. Wait for the prior run's
4833
+ // accepted queue BEFORE `readJournal`; do not reject paused resumes — the
4834
+ // wait is the fix.
4835
+ if (resumeFrom !== undefined) {
4836
+ const priorDrain = workflowJournalDrains.get(resumeFrom.runId);
4837
+ if (priorDrain !== undefined) await priorDrain();
4838
+ }
4839
+ const replay = resumeFrom !== undefined ? await readJournal(resumeFrom.journalPath) : undefined;
4840
+
4841
+ // Everything the two waits above protected is re-proved here, in one
4842
+ // synchronous continuation and BEFORE any artifact is written or a new
4843
+ // run is published: the entering session and its epoch (a switch or
4844
+ // shutdown), the root's cleanup reservation, and the resume selection
4845
+ // itself (cleanup can forget the prior run, and the record can move to a
4846
+ // different state while this read was suspended).
4847
+ if (sessionEpoch !== admitEpoch || ctx.sessionManager.getSessionId() !== workflowRootSessionId) {
4848
+ return textResult(
4849
+ "Workflow not started: the session changed while the previous run's journal was still being written.",
4850
+ );
4851
+ }
4852
+ try {
4853
+ assertCleanupRootAccess(workflowRootSessionId);
4854
+ } catch (error) {
4855
+ return textResult(`Workflow not started: ${error instanceof Error ? error.message : String(error)}.`);
4856
+ }
4857
+ if (resumeFrom !== undefined) {
4858
+ const still = resolveResumeTarget(params.resumeFromRunId, workflowTasks);
4859
+ if (still === undefined || !still.ok) {
4860
+ return textResult(
4861
+ still === undefined
4862
+ ? `Workflow not started: resume source "${resumeFrom.runId}" is no longer selected.`
4863
+ : still.message,
4864
+ );
4865
+ }
4866
+ if (still.journalPath !== resumeFrom.journalPath) {
4867
+ return textResult(
4868
+ `Workflow not started: the journal for "${resumeFrom.runId}" changed while it was being read.`,
4869
+ );
4870
+ }
4871
+ }
4872
+
4873
+ beginWorkflowCleanupProof(runId, workflowRootSessionId);
2649
4874
  // Every invocation lands on disk next to the agent transcripts, so
2650
4875
  // iterating is edit-the-file-then-rerun-with-scriptPath rather than
2651
4876
  // re-emitting the whole source. The journal sits beside it under the same
2652
- // id, which is what makes a run id enough to resume from.
4877
+ // id, which is what makes a run id enough to resume from. Written only
4878
+ // after the waits above, so a stale read cannot leave artifacts behind.
2653
4879
  let savedPath: string | undefined;
2654
4880
  let journalPath: string | undefined;
2655
4881
  try {
@@ -2663,29 +4889,65 @@ Terse command-style prompts produce shallow, generic work.
2663
4889
  console.warn(`[pi-subagents] could not persist workflow script: ${err instanceof Error ? err.message : String(err)}`);
2664
4890
  }
2665
4891
 
2666
- const replay = resumeFrom !== undefined ? readJournal(resumeFrom.journalPath) : undefined;
4892
+ // A resume re-runs what the earlier run ran, args and default role
4893
+ // included. Only a property the caller actually supplied replaces them:
4894
+ // `Object.hasOwn` rather than `??`, so an explicit `args: null` wins while
4895
+ // an omitted `args` keeps the original (and a new run stays `undefined`,
4896
+ // which scripts already branch on).
4897
+ const args = resumeFrom !== undefined && !Object.hasOwn(params, "args") ? resumeFrom.args : params.args;
4898
+ // Per-run call > the resumed run's frozen choice > the project setting.
4899
+ // A script's `opts.agentType` is applied by the runtime and outranks all.
4900
+ const defaultAgentType =
4901
+ requestedAgentType ?? resumeFrom?.defaultAgentType ?? workflowDefaultAgentType;
4902
+ // Whether something the caller can see named that default: this call's
4903
+ // `agentType`, or the run being resumed. A role reached only through the
4904
+ // project setting is not explicit, which is what keeps an unpinned default
4905
+ // from silently running the parent model (see workflow/host.ts).
4906
+ const defaultAgentTypeExplicit =
4907
+ requestedAgentType !== undefined || (resumeFrom?.defaultAgentTypeExplicit ?? false);
2667
4908
 
2668
4909
  const task = createWorkflowTask({
2669
4910
  id: runId,
2670
4911
  script: resolved.script,
2671
4912
  scriptPath: resolved.scriptPath ?? savedPath,
2672
- args: params.args,
4913
+ args,
4914
+ defaultAgentType,
4915
+ defaultAgentTypeExplicit,
2673
4916
  meta,
2674
4917
  toolCallId,
2675
4918
  ...(journalPath !== undefined ? { journalPath } : {}),
2676
4919
  ...(replay !== undefined && replay.length > 0 ? { replay, resumedFrom: resumeFrom!.runId } : {}),
2677
4920
  });
4921
+ const generatedPaths = [savedPath, journalPath].filter((path): path is string => path !== undefined);
4922
+ const externalPaths: string[] = [];
4923
+ if (resolved.scriptPath !== undefined) {
4924
+ const source = resolve(resolved.scriptPath);
4925
+ // A resume may re-run a previous run's generated copy. That copy IS
4926
+ // ours; marking it external would protect it from cleanup forever.
4927
+ if (!knownGeneratedWorkflowPaths.has(source)) externalPaths.push(source);
4928
+ }
4929
+ rememberWorkflowArtifacts(runId, { generatedPaths, externalPaths }, {
4930
+ rootSessionId: workflowRootSessionId,
4931
+ store: workflowStore,
4932
+ });
4933
+ updateWorkflowCleanupProof(runId, generatedPaths, externalPaths);
4934
+ const initialPersistence = await persistWorkflowArtifactStatus(task);
4935
+ recordWorkflowPersistenceResult(runId, initialPersistence);
4936
+ // Persistence yields after the earlier session check. This launch may
4937
+ // have missed shutdown's abort sweep; never publish an un-aborted worker.
4938
+ const launchRefusal = workflowLaunchRefusal(ctx, admitEpoch, workflowRootSessionId);
4939
+ if (launchRefusal !== undefined) {
4940
+ task.abortController.abort();
4941
+ settleWorkflowCleanupProof(runId, initialPersistence);
4942
+ return textResult(`Workflow not started: ${launchRefusal}.`);
4943
+ }
2678
4944
  workflowTasks.set(runId, task);
2679
- // The run's own row has to appear now, not when it settles. Its agents
2680
- // are owned by it, so their lifecycle callbacks no longer refresh these
2681
- // surfaces — nothing else would register the widget for a run whose
2682
- // first agent has not started yet.
2683
4945
  widget.update();
2684
- fleet.update();
2685
4946
 
2686
4947
  // Background, like Claude Code: the id comes back now and the run keeps
2687
- // going without the tool call.
2688
- void runWorkflowTask(ctx, task).then(() => notifyWorkflowFinished(task));
4948
+ // going without the tool call. The promise and journal drain are tracked
4949
+ // here, before this returns, so shutdown can await them.
4950
+ launchWorkflowRun(ctx, task, () => notifyWorkflowFinished(task));
2689
4951
 
2690
4952
  return {
2691
4953
  content: [{
@@ -2693,6 +4955,7 @@ Terse command-style prompts produce shallow, generic work.
2693
4955
  text:
2694
4956
  `Workflow "${meta.name}" started in the background.\n` +
2695
4957
  `Task ID: ${runId}\n` +
4958
+ `Default agent role: ${task.defaultAgentType}\n` +
2696
4959
  (task.scriptPath ? `Script: ${task.scriptPath}\n` : "") +
2697
4960
  (task.resumedFrom !== undefined
2698
4961
  ? `Resuming ${task.resumedFrom}: ${task.replay?.length ?? 0} recorded call(s) available to replay.\n`
@@ -2760,7 +5023,6 @@ Terse command-style prompts produce shallow, generic work.
2760
5023
 
2761
5024
  workflowsEnabled = false; // not setWorkflowsEnabled: this is not the user pinning it
2762
5025
  widget.update();
2763
- fleet.update();
2764
5026
  warn(verdict.message);
2765
5027
 
2766
5028
  if (!verdict.withdraw) return;
@@ -2785,8 +5047,9 @@ Terse command-style prompts produce shallow, generic work.
2785
5047
  * session_start for exactly this reason.
2786
5048
  */
2787
5049
  let workflowFlagHandled = false;
2788
- function runWorkflowFlag(ctx: ExtensionContext): void {
5050
+ async function runWorkflowFlag(ctx: ExtensionContext): Promise<void> {
2789
5051
  if (workflowFlagHandled) return;
5052
+ const admitEpoch = sessionEpoch;
2790
5053
  const flag = pi.getFlag(WORKFLOW_FILE_FLAG);
2791
5054
  if (flag === undefined || flag === false) return;
2792
5055
  workflowFlagHandled = true;
@@ -2832,15 +5095,45 @@ Terse command-style prompts produce shallow, generic work.
2832
5095
  return;
2833
5096
  }
2834
5097
 
2835
- const task = createWorkflowTask({ id: workflowRunId(), script, scriptPath: path, meta });
5098
+ const workflowRootSessionId = ctx.sessionManager.getSessionId();
5099
+ const workflowStore = (workflowRootSessionId === undefined ? undefined : reportStores.get(workflowRootSessionId)) ?? reportStore;
5100
+ const initialRefusal = workflowLaunchRefusal(ctx, admitEpoch, workflowRootSessionId);
5101
+ if (initialRefusal !== undefined) {
5102
+ report(`Workflow not started: ${initialRefusal}.`, "warning");
5103
+ return;
5104
+ }
5105
+ const task = createWorkflowTask({
5106
+ id: workflowRunId(),
5107
+ script,
5108
+ scriptPath: path,
5109
+ meta,
5110
+ defaultAgentType: getWorkflowDefaultAgentType(),
5111
+ });
5112
+ beginWorkflowCleanupProof(task.id, workflowRootSessionId);
5113
+ // A CLI script is user-authored: provenance only, never an owned artifact.
5114
+ rememberWorkflowArtifacts(task.id, { generatedPaths: [], externalPaths: [resolve(path)] }, {
5115
+ rootSessionId: workflowRootSessionId,
5116
+ store: workflowStore,
5117
+ });
5118
+ updateWorkflowCleanupProof(task.id, [], [resolve(path)]);
5119
+ const initialPersistence = await persistWorkflowArtifactStatus(task);
5120
+ recordWorkflowPersistenceResult(task.id, initialPersistence);
5121
+ const launchRefusal = workflowLaunchRefusal(ctx, admitEpoch, workflowRootSessionId);
5122
+ if (launchRefusal !== undefined) {
5123
+ task.abortController.abort();
5124
+ settleWorkflowCleanupProof(task.id, initialPersistence);
5125
+ report(`Workflow not started: ${launchRefusal}.`, "warning");
5126
+ return;
5127
+ }
2836
5128
  workflowTasks.set(task.id, task);
2837
5129
  widget.update();
2838
- fleet.update();
2839
5130
  report(`Running workflow ${meta.name}…`, "info");
2840
5131
 
2841
5132
  // Detached: session_start is awaited by the host, and a workflow can run for
2842
- // minutes — blocking here would hold the whole session's startup.
2843
- void runWorkflowTask(ctx, task).then(() => {
5133
+ // minutes — blocking here would hold the whole session's startup. Tracked
5134
+ // before this returns, so shutdown awaits the real run and its journal.
5135
+ launchWorkflowRun(ctx, task, () => {
5136
+ if (discardedWorkflowNotifications.has(task.id)) return;
2844
5137
  // No tool call to attach a result card to, so the card becomes a session
2845
5138
  // entry (same layout), and the outcome is handed to the model as context
2846
5139
  // for its next turn rather than forcing one.
@@ -2851,38 +5144,221 @@ Terse command-style prompts produce shallow, generic work.
2851
5144
  display: false,
2852
5145
  }, { deliverAs: "nextTurn" });
2853
5146
  widget.update();
2854
- fleet.update();
2855
5147
  });
2856
5148
  }
2857
5149
 
2858
5150
  // ---- get_subagent_result tool ----
2859
5151
 
5152
+ /**
5153
+ * Archived twin of the live result body. Provenance, complete report and an
5154
+ * honest expired/deleted/unknown message; never a notification, never stored
5155
+ * usage billed, and never a fabricated stat for a legacy record.
5156
+ */
5157
+ async function formatArchivedResult(target: ReportStore, lookup: ReportLookup, verbose: boolean): Promise<string> {
5158
+ let conversation: string | undefined;
5159
+ if (verbose && lookup.status === "found") {
5160
+ conversation = await target.readConversation(lookup.report);
5161
+ }
5162
+ return formatArchivedReportLookup(lookup, {
5163
+ showCost,
5164
+ ...(conversation === undefined ? {} : { conversation }),
5165
+ });
5166
+ }
5167
+
2860
5168
  registerToolReportingUsage(defineTool({
2861
5169
  name: SUBAGENT_TOOL_NAMES.GET_RESULT,
2862
5170
  label: "Get Agent Result",
2863
5171
  description:
2864
- "Check status and retrieve a background agent's full result — its completion notification carries only a preview. Use the agent ID returned by Agent.",
5172
+ "Check a background agent's status or read its result. A finished agent returns its complete final result immediately, and reading it suppresses its completion notification. In the terminal UI, waiting on a running agent releases the main turn instead of blocking: the agent keeps running, nothing has finished yet (treat the receipt as PENDING), and its completion notification later carries the complete final report — do not poll for it. Complete final reports also arrive automatically for agents nobody waited on. Completed reports remain retrievable for 30 days after runtime eviction or reload; exact IDs work across sessions/projects, while handles search the current root session only.",
2865
5173
  promptSnippet: "Check status and retrieve results from a background agent",
5174
+ promptGuidelines: [
5175
+ "get_subagent_result with wait: true on a running or queued agent returns at once in the terminal UI: the main turn is released, the agent keeps running, and its completion notification arrives as a later turn carrying the result. Treat that notice as \"pending\" — do not call again to poll, do not fabricate the result, and say the agent is still running if the user asks first.",
5176
+ "When all remaining work is delegated, make wait: true your last/sole tool action to release control without an extra model response. Mixed batches with nonterminating sibling tools continue normally.",
5177
+ "Outside the terminal UI — print mode and nested agents — wait: true blocks until the agent finishes and returns its result inline.",
5178
+ "For completed work evicted from memory or from an earlier session/project, use its exact agent ID. Retained reads return the complete report without another wakeup or rebilling stored usage; verbose opts into existing raw history.",
5179
+ ],
2866
5180
  parameters: Type.Object({
2867
5181
  agent_id: Type.String({
2868
- description: "The agent ID to check. The agent's handle also works — its `name` if you gave it one, otherwise its type (`explore`, `explore-2`).",
5182
+ description: "The live or retained agent ID to check. Exact IDs work across sessions/projects. The agent's handle also works within the current root session — its `name` if you gave it one, otherwise its type (`explore`, `explore-2`).",
2869
5183
  }),
2870
5184
  wait: Type.Optional(
2871
5185
  Type.Boolean({
2872
- description: "If true, wait for the agent to complete before returning. Default: false.",
5186
+ description: "If true, wait for the agent to complete. In the terminal UI a wait on a running agent releases the main turn instead and the completion notification delivers the result; elsewhere it blocks. Default: false.",
2873
5187
  }),
2874
5188
  ),
2875
5189
  verbose: Type.Optional(
2876
5190
  Type.Boolean({
2877
- description: "If true, include the agent's full conversation (messages + tool calls). Default: false.",
5191
+ description: "If true, include the agent's conversation (messages + tool calls). A released wait honors it in the completion notification as an opt-in transcript excerpt; if that excerpt is bounded, calling this again with verbose: true returns the full conversation. The final report itself is always complete. Default: false.",
2878
5192
  }),
2879
5193
  ),
2880
5194
  }),
2881
- execute: async (_toolCallId, params, signal, _onUpdate, _ctx) => {
2882
- const record = resolveAgentRef(params.agent_id);
2883
- if (!record || !isTopLevelAgent(record)) {
5195
+ execute: async (_toolCallId, params, signal, _onUpdate, ctx) => {
5196
+ let record = resolveAgentRef(params.agent_id);
5197
+ // A KNOWN owned live record is refused outright. It must not fall through
5198
+ // to the archive, where a same-id saved row from an earlier run could be
5199
+ // surfaced as if this session's parent could read it.
5200
+ if (record !== undefined && !isTopLevelAgent(record)) {
2884
5201
  return textResult(`Agent not found: "${params.agent_id}". It may have been cleaned up.`);
2885
5202
  }
5203
+ if (record !== undefined) {
5204
+ const refusal = cleanupReadRefusal({
5205
+ agentId: record.id,
5206
+ sessionFile: record.sessionFile,
5207
+ rootSessionId: record.rootSessionId,
5208
+ });
5209
+ if (refusal !== undefined) {
5210
+ return textResult(`Agent "${record.id}" is being cleaned up (${refusal}); its report and conversation are not readable right now.`);
5211
+ }
5212
+ }
5213
+
5214
+ if (record === undefined) {
5215
+ // Runtime eviction/reload miss: durable reports are the only source.
5216
+ // Bind lazily for harnesses that never emitted session_start, and give
5217
+ // the store the current parent's custom records so a pre-upgrade
5218
+ // completion can be recovered authoritatively (never from a raw tail).
5219
+ const root = ctx.sessionManager?.getSessionId?.();
5220
+ const parentEntries = ctx.sessionManager?.getBranch?.() ?? [];
5221
+ // Invalidation token for the entering root, taken BEFORE the lookup: the
5222
+ // whole read below is asynchronous, so a cleanup can begin — and finish —
5223
+ // while it is in flight.
5224
+ const enterToken = cleanupReadTokenFor(root);
5225
+ await ensureReportBinding(ctx);
5226
+ // Read-your-writes, pinned to the entering root/branch: the SDK can
5227
+ // switch its session manager while this filesystem operation yields.
5228
+ const target = (root === undefined ? undefined : reportStores.get(root)) ?? reportStore;
5229
+ const drained = await target.flush();
5230
+ if (drained.status !== "flushed") {
5231
+ return textResult(`Agent "${params.agent_id}" report is not readable yet: pending report writes did not flush (${drained.reason}).`);
5232
+ }
5233
+ const lookup = await target.find(params.agent_id, parentEntries);
5234
+ // The report's own root is what a cleanup would rewrite, and it need not
5235
+ // be the entering one: exact ids are answered across roots.
5236
+ const reportRoot = lookup.status === "found" ? lookup.report.rootSessionId : undefined;
5237
+ const lookupToken = cleanupReadTokenFor(reportRoot);
5238
+ const archivedRefusal = lookup.status === "found"
5239
+ ? cleanupReadRefusal({
5240
+ agentId: lookup.report.id,
5241
+ sessionFile: lookup.report.sessionFile,
5242
+ rootSessionId: lookup.report.rootSessionId,
5243
+ })
5244
+ : undefined;
5245
+ if (archivedRefusal !== undefined) {
5246
+ return textResult(`Agent "${params.agent_id}" is being cleaned up (${archivedRefusal}); its archived report is not readable right now.`);
5247
+ }
5248
+ // A resume can start while the archive read is in flight; live always
5249
+ // wins. Recheck again after an opt-in conversation read below.
5250
+ const relive = resolveAgentRef(params.agent_id);
5251
+ if (relive !== undefined) {
5252
+ if (!isTopLevelAgent(relive)) {
5253
+ return textResult(`Agent not found: "${params.agent_id}". It may have been cleaned up.`);
5254
+ }
5255
+ record = relive;
5256
+ } else {
5257
+ const archived = await formatArchivedResult(target, lookup, params.verbose === true);
5258
+ const postReadRefusal = lookup.status === "found"
5259
+ ? cleanupReadRefusal({
5260
+ agentId: lookup.report.id,
5261
+ sessionFile: lookup.report.sessionFile,
5262
+ rootSessionId: lookup.report.rootSessionId,
5263
+ })
5264
+ : undefined;
5265
+ if (postReadRefusal !== undefined) {
5266
+ return textResult(`Agent "${params.agent_id}" is being cleaned up (${postReadRefusal}); its archived report is not readable right now.`);
5267
+ }
5268
+ // The operation's absence proves nothing: a cleanup that ran entirely
5269
+ // inside this read has already released its barriers. Either edge of
5270
+ // that interval moved these tokens, and the durable entry itself is the
5271
+ // final word — after a confirmed deletion it is a receipt, not a body.
5272
+ if (cleanupReadTokenFor(root) !== enterToken || cleanupReadTokenFor(reportRoot) !== lookupToken) {
5273
+ return textResult(
5274
+ `Agent "${params.agent_id}" is no longer available — a cleanup changed its report while it was being read; its body was not returned.`,
5275
+ );
5276
+ }
5277
+ if (lookup.status === "found" && lookup.provenance === "archive") {
5278
+ // A deletion receipt is never unlinked, so a durable entry that is
5279
+ // PRESENT and no longer `full` — or rewritten at another generation
5280
+ // — is proof this body was replaced before this continuation
5281
+ // resumed. An UNREADABLE entry proves nothing and is refused: its
5282
+ // absence is not a missing archiver row, it is an unknown one. An
5283
+ // ABSENT entry is refused too: this body's provenance is the
5284
+ // archive row itself, so a proven-missing row means the body this
5285
+ // call captured is no longer the archived report — the token
5286
+ // recheck below cannot make that up. Genuine parent-record and
5287
+ // legacy-output recoveries have their own provenance and do not
5288
+ // reach this branch.
5289
+ const durable = await target.readEntryState(lookup.report.rootSessionId, lookup.report.id);
5290
+ if (durable.status === "uncertain") {
5291
+ return textResult(
5292
+ `Agent "${params.agent_id}" is no longer available — its durable report could not be verified during the read; its body was not returned.`,
5293
+ );
5294
+ }
5295
+ if (durable.status === "absent") {
5296
+ return textResult(
5297
+ `Agent "${params.agent_id}" is no longer available — its durable report entry is missing; its body was not returned.`,
5298
+ );
5299
+ }
5300
+ if (durable.entry.state !== "full" || durable.entry.entryGeneration !== lookup.entry.entryGeneration) {
5301
+ return textResult(
5302
+ `Agent "${params.agent_id}" is no longer available — its durable report was deleted during the read; its body was not returned.`,
5303
+ );
5304
+ }
5305
+ }
5306
+ const afterRead = resolveAgentRef(params.agent_id);
5307
+ if (afterRead === undefined) {
5308
+ // The durable-entry read above is the LAST await. Recheck the
5309
+ // operation's token and this id's availability now, immediately
5310
+ // before the body captured BEFORE that await could be returned.
5311
+ const finalRefusal = lookup.status === "found"
5312
+ ? cleanupReadRefusal({
5313
+ agentId: lookup.report.id,
5314
+ sessionFile: lookup.report.sessionFile,
5315
+ rootSessionId: lookup.report.rootSessionId,
5316
+ })
5317
+ : undefined;
5318
+ if (finalRefusal !== undefined) {
5319
+ return textResult(`Agent "${params.agent_id}" is being cleaned up (${finalRefusal}); its archived report is not readable right now.`);
5320
+ }
5321
+ if (cleanupReadTokenFor(root) !== enterToken || cleanupReadTokenFor(reportRoot) !== lookupToken) {
5322
+ return textResult(
5323
+ `Agent "${params.agent_id}" is no longer available — a cleanup changed its report while it was being read; its body was not returned.`,
5324
+ );
5325
+ }
5326
+ return textResult(archived);
5327
+ }
5328
+ if (!isTopLevelAgent(afterRead)) {
5329
+ return textResult(`Agent not found: "${params.agent_id}". It may have been cleaned up.`);
5330
+ }
5331
+ record = afterRead;
5332
+ }
5333
+ }
5334
+
5335
+ // Interactive wait: release the main turn instead of blocking it.
5336
+ //
5337
+ // Nothing here waits, polls, or arms a second wakeup. The agent's existing
5338
+ // completion notification is the one channel that wakes the parent, and
5339
+ // `terminate` is how this tool result stops pi from making the automatic
5340
+ // post-tool model call — pi honors it only when every finalized result in
5341
+ // the batch asks for it, which is why a sibling that needs its own result
5342
+ // keeps the turn alive rather than being cut off. The result stays
5343
+ // unconsumed, so the notification still fires; that is also what a
5344
+ // cancelled wait leaves behind.
5345
+ if (params.wait && (record.status === "running" || record.status === "queued") && ctx.mode === "tui") {
5346
+ // Same contract as the blocking path's `abortable`: an already-cancelled
5347
+ // call rejects, and nothing is registered for a caller that is gone.
5348
+ if (signal?.aborted) throw signal.reason;
5349
+ deferResultDelivery(record, { verbose: params.verbose === true });
5350
+ return {
5351
+ ...textResult(
5352
+ `PENDING — Agent ${record.id} is still ${record.status}; nothing has finished and there is no result yet. The main turn yielded.\n` +
5353
+ `The agent continues in the background. Its complete final report will arrive automatically in a later turn` +
5354
+ (params.verbose
5355
+ ? ", with the full conversation appended as an opt-in transcript excerpt — the report itself is never truncated, and get_subagent_result with verbose: true returns the full transcript.\n"
5356
+ : ".\n") +
5357
+ `Treat it as PENDING: do not poll or wait again, and do not fabricate its result.`,
5358
+ ),
5359
+ terminate: true,
5360
+ };
5361
+ }
2886
5362
 
2887
5363
  // Wait for completion if requested. Cancellation stops only this tool
2888
5364
  // call; the background agent keeps running and remains unconsumed so its
@@ -2931,10 +5407,13 @@ Terse command-style prompts produce shallow, generic work.
2931
5407
  Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? "" : "s"} arrived after the agent finished and ${record.droppedSteers === 1 ? "was" : "were"} discarded.`;
2932
5408
  }
2933
5409
 
2934
- // Mark result as consumed — suppresses the completion notification
5410
+ // Mark result as consumed — suppresses the completion notification, and
5411
+ // spends any deferred interest: the parent has the result already, so the
5412
+ // wakeup it asked for has nothing left to deliver.
2935
5413
  if (record.status !== "running" && record.status !== "queued") {
2936
5414
  record.resultConsumed = true;
2937
- cancelNudge(params.agent_id);
5415
+ cancelNudge(record.id);
5416
+ deferredResultInterest.delete(record.id);
2938
5417
  }
2939
5418
 
2940
5419
  // Verbose: include full conversation
@@ -2965,8 +5444,30 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
2965
5444
  message: Type.String({
2966
5445
  description: "The steering message to send. This will appear as a user message in the agent's conversation.",
2967
5446
  }),
5447
+ goalGuard: Type.Optional(Type.Object({
5448
+ version: Type.Literal(1),
5449
+ sessionId: Type.String({ description: "Live root session id the guard was issued for" }),
5450
+ goalId: Type.String({ description: "Goal that owns this guarded steering action" }),
5451
+ runGeneration: Type.Number({ description: "Exact run generation of the target agent in the goal agent snapshot" }),
5452
+ operationId: Type.String({ description: "Unique action id; a repeat for the same run generation is refused" }),
5453
+ }, {
5454
+ description: "Reserved for goal-orchestration clients. Ordinary steering must omit it; an unguarded call behaves exactly as before and a malformed or unavailable guard is refused without steering.",
5455
+ })),
2968
5456
  }),
2969
- execute: async (_toolCallId, params, _signal, _onUpdate, _ctx) => {
5457
+ execute: async (_toolCallId, params, signal, _onUpdate, _ctx) => {
5458
+ if (params.goalGuard !== undefined) {
5459
+ // Same ORIGINAL tool, same permission hooks. The bridge validates
5460
+ // session/ownership/generation/cancellation and delivers through
5461
+ // steerAcknowledged; a refusal throws a real tool error.
5462
+ const receipt = await goalBridge.steer(params.goalGuard, params.agent_id, params.message, signal);
5463
+ pi.events.emit("subagents:steered", { id: receipt.agentId, message: params.message });
5464
+ return textResult(
5465
+ `Steering message sent to agent ${receipt.agentId} (run ${receipt.runGeneration}). ` +
5466
+ (receipt.abortedAfterDelivery
5467
+ ? "It was acknowledged before the caller's cancellation and cannot be unsent."
5468
+ : "The agent will process it after its current tool execution."),
5469
+ );
5470
+ }
2970
5471
  const record = resolveAgentRef(params.agent_id);
2971
5472
  if (!record || !isTopLevelAgent(record)) {
2972
5473
  return textResult(`Agent not found: "${params.agent_id}". It may have been cleaned up.`);
@@ -3023,16 +5524,15 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
3023
5524
  // ---- main-session awareness of live agents ----
3024
5525
 
3025
5526
  // Top-level only by construction: this extension returns early in child
3026
- // sessions (see the top of this function). pi rebuilds `sections` fresh
3027
- // each turn, so an idle session simply gets no section. Hosts without
3028
- // mutable sections are skipped — never fall back to a full systemPrompt.
3029
- pi.on("before_agent_start", (event) => {
3030
- const options: unknown = (event as { systemPromptOptions?: unknown }).systemPromptOptions;
3031
- if (typeof options !== "object" || options === null) return;
3032
- const sections = (options as { sections?: unknown }).sections;
3033
- if (typeof sections !== "object" || sections === null) return;
3034
- const text = buildActiveAgentsSection(manager.listAgents().filter(isTopLevelAgent));
3035
- if (text) (sections as Record<string, string>)[ACTIVE_AGENTS_SECTION] = text;
5527
+ // sessions (see the top of this function). An appended hidden message, not a
5528
+ // `systemPromptOptions` section: see active-agents-prompt.ts for why a section
5529
+ // edit costs the prompt cache. Never a full systemPrompt either.
5530
+ pi.on("before_agent_start", (_event, ctx) => {
5531
+ const content = nextActiveAgentsMessage(
5532
+ manager.listAgents().filter(isTopLevelAgent),
5533
+ ctx.sessionManager?.getBranch?.() ?? [],
5534
+ );
5535
+ if (content) return { message: { customType: ACTIVE_AGENTS_MESSAGE_TYPE, content, display: false } };
3036
5536
  });
3037
5537
 
3038
5538
  // ---- stop_subagent tool ----
@@ -3057,7 +5557,7 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
3057
5557
  if (record.status !== "running" && record.status !== "queued") {
3058
5558
  return textResult(`Agent ${record.id} is already ${record.status}; nothing to stop.`);
3059
5559
  }
3060
- const wasQueued = record.status === "queued";
5560
+ const wasQueued = manager.isQueued(record.id);
3061
5561
  if (!manager.abort(record.id)) {
3062
5562
  return textResult(`Agent ${record.id} is already ${record.status}; nothing to stop.`);
3063
5563
  }
@@ -3097,7 +5597,7 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
3097
5597
  }
3098
5598
 
3099
5599
  async function showAgentsMenu(ctx: ExtensionCommandContext) {
3100
- reloadCustomAgents();
5600
+ await reloadCustomAgentsAsync();
3101
5601
  const allNames = getAllTypes();
3102
5602
 
3103
5603
  // Build select options
@@ -3242,30 +5742,88 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
3242
5742
  * caller — geometry and dismissal mirror the viewer wiring exactly.
3243
5743
  */
3244
5744
  async function showFleetOverlay(ctx: ExtensionContext): Promise<void> {
3245
- await ctx.ui.custom<undefined>(
3246
- (tui, theme, _keybindings, done) =>
3247
- new FleetOverlay({
3248
- tui,
3249
- theme,
3250
- records: () => manager.listAgents().filter(isTopLevelAgent),
3251
- // No workflow source when the feature is off, exactly as the
3252
- // conversation surfaces treat it: never advertise a switched-off run.
3253
- workflows: isWorkflowsEnabled() ? fleetWorkflows : () => [],
3254
- activity: agentActivity,
3255
- showCost: isShowCostEnabled,
3256
- openAgent: record => viewAgentConversation(ctx, record),
3257
- openWorkflow: id => openWorkflowFromFleet(id, workflowMenuDeps),
3258
- notify: (message, type) => ctx.ui.notify(message, type),
3259
- done,
3260
- }),
3261
- {
3262
- overlay: true,
3263
- overlayOptions: { anchor: "top-left", width: "100%", maxHeight: "100%", margin: 0 },
3264
- },
3265
- );
5745
+ // The fleet frame is anchored over the whole terminal, including the
5746
+ // editor container that `ctx.ui.input` draws its prompt into. Hide it while
5747
+ // a prompt is open (so the question and the typed answer are visible) and
5748
+ // restore it once the prompt resolves, cancellation and errors included.
5749
+ hubOpen = true;
5750
+ let overlay: OverlayHandle | undefined;
5751
+ let closed = false;
5752
+ const promptWhileHidden = async (title: string): Promise<string | undefined> => {
5753
+ const handle = overlay;
5754
+ if (!handle || closed) return ctx.ui.input(title, "");
5755
+ handle.setHidden(true);
5756
+ try {
5757
+ return await ctx.ui.input(title, "");
5758
+ } finally {
5759
+ // The overlay may have been torn down while the prompt was open; only
5760
+ // touch it when it is still the live surface.
5761
+ if (!closed) handle.setHidden(false);
5762
+ }
5763
+ };
5764
+
5765
+ try {
5766
+ await ctx.ui.custom<undefined>(
5767
+ (tui, theme, _keybindings, done) =>
5768
+ new FleetOverlay({
5769
+ tui,
5770
+ theme,
5771
+ records: () => manager.listAgents().filter(isTopLevelAgent),
5772
+ // No workflow source when the feature is off, exactly as the
5773
+ // conversation surfaces treat it: never advertise a switched-off run.
5774
+ workflows: isWorkflowsEnabled() ? fleetWorkflows : () => [],
5775
+ activity: agentActivity,
5776
+ showCost: isShowCostEnabled,
5777
+ openAgent: record => viewAgentConversation(ctx, record),
5778
+ openWorkflow: id => openWorkflowFromFleet(id, workflowMenuDeps),
5779
+ notify: (message, type) => ctx.ui.notify(message, type),
5780
+ done: result => {
5781
+ closed = true;
5782
+ done(result);
5783
+ },
5784
+ // Tree view: nested children too, never workflow-owned agents (the run reports for them).
5785
+ allRecords: () => manager.listAgents().filter(record => !record.workflowId),
5786
+ stopAgent: record => manager.abort(record.id),
5787
+ resumeAgent: async record => {
5788
+ if (!record.session) {
5789
+ ctx.ui.notify("Agent session is gone — it cannot be resumed.", "warning");
5790
+ return;
5791
+ }
5792
+ const message = await promptWhileHidden(`Resume ${record.alias ?? record.handle ?? record.type} with:`);
5793
+ if (!message?.trim()) return;
5794
+ const registry = await reloadCustomAgentsAsync();
5795
+ const config = getAgentConfigIn(registry, record.type);
5796
+ const resumed = await startBackgroundResume(ctx, record, message.trim(), {
5797
+ outputTranscript: config?.outputTranscript ?? getOutputTranscriptDefault(),
5798
+ maxTurns: normalizeMaxTurns(config?.maxTurns ?? getDefaultMaxTurns()),
5799
+ });
5800
+ ctx.ui.notify(resumed ? `Resuming "${record.description}".` : "Could not resume — it is still running.", resumed ? "info" : "warning");
5801
+ },
5802
+ }),
5803
+ {
5804
+ overlay: true,
5805
+ overlayOptions: { anchor: "top-left", width: "100%", maxHeight: "100%", margin: 0 },
5806
+ onHandle: handle => {
5807
+ overlay = handle;
5808
+ },
5809
+ },
5810
+ );
5811
+ } finally {
5812
+ closed = true;
5813
+ hubOpen = false;
5814
+ }
3266
5815
  }
3267
5816
 
3268
5817
  async function viewAgentConversation(ctx: ExtensionContext, record: AgentRecord, onCloseReady?: (close: () => void) => void) {
5818
+ const cleanupRefusal = cleanupReadRefusal({
5819
+ agentId: record.id,
5820
+ sessionFile: record.sessionFile,
5821
+ rootSessionId: record.rootSessionId,
5822
+ });
5823
+ if (cleanupRefusal !== undefined) {
5824
+ ctx.ui.notify(`"${record.description}" is being cleaned up (${cleanupRefusal}); its conversation is not readable right now.`, "warning");
5825
+ return;
5826
+ }
3269
5827
  if (!record.session) {
3270
5828
  ctx.ui.notify(`Agent is ${record.status === "queued" ? "queued" : "expired"} — no session available.`, "info");
3271
5829
  return;
@@ -3290,7 +5848,8 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
3290
5848
  }
3291
5849
  return accepted;
3292
5850
  }
3293
- const config = getAgentConfig(record.type);
5851
+ const registry = await reloadCustomAgentsAsync();
5852
+ const config = getAgentConfigIn(registry, record.type);
3294
5853
  return !!await startBackgroundResume(ctx, record, message, {
3295
5854
  outputTranscript: config?.outputTranscript ?? getOutputTranscriptDefault(),
3296
5855
  maxTurns: normalizeMaxTurns(config?.maxTurns ?? getDefaultMaxTurns()),
@@ -3343,7 +5902,7 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
3343
5902
  if (edited !== undefined && edited !== content) {
3344
5903
  const { writeFileSync } = await import("node:fs");
3345
5904
  writeFileSync(file.path, edited, "utf-8");
3346
- reloadCustomAgents();
5905
+ await reloadCustomAgentsAsync();
3347
5906
  ctx.ui.notify(`Updated ${file.path}`, "info");
3348
5907
  }
3349
5908
  } else if (choice === "Delete") {
@@ -3351,7 +5910,7 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
3351
5910
  const confirmed = await ctx.ui.confirm("Delete agent", `Delete ${name} from ${file.location} (${file.path})?`);
3352
5911
  if (confirmed) {
3353
5912
  unlinkSync(file.path);
3354
- reloadCustomAgents();
5913
+ await reloadCustomAgentsAsync();
3355
5914
  ctx.ui.notify(`Deleted ${file.path}`, "info");
3356
5915
  }
3357
5916
  }
@@ -3359,7 +5918,7 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
3359
5918
  const confirmed = await ctx.ui.confirm("Reset to default", `Delete override ${file.path} and restore embedded default?`);
3360
5919
  if (confirmed) {
3361
5920
  unlinkSync(file.path);
3362
- reloadCustomAgents();
5921
+ await reloadCustomAgentsAsync();
3363
5922
  ctx.ui.notify(`Restored default ${name}`, "info");
3364
5923
  }
3365
5924
  } else if (choice.startsWith("Eject")) {
@@ -3392,7 +5951,7 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
3392
5951
 
3393
5952
  const { writeFileSync } = await import("node:fs");
3394
5953
  writeFileSync(targetPath, content, "utf-8");
3395
- reloadCustomAgents();
5954
+ await reloadCustomAgentsAsync();
3396
5955
  ctx.ui.notify(`Ejected ${name} to ${targetPath}`, "info");
3397
5956
  }
3398
5957
 
@@ -3415,7 +5974,7 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
3415
5974
  }
3416
5975
  const { writeFileSync } = await import("node:fs");
3417
5976
  writeFileSync(file.path, updated, "utf-8");
3418
- reloadCustomAgents();
5977
+ await reloadCustomAgentsAsync();
3419
5978
  ctx.ui.notify(`Disabled ${name} (${file.path})`, "info");
3420
5979
  return;
3421
5980
  }
@@ -3433,7 +5992,7 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
3433
5992
  const targetPath = join(targetDir, `${name}.md`);
3434
5993
  const { writeFileSync } = await import("node:fs");
3435
5994
  writeFileSync(targetPath, "---\nenabled: false\n---\n", "utf-8");
3436
- reloadCustomAgents();
5995
+ await reloadCustomAgentsAsync();
3437
5996
  ctx.ui.notify(`Disabled ${name} (${targetPath})`, "info");
3438
5997
  }
3439
5998
 
@@ -3455,11 +6014,11 @@ Note: ${record.droppedSteers} steering message${record.droppedSteers === 1 ? ""
3455
6014
  // If the file was just a stub ("---\n---\n"), delete it to restore the built-in default
3456
6015
  if (isEmptyStub(updated)) {
3457
6016
  unlinkSync(file.path);
3458
- reloadCustomAgents();
6017
+ await reloadCustomAgentsAsync();
3459
6018
  ctx.ui.notify(`Enabled ${name} (removed ${file.path})`, "info");
3460
6019
  } else {
3461
6020
  writeFileSync(file.path, updated, "utf-8");
3462
- reloadCustomAgents();
6021
+ await reloadCustomAgentsAsync();
3463
6022
  ctx.ui.notify(`Enabled ${name} (${file.path})`, "info");
3464
6023
  }
3465
6024
  }
@@ -3553,7 +6112,8 @@ Write the file using the write tool. Only write the file, nothing else.`;
3553
6112
 
3554
6113
  const { record } = await manager.spawnAndWait(pi, ctx, "general-purpose", generatePrompt, {
3555
6114
  description: `Generate ${name} agent`,
3556
- maxTurns: 5,
6115
+ // No hardcoded turn cap here: the configured agent/default budget (or
6116
+ // unlimited) decides, so a wizard run is not silently cut at five turns.
3557
6117
  // Exempt from maxConcurrentForeground. This runs from a modal wizard, not
3558
6118
  // a tool call: it passes no signal, and Esc in `ctx.ui` never reaches the
3559
6119
  // manager — so a user waiting behind a full pool would have no way to
@@ -3567,7 +6127,7 @@ Write the file using the write tool. Only write the file, nothing else.`;
3567
6127
  return;
3568
6128
  }
3569
6129
 
3570
- reloadCustomAgents();
6130
+ await reloadCustomAgentsAsync();
3571
6131
 
3572
6132
  if (existsSync(targetPath)) {
3573
6133
  ctx.ui.notify(`Created ${targetPath}`, "info");
@@ -3647,7 +6207,7 @@ Write the file using the write tool. Only write the file, nothing else.`;
3647
6207
 
3648
6208
  const { writeFileSync } = await import("node:fs");
3649
6209
  writeFileSync(targetPath, content, "utf-8");
3650
- reloadCustomAgents();
6210
+ await reloadCustomAgentsAsync();
3651
6211
  ctx.ui.notify(`Created ${targetPath}`, "info");
3652
6212
  }
3653
6213
 
@@ -3669,6 +6229,9 @@ Write the file using the write tool. Only write the file, nothing else.`;
3669
6229
  // normalizeMaxTurns() in agent-runner.ts (which maps 0 → undefined).
3670
6230
  defaultMaxTurns: getDefaultMaxTurns() ?? 0,
3671
6231
  graceTurns: getGraceTurns(),
6232
+ // The policy the tool schema and resolver actually honor, written back so
6233
+ // an unrelated settings save cannot erase it.
6234
+ allowPerCallTurnLimits: getAllowPerCallTurnLimits(),
3672
6235
  defaultJoinMode: getDefaultJoinMode(),
3673
6236
  backgroundByDefault: getBackgroundByDefault(),
3674
6237
  schedulingEnabled: isSchedulingEnabled(),
@@ -3676,10 +6239,10 @@ Write the file using the write tool. Only write the file, nothing else.`;
3676
6239
  strictAgentFiles,
3677
6240
  disableDefaultAgents: isDefaultsDisabled(),
3678
6241
  toolDescriptionMode: getToolDescriptionMode(),
3679
- fleetView: isFleetViewEnabled(),
3680
6242
  agentMentions: getAgentMentionMode(),
3681
6243
  rememberAgents: getRememberAgents(),
3682
6244
  widgetMode: getWidgetMode(),
6245
+ widgetPlacement: getWidgetPlacement(),
3683
6246
  outputTranscript: getOutputTranscriptDefault(),
3684
6247
  worktreeIsolation: isWorktreeIsolationEnabled(),
3685
6248
  // The user's answer, not the effective one. A stand-down for another
@@ -3690,6 +6253,7 @@ Write the file using the write tool. Only write the file, nothing else.`;
3690
6253
  // JSON.stringify, so unset stays unset — same reasoning as
3691
6254
  // `fallbackSubagent` below.
3692
6255
  workflowsEnabled: isWorkflowsPinned() ? isWorkflowsEnabled() : undefined,
6256
+ workflowDefaultAgentType: getWorkflowDefaultAgentType(),
3693
6257
  maxSubagentDepth: getMaxSubagentDepth(),
3694
6258
  // Keep unset strict dispatch unset; don't turn it into an explicit
3695
6259
  // fallback when saving an unrelated setting. JSON.stringify drops undefined.
@@ -3727,6 +6291,15 @@ Write the file using the write tool. Only write the file, nothing else.`;
3727
6291
  // fallback targets are offered; unrelated saves preserve unset.
3728
6292
  const fallbackValue = getFallbackSubagent() ?? NO_FALLBACK;
3729
6293
  const fallbackValues = [...new Set([...getAvailableTypes(), NO_FALLBACK])];
6294
+ // The role list offers enabled agents only, but never drops a configured
6295
+ // default that is currently disabled or renamed: that would make the
6296
+ // stored value unrepresentable in the list and invite a stray save to
6297
+ // replace it with whatever happens to be available.
6298
+ const workflowDefault = getWorkflowDefaultAgentType();
6299
+ const availableRoles = getAvailableTypes();
6300
+ const workflowDefaultValues = availableRoles.includes(workflowDefault)
6301
+ ? availableRoles
6302
+ : [workflowDefault, ...availableRoles];
3730
6303
 
3731
6304
  return [
3732
6305
  {
@@ -3739,7 +6312,7 @@ Write the file using the write tool. Only write the file, nothing else.`;
3739
6312
  {
3740
6313
  id: "maxConcurrentForeground",
3741
6314
  label: "Max foreground concurrency",
3742
- description: "Max concurrent foreground (blocking) agents (0 = unlimited, Enter to type)",
6315
+ description: "Max concurrent inline foreground agents — headless/print/RPC only; terminal-UI foreground requests yield as logical awaits (0 = unlimited, Enter to type)",
3743
6316
  currentValue: String(mcf),
3744
6317
  values: [String(mcf)],
3745
6318
  },
@@ -3750,6 +6323,14 @@ Write the file using the write tool. Only write the file, nothing else.`;
3750
6323
  currentValue: String(dmt),
3751
6324
  values: [String(dmt)],
3752
6325
  },
6326
+ {
6327
+ id: "allowPerCallTurnLimits",
6328
+ label: "Allow per-call turn limits",
6329
+ description:
6330
+ "Let an Agent/nested/RPC caller's max_turns cap a run (off = configured agent/role and default budgets decide; the parameter is hidden from the tool schema on next pi session)",
6331
+ currentValue: getAllowPerCallTurnLimits() ? "on" : "off",
6332
+ values: ["on", "off"],
6333
+ },
3753
6334
  {
3754
6335
  id: "graceTurns",
3755
6336
  label: "Grace turns",
@@ -3774,7 +6355,7 @@ Write the file using the write tool. Only write the file, nothing else.`;
3774
6355
  {
3775
6356
  id: "backgroundByDefault",
3776
6357
  label: "Background by default",
3777
- description: "An Agent call that doesn't say runs detached (off = blocks the turn and returns inline)",
6358
+ description: "An Agent call that doesn't say runs detached (off = interactive requests yield immediately as a PENDING logical await with the report arriving later; headless/print/RPC calls block and return inline)",
3778
6359
  currentValue: getBackgroundByDefault() ? "on" : "off",
3779
6360
  values: ["on", "off"],
3780
6361
  },
@@ -3794,6 +6375,14 @@ Write the file using the write tool. Only write the file, nothing else.`;
3794
6375
  currentValue: isWorkflowsEnabled() ? "on" : "off",
3795
6376
  values: ["on", "off"],
3796
6377
  },
6378
+ {
6379
+ id: "workflowDefaultAgentType",
6380
+ label: "Workflow default agent",
6381
+ description:
6382
+ "Agent type a workflow's agent() calls use when they name none (default: task). A SubagentWorkflow call's agentType, or a script's per-call opts.agentType, outranks it. Applies to runs started from now on; a stored value is kept even while that role is unavailable.",
6383
+ currentValue: workflowDefault,
6384
+ values: workflowDefaultValues,
6385
+ },
3797
6386
  {
3798
6387
  id: "scopeModels",
3799
6388
  label: "Scope models",
@@ -3849,7 +6438,7 @@ Write the file using the write tool. Only write the file, nothing else.`;
3849
6438
  id: "showCost",
3850
6439
  label: "Show cost",
3851
6440
  description:
3852
- "Show an estimated `~$0.0042` beside subagent token counts in the widget, fleet view, results and notifications. Priced by pi from the model's rates — omitted entirely for a model it has no rates for.",
6441
+ "Show an estimated `~$0.0042` beside subagent token counts in the widget, Agent Hub, results and notifications. Priced by pi from the model's rates — omitted entirely for a model it has no rates for.",
3853
6442
  currentValue: isShowCostEnabled() ? "on" : "off",
3854
6443
  values: ["on", "off"],
3855
6444
  },
@@ -3869,13 +6458,6 @@ Write the file using the write tool. Only write the file, nothing else.`;
3869
6458
  currentValue: getViewerMarkdown(),
3870
6459
  values: ["off", "assistant", "all"],
3871
6460
  },
3872
- {
3873
- id: "fleetView",
3874
- label: "Fleet view",
3875
- description: "Claude Code-style main+subagents list below the editor (↓/← to navigate, Enter to view)",
3876
- currentValue: isFleetViewEnabled() ? "on" : "off",
3877
- values: ["on", "off"],
3878
- },
3879
6461
  {
3880
6462
  id: "agentMentions",
3881
6463
  label: "Agent mentions",
@@ -3893,10 +6475,17 @@ Write the file using the write tool. Only write the file, nothing else.`;
3893
6475
  {
3894
6476
  id: "widgetMode",
3895
6477
  label: "Widget",
3896
- description: "Above-editor agent widget: all = every agent; background = hide foreground (they already render inline); off = hide the widget.",
6478
+ description: "Compact agent widget: all = every agent; background = hide foreground (they already render inline); off = hide the widget.",
3897
6479
  currentValue: getWidgetMode(),
3898
6480
  values: ["all", "background", "off"],
3899
6481
  },
6482
+ {
6483
+ id: "widgetPlacement",
6484
+ label: "Widget placement",
6485
+ description: "Place the compact agent list above or below the editor. Applied immediately; above is the default.",
6486
+ currentValue: getWidgetPlacement(),
6487
+ values: ["above", "below"],
6488
+ },
3900
6489
  {
3901
6490
  id: "toolDescriptionMode",
3902
6491
  label: "Tool description",
@@ -3932,6 +6521,21 @@ Write the file using the write tool. Only write the file, nothing else.`;
3932
6521
  setDefaultMaxTurns(n);
3933
6522
  notifyApplied(ctx, `Default max turns set to ${n}`);
3934
6523
  }
6524
+ } else if (id === "allowPerCallTurnLimits") {
6525
+ const enabled = value === "on";
6526
+ if (enabled === getAllowPerCallTurnLimits()) {
6527
+ ctx.ui.notify(`Per-call turn limits already ${enabled ? "allowed" : "ignored"}.`, "info");
6528
+ } else {
6529
+ setAllowPerCallTurnLimits(enabled);
6530
+ // Runtime filtering is live; the `max_turns` parameter only appears or
6531
+ // disappears from the tool schema when the schema is built at load.
6532
+ notifyApplied(
6533
+ ctx,
6534
+ enabled
6535
+ ? "Per-call turn limits allowed. Caller max_turns now caps runs; tool schema updates on next pi session."
6536
+ : "Per-call turn limits ignored. Configured agent/role and default budgets decide; the max_turns parameter is hidden on next pi session.",
6537
+ );
6538
+ }
3935
6539
  } else if (id === "graceTurns") {
3936
6540
  const n = parseInt(value, 10);
3937
6541
  if (n >= 1) {
@@ -3959,7 +6563,7 @@ Write the file using the write tool. Only write the file, nothing else.`;
3959
6563
  ctx,
3960
6564
  enabled
3961
6565
  ? "Agent calls run in the background unless they pass run_in_background: false"
3962
- : "Agent calls block and return inline unless they pass run_in_background: true",
6566
+ : "Unqualified Agent calls now request foreground: the terminal UI yields immediately as a PENDING logical await and reports later; headless/print/RPC runs block and return inline",
3963
6567
  );
3964
6568
  } else if (id === "schedulingEnabled") {
3965
6569
  const enabled = value === "on";
@@ -3987,6 +6591,11 @@ Write the file using the write tool. Only write the file, nothing else.`;
3987
6591
  `Workflows ${enabled ? "enabled" : "disabled"}. Tool spec change takes effect on next pi session.`,
3988
6592
  );
3989
6593
  }
6594
+ } else if (id === "workflowDefaultAgentType") {
6595
+ setWorkflowDefaultAgentType(value);
6596
+ // New runs only: a task freezes its default when it is created, which is
6597
+ // what lets a resume keep replaying under the role it started with.
6598
+ notifyApplied(ctx, `Workflow default agent set to ${value}`);
3990
6599
  } else if (id === "scopeModels") {
3991
6600
  const enabled = value === "on";
3992
6601
  setScopeModelsEnabled(enabled);
@@ -4043,10 +6652,6 @@ Write the file using the write tool. Only write the file, nothing else.`;
4043
6652
  } else if (id === "viewerMarkdown") {
4044
6653
  setViewerMarkdown(value as ViewerMarkdownMode);
4045
6654
  notifyApplied(ctx, `Viewer markdown set to ${value}`);
4046
- } else if (id === "fleetView") {
4047
- const enabled = value === "on";
4048
- setFleetViewEnabled(enabled);
4049
- notifyApplied(ctx, `Fleet view ${enabled ? "enabled" : "disabled"}`);
4050
6655
  } else if (id === "agentMentions") {
4051
6656
  const mode = value as AgentMentionMode;
4052
6657
  setAgentMentionMode(mode);
@@ -4065,6 +6670,9 @@ Write the file using the write tool. Only write the file, nothing else.`;
4065
6670
  } else if (id === "widgetMode") {
4066
6671
  setWidgetMode(value as WidgetMode);
4067
6672
  notifyApplied(ctx, `Widget set to ${value}`);
6673
+ } else if (id === "widgetPlacement") {
6674
+ setWidgetPlacement(value as WidgetPlacement);
6675
+ notifyApplied(ctx, `Widget placement set to ${value}`);
4068
6676
  }
4069
6677
  }
4070
6678
 
@@ -4190,6 +6798,31 @@ Write the file using the write tool. Only write the file, nothing else.`;
4190
6798
  handler: async (_args, ctx) => { await showAgentsMenu(ctx); },
4191
6799
  });
4192
6800
 
6801
+ // Session-only "subagents off" — see force-main-model.ts for the semantics.
6802
+ pi.registerCommand("subagents", {
6803
+ description: "Force new subagents onto the main model (session only): /subagents on|off",
6804
+ handler: async (args, ctx) => {
6805
+ const tokens = (args ?? "").trim().split(/\s+/).filter(Boolean);
6806
+ if (tokens[0]?.toLowerCase() === "cleanup") {
6807
+ await handleCleanupCommand(tokens.slice(1), ctx);
6808
+ return;
6809
+ }
6810
+ const arg = (args ?? "").trim().toLowerCase();
6811
+ if (arg !== "" && arg !== "on" && arg !== "off") {
6812
+ ctx.ui.notify("Usage: /subagents [on|off] — no argument toggles the current state.", "warning");
6813
+ return;
6814
+ }
6815
+ const next = arg === "" ? !isForceMainModel() : arg === "off";
6816
+ setForceMainModel(next);
6817
+ ctx.ui.notify(
6818
+ next
6819
+ ? "Subagents OFF — new spawns, and anything they spawn, run on the main model until pi exits or /subagents on."
6820
+ : "Subagents ON — agent model pins and caller overrides apply again.",
6821
+ "info",
6822
+ );
6823
+ },
6824
+ });
6825
+
4193
6826
  // The fleet overlay's third door: the same two-pane surface as `←` at an
4194
6827
  // empty prompt and `/agents → Running agents`, reachable without the menu
4195
6828
  // hop or an empty prompt. Registered unconditionally like `/agents` — the
@@ -4200,19 +6833,24 @@ Write the file using the write tool. Only write the file, nothing else.`;
4200
6833
  handler: async (_args, ctx) => { await showFleetOverlay(ctx); },
4201
6834
  });
4202
6835
 
4203
- /**
4204
- * What `/agents → Workflows` and the fleet list's `workflow` rows need from
4205
- * here. One object, built once: both entry points open the same inspector,
4206
- * and handing them different views of the session would let the two drift.
4207
- */
6836
+ // Agent Hub chord (oh-my-pi's Alt+A). Opens the same overlay; Alt+A inside it closes it.
6837
+ // Hosts without a shortcut API keep `←` and /agent-fleet.
6838
+ if (typeof pi.registerShortcut === "function") {
6839
+ pi.registerShortcut("alt+a", {
6840
+ description: "Open the agent hub (fleet overlay)",
6841
+ handler: async ctx => {
6842
+ if (ctx.mode === "tui") await showFleetOverlay(ctx);
6843
+ },
6844
+ });
6845
+ }
6846
+
6847
+ /** Shared inspector dependencies for `/agents → Workflows` and Agent Hub. */
4208
6848
  const workflowMenuDeps: WorkflowMenuDeps = {
4209
6849
  tasks: workflowTasks,
4210
6850
  getRecord: id => manager.getRecord(id),
4211
6851
  viewAgentConversation,
4212
- // Read lazily: `currentCtx` is rebound on every session_start, and the
4213
- // fleet list may act between sessions, when there is none.
6852
+ // Read lazily: `currentCtx` is rebound on every session_start.
4214
6853
  getCtx: () => currentCtx as unknown as ExtensionCommandContext | undefined,
4215
6854
  };
4216
6855
 
4217
- fleet.setWorkflowSource(fleetWorkflows, id => openWorkflowFromFleet(id, workflowMenuDeps));
4218
6856
  }