@agimon-ai/doompi-team 0.0.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (520) hide show
  1. package/LICENSE +25 -0
  2. package/README.md +46 -0
  3. package/dist/_virtual/_@oxc-project_runtime@0.127.0/helpers/decorate.cjs +1 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.127.0/helpers/decorate.mjs +1 -0
  5. package/dist/_virtual/_@oxc-project_runtime@0.127.0/helpers/decorateMetadata.cjs +1 -0
  6. package/dist/_virtual/_@oxc-project_runtime@0.127.0/helpers/decorateMetadata.mjs +1 -0
  7. package/dist/_virtual/_@oxc-project_runtime@0.127.0/helpers/decorateParam.cjs +1 -0
  8. package/dist/_virtual/_@oxc-project_runtime@0.127.0/helpers/decorateParam.mjs +1 -0
  9. package/dist/_virtual/_rolldown/runtime.cjs +1 -0
  10. package/dist/_virtual/_rolldown/runtime.mjs +1 -0
  11. package/dist/agents/discovery.cjs +2 -0
  12. package/dist/agents/discovery.cjs.map +1 -0
  13. package/dist/agents/discovery.mjs +2 -0
  14. package/dist/agents/discovery.mjs.map +1 -0
  15. package/dist/agents/frontmatter.cjs +10 -0
  16. package/dist/agents/frontmatter.cjs.map +1 -0
  17. package/dist/agents/frontmatter.mjs +10 -0
  18. package/dist/agents/frontmatter.mjs.map +1 -0
  19. package/dist/agents/loader.cjs +2 -0
  20. package/dist/agents/loader.cjs.map +1 -0
  21. package/dist/agents/loader.mjs +2 -0
  22. package/dist/agents/loader.mjs.map +1 -0
  23. package/dist/agents/memory.cjs +3 -0
  24. package/dist/agents/memory.cjs.map +1 -0
  25. package/dist/agents/memory.mjs +3 -0
  26. package/dist/agents/memory.mjs.map +1 -0
  27. package/dist/agents/projectRoot.cjs +2 -0
  28. package/dist/agents/projectRoot.cjs.map +1 -0
  29. package/dist/agents/projectRoot.mjs +2 -0
  30. package/dist/agents/projectRoot.mjs.map +1 -0
  31. package/dist/agents/settings.cjs +2 -0
  32. package/dist/agents/settings.cjs.map +1 -0
  33. package/dist/agents/settings.mjs +2 -0
  34. package/dist/agents/settings.mjs.map +1 -0
  35. package/dist/agents/skills.cjs +0 -0
  36. package/dist/agents/skills.cjs.map +1 -0
  37. package/dist/agents/skills.mjs +5 -0
  38. package/dist/agents/skills.mjs.map +1 -0
  39. package/dist/agents/types.d.cts +121 -0
  40. package/dist/agents/types.d.cts.map +1 -0
  41. package/dist/agents/types.d.mts +121 -0
  42. package/dist/agents/types.d.mts.map +1 -0
  43. package/dist/api/backgroundWork.cjs +1 -0
  44. package/dist/api/backgroundWork.d.cts +2 -0
  45. package/dist/api/backgroundWork.d.mts +2 -0
  46. package/dist/api/backgroundWork.mjs +1 -0
  47. package/dist/api/capabilityCeiling.cjs +1 -0
  48. package/dist/api/capabilityCeiling.d.cts +3 -0
  49. package/dist/api/capabilityCeiling.d.mts +3 -0
  50. package/dist/api/capabilityCeiling.mjs +2 -0
  51. package/dist/api/capabilityCeiling.mjs.map +1 -0
  52. package/dist/api/delegation.cjs +1 -0
  53. package/dist/api/delegation.d.cts +2 -0
  54. package/dist/api/delegation.d.mts +2 -0
  55. package/dist/api/delegation.mjs +1 -0
  56. package/dist/api/teamSnapshot.cjs +1 -0
  57. package/dist/api/teamSnapshot.d.cts +2 -0
  58. package/dist/api/teamSnapshot.d.mts +2 -0
  59. package/dist/api/teamSnapshot.mjs +2 -0
  60. package/dist/api/teamSnapshot.mjs.map +1 -0
  61. package/dist/container/bindOrRebind.cjs +2 -0
  62. package/dist/container/bindOrRebind.cjs.map +1 -0
  63. package/dist/container/bindOrRebind.mjs +2 -0
  64. package/dist/container/bindOrRebind.mjs.map +1 -0
  65. package/dist/container/globalBridge.cjs +2 -0
  66. package/dist/container/globalBridge.cjs.map +1 -0
  67. package/dist/container/globalBridge.d.cts +19 -0
  68. package/dist/container/globalBridge.d.cts.map +1 -0
  69. package/dist/container/globalBridge.d.mts +19 -0
  70. package/dist/container/globalBridge.d.mts.map +1 -0
  71. package/dist/container/globalBridge.mjs +2 -0
  72. package/dist/container/globalBridge.mjs.map +1 -0
  73. package/dist/container/index.cjs +2 -0
  74. package/dist/container/index.cjs.map +1 -0
  75. package/dist/container/index.d.cts +38 -0
  76. package/dist/container/index.d.cts.map +1 -0
  77. package/dist/container/index.d.mts +38 -0
  78. package/dist/container/index.d.mts.map +1 -0
  79. package/dist/container/index.mjs +2 -0
  80. package/dist/container/index.mjs.map +1 -0
  81. package/dist/container/modules/agents.cjs +2 -0
  82. package/dist/container/modules/agents.cjs.map +1 -0
  83. package/dist/container/modules/agents.d.cts +1 -0
  84. package/dist/container/modules/agents.d.mts +1 -0
  85. package/dist/container/modules/agents.mjs +2 -0
  86. package/dist/container/modules/agents.mjs.map +1 -0
  87. package/dist/container/modules/core.cjs +2 -0
  88. package/dist/container/modules/core.cjs.map +1 -0
  89. package/dist/container/modules/core.d.cts +1 -0
  90. package/dist/container/modules/core.d.mts +1 -0
  91. package/dist/container/modules/core.mjs +2 -0
  92. package/dist/container/modules/core.mjs.map +1 -0
  93. package/dist/container/modules/extensions.cjs +2 -0
  94. package/dist/container/modules/extensions.cjs.map +1 -0
  95. package/dist/container/modules/extensions.mjs +2 -0
  96. package/dist/container/modules/extensions.mjs.map +1 -0
  97. package/dist/container/modules/intercom.cjs +2 -0
  98. package/dist/container/modules/intercom.cjs.map +1 -0
  99. package/dist/container/modules/intercom.mjs +2 -0
  100. package/dist/container/modules/intercom.mjs.map +1 -0
  101. package/dist/container/modules/runs.cjs +2 -0
  102. package/dist/container/modules/runs.cjs.map +1 -0
  103. package/dist/container/modules/runs.mjs +2 -0
  104. package/dist/container/modules/runs.mjs.map +1 -0
  105. package/dist/container/types.cjs +2 -0
  106. package/dist/container/types.cjs.map +1 -0
  107. package/dist/container/types.d.cts +45 -0
  108. package/dist/container/types.d.cts.map +1 -0
  109. package/dist/container/types.d.mts +45 -0
  110. package/dist/container/types.d.mts.map +1 -0
  111. package/dist/container/types.mjs +2 -0
  112. package/dist/container/types.mjs.map +1 -0
  113. package/dist/env.cjs +2 -0
  114. package/dist/env.cjs.map +1 -0
  115. package/dist/env.d.cts +65 -0
  116. package/dist/env.d.cts.map +1 -0
  117. package/dist/env.d.mts +65 -0
  118. package/dist/env.d.mts.map +1 -0
  119. package/dist/env.mjs +2 -0
  120. package/dist/env.mjs.map +1 -0
  121. package/dist/extension.cjs +2 -0
  122. package/dist/extension.cjs.map +1 -0
  123. package/dist/extension.mjs +2 -0
  124. package/dist/extension.mjs.map +1 -0
  125. package/dist/extensions/config.cjs +2 -0
  126. package/dist/extensions/config.cjs.map +1 -0
  127. package/dist/extensions/config.mjs +2 -0
  128. package/dist/extensions/config.mjs.map +1 -0
  129. package/dist/extensions/delegationBridge.cjs +2 -0
  130. package/dist/extensions/delegationBridge.cjs.map +1 -0
  131. package/dist/extensions/delegationBridge.mjs +2 -0
  132. package/dist/extensions/delegationBridge.mjs.map +1 -0
  133. package/dist/extensions/doom.cjs +2 -0
  134. package/dist/extensions/doom.cjs.map +1 -0
  135. package/dist/extensions/doom.d.cts +8 -0
  136. package/dist/extensions/doom.d.cts.map +1 -0
  137. package/dist/extensions/doom.d.mts +8 -0
  138. package/dist/extensions/doom.d.mts.map +1 -0
  139. package/dist/extensions/doom.mjs +2 -0
  140. package/dist/extensions/doom.mjs.map +1 -0
  141. package/dist/extensions/fablePlanBridge.cjs +2 -0
  142. package/dist/extensions/fablePlanBridge.cjs.map +1 -0
  143. package/dist/extensions/fablePlanBridge.mjs +2 -0
  144. package/dist/extensions/fablePlanBridge.mjs.map +1 -0
  145. package/dist/extensions/managementActions.cjs +2 -0
  146. package/dist/extensions/managementActions.cjs.map +1 -0
  147. package/dist/extensions/managementActions.mjs +2 -0
  148. package/dist/extensions/managementActions.mjs.map +1 -0
  149. package/dist/extensions/operationJournal.cjs +2 -0
  150. package/dist/extensions/operationJournal.cjs.map +1 -0
  151. package/dist/extensions/operationJournal.mjs +2 -0
  152. package/dist/extensions/operationJournal.mjs.map +1 -0
  153. package/dist/extensions/orchestratorPrompt.cjs +35 -0
  154. package/dist/extensions/orchestratorPrompt.cjs.map +1 -0
  155. package/dist/extensions/orchestratorPrompt.mjs +35 -0
  156. package/dist/extensions/orchestratorPrompt.mjs.map +1 -0
  157. package/dist/extensions/pi.cjs +2 -0
  158. package/dist/extensions/pi.cjs.map +1 -0
  159. package/dist/extensions/pi.d.cts +2 -0
  160. package/dist/extensions/pi.d.mts +2 -0
  161. package/dist/extensions/pi.mjs +2 -0
  162. package/dist/extensions/pi.mjs.map +1 -0
  163. package/dist/extensions/schemas.cjs +1 -0
  164. package/dist/extensions/schemas.mjs +2 -0
  165. package/dist/extensions/schemas.mjs.map +1 -0
  166. package/dist/extensions/spawnPlan.cjs +3 -0
  167. package/dist/extensions/spawnPlan.cjs.map +1 -0
  168. package/dist/extensions/spawnPlan.mjs +3 -0
  169. package/dist/extensions/spawnPlan.mjs.map +1 -0
  170. package/dist/extensions/standard.cjs +2 -0
  171. package/dist/extensions/standard.cjs.map +1 -0
  172. package/dist/extensions/standard.d.cts +8 -0
  173. package/dist/extensions/standard.d.cts.map +1 -0
  174. package/dist/extensions/standard.d.mts +8 -0
  175. package/dist/extensions/standard.d.mts.map +1 -0
  176. package/dist/extensions/standard.mjs +2 -0
  177. package/dist/extensions/standard.mjs.map +1 -0
  178. package/dist/extensions/statusViews.cjs +7 -0
  179. package/dist/extensions/statusViews.cjs.map +1 -0
  180. package/dist/extensions/statusViews.mjs +7 -0
  181. package/dist/extensions/statusViews.mjs.map +1 -0
  182. package/dist/extensions/subagentPromptRuntime.cjs +18 -0
  183. package/dist/extensions/subagentPromptRuntime.cjs.map +1 -0
  184. package/dist/extensions/subagentPromptRuntime.d.cts +58 -0
  185. package/dist/extensions/subagentPromptRuntime.d.cts.map +1 -0
  186. package/dist/extensions/subagentPromptRuntime.d.mts +58 -0
  187. package/dist/extensions/subagentPromptRuntime.d.mts.map +1 -0
  188. package/dist/extensions/subagentPromptRuntime.mjs +18 -0
  189. package/dist/extensions/subagentPromptRuntime.mjs.map +1 -0
  190. package/dist/extensions/subagentPromptRuntimeEntry.cjs +2 -0
  191. package/dist/extensions/subagentPromptRuntimeEntry.cjs.map +1 -0
  192. package/dist/extensions/subagentPromptRuntimeEntry.d.cts +2 -0
  193. package/dist/extensions/subagentPromptRuntimeEntry.d.mts +2 -0
  194. package/dist/extensions/subagentPromptRuntimeEntry.mjs +2 -0
  195. package/dist/extensions/subagentPromptRuntimeEntry.mjs.map +1 -0
  196. package/dist/extensions/subagentTool.cjs +7 -0
  197. package/dist/extensions/subagentTool.cjs.map +1 -0
  198. package/dist/extensions/subagentTool.mjs +7 -0
  199. package/dist/extensions/subagentTool.mjs.map +1 -0
  200. package/dist/extensions/toolDescription.cjs +2 -0
  201. package/dist/extensions/toolDescription.cjs.map +1 -0
  202. package/dist/extensions/toolDescription.mjs +2 -0
  203. package/dist/extensions/toolDescription.mjs.map +1 -0
  204. package/dist/index.cjs +2 -0
  205. package/dist/index.cjs.map +1 -0
  206. package/dist/index.d.cts +34 -0
  207. package/dist/index.d.cts.map +1 -0
  208. package/dist/index.d.mts +34 -0
  209. package/dist/index.d.mts.map +1 -0
  210. package/dist/index.mjs +2 -0
  211. package/dist/index.mjs.map +1 -0
  212. package/dist/intercom/intercomBridge.cjs +2 -0
  213. package/dist/intercom/intercomBridge.cjs.map +1 -0
  214. package/dist/intercom/intercomBridge.mjs +2 -0
  215. package/dist/intercom/intercomBridge.mjs.map +1 -0
  216. package/dist/intercom/nativeTeamChannel.cjs +5 -0
  217. package/dist/intercom/nativeTeamChannel.cjs.map +1 -0
  218. package/dist/intercom/nativeTeamChannel.d.cts +22 -0
  219. package/dist/intercom/nativeTeamChannel.d.cts.map +1 -0
  220. package/dist/intercom/nativeTeamChannel.d.mts +22 -0
  221. package/dist/intercom/nativeTeamChannel.d.mts.map +1 -0
  222. package/dist/intercom/nativeTeamChannel.mjs +5 -0
  223. package/dist/intercom/nativeTeamChannel.mjs.map +1 -0
  224. package/dist/intercom/supervisorControlChannel.cjs +2 -0
  225. package/dist/intercom/supervisorControlChannel.cjs.map +1 -0
  226. package/dist/intercom/supervisorControlChannel.mjs +2 -0
  227. package/dist/intercom/supervisorControlChannel.mjs.map +1 -0
  228. package/dist/protocol/backgroundWork.cjs +2 -0
  229. package/dist/protocol/backgroundWork.cjs.map +1 -0
  230. package/dist/protocol/backgroundWork.d.cts +52 -0
  231. package/dist/protocol/backgroundWork.d.cts.map +1 -0
  232. package/dist/protocol/backgroundWork.d.mts +52 -0
  233. package/dist/protocol/backgroundWork.d.mts.map +1 -0
  234. package/dist/protocol/backgroundWork.mjs +2 -0
  235. package/dist/protocol/backgroundWork.mjs.map +1 -0
  236. package/dist/protocol/capabilityCeiling.cjs +2 -0
  237. package/dist/protocol/capabilityCeiling.cjs.map +1 -0
  238. package/dist/protocol/capabilityCeiling.d.cts +51 -0
  239. package/dist/protocol/capabilityCeiling.d.cts.map +1 -0
  240. package/dist/protocol/capabilityCeiling.d.mts +51 -0
  241. package/dist/protocol/capabilityCeiling.d.mts.map +1 -0
  242. package/dist/protocol/capabilityCeiling.mjs +2 -0
  243. package/dist/protocol/capabilityCeiling.mjs.map +1 -0
  244. package/dist/protocol/delegation.cjs +2 -0
  245. package/dist/protocol/delegation.cjs.map +1 -0
  246. package/dist/protocol/delegation.d.cts +269 -0
  247. package/dist/protocol/delegation.d.cts.map +1 -0
  248. package/dist/protocol/delegation.d.mts +269 -0
  249. package/dist/protocol/delegation.d.mts.map +1 -0
  250. package/dist/protocol/delegation.mjs +2 -0
  251. package/dist/protocol/delegation.mjs.map +1 -0
  252. package/dist/runs/background/asyncExecution.cjs +2 -0
  253. package/dist/runs/background/asyncExecution.cjs.map +1 -0
  254. package/dist/runs/background/asyncExecution.mjs +2 -0
  255. package/dist/runs/background/asyncExecution.mjs.map +1 -0
  256. package/dist/runs/background/asyncJobTracker.cjs +2 -0
  257. package/dist/runs/background/asyncJobTracker.cjs.map +1 -0
  258. package/dist/runs/background/asyncJobTracker.mjs +2 -0
  259. package/dist/runs/background/asyncJobTracker.mjs.map +1 -0
  260. package/dist/runs/background/cliRunnerEntry.cjs +2 -0
  261. package/dist/runs/background/cliRunnerEntry.cjs.map +1 -0
  262. package/dist/runs/background/cliRunnerEntry.d.cts +1 -0
  263. package/dist/runs/background/cliRunnerEntry.d.mts +1 -0
  264. package/dist/runs/background/cliRunnerEntry.mjs +2 -0
  265. package/dist/runs/background/cliRunnerEntry.mjs.map +1 -0
  266. package/dist/runs/background/completionBatcher.cjs +2 -0
  267. package/dist/runs/background/completionBatcher.cjs.map +1 -0
  268. package/dist/runs/background/completionBatcher.mjs +2 -0
  269. package/dist/runs/background/completionBatcher.mjs.map +1 -0
  270. package/dist/runs/background/notify.cjs +4 -0
  271. package/dist/runs/background/notify.cjs.map +1 -0
  272. package/dist/runs/background/notify.mjs +4 -0
  273. package/dist/runs/background/notify.mjs.map +1 -0
  274. package/dist/runs/background/parentWatchdog.cjs +2 -0
  275. package/dist/runs/background/parentWatchdog.cjs.map +1 -0
  276. package/dist/runs/background/parentWatchdog.mjs +2 -0
  277. package/dist/runs/background/parentWatchdog.mjs.map +1 -0
  278. package/dist/runs/background/processTerminal.cjs +2 -0
  279. package/dist/runs/background/processTerminal.cjs.map +1 -0
  280. package/dist/runs/background/processTerminal.mjs +2 -0
  281. package/dist/runs/background/processTerminal.mjs.map +1 -0
  282. package/dist/runs/background/resultWatcher.cjs +2 -0
  283. package/dist/runs/background/resultWatcher.cjs.map +1 -0
  284. package/dist/runs/background/resultWatcher.mjs +2 -0
  285. package/dist/runs/background/resultWatcher.mjs.map +1 -0
  286. package/dist/runs/background/runIdResolver.cjs +2 -0
  287. package/dist/runs/background/runIdResolver.cjs.map +1 -0
  288. package/dist/runs/background/runIdResolver.mjs +2 -0
  289. package/dist/runs/background/runIdResolver.mjs.map +1 -0
  290. package/dist/runs/background/runnerBootstrap.cjs +2 -0
  291. package/dist/runs/background/runnerBootstrap.cjs.map +1 -0
  292. package/dist/runs/background/runnerBootstrap.mjs +2 -0
  293. package/dist/runs/background/runnerBootstrap.mjs.map +1 -0
  294. package/dist/runs/background/runnerExecution.cjs +2 -0
  295. package/dist/runs/background/runnerExecution.cjs.map +1 -0
  296. package/dist/runs/background/runnerExecution.mjs +2 -0
  297. package/dist/runs/background/runnerExecution.mjs.map +1 -0
  298. package/dist/runs/background/runnerReporting.cjs +3 -0
  299. package/dist/runs/background/runnerReporting.cjs.map +1 -0
  300. package/dist/runs/background/runnerReporting.mjs +3 -0
  301. package/dist/runs/background/runnerReporting.mjs.map +1 -0
  302. package/dist/runs/background/runnerTeamMembership.cjs +2 -0
  303. package/dist/runs/background/runnerTeamMembership.cjs.map +1 -0
  304. package/dist/runs/background/runnerTeamMembership.mjs +2 -0
  305. package/dist/runs/background/runnerTeamMembership.mjs.map +1 -0
  306. package/dist/runs/background/spawnHandshake.cjs +2 -0
  307. package/dist/runs/background/spawnHandshake.cjs.map +1 -0
  308. package/dist/runs/background/spawnHandshake.mjs +2 -0
  309. package/dist/runs/background/spawnHandshake.mjs.map +1 -0
  310. package/dist/runs/background/staleRunReconciler.cjs +2 -0
  311. package/dist/runs/background/staleRunReconciler.cjs.map +1 -0
  312. package/dist/runs/background/staleRunReconciler.mjs +2 -0
  313. package/dist/runs/background/staleRunReconciler.mjs.map +1 -0
  314. package/dist/runs/background/statusReader.cjs +2 -0
  315. package/dist/runs/background/statusReader.cjs.map +1 -0
  316. package/dist/runs/background/statusReader.mjs +2 -0
  317. package/dist/runs/background/statusReader.mjs.map +1 -0
  318. package/dist/runs/background/statusWriter.cjs +2 -0
  319. package/dist/runs/background/statusWriter.cjs.map +1 -0
  320. package/dist/runs/background/statusWriter.mjs +2 -0
  321. package/dist/runs/background/statusWriter.mjs.map +1 -0
  322. package/dist/runs/background/subagentWait.cjs +2 -0
  323. package/dist/runs/background/subagentWait.cjs.map +1 -0
  324. package/dist/runs/background/subagentWait.mjs +2 -0
  325. package/dist/runs/background/subagentWait.mjs.map +1 -0
  326. package/dist/runs/background/terminalPersistence.cjs +2 -0
  327. package/dist/runs/background/terminalPersistence.cjs.map +1 -0
  328. package/dist/runs/background/terminalPersistence.mjs +2 -0
  329. package/dist/runs/background/terminalPersistence.mjs.map +1 -0
  330. package/dist/runs/registry/processGroup.cjs +2 -0
  331. package/dist/runs/registry/processGroup.cjs.map +1 -0
  332. package/dist/runs/registry/processGroup.mjs +2 -0
  333. package/dist/runs/registry/processGroup.mjs.map +1 -0
  334. package/dist/runs/registry/runRegistry.cjs +2 -0
  335. package/dist/runs/registry/runRegistry.cjs.map +1 -0
  336. package/dist/runs/registry/runRegistry.mjs +2 -0
  337. package/dist/runs/registry/runRegistry.mjs.map +1 -0
  338. package/dist/runs/registry/sessionLifecycle.cjs +2 -0
  339. package/dist/runs/registry/sessionLifecycle.cjs.map +1 -0
  340. package/dist/runs/registry/sessionLifecycle.mjs +2 -0
  341. package/dist/runs/registry/sessionLifecycle.mjs.map +1 -0
  342. package/dist/runs/registry/suspendedRuns.cjs +4 -0
  343. package/dist/runs/registry/suspendedRuns.cjs.map +1 -0
  344. package/dist/runs/registry/suspendedRuns.mjs +4 -0
  345. package/dist/runs/registry/suspendedRuns.mjs.map +1 -0
  346. package/dist/runs/sdkRunnerEntry.cjs +2 -0
  347. package/dist/runs/sdkRunnerEntry.cjs.map +1 -0
  348. package/dist/runs/sdkRunnerEntry.d.cts +1 -0
  349. package/dist/runs/sdkRunnerEntry.d.mts +1 -0
  350. package/dist/runs/sdkRunnerEntry.mjs +2 -0
  351. package/dist/runs/sdkRunnerEntry.mjs.map +1 -0
  352. package/dist/runs/shared/claudeFableProfile.cjs +4 -0
  353. package/dist/runs/shared/claudeFableProfile.cjs.map +1 -0
  354. package/dist/runs/shared/claudeFableProfile.mjs +4 -0
  355. package/dist/runs/shared/claudeFableProfile.mjs.map +1 -0
  356. package/dist/runs/shared/depthGuard.cjs +2 -0
  357. package/dist/runs/shared/depthGuard.cjs.map +1 -0
  358. package/dist/runs/shared/depthGuard.mjs +2 -0
  359. package/dist/runs/shared/depthGuard.mjs.map +1 -0
  360. package/dist/runs/shared/mcpDirectToolAllowlist.cjs +2 -0
  361. package/dist/runs/shared/mcpDirectToolAllowlist.cjs.map +1 -0
  362. package/dist/runs/shared/mcpDirectToolAllowlist.mjs +2 -0
  363. package/dist/runs/shared/mcpDirectToolAllowlist.mjs.map +1 -0
  364. package/dist/runs/shared/modelFallback.cjs +2 -0
  365. package/dist/runs/shared/modelFallback.cjs.map +1 -0
  366. package/dist/runs/shared/modelFallback.mjs +2 -0
  367. package/dist/runs/shared/modelFallback.mjs.map +1 -0
  368. package/dist/runs/shared/modelScope.cjs +2 -0
  369. package/dist/runs/shared/modelScope.cjs.map +1 -0
  370. package/dist/runs/shared/modelScope.mjs +2 -0
  371. package/dist/runs/shared/modelScope.mjs.map +1 -0
  372. package/dist/runs/shared/nestedPath.cjs +2 -0
  373. package/dist/runs/shared/nestedPath.cjs.map +1 -0
  374. package/dist/runs/shared/nestedPath.mjs +2 -0
  375. package/dist/runs/shared/nestedPath.mjs.map +1 -0
  376. package/dist/runs/shared/piArgs.cjs +2 -0
  377. package/dist/runs/shared/piArgs.cjs.map +1 -0
  378. package/dist/runs/shared/piArgs.mjs +2 -0
  379. package/dist/runs/shared/piArgs.mjs.map +1 -0
  380. package/dist/runs/shared/piSpawn.cjs +2 -0
  381. package/dist/runs/shared/piSpawn.cjs.map +1 -0
  382. package/dist/runs/shared/piSpawn.mjs +2 -0
  383. package/dist/runs/shared/piSpawn.mjs.map +1 -0
  384. package/dist/runs/shared/runWithConcurrency.cjs +2 -0
  385. package/dist/runs/shared/runWithConcurrency.cjs.map +1 -0
  386. package/dist/runs/shared/runWithConcurrency.mjs +2 -0
  387. package/dist/runs/shared/runWithConcurrency.mjs.map +1 -0
  388. package/dist/runs/shared/runtimeRegistry.cjs +2 -0
  389. package/dist/runs/shared/runtimeRegistry.cjs.map +1 -0
  390. package/dist/runs/shared/runtimeRegistry.mjs +2 -0
  391. package/dist/runs/shared/runtimeRegistry.mjs.map +1 -0
  392. package/dist/runs/shared/structuredOutput.cjs +2 -0
  393. package/dist/runs/shared/structuredOutput.cjs.map +1 -0
  394. package/dist/runs/shared/structuredOutput.mjs +2 -0
  395. package/dist/runs/shared/structuredOutput.mjs.map +1 -0
  396. package/dist/runs/shared/toolAvailability.cjs +2 -0
  397. package/dist/runs/shared/toolAvailability.cjs.map +1 -0
  398. package/dist/runs/shared/toolAvailability.mjs +2 -0
  399. package/dist/runs/shared/toolAvailability.mjs.map +1 -0
  400. package/dist/runs/shared/toolBudget.cjs +2 -0
  401. package/dist/runs/shared/toolBudget.cjs.map +1 -0
  402. package/dist/runs/shared/toolBudget.mjs +2 -0
  403. package/dist/runs/shared/toolBudget.mjs.map +1 -0
  404. package/dist/shared/artifacts.cjs +2 -0
  405. package/dist/shared/artifacts.cjs.map +1 -0
  406. package/dist/shared/artifacts.mjs +2 -0
  407. package/dist/shared/artifacts.mjs.map +1 -0
  408. package/dist/shared/atomicJson.cjs +2 -0
  409. package/dist/shared/atomicJson.cjs.map +1 -0
  410. package/dist/shared/atomicJson.mjs +2 -0
  411. package/dist/shared/atomicJson.mjs.map +1 -0
  412. package/dist/shared/boundedKeySet.cjs +2 -0
  413. package/dist/shared/boundedKeySet.cjs.map +1 -0
  414. package/dist/shared/boundedKeySet.mjs +2 -0
  415. package/dist/shared/boundedKeySet.mjs.map +1 -0
  416. package/dist/shared/childTranscript.cjs +5 -0
  417. package/dist/shared/childTranscript.cjs.map +1 -0
  418. package/dist/shared/childTranscript.mjs +5 -0
  419. package/dist/shared/childTranscript.mjs.map +1 -0
  420. package/dist/shared/configDir.cjs +2 -0
  421. package/dist/shared/configDir.cjs.map +1 -0
  422. package/dist/shared/configDir.mjs +2 -0
  423. package/dist/shared/configDir.mjs.map +1 -0
  424. package/dist/shared/errors.cjs +2 -0
  425. package/dist/shared/errors.cjs.map +1 -0
  426. package/dist/shared/errors.mjs +2 -0
  427. package/dist/shared/errors.mjs.map +1 -0
  428. package/dist/shared/fileSystemRetry.cjs +2 -0
  429. package/dist/shared/fileSystemRetry.cjs.map +1 -0
  430. package/dist/shared/fileSystemRetry.mjs +2 -0
  431. package/dist/shared/fileSystemRetry.mjs.map +1 -0
  432. package/dist/shared/formatters.cjs +2 -0
  433. package/dist/shared/formatters.cjs.map +1 -0
  434. package/dist/shared/formatters.mjs +2 -0
  435. package/dist/shared/formatters.mjs.map +1 -0
  436. package/dist/shared/lruCache.cjs +2 -0
  437. package/dist/shared/lruCache.cjs.map +1 -0
  438. package/dist/shared/lruCache.mjs +2 -0
  439. package/dist/shared/lruCache.mjs.map +1 -0
  440. package/dist/shared/modelInfo.cjs +2 -0
  441. package/dist/shared/modelInfo.cjs.map +1 -0
  442. package/dist/shared/modelInfo.mjs +2 -0
  443. package/dist/shared/modelInfo.mjs.map +1 -0
  444. package/dist/shared/modelResolution.cjs +2 -0
  445. package/dist/shared/modelResolution.cjs.map +1 -0
  446. package/dist/shared/modelResolution.mjs +2 -0
  447. package/dist/shared/modelResolution.mjs.map +1 -0
  448. package/dist/shared/paths.cjs +2 -0
  449. package/dist/shared/paths.cjs.map +1 -0
  450. package/dist/shared/paths.mjs +2 -0
  451. package/dist/shared/paths.mjs.map +1 -0
  452. package/dist/shared/pollScheduler.cjs +2 -0
  453. package/dist/shared/pollScheduler.cjs.map +1 -0
  454. package/dist/shared/pollScheduler.mjs +2 -0
  455. package/dist/shared/pollScheduler.mjs.map +1 -0
  456. package/dist/shared/scopeOwner.cjs +2 -0
  457. package/dist/shared/scopeOwner.cjs.map +1 -0
  458. package/dist/shared/scopeOwner.mjs +2 -0
  459. package/dist/shared/scopeOwner.mjs.map +1 -0
  460. package/dist/shared/versioned.cjs +2 -0
  461. package/dist/shared/versioned.cjs.map +1 -0
  462. package/dist/shared/versioned.mjs +2 -0
  463. package/dist/shared/versioned.mjs.map +1 -0
  464. package/dist/slash/chainExpression.cjs +2 -0
  465. package/dist/slash/chainExpression.cjs.map +1 -0
  466. package/dist/slash/chainExpression.mjs +2 -0
  467. package/dist/slash/chainExpression.mjs.map +1 -0
  468. package/dist/slash/doctor.cjs +5 -0
  469. package/dist/slash/doctor.cjs.map +1 -0
  470. package/dist/slash/doctor.mjs +5 -0
  471. package/dist/slash/doctor.mjs.map +1 -0
  472. package/dist/slash/slashCommands.cjs +4 -0
  473. package/dist/slash/slashCommands.cjs.map +1 -0
  474. package/dist/slash/slashCommands.mjs +4 -0
  475. package/dist/slash/slashCommands.mjs.map +1 -0
  476. package/dist/slash/spawnRequestMapping.cjs +2 -0
  477. package/dist/slash/spawnRequestMapping.cjs.map +1 -0
  478. package/dist/slash/spawnRequestMapping.mjs +2 -0
  479. package/dist/slash/spawnRequestMapping.mjs.map +1 -0
  480. package/dist/slash/subagentLaunch.cjs +2 -0
  481. package/dist/slash/subagentLaunch.cjs.map +1 -0
  482. package/dist/slash/subagentLaunch.mjs +2 -0
  483. package/dist/slash/subagentLaunch.mjs.map +1 -0
  484. package/dist/tui/agentCatalog.cjs +2 -0
  485. package/dist/tui/agentCatalog.cjs.map +1 -0
  486. package/dist/tui/agentCatalog.mjs +2 -0
  487. package/dist/tui/agentCatalog.mjs.map +1 -0
  488. package/dist/tui/agentResourceProjection.cjs +2 -0
  489. package/dist/tui/agentResourceProjection.cjs.map +1 -0
  490. package/dist/tui/agentResourceProjection.mjs +2 -0
  491. package/dist/tui/agentResourceProjection.mjs.map +1 -0
  492. package/dist/tui/completionNotice.cjs +5 -0
  493. package/dist/tui/completionNotice.cjs.map +1 -0
  494. package/dist/tui/completionNotice.mjs +5 -0
  495. package/dist/tui/completionNotice.mjs.map +1 -0
  496. package/dist/tui/fleet.cjs +3 -0
  497. package/dist/tui/fleet.cjs.map +1 -0
  498. package/dist/tui/fleet.mjs +3 -0
  499. package/dist/tui/fleet.mjs.map +1 -0
  500. package/dist/tui/fleetAgentView.cjs +2 -0
  501. package/dist/tui/fleetAgentView.cjs.map +1 -0
  502. package/dist/tui/fleetAgentView.mjs +2 -0
  503. package/dist/tui/fleetAgentView.mjs.map +1 -0
  504. package/dist/tui/fleetStatus.cjs +2 -0
  505. package/dist/tui/fleetStatus.cjs.map +1 -0
  506. package/dist/tui/fleetStatus.mjs +2 -0
  507. package/dist/tui/fleetStatus.mjs.map +1 -0
  508. package/dist/tui/fleetTranscript.cjs +5 -0
  509. package/dist/tui/fleetTranscript.cjs.map +1 -0
  510. package/dist/tui/fleetTranscript.mjs +5 -0
  511. package/dist/tui/fleetTranscript.mjs.map +1 -0
  512. package/dist/tui/register.cjs +2 -0
  513. package/dist/tui/register.cjs.map +1 -0
  514. package/dist/tui/register.mjs +2 -0
  515. package/dist/tui/register.mjs.map +1 -0
  516. package/dist/types.d.cts +59 -0
  517. package/dist/types.d.cts.map +1 -0
  518. package/dist/types.d.mts +59 -0
  519. package/dist/types.d.mts.map +1 -0
  520. package/package.json +86 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"statusViews.mjs","names":[],"sources":["../../src/extensions/statusViews.ts"],"sourcesContent":["/**\n * Plain-text renderings of `action: 'status'`'s optional `view` modes, for the\n * MODEL rather than for a terminal.\n *\n * WHY THIS IS NOT `tui/fleet.ts` OR `renderFleetTranscript`:\n * Those exist, they are correct, and they are wired to the `/fleet` slash\n * command - but every one of them takes a `Theme` and emits ANSI escapes,\n * because their reader is a human looking at a TUI overlay. A tool result is\n * read by a model, where escape sequences are noise it pays tokens for and\n * cannot act on. So this module reuses the transcript READER\n * (`readFleetTranscript`, which is pure parsing) and does its own formatting,\n * rather than reusing a renderer whose whole job is the part that does not\n * transfer.\n *\n * WHY THESE VIEWS ARE WIRED AT ALL RATHER THAN DELETED FROM THE DESCRIPTION:\n * `view: 'fleet'` and `view: 'transcript'` were already documented on the\n * `subagent` tool, and neither worked - `status` read `id` first and threw\n * before ever looking at `view`, so the documented `{action:'status',\n * view:'fleet'}` call could not succeed at all. Between deleting the promise\n * and honouring it, honouring it is worth more: reading a running child's\n * output is the one coordinator capability the sibling implementation has\n * (`task_output`) that this package otherwise lacks, and the pieces to build\n * it were already here.\n *\n * DELIBERATELY NOT SUPPORTED: `index`.\n * A chain or fan-out child is its own run with its own id, not an index into\n * this run's transcript, and nothing in this package maps \"child N of run X\"\n * to a run id (see `asyncExecution.ts`'s CHILD INDEX section - the index is\n * an input the caller already knows, never something resolved back). Accepting\n * `index` here and ignoring it would be the same false affordance this whole\n * pass exists to remove, so `status` does not document it; `steer` and\n * `append-step`, which really do use it, still do.\n */\n\nimport type { TrackedAsyncJob } from '../runs/background/asyncJobTracker.ts';\nimport type { AsyncRunStatus } from '../runs/background/asyncExecution.ts';\nimport { isSuspendedRunResumable, type SuspendedRun } from '../runs/registry/suspendedRuns.ts';\nimport { readFleetTranscript, type FleetTranscriptEvent } from '../tui/fleetTranscript.ts';\nimport { formatDuration } from '../shared/formatters.ts';\n\n/** Default transcript tail length. Matches the value the tool description has always advertised. */\nexport const DEFAULT_TRANSCRIPT_LINES = 80;\n\nfunction age(job: TrackedAsyncJob, now: number): string {\n return job.startedAt ? formatDuration(Math.max(0, now - job.startedAt)) : 'unknown';\n}\n\n/**\n * The active-fleet overview: every run this session is tracking, one per line.\n *\n * Takes `now` rather than calling `Date.now()` so a test asserting rendered\n * ages does not have to freeze global time.\n */\nexport function formatFleetView(\n jobs: TrackedAsyncJob[],\n now: number = Date.now(),\n suspended: SuspendedRun[] = [],\n): string {\n if (jobs.length === 0 && suspended.length === 0) {\n return 'No runs tracked in this session. A run appears here once it has been launched from this session.';\n }\n\n const lines = [`${jobs.length} active run${jobs.length === 1 ? '' : 's'}:`];\n for (const job of jobs) {\n const parts = [`- ${job.runId}`, job.status ?? 'starting', age(job, now)];\n if (job.activityState) parts.push(job.activityState);\n if (job.attentionReason) parts.push(job.attentionReason);\n if (job.error) parts.push(`error: ${job.error}`);\n lines.push(parts.join(' · '));\n }\n if (suspended.length > 0) {\n lines.push('', `${suspended.length} suspended run${suspended.length === 1 ? '' : 's'}:`);\n for (const run of suspended) {\n const recovery = isSuspendedRunResumable(run)\n ? `restore with { action: \"restore\", id: \"${run.runId}\" }`\n : 'not resumable; submit a new explicit run';\n lines.push(`- ${run.runId} (${run.agent}, ${run.runtime}): ${recovery}`);\n }\n }\n if (jobs.length > 0) {\n lines.push('');\n lines.push(`Inspect one with { action: \"status\", id: \"<run id>\", transcriptLines: ${DEFAULT_TRANSCRIPT_LINES} }.`);\n }\n return lines.join('\\n');\n}\n\n/** Tool output shown to the model, bounded so one long result cannot crowd out the rest of the tail. */\nconst TOOL_RESULT_PREVIEW_LINES = 5;\n\nfunction formatEvent(event: FleetTranscriptEvent): string {\n if (event.kind === 'tool') {\n const status = event.status === 'running' ? '…' : event.status === 'error' ? 'error' : 'ok';\n const args = event.args ? JSON.stringify(event.args) : event.text;\n const header = `[tool ${status}] ${event.name ?? 'tool'}${args ? ` ${args}` : ''}`;\n const result = event.result?.trimEnd();\n if (!result) return header;\n // The result is the half the model most needs: it is what the call\n // actually learned, and it used to be dropped entirely.\n const body = result.split('\\n');\n const shown = body.slice(0, TOOL_RESULT_PREVIEW_LINES);\n const hidden = body.length - shown.length;\n return [header, ...shown.map((line) => ` ${line}`), hidden > 0 ? ` … +${hidden} lines` : undefined]\n .filter((line): line is string => line !== undefined)\n .join('\\n');\n }\n return `[${event.kind}] ${event.text}`;\n}\n\n/**\n * A run's transcript tail.\n *\n * Bounded from the END, not the start: a caller asking for 80 lines of a\n * long-running child wants the most recent 80, not the first 80 of its\n * startup. When the window drops anything, the fact that it did is stated,\n * so a reader never mistakes a tail for the whole run.\n */\nexport function formatRunTranscript(status: AsyncRunStatus | undefined, maxLines: number): string {\n const transcriptPath = status?.transcriptPath;\n if (!transcriptPath) {\n return status\n ? 'This run has no transcript. Artifacts were disabled for it (artifacts: false), so nothing was recorded.'\n : 'No status found for this run, so there is no transcript to read.';\n }\n\n const transcript = readFleetTranscript(transcriptPath);\n if (transcript.warning) {\n return `Transcript at '${transcriptPath}' could not be read: ${transcript.warning}`;\n }\n if (transcript.events.length === 0) {\n return `Transcript at '${transcriptPath}' is empty. The run has not written anything yet.`;\n }\n\n const rendered = transcript.events.flatMap((event) => formatEvent(event).split('\\n'));\n const kept = rendered.slice(-maxLines);\n const dropped = rendered.length - kept.length;\n const header =\n dropped > 0\n ? `Last ${kept.length} of ${rendered.length} transcript lines (${dropped} earlier line(s) not shown):`\n : `Transcript (${kept.length} line(s)):`;\n return [header, '', ...kept].join('\\n');\n}\n"],"mappings":"4UA2CA,SAAS,EAAI,EAAsB,EAAqB,CACtD,OAAO,EAAI,UAAY,EAAe,KAAK,IAAI,EAAG,EAAM,EAAI,UAAU,CAAC,CAAG,UAS5E,SAAgB,EACd,EACA,EAAc,KAAK,KAAK,CACxB,EAA4B,EAAE,CACtB,CACR,GAAI,EAAK,SAAW,GAAK,EAAU,SAAW,EAC5C,MAAO,mGAGT,IAAM,EAAQ,CAAC,GAAG,EAAK,OAAO,aAAa,EAAK,SAAW,EAAI,GAAK,IAAI,GAAG,CAC3E,IAAK,IAAM,KAAO,EAAM,CACtB,IAAM,EAAQ,CAAC,KAAK,EAAI,QAAS,EAAI,QAAU,WAAY,EAAI,EAAK,EAAI,CAAC,CACrE,EAAI,eAAe,EAAM,KAAK,EAAI,cAAc,CAChD,EAAI,iBAAiB,EAAM,KAAK,EAAI,gBAAgB,CACpD,EAAI,OAAO,EAAM,KAAK,UAAU,EAAI,QAAQ,CAChD,EAAM,KAAK,EAAM,KAAK,MAAM,CAAC,CAE/B,GAAI,EAAU,OAAS,EAAG,CACxB,EAAM,KAAK,GAAI,GAAG,EAAU,OAAO,gBAAgB,EAAU,SAAW,EAAI,GAAK,IAAI,GAAG,CACxF,IAAK,IAAM,KAAO,EAAW,CAC3B,IAAM,EAAW,EAAwB,EAAI,CACzC,0CAA0C,EAAI,MAAM,KACpD,2CACJ,EAAM,KAAK,KAAK,EAAI,MAAM,IAAI,EAAI,MAAM,IAAI,EAAI,QAAQ,KAAK,IAAW,EAO5E,OAJI,EAAK,OAAS,IAChB,EAAM,KAAK,GAAG,CACd,EAAM,KAAK,8E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,CAiDnD,EAA4B"}
