@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,27 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+
5
+ // Node loads this before Pi selects its session and creates cwd-bound services.
6
+ // Use the SDK beside the actual CLI (bundled or unbundled), never our dev peer.
7
+ const configuration = process.env.PI_SUBAGENT_SESSION_CWD;
8
+ if (configuration) {
9
+ const { sessionFile, cwd, nodeOptions } = JSON.parse(configuration) as {
10
+ sessionFile: string;
11
+ cwd: string;
12
+ nodeOptions?: string;
13
+ };
14
+ const sdkUrl = pathToFileURL(join(dirname(realpathSync(process.argv[1])), "index.js"));
15
+ const { SessionManager }: typeof import("@earendil-works/pi-coding-agent") = await import(sdkUrl.href);
16
+ const open = SessionManager.open;
17
+ SessionManager.open = (file, sessionDir, cwdOverride) => {
18
+ if (resolve(file) !== sessionFile) return open(file, sessionDir, cwdOverride);
19
+ SessionManager.open = open;
20
+ // Keep the preload through a native launcher, then clear it before tools or nested children start.
21
+ delete process.env.PI_SUBAGENT_SESSION_CWD;
22
+ if (nodeOptions === undefined) delete process.env.NODE_OPTIONS;
23
+ else process.env.NODE_OPTIONS = nodeOptions;
24
+ // Public Pi SDK override preserves the file, header, identity and history.
25
+ return open(file, sessionDir, cwd);
26
+ };
27
+ }
@@ -0,0 +1,267 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { OutputMode, SavedOutputReference } from "../../shared/types.ts";
4
+
5
+ export interface SingleOutputSnapshot {
6
+ exists: boolean;
7
+ mtimeMs?: number;
8
+ ctimeMs?: number;
9
+ size?: number;
10
+ ino?: number;
11
+ }
12
+
13
+ export interface SingleOutputCleanupResult {
14
+ path: string;
15
+ action: "deleted" | "already-missing" | "skipped";
16
+ reason?: string;
17
+ error?: string;
18
+ }
19
+
20
+ export function normalizeSingleOutputOverride(
21
+ output: string | boolean | undefined,
22
+ defaultOutput: string | false | undefined,
23
+ ): string | false | undefined {
24
+ if (output === false || output === "false") return false;
25
+ if (output === true || output === "true") return defaultOutput;
26
+ if (typeof output === "string" && output.length > 0) return output;
27
+ return undefined;
28
+ }
29
+
30
+ export function resolveSingleOutputPath(
31
+ output: string | boolean | undefined,
32
+ runtimeCwd: string,
33
+ requestedCwd?: string,
34
+ ): string | undefined {
35
+ if (typeof output !== "string" || !output || output === "false" || output === "true") return undefined;
36
+ if (path.isAbsolute(output)) return output;
37
+ const baseCwd = requestedCwd
38
+ ? (path.isAbsolute(requestedCwd) ? requestedCwd : path.resolve(runtimeCwd, requestedCwd))
39
+ : runtimeCwd;
40
+ return path.resolve(baseCwd, output);
41
+ }
42
+
43
+ function safeOutputSegment(value: string, fallback: string): string {
44
+ const sanitized = value.replace(/[^\w.-]/g, "_").replace(/^\.+$/, "");
45
+ return sanitized || fallback;
46
+ }
47
+
48
+ export function materializeAgentDefaultOutputPath(params: {
49
+ output: string | false | undefined;
50
+ artifactsDir: string;
51
+ runId: string;
52
+ agent: string;
53
+ index?: number | string;
54
+ }): string | false | undefined {
55
+ if (typeof params.output !== "string" || !params.output || params.output === "false" || params.output === "true") return params.output;
56
+ if (path.isAbsolute(params.output)) return params.output;
57
+ const suffix = params.index !== undefined ? `_${safeOutputSegment(String(params.index), "index")}` : "";
58
+ const safeAgent = safeOutputSegment(params.agent, "agent");
59
+ const safeBaseName = safeOutputSegment(path.basename(params.output), "output.md");
60
+ return path.join(params.artifactsDir, "requested-outputs", `${params.runId}_${safeAgent}${suffix}_${safeBaseName}`);
61
+ }
62
+
63
+ export function injectSingleOutputInstruction(task: string, outputPath: string | undefined): string {
64
+ if (!outputPath) return task;
65
+ return `${task}\n\n---\n**Output:** Write your findings to: ${outputPath}`;
66
+ }
67
+
68
+ function countLines(text: string): number {
69
+ if (!text) return 0;
70
+ const newlineMatches = text.match(/\r\n|\r|\n/g);
71
+ return (newlineMatches?.length ?? 0) + (/[\r\n]$/.test(text) ? 0 : 1);
72
+ }
73
+
74
+ function formatByteSize(bytes: number): string {
75
+ if (bytes < 1024) return `${bytes} B`;
76
+ const units = ["KB", "MB", "GB", "TB"];
77
+ let value = bytes / 1024;
78
+ let unitIndex = 0;
79
+ while (value >= 1024 && unitIndex < units.length - 1) {
80
+ value /= 1024;
81
+ unitIndex++;
82
+ }
83
+ return `${value.toFixed(1)} ${units[unitIndex]}`;
84
+ }
85
+
86
+ export function formatSavedOutputReference(savedPath: string, fullOutput: string): SavedOutputReference {
87
+ const absolutePath = path.resolve(savedPath);
88
+ const bytes = Buffer.byteLength(fullOutput, "utf-8");
89
+ const lines = countLines(fullOutput);
90
+ return {
91
+ path: absolutePath,
92
+ bytes,
93
+ lines,
94
+ message: `Output saved to: ${absolutePath} (${formatByteSize(bytes)}, ${lines} ${lines === 1 ? "line" : "lines"}). Read this file if needed.`,
95
+ };
96
+ }
97
+
98
+ export function formatConsumedOutputReference(outputPath: string, fullOutput: string, cleanup: SingleOutputCleanupResult): SavedOutputReference {
99
+ const absolutePath = path.resolve(outputPath);
100
+ const bytes = Buffer.byteLength(fullOutput, "utf-8");
101
+ const lines = countLines(fullOutput);
102
+ const status = cleanup.action === "deleted"
103
+ ? "removed after capture"
104
+ : cleanup.action === "already-missing"
105
+ ? "already absent after capture"
106
+ : `not removed${cleanup.reason ? `: ${cleanup.reason}` : ""}`;
107
+ return {
108
+ path: absolutePath,
109
+ bytes,
110
+ lines,
111
+ message: `Output file consumed: ${absolutePath} (${formatByteSize(bytes)}, ${lines} ${lines === 1 ? "line" : "lines"}); ${status}.`,
112
+ };
113
+ }
114
+
115
+ export function findDuplicateOutputPath(
116
+ items: ReadonlyArray<{ agent: string; outputPath?: string }>,
117
+ ): string | undefined {
118
+ const seen = new Map<string, { index: number; agent: string }>();
119
+ for (let index = 0; index < items.length; index++) {
120
+ const outputPath = items[index]?.outputPath;
121
+ if (!outputPath) continue;
122
+ const previous = seen.get(outputPath);
123
+ if (previous) {
124
+ return `Parallel tasks ${previous.index + 1} (${previous.agent}) and ${index + 1} (${items[index]!.agent}) resolve output to the same path: ${outputPath}. Use distinct output paths.`;
125
+ }
126
+ seen.set(outputPath, { index, agent: items[index]!.agent });
127
+ }
128
+ return undefined;
129
+ }
130
+
131
+ export function validateFileOnlyOutputMode(outputMode: OutputMode | undefined, outputPath: string | undefined, context: string): string | undefined {
132
+ if (outputMode === "file-only" && !outputPath) {
133
+ return `${context} sets outputMode: "file-only" but does not configure an output file. Set output to a path or use outputMode: "inline".`;
134
+ }
135
+ return undefined;
136
+ }
137
+
138
+ export function captureSingleOutputSnapshot(outputPath: string | undefined): SingleOutputSnapshot | undefined {
139
+ if (!outputPath) return undefined;
140
+ try {
141
+ const stat = fs.statSync(outputPath);
142
+ return { exists: true, mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs, size: stat.size, ino: stat.ino };
143
+ } catch {
144
+ // The snapshot is advisory; resolveSingleOutput reports concrete read/write failures.
145
+ return { exists: false };
146
+ }
147
+ }
148
+
149
+ function matchesSnapshot(stat: fs.Stats, snapshot: SingleOutputSnapshot | undefined): boolean {
150
+ return snapshot?.exists === true
151
+ && stat.mtimeMs === snapshot.mtimeMs
152
+ && stat.ctimeMs === snapshot.ctimeMs
153
+ && stat.size === snapshot.size
154
+ && stat.ino === snapshot.ino;
155
+ }
156
+
157
+ function persistSingleOutput(
158
+ outputPath: string | undefined,
159
+ fullOutput: string,
160
+ ): { savedPath?: string; error?: string } {
161
+ if (!outputPath) return {};
162
+ try {
163
+ fs.mkdirSync(path.dirname(outputPath), { recursive: true });
164
+ fs.writeFileSync(outputPath, fullOutput, "utf-8");
165
+ return { savedPath: outputPath };
166
+ } catch (err) {
167
+ return { error: err instanceof Error ? err.message : String(err) };
168
+ }
169
+ }
170
+
171
+ export function resolveSingleOutput(
172
+ outputPath: string | undefined,
173
+ fallbackOutput: string,
174
+ beforeRun: SingleOutputSnapshot | undefined,
175
+ ): { fullOutput: string; savedPath?: string; saveError?: string; writtenSnapshot?: SingleOutputSnapshot } {
176
+ if (!outputPath) return { fullOutput: fallbackOutput };
177
+
178
+ try {
179
+ const stat = fs.statSync(outputPath);
180
+ if (!matchesSnapshot(stat, beforeRun)) {
181
+ // ponytail: acceptance and downstream prompts explicitly request this full
182
+ // individual output; it must fit their heap. Inspection uses readOutputPage.
183
+ return { fullOutput: fs.readFileSync(outputPath, "utf-8"), savedPath: outputPath };
184
+ }
185
+ } catch (error) {
186
+ const code = error && typeof error === "object" && "code" in error ? (error as { code?: unknown }).code : undefined;
187
+ if (code !== "ENOENT" && code !== "ENOTDIR") {
188
+ return {
189
+ fullOutput: fallbackOutput,
190
+ saveError: `Failed to read changed output file: ${error instanceof Error ? error.message : String(error)}`,
191
+ };
192
+ }
193
+ }
194
+
195
+ const save = persistSingleOutput(outputPath, fallbackOutput);
196
+ if (save.savedPath) return { fullOutput: fallbackOutput, savedPath: save.savedPath, writtenSnapshot: captureSingleOutputSnapshot(save.savedPath) };
197
+ return { fullOutput: fallbackOutput, saveError: save.error };
198
+ }
199
+
200
+ export function cleanupSingleOutputFile(
201
+ outputPath: string | undefined,
202
+ fullOutput: string,
203
+ beforeRun: SingleOutputSnapshot | undefined,
204
+ ): SingleOutputCleanupResult | undefined {
205
+ if (!outputPath) return undefined;
206
+ const absolutePath = path.resolve(outputPath);
207
+ try {
208
+ const stat = fs.statSync(outputPath);
209
+ const fd = fs.openSync(outputPath, "r");
210
+ let equal = stat.size === Buffer.byteLength(fullOutput);
211
+ try {
212
+ let position = 0;
213
+ for (let start = 0; equal && start < fullOutput.length;) {
214
+ let end = Math.min(start + 16384, fullOutput.length);
215
+ if (end < fullOutput.length && /[\uD800-\uDBFF]/.test(fullOutput[end - 1]!)) end--;
216
+ const expected = Buffer.from(fullOutput.slice(start, end));
217
+ const actual = Buffer.allocUnsafe(expected.length);
218
+ equal = fs.readSync(fd, actual, 0, actual.length, position) === actual.length && actual.equals(expected);
219
+ position += expected.length; start = end;
220
+ }
221
+ const current = fs.fstatSync(fd), located = fs.statSync(outputPath);
222
+ equal &&= current.ino === stat.ino && current.size === stat.size && current.ctimeMs === stat.ctimeMs
223
+ && located.ino === current.ino && located.dev === current.dev && located.ctimeMs === current.ctimeMs;
224
+ } finally { fs.closeSync(fd); }
225
+ if (!equal) {
226
+ return { path: absolutePath, action: "skipped", reason: "file changed after capture" };
227
+ }
228
+ if (matchesSnapshot(stat, beforeRun)) {
229
+ return { path: absolutePath, action: "skipped", reason: "file preexisted and was unchanged" };
230
+ }
231
+ fs.unlinkSync(outputPath);
232
+ return { path: absolutePath, action: "deleted" };
233
+ } catch (error) {
234
+ const code = error && typeof error === "object" && "code" in error ? (error as { code?: unknown }).code : undefined;
235
+ if (code === "ENOENT" || code === "ENOTDIR") return { path: absolutePath, action: "already-missing" };
236
+ return { path: absolutePath, action: "skipped", error: error instanceof Error ? error.message : String(error) };
237
+ }
238
+ }
239
+
240
+ export function finalizeSingleOutput(params: {
241
+ fullOutput: string;
242
+ truncatedOutput?: string;
243
+ outputPath?: string;
244
+ outputMode?: OutputMode;
245
+ exitCode: number;
246
+ savedPath?: string;
247
+ outputReference?: SavedOutputReference;
248
+ saveError?: string;
249
+ cleanup?: SingleOutputCleanupResult;
250
+ }): { displayOutput: string; savedPath?: string; outputReference?: SavedOutputReference; saveError?: string } {
251
+ let displayOutput = params.truncatedOutput || params.fullOutput;
252
+ if (params.exitCode === 0 && params.savedPath) {
253
+ const outputReference = params.outputReference ?? (params.cleanup && params.outputMode !== "file-only"
254
+ ? formatConsumedOutputReference(params.savedPath, params.fullOutput, params.cleanup)
255
+ : formatSavedOutputReference(params.savedPath, params.fullOutput));
256
+ if (params.outputMode === "file-only") {
257
+ return { displayOutput: outputReference.message, savedPath: params.savedPath, outputReference };
258
+ }
259
+ displayOutput += `\n\n${outputReference.message}`;
260
+ return { displayOutput, savedPath: params.cleanup ? undefined : params.savedPath, outputReference };
261
+ }
262
+ if (params.exitCode === 0 && params.saveError && params.outputPath) {
263
+ displayOutput += `\n\nOutput file error: ${params.outputPath}\n${params.saveError}`;
264
+ return { displayOutput, saveError: params.saveError };
265
+ }
266
+ return { displayOutput };
267
+ }
@@ -0,0 +1,18 @@
1
+ import type { JsonAgentSessionEvent } from "@earendil-works/pi-coding-agent";
2
+
3
+ type TextEvent = {
4
+ type?: string;
5
+ message?: { role: string };
6
+ assistantMessageEvent?: Extract<JsonAgentSessionEvent, { type: "message_update" }>["assistantMessageEvent"];
7
+ };
8
+
9
+ /** Native JSON stdout sends text deltas, not cumulative message/partial snapshots. */
10
+ export function updateStreamingText(current: string | undefined, event: TextEvent): string | undefined {
11
+ if (event.type === "agent_start" || event.type === "message_end" && event.message?.role === "assistant") return undefined;
12
+ if (event.type === "message_start" && event.message?.role === "assistant") return "";
13
+ if (event.type !== "message_update") return current;
14
+ const update = event.assistantMessageEvent;
15
+ if (update?.type === "text_start") return current ? `${current}\n\n` : "";
16
+ if (update?.type === "text_delta") return ((current ?? "") + update.delta).slice(-8192);
17
+ return current;
18
+ }
@@ -0,0 +1,68 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { Compile } from "../../shared/native-typebox.ts";
5
+ import type { JsonSchemaObject } from "../../shared/types.ts";
6
+
7
+ export const STRUCTURED_OUTPUT_SCHEMA_ENV = "PI_SUBAGENT_STRUCTURED_OUTPUT_SCHEMA";
8
+ export const STRUCTURED_OUTPUT_CAPTURE_ENV = "PI_SUBAGENT_STRUCTURED_OUTPUT_CAPTURE";
9
+
10
+ export interface StructuredOutputRuntime {
11
+ schema: JsonSchemaObject;
12
+ schemaPath: string;
13
+ outputPath: string;
14
+ }
15
+
16
+ interface CompiledJsonSchema {
17
+ Check(value: unknown): boolean;
18
+ Errors(value: unknown): Iterable<{ instancePath?: string; message?: string }>;
19
+ }
20
+
21
+ export function assertJsonSchemaObject(schema: unknown, label = "outputSchema"): asserts schema is JsonSchemaObject {
22
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
23
+ throw new Error(`${label} must be a JSON Schema object.`);
24
+ }
25
+ }
26
+
27
+ export function createStructuredOutputRuntime(schema: JsonSchemaObject, baseDir?: string): StructuredOutputRuntime {
28
+ assertJsonSchemaObject(schema);
29
+ const rootDir = baseDir ?? os.tmpdir();
30
+ fs.mkdirSync(rootDir, { recursive: true });
31
+ const dir = fs.mkdtempSync(path.join(rootDir, "pi-subagent-structured-"));
32
+ const schemaPath = path.join(dir, "schema.json");
33
+ const outputPath = path.join(dir, "output.json");
34
+ fs.writeFileSync(schemaPath, JSON.stringify(schema), { mode: 0o600 });
35
+ return { schema, schemaPath, outputPath };
36
+ }
37
+
38
+ export function validateStructuredOutputValue(schema: JsonSchemaObject, value: unknown): { status: "valid" } | { status: "invalid"; message: string } {
39
+ let validator: CompiledJsonSchema;
40
+ try {
41
+ validator = (Compile as (schema: unknown) => CompiledJsonSchema)(schema);
42
+ } catch (error) {
43
+ return { status: "invalid", message: `invalid outputSchema: ${error instanceof Error ? error.message : String(error)}` };
44
+ }
45
+ if (validator.Check(value)) return { status: "valid" };
46
+ const errors = [...validator.Errors(value)]
47
+ .slice(0, 8)
48
+ .map((error) => {
49
+ const pathText = error.instancePath ? error.instancePath.replace(/^\//, "").replace(/\//g, ".") : "root";
50
+ return `${pathText}: ${error.message}`;
51
+ });
52
+ return { status: "invalid", message: errors.join("; ") || "schema validation failed" };
53
+ }
54
+
55
+ export function readStructuredOutput(runtime: StructuredOutputRuntime): { value?: unknown; error?: string } {
56
+ if (!fs.existsSync(runtime.outputPath)) {
57
+ return { error: "Missing structured_output call; this step has outputSchema and must finish by calling structured_output." };
58
+ }
59
+ let value: unknown;
60
+ try {
61
+ value = JSON.parse(fs.readFileSync(runtime.outputPath, "utf-8"));
62
+ } catch (error) {
63
+ return { error: `Failed to read structured output: ${error instanceof Error ? error.message : String(error)}` };
64
+ }
65
+ const validation = validateStructuredOutputValue(runtime.schema, value);
66
+ if (validation.status === "invalid") return { error: `Structured output validation failed: ${validation.message}` };
67
+ return { value };
68
+ }
@@ -0,0 +1,219 @@
1
+ import {
2
+ type ActivityState,
3
+ type ControlConfig,
4
+ type ControlEvent,
5
+ type ControlEventType,
6
+ type ControlNotificationChannel,
7
+ type ResolvedControlConfig,
8
+ } from "../../shared/types.ts";
9
+
10
+ import { formatRunAction } from "../../shared/status-format.ts";
11
+ import { readStatus } from "../../shared/utils.ts";
12
+ import { getRunMetadataDir } from "./supervisor-questions.ts";
13
+
14
+ export function isObsoleteIdleNotice(details: { event: ControlEvent; asyncDir?: string }): boolean {
15
+ const event = details?.event;
16
+ if (!event || event.reason !== "idle" || event.supervisorQuestion) return false;
17
+ let status;
18
+ try {
19
+ status = readStatus(details.asyncDir ?? getRunMetadataDir(event.runId));
20
+ } catch {
21
+ // Without readable terminal evidence, retain the actionable notice.
22
+ return false;
23
+ }
24
+ if (!status || status.runId !== event.runId) return false;
25
+ const child = event.index === undefined ? undefined : status.steps?.[event.index];
26
+ return ["complete", "failed", "blocked", "paused"].includes(status.state)
27
+ || Boolean(child && ["complete", "completed", "failed", "blocked", "paused", "timed-out"].includes(child.status));
28
+ }
29
+
30
+ const CONTROL_EVENT_TYPES: ControlEventType[] = ["needs_attention"];
31
+ const CONTROL_NOTIFICATION_CHANNELS: ControlNotificationChannel[] = ["event", "async", "intercom"];
32
+ const DEFAULT_NOTIFY_ON: ControlEventType[] = ["needs_attention"];
33
+
34
+ export const DEFAULT_CONTROL_CONFIG: ResolvedControlConfig = {
35
+ enabled: true,
36
+ needsAttentionAfterMs: 10 * 60_000,
37
+ failedToolAttemptsBeforeAttention: 3,
38
+ notifyOn: DEFAULT_NOTIFY_ON,
39
+ notifyChannels: CONTROL_NOTIFICATION_CHANNELS,
40
+ };
41
+
42
+ function parsePositiveInt(value: unknown): number | undefined {
43
+ if (typeof value !== "number") return undefined;
44
+ if (!Number.isFinite(value) || !Number.isInteger(value) || value < 1) return undefined;
45
+ return value;
46
+ }
47
+
48
+ function parseControlList<T extends string>(value: unknown, allowed: readonly T[]): T[] | undefined {
49
+ if (!Array.isArray(value)) return undefined;
50
+ if (value.length === 0) return [];
51
+ const allowedSet = new Set(allowed);
52
+ const parsed = value.filter((entry): entry is T => typeof entry === "string" && allowedSet.has(entry as T));
53
+ return parsed.length > 0 ? Array.from(new Set(parsed)) : undefined;
54
+ }
55
+
56
+ export function resolveControlConfig(
57
+ globalConfig?: ControlConfig,
58
+ override?: ControlConfig,
59
+ ): ResolvedControlConfig {
60
+ const enabled = override?.enabled ?? globalConfig?.enabled ?? DEFAULT_CONTROL_CONFIG.enabled;
61
+ const needsAttentionAfterMs = parsePositiveInt(override?.needsAttentionAfterMs)
62
+ ?? parsePositiveInt(globalConfig?.needsAttentionAfterMs)
63
+ ?? DEFAULT_CONTROL_CONFIG.needsAttentionAfterMs;
64
+ const failedToolAttemptsBeforeAttention = parsePositiveInt(override?.failedToolAttemptsBeforeAttention)
65
+ ?? parsePositiveInt(globalConfig?.failedToolAttemptsBeforeAttention)
66
+ ?? DEFAULT_CONTROL_CONFIG.failedToolAttemptsBeforeAttention;
67
+ const notifyOn = parseControlList(override?.notifyOn, CONTROL_EVENT_TYPES)
68
+ ?? parseControlList(globalConfig?.notifyOn, CONTROL_EVENT_TYPES)
69
+ ?? DEFAULT_CONTROL_CONFIG.notifyOn;
70
+ const notifyChannels = parseControlList(override?.notifyChannels, CONTROL_NOTIFICATION_CHANNELS)
71
+ ?? parseControlList(globalConfig?.notifyChannels, CONTROL_NOTIFICATION_CHANNELS)
72
+ ?? DEFAULT_CONTROL_CONFIG.notifyChannels;
73
+ return {
74
+ enabled,
75
+ needsAttentionAfterMs,
76
+ failedToolAttemptsBeforeAttention,
77
+ notifyOn: [...notifyOn],
78
+ notifyChannels: [...notifyChannels],
79
+ };
80
+ }
81
+
82
+ export function deriveActivityState(input: {
83
+ config: ResolvedControlConfig;
84
+ startedAt: number;
85
+ lastActivityAt?: number;
86
+ now?: number;
87
+ }): ActivityState | undefined {
88
+ if (!input.config.enabled) return undefined;
89
+ const now = input.now ?? Date.now();
90
+ const lastActivity = input.lastActivityAt ?? input.startedAt;
91
+ const ageMs = Math.max(0, now - lastActivity);
92
+ return ageMs > input.config.needsAttentionAfterMs ? "needs_attention" : undefined;
93
+ }
94
+
95
+ export function buildControlEvent(input: {
96
+ type?: ControlEventType;
97
+ from?: ActivityState;
98
+ to: ActivityState;
99
+ runId: string;
100
+ agent: string;
101
+ index?: number;
102
+ ts?: number;
103
+ lastActivityAt?: number;
104
+ message?: string;
105
+ reason?: ControlEvent["reason"];
106
+ turns?: number;
107
+ tokens?: number;
108
+ toolCount?: number;
109
+ currentTool?: string;
110
+ currentToolDurationMs?: number;
111
+ currentPath?: string;
112
+ elapsedMs?: number;
113
+ recentFailureSummary?: string;
114
+ supervisorQuestion?: ControlEvent["supervisorQuestion"];
115
+ }): ControlEvent {
116
+ const ts = input.ts ?? Date.now();
117
+ const type = input.type ?? "needs_attention";
118
+ const elapsedMs = input.elapsedMs ?? (input.lastActivityAt !== undefined ? Math.max(0, ts - input.lastActivityAt) : undefined);
119
+ const elapsedSeconds = elapsedMs !== undefined ? Math.floor(elapsedMs / 1000) : undefined;
120
+ const question = input.supervisorQuestion;
121
+ const observation = input.currentTool
122
+ ? `${input.currentTool} still active${input.currentToolDurationMs !== undefined ? ` for ${Math.floor(input.currentToolDurationMs / 1000)}s` : ""}${elapsedSeconds !== undefined ? `; no observed output/events for ${elapsedSeconds}s` : ""}`
123
+ : elapsedSeconds !== undefined ? `no observed activity for ${elapsedSeconds}s` : undefined;
124
+ const signal = question
125
+ ? question.state === "awaiting_input" ? `Waiting for supervisor input (question ${question.questionId})` : `Supervisor answer saved for question ${question.questionId}; delivery unconfirmed`
126
+ : `${input.agent} needs attention`;
127
+ const message = input.message ?? `${signal}${observation ? ` (${observation})` : ""}`;
128
+ return {
129
+ type,
130
+ ...(input.from ? { from: input.from } : {}),
131
+ to: input.to,
132
+ ts,
133
+ runId: input.runId,
134
+ agent: input.agent,
135
+ ...(input.index !== undefined ? { index: input.index } : {}),
136
+ message,
137
+ reason: input.reason ?? "idle",
138
+ ...(input.turns !== undefined ? { turns: input.turns } : {}),
139
+ ...(input.tokens !== undefined ? { tokens: input.tokens } : {}),
140
+ ...(input.toolCount !== undefined ? { toolCount: input.toolCount } : {}),
141
+ ...(input.currentTool ? { currentTool: input.currentTool } : {}),
142
+ ...(input.currentToolDurationMs !== undefined ? { currentToolDurationMs: input.currentToolDurationMs } : {}),
143
+ ...(input.currentPath ? { currentPath: input.currentPath } : {}),
144
+ ...(elapsedMs !== undefined ? { elapsedMs } : {}),
145
+ ...(input.recentFailureSummary ? { recentFailureSummary: input.recentFailureSummary } : {}),
146
+ ...(question ? { supervisorQuestion: question } : {}),
147
+ };
148
+ }
149
+
150
+ export function shouldNotifyControlEvent(config: ResolvedControlConfig, event: ControlEvent): boolean {
151
+ return config.enabled && config.notifyOn.includes(event.type);
152
+ }
153
+
154
+ export function controlNotificationKey(event: ControlEvent, childIntercomTarget?: string): string {
155
+ const childKey = childIntercomTarget ?? (event.index !== undefined ? `${event.runId}:${event.index}` : event.runId);
156
+ return `${childKey}:${event.type}:${event.reason ?? "idle"}`;
157
+ }
158
+
159
+ export function claimControlNotification(config: ResolvedControlConfig, event: ControlEvent, seenKeys: Set<string>, childIntercomTarget?: string): boolean {
160
+ if (!shouldNotifyControlEvent(config, event)) return false;
161
+ const key = controlNotificationKey(event, childIntercomTarget);
162
+ if (seenKeys.has(key)) return false;
163
+ seenKeys.add(key);
164
+ return true;
165
+ }
166
+
167
+ export function formatControlNoticeMessage(event: ControlEvent, childIntercomTarget?: string, childSafe = false): string {
168
+ const runTarget = event.runId;
169
+ if (event.reason === "completion_guard") {
170
+ return [
171
+ `Subagent failed: ${event.agent}`,
172
+ `Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
173
+ `Signal: ${event.message}`,
174
+ "Next: read the output artifact or session from the subagent result, then retry with a more explicit implementation prompt or handle the fix directly.",
175
+ childIntercomTarget ? `Run intercom target (may be inactive): ${childIntercomTarget}` : undefined,
176
+ ].filter((line): line is string => Boolean(line)).join("\n");
177
+ }
178
+
179
+ const nudgeCommand = formatRunAction("nudge", runTarget, { ...(event.index !== undefined ? { index: event.index } : {}), message: "What are you blocked on? Reply with the smallest next step, or state the exact decision you need." }, childSafe);
180
+ const question = event.supervisorQuestion;
181
+ const askCommand = childIntercomTarget
182
+ ? `intercom({ action: "ask", to: "${childIntercomTarget}", delivery: "steer", message: "What are you blocked on? Reply with the smallest next step, or state the exact decision you need." })`
183
+ : undefined;
184
+ return [
185
+ `Subagent needs attention: ${event.agent}`,
186
+ `Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
187
+ `Signal: ${event.message}`,
188
+ event.recentFailureSummary ? `Recent failures: ${event.recentFailureSummary}` : undefined,
189
+ ...(question ? [
190
+ `Question ID: ${question.questionId}`,
191
+ question.state === "answer_pending" ? "The saved answer has not been confirmed delivered. Inspect the child and retry the same answer; do not assume it resumed." : "Answer the saved question so the child can continue.",
192
+ `Questions: ${formatRunAction("questions", runTarget, {}, childSafe)}`,
193
+ `Answer: ${formatRunAction("answer", runTarget, { questionId: question.questionId, message: question.answer ?? "..." }, childSafe)}`,
194
+ ] : [
195
+ event.reason === "idle" && event.currentTool ? "Hint: Inspect command progress. A long-running tool may still be running or hung; elapsed time alone does not prove either." : "Hint: Inspect status first unless the run is clearly blocked.",
196
+ `Nudge (preferred live coordination): ${nudgeCommand}`,
197
+ childIntercomTarget
198
+ ? `Ask (blocking wait only; parent must remain alive): ${askCommand}`
199
+ : "Ask (blocking wait only): no child message route registered",
200
+ ]),
201
+ `Status: ${formatRunAction("status", runTarget, {}, childSafe)}`,
202
+ `${childSafe ? "Interrupt" : "Stop"}: ${formatRunAction("interrupt", runTarget, {}, childSafe)}`,
203
+ ].filter((line): line is string => Boolean(line)).join("\n");
204
+ }
205
+
206
+ export function formatControlIntercomMessage(event: ControlEvent, childIntercomTarget?: string, childSafe = false): string {
207
+ const statusLabel = event.reason === "completion_guard"
208
+ ? "subagent failed"
209
+ : "subagent needs attention";
210
+ return [
211
+ statusLabel,
212
+ "",
213
+ event.reason === "completion_guard"
214
+ ? `${event.agent} failed in run ${event.runId}.`
215
+ : `${event.agent} needs attention in run ${event.runId}.`,
216
+ "",
217
+ formatControlNoticeMessage(event, childIntercomTarget, childSafe),
218
+ ].join("\n");
219
+ }