@xzzpig/pi-subagents 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/CHANGELOG.md +1621 -0
  2. package/LICENSE +21 -0
  3. package/README.md +118 -0
  4. package/agents/delegate.md +14 -0
  5. package/agents/oracle.md +74 -0
  6. package/agents/researcher.md +52 -0
  7. package/agents/reviewer.md +79 -0
  8. package/agents/scout.md +50 -0
  9. package/agents/worker.md +58 -0
  10. package/index.ts +1 -0
  11. package/inspector-runner.mjs +11 -0
  12. package/install.mjs +93 -0
  13. package/package.json +105 -0
  14. package/prompts/gather-context-and-clarify.md +13 -0
  15. package/prompts/parallel-cleanup.md +59 -0
  16. package/prompts/parallel-research.md +50 -0
  17. package/prompts/parallel-review.md +54 -0
  18. package/prompts/review-loop.md +43 -0
  19. package/skills/pi-subagents/SKILL.md +41 -0
  20. package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
  21. package/skills/pi-subagents/references/execution-controls.md +428 -0
  22. package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
  24. package/src/agents/agent-management.ts +1256 -0
  25. package/src/agents/agent-memory.ts +254 -0
  26. package/src/agents/agent-refinements.ts +624 -0
  27. package/src/agents/agent-scope.ts +6 -0
  28. package/src/agents/agent-selection.ts +25 -0
  29. package/src/agents/agent-serializer.ts +163 -0
  30. package/src/agents/agents.ts +1889 -0
  31. package/src/agents/chain-serializer.ts +280 -0
  32. package/src/agents/frontmatter.ts +149 -0
  33. package/src/agents/identity.ts +30 -0
  34. package/src/agents/proactive-skills.ts +194 -0
  35. package/src/agents/skills.ts +761 -0
  36. package/src/api/background-work.ts +197 -0
  37. package/src/api/capability-ceiling.ts +17 -0
  38. package/src/api/control-channel.ts +4 -0
  39. package/src/api/delegation.ts +119 -0
  40. package/src/api/external-runs.ts +129 -0
  41. package/src/api/intercom-bridge.ts +3 -0
  42. package/src/api/pi-args.ts +5 -0
  43. package/src/api/preflight.ts +403 -0
  44. package/src/api/shared-types.ts +19 -0
  45. package/src/extension/config.ts +76 -0
  46. package/src/extension/control-notices.ts +58 -0
  47. package/src/extension/doctor.ts +230 -0
  48. package/src/extension/fanout-child.ts +201 -0
  49. package/src/extension/index.ts +805 -0
  50. package/src/extension/public-execution.ts +71 -0
  51. package/src/extension/rpc.ts +653 -0
  52. package/src/extension/schemas.ts +375 -0
  53. package/src/extension/steering-notices.ts +35 -0
  54. package/src/extension/tool-description.ts +164 -0
  55. package/src/inspectors/herdr/actions.ts +229 -0
  56. package/src/inspectors/herdr/client.ts +130 -0
  57. package/src/inspectors/herdr/inspector-runner.ts +141 -0
  58. package/src/inspectors/herdr/project-panes.ts +154 -0
  59. package/src/integrations/herdr-status.ts +330 -0
  60. package/src/intercom/intercom-bridge.ts +187 -0
  61. package/src/intercom/native-supervisor-channel.ts +715 -0
  62. package/src/intercom/result-intercom.ts +421 -0
  63. package/src/missions/actions.ts +410 -0
  64. package/src/missions/goal-driver.ts +162 -0
  65. package/src/missions/lifecycle.ts +346 -0
  66. package/src/missions/store.ts +507 -0
  67. package/src/missions/types.ts +157 -0
  68. package/src/missions/workflow-state.ts +250 -0
  69. package/src/policy/authority.ts +46 -0
  70. package/src/profiles/profiles.ts +661 -0
  71. package/src/runs/background/async-execution.ts +1574 -0
  72. package/src/runs/background/async-job-tracker.ts +511 -0
  73. package/src/runs/background/async-resume.ts +539 -0
  74. package/src/runs/background/async-status.ts +542 -0
  75. package/src/runs/background/auto-drain.ts +67 -0
  76. package/src/runs/background/chain-append.ts +328 -0
  77. package/src/runs/background/chain-root-attachment.ts +199 -0
  78. package/src/runs/background/completion-batcher.ts +168 -0
  79. package/src/runs/background/completion-dedupe.ts +54 -0
  80. package/src/runs/background/control-channel.ts +692 -0
  81. package/src/runs/background/fleet-view.ts +540 -0
  82. package/src/runs/background/notify.ts +332 -0
  83. package/src/runs/background/parallel-groups.ts +45 -0
  84. package/src/runs/background/process-terminal.ts +280 -0
  85. package/src/runs/background/result-watcher.ts +414 -0
  86. package/src/runs/background/retained-children.ts +68 -0
  87. package/src/runs/background/run-id-resolver.ts +167 -0
  88. package/src/runs/background/run-status.ts +504 -0
  89. package/src/runs/background/scheduled-runs.ts +753 -0
  90. package/src/runs/background/stale-run-reconciler.ts +396 -0
  91. package/src/runs/background/steering.ts +239 -0
  92. package/src/runs/background/subagent-runner.ts +4718 -0
  93. package/src/runs/background/subagent-wait.ts +661 -0
  94. package/src/runs/background/top-level-async.ts +14 -0
  95. package/src/runs/background/wait-completions.ts +112 -0
  96. package/src/runs/background/wait-config.ts +36 -0
  97. package/src/runs/background/wait-subscriptions.ts +253 -0
  98. package/src/runs/background/wait-tool.ts +34 -0
  99. package/src/runs/foreground/async-steering-action.ts +256 -0
  100. package/src/runs/foreground/async-stop-action.ts +65 -0
  101. package/src/runs/foreground/chain-clarify.ts +1354 -0
  102. package/src/runs/foreground/chain-execution.ts +1527 -0
  103. package/src/runs/foreground/execution.ts +1868 -0
  104. package/src/runs/foreground/foreground-control.ts +132 -0
  105. package/src/runs/foreground/subagent-executor.ts +5532 -0
  106. package/src/runs/shared/acceptance.ts +1365 -0
  107. package/src/runs/shared/agent-contract.ts +38 -0
  108. package/src/runs/shared/capability-ceiling.ts +209 -0
  109. package/src/runs/shared/chain-outputs.ts +118 -0
  110. package/src/runs/shared/child-protocol.ts +401 -0
  111. package/src/runs/shared/completion-guard.ts +95 -0
  112. package/src/runs/shared/context-mode.ts +44 -0
  113. package/src/runs/shared/dynamic-fanout.ts +297 -0
  114. package/src/runs/shared/external-cli-runner.ts +130 -0
  115. package/src/runs/shared/long-running-guard.ts +220 -0
  116. package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
  117. package/src/runs/shared/model-fallback.ts +336 -0
  118. package/src/runs/shared/model-scope.ts +128 -0
  119. package/src/runs/shared/nested-events.ts +1076 -0
  120. package/src/runs/shared/nested-path.ts +52 -0
  121. package/src/runs/shared/nested-render.ts +123 -0
  122. package/src/runs/shared/parallel-handoff.ts +238 -0
  123. package/src/runs/shared/parallel-utils.ts +256 -0
  124. package/src/runs/shared/permissions.ts +95 -0
  125. package/src/runs/shared/pi-args.ts +808 -0
  126. package/src/runs/shared/pi-spawn.ts +163 -0
  127. package/src/runs/shared/process-signal.ts +19 -0
  128. package/src/runs/shared/run-history.ts +181 -0
  129. package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
  130. package/src/runs/shared/session-lease.ts +299 -0
  131. package/src/runs/shared/single-output.ts +235 -0
  132. package/src/runs/shared/spawn-budget.ts +128 -0
  133. package/src/runs/shared/structured-output.ts +182 -0
  134. package/src/runs/shared/subagent-control.ts +231 -0
  135. package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
  136. package/src/runs/shared/subagent-startup-retry.ts +104 -0
  137. package/src/runs/shared/task-intent.ts +181 -0
  138. package/src/runs/shared/tool-availability.ts +83 -0
  139. package/src/runs/shared/tool-budget.ts +80 -0
  140. package/src/runs/shared/turn-budget.ts +98 -0
  141. package/src/runs/shared/usage-budget.ts +65 -0
  142. package/src/runs/shared/workflow-graph.ts +231 -0
  143. package/src/runs/shared/worktree.ts +759 -0
  144. package/src/shared/accessible-dir.ts +47 -0
  145. package/src/shared/artifacts.ts +285 -0
  146. package/src/shared/atomic-json.ts +61 -0
  147. package/src/shared/child-transcript.ts +264 -0
  148. package/src/shared/file-coalescer.ts +40 -0
  149. package/src/shared/file-system-retry.ts +47 -0
  150. package/src/shared/fork-context.ts +213 -0
  151. package/src/shared/formatters.ts +133 -0
  152. package/src/shared/jsonl-writer.ts +81 -0
  153. package/src/shared/launch-contract.ts +124 -0
  154. package/src/shared/model-info.ts +81 -0
  155. package/src/shared/post-exit-stdio-guard.ts +85 -0
  156. package/src/shared/session-identity.ts +10 -0
  157. package/src/shared/session-tokens.ts +44 -0
  158. package/src/shared/settings.ts +501 -0
  159. package/src/shared/status-format.ts +55 -0
  160. package/src/shared/types.ts +2069 -0
  161. package/src/shared/utils.ts +613 -0
  162. package/src/slash/delegation-adapters.ts +434 -0
  163. package/src/slash/delegation-json.ts +108 -0
  164. package/src/slash/delegation-request.ts +166 -0
  165. package/src/slash/prompt-template-bridge.ts +383 -0
  166. package/src/slash/prompt-workflows.ts +300 -0
  167. package/src/slash/selector.ts +147 -0
  168. package/src/slash/slash-bridge.ts +192 -0
  169. package/src/slash/slash-commands.ts +994 -0
  170. package/src/slash/slash-live-state.ts +296 -0
  171. package/src/slash/subagents-admin.ts +432 -0
  172. package/src/tui/fleet-status.ts +564 -0
  173. package/src/tui/fleet-transcript.ts +577 -0
  174. package/src/tui/fleet.ts +879 -0
  175. package/src/tui/render-helpers.ts +80 -0
  176. package/src/tui/render.ts +2029 -0
  177. package/src/types/pi-runtime-compat.d.ts +8 -0
  178. package/src/watchdog/change-signature.ts +220 -0
  179. package/src/watchdog/child-status.ts +205 -0
  180. package/src/watchdog/emission-guard.ts +123 -0
  181. package/src/watchdog/lsp-diagnostics.ts +537 -0
  182. package/src/watchdog/model-selection.ts +167 -0
  183. package/src/watchdog/permission-arbiter.ts +145 -0
  184. package/src/watchdog/register-child.ts +117 -0
  185. package/src/watchdog/register-main.ts +440 -0
  186. package/src/watchdog/render.ts +54 -0
  187. package/src/watchdog/review.ts +302 -0
  188. package/src/watchdog/runtime.ts +868 -0
  189. package/src/watchdog/scope.ts +62 -0
  190. package/src/watchdog/settings.ts +568 -0
  191. package/src/watchdog/tool-actions.ts +155 -0
  192. package/src/watchdog/turn-delta.ts +161 -0
  193. package/src/watchdog/types.ts +198 -0
  194. package/src/watchdog/warning-format.ts +73 -0
  195. package/src/workflows/chat-progress.ts +140 -0
  196. package/src/workflows/scripted-workflow.ts +506 -0
