@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":"managementActions.mjs","names":[],"sources":["../../src/extensions/managementActions.ts"],"sourcesContent":["/**\n * Dispatches the `subagent` tool's management/control `action` values to\n * services that already exist. Nothing new invented here - every method is\n * a thin composition, matching `spawnPlan.ts`'s own \"preflight throws,\n * per-item failure does not\" split where it applies.\n *\n * `list()` returns this process's tracked fleet. `status(id)` resolves the run\n * directory and uses the canonical status reader, preserving corrupt-status\n * failures instead of silently treating them as a missing run.\n *\n * WHAT \"STEER SUCCEEDED\" MEANS HERE:\n * `steer()` writes the request, then waits up to three seconds for the exact\n * request-id and child-index acknowledgment. The targeted consumer reads only\n * that file, so concurrent callers cannot consume each other's acknowledgments.\n * A timeout reports `pending`; a delivered or failed acknowledgment includes\n * the child's message unchanged for the tool surface to show the caller.\n */\n\nimport * as path from 'node:path';\nimport { inject, injectable } from 'inversify';\nimport { DOOM_TEAM_TYPES } from '../container/types.ts';\nimport type { AsyncRunStatus } from '../runs/background/asyncExecution.ts';\nimport type { IAsyncJobTracker, TrackedAsyncJob } from '../runs/background/asyncJobTracker.ts';\nimport {\n consumeSteerAck,\n requestAsyncInterrupt,\n requestAsyncStop,\n requestAsyncSteer,\n} from '../intercom/supervisorControlChannel.ts';\nimport type { IRunIdResolver } from '../runs/background/runIdResolver.ts';\nimport { readAsyncRunStatusResultAt } from '../runs/background/statusReader.ts';\nimport { STATUS_FILE_NAME } from '../runs/background/statusWriter.ts';\nimport { DoomTeamExpectedError } from '../shared/errors.ts';\n\nexport interface StatusActionResult {\n runId: string;\n runDir: string | undefined;\n resultPath?: string;\n claimed: boolean;\n status: AsyncRunStatus | undefined;\n}\n\nexport interface ListActionResult {\n runs: TrackedAsyncJob[];\n}\n\n/** The interrupt/stop request file path written, for a caller that wants to report it. */\nexport interface ControlActionResult {\n requestPath: string;\n}\n\n/**\n * Deliberately separate from `ControlActionResult` because steering adds a\n * correlated acknowledgment state and message.\n */\nexport interface SteerActionResult {\n requestPath: string;\n requestId: string;\n index: number;\n state: 'delivered' | 'failed' | 'pending';\n message: string;\n}\n\nexport interface IManagementActions {\n /** Resolves `id` (exact or unambiguous prefix) and reads that run's own `status.json`. `status: undefined` when the run has none (yet, or ever). Throws only on an AMBIGUOUS prefix - see `RunIdResolver.resolve()`. */\n status(id: string): StatusActionResult;\n /** Every run this process has tracked since it started tracking. Not every run that ever existed - see the module header. */\n list(): ListActionResult;\n interrupt(id: string, reason?: string): ControlActionResult;\n stop(id: string, reason?: string): ControlActionResult;\n /** Writes a steer request and waits briefly for that request's exact child acknowledgment. */\n steer(id: string, message: string, targetIndex?: number, signal?: AbortSignal): Promise<SteerActionResult>;\n}\n\nfunction resolveRunDirOrThrow(resolver: IRunIdResolver, id: string): { runId: string; runDir: string } {\n const resolved = resolver.resolve(id);\n if (!resolved?.runDir) {\n throw new DoomTeamExpectedError(\n 'run_not_found',\n `No active run matches '${id}'.`,\n false,\n 'Call subagent({\"action\":\"status\"}) and retry with an exact run id.',\n );\n }\n return { runId: resolved.runId, runDir: resolved.runDir };\n}\n\n@injectable()\nexport class ManagementActions implements IManagementActions {\n protected readonly steerAckTimeoutMs: number = 3_000;\n protected readonly steerAckPollIntervalMs: number = 25;\n\n constructor(\n @inject(DOOM_TEAM_TYPES.RunIdResolver) private readonly runIds: IRunIdResolver,\n @inject(DOOM_TEAM_TYPES.AsyncJobTracker) private readonly jobs: IAsyncJobTracker,\n ) {}\n\n /** Generated up front so the caller (and, later, an ack-wait) can correlate a steer request without parsing it back out of the written file's path. */\n protected generateSteerRequestId(): string {\n return crypto.randomUUID();\n }\n\n protected readRunStatus(runDir: string): AsyncRunStatus | undefined {\n const result = readAsyncRunStatusResultAt(path.join(runDir, STATUS_FILE_NAME));\n if (result.kind === 'ok') return result.status;\n if (result.kind === 'missing') return undefined;\n throw new DoomTeamExpectedError(\n 'status_corrupt',\n `Run status is ${result.kind} at '${result.path}'.`,\n result.kind === 'io_error',\n 'Inspect the run transcript or stop the run, then retry status.',\n );\n }\n\n status(id: string): StatusActionResult {\n const resolved = this.runIds.resolve(id);\n if (!resolved) {\n return { runId: id, runDir: undefined, resultPath: undefined, claimed: false, status: undefined };\n }\n return {\n runId: resolved.runId,\n runDir: resolved.runDir,\n resultPath: resolved.resultPath,\n claimed: resolved.claimed,\n status: resolved.runDir ? this.readRunStatus(resolved.runDir) : undefined,\n };\n }\n\n list(): ListActionResult {\n return { runs: this.jobs.list() };\n }\n\n interrupt(id: string, reason?: string): ControlActionResult {\n const { runDir } = resolveRunDirOrThrow(this.runIds, id);\n return { requestPath: requestAsyncInterrupt(runDir, reason ? { reason } : {}) };\n }\n\n stop(id: string, reason?: string): ControlActionResult {\n const { runDir } = resolveRunDirOrThrow(this.runIds, id);\n return { requestPath: requestAsyncStop(runDir, reason ? { reason } : {}) };\n }\n\n protected wait(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Error('Steer acknowledgment wait cancelled.'));\n return;\n }\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n 'abort',\n () => {\n clearTimeout(timer);\n reject(new Error('Steer acknowledgment wait cancelled.'));\n },\n { once: true },\n );\n });\n }\n\n async steer(id: string, message: string, targetIndex?: number, signal?: AbortSignal): Promise<SteerActionResult> {\n const { runDir } = resolveRunDirOrThrow(this.runIds, id);\n const resolvedIndex = targetIndex ?? this.readRunStatus(runDir)?.fanoutIndex ?? 0;\n const requestId = this.generateSteerRequestId();\n const requestPath = requestAsyncSteer(runDir, {\n message,\n id: requestId,\n targetIndex: resolvedIndex,\n });\n const deadline = Date.now() + this.steerAckTimeoutMs;\n while (Date.now() <= deadline) {\n const ack = consumeSteerAck(runDir, resolvedIndex, requestId);\n if (ack) {\n return { requestPath, requestId, index: ack.index, state: ack.state, message: ack.message };\n }\n await this.wait(this.steerAckPollIntervalMs, signal);\n }\n return {\n requestPath,\n requestId,\n index: resolvedIndex,\n state: 'pending',\n message: 'No child acknowledgment arrived within 3 seconds.',\n };\n }\n}\n"],"mappings":"mhCA0EA,SAAS,EAAqB,EAA0B,EAA+C,CACrG,IAAM,EAAW,EAAS,QAAQ,EAAG,CACrC,GAAI,CAAC,GAAU,OACb,MAAM,IAAI,EACR,gBACA,0BAA0B,EAAG,IAC7B,GACA,qEACD,CAEH,MAAO,CAAE,MAAO,EAAS,MAAO,OAAQ,EAAS,OAAQ,oBAhEH,IAQP,IAE+B,IACV,IACV,eAwDrD,KAAsD,CAC3D,kBAA+C,IAC/C,uBAAoD,GAEpD,YACE,EACA,EACA,CAFwD,KAAA,OAAA,EACE,KAAA,KAAA,EAI5D,wBAA2C,CACzC,OAAO,OAAO,YAAY,CAG5B,cAAwB,EAA4C,CAClE,IAAM,EAAS,EAA2B,EAAK,KAAK,EAAQ,EAAiB,CAAC,CAC9E,GAAI,EAAO,OAAS,KAAM,OAAO,EAAO,OACpC,KAAO,OAAS,UACpB,MAAM,IAAI,EACR,iBACA,iBAAiB,EAAO,KAAK,OAAO,EAAO,KAAK,IAChD,EAAO,OAAS,WAChB,iEACD,CAGH,OAAO,EAAgC,CACrC,IAAM,EAAW,KAAK,OAAO,QAAQ,EAAG,CAIxC,O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,EAAgB,EAAQ,EAAe,EAAU,CAC7D,GAAI,EACF,MAAO,CAAE,cAAa,YAAW,MAAO,EAAI,MAAO,MAAO,EAAI,MAAO,QAAS,EAAI,QAAS,CAE7F,MAAM,KAAK,KAAK,KAAK,uBAAwB,EAAO,CAEtD,MAAO,CACL,cACA,YACA,MAAO,EACP,MAAO,UACP,QAAS,oDACV,QAhGJ,GAAY,KAMR,EAAO,EAAgB,cAAc,CAAA,KACrC,EAAO,EAAgB,gBAAgB,CAAA"}
@@ -0,0 +1,2 @@
1
+ const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`../shared/atomicJson.cjs`),n=require(`../shared/paths.cjs`),r=require(`../shared/errors.cjs`);let i=require(`node:fs`);i=e.__toESM(i,1);let a=require(`node:path`);a=e.__toESM(a,1);let o=require(`node:crypto`);const s=`sha256`;function c(e){return(0,o.createHash)(s).update(JSON.stringify(e)).digest(`hex`)}function l(e){let t=(0,o.createHash)(s).update(e).digest(`hex`);return a.join(a.dirname(n.currentRunsDir()),`operations`,`${t}.json`)}function u(e){return JSON.parse(i.readFileSync(e,`utf8`))}function d(e,t,n){let o=l(e),s=c(t);i.mkdirSync(a.dirname(o),{recursive:!0});let d={version:1,operationId:e,argumentHash:s,runIds:n,state:`pending`,createdAt:Date.now()};try{return i.writeFileSync(o,JSON.stringify(d),{flag:`wx`,mode:384}),{kind:`new`,record:d}}catch(t){if(!(t instanceof Error&&`code`in t&&t.code===`EEXIST`))throw t;let n=u(o);if(n.argumentHash!==s)throw new r.DoomTeamExpectedError(`operation_conflict`,`Operation '${e}' was already used with different arguments.`,!1,`Submit the operation as a new tool call.`);return{kind:`replay`,record:n}}}function f(e,n,r){t.writeAtomicJson(l(e),{...n,state:`completed`,result:r})}exports.completeOperation=f,exports.startOperation=d;
2
+ //# sourceMappingURL=operationJournal.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"operationJournal.cjs","names":["path","currentRunsDir","fs","DoomTeamExpectedError"],"sources":["../../src/extensions/operationJournal.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport { writeAtomicJson } from '../shared/atomicJson.ts';\nimport { currentRunsDir } from '../shared/paths.ts';\nimport { DoomTeamExpectedError } from '../shared/errors.ts';\n\nconst HASH_ALGORITHM = 'sha256';\nconst HASH_ENCODING = 'hex';\n\ninterface OperationRecord<TResult> {\n version: 1;\n operationId: string;\n argumentHash: string;\n runIds: string[];\n state: 'pending' | 'completed';\n createdAt: number;\n result?: TResult;\n}\n\nexport type OperationStart<TResult> =\n | { kind: 'new'; record: OperationRecord<TResult> }\n | { kind: 'replay'; record: OperationRecord<TResult> };\n\nfunction hashArguments(args: unknown): string {\n return createHash(HASH_ALGORITHM).update(JSON.stringify(args)).digest(HASH_ENCODING);\n}\n\nfunction journalPath(operationId: string): string {\n const safeId = createHash(HASH_ALGORITHM).update(operationId).digest(HASH_ENCODING);\n return path.join(path.dirname(currentRunsDir()), 'operations', `${safeId}.json`);\n}\n\nfunction readRecord<TResult>(file: string): OperationRecord<TResult> {\n return JSON.parse(fs.readFileSync(file, 'utf8')) as OperationRecord<TResult>;\n}\n\n/** Persist replay identity and run ids before any side effect is started. */\nexport function startOperation<TResult>(operationId: string, args: unknown, runIds: string[]): OperationStart<TResult> {\n const file = journalPath(operationId);\n const argumentHash = hashArguments(args);\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const record: OperationRecord<TResult> = {\n version: 1,\n operationId,\n argumentHash,\n runIds,\n state: 'pending',\n createdAt: Date.now(),\n };\n try {\n fs.writeFileSync(file, JSON.stringify(record), { flag: 'wx', mode: 0o600 });\n return { kind: 'new', record };\n } catch (error) {\n if (!(error instanceof Error && 'code' in error && error.code === 'EEXIST')) throw error;\n const existing = readRecord<TResult>(file);\n if (existing.argumentHash !== argumentHash) {\n throw new DoomTeamExpectedError(\n 'operation_conflict',\n `Operation '${operationId}' was already used with different arguments.`,\n false,\n 'Submit the operation as a new tool call.',\n );\n }\n return { kind: 'replay', record: existing };\n }\n}\n\nexport function completeOperation<TResult>(\n operationId: string,\n record: OperationRecord<TResult>,\n result: TResult,\n): void {\n writeAtomicJson(journalPath(operationId), { ...record, state: 'completed', result });\n}\n"],"mappings":"iRAQA,MAAM,EAAiB,SAiBvB,SAAS,EAAc,EAAuB,CAC5C,OAAA,EAAA,EAAA,YAAkB,EAAe,CAAC,OAAO,KAAK,UAAU,EAAK,CAAC,CAAC,OAAO,MAAc,CAGtF,SAAS,EAAY,EAA6B,CAChD,IAAM,GAAA,EAAA,EAAA,YAAoB,EAAe,CAAC,OAAO,EAAY,CAAC,OAAO,MAAc,CACnF,OAAOA,EAAK,KAAKA,EAAK,QAAQC,EAAAA,gBAAgB,CAAC,CAAE,aAAc,GAAG,EAAO,OAAO,CAGlF,SAAS,EAAoB,EAAwC,CACnE,OAAO,KAAK,MAAMC,EAAG,aAAa,EAAM,OAAO,CAAC,CAIlD,SAAgB,EAAwB,EAAqB,EAAe,EAA2C,CACrH,IAAM,EAAO,EAAY,EAAY,CAC/B,EAAe,EAAc,EAAK,CACxC,EAAG,UAAUF,EAAK,QAAQ,EAAK,CAAE,CAAE,UAAW,GAAM,CAAC,CACrD,IAAM,EAAmC,CACvC,QAAS,EACT,cACA,eACA,SACA,MAAO,UACP,UAAW,KAAK,KAAK,CACtB,CACD,GAAI,CAEF,OADA,EAAG,cAAc,EAAM,KAAK,UAAU,EAAO,CAAE,CAAE,KAAM,KAAM,KAAM,IAAO,CAAC,CACpE,CAAE,KAAM,MAAO,SAAQ,OACvB,EAAO,CACd,GAAI,EAAE,aAAiB,OAAS,SAAU,GAAS,EAAM,OAAS,UAAW,MAAM,EACnF,IAAM,EAAW,EAAoB,EAAK,CAC1C,GAAI,EAAS,eAAiB,EAC5B,MAAM,IAAIG,EAAAA,sBACR,qBACA,cAAc,EAAY,8CAC1B,GACA,2CACD,CAEH,MAAO,CAAE,KAAM,SAAU,OAAQ,EAAU,EAI/C,SAAgB,EACd,EACA,EACA,EACM,CACN,EAAA,gBAAgB,EAAY,EAAY,CAAE,CAAE,GAAG,EAAQ,MAAO,YAAa,SAAQ,CAAC"}
@@ -0,0 +1,2 @@
1
+ import{__esmMin as e}from"../_virtual/_rolldown/runtime.mjs";import{init_atomicJson as t,writeAtomicJson as n}from"../shared/atomicJson.mjs";import{currentRunsDir as r,init_paths as i}from"../shared/paths.mjs";import{DoomTeamExpectedError as a,init_errors as o}from"../shared/errors.mjs";import*as s from"node:fs";import*as c from"node:path";import{createHash as l}from"node:crypto";function u(e){return l(h).update(JSON.stringify(e)).digest(g)}function d(e){let t=l(h).update(e).digest(g);return c.join(c.dirname(r()),`operations`,`${t}.json`)}function f(e){return JSON.parse(s.readFileSync(e,`utf8`))}function p(e,t,n){let r=d(e),i=u(t);s.mkdirSync(c.dirname(r),{recursive:!0});let o={version:1,operationId:e,argumentHash:i,runIds:n,state:`pending`,createdAt:Date.now()};try{return s.writeFileSync(r,JSON.stringify(o),{flag:`wx`,mode:384}),{kind:`new`,record:o}}catch(t){if(!(t instanceof Error&&`code`in t&&t.code===`EEXIST`))throw t;let n=f(r);if(n.argumentHash!==i)throw new a(`operation_conflict`,`Operation '${e}' was already used with different arguments.`,!1,`Submit the operation as a new tool call.`);return{kind:`replay`,record:n}}}function m(e,t,r){n(d(e),{...t,state:`completed`,result:r})}var h,g,_=e((()=>{t(),i(),o(),h=`sha256`,g=`hex`}));_();export{m as completeOperation,_ as init_operationJournal,p as startOperation};
2
+ //# sourceMappingURL=operationJournal.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"operationJournal.mjs","names":[],"sources":["../../src/extensions/operationJournal.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport { writeAtomicJson } from '../shared/atomicJson.ts';\nimport { currentRunsDir } from '../shared/paths.ts';\nimport { DoomTeamExpectedError } from '../shared/errors.ts';\n\nconst HASH_ALGORITHM = 'sha256';\nconst HASH_ENCODING = 'hex';\n\ninterface OperationRecord<TResult> {\n version: 1;\n operationId: string;\n argumentHash: string;\n runIds: string[];\n state: 'pending' | 'completed';\n createdAt: number;\n result?: TResult;\n}\n\nexport type OperationStart<TResult> =\n | { kind: 'new'; record: OperationRecord<TResult> }\n | { kind: 'replay'; record: OperationRecord<TResult> };\n\nfunction hashArguments(args: unknown): string {\n return createHash(HASH_ALGORITHM).update(JSON.stringify(args)).digest(HASH_ENCODING);\n}\n\nfunction journalPath(operationId: string): string {\n const safeId = createHash(HASH_ALGORITHM).update(operationId).digest(HASH_ENCODING);\n return path.join(path.dirname(currentRunsDir()), 'operations', `${safeId}.json`);\n}\n\nfunction readRecord<TResult>(file: string): OperationRecord<TResult> {\n return JSON.parse(fs.readFileSync(file, 'utf8')) as OperationRecord<TResult>;\n}\n\n/** Persist replay identity and run ids before any side effect is started. */\nexport function startOperation<TResult>(operationId: string, args: unknown, runIds: string[]): OperationStart<TResult> {\n const file = journalPath(operationId);\n const argumentHash = hashArguments(args);\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const record: OperationRecord<TResult> = {\n version: 1,\n operationId,\n argumentHash,\n runIds,\n state: 'pending',\n createdAt: Date.now(),\n };\n try {\n fs.writeFileSync(file, JSON.stringify(record), { flag: 'wx', mode: 0o600 });\n return { kind: 'new', record };\n } catch (error) {\n if (!(error instanceof Error && 'code' in error && error.code === 'EEXIST')) throw error;\n const existing = readRecord<TResult>(file);\n if (existing.argumentHash !== argumentHash) {\n throw new DoomTeamExpectedError(\n 'operation_conflict',\n `Operation '${operationId}' was already used with different arguments.`,\n false,\n 'Submit the operation as a new tool call.',\n );\n }\n return { kind: 'replay', record: existing };\n }\n}\n\nexport function completeOperation<TResult>(\n operationId: string,\n record: OperationRecord<TResult>,\n result: TResult,\n): void {\n writeAtomicJson(journalPath(operationId), { ...record, state: 'completed', result });\n}\n"],"mappings":"+XAyBA,SAAS,EAAc,EAAuB,CAC5C,OAAO,EAAW,EAAe,CAAC,OAAO,KAAK,UAAU,EAAK,CAAC,CAAC,OAAO,EAAc,CAGtF,SAAS,EAAY,EAA6B,CAChD,IAAM,EAAS,EAAW,EAAe,CAAC,OAAO,EAAY,CAAC,OAAO,EAAc,CACnF,OAAO,EAAK,KAAK,EAAK,QAAQ,GAAgB,CAAC,CAAE,aAAc,GAAG,EAAO,OAAO,CAGlF,SAAS,EAAoB,EAAwC,CACnE,OAAO,KAAK,MAAM,EAAG,aAAa,EAAM,OAAO,CAAC,CAIlD,SAAgB,EAAwB,EAAqB,EAAe,EAA2C,CACrH,IAAM,EAAO,EAAY,EAAY,CAC/B,EAAe,EAAc,EAAK,CACxC,EAAG,UAAU,EAAK,QAAQ,EAAK,CAAE,CAAE,UAAW,GAAM,CAAC,CACrD,IAAM,EAAmC,CACvC,QAAS,EACT,cACA,eACA,SACA,MAAO,UACP,UAAW,KAAK,KAAK,CACtB,CACD,GAAI,CAEF,OADA,EAAG,cAAc,EAAM,KAAK,UAAU,EAAO,CAAE,CAAE,KAAM,KAAM,KAAM,IAAO,CAAC,CACpE,CAAE,KAAM,MAAO,SAAQ,OACvB,EAAO,CACd,GAAI,EAAE,aAAiB,OAAS,SAAU,GAAS,EAAM,OAAS,UAAW,MAAM,EACnF,IAAM,EAAW,EAAoB,EAAK,CAC1C,GAAI,EAAS,eAAiB,EAC5B,MAAM,IAAI,EACR,qBACA,cAAc,EAAY,8CAC1B,GACA,2CACD,CAEH,MAAO,CAAE,KAAM,SAAU,OAAQ,EAAU,EAI/C,SAAgB,EACd,EACA,EACA,EACM,CACN,EAAgB,EAAY,EAAY,CAAE,CAAE,GAAG,EAAQ,MAAO,YAAa,SAAQ,CAAC,sBAtE5B,IACN,IACQ,CAEtD,EAAiB,SACjB,EAAgB"}
@@ -0,0 +1,35 @@
1
+ const e=`## Delegating to subagents
2
+
3
+ You can delegate work to subagent runs. Doing so well is a skill; doing it
4
+ reflexively wastes time and tokens.
5
+
6
+ **Do it yourself when you can.** A task you can finish with your own tools in a
7
+ few steps should not become a subagent. Delegation costs a process launch, a
8
+ cold context, and a round trip. It pays off for work that is genuinely parallel,
9
+ genuinely long, or genuinely better done in a fresh context.
10
+
11
+ **Launches return immediately.** \`{action:"run", requests:[...]}\` returns run
12
+ handles after startup, not completion. After launching, choose whether to keep
13
+ doing useful work that does not duplicate the delegated scope, or end your turn
14
+ and wait. Do not sleep or poll status in a loop. Completion messages wake you
15
+ automatically. Use \`{action:"wait"}\` only when the current turn genuinely
16
+ cannot end without a completion or attention result.
17
+
18
+ **Results arrive as messages, not return values.** A finished run shows up as a
19
+ completion message carrying its run id, its summary, and the handling it needs.
20
+ Act on it: incorporate the finding, reject it with a reason, or say why it does
21
+ not apply. Never acknowledge one passively, and never invent or predict a
22
+ result that has not arrived. Use the run id it gives you to follow up -
23
+ \`{action:"status", id, transcriptLines:80}\` for recent output, or
24
+ \`{action:"steer", id, message}\` to redirect a live Pi child.
25
+
26
+ **Workers cannot see this conversation.** Every task string must stand alone:
27
+ the goal, the paths, the constraints, the expected output. When you delegate
28
+ follow-up work after a research run, read the findings first and write the next
29
+ prompt with the specific files and changes in it. Writing "based on your
30
+ findings" hands your own understanding to someone who does not have it.
31
+
32
+ **Children are not orchestrators.** Give every child a self-contained task.
33
+ Tool availability, including coordination, is controlled by the selected layer;
34
+ children must not assume they can contact main or delegate further.`;function t(e){return e.orchestratorPrompt!==!1}function n(t){return t?.includes(`## Delegating to subagents`)?t:t?`${t}\n\n${e}`:e}exports.appendOrchestratorPrompt=n,exports.shouldInjectOrchestratorPrompt=t;
35
+ //# sourceMappingURL=orchestratorPrompt.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orchestratorPrompt.cjs","names":[],"sources":["../../src/extensions/orchestratorPrompt.ts"],"sourcesContent":["/**\n * The system-prompt addendum that teaches a parent session how to orchestrate.\n *\n * WHY THIS EXISTS, AND WHY IT IS NOT MORE TOOL-DESCRIPTION TEXT:\n * Until this module, every piece of orchestration guidance this package had\n * lived inside the `subagent` tool's own description. That is the wrong\n * surface for it twice over. A tool description is read as \"how do I call this\n * thing\", so behavioural rules (\"choose what to do after launching\", \"synthesize\n * before delegating again\") compete for attention with call mechanics and lose.\n * And a description is only consulted when the model is already considering\n * that tool, whereas the rule that matters most - do not delegate work you\n * should just do - has to land BEFORE it reaches for the tool at all.\n *\n * So this is a MOVE, not an addition: the behavioural half of\n * `toolDescription.ts` came here, and the description kept the mechanics.\n * Token cost is close to neutral; placement is strictly better.\n *\n * WHY IT IS DEFAULT-ON:\n * `doom-pi` loads this extension in every session, so an opt-in flag would\n * mean nearly every session runs without it - which is today's behaviour and\n * today's problem. `ExtensionConfig.orchestratorPrompt: false` is the escape\n * hatch for a session that wants the tools without the guidance.\n *\n * KEEP THIS SHORT. It is prepended to every turn of every session. Anything\n * that is really call mechanics belongs in the tool description; anything that\n * is really package trivia belongs in a doc nobody pays per-turn for.\n */\n\n/**\n * Marker used to detect an addendum this package already appended, so a repeat\n * `before_agent_start` (or a host that replays the hook) cannot stack two\n * copies into one prompt.\n */\nexport const ORCHESTRATOR_PROMPT_MARKER = '## Delegating to subagents';\n\nexport const ORCHESTRATOR_PROMPT = `${ORCHESTRATOR_PROMPT_MARKER}\n\nYou can delegate work to subagent runs. Doing so well is a skill; doing it\nreflexively wastes time and tokens.\n\n**Do it yourself when you can.** A task you can finish with your own tools in a\nfew steps should not become a subagent. Delegation costs a process launch, a\ncold context, and a round trip. It pays off for work that is genuinely parallel,\ngenuinely long, or genuinely better done in a fresh context.\n\n**Launches return immediately.** \\`{action:\"run\", requests:[...]}\\` returns run\nhandles after startup, not completion. After launching, choose whether to keep\ndoing useful work that does not duplicate the delegated scope, or end your turn\nand wait. Do not sleep or poll status in a loop. Completion messages wake you\nautomatically. Use \\`{action:\"wait\"}\\` only when the current turn genuinely\ncannot end without a completion or attention result.\n\n**Results arrive as messages, not return values.** A finished run shows up as a\ncompletion message carrying its run id, its summary, and the handling it needs.\nAct on it: incorporate the finding, reject it with a reason, or say why it does\nnot apply. Never acknowledge one passively, and never invent or predict a\nresult that has not arrived. Use the run id it gives you to follow up -\n\\`{action:\"status\", id, transcriptLines:80}\\` for recent output, or\n\\`{action:\"steer\", id, message}\\` to redirect a live Pi child.\n\n**Workers cannot see this conversation.** Every task string must stand alone:\nthe goal, the paths, the constraints, the expected output. When you delegate\nfollow-up work after a research run, read the findings first and write the next\nprompt with the specific files and changes in it. Writing \"based on your\nfindings\" hands your own understanding to someone who does not have it.\n\n**Children are not orchestrators.** Give every child a self-contained task.\nTool availability, including coordination, is controlled by the selected layer;\nchildren must not assume they can contact main or delegate further.`;\n\nexport interface OrchestratorPromptConfig {\n /** `false` disables the addendum. Any other value, including absent, enables it. */\n orchestratorPrompt?: boolean;\n}\n\n/** Whether this session should receive the addendum. */\nexport function shouldInjectOrchestratorPrompt(config: OrchestratorPromptConfig): boolean {\n return config.orchestratorPrompt !== false;\n}\n\n/**\n * Append the addendum to a session's system prompt.\n *\n * Idempotent by marker rather than by a registration guard: the caller is a\n * per-turn hook, and the same base prompt reaching it twice must not produce a\n * prompt carrying the guidance twice.\n */\nexport function appendOrchestratorPrompt(systemPrompt: string | undefined): string {\n if (systemPrompt?.includes(ORCHESTRATOR_PROMPT_MARKER)) return systemPrompt;\n return systemPrompt ? `${systemPrompt}\\n\\n${ORCHESTRATOR_PROMPT}` : ORCHESTRATOR_PROMPT;\n}\n"],"mappings":"AAiCA,MAEa,EAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qEAyCnC,SAAgB,EAA+B,EAA2C,CACxF,OAAO,EAAO,qBAAuB,GAUvC,SAAgB,EAAyB,EAA0C,CAEjF,OADI,GAAc,SAAA,6BAAoC,CAAS,EACxD,EAAe,GAAG,EAAa,MAAM,IAAwB"}
@@ -0,0 +1,35 @@
1
+ const e=`## Delegating to subagents
2
+
3
+ You can delegate work to subagent runs. Doing so well is a skill; doing it
4
+ reflexively wastes time and tokens.
5
+
6
+ **Do it yourself when you can.** A task you can finish with your own tools in a
7
+ few steps should not become a subagent. Delegation costs a process launch, a
8
+ cold context, and a round trip. It pays off for work that is genuinely parallel,
9
+ genuinely long, or genuinely better done in a fresh context.
10
+
11
+ **Launches return immediately.** \`{action:"run", requests:[...]}\` returns run
12
+ handles after startup, not completion. After launching, choose whether to keep
13
+ doing useful work that does not duplicate the delegated scope, or end your turn
14
+ and wait. Do not sleep or poll status in a loop. Completion messages wake you
15
+ automatically. Use \`{action:"wait"}\` only when the current turn genuinely
16
+ cannot end without a completion or attention result.
17
+
18
+ **Results arrive as messages, not return values.** A finished run shows up as a
19
+ completion message carrying its run id, its summary, and the handling it needs.
20
+ Act on it: incorporate the finding, reject it with a reason, or say why it does
21
+ not apply. Never acknowledge one passively, and never invent or predict a
22
+ result that has not arrived. Use the run id it gives you to follow up -
23
+ \`{action:"status", id, transcriptLines:80}\` for recent output, or
24
+ \`{action:"steer", id, message}\` to redirect a live Pi child.
25
+
26
+ **Workers cannot see this conversation.** Every task string must stand alone:
27
+ the goal, the paths, the constraints, the expected output. When you delegate
28
+ follow-up work after a research run, read the findings first and write the next
29
+ prompt with the specific files and changes in it. Writing "based on your
30
+ findings" hands your own understanding to someone who does not have it.
31
+
32
+ **Children are not orchestrators.** Give every child a self-contained task.
33
+ Tool availability, including coordination, is controlled by the selected layer;
34
+ children must not assume they can contact main or delegate further.`;function t(e){return e.orchestratorPrompt!==!1}function n(t){return t?.includes(`## Delegating to subagents`)?t:t?`${t}\n\n${e}`:e}export{n as appendOrchestratorPrompt,t as shouldInjectOrchestratorPrompt};
35
+ //# sourceMappingURL=orchestratorPrompt.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orchestratorPrompt.mjs","names":[],"sources":["../../src/extensions/orchestratorPrompt.ts"],"sourcesContent":["/**\n * The system-prompt addendum that teaches a parent session how to orchestrate.\n *\n * WHY THIS EXISTS, AND WHY IT IS NOT MORE TOOL-DESCRIPTION TEXT:\n * Until this module, every piece of orchestration guidance this package had\n * lived inside the `subagent` tool's own description. That is the wrong\n * surface for it twice over. A tool description is read as \"how do I call this\n * thing\", so behavioural rules (\"choose what to do after launching\", \"synthesize\n * before delegating again\") compete for attention with call mechanics and lose.\n * And a description is only consulted when the model is already considering\n * that tool, whereas the rule that matters most - do not delegate work you\n * should just do - has to land BEFORE it reaches for the tool at all.\n *\n * So this is a MOVE, not an addition: the behavioural half of\n * `toolDescription.ts` came here, and the description kept the mechanics.\n * Token cost is close to neutral; placement is strictly better.\n *\n * WHY IT IS DEFAULT-ON:\n * `doom-pi` loads this extension in every session, so an opt-in flag would\n * mean nearly every session runs without it - which is today's behaviour and\n * today's problem. `ExtensionConfig.orchestratorPrompt: false` is the escape\n * hatch for a session that wants the tools without the guidance.\n *\n * KEEP THIS SHORT. It is prepended to every turn of every session. Anything\n * that is really call mechanics belongs in the tool description; anything that\n * is really package trivia belongs in a doc nobody pays per-turn for.\n */\n\n/**\n * Marker used to detect an addendum this package already appended, so a repeat\n * `before_agent_start` (or a host that replays the hook) cannot stack two\n * copies into one prompt.\n */\nexport const ORCHESTRATOR_PROMPT_MARKER = '## Delegating to subagents';\n\nexport const ORCHESTRATOR_PROMPT = `${ORCHESTRATOR_PROMPT_MARKER}\n\nYou can delegate work to subagent runs. Doing so well is a skill; doing it\nreflexively wastes time and tokens.\n\n**Do it yourself when you can.** A task you can finish with your own tools in a\nfew steps should not become a subagent. Delegation costs a process launch, a\ncold context, and a round trip. It pays off for work that is genuinely parallel,\ngenuinely long, or genuinely better done in a fresh context.\n\n**Launches return immediately.** \\`{action:\"run\", requests:[...]}\\` returns run\nhandles after startup, not completion. After launching, choose whether to keep\ndoing useful work that does not duplicate the delegated scope, or end your turn\nand wait. Do not sleep or poll status in a loop. Completion messages wake you\nautomatically. Use \\`{action:\"wait\"}\\` only when the current turn genuinely\ncannot end without a completion or attention result.\n\n**Results arrive as messages, not return values.** A finished run shows up as a\ncompletion message carrying its run id, its summary, and the handling it needs.\nAct on it: incorporate the finding, reject it with a reason, or say why it does\nnot apply. Never acknowledge one passively, and never invent or predict a\nresult that has not arrived. Use the run id it gives you to follow up -\n\\`{action:\"status\", id, transcriptLines:80}\\` for recent output, or\n\\`{action:\"steer\", id, message}\\` to redirect a live Pi child.\n\n**Workers cannot see this conversation.** Every task string must stand alone:\nthe goal, the paths, the constraints, the expected output. When you delegate\nfollow-up work after a research run, read the findings first and write the next\nprompt with the specific files and changes in it. Writing \"based on your\nfindings\" hands your own understanding to someone who does not have it.\n\n**Children are not orchestrators.** Give every child a self-contained task.\nTool availability, including coordination, is controlled by the selected layer;\nchildren must not assume they can contact main or delegate further.`;\n\nexport interface OrchestratorPromptConfig {\n /** `false` disables the addendum. Any other value, including absent, enables it. */\n orchestratorPrompt?: boolean;\n}\n\n/** Whether this session should receive the addendum. */\nexport function shouldInjectOrchestratorPrompt(config: OrchestratorPromptConfig): boolean {\n return config.orchestratorPrompt !== false;\n}\n\n/**\n * Append the addendum to a session's system prompt.\n *\n * Idempotent by marker rather than by a registration guard: the caller is a\n * per-turn hook, and the same base prompt reaching it twice must not produce a\n * prompt carrying the guidance twice.\n */\nexport function appendOrchestratorPrompt(systemPrompt: string | undefined): string {\n if (systemPrompt?.includes(ORCHESTRATOR_PROMPT_MARKER)) return systemPrompt;\n return systemPrompt ? `${systemPrompt}\\n\\n${ORCHESTRATOR_PROMPT}` : ORCHESTRATOR_PROMPT;\n}\n"],"mappings":"AAiCA,MAEa,EAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qEAyCnC,SAAgB,EAA+B,EAA2C,CACxF,OAAO,EAAO,qBAAuB,GAUvC,SAAgB,EAAyB,EAA0C,CAEjF,OADI,GAAc,SAAA,6BAAoC,CAAS,EACxD,EAAe,GAAG,EAAa,MAAM,IAAwB"}
@@ -0,0 +1,2 @@
1
+ var e=require(`./standard.cjs`).activateStandardTeamExtension;module.exports=e;
2
+ //# sourceMappingURL=pi.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pi.cjs","names":["activateStandardTeamExtension"],"sources":["../../src/extensions/pi.ts"],"sourcesContent":["import { activateStandardTeamExtension } from './standard.ts';\n\nexport default activateStandardTeamExtension;\n"],"mappings":"AAEA,IAAA,2BAAeA,CAAAA"}
@@ -0,0 +1,2 @@
1
+ import { activateStandardTeamExtension } from "./standard.cjs";
2
+ export = activateStandardTeamExtension;
@@ -0,0 +1,2 @@
1
+ import { activateStandardTeamExtension } from "./standard.mjs";
2
+ export { activateStandardTeamExtension as default };
@@ -0,0 +1,2 @@
1
+ import{activateStandardTeamExtension as e}from"./standard.mjs";var t=e;export{t as default};
2
+ //# sourceMappingURL=pi.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pi.mjs","names":[],"sources":["../../src/extensions/pi.ts"],"sourcesContent":["import { activateStandardTeamExtension } from './standard.ts';\n\nexport default activateStandardTeamExtension;\n"],"mappings":"+DAEA,IAAA,EAAe"}
@@ -0,0 +1 @@
1
+ require(`../_virtual/_rolldown/runtime.cjs`),require(`@agimon-ai/doompi-extension-contracts/subagent-tool`);
@@ -0,0 +1,2 @@
1
+ import{__esmMin as e}from"../_virtual/_rolldown/runtime.mjs";import{SUBAGENT_ACTIONS as t,SUBAGENT_ACTION_FIELDS as n,SubagentParams as r}from"@agimon-ai/doompi-extension-contracts/subagent-tool";var i=e((()=>{}));i();export{t as SUBAGENT_ACTIONS,n as SUBAGENT_ACTION_FIELDS,r as SubagentParams,i as init_schemas};
2
+ //# sourceMappingURL=schemas.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemas.mjs","names":[],"sources":["../../src/extensions/schemas.ts"],"sourcesContent":["export {\n SUBAGENT_ACTION_FIELDS,\n SUBAGENT_ACTIONS,\n SubagentParams,\n type SubagentAction,\n type SubagentToolParams,\n} from '@agimon-ai/doompi-extension-contracts/subagent-tool';\n"],"mappings":""}
@@ -0,0 +1,3 @@
1
+ const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`../_virtual/_@oxc-project_runtime@0.127.0/helpers/decorate.cjs`),n=require(`../agents/discovery.cjs`);require(`../env.cjs`);const r=require(`../agents/skills.cjs`),i=require(`../container/types.cjs`),a=require(`../protocol/capabilityCeiling.cjs`),o=require(`../_virtual/_@oxc-project_runtime@0.127.0/helpers/decorateMetadata.cjs`),s=require(`../_virtual/_@oxc-project_runtime@0.127.0/helpers/decorateParam.cjs`),c=require(`../shared/errors.cjs`),l=require(`../runs/shared/depthGuard.cjs`),u=require(`../runs/shared/runWithConcurrency.cjs`),d=require(`../runs/shared/runtimeRegistry.cjs`),f=require(`../runs/shared/modelFallback.cjs`);let p=require(`node:fs`);p=e.__toESM(p,1);let m=require(`node:path`);m=e.__toESM(m,1);let h=require(`inversify`),g=require(`@earendil-works/pi-coding-agent`);var _;const v=`fresh`,y=`runtime "pi"`;function b(e){if(!e?.trim())return!1;try{return p.accessSync(e,p.constants.R_OK),!0}catch{return!1}}function x(e,t){let n=e.getSessionFile();if(!b(n))return;let r=e.getLeafEntry(),i=t===`tool`&&r?.type===`message`&&r.message.role===`assistant`?r.parentId:r?.id??e.getLeafId();return i?{sessionFile:n,leafId:i}:void 0}function S(e){return!!e.leafId.trim()&&b(e.sessionFile)}function C(e,t){return e.sessionFile?v:e.context??t.defaultContext??v}const w=[`read`,`grep`,`find`,`ls`];function T(e,t){return t?e?`${e}\n\n${t}`:t:e}function E(e,t,n){if(d.isPiRuntime(e))return[];let r=[`Runtime '${e}' does not load Pi child extensions or hooks; launched best effort.`],i=[...t.tools!==void 0||t.mcpDirectTools?.length?[`tools`]:[],...t.skills?.length||t.skillPath?.length?[`skills`]:[],...t.extensions!==void 0||t.subagentOnlyExtensions?.length?[`extensions`]:[]];return i.length>0&&r.push(`Doom Team cannot project or enforce configured Pi ${i.join(`, `)} on runtime '${e}'.`),t.skills?.length&&r.push(`Configured skills were not injected: ${t.skills.join(`, `)}.`),n?.length&&r.push(`Runtime '${e}' cannot enforce layer subagent tool exclusions; launched best effort for: ${n.join(`, `)}.`),r}function D(e,t,n,r,i){let a=d.isPiRuntime(n)&&r&&i!==void 0?`${r.provider}/${r.id}`:void 0,[o,...s]=(d.isPiRuntime(n)?[e.model,a,t.model,...t.fallbackModels??[]]:[e.model??t.model,...t.fallbackModels??[]]).filter(e=>!!e?.trim());return{primaryModel:o,fallbackModels:s,model:f.selectAvailableModel(o,s,i)}}const O=`invalid_request`,k=`runtime_unavailable`,A=`unsupported_context`,j=`unsupported_operation`;let M=class{constructor(e,t,n=new a.SubagentCapabilityPolicyStore,i=new r.SkillDiscoveryService){this.agents=e,this.spawner=t,this.policies=n,this.skills=i}generateRunId(){return crypto.randomUUID()}createForkSessionFile(e,t){let n=g.SessionManager.open(e.sessionFile,void 0,t),r=n.createBranchedSession(e.leafId);if(!r)throw Error(`Could not create a branched Pi session from '${e.sessionFile}'.`);if(!p.existsSync(r)){let e=n.getHeader();if(!e)throw Error(`Forked Pi session '${r}' has no header.`);let t=[e,...n.getEntries()];p.writeFileSync(r,`${t.map(e=>JSON.stringify(e)).join(`
2
+ `)}\n`,{flag:`wx`})}return r}removePreparedSessionFile(e){p.rmSync(e,{force:!0})}validateCwd(e){let t;try{t=p.statSync(e)}catch{throw new c.DoomTeamExpectedError(O,`Working directory '${e}' does not exist.`,!1,`Retry with an existing directory.`)}if(!t.isDirectory())throw new c.DoomTeamExpectedError(O,`Working directory '${e}' is not a directory.`,!1,`Retry with an existing directory.`)}resolveLayerExcludeTools(){return n.resolveActiveLayerSubagentConfig()?.config.excludeTools}executableAvailable(e){if(m.isAbsolute(e)||e.includes(m.sep))try{return p.accessSync(e,p.constants.X_OK),!0}catch{return!1}return(process.env.PATH??``).split(m.delimiter).filter(Boolean).some(t=>{try{return p.accessSync(m.join(t,e),p.constants.X_OK),!0}catch{return!1}})}resolveTaskList(e){let t=e.single!==void 0;if(t===(e.tasks!==void 0))throw new c.DoomTeamExpectedError(O,`A run requires exactly one of internal single or tasks representations.`,!1,`Submit a non-empty requests array.`);if(t)return[e.single];if(!e.tasks||e.tasks.length===0)throw new c.DoomTeamExpectedError(O,`A run requires at least one entry in its requests collection.`,!1,`Submit a non-empty requests array.`);return e.tasks}resolveAgentOrThrow(e,t,n){let r=this.agents.find(t,n,e);if(!r)throw new c.DoomTeamExpectedError(`agent_not_found`,`Unknown agent '${e}'.`,!1,`Call subagent({"action":"agents"}) and retry with an exact name.`);return r}resolveExecutableAgent(e,t,n){return e.inlineAgent?{name:e.agent.trim(),systemPromptMode:`append`,inheritProjectContext:!0,inheritSkills:!1,systemPrompt:e.inlineAgent.systemPrompt.trim(),tools:[...w],defaultContext:v,runtime:`pi`}:this.resolveAgentOrThrow(e.agent,t,n)}projectConfiguredSkills(e,t,n,i){if(!d.isPiRuntime(i)||!e.skills?.length)return{systemPrompt:e.systemPrompt,requireReadTool:!1,warnings:[]};let a=this.skills.resolveSkillsWithFallback(e.skills,t,n,e.skillPath,n),o=r.buildSkillInjection(a.resolved);return{systemPrompt:T(e.systemPrompt,o),requireReadTool:o.length>0,warnings:a.missing.length>0?[`Agent '${e.name}' could not resolve configured skills: ${a.missing.join(`, `)}; launched with resolved skills only.`]:[]}}async spawnOneChild(e){let{runId:t,operationId:n,agentConfig:r,capabilityCeiling:i,excludeTools:a,taskInput:o,childIndex:s,fanout:c,fallbackCwd:l,parentSessionId:u,parentSessionFile:f,preparedSessionFile:p,handshakeTimeoutMs:m,artifacts:h,artifactDir:g,availableModels:_,parentModel:v,runtime:y,runtimes:b}=e,x=o.cwd??l,S=o.task??``,w=C(o,r),T=o.runtime??y??r.runtime??`pi`,O=D(o,r,T,v,_);if(O.primaryModel&&_!==void 0&&!O.model)return{agent:r.name,task:S,childIndex:s,error:`No authenticated model is available for '${r.name}'. Checked: ${[O.primaryModel,...O.fallbackModels].join(`, `)}.`};let k;try{k=this.projectConfiguredSkills(r,x,l,T)}catch(e){return{agent:r.name,task:S,childIndex:s,error:e instanceof Error?e.message:String(e)}}let A=[...k.warnings,...E(T,r,a)],j=A.length>0?A.join(` `):void 0,M={runId:t,...n?{operationId:n}:{},agent:r.name,...o.inlineAgent?{inlineAgent:o.inlineAgent}:{},task:S,cwd:x,childIndex:s,fanout:c,...f?{parentSessionFile:f}:{},piArgs:{baseArgs:[],sessionEnabled:d.isPiRuntime(T),...o.sessionFile?{sessionFile:o.sessionFile}:p?{sessionFile:p}:{},inheritProjectContext:r.inheritProjectContext,inheritSkills:r.inheritSkills,systemPromptMode:r.systemPromptMode,systemPrompt:k.systemPrompt,requireReadTool:k.requireReadTool,model:O.model,thinking:r.thinking,tools:r.tools,extensions:r.extensions,subagentOnlyExtensions:r.subagentOnlyExtensions,mcpDirectTools:r.mcpDirectTools,excludeTools:a,capabilityCeiling:i,cwd:x,...w===`fork`&&u?{parentSessionId:u}:{}},...m===void 0?{}:{handshakeTimeoutMs:m},...h===void 0?{}:{artifacts:h},...g===void 0?{}:{artifactDir:g},runtime:T,runtimes:b};try{let e=await this.spawner.spawn(M);return{agent:r.name,task:S,childIndex:s,runId:e.runId,pid:e.pid,...j?{warning:j}:{}}}catch(e){return{agent:r.name,task:S,childIndex:s,error:e instanceof Error?e.message:String(e),...j?{warning:j}:{}}}}async spawn(e,t){let n=this.resolveTaskList(e),r=n.length>1,i=this.resolveLayerExcludeTools(),a=this.policies.resolve(),o=l.preflightSubagentDepth(e.currentDepth??l.resolveCurrentSubagentDepth(),t);if(o.error)throw new c.DoomTeamExpectedError(j,o.error,!1,`Give each child a self-contained task within the selected layer policy.`);let s=t.parallel?.maxTasks??8;if(n.length>s)throw new c.DoomTeamExpectedError(O,`Run requested ${n.length} tasks, but at most ${s} may run at once. Concurrency throttles how fast they start, not how many run.`,!1,`Split the requests into smaller explicit run calls.`);for(let e of n){if(!e.task?.trim())throw new c.DoomTeamExpectedError(O,`Run request for '${e.agent}' requires a nonblank task.`,!1,`Provide a self-contained nonblank task.`);if(e.inlineAgent&&!e.inlineAgent.systemPrompt.trim())throw new c.DoomTeamExpectedError(O,`Inline agent '${e.agent}' requires a nonblank system prompt.`,!1,`Provide a focused read-only exploration role.`)}let f=n.map(t=>this.resolveExecutableAgent(t,t.cwd??e.cwd,e.agentScope));for(let[t,r]of n.entries()){let n=C(r,f[t]),i=r.runtime??e.runtime??f[t].runtime??`pi`;if(n===`fork`){if(!d.isPiRuntime(i))throw new c.DoomTeamExpectedError(A,`Fork context requires ${y} for '${r.agent}'.`,!1,`Use a Pi agent for fork context or explicitly request a fresh run.`);let t=e.parentSessionFile&&e.parentLeafId?{sessionFile:e.parentSessionFile,leafId:e.parentLeafId}:void 0;if(!t||!S(t))throw new c.DoomTeamExpectedError(A,`Fork context is unavailable for '${r.agent}': the parent Pi session has no readable source.`,!1,`Use an active persisted Pi session or explicitly request a fresh run.`)}}if(e.preallocatedRunIds&&e.preallocatedRunIds.length!==n.length)throw new c.DoomTeamExpectedError(`operation_conflict`,`The operation journal run-id count does not match the request count.`,!1,`Submit the run as a new tool call.`);let p=e.preallocatedRunIds??n.map(()=>this.generateRunId()),m=d.resolveRuntimeTable(t.runtimes);for(let[t,r]of n.entries()){let n=f[t],i=r.cwd??e.cwd;this.validateCwd(i);let o=r.runtime??e.runtime??n.runtime??`pi`,s=D(r,n,o,e.parentModel,e.availableModels);if(s.primaryModel&&e.availableModels!==void 0&&!s.model)throw new c.DoomTeamExpectedError(`model_unavailable`,`No authenticated model is available for '${n.name}'.`,!1,`Authenticate the requested model or choose an available model.`);if(r.inlineAgent&&!d.isPiRuntime(o))throw new c.DoomTeamExpectedError(j,`Inline agent '${r.agent}' requires ${y} to enforce its read-only tools.`,!1,`Remove the runtime override or use a discovered external-runtime agent without inlineAgent.`);if(a&&!d.isPiRuntime(o))throw new c.DoomTeamExpectedError(j,`Runtime '${o}' cannot enforce the active capability ceiling.`,!1,`Use ${y} while plan mode or another capability ceiling is active.`);if(!d.isPiRuntime(o)){let e;try{e=d.resolveRuntimeLaunch(o,m,{prompt:r.task??``,cwd:i}).command}catch(e){throw new c.DoomTeamExpectedError(k,e instanceof Error?e.message:String(e),!1,`Configure a valid external runtime or use ${y}.`)}if(!this.executableAvailable(e))throw new c.DoomTeamExpectedError(k,`Executable '${e}' for runtime '${o}' is unavailable.`,!1,`Install the executable, configure its absolute path, or use ${y}.`)}}let h=e.parentSessionFile&&e.parentLeafId?{sessionFile:e.parentSessionFile,leafId:e.parentLeafId}:void 0,g=[];try{for(let[t,r]of n.entries())g.push(C(r,f[t])===`fork`?this.createForkSessionFile(h,r.cwd??e.cwd):void 0)}catch(e){for(let e of g)e&&this.removePreparedSessionFile(e);throw new c.DoomTeamExpectedError(A,e instanceof Error?e.message:String(e),!1,`Retry from an active persisted Pi session or explicitly request a fresh run.`)}let _=r?e.concurrency??t.parallel?.concurrency??4:1;return{outcomes:(await u.runWithConcurrency(n.map((n,o)=>()=>this.spawnOneChild({runId:p[o],operationId:e.operationId,agentConfig:f[o],excludeTools:i,capabilityCeiling:a,taskInput:n,childIndex:o,fanout:r,fallbackCwd:e.cwd,parentSessionId:e.parentSessionId,parentSessionFile:e.parentSessionFile,preparedSessionFile:g[o],handshakeTimeoutMs:t.handshakeTimeoutMs,artifacts:e.artifacts,artifactDir:t.artifactDir,availableModels:e.availableModels,parentModel:e.parentModel,runtime:e.runtime,runtimes:m})),_)).map((e,t)=>e.status===`fulfilled`?e.value:{agent:f[t].name,task:n[t].task??``,childIndex:t,error:e.reason instanceof Error?e.reason.message:String(e.reason)})}}};M=t.__decorate([(0,h.injectable)(),s.__decorateParam(0,(0,h.inject)(i.DOOM_TEAM_TYPES.AgentDiscoveryService)),s.__decorateParam(1,(0,h.inject)(i.DOOM_TEAM_TYPES.AsyncSubagentSpawner)),s.__decorateParam(2,(0,h.inject)(i.DOOM_TEAM_TYPES.SubagentCapabilityPolicyStore)),s.__decorateParam(3,(0,h.inject)(i.DOOM_TEAM_TYPES.SkillDiscoveryService)),o.__decorateMetadata(`design:paramtypes`,[Object,Object,typeof(_=a.SubagentCapabilityPolicyStore!==void 0&&a.SubagentCapabilityPolicyStore)==`function`?_:Object,Object])],M),Object.defineProperty(exports,`SpawnPlanner`,{enumerable:!0,get:function(){return M}}),exports.captureSessionForkSource=x;
3
+ //# sourceMappingURL=spawnPlan.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spawnPlan.cjs","names":["fs","isPiRuntime","selectAvailableModel","SubagentCapabilityPolicyStore","SkillDiscoveryService","SessionManager","DoomTeamExpectedError","resolveActiveLayerSubagentConfig","path","buildSkillInjection","preflightSubagentDepth","resolveCurrentSubagentDepth","resolveRuntimeTable","resolveRuntimeLaunch","runWithConcurrency","DOOM_TEAM_TYPES"],"sources":["../../src/extensions/spawnPlan.ts"],"sourcesContent":["/**\n * Turns `subagent` tool params into a resolved sequence of\n * `AsyncSubagentSpawner.spawn()` calls: SINGLE (one child), PARALLEL (N\n * children, bounded by `concurrency`).\n *\n * WHY THIS IS NEW LOGIC, NOT COMPOSITION:\n * `AsyncSubagentSpawner` is deliberately a per-child primitive -\n * `childIndex`/`fanout` arrive as inputs it does not derive (see that\n * module's header). Nothing else in this package decides \"how many\n * children, in what order, at what `childIndex`\" from a `subagent` tool\n * call. That decision is this file's job.\n *\n * PREFLIGHT, ALL-OR-NOTHING:\n * `resolveCurrentSubagentDepth`/`preflightSubagentDepth` run once, before\n * anything spawns. A depth refusal throws - a declared plan that cannot run\n * at all should produce one clear refusal, not a partial fan-out.\n * `AgentDiscoveryService.find` resolves and validates every child's agent\n * name up front too, for the same reason: a typo'd agent name is a\n * preflight failure named at the tool boundary, not a spawn error surfacing\n * deep inside one child while its siblings are already running.\n *\n * ONCE THE BATCH HAS STARTED, PER-CHILD FAILURE IS A RESULT, NOT AN\n * EXCEPTION:\n * `runWithConcurrency` never lets one child's rejection abort its siblings,\n * matching `failFast` being opt-in in the schema, not the default. Every\n * child gets an outcome - `{runId, pid}` on success, `{error}` on failure -\n * and the caller (`subagentTool.ts`) decides how to report a mixed batch.\n *\n * WHAT THIS DOES NOT WIRE YET, AND WHY - FLAGGED, NOT SILENTLY GUESSED:\n * - `maxSubagentSpawnsPerSession` (`spawn-budget.ts`) is NOT enforced here.\n * `preflightSpawnBudget` needs a durable, session-scoped `SpawnBudgetStore`\n * that accumulates spend ACROSS separate tool calls in the same session;\n * inventing a fresh store per call would never track real spend and would\n * be worse than not checking at all (false confidence). Wiring this needs\n * a real session-scoped store (`GlobalStateBridge`'s `protocolSlot`\n * pattern, used by `capabilityCeiling.ts`, is the likely shape) - a\n * follow-up, not guessed here.\n * - Fork context is resolved here and requires a captured persisted Pi source;\n * unavailable or non-Pi fork requests fail closed rather than becoming fresh\n * launches.\n * - Per-task overrides with no direct `BuildPiArgsInput` field confirmed yet\n * (`skill`, `toolBudget`, `turnBudget`, `outputSchema`/structured output,\n * `acceptance`, `output`/`outputMode`) are not mapped into `piArgs` for\n * v1. Each child still gets its resolved `AgentConfig`'s own defaults\n * (`systemPromptMode`, `inheritProjectContext`, `inheritSkills`,\n * `systemPrompt`) - not nothing, just not every param override yet.\n *\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { InlineAgent } from '@agimon-ai/doompi-extension-contracts/subagent-tool';\nimport { SessionManager } from '@earendil-works/pi-coding-agent';\nimport { inject, injectable } from 'inversify';\nimport { DOOM_TEAM_TYPES } from '../container/types.ts';\nimport { resolveActiveLayerSubagentConfig } from '../agents/discovery.ts';\nimport { buildSkillInjection, SkillDiscoveryService, type ISkillDiscoveryService } from '../agents/skills.ts';\nimport type { AgentConfig, IAgentDiscoveryService, AgentScope } from '../agents/types.ts';\nimport type {\n AsyncSubagentSpawnInput,\n AsyncSubagentSpawnResult,\n IAsyncSubagentSpawner,\n} from '../runs/background/asyncExecution.ts';\nimport { preflightSubagentDepth, resolveCurrentSubagentDepth } from '../runs/shared/depthGuard.ts';\nimport {\n SubagentCapabilityPolicyStore,\n type ResolvedSubagentCapabilityCeiling,\n} from '../protocol/capabilityCeiling.ts';\nimport { runWithConcurrency } from '../runs/shared/runWithConcurrency.ts';\nimport {\n isPiRuntime,\n resolveRuntimeLaunch,\n resolveRuntimeTable,\n type RuntimeTable,\n} from '../runs/shared/runtimeRegistry.ts';\nimport { PI_RUNTIME_NAME } from '../env.ts';\nimport { selectAvailableModel, type AvailableModelInfo, type ParentModel } from '../runs/shared/modelFallback.ts';\nimport type { ExtensionConfig } from './config.ts';\nimport { DoomTeamExpectedError } from '../shared/errors.ts';\n\nconst CONTEXT_FRESH = 'fresh' as const;\nconst PI_RUNTIME_REQUIREMENT = `runtime \"${PI_RUNTIME_NAME}\"`;\n\ntype SessionForkCaptureMode = 'tool' | 'settled';\n\nexport interface SessionForkSource {\n sessionFile: string;\n leafId: string;\n}\n\nexport type SessionForkSourceManager = Pick<SessionManager, 'getSessionFile' | 'getLeafId' | 'getLeafEntry'>;\n\nfunction readableSessionFile(sessionFile: string | undefined): sessionFile is string {\n if (!sessionFile?.trim()) return false;\n try {\n fs.accessSync(sessionFile, fs.constants.R_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Capture the parent branch while excluding an assistant turn whose tool is still executing. */\nexport function captureSessionForkSource(\n manager: SessionForkSourceManager,\n mode: SessionForkCaptureMode,\n): SessionForkSource | undefined {\n const sessionFile = manager.getSessionFile();\n if (!readableSessionFile(sessionFile)) return undefined;\n\n const leaf = manager.getLeafEntry();\n const leafId =\n mode === 'tool' && leaf?.type === 'message' && leaf.message.role === 'assistant'\n ? leaf.parentId\n : (leaf?.id ?? manager.getLeafId());\n return leafId ? { sessionFile, leafId } : undefined;\n}\n\nfunction isSessionForkSourceAvailable(source: SessionForkSource): boolean {\n return Boolean(source.leafId.trim()) && readableSessionFile(source.sessionFile);\n}\n\nexport interface SpawnPlanTaskInput {\n agent: string;\n inlineAgent?: InlineAgent;\n task?: string;\n cwd?: string;\n model?: string;\n runtime?: string;\n context?: typeof CONTEXT_FRESH | 'fork';\n /**\n * An existing child transcript to continue instead of starting fresh.\n *\n * Set only by a restore. `sdkRunnerEntry.ts` opens it through\n * `SessionManager.open`, which is what makes a restored run pick up where it\n * was suspended rather than redo the task.\n */\n sessionFile?: string;\n}\n\ntype ExecutableAgentConfig = Pick<\n AgentConfig,\n | 'name'\n | 'defaultContext'\n | 'extensions'\n | 'fallbackModels'\n | 'inheritProjectContext'\n | 'inheritSkills'\n | 'mcpDirectTools'\n | 'model'\n | 'runtime'\n | 'skills'\n | 'skillPath'\n | 'subagentOnlyExtensions'\n | 'systemPrompt'\n | 'systemPromptMode'\n | 'thinking'\n | 'tools'\n>;\n\nfunction resolveEffectiveContext(\n taskInput: SpawnPlanTaskInput,\n agent: Pick<ExecutableAgentConfig, 'defaultContext'>,\n): typeof CONTEXT_FRESH | 'fork' {\n return taskInput.sessionFile ? CONTEXT_FRESH : (taskInput.context ?? agent.defaultContext ?? CONTEXT_FRESH);\n}\n\nexport interface SpawnPlanRequest {\n /** SINGLE mode: exactly one child. Mutually exclusive with `tasks`. */\n single?: SpawnPlanTaskInput;\n /** PARALLEL mode: N children, fanned out. Mutually exclusive with `single`. */\n tasks?: SpawnPlanTaskInput[];\n /** Max children in flight at once for PARALLEL mode. Ignored for SINGLE. Defaults to `config.parallel.concurrency` or 4. */\n concurrency?: number;\n /** Fallback cwd for any task that omits its own. */\n cwd: string;\n agentScope: AgentScope;\n /** Legacy session identity retained for delegation correlation. */\n parentSessionId?: string;\n /** Persisted parent transcript used for true Pi forks. */\n parentSessionFile?: string;\n /** Settled parent leaf used for true Pi forks. */\n parentLeafId?: string;\n artifacts?: boolean;\n /** Authenticated models reported by the live parent host. Undefined for callers without a host context. */\n availableModels?: AvailableModelInfo[];\n /** The live parent model, forwarded only for Pi child selection. */\n parentModel?: ParentModel;\n /** Overrides `resolveCurrentSubagentDepth()`'s own env read - a test seam, not a runtime path. */\n currentDepth?: number;\n /** Which runtime executes every child of this request. Defaults per agent, then to `pi`. */\n runtime?: string;\n /** Stable Pi tool-call identity used to correlate this batch. */\n operationId?: string;\n /** Run ids persisted by the operation journal before any process starts. */\n preallocatedRunIds?: string[];\n}\n\n/** Everything one child spawn needs. An object because this reached ten positional parameters. */\ninterface SpawnOneChildInput {\n runId: string;\n operationId?: string;\n agentConfig: ExecutableAgentConfig;\n excludeTools?: string[];\n capabilityCeiling?: ResolvedSubagentCapabilityCeiling;\n taskInput: SpawnPlanTaskInput;\n childIndex: number;\n fanout: boolean;\n fallbackCwd: string;\n parentSessionId: string | undefined;\n parentSessionFile: string | undefined;\n preparedSessionFile: string | undefined;\n handshakeTimeoutMs: number | undefined;\n artifacts: boolean | undefined;\n artifactDir: ExtensionConfig['artifactDir'];\n availableModels: AvailableModelInfo[] | undefined;\n parentModel: ParentModel | undefined;\n runtime: string | undefined;\n runtimes: RuntimeTable;\n}\n\nexport interface SpawnPlanChildOutcome {\n agent: string;\n task: string;\n /** This spawn's position among its siblings. Always 0 for SINGLE mode. */\n childIndex: number;\n runId?: string;\n pid?: number;\n error?: string;\n warning?: string;\n}\n\nexport interface SpawnPlanResult {\n outcomes: SpawnPlanChildOutcome[];\n}\n\nconst DEFAULT_PARALLEL_CONCURRENCY = 4;\n/**\n * Hard ceiling on how many children one PARALLEL call may launch.\n *\n * `concurrency` does NOT bound this, and cannot: `spawnOneChild` resolves as\n * soon as its child confirms it started, and the child then runs detached. So\n * `runWithConcurrency` throttles how fast children are STARTED, not how many\n * are running - `{tasks: [8], concurrency: 4}` ends up with eight live model\n * processes, not four. Until a launch queue exists that drains as runs go\n * terminal, a width cap is the only thing standing between a fan-out and the\n * machine. 8 matches the sibling implementation's `PI_TEAM_MATE_MAX_PARALLEL`.\n */\nconst DEFAULT_PARALLEL_MAX_TASKS = 8;\nconst INLINE_AGENT_TOOLS = ['read', 'grep', 'find', 'ls'] as const;\n\nfunction appendPromptSection(prompt: string, section: string): string {\n if (!section) return prompt;\n return prompt ? `${prompt}\\n\\n${section}` : section;\n}\n\nfunction bestEffortRuntimeWarnings(\n runtime: string,\n agentConfig: ExecutableAgentConfig,\n excludeTools: string[] | undefined,\n): string[] {\n if (isPiRuntime(runtime)) return [];\n\n const warnings = [`Runtime '${runtime}' does not load Pi child extensions or hooks; launched best effort.`];\n const unsupportedResources = [\n ...(agentConfig.tools !== undefined || agentConfig.mcpDirectTools?.length ? ['tools'] : []),\n ...(agentConfig.skills?.length || agentConfig.skillPath?.length ? ['skills'] : []),\n ...(agentConfig.extensions !== undefined || agentConfig.subagentOnlyExtensions?.length ? ['extensions'] : []),\n ];\n if (unsupportedResources.length > 0) {\n warnings.push(\n `Doom Team cannot project or enforce configured Pi ${unsupportedResources.join(', ')} on runtime '${runtime}'.`,\n );\n }\n if (agentConfig.skills?.length) {\n warnings.push(`Configured skills were not injected: ${agentConfig.skills.join(', ')}.`);\n }\n if (excludeTools?.length) {\n warnings.push(\n `Runtime '${runtime}' cannot enforce layer subagent tool exclusions; launched best effort for: ${excludeTools.join(', ')}.`,\n );\n }\n return warnings;\n}\n\ninterface ChildSkillProjection {\n systemPrompt: string;\n requireReadTool: boolean;\n warnings: string[];\n}\n\ninterface ResolvedModelSelection {\n primaryModel: string | undefined;\n fallbackModels: string[];\n model: string | undefined;\n}\n\nfunction resolvedModelSelection(\n taskInput: SpawnPlanTaskInput,\n agentConfig: Pick<ExecutableAgentConfig, 'model' | 'fallbackModels'>,\n runtime: string,\n parentModel: ParentModel | undefined,\n availableModels: AvailableModelInfo[] | undefined,\n): ResolvedModelSelection {\n const parentModelId =\n isPiRuntime(runtime) && parentModel && availableModels !== undefined\n ? `${parentModel.provider}/${parentModel.id}`\n : undefined;\n const ordered = isPiRuntime(runtime)\n ? [taskInput.model, parentModelId, agentConfig.model, ...(agentConfig.fallbackModels ?? [])]\n : [taskInput.model ?? agentConfig.model, ...(agentConfig.fallbackModels ?? [])];\n const candidates = ordered.filter((candidate): candidate is string => Boolean(candidate?.trim()));\n const [primaryModel, ...fallbackModels] = candidates;\n return {\n primaryModel,\n fallbackModels,\n model: selectAvailableModel(primaryModel, fallbackModels, availableModels),\n };\n}\n\nexport interface ISpawnPlanner {\n /**\n * Resolves the plan and spawns every child. Throws on any PREFLIGHT\n * failure (bad request shape, depth exceeded, unknown agent) before\n * anything spawns. Never throws for an individual child's spawn failure\n * once the batch has started - that is a `{error}` outcome instead.\n */\n spawn(request: SpawnPlanRequest, config: ExtensionConfig): Promise<SpawnPlanResult>;\n}\n\nconst ERROR_CODE_AGENT_NOT_FOUND = 'agent_not_found' as const;\nconst ERROR_CODE_INVALID_REQUEST = 'invalid_request' as const;\nconst ERROR_CODE_MODEL_UNAVAILABLE = 'model_unavailable' as const;\nconst ERROR_CODE_OPERATION_CONFLICT = 'operation_conflict' as const;\nconst ERROR_CODE_RUNTIME_UNAVAILABLE = 'runtime_unavailable' as const;\nconst ERROR_CODE_UNSUPPORTED_CONTEXT = 'unsupported_context' as const;\nconst ERROR_CODE_UNSUPPORTED_OPERATION = 'unsupported_operation' as const;\n\n@injectable()\nexport class SpawnPlanner implements ISpawnPlanner {\n constructor(\n @inject(DOOM_TEAM_TYPES.AgentDiscoveryService) private readonly agents: IAgentDiscoveryService,\n @inject(DOOM_TEAM_TYPES.AsyncSubagentSpawner) private readonly spawner: IAsyncSubagentSpawner,\n @inject(DOOM_TEAM_TYPES.SubagentCapabilityPolicyStore)\n private readonly policies: SubagentCapabilityPolicyStore = new SubagentCapabilityPolicyStore(),\n @inject(DOOM_TEAM_TYPES.SkillDiscoveryService)\n private readonly skills: ISkillDiscoveryService = new SkillDiscoveryService(),\n ) {}\n\n protected generateRunId(): string {\n return crypto.randomUUID();\n }\n\n protected createForkSessionFile(source: SessionForkSource, cwd: string): string {\n const sessionManager = SessionManager.open(source.sessionFile, undefined, cwd);\n const sessionFile = sessionManager.createBranchedSession(source.leafId);\n if (!sessionFile) throw new Error(`Could not create a branched Pi session from '${source.sessionFile}'.`);\n\n // Pi defers writing user-only branches until an assistant response. A tool-safe\n // fork usually ends at the user message immediately before the active tool call,\n // so materialize that valid child transcript before the runner opens it.\n if (!fs.existsSync(sessionFile)) {\n const header = sessionManager.getHeader();\n if (!header) throw new Error(`Forked Pi session '${sessionFile}' has no header.`);\n const records = [header, ...sessionManager.getEntries()];\n fs.writeFileSync(sessionFile, `${records.map((record) => JSON.stringify(record)).join('\\n')}\\n`, { flag: 'wx' });\n }\n return sessionFile;\n }\n\n protected removePreparedSessionFile(sessionFile: string): void {\n fs.rmSync(sessionFile, { force: true });\n }\n\n protected validateCwd(cwd: string): void {\n let stat: fs.Stats;\n try {\n stat = fs.statSync(cwd);\n } catch {\n throw new DoomTeamExpectedError(\n ERROR_CODE_INVALID_REQUEST,\n `Working directory '${cwd}' does not exist.`,\n false,\n 'Retry with an existing directory.',\n );\n }\n if (!stat.isDirectory()) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_INVALID_REQUEST,\n `Working directory '${cwd}' is not a directory.`,\n false,\n 'Retry with an existing directory.',\n );\n }\n }\n\n protected resolveLayerExcludeTools(): string[] | undefined {\n return resolveActiveLayerSubagentConfig()?.config.excludeTools;\n }\n\n protected executableAvailable(command: string): boolean {\n if (path.isAbsolute(command) || command.includes(path.sep)) {\n try {\n fs.accessSync(command, fs.constants.X_OK);\n return true;\n } catch {\n return false;\n }\n }\n return (process.env.PATH ?? '')\n .split(path.delimiter)\n .filter(Boolean)\n .some((directory) => {\n try {\n fs.accessSync(path.join(directory, command), fs.constants.X_OK);\n return true;\n } catch {\n return false;\n }\n });\n }\n\n private resolveTaskList(request: SpawnPlanRequest): SpawnPlanTaskInput[] {\n const hasSingle = request.single !== undefined;\n const hasTasks = request.tasks !== undefined;\n if (hasSingle === hasTasks) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_INVALID_REQUEST,\n 'A run requires exactly one of internal single or tasks representations.',\n false,\n 'Submit a non-empty requests array.',\n );\n }\n if (hasSingle) return [request.single!];\n if (!request.tasks || request.tasks.length === 0) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_INVALID_REQUEST,\n 'A run requires at least one entry in its requests collection.',\n false,\n 'Submit a non-empty requests array.',\n );\n }\n return request.tasks;\n }\n\n private resolveAgentOrThrow(name: string, cwd: string, scope: AgentScope) {\n const resolved = this.agents.find(cwd, scope, name);\n if (!resolved) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_AGENT_NOT_FOUND,\n `Unknown agent '${name}'.`,\n false,\n 'Call subagent({\"action\":\"agents\"}) and retry with an exact name.',\n );\n }\n return resolved;\n }\n\n private resolveExecutableAgent(taskInput: SpawnPlanTaskInput, cwd: string, scope: AgentScope): ExecutableAgentConfig {\n if (!taskInput.inlineAgent) return this.resolveAgentOrThrow(taskInput.agent, cwd, scope);\n return {\n name: taskInput.agent.trim(),\n systemPromptMode: 'append',\n inheritProjectContext: true,\n inheritSkills: false,\n systemPrompt: taskInput.inlineAgent.systemPrompt.trim(),\n tools: [...INLINE_AGENT_TOOLS],\n defaultContext: CONTEXT_FRESH,\n runtime: PI_RUNTIME_NAME,\n };\n }\n\n private projectConfiguredSkills(\n agentConfig: ExecutableAgentConfig,\n childCwd: string,\n requestCwd: string,\n runtime: string,\n ): ChildSkillProjection {\n if (!isPiRuntime(runtime) || !agentConfig.skills?.length) {\n return { systemPrompt: agentConfig.systemPrompt, requireReadTool: false, warnings: [] };\n }\n\n const resolution = this.skills.resolveSkillsWithFallback(\n agentConfig.skills,\n childCwd,\n requestCwd,\n agentConfig.skillPath,\n requestCwd,\n );\n const injection = buildSkillInjection(resolution.resolved);\n return {\n systemPrompt: appendPromptSection(agentConfig.systemPrompt, injection),\n requireReadTool: injection.length > 0,\n warnings:\n resolution.missing.length > 0\n ? [\n `Agent '${agentConfig.name}' could not resolve configured skills: ${resolution.missing.join(', ')}; launched with resolved skills only.`,\n ]\n : [],\n };\n }\n\n /**\n * Spawns exactly one child and returns its outcome. Shared by `spawn()`\n * (SINGLE/PARALLEL) and `spawnChain()`'s per-step/per-parallel-group-child\n * calls, so the `AsyncSubagentSpawnInput` mapping exists in exactly one\n * place. Never throws - a spawn failure becomes an `{error}` outcome, per\n * the \"preflight throws, per-child failure does not\" split documented in\n * the module header.\n */\n private async spawnOneChild(input: SpawnOneChildInput): Promise<SpawnPlanChildOutcome> {\n const {\n runId,\n operationId,\n agentConfig,\n capabilityCeiling,\n excludeTools,\n taskInput,\n childIndex,\n fanout,\n fallbackCwd,\n parentSessionId,\n parentSessionFile,\n preparedSessionFile,\n handshakeTimeoutMs,\n artifacts,\n artifactDir,\n availableModels,\n parentModel,\n runtime,\n runtimes,\n } = input;\n const cwd = taskInput.cwd ?? fallbackCwd;\n const task = taskInput.task ?? '';\n const effectiveContext = resolveEffectiveContext(taskInput, agentConfig);\n const effectiveRuntime = taskInput.runtime ?? runtime ?? agentConfig.runtime ?? PI_RUNTIME_NAME;\n const modelSelection = resolvedModelSelection(\n taskInput,\n agentConfig,\n effectiveRuntime,\n parentModel,\n availableModels,\n );\n if (modelSelection.primaryModel && availableModels !== undefined && !modelSelection.model) {\n return {\n agent: agentConfig.name,\n task,\n childIndex,\n error: `No authenticated model is available for '${agentConfig.name}'. Checked: ${[\n modelSelection.primaryModel,\n ...modelSelection.fallbackModels,\n ].join(', ')}.`,\n };\n }\n\n let skillProjection: ChildSkillProjection;\n try {\n skillProjection = this.projectConfiguredSkills(agentConfig, cwd, fallbackCwd, effectiveRuntime);\n } catch (error) {\n return {\n agent: agentConfig.name,\n task,\n childIndex,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n const warnings = [\n ...skillProjection.warnings,\n ...bestEffortRuntimeWarnings(effectiveRuntime, agentConfig, excludeTools),\n ];\n const warning = warnings.length > 0 ? warnings.join(' ') : undefined;\n\n // Persist every Pi child's own transcript so a later explicit restore can\n // continue it. External runtimes retain their existing session behavior.\n const spawnInput: AsyncSubagentSpawnInput = {\n runId,\n ...(operationId ? { operationId } : {}),\n agent: agentConfig.name,\n ...(taskInput.inlineAgent ? { inlineAgent: taskInput.inlineAgent } : {}),\n task,\n cwd,\n childIndex,\n fanout,\n ...(parentSessionFile ? { parentSessionFile } : {}),\n piArgs: {\n baseArgs: [],\n sessionEnabled: isPiRuntime(effectiveRuntime),\n ...(taskInput.sessionFile\n ? { sessionFile: taskInput.sessionFile }\n : preparedSessionFile\n ? { sessionFile: preparedSessionFile }\n : {}),\n inheritProjectContext: agentConfig.inheritProjectContext,\n inheritSkills: agentConfig.inheritSkills,\n systemPromptMode: agentConfig.systemPromptMode,\n systemPrompt: skillProjection.systemPrompt,\n requireReadTool: skillProjection.requireReadTool,\n model: modelSelection.model,\n thinking: agentConfig.thinking,\n tools: agentConfig.tools,\n extensions: agentConfig.extensions,\n subagentOnlyExtensions: agentConfig.subagentOnlyExtensions,\n mcpDirectTools: agentConfig.mcpDirectTools,\n excludeTools,\n capabilityCeiling,\n cwd,\n ...(effectiveContext === 'fork' && parentSessionId ? { parentSessionId } : {}),\n },\n ...(handshakeTimeoutMs !== undefined ? { handshakeTimeoutMs } : {}),\n ...(artifacts !== undefined ? { artifacts } : {}),\n ...(artifactDir !== undefined ? { artifactDir } : {}),\n // Per-call `runtime` wins over the agent's own default, matching how\n // `model` and `context` already resolve.\n runtime: effectiveRuntime,\n runtimes,\n };\n\n try {\n const result: AsyncSubagentSpawnResult = await this.spawner.spawn(spawnInput);\n return {\n agent: agentConfig.name,\n task,\n childIndex,\n runId: result.runId,\n pid: result.pid,\n ...(warning ? { warning } : {}),\n };\n } catch (error) {\n return {\n agent: agentConfig.name,\n task,\n childIndex,\n error: error instanceof Error ? error.message : String(error),\n ...(warning ? { warning } : {}),\n };\n }\n }\n\n async spawn(request: SpawnPlanRequest, config: ExtensionConfig): Promise<SpawnPlanResult> {\n const tasks = this.resolveTaskList(request);\n const fanout = tasks.length > 1;\n const layerExcludeTools = this.resolveLayerExcludeTools();\n const capabilityCeiling = this.policies.resolve();\n\n // PREFLIGHT - all before any spawn call, so a declared plan that cannot\n // run at all produces one refusal, not a partial fan-out.\n const currentDepth = request.currentDepth ?? resolveCurrentSubagentDepth();\n const depthCheck = preflightSubagentDepth(currentDepth, config);\n if (depthCheck.error) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_UNSUPPORTED_OPERATION,\n depthCheck.error,\n false,\n 'Give each child a self-contained task within the selected layer policy.',\n );\n }\n\n const maxTasks = config.parallel?.maxTasks ?? DEFAULT_PARALLEL_MAX_TASKS;\n if (tasks.length > maxTasks) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_INVALID_REQUEST,\n `Run requested ${tasks.length} tasks, but at most ${maxTasks} may run at once. Concurrency throttles how fast they start, not how many run.`,\n false,\n 'Split the requests into smaller explicit run calls.',\n );\n }\n\n for (const taskInput of tasks) {\n if (!taskInput.task?.trim()) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_INVALID_REQUEST,\n `Run request for '${taskInput.agent}' requires a nonblank task.`,\n false,\n 'Provide a self-contained nonblank task.',\n );\n }\n if (taskInput.inlineAgent && !taskInput.inlineAgent.systemPrompt.trim()) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_INVALID_REQUEST,\n `Inline agent '${taskInput.agent}' requires a nonblank system prompt.`,\n false,\n 'Provide a focused read-only exploration role.',\n );\n }\n }\n\n const resolvedAgents = tasks.map((taskInput) =>\n this.resolveExecutableAgent(taskInput, taskInput.cwd ?? request.cwd, request.agentScope),\n );\n for (const [index, taskInput] of tasks.entries()) {\n const effectiveContext = resolveEffectiveContext(taskInput, resolvedAgents[index]!);\n const runtime = taskInput.runtime ?? request.runtime ?? resolvedAgents[index]!.runtime ?? PI_RUNTIME_NAME;\n if (effectiveContext === 'fork') {\n if (!isPiRuntime(runtime)) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_UNSUPPORTED_CONTEXT,\n `Fork context requires ${PI_RUNTIME_REQUIREMENT} for '${taskInput.agent}'.`,\n false,\n 'Use a Pi agent for fork context or explicitly request a fresh run.',\n );\n }\n const source =\n request.parentSessionFile && request.parentLeafId\n ? { sessionFile: request.parentSessionFile, leafId: request.parentLeafId }\n : undefined;\n if (!source || !isSessionForkSourceAvailable(source)) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_UNSUPPORTED_CONTEXT,\n `Fork context is unavailable for '${taskInput.agent}': the parent Pi session has no readable source.`,\n false,\n 'Use an active persisted Pi session or explicitly request a fresh run.',\n );\n }\n }\n }\n\n if (request.preallocatedRunIds && request.preallocatedRunIds.length !== tasks.length) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_OPERATION_CONFLICT,\n 'The operation journal run-id count does not match the request count.',\n false,\n 'Submit the run as a new tool call.',\n );\n }\n const runIds = request.preallocatedRunIds ?? tasks.map(() => this.generateRunId());\n const runtimes = resolveRuntimeTable(config.runtimes);\n for (const [index, taskInput] of tasks.entries()) {\n const agent = resolvedAgents[index]!;\n const cwd = taskInput.cwd ?? request.cwd;\n this.validateCwd(cwd);\n const runtime = taskInput.runtime ?? request.runtime ?? agent.runtime ?? PI_RUNTIME_NAME;\n const modelSelection = resolvedModelSelection(\n taskInput,\n agent,\n runtime,\n request.parentModel,\n request.availableModels,\n );\n if (modelSelection.primaryModel && request.availableModels !== undefined && !modelSelection.model) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_MODEL_UNAVAILABLE,\n `No authenticated model is available for '${agent.name}'.`,\n false,\n 'Authenticate the requested model or choose an available model.',\n );\n }\n if (taskInput.inlineAgent && !isPiRuntime(runtime)) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_UNSUPPORTED_OPERATION,\n `Inline agent '${taskInput.agent}' requires ${PI_RUNTIME_REQUIREMENT} to enforce its read-only tools.`,\n false,\n 'Remove the runtime override or use a discovered external-runtime agent without inlineAgent.',\n );\n }\n if (capabilityCeiling && !isPiRuntime(runtime)) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_UNSUPPORTED_OPERATION,\n `Runtime '${runtime}' cannot enforce the active capability ceiling.`,\n false,\n `Use ${PI_RUNTIME_REQUIREMENT} while plan mode or another capability ceiling is active.`,\n );\n }\n if (!isPiRuntime(runtime)) {\n let command: string;\n try {\n command = resolveRuntimeLaunch(runtime, runtimes, { prompt: taskInput.task ?? '', cwd }).command;\n } catch (error) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_RUNTIME_UNAVAILABLE,\n error instanceof Error ? error.message : String(error),\n false,\n `Configure a valid external runtime or use ${PI_RUNTIME_REQUIREMENT}.`,\n );\n }\n if (!this.executableAvailable(command)) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_RUNTIME_UNAVAILABLE,\n `Executable '${command}' for runtime '${runtime}' is unavailable.`,\n false,\n `Install the executable, configure its absolute path, or use ${PI_RUNTIME_REQUIREMENT}.`,\n );\n }\n }\n }\n const forkSource =\n request.parentSessionFile && request.parentLeafId\n ? { sessionFile: request.parentSessionFile, leafId: request.parentLeafId }\n : undefined;\n const preparedSessionFiles: Array<string | undefined> = [];\n try {\n for (const [index, taskInput] of tasks.entries()) {\n preparedSessionFiles.push(\n resolveEffectiveContext(taskInput, resolvedAgents[index]!) === 'fork'\n ? this.createForkSessionFile(forkSource!, taskInput.cwd ?? request.cwd)\n : undefined,\n );\n }\n } catch (error) {\n for (const sessionFile of preparedSessionFiles) {\n if (sessionFile) this.removePreparedSessionFile(sessionFile);\n }\n throw new DoomTeamExpectedError(\n ERROR_CODE_UNSUPPORTED_CONTEXT,\n error instanceof Error ? error.message : String(error),\n false,\n 'Retry from an active persisted Pi session or explicitly request a fresh run.',\n );\n }\n\n const concurrency = fanout\n ? (request.concurrency ?? config.parallel?.concurrency ?? DEFAULT_PARALLEL_CONCURRENCY)\n : 1;\n\n const factories = tasks.map(\n (taskInput, childIndex) => () =>\n this.spawnOneChild({\n runId: runIds[childIndex]!,\n operationId: request.operationId,\n agentConfig: resolvedAgents[childIndex]!,\n excludeTools: layerExcludeTools,\n capabilityCeiling,\n taskInput,\n childIndex,\n fanout,\n fallbackCwd: request.cwd,\n parentSessionId: request.parentSessionId,\n parentSessionFile: request.parentSessionFile,\n preparedSessionFile: preparedSessionFiles[childIndex],\n handshakeTimeoutMs: config.handshakeTimeoutMs,\n artifacts: request.artifacts,\n artifactDir: config.artifactDir,\n availableModels: request.availableModels,\n parentModel: request.parentModel,\n runtime: request.runtime,\n runtimes,\n }),\n );\n\n const settled = await runWithConcurrency(factories, concurrency);\n // `spawnOneChild` never rejects (it catches its own spawn failure into\n // an `{error}` outcome), so `runWithConcurrency` never sees a rejection\n // here - this unwrap is defensive, not a real branch.\n const outcomes = settled.map((outcome, index) =>\n outcome.status === 'fulfilled'\n ? outcome.value\n : {\n agent: resolvedAgents[index]!.name,\n task: tasks[index]!.task ?? '',\n childIndex: index,\n error: outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason),\n },\n );\n\n return { outcomes };\n }\n}\n"],"mappings":"81BAgFA,MAAM,EAAgB,QAChB,EAAyB,eAW/B,SAAS,EAAoB,EAAwD,CACnF,GAAI,CAAC,GAAa,MAAM,CAAE,MAAO,GACjC,GAAI,CAEF,OADA,EAAG,WAAW,EAAaA,EAAG,UAAU,KAAK,CACtC,QACD,CACN,MAAO,IAKX,SAAgB,EACd,EACA,EAC+B,CAC/B,IAAM,EAAc,EAAQ,gBAAgB,CAC5C,GAAI,CAAC,EAAoB,EAAY,CAAE,OAEvC,IAAM,EAAO,EAAQ,cAAc,CAC7B,EACJ,IAAS,QAAU,GAAM,OAAS,WAAa,EAAK,QAAQ,OAAS,YACjE,EAAK,SACJ,GAAM,IAAM,EAAQ,WAAW,CACtC,OAAO,EAAS,CAAE,cAAa,SAAQ,CAAG,IAAA,GAG5C,SAAS,EAA6B,EAAoC,CACxE,MAAO,EAAQ,EAAO,OAAO,MAAM,EAAK,EAAoB,EAAO,YAAY,CAyCjF,SAAS,EACP,EACA,EAC+B,CAC/B,OAAO,EAAU,YAAc,EAAiB,EAAU,SAAW,EAAM,gBAAkB,EAwE/F,MAaM,EAAqB,CAAC,OAAQ,OAAQ,OAAQ,KAAK,CAEzD,SAAS,EAAoB,EAAgB,EAAyB,CAEpE,OADK,EACE,EAAS,GAAG,EAAO,MAAM,IAAY,EADvB,EAIvB,SAAS,EACP,EACA,EACA,EACU,CACV,GAAIC,EAAAA,YAAY,EAAQ,CAAE,MAAO,EAAE,CAEnC,IAAM,EAAW,CAAC,YAAY,EAAQ,qEAAqE,CACrG,EAAuB,CAC3B,GAAI,EAAY,QAAU,IAAA,IAAa,EAAY,gBAAgB,OAAS,CAAC,QAAQ,CAAG,EAAE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project_runtime@0.127.0/helpers/decorate.mjs";import{init_discovery as r,resolveActiveLayerSubagentConfig as i}from"../agents/discovery.mjs";import{init_env as a}from"../env.mjs";import{SkillDiscoveryService as o,buildSkillInjection as s,init_skills as c}from"../agents/skills.mjs";import{DOOM_TEAM_TYPES as l,init_types as u}from"../container/types.mjs";import{SubagentCapabilityPolicyStore as d,init_capabilityCeiling as f}from"../protocol/capabilityCeiling.mjs";import{__decorateMetadata as p,init_decorateMetadata as m}from"../_virtual/_@oxc-project_runtime@0.127.0/helpers/decorateMetadata.mjs";import{__decorateParam as h,init_decorateParam as g}from"../_virtual/_@oxc-project_runtime@0.127.0/helpers/decorateParam.mjs";import{DoomTeamExpectedError as _,init_errors as v}from"../shared/errors.mjs";import{init_depthGuard as y,preflightSubagentDepth as b,resolveCurrentSubagentDepth as x}from"../runs/shared/depthGuard.mjs";import{init_runWithConcurrency as S,runWithConcurrency as C}from"../runs/shared/runWithConcurrency.mjs";import{init_runtimeRegistry as w,isPiRuntime as T,resolveRuntimeLaunch as E,resolveRuntimeTable as D}from"../runs/shared/runtimeRegistry.mjs";import{init_modelFallback as O,selectAvailableModel as k}from"../runs/shared/modelFallback.mjs";import*as A from"node:fs";import*as j from"node:path";import{inject as M,injectable as N}from"inversify";import{SessionManager as P}from"@earendil-works/pi-coding-agent";function F(e){if(!e?.trim())return!1;try{return A.accessSync(e,A.constants.R_OK),!0}catch{return!1}}function I(e,t){let n=e.getSessionFile();if(!F(n))return;let r=e.getLeafEntry(),i=t===`tool`&&r?.type===`message`&&r.message.role===`assistant`?r.parentId:r?.id??e.getLeafId();return i?{sessionFile:n,leafId:i}:void 0}function ee(e){return!!e.leafId.trim()&&F(e.sessionFile)}function L(e,t){return e.sessionFile?B:e.context??t.defaultContext??B}function te(e,t){return t?e?`${e}\n\n${t}`:t:e}function ne(e,t,n){if(T(e))return[];let r=[`Runtime '${e}' does not load Pi child extensions or hooks; launched best effort.`],i=[...t.tools!==void 0||t.mcpDirectTools?.length?[`tools`]:[],...t.skills?.length||t.skillPath?.length?[`skills`]:[],...t.extensions!==void 0||t.subagentOnlyExtensions?.length?[`extensions`]:[]];return i.length>0&&r.push(`Doom Team cannot project or enforce configured Pi ${i.join(`, `)} on runtime '${e}'.`),t.skills?.length&&r.push(`Configured skills were not injected: ${t.skills.join(`, `)}.`),n?.length&&r.push(`Runtime '${e}' cannot enforce layer subagent tool exclusions; launched best effort for: ${n.join(`, `)}.`),r}function R(e,t,n,r,i){let a=T(n)&&r&&i!==void 0?`${r.provider}/${r.id}`:void 0,[o,...s]=(T(n)?[e.model,a,t.model,...t.fallbackModels??[]]:[e.model??t.model,...t.fallbackModels??[]]).filter(e=>!!e?.trim());return{primaryModel:o,fallbackModels:s,model:k(o,s,i)}}var z,B,V,H,U,W,G,K,q,J,Y,X,Z,Q,$=e((()=>{u(),r(),c(),y(),f(),S(),w(),a(),O(),v(),m(),g(),n(),B=`fresh`,V=`runtime "pi"`,H=4,U=8,W=[`read`,`grep`,`find`,`ls`],G=`agent_not_found`,K=`invalid_request`,q=`model_unavailable`,J=`operation_conflict`,Y=`runtime_unavailable`,X=`unsupported_context`,Z=`unsupported_operation`,Q=class{constructor(e,t,n=new d,r=new o){this.agents=e,this.spawner=t,this.policies=n,this.skills=r}generateRunId(){return crypto.randomUUID()}createForkSessionFile(e,t){let n=P.open(e.sessionFile,void 0,t),r=n.createBranchedSession(e.leafId);if(!r)throw Error(`Could not create a branched Pi session from '${e.sessionFile}'.`);if(!A.existsSync(r)){let e=n.getHeader();if(!e)throw Error(`Forked Pi session '${r}' has no header.`);let t=[e,...n.getEntries()];A.writeFileSync(r,`${t.map(e=>JSON.stringify(e)).join(`
2
+ `)}\n`,{flag:`wx`})}return r}removePreparedSessionFile(e){A.rmSync(e,{force:!0})}validateCwd(e){let t;try{t=A.statSync(e)}catch{throw new _(K,`Working directory '${e}' does not exist.`,!1,`Retry with an existing directory.`)}if(!t.isDirectory())throw new _(K,`Working directory '${e}' is not a directory.`,!1,`Retry with an existing directory.`)}resolveLayerExcludeTools(){return i()?.config.excludeTools}executableAvailable(e){if(j.isAbsolute(e)||e.includes(j.sep))try{return A.accessSync(e,A.constants.X_OK),!0}catch{return!1}return(process.env.PATH??``).split(j.delimiter).filter(Boolean).some(t=>{try{return A.accessSync(j.join(t,e),A.constants.X_OK),!0}catch{return!1}})}resolveTaskList(e){let t=e.single!==void 0;if(t===(e.tasks!==void 0))throw new _(K,`A run requires exactly one of internal single or tasks representations.`,!1,`Submit a non-empty requests array.`);if(t)return[e.single];if(!e.tasks||e.tasks.length===0)throw new _(K,`A run requires at least one entry in its requests collection.`,!1,`Submit a non-empty requests array.`);return e.tasks}resolveAgentOrThrow(e,t,n){let r=this.agents.find(t,n,e);if(!r)throw new _(G,`Unknown agent '${e}'.`,!1,`Call subagent({"action":"agents"}) and retry with an exact name.`);return r}resolveExecutableAgent(e,t,n){return e.inlineAgent?{name:e.agent.trim(),systemPromptMode:`append`,inheritProjectContext:!0,inheritSkills:!1,systemPrompt:e.inlineAgent.systemPrompt.trim(),tools:[...W],defaultContext:B,runtime:`pi`}:this.resolveAgentOrThrow(e.agent,t,n)}projectConfiguredSkills(e,t,n,r){if(!T(r)||!e.skills?.length)return{systemPrompt:e.systemPrompt,requireReadTool:!1,warnings:[]};let i=this.skills.resolveSkillsWithFallback(e.skills,t,n,e.skillPath,n),a=s(i.resolved);return{systemPrompt:te(e.systemPrompt,a),requireReadTool:a.length>0,warnings:i.missing.length>0?[`Agent '${e.name}' could not resolve configured skills: ${i.missing.join(`, `)}; launched with resolved skills only.`]:[]}}async spawnOneChild(e){let{runId:t,operationId:n,agentConfig:r,capabilityCeiling:i,excludeTools:a,taskInput:o,childIndex:s,fanout:c,fallbackCwd:l,parentSessionId:u,parentSessionFile:d,preparedSessionFile:f,handshakeTimeoutMs:p,artifacts:m,artifactDir:h,availableModels:g,parentModel:_,runtime:v,runtimes:y}=e,b=o.cwd??l,x=o.task??``,S=L(o,r),C=o.runtime??v??r.runtime??`pi`,w=R(o,r,C,_,g);if(w.primaryModel&&g!==void 0&&!w.model)return{agent:r.name,task:x,childIndex:s,error:`No authenticated model is available for '${r.name}'. Checked: ${[w.primaryModel,...w.fallbackModels].join(`, `)}.`};let E;try{E=this.projectConfiguredSkills(r,b,l,C)}catch(e){return{agent:r.name,task:x,childIndex:s,error:e instanceof Error?e.message:String(e)}}let D=[...E.warnings,...ne(C,r,a)],O=D.length>0?D.join(` `):void 0,k={runId:t,...n?{operationId:n}:{},agent:r.name,...o.inlineAgent?{inlineAgent:o.inlineAgent}:{},task:x,cwd:b,childIndex:s,fanout:c,...d?{parentSessionFile:d}:{},piArgs:{baseArgs:[],sessionEnabled:T(C),...o.sessionFile?{sessionFile:o.sessionFile}:f?{sessionFile:f}:{},inheritProjectContext:r.inheritProjectContext,inheritSkills:r.inheritSkills,systemPromptMode:r.systemPromptMode,systemPrompt:E.systemPrompt,requireReadTool:E.requireReadTool,model:w.model,thinking:r.thinking,tools:r.tools,extensions:r.extensions,subagentOnlyExtensions:r.subagentOnlyExtensions,mcpDirectTools:r.mcpDirectTools,excludeTools:a,capabilityCeiling:i,cwd:b,...S===`fork`&&u?{parentSessionId:u}:{}},...p===void 0?{}:{handshakeTimeoutMs:p},...m===void 0?{}:{artifacts:m},...h===void 0?{}:{artifactDir:h},runtime:C,runtimes:y};try{let e=await this.spawner.spawn(k);return{agent:r.name,task:x,childIndex:s,runId:e.runId,pid:e.pid,...O?{warning:O}:{}}}catch(e){return{agent:r.name,task:x,childIndex:s,error:e instanceof Error?e.message:String(e),...O?{warning:O}:{}}}}async spawn(e,t){let n=this.resolveTaskList(e),r=n.length>1,i=this.resolveLayerExcludeTools(),a=this.policies.resolve(),o=b(e.currentDepth??x(),t);if(o.error)throw new _(Z,o.error,!1,`Give each child a self-contained task within the selected layer policy.`);let s=t.parallel?.maxTasks??U;if(n.length>s)throw new _(K,`Run requested ${n.length} tasks, but at most ${s} may run at once. Concurrency throttles how fast they start, not how many run.`,!1,`Split the requests into smaller explicit run calls.`);for(let e of n){if(!e.task?.trim())throw new _(K,`Run request for '${e.agent}' requires a nonblank task.`,!1,`Provide a self-contained nonblank task.`);if(e.inlineAgent&&!e.inlineAgent.systemPrompt.trim())throw new _(K,`Inline agent '${e.agent}' requires a nonblank system prompt.`,!1,`Provide a focused read-only exploration role.`)}let c=n.map(t=>this.resolveExecutableAgent(t,t.cwd??e.cwd,e.agentScope));for(let[t,r]of n.entries()){let n=L(r,c[t]),i=r.runtime??e.runtime??c[t].runtime??`pi`;if(n===`fork`){if(!T(i))throw new _(X,`Fork context requires ${V} for '${r.agent}'.`,!1,`Use a Pi agent for fork context or explicitly request a fresh run.`);let t=e.parentSessionFile&&e.parentLeafId?{sessionFile:e.parentSessionFile,leafId:e.parentLeafId}:void 0;if(!t||!ee(t))throw new _(X,`Fork context is unavailable for '${r.agent}': the parent Pi session has no readable source.`,!1,`Use an active persisted Pi session or explicitly request a fresh run.`)}}if(e.preallocatedRunIds&&e.preallocatedRunIds.length!==n.length)throw new _(J,`The operation journal run-id count does not match the request count.`,!1,`Submit the run as a new tool call.`);let l=e.preallocatedRunIds??n.map(()=>this.generateRunId()),u=D(t.runtimes);for(let[t,r]of n.entries()){let n=c[t],i=r.cwd??e.cwd;this.validateCwd(i);let o=r.runtime??e.runtime??n.runtime??`pi`,s=R(r,n,o,e.parentModel,e.availableModels);if(s.primaryModel&&e.availableModels!==void 0&&!s.model)throw new _(q,`No authenticated model is available for '${n.name}'.`,!1,`Authenticate the requested model or choose an available model.`);if(r.inlineAgent&&!T(o))throw new _(Z,`Inline agent '${r.agent}' requires ${V} to enforce its read-only tools.`,!1,`Remove the runtime override or use a discovered external-runtime agent without inlineAgent.`);if(a&&!T(o))throw new _(Z,`Runtime '${o}' cannot enforce the active capability ceiling.`,!1,`Use ${V} while plan mode or another capability ceiling is active.`);if(!T(o)){let e;try{e=E(o,u,{prompt:r.task??``,cwd:i}).command}catch(e){throw new _(Y,e instanceof Error?e.message:String(e),!1,`Configure a valid external runtime or use ${V}.`)}if(!this.executableAvailable(e))throw new _(Y,`Executable '${e}' for runtime '${o}' is unavailable.`,!1,`Install the executable, configure its absolute path, or use ${V}.`)}}let d=e.parentSessionFile&&e.parentLeafId?{sessionFile:e.parentSessionFile,leafId:e.parentLeafId}:void 0,f=[];try{for(let[t,r]of n.entries())f.push(L(r,c[t])===`fork`?this.createForkSessionFile(d,r.cwd??e.cwd):void 0)}catch(e){for(let e of f)e&&this.removePreparedSessionFile(e);throw new _(X,e instanceof Error?e.message:String(e),!1,`Retry from an active persisted Pi session or explicitly request a fresh run.`)}let p=r?e.concurrency??t.parallel?.concurrency??H:1;return{outcomes:(await C(n.map((n,o)=>()=>this.spawnOneChild({runId:l[o],operationId:e.operationId,agentConfig:c[o],excludeTools:i,capabilityCeiling:a,taskInput:n,childIndex:o,fanout:r,fallbackCwd:e.cwd,parentSessionId:e.parentSessionId,parentSessionFile:e.parentSessionFile,preparedSessionFile:f[o],handshakeTimeoutMs:t.handshakeTimeoutMs,artifacts:e.artifacts,artifactDir:t.artifactDir,availableModels:e.availableModels,parentModel:e.parentModel,runtime:e.runtime,runtimes:u})),p)).map((e,t)=>e.status===`fulfilled`?e.value:{agent:c[t].name,task:n[t].task??``,childIndex:t,error:e.reason instanceof Error?e.reason.message:String(e.reason)})}}},Q=t([N(),h(0,M(l.AgentDiscoveryService)),h(1,M(l.AsyncSubagentSpawner)),h(2,M(l.SubagentCapabilityPolicyStore)),h(3,M(l.SkillDiscoveryService)),p(`design:paramtypes`,[Object,Object,typeof(z=d!==void 0&&d)==`function`?z:Object,Object])],Q)}));$();export{Q as SpawnPlanner,I as captureSessionForkSource,$ as init_spawnPlan};
3
+ //# sourceMappingURL=spawnPlan.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spawnPlan.mjs","names":[],"sources":["../../src/extensions/spawnPlan.ts"],"sourcesContent":["/**\n * Turns `subagent` tool params into a resolved sequence of\n * `AsyncSubagentSpawner.spawn()` calls: SINGLE (one child), PARALLEL (N\n * children, bounded by `concurrency`).\n *\n * WHY THIS IS NEW LOGIC, NOT COMPOSITION:\n * `AsyncSubagentSpawner` is deliberately a per-child primitive -\n * `childIndex`/`fanout` arrive as inputs it does not derive (see that\n * module's header). Nothing else in this package decides \"how many\n * children, in what order, at what `childIndex`\" from a `subagent` tool\n * call. That decision is this file's job.\n *\n * PREFLIGHT, ALL-OR-NOTHING:\n * `resolveCurrentSubagentDepth`/`preflightSubagentDepth` run once, before\n * anything spawns. A depth refusal throws - a declared plan that cannot run\n * at all should produce one clear refusal, not a partial fan-out.\n * `AgentDiscoveryService.find` resolves and validates every child's agent\n * name up front too, for the same reason: a typo'd agent name is a\n * preflight failure named at the tool boundary, not a spawn error surfacing\n * deep inside one child while its siblings are already running.\n *\n * ONCE THE BATCH HAS STARTED, PER-CHILD FAILURE IS A RESULT, NOT AN\n * EXCEPTION:\n * `runWithConcurrency` never lets one child's rejection abort its siblings,\n * matching `failFast` being opt-in in the schema, not the default. Every\n * child gets an outcome - `{runId, pid}` on success, `{error}` on failure -\n * and the caller (`subagentTool.ts`) decides how to report a mixed batch.\n *\n * WHAT THIS DOES NOT WIRE YET, AND WHY - FLAGGED, NOT SILENTLY GUESSED:\n * - `maxSubagentSpawnsPerSession` (`spawn-budget.ts`) is NOT enforced here.\n * `preflightSpawnBudget` needs a durable, session-scoped `SpawnBudgetStore`\n * that accumulates spend ACROSS separate tool calls in the same session;\n * inventing a fresh store per call would never track real spend and would\n * be worse than not checking at all (false confidence). Wiring this needs\n * a real session-scoped store (`GlobalStateBridge`'s `protocolSlot`\n * pattern, used by `capabilityCeiling.ts`, is the likely shape) - a\n * follow-up, not guessed here.\n * - Fork context is resolved here and requires a captured persisted Pi source;\n * unavailable or non-Pi fork requests fail closed rather than becoming fresh\n * launches.\n * - Per-task overrides with no direct `BuildPiArgsInput` field confirmed yet\n * (`skill`, `toolBudget`, `turnBudget`, `outputSchema`/structured output,\n * `acceptance`, `output`/`outputMode`) are not mapped into `piArgs` for\n * v1. Each child still gets its resolved `AgentConfig`'s own defaults\n * (`systemPromptMode`, `inheritProjectContext`, `inheritSkills`,\n * `systemPrompt`) - not nothing, just not every param override yet.\n *\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { InlineAgent } from '@agimon-ai/doompi-extension-contracts/subagent-tool';\nimport { SessionManager } from '@earendil-works/pi-coding-agent';\nimport { inject, injectable } from 'inversify';\nimport { DOOM_TEAM_TYPES } from '../container/types.ts';\nimport { resolveActiveLayerSubagentConfig } from '../agents/discovery.ts';\nimport { buildSkillInjection, SkillDiscoveryService, type ISkillDiscoveryService } from '../agents/skills.ts';\nimport type { AgentConfig, IAgentDiscoveryService, AgentScope } from '../agents/types.ts';\nimport type {\n AsyncSubagentSpawnInput,\n AsyncSubagentSpawnResult,\n IAsyncSubagentSpawner,\n} from '../runs/background/asyncExecution.ts';\nimport { preflightSubagentDepth, resolveCurrentSubagentDepth } from '../runs/shared/depthGuard.ts';\nimport {\n SubagentCapabilityPolicyStore,\n type ResolvedSubagentCapabilityCeiling,\n} from '../protocol/capabilityCeiling.ts';\nimport { runWithConcurrency } from '../runs/shared/runWithConcurrency.ts';\nimport {\n isPiRuntime,\n resolveRuntimeLaunch,\n resolveRuntimeTable,\n type RuntimeTable,\n} from '../runs/shared/runtimeRegistry.ts';\nimport { PI_RUNTIME_NAME } from '../env.ts';\nimport { selectAvailableModel, type AvailableModelInfo, type ParentModel } from '../runs/shared/modelFallback.ts';\nimport type { ExtensionConfig } from './config.ts';\nimport { DoomTeamExpectedError } from '../shared/errors.ts';\n\nconst CONTEXT_FRESH = 'fresh' as const;\nconst PI_RUNTIME_REQUIREMENT = `runtime \"${PI_RUNTIME_NAME}\"`;\n\ntype SessionForkCaptureMode = 'tool' | 'settled';\n\nexport interface SessionForkSource {\n sessionFile: string;\n leafId: string;\n}\n\nexport type SessionForkSourceManager = Pick<SessionManager, 'getSessionFile' | 'getLeafId' | 'getLeafEntry'>;\n\nfunction readableSessionFile(sessionFile: string | undefined): sessionFile is string {\n if (!sessionFile?.trim()) return false;\n try {\n fs.accessSync(sessionFile, fs.constants.R_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Capture the parent branch while excluding an assistant turn whose tool is still executing. */\nexport function captureSessionForkSource(\n manager: SessionForkSourceManager,\n mode: SessionForkCaptureMode,\n): SessionForkSource | undefined {\n const sessionFile = manager.getSessionFile();\n if (!readableSessionFile(sessionFile)) return undefined;\n\n const leaf = manager.getLeafEntry();\n const leafId =\n mode === 'tool' && leaf?.type === 'message' && leaf.message.role === 'assistant'\n ? leaf.parentId\n : (leaf?.id ?? manager.getLeafId());\n return leafId ? { sessionFile, leafId } : undefined;\n}\n\nfunction isSessionForkSourceAvailable(source: SessionForkSource): boolean {\n return Boolean(source.leafId.trim()) && readableSessionFile(source.sessionFile);\n}\n\nexport interface SpawnPlanTaskInput {\n agent: string;\n inlineAgent?: InlineAgent;\n task?: string;\n cwd?: string;\n model?: string;\n runtime?: string;\n context?: typeof CONTEXT_FRESH | 'fork';\n /**\n * An existing child transcript to continue instead of starting fresh.\n *\n * Set only by a restore. `sdkRunnerEntry.ts` opens it through\n * `SessionManager.open`, which is what makes a restored run pick up where it\n * was suspended rather than redo the task.\n */\n sessionFile?: string;\n}\n\ntype ExecutableAgentConfig = Pick<\n AgentConfig,\n | 'name'\n | 'defaultContext'\n | 'extensions'\n | 'fallbackModels'\n | 'inheritProjectContext'\n | 'inheritSkills'\n | 'mcpDirectTools'\n | 'model'\n | 'runtime'\n | 'skills'\n | 'skillPath'\n | 'subagentOnlyExtensions'\n | 'systemPrompt'\n | 'systemPromptMode'\n | 'thinking'\n | 'tools'\n>;\n\nfunction resolveEffectiveContext(\n taskInput: SpawnPlanTaskInput,\n agent: Pick<ExecutableAgentConfig, 'defaultContext'>,\n): typeof CONTEXT_FRESH | 'fork' {\n return taskInput.sessionFile ? CONTEXT_FRESH : (taskInput.context ?? agent.defaultContext ?? CONTEXT_FRESH);\n}\n\nexport interface SpawnPlanRequest {\n /** SINGLE mode: exactly one child. Mutually exclusive with `tasks`. */\n single?: SpawnPlanTaskInput;\n /** PARALLEL mode: N children, fanned out. Mutually exclusive with `single`. */\n tasks?: SpawnPlanTaskInput[];\n /** Max children in flight at once for PARALLEL mode. Ignored for SINGLE. Defaults to `config.parallel.concurrency` or 4. */\n concurrency?: number;\n /** Fallback cwd for any task that omits its own. */\n cwd: string;\n agentScope: AgentScope;\n /** Legacy session identity retained for delegation correlation. */\n parentSessionId?: string;\n /** Persisted parent transcript used for true Pi forks. */\n parentSessionFile?: string;\n /** Settled parent leaf used for true Pi forks. */\n parentLeafId?: string;\n artifacts?: boolean;\n /** Authenticated models reported by the live parent host. Undefined for callers without a host context. */\n availableModels?: AvailableModelInfo[];\n /** The live parent model, forwarded only for Pi child selection. */\n parentModel?: ParentModel;\n /** Overrides `resolveCurrentSubagentDepth()`'s own env read - a test seam, not a runtime path. */\n currentDepth?: number;\n /** Which runtime executes every child of this request. Defaults per agent, then to `pi`. */\n runtime?: string;\n /** Stable Pi tool-call identity used to correlate this batch. */\n operationId?: string;\n /** Run ids persisted by the operation journal before any process starts. */\n preallocatedRunIds?: string[];\n}\n\n/** Everything one child spawn needs. An object because this reached ten positional parameters. */\ninterface SpawnOneChildInput {\n runId: string;\n operationId?: string;\n agentConfig: ExecutableAgentConfig;\n excludeTools?: string[];\n capabilityCeiling?: ResolvedSubagentCapabilityCeiling;\n taskInput: SpawnPlanTaskInput;\n childIndex: number;\n fanout: boolean;\n fallbackCwd: string;\n parentSessionId: string | undefined;\n parentSessionFile: string | undefined;\n preparedSessionFile: string | undefined;\n handshakeTimeoutMs: number | undefined;\n artifacts: boolean | undefined;\n artifactDir: ExtensionConfig['artifactDir'];\n availableModels: AvailableModelInfo[] | undefined;\n parentModel: ParentModel | undefined;\n runtime: string | undefined;\n runtimes: RuntimeTable;\n}\n\nexport interface SpawnPlanChildOutcome {\n agent: string;\n task: string;\n /** This spawn's position among its siblings. Always 0 for SINGLE mode. */\n childIndex: number;\n runId?: string;\n pid?: number;\n error?: string;\n warning?: string;\n}\n\nexport interface SpawnPlanResult {\n outcomes: SpawnPlanChildOutcome[];\n}\n\nconst DEFAULT_PARALLEL_CONCURRENCY = 4;\n/**\n * Hard ceiling on how many children one PARALLEL call may launch.\n *\n * `concurrency` does NOT bound this, and cannot: `spawnOneChild` resolves as\n * soon as its child confirms it started, and the child then runs detached. So\n * `runWithConcurrency` throttles how fast children are STARTED, not how many\n * are running - `{tasks: [8], concurrency: 4}` ends up with eight live model\n * processes, not four. Until a launch queue exists that drains as runs go\n * terminal, a width cap is the only thing standing between a fan-out and the\n * machine. 8 matches the sibling implementation's `PI_TEAM_MATE_MAX_PARALLEL`.\n */\nconst DEFAULT_PARALLEL_MAX_TASKS = 8;\nconst INLINE_AGENT_TOOLS = ['read', 'grep', 'find', 'ls'] as const;\n\nfunction appendPromptSection(prompt: string, section: string): string {\n if (!section) return prompt;\n return prompt ? `${prompt}\\n\\n${section}` : section;\n}\n\nfunction bestEffortRuntimeWarnings(\n runtime: string,\n agentConfig: ExecutableAgentConfig,\n excludeTools: string[] | undefined,\n): string[] {\n if (isPiRuntime(runtime)) return [];\n\n const warnings = [`Runtime '${runtime}' does not load Pi child extensions or hooks; launched best effort.`];\n const unsupportedResources = [\n ...(agentConfig.tools !== undefined || agentConfig.mcpDirectTools?.length ? ['tools'] : []),\n ...(agentConfig.skills?.length || agentConfig.skillPath?.length ? ['skills'] : []),\n ...(agentConfig.extensions !== undefined || agentConfig.subagentOnlyExtensions?.length ? ['extensions'] : []),\n ];\n if (unsupportedResources.length > 0) {\n warnings.push(\n `Doom Team cannot project or enforce configured Pi ${unsupportedResources.join(', ')} on runtime '${runtime}'.`,\n );\n }\n if (agentConfig.skills?.length) {\n warnings.push(`Configured skills were not injected: ${agentConfig.skills.join(', ')}.`);\n }\n if (excludeTools?.length) {\n warnings.push(\n `Runtime '${runtime}' cannot enforce layer subagent tool exclusions; launched best effort for: ${excludeTools.join(', ')}.`,\n );\n }\n return warnings;\n}\n\ninterface ChildSkillProjection {\n systemPrompt: string;\n requireReadTool: boolean;\n warnings: string[];\n}\n\ninterface ResolvedModelSelection {\n primaryModel: string | undefined;\n fallbackModels: string[];\n model: string | undefined;\n}\n\nfunction resolvedModelSelection(\n taskInput: SpawnPlanTaskInput,\n agentConfig: Pick<ExecutableAgentConfig, 'model' | 'fallbackModels'>,\n runtime: string,\n parentModel: ParentModel | undefined,\n availableModels: AvailableModelInfo[] | undefined,\n): ResolvedModelSelection {\n const parentModelId =\n isPiRuntime(runtime) && parentModel && availableModels !== undefined\n ? `${parentModel.provider}/${parentModel.id}`\n : undefined;\n const ordered = isPiRuntime(runtime)\n ? [taskInput.model, parentModelId, agentConfig.model, ...(agentConfig.fallbackModels ?? [])]\n : [taskInput.model ?? agentConfig.model, ...(agentConfig.fallbackModels ?? [])];\n const candidates = ordered.filter((candidate): candidate is string => Boolean(candidate?.trim()));\n const [primaryModel, ...fallbackModels] = candidates;\n return {\n primaryModel,\n fallbackModels,\n model: selectAvailableModel(primaryModel, fallbackModels, availableModels),\n };\n}\n\nexport interface ISpawnPlanner {\n /**\n * Resolves the plan and spawns every child. Throws on any PREFLIGHT\n * failure (bad request shape, depth exceeded, unknown agent) before\n * anything spawns. Never throws for an individual child's spawn failure\n * once the batch has started - that is a `{error}` outcome instead.\n */\n spawn(request: SpawnPlanRequest, config: ExtensionConfig): Promise<SpawnPlanResult>;\n}\n\nconst ERROR_CODE_AGENT_NOT_FOUND = 'agent_not_found' as const;\nconst ERROR_CODE_INVALID_REQUEST = 'invalid_request' as const;\nconst ERROR_CODE_MODEL_UNAVAILABLE = 'model_unavailable' as const;\nconst ERROR_CODE_OPERATION_CONFLICT = 'operation_conflict' as const;\nconst ERROR_CODE_RUNTIME_UNAVAILABLE = 'runtime_unavailable' as const;\nconst ERROR_CODE_UNSUPPORTED_CONTEXT = 'unsupported_context' as const;\nconst ERROR_CODE_UNSUPPORTED_OPERATION = 'unsupported_operation' as const;\n\n@injectable()\nexport class SpawnPlanner implements ISpawnPlanner {\n constructor(\n @inject(DOOM_TEAM_TYPES.AgentDiscoveryService) private readonly agents: IAgentDiscoveryService,\n @inject(DOOM_TEAM_TYPES.AsyncSubagentSpawner) private readonly spawner: IAsyncSubagentSpawner,\n @inject(DOOM_TEAM_TYPES.SubagentCapabilityPolicyStore)\n private readonly policies: SubagentCapabilityPolicyStore = new SubagentCapabilityPolicyStore(),\n @inject(DOOM_TEAM_TYPES.SkillDiscoveryService)\n private readonly skills: ISkillDiscoveryService = new SkillDiscoveryService(),\n ) {}\n\n protected generateRunId(): string {\n return crypto.randomUUID();\n }\n\n protected createForkSessionFile(source: SessionForkSource, cwd: string): string {\n const sessionManager = SessionManager.open(source.sessionFile, undefined, cwd);\n const sessionFile = sessionManager.createBranchedSession(source.leafId);\n if (!sessionFile) throw new Error(`Could not create a branched Pi session from '${source.sessionFile}'.`);\n\n // Pi defers writing user-only branches until an assistant response. A tool-safe\n // fork usually ends at the user message immediately before the active tool call,\n // so materialize that valid child transcript before the runner opens it.\n if (!fs.existsSync(sessionFile)) {\n const header = sessionManager.getHeader();\n if (!header) throw new Error(`Forked Pi session '${sessionFile}' has no header.`);\n const records = [header, ...sessionManager.getEntries()];\n fs.writeFileSync(sessionFile, `${records.map((record) => JSON.stringify(record)).join('\\n')}\\n`, { flag: 'wx' });\n }\n return sessionFile;\n }\n\n protected removePreparedSessionFile(sessionFile: string): void {\n fs.rmSync(sessionFile, { force: true });\n }\n\n protected validateCwd(cwd: string): void {\n let stat: fs.Stats;\n try {\n stat = fs.statSync(cwd);\n } catch {\n throw new DoomTeamExpectedError(\n ERROR_CODE_INVALID_REQUEST,\n `Working directory '${cwd}' does not exist.`,\n false,\n 'Retry with an existing directory.',\n );\n }\n if (!stat.isDirectory()) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_INVALID_REQUEST,\n `Working directory '${cwd}' is not a directory.`,\n false,\n 'Retry with an existing directory.',\n );\n }\n }\n\n protected resolveLayerExcludeTools(): string[] | undefined {\n return resolveActiveLayerSubagentConfig()?.config.excludeTools;\n }\n\n protected executableAvailable(command: string): boolean {\n if (path.isAbsolute(command) || command.includes(path.sep)) {\n try {\n fs.accessSync(command, fs.constants.X_OK);\n return true;\n } catch {\n return false;\n }\n }\n return (process.env.PATH ?? '')\n .split(path.delimiter)\n .filter(Boolean)\n .some((directory) => {\n try {\n fs.accessSync(path.join(directory, command), fs.constants.X_OK);\n return true;\n } catch {\n return false;\n }\n });\n }\n\n private resolveTaskList(request: SpawnPlanRequest): SpawnPlanTaskInput[] {\n const hasSingle = request.single !== undefined;\n const hasTasks = request.tasks !== undefined;\n if (hasSingle === hasTasks) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_INVALID_REQUEST,\n 'A run requires exactly one of internal single or tasks representations.',\n false,\n 'Submit a non-empty requests array.',\n );\n }\n if (hasSingle) return [request.single!];\n if (!request.tasks || request.tasks.length === 0) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_INVALID_REQUEST,\n 'A run requires at least one entry in its requests collection.',\n false,\n 'Submit a non-empty requests array.',\n );\n }\n return request.tasks;\n }\n\n private resolveAgentOrThrow(name: string, cwd: string, scope: AgentScope) {\n const resolved = this.agents.find(cwd, scope, name);\n if (!resolved) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_AGENT_NOT_FOUND,\n `Unknown agent '${name}'.`,\n false,\n 'Call subagent({\"action\":\"agents\"}) and retry with an exact name.',\n );\n }\n return resolved;\n }\n\n private resolveExecutableAgent(taskInput: SpawnPlanTaskInput, cwd: string, scope: AgentScope): ExecutableAgentConfig {\n if (!taskInput.inlineAgent) return this.resolveAgentOrThrow(taskInput.agent, cwd, scope);\n return {\n name: taskInput.agent.trim(),\n systemPromptMode: 'append',\n inheritProjectContext: true,\n inheritSkills: false,\n systemPrompt: taskInput.inlineAgent.systemPrompt.trim(),\n tools: [...INLINE_AGENT_TOOLS],\n defaultContext: CONTEXT_FRESH,\n runtime: PI_RUNTIME_NAME,\n };\n }\n\n private projectConfiguredSkills(\n agentConfig: ExecutableAgentConfig,\n childCwd: string,\n requestCwd: string,\n runtime: string,\n ): ChildSkillProjection {\n if (!isPiRuntime(runtime) || !agentConfig.skills?.length) {\n return { systemPrompt: agentConfig.systemPrompt, requireReadTool: false, warnings: [] };\n }\n\n const resolution = this.skills.resolveSkillsWithFallback(\n agentConfig.skills,\n childCwd,\n requestCwd,\n agentConfig.skillPath,\n requestCwd,\n );\n const injection = buildSkillInjection(resolution.resolved);\n return {\n systemPrompt: appendPromptSection(agentConfig.systemPrompt, injection),\n requireReadTool: injection.length > 0,\n warnings:\n resolution.missing.length > 0\n ? [\n `Agent '${agentConfig.name}' could not resolve configured skills: ${resolution.missing.join(', ')}; launched with resolved skills only.`,\n ]\n : [],\n };\n }\n\n /**\n * Spawns exactly one child and returns its outcome. Shared by `spawn()`\n * (SINGLE/PARALLEL) and `spawnChain()`'s per-step/per-parallel-group-child\n * calls, so the `AsyncSubagentSpawnInput` mapping exists in exactly one\n * place. Never throws - a spawn failure becomes an `{error}` outcome, per\n * the \"preflight throws, per-child failure does not\" split documented in\n * the module header.\n */\n private async spawnOneChild(input: SpawnOneChildInput): Promise<SpawnPlanChildOutcome> {\n const {\n runId,\n operationId,\n agentConfig,\n capabilityCeiling,\n excludeTools,\n taskInput,\n childIndex,\n fanout,\n fallbackCwd,\n parentSessionId,\n parentSessionFile,\n preparedSessionFile,\n handshakeTimeoutMs,\n artifacts,\n artifactDir,\n availableModels,\n parentModel,\n runtime,\n runtimes,\n } = input;\n const cwd = taskInput.cwd ?? fallbackCwd;\n const task = taskInput.task ?? '';\n const effectiveContext = resolveEffectiveContext(taskInput, agentConfig);\n const effectiveRuntime = taskInput.runtime ?? runtime ?? agentConfig.runtime ?? PI_RUNTIME_NAME;\n const modelSelection = resolvedModelSelection(\n taskInput,\n agentConfig,\n effectiveRuntime,\n parentModel,\n availableModels,\n );\n if (modelSelection.primaryModel && availableModels !== undefined && !modelSelection.model) {\n return {\n agent: agentConfig.name,\n task,\n childIndex,\n error: `No authenticated model is available for '${agentConfig.name}'. Checked: ${[\n modelSelection.primaryModel,\n ...modelSelection.fallbackModels,\n ].join(', ')}.`,\n };\n }\n\n let skillProjection: ChildSkillProjection;\n try {\n skillProjection = this.projectConfiguredSkills(agentConfig, cwd, fallbackCwd, effectiveRuntime);\n } catch (error) {\n return {\n agent: agentConfig.name,\n task,\n childIndex,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n const warnings = [\n ...skillProjection.warnings,\n ...bestEffortRuntimeWarnings(effectiveRuntime, agentConfig, excludeTools),\n ];\n const warning = warnings.length > 0 ? warnings.join(' ') : undefined;\n\n // Persist every Pi child's own transcript so a later explicit restore can\n // continue it. External runtimes retain their existing session behavior.\n const spawnInput: AsyncSubagentSpawnInput = {\n runId,\n ...(operationId ? { operationId } : {}),\n agent: agentConfig.name,\n ...(taskInput.inlineAgent ? { inlineAgent: taskInput.inlineAgent } : {}),\n task,\n cwd,\n childIndex,\n fanout,\n ...(parentSessionFile ? { parentSessionFile } : {}),\n piArgs: {\n baseArgs: [],\n sessionEnabled: isPiRuntime(effectiveRuntime),\n ...(taskInput.sessionFile\n ? { sessionFile: taskInput.sessionFile }\n : preparedSessionFile\n ? { sessionFile: preparedSessionFile }\n : {}),\n inheritProjectContext: agentConfig.inheritProjectContext,\n inheritSkills: agentConfig.inheritSkills,\n systemPromptMode: agentConfig.systemPromptMode,\n systemPrompt: skillProjection.systemPrompt,\n requireReadTool: skillProjection.requireReadTool,\n model: modelSelection.model,\n thinking: agentConfig.thinking,\n tools: agentConfig.tools,\n extensions: agentConfig.extensions,\n subagentOnlyExtensions: agentConfig.subagentOnlyExtensions,\n mcpDirectTools: agentConfig.mcpDirectTools,\n excludeTools,\n capabilityCeiling,\n cwd,\n ...(effectiveContext === 'fork' && parentSessionId ? { parentSessionId } : {}),\n },\n ...(handshakeTimeoutMs !== undefined ? { handshakeTimeoutMs } : {}),\n ...(artifacts !== undefined ? { artifacts } : {}),\n ...(artifactDir !== undefined ? { artifactDir } : {}),\n // Per-call `runtime` wins over the agent's own default, matching how\n // `model` and `context` already resolve.\n runtime: effectiveRuntime,\n runtimes,\n };\n\n try {\n const result: AsyncSubagentSpawnResult = await this.spawner.spawn(spawnInput);\n return {\n agent: agentConfig.name,\n task,\n childIndex,\n runId: result.runId,\n pid: result.pid,\n ...(warning ? { warning } : {}),\n };\n } catch (error) {\n return {\n agent: agentConfig.name,\n task,\n childIndex,\n error: error instanceof Error ? error.message : String(error),\n ...(warning ? { warning } : {}),\n };\n }\n }\n\n async spawn(request: SpawnPlanRequest, config: ExtensionConfig): Promise<SpawnPlanResult> {\n const tasks = this.resolveTaskList(request);\n const fanout = tasks.length > 1;\n const layerExcludeTools = this.resolveLayerExcludeTools();\n const capabilityCeiling = this.policies.resolve();\n\n // PREFLIGHT - all before any spawn call, so a declared plan that cannot\n // run at all produces one refusal, not a partial fan-out.\n const currentDepth = request.currentDepth ?? resolveCurrentSubagentDepth();\n const depthCheck = preflightSubagentDepth(currentDepth, config);\n if (depthCheck.error) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_UNSUPPORTED_OPERATION,\n depthCheck.error,\n false,\n 'Give each child a self-contained task within the selected layer policy.',\n );\n }\n\n const maxTasks = config.parallel?.maxTasks ?? DEFAULT_PARALLEL_MAX_TASKS;\n if (tasks.length > maxTasks) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_INVALID_REQUEST,\n `Run requested ${tasks.length} tasks, but at most ${maxTasks} may run at once. Concurrency throttles how fast they start, not how many run.`,\n false,\n 'Split the requests into smaller explicit run calls.',\n );\n }\n\n for (const taskInput of tasks) {\n if (!taskInput.task?.trim()) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_INVALID_REQUEST,\n `Run request for '${taskInput.agent}' requires a nonblank task.`,\n false,\n 'Provide a self-contained nonblank task.',\n );\n }\n if (taskInput.inlineAgent && !taskInput.inlineAgent.systemPrompt.trim()) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_INVALID_REQUEST,\n `Inline agent '${taskInput.agent}' requires a nonblank system prompt.`,\n false,\n 'Provide a focused read-only exploration role.',\n );\n }\n }\n\n const resolvedAgents = tasks.map((taskInput) =>\n this.resolveExecutableAgent(taskInput, taskInput.cwd ?? request.cwd, request.agentScope),\n );\n for (const [index, taskInput] of tasks.entries()) {\n const effectiveContext = resolveEffectiveContext(taskInput, resolvedAgents[index]!);\n const runtime = taskInput.runtime ?? request.runtime ?? resolvedAgents[index]!.runtime ?? PI_RUNTIME_NAME;\n if (effectiveContext === 'fork') {\n if (!isPiRuntime(runtime)) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_UNSUPPORTED_CONTEXT,\n `Fork context requires ${PI_RUNTIME_REQUIREMENT} for '${taskInput.agent}'.`,\n false,\n 'Use a Pi agent for fork context or explicitly request a fresh run.',\n );\n }\n const source =\n request.parentSessionFile && request.parentLeafId\n ? { sessionFile: request.parentSessionFile, leafId: request.parentLeafId }\n : undefined;\n if (!source || !isSessionForkSourceAvailable(source)) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_UNSUPPORTED_CONTEXT,\n `Fork context is unavailable for '${taskInput.agent}': the parent Pi session has no readable source.`,\n false,\n 'Use an active persisted Pi session or explicitly request a fresh run.',\n );\n }\n }\n }\n\n if (request.preallocatedRunIds && request.preallocatedRunIds.length !== tasks.length) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_OPERATION_CONFLICT,\n 'The operation journal run-id count does not match the request count.',\n false,\n 'Submit the run as a new tool call.',\n );\n }\n const runIds = request.preallocatedRunIds ?? tasks.map(() => this.generateRunId());\n const runtimes = resolveRuntimeTable(config.runtimes);\n for (const [index, taskInput] of tasks.entries()) {\n const agent = resolvedAgents[index]!;\n const cwd = taskInput.cwd ?? request.cwd;\n this.validateCwd(cwd);\n const runtime = taskInput.runtime ?? request.runtime ?? agent.runtime ?? PI_RUNTIME_NAME;\n const modelSelection = resolvedModelSelection(\n taskInput,\n agent,\n runtime,\n request.parentModel,\n request.availableModels,\n );\n if (modelSelection.primaryModel && request.availableModels !== undefined && !modelSelection.model) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_MODEL_UNAVAILABLE,\n `No authenticated model is available for '${agent.name}'.`,\n false,\n 'Authenticate the requested model or choose an available model.',\n );\n }\n if (taskInput.inlineAgent && !isPiRuntime(runtime)) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_UNSUPPORTED_OPERATION,\n `Inline agent '${taskInput.agent}' requires ${PI_RUNTIME_REQUIREMENT} to enforce its read-only tools.`,\n false,\n 'Remove the runtime override or use a discovered external-runtime agent without inlineAgent.',\n );\n }\n if (capabilityCeiling && !isPiRuntime(runtime)) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_UNSUPPORTED_OPERATION,\n `Runtime '${runtime}' cannot enforce the active capability ceiling.`,\n false,\n `Use ${PI_RUNTIME_REQUIREMENT} while plan mode or another capability ceiling is active.`,\n );\n }\n if (!isPiRuntime(runtime)) {\n let command: string;\n try {\n command = resolveRuntimeLaunch(runtime, runtimes, { prompt: taskInput.task ?? '', cwd }).command;\n } catch (error) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_RUNTIME_UNAVAILABLE,\n error instanceof Error ? error.message : String(error),\n false,\n `Configure a valid external runtime or use ${PI_RUNTIME_REQUIREMENT}.`,\n );\n }\n if (!this.executableAvailable(command)) {\n throw new DoomTeamExpectedError(\n ERROR_CODE_RUNTIME_UNAVAILABLE,\n `Executable '${command}' for runtime '${runtime}' is unavailable.`,\n false,\n `Install the executable, configure its absolute path, or use ${PI_RUNTIME_REQUIREMENT}.`,\n );\n }\n }\n }\n const forkSource =\n request.parentSessionFile && request.parentLeafId\n ? { sessionFile: request.parentSessionFile, leafId: request.parentLeafId }\n : undefined;\n const preparedSessionFiles: Array<string | undefined> = [];\n try {\n for (const [index, taskInput] of tasks.entries()) {\n preparedSessionFiles.push(\n resolveEffectiveContext(taskInput, resolvedAgents[index]!) === 'fork'\n ? this.createForkSessionFile(forkSource!, taskInput.cwd ?? request.cwd)\n : undefined,\n );\n }\n } catch (error) {\n for (const sessionFile of preparedSessionFiles) {\n if (sessionFile) this.removePreparedSessionFile(sessionFile);\n }\n throw new DoomTeamExpectedError(\n ERROR_CODE_UNSUPPORTED_CONTEXT,\n error instanceof Error ? error.message : String(error),\n false,\n 'Retry from an active persisted Pi session or explicitly request a fresh run.',\n );\n }\n\n const concurrency = fanout\n ? (request.concurrency ?? config.parallel?.concurrency ?? DEFAULT_PARALLEL_CONCURRENCY)\n : 1;\n\n const factories = tasks.map(\n (taskInput, childIndex) => () =>\n this.spawnOneChild({\n runId: runIds[childIndex]!,\n operationId: request.operationId,\n agentConfig: resolvedAgents[childIndex]!,\n excludeTools: layerExcludeTools,\n capabilityCeiling,\n taskInput,\n childIndex,\n fanout,\n fallbackCwd: request.cwd,\n parentSessionId: request.parentSessionId,\n parentSessionFile: request.parentSessionFile,\n preparedSessionFile: preparedSessionFiles[childIndex],\n handshakeTimeoutMs: config.handshakeTimeoutMs,\n artifacts: request.artifacts,\n artifactDir: config.artifactDir,\n availableModels: request.availableModels,\n parentModel: request.parentModel,\n runtime: request.runtime,\n runtimes,\n }),\n );\n\n const settled = await runWithConcurrency(factories, concurrency);\n // `spawnOneChild` never rejects (it catches its own spawn failure into\n // an `{error}` outcome), so `runWithConcurrency` never sees a rejection\n // here - this unwrap is defensive, not a real branch.\n const outcomes = settled.map((outcome, index) =>\n outcome.status === 'fulfilled'\n ? outcome.value\n : {\n agent: resolvedAgents[index]!.name,\n task: tasks[index]!.task ?? '',\n childIndex: index,\n error: outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason),\n },\n );\n\n return { outcomes };\n }\n}\n"],"mappings":"+hDA4FA,SAAS,EAAoB,EAAwD,CACnF,GAAI,CAAC,GAAa,MAAM,CAAE,MAAO,GACjC,GAAI,CAEF,OADA,EAAG,WAAW,EAAa,EAAG,UAAU,KAAK,CACtC,QACD,CACN,MAAO,IAKX,SAAgB,EACd,EACA,EAC+B,CAC/B,IAAM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,EAAO,YACpB,gBAAiB,EAAQ,gBACzB,YAAa,EAAQ,YACrB,QAAS,EAAQ,QACjB,WACD,CAAC,CAG4C,CAAE,EAAY,EAIvC,KAAK,EAAS,IACrC,EAAQ,SAAW,YACf,EAAQ,MACR,CACE,MAAO,EAAe,GAAQ,KAC9B,KAAM,EAAM,GAAQ,MAAQ,GAC5B,WAAY,EACZ,MAAO,EAAQ,kBAAkB,MAAQ,EAAQ,OAAO,QAAU,OAAO,EAAQ,OAAO,CACzF,CAGU,CAAE,QAngBtB,GAAY,KAGR,EAAO,EAAgB,sBAAsB,CAAA,KAC7C,EAAO,EAAgB,qBAAqB,CAAA,KAC5C,EAAO,EAAgB,8BAA8B,CAAA,KAErD,EAAO,EAAgB,sBAAsB,CAAA"}
@@ -0,0 +1,2 @@
1
+ const e=require(`../extension.cjs`);function t(t){e.activateDoomTeamExtension(t,{doomIntegrations:!1})}exports.activateStandardTeamExtension=t;
2
+ //# sourceMappingURL=standard.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"standard.cjs","names":[],"sources":["../../src/extensions/standard.ts"],"sourcesContent":["import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\n\nimport { activateDoomTeamExtension } from '../extension.ts';\n\n/** Standard Pi composition, with Doom-only leader contributions disabled. */\nexport function activateStandardTeamExtension(pi: ExtensionAPI): void {\n activateDoomTeamExtension(pi, { doomIntegrations: false });\n}\n"],"mappings":"oCAKA,SAAgB,EAA8B,EAAwB,CACpE,EAAA,0BAA0B,EAAI,CAAE,iBAAkB,GAAO,CAAC"}
@@ -0,0 +1,8 @@
1
+ import { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+
3
+ //#region src/extensions/standard.d.ts
4
+ /** Standard Pi composition, with Doom-only leader contributions disabled. */
5
+ declare function activateStandardTeamExtension(pi: ExtensionAPI): void;
6
+ //#endregion
7
+ export { activateStandardTeamExtension };
8
+ //# sourceMappingURL=standard.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"standard.d.cts","names":[],"sources":["../../src/extensions/standard.ts"],"mappings":";;;;iBAKgB,6BAAA,CAA8B,EAAA,EAAI,YAAA"}
@@ -0,0 +1,8 @@
1
+ import { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+
3
+ //#region src/extensions/standard.d.ts
4
+ /** Standard Pi composition, with Doom-only leader contributions disabled. */
5
+ declare function activateStandardTeamExtension(pi: ExtensionAPI): void;
6
+ //#endregion
7
+ export { activateStandardTeamExtension };
8
+ //# sourceMappingURL=standard.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"standard.d.mts","names":[],"sources":["../../src/extensions/standard.ts"],"mappings":";;;;iBAKgB,6BAAA,CAA8B,EAAA,EAAI,YAAA"}
@@ -0,0 +1,2 @@
1
+ import{activateDoomTeamExtension as e}from"../extension.mjs";function t(t){e(t,{doomIntegrations:!1})}export{t as activateStandardTeamExtension};
2
+ //# sourceMappingURL=standard.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"standard.mjs","names":[],"sources":["../../src/extensions/standard.ts"],"sourcesContent":["import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\n\nimport { activateDoomTeamExtension } from '../extension.ts';\n\n/** Standard Pi composition, with Doom-only leader contributions disabled. */\nexport function activateStandardTeamExtension(pi: ExtensionAPI): void {\n activateDoomTeamExtension(pi, { doomIntegrations: false });\n}\n"],"mappings":"6DAKA,SAAgB,EAA8B,EAAwB,CACpE,EAA0B,EAAI,CAAE,iBAAkB,GAAO,CAAC"}
@@ -0,0 +1,7 @@
1
+ const e=require(`../runs/registry/suspendedRuns.cjs`),t=require(`../shared/formatters.cjs`),n=require(`../tui/fleetTranscript.cjs`);function r(e,n){return e.startedAt?t.formatDuration(Math.max(0,n-e.startedAt)):`unknown`}function i(t,n=Date.now(),i=[]){if(t.length===0&&i.length===0)return`No runs tracked in this session. A run appears here once it has been launched from this session.`;let a=[`${t.length} active run${t.length===1?``:`s`}:`];for(let e of t){let t=[`- ${e.runId}`,e.status??`starting`,r(e,n)];e.activityState&&t.push(e.activityState),e.attentionReason&&t.push(e.attentionReason),e.error&&t.push(`error: ${e.error}`),a.push(t.join(` · `))}if(i.length>0){a.push(``,`${i.length} suspended run${i.length===1?``:`s`}:`);for(let t of i){let n=e.isSuspendedRunResumable(t)?`restore with { action: "restore", id: "${t.runId}" }`:`not resumable; submit a new explicit run`;a.push(`- ${t.runId} (${t.agent}, ${t.runtime}): ${n}`)}}return t.length>0&&(a.push(``),a.push(`Inspect one with { action: "status", id: "<run id>", transcriptLines: 80 }.`)),a.join(`
2
+ `)}function a(e){if(e.kind===`tool`){let t=e.status===`running`?`…`:e.status===`error`?`error`:`ok`,n=e.args?JSON.stringify(e.args):e.text,r=`[tool ${t}] ${e.name??`tool`}${n?` ${n}`:``}`,i=e.result?.trimEnd();if(!i)return r;let a=i.split(`
3
+ `),o=a.slice(0,5),s=a.length-o.length;return[r,...o.map(e=>` ${e}`),s>0?` … +${s} lines`:void 0].filter(e=>e!==void 0).join(`
4
+ `)}return`[${e.kind}] ${e.text}`}function o(e,t){let r=e?.transcriptPath;if(!r)return e?`This run has no transcript. Artifacts were disabled for it (artifacts: false), so nothing was recorded.`:`No status found for this run, so there is no transcript to read.`;let i=n.readFleetTranscript(r);if(i.warning)return`Transcript at '${r}' could not be read: ${i.warning}`;if(i.events.length===0)return`Transcript at '${r}' is empty. The run has not written anything yet.`;let o=i.events.flatMap(e=>a(e).split(`
5
+ `)),s=o.slice(-t),c=o.length-s.length;return[c>0?`Last ${s.length} of ${o.length} transcript lines (${c} earlier line(s) not shown):`:`Transcript (${s.length} line(s)):`,``,...s].join(`
6
+ `)}exports.formatFleetView=i,exports.formatRunTranscript=o;
7
+ //# sourceMappingURL=statusViews.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"statusViews.cjs","names":["formatDuration","isSuspendedRunResumable","readFleetTranscript"],"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":"oIA2CA,SAAS,EAAI,EAAsB,EAAqB,CACtD,OAAO,EAAI,UAAYA,EAAAA,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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CAEf,MAAO,IAAI,EAAM,KAAK,IAAI,EAAM,OAWlC,SAAgB,EAAoB,EAAoC,EAA0B,CAChG,IAAM,EAAiB,GAAQ,eAC/B,GAAI,CAAC,EACH,OAAO,EACH,0GACA,mEAGN,IAAM,EAAaC,EAAAA,oBAAoB,EAAe,CACtD,GAAI,EAAW,QACb,MAAO,kBAAkB,EAAe,uBAAuB,EAAW,UAE5E,GAAI,EAAW,OAAO,SAAW,EAC/B,MAAO,kBAAkB,EAAe,mDAG1C,IAAM,EAAW,EAAW,OAAO,QAAS,GAAU,EAAY,EAAM,CAAC,MAAM;EAAK,CAAC,CAC/E,EAAO,EAAS,MAAM,CAAC,EAAS,CAChC,EAAU,EAAS,OAAS,EAAK,OAKvC,MAAO,CAHL,EAAU,EACN,QAAQ,EAAK,OAAO,MAAM,EAAS,OAAO,qBAAqB,EAAQ,8BACvE,eAAe,EAAK,OAAO,YACjB,GAAI,GAAG,EAAK,CAAC,KAAK;EAAK"}
@@ -0,0 +1,7 @@
1
+ import{__esmMin as e}from"../_virtual/_rolldown/runtime.mjs";import{init_suspendedRuns as t,isSuspendedRunResumable as n}from"../runs/registry/suspendedRuns.mjs";import{formatDuration as r,init_formatters as i}from"../shared/formatters.mjs";import{init_fleetTranscript as a,readFleetTranscript as o}from"../tui/fleetTranscript.mjs";function s(e,t){return e.startedAt?r(Math.max(0,t-e.startedAt)):`unknown`}function c(e,t=Date.now(),r=[]){if(e.length===0&&r.length===0)return`No runs tracked in this session. A run appears here once it has been launched from this session.`;let i=[`${e.length} active run${e.length===1?``:`s`}:`];for(let n of e){let e=[`- ${n.runId}`,n.status??`starting`,s(n,t)];n.activityState&&e.push(n.activityState),n.attentionReason&&e.push(n.attentionReason),n.error&&e.push(`error: ${n.error}`),i.push(e.join(` · `))}if(r.length>0){i.push(``,`${r.length} suspended run${r.length===1?``:`s`}:`);for(let e of r){let t=n(e)?`restore with { action: "restore", id: "${e.runId}" }`:`not resumable; submit a new explicit run`;i.push(`- ${e.runId} (${e.agent}, ${e.runtime}): ${t}`)}}return e.length>0&&(i.push(``),i.push(`Inspect one with { action: "status", id: "<run id>", transcriptLines: 80 }.`)),i.join(`
2
+ `)}function l(e){if(e.kind===`tool`){let t=e.status===`running`?`…`:e.status===`error`?`error`:`ok`,n=e.args?JSON.stringify(e.args):e.text,r=`[tool ${t}] ${e.name??`tool`}${n?` ${n}`:``}`,i=e.result?.trimEnd();if(!i)return r;let a=i.split(`
3
+ `),o=a.slice(0,d),s=a.length-o.length;return[r,...o.map(e=>` ${e}`),s>0?` … +${s} lines`:void 0].filter(e=>e!==void 0).join(`
4
+ `)}return`[${e.kind}] ${e.text}`}function u(e,t){let n=e?.transcriptPath;if(!n)return e?`This run has no transcript. Artifacts were disabled for it (artifacts: false), so nothing was recorded.`:`No status found for this run, so there is no transcript to read.`;let r=o(n);if(r.warning)return`Transcript at '${n}' could not be read: ${r.warning}`;if(r.events.length===0)return`Transcript at '${n}' is empty. The run has not written anything yet.`;let i=r.events.flatMap(e=>l(e).split(`
5
+ `)),a=i.slice(-t),s=i.length-a.length;return[s>0?`Last ${a.length} of ${i.length} transcript lines (${s} earlier line(s) not shown):`:`Transcript (${a.length} line(s)):`,``,...a].join(`
6
+ `)}var d,f=e((()=>{t(),a(),i(),d=5}));f();export{c as formatFleetView,u as formatRunTranscript,f as init_statusViews};
7
+ //# sourceMappingURL=statusViews.mjs.map