@fitchmultz/pi-subagents 0.0.0-stage → 0.44.5

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 (347) hide show
  1. package/CHANGELOG.md +1654 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1533 -2
  4. package/agents/context-builder.md +97 -0
  5. package/agents/debugger.md +51 -0
  6. package/agents/delegate.md +13 -0
  7. package/agents/fixer.md +37 -0
  8. package/agents/oracle.md +71 -0
  9. package/agents/planner.md +72 -0
  10. package/agents/researcher.md +51 -0
  11. package/agents/reviewer-claude.md +69 -0
  12. package/agents/reviewer-gpt.md +68 -0
  13. package/agents/reviewer-ponytail.md +82 -0
  14. package/agents/reviewer-security.md +81 -0
  15. package/agents/reviewer.md +69 -0
  16. package/agents/scout.md +66 -0
  17. package/agents/ui-designer.md +51 -0
  18. package/agents/watcher.md +26 -0
  19. package/agents/worker.md +46 -0
  20. package/agents/writer.md +36 -0
  21. package/dist/agents/agent-management.js +923 -0
  22. package/dist/agents/agent-scope.js +7 -0
  23. package/dist/agents/agent-selection.js +20 -0
  24. package/dist/agents/agent-serializer.js +100 -0
  25. package/dist/agents/agents.js +752 -0
  26. package/dist/agents/chain-serializer.js +367 -0
  27. package/dist/agents/frontmatter.js +21 -0
  28. package/dist/agents/identity.js +29 -0
  29. package/dist/agents/skills.js +570 -0
  30. package/dist/extension/build-info.js +1 -0
  31. package/dist/extension/compact-tools.js +112 -0
  32. package/dist/extension/config.js +22 -0
  33. package/dist/extension/control-notices.js +29 -0
  34. package/dist/extension/doctor.js +143 -0
  35. package/dist/extension/fanout-child.js +326 -0
  36. package/dist/extension/index.js +577 -0
  37. package/dist/extension/schemas.js +416 -0
  38. package/dist/extension/tool-input.js +20 -0
  39. package/dist/extension/tool-result.js +14 -0
  40. package/dist/history/canonical-result.js +81 -0
  41. package/dist/history/database.js +72 -0
  42. package/dist/history/index.js +199 -0
  43. package/dist/history/ingest.js +468 -0
  44. package/dist/history/queries.js +350 -0
  45. package/dist/history/store.js +216 -0
  46. package/dist/history/types.js +4 -0
  47. package/dist/history/worker.js +466 -0
  48. package/dist/intercom/intercom-bridge.js +112 -0
  49. package/dist/intercom/live-intercom.js +94 -0
  50. package/dist/intercom/result-intercom.js +373 -0
  51. package/dist/pi-intercom/agent-dir.js +10 -0
  52. package/dist/pi-intercom/bridge.js +750 -0
  53. package/dist/pi-intercom/broker/broker.js +426 -0
  54. package/dist/pi-intercom/broker/client.js +492 -0
  55. package/dist/pi-intercom/broker/framing.js +65 -0
  56. package/dist/pi-intercom/broker/paths.js +42 -0
  57. package/dist/pi-intercom/broker/pid.js +66 -0
  58. package/dist/pi-intercom/broker/spawn.js +221 -0
  59. package/dist/pi-intercom/config.js +102 -0
  60. package/dist/pi-intercom/index.js +2942 -0
  61. package/dist/pi-intercom/reply-tracker.js +182 -0
  62. package/dist/pi-intercom/session-targets.js +128 -0
  63. package/dist/pi-intercom/subagent-live-events.js +132 -0
  64. package/dist/pi-intercom/topics.js +157 -0
  65. package/dist/pi-intercom/types.js +163 -0
  66. package/dist/pi-intercom/ui/compose.js +269 -0
  67. package/dist/pi-intercom/ui/inline-message.js +80 -0
  68. package/dist/pi-intercom/ui/session-list.js +124 -0
  69. package/dist/runs/background/async-control.js +95 -0
  70. package/dist/runs/background/async-execution.js +676 -0
  71. package/dist/runs/background/async-job-tracker.js +383 -0
  72. package/dist/runs/background/async-result-file.js +58 -0
  73. package/dist/runs/background/async-resume.js +305 -0
  74. package/dist/runs/background/async-status.js +442 -0
  75. package/dist/runs/background/completion-dedupe.js +69 -0
  76. package/dist/runs/background/completion-delivery.js +245 -0
  77. package/dist/runs/background/notify.js +71 -0
  78. package/dist/runs/background/parallel-groups.js +55 -0
  79. package/dist/runs/background/result-watcher.js +426 -0
  80. package/dist/runs/background/run-id-resolver.js +64 -0
  81. package/dist/runs/background/run-status.js +382 -0
  82. package/dist/runs/background/stale-run-reconciler.js +335 -0
  83. package/dist/runs/background/subagent-runner-launcher.js +55 -0
  84. package/dist/runs/background/subagent-runner.js +1872 -0
  85. package/dist/runs/background/top-level-async.js +5 -0
  86. package/dist/runs/foreground/chain-clarify.js +1152 -0
  87. package/dist/runs/foreground/clarify-invocation.js +72 -0
  88. package/dist/runs/foreground/execution-input.js +423 -0
  89. package/dist/runs/foreground/foreground-control.js +817 -0
  90. package/dist/runs/foreground/question-control.js +88 -0
  91. package/dist/runs/foreground/run-async-path.js +205 -0
  92. package/dist/runs/foreground/subagent-executor.js +442 -0
  93. package/dist/runs/foreground/subagent-params.js +165 -0
  94. package/dist/runs/foreground/wait-run.js +141 -0
  95. package/dist/runs/shared/acceptance-contract.js +253 -0
  96. package/dist/runs/shared/acceptance-evaluation.js +256 -0
  97. package/dist/runs/shared/acceptance-finalization.js +280 -0
  98. package/dist/runs/shared/acceptance-reports.js +147 -0
  99. package/dist/runs/shared/acceptance.js +4 -0
  100. package/dist/runs/shared/chain-outputs.js +110 -0
  101. package/dist/runs/shared/child-attempt.js +693 -0
  102. package/dist/runs/shared/child-execution-cwd.js +96 -0
  103. package/dist/runs/shared/child-observations.js +114 -0
  104. package/dist/runs/shared/claude-code.js +199 -0
  105. package/dist/runs/shared/completion-guard.js +31 -0
  106. package/dist/runs/shared/dynamic-fanout.js +274 -0
  107. package/dist/runs/shared/history-index.js +72 -0
  108. package/dist/runs/shared/mcp-direct-tool-allowlist.js +334 -0
  109. package/dist/runs/shared/model-fallback.js +185 -0
  110. package/dist/runs/shared/mutating-tool-guard.js +170 -0
  111. package/dist/runs/shared/native-finalization.js +101 -0
  112. package/dist/runs/shared/native-usage.js +153 -0
  113. package/dist/runs/shared/nested-events.js +700 -0
  114. package/dist/runs/shared/nested-path.js +48 -0
  115. package/dist/runs/shared/nested-render.js +108 -0
  116. package/dist/runs/shared/parallel-utils.js +61 -0
  117. package/dist/runs/shared/parent-receipts.js +68 -0
  118. package/dist/runs/shared/parent-usage.js +121 -0
  119. package/dist/runs/shared/pi-args.js +310 -0
  120. package/dist/runs/shared/pi-spawn.js +52 -0
  121. package/dist/runs/shared/run-history-queries.js +45 -0
  122. package/dist/runs/shared/run-history.js +110 -0
  123. package/dist/runs/shared/run-id-ambiguity.js +4 -0
  124. package/dist/runs/shared/run-records.js +679 -0
  125. package/dist/runs/shared/session-cwd-preload.js +33 -0
  126. package/dist/runs/shared/single-output.js +222 -0
  127. package/dist/runs/shared/streaming-text.js +15 -0
  128. package/dist/runs/shared/structured-output.js +55 -0
  129. package/dist/runs/shared/subagent-control.js +179 -0
  130. package/dist/runs/shared/subagent-prompt-runtime.js +197 -0
  131. package/dist/runs/shared/subagent-tool-loop-guard.js +66 -0
  132. package/dist/runs/shared/supervisor-questions.js +350 -0
  133. package/dist/runs/shared/workflow-graph.js +214 -0
  134. package/dist/runs/shared/workflow-policy.js +84 -0
  135. package/dist/runs/shared/worktree.js +525 -0
  136. package/dist/shared/agent-context-policy.js +126 -0
  137. package/dist/shared/artifacts.js +96 -0
  138. package/dist/shared/atomic-json.js +13 -0
  139. package/dist/shared/cooperative.js +20 -0
  140. package/dist/shared/execution-cwd.js +14 -0
  141. package/dist/shared/file-coalescer.js +21 -0
  142. package/dist/shared/fork-context.js +49 -0
  143. package/dist/shared/formatters.js +85 -0
  144. package/dist/shared/journal-reader.js +407 -0
  145. package/dist/shared/lazy-tools.js +32 -0
  146. package/dist/shared/model-info.js +68 -0
  147. package/dist/shared/native-session.js +15 -0
  148. package/dist/shared/native-tui.js +18 -0
  149. package/dist/shared/native-typebox.js +20 -0
  150. package/dist/shared/post-exit-stdio-guard.js +197 -0
  151. package/dist/shared/prompt-sections.js +8 -0
  152. package/dist/shared/session-entries.js +52 -0
  153. package/dist/shared/session-identity.js +14 -0
  154. package/dist/shared/settings.js +254 -0
  155. package/dist/shared/status-format.js +111 -0
  156. package/dist/shared/temp-root.js +114 -0
  157. package/dist/shared/types.js +207 -0
  158. package/dist/shared/ui-mode.js +3 -0
  159. package/dist/shared/utils.js +334 -0
  160. package/dist/slash/prompt-template-bridge.js +298 -0
  161. package/dist/slash/slash-bridge.js +116 -0
  162. package/dist/slash/slash-commands.js +607 -0
  163. package/dist/slash/slash-live-state.js +246 -0
  164. package/dist/tui/action-hints.js +75 -0
  165. package/dist/tui/agent-history.js +197 -0
  166. package/dist/tui/agent-view.js +1656 -0
  167. package/dist/tui/render.js +1515 -0
  168. package/docs/intercom-bridge.md +212 -0
  169. package/docs/intercom.md +581 -0
  170. package/docs/performance.md +121 -0
  171. package/package.json +102 -4
  172. package/prompts/gather-context-and-clarify.md +14 -0
  173. package/prompts/parallel-cleanup.md +62 -0
  174. package/prompts/parallel-context-build.md +56 -0
  175. package/prompts/parallel-handoff-plan.md +62 -0
  176. package/prompts/parallel-research.md +51 -0
  177. package/prompts/parallel-review.md +59 -0
  178. package/prompts/review-loop.md +42 -0
  179. package/scripts/build.mjs +134 -0
  180. package/scripts/check-compat.mjs +48 -0
  181. package/scripts/compat-host.mjs +19 -0
  182. package/scripts/intercom-bridge-credentials.mjs +143 -0
  183. package/scripts/intercom-remote.mjs +103 -0
  184. package/scripts/linux-smoke.sh +51 -0
  185. package/scripts/local-install-smoke.mjs +66 -0
  186. package/scripts/native-package-smoke.mjs +82 -0
  187. package/scripts/package-smoke.mjs +209 -0
  188. package/scripts/prepare.mjs +67 -0
  189. package/scripts/real-pi-smoke.mjs +415 -0
  190. package/scripts/run-tests.mjs +149 -0
  191. package/skills/pi-intercom/SKILL.md +113 -0
  192. package/skills/pi-intercom/evals/evals.json +29 -0
  193. package/skills/pi-intercom/evals/trigger-evals.json +47 -0
  194. package/skills/pi-intercom/references/peer-sessions.md +69 -0
  195. package/skills/pi-subagents/SKILL.md +76 -0
  196. package/skills/pi-subagents/evals/evals.json +29 -0
  197. package/skills/pi-subagents/evals/trigger-evals.json +42 -0
  198. package/skills/pi-subagents/references/full-orchestration-guide.md +863 -0
  199. package/src/agents/agent-management.ts +813 -0
  200. package/src/agents/agent-scope.ts +7 -0
  201. package/src/agents/agent-selection.ts +23 -0
  202. package/src/agents/agent-serializer.ts +99 -0
  203. package/src/agents/agents.ts +916 -0
  204. package/src/agents/chain-serializer.ts +329 -0
  205. package/src/agents/frontmatter.ts +21 -0
  206. package/src/agents/identity.ts +30 -0
  207. package/src/agents/skills.ts +637 -0
  208. package/src/extension/build-info.ts +2 -0
  209. package/src/extension/compact-tools.ts +114 -0
  210. package/src/extension/config.ts +23 -0
  211. package/src/extension/control-notices.ts +47 -0
  212. package/src/extension/doctor.ts +171 -0
  213. package/src/extension/fanout-child.ts +312 -0
  214. package/src/extension/index.ts +649 -0
  215. package/src/extension/schemas.ts +444 -0
  216. package/src/extension/tool-input.ts +19 -0
  217. package/src/extension/tool-result.ts +16 -0
  218. package/src/history/canonical-result.ts +62 -0
  219. package/src/history/database.ts +59 -0
  220. package/src/history/index.ts +156 -0
  221. package/src/history/ingest.ts +349 -0
  222. package/src/history/queries.ts +241 -0
  223. package/src/history/store.ts +203 -0
  224. package/src/history/types.ts +166 -0
  225. package/src/history/worker.ts +321 -0
  226. package/src/intercom/intercom-bridge.ts +123 -0
  227. package/src/intercom/live-intercom.ts +104 -0
  228. package/src/intercom/result-intercom.ts +429 -0
  229. package/src/pi-intercom/agent-dir.ts +9 -0
  230. package/src/pi-intercom/bridge.ts +668 -0
  231. package/src/pi-intercom/broker/broker.ts +463 -0
  232. package/src/pi-intercom/broker/client.ts +558 -0
  233. package/src/pi-intercom/broker/framing.ts +77 -0
  234. package/src/pi-intercom/broker/paths.ts +47 -0
  235. package/src/pi-intercom/broker/pid.ts +59 -0
  236. package/src/pi-intercom/broker/spawn.ts +248 -0
  237. package/src/pi-intercom/config.ts +142 -0
  238. package/src/pi-intercom/index.ts +2929 -0
  239. package/src/pi-intercom/reply-tracker.ts +211 -0
  240. package/src/pi-intercom/session-targets.ts +172 -0
  241. package/src/pi-intercom/subagent-live-events.ts +133 -0
  242. package/src/pi-intercom/topics.ts +125 -0
  243. package/src/pi-intercom/types.ts +271 -0
  244. package/src/pi-intercom/ui/compose.ts +289 -0
  245. package/src/pi-intercom/ui/inline-message.ts +92 -0
  246. package/src/pi-intercom/ui/session-list.ts +139 -0
  247. package/src/runs/background/async-control.ts +89 -0
  248. package/src/runs/background/async-execution.ts +850 -0
  249. package/src/runs/background/async-job-tracker.ts +385 -0
  250. package/src/runs/background/async-result-file.ts +62 -0
  251. package/src/runs/background/async-resume.ts +333 -0
  252. package/src/runs/background/async-status.ts +481 -0
  253. package/src/runs/background/completion-dedupe.ts +79 -0
  254. package/src/runs/background/completion-delivery.ts +195 -0
  255. package/src/runs/background/notify.ts +123 -0
  256. package/src/runs/background/parallel-groups.ts +53 -0
  257. package/src/runs/background/result-watcher.ts +423 -0
  258. package/src/runs/background/run-id-resolver.ts +69 -0
  259. package/src/runs/background/run-status.ts +384 -0
  260. package/src/runs/background/stale-run-reconciler.ts +369 -0
  261. package/src/runs/background/subagent-runner-launcher.ts +56 -0
  262. package/src/runs/background/subagent-runner.ts +2053 -0
  263. package/src/runs/background/top-level-async.ts +13 -0
  264. package/src/runs/foreground/chain-clarify.ts +1340 -0
  265. package/src/runs/foreground/clarify-invocation.ts +77 -0
  266. package/src/runs/foreground/execution-input.ts +467 -0
  267. package/src/runs/foreground/foreground-control.ts +821 -0
  268. package/src/runs/foreground/question-control.ts +82 -0
  269. package/src/runs/foreground/run-async-path.ts +243 -0
  270. package/src/runs/foreground/subagent-executor.ts +501 -0
  271. package/src/runs/foreground/subagent-params.ts +320 -0
  272. package/src/runs/foreground/wait-run.ts +124 -0
  273. package/src/runs/shared/acceptance-contract.ts +257 -0
  274. package/src/runs/shared/acceptance-evaluation.ts +275 -0
  275. package/src/runs/shared/acceptance-finalization.ts +353 -0
  276. package/src/runs/shared/acceptance-reports.ts +152 -0
  277. package/src/runs/shared/acceptance.ts +33 -0
  278. package/src/runs/shared/chain-outputs.ts +114 -0
  279. package/src/runs/shared/child-attempt.ts +623 -0
  280. package/src/runs/shared/child-execution-cwd.ts +91 -0
  281. package/src/runs/shared/child-observations.ts +99 -0
  282. package/src/runs/shared/claude-code.ts +243 -0
  283. package/src/runs/shared/completion-guard.ts +35 -0
  284. package/src/runs/shared/dynamic-fanout.ts +295 -0
  285. package/src/runs/shared/history-index.ts +69 -0
  286. package/src/runs/shared/mcp-direct-tool-allowlist.ts +376 -0
  287. package/src/runs/shared/model-fallback.ts +219 -0
  288. package/src/runs/shared/mutating-tool-guard.ts +194 -0
  289. package/src/runs/shared/native-finalization.ts +128 -0
  290. package/src/runs/shared/native-usage.ts +113 -0
  291. package/src/runs/shared/nested-events.ts +752 -0
  292. package/src/runs/shared/nested-path.ts +52 -0
  293. package/src/runs/shared/nested-render.ts +119 -0
  294. package/src/runs/shared/parallel-utils.ts +153 -0
  295. package/src/runs/shared/parent-receipts.ts +59 -0
  296. package/src/runs/shared/parent-usage.ts +121 -0
  297. package/src/runs/shared/pi-args.ts +350 -0
  298. package/src/runs/shared/pi-spawn.ts +52 -0
  299. package/src/runs/shared/run-history-queries.ts +44 -0
  300. package/src/runs/shared/run-history.ts +100 -0
  301. package/src/runs/shared/run-id-ambiguity.ts +4 -0
  302. package/src/runs/shared/run-records.ts +607 -0
  303. package/src/runs/shared/session-cwd-preload.ts +27 -0
  304. package/src/runs/shared/single-output.ts +267 -0
  305. package/src/runs/shared/streaming-text.ts +18 -0
  306. package/src/runs/shared/structured-output.ts +68 -0
  307. package/src/runs/shared/subagent-control.ts +219 -0
  308. package/src/runs/shared/subagent-prompt-runtime.ts +201 -0
  309. package/src/runs/shared/subagent-tool-loop-guard.ts +89 -0
  310. package/src/runs/shared/supervisor-questions.ts +415 -0
  311. package/src/runs/shared/workflow-graph.ts +220 -0
  312. package/src/runs/shared/workflow-policy.ts +125 -0
  313. package/src/runs/shared/worktree.ts +635 -0
  314. package/src/shared/agent-context-policy.ts +184 -0
  315. package/src/shared/artifacts.ts +95 -0
  316. package/src/shared/atomic-json.ts +16 -0
  317. package/src/shared/cooperative.ts +21 -0
  318. package/src/shared/execution-cwd.ts +14 -0
  319. package/src/shared/file-coalescer.ts +29 -0
  320. package/src/shared/fork-context.ts +68 -0
  321. package/src/shared/formatters.ts +84 -0
  322. package/src/shared/journal-reader.ts +333 -0
  323. package/src/shared/lazy-tools.ts +36 -0
  324. package/src/shared/model-info.ts +81 -0
  325. package/src/shared/native-session.ts +8 -0
  326. package/src/shared/native-tui.ts +10 -0
  327. package/src/shared/native-typebox.ts +14 -0
  328. package/src/shared/post-exit-stdio-guard.ts +204 -0
  329. package/src/shared/prompt-sections.ts +10 -0
  330. package/src/shared/session-entries.ts +49 -0
  331. package/src/shared/session-identity.ts +18 -0
  332. package/src/shared/settings.ts +384 -0
  333. package/src/shared/status-format.ts +123 -0
  334. package/src/shared/temp-root.ts +107 -0
  335. package/src/shared/types.ts +1260 -0
  336. package/src/shared/ui-mode.ts +5 -0
  337. package/src/shared/utils.ts +342 -0
  338. package/src/slash/prompt-template-bridge.ts +408 -0
  339. package/src/slash/slash-bridge.ts +178 -0
  340. package/src/slash/slash-commands.ts +617 -0
  341. package/src/slash/slash-live-state.ts +292 -0
  342. package/src/tui/action-hints.ts +69 -0
  343. package/src/tui/agent-history.ts +210 -0
  344. package/src/tui/agent-view.ts +1323 -0
  345. package/src/tui/render.ts +1550 -0
  346. package/tsconfig.build.json +12 -0
  347. package/tsconfig.json +19 -0