@@ -0,0 +1,542 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { formatDuration, formatModelThinking, formatTokens, shortenPath } from "../../shared/formatters.ts";
4
+ import { formatActivityLabel, formatParallelOutcome } from "../../shared/status-format.ts";
5
+ import { type ActivityState, type AsyncJobStep, type AsyncParallelGroupStatus, type AsyncStatus, type CostSummary, type Details, type LaunchResolvedChildExtensionsV1, type RuntimeAcknowledgedChildExtensionsV1, type NestedRunSummary, type SteeringStatus, type SubagentRunMode, type TokenUsage, type TurnBudgetState, type UsageBudgetState, type ChainCheckpointState } from "../../shared/types.ts";
6
+ import type { ResolvedSubagentCapabilityCeiling, SubagentCapabilityAudit } from "../shared/capability-ceiling.ts";
7
+ import { readStatus } from "../../shared/utils.ts";
8
+ import { attachRootChildrenToSteps, buildNestedRouteIndex, type NestedRoute, projectNestedEvents } from "../shared/nested-events.ts";
9
+ import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
10
+ import { flatToLogicalStepIndex, normalizeParallelGroups } from "./parallel-groups.ts";
11
+ import { contextModeLabel, summarizeContextModes, type ContextMode, type ContextSummary } from "../shared/context-mode.ts";
12
+ import { reconcileAsyncRun, reconcileNestedAsyncDescendants } from "./stale-run-reconciler.ts";
13
+ import { readProcessTerminal, sanitizeProcessTerminal } from "./process-terminal.ts";
14
+
15
+ interface AsyncRunStepSummary {
16
+ index: number;
17
+ agent: string;
18
+ context?: ContextMode;
19
+ label?: string;
20
+ description?: string;
21
+ phase?: string;
22
+ outputName?: string;
23
+ structured?: boolean;
24
+ checkpoint?: ChainCheckpointState;
25
+ status: AsyncJobStep["status"];
26
+ activityState?: ActivityState;
27
+ lastActivityAt?: number;
28
+ currentTool?: string;
29
+ currentToolArgs?: string;
30
+ currentToolStartedAt?: number;
31
+ currentPath?: string;
32
+ recentTools?: Array<{ tool: string; args: string; endMs: number }>;
33
+ recentOutput?: string[];
34
+ turnCount?: number;
35
+ toolCount?: number;
36
+ steering?: SteeringStatus;
37
+ durationMs?: number;
38
+ tokens?: TokenUsage;
39
+ totalCost?: CostSummary;
40
+ skills?: string[];
41
+ model?: string;
42
+ thinking?: string;
43
+ attemptedModels?: string[];
44
+ sessionFile?: string;
45
+ transcriptPath?: string;
46
+ error?: string;
47
+ timedOut?: boolean;
48
+ stopped?: boolean;
49
+ turnBudget?: TurnBudgetState;
50
+ turnBudgetExceeded?: boolean;
51
+ wrapUpRequested?: boolean;
52
+ acceptance?: AsyncJobStep["acceptance"];
53
+ agentContract?: AsyncJobStep["agentContract"];
54
+ execution?: AsyncJobStep["execution"];
55
+ review?: AsyncJobStep["review"];
56
+ effects?: AsyncJobStep["effects"];
57
+ processTerminal?: AsyncJobStep["processTerminal"];
58
+ launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
59
+ runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
60
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
61
+ capabilityAudit?: SubagentCapabilityAudit;
62
+ children?: NestedRunSummary[];
63
+ }
64
+
65
+ export interface AsyncRunSummary {
66
+ id: string;
67
+ asyncDir: string;
68
+ toolCallId?: string;
69
+ sessionId?: string;
70
+ state: "queued" | "running" | "complete" | "failed" | "paused" | "stopped" | "rejected";
71
+ error?: string;
72
+ activityState?: ActivityState;
73
+ lastActivityAt?: number;
74
+ currentTool?: string;
75
+ currentToolStartedAt?: number;
76
+ currentPath?: string;
77
+ turnCount?: number;
78
+ toolCount?: number;
79
+ steering?: SteeringStatus;
80
+ mode: SubagentRunMode;
81
+ context?: ContextSummary;
82
+ cwd?: string;
83
+ startedAt: number;
84
+ lastUpdate?: number;
85
+ endedAt?: number;
86
+ timeoutMs?: number;
87
+ deadlineAt?: number;
88
+ timedOut?: boolean;
89
+ stopped?: boolean;
90
+ turnBudget?: TurnBudgetState;
91
+ turnBudgetExceeded?: boolean;
92
+ wrapUpRequested?: boolean;
93
+ currentStep?: number;
94
+ chainStepCount?: number;
95
+ pendingAppends?: number;
96
+ parallelGroups?: AsyncParallelGroupStatus[];
97
+ steps: AsyncRunStepSummary[];
98
+ checkpoint?: ChainCheckpointState;
99
+ sessionDir?: string;
100
+ outputFile?: string;
101
+ totalTokens?: TokenUsage;
102
+ totalCost?: CostSummary;
103
+ usageBudget?: UsageBudgetState;
104
+ sessionFile?: string;
105
+ nestedChildren?: NestedRunSummary[];
106
+ nestedWarnings?: string[];
107
+ processTerminal?: AsyncStatus["processTerminal"];
108
+ launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
109
+ runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
110
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
111
+ capabilityAudit?: SubagentCapabilityAudit;
112
+ parentWorkflowRunId?: string;
113
+ workflowKey?: string;
114
+ workflow?: Details["workflow"];
115
+ }
116
+
117
+ interface AsyncRunListOptions {
118
+ states?: Array<AsyncRunSummary["state"]>;
119
+ sessionId?: string;
120
+ limit?: number;
121
+ /** Limits status-file reads after candidates are ordered by status mtime. */
122
+ entryLimit?: number;
123
+ resultsDir?: string;
124
+ kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
125
+ now?: () => number;
126
+ reconcile?: boolean;
127
+ runId?: string;
128
+ }
129
+
130
+ function getErrorMessage(error: unknown): string {
131
+ return error instanceof Error ? error.message : String(error);
132
+ }
133
+
134
+ function isNotFoundError(error: unknown): boolean {
135
+ return typeof error === "object"
136
+ && error !== null
137
+ && "code" in error
138
+ && (error as NodeJS.ErrnoException).code === "ENOENT";
139
+ }
140
+
141
+ function isAsyncRunDir(root: string, entry: string): boolean {
142
+ const entryPath = path.join(root, entry);
143
+ try {
144
+ return fs.statSync(entryPath).isDirectory();
145
+ } catch (error) {
146
+ if (isNotFoundError(error)) return false;
147
+ throw new Error(`Failed to inspect async run path '${entryPath}': ${getErrorMessage(error)}`, {
148
+ cause: error instanceof Error ? error : undefined,
149
+ });
150
+ }
151
+ }
152
+
153
+ type TargetedAsyncRunResolution =
154
+ | { kind: "exact"; id: string }
155
+ | { kind: "scan" }
156
+ | { kind: "reject" };
157
+
158
+ /**
159
+ * Resolve an exact targeted run without following a run-directory symlink or
160
+ * accepting a path whose canonical location escaped the async root.
161
+ */
162
+ export function resolveTargetedAsyncRun(asyncDirRoot: string, id: string, sessionId?: string): TargetedAsyncRunResolution {
163
+ if (!id || id === "." || id === ".." || path.basename(id) !== id) return { kind: "reject" };
164
+ const asyncDir = path.join(asyncDirRoot, id);
165
+ let entryStat: fs.Stats;
166
+ try {
167
+ entryStat = fs.lstatSync(asyncDir);
168
+ } catch (error) {
169
+ if (isNotFoundError(error)) return { kind: "scan" };
170
+ throw new Error(`Failed to inspect async run path '${asyncDir}': ${getErrorMessage(error)}`, {
171
+ cause: error instanceof Error ? error : undefined,
172
+ });
173
+ }
174
+ if (!entryStat.isDirectory() || entryStat.isSymbolicLink()) return { kind: "reject" };
175
+ try {
176
+ const canonicalRoot = fs.realpathSync(asyncDirRoot);
177
+ const canonicalDir = fs.realpathSync(asyncDir);
178
+ if (canonicalDir !== canonicalRoot && !canonicalDir.startsWith(`${canonicalRoot}${path.sep}`)) return { kind: "reject" };
179
+ } catch (error) {
180
+ if (isNotFoundError(error)) return { kind: "reject" };
181
+ throw new Error(`Failed to resolve async run path '${asyncDir}': ${getErrorMessage(error)}`, {
182
+ cause: error instanceof Error ? error : undefined,
183
+ });
184
+ }
185
+ if (sessionId !== undefined) {
186
+ const status = readStatus(asyncDir);
187
+ if (status?.sessionId !== sessionId) return { kind: "scan" };
188
+ }
189
+ return { kind: "exact", id };
190
+ }
191
+
192
+ function outputFileMtime(outputFile: string | undefined): number | undefined {
193
+ if (!outputFile) return undefined;
194
+ try {
195
+ return fs.statSync(outputFile).mtimeMs;
196
+ } catch (error) {
197
+ if (isNotFoundError(error)) return undefined;
198
+ throw new Error(`Failed to inspect async output file '${outputFile}': ${getErrorMessage(error)}`, {
199
+ cause: error instanceof Error ? error : undefined,
200
+ });
201
+ }
202
+ }
203
+
204
+ function deriveAsyncActivityState(asyncDir: string, status: AsyncStatus): { activityState?: ActivityState; lastActivityAt?: number } {
205
+ if (status.state !== "running") return { activityState: status.activityState, lastActivityAt: status.lastActivityAt };
206
+ const outputPath = status.outputFile ? (path.isAbsolute(status.outputFile) ? status.outputFile : path.join(asyncDir, status.outputFile)) : undefined;
207
+ const currentStep = typeof status.currentStep === "number" ? status.steps?.[status.currentStep] : undefined;
208
+ return {
209
+ activityState: status.activityState,
210
+ lastActivityAt: status.lastActivityAt
211
+ ?? outputFileMtime(outputPath)
212
+ ?? currentStep?.lastActivityAt
213
+ ?? (status.mode === "workflow" ? undefined : currentStep?.startedAt ?? status.startedAt),
214
+ };
215
+ }
216
+
217
+ function statusToSummary(asyncDir: string, status: AsyncStatus & { cwd?: string }, nestedWarnings: string[] = [], nestedRoute?: NestedRoute): AsyncRunSummary {
218
+ if (status.sessionId !== undefined && typeof status.sessionId !== "string") {
219
+ throw new Error(`Invalid async status '${path.join(asyncDir, "status.json")}': sessionId must be a string.`);
220
+ }
221
+ const { activityState, lastActivityAt } = deriveAsyncActivityState(asyncDir, status);
222
+ const processTerminal = readProcessTerminal(asyncDir, { runId: status.runId, runnerProcessInstanceId: status.processTerminal?.runnerProcessInstanceId })
223
+ ?? sanitizeProcessTerminal(status.processTerminal, { runId: status.runId, runnerProcessInstanceId: status.processTerminal?.runnerProcessInstanceId }, path.join(asyncDir, "status.json"));
224
+ const steps = status.steps ?? [];
225
+ const chainStepCount = status.chainStepCount ?? steps.length;
226
+ const parallelGroups = normalizeParallelGroups(status.parallelGroups, steps.length, chainStepCount);
227
+ let nestedChildren: NestedRunSummary[] = [];
228
+ if (nestedWarnings.length === 0 && nestedRoute) {
229
+ try {
230
+ // The route is resolved by the caller via buildNestedRouteIndex, so this
231
+ // avoids a fresh scan of the nested-events directory per run.
232
+ nestedChildren = projectNestedEvents(nestedRoute)?.children ?? [];
233
+ } catch (error) {
234
+ nestedWarnings.push(`Nested status unavailable: ${getErrorMessage(error)}`);
235
+ }
236
+ }
237
+ const summarizedSteps = steps.map((step, index) => {
238
+ const stepActivityState = step.activityState;
239
+ const stepLastActivityAt = step.lastActivityAt;
240
+ return {
241
+ index,
242
+ agent: step.agent,
243
+ ...(step.context ? { context: step.context } : {}),
244
+ ...(step.label ? { label: step.label } : {}),
245
+ ...(step.description ? { description: step.description } : {}),
246
+ ...(step.phase ? { phase: step.phase } : {}),
247
+ ...(step.outputName ? { outputName: step.outputName } : {}),
248
+ ...(step.structured ? { structured: step.structured } : {}),
249
+ ...(step.checkpoint ? { checkpoint: step.checkpoint } : {}),
250
+ status: step.status,
251
+ ...(stepActivityState ? { activityState: stepActivityState } : {}),
252
+ ...(stepLastActivityAt ? { lastActivityAt: stepLastActivityAt } : {}),
253
+ ...(step.currentTool ? { currentTool: step.currentTool } : {}),
254
+ ...(step.currentToolArgs ? { currentToolArgs: step.currentToolArgs } : {}),
255
+ ...(step.currentToolStartedAt ? { currentToolStartedAt: step.currentToolStartedAt } : {}),
256
+ ...(step.currentPath ? { currentPath: step.currentPath } : {}),
257
+ ...(step.recentTools ? { recentTools: step.recentTools.map((tool) => ({ ...tool })) } : {}),
258
+ ...(step.recentOutput ? { recentOutput: [...step.recentOutput] } : {}),
259
+ ...(step.turnCount !== undefined ? { turnCount: step.turnCount } : {}),
260
+ ...(step.toolCount !== undefined ? { toolCount: step.toolCount } : {}),
261
+ ...(step.steering ? { steering: step.steering } : {}),
262
+ ...(step.durationMs !== undefined ? { durationMs: step.durationMs } : {}),
263
+ ...(step.tokens ? { tokens: step.tokens } : {}),
264
+ ...(step.totalCost ? { totalCost: step.totalCost } : {}),
265
+ ...(step.skills ? { skills: step.skills } : {}),
266
+ ...(step.model ? { model: step.model } : {}),
267
+ ...(step.thinking ? { thinking: step.thinking } : {}),
268
+ ...(step.attemptedModels ? { attemptedModels: step.attemptedModels } : {}),
269
+ ...(step.sessionFile ? { sessionFile: step.sessionFile } : {}),
270
+ ...(step.transcriptPath ? { transcriptPath: step.transcriptPath } : {}),
271
+ ...(step.error ? { error: step.error } : {}),
272
+ ...(step.timedOut !== undefined ? { timedOut: step.timedOut } : {}),
273
+ ...(step.stopped !== undefined ? { stopped: step.stopped } : {}),
274
+ ...(step.turnBudget ? { turnBudget: step.turnBudget } : {}),
275
+ ...(step.turnBudgetExceeded !== undefined ? { turnBudgetExceeded: step.turnBudgetExceeded } : {}),
276
+ ...(step.wrapUpRequested !== undefined ? { wrapUpRequested: step.wrapUpRequested } : {}),
277
+ ...(step.acceptance ? { acceptance: step.acceptance } : {}),
278
+ ...(step.agentContract ? { agentContract: step.agentContract } : {}),
279
+ ...(step.launchContractDigest ? { launchContractDigest: step.launchContractDigest } : {}),
280
+ ...(step.launchResolvedExtensions ? { launchResolvedExtensions: step.launchResolvedExtensions } : {}),
281
+ ...(step.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: step.runtimeAcknowledgedExtensions } : {}),
282
+ ...(step.execution ? { execution: step.execution } : {}),
283
+ ...(step.review ? { review: step.review } : {}),
284
+ ...(step.effects ? { effects: step.effects } : {}),
285
+ ...(step.processTerminal ? { processTerminal: sanitizeProcessTerminal(step.processTerminal, { runId: status.runId, runnerProcessInstanceId: step.processTerminal.runnerProcessInstanceId }, `${path.join(asyncDir, "status.json")} step ${index}`) } : {}),
286
+ ...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),
287
+ ...(step.capabilityAudit ? { capabilityAudit: step.capabilityAudit } : {}),
288
+ ...(step.children?.length ? { children: step.children } : {}),
289
+ };
290
+ });
291
+ attachRootChildrenToSteps(status.runId || path.basename(asyncDir), summarizedSteps, nestedChildren);
292
+ return {
293
+ id: status.runId || path.basename(asyncDir),
294
+ asyncDir,
295
+ ...(status.toolCallId ? { toolCallId: status.toolCallId } : {}),
296
+ ...(status.sessionId ? { sessionId: status.sessionId } : {}),
297
+ state: status.state,
298
+ ...(status.error ? { error: status.error } : {}),
299
+ activityState,
300
+ lastActivityAt,
301
+ currentTool: status.currentTool,
302
+ currentToolStartedAt: status.currentToolStartedAt,
303
+ currentPath: status.currentPath,
304
+ turnCount: status.turnCount,
305
+ toolCount: status.toolCount,
306
+ steering: status.steering,
307
+ mode: status.mode,
308
+ ...(summarizeContextModes(summarizedSteps.map((step) => step.context)) ? { context: summarizeContextModes(summarizedSteps.map((step) => step.context)) } : {}),
309
+ cwd: status.cwd,
310
+ startedAt: status.startedAt,
311
+ lastUpdate: status.lastUpdate,
312
+ endedAt: status.endedAt,
313
+ ...(status.timeoutMs !== undefined ? { timeoutMs: status.timeoutMs } : {}),
314
+ ...(status.deadlineAt !== undefined ? { deadlineAt: status.deadlineAt } : {}),
315
+ ...(status.timedOut !== undefined ? { timedOut: status.timedOut } : {}),
316
+ ...(status.stopped !== undefined ? { stopped: status.stopped } : {}),
317
+ ...(status.turnBudget ? { turnBudget: status.turnBudget } : {}),
318
+ ...(status.turnBudgetExceeded !== undefined ? { turnBudgetExceeded: status.turnBudgetExceeded } : {}),
319
+ ...(status.wrapUpRequested !== undefined ? { wrapUpRequested: status.wrapUpRequested } : {}),
320
+ currentStep: status.currentStep,
321
+ ...(status.chainStepCount !== undefined ? { chainStepCount: status.chainStepCount } : {}),
322
+ ...(status.pendingAppends !== undefined ? { pendingAppends: status.pendingAppends } : {}),
323
+ ...(parallelGroups.length ? { parallelGroups } : {}),
324
+ steps: summarizedSteps,
325
+ ...(status.checkpoint ? { checkpoint: status.checkpoint } : {}),
326
+ ...(nestedChildren.length ? { nestedChildren } : {}),
327
+ ...(nestedWarnings.length ? { nestedWarnings } : {}),
328
+ ...(processTerminal ? { processTerminal } : {}),
329
+ ...(status.launchContractDigest ? { launchContractDigest: status.launchContractDigest } : {}),
330
+ ...(status.launchResolvedExtensions ? { launchResolvedExtensions: status.launchResolvedExtensions } : {}),
331
+ ...(status.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: status.runtimeAcknowledgedExtensions } : {}),
332
+ ...(status.capabilityCeiling ? { capabilityCeiling: status.capabilityCeiling } : {}),
333
+ ...(status.capabilityAudit ? { capabilityAudit: status.capabilityAudit } : {}),
334
+ ...(status.parentWorkflowRunId ? { parentWorkflowRunId: status.parentWorkflowRunId } : {}),
335
+ ...(status.workflowKey ? { workflowKey: status.workflowKey } : {}),
336
+ ...(status.workflow ? { workflow: status.workflow } : {}),
337
+ ...(status.sessionDir ? { sessionDir: status.sessionDir } : {}),
338
+ ...(status.outputFile ? { outputFile: status.outputFile } : {}),
339
+ ...(status.totalTokens ? { totalTokens: status.totalTokens } : {}),
340
+ ...(status.totalCost ? { totalCost: status.totalCost } : {}),
341
+ ...(status.usageBudget ? { usageBudget: status.usageBudget } : {}),
342
+ ...(status.sessionFile ? { sessionFile: status.sessionFile } : {}),
343
+ };
344
+ }
345
+
346
+ export function summarizeAsyncStatus(asyncDir: string, status: AsyncStatus & { cwd?: string }): AsyncRunSummary {
347
+ return statusToSummary(asyncDir, status);
348
+ }
349
+
350
+ function sortRuns(runs: AsyncRunSummary[]): AsyncRunSummary[] {
351
+ const rank = (state: AsyncRunSummary["state"]): number => {
352
+ switch (state) {
353
+ case "running": return 0;
354
+ case "queued": return 1;
355
+ case "failed": return 2;
356
+ case "stopped": return 2;
357
+ case "paused": return 2;
358
+ case "complete": return 3;
359
+ default: return 4;
360
+ }
361
+ };
362
+ return [...runs].sort((a, b) => {
363
+ const byState = rank(a.state) - rank(b.state);
364
+ if (byState !== 0) return byState;
365
+ const aTime = a.lastUpdate ?? a.endedAt ?? a.startedAt;
366
+ const bTime = b.lastUpdate ?? b.endedAt ?? b.startedAt;
367
+ return bTime - aTime;
368
+ });
369
+ }
370
+
371
+ export function listAsyncRuns(asyncDirRoot: string, options: AsyncRunListOptions = {}): AsyncRunSummary[] {
372
+ let entries: string[];
373
+ try {
374
+ if (options.runId !== undefined) {
375
+ const resolution = resolveTargetedAsyncRun(asyncDirRoot, options.runId, options.sessionId);
376
+ entries = resolution.kind === "exact"
377
+ ? [resolution.id]
378
+ : resolution.kind === "scan"
379
+ ? fs.readdirSync(asyncDirRoot).filter((entry) =>
380
+ (entry === options.runId || entry.startsWith(options.runId!))
381
+ && resolveTargetedAsyncRun(asyncDirRoot, entry, options.sessionId).kind === "exact"
382
+ )
383
+ : [];
384
+ } else {
385
+ entries = fs.readdirSync(asyncDirRoot).filter((entry) => isAsyncRunDir(asyncDirRoot, entry));
386
+ }
387
+ } catch (error) {
388
+ if (isNotFoundError(error)) return [];
389
+ throw new Error(`Failed to list async runs in '${asyncDirRoot}': ${getErrorMessage(error)}`, {
390
+ cause: error instanceof Error ? error : undefined,
391
+ });
392
+ }
393
+
394
+ if (options.entryLimit !== undefined) {
395
+ const limit = Math.max(0, Math.floor(options.entryLimit));
396
+ entries = entries
397
+ .map((entry) => {
398
+ try {
399
+ return { entry, mtimeMs: fs.statSync(path.join(asyncDirRoot, entry, "status.json")).mtimeMs };
400
+ } catch (error) {
401
+ if (isNotFoundError(error)) return undefined;
402
+ throw new Error(`Failed to inspect async status file for '${entry}': ${getErrorMessage(error)}`, {
403
+ cause: error instanceof Error ? error : undefined,
404
+ });
405
+ }
406
+ })
407
+ .filter((candidate): candidate is { entry: string; mtimeMs: number } => candidate !== undefined)
408
+ .sort((left, right) => right.mtimeMs - left.mtimeMs)
409
+ .slice(0, limit)
410
+ .map((candidate) => candidate.entry);
411
+ }
412
+
413
+ const allowedStates = options.states ? new Set(options.states) : undefined;
414
+ const runs: AsyncRunSummary[] = [];
415
+ // Route resolution for every run shares a single index built from the
416
+ // nested-events directory, so the per-run lookup is O(1) instead of scanning
417
+ // the directory once per run. The index is built lazily on first use, so
418
+ // load-time restoration (which only wants queued/running runs) skips it
419
+ // entirely when no active runs match.
420
+ let nestedRouteIndex: Map<string, NestedRoute> | undefined;
421
+ const resolveNestedRoute = (rootRunId: string): NestedRoute | undefined => {
422
+ if (!nestedRouteIndex) nestedRouteIndex = buildNestedRouteIndex();
423
+ return nestedRouteIndex.get(rootRunId);
424
+ };
425
+ for (const entry of entries) {
426
+ const asyncDir = path.join(asyncDirRoot, entry);
427
+ const reconciliation = options.reconcile === false
428
+ ? undefined
429
+ : reconcileAsyncRun(asyncDir, { resultsDir: options.resultsDir, kill: options.kill, now: options.now });
430
+ const status = (reconciliation?.status ?? readStatus(asyncDir)) as (AsyncStatus & { cwd?: string }) | null;
431
+ if (!status) continue;
432
+ // Filter before the nested-route lookup: the lookup builds an index over
433
+ // the nested-events directory, so deferring it for filtered-out runs keeps
434
+ // restoration at load from scanning that directory when no active runs
435
+ // match.
436
+ if (allowedStates && !allowedStates.has(status.state)) continue;
437
+ if (options.sessionId && status.sessionId !== options.sessionId) continue;
438
+ const nestedWarnings: string[] = [];
439
+ let nestedRoute: NestedRoute | undefined;
440
+ if (options.reconcile !== false) {
441
+ try {
442
+ nestedRoute = resolveNestedRoute(status.runId || path.basename(asyncDir));
443
+ if (nestedRoute) reconcileNestedAsyncDescendants(nestedRoute, { resultsDir: options.resultsDir, kill: options.kill, now: options.now });
444
+ } catch (error) {
445
+ nestedWarnings.push(`Nested status unavailable: ${getErrorMessage(error)}`);
446
+ }
447
+ }
448
+ const summary = statusToSummary(asyncDir, status, nestedWarnings, nestedRoute);
449
+ runs.push(summary);
450
+ }
451
+
452
+ const sorted = sortRuns(runs);
453
+ return options.limit !== undefined ? sorted.slice(0, options.limit) : sorted;
454
+ }
455
+
456
+ function formatActivityFacts(input: { activityState?: ActivityState; lastActivityAt?: number; currentTool?: string; currentToolStartedAt?: number; currentPath?: string; turnCount?: number; toolCount?: number; steering?: SteeringStatus; turnBudget?: TurnBudgetState; turnBudgetExceeded?: boolean; wrapUpRequested?: boolean }): string | undefined {
457
+ const facts: string[] = [];
458
+ if (input.currentTool && input.currentToolStartedAt !== undefined) facts.push(`tool ${input.currentTool} ${formatDuration(Math.max(0, Date.now() - input.currentToolStartedAt))}`);
459
+ else if (input.currentTool) facts.push(`tool ${input.currentTool}`);
460
+ if (input.currentPath) facts.push(shortenPath(input.currentPath));
461
+ if (input.turnCount !== undefined) facts.push(`${input.turnCount} turns`);
462
+ if (input.turnBudgetExceeded && input.turnBudget) facts.push(`turn budget exceeded ${input.turnBudget.turnCount}/${input.turnBudget.maxTurns}+${input.turnBudget.graceTurns}`);
463
+ else if (input.turnBudget?.outcome === "termination-deferred") facts.push(`turn-budget termination deferred ${input.turnBudget.turnCount}/${input.turnBudget.maxTurns}+${input.turnBudget.graceTurns}`);
464
+ else if (input.wrapUpRequested && input.turnBudget) facts.push(`wrap-up requested ${input.turnBudget.turnCount}/${input.turnBudget.maxTurns}`);
465
+ else if (input.turnBudget) facts.push(`turn budget ${input.turnBudget.turnCount}/${input.turnBudget.maxTurns}+${input.turnBudget.graceTurns}`);
466
+ if (input.toolCount !== undefined) facts.push(`${input.toolCount} tools`);
467
+ if (input.steering) facts.push(`steering ${input.steering.scheduled} scheduled, ${input.steering.pending} pending, ${input.steering.delivered} delivered, ${input.steering.failed} failed, ${input.steering.recovered} recovered`);
468
+ const activity = formatActivityLabel(input.lastActivityAt, input.activityState);
469
+ return activity || facts.length ? [activity, ...facts].filter(Boolean).join(" | ") : undefined;
470
+ }
471
+
472
+ function formatStepLine(step: AsyncRunStepSummary): string {
473
+ const display = step.label ? `${step.label} (${step.agent})` : step.agent;
474
+ const context = contextModeLabel(step.context);
475
+ const phase = step.phase ? `[${step.phase}] ` : "";
476
+ const parts = [`${step.index + 1}. ${phase}${display}${context ? ` ${context}` : ""}`, step.status];
477
+ const activity = formatActivityFacts(step);
478
+ if (activity) parts.push(activity);
479
+ const modelThinking = formatModelThinking(step.model, step.thinking);
480
+ if (modelThinking) parts.push(modelThinking);
481
+ if (step.durationMs !== undefined) parts.push(formatDuration(step.durationMs));
482
+ if (step.tokens) parts.push(`${formatTokens(step.tokens.total)} tok`);
483
+ return parts.join(" | ");
484
+ }
485
+
486
+ export function formatAsyncRunOutputPath(run: Pick<AsyncRunSummary, "asyncDir" | "outputFile">): string | undefined {
487
+ if (!run.outputFile) return undefined;
488
+ return path.isAbsolute(run.outputFile) ? run.outputFile : path.join(run.asyncDir, run.outputFile);
489
+ }
490
+
491
+ export function formatAsyncRunProgressLabel(run: Pick<AsyncRunSummary, "mode" | "state" | "currentStep" | "chainStepCount" | "parallelGroups" | "steps">): string {
492
+ const stepCount = run.steps.length || 1;
493
+ const chainStepCount = run.chainStepCount ?? stepCount;
494
+ const groups = normalizeParallelGroups(run.parallelGroups, run.steps.length, chainStepCount);
495
+ const activeGroup = run.currentStep !== undefined
496
+ ? groups.find((group) => run.currentStep! >= group.start && run.currentStep! < group.start + group.count)
497
+ : undefined;
498
+ if (activeGroup) {
499
+ const groupSteps = run.steps.slice(activeGroup.start, activeGroup.start + activeGroup.count);
500
+ const groupLabel = formatParallelOutcome(groupSteps, activeGroup.count, { showRunning: run.state === "running" });
501
+ if (run.mode === "parallel") return groupLabel;
502
+ return `step ${activeGroup.stepIndex + 1}/${chainStepCount} · parallel group: ${groupLabel}`;
503
+ }
504
+ if (run.mode === "parallel") return formatParallelOutcome(run.steps, stepCount, { showRunning: run.state === "running" });
505
+ if (run.mode === "chain" && run.currentStep !== undefined && groups.length > 0) {
506
+ const logicalStep = flatToLogicalStepIndex(run.currentStep, chainStepCount, groups);
507
+ return `step ${logicalStep + 1}/${chainStepCount}`;
508
+ }
509
+ return run.currentStep !== undefined ? `step ${run.currentStep + 1}/${stepCount}` : `steps ${stepCount}`;
510
+ }
511
+
512
+ function formatRunHeader(run: AsyncRunSummary): string {
513
+ const stepLabel = formatAsyncRunProgressLabel(run);
514
+ const cwd = run.cwd ? shortenPath(run.cwd) : shortenPath(run.asyncDir);
515
+ const activity = formatActivityFacts(run);
516
+ const pending = run.pendingAppends ? ` | ${run.pendingAppends} pending append${run.pendingAppends === 1 ? "" : "s"}` : "";
517
+ const context = contextModeLabel(run.context);
518
+ return `${run.id} | ${run.state}${activity ? ` | ${activity}` : ""} | ${run.mode}${context ? ` ${context}` : ""} | ${stepLabel}${pending} | ${cwd}`;
519
+ }
520
+
521
+ export function formatAsyncRunList(runs: AsyncRunSummary[], heading = "Active async runs"): string {
522
+ if (runs.length === 0) return `No ${heading.toLowerCase()}.`;
523
+
524
+ const lines = [`${heading}: ${runs.length}`, ""];
525
+ for (const run of runs) {
526
+ lines.push(`- ${formatRunHeader(run)}`);
527
+ for (const step of run.steps) {
528
+ lines.push(` ${formatStepLine(step)}`);
529
+ lines.push(...formatNestedRunStatusLines(step.children, { indent: " ", maxLines: 12 }));
530
+ }
531
+ const attached = new Set(run.steps.flatMap((step) => step.children?.map((child) => child.id) ?? []));
532
+ const unattached = run.nestedChildren?.filter((child) => !attached.has(child.id)) ?? [];
533
+ lines.push(...formatNestedRunStatusLines(unattached, { indent: " ", maxLines: 12 }));
534
+ if (run.error) lines.push(` Error: ${run.error}`);
535
+ for (const warning of run.nestedWarnings ?? []) lines.push(` Warning: ${warning}`);
536
+ const outputPath = formatAsyncRunOutputPath(run);
537
+ if (outputPath) lines.push(` output: ${shortenPath(outputPath)}`);
538
+ if (run.sessionFile) lines.push(` session: ${shortenPath(run.sessionFile)}`);
539
+ lines.push("");
540
+ }
541
+ return lines.join("\n").trimEnd();
542
+ }
@@ -0,0 +1,67 @@
1
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
+ import { snapshotBackgroundWork } from "../../api/background-work.ts";
3
+ import { DIRS, type Details, type SubagentState } from "../../shared/types.ts";
4
+ import { listAsyncRuns } from "./async-status.ts";
5
+ import { waitForSubagents, type SubagentWaitDeps, type SubagentWaitParams, type WaitEventBus } from "./subagent-wait.ts";
6
+
7
+ export const DEFAULT_AUTO_DRAIN_TIMEOUT_MS = 30 * 60 * 1000;
8
+
9
+ export interface AutoDrainDeps {
10
+ state: SubagentState;
11
+ events?: WaitEventBus;
12
+ timeoutMs?: number;
13
+ now?: () => number;
14
+ wait?: (
15
+ params: SubagentWaitParams,
16
+ signal: AbortSignal | undefined,
17
+ deps: SubagentWaitDeps,
18
+ ) => Promise<AgentToolResult<Details>>;
19
+ hasWork?: (sessionId: string, nowMs: number) => boolean;
20
+ }
21
+
22
+ function resultText(value: AgentToolResult<Details>): string {
23
+ return value.content.map((part) => part.type === "text" ? part.text : "").join(" ").trim();
24
+ }
25
+
26
+ function hasOutstandingWork(sessionId: string, nowMs: number): boolean {
27
+ const asyncRuns = listAsyncRuns(DIRS.async, {
28
+ states: ["queued", "running"],
29
+ sessionId,
30
+ resultsDir: DIRS.results,
31
+ now: () => nowMs,
32
+ });
33
+ return asyncRuns.length > 0 || snapshotBackgroundWork(sessionId, nowMs).items.length > 0;
34
+ }
35
+
36
+ /** Drain all work owned by the current headless session, including work added while draining. */
37
+ export async function drainOutstandingWork(deps: AutoDrainDeps): Promise<void> {
38
+ const sessionId = deps.state.currentSessionId;
39
+ if (!sessionId) throw new Error("Cannot auto-drain background work without an active session identity.");
40
+ const now = deps.now ?? Date.now;
41
+ const timeoutMs = deps.timeoutMs ?? DEFAULT_AUTO_DRAIN_TIMEOUT_MS;
42
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("Auto-drain timeoutMs must be a positive finite number.");
43
+ const deadlineAt = now() + timeoutMs;
44
+ const hasWork = deps.hasWork ?? hasOutstandingWork;
45
+ const wait = deps.wait ?? waitForSubagents;
46
+
47
+ while (hasWork(sessionId, now())) {
48
+ const remainingMs = deadlineAt - now();
49
+ if (remainingMs <= 0) {
50
+ throw new Error(`Auto-drain timed out after ${timeoutMs}ms with background work still active in session '${sessionId}'.`);
51
+ }
52
+ const waitResult = await wait(
53
+ { all: true, timeoutMs: remainingMs },
54
+ undefined,
55
+ {
56
+ state: deps.state,
57
+ events: deps.events,
58
+ now,
59
+ stopOnAttention: false,
60
+ failOnFailedRuns: true,
61
+ },
62
+ );
63
+ if (waitResult.isError) {
64
+ throw new Error(`Auto-drain failed for session '${sessionId}': ${resultText(waitResult) || "subagent_wait returned an error without details"}.`);
65
+ }
66
+ }
67
+ }