@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,67 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Purpose: Build generated dist output for GitHub/source installs even when Pi invokes npm install --omit=dev.
4
+ * Responsibilities: Build with the local compiler when present; otherwise install only the pinned
5
+ * `typescript` into a throwaway prefix, build with it, and delete the prefix. Emit needs no type
6
+ * information (tsconfig.build.json sets noCheck), so the Pi host graph is never installed here.
7
+ * Scope: Package install lifecycle only; runtime behavior remains owned by scripts/build.mjs.
8
+ * Usage: package.json prepare script.
9
+ */
10
+
11
+ import { execFile as execFileCallback } from "node:child_process";
12
+ import { existsSync } from "node:fs";
13
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
14
+ import { tmpdir } from "node:os";
15
+ import { join } from "node:path";
16
+ import process from "node:process";
17
+ import { promisify } from "node:util";
18
+
19
+ const execFile = promisify(execFileCallback);
20
+ const cwd = process.cwd();
21
+ const buildScript = join(cwd, "scripts", "build.mjs");
22
+ const tscBin = (root) => join(root, "node_modules", "typescript", "bin", "tsc");
23
+
24
+ // No shell: process.execPath runs scripts and npm's cli.js directly, which is safe for
25
+ // paths containing spaces on every platform (shell:true concatenates args unescaped).
26
+ async function runNode(args) {
27
+ const { stderr, stdout } = await execFile(process.execPath, args, { cwd, maxBuffer: 20 * 1024 * 1024 });
28
+ // Forward output on success too: install-time diagnostics such as the
29
+ // concurrent-swap race-loss warning are otherwise swallowed.
30
+ if (stdout) process.stdout.write(stdout);
31
+ if (stderr) process.stderr.write(stderr);
32
+ }
33
+
34
+ async function main() {
35
+ if (existsSync(tscBin(cwd))) {
36
+ await runNode([buildScript]);
37
+ return;
38
+ }
39
+ const npmExecPath = process.env.npm_execpath;
40
+ if (!npmExecPath) throw new Error(`npm_execpath is not set; run "npm install" manually in ${cwd} and retry.`);
41
+ const { devDependencies } = JSON.parse(await readFile(join(cwd, "package.json"), "utf8"));
42
+ const prefix = await mkdtemp(join(tmpdir(), "pi-subagents-tsc-"));
43
+ try {
44
+ await runNode([
45
+ npmExecPath,
46
+ "install",
47
+ `typescript@${devDependencies.typescript}`,
48
+ "--prefix",
49
+ prefix,
50
+ "--no-save",
51
+ "--no-package-lock",
52
+ "--ignore-scripts",
53
+ "--no-audit",
54
+ "--no-fund",
55
+ ]);
56
+ await runNode([buildScript, tscBin(prefix)]);
57
+ } finally {
58
+ await rm(prefix, { force: true, recursive: true, maxRetries: 5, retryDelay: 100 });
59
+ }
60
+ }
61
+
62
+ main().catch((error) => {
63
+ if (error?.stdout) process.stdout.write(error.stdout);
64
+ if (error?.stderr) process.stderr.write(error.stderr);
65
+ console.error(error instanceof Error ? error.message : String(error));
66
+ process.exitCode = 1;
67
+ });
@@ -0,0 +1,415 @@
1
+ #!/usr/bin/env node
2
+ import { execFile } from "node:child_process";
3
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { basename, dirname, join, resolve } from "node:path";
6
+ import process from "node:process";
7
+ import { setTimeout as delay } from "node:timers/promises";
8
+ import { promisify } from "node:util";
9
+ import { attachChildProcessLifecycle, isChildTreeAlive, trySignalChildTree } from "../src/shared/post-exit-stdio-guard.ts";
10
+ import { getBrokerSocketPath } from "../src/pi-intercom/broker/paths.ts";
11
+
12
+ const execFileAsync = promisify(execFile);
13
+ const DEFAULT_TIMEOUT_MS = 120_000;
14
+ const authAgentDir = process.env.PI_REAL_SMOKE_AUTH_AGENT_DIR
15
+ ?? (process.env.HOME ? join(process.env.HOME, ".pi", "agent") : undefined);
16
+
17
+ function usage() {
18
+ console.log(`Usage: node scripts/real-pi-smoke.mjs [--llm] [--llm-full] [--keep-temp] [--timeout-ms <ms>]\n\nRuns an opt-in real Pi package smoke for this checkout. It uses an isolated\ntemporary Pi home, installs the single pi-subagents package with bundled intercom, verifies pi list,\nand loads both extension entries. It does not install pi-fitch-kit, publish anything,\nor create GitHub Actions.\n\nOptions:\n --llm Also run live model-backed list, foreground, and async-completion smoke prompts\n --llm-full Also run broader live parallel, chain, output, and acceptance prompts\n --keep-temp Keep the isolated temporary home for debugging\n --timeout-ms <ms> Per-command timeout in milliseconds (default: ${DEFAULT_TIMEOUT_MS})\n -h, --help Show this help\n\nEnvironment:\n PI_REAL_SMOKE_AUTH_AGENT_DIR Source Pi agent dir for auth.json/models.json during --llm (default: ~/.pi/agent)\n PI_REAL_SMOKE_MODEL Model passed to live --llm smoke prompts, e.g. openai/gpt-6-astra\n PI_REAL_SMOKE_PROVIDER Provider passed to live --llm smoke prompts\n\nExit codes:\n 0 real Pi smoke passed\n 1 install/list/live smoke failed\n 2 invalid arguments`);
19
+ }
20
+
21
+ function parsePositiveInteger(value, source) {
22
+ if (!/^\d+$/.test(value)) throw new Error(`${source} must be a positive integer, got ${value}`);
23
+ const parsed = Number(value);
24
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) throw new Error(`${source} must be a positive safe integer, got ${value}`);
25
+ return parsed;
26
+ }
27
+
28
+ function parseArgs(argv) {
29
+ const options = { llm: false, llmFull: false, keepTemp: false, timeoutMs: DEFAULT_TIMEOUT_MS };
30
+ for (let index = 0; index < argv.length; index += 1) {
31
+ const arg = argv[index];
32
+ if (arg === "--help" || arg === "-h") {
33
+ usage();
34
+ process.exit(0);
35
+ }
36
+ if (arg === "--llm") {
37
+ options.llm = true;
38
+ continue;
39
+ }
40
+ if (arg === "--llm-full") {
41
+ options.llm = true;
42
+ options.llmFull = true;
43
+ continue;
44
+ }
45
+ if (arg === "--keep-temp") {
46
+ options.keepTemp = true;
47
+ continue;
48
+ }
49
+ if (arg === "--timeout-ms") {
50
+ const value = argv[index + 1];
51
+ if (!value) throw new Error("--timeout-ms requires a value");
52
+ options.timeoutMs = parsePositiveInteger(value, "--timeout-ms");
53
+ index += 1;
54
+ continue;
55
+ }
56
+ if (arg.startsWith("--timeout-ms=")) {
57
+ options.timeoutMs = parsePositiveInteger(arg.slice("--timeout-ms=".length), "--timeout-ms");
58
+ continue;
59
+ }
60
+ throw new Error(`Unknown option: ${arg}`);
61
+ }
62
+ return options;
63
+ }
64
+
65
+ function copyLiveAuth(agentDir) {
66
+ if (!authAgentDir || !existsSync(authAgentDir)) return [];
67
+ mkdirSync(agentDir, { recursive: true });
68
+ const copied = [];
69
+ for (const filename of ["auth.json", "models.json"]) {
70
+ const source = join(authAgentDir, filename);
71
+ if (!existsSync(source)) continue;
72
+ copyFileSync(source, join(agentDir, filename));
73
+ copied.push(filename);
74
+ }
75
+ return copied;
76
+ }
77
+
78
+ function isolatedEnv(root, agentDir) {
79
+ const home = join(root, "home");
80
+ const env = { ...process.env };
81
+ for (const key of Object.keys(env)) if (key.startsWith("PI_SUBAGENT_")) delete env[key];
82
+ return {
83
+ ...env,
84
+ HOME: home,
85
+ XDG_CONFIG_HOME: join(home, ".config"),
86
+ XDG_CACHE_HOME: join(home, ".cache"),
87
+ PI_CODING_AGENT_DIR: agentDir,
88
+ PI_SUBAGENT_TEMP_ROOT: join(root, "pi-subagents-runtime"),
89
+ PI_OFFLINE: "1",
90
+ PATH: process.env.PATH ?? "",
91
+ };
92
+ }
93
+
94
+ function run(label, command, args, options) {
95
+ const { cwd, env, timeoutMs, input, signal, processes } = options;
96
+ signal.throwIfAborted();
97
+ return new Promise((resolve, reject) => {
98
+ let discovery;
99
+ let discoveryError;
100
+ const finish = async (error, output) => {
101
+ clearTimeout(timer);
102
+ clearInterval(watcher);
103
+ signal.removeEventListener("abort", cancel);
104
+ await discovery;
105
+ if (error) reject(error);
106
+ else resolve(output);
107
+ };
108
+ const child = execFile(command, args, { cwd, env, encoding: "utf8", detached: true, maxBuffer: 16 * 1024 * 1024 }, (error, stdout, stderr) => {
109
+ const output = `${stdout ?? ""}${stderr ?? ""}`;
110
+ void finish(error ? new Error(`${label} failed with ${error.code ?? "spawn error"}\nCommand: ${command} ${args.join(" ")}\n${output}`) : undefined, output);
111
+ });
112
+ attachChildProcessLifecycle(child);
113
+ if (child.pid) {
114
+ const entry = { child };
115
+ processes.set(child.pid, entry);
116
+ child.once("close", () => { entry.exited = !isChildTreeAlive(child); });
117
+ }
118
+ // Remember detached startup children while their parent is still alive, even if startup fails.
119
+ const watcher = setInterval(() => {
120
+ discovery ??= collectOwnedProcesses(options).catch((error) => {
121
+ if (error.message !== discoveryError) console.error(`[real-pi-smoke] process discovery: ${error.message}`);
122
+ discoveryError = error.message;
123
+ }).finally(() => { discovery = undefined; });
124
+ }, 100);
125
+ // Reject without killing the parent first: finally owns cleanup of it AND its detached workers.
126
+ const timer = setTimeout(() => { void finish(new Error(`${label} timed out after ${timeoutMs}ms\nCommand: ${command} ${args.join(" ")}`)); }, timeoutMs);
127
+ const cancel = () => { void finish(signal.reason); };
128
+ signal.addEventListener("abort", cancel, { once: true });
129
+ child.stdin.on("error", () => {}); // A command may exit without reading its RPC input.
130
+ child.stdin.end(input);
131
+ });
132
+ }
133
+
134
+ function* filesIn(dir) {
135
+ if (!existsSync(dir)) return;
136
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
137
+ const file = join(dir, entry.name);
138
+ if (entry.isDirectory()) yield* filesIn(file);
139
+ else if (entry.isFile()) yield file;
140
+ }
141
+ }
142
+
143
+ function processRef(pid) {
144
+ if (!Number.isSafeInteger(pid) || pid <= 1 || pid === process.pid) throw new Error("Invalid smoke-owned process ID");
145
+ return { pid, kill: (signal) => process.kill(pid, signal) };
146
+ }
147
+
148
+ async function collectOwnedProcesses({ root, env, processes }) {
149
+ const remember = (pid, broker = false) => {
150
+ if (pid === undefined) return;
151
+ if (!processes.has(pid)) processes.set(pid, { child: processRef(pid) });
152
+ if (broker) processes.get(pid).broker = true;
153
+ };
154
+ // Only this attempt's private run files, never the user's shared runtime or process argv.
155
+ for (const dir of [env.PI_SUBAGENT_TEMP_ROOT, join(env.PI_CODING_AGENT_DIR, "sessions", "subagent-runs")]) {
156
+ for (const file of filesIn(dir)) {
157
+ if (basename(file) === "status.json" || (basename(dirname(file)) === "contracts" && file.endsWith(".json"))) {
158
+ remember(JSON.parse(readFileSync(file, "utf8")).pid);
159
+ }
160
+ }
161
+ }
162
+ // The parent records the detached launcher PID; status.json records its runner, not the launcher.
163
+ for (const file of filesIn(join(root, "sessions"))) {
164
+ if (!file.endsWith(".jsonl")) continue;
165
+ const lines = readFileSync(file, "utf8").split("\n").slice(0, -1); // An active append may have a partial final line.
166
+ const header = lines[0] ? JSON.parse(lines[0]) : undefined;
167
+ for (const line of lines) {
168
+ if (!line.trim()) continue;
169
+ const entry = JSON.parse(line);
170
+ if (entry.type === "custom" && entry.customType === "subagent-run" && entry.data?.ownerSessionId === header?.id) remember(entry.data.pid);
171
+ }
172
+ }
173
+ const brokerPid = join(env.PI_CODING_AGENT_DIR, "intercom", "broker.pid");
174
+ if (existsSync(brokerPid)) remember(Number(readFileSync(brokerPid, "utf8").split("\n")[0]), true);
175
+ // Startup can precede PID-file publication. Query only direct children of known owned PIDs,
176
+ // including new Map entries (grandchildren), before signalling their parents. No argv/global scan.
177
+ for (const entry of processes.values()) {
178
+ if (!entry.exited) entry.exited = !isChildTreeAlive(entry.child);
179
+ if (entry.exited) continue;
180
+ const { child } = entry;
181
+ try {
182
+ const { stdout } = await execFileAsync("pgrep", ["-P", String(child.pid)], { env, encoding: "utf8", timeout: 1000 });
183
+ for (const pid of stdout.trim().split(/\s+/).filter(Boolean)) remember(Number(pid));
184
+ } catch (error) {
185
+ if (error.code !== 1) throw error; // pgrep's exit 1 means no matching children.
186
+ }
187
+ }
188
+ }
189
+
190
+ async function stopOwnedProcesses(options) {
191
+ let lastError;
192
+ while (true) {
193
+ let collected = false;
194
+ try {
195
+ await collectOwnedProcesses(options);
196
+ collected = true;
197
+ } catch (error) {
198
+ // Keep the controller alive and credentials in place if ownership cannot yet be read.
199
+ if (error.message !== lastError) console.error(`[real-pi-smoke] waiting for owned-process cleanup: ${error.message}`);
200
+ lastError = error.message;
201
+ }
202
+ const alive = [...options.processes.values()].filter((entry) => {
203
+ if (!entry.exited) entry.exited = !isChildTreeAlive(entry.child);
204
+ return !entry.exited;
205
+ });
206
+ if (collected && alive.length === 0) return;
207
+ const workers = alive.filter((entry) => !entry.broker);
208
+ // Stop the broker last, so exiting workers cannot restart it during cleanup.
209
+ for (const entry of workers.length ? workers : alive) {
210
+ if (!entry.stoppedAt) {
211
+ entry.stoppedAt = Date.now();
212
+ trySignalChildTree(entry.child, "SIGTERM");
213
+ } else if (Date.now() - entry.stoppedAt >= 3000) trySignalChildTree(entry.child, "SIGKILL");
214
+ }
215
+ await delay(50);
216
+ }
217
+ }
218
+
219
+ function runPi(label, args, options) {
220
+ return run(label, "pi", args, options);
221
+ }
222
+
223
+ async function verifyBundledResources(options) {
224
+ const output = await runPi("pi load bundled resources", ["--mode", "rpc", "--no-session", "--offline", "--approve"], {
225
+ ...options,
226
+ input: `${JSON.stringify({ id: "commands", type: "get_commands" })}\n`,
227
+ });
228
+ let response;
229
+ for (const line of output.split(/\r?\n/)) {
230
+ try {
231
+ const parsed = JSON.parse(line);
232
+ if (parsed?.type === "response" && parsed?.id === "commands") response = parsed;
233
+ } catch {
234
+ // Ignore non-protocol stderr lines.
235
+ }
236
+ }
237
+ const commands = response?.success === true && Array.isArray(response?.data?.commands)
238
+ ? response.data.commands.map((command) => command?.name)
239
+ : [];
240
+ for (const name of ["intercom", "subagents-doctor", "skill:pi-intercom", "skill:pi-subagents"]) {
241
+ if (!commands.includes(name)) throw new Error(`bundled Pi resources did not register ${name}:\n${output}`);
242
+ }
243
+ }
244
+
245
+ async function runLivePrompt(label, prompt, options, expectedTool) {
246
+ const args = ["--print", "--mode", "json", "--session-dir", join(options.root, "sessions"), "--approve"];
247
+ if (process.env.PI_REAL_SMOKE_PROVIDER) args.push("--provider", process.env.PI_REAL_SMOKE_PROVIDER);
248
+ if (process.env.PI_REAL_SMOKE_MODEL) args.push("--model", process.env.PI_REAL_SMOKE_MODEL, "--models", process.env.PI_REAL_SMOKE_MODEL);
249
+ args.push(prompt);
250
+ const output = await runPi(label, args, options);
251
+ writeFileSync(join(options.root, `${label.replace(/ /g, "-")}.jsonl`), output);
252
+ const events = output.split("\n").flatMap((line) => {
253
+ try { return [JSON.parse(line)]; } catch { return []; }
254
+ });
255
+ if (!events.some((event) => event.type === "tool_execution_start" && event.toolName === expectedTool)) {
256
+ throw new Error(`${label} never invoked ${expectedTool}; a matching final sentence is not execution evidence.`);
257
+ }
258
+ const errors = events.filter((event) => event.type === "tool_execution_end" && event.isError);
259
+ if (errors.length) throw new Error(`${label} had ${errors.length} failed tool call(s); inspect its saved wire log.`);
260
+ if (!events.some((event) => event.type === "agent_settled")) throw new Error(`${label} did not reach agent_settled.`);
261
+ return events.filter((event) => event.type === "message_end" && event.message?.role === "assistant")
262
+ .flatMap((event) => event.message.content.filter((part) => part.type === "text").map((part) => part.text)).join("\n");
263
+ }
264
+
265
+ function auditSavedModels(dir, expectedModel) {
266
+ const models = new Set();
267
+ let responses = 0;
268
+ const visit = (directory) => {
269
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
270
+ const file = join(directory, entry.name);
271
+ if (entry.isDirectory()) visit(file);
272
+ else if (entry.name.endsWith(".jsonl")) {
273
+ for (const line of readFileSync(file, "utf8").split("\n")) {
274
+ if (!line.trim()) continue;
275
+ const entry = JSON.parse(line);
276
+ if (entry.type !== "message" || entry.message?.role !== "assistant") continue;
277
+ responses++;
278
+ models.add(`${entry.message.provider}/${entry.message.model}`);
279
+ }
280
+ }
281
+ }
282
+ };
283
+ visit(dir);
284
+ if (!responses) throw new Error("No saved assistant messages found for model audit.");
285
+ if (expectedModel?.includes("/") && [...models].some((model) => model !== expectedModel)) {
286
+ throw new Error(`Unexpected model in saved parent/child sessions: ${[...models].join(", ")}`);
287
+ }
288
+ console.log(`[real-pi-smoke] audited ${responses} saved parent/child responses: ${[...models].join(", ")}`);
289
+ }
290
+
291
+ function requireOutput(label, output, pattern) {
292
+ if (!pattern.test(output)) {
293
+ throw new Error(`${label} did not include expected evidence ${pattern}.\nOutput:\n${output}`);
294
+ }
295
+ const compact = output.trim().split(/\r?\n/).slice(-8).join("\n");
296
+ console.log(`[real-pi-smoke] ${label} output evidence:\n${compact}`);
297
+ }
298
+
299
+ async function waitForAsyncCompletion(runId, pattern, { env, timeoutMs, signal }) {
300
+ const dir = join(env.PI_SUBAGENT_TEMP_ROOT, "async-subagent-runs", runId);
301
+ const deadline = Date.now() + timeoutMs;
302
+ let lastState = "missing";
303
+ let lastOutput = "";
304
+ while (Date.now() < deadline) {
305
+ signal.throwIfAborted();
306
+ const statusPath = join(dir, "status.json");
307
+ const outputPath = join(dir, "output-0.log");
308
+ if (existsSync(outputPath)) lastOutput = readFileSync(outputPath, "utf8");
309
+ if (existsSync(statusPath)) {
310
+ const status = JSON.parse(readFileSync(statusPath, "utf8"));
311
+ lastState = String(status.state ?? "unknown");
312
+ if (lastState === "complete" && status.pid && !isChildTreeAlive(processRef(status.pid))) {
313
+ if (!pattern.test(lastOutput)) throw new Error(`async run ${runId} completed without ${pattern}.\nOutput:\n${lastOutput}`);
314
+ const compact = lastOutput.trim().split(/\r?\n/).slice(-8).join("\n");
315
+ console.log(`[real-pi-smoke] async run ${runId} completed:\n${compact}`);
316
+ return;
317
+ }
318
+ if (lastState === "failed" || lastState === "paused") throw new Error(`async run ${runId} ended ${lastState}.\nOutput:\n${lastOutput}`);
319
+ }
320
+ await delay(500, undefined, { signal });
321
+ }
322
+ throw new Error(`async run ${runId} did not complete after ${timeoutMs}ms (last state: ${lastState}).\nOutput:\n${lastOutput}`);
323
+ }
324
+
325
+ async function main() {
326
+ let options;
327
+ try {
328
+ options = parseArgs(process.argv.slice(2));
329
+ } catch (error) {
330
+ console.error(`[real-pi-smoke] ${error instanceof Error ? error.message : String(error)}`);
331
+ usage();
332
+ process.exit(2);
333
+ }
334
+
335
+ const repoRoot = resolve(process.cwd());
336
+ const root = mkdtempSync(join(tmpdir(), "pi-subagents-real-pi-smoke-"));
337
+ const agentDir = join(root, "pi-agent");
338
+ const projectRoot = join(root, "project");
339
+ const projectAgentsDir = join(projectRoot, ".pi", "agents");
340
+ mkdirSync(projectAgentsDir, { recursive: true });
341
+ writeFileSync(join(projectAgentsDir, "real-smoke.md"), `---
342
+ name: real-smoke
343
+ description: Isolated live smoke agent
344
+ systemPromptMode: replace
345
+ inheritProjectContext: false
346
+ inheritSkills: false
347
+ tools: read
348
+ extensions:
349
+ ---
350
+
351
+ Follow the task exactly and return its requested text without using tools.
352
+ `, "utf-8");
353
+ const env = isolatedEnv(root, agentDir);
354
+ const cancellation = new AbortController();
355
+ const cancel = (signal) => cancellation.abort(new Error(`Cancelled by ${signal}`));
356
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) process.on(signal, cancel);
357
+ const runOptions = { cwd: projectRoot, env, timeoutMs: options.timeoutMs, root, signal: cancellation.signal, processes: new Map() };
358
+
359
+ try {
360
+ await runPi("pi install pi-subagents", ["install", repoRoot, "--approve"], runOptions);
361
+ const list = await runPi("pi list", ["list", "--approve"], runOptions);
362
+ if (!list.includes(repoRoot)) throw new Error(`pi list did not include ${repoRoot}:\n${list}`);
363
+ await verifyBundledResources(runOptions);
364
+ console.log(`[real-pi-smoke] active Pi ${(await runPi("pi version", ["--version"], runOptions)).trim()}`);
365
+
366
+ if (options.llm) {
367
+ const copiedAuthFiles = copyLiveAuth(agentDir);
368
+ if (copiedAuthFiles.length > 0) console.log(`[real-pi-smoke] copied ${copiedAuthFiles.join(" and ")} into isolated Pi agent dir for live provider auth`);
369
+ const childModelInstruction = process.env.PI_REAL_SMOKE_MODEL ? ` Pass model override '${process.env.PI_REAL_SMOKE_MODEL}' to every subagent run.` : "";
370
+ const intercomPrompt = "Call the intercom tool with action status. Reply exactly with 'real-pi-smoke intercom ok' if the tool output includes 'Connected: Yes'.";
371
+ const listPrompt = "Use the agent_runs tool with action profiles. Reply exactly with 'real-pi-smoke list ok' if reviewer, scout, oracle, and watcher are available.";
372
+ const foregroundPrompt = `Use the delegate tool to run real-smoke with task 'Reply exactly: real-pi-smoke foreground ok', async false and output false.${childModelInstruction} If the tool returns an output artifact path instead of inline output, read that file. Then reply exactly 'real-pi-smoke foreground ok' only if the child result contains it.`;
373
+ const asyncPrompt = `Use the delegate tool to run real-smoke with task 'Reply exactly: real-pi-smoke async ok', output false.${childModelInstruction} Set async true so it launches in the background. Do not call status and do not wait for completion. Reply with 'real-pi-smoke async launched ok' and quote the exact tool result line beginning 'Async:' including the run id.`;
374
+ requireOutput("real Pi intercom prompt", await runLivePrompt("real Pi intercom prompt", intercomPrompt, runOptions, "intercom"), /real-pi-smoke intercom ok/);
375
+ requireOutput("real Pi subagent list prompt", await runLivePrompt("real Pi subagent list prompt", listPrompt, runOptions, "agent_runs"), /real-pi-smoke list ok/);
376
+ requireOutput("real Pi foreground subagent prompt", await runLivePrompt("real Pi foreground subagent prompt", foregroundPrompt, runOptions, "delegate"), /real-pi-smoke foreground ok/);
377
+ const asyncOutput = await runLivePrompt("real Pi async subagent prompt", asyncPrompt, runOptions, "delegate");
378
+ requireOutput("real Pi async subagent prompt", asyncOutput, /real-pi-smoke async (?:launched )?ok/i);
379
+ const asyncRunId = asyncOutput.match(/Async(?: parallel)?:\s+(?:\S+|\[[^\]]+\])\s+\[([0-9a-f-]{36})\]/i)?.[1]
380
+ ?? asyncOutput.match(/\[([0-9a-f-]{36})\]/i)?.[1]
381
+ ?? asyncOutput.match(/\b([0-9a-f]{8}-[0-9a-f-]{27})\b/i)?.[1];
382
+ if (!asyncRunId) throw new Error(`Could not parse async run id from output:\n${asyncOutput}`);
383
+ await waitForAsyncCompletion(asyncRunId, /^real-pi-smoke async ok$/m, runOptions);
384
+
385
+ if (options.llmFull) {
386
+ const outputPath = join(root, "live-output-smoke.txt");
387
+ const parallelPrompt = `Use the subagent tool in parallel mode with two delegate tasks and async false. Task 1 replies exactly 'real-pi-smoke parallel A ok'. Task 2 replies exactly 'real-pi-smoke parallel B ok'. Set output false and progress false for both.${childModelInstruction} Reply exactly 'real-pi-smoke parallel ok' only if both child outputs are present.`;
388
+ const chainPrompt = `Use the subagent tool chain mode with two delegate steps and async false.${childModelInstruction} Step 1 task: 'Reply exactly: real-pi-smoke chain step1 ok'. Step 2 task: 'Previous output is {previous}. Reply exactly: real-pi-smoke chain step2 ok'. Reply exactly 'real-pi-smoke chain ok' only if step 2 ran after step 1.`;
389
+ const outputPrompt = `Use the subagent tool to run delegate with task 'Write exactly real-pi-smoke output ok plus newline to the requested output path, then reply exactly wrote output smoke'. Set async false, output to ${JSON.stringify(outputPath)}, and outputMode to file-only.${childModelInstruction} Reply exactly 'real-pi-smoke output ok' only after the tool returns.`;
390
+ const acceptancePrompt = `Use the subagent tool to run delegate with task 'Final answer exactly: real-pi-smoke acceptance ok evidence=manual-notes'. Set async false. Include acceptance criteria requiring the final answer to contain real-pi-smoke acceptance ok and evidence manual-notes, with maxFinalizationTurns 2.${childModelInstruction} Reply exactly 'real-pi-smoke acceptance ok' only if the child completed.`;
391
+ requireOutput("real Pi parallel subagent prompt", await runLivePrompt("real Pi parallel subagent prompt", parallelPrompt, runOptions, "subagent"), /real-pi-smoke parallel ok/);
392
+ requireOutput("real Pi chain subagent prompt", await runLivePrompt("real Pi chain subagent prompt", chainPrompt, runOptions, "subagent"), /real-pi-smoke chain ok/);
393
+ requireOutput("real Pi output subagent prompt", await runLivePrompt("real Pi output subagent prompt", outputPrompt, runOptions, "subagent"), /real-pi-smoke output ok/);
394
+ if (!existsSync(outputPath) || !/real-pi-smoke output ok/.test(readFileSync(outputPath, "utf8"))) throw new Error(`output smoke file missing expected content: ${outputPath}`);
395
+ requireOutput("real Pi acceptance subagent prompt", await runLivePrompt("real Pi acceptance subagent prompt", acceptancePrompt, runOptions, "subagent"), /real-pi-smoke acceptance ok/);
396
+ }
397
+ auditSavedModels(join(root, "sessions"), process.env.PI_REAL_SMOKE_MODEL);
398
+ }
399
+
400
+ console.log(`[real-pi-smoke] installed the single pi-subagents package, loaded bundled intercom, and verified pi list in ${agentDir}`);
401
+ if (!options.llm) console.log("[real-pi-smoke] live model subagent prompts skipped; pass --llm to exercise foreground/async paths.");
402
+ } finally {
403
+ await stopOwnedProcesses(runOptions);
404
+ rmSync(dirname(getBrokerSocketPath(agentDir)), { recursive: true, force: true });
405
+ for (const name of ["auth.json", "models.json"]) rmSync(join(agentDir, name), { force: true });
406
+ if (options.keepTemp) console.log(`[real-pi-smoke] kept temp root ${root}`);
407
+ else rmSync(root, { recursive: true, force: true });
408
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) process.off(signal, cancel);
409
+ }
410
+ }
411
+
412
+ main().catch((error) => {
413
+ console.error(`[real-pi-smoke] ${error instanceof Error ? error.message : String(error)}`);
414
+ process.exitCode = 1;
415
+ });
@@ -0,0 +1,149 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from "node:child_process";
3
+ import { mkdtempSync, readdirSync, rmSync } from "node:fs";
4
+ import { availableParallelism, tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+
7
+ const DEFAULT_TIMEOUT_MS = { unit: 300_000, integration: 900_000 };
8
+
9
+ function usage() {
10
+ console.log(`Usage: node scripts/run-tests.mjs [unit|integration|all] [--timeout-ms <ms>]\n\nRuns the local TypeScript test suites through Node's test runner.\n\nModes:\n unit Run test/unit/*.test.ts\n integration Run test/integration/*.test.ts\n all Run unit, then integration\n\nOptions:\n --timeout-ms <ms> Per-suite watchdog timeout in milliseconds\n -h, --help Show this help\n\nEnvironment:\n PI_TEST_TIMEOUT_MS Per-suite timeout when --timeout-ms is omitted (default: unit 300000, integration 900000)\n\nExit codes:\n 0 selected suite(s) passed\n 1 tests failed, timed out, or could not start\n 2 invalid arguments`);
11
+ }
12
+
13
+ function parsePositiveInteger(value, source) {
14
+ if (!/^\d+$/.test(value)) {
15
+ console.error(`${source} must be a positive integer number of milliseconds, got: ${value}`);
16
+ process.exit(2);
17
+ }
18
+ const parsed = Number(value);
19
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) {
20
+ console.error(`${source} must be a positive safe integer number of milliseconds, got: ${value}`);
21
+ process.exit(2);
22
+ }
23
+ return parsed;
24
+ }
25
+
26
+ function parseArgs(argv) {
27
+ let mode = "unit";
28
+ let timeoutMs = process.env.PI_TEST_TIMEOUT_MS
29
+ ? parsePositiveInteger(process.env.PI_TEST_TIMEOUT_MS, "PI_TEST_TIMEOUT_MS")
30
+ : undefined;
31
+
32
+ for (let index = 0; index < argv.length; index += 1) {
33
+ const arg = argv[index];
34
+ if (arg === "--help" || arg === "-h") {
35
+ usage();
36
+ process.exit(0);
37
+ }
38
+ if (arg === "--timeout-ms") {
39
+ const value = argv[index + 1];
40
+ if (!value) {
41
+ console.error("--timeout-ms requires a value");
42
+ process.exit(2);
43
+ }
44
+ timeoutMs = parsePositiveInteger(value, "--timeout-ms");
45
+ index += 1;
46
+ continue;
47
+ }
48
+ if (arg.startsWith("--timeout-ms=")) {
49
+ timeoutMs = parsePositiveInteger(arg.slice("--timeout-ms=".length), "--timeout-ms");
50
+ continue;
51
+ }
52
+ if (arg.startsWith("-")) {
53
+ console.error(`Unknown option: ${arg}`);
54
+ process.exit(2);
55
+ }
56
+ mode = arg;
57
+ }
58
+
59
+ if (!["unit", "integration", "all"].includes(mode)) {
60
+ console.error(`Unknown mode: ${mode}`);
61
+ usage();
62
+ process.exit(2);
63
+ }
64
+
65
+ return { mode, timeoutMs };
66
+ }
67
+
68
+ function testFiles(dir) {
69
+ return readdirSync(dir)
70
+ .filter((name) => name.endsWith(".test.ts"))
71
+ .sort()
72
+ .map((name) => join(dir, name));
73
+ }
74
+
75
+ function sanitizedEnv() {
76
+ const env = { ...process.env };
77
+ for (const key of Object.keys(env)) {
78
+ if (key.startsWith("PI_SUBAGENT_")) delete env[key];
79
+ }
80
+ return env;
81
+ }
82
+
83
+ function runNodeTest(label, imports, files, timeoutMs, concurrency) {
84
+ const args = [
85
+ ...imports.flatMap((specifier) => ["--import", specifier]),
86
+ ...(concurrency ? [`--test-concurrency=${concurrency}`] : []),
87
+ "--test",
88
+ ...files,
89
+ ];
90
+ const startedAt = Date.now();
91
+ const tempRoot = mkdtempSync(join(tmpdir(), "pi-subagents-test-"));
92
+ const env = sanitizedEnv();
93
+ env.PI_SUBAGENT_TEMP_ROOT = tempRoot;
94
+ env.HOME = tempRoot;
95
+ delete env.PI_CODING_AGENT_DIR;
96
+ let result;
97
+ try {
98
+ result = spawnSync(process.execPath, args, {
99
+ stdio: "inherit",
100
+ env,
101
+ timeout: timeoutMs,
102
+ killSignal: "SIGTERM",
103
+ });
104
+ } finally {
105
+ // Children of a killed runner can still be writing here; cleanup must not hide the timeout report.
106
+ try {
107
+ rmSync(tempRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
108
+ } catch (error) {
109
+ console.error(`Could not remove ${tempRoot}: ${error.message}`);
110
+ }
111
+ }
112
+ const elapsedMs = Date.now() - startedAt;
113
+ if (result.error) {
114
+ if (result.error.code === "ETIMEDOUT") {
115
+ console.error(`${label} timed out after ${timeoutMs}ms (elapsed ${elapsedMs}ms).`);
116
+ console.error(`Command: ${process.execPath} ${args.join(" ")}`);
117
+ console.error("Set PI_TEST_TIMEOUT_MS or pass --timeout-ms <ms> to adjust the local watchdog.");
118
+ return 1;
119
+ }
120
+ console.error(`Failed to start ${label}: ${result.error.message}`);
121
+ return 1;
122
+ }
123
+ if (result.signal) {
124
+ console.error(`${label} exited due to signal ${result.signal} after ${elapsedMs}ms.`);
125
+ console.error(`Command: ${process.execPath} ${args.join(" ")}`);
126
+ return 1;
127
+ }
128
+ return result.status ?? 1;
129
+ }
130
+
131
+ const { mode, timeoutMs } = parseArgs(process.argv.slice(2));
132
+ const unit = () => runNodeTest("unit tests", [], testFiles("test/unit"), timeoutMs ?? DEFAULT_TIMEOUT_MS.unit);
133
+ const integration = () => runNodeTest("integration tests", [], testFiles("test/integration"), timeoutMs ?? DEFAULT_TIMEOUT_MS.integration, Math.min(4, Math.max(1, availableParallelism() - 1)));
134
+
135
+ let status;
136
+ switch (mode) {
137
+ case "unit":
138
+ status = unit();
139
+ break;
140
+ case "integration":
141
+ status = integration();
142
+ break;
143
+ case "all":
144
+ status = unit();
145
+ if (status === 0) status = integration();
146
+ break;
147
+ }
148
+
149
+ process.exit(status);