@fitchmultz/pi-subagents 0.0.0-stage → 0.44.4

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 (342) hide show
  1. package/CHANGELOG.md +1645 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1529 -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 +194 -0
  43. package/dist/history/ingest.js +447 -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 +461 -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/broker/broker.js +426 -0
  53. package/dist/pi-intercom/broker/client.js +492 -0
  54. package/dist/pi-intercom/broker/framing.js +65 -0
  55. package/dist/pi-intercom/broker/paths.js +42 -0
  56. package/dist/pi-intercom/broker/pid.js +66 -0
  57. package/dist/pi-intercom/broker/spawn.js +221 -0
  58. package/dist/pi-intercom/config.js +102 -0
  59. package/dist/pi-intercom/index.js +2942 -0
  60. package/dist/pi-intercom/reply-tracker.js +182 -0
  61. package/dist/pi-intercom/session-targets.js +128 -0
  62. package/dist/pi-intercom/subagent-live-events.js +132 -0
  63. package/dist/pi-intercom/topics.js +157 -0
  64. package/dist/pi-intercom/types.js +163 -0
  65. package/dist/pi-intercom/ui/compose.js +269 -0
  66. package/dist/pi-intercom/ui/inline-message.js +80 -0
  67. package/dist/pi-intercom/ui/session-list.js +124 -0
  68. package/dist/runs/background/async-control.js +95 -0
  69. package/dist/runs/background/async-execution.js +676 -0
  70. package/dist/runs/background/async-job-tracker.js +383 -0
  71. package/dist/runs/background/async-result-file.js +58 -0
  72. package/dist/runs/background/async-resume.js +305 -0
  73. package/dist/runs/background/async-status.js +442 -0
  74. package/dist/runs/background/completion-dedupe.js +69 -0
  75. package/dist/runs/background/completion-delivery.js +245 -0
  76. package/dist/runs/background/notify.js +71 -0
  77. package/dist/runs/background/parallel-groups.js +55 -0
  78. package/dist/runs/background/result-watcher.js +426 -0
  79. package/dist/runs/background/run-id-resolver.js +64 -0
  80. package/dist/runs/background/run-status.js +382 -0
  81. package/dist/runs/background/stale-run-reconciler.js +335 -0
  82. package/dist/runs/background/subagent-runner-launcher.js +55 -0
  83. package/dist/runs/background/subagent-runner.js +1872 -0
  84. package/dist/runs/background/top-level-async.js +5 -0
  85. package/dist/runs/foreground/chain-clarify.js +1152 -0
  86. package/dist/runs/foreground/clarify-invocation.js +72 -0
  87. package/dist/runs/foreground/execution-input.js +423 -0
  88. package/dist/runs/foreground/foreground-control.js +817 -0
  89. package/dist/runs/foreground/question-control.js +77 -0
  90. package/dist/runs/foreground/run-async-path.js +205 -0
  91. package/dist/runs/foreground/subagent-executor.js +442 -0
  92. package/dist/runs/foreground/subagent-params.js +165 -0
  93. package/dist/runs/foreground/wait-run.js +139 -0
  94. package/dist/runs/shared/acceptance-contract.js +253 -0
  95. package/dist/runs/shared/acceptance-evaluation.js +256 -0
  96. package/dist/runs/shared/acceptance-finalization.js +280 -0
  97. package/dist/runs/shared/acceptance-reports.js +147 -0
  98. package/dist/runs/shared/acceptance.js +4 -0
  99. package/dist/runs/shared/chain-outputs.js +110 -0
  100. package/dist/runs/shared/child-attempt.js +693 -0
  101. package/dist/runs/shared/child-execution-cwd.js +96 -0
  102. package/dist/runs/shared/child-observations.js +114 -0
  103. package/dist/runs/shared/claude-code.js +199 -0
  104. package/dist/runs/shared/completion-guard.js +31 -0
  105. package/dist/runs/shared/dynamic-fanout.js +274 -0
  106. package/dist/runs/shared/history-index.js +72 -0
  107. package/dist/runs/shared/mcp-direct-tool-allowlist.js +334 -0
  108. package/dist/runs/shared/model-fallback.js +185 -0
  109. package/dist/runs/shared/mutating-tool-guard.js +170 -0
  110. package/dist/runs/shared/native-finalization.js +101 -0
  111. package/dist/runs/shared/native-usage.js +153 -0
  112. package/dist/runs/shared/nested-events.js +700 -0
  113. package/dist/runs/shared/nested-path.js +48 -0
  114. package/dist/runs/shared/nested-render.js +108 -0
  115. package/dist/runs/shared/parallel-utils.js +61 -0
  116. package/dist/runs/shared/parent-receipts.js +68 -0
  117. package/dist/runs/shared/parent-usage.js +121 -0
  118. package/dist/runs/shared/pi-args.js +310 -0
  119. package/dist/runs/shared/pi-spawn.js +52 -0
  120. package/dist/runs/shared/run-history-queries.js +45 -0
  121. package/dist/runs/shared/run-history.js +103 -0
  122. package/dist/runs/shared/run-id-ambiguity.js +4 -0
  123. package/dist/runs/shared/run-records.js +679 -0
  124. package/dist/runs/shared/session-cwd-preload.js +33 -0
  125. package/dist/runs/shared/single-output.js +222 -0
  126. package/dist/runs/shared/streaming-text.js +15 -0
  127. package/dist/runs/shared/structured-output.js +55 -0
  128. package/dist/runs/shared/subagent-control.js +179 -0
  129. package/dist/runs/shared/subagent-prompt-runtime.js +197 -0
  130. package/dist/runs/shared/subagent-tool-loop-guard.js +66 -0
  131. package/dist/runs/shared/supervisor-questions.js +320 -0
  132. package/dist/runs/shared/workflow-graph.js +214 -0
  133. package/dist/runs/shared/workflow-policy.js +84 -0
  134. package/dist/runs/shared/worktree.js +525 -0
  135. package/dist/shared/agent-context-policy.js +126 -0
  136. package/dist/shared/artifacts.js +96 -0
  137. package/dist/shared/atomic-json.js +13 -0
  138. package/dist/shared/cooperative.js +20 -0
  139. package/dist/shared/execution-cwd.js +14 -0
  140. package/dist/shared/file-coalescer.js +21 -0
  141. package/dist/shared/fork-context.js +49 -0
  142. package/dist/shared/formatters.js +85 -0
  143. package/dist/shared/journal-reader.js +407 -0
  144. package/dist/shared/lazy-tools.js +32 -0
  145. package/dist/shared/model-info.js +68 -0
  146. package/dist/shared/native-session.js +15 -0
  147. package/dist/shared/native-tui.js +18 -0
  148. package/dist/shared/native-typebox.js +20 -0
  149. package/dist/shared/post-exit-stdio-guard.js +197 -0
  150. package/dist/shared/prompt-sections.js +8 -0
  151. package/dist/shared/session-entries.js +52 -0
  152. package/dist/shared/session-identity.js +14 -0
  153. package/dist/shared/settings.js +254 -0
  154. package/dist/shared/status-format.js +111 -0
  155. package/dist/shared/temp-root.js +114 -0
  156. package/dist/shared/types.js +207 -0
  157. package/dist/shared/ui-mode.js +3 -0
  158. package/dist/shared/utils.js +334 -0
  159. package/dist/slash/prompt-template-bridge.js +298 -0
  160. package/dist/slash/slash-bridge.js +116 -0
  161. package/dist/slash/slash-commands.js +607 -0
  162. package/dist/slash/slash-live-state.js +246 -0
  163. package/dist/tui/action-hints.js +75 -0
  164. package/dist/tui/agent-history.js +197 -0
  165. package/dist/tui/agent-view.js +1656 -0
  166. package/dist/tui/render.js +1515 -0
  167. package/docs/intercom.md +579 -0
  168. package/docs/performance.md +121 -0
  169. package/package.json +101 -4
  170. package/prompts/gather-context-and-clarify.md +14 -0
  171. package/prompts/parallel-cleanup.md +62 -0
  172. package/prompts/parallel-context-build.md +56 -0
  173. package/prompts/parallel-handoff-plan.md +62 -0
  174. package/prompts/parallel-research.md +51 -0
  175. package/prompts/parallel-review.md +59 -0
  176. package/prompts/review-loop.md +42 -0
  177. package/scripts/build.mjs +134 -0
  178. package/scripts/check-compat.mjs +48 -0
  179. package/scripts/compat-host.mjs +19 -0
  180. package/scripts/linux-smoke.sh +51 -0
  181. package/scripts/local-install-smoke.mjs +66 -0
  182. package/scripts/native-package-smoke.mjs +82 -0
  183. package/scripts/package-smoke.mjs +205 -0
  184. package/scripts/prepare.mjs +67 -0
  185. package/scripts/real-pi-smoke.mjs +415 -0
  186. package/scripts/run-tests.mjs +149 -0
  187. package/skills/pi-intercom/SKILL.md +113 -0
  188. package/skills/pi-intercom/evals/evals.json +29 -0
  189. package/skills/pi-intercom/evals/trigger-evals.json +47 -0
  190. package/skills/pi-intercom/references/peer-sessions.md +69 -0
  191. package/skills/pi-subagents/SKILL.md +76 -0
  192. package/skills/pi-subagents/evals/evals.json +29 -0
  193. package/skills/pi-subagents/evals/trigger-evals.json +42 -0
  194. package/skills/pi-subagents/references/full-orchestration-guide.md +863 -0
  195. package/src/agents/agent-management.ts +813 -0
  196. package/src/agents/agent-scope.ts +7 -0
  197. package/src/agents/agent-selection.ts +23 -0
  198. package/src/agents/agent-serializer.ts +99 -0
  199. package/src/agents/agents.ts +916 -0
  200. package/src/agents/chain-serializer.ts +329 -0
  201. package/src/agents/frontmatter.ts +21 -0
  202. package/src/agents/identity.ts +30 -0
  203. package/src/agents/skills.ts +637 -0
  204. package/src/extension/build-info.ts +2 -0
  205. package/src/extension/compact-tools.ts +114 -0
  206. package/src/extension/config.ts +23 -0
  207. package/src/extension/control-notices.ts +47 -0
  208. package/src/extension/doctor.ts +171 -0
  209. package/src/extension/fanout-child.ts +312 -0
  210. package/src/extension/index.ts +649 -0
  211. package/src/extension/schemas.ts +444 -0
  212. package/src/extension/tool-input.ts +19 -0
  213. package/src/extension/tool-result.ts +16 -0
  214. package/src/history/canonical-result.ts +62 -0
  215. package/src/history/database.ts +59 -0
  216. package/src/history/index.ts +152 -0
  217. package/src/history/ingest.ts +332 -0
  218. package/src/history/queries.ts +241 -0
  219. package/src/history/store.ts +203 -0
  220. package/src/history/types.ts +166 -0
  221. package/src/history/worker.ts +317 -0
  222. package/src/intercom/intercom-bridge.ts +123 -0
  223. package/src/intercom/live-intercom.ts +104 -0
  224. package/src/intercom/result-intercom.ts +429 -0
  225. package/src/pi-intercom/agent-dir.ts +9 -0
  226. package/src/pi-intercom/broker/broker.ts +463 -0
  227. package/src/pi-intercom/broker/client.ts +558 -0
  228. package/src/pi-intercom/broker/framing.ts +77 -0
  229. package/src/pi-intercom/broker/paths.ts +47 -0
  230. package/src/pi-intercom/broker/pid.ts +59 -0
  231. package/src/pi-intercom/broker/spawn.ts +248 -0
  232. package/src/pi-intercom/config.ts +142 -0
  233. package/src/pi-intercom/index.ts +2929 -0
  234. package/src/pi-intercom/reply-tracker.ts +211 -0
  235. package/src/pi-intercom/session-targets.ts +172 -0
  236. package/src/pi-intercom/subagent-live-events.ts +133 -0
  237. package/src/pi-intercom/topics.ts +125 -0
  238. package/src/pi-intercom/types.ts +271 -0
  239. package/src/pi-intercom/ui/compose.ts +289 -0
  240. package/src/pi-intercom/ui/inline-message.ts +92 -0
  241. package/src/pi-intercom/ui/session-list.ts +139 -0
  242. package/src/runs/background/async-control.ts +89 -0
  243. package/src/runs/background/async-execution.ts +850 -0
  244. package/src/runs/background/async-job-tracker.ts +385 -0
  245. package/src/runs/background/async-result-file.ts +62 -0
  246. package/src/runs/background/async-resume.ts +333 -0
  247. package/src/runs/background/async-status.ts +481 -0
  248. package/src/runs/background/completion-dedupe.ts +79 -0
  249. package/src/runs/background/completion-delivery.ts +195 -0
  250. package/src/runs/background/notify.ts +123 -0
  251. package/src/runs/background/parallel-groups.ts +53 -0
  252. package/src/runs/background/result-watcher.ts +423 -0
  253. package/src/runs/background/run-id-resolver.ts +69 -0
  254. package/src/runs/background/run-status.ts +384 -0
  255. package/src/runs/background/stale-run-reconciler.ts +369 -0
  256. package/src/runs/background/subagent-runner-launcher.ts +56 -0
  257. package/src/runs/background/subagent-runner.ts +2053 -0
  258. package/src/runs/background/top-level-async.ts +13 -0
  259. package/src/runs/foreground/chain-clarify.ts +1340 -0
  260. package/src/runs/foreground/clarify-invocation.ts +77 -0
  261. package/src/runs/foreground/execution-input.ts +467 -0
  262. package/src/runs/foreground/foreground-control.ts +821 -0
  263. package/src/runs/foreground/question-control.ts +70 -0
  264. package/src/runs/foreground/run-async-path.ts +243 -0
  265. package/src/runs/foreground/subagent-executor.ts +501 -0
  266. package/src/runs/foreground/subagent-params.ts +320 -0
  267. package/src/runs/foreground/wait-run.ts +121 -0
  268. package/src/runs/shared/acceptance-contract.ts +257 -0
  269. package/src/runs/shared/acceptance-evaluation.ts +275 -0
  270. package/src/runs/shared/acceptance-finalization.ts +353 -0
  271. package/src/runs/shared/acceptance-reports.ts +152 -0
  272. package/src/runs/shared/acceptance.ts +33 -0
  273. package/src/runs/shared/chain-outputs.ts +114 -0
  274. package/src/runs/shared/child-attempt.ts +623 -0
  275. package/src/runs/shared/child-execution-cwd.ts +91 -0
  276. package/src/runs/shared/child-observations.ts +99 -0
  277. package/src/runs/shared/claude-code.ts +243 -0
  278. package/src/runs/shared/completion-guard.ts +35 -0
  279. package/src/runs/shared/dynamic-fanout.ts +295 -0
  280. package/src/runs/shared/history-index.ts +69 -0
  281. package/src/runs/shared/mcp-direct-tool-allowlist.ts +376 -0
  282. package/src/runs/shared/model-fallback.ts +219 -0
  283. package/src/runs/shared/mutating-tool-guard.ts +194 -0
  284. package/src/runs/shared/native-finalization.ts +128 -0
  285. package/src/runs/shared/native-usage.ts +113 -0
  286. package/src/runs/shared/nested-events.ts +752 -0
  287. package/src/runs/shared/nested-path.ts +52 -0
  288. package/src/runs/shared/nested-render.ts +119 -0
  289. package/src/runs/shared/parallel-utils.ts +153 -0
  290. package/src/runs/shared/parent-receipts.ts +59 -0
  291. package/src/runs/shared/parent-usage.ts +121 -0
  292. package/src/runs/shared/pi-args.ts +350 -0
  293. package/src/runs/shared/pi-spawn.ts +52 -0
  294. package/src/runs/shared/run-history-queries.ts +44 -0
  295. package/src/runs/shared/run-history.ts +93 -0
  296. package/src/runs/shared/run-id-ambiguity.ts +4 -0
  297. package/src/runs/shared/run-records.ts +607 -0
  298. package/src/runs/shared/session-cwd-preload.ts +27 -0
  299. package/src/runs/shared/single-output.ts +267 -0
  300. package/src/runs/shared/streaming-text.ts +18 -0
  301. package/src/runs/shared/structured-output.ts +68 -0
  302. package/src/runs/shared/subagent-control.ts +219 -0
  303. package/src/runs/shared/subagent-prompt-runtime.ts +201 -0
  304. package/src/runs/shared/subagent-tool-loop-guard.ts +89 -0
  305. package/src/runs/shared/supervisor-questions.ts +372 -0
  306. package/src/runs/shared/workflow-graph.ts +220 -0
  307. package/src/runs/shared/workflow-policy.ts +125 -0
  308. package/src/runs/shared/worktree.ts +635 -0
  309. package/src/shared/agent-context-policy.ts +184 -0
  310. package/src/shared/artifacts.ts +95 -0
  311. package/src/shared/atomic-json.ts +16 -0
  312. package/src/shared/cooperative.ts +21 -0
  313. package/src/shared/execution-cwd.ts +14 -0
  314. package/src/shared/file-coalescer.ts +29 -0
  315. package/src/shared/fork-context.ts +68 -0
  316. package/src/shared/formatters.ts +84 -0
  317. package/src/shared/journal-reader.ts +333 -0
  318. package/src/shared/lazy-tools.ts +36 -0
  319. package/src/shared/model-info.ts +81 -0
  320. package/src/shared/native-session.ts +8 -0
  321. package/src/shared/native-tui.ts +10 -0
  322. package/src/shared/native-typebox.ts +14 -0
  323. package/src/shared/post-exit-stdio-guard.ts +204 -0
  324. package/src/shared/prompt-sections.ts +10 -0
  325. package/src/shared/session-entries.ts +49 -0
  326. package/src/shared/session-identity.ts +18 -0
  327. package/src/shared/settings.ts +384 -0
  328. package/src/shared/status-format.ts +123 -0
  329. package/src/shared/temp-root.ts +107 -0
  330. package/src/shared/types.ts +1259 -0
  331. package/src/shared/ui-mode.ts +5 -0
  332. package/src/shared/utils.ts +342 -0
  333. package/src/slash/prompt-template-bridge.ts +408 -0
  334. package/src/slash/slash-bridge.ts +178 -0
  335. package/src/slash/slash-commands.ts +617 -0
  336. package/src/slash/slash-live-state.ts +292 -0
  337. package/src/tui/action-hints.ts +69 -0
  338. package/src/tui/agent-history.ts +210 -0
  339. package/src/tui/agent-view.ts +1323 -0
  340. package/src/tui/render.ts +1550 -0
  341. package/tsconfig.build.json +12 -0
  342. package/tsconfig.json +19 -0