@@ -0,0 +1,18 @@
1
+ const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`../shared/configDir.cjs`),n=require(`../env.cjs`),r=require(`../container/types.cjs`),i=require(`../intercom/supervisorControlChannel.cjs`),a=require(`../shared/paths.cjs`),o=require(`../intercom/nativeTeamChannel.cjs`),s=require(`../runs/shared/toolBudget.cjs`),c=require(`../container/index.cjs`),l=require(`../shared/childTranscript.cjs`),u=require(`../runs/shared/structuredOutput.cjs`),d=require(`../runs/shared/toolAvailability.cjs`);let f=require(`node:fs`);f=e.__toESM(f,1);let p=require(`node:path`);p=e.__toESM(p,1);function m(){return{steerNudgeFailures:0,watchErrors:0,watchCloseFailures:0}}const h=[`This subagent step has a strict structured output contract.`,"Your final action must be to call the `structured_output` tool with JSON matching the provided schema.","Do not rely on prose-only completion; if you do not call `structured_output`, the parent will fail this step."].join(`
2
+ `),g=[`You are a child subagent, not the parent orchestrator.`,`The parent session owns delegation, orchestration, review fanout, and follow-up worker launches.`,`Ignore prior parent-only orchestration instructions in inherited conversation history.`,`Do not propose or run subagents. Complete only your assigned role-specific task with the tools available to you.`,`If you need to edit files, use the available editing tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.`].join(`
3
+ `),_=[`You are a child subagent with explicit fanout responsibility for this assigned task.`,`The parent session owns final orchestration, acceptance, and follow-up implementation launches.`,"You may use the `subagent` tool only for the fanout work explicitly requested in this task.",`Do not broaden yourself into general parent orchestration. Do not launch follow-up workers unless the task explicitly asks for that.`,`The maxSubagentDepth cap still applies and may block further fanout.`,`If you need to edit files, use the available editing tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.`].join(`
4
+ `);function v(e,t,n){e.on.call(e,t,n)}function y(e){return typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`}function b(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.role!==`assistant`||!Array.isArray(n.content))continue;let r=n.content.filter(y).map(e=>e.text).join(`
5
+ `).trim();if(r)return r}return``}function x(e,t=c.createPromptRuntimeContainer()){let i=process.env[n.SUBAGENT_RUN_ID_ENV]?.trim();if(!i)return;let a=t.get(r.DOOM_TEAM_TYPES.PollScheduler),s=t.get(r.DOOM_TEAM_TYPES.RunnerBootstrap),u=t.get(r.DOOM_TEAM_TYPES.RunnerExecution),d=t.get(r.DOOM_TEAM_TYPES.RunnerReporting),f,p,m=0,h=new WeakSet;v(e,`session_start`,(t,n)=>{if(f)return;a.start();let r=n.sessionManager.getSessionFile(),c=r?d.recordSessionFile(r):void 0,l=s.bootstrap(i,c);l.teamContext&&Object.assign(process.env,o.nativeTeamMemberEnvironment(l.teamContext)),u.start(i,{onSteer:t=>{let n=e.sendUserMessage;if(!n){H(t,`failed`,`Child Pi session does not support sendUserMessage steering.`);return}try{n(V(t),{deliverAs:`steer`}),H(t,`delivered`,`Pi accepted the correlated steering input.`)}catch(e){throw H(t,`failed`,e instanceof Error?e.message:String(e)),e}}}),f={teamContext:l.teamContext},u.setActivity(`working`)}),v(e,`agent_start`,()=>{f&&u.setActivity(`working`)}),v(e,`message_end`,e=>{if(!f||!e.message||typeof e.message!=`object`||h.has(e.message))return;h.add(e.message);let t=l.getMessageUsageTokens(e.message);t!==void 0&&(p=(p??0)+t,u.setProgress({tokens:p}))}),v(e,`tool_execution_start`,e=>{if(!f)return;let t=e.toolName??e.tool?.name;m+=1,u.setProgress({toolCount:m,...typeof t==`string`&&t.length>0?{currentTool:t}:{}}),u.setActivity(t===`intercom`&&e.args?.action===`ask`?`waiting_for_reply`:`tool`)}),v(e,`tool_execution_end`,()=>{f&&u.setActivity(`working`)}),v(e,`agent_end`,e=>{if(!f)return;u.setActivity(`finalizing`);let t=b(e.messages);u.complete(!0,t)})}const S=new Set([`subagent-orchestration-instructions`,`subagent-slash-result`,`subagent-slash-text-result`,`subagent-notify`,`subagent_control_notice`,`subagent-control`,`subagent-control-notice`]),C=/<name>\s*pi-subagents\s*<\/name>/,w=`
6
+
7
+ The following skills provide specialized instructions for specific tasks.`,T=`
8
+ Current date:`;function E(e){let t=process.env[e];if(t!==void 0)return t!==`0`}function D(){let e=process.env[n.REQUIRED_CHILD_TOOLS_ENV]?.trim();if(!e)return;let t=JSON.parse(e);if(!Array.isArray(t)||t.some(e=>typeof e!=`string`||!e))throw Error(`Invalid ${n.REQUIRED_CHILD_TOOLS_ENV} payload.`);return t}function O(){let e=process.env[n.MCP_DIRECT_CHILD_TOOLS_ENV]?.trim();if(e)try{let t=JSON.parse(e);return!Array.isArray(t)||t.some(e=>typeof e!=`string`||!e)?void 0:t}catch{return}}function k(e){let t=process.env[n.CHILD_TOOL_DIAGNOSTIC_PATH_ENV]?.trim(),r=D();if(!(!t||!r))return d.writeChildToolDiagnostic(t,r,e.getAllTools().map(e=>e.name),process.env[n.SUBAGENT_CHILD_AGENT_ENV]?.trim(),O())}function A(e,t,n){let r=e.length;for(let i of n){let n=e.indexOf(i,t);n!==-1&&n<r&&(r=n)}return r}function j(e){let t=e.indexOf(`
9
+
10
+ # Project Context
11
+
12
+ Project-specific instructions and guidelines:
13
+
14
+ `);if(t===-1)return e;let n=A(e,t+68,[w,T]);return`${e.slice(0,t)}${e.slice(n)}`}function M(e){let t=e.indexOf(w);if(t===-1)return e;let n=A(e,t+75,[T]);return`${e.slice(0,t)}${e.slice(n)}`}function N(e){return e.replace(/\n{0,2}<skill\s+name=["']pi-subagents["'][^>]*>[\s\S]*?<\/skill>\n{0,2}/g,`
15
+
16
+ `).replace(/[ \t]*<skill>\s*[\s\S]*?<\/skill>\s*/g,e=>C.test(e)?``:e)}function P(e){let t=e;for(let e of[g,_])t=t.split(e).join(``);return t.replace(/^(?:[ \t]*\r?\n)+/,``)}function F(e,t){let n=e;return t.inheritProjectContext||(n=j(n)),t.inheritSkills||(n=M(n)),n=N(n),n=P(n),`${t.fanoutChild?_:g}${process.env.PI_SUBAGENT_STRUCTURED_OUTPUT_CAPTURE?`\n\n${h}`:``}\n\n${n}`}function I(e){let t=e;return t?.role!==`custom`||typeof t.customType!=`string`?!1:S.has(t.customType)}function L(e){let t=e;return t?.role===`toolResult`&&t.toolName===`subagent`}function R(e){let t=e;return t?.type===`toolCall`&&t.name===`subagent`}function z(e){let t=e;if(t?.role!==`assistant`||!Array.isArray(t.content))return e;let n=t.content.filter(e=>!R(e));if(n.length===t.content.length)return e;if(n.length!==0)return{...t,content:n}}function B(e){let t=process.env[n.SUBAGENT_FANOUT_CHILD_ENV]===`1`,r=!1,i=[];for(let n of e){if(I(n)||!t&&L(n)){r=!0;continue}let e=t?n:z(n);if(e===void 0){r=!0;continue}e!==n&&(r=!0),i.push(e)}return r?i:e}function V(e){return[`Mid-run steering from the parent orchestrator:`,``,e.message,``,`Incorporate this guidance at the next safe point. Do not restart the task unless the guidance explicitly asks you to.`].join(`
17
+ `)}function H(e,t,r){let a=process.env[n.SUBAGENT_STEER_ACK_DIR_ENV]?.trim(),o=Number(process.env[n.SUBAGENT_CHILD_INDEX_ENV]);!a||!Number.isInteger(o)||o<0||i.writeSteerAckAt(i.steerAckPathFromDir(a,e.id),{requestId:e.id,index:o,ts:Date.now(),state:t,message:r})}function U(e,t,n){if(!t)return;let r=0,i=!1,a=e.sendUserMessage;v(e,`tool_call`,e=>{let o=typeof e.toolName==`string`?e.toolName:`tool`;if(r++,t.soft!==void 0&&r>=t.soft&&!i){i=!0;try{a?.(s.toolBudgetSoftNudge(t,r),{deliverAs:`steer`})}catch(e){n.steerNudgeFailures+=1,n.lastError=e}}if(s.shouldBlockToolForBudget(t,o,r))return{block:!0,reason:s.toolBudgetBlockedMessage(t,o,r)}})}function W(e,r={}){let a=r.diagnostics??m(),o=process.env[n.SUBAGENT_STEER_INBOX_ENV]?.trim();if(!o)return;let s=process.env[n.SUBAGENT_STEER_CAPABILITY_ENV]?.trim(),c=process.env[n.SUBAGENT_STEER_ACK_DIR_ENV]?.trim(),l=e.sendUserMessage,u=Number(process.env[n.SUBAGENT_CHILD_INDEX_ENV]),d=new Map,p=!1,h=!1,g=!1,_=typeof l==`function`,y,b,x=(e,t,n)=>{!c||!Number.isInteger(u)||u<0||i.writeSteerAckAt(i.steerAckPathFromDir(c,e.id),{requestId:e.id,index:u,ts:Date.now(),state:t,message:n})},S=()=>{!s||!Number.isInteger(u)||u<0||i.writeSteerCapabilityAt(s,{index:u,pid:process.pid,readyAt:Date.now(),supported:_})},C=()=>{if(!(p||h)){h=!0;try{for(let e of i.claimSteerRequestsFromDir(o)){if(!_||typeof l!=`function`){x(e.request,`failed`,`Child Pi session does not support sendUserMessage steering.`),e.commit();continue}let t=V(e.request),n=d.get(t)??[];n.push(e.request.id),d.set(t,n);try{l(t,{deliverAs:`steer`}),e.commit()}catch(r){n.pop(),n.length===0&&d.delete(t),e.release(),x(e.request,`failed`,r instanceof Error?r.message:String(r))}}}finally{h=!1}}},w=e=>{if(p||!e||typeof e!=`object`)return;let t=e;if(t.source!==`extension`||t.streamingBehavior!==`steer`)return;let n=typeof t.text==`string`?t.text:typeof t.content==`string`?t.content:void 0;if(!n)return;let r=d.get(n),i=r?.shift();i&&(r?.length===0&&d.delete(n),x({type:`steer`,id:i,ts:Date.now(),message:n},`delivered`,`Pi accepted the correlated steering input.`))},T=()=>{if(!(g||p)){try{f.mkdirSync(o,{recursive:!0}),S()}catch{return}g=!0;try{y=(r.watch??f.watch)(t.resolveWatchPath(o,r.nativeRealpath),()=>C()),y.on(`error`,e=>{a.watchErrors+=1,a.lastError=e})}catch{y=void 0}b=setInterval(C,250),b.unref?.()}},E=()=>{T(),C()};v(e,`input`,w),v(e,`session_start`,()=>T());for(let t of[`message_start`,`message_update`,`message_end`,`tool_execution_start`,`tool_execution_end`,`turn_end`])v(e,t,E);v(e,`session_shutdown`,()=>{p=!0;try{y?.close()}catch(e){a.watchCloseFailures+=1,a.lastError=e}b&&clearInterval(b)})}function G(e,t=m()){a.adoptSessionScopeFromEnv(),W(e,{diagnostics:t}),U(e,s.decodeToolBudgetEnv(process.env[n.TOOL_BUDGET_ENV],{allowZero:process.env[n.TOOL_BUDGET_ZERO_AUTH_ENV]===`1`}),t);let i=c.createPromptRuntimeContainer();x(e,i);let o=i.get(r.DOOM_TEAM_TYPES.NativeTeamChannelService);v(e,`session_start`,()=>{o.createRuntime(e).bindChildFromEnvironment()}),v(e,`agent_start`,()=>{k(e)});let l=process.env[n.STRUCTURED_OUTPUT_CAPTURE_ENV],d=process.env[n.STRUCTURED_OUTPUT_SCHEMA_ENV];if(l&&d){let t=JSON.parse(f.readFileSync(d,`utf-8`)),n=u.createStructuredOutputToolParameters(t),r=new u.StructuredOutputValidator;e.registerTool.bind(e)({name:`structured_output`,label:`Structured Output`,description:`Submit the required final structured output for this subagent step. This terminates the step.`,parameters:n,async execute(e,n){let i=await r.validateValue(t,n.value);if(i.status===`invalid`)throw Error(`Structured output validation failed: ${i.message}`);return f.mkdirSync(p.dirname(l),{recursive:!0}),f.writeFileSync(l,JSON.stringify(n.value),{mode:384}),{content:[{type:`text`,text:`Structured output captured.`}],details:{path:l},terminate:!0}}})}v(e,`context`,e=>{let t=B(e.messages);if(t!==e.messages)return{messages:t}}),v(e,`before_agent_start`,async t=>{let r=process.env[n.SUBAGENT_INTERCOM_SESSION_NAME_ENV]?.trim();r&&typeof e.setSessionName==`function`&&e.setSessionName(r);let i=E(n.INHERIT_PROJECT_CONTEXT_ENV),a=E(n.INHERIT_SKILLS_ENV),o=E(n.SUBAGENT_FANOUT_CHILD_ENV),s=t.systemPrompt;if((i!==void 0||a!==void 0||o!==void 0)&&(s=F(t.systemPrompt,{inheritProjectContext:i??!0,inheritSkills:a??!0,fanoutChild:o===!0})),s!==t.systemPrompt)return{systemPrompt:s}})}exports.registerSubagentPromptRuntime=G;
18
+ //# sourceMappingURL=subagentPromptRuntime.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subagentPromptRuntime.cjs","names":["createPromptRuntimeContainer","SUBAGENT_RUN_ID_ENV","DOOM_TEAM_TYPES","nativeTeamMemberEnvironment","getMessageUsageTokens","REQUIRED_CHILD_TOOLS_ENV","MCP_DIRECT_CHILD_TOOLS_ENV","CHILD_TOOL_DIAGNOSTIC_PATH_ENV","writeChildToolDiagnostic","SUBAGENT_CHILD_AGENT_ENV","SUBAGENT_FANOUT_CHILD_ENV","SUBAGENT_STEER_ACK_DIR_ENV","SUBAGENT_CHILD_INDEX_ENV","steerAckPathFromDir","toolBudgetSoftNudge","shouldBlockToolForBudget","toolBudgetBlockedMessage","SUBAGENT_STEER_INBOX_ENV","SUBAGENT_STEER_CAPABILITY_ENV","claimSteerRequestsFromDir","fs","resolveWatchPath","decodeToolBudgetEnv","TOOL_BUDGET_ENV","TOOL_BUDGET_ZERO_AUTH_ENV","STRUCTURED_OUTPUT_CAPTURE_ENV","STRUCTURED_OUTPUT_SCHEMA_ENV","createStructuredOutputToolParameters","StructuredOutputValidator","path","SUBAGENT_INTERCOM_SESSION_NAME_ENV","INHERIT_PROJECT_CONTEXT_ENV","INHERIT_SKILLS_ENV"],"sources":["../../src/extensions/subagentPromptRuntime.ts"],"sourcesContent":["/**\n * The extension loaded INSIDE every spawned child: prompt rewriting,\n * mid-run steering delivery, the tool-call budget, native supervisor/team\n * messaging, and the `structured_output` tool.\n *\n * WHY THIS RUNS IN A DIFFERENT WORLD THAN EVERYTHING ELSE PORTED SO FAR:\n * Every other module in this package runs in the parent or the runner\n * process. This one is loaded BY the child's own Pi process\n * (`piArgs.ts`'s `resolveRuntimeExtensionPath` resolves it onto the\n * child's `--extension` args). The child's stdout IS its captured\n * transcript - a stray console write here does not go to a developer's\n * terminal, it becomes part of the child's output. Nothing in this file\n * writes to the console, ever; a failure that would have been\n * logged elsewhere is swallowed with a comment when there is no safe channel\n * to report it.\n *\n * FIX (claim-by-rename for the per-child steer inbox):\n * The predecessor's `registerSteeringInbox` called\n * `consumeSteerRequestsFromDir`, which deletes every queued request before\n * attempting delivery, then manually re-queued whatever it had not yet\n * attempted (`requests.slice(index + 1)`) if `sendUserMessage` threw\n * partway through a batch - but the request that was actually attempted\n * when the throw happened was already gone, lost the same way FIX 1 in\n * `control-channel.ts` was written to close for the runner-side steer\n * queue. This module's `flush()` uses `claimSteerRequestsFromDir` (already\n * exported from `control-channel.ts`, directory-agnostic) instead: each\n * request is claimed individually, and a failed `sendUserMessage` call\n * calls `release()` on that one claim so it is retried on the next flush,\n * while every OTHER claim in the same batch is still committed or released\n * independently. That is also a behavioural improvement over the\n * predecessor's `break`-on-first-failure, which abandoned the rest of a\n * batch rather than giving each message its own outcome - the same\n * per-item independence `ControlChannelWatcher.check()` already applies on\n * the runner side.\n *\n * Child runtimes keep the native team transport for lifecycle and result\n * delivery, but model-visible coordination tools are filtered by the selected\n * layer policy. They never register the root orchestration tool or a separate\n * wait alias.\n *\n * AVOID:\n * - Writing to the console. See the header above\n * - Reintroducing the predecessor's \"delete the whole batch, dispatch,\n * re-queue what failed\" shape for the steer inbox. See the FIX above\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { Container } from 'inversify';\nimport type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\n\nimport { createPromptRuntimeContainer, DOOM_TEAM_TYPES } from '../container/index.ts';\nimport {\n CHILD_TOOL_DIAGNOSTIC_PATH_ENV,\n INHERIT_PROJECT_CONTEXT_ENV,\n INHERIT_SKILLS_ENV,\n MCP_DIRECT_CHILD_TOOLS_ENV,\n REQUIRED_CHILD_TOOLS_ENV,\n STRUCTURED_OUTPUT_CAPTURE_ENV,\n STRUCTURED_OUTPUT_SCHEMA_ENV,\n SUBAGENT_CHILD_AGENT_ENV,\n SUBAGENT_CHILD_INDEX_ENV,\n SUBAGENT_FANOUT_CHILD_ENV,\n SUBAGENT_INTERCOM_SESSION_NAME_ENV,\n SUBAGENT_RUN_ID_ENV,\n SUBAGENT_STEER_ACK_DIR_ENV,\n SUBAGENT_STEER_CAPABILITY_ENV,\n SUBAGENT_STEER_INBOX_ENV,\n TOOL_BUDGET_ENV,\n TOOL_BUDGET_ZERO_AUTH_ENV,\n} from '../env.ts';\nimport {\n type INativeTeamChannelService,\n NATIVE_TEAM_TOOL_NAME,\n nativeTeamMemberEnvironment,\n type TeamMemberContext,\n} from '../intercom/nativeTeamChannel.ts';\nimport { resolveWatchPath } from '../shared/configDir.ts';\nimport { getMessageUsageTokens, type ChildTranscriptMessage } from '../shared/childTranscript.ts';\nimport { adoptSessionScopeFromEnv } from '../shared/paths.ts';\nimport type { JsonSchemaObject } from '../types.ts';\nimport {\n claimSteerRequestsFromDir,\n steerAckPathFromDir,\n writeSteerAckAt,\n writeSteerCapabilityAt,\n type SteerRequest,\n} from '../intercom/supervisorControlChannel.ts';\nimport type { IPollScheduler } from '../shared/pollScheduler.ts';\nimport type { IRunnerBootstrap } from '../runs/background/runnerBootstrap.ts';\nimport type { IRunnerExecution } from '../runs/background/runnerExecution.ts';\nimport type { IRunnerReporting } from '../runs/background/runnerReporting.ts';\nimport { createStructuredOutputToolParameters, StructuredOutputValidator } from '../runs/shared/structuredOutput.ts';\nimport { writeChildToolDiagnostic, type ChildToolDiagnostic } from '../runs/shared/toolAvailability.ts';\nimport {\n decodeToolBudgetEnv,\n shouldBlockToolForBudget,\n toolBudgetBlockedMessage,\n toolBudgetSoftNudge,\n} from '../runs/shared/toolBudget.ts';\nimport type { ResolvedToolBudget } from '../runs/shared/toolBudget.ts';\n\nconst STEER_FLUSH_POLL_INTERVAL_MS = 250;\n\n/**\n * Failures this runtime absorbed rather than propagated.\n *\n * WHY RECORD RATHER THAN LOG:\n * This module runs inside the spawned child, where stdout IS the child's\n * captured transcript. Writing a diagnostic there would corrupt the very\n * output the run exists to produce, so nothing here may reach stdio. But a\n * discarded error is indistinguishable from one that never happened, and a\n * watcher that fails on every event looks exactly like a quiet inbox. These\n * counters are the compromise: cheap, bounded, and queryable by a caller that\n * wants to know whether the child's steering path was actually healthy.\n *\n * WHY THIS IS CALLER-OWNED, NOT MODULE STATE:\n * A module-level singleton here would be exactly the bug this package's \"no\n * module-level mutable state\" rule exists to prevent - see\n * `nativeTeamChannel.ts`'s header: \"a second session in the same process\n * cannot inherit the first one's [state]\". `registerSubagentPromptRuntime`\n * runs once per real child process, so a singleton would rarely matter in\n * production, but every test in this file registers multiple independent\n * runtimes in one process, and a shared singleton would leak counts between\n * them silently. `createPromptRuntimeDiagnostics()` hands each registration\n * its own object instead; the caller keeps the reference to read later, and\n * a fresh registration is what \"reset\" means - there is no shared state left\n * to reset.\n *\n * AVOID:\n * - Adding a `console.*` here, on any path, for any reason\n * - Treating a non-zero count as fatal; every one of these is a degraded-mode\n * path with a working fallback, which is why it was absorbed in the first place\n * - Reintroducing a module-level instance of this. See the header above\n */\nexport interface PromptRuntimeDiagnostics {\n /** Advisory tool-budget nudges that could not be delivered to the child. */\n steerNudgeFailures: number;\n /** Errors emitted by the steer-inbox watcher. The interval poll covers these. */\n watchErrors: number;\n /** Failures closing the watcher during shutdown. */\n watchCloseFailures: number;\n /** The most recent absorbed failure, whichever kind it was. */\n lastError?: unknown;\n}\n\n/** A fresh, zeroed diagnostics object for one registration. See the interface doc for why this is not a singleton. */\nexport function createPromptRuntimeDiagnostics(): PromptRuntimeDiagnostics {\n return { steerNudgeFailures: 0, watchErrors: 0, watchCloseFailures: 0 };\n}\n\nconst STRUCTURED_OUTPUT_INSTRUCTIONS = [\n 'This subagent step has a strict structured output contract.',\n 'Your final action must be to call the `structured_output` tool with JSON matching the provided schema.',\n 'Do not rely on prose-only completion; if you do not call `structured_output`, the parent will fail this step.',\n].join('\\n');\n\nexport const CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS = [\n 'You are a child subagent, not the parent orchestrator.',\n 'The parent session owns delegation, orchestration, review fanout, and follow-up worker launches.',\n 'Ignore prior parent-only orchestration instructions in inherited conversation history.',\n 'Do not propose or run subagents. Complete only your assigned role-specific task with the tools available to you.',\n 'If you need to edit files, use the available editing tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.',\n].join('\\n');\n\nexport const CHILD_FANOUT_BOUNDARY_INSTRUCTIONS = [\n 'You are a child subagent with explicit fanout responsibility for this assigned task.',\n 'The parent session owns final orchestration, acceptance, and follow-up implementation launches.',\n 'You may use the `subagent` tool only for the fanout work explicitly requested in this task.',\n 'Do not broaden yourself into general parent orchestration. Do not launch follow-up workers unless the task explicitly asks for that.',\n 'The maxSubagentDepth cap still applies and may block further fanout.',\n 'If you need to edit files, use the available editing tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.',\n].join('\\n');\n\n/**\n * `pi.on` typed loosely: the extension API's event payloads are not typed\n * per event name, so every call site narrows its own handler's parameter.\n * `.call(pi, ...)` binds `this` explicitly rather than extracting `pi.on` as\n * a bare reference, which is what an unbound method call would otherwise risk.\n *\n * The handler is given `ctx: ExtensionContext` as a second parameter,\n * matching the real `pi.on` signature (`ExtensionHandler<E, R> = (event: E,\n * ctx: ExtensionContext) => ...`) even though most registrations here never\n * read it - existing single-parameter handlers stay valid without change\n * (JS ignores a callback's unused trailing parameters), and the one call\n * site that DOES need it (`session_start`, for `ctx.sessionManager` - see\n * `registerDeliverableGuardCheck`'s doc) no longer has to reach past this\n * wrapper to get it.\n */\nfunction onEvent<E = unknown>(\n pi: ExtensionAPI,\n event: string,\n handler: (event: E, ctx: ExtensionContext) => unknown,\n): void {\n (pi.on as unknown as (event: string, handler: (event: E, ctx: ExtensionContext) => unknown) => void).call(\n pi,\n event,\n handler,\n );\n}\n\n/** A text block from an assistant message's content array. Narrowed structurally, not imported from `@earendil-works/pi-ai`, matching this file's habit of ad-hoc event-payload types (see `onEvent`'s own doc). */\ninterface AssistantTextBlock {\n type: 'text';\n text: string;\n}\n\n/** The subset of `AgentEndEvent`/message shape this file actually reads. */\ninterface DeliverableCheckMessage {\n role?: string;\n content?: unknown;\n}\n\nfunction isAssistantTextBlock(block: unknown): block is AssistantTextBlock {\n return (\n typeof block === 'object' &&\n block !== null &&\n (block as { type?: unknown }).type === 'text' &&\n typeof (block as { text?: unknown }).text === 'string'\n );\n}\n\n/**\n * The last non-empty assistant text found in `messages`, or `''`.\n *\n * `DeliverableGuardInput.summary` is checked for the `'summary'`-kind\n * expectation, and nothing in this package tracks a run's summary text\n * per-turn - `RunnerReporting` only computes one at the terminal\n * `mutateTerminalStatus` callback, which has not happened yet when a\n * mid-run deliverable check needs to run. The assistant's own most recent\n * text output is the best available proxy for \"what would this run's\n * summary be if it stopped now\" without a dedicated tracking mechanism this\n * package does not have yet. Best-effort by construction: an unparseable or\n * missing message reads as an empty summary, which is the SAFE failure\n * direction for this guard (nudging once more than strictly necessary,\n * never fewer times than necessary).\n */\nexport function extractAssistantSummaryText(messages: readonly DeliverableCheckMessage[]): string {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index];\n if (message?.role !== 'assistant' || !Array.isArray(message.content)) continue;\n const text = message.content\n .filter(isAssistantTextBlock)\n .map((block) => block.text)\n .join('\\n')\n .trim();\n if (text) return text;\n }\n return '';\n}\n\n/**\n * Wires `DeliverableGuard`'s write side into this process. See the module\n * doc's overall framing: everything else in the missing-deliverable chain\n * (detection, the single nudge, escalation, the fold into `status.json`,\n * `AsyncJobTracker`'s read and folded wait action already exist;\n * nothing called it. This is that call.\n *\n * WHY THIS RESOLVES ITS OWN CONTAINER, HERE:\n * `RunnerBootstrap`/`RunnerExecution`/`DeliverableGuard` are DI-bound\n * services (`container/modules/runs.ts`), and this file is the one place\n * `container/index.ts` documents as the in-child composition root\n * (`createPromptRuntimeContainer()`) - filed under `src/extensions/**`, the\n * boundary reserved for composition roots (see `vibe-lint.config.yaml`'s\n * `extensions` boundary), not under `src/runs/**` where it used to live. It\n * was moved here specifically so it could stop being the one exception\n * carved into the `runs` boundary's allowlist for `src/container/index.ts` -\n * a domain that can build its own container can bypass every composition\n * decision above it, and that hole is now closed rather than merely\n * documented. `container` is an optional parameter, defaulting to the real\n * container, purely so a test can supply one pre-loaded with fakes via\n * `container.rebind(...)` instead of standing up the real filesystem-backed\n * services.\n *\n * WHY `session_start` BOOTSTRAPS, AND WHY IT ONLY EVER RUNS ONCE:\n * `RunnerBootstrap.bootstrap()` is genuinely the FIRST real caller this\n * package has ever had for it - it opens `status.json`, wires\n * `TerminalPersistenceService`'s finalize callback, and writes the startup\n * handshake `SpawnHandshake.waitForHandshake()` on the parent side blocks\n * on. `RunnerExecution.start()` then begins watching the control inbox.\n * `ControlChannelWatcher` depends on `PollScheduler`\n * (`control-channel.ts:809`), which nothing in this package's runner\n * services ever calls `.start()` on by itself (see `pollScheduler.ts`'s own\n * AVOID note: \"a registered-but-unstarted PollScheduler never ticks\") - so\n * this starts it explicitly, once, alongside bootstrap. The `resolved` guard\n * makes a stray second `session_start` (nothing in this file's other\n * registrations assumes it fires only once) a no-op rather than a second\n * bootstrap of the same run.\n *\n * WHY `execution.start()` IS GIVEN AN `onSteer` HANDLER:\n * `DeliverableGuard.deliverNudge()` drops a nudge into this run's OWN\n * steer-requests queue via `requestAsyncSteer` (see that method's doc) and\n * calls it delivered once the write succeeds. But the write alone does not\n * reach the child: `ControlChannelWatcher`, wired up by `execution.start()`,\n * claims and commits (deletes) every request it finds in that queue whether\n * or not a handler is registered for it - found by testing this file\n * against the REAL `ControlChannelWatcher` rather than a fake with no side\n * effects, which is exactly the failure mode this task kept turning up\n * elsewhere (`createRunsModule()` never loaded into any root;\n * `PollScheduler.start()` never called). `onSteer` is the missing delivery\n * half: it reuses `formatSteerMessage`/`sendUserMessage`, the same\n * mechanism `registerSteeringInbox` already uses for its own, separate\n * steer queue, so a nudge actually lands in the child's conversation instead\n * of being silently claimed and discarded.\n *\n * WHY `agent_end`, NOT `turn_end`:\n * `agent_end`'s own event (`AgentEndEvent.messages`) carries the full\n * message history for this agent loop, which `extractAssistantSummaryText`\n * reads from - `turn_end` only carries the one message that ended that turn,\n * not the memory of what preceded it, and `DeliverableGuard`'s own doc\n * frames this check as \"end-of-turn or idle\", not \"every turn.\"\n *\n * `unansweredAsks` AND `memberId`:\n * Both come from this run's own bound `TeamMemberContext`, which\n * `RunnerBootstrap.bootstrap()` already holds (from registering as a team\n * member) and now returns on its result. `memberId` is `teamContext.memberId`\n * directly. `unansweredAsks` calls `pendingAsksAddressedTo(teamContext,\n * teamContext.memberId, now)` - see `deliverable-guard.ts`'s own AVOID\n * section for why `DeliverableGuard` cannot call that itself, and that\n * function's own doc for why it deliberately returns id/sender/time only,\n * never the question's text (this maps its result into a factual, non-\n * fabricated placeholder message rather than guessing at content it was\n * never given). A standalone run with no team root forwarded has no\n * `teamContext` at all, in which case both are simply omitted - narrower\n * than the real behaviour, never wider, matching every other gap in this\n * file when there is genuinely nothing to report rather than something\n * unknown to guess at.\n *\n * `session_start` ALSO RECORDS THIS RUN'S OWN SESSION FILE:\n * `ctx.sessionManager.getSessionFile()` is the only place in this process\n * that ever answers \"what is my own transcript path\" - see\n * `runnerReporting.ts`'s header for why the value has to come from here\n * (the child) rather than be derived by the parent. `RunnerReporting`\n * validates and retains it while `RunnerBootstrap` writes it before the\n * ready handshake. `getSessionFile()` can return `undefined` (no persisted\n * transcript for this run); that case is simply not recorded, the same\n * \"omit rather than guess\" shape as `unansweredAsks`/`teamContext` above.\n */\nexport function registerRunnerLifecycle(pi: ExtensionAPI, container: Container = createPromptRuntimeContainer()): void {\n const runId = process.env[SUBAGENT_RUN_ID_ENV]?.trim();\n if (!runId) return;\n\n const pollScheduler = container.get<IPollScheduler>(DOOM_TEAM_TYPES.PollScheduler);\n const bootstrap = container.get<IRunnerBootstrap>(DOOM_TEAM_TYPES.RunnerBootstrap);\n const execution = container.get<IRunnerExecution>(DOOM_TEAM_TYPES.RunnerExecution);\n const reporting = container.get<IRunnerReporting>(DOOM_TEAM_TYPES.RunnerReporting);\n\n let resolved: { teamContext: TeamMemberContext | undefined } | undefined;\n let cumulativeTokens: number | undefined;\n let toolCount = 0;\n const countedMessages = new WeakSet<object>();\n\n onEvent(pi, 'session_start', (_event, ctx) => {\n if (resolved) return;\n pollScheduler.start();\n const sessionFile = ctx.sessionManager.getSessionFile();\n const recordedSessionFile = sessionFile ? reporting.recordSessionFile(sessionFile) : undefined;\n const bootstrapped = bootstrap.bootstrap(runId, recordedSessionFile);\n if (bootstrapped.teamContext) Object.assign(process.env, nativeTeamMemberEnvironment(bootstrapped.teamContext));\n // `onSteer` is the delivery half of `DeliverableGuard.deliverNudge`'s\n // write side (see `RunnerExecutionHandlers.onSteer`'s own doc, which\n // cross-references it): `deliverNudge` drops a request into this run's\n // OWN steer-requests queue via `requestAsyncSteer`, and\n // `ControlChannelWatcher` (wired up by `execution.start()` below) claims\n // it and calls this handler. Without it, `execution.start()` still\n // claims and commits the nudge - `deliverNudge` reports\n // `nudgeDelivered: true`, `status.json` still shows `needs_attention` -\n // but the request is silently discarded before it ever reaches the\n // child's own conversation. `formatSteerMessage`/`sendUserMessage` are\n // the exact same delivery this file already uses for\n // `registerSteeringInbox`'s separate queue.\n execution.start(runId, {\n onSteer: (request) => {\n const sendUserMessage = (\n pi as { sendUserMessage?: (content: string, options: { deliverAs: 'steer' }) => unknown }\n ).sendUserMessage;\n if (!sendUserMessage) {\n acknowledgeRunnerSteer(request, 'failed', 'Child Pi session does not support sendUserMessage steering.');\n return;\n }\n try {\n sendUserMessage(formatSteerMessage(request), { deliverAs: 'steer' });\n acknowledgeRunnerSteer(request, 'delivered', 'Pi accepted the correlated steering input.');\n } catch (error) {\n acknowledgeRunnerSteer(request, 'failed', error instanceof Error ? error.message : String(error));\n throw error;\n }\n },\n });\n resolved = { teamContext: bootstrapped.teamContext };\n execution.setActivity('working');\n });\n\n onEvent(pi, 'agent_start', () => {\n if (resolved) execution.setActivity('working');\n });\n onEvent<{ message?: ChildTranscriptMessage }>(pi, 'message_end', (event) => {\n if (!resolved || !event.message || typeof event.message !== 'object') return;\n if (countedMessages.has(event.message)) return;\n countedMessages.add(event.message);\n const messageTokens = getMessageUsageTokens(event.message);\n if (messageTokens === undefined) return;\n cumulativeTokens = (cumulativeTokens ?? 0) + messageTokens;\n execution.setProgress({ tokens: cumulativeTokens });\n });\n onEvent<{ toolName?: string; tool?: { name?: string }; args?: { action?: string } }>(\n pi,\n 'tool_execution_start',\n (event) => {\n if (!resolved) return;\n const toolName = event.toolName ?? event.tool?.name;\n toolCount += 1;\n execution.setProgress({\n toolCount,\n ...(typeof toolName === 'string' && toolName.length > 0 ? { currentTool: toolName } : {}),\n });\n execution.setActivity(\n toolName === NATIVE_TEAM_TOOL_NAME && event.args?.action === 'ask' ? 'waiting_for_reply' : 'tool',\n );\n },\n );\n onEvent(pi, 'tool_execution_end', () => {\n if (resolved) execution.setActivity('working');\n });\n onEvent<{ messages: DeliverableCheckMessage[] }>(pi, 'agent_end', (event) => {\n if (!resolved) return; // session_start has not bootstrapped yet; nothing to report against.\n execution.setActivity('finalizing');\n const summary = extractAssistantSummaryText(event.messages);\n execution.complete(true, summary);\n });\n}\n\nconst PARENT_ONLY_CUSTOM_MESSAGE_TYPES = new Set([\n 'subagent-orchestration-instructions',\n 'subagent-slash-result',\n 'subagent-slash-text-result',\n 'subagent-notify',\n 'subagent_control_notice',\n 'subagent-control',\n 'subagent-control-notice',\n]);\nconst SUBAGENT_ORCHESTRATION_SKILL_NAME_PATTERN = /<name>\\s*pi-subagents\\s*<\\/name>/;\nconst PROJECT_CONTEXT_HEADER = '\\n\\n# Project Context\\n\\nProject-specific instructions and guidelines:\\n\\n';\nconst SKILLS_HEADER = '\\n\\nThe following skills provide specialized instructions for specific tasks.';\nconst DATE_HEADER = '\\nCurrent date:';\n\nfunction readBooleanEnv(name: string): boolean | undefined {\n const value = process.env[name];\n if (value === undefined) return undefined;\n return value !== '0';\n}\n\nfunction readRequiredChildTools(): string[] | undefined {\n const encoded = process.env[REQUIRED_CHILD_TOOLS_ENV]?.trim();\n if (!encoded) return undefined;\n const required = JSON.parse(encoded) as unknown;\n if (!Array.isArray(required) || required.some((name) => typeof name !== 'string' || !name)) {\n throw new Error(`Invalid ${REQUIRED_CHILD_TOOLS_ENV} payload.`);\n }\n return required;\n}\n\nfunction readMcpDirectChildTools(): string[] | undefined {\n const encoded = process.env[MCP_DIRECT_CHILD_TOOLS_ENV]?.trim();\n if (!encoded) return undefined;\n try {\n const tools = JSON.parse(encoded) as unknown;\n if (!Array.isArray(tools) || tools.some((name) => typeof name !== 'string' || !name)) return undefined;\n return tools;\n } catch {\n return undefined;\n }\n}\n\nfunction refreshChildToolDiagnostic(pi: ExtensionAPI): ChildToolDiagnostic | undefined {\n const filePath = process.env[CHILD_TOOL_DIAGNOSTIC_PATH_ENV]?.trim();\n const required = readRequiredChildTools();\n if (!filePath || !required) return undefined;\n const available = pi.getAllTools().map((tool) => tool.name);\n return writeChildToolDiagnostic(\n filePath,\n required,\n available,\n process.env[SUBAGENT_CHILD_AGENT_ENV]?.trim(),\n readMcpDirectChildTools(),\n );\n}\n\nfunction findSectionEnd(prompt: string, startIndex: number, nextHeaders: string[]): number {\n let endIndex = prompt.length;\n for (const header of nextHeaders) {\n const index = prompt.indexOf(header, startIndex);\n if (index !== -1 && index < endIndex) {\n endIndex = index;\n }\n }\n return endIndex;\n}\n\nexport function stripProjectContext(prompt: string): string {\n const startIndex = prompt.indexOf(PROJECT_CONTEXT_HEADER);\n if (startIndex === -1) return prompt;\n const endIndex = findSectionEnd(prompt, startIndex + PROJECT_CONTEXT_HEADER.length, [SKILLS_HEADER, DATE_HEADER]);\n return `${prompt.slice(0, startIndex)}${prompt.slice(endIndex)}`;\n}\n\nexport function stripInheritedSkills(prompt: string): string {\n const startIndex = prompt.indexOf(SKILLS_HEADER);\n if (startIndex === -1) return prompt;\n const endIndex = findSectionEnd(prompt, startIndex + SKILLS_HEADER.length, [DATE_HEADER]);\n return `${prompt.slice(0, startIndex)}${prompt.slice(endIndex)}`;\n}\n\nexport function stripSubagentOrchestrationSkill(prompt: string): string {\n return prompt\n .replace(/\\n{0,2}<skill\\s+name=[\"']pi-subagents[\"'][^>]*>[\\s\\S]*?<\\/skill>\\n{0,2}/g, '\\n\\n')\n .replace(/[ \\t]*<skill>\\s*[\\s\\S]*?<\\/skill>\\s*/g, (block) =>\n SUBAGENT_ORCHESTRATION_SKILL_NAME_PATTERN.test(block) ? '' : block,\n );\n}\n\nfunction stripChildBoundaryInstructions(prompt: string): string {\n let rewritten = prompt;\n for (const boundary of [CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS, CHILD_FANOUT_BOUNDARY_INSTRUCTIONS]) {\n rewritten = rewritten.split(boundary).join('');\n }\n return rewritten.replace(/^(?:[ \\t]*\\r?\\n)+/, '');\n}\n\nexport function rewriteSubagentPrompt(\n prompt: string,\n options: { inheritProjectContext: boolean; inheritSkills: boolean; fanoutChild?: boolean },\n): string {\n let rewritten = prompt;\n if (!options.inheritProjectContext) {\n rewritten = stripProjectContext(rewritten);\n }\n if (!options.inheritSkills) {\n rewritten = stripInheritedSkills(rewritten);\n }\n rewritten = stripSubagentOrchestrationSkill(rewritten);\n rewritten = stripChildBoundaryInstructions(rewritten);\n const boundary = options.fanoutChild ? CHILD_FANOUT_BOUNDARY_INSTRUCTIONS : CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS;\n const structured = process.env[STRUCTURED_OUTPUT_CAPTURE_ENV] ? `\\n\\n${STRUCTURED_OUTPUT_INSTRUCTIONS}` : '';\n return `${boundary}${structured}\\n\\n${rewritten}`;\n}\n\nfunction isParentOnlySubagentMessage(message: unknown): boolean {\n const m = message as { role?: string; customType?: string };\n if (m?.role !== 'custom' || typeof m.customType !== 'string') return false;\n return PARENT_ONLY_CUSTOM_MESSAGE_TYPES.has(m.customType);\n}\n\nfunction isSubagentToolResultMessage(message: unknown): boolean {\n const m = message as { role?: string; toolName?: string };\n return m?.role === 'toolResult' && m.toolName === 'subagent';\n}\n\nfunction isSubagentToolCallBlock(block: unknown): boolean {\n const b = block as { type?: string; name?: string };\n return b?.type === 'toolCall' && b.name === 'subagent';\n}\n\nfunction stripAssistantSubagentToolCallBlocks(message: unknown): unknown {\n const m = message as { role?: string; content?: unknown };\n if (m?.role !== 'assistant' || !Array.isArray(m.content)) return message;\n const filteredContent = m.content.filter((block) => !isSubagentToolCallBlock(block));\n if (filteredContent.length === m.content.length) return message;\n if (filteredContent.length === 0) return undefined;\n return { ...m, content: filteredContent };\n}\n\nexport function stripParentOnlySubagentMessages(messages: unknown[]): unknown[] {\n const preserveCurrentFanoutToolHistory = process.env[SUBAGENT_FANOUT_CHILD_ENV] === '1';\n let changed = false;\n const filtered: unknown[] = [];\n for (const message of messages) {\n if (\n isParentOnlySubagentMessage(message) ||\n (!preserveCurrentFanoutToolHistory && isSubagentToolResultMessage(message))\n ) {\n changed = true;\n continue;\n }\n const stripped = preserveCurrentFanoutToolHistory ? message : stripAssistantSubagentToolCallBlocks(message);\n if (stripped === undefined) {\n changed = true;\n continue;\n }\n if (stripped !== message) changed = true;\n filtered.push(stripped);\n }\n return changed ? filtered : messages;\n}\n\nexport function formatSteerMessage(request: SteerRequest): string {\n return [\n 'Mid-run steering from the parent orchestrator:',\n '',\n request.message,\n '',\n 'Incorporate this guidance at the next safe point. Do not restart the task unless the guidance explicitly asks you to.',\n ].join('\\n');\n}\n\nfunction acknowledgeRunnerSteer(request: SteerRequest, state: 'delivered' | 'failed', message: string): void {\n const ackDir = process.env[SUBAGENT_STEER_ACK_DIR_ENV]?.trim();\n const childIndex = Number(process.env[SUBAGENT_CHILD_INDEX_ENV]);\n if (!ackDir || !Number.isInteger(childIndex) || childIndex < 0) return;\n writeSteerAckAt(steerAckPathFromDir(ackDir, request.id), {\n requestId: request.id,\n index: childIndex,\n ts: Date.now(),\n state,\n message,\n });\n}\n\nfunction registerToolBudget(\n pi: ExtensionAPI,\n budget: ResolvedToolBudget | undefined,\n diagnostics: PromptRuntimeDiagnostics,\n): void {\n if (!budget) return;\n let toolCount = 0;\n let softNudged = false;\n const sendUserMessage = (pi as { sendUserMessage?: (content: string, options: { deliverAs: 'steer' }) => unknown })\n .sendUserMessage;\n onEvent<{ toolName?: string }>(pi, 'tool_call', (event) => {\n const toolName = typeof event.toolName === 'string' ? event.toolName : 'tool';\n toolCount++;\n if (budget.soft !== undefined && toolCount >= budget.soft && !softNudged) {\n softNudged = true;\n try {\n sendUserMessage?.(toolBudgetSoftNudge(budget, toolCount), { deliverAs: 'steer' });\n } catch (error) {\n // Advisory nudge only; the child's own output is what matters. Recorded\n // rather than discarded so a host that never accepts steering is\n // discoverable instead of silently dropping every nudge.\n diagnostics.steerNudgeFailures += 1;\n diagnostics.lastError = error;\n }\n }\n if (!shouldBlockToolForBudget(budget, toolName, toolCount)) return undefined;\n return { block: true, reason: toolBudgetBlockedMessage(budget, toolName, toolCount) };\n });\n}\n\n/**\n * Deliver mid-run steer requests queued for THIS child (by fan-out index)\n * into its own session via `sendUserMessage`. See the module doc's FIX for\n * why this claims each request individually rather than batch-deleting.\n */\nexport function registerSteeringInbox(\n pi: ExtensionAPI,\n deps: {\n watch?: typeof fs.watch;\n nativeRealpath?: (filePath: string) => string;\n diagnostics?: PromptRuntimeDiagnostics;\n } = {},\n): void {\n const diagnostics = deps.diagnostics ?? createPromptRuntimeDiagnostics();\n const steerInbox = process.env[SUBAGENT_STEER_INBOX_ENV]?.trim();\n if (!steerInbox) return;\n const capabilityPath = process.env[SUBAGENT_STEER_CAPABILITY_ENV]?.trim();\n const ackDir = process.env[SUBAGENT_STEER_ACK_DIR_ENV]?.trim();\n const sendUserMessage = (pi as { sendUserMessage?: (content: string, options: { deliverAs: 'steer' }) => unknown })\n .sendUserMessage;\n const childIndex = Number(process.env[SUBAGENT_CHILD_INDEX_ENV]);\n const pending = new Map<string, string[]>();\n let disposed = false;\n let flushing = false;\n let started = false;\n const canSteer = typeof sendUserMessage === 'function';\n let watcher: fs.FSWatcher | undefined;\n let interval: NodeJS.Timeout | undefined;\n\n const acknowledge = (request: SteerRequest, state: 'delivered' | 'failed', message: string): void => {\n if (!ackDir || !Number.isInteger(childIndex) || childIndex < 0) return;\n writeSteerAckAt(steerAckPathFromDir(ackDir, request.id), {\n requestId: request.id,\n index: childIndex,\n ts: Date.now(),\n state,\n message,\n });\n };\n const publishCapability = (): void => {\n if (!capabilityPath || !Number.isInteger(childIndex) || childIndex < 0) return;\n writeSteerCapabilityAt(capabilityPath, {\n index: childIndex,\n pid: process.pid,\n readyAt: Date.now(),\n supported: canSteer,\n });\n };\n\n const flush = (): void => {\n if (disposed || flushing) return;\n flushing = true;\n try {\n for (const claim of claimSteerRequestsFromDir(steerInbox)) {\n if (!canSteer || typeof sendUserMessage !== 'function') {\n acknowledge(claim.request, 'failed', 'Child Pi session does not support sendUserMessage steering.');\n claim.commit();\n continue;\n }\n const formatted = formatSteerMessage(claim.request);\n const ids = pending.get(formatted) ?? [];\n ids.push(claim.request.id);\n pending.set(formatted, ids);\n try {\n sendUserMessage(formatted, { deliverAs: 'steer' });\n claim.commit();\n } catch (error) {\n ids.pop();\n if (ids.length === 0) pending.delete(formatted);\n // Recoverable: this claim goes back to the queue for the next\n // flush to retry, instead of being lost. See the module doc's FIX.\n claim.release();\n acknowledge(claim.request, 'failed', error instanceof Error ? error.message : String(error));\n }\n }\n } finally {\n flushing = false;\n }\n };\n const onInput = (event: unknown): undefined => {\n if (disposed || !event || typeof event !== 'object') return undefined;\n const input = event as { source?: unknown; streamingBehavior?: unknown; text?: unknown; content?: unknown };\n if (input.source !== 'extension' || input.streamingBehavior !== 'steer') return undefined;\n const text =\n typeof input.text === 'string' ? input.text : typeof input.content === 'string' ? input.content : undefined;\n if (!text) return undefined;\n const ids = pending.get(text);\n const requestId = ids?.shift();\n if (!requestId) return undefined;\n if (ids?.length === 0) pending.delete(text);\n acknowledge(\n { type: 'steer', id: requestId, ts: Date.now(), message: text },\n 'delivered',\n 'Pi accepted the correlated steering input.',\n );\n return undefined;\n };\n const start = (): void => {\n if (started || disposed) return;\n try {\n fs.mkdirSync(steerInbox, { recursive: true });\n publishCapability();\n } catch {\n // No channel to report a startup failure on from inside the child;\n // the parent observes a missing capability file and treats it as\n // \"steering unsupported for this child\" on its own.\n return;\n }\n started = true;\n try {\n watcher = (deps.watch ?? fs.watch)(resolveWatchPath(steerInbox, deps.nativeRealpath), () => flush());\n watcher.on('error', (error) => {\n // fs.watch emits on transient FS errors and the interval poll below\n // keeps delivery live regardless, so this is not fatal. Recorded so a\n // watch that fails on every event is distinguishable from a quiet inbox.\n diagnostics.watchErrors += 1;\n diagnostics.lastError = error;\n });\n } catch {\n watcher = undefined;\n }\n interval = setInterval(flush, STEER_FLUSH_POLL_INTERVAL_MS);\n interval.unref?.();\n };\n const activate = (): undefined => {\n start();\n flush();\n return undefined;\n };\n\n // Register input before the watcher so an accepted extension input cannot race request dispatch.\n onEvent(pi, 'input', onInput);\n onEvent(pi, 'session_start', () => start());\n for (const eventName of [\n 'message_start',\n 'message_update',\n 'message_end',\n 'tool_execution_start',\n 'tool_execution_end',\n 'turn_end',\n ] as const) {\n onEvent(pi, eventName, activate);\n }\n onEvent(pi, 'session_shutdown', () => {\n disposed = true;\n try {\n watcher?.close();\n } catch (error) {\n // Best effort; the process is shutting down regardless. Still recorded,\n // because a close that always fails is a leaked descriptor per run.\n diagnostics.watchCloseFailures += 1;\n diagnostics.lastError = error;\n }\n if (interval) clearInterval(interval);\n });\n}\n\n/**\n * `diagnostics` is optional and defaults to a fresh object: the `.cts` entry\n * point calls this with a single argument (`pi`), matching the host contract\n * `resolveRuntimeExtensionPath` resolves onto every child's `--extension`\n * args, so that call keeps working unchanged. A caller that wants to observe\n * what this runtime absorbed - see `PromptRuntimeDiagnostics` - passes its\n * own object and keeps the reference; this function only ever mutates it, it\n * never owns or resets it.\n */\nexport function registerSubagentPromptRuntime(\n pi: ExtensionAPI,\n diagnostics: PromptRuntimeDiagnostics = createPromptRuntimeDiagnostics(),\n): void {\n // First, before any scoped path is touched. Pi loads extensions through jiti\n // with `moduleCache: false`, so this extension gets its OWN instance of\n // `shared/paths.ts` - the scope the surrounding runner process adopted is not\n // visible here, and has to be read from the environment again.\n adoptSessionScopeFromEnv();\n registerSteeringInbox(pi, { diagnostics });\n registerToolBudget(\n pi,\n decodeToolBudgetEnv(process.env[TOOL_BUDGET_ENV], { allowZero: process.env[TOOL_BUDGET_ZERO_AUTH_ENV] === '1' }),\n diagnostics,\n );\n // One container for this whole registration, not one built inside each\n // resolver's own default parameter: this process has exactly one\n // composition root (see container/index.ts and this function's own doc),\n // and a second independent createPromptRuntimeContainer() call anywhere\n // else in this function would silently mean two sets of \"singletons\" in\n // one process, defeating the point of a shared container.\n const container = createPromptRuntimeContainer();\n registerRunnerLifecycle(pi, container);\n\n const teamChannels = container.get<INativeTeamChannelService>(DOOM_TEAM_TYPES.NativeTeamChannelService);\n\n onEvent(pi, 'session_start', () => {\n const teamRuntime = teamChannels.createRuntime(pi);\n teamRuntime.bindChildFromEnvironment();\n });\n onEvent(pi, 'agent_start', () => {\n refreshChildToolDiagnostic(pi);\n });\n // `agent_end` intentionally does not drain outstanding work here. See the\n // module doc's \"WHAT IS DELIBERATELY NOT WIRED YET\" for why.\n\n const structuredOutputPath = process.env[STRUCTURED_OUTPUT_CAPTURE_ENV];\n const structuredSchemaPath = process.env[STRUCTURED_OUTPUT_SCHEMA_ENV];\n if (structuredOutputPath && structuredSchemaPath) {\n const schema = JSON.parse(fs.readFileSync(structuredSchemaPath, 'utf-8')) as JsonSchemaObject;\n const parameters = createStructuredOutputToolParameters(schema);\n const validator = new StructuredOutputValidator();\n const registerTool = (\n pi.registerTool as unknown as (tool: {\n name: string;\n label: string;\n description: string;\n parameters: unknown;\n execute: (_id: string, params: { value: unknown }) => Promise<unknown>;\n }) => void\n ).bind(pi);\n registerTool({\n name: 'structured_output',\n label: 'Structured Output',\n description: 'Submit the required final structured output for this subagent step. This terminates the step.',\n parameters: parameters as never,\n async execute(_id: string, params: { value: unknown }) {\n const validation = await validator.validateValue(schema, params.value);\n if (validation.status === 'invalid') {\n throw new Error(`Structured output validation failed: ${validation.message}`);\n }\n fs.mkdirSync(path.dirname(structuredOutputPath), { recursive: true });\n fs.writeFileSync(structuredOutputPath, JSON.stringify(params.value), { mode: 0o600 });\n return {\n content: [{ type: 'text', text: 'Structured output captured.' }],\n details: { path: structuredOutputPath },\n terminate: true,\n };\n },\n });\n }\n\n onEvent<{ messages: unknown[] }>(pi, 'context', (event) => {\n const messages = stripParentOnlySubagentMessages(event.messages);\n if (messages === event.messages) return undefined;\n return { messages };\n });\n\n onEvent<{ systemPrompt: string }>(pi, 'before_agent_start', async (event) => {\n const intercomSessionName = process.env[SUBAGENT_INTERCOM_SESSION_NAME_ENV]?.trim();\n if (intercomSessionName && typeof pi.setSessionName === 'function') {\n pi.setSessionName(intercomSessionName);\n }\n\n const inheritProjectContext = readBooleanEnv(INHERIT_PROJECT_CONTEXT_ENV);\n const inheritSkills = readBooleanEnv(INHERIT_SKILLS_ENV);\n const fanoutChild = readBooleanEnv(SUBAGENT_FANOUT_CHILD_ENV);\n let rewritten = event.systemPrompt;\n if (inheritProjectContext !== undefined || inheritSkills !== undefined || fanoutChild !== undefined) {\n rewritten = rewriteSubagentPrompt(event.systemPrompt, {\n inheritProjectContext: inheritProjectContext ?? true,\n inheritSkills: inheritSkills ?? true,\n fanoutChild: fanoutChild === true,\n });\n }\n if (rewritten === event.systemPrompt) return;\n return { systemPrompt: rewritten };\n });\n}\n"],"mappings":"8kBAmJA,SAAgB,GAA2D,CACzE,MAAO,CAAE,mBAAoB,EAAG,YAAa,EAAG,mBAAoB,EAAG,CAGzE,MAAM,EAAiC,CACrC,8DACA,yGACA,gHACD,CAAC,KAAK;EAAK,CAEC,EAAuC,CAClD,yDACA,mGACA,yFACA,mHACA,oIACD,CAAC,KAAK;EAAK,CAEC,EAAqC,CAChD,uFACA,kGACA,8FACA,uIACA,uEACA,oIACD,CAAC,KAAK;EAAK,CAiBZ,SAAS,EACP,EACA,EACA,EACM,CACL,EAAG,GAAiG,KACnG,EACA,EACA,EACD,CAeH,SAAS,EAAqB,EAA6C,CACzE,OACE,OAAO,GAAU,YACjB,GACC,EAA6B,OAAS,QACvC,OAAQ,EAA6B,MAAS,SAmBlD,SAAgB,EAA4B,EAAsD,CAChG,IAAK,IAAI,EAAQ,EAAS,OAAS,EAAG,GAAS,EAAG,IAAY,CAC5D,IAAM,EAAU,EAAS,GACzB,GAAI,GAAS,OAAS,a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AAU,cAAc,EAAQ,EAAO,MAAM,CACtE,GAAI,EAAW,SAAW,UACxB,MAAU,MAAM,wCAAwC,EAAW,UAAU,CAI/E,OAFA,EAAG,UAAUC,EAAK,QAAQ,EAAqB,CAAE,CAAE,UAAW,GAAM,CAAC,CACrE,EAAG,cAAc,EAAsB,KAAK,UAAU,EAAO,MAAM,CAAE,CAAE,KAAM,IAAO,CAAC,CAC9E,CACL,QAAS,CAAC,CAAE,KAAM,OAAQ,KAAM,8BAA+B,CAAC,CAChE,QAAS,CAAE,KAAM,EAAsB,CACvC,UAAW,GACZ,EAEJ,CAAC,CAGJ,EAAiC,EAAI,UAAY,GAAU,CACzD,IAAM,EAAW,EAAgC,EAAM,SAAS,CAC5D,OAAa,EAAM,SACvB,MAAO,CAAE,WAAU,EACnB,CAEF,EAAkC,EAAI,qBAAsB,KAAO,IAAU,CAC3E,IAAM,EAAsB,QAAQ,IAAIC,EAAAA,qCAAqC,MAAM,CAC/E,GAAuB,OAAO,EAAG,gBAAmB,YACtD,EAAG,eAAe,EAAoB,CAGxC,IAAM,EAAwB,EAAeC,EAAAA,4BAA4B,CACnE,EAAgB,EAAeC,EAAAA,mBAAmB,CAClD,EAAc,EAAetB,EAAAA,0BAA0B,CACzD,EAAY,EAAM,aACtB,IAAI,IAA0B,IAAA,IAAa,IAAkB,IAAA,IAAa,IAAgB,IAAA,MACxF,EAAY,EAAsB,EAAM,aAAc,CACpD,sBAAuB,GAAyB,GAChD,cAAe,GAAiB,GAChC,YAAa,IAAgB,GAC9B,CAAC,EAEA,IAAc,EAAM,aACxB,MAAO,CAAE,aAAc,EAAW,EAClC"}
@@ -0,0 +1,58 @@
1
+ import { Container } from "inversify";
2
+ import { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+
4
+ //#region src/extensions/subagentPromptRuntime.d.ts
5
+ /**
6
+ * Failures this runtime absorbed rather than propagated.
7
+ *
8
+ * WHY RECORD RATHER THAN LOG:
9
+ * This module runs inside the spawned child, where stdout IS the child's
10
+ * captured transcript. Writing a diagnostic there would corrupt the very
11
+ * output the run exists to produce, so nothing here may reach stdio. But a
12
+ * discarded error is indistinguishable from one that never happened, and a
13
+ * watcher that fails on every event looks exactly like a quiet inbox. These
14
+ * counters are the compromise: cheap, bounded, and queryable by a caller that
15
+ * wants to know whether the child's steering path was actually healthy.
16
+ *
17
+ * WHY THIS IS CALLER-OWNED, NOT MODULE STATE:
18
+ * A module-level singleton here would be exactly the bug this package's "no
19
+ * module-level mutable state" rule exists to prevent - see
20
+ * `nativeTeamChannel.ts`'s header: "a second session in the same process
21
+ * cannot inherit the first one's [state]". `registerSubagentPromptRuntime`
22
+ * runs once per real child process, so a singleton would rarely matter in
23
+ * production, but every test in this file registers multiple independent
24
+ * runtimes in one process, and a shared singleton would leak counts between
25
+ * them silently. `createPromptRuntimeDiagnostics()` hands each registration
26
+ * its own object instead; the caller keeps the reference to read later, and
27
+ * a fresh registration is what "reset" means - there is no shared state left
28
+ * to reset.
29
+ *
30
+ * AVOID:
31
+ * - Adding a `console.*` here, on any path, for any reason
32
+ * - Treating a non-zero count as fatal; every one of these is a degraded-mode
33
+ * path with a working fallback, which is why it was absorbed in the first place
34
+ * - Reintroducing a module-level instance of this. See the header above
35
+ */
36
+ interface PromptRuntimeDiagnostics {
37
+ /** Advisory tool-budget nudges that could not be delivered to the child. */
38
+ steerNudgeFailures: number;
39
+ /** Errors emitted by the steer-inbox watcher. The interval poll covers these. */
40
+ watchErrors: number;
41
+ /** Failures closing the watcher during shutdown. */
42
+ watchCloseFailures: number;
43
+ /** The most recent absorbed failure, whichever kind it was. */
44
+ lastError?: unknown;
45
+ }
46
+ /**
47
+ * `diagnostics` is optional and defaults to a fresh object: the `.cts` entry
48
+ * point calls this with a single argument (`pi`), matching the host contract
49
+ * `resolveRuntimeExtensionPath` resolves onto every child's `--extension`
50
+ * args, so that call keeps working unchanged. A caller that wants to observe
51
+ * what this runtime absorbed - see `PromptRuntimeDiagnostics` - passes its
52
+ * own object and keeps the reference; this function only ever mutates it, it
53
+ * never owns or resets it.
54
+ */
55
+ declare function registerSubagentPromptRuntime(pi: ExtensionAPI, diagnostics?: PromptRuntimeDiagnostics): void;
56
+ //#endregion
57
+ export { registerSubagentPromptRuntime };
58
+ //# sourceMappingURL=subagentPromptRuntime.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subagentPromptRuntime.d.cts","names":[],"sources":["../../src/extensions/subagentPromptRuntime.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAuIiB,wBAAA;;EAEf,kBAAA;;EAEA,WAAA;;EAEA,kBAAA;;EAEA,SAAA;AAAA;;;;;;;;;;iBA+pBc,6BAAA,CACd,EAAA,EAAI,YAAA,EACJ,WAAA,GAAa,wBAAA"}
@@ -0,0 +1,58 @@
1
+ import { Container } from "inversify";
2
+ import { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+
4
+ //#region src/extensions/subagentPromptRuntime.d.ts
5
+ /**
6
+ * Failures this runtime absorbed rather than propagated.
7
+ *
8
+ * WHY RECORD RATHER THAN LOG:
9
+ * This module runs inside the spawned child, where stdout IS the child's
10
+ * captured transcript. Writing a diagnostic there would corrupt the very
11
+ * output the run exists to produce, so nothing here may reach stdio. But a
12
+ * discarded error is indistinguishable from one that never happened, and a
13
+ * watcher that fails on every event looks exactly like a quiet inbox. These
14
+ * counters are the compromise: cheap, bounded, and queryable by a caller that
15
+ * wants to know whether the child's steering path was actually healthy.
16
+ *
17
+ * WHY THIS IS CALLER-OWNED, NOT MODULE STATE:
18
+ * A module-level singleton here would be exactly the bug this package's "no
19
+ * module-level mutable state" rule exists to prevent - see
20
+ * `nativeTeamChannel.ts`'s header: "a second session in the same process
21
+ * cannot inherit the first one's [state]". `registerSubagentPromptRuntime`
22
+ * runs once per real child process, so a singleton would rarely matter in
23
+ * production, but every test in this file registers multiple independent
24
+ * runtimes in one process, and a shared singleton would leak counts between
25
+ * them silently. `createPromptRuntimeDiagnostics()` hands each registration
26
+ * its own object instead; the caller keeps the reference to read later, and
27
+ * a fresh registration is what "reset" means - there is no shared state left
28
+ * to reset.
29
+ *
30
+ * AVOID:
31
+ * - Adding a `console.*` here, on any path, for any reason
32
+ * - Treating a non-zero count as fatal; every one of these is a degraded-mode
33
+ * path with a working fallback, which is why it was absorbed in the first place
34
+ * - Reintroducing a module-level instance of this. See the header above
35
+ */
36
+ interface PromptRuntimeDiagnostics {
37
+ /** Advisory tool-budget nudges that could not be delivered to the child. */
38
+ steerNudgeFailures: number;
39
+ /** Errors emitted by the steer-inbox watcher. The interval poll covers these. */
40
+ watchErrors: number;
41
+ /** Failures closing the watcher during shutdown. */
42
+ watchCloseFailures: number;
43
+ /** The most recent absorbed failure, whichever kind it was. */
44
+ lastError?: unknown;
45
+ }
46
+ /**
47
+ * `diagnostics` is optional and defaults to a fresh object: the `.cts` entry
48
+ * point calls this with a single argument (`pi`), matching the host contract
49
+ * `resolveRuntimeExtensionPath` resolves onto every child's `--extension`
50
+ * args, so that call keeps working unchanged. A caller that wants to observe
51
+ * what this runtime absorbed - see `PromptRuntimeDiagnostics` - passes its
52
+ * own object and keeps the reference; this function only ever mutates it, it
53
+ * never owns or resets it.
54
+ */
55
+ declare function registerSubagentPromptRuntime(pi: ExtensionAPI, diagnostics?: PromptRuntimeDiagnostics): void;
56
+ //#endregion
57
+ export { registerSubagentPromptRuntime };
58
+ //# sourceMappingURL=subagentPromptRuntime.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subagentPromptRuntime.d.mts","names":[],"sources":["../../src/extensions/subagentPromptRuntime.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAuIiB,wBAAA;;EAEf,kBAAA;;EAEA,WAAA;;EAEA,kBAAA;;EAEA,SAAA;AAAA;;;;;;;;;;iBA+pBc,6BAAA,CACd,EAAA,EAAI,YAAA,EACJ,WAAA,GAAa,wBAAA"}
@@ -0,0 +1,18 @@
1
+ import{__esmMin as e}from"../_virtual/_rolldown/runtime.mjs";import{init_configDir as t,resolveWatchPath as n}from"../shared/configDir.mjs";import{CHILD_TOOL_DIAGNOSTIC_PATH_ENV as r,INHERIT_PROJECT_CONTEXT_ENV as i,INHERIT_SKILLS_ENV as a,MCP_DIRECT_CHILD_TOOLS_ENV as o,REQUIRED_CHILD_TOOLS_ENV as s,STRUCTURED_OUTPUT_CAPTURE_ENV as c,STRUCTURED_OUTPUT_SCHEMA_ENV as l,SUBAGENT_CHILD_AGENT_ENV as u,SUBAGENT_CHILD_INDEX_ENV as d,SUBAGENT_FANOUT_CHILD_ENV as f,SUBAGENT_INTERCOM_SESSION_NAME_ENV as p,SUBAGENT_RUN_ID_ENV as m,SUBAGENT_STEER_ACK_DIR_ENV as h,SUBAGENT_STEER_CAPABILITY_ENV as g,SUBAGENT_STEER_INBOX_ENV as ee,TOOL_BUDGET_ENV as _,TOOL_BUDGET_ZERO_AUTH_ENV as v,init_env as y}from"../env.mjs";import{DOOM_TEAM_TYPES as b}from"../container/types.mjs";import{claimSteerRequestsFromDir as x,init_supervisorControlChannel as S,steerAckPathFromDir as C,writeSteerAckAt as w,writeSteerCapabilityAt as te}from"../intercom/supervisorControlChannel.mjs";import{adoptSessionScopeFromEnv as T,init_paths as E}from"../shared/paths.mjs";import{init_nativeTeamChannel as D,nativeTeamMemberEnvironment as O}from"../intercom/nativeTeamChannel.mjs";import{decodeToolBudgetEnv as ne,init_toolBudget as re,shouldBlockToolForBudget as ie,toolBudgetBlockedMessage as k,toolBudgetSoftNudge as ae}from"../runs/shared/toolBudget.mjs";import{createPromptRuntimeContainer as A,init_container as oe}from"../container/index.mjs";import{getMessageUsageTokens as se,init_childTranscript as ce}from"../shared/childTranscript.mjs";import{StructuredOutputValidator as le,createStructuredOutputToolParameters as ue,init_structuredOutput as de}from"../runs/shared/structuredOutput.mjs";import{init_toolAvailability as fe,writeChildToolDiagnostic as pe}from"../runs/shared/toolAvailability.mjs";import*as j from"node:fs";import*as M from"node:path";function N(){return{steerNudgeFailures:0,watchErrors:0,watchCloseFailures:0}}function P(e,t,n){e.on.call(e,t,n)}function F(e){return typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`}function I(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.role!==`assistant`||!Array.isArray(n.content))continue;let r=n.content.filter(F).map(e=>e.text).join(`
2
+ `).trim();if(r)return r}return``}function L(e,t=A()){let n=process.env[m]?.trim();if(!n)return;let r=t.get(b.PollScheduler),i=t.get(b.RunnerBootstrap),a=t.get(b.RunnerExecution),o=t.get(b.RunnerReporting),s,c,l=0,u=new WeakSet;P(e,`session_start`,(t,c)=>{if(s)return;r.start();let l=c.sessionManager.getSessionFile(),u=l?o.recordSessionFile(l):void 0,d=i.bootstrap(n,u);d.teamContext&&Object.assign(process.env,O(d.teamContext)),a.start(n,{onSteer:t=>{let n=e.sendUserMessage;if(!n){U(t,`failed`,`Child Pi session does not support sendUserMessage steering.`);return}try{n(H(t),{deliverAs:`steer`}),U(t,`delivered`,`Pi accepted the correlated steering input.`)}catch(e){throw U(t,`failed`,e instanceof Error?e.message:String(e)),e}}}),s={teamContext:d.teamContext},a.setActivity(`working`)}),P(e,`agent_start`,()=>{s&&a.setActivity(`working`)}),P(e,`message_end`,e=>{if(!s||!e.message||typeof e.message!=`object`||u.has(e.message))return;u.add(e.message);let t=se(e.message);t!==void 0&&(c=(c??0)+t,a.setProgress({tokens:c}))}),P(e,`tool_execution_start`,e=>{if(!s)return;let t=e.toolName??e.tool?.name;l+=1,a.setProgress({toolCount:l,...typeof t==`string`&&t.length>0?{currentTool:t}:{}}),a.setActivity(t===`intercom`&&e.args?.action===`ask`?`waiting_for_reply`:`tool`)}),P(e,`tool_execution_end`,()=>{s&&a.setActivity(`working`)}),P(e,`agent_end`,e=>{if(!s)return;a.setActivity(`finalizing`);let t=I(e.messages);a.complete(!0,t)})}function R(e){let t=process.env[e];if(t!==void 0)return t!==`0`}function z(){let e=process.env[s]?.trim();if(!e)return;let t=JSON.parse(e);if(!Array.isArray(t)||t.some(e=>typeof e!=`string`||!e))throw Error(`Invalid ${s} payload.`);return t}function B(){let e=process.env[o]?.trim();if(e)try{let t=JSON.parse(e);return!Array.isArray(t)||t.some(e=>typeof e!=`string`||!e)?void 0:t}catch{return}}function me(e){let t=process.env[r]?.trim(),n=z();if(!(!t||!n))return pe(t,n,e.getAllTools().map(e=>e.name),process.env[u]?.trim(),B())}function V(e,t,n){let r=e.length;for(let i of n){let n=e.indexOf(i,t);n!==-1&&n<r&&(r=n)}return r}function he(e){let t=e.indexOf(X);if(t===-1)return e;let n=V(e,t+68,[Z,Q]);return`${e.slice(0,t)}${e.slice(n)}`}function ge(e){let t=e.indexOf(Z);if(t===-1)return e;let n=V(e,t+75,[Q]);return`${e.slice(0,t)}${e.slice(n)}`}function _e(e){return e.replace(/\n{0,2}<skill\s+name=["']pi-subagents["'][^>]*>[\s\S]*?<\/skill>\n{0,2}/g,`
3
+
4
+ `).replace(/[ \t]*<skill>\s*[\s\S]*?<\/skill>\s*/g,e=>Y.test(e)?``:e)}function ve(e){let t=e;for(let e of[K,q])t=t.split(e).join(``);return t.replace(/^(?:[ \t]*\r?\n)+/,``)}function ye(e,t){let n=e;return t.inheritProjectContext||(n=he(n)),t.inheritSkills||(n=ge(n)),n=_e(n),n=ve(n),`${t.fanoutChild?q:K}${process.env.PI_SUBAGENT_STRUCTURED_OUTPUT_CAPTURE?`\n\n${G}`:``}\n\n${n}`}function be(e){let t=e;return t?.role!==`custom`||typeof t.customType!=`string`?!1:J.has(t.customType)}function xe(e){let t=e;return t?.role===`toolResult`&&t.toolName===`subagent`}function Se(e){let t=e;return t?.type===`toolCall`&&t.name===`subagent`}function Ce(e){let t=e;if(t?.role!==`assistant`||!Array.isArray(t.content))return e;let n=t.content.filter(e=>!Se(e));if(n.length===t.content.length)return e;if(n.length!==0)return{...t,content:n}}function we(e){let t=process.env[f]===`1`,n=!1,r=[];for(let i of e){if(be(i)||!t&&xe(i)){n=!0;continue}let e=t?i:Ce(i);if(e===void 0){n=!0;continue}e!==i&&(n=!0),r.push(e)}return n?r:e}function H(e){return[`Mid-run steering from the parent orchestrator:`,``,e.message,``,`Incorporate this guidance at the next safe point. Do not restart the task unless the guidance explicitly asks you to.`].join(`
5
+ `)}function U(e,t,n){let r=process.env[h]?.trim(),i=Number(process.env[d]);!r||!Number.isInteger(i)||i<0||w(C(r,e.id),{requestId:e.id,index:i,ts:Date.now(),state:t,message:n})}function Te(e,t,n){if(!t)return;let r=0,i=!1,a=e.sendUserMessage;P(e,`tool_call`,e=>{let o=typeof e.toolName==`string`?e.toolName:`tool`;if(r++,t.soft!==void 0&&r>=t.soft&&!i){i=!0;try{a?.(ae(t,r),{deliverAs:`steer`})}catch(e){n.steerNudgeFailures+=1,n.lastError=e}}if(ie(t,o,r))return{block:!0,reason:k(t,o,r)}})}function Ee(e,t={}){let r=t.diagnostics??N(),i=process.env[ee]?.trim();if(!i)return;let a=process.env[g]?.trim(),o=process.env[h]?.trim(),s=e.sendUserMessage,c=Number(process.env[d]),l=new Map,u=!1,f=!1,p=!1,m=typeof s==`function`,_,v,y=(e,t,n)=>{!o||!Number.isInteger(c)||c<0||w(C(o,e.id),{requestId:e.id,index:c,ts:Date.now(),state:t,message:n})},b=()=>{!a||!Number.isInteger(c)||c<0||te(a,{index:c,pid:process.pid,readyAt:Date.now(),supported:m})},S=()=>{if(!(u||f)){f=!0;try{for(let e of x(i)){if(!m||typeof s!=`function`){y(e.request,`failed`,`Child Pi session does not support sendUserMessage steering.`),e.commit();continue}let t=H(e.request),n=l.get(t)??[];n.push(e.request.id),l.set(t,n);try{s(t,{deliverAs:`steer`}),e.commit()}catch(r){n.pop(),n.length===0&&l.delete(t),e.release(),y(e.request,`failed`,r instanceof Error?r.message:String(r))}}}finally{f=!1}}},T=e=>{if(u||!e||typeof e!=`object`)return;let t=e;if(t.source!==`extension`||t.streamingBehavior!==`steer`)return;let n=typeof t.text==`string`?t.text:typeof t.content==`string`?t.content:void 0;if(!n)return;let r=l.get(n),i=r?.shift();i&&(r?.length===0&&l.delete(n),y({type:`steer`,id:i,ts:Date.now(),message:n},`delivered`,`Pi accepted the correlated steering input.`))},E=()=>{if(!(p||u)){try{j.mkdirSync(i,{recursive:!0}),b()}catch{return}p=!0;try{_=(t.watch??j.watch)(n(i,t.nativeRealpath),()=>S()),_.on(`error`,e=>{r.watchErrors+=1,r.lastError=e})}catch{_=void 0}v=setInterval(S,W),v.unref?.()}},D=()=>{E(),S()};P(e,`input`,T),P(e,`session_start`,()=>E());for(let t of[`message_start`,`message_update`,`message_end`,`tool_execution_start`,`tool_execution_end`,`turn_end`])P(e,t,D);P(e,`session_shutdown`,()=>{u=!0;try{_?.close()}catch(e){r.watchCloseFailures+=1,r.lastError=e}v&&clearInterval(v)})}function De(e,t=N()){T(),Ee(e,{diagnostics:t}),Te(e,ne(process.env[_],{allowZero:process.env[v]===`1`}),t);let n=A();L(e,n);let r=n.get(b.NativeTeamChannelService);P(e,`session_start`,()=>{r.createRuntime(e).bindChildFromEnvironment()}),P(e,`agent_start`,()=>{me(e)});let o=process.env[c],s=process.env[l];if(o&&s){let t=JSON.parse(j.readFileSync(s,`utf-8`)),n=ue(t),r=new le;e.registerTool.bind(e)({name:`structured_output`,label:`Structured Output`,description:`Submit the required final structured output for this subagent step. This terminates the step.`,parameters:n,async execute(e,n){let i=await r.validateValue(t,n.value);if(i.status===`invalid`)throw Error(`Structured output validation failed: ${i.message}`);return j.mkdirSync(M.dirname(o),{recursive:!0}),j.writeFileSync(o,JSON.stringify(n.value),{mode:384}),{content:[{type:`text`,text:`Structured output captured.`}],details:{path:o},terminate:!0}}})}P(e,`context`,e=>{let t=we(e.messages);if(t!==e.messages)return{messages:t}}),P(e,`before_agent_start`,async t=>{let n=process.env[p]?.trim();n&&typeof e.setSessionName==`function`&&e.setSessionName(n);let r=R(i),o=R(a),s=R(f),c=t.systemPrompt;if((r!==void 0||o!==void 0||s!==void 0)&&(c=ye(t.systemPrompt,{inheritProjectContext:r??!0,inheritSkills:o??!0,fanoutChild:s===!0})),c!==t.systemPrompt)return{systemPrompt:c}})}var W,G,K,q,J,Y,X,Z,Q,$=e((()=>{oe(),y(),D(),t(),ce(),E(),S(),de(),fe(),re(),W=250,G=[`This subagent step has a strict structured output contract.`,"Your final action must be to call the `structured_output` tool with JSON matching the provided schema.","Do not rely on prose-only completion; if you do not call `structured_output`, the parent will fail this step."].join(`
6
+ `),K=[`You are a child subagent, not the parent orchestrator.`,`The parent session owns delegation, orchestration, review fanout, and follow-up worker launches.`,`Ignore prior parent-only orchestration instructions in inherited conversation history.`,`Do not propose or run subagents. Complete only your assigned role-specific task with the tools available to you.`,`If you need to edit files, use the available editing tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.`].join(`
7
+ `),q=[`You are a child subagent with explicit fanout responsibility for this assigned task.`,`The parent session owns final orchestration, acceptance, and follow-up implementation launches.`,"You may use the `subagent` tool only for the fanout work explicitly requested in this task.",`Do not broaden yourself into general parent orchestration. Do not launch follow-up workers unless the task explicitly asks for that.`,`The maxSubagentDepth cap still applies and may block further fanout.`,`If you need to edit files, use the available editing tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.`].join(`
8
+ `),J=new Set([`subagent-orchestration-instructions`,`subagent-slash-result`,`subagent-slash-text-result`,`subagent-notify`,`subagent_control_notice`,`subagent-control`,`subagent-control-notice`]),Y=/<name>\s*pi-subagents\s*<\/name>/,X=`
9
+
10
+ # Project Context
11
+
12
+ Project-specific instructions and guidelines:
13
+
14
+ `,Z=`
15
+
16
+ The following skills provide specialized instructions for specific tasks.`,Q=`
17
+ Current date:`}));$();export{$ as init_subagentPromptRuntime,De as registerSubagentPromptRuntime};
18
+ //# sourceMappingURL=subagentPromptRuntime.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subagentPromptRuntime.mjs","names":[],"sources":["../../src/extensions/subagentPromptRuntime.ts"],"sourcesContent":["/**\n * The extension loaded INSIDE every spawned child: prompt rewriting,\n * mid-run steering delivery, the tool-call budget, native supervisor/team\n * messaging, and the `structured_output` tool.\n *\n * WHY THIS RUNS IN A DIFFERENT WORLD THAN EVERYTHING ELSE PORTED SO FAR:\n * Every other module in this package runs in the parent or the runner\n * process. This one is loaded BY the child's own Pi process\n * (`piArgs.ts`'s `resolveRuntimeExtensionPath` resolves it onto the\n * child's `--extension` args). The child's stdout IS its captured\n * transcript - a stray console write here does not go to a developer's\n * terminal, it becomes part of the child's output. Nothing in this file\n * writes to the console, ever; a failure that would have been\n * logged elsewhere is swallowed with a comment when there is no safe channel\n * to report it.\n *\n * FIX (claim-by-rename for the per-child steer inbox):\n * The predecessor's `registerSteeringInbox` called\n * `consumeSteerRequestsFromDir`, which deletes every queued request before\n * attempting delivery, then manually re-queued whatever it had not yet\n * attempted (`requests.slice(index + 1)`) if `sendUserMessage` threw\n * partway through a batch - but the request that was actually attempted\n * when the throw happened was already gone, lost the same way FIX 1 in\n * `control-channel.ts` was written to close for the runner-side steer\n * queue. This module's `flush()` uses `claimSteerRequestsFromDir` (already\n * exported from `control-channel.ts`, directory-agnostic) instead: each\n * request is claimed individually, and a failed `sendUserMessage` call\n * calls `release()` on that one claim so it is retried on the next flush,\n * while every OTHER claim in the same batch is still committed or released\n * independently. That is also a behavioural improvement over the\n * predecessor's `break`-on-first-failure, which abandoned the rest of a\n * batch rather than giving each message its own outcome - the same\n * per-item independence `ControlChannelWatcher.check()` already applies on\n * the runner side.\n *\n * Child runtimes keep the native team transport for lifecycle and result\n * delivery, but model-visible coordination tools are filtered by the selected\n * layer policy. They never register the root orchestration tool or a separate\n * wait alias.\n *\n * AVOID:\n * - Writing to the console. See the header above\n * - Reintroducing the predecessor's \"delete the whole batch, dispatch,\n * re-queue what failed\" shape for the steer inbox. See the FIX above\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { Container } from 'inversify';\nimport type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\n\nimport { createPromptRuntimeContainer, DOOM_TEAM_TYPES } from '../container/index.ts';\nimport {\n CHILD_TOOL_DIAGNOSTIC_PATH_ENV,\n INHERIT_PROJECT_CONTEXT_ENV,\n INHERIT_SKILLS_ENV,\n MCP_DIRECT_CHILD_TOOLS_ENV,\n REQUIRED_CHILD_TOOLS_ENV,\n STRUCTURED_OUTPUT_CAPTURE_ENV,\n STRUCTURED_OUTPUT_SCHEMA_ENV,\n SUBAGENT_CHILD_AGENT_ENV,\n SUBAGENT_CHILD_INDEX_ENV,\n SUBAGENT_FANOUT_CHILD_ENV,\n SUBAGENT_INTERCOM_SESSION_NAME_ENV,\n SUBAGENT_RUN_ID_ENV,\n SUBAGENT_STEER_ACK_DIR_ENV,\n SUBAGENT_STEER_CAPABILITY_ENV,\n SUBAGENT_STEER_INBOX_ENV,\n TOOL_BUDGET_ENV,\n TOOL_BUDGET_ZERO_AUTH_ENV,\n} from '../env.ts';\nimport {\n type INativeTeamChannelService,\n NATIVE_TEAM_TOOL_NAME,\n nativeTeamMemberEnvironment,\n type TeamMemberContext,\n} from '../intercom/nativeTeamChannel.ts';\nimport { resolveWatchPath } from '../shared/configDir.ts';\nimport { getMessageUsageTokens, type ChildTranscriptMessage } from '../shared/childTranscript.ts';\nimport { adoptSessionScopeFromEnv } from '../shared/paths.ts';\nimport type { JsonSchemaObject } from '../types.ts';\nimport {\n claimSteerRequestsFromDir,\n steerAckPathFromDir,\n writeSteerAckAt,\n writeSteerCapabilityAt,\n type SteerRequest,\n} from '../intercom/supervisorControlChannel.ts';\nimport type { IPollScheduler } from '../shared/pollScheduler.ts';\nimport type { IRunnerBootstrap } from '../runs/background/runnerBootstrap.ts';\nimport type { IRunnerExecution } from '../runs/background/runnerExecution.ts';\nimport type { IRunnerReporting } from '../runs/background/runnerReporting.ts';\nimport { createStructuredOutputToolParameters, StructuredOutputValidator } from '../runs/shared/structuredOutput.ts';\nimport { writeChildToolDiagnostic, type ChildToolDiagnostic } from '../runs/shared/toolAvailability.ts';\nimport {\n decodeToolBudgetEnv,\n shouldBlockToolForBudget,\n toolBudgetBlockedMessage,\n toolBudgetSoftNudge,\n} from '../runs/shared/toolBudget.ts';\nimport type { ResolvedToolBudget } from '../runs/shared/toolBudget.ts';\n\nconst STEER_FLUSH_POLL_INTERVAL_MS = 250;\n\n/**\n * Failures this runtime absorbed rather than propagated.\n *\n * WHY RECORD RATHER THAN LOG:\n * This module runs inside the spawned child, where stdout IS the child's\n * captured transcript. Writing a diagnostic there would corrupt the very\n * output the run exists to produce, so nothing here may reach stdio. But a\n * discarded error is indistinguishable from one that never happened, and a\n * watcher that fails on every event looks exactly like a quiet inbox. These\n * counters are the compromise: cheap, bounded, and queryable by a caller that\n * wants to know whether the child's steering path was actually healthy.\n *\n * WHY THIS IS CALLER-OWNED, NOT MODULE STATE:\n * A module-level singleton here would be exactly the bug this package's \"no\n * module-level mutable state\" rule exists to prevent - see\n * `nativeTeamChannel.ts`'s header: \"a second session in the same process\n * cannot inherit the first one's [state]\". `registerSubagentPromptRuntime`\n * runs once per real child process, so a singleton would rarely matter in\n * production, but every test in this file registers multiple independent\n * runtimes in one process, and a shared singleton would leak counts between\n * them silently. `createPromptRuntimeDiagnostics()` hands each registration\n * its own object instead; the caller keeps the reference to read later, and\n * a fresh registration is what \"reset\" means - there is no shared state left\n * to reset.\n *\n * AVOID:\n * - Adding a `console.*` here, on any path, for any reason\n * - Treating a non-zero count as fatal; every one of these is a degraded-mode\n * path with a working fallback, which is why it was absorbed in the first place\n * - Reintroducing a module-level instance of this. See the header above\n */\nexport interface PromptRuntimeDiagnostics {\n /** Advisory tool-budget nudges that could not be delivered to the child. */\n steerNudgeFailures: number;\n /** Errors emitted by the steer-inbox watcher. The interval poll covers these. */\n watchErrors: number;\n /** Failures closing the watcher during shutdown. */\n watchCloseFailures: number;\n /** The most recent absorbed failure, whichever kind it was. */\n lastError?: unknown;\n}\n\n/** A fresh, zeroed diagnostics object for one registration. See the interface doc for why this is not a singleton. */\nexport function createPromptRuntimeDiagnostics(): PromptRuntimeDiagnostics {\n return { steerNudgeFailures: 0, watchErrors: 0, watchCloseFailures: 0 };\n}\n\nconst STRUCTURED_OUTPUT_INSTRUCTIONS = [\n 'This subagent step has a strict structured output contract.',\n 'Your final action must be to call the `structured_output` tool with JSON matching the provided schema.',\n 'Do not rely on prose-only completion; if you do not call `structured_output`, the parent will fail this step.',\n].join('\\n');\n\nexport const CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS = [\n 'You are a child subagent, not the parent orchestrator.',\n 'The parent session owns delegation, orchestration, review fanout, and follow-up worker launches.',\n 'Ignore prior parent-only orchestration instructions in inherited conversation history.',\n 'Do not propose or run subagents. Complete only your assigned role-specific task with the tools available to you.',\n 'If you need to edit files, use the available editing tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.',\n].join('\\n');\n\nexport const CHILD_FANOUT_BOUNDARY_INSTRUCTIONS = [\n 'You are a child subagent with explicit fanout responsibility for this assigned task.',\n 'The parent session owns final orchestration, acceptance, and follow-up implementation launches.',\n 'You may use the `subagent` tool only for the fanout work explicitly requested in this task.',\n 'Do not broaden yourself into general parent orchestration. Do not launch follow-up workers unless the task explicitly asks for that.',\n 'The maxSubagentDepth cap still applies and may block further fanout.',\n 'If you need to edit files, use the available editing tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.',\n].join('\\n');\n\n/**\n * `pi.on` typed loosely: the extension API's event payloads are not typed\n * per event name, so every call site narrows its own handler's parameter.\n * `.call(pi, ...)` binds `this` explicitly rather than extracting `pi.on` as\n * a bare reference, which is what an unbound method call would otherwise risk.\n *\n * The handler is given `ctx: ExtensionContext` as a second parameter,\n * matching the real `pi.on` signature (`ExtensionHandler<E, R> = (event: E,\n * ctx: ExtensionContext) => ...`) even though most registrations here never\n * read it - existing single-parameter handlers stay valid without change\n * (JS ignores a callback's unused trailing parameters), and the one call\n * site that DOES need it (`session_start`, for `ctx.sessionManager` - see\n * `registerDeliverableGuardCheck`'s doc) no longer has to reach past this\n * wrapper to get it.\n */\nfunction onEvent<E = unknown>(\n pi: ExtensionAPI,\n event: string,\n handler: (event: E, ctx: ExtensionContext) => unknown,\n): void {\n (pi.on as unknown as (event: string, handler: (event: E, ctx: ExtensionContext) => unknown) => void).call(\n pi,\n event,\n handler,\n );\n}\n\n/** A text block from an assistant message's content array. Narrowed structurally, not imported from `@earendil-works/pi-ai`, matching this file's habit of ad-hoc event-payload types (see `onEvent`'s own doc). */\ninterface AssistantTextBlock {\n type: 'text';\n text: string;\n}\n\n/** The subset of `AgentEndEvent`/message shape this file actually reads. */\ninterface DeliverableCheckMessage {\n role?: string;\n content?: unknown;\n}\n\nfunction isAssistantTextBlock(block: unknown): block is AssistantTextBlock {\n return (\n typeof block === 'object' &&\n block !== null &&\n (block as { type?: unknown }).type === 'text' &&\n typeof (block as { text?: unknown }).text === 'string'\n );\n}\n\n/**\n * The last non-empty assistant text found in `messages`, or `''`.\n *\n * `DeliverableGuardInput.summary` is checked for the `'summary'`-kind\n * expectation, and nothing in this package tracks a run's summary text\n * per-turn - `RunnerReporting` only computes one at the terminal\n * `mutateTerminalStatus` callback, which has not happened yet when a\n * mid-run deliverable check needs to run. The assistant's own most recent\n * text output is the best available proxy for \"what would this run's\n * summary be if it stopped now\" without a dedicated tracking mechanism this\n * package does not have yet. Best-effort by construction: an unparseable or\n * missing message reads as an empty summary, which is the SAFE failure\n * direction for this guard (nudging once more than strictly necessary,\n * never fewer times than necessary).\n */\nexport function extractAssistantSummaryText(messages: readonly DeliverableCheckMessage[]): string {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index];\n if (message?.role !== 'assistant' || !Array.isArray(message.content)) continue;\n const text = message.content\n .filter(isAssistantTextBlock)\n .map((block) => block.text)\n .join('\\n')\n .trim();\n if (text) return text;\n }\n return '';\n}\n\n/**\n * Wires `DeliverableGuard`'s write side into this process. See the module\n * doc's overall framing: everything else in the missing-deliverable chain\n * (detection, the single nudge, escalation, the fold into `status.json`,\n * `AsyncJobTracker`'s read and folded wait action already exist;\n * nothing called it. This is that call.\n *\n * WHY THIS RESOLVES ITS OWN CONTAINER, HERE:\n * `RunnerBootstrap`/`RunnerExecution`/`DeliverableGuard` are DI-bound\n * services (`container/modules/runs.ts`), and this file is the one place\n * `container/index.ts` documents as the in-child composition root\n * (`createPromptRuntimeContainer()`) - filed under `src/extensions/**`, the\n * boundary reserved for composition roots (see `vibe-lint.config.yaml`'s\n * `extensions` boundary), not under `src/runs/**` where it used to live. It\n * was moved here specifically so it could stop being the one exception\n * carved into the `runs` boundary's allowlist for `src/container/index.ts` -\n * a domain that can build its own container can bypass every composition\n * decision above it, and that hole is now closed rather than merely\n * documented. `container` is an optional parameter, defaulting to the real\n * container, purely so a test can supply one pre-loaded with fakes via\n * `container.rebind(...)` instead of standing up the real filesystem-backed\n * services.\n *\n * WHY `session_start` BOOTSTRAPS, AND WHY IT ONLY EVER RUNS ONCE:\n * `RunnerBootstrap.bootstrap()` is genuinely the FIRST real caller this\n * package has ever had for it - it opens `status.json`, wires\n * `TerminalPersistenceService`'s finalize callback, and writes the startup\n * handshake `SpawnHandshake.waitForHandshake()` on the parent side blocks\n * on. `RunnerExecution.start()` then begins watching the control inbox.\n * `ControlChannelWatcher` depends on `PollScheduler`\n * (`control-channel.ts:809`), which nothing in this package's runner\n * services ever calls `.start()` on by itself (see `pollScheduler.ts`'s own\n * AVOID note: \"a registered-but-unstarted PollScheduler never ticks\") - so\n * this starts it explicitly, once, alongside bootstrap. The `resolved` guard\n * makes a stray second `session_start` (nothing in this file's other\n * registrations assumes it fires only once) a no-op rather than a second\n * bootstrap of the same run.\n *\n * WHY `execution.start()` IS GIVEN AN `onSteer` HANDLER:\n * `DeliverableGuard.deliverNudge()` drops a nudge into this run's OWN\n * steer-requests queue via `requestAsyncSteer` (see that method's doc) and\n * calls it delivered once the write succeeds. But the write alone does not\n * reach the child: `ControlChannelWatcher`, wired up by `execution.start()`,\n * claims and commits (deletes) every request it finds in that queue whether\n * or not a handler is registered for it - found by testing this file\n * against the REAL `ControlChannelWatcher` rather than a fake with no side\n * effects, which is exactly the failure mode this task kept turning up\n * elsewhere (`createRunsModule()` never loaded into any root;\n * `PollScheduler.start()` never called). `onSteer` is the missing delivery\n * half: it reuses `formatSteerMessage`/`sendUserMessage`, the same\n * mechanism `registerSteeringInbox` already uses for its own, separate\n * steer queue, so a nudge actually lands in the child's conversation instead\n * of being silently claimed and discarded.\n *\n * WHY `agent_end`, NOT `turn_end`:\n * `agent_end`'s own event (`AgentEndEvent.messages`) carries the full\n * message history for this agent loop, which `extractAssistantSummaryText`\n * reads from - `turn_end` only carries the one message that ended that turn,\n * not the memory of what preceded it, and `DeliverableGuard`'s own doc\n * frames this check as \"end-of-turn or idle\", not \"every turn.\"\n *\n * `unansweredAsks` AND `memberId`:\n * Both come from this run's own bound `TeamMemberContext`, which\n * `RunnerBootstrap.bootstrap()` already holds (from registering as a team\n * member) and now returns on its result. `memberId` is `teamContext.memberId`\n * directly. `unansweredAsks` calls `pendingAsksAddressedTo(teamContext,\n * teamContext.memberId, now)` - see `deliverable-guard.ts`'s own AVOID\n * section for why `DeliverableGuard` cannot call that itself, and that\n * function's own doc for why it deliberately returns id/sender/time only,\n * never the question's text (this maps its result into a factual, non-\n * fabricated placeholder message rather than guessing at content it was\n * never given). A standalone run with no team root forwarded has no\n * `teamContext` at all, in which case both are simply omitted - narrower\n * than the real behaviour, never wider, matching every other gap in this\n * file when there is genuinely nothing to report rather than something\n * unknown to guess at.\n *\n * `session_start` ALSO RECORDS THIS RUN'S OWN SESSION FILE:\n * `ctx.sessionManager.getSessionFile()` is the only place in this process\n * that ever answers \"what is my own transcript path\" - see\n * `runnerReporting.ts`'s header for why the value has to come from here\n * (the child) rather than be derived by the parent. `RunnerReporting`\n * validates and retains it while `RunnerBootstrap` writes it before the\n * ready handshake. `getSessionFile()` can return `undefined` (no persisted\n * transcript for this run); that case is simply not recorded, the same\n * \"omit rather than guess\" shape as `unansweredAsks`/`teamContext` above.\n */\nexport function registerRunnerLifecycle(pi: ExtensionAPI, container: Container = createPromptRuntimeContainer()): void {\n const runId = process.env[SUBAGENT_RUN_ID_ENV]?.trim();\n if (!runId) return;\n\n const pollScheduler = container.get<IPollScheduler>(DOOM_TEAM_TYPES.PollScheduler);\n const bootstrap = container.get<IRunnerBootstrap>(DOOM_TEAM_TYPES.RunnerBootstrap);\n const execution = container.get<IRunnerExecution>(DOOM_TEAM_TYPES.RunnerExecution);\n const reporting = container.get<IRunnerReporting>(DOOM_TEAM_TYPES.RunnerReporting);\n\n let resolved: { teamContext: TeamMemberContext | undefined } | undefined;\n let cumulativeTokens: number | undefined;\n let toolCount = 0;\n const countedMessages = new WeakSet<object>();\n\n onEvent(pi, 'session_start', (_event, ctx) => {\n if (resolved) return;\n pollScheduler.start();\n const sessionFile = ctx.sessionManager.getSessionFile();\n const recordedSessionFile = sessionFile ? reporting.recordSessionFile(sessionFile) : undefined;\n const bootstrapped = bootstrap.bootstrap(runId, recordedSessionFile);\n if (bootstrapped.teamContext) Object.assign(process.env, nativeTeamMemberEnvironment(bootstrapped.teamContext));\n // `onSteer` is the delivery half of `DeliverableGuard.deliverNudge`'s\n // write side (see `RunnerExecutionHandlers.onSteer`'s own doc, which\n // cross-references it): `deliverNudge` drops a request into this run's\n // OWN steer-requests queue via `requestAsyncSteer`, and\n // `ControlChannelWatcher` (wired up by `execution.start()` below) claims\n // it and calls this handler. Without it, `execution.start()` still\n // claims and commits the nudge - `deliverNudge` reports\n // `nudgeDelivered: true`, `status.json` still shows `needs_attention` -\n // but the request is silently discarded before it ever reaches the\n // child's own conversation. `formatSteerMessage`/`sendUserMessage` are\n // the exact same delivery this file already uses for\n // `registerSteeringInbox`'s separate queue.\n execution.start(runId, {\n onSteer: (request) => {\n const sendUserMessage = (\n pi as { sendUserMessage?: (content: string, options: { deliverAs: 'steer' }) => unknown }\n ).sendUserMessage;\n if (!sendUserMessage) {\n acknowledgeRunnerSteer(request, 'failed', 'Child Pi session does not support sendUserMessage steering.');\n return;\n }\n try {\n sendUserMessage(formatSteerMessage(request), { deliverAs: 'steer' });\n acknowledgeRunnerSteer(request, 'delivered', 'Pi accepted the correlated steering input.');\n } catch (error) {\n acknowledgeRunnerSteer(request, 'failed', error instanceof Error ? error.message : String(error));\n throw error;\n }\n },\n });\n resolved = { teamContext: bootstrapped.teamContext };\n execution.setActivity('working');\n });\n\n onEvent(pi, 'agent_start', () => {\n if (resolved) execution.setActivity('working');\n });\n onEvent<{ message?: ChildTranscriptMessage }>(pi, 'message_end', (event) => {\n if (!resolved || !event.message || typeof event.message !== 'object') return;\n if (countedMessages.has(event.message)) return;\n countedMessages.add(event.message);\n const messageTokens = getMessageUsageTokens(event.message);\n if (messageTokens === undefined) return;\n cumulativeTokens = (cumulativeTokens ?? 0) + messageTokens;\n execution.setProgress({ tokens: cumulativeTokens });\n });\n onEvent<{ toolName?: string; tool?: { name?: string }; args?: { action?: string } }>(\n pi,\n 'tool_execution_start',\n (event) => {\n if (!resolved) return;\n const toolName = event.toolName ?? event.tool?.name;\n toolCount += 1;\n execution.setProgress({\n toolCount,\n ...(typeof toolName === 'string' && toolName.length > 0 ? { currentTool: toolName } : {}),\n });\n execution.setActivity(\n toolName === NATIVE_TEAM_TOOL_NAME && event.args?.action === 'ask' ? 'waiting_for_reply' : 'tool',\n );\n },\n );\n onEvent(pi, 'tool_execution_end', () => {\n if (resolved) execution.setActivity('working');\n });\n onEvent<{ messages: DeliverableCheckMessage[] }>(pi, 'agent_end', (event) => {\n if (!resolved) return; // session_start has not bootstrapped yet; nothing to report against.\n execution.setActivity('finalizing');\n const summary = extractAssistantSummaryText(event.messages);\n execution.complete(true, summary);\n });\n}\n\nconst PARENT_ONLY_CUSTOM_MESSAGE_TYPES = new Set([\n 'subagent-orchestration-instructions',\n 'subagent-slash-result',\n 'subagent-slash-text-result',\n 'subagent-notify',\n 'subagent_control_notice',\n 'subagent-control',\n 'subagent-control-notice',\n]);\nconst SUBAGENT_ORCHESTRATION_SKILL_NAME_PATTERN = /<name>\\s*pi-subagents\\s*<\\/name>/;\nconst PROJECT_CONTEXT_HEADER = '\\n\\n# Project Context\\n\\nProject-specific instructions and guidelines:\\n\\n';\nconst SKILLS_HEADER = '\\n\\nThe following skills provide specialized instructions for specific tasks.';\nconst DATE_HEADER = '\\nCurrent date:';\n\nfunction readBooleanEnv(name: string): boolean | undefined {\n const value = process.env[name];\n if (value === undefined) return undefined;\n return value !== '0';\n}\n\nfunction readRequiredChildTools(): string[] | undefined {\n const encoded = process.env[REQUIRED_CHILD_TOOLS_ENV]?.trim();\n if (!encoded) return undefined;\n const required = JSON.parse(encoded) as unknown;\n if (!Array.isArray(required) || required.some((name) => typeof name !== 'string' || !name)) {\n throw new Error(`Invalid ${REQUIRED_CHILD_TOOLS_ENV} payload.`);\n }\n return required;\n}\n\nfunction readMcpDirectChildTools(): string[] | undefined {\n const encoded = process.env[MCP_DIRECT_CHILD_TOOLS_ENV]?.trim();\n if (!encoded) return undefined;\n try {\n const tools = JSON.parse(encoded) as unknown;\n if (!Array.isArray(tools) || tools.some((name) => typeof name !== 'string' || !name)) return undefined;\n return tools;\n } catch {\n return undefined;\n }\n}\n\nfunction refreshChildToolDiagnostic(pi: ExtensionAPI): ChildToolDiagnostic | undefined {\n const filePath = process.env[CHILD_TOOL_DIAGNOSTIC_PATH_ENV]?.trim();\n const required = readRequiredChildTools();\n if (!filePath || !required) return undefined;\n const available = pi.getAllTools().map((tool) => tool.name);\n return writeChildToolDiagnostic(\n filePath,\n required,\n available,\n process.env[SUBAGENT_CHILD_AGENT_ENV]?.trim(),\n readMcpDirectChildTools(),\n );\n}\n\nfunction findSectionEnd(prompt: string, startIndex: number, nextHeaders: string[]): number {\n let endIndex = prompt.length;\n for (const header of nextHeaders) {\n const index = prompt.indexOf(header, startIndex);\n if (index !== -1 && index < endIndex) {\n endIndex = index;\n }\n }\n return endIndex;\n}\n\nexport function stripProjectContext(prompt: string): string {\n const startIndex = prompt.indexOf(PROJECT_CONTEXT_HEADER);\n if (startIndex === -1) return prompt;\n const endIndex = findSectionEnd(prompt, startIndex + PROJECT_CONTEXT_HEADER.length, [SKILLS_HEADER, DATE_HEADER]);\n return `${prompt.slice(0, startIndex)}${prompt.slice(endIndex)}`;\n}\n\nexport function stripInheritedSkills(prompt: string): string {\n const startIndex = prompt.indexOf(SKILLS_HEADER);\n if (startIndex === -1) return prompt;\n const endIndex = findSectionEnd(prompt, startIndex + SKILLS_HEADER.length, [DATE_HEADER]);\n return `${prompt.slice(0, startIndex)}${prompt.slice(endIndex)}`;\n}\n\nexport function stripSubagentOrchestrationSkill(prompt: string): string {\n return prompt\n .replace(/\\n{0,2}<skill\\s+name=[\"']pi-subagents[\"'][^>]*>[\\s\\S]*?<\\/skill>\\n{0,2}/g, '\\n\\n')\n .replace(/[ \\t]*<skill>\\s*[\\s\\S]*?<\\/skill>\\s*/g, (block) =>\n SUBAGENT_ORCHESTRATION_SKILL_NAME_PATTERN.test(block) ? '' : block,\n );\n}\n\nfunction stripChildBoundaryInstructions(prompt: string): string {\n let rewritten = prompt;\n for (const boundary of [CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS, CHILD_FANOUT_BOUNDARY_INSTRUCTIONS]) {\n rewritten = rewritten.split(boundary).join('');\n }\n return rewritten.replace(/^(?:[ \\t]*\\r?\\n)+/, '');\n}\n\nexport function rewriteSubagentPrompt(\n prompt: string,\n options: { inheritProjectContext: boolean; inheritSkills: boolean; fanoutChild?: boolean },\n): string {\n let rewritten = prompt;\n if (!options.inheritProjectContext) {\n rewritten = stripProjectContext(rewritten);\n }\n if (!options.inheritSkills) {\n rewritten = stripInheritedSkills(rewritten);\n }\n rewritten = stripSubagentOrchestrationSkill(rewritten);\n rewritten = stripChildBoundaryInstructions(rewritten);\n const boundary = options.fanoutChild ? CHILD_FANOUT_BOUNDARY_INSTRUCTIONS : CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS;\n const structured = process.env[STRUCTURED_OUTPUT_CAPTURE_ENV] ? `\\n\\n${STRUCTURED_OUTPUT_INSTRUCTIONS}` : '';\n return `${boundary}${structured}\\n\\n${rewritten}`;\n}\n\nfunction isParentOnlySubagentMessage(message: unknown): boolean {\n const m = message as { role?: string; customType?: string };\n if (m?.role !== 'custom' || typeof m.customType !== 'string') return false;\n return PARENT_ONLY_CUSTOM_MESSAGE_TYPES.has(m.customType);\n}\n\nfunction isSubagentToolResultMessage(message: unknown): boolean {\n const m = message as { role?: string; toolName?: string };\n return m?.role === 'toolResult' && m.toolName === 'subagent';\n}\n\nfunction isSubagentToolCallBlock(block: unknown): boolean {\n const b = block as { type?: string; name?: string };\n return b?.type === 'toolCall' && b.name === 'subagent';\n}\n\nfunction stripAssistantSubagentToolCallBlocks(message: unknown): unknown {\n const m = message as { role?: string; content?: unknown };\n if (m?.role !== 'assistant' || !Array.isArray(m.content)) return message;\n const filteredContent = m.content.filter((block) => !isSubagentToolCallBlock(block));\n if (filteredContent.length === m.content.length) return message;\n if (filteredContent.length === 0) return undefined;\n return { ...m, content: filteredContent };\n}\n\nexport function stripParentOnlySubagentMessages(messages: unknown[]): unknown[] {\n const preserveCurrentFanoutToolHistory = process.env[SUBAGENT_FANOUT_CHILD_ENV] === '1';\n let changed = false;\n const filtered: unknown[] = [];\n for (const message of messages) {\n if (\n isParentOnlySubagentMessage(message) ||\n (!preserveCurrentFanoutToolHistory && isSubagentToolResultMessage(message))\n ) {\n changed = true;\n continue;\n }\n const stripped = preserveCurrentFanoutToolHistory ? message : stripAssistantSubagentToolCallBlocks(message);\n if (stripped === undefined) {\n changed = true;\n continue;\n }\n if (stripped !== message) changed = true;\n filtered.push(stripped);\n }\n return changed ? filtered : messages;\n}\n\nexport function formatSteerMessage(request: SteerRequest): string {\n return [\n 'Mid-run steering from the parent orchestrator:',\n '',\n request.message,\n '',\n 'Incorporate this guidance at the next safe point. Do not restart the task unless the guidance explicitly asks you to.',\n ].join('\\n');\n}\n\nfunction acknowledgeRunnerSteer(request: SteerRequest, state: 'delivered' | 'failed', message: string): void {\n const ackDir = process.env[SUBAGENT_STEER_ACK_DIR_ENV]?.trim();\n const childIndex = Number(process.env[SUBAGENT_CHILD_INDEX_ENV]);\n if (!ackDir || !Number.isInteger(childIndex) || childIndex < 0) return;\n writeSteerAckAt(steerAckPathFromDir(ackDir, request.id), {\n requestId: request.id,\n index: childIndex,\n ts: Date.now(),\n state,\n message,\n });\n}\n\nfunction registerToolBudget(\n pi: ExtensionAPI,\n budget: ResolvedToolBudget | undefined,\n diagnostics: PromptRuntimeDiagnostics,\n): void {\n if (!budget) return;\n let toolCount = 0;\n let softNudged = false;\n const sendUserMessage = (pi as { sendUserMessage?: (content: string, options: { deliverAs: 'steer' }) => unknown })\n .sendUserMessage;\n onEvent<{ toolName?: string }>(pi, 'tool_call', (event) => {\n const toolName = typeof event.toolName === 'string' ? event.toolName : 'tool';\n toolCount++;\n if (budget.soft !== undefined && toolCount >= budget.soft && !softNudged) {\n softNudged = true;\n try {\n sendUserMessage?.(toolBudgetSoftNudge(budget, toolCount), { deliverAs: 'steer' });\n } catch (error) {\n // Advisory nudge only; the child's own output is what matters. Recorded\n // rather than discarded so a host that never accepts steering is\n // discoverable instead of silently dropping every nudge.\n diagnostics.steerNudgeFailures += 1;\n diagnostics.lastError = error;\n }\n }\n if (!shouldBlockToolForBudget(budget, toolName, toolCount)) return undefined;\n return { block: true, reason: toolBudgetBlockedMessage(budget, toolName, toolCount) };\n });\n}\n\n/**\n * Deliver mid-run steer requests queued for THIS child (by fan-out index)\n * into its own session via `sendUserMessage`. See the module doc's FIX for\n * why this claims each request individually rather than batch-deleting.\n */\nexport function registerSteeringInbox(\n pi: ExtensionAPI,\n deps: {\n watch?: typeof fs.watch;\n nativeRealpath?: (filePath: string) => string;\n diagnostics?: PromptRuntimeDiagnostics;\n } = {},\n): void {\n const diagnostics = deps.diagnostics ?? createPromptRuntimeDiagnostics();\n const steerInbox = process.env[SUBAGENT_STEER_INBOX_ENV]?.trim();\n if (!steerInbox) return;\n const capabilityPath = process.env[SUBAGENT_STEER_CAPABILITY_ENV]?.trim();\n const ackDir = process.env[SUBAGENT_STEER_ACK_DIR_ENV]?.trim();\n const sendUserMessage = (pi as { sendUserMessage?: (content: string, options: { deliverAs: 'steer' }) => unknown })\n .sendUserMessage;\n const childIndex = Number(process.env[SUBAGENT_CHILD_INDEX_ENV]);\n const pending = new Map<string, string[]>();\n let disposed = false;\n let flushing = false;\n let started = false;\n const canSteer = typeof sendUserMessage === 'function';\n let watcher: fs.FSWatcher | undefined;\n let interval: NodeJS.Timeout | undefined;\n\n const acknowledge = (request: SteerRequest, state: 'delivered' | 'failed', message: string): void => {\n if (!ackDir || !Number.isInteger(childIndex) || childIndex < 0) return;\n writeSteerAckAt(steerAckPathFromDir(ackDir, request.id), {\n requestId: request.id,\n index: childIndex,\n ts: Date.now(),\n state,\n message,\n });\n };\n const publishCapability = (): void => {\n if (!capabilityPath || !Number.isInteger(childIndex) || childIndex < 0) return;\n writeSteerCapabilityAt(capabilityPath, {\n index: childIndex,\n pid: process.pid,\n readyAt: Date.now(),\n supported: canSteer,\n });\n };\n\n const flush = (): void => {\n if (disposed || flushing) return;\n flushing = true;\n try {\n for (const claim of claimSteerRequestsFromDir(steerInbox)) {\n if (!canSteer || typeof sendUserMessage !== 'function') {\n acknowledge(claim.request, 'failed', 'Child Pi session does not support sendUserMessage steering.');\n claim.commit();\n continue;\n }\n const formatted = formatSteerMessage(claim.request);\n const ids = pending.get(formatted) ?? [];\n ids.push(claim.request.id);\n pending.set(formatted, ids);\n try {\n sendUserMessage(formatted, { deliverAs: 'steer' });\n claim.commit();\n } catch (error) {\n ids.pop();\n if (ids.length === 0) pending.delete(formatted);\n // Recoverable: this claim goes back to the queue for the next\n // flush to retry, instead of being lost. See the module doc's FIX.\n claim.release();\n acknowledge(claim.request, 'failed', error instanceof Error ? error.message : String(error));\n }\n }\n } finally {\n flushing = false;\n }\n };\n const onInput = (event: unknown): undefined => {\n if (disposed || !event || typeof event !== 'object') return undefined;\n const input = event as { source?: unknown; streamingBehavior?: unknown; text?: unknown; content?: unknown };\n if (input.source !== 'extension' || input.streamingBehavior !== 'steer') return undefined;\n const text =\n typeof input.text === 'string' ? input.text : typeof input.content === 'string' ? input.content : undefined;\n if (!text) return undefined;\n const ids = pending.get(text);\n const requestId = ids?.shift();\n if (!requestId) return undefined;\n if (ids?.length === 0) pending.delete(text);\n acknowledge(\n { type: 'steer', id: requestId, ts: Date.now(), message: text },\n 'delivered',\n 'Pi accepted the correlated steering input.',\n );\n return undefined;\n };\n const start = (): void => {\n if (started || disposed) return;\n try {\n fs.mkdirSync(steerInbox, { recursive: true });\n publishCapability();\n } catch {\n // No channel to report a startup failure on from inside the child;\n // the parent observes a missing capability file and treats it as\n // \"steering unsupported for this child\" on its own.\n return;\n }\n started = true;\n try {\n watcher = (deps.watch ?? fs.watch)(resolveWatchPath(steerInbox, deps.nativeRealpath), () => flush());\n watcher.on('error', (error) => {\n // fs.watch emits on transient FS errors and the interval poll below\n // keeps delivery live regardless, so this is not fatal. Recorded so a\n // watch that fails on every event is distinguishable from a quiet inbox.\n diagnostics.watchErrors += 1;\n diagnostics.lastError = error;\n });\n } catch {\n watcher = undefined;\n }\n interval = setInterval(flush, STEER_FLUSH_POLL_INTERVAL_MS);\n interval.unref?.();\n };\n const activate = (): undefined => {\n start();\n flush();\n return undefined;\n };\n\n // Register input before the watcher so an accepted extension input cannot race request dispatch.\n onEvent(pi, 'input', onInput);\n onEvent(pi, 'session_start', () => start());\n for (const eventName of [\n 'message_start',\n 'message_update',\n 'message_end',\n 'tool_execution_start',\n 'tool_execution_end',\n 'turn_end',\n ] as const) {\n onEvent(pi, eventName, activate);\n }\n onEvent(pi, 'session_shutdown', () => {\n disposed = true;\n try {\n watcher?.close();\n } catch (error) {\n // Best effort; the process is shutting down regardless. Still recorded,\n // because a close that always fails is a leaked descriptor per run.\n diagnostics.watchCloseFailures += 1;\n diagnostics.lastError = error;\n }\n if (interval) clearInterval(interval);\n });\n}\n\n/**\n * `diagnostics` is optional and defaults to a fresh object: the `.cts` entry\n * point calls this with a single argument (`pi`), matching the host contract\n * `resolveRuntimeExtensionPath` resolves onto every child's `--extension`\n * args, so that call keeps working unchanged. A caller that wants to observe\n * what this runtime absorbed - see `PromptRuntimeDiagnostics` - passes its\n * own object and keeps the reference; this function only ever mutates it, it\n * never owns or resets it.\n */\nexport function registerSubagentPromptRuntime(\n pi: ExtensionAPI,\n diagnostics: PromptRuntimeDiagnostics = createPromptRuntimeDiagnostics(),\n): void {\n // First, before any scoped path is touched. Pi loads extensions through jiti\n // with `moduleCache: false`, so this extension gets its OWN instance of\n // `shared/paths.ts` - the scope the surrounding runner process adopted is not\n // visible here, and has to be read from the environment again.\n adoptSessionScopeFromEnv();\n registerSteeringInbox(pi, { diagnostics });\n registerToolBudget(\n pi,\n decodeToolBudgetEnv(process.env[TOOL_BUDGET_ENV], { allowZero: process.env[TOOL_BUDGET_ZERO_AUTH_ENV] === '1' }),\n diagnostics,\n );\n // One container for this whole registration, not one built inside each\n // resolver's own default parameter: this process has exactly one\n // composition root (see container/index.ts and this function's own doc),\n // and a second independent createPromptRuntimeContainer() call anywhere\n // else in this function would silently mean two sets of \"singletons\" in\n // one process, defeating the point of a shared container.\n const container = createPromptRuntimeContainer();\n registerRunnerLifecycle(pi, container);\n\n const teamChannels = container.get<INativeTeamChannelService>(DOOM_TEAM_TYPES.NativeTeamChannelService);\n\n onEvent(pi, 'session_start', () => {\n const teamRuntime = teamChannels.createRuntime(pi);\n teamRuntime.bindChildFromEnvironment();\n });\n onEvent(pi, 'agent_start', () => {\n refreshChildToolDiagnostic(pi);\n });\n // `agent_end` intentionally does not drain outstanding work here. See the\n // module doc's \"WHAT IS DELIBERATELY NOT WIRED YET\" for why.\n\n const structuredOutputPath = process.env[STRUCTURED_OUTPUT_CAPTURE_ENV];\n const structuredSchemaPath = process.env[STRUCTURED_OUTPUT_SCHEMA_ENV];\n if (structuredOutputPath && structuredSchemaPath) {\n const schema = JSON.parse(fs.readFileSync(structuredSchemaPath, 'utf-8')) as JsonSchemaObject;\n const parameters = createStructuredOutputToolParameters(schema);\n const validator = new StructuredOutputValidator();\n const registerTool = (\n pi.registerTool as unknown as (tool: {\n name: string;\n label: string;\n description: string;\n parameters: unknown;\n execute: (_id: string, params: { value: unknown }) => Promise<unknown>;\n }) => void\n ).bind(pi);\n registerTool({\n name: 'structured_output',\n label: 'Structured Output',\n description: 'Submit the required final structured output for this subagent step. This terminates the step.',\n parameters: parameters as never,\n async execute(_id: string, params: { value: unknown }) {\n const validation = await validator.validateValue(schema, params.value);\n if (validation.status === 'invalid') {\n throw new Error(`Structured output validation failed: ${validation.message}`);\n }\n fs.mkdirSync(path.dirname(structuredOutputPath), { recursive: true });\n fs.writeFileSync(structuredOutputPath, JSON.stringify(params.value), { mode: 0o600 });\n return {\n content: [{ type: 'text', text: 'Structured output captured.' }],\n details: { path: structuredOutputPath },\n terminate: true,\n };\n },\n });\n }\n\n onEvent<{ messages: unknown[] }>(pi, 'context', (event) => {\n const messages = stripParentOnlySubagentMessages(event.messages);\n if (messages === event.messages) return undefined;\n return { messages };\n });\n\n onEvent<{ systemPrompt: string }>(pi, 'before_agent_start', async (event) => {\n const intercomSessionName = process.env[SUBAGENT_INTERCOM_SESSION_NAME_ENV]?.trim();\n if (intercomSessionName && typeof pi.setSessionName === 'function') {\n pi.setSessionName(intercomSessionName);\n }\n\n const inheritProjectContext = readBooleanEnv(INHERIT_PROJECT_CONTEXT_ENV);\n const inheritSkills = readBooleanEnv(INHERIT_SKILLS_ENV);\n const fanoutChild = readBooleanEnv(SUBAGENT_FANOUT_CHILD_ENV);\n let rewritten = event.systemPrompt;\n if (inheritProjectContext !== undefined || inheritSkills !== undefined || fanoutChild !== undefined) {\n rewritten = rewriteSubagentPrompt(event.systemPrompt, {\n inheritProjectContext: inheritProjectContext ?? true,\n inheritSkills: inheritSkills ?? true,\n fanoutChild: fanoutChild === true,\n });\n }\n if (rewritten === event.systemPrompt) return;\n return { systemPrompt: rewritten };\n });\n}\n"],"mappings":"oyDAmJA,SAAgB,GAA2D,CACzE,MAAO,CAAE,mBA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 +1,2 @@
1
+ const e=require(`./subagentPromptRuntime.cjs`);module.exports=e.registerSubagentPromptRuntime;
2
+ //# sourceMappingURL=subagentPromptRuntimeEntry.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subagentPromptRuntimeEntry.cjs","names":["registerSubagentPromptRuntime"],"sources":["../../src/extensions/subagentPromptRuntimeEntry.cts"],"sourcesContent":["import { registerSubagentPromptRuntime } from './subagentPromptRuntime.ts';\n\n// Pi's jiti loader imports extension factories through the CommonJS default interop path.\nexport = registerSubagentPromptRuntime;\n"],"mappings":"8DAGSA,EAAAA"}
@@ -0,0 +1,2 @@
1
+ import { registerSubagentPromptRuntime } from "./subagentPromptRuntime.cjs";
2
+ export = registerSubagentPromptRuntime;
@@ -0,0 +1,2 @@
1
+ import { registerSubagentPromptRuntime } from "./subagentPromptRuntime.mjs";
2
+ export { registerSubagentPromptRuntime as default };
@@ -0,0 +1,2 @@
1
+ import{__commonJSMin as e}from"../_virtual/_rolldown/runtime.mjs";import{init_subagentPromptRuntime as t,registerSubagentPromptRuntime as n}from"./subagentPromptRuntime.mjs";var r=e(((e,r)=>{t(),r.exports=n}));export default r();export{};
2
+ //# sourceMappingURL=subagentPromptRuntimeEntry.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subagentPromptRuntimeEntry.mjs","names":[],"sources":["../../src/extensions/subagentPromptRuntimeEntry.cts"],"sourcesContent":["import { registerSubagentPromptRuntime } from './subagentPromptRuntime.ts';\n\n// Pi's jiti loader imports extension factories through the CommonJS default interop path.\nexport = registerSubagentPromptRuntime;\n"],"mappings":"kMAA2E,WAGlE"}
@@ -0,0 +1,7 @@
1
+ require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../agents/memory.cjs`),t=require(`../_virtual/_@oxc-project_runtime@0.127.0/helpers/decorate.cjs`),n=require(`../container/types.cjs`),r=require(`../_virtual/_@oxc-project_runtime@0.127.0/helpers/decorateMetadata.cjs`),i=require(`../_virtual/_@oxc-project_runtime@0.127.0/helpers/decorateParam.cjs`),a=require(`../shared/paths.cjs`),o=require(`../shared/errors.cjs`),s=require(`../runs/shared/runtimeRegistry.cjs`),c=require(`../shared/modelResolution.cjs`),l=require(`../runs/shared/modelFallback.cjs`),u=require(`./spawnPlan.cjs`),d=require(`../runs/background/asyncJobTracker.cjs`),f=require(`../runs/registry/suspendedRuns.cjs`),p=require(`./config.cjs`),m=require(`./operationJournal.cjs`);require(`./schemas.cjs`);const h=require(`./statusViews.cjs`),g=require(`./toolDescription.cjs`);let _=require(`inversify`),v=require(`node:crypto`),y=require(`@agimon-ai/doompi-extension-contracts/subagent-tool`);const b=`subagent`,x=new Set(Object.values(y.SUBAGENT_ACTIONS));function S(e,t){return{content:[{type:`text`,text:e}],details:t}}function C(e,t){return S(e,{action:t,partial:!0})}function w(e){switch(e.action){case y.SUBAGENT_ACTIONS.run:return`Starting ${e.requests.length} subagent${e.requests.length===1?``:`s`}...`;case y.SUBAGENT_ACTIONS.wait:return`Waiting for subagent activity...`;case y.SUBAGENT_ACTIONS.steer:return`Steering subagent ${e.id}...`;case y.SUBAGENT_ACTIONS.stop:return`Requesting stop for subagent ${e.id}...`;case y.SUBAGENT_ACTIONS.restore:return`Restoring subagent ${e.id}...`;default:return}}function T(e){return e===`timeout`?[`The wait timed out; the runs may still be active.`,`Inspect subagent status, wait again with a deliberate timeout, or ask the user before stopping work.`]:e===`attention`?[`Inspect the affected run status or transcript, then steer it or ask the user for the required decision.`]:e===`no-active-runs`?[`Inspect fleet status and verify the run ids instead of polling the same empty wait again.`]:e===`aborted`?[`The wait was cancelled; inspect current run status before deciding what to do next.`]:[]}function E(e,t){try{return e.getAllTools().some(e=>e.name===t)}catch{return!1}}function D(e){return e??`both`}function O(e){return[`Executable agents:`,...e.length?e.toSorted((e,t)=>e.name.localeCompare(t.name)).map(e=>`- ${e.name} (${e.source}): ${e.description}`):[`- (none)`]].join(`
2
+ `)}function k(t){let n=[...t.tools??[],...(t.mcpDirectTools??[]).map(e=>`mcp:${e}`)];return{name:t.name,source:t.source,description:t.description,runtime:t.runtime??`pi`,writeCapable:e.agentHasWriteTools(t),...t.model?{model:t.model}:{},...t.fallbackModels?.length?{fallbackModels:t.fallbackModels}:{},...n.length?{tools:n}:{}}}function A(e){return{...e,resumable:f.isSuspendedRunResumable(e)}}function j(e){let t=k(e);return[`Agent: ${e.name} (${e.source})`,`Description: ${e.description}`,`Runtime: ${String(t.runtime)}`,`Write capable: ${t.writeCapable?`yes`:`no`}`,...e.model?[`Model: ${e.model}`]:[],...Array.isArray(t.tools)?[`Tools: ${t.tools.join(`, `)}`]:[]].join(`
3
+ `)}function M(e,t,n){if(typeof e[t]!=`string`||!e[t].trim())throw o.invalidRequest(`action='${n}' requires nonblank '${t}'.`,`Correct the request and retry.`)}function N(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e;if(typeof t.action!=`string`||!x.has(t.action)||t.action===y.SUBAGENT_ACTIONS.run||typeof t.model!=`string`)return e;let{model:n,...r}=t;return r}function P(e){let t=N(e);if(!t||typeof t!=`object`||Array.isArray(t))throw o.invalidRequest(`subagent parameters must be an object.`,`Call subagent with one documented action shape.`);let n=t,r=n.action;if(typeof r!=`string`||!x.has(r))throw o.invalidRequest(`Unsupported or missing subagent action ${JSON.stringify(r)}.`,`Use one of: ${[...x].join(`, `)}.`);let i=y.SUBAGENT_ACTION_FIELDS[r],a=Object.keys(n).filter(e=>!i.includes(e));if(a.length)throw o.invalidRequest(`action='${r}' does not accept: ${a.join(`, `)}.`,`Remove unknown fields and retry.`);if(r===`run`&&(!Array.isArray(n.requests)||n.requests.length===0))throw o.invalidRequest(`action='run' requires a nonempty 'requests' array.`,`Add at least one agent and task.`);return r===`steer`&&(M(n,`id`,r),M(n,`message`,r)),(r===`stop`||r===`restore`)&&M(n,`id`,r),t}let F=class{registeredHosts=new WeakSet;constructor(e,t,n,r,i){this.planner=e,this.management=t,this.tracker=n,this.discovery=r,this.waiter=i}registerTool(e){if(!this.registeredHosts.has(e)){if(E(e,`subagent`))throw new o.DoomTeamExpectedError(`tool_conflict`,`A foreign '${b}' tool is already registered.`,!1,`Disable the competing extension, then reload Doom Team.`);e.registerTool(this.buildTool()),this.registeredHosts.add(e)}}trackOutcomes(e,t){let n=this.tracker.forSession(t.sessionManager.getSessionId());for(let t of e.outcomes)t.runId&&n.track(t.runId);return e}buildSpawnRequest(e,t,n,r){let i=t.requests.map(e=>{if(!e.agent.trim()||!e.task.trim())throw o.invalidRequest(`Every run request requires nonblank agent and task values.`,`Correct the request and retry.`);return{agent:e.agent.trim(),...e.inlineAgent?{inlineAgent:e.inlineAgent}:{},task:e.task.trim(),...e.cwd?{cwd:e.cwd}:{},...e.model?{model:e.model}:{},...e.runtime?{runtime:e.runtime}:{}}}),a=u.captureSessionForkSource(n.sessionManager,`tool`),s=l.normalizeParentModel(n.model);return{tasks:i,cwd:n.cwd,agentScope:D(t.scope),parentSessionId:n.sessionManager.getSessionId(),...a?{parentSessionFile:a.sessionFile,parentLeafId:a.leafId}:{},...t.concurrency===void 0?{}:{concurrency:t.concurrency},...t.artifacts===void 0?{}:{artifacts:t.artifacts},availableModels:c.authenticatedModelInfos(n.modelRegistry),...s?{parentModel:s}:{},operationId:e,preallocatedRunIds:r}}async executeRun(e,t,n){let r=m.startOperation(e,t,t.requests.map(()=>(0,v.randomUUID)()));if(r.kind===`replay`){if(r.record.state===`completed`&&r.record.result)return r.record.result;throw new o.DoomTeamExpectedError(`delivery_unconfirmed`,`Operation '${e}' is already pending for runs: ${r.record.runIds.join(`, `)}.`,!0,`Call subagent({"action":"status"}) and do not submit the run again.`)}let i=this.trackOutcomes(await this.planner.spawn(this.buildSpawnRequest(e,t,n,r.record.runIds),p.loadConfig().config),n),a=i.outcomes.filter(e=>e.runId),s=i.outcomes.filter(e=>!e.runId),c=i.outcomes.map(e=>`- ${e.agent}: ${e.runId?`started as ${e.runId}`:`failed: ${e.error??`unknown error`}`}${e.warning?`\n Warning: ${e.warning}`:``}`);if(a.length===0&&s.length>0)throw new o.DoomTeamExpectedError(`runtime_unavailable`,`No requested subagent started.\n${c.join(`
4
+ `)}`,!0,`Call subagent({"action":"agents"}) to verify exact agent names, correct only the failed requests, or ask the user if a different delegation approach is needed.`);let l=S([`Run request: started ${a.length}/${i.outcomes.length} background agents; failed ${s.length}.`,...c,...a.length>0?[``,`They run independently of this turn and will send completion notifications. Continue non-overlapping work, or end the turn and wait.`]:[],...s.length>0?[``,`Do not retry the whole request because some runs already started. Inspect the failed entries and submit only corrected replacements for those items.`]:[]].join(`
5
+ `),{spawn:i,started:a.length,failed:s.length});return m.completeOperation(e,r.record,l),l}executeAgents(e,t){let n=e.cwd??t.cwd,r=D(e.scope);if(!e.name){let e=this.discovery.discover(n,r);return S(O(e.agents),{agents:e.agents.map(k)})}let i=this.discovery.find(n,r,e.name);if(!i){let t=this.discovery.discover(n,r).agents.map(e=>e.name).toSorted();throw new o.DoomTeamExpectedError(`agent_not_found`,`No executable agent matches '${e.name}'.${t.length?` Available: ${t.join(`, `)}.`:``}`,!1,`Call subagent({"action":"agents"}) and retry with an exact name.`)}return S(j(i),{agent:k(i)})}async executeManagement(e,t,n,r,i){let l=this.tracker.forSession(t.sessionManager.getSessionId());switch(e.action){case y.SUBAGENT_ACTIONS.status:{let t=f.listSuspendedRuns(a.requireCurrentSessionScope());if(!(`id`in e)){if(`transcriptLines`in e&&e.transcriptLines!==void 0)throw o.invalidRequest(`transcriptLines requires a run id.`,`Add id or omit transcriptLines for fleet status.`);let n=l.list();return S(h.formatFleetView(n,Date.now(),t),{fleet:n,suspended:t.map(A)})}let n=e.id;if(!n)throw o.invalidRequest(`transcriptLines requires a run id.`,`Add id or omit transcriptLines for fleet status.`);let r=t.find(e=>e.runId===n);if(r&&e.transcriptLines===void 0){let e=f.isSuspendedRunResumable(r)?`Restore it with { action: "restore", id: "${r.runId}" }.`:`It is not resumable; submit a new explicit run.`;return S(`Run '${r.runId}' is suspended. ${e}`,{suspended:A(r)})}let i=this.management.status(n);if(!i.runDir&&!i.resultPath&&!r)throw new o.DoomTeamExpectedError(`run_not_found`,`No run matches '${n}'.`,!1,`Call subagent({"action":"status"}) and retry with an exact id.`);return e.transcriptLines===void 0?S(i.status?`Run '${i.runId}': ${i.status.state}`:`Run '${i.runId}' has no status yet.`,{status:i}):S(h.formatRunTranscript(i.status,e.transcriptLines??80),{transcript:{runId:i.runId}})}case y.SUBAGENT_ACTIONS.wait:{let r=e.ids?.map(e=>d.resolveTrackedRunId(l,e)),i=await this.waiter.wait({target:r?{ids:r}:{all:!0},sessionId:t.sessionManager.getSessionId(),waitFor:e.until,timeoutMs:e.timeoutMs,signal:n});return S([`Subagent wait: ${i.reason}.`,...T(i.reason)].join(`
6
+ `),{outcome:i})}case y.SUBAGENT_ACTIONS.stop:{let t=d.resolveTrackedRunId(l,e.id),n=this.management.stop(t,e.reason);return S(`Stop requested for '${t}'.`,{control:n})}case y.SUBAGENT_ACTIONS.steer:{let t=d.resolveTrackedRunId(l,e.id),r=this.tracker.get(t)?.runtime;if(r&&!s.isPiRuntime(r))throw new o.DoomTeamExpectedError(`unsupported_operation`,`Run '${t}' uses '${r}', which does not support steering.`,!1,`Use subagent({"action":"stop","id":"${t}"}) to terminate it.`);let i=await this.management.steer(t,e.message,void 0,n);return S(`Steer request '${i.requestId}' for '${t}' is ${i.state}: ${i.message}`,{steer:i})}case y.SUBAGENT_ACTIONS.suspended:{let e=f.listSuspendedRuns(a.requireCurrentSessionScope());return S(e.length?f.formatSuspendedRuns(e):`No suspended subagents in this session.`,{suspended:e.map(A)})}case y.SUBAGENT_ACTIONS.restore:{let n=a.requireCurrentSessionScope(),s=f.listSuspendedRuns(n).find(t=>t.runId===e.id);if(!s)throw new o.DoomTeamExpectedError(`run_not_found`,`No suspended run matches '${e.id}'.`,!1,`Call subagent({"action":"suspended"}) and retry with an exact id.`);if(!f.isSuspendedRunResumable(s))throw new o.DoomTeamExpectedError(`not_resumable`,`Suspended run '${e.id}' does not have complete, readable Pi recovery state.`,!1,`Submit a new explicit run request instead of restoring this record.`);let l=this.trackOutcomes(await this.planner.spawn({single:{agent:s.agent,...s.inlineAgent?{inlineAgent:s.inlineAgent}:{},task:s.task,cwd:s.cwd,...s.model?{model:s.model}:{},sessionFile:s.sessionFile},cwd:s.cwd,agentScope:`both`,runtime:`pi`,availableModels:c.authenticatedModelInfos(t.modelRegistry),...i?{operationId:i}:{},...r?{preallocatedRunIds:r}:{}},p.loadConfig().config),t).outcomes[0];if(!l?.runId)throw new o.DoomTeamExpectedError(`not_resumable`,`Could not restore '${e.id}': ${l?.error??`the spawn produced no run.`}`,!0,`Inspect suspended state, then submit a new explicit run if recovery is not possible.`);return f.clearSuspendedRun(n,e.id),S(`Restored '${e.id}' as '${l.runId}', continuing its transcript.`,{restore:{...l,restoredFrom:e.id}})}}}buildTool(){return{name:b,label:`Subagent`,description:g.SUBAGENT_TOOL_DESCRIPTION,parameters:y.SubagentParams,prepareArguments:P,execute:async(e,t,n,r,i)=>{let a=P(t),s=w(a);if(s&&r?.(C(s,a.action)),a.action===y.SUBAGENT_ACTIONS.run)return this.executeRun(e,a,i);if(a.action===y.SUBAGENT_ACTIONS.agents)return this.executeAgents(a,i);if(!(a.action===y.SUBAGENT_ACTIONS.steer||a.action===y.SUBAGENT_ACTIONS.stop||a.action===y.SUBAGENT_ACTIONS.restore))return this.executeManagement(a,i,n);let c=m.startOperation(e,a,a.action===y.SUBAGENT_ACTIONS.restore?[(0,v.randomUUID)()]:[]);if(c.kind===`replay`){if(c.record.state===`completed`&&c.record.result)return c.record.result;throw new o.DoomTeamExpectedError(`delivery_unconfirmed`,`Operation '${e}' is already pending.`,!0,`Inspect run status before retrying this control operation.`)}let l=await this.executeManagement(a,i,n,c.record.runIds,e);return m.completeOperation(e,c.record,l),l}}}};F=t.__decorate([(0,_.injectable)(),i.__decorateParam(0,(0,_.inject)(n.DOOM_TEAM_TYPES.SpawnPlanner)),i.__decorateParam(1,(0,_.inject)(n.DOOM_TEAM_TYPES.ManagementActions)),i.__decorateParam(2,(0,_.inject)(n.DOOM_TEAM_TYPES.AsyncJobTracker)),i.__decorateParam(3,(0,_.inject)(n.DOOM_TEAM_TYPES.AgentDiscoveryService)),i.__decorateParam(4,(0,_.inject)(n.DOOM_TEAM_TYPES.SubagentWaiter)),r.__decorateMetadata(`design:paramtypes`,[Object,Object,Object,Object,Object])],F),Object.defineProperty(exports,`SubagentToolService`,{enumerable:!0,get:function(){return F}});
7
+ //# sourceMappingURL=subagentTool.cjs.map