@@ -0,0 +1,333 @@
1
+ import * as fs from "node:fs";
2
+ import { formatRunIdAmbiguity } from "../shared/run-id-ambiguity.ts";
3
+ import * as path from "node:path";
4
+ import { ASYNC_DIR, RESULTS_DIR, type AsyncStatus, type ResolvedAcceptanceConfig } from "../../shared/types.ts";
5
+ import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.ts";
6
+ import { checkPidLiveness, reconcileAsyncRun } from "./stale-run-reconciler.ts";
7
+ import { isDurableRun, readAsyncResultFile, type ParsedAsyncResultFile } from "./async-result-file.ts";
8
+ import { QUESTIONS_DIR, readQuestionContract, readRunJson } from "../shared/supervisor-questions.ts";
9
+ import { readStatus } from "../../shared/utils.ts";
10
+
11
+ export interface AsyncResumeParams {
12
+ id?: string;
13
+ runId?: string;
14
+ dir?: string;
15
+ index?: number;
16
+ }
17
+
18
+ export interface AsyncResumeDeps {
19
+ asyncDirRoot?: string;
20
+ resultsDir?: string;
21
+ kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
22
+ now?: () => number;
23
+ }
24
+
25
+ export type AsyncResumeTarget = {
26
+ kind: "live" | "revive";
27
+ runId: string;
28
+ asyncDir?: string;
29
+ state: AsyncStatus["state"];
30
+ agent: string;
31
+ index: number;
32
+ intercomTarget: string;
33
+ cwd?: string;
34
+ sessionFile?: string;
35
+ effectiveAcceptance?: ResolvedAcceptanceConfig;
36
+ };
37
+
38
+ export interface AsyncRunLocation {
39
+ asyncDir: string | null;
40
+ resultPath: string | null;
41
+ resolvedId?: string;
42
+ }
43
+
44
+ export interface AsyncRunRecord {
45
+ location: AsyncRunLocation;
46
+ status: AsyncStatus | null;
47
+ durable: boolean;
48
+ }
49
+
50
+ function validateOptionalString(value: Record<string, unknown>, field: string, source: string, displayField = field): string | undefined {
51
+ const fieldValue = value[field];
52
+ if (fieldValue === undefined) return undefined;
53
+ if (typeof fieldValue !== "string") throw new Error(`Invalid async result file '${source}': ${displayField} must be a string.`);
54
+ return fieldValue;
55
+ }
56
+
57
+ function validateResultFile(data: ParsedAsyncResultFile, resultPath: string): ParsedAsyncResultFile {
58
+ if (data.results !== undefined) {
59
+ if (!Array.isArray(data.results)) throw new Error(`Invalid async result file '${resultPath}': results must be an array.`);
60
+ data.results.forEach((child, index) => {
61
+ const record = child as Record<string, unknown>;
62
+ validateOptionalString(record, "agent", resultPath, `results[${index}].agent`);
63
+ validateOptionalString(record, "sessionFile", resultPath, `results[${index}].sessionFile`);
64
+ validateOptionalString(record, "intercomTarget", resultPath, `results[${index}].intercomTarget`);
65
+ const success = child.success;
66
+ if (success !== undefined && typeof success !== "boolean") throw new Error(`Invalid async result file '${resultPath}': results[${index}].success must be a boolean.`);
67
+ });
68
+ }
69
+ const record = data as Record<string, unknown>;
70
+ const success = data.success;
71
+ if (success !== undefined && typeof success !== "boolean") throw new Error(`Invalid async result file '${resultPath}': success must be a boolean.`);
72
+ validateOptionalString(record, "id", resultPath);
73
+ validateOptionalString(record, "runId", resultPath);
74
+ validateOptionalString(record, "agent", resultPath);
75
+ validateOptionalString(record, "mode", resultPath);
76
+ validateOptionalString(record, "state", resultPath);
77
+ validateOptionalString(record, "cwd", resultPath);
78
+ validateOptionalString(record, "sessionFile", resultPath);
79
+ return data;
80
+ }
81
+
82
+ function readResultFile(resultPath: string): ParsedAsyncResultFile {
83
+ return validateResultFile(readAsyncResultFile(resultPath), resultPath);
84
+ }
85
+
86
+ function assertRunId(value: string | undefined, field: "id" | "runId"): string | undefined {
87
+ if (value === undefined) return undefined;
88
+ if (value.trim() === "") throw new Error(`${field} must not be empty.`);
89
+ if (path.isAbsolute(value) || /[\\/]/.test(value) || value.includes("..")) {
90
+ throw new Error(`${field} must be an async run id or prefix, not a path.`);
91
+ }
92
+ return value;
93
+ }
94
+
95
+ function assertInsideRoot(root: string, target: string, label: string): void {
96
+ const rootPath = path.resolve(root);
97
+ const targetPath = path.resolve(target);
98
+ const relative = path.relative(rootPath, targetPath);
99
+ if (relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative))) return;
100
+ throw new Error(`${label} must be inside ${rootPath}.`);
101
+ }
102
+
103
+ function prefixedRunIds(dir: string, prefix: string, suffix = ""): string[] {
104
+ if (!fs.existsSync(dir)) return [];
105
+ return fs.readdirSync(dir)
106
+ .filter((entry) => entry.startsWith(prefix) && (!suffix || entry.endsWith(suffix)))
107
+ .map((entry) => suffix ? entry.slice(0, -suffix.length) : entry)
108
+ .sort();
109
+ }
110
+
111
+ export function asyncRunRoots(asyncDirRoot: string): string[] {
112
+ return [...new Set([path.resolve(asyncDirRoot), path.resolve(QUESTIONS_DIR)])];
113
+ }
114
+
115
+ export function exactAsyncRunLocation(runId: string, asyncDirRoot: string, resultsDir: string): AsyncRunLocation {
116
+ return resolveAsyncRunRecord(runId, asyncDirRoot, resultsDir, false).location;
117
+ }
118
+
119
+ /** Resolve canonical precedence and decode each candidate status once for this pass. */
120
+ export function readAsyncRunRecord(runId: string, asyncDirRoot: string, resultsDir: string): AsyncRunRecord {
121
+ return resolveAsyncRunRecord(runId, asyncDirRoot, resultsDir, true);
122
+ }
123
+
124
+ function resolveAsyncRunRecord(runId: string, asyncDirRoot: string, resultsDir: string, readLegacyStatus: boolean): AsyncRunRecord {
125
+ assertRunId(runId, "id");
126
+ const durableDir = path.join(QUESTIONS_DIR, runId);
127
+ const legacyDir = path.join(asyncDirRoot, runId);
128
+ const durableStatus = readStatus(durableDir);
129
+ const durableResult = path.join(durableDir, "result.json");
130
+ const durable = isDurableRun(durableStatus) || isDurableRun(readRunJson<object>(path.join(durableDir, "launch.json")));
131
+ const asyncDir = durable ? durableDir : fs.existsSync(legacyDir) ? legacyDir : durableStatus ? durableDir : null;
132
+ const status = asyncDir === durableDir ? durableStatus : asyncDir && readLegacyStatus ? readStatus(asyncDir) : null;
133
+ return {
134
+ location: { asyncDir, resultPath: fs.existsSync(durableResult) ? durableResult : exactResultPath(resultsDir, runId), resolvedId: runId },
135
+ status,
136
+ durable: durable || isDurableRun(status),
137
+ };
138
+ }
139
+
140
+ function exactResultPath(resultsDir: string, runId: string): string | null {
141
+ const resultPath = path.join(resultsDir, `${runId}.json`);
142
+ assertInsideRoot(resultsDir, resultPath, "Async result file");
143
+ return fs.existsSync(resultPath) ? resultPath : null;
144
+ }
145
+
146
+ export function findAsyncRunPrefixMatches(prefix: string, asyncDirRoot: string, resultsDir: string): Array<{ id: string; location: AsyncRunLocation }> {
147
+ const requestedId = assertRunId(prefix, "id");
148
+ if (!requestedId) return [];
149
+ const asyncRoot = path.resolve(asyncDirRoot);
150
+ const resultRoot = path.resolve(resultsDir);
151
+ const matchingIds = [...new Set([
152
+ ...prefixedRunIds(asyncRoot, requestedId),
153
+ ...prefixedRunIds(QUESTIONS_DIR, requestedId).filter((id) => fs.existsSync(path.join(QUESTIONS_DIR, id, "status.json")) || fs.existsSync(path.join(QUESTIONS_DIR, id, "result.json")) || fs.existsSync(path.join(QUESTIONS_DIR, id, "launch.json"))),
154
+ ...prefixedRunIds(resultRoot, requestedId, ".json"),
155
+ ])].sort();
156
+ return matchingIds.map((id) => ({ id, location: exactAsyncRunLocation(id, asyncRoot, resultRoot) }));
157
+ }
158
+
159
+ export function resolveAsyncRunLocation(params: AsyncResumeParams, asyncDirRoot: string, resultsDir: string): AsyncRunLocation {
160
+ const asyncRoot = path.resolve(asyncDirRoot);
161
+ const resultRoot = path.resolve(resultsDir);
162
+ const requestedId = assertRunId(params.id, "id") ?? assertRunId(params.runId, "runId");
163
+ if (params.dir) {
164
+ const asyncDir = path.resolve(params.dir);
165
+ if (!asyncRunRoots(asyncRoot).some((root) => {
166
+ const relative = path.relative(root, asyncDir);
167
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
168
+ })) {
169
+ throw new Error(`Async run directory must be inside ${asyncRunRoots(asyncRoot).join(" or ")}.`);
170
+ }
171
+ const resolvedId = requestedId ?? path.basename(asyncDir);
172
+ if (requestedId && requestedId !== path.basename(asyncDir)) {
173
+ throw new Error(`Async run id '${requestedId}' does not match directory '${path.basename(asyncDir)}'.`);
174
+ }
175
+ const location = exactAsyncRunLocation(resolvedId, asyncRoot, resultRoot);
176
+ const canonical = location.asyncDir && isDurableRun(readRunJson<object>(path.join(location.asyncDir, "launch.json")));
177
+ return { ...location, asyncDir: canonical ? location.asyncDir : asyncDir };
178
+ }
179
+ if (!requestedId) return { asyncDir: null, resultPath: null };
180
+
181
+ const direct = exactAsyncRunLocation(requestedId, asyncRoot, resultRoot);
182
+ if (direct.asyncDir || direct.resultPath) return direct;
183
+
184
+ const matching = findAsyncRunPrefixMatches(requestedId, asyncRoot, resultRoot);
185
+ if (matching.length === 0) return { asyncDir: null, resultPath: null, resolvedId: requestedId };
186
+ if (matching.length > 1) {
187
+ throw new Error(formatRunIdAmbiguity("async", requestedId, matching.map((match) => match.id)));
188
+ }
189
+ return matching[0]!.location;
190
+ }
191
+
192
+ function validateStatusForResume(status: AsyncStatus | null, source: string): void {
193
+ if (!status) return;
194
+ if (typeof status.runId !== "string") throw new Error(`Invalid async status '${source}': runId must be a string.`);
195
+ if (status.sessionId !== undefined && typeof status.sessionId !== "string") throw new Error(`Invalid async status '${source}': sessionId must be a string.`);
196
+ if (status.cwd !== undefined && typeof status.cwd !== "string") throw new Error(`Invalid async status '${source}': cwd must be a string.`);
197
+ if (status.sessionFile !== undefined && typeof status.sessionFile !== "string") throw new Error(`Invalid async status '${source}': sessionFile must be a string.`);
198
+ if (status.steps !== undefined) {
199
+ if (!Array.isArray(status.steps)) throw new Error(`Invalid async status '${source}': steps must be an array.`);
200
+ status.steps.forEach((step, index) => {
201
+ if (!step || typeof step !== "object" || Array.isArray(step)) throw new Error(`Invalid async status '${source}': steps[${index}] must be an object.`);
202
+ if (typeof step.agent !== "string") throw new Error(`Invalid async status '${source}': steps[${index}].agent must be a string.`);
203
+ if (step.sessionFile !== undefined && typeof step.sessionFile !== "string") throw new Error(`Invalid async status '${source}': steps[${index}].sessionFile must be a string.`);
204
+ });
205
+ }
206
+ }
207
+
208
+ function validateResumeSessionFile(runId: string, sessionFile: string): string {
209
+ if (path.extname(sessionFile) !== ".jsonl") throw new Error(`Async run '${runId}' session file must be a .jsonl file: ${sessionFile}`);
210
+ const resolved = path.resolve(sessionFile);
211
+ if (!fs.existsSync(resolved)) throw new Error(`Async run '${runId}' session file does not exist: ${sessionFile}`);
212
+ return resolved;
213
+ }
214
+
215
+ export function resolveAsyncResumeTarget(params: AsyncResumeParams, deps: AsyncResumeDeps = {}): AsyncResumeTarget {
216
+ const asyncDirRoot = deps.asyncDirRoot ?? ASYNC_DIR;
217
+ const resultsDir = deps.resultsDir ?? RESULTS_DIR;
218
+ const location = resolveAsyncRunLocation(params, asyncDirRoot, resultsDir);
219
+ if (!location.asyncDir && !location.resultPath) {
220
+ throw new Error("Async run not found. Provide id or dir.");
221
+ }
222
+
223
+ const reconciliation = location.asyncDir
224
+ ? reconcileAsyncRun(location.asyncDir, { resultsDir, kill: deps.kill, now: deps.now })
225
+ : undefined;
226
+ const status = reconciliation?.status ?? null;
227
+ validateStatusForResume(status, location.asyncDir ? path.join(location.asyncDir, "status.json") : "status.json");
228
+ const result = location.resultPath ? readResultFile(location.resultPath) : undefined;
229
+ const runId = status?.runId ?? result?.runId ?? result?.id ?? location.resolvedId ?? (location.asyncDir ? path.basename(location.asyncDir) : "unknown");
230
+ const state = status?.state ?? result?.terminalState;
231
+ if (!state) throw new Error(`Status file not found for async run '${runId}'.`);
232
+
233
+ const statusSteps = status?.steps ?? [];
234
+ const resultSteps = result?.results ?? [];
235
+ const stepCount = statusSteps.length || resultSteps.length || (result?.agent ? 1 : 0);
236
+ const requestedIndex = params.index;
237
+ if (requestedIndex !== undefined && !Number.isInteger(requestedIndex)) throw new Error(`Async run '${runId}' index must be an integer.`);
238
+ const terminalStepStatuses = new Set(["complete", "completed", "failed", "blocked", "paused"]);
239
+
240
+ if (state === "running") {
241
+ if (requestedIndex !== undefined) {
242
+ if (requestedIndex < 0 || requestedIndex >= stepCount) throw new Error(`Async run '${runId}' has ${stepCount} children. Index ${requestedIndex} is out of range.`);
243
+ const selectedStep = statusSteps[requestedIndex];
244
+ if (selectedStep?.status === "running") {
245
+ return {
246
+ kind: "live",
247
+ runId,
248
+ asyncDir: location.asyncDir ?? undefined,
249
+ state,
250
+ agent: selectedStep.agent,
251
+ index: requestedIndex,
252
+ intercomTarget: resolveSubagentIntercomTarget(runId, selectedStep.agent, requestedIndex),
253
+ cwd: status?.cwd ?? result?.cwd,
254
+ sessionFile: selectedStep.sessionFile ?? status?.sessionFile ?? result?.sessionFile,
255
+ };
256
+ }
257
+ if (selectedStep?.status === "pending") throw new Error(`Async run '${runId}' child ${requestedIndex} is pending and has not started yet. Wait for it to run or complete before resuming.`);
258
+ if (selectedStep && !terminalStepStatuses.has(selectedStep.status)) throw new Error(`Async run '${runId}' child ${requestedIndex} is ${selectedStep.status} and cannot be revived yet.`);
259
+ } else {
260
+ const running = statusSteps
261
+ .map((step, index) => ({ step, index }))
262
+ .filter(({ step }) => step.status === "running");
263
+ const selected = running.length === 1 ? running[0] : undefined;
264
+ if (!selected) {
265
+ throw new Error(`Async run '${runId}' has ${running.length} running children. Provide index to choose one.`);
266
+ }
267
+ return {
268
+ kind: "live",
269
+ runId,
270
+ asyncDir: location.asyncDir ?? undefined,
271
+ state,
272
+ agent: selected.step.agent,
273
+ index: selected.index,
274
+ intercomTarget: resolveSubagentIntercomTarget(runId, selected.step.agent, selected.index),
275
+ cwd: status?.cwd ?? result?.cwd,
276
+ sessionFile: selected.step.sessionFile ?? status?.sessionFile ?? result?.sessionFile,
277
+ };
278
+ }
279
+ }
280
+
281
+ if (stepCount > 1 && requestedIndex === undefined) {
282
+ throw new Error(`Async run '${runId}' has ${stepCount} children. Provide index to choose one.`);
283
+ }
284
+ const index = requestedIndex ?? 0;
285
+ if (!Number.isInteger(index)) throw new Error(`Async run '${runId}' index must be an integer.`);
286
+ if (index < 0 || index >= stepCount) throw new Error(`Async run '${runId}' has ${stepCount} children. Index ${index} is out of range.`);
287
+ const contract = readQuestionContract(runId, index);
288
+ if (contract?.pid && checkPidLiveness(contract.pid, deps.kill) !== "dead") {
289
+ const agent = statusSteps[index]?.agent ?? resultSteps[index]?.agent ?? result?.agent ?? contract.launch?.agent.name;
290
+ if (!agent) throw new Error(`Could not determine child agent for async run '${runId}'.`);
291
+ return { kind: "live", runId, asyncDir: location.asyncDir ?? undefined, state, agent, index,
292
+ intercomTarget: resolveSubagentIntercomTarget(runId, agent, index), cwd: status?.cwd ?? result?.cwd, sessionFile: contract.sessionFile };
293
+ }
294
+ const agent = statusSteps[index]?.agent ?? resultSteps[index]?.agent ?? result?.agent;
295
+ if (!agent) throw new Error(`Could not determine child agent for async run '${runId}'.`);
296
+ const sessionFile = statusSteps[index]?.sessionFile
297
+ ?? resultSteps[index]?.sessionFile
298
+ ?? (stepCount === 1 ? status?.sessionFile ?? result?.sessionFile : undefined);
299
+ if (!sessionFile) throw new Error(`Async run '${runId}' child ${index} does not have a persisted session file to resume from.`);
300
+ const resolvedSessionFile = validateResumeSessionFile(runId, sessionFile);
301
+ const effectiveAcceptance = statusSteps[index]?.acceptance?.effectiveAcceptance
302
+ ?? resultSteps[index]?.acceptance?.effectiveAcceptance;
303
+
304
+ return {
305
+ kind: "revive",
306
+ runId,
307
+ asyncDir: location.asyncDir ?? undefined,
308
+ state,
309
+ agent,
310
+ index,
311
+ intercomTarget: resolveSubagentIntercomTarget(runId, agent, index),
312
+ cwd: status?.cwd ?? result?.cwd,
313
+ sessionFile: resolvedSessionFile,
314
+ effectiveAcceptance,
315
+ };
316
+ }
317
+
318
+ export function buildRevivedAsyncTask(target: Pick<AsyncResumeTarget, "runId" | "agent" | "sessionFile">, message: string, origin?: "human"): string {
319
+ return [
320
+ "You are reviving a previous subagent conversation.",
321
+ "",
322
+ `Original run: ${target.runId}`,
323
+ `Original agent: ${target.agent}`,
324
+ target.sessionFile ? `Original session file: ${target.sessionFile}` : undefined,
325
+ "",
326
+ origin === "human"
327
+ ? "Use the stored session context as background. This is a direct user follow-up (human origin); respond in this conversation where the user can see it. Do not relay it to the parent."
328
+ : "Use the stored session context as background. Answer the orchestrator's follow-up below. Do not assume the original child process is still alive.",
329
+ "",
330
+ "Follow-up:",
331
+ message,
332
+ ].filter((line): line is string => line !== undefined).join("\n");
333
+ }