@@ -0,0 +1,335 @@
1
+ import * as fs from "node:fs";
2
+ import { readOutputPage } from "../../shared/journal-reader.js";
3
+ import * as path from "node:path";
4
+ import { writeAtomicJson } from "../../shared/atomic-json.js";
5
+ import { RESULTS_DIR, RUNNER_ERROR_LOG_FILE } from "../../shared/types.js";
6
+ import { normalizeParallelGroups } from "./parallel-groups.js";
7
+ import { nestedSummaryFromAsyncStatus, projectNestedEvents, resolveNestedAsyncDir, writeNestedEvent } from "../shared/nested-events.js";
8
+ import { isDurableRun, readAsyncResultFileIfExists } from "./async-result-file.js";
9
+ import { readRunJson } from "../shared/supervisor-questions.js";
10
+ import { readStatus } from "../../shared/utils.js";
11
+ function isNotFoundError(error) {
12
+ return typeof error === "object"
13
+ && error !== null
14
+ && "code" in error
15
+ && error.code === "ENOENT";
16
+ }
17
+ function appendJsonl(filePath, payload) {
18
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
19
+ fs.appendFileSync(filePath, `${JSON.stringify(payload)}\n`, "utf-8");
20
+ }
21
+ function readStatusFile(asyncDir) {
22
+ return readStatus(asyncDir);
23
+ }
24
+ function readResultRepairData(resultPath) {
25
+ const data = readAsyncResultFileIfExists(resultPath);
26
+ if (!data)
27
+ return undefined;
28
+ return { state: data.terminalState, timestamp: data.timestamp, ...(Array.isArray(data.results) ? { results: data.results } : {}) };
29
+ }
30
+ function childState(overallState, child) {
31
+ if (child?.success === true)
32
+ return "complete";
33
+ if (child?.interrupted === true)
34
+ return "paused";
35
+ if (child?.acceptance?.status === "blocked" && (child.exitCode === 0 || child.exitCode === undefined))
36
+ return "blocked";
37
+ if (child?.success === false)
38
+ return "failed";
39
+ return overallState;
40
+ }
41
+ function withoutLiveActivity(value) {
42
+ return {
43
+ ...value,
44
+ activityState: undefined,
45
+ currentTool: undefined,
46
+ currentToolArgs: undefined,
47
+ currentToolStartedAt: undefined,
48
+ currentPath: undefined,
49
+ };
50
+ }
51
+ function terminalStatusFromResult(status, resultPath, now) {
52
+ const repair = readResultRepairData(resultPath);
53
+ if (!repair)
54
+ return undefined;
55
+ now = repair.timestamp ?? now;
56
+ const steps = (status.steps ?? []).map((step, index) => {
57
+ if (step.status !== "running" && step.status !== "pending")
58
+ return withoutLiveActivity(step);
59
+ const child = repair.results?.[index];
60
+ if (isDurableRun(status) && step.status === "pending" && !child)
61
+ return withoutLiveActivity(step);
62
+ const state = childState(repair.state, child);
63
+ return withoutLiveActivity({
64
+ ...step,
65
+ status: state === "complete" ? "complete" : state,
66
+ endedAt: step.endedAt ?? now,
67
+ durationMs: step.startedAt !== undefined && step.durationMs === undefined ? Math.max(0, now - step.startedAt) : step.durationMs,
68
+ exitCode: step.exitCode ?? (state === "complete" || state === "blocked" || state === "paused" ? 0 : 1),
69
+ error: state === "failed" ? step.error ?? child?.error : step.error,
70
+ sessionFile: step.sessionFile ?? child?.sessionFile,
71
+ model: step.model ?? child?.model,
72
+ attemptedModels: step.attemptedModels ?? child?.attemptedModels,
73
+ modelAttempts: step.modelAttempts ?? child?.modelAttempts,
74
+ acceptance: step.acceptance ?? child?.acceptance,
75
+ agentProcessExit: step.agentProcessExit ?? child?.agentProcessExit,
76
+ });
77
+ });
78
+ return withoutLiveActivity({
79
+ ...status,
80
+ state: repair.state,
81
+ lastUpdate: now,
82
+ endedAt: status.endedAt ?? now,
83
+ steps,
84
+ });
85
+ }
86
+ function buildStartedStatus(asyncDir, startedRun, now) {
87
+ const startedAt = startedRun.startedAt ?? now;
88
+ const agents = startedRun.agents?.length ? startedRun.agents : ["subagent"];
89
+ const chainStepCount = startedRun.chainStepCount;
90
+ const parallelGroups = chainStepCount !== undefined
91
+ ? normalizeParallelGroups(startedRun.parallelGroups, agents.length, chainStepCount)
92
+ : [];
93
+ return {
94
+ runId: startedRun.runId || path.basename(asyncDir),
95
+ ...(startedRun.sessionId ? { sessionId: startedRun.sessionId } : {}),
96
+ mode: startedRun.mode ?? "single",
97
+ state: "running",
98
+ pid: startedRun.pid,
99
+ startedAt,
100
+ lastUpdate: now,
101
+ currentStep: 0,
102
+ ...(chainStepCount !== undefined ? { chainStepCount } : {}),
103
+ ...(parallelGroups.length ? { parallelGroups } : {}),
104
+ steps: agents.map((agent) => ({
105
+ agent,
106
+ status: "running",
107
+ startedAt,
108
+ })),
109
+ ...(startedRun.sessionFile ? { sessionFile: startedRun.sessionFile } : {}),
110
+ };
111
+ }
112
+ function readCompletedStepOutput(asyncDir, index) {
113
+ try {
114
+ return readOutputPage(path.join(asyncDir, `output-${index}.log`)).text.trim();
115
+ }
116
+ catch (error) {
117
+ if (isNotFoundError(error))
118
+ return "";
119
+ throw error;
120
+ }
121
+ }
122
+ const RUNNER_STDERR_EXCERPT_BYTES = 16 * 1024;
123
+ const UNSAFE_CONTROL_CHARACTERS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g;
124
+ function readRunnerStderr(asyncDir) {
125
+ let fd;
126
+ try {
127
+ fd = fs.openSync(path.join(asyncDir, RUNNER_ERROR_LOG_FILE), "r");
128
+ const size = fs.fstatSync(fd).size;
129
+ const length = Math.min(size, RUNNER_STDERR_EXCERPT_BYTES);
130
+ const buffer = Buffer.alloc(length);
131
+ const bytesRead = fs.readSync(fd, buffer, 0, length, Math.max(0, size - length));
132
+ const excerpt = buffer.subarray(0, bytesRead).toString("utf-8").replace(UNSAFE_CONTROL_CHARACTERS, "�").trim();
133
+ if (!excerpt)
134
+ return undefined;
135
+ return size > length ? `[runner stderr truncated to last ${length} bytes]\n${excerpt}` : excerpt;
136
+ }
137
+ catch {
138
+ return undefined;
139
+ }
140
+ finally {
141
+ if (fd !== undefined) {
142
+ try {
143
+ fs.closeSync(fd);
144
+ }
145
+ catch { }
146
+ }
147
+ }
148
+ }
149
+ function buildFailedRepair(status, asyncDir, now, reason) {
150
+ const runId = status.runId || path.basename(asyncDir);
151
+ const pid = typeof status.pid === "number" ? status.pid : "unknown";
152
+ const defaultMessage = `Async runner process ${pid} exited or disappeared before writing a result. Completion is unconfirmed.`;
153
+ const runnerStderr = reason ? undefined : readRunnerStderr(asyncDir);
154
+ const message = reason ?? (runnerStderr ? `${defaultMessage}\n\nRunner stderr:\n${runnerStderr}` : defaultMessage);
155
+ const steps = status.steps?.length ? status.steps : [{ agent: "subagent", status: "running" }];
156
+ const repairedSteps = steps.map((step) => step.status === "running" || String(step.status) === "queued" || step.status === "pending"
157
+ ? withoutLiveActivity({
158
+ ...step,
159
+ status: "failed",
160
+ endedAt: step.endedAt ?? now,
161
+ durationMs: step.startedAt !== undefined && step.durationMs === undefined ? Math.max(0, now - step.startedAt) : step.durationMs,
162
+ exitCode: step.exitCode ?? 1,
163
+ error: step.error ?? message,
164
+ })
165
+ : withoutLiveActivity(step));
166
+ const repairedStatus = withoutLiveActivity({
167
+ ...status,
168
+ state: "failed",
169
+ lastUpdate: now,
170
+ endedAt: now,
171
+ steps: repairedSteps,
172
+ });
173
+ const resultAgent = repairedSteps[status.currentStep ?? 0]?.agent ?? repairedSteps[0]?.agent ?? "subagent";
174
+ return {
175
+ status: repairedStatus,
176
+ message,
177
+ result: {
178
+ id: runId,
179
+ agent: resultAgent,
180
+ mode: status.mode,
181
+ success: false,
182
+ state: "failed",
183
+ summary: message,
184
+ results: repairedSteps.map((step, index) => {
185
+ const success = step.status === "complete" || step.status === "completed";
186
+ return {
187
+ agent: step.agent,
188
+ output: success ? readCompletedStepOutput(asyncDir, index) : message,
189
+ error: success ? undefined : step.error ?? message,
190
+ success,
191
+ model: step.model,
192
+ attemptedModels: step.attemptedModels,
193
+ modelAttempts: step.modelAttempts,
194
+ sessionFile: step.sessionFile,
195
+ };
196
+ }),
197
+ exitCode: 1,
198
+ timestamp: now,
199
+ durationMs: Math.max(0, now - status.startedAt),
200
+ asyncDir,
201
+ sessionId: status.sessionId,
202
+ cwd: status.cwd,
203
+ sessionFile: status.sessionFile,
204
+ },
205
+ };
206
+ }
207
+ function writeFailedRepair(asyncDir, status, resultPath, now, reason) {
208
+ const repair = buildFailedRepair(status, asyncDir, now, reason);
209
+ writeAtomicJson(resultPath, repair.result);
210
+ writeAtomicJson(path.join(asyncDir, "status.json"), repair.status);
211
+ appendJsonl(path.join(asyncDir, "events.jsonl"), {
212
+ type: "subagent.run.repaired_stale",
213
+ ts: now,
214
+ runId: repair.status.runId,
215
+ pid: status.pid,
216
+ resultPath,
217
+ message: repair.message,
218
+ });
219
+ return { status: repair.status, repaired: true, resultPath, message: repair.message };
220
+ }
221
+ function terminal(state) {
222
+ return state === "complete" || state === "failed" || state === "blocked" || state === "paused";
223
+ }
224
+ function* nestedRuns(children) {
225
+ for (const child of children ?? []) {
226
+ yield child;
227
+ yield* nestedRuns(child.children);
228
+ yield* nestedRuns(child.steps?.flatMap((step) => step.children ?? []));
229
+ }
230
+ }
231
+ export function reconcileNestedAsyncDescendants(route, options = {}) {
232
+ const registry = projectNestedEvents(route);
233
+ for (const run of nestedRuns(registry.children)) {
234
+ if (run.state !== "running" && run.state !== "queued")
235
+ continue;
236
+ const asyncDir = resolveNestedAsyncDir(route.rootRunId, run);
237
+ if (!asyncDir)
238
+ continue;
239
+ const result = reconcileAsyncRun(asyncDir, {
240
+ ...options,
241
+ resultsDir: path.join(options.resultsDir ?? RESULTS_DIR, "nested", route.rootRunId),
242
+ });
243
+ const status = result.status;
244
+ if (!status)
245
+ continue;
246
+ const ts = options.now?.() ?? Date.now();
247
+ const child = nestedSummaryFromAsyncStatus(status, asyncDir, {
248
+ id: run.id, parentRunId: run.parentRunId, parentStepIndex: run.parentStepIndex,
249
+ depth: run.depth, path: run.path, mode: run.mode, ts,
250
+ });
251
+ child.steps?.forEach((step, index) => { step.children = run.steps?.[index]?.children; });
252
+ Object.assign(run, child, result.message ? { error: result.message } : {});
253
+ if (isDurableRun(status))
254
+ continue;
255
+ if (!result.repaired && !terminal(status.state))
256
+ continue;
257
+ writeNestedEvent(route, {
258
+ type: terminal(status.state) ? "subagent.nested.completed" : "subagent.nested.updated",
259
+ ts,
260
+ parentRunId: run.parentRunId,
261
+ parentStepIndex: run.parentStepIndex,
262
+ child,
263
+ });
264
+ }
265
+ return registry.children;
266
+ }
267
+ export function checkPidLiveness(pid, kill = process.kill) {
268
+ try {
269
+ kill(pid, 0);
270
+ return "alive";
271
+ }
272
+ catch (error) {
273
+ const code = typeof error === "object" && error !== null && "code" in error
274
+ ? error.code
275
+ : undefined;
276
+ if (code === "ESRCH")
277
+ return "dead";
278
+ if (code === "EPERM")
279
+ return "unknown";
280
+ return "unknown";
281
+ }
282
+ }
283
+ export function reconcileAsyncRun(asyncDir, options = {}, record) {
284
+ const now = options.now?.() ?? Date.now();
285
+ const status = record ? record.status : readStatusFile(asyncDir);
286
+ const startedStatus = !status && options.startedRun ? buildStartedStatus(asyncDir, options.startedRun, now) : undefined;
287
+ const effectiveStatus = status ?? startedStatus;
288
+ if (!effectiveStatus)
289
+ return { status: null, repaired: false };
290
+ const runId = effectiveStatus.runId || path.basename(asyncDir);
291
+ const durable = isDurableRun(effectiveStatus) || (record ? record.durable : isDurableRun(readRunJson(path.join(asyncDir, "launch.json"))));
292
+ const resultPath = durable ? path.join(asyncDir, "result.json") : path.join(options.resultsDir ?? RESULTS_DIR, `${runId}.json`);
293
+ if (durable) {
294
+ // The detached owner is the only execution writer. Inspection projects evidence.
295
+ const final = terminalStatusFromResult(effectiveStatus, resultPath, effectiveStatus.endedAt ?? now);
296
+ if (final)
297
+ return { status: final, repaired: false, resultPath };
298
+ if (typeof effectiveStatus.pid === "number" && checkPidLiveness(effectiveStatus.pid, options.kill) === "dead") {
299
+ const failure = buildFailedRepair(effectiveStatus, asyncDir, effectiveStatus.lastUpdate ?? effectiveStatus.startedAt);
300
+ return { status: failure.status, repaired: false, message: failure.message };
301
+ }
302
+ if (terminal(effectiveStatus.state))
303
+ return { status: { ...effectiveStatus, state: "running" }, repaired: false, message: "Waiting for the owner's final result. Completion is unconfirmed." };
304
+ return { status: effectiveStatus, repaired: false };
305
+ }
306
+ if (fs.existsSync(resultPath)) {
307
+ const terminalStatus = effectiveStatus.state === "running" || effectiveStatus.state === "queued"
308
+ ? terminalStatusFromResult(effectiveStatus, resultPath, now)
309
+ : undefined;
310
+ if (terminalStatus) {
311
+ writeAtomicJson(path.join(asyncDir, "status.json"), terminalStatus);
312
+ return { status: terminalStatus, repaired: true, resultPath, message: "Existing async result file was used to repair stale running status." };
313
+ }
314
+ return { status: effectiveStatus, repaired: false, resultPath };
315
+ }
316
+ if ((effectiveStatus.state !== "running" && effectiveStatus.state !== "queued") || typeof effectiveStatus.pid !== "number") {
317
+ return { status: status ?? null, repaired: false, resultPath };
318
+ }
319
+ if (!status) {
320
+ const startedAt = options.startedRun?.startedAt ?? effectiveStatus.startedAt;
321
+ if (now - startedAt < (options.missingStatusGraceMs ?? 1000)) {
322
+ return { status: null, repaired: false, resultPath };
323
+ }
324
+ }
325
+ const liveness = checkPidLiveness(effectiveStatus.pid, options.kill);
326
+ if (liveness !== "dead") {
327
+ const staleAfterMs = options.staleAlivePidMs ?? 24 * 60 * 60 * 1000;
328
+ const lastUpdate = effectiveStatus.lastUpdate ?? effectiveStatus.startedAt;
329
+ if (now - lastUpdate <= staleAfterMs)
330
+ return { status: status ?? null, repaired: false, resultPath };
331
+ const message = `Async runner process ${effectiveStatus.pid} still has a live PID, but status has not updated for ${now - lastUpdate}ms. Marked run failed by stale-run reconciliation because PID ownership cannot be verified.`;
332
+ return writeFailedRepair(asyncDir, effectiveStatus, resultPath, now, message);
333
+ }
334
+ return writeFailedRepair(asyncDir, effectiveStatus, resultPath, now);
335
+ }
@@ -0,0 +1,55 @@
1
+ import { spawn } from "node:child_process";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { setTimeout as delay } from "node:timers/promises";
5
+ const RETRY_WINDOW_MS = 30_000;
6
+ const RETRY_DELAY_MS = 500;
7
+ const MAX_STDERR_LENGTH = 64 * 1024;
8
+ function run(runnerPath, configPath, piPackageRoot) {
9
+ return new Promise((resolve) => {
10
+ const child = spawn(process.execPath, [runnerPath, configPath], {
11
+ stdio: ["ignore", "inherit", "pipe"],
12
+ env: piPackageRoot ? { ...process.env, PI_PACKAGE_DIR: process.env.PI_PACKAGE_DIR ?? piPackageRoot } : process.env,
13
+ });
14
+ let stderr = "";
15
+ child.stderr.on("data", (chunk) => {
16
+ process.stderr.write(chunk);
17
+ stderr = `${stderr}${chunk.toString()}`.slice(-MAX_STDERR_LENGTH);
18
+ });
19
+ child.once("error", (error) => {
20
+ const stderr = error.stack ?? error.message;
21
+ process.stderr.write(`${stderr}\n`);
22
+ resolve({ code: 1, stderr });
23
+ });
24
+ child.once("close", (code) => resolve({ code: code ?? 1, stderr }));
25
+ });
26
+ }
27
+ const [runnerPath, configPath] = process.argv.slice(2);
28
+ if (!runnerPath || !configPath)
29
+ throw new Error("Usage: subagent-runner-launcher <runner> <config>");
30
+ let statusPath;
31
+ let piPackageRoot;
32
+ try {
33
+ const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
34
+ if (typeof config.piPackageRoot === "string")
35
+ piPackageRoot = config.piPackageRoot;
36
+ if (typeof config.asyncDir === "string")
37
+ statusPath = path.join(config.asyncDir, "status.json");
38
+ }
39
+ catch { }
40
+ // ponytail: bridge short in-place extension updates; use shared update locking if longer gaps appear.
41
+ const deadline = Date.now() + RETRY_WINDOW_MS;
42
+ let announcedRetry = false;
43
+ while (true) {
44
+ const result = await run(runnerPath, configPath, piPackageRoot);
45
+ const failedBeforeStartup = !statusPath || !fs.existsSync(statusPath);
46
+ if (result.code === 0 || !failedBeforeStartup || !result.stderr.includes("ERR_MODULE_NOT_FOUND") || Date.now() >= deadline) {
47
+ process.exitCode = result.code;
48
+ break;
49
+ }
50
+ if (!announcedRetry) {
51
+ process.stderr.write("[pi-subagents] Runner dependencies are being updated; retrying startup.\n");
52
+ announcedRetry = true;
53
+ }
54
+ await delay(RETRY_DELAY_MS);
55
+ }