@agimon-ai/doompi-task 0.0.1-alpha.8 → 0.0.1-alpha.80

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 (576) hide show
  1. package/README.md +123 -15
  2. package/dist/_virtual/_rolldown/runtime.cjs +23 -1
  3. package/dist/api-contracts.cjs +7 -0
  4. package/dist/api-contracts.d.cts +2 -0
  5. package/dist/api-contracts.d.mts +2 -0
  6. package/dist/api-contracts.mjs +2 -0
  7. package/dist/commands.cjs +4 -2
  8. package/dist/commands.d.cts +2 -14
  9. package/dist/commands.d.mts +2 -14
  10. package/dist/commands.mjs +2 -2
  11. package/dist/config.cjs +19 -2
  12. package/dist/config.d.cts +2 -38
  13. package/dist/config.d.mts +2 -38
  14. package/dist/config.mjs +2 -2
  15. package/dist/delegation-manager.cjs +10 -0
  16. package/dist/delegation-manager.d.cts +3 -0
  17. package/dist/delegation-manager.d.mts +3 -0
  18. package/dist/delegation-manager.mjs +3 -0
  19. package/dist/extensions/mcp.cjs +1866 -0
  20. package/dist/extensions/mcp.cjs.map +1 -0
  21. package/dist/extensions/mcp.d.cts +5 -0
  22. package/dist/extensions/mcp.d.cts.map +1 -0
  23. package/dist/extensions/mcp.d.mts +5 -0
  24. package/dist/extensions/mcp.d.mts.map +1 -0
  25. package/dist/extensions/mcp.mjs +1836 -0
  26. package/dist/extensions/mcp.mjs.map +1 -0
  27. package/dist/extensions/pi.cjs +49 -1
  28. package/dist/extensions/pi.cjs.map +1 -1
  29. package/dist/extensions/pi.d.cts +5 -2
  30. package/dist/extensions/pi.d.cts.map +1 -0
  31. package/dist/extensions/pi.d.mts +5 -2
  32. package/dist/extensions/pi.d.mts.map +1 -0
  33. package/dist/extensions/pi.mjs +44 -1
  34. package/dist/extensions/pi.mjs.map +1 -1
  35. package/dist/extensions/server.cjs +57 -0
  36. package/dist/extensions/server.cjs.map +1 -0
  37. package/dist/extensions/server.d.cts +5 -0
  38. package/dist/extensions/server.d.cts.map +1 -0
  39. package/dist/extensions/server.d.mts +5 -0
  40. package/dist/extensions/server.d.mts.map +1 -0
  41. package/dist/extensions/server.mjs +52 -0
  42. package/dist/extensions/server.mjs.map +1 -0
  43. package/dist/extensions/web.mjs +1013 -0
  44. package/dist/extensions/web.mjs.map +1 -0
  45. package/dist/index.cjs +106 -1
  46. package/dist/index.d.cts +16 -15
  47. package/dist/index.d.mts +16 -15
  48. package/dist/index.mjs +16 -1
  49. package/dist/logSinkTelemetry.cjs +6 -2
  50. package/dist/logSinkTelemetry.d.cts +3 -51
  51. package/dist/logSinkTelemetry.d.mts +3 -51
  52. package/dist/logSinkTelemetry.mjs +3 -2
  53. package/dist/src/constants/promptGuidelines.cjs +26 -0
  54. package/dist/src/constants/promptGuidelines.cjs.map +1 -0
  55. package/dist/src/constants/promptGuidelines.d.cts +13 -0
  56. package/dist/src/constants/promptGuidelines.d.cts.map +1 -0
  57. package/dist/src/constants/promptGuidelines.d.mts +13 -0
  58. package/dist/src/constants/promptGuidelines.d.mts.map +1 -0
  59. package/dist/src/constants/promptGuidelines.mjs +26 -0
  60. package/dist/src/constants/promptGuidelines.mjs.map +1 -0
  61. package/dist/src/constants/task.cjs +6 -0
  62. package/dist/src/constants/task.cjs.map +1 -0
  63. package/dist/src/constants/task.d.cts +4 -0
  64. package/dist/src/constants/task.d.cts.map +1 -0
  65. package/dist/src/constants/task.d.mts +4 -0
  66. package/dist/src/constants/task.d.mts.map +1 -0
  67. package/dist/src/constants/task.mjs +6 -0
  68. package/dist/src/constants/task.mjs.map +1 -0
  69. package/dist/src/extensions/(backend)/channel/_lib/task-graph.cjs +90 -0
  70. package/dist/src/extensions/(backend)/channel/_lib/task-graph.cjs.map +1 -0
  71. package/dist/src/extensions/(backend)/channel/_lib/task-graph.mjs +89 -0
  72. package/dist/src/extensions/(backend)/channel/_lib/task-graph.mjs.map +1 -0
  73. package/dist/src/extensions/(backend)/channel/task-graph.server.cjs +7 -0
  74. package/dist/src/extensions/(backend)/channel/task-graph.server.cjs.map +1 -0
  75. package/dist/src/extensions/(backend)/channel/task-graph.server.mjs +8 -0
  76. package/dist/src/extensions/(backend)/channel/task-graph.server.mjs.map +1 -0
  77. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.cjs +317 -0
  78. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.cjs.map +1 -0
  79. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.d.cts +39 -0
  80. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.d.cts.map +1 -0
  81. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.d.mts +39 -0
  82. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.d.mts.map +1 -0
  83. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.mjs +317 -0
  84. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.mjs.map +1 -0
  85. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.server.cjs +95 -0
  86. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.server.cjs.map +1 -0
  87. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.server.mjs +95 -0
  88. package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.server.mjs.map +1 -0
  89. package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.cli.cjs +30 -0
  90. package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.cli.cjs.map +1 -0
  91. package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.cli.d.cts +20 -0
  92. package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.cli.d.cts.map +1 -0
  93. package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.cli.d.mts +20 -0
  94. package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.cli.d.mts.map +1 -0
  95. package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.cli.mjs +29 -0
  96. package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.cli.mjs.map +1 -0
  97. package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.server.cjs +19 -0
  98. package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.server.cjs.map +1 -0
  99. package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.server.mjs +19 -0
  100. package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.server.mjs.map +1 -0
  101. package/dist/src/extensions/workspaces/sessions/(backend)/command/tasks.cli.cjs +8 -0
  102. package/dist/src/extensions/workspaces/sessions/(backend)/command/tasks.cli.cjs.map +1 -0
  103. package/dist/src/extensions/workspaces/sessions/(backend)/command/tasks.cli.mjs +9 -0
  104. package/dist/src/extensions/workspaces/sessions/(backend)/command/tasks.cli.mjs.map +1 -0
  105. package/dist/src/extensions/workspaces/sessions/(backend)/command/tasks.server.cjs +7 -0
  106. package/dist/src/extensions/workspaces/sessions/(backend)/command/tasks.server.cjs.map +1 -0
  107. package/dist/src/extensions/workspaces/sessions/(backend)/command/tasks.server.mjs +8 -0
  108. package/dist/src/extensions/workspaces/sessions/(backend)/command/tasks.server.mjs.map +1 -0
  109. package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-compact.cli.cjs +6 -0
  110. package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-compact.cli.cjs.map +1 -0
  111. package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-compact.cli.mjs +6 -0
  112. package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-compact.cli.mjs.map +1 -0
  113. package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-start.cli.cjs +6 -0
  114. package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-start.cli.cjs.map +1 -0
  115. package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-start.cli.mjs +6 -0
  116. package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-start.cli.mjs.map +1 -0
  117. package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-tree.cli.cjs +6 -0
  118. package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-tree.cli.cjs.map +1 -0
  119. package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-tree.cli.mjs +6 -0
  120. package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-tree.cli.mjs.map +1 -0
  121. package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/tool-execution-end.cli.cjs +6 -0
  122. package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/tool-execution-end.cli.cjs.map +1 -0
  123. package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/tool-execution-end.cli.mjs +6 -0
  124. package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/tool-execution-end.cli.mjs.map +1 -0
  125. package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-compact.cli.cjs +7 -0
  126. package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-compact.cli.cjs.map +1 -0
  127. package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-compact.cli.mjs +8 -0
  128. package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-compact.cli.mjs.map +1 -0
  129. package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-start.cli.cjs +7 -0
  130. package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-start.cli.cjs.map +1 -0
  131. package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-start.cli.mjs +8 -0
  132. package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-start.cli.mjs.map +1 -0
  133. package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-tree.cli.cjs +7 -0
  134. package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-tree.cli.cjs.map +1 -0
  135. package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-tree.cli.mjs +8 -0
  136. package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-tree.cli.mjs.map +1 -0
  137. package/dist/src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.cli.cjs +7 -0
  138. package/dist/src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.cli.cjs.map +1 -0
  139. package/dist/src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.cli.mjs +8 -0
  140. package/dist/src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.cli.mjs.map +1 -0
  141. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/task-board.server.cjs +20 -0
  142. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/task-board.server.cjs.map +1 -0
  143. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/task-board.server.mjs +20 -0
  144. package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/task-board.server.mjs.map +1 -0
  145. package/dist/src/extensions/workspaces/sessions/(backend)/resource/task-board.server.cjs +7 -0
  146. package/dist/src/extensions/workspaces/sessions/(backend)/resource/task-board.server.cjs.map +1 -0
  147. package/dist/src/extensions/workspaces/sessions/(backend)/resource/task-board.server.mjs +8 -0
  148. package/dist/src/extensions/workspaces/sessions/(backend)/resource/task-board.server.mjs.map +1 -0
  149. package/dist/src/extensions/workspaces/sessions/(backend)/root.cli.cjs +11 -0
  150. package/dist/src/extensions/workspaces/sessions/(backend)/root.cli.cjs.map +1 -0
  151. package/dist/src/extensions/workspaces/sessions/(backend)/root.cli.mjs +12 -0
  152. package/dist/src/extensions/workspaces/sessions/(backend)/root.cli.mjs.map +1 -0
  153. package/dist/src/extensions/workspaces/sessions/(backend)/root.server.cjs +7 -0
  154. package/dist/src/extensions/workspaces/sessions/(backend)/root.server.cjs.map +1 -0
  155. package/dist/src/extensions/workspaces/sessions/(backend)/root.server.mjs +8 -0
  156. package/dist/src/extensions/workspaces/sessions/(backend)/root.server.mjs.map +1 -0
  157. package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.cli.cjs +160 -0
  158. package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.cli.cjs.map +1 -0
  159. package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.cli.d.cts +25 -0
  160. package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.cli.d.cts.map +1 -0
  161. package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.cli.d.mts +25 -0
  162. package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.cli.d.mts.map +1 -0
  163. package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.cli.mjs +157 -0
  164. package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.cli.mjs.map +1 -0
  165. package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.server.cjs +7 -0
  166. package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.server.cjs.map +1 -0
  167. package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.server.mjs +8 -0
  168. package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.server.mjs.map +1 -0
  169. package/dist/src/extensions/workspaces/sessions/(backend)/tool/task.cli.cjs +7 -0
  170. package/dist/src/extensions/workspaces/sessions/(backend)/tool/task.cli.cjs.map +1 -0
  171. package/dist/src/extensions/workspaces/sessions/(backend)/tool/task.cli.mjs +8 -0
  172. package/dist/src/extensions/workspaces/sessions/(backend)/tool/task.cli.mjs.map +1 -0
  173. package/dist/src/extensions/workspaces/sessions/(backend)/tool/task.server.cjs +7 -0
  174. package/dist/src/extensions/workspaces/sessions/(backend)/tool/task.server.cjs.map +1 -0
  175. package/dist/src/extensions/workspaces/sessions/(backend)/tool/task.server.mjs +8 -0
  176. package/dist/src/extensions/workspaces/sessions/(backend)/tool/task.server.mjs.map +1 -0
  177. package/dist/src/extensions/workspaces/sessions/(frontend)/_shared/format.cli.cjs +333 -0
  178. package/dist/src/extensions/workspaces/sessions/(frontend)/_shared/format.cli.cjs.map +1 -0
  179. package/dist/src/extensions/workspaces/sessions/(frontend)/_shared/format.cli.d.cts +61 -0
  180. package/dist/src/extensions/workspaces/sessions/(frontend)/_shared/format.cli.d.cts.map +1 -0
  181. package/dist/src/extensions/workspaces/sessions/(frontend)/_shared/format.cli.d.mts +61 -0
  182. package/dist/src/extensions/workspaces/sessions/(frontend)/_shared/format.cli.d.mts.map +1 -0
  183. package/dist/src/extensions/workspaces/sessions/(frontend)/_shared/format.cli.mjs +322 -0
  184. package/dist/src/extensions/workspaces/sessions/(frontend)/_shared/format.cli.mjs.map +1 -0
  185. package/dist/src/extensions/workspaces/sessions/(frontend)/message/doom-task-notify.cli.cjs +9 -0
  186. package/dist/src/extensions/workspaces/sessions/(frontend)/message/doom-task-notify.cli.cjs.map +1 -0
  187. package/dist/src/extensions/workspaces/sessions/(frontend)/message/doom-task-notify.cli.mjs +9 -0
  188. package/dist/src/extensions/workspaces/sessions/(frontend)/message/doom-task-notify.cli.mjs.map +1 -0
  189. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/selectors.cjs +149 -0
  190. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/selectors.cjs.map +1 -0
  191. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/selectors.d.cts +59 -0
  192. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/selectors.d.cts.map +1 -0
  193. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/selectors.d.mts +59 -0
  194. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/selectors.d.mts.map +1 -0
  195. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/selectors.mjs +142 -0
  196. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/selectors.mjs.map +1 -0
  197. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/task-space.cli.cjs +358 -0
  198. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/task-space.cli.cjs.map +1 -0
  199. package/dist/{tui/taskSpace.d.cts → src/extensions/workspaces/sessions/(frontend)/overlay/_lib/task-space.cli.d.cts} +12 -12
  200. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/task-space.cli.d.cts.map +1 -0
  201. package/dist/{tui/taskSpace.d.mts → src/extensions/workspaces/sessions/(frontend)/overlay/_lib/task-space.cli.d.mts} +12 -12
  202. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/task-space.cli.d.mts.map +1 -0
  203. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/task-space.cli.mjs +355 -0
  204. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/task-space.cli.mjs.map +1 -0
  205. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/taskOverlay.cjs +165 -0
  206. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/taskOverlay.cjs.map +1 -0
  207. package/dist/{tui → src/extensions/workspaces/sessions/(frontend)/overlay/_lib}/taskOverlay.d.cts +8 -7
  208. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/taskOverlay.d.cts.map +1 -0
  209. package/dist/{tui → src/extensions/workspaces/sessions/(frontend)/overlay/_lib}/taskOverlay.d.mts +8 -7
  210. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/taskOverlay.d.mts.map +1 -0
  211. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/taskOverlay.mjs +164 -0
  212. package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/taskOverlay.mjs.map +1 -0
  213. package/dist/src/extensions/workspaces/sessions/(frontend)/tool/_lib/task.cli.cjs +13 -0
  214. package/dist/src/extensions/workspaces/sessions/(frontend)/tool/_lib/task.cli.cjs.map +1 -0
  215. package/dist/src/extensions/workspaces/sessions/(frontend)/tool/_lib/task.cli.mjs +13 -0
  216. package/dist/src/extensions/workspaces/sessions/(frontend)/tool/_lib/task.cli.mjs.map +1 -0
  217. package/dist/src/extensions/workspaces/sessions/(frontend)/tool/task.cli.cjs +7 -0
  218. package/dist/src/extensions/workspaces/sessions/(frontend)/tool/task.cli.cjs.map +1 -0
  219. package/dist/src/extensions/workspaces/sessions/(frontend)/tool/task.cli.mjs +8 -0
  220. package/dist/src/extensions/workspaces/sessions/(frontend)/tool/task.cli.mjs.map +1 -0
  221. package/dist/src/models/task.cjs +29 -0
  222. package/dist/src/models/task.cjs.map +1 -0
  223. package/dist/{store/types.d.cts → src/models/task.d.cts} +52 -31
  224. package/dist/src/models/task.d.cts.map +1 -0
  225. package/dist/{store/types.d.mts → src/models/task.d.mts} +52 -31
  226. package/dist/src/models/task.d.mts.map +1 -0
  227. package/dist/src/models/task.mjs +26 -0
  228. package/dist/src/models/task.mjs.map +1 -0
  229. package/dist/src/models/taskGraph.cjs +67 -0
  230. package/dist/{store → src/models}/taskGraph.cjs.map +1 -1
  231. package/dist/{store → src/models}/taskGraph.d.cts +7 -8
  232. package/dist/src/models/taskGraph.d.cts.map +1 -0
  233. package/dist/{store → src/models}/taskGraph.d.mts +7 -8
  234. package/dist/src/models/taskGraph.d.mts.map +1 -0
  235. package/dist/src/models/taskGraph.mjs +63 -0
  236. package/dist/{store → src/models}/taskGraph.mjs.map +1 -1
  237. package/dist/src/schemas/apiContracts.cjs +51 -0
  238. package/dist/src/schemas/apiContracts.cjs.map +1 -0
  239. package/dist/src/schemas/apiContracts.d.cts +53 -0
  240. package/dist/src/schemas/apiContracts.d.cts.map +1 -0
  241. package/dist/src/schemas/apiContracts.d.mts +53 -0
  242. package/dist/src/schemas/apiContracts.d.mts.map +1 -0
  243. package/dist/src/schemas/apiContracts.mjs +49 -0
  244. package/dist/src/schemas/apiContracts.mjs.map +1 -0
  245. package/dist/src/schemas/task.cjs +130 -0
  246. package/dist/src/schemas/task.cjs.map +1 -0
  247. package/dist/{tool/schema.d.cts → src/schemas/task.d.cts} +46 -29
  248. package/dist/src/schemas/task.d.cts.map +1 -0
  249. package/dist/{tool/schema.d.mts → src/schemas/task.d.mts} +46 -29
  250. package/dist/src/schemas/task.d.mts.map +1 -0
  251. package/dist/src/schemas/task.mjs +117 -0
  252. package/dist/src/schemas/task.mjs.map +1 -0
  253. package/dist/src/services/config/index.cjs +88 -0
  254. package/dist/src/services/config/index.cjs.map +1 -0
  255. package/dist/src/services/config/index.d.cts +42 -0
  256. package/dist/src/services/config/index.d.cts.map +1 -0
  257. package/dist/src/services/config/index.d.mts +42 -0
  258. package/dist/src/services/config/index.d.mts.map +1 -0
  259. package/dist/src/services/config/index.mjs +72 -0
  260. package/dist/src/services/config/index.mjs.map +1 -0
  261. package/dist/src/services/contextContribution/index.cjs +51 -0
  262. package/dist/src/services/contextContribution/index.cjs.map +1 -0
  263. package/dist/src/services/contextContribution/index.mjs +46 -0
  264. package/dist/src/services/contextContribution/index.mjs.map +1 -0
  265. package/dist/src/services/delegation/index.cjs +629 -0
  266. package/dist/src/services/delegation/index.cjs.map +1 -0
  267. package/dist/{delegation/manager.d.cts → src/services/delegation/index.d.cts} +52 -49
  268. package/dist/src/services/delegation/index.d.cts.map +1 -0
  269. package/dist/{delegation/manager.d.mts → src/services/delegation/index.d.mts} +52 -49
  270. package/dist/src/services/delegation/index.d.mts.map +1 -0
  271. package/dist/src/services/delegation/index.mjs +623 -0
  272. package/dist/src/services/delegation/index.mjs.map +1 -0
  273. package/dist/src/services/delegationPlatform/index.cjs +23 -0
  274. package/dist/src/services/delegationPlatform/index.cjs.map +1 -0
  275. package/dist/src/services/delegationPlatform/index.mjs +21 -0
  276. package/dist/src/services/delegationPlatform/index.mjs.map +1 -0
  277. package/dist/src/services/invariants/index.cjs +64 -0
  278. package/dist/src/services/invariants/index.cjs.map +1 -0
  279. package/dist/src/services/invariants/index.d.cts +23 -0
  280. package/dist/src/services/invariants/index.d.cts.map +1 -0
  281. package/dist/src/services/invariants/index.d.mts +23 -0
  282. package/dist/src/services/invariants/index.d.mts.map +1 -0
  283. package/dist/src/services/invariants/index.mjs +62 -0
  284. package/dist/src/services/invariants/index.mjs.map +1 -0
  285. package/dist/src/services/logSinkTelemetry/index.cjs +43 -0
  286. package/dist/src/services/logSinkTelemetry/index.cjs.map +1 -0
  287. package/dist/src/services/logSinkTelemetry/index.d.cts +23 -0
  288. package/dist/src/services/logSinkTelemetry/index.d.cts.map +1 -0
  289. package/dist/src/services/logSinkTelemetry/index.d.mts +23 -0
  290. package/dist/src/services/logSinkTelemetry/index.d.mts.map +1 -0
  291. package/dist/src/services/logSinkTelemetry/index.mjs +41 -0
  292. package/dist/src/services/logSinkTelemetry/index.mjs.map +1 -0
  293. package/dist/src/services/paths/index.cjs +233 -0
  294. package/dist/src/services/paths/index.cjs.map +1 -0
  295. package/dist/src/services/paths/index.d.cts +25 -0
  296. package/dist/src/services/paths/index.d.cts.map +1 -0
  297. package/dist/src/services/paths/index.d.mts +25 -0
  298. package/dist/src/services/paths/index.d.mts.map +1 -0
  299. package/dist/src/services/paths/index.mjs +218 -0
  300. package/dist/src/services/paths/index.mjs.map +1 -0
  301. package/dist/src/services/processLiveness/index.cjs +20 -0
  302. package/dist/src/services/processLiveness/index.cjs.map +1 -0
  303. package/dist/{store/processLiveness.d.cts → src/services/processLiveness/index.d.cts} +3 -4
  304. package/dist/src/services/processLiveness/index.d.cts.map +1 -0
  305. package/dist/{store/processLiveness.d.mts → src/services/processLiveness/index.d.mts} +3 -4
  306. package/dist/src/services/processLiveness/index.d.mts.map +1 -0
  307. package/dist/src/services/processLiveness/index.mjs +20 -0
  308. package/dist/src/services/processLiveness/index.mjs.map +1 -0
  309. package/dist/src/services/reconcile/index.cjs +65 -0
  310. package/dist/src/services/reconcile/index.cjs.map +1 -0
  311. package/dist/{store/reconcile.d.cts → src/services/reconcile/index.d.cts} +8 -9
  312. package/dist/src/services/reconcile/index.d.cts.map +1 -0
  313. package/dist/{store/reconcile.d.mts → src/services/reconcile/index.d.mts} +8 -9
  314. package/dist/src/services/reconcile/index.d.mts.map +1 -0
  315. package/dist/src/services/reconcile/index.mjs +63 -0
  316. package/dist/src/services/reconcile/index.mjs.map +1 -0
  317. package/dist/src/services/reducer/index.cjs +350 -0
  318. package/dist/src/services/reducer/index.cjs.map +1 -0
  319. package/dist/{store/reducer.d.cts → src/services/reducer/index.d.cts} +12 -13
  320. package/dist/src/services/reducer/index.d.cts.map +1 -0
  321. package/dist/{store/reducer.d.mts → src/services/reducer/index.d.mts} +12 -13
  322. package/dist/src/services/reducer/index.d.mts.map +1 -0
  323. package/dist/src/services/reducer/index.mjs +345 -0
  324. package/dist/src/services/reducer/index.mjs.map +1 -0
  325. package/dist/src/services/taskNarration/index.cjs +32 -0
  326. package/dist/src/services/taskNarration/index.cjs.map +1 -0
  327. package/dist/src/services/taskNarration/index.mjs +32 -0
  328. package/dist/src/services/taskNarration/index.mjs.map +1 -0
  329. package/dist/src/services/taskResult/index.cjs +174 -0
  330. package/dist/src/services/taskResult/index.cjs.map +1 -0
  331. package/dist/src/services/taskResult/index.d.cts +50 -0
  332. package/dist/src/services/taskResult/index.d.cts.map +1 -0
  333. package/dist/src/services/taskResult/index.d.mts +50 -0
  334. package/dist/src/services/taskResult/index.d.mts.map +1 -0
  335. package/dist/src/services/taskResult/index.mjs +165 -0
  336. package/dist/src/services/taskResult/index.mjs.map +1 -0
  337. package/dist/src/services/taskStore/index.cjs +216 -0
  338. package/dist/src/services/taskStore/index.cjs.map +1 -0
  339. package/dist/{store/taskStore.d.cts → src/services/taskStore/index.d.cts} +17 -25
  340. package/dist/src/services/taskStore/index.d.cts.map +1 -0
  341. package/dist/{store/taskStore.d.mts → src/services/taskStore/index.d.mts} +17 -25
  342. package/dist/src/services/taskStore/index.d.mts.map +1 -0
  343. package/dist/src/services/taskStore/index.mjs +213 -0
  344. package/dist/src/services/taskStore/index.mjs.map +1 -0
  345. package/dist/src/services/taskTool/index.cjs +106 -0
  346. package/dist/src/services/taskTool/index.cjs.map +1 -0
  347. package/dist/src/services/taskTool/index.mjs +105 -0
  348. package/dist/src/services/taskTool/index.mjs.map +1 -0
  349. package/dist/src/types/delegation.cjs +7 -0
  350. package/dist/src/types/delegation.cjs.map +1 -0
  351. package/dist/src/types/delegation.d.cts +5 -0
  352. package/dist/src/types/delegation.d.cts.map +1 -0
  353. package/dist/src/types/delegation.d.mts +5 -0
  354. package/dist/src/types/delegation.d.mts.map +1 -0
  355. package/dist/src/types/delegation.mjs +7 -0
  356. package/dist/src/types/delegation.mjs.map +1 -0
  357. package/dist/src/types/telemetry.cjs +26 -0
  358. package/dist/src/types/telemetry.cjs.map +1 -0
  359. package/dist/src/types/telemetry.d.cts +35 -0
  360. package/dist/src/types/telemetry.d.cts.map +1 -0
  361. package/dist/src/types/telemetry.d.mts +35 -0
  362. package/dist/src/types/telemetry.d.mts.map +1 -0
  363. package/dist/src/types/telemetry.mjs +26 -0
  364. package/dist/src/types/telemetry.mjs.map +1 -0
  365. package/dist/src/types/webTasks.cjs +7 -0
  366. package/dist/src/types/webTasks.cjs.map +1 -0
  367. package/dist/src/types/webTasks.mjs +7 -0
  368. package/dist/src/types/webTasks.mjs.map +1 -0
  369. package/dist/store-invariants.cjs +5 -0
  370. package/dist/store-invariants.d.cts +2 -0
  371. package/dist/store-invariants.d.mts +2 -0
  372. package/dist/store-invariants.mjs +2 -0
  373. package/dist/store-paths.cjs +14 -0
  374. package/dist/store-paths.d.cts +2 -0
  375. package/dist/store-paths.d.mts +2 -0
  376. package/dist/store-paths.mjs +2 -0
  377. package/dist/store-process-liveness.cjs +3 -0
  378. package/dist/store-process-liveness.d.cts +2 -0
  379. package/dist/store-process-liveness.d.mts +2 -0
  380. package/dist/store-process-liveness.mjs +2 -0
  381. package/dist/store-reconcile.cjs +5 -0
  382. package/dist/store-reconcile.d.cts +2 -0
  383. package/dist/store-reconcile.d.mts +2 -0
  384. package/dist/store-reconcile.mjs +2 -0
  385. package/dist/store-reducer.cjs +8 -0
  386. package/dist/store-reducer.d.cts +2 -0
  387. package/dist/store-reducer.d.mts +2 -0
  388. package/dist/store-reducer.mjs +2 -0
  389. package/dist/store-task-graph.cjs +7 -0
  390. package/dist/store-task-graph.d.cts +2 -0
  391. package/dist/store-task-graph.d.mts +2 -0
  392. package/dist/store-task-graph.mjs +2 -0
  393. package/dist/store-task-store.cjs +3 -0
  394. package/dist/store-task-store.d.cts +2 -0
  395. package/dist/store-task-store.d.mts +2 -0
  396. package/dist/store-task-store.mjs +2 -0
  397. package/dist/store-types.cjs +6 -0
  398. package/dist/store-types.d.cts +2 -0
  399. package/dist/store-types.d.mts +2 -0
  400. package/dist/store-types.mjs +2 -0
  401. package/dist/tool-prompt-guidelines.cjs +3 -0
  402. package/dist/tool-prompt-guidelines.d.cts +2 -0
  403. package/dist/tool-prompt-guidelines.d.mts +2 -0
  404. package/dist/tool-prompt-guidelines.mjs +2 -0
  405. package/dist/tool-response-envelope.cjs +12 -0
  406. package/dist/tool-response-envelope.d.cts +2 -0
  407. package/dist/tool-response-envelope.d.mts +2 -0
  408. package/dist/tool-response-envelope.mjs +2 -0
  409. package/dist/tool-schema.cjs +17 -0
  410. package/dist/tool-schema.d.cts +3 -0
  411. package/dist/tool-schema.d.mts +3 -0
  412. package/dist/tool-schema.mjs +3 -0
  413. package/dist/tool-task-tool.cjs +6 -0
  414. package/dist/tool-task-tool.d.cts +3 -0
  415. package/dist/tool-task-tool.d.mts +3 -0
  416. package/dist/tool-task-tool.mjs +3 -0
  417. package/dist/tui-format.cjs +14 -0
  418. package/dist/tui-format.d.cts +2 -0
  419. package/dist/tui-format.d.mts +2 -0
  420. package/dist/tui-format.mjs +2 -0
  421. package/dist/tui-selectors.cjs +10 -0
  422. package/dist/tui-selectors.d.cts +2 -0
  423. package/dist/tui-selectors.d.mts +2 -0
  424. package/dist/tui-selectors.mjs +2 -0
  425. package/dist/tui-task-overlay.cjs +4 -0
  426. package/dist/tui-task-overlay.d.cts +2 -0
  427. package/dist/tui-task-overlay.d.mts +2 -0
  428. package/dist/tui-task-overlay.mjs +2 -0
  429. package/dist/tui-task-space.cjs +5 -0
  430. package/dist/tui-task-space.d.cts +2 -0
  431. package/dist/tui-task-space.d.mts +2 -0
  432. package/dist/tui-task-space.mjs +2 -0
  433. package/package.json +167 -109
  434. package/src/types/webTasks.ts +24 -0
  435. package/dist/commands.cjs.map +0 -1
  436. package/dist/commands.d.cts.map +0 -1
  437. package/dist/commands.d.mts.map +0 -1
  438. package/dist/commands.mjs.map +0 -1
  439. package/dist/config.cjs.map +0 -1
  440. package/dist/config.d.cts.map +0 -1
  441. package/dist/config.d.mts.map +0 -1
  442. package/dist/config.mjs.map +0 -1
  443. package/dist/delegation/manager.cjs +0 -6
  444. package/dist/delegation/manager.cjs.map +0 -1
  445. package/dist/delegation/manager.d.cts.map +0 -1
  446. package/dist/delegation/manager.d.mts.map +0 -1
  447. package/dist/delegation/manager.mjs +0 -6
  448. package/dist/delegation/manager.mjs.map +0 -1
  449. package/dist/extension.cjs +0 -3
  450. package/dist/extension.cjs.map +0 -1
  451. package/dist/extension.d.cts +0 -12
  452. package/dist/extension.d.cts.map +0 -1
  453. package/dist/extension.d.mts +0 -12
  454. package/dist/extension.d.mts.map +0 -1
  455. package/dist/extension.mjs +0 -3
  456. package/dist/extension.mjs.map +0 -1
  457. package/dist/extensions/doom.cjs +0 -2
  458. package/dist/extensions/doom.cjs.map +0 -1
  459. package/dist/extensions/doom.d.cts +0 -6
  460. package/dist/extensions/doom.d.cts.map +0 -1
  461. package/dist/extensions/doom.d.mts +0 -7
  462. package/dist/extensions/doom.d.mts.map +0 -1
  463. package/dist/extensions/doom.mjs +0 -2
  464. package/dist/extensions/doom.mjs.map +0 -1
  465. package/dist/logSinkTelemetry.cjs.map +0 -1
  466. package/dist/logSinkTelemetry.d.cts.map +0 -1
  467. package/dist/logSinkTelemetry.d.mts.map +0 -1
  468. package/dist/logSinkTelemetry.mjs.map +0 -1
  469. package/dist/store/invariants.cjs +0 -2
  470. package/dist/store/invariants.cjs.map +0 -1
  471. package/dist/store/invariants.d.cts +0 -14
  472. package/dist/store/invariants.d.cts.map +0 -1
  473. package/dist/store/invariants.d.mts +0 -14
  474. package/dist/store/invariants.d.mts.map +0 -1
  475. package/dist/store/invariants.mjs +0 -2
  476. package/dist/store/invariants.mjs.map +0 -1
  477. package/dist/store/paths.cjs +0 -2
  478. package/dist/store/paths.cjs.map +0 -1
  479. package/dist/store/paths.d.cts +0 -23
  480. package/dist/store/paths.d.cts.map +0 -1
  481. package/dist/store/paths.d.mts +0 -23
  482. package/dist/store/paths.d.mts.map +0 -1
  483. package/dist/store/paths.mjs +0 -2
  484. package/dist/store/paths.mjs.map +0 -1
  485. package/dist/store/processLiveness.cjs +0 -2
  486. package/dist/store/processLiveness.cjs.map +0 -1
  487. package/dist/store/processLiveness.d.cts.map +0 -1
  488. package/dist/store/processLiveness.d.mts.map +0 -1
  489. package/dist/store/processLiveness.mjs +0 -2
  490. package/dist/store/processLiveness.mjs.map +0 -1
  491. package/dist/store/reconcile.cjs +0 -2
  492. package/dist/store/reconcile.cjs.map +0 -1
  493. package/dist/store/reconcile.d.cts.map +0 -1
  494. package/dist/store/reconcile.d.mts.map +0 -1
  495. package/dist/store/reconcile.mjs +0 -2
  496. package/dist/store/reconcile.mjs.map +0 -1
  497. package/dist/store/reducer.cjs +0 -3
  498. package/dist/store/reducer.cjs.map +0 -1
  499. package/dist/store/reducer.d.cts.map +0 -1
  500. package/dist/store/reducer.d.mts.map +0 -1
  501. package/dist/store/reducer.mjs +0 -3
  502. package/dist/store/reducer.mjs.map +0 -1
  503. package/dist/store/taskGraph.cjs +0 -2
  504. package/dist/store/taskGraph.d.cts.map +0 -1
  505. package/dist/store/taskGraph.d.mts.map +0 -1
  506. package/dist/store/taskGraph.mjs +0 -2
  507. package/dist/store/taskStore.cjs +0 -2
  508. package/dist/store/taskStore.cjs.map +0 -1
  509. package/dist/store/taskStore.d.cts.map +0 -1
  510. package/dist/store/taskStore.d.mts.map +0 -1
  511. package/dist/store/taskStore.mjs +0 -2
  512. package/dist/store/taskStore.mjs.map +0 -1
  513. package/dist/store/types.cjs +0 -2
  514. package/dist/store/types.cjs.map +0 -1
  515. package/dist/store/types.d.cts.map +0 -1
  516. package/dist/store/types.d.mts.map +0 -1
  517. package/dist/store/types.mjs +0 -2
  518. package/dist/store/types.mjs.map +0 -1
  519. package/dist/tool/promptGuidelines.cjs +0 -2
  520. package/dist/tool/promptGuidelines.cjs.map +0 -1
  521. package/dist/tool/promptGuidelines.d.cts +0 -5
  522. package/dist/tool/promptGuidelines.d.cts.map +0 -1
  523. package/dist/tool/promptGuidelines.d.mts +0 -5
  524. package/dist/tool/promptGuidelines.d.mts.map +0 -1
  525. package/dist/tool/promptGuidelines.mjs +0 -2
  526. package/dist/tool/promptGuidelines.mjs.map +0 -1
  527. package/dist/tool/responseEnvelope.cjs +0 -6
  528. package/dist/tool/responseEnvelope.cjs.map +0 -1
  529. package/dist/tool/responseEnvelope.d.cts +0 -39
  530. package/dist/tool/responseEnvelope.d.cts.map +0 -1
  531. package/dist/tool/responseEnvelope.d.mts +0 -39
  532. package/dist/tool/responseEnvelope.d.mts.map +0 -1
  533. package/dist/tool/responseEnvelope.mjs +0 -6
  534. package/dist/tool/responseEnvelope.mjs.map +0 -1
  535. package/dist/tool/schema.cjs +0 -2
  536. package/dist/tool/schema.cjs.map +0 -1
  537. package/dist/tool/schema.d.cts.map +0 -1
  538. package/dist/tool/schema.d.mts.map +0 -1
  539. package/dist/tool/schema.mjs +0 -2
  540. package/dist/tool/schema.mjs.map +0 -1
  541. package/dist/tool/taskTool.cjs +0 -3
  542. package/dist/tool/taskTool.cjs.map +0 -1
  543. package/dist/tool/taskTool.d.cts +0 -17
  544. package/dist/tool/taskTool.d.cts.map +0 -1
  545. package/dist/tool/taskTool.d.mts +0 -17
  546. package/dist/tool/taskTool.d.mts.map +0 -1
  547. package/dist/tool/taskTool.mjs +0 -3
  548. package/dist/tool/taskTool.mjs.map +0 -1
  549. package/dist/tui/format.cjs +0 -4
  550. package/dist/tui/format.cjs.map +0 -1
  551. package/dist/tui/format.d.cts +0 -62
  552. package/dist/tui/format.d.cts.map +0 -1
  553. package/dist/tui/format.d.mts +0 -62
  554. package/dist/tui/format.d.mts.map +0 -1
  555. package/dist/tui/format.mjs +0 -4
  556. package/dist/tui/format.mjs.map +0 -1
  557. package/dist/tui/selectors.cjs +0 -2
  558. package/dist/tui/selectors.cjs.map +0 -1
  559. package/dist/tui/selectors.d.cts +0 -53
  560. package/dist/tui/selectors.d.cts.map +0 -1
  561. package/dist/tui/selectors.d.mts +0 -53
  562. package/dist/tui/selectors.d.mts.map +0 -1
  563. package/dist/tui/selectors.mjs +0 -2
  564. package/dist/tui/selectors.mjs.map +0 -1
  565. package/dist/tui/taskOverlay.cjs +0 -2
  566. package/dist/tui/taskOverlay.cjs.map +0 -1
  567. package/dist/tui/taskOverlay.d.cts.map +0 -1
  568. package/dist/tui/taskOverlay.d.mts.map +0 -1
  569. package/dist/tui/taskOverlay.mjs +0 -2
  570. package/dist/tui/taskOverlay.mjs.map +0 -1
  571. package/dist/tui/taskSpace.cjs +0 -5
  572. package/dist/tui/taskSpace.cjs.map +0 -1
  573. package/dist/tui/taskSpace.d.cts.map +0 -1
  574. package/dist/tui/taskSpace.d.mts.map +0 -1
  575. package/dist/tui/taskSpace.mjs +0 -5
  576. package/dist/tui/taskSpace.mjs.map +0 -1
@@ -0,0 +1,1866 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ //#region \0rolldown/runtime.js
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
+ key = keys[i];
15
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: ((k) => from[k]).bind(null, key),
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+ //#endregion
27
+ let _agimon_ai_doompi_core_mcp_facet = require("@agimon-ai/doompi-core/mcp-facet");
28
+ let _agimon_ai_doompi_core_delegation = require("@agimon-ai/doompi-core/delegation");
29
+ let node_crypto = require("node:crypto");
30
+ let node_path = require("node:path");
31
+ node_path = __toESM(node_path, 1);
32
+ let node_fs = require("node:fs");
33
+ node_fs = __toESM(node_fs, 1);
34
+ let node_os = require("node:os");
35
+ node_os = __toESM(node_os, 1);
36
+ let _agimon_ai_doompi_core_child_process = require("@agimon-ai/doompi-core/child-process");
37
+ let typebox_value = require("typebox/value");
38
+ let typebox = require("typebox");
39
+ //#region src/services/config/index.ts
40
+ const MAX_TASKS_ENV = "DOOM_TASK_MAX_TASKS";
41
+ const DELEGATION_TIMEOUT_MS_ENV = "DOOM_TASK_DELEGATION_TIMEOUT_MS";
42
+ /** Deliberately under the subagents auto-drain ceiling (30 min) so a headless
43
+ * session still gets the failure and a model turn before draining gives up. */
44
+ const DEFAULT_DELEGATION_TIMEOUT_MS = 12e5;
45
+ /** Maximum number of non-deleted tasks retained on one board. */
46
+ function getMaxTasks(env = process.env) {
47
+ const raw = Number(env[MAX_TASKS_ENV]);
48
+ return Number.isSafeInteger(raw) && raw > 0 ? raw : 15;
49
+ }
50
+ /** How long a delegated run may go without reporting a result. */
51
+ function getDelegationTimeoutMs(env = process.env) {
52
+ const raw = Number(env[DELEGATION_TIMEOUT_MS_ENV]);
53
+ return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_DELEGATION_TIMEOUT_MS;
54
+ }
55
+ //#endregion
56
+ //#region src/models/taskGraph.ts
57
+ const COMPLETED_STATUS = "completed";
58
+ const DELETED_STATUS$2 = "deleted";
59
+ /** True when a non-empty list has no visible work left to finish. */
60
+ function isTaskListComplete(taskList) {
61
+ const visible = taskList.filter((task) => task.status !== DELETED_STATUS$2);
62
+ return visible.length > 0 && visible.every((task) => task.status === COMPLETED_STATUS);
63
+ }
64
+ /**
65
+ * Would merging `newBlockedBy` into `taskId`'s dependencies introduce a cycle?
66
+ *
67
+ * Takes the proposed additions explicitly so the reducer can ask the question
68
+ * before mutating anything.
69
+ */
70
+ function detectCycle(taskList, taskId, newBlockedBy) {
71
+ const edges = /* @__PURE__ */ new Map();
72
+ for (const task of taskList) if (task.id === taskId) edges.set(task.id, [.../* @__PURE__ */ new Set([...task.blockedBy ?? [], ...newBlockedBy])]);
73
+ else edges.set(task.id, task.blockedBy ? [...task.blockedBy] : []);
74
+ const visiting = /* @__PURE__ */ new Set();
75
+ const visited = /* @__PURE__ */ new Set();
76
+ const hasCycleFrom = (node) => {
77
+ if (visiting.has(node)) return true;
78
+ if (visited.has(node)) return false;
79
+ visiting.add(node);
80
+ for (const next of edges.get(node) ?? []) if (hasCycleFrom(next)) return true;
81
+ visiting.delete(node);
82
+ visited.add(node);
83
+ return false;
84
+ };
85
+ for (const node of edges.keys()) if (hasCycleFrom(node)) return true;
86
+ return false;
87
+ }
88
+ /** Inverse adjacency: for each task, which tasks list it in their blockedBy. */
89
+ function deriveBlocks(taskList) {
90
+ const blocks = /* @__PURE__ */ new Map();
91
+ for (const task of taskList) for (const dep of task.blockedBy ?? []) {
92
+ const dependents = blocks.get(dep) ?? [];
93
+ dependents.push(task.id);
94
+ blocks.set(dep, dependents);
95
+ }
96
+ return blocks;
97
+ }
98
+ /**
99
+ * Blocking dependencies of a task that are not yet resolved.
100
+ *
101
+ * `completed` clears a dependency; `failed` deliberately does not, so a failed
102
+ * delegation keeps its dependents blocked instead of silently releasing work
103
+ * that was never actually finished.
104
+ */
105
+ function unresolvedBlockers(taskList, task) {
106
+ return (task.blockedBy ?? []).filter((dep) => {
107
+ const blocker = taskList.find((candidate) => candidate.id === dep);
108
+ if (!blocker) return false;
109
+ return blocker.status !== COMPLETED_STATUS && blocker.status !== DELETED_STATUS$2;
110
+ });
111
+ }
112
+ function isBlocked(taskList, task) {
113
+ return unresolvedBlockers(taskList, task).length > 0;
114
+ }
115
+ //#endregion
116
+ //#region src/types/telemetry.ts
117
+ const TASK_EVENT = {
118
+ notificationFailed: "doom_task.notification_failed",
119
+ storeReadFailed: "doom_task.store_read_failed",
120
+ storeLockTimeout: "doom_task.store_lock_timeout",
121
+ storeLockBreakFailed: "doom_task.store_lock_break_failed",
122
+ storeWatchFailed: "doom_task.store_watch_failed",
123
+ storeListenerFailed: "doom_task.store_listener_failed",
124
+ storeCommitListenerFailed: "doom_task.store_commit_listener_failed",
125
+ storeSweepFailed: "doom_task.store_sweep_failed",
126
+ sessionStartFailed: "doom_task.session_start_failed",
127
+ sessionStartDegraded: "doom_task.session_start_degraded",
128
+ toolFailed: "doom_task.tool_failed",
129
+ delegationRequestFailed: "doom_task.delegation_request_failed",
130
+ delegationStartFailed: "doom_task.delegation_start_failed",
131
+ delegationResponseFailed: "doom_task.delegation_response_failed",
132
+ delegationSettleFailed: "doom_task.delegation_settle_failed",
133
+ delegationTimedOut: "doom_task.delegation_timed_out",
134
+ delegationOrphaned: "doom_task.delegation_orphaned",
135
+ delegationAssigned: "doom_task.delegation_assigned",
136
+ delegationCompleted: "doom_task.delegation_completed"
137
+ };
138
+ //#endregion
139
+ //#region src/models/task.ts
140
+ const DELETED_STATUS$1 = "deleted";
141
+ function emptyDocument() {
142
+ return {
143
+ version: 1,
144
+ rev: 0,
145
+ nextId: 1,
146
+ tasks: []
147
+ };
148
+ }
149
+ /**
150
+ * A delegation is "live" while the owning run may still produce a response.
151
+ *
152
+ * Takes the delegation shape rather than `Task` so the cockpit's `WebTask`,
153
+ * which carries the state as a plain string, answers the question the same way
154
+ * the store does.
155
+ */
156
+ function isDelegationActive(task) {
157
+ const state = task.delegation?.state;
158
+ return state === "requested" || state === "running";
159
+ }
160
+ //#endregion
161
+ //#region src/services/processLiveness/index.ts
162
+ /**
163
+ * Is a process still running?
164
+ *
165
+ * Signal 0 performs the permission and existence check without delivering a
166
+ * signal. EPERM means the process exists but belongs to another user, which
167
+ * still counts as alive.
168
+ */
169
+ function isProcessAlive(pid) {
170
+ try {
171
+ process.kill(pid, 0);
172
+ return true;
173
+ } catch (error) {
174
+ return error.code === "EPERM";
175
+ }
176
+ }
177
+ //#endregion
178
+ //#region src/services/reconcile/index.ts
179
+ const ERR_ORPHANED_BY_RESTART = "Delegation orphaned by harness restart";
180
+ const ERR_ORPHANED_BY_SESSION = "Delegation orphaned by session restart";
181
+ /**
182
+ * Recover tasks that no longer have anyone able to finish them.
183
+ *
184
+ * A subagent run dies with the harness that spawned it, but the store file
185
+ * outlives both, so a crash leaves tasks stuck in `in_progress` forever. Two
186
+ * kinds of delegation qualify as dead:
187
+ *
188
+ * - the owning pid is gone, so nothing is left to report a result;
189
+ * - the owning pid is *this* process, yet the request is absent from the live
190
+ * set. Settling requires an in-memory record, so an in-process session
191
+ * restart (which clears that map without writing to the store) leaves rows
192
+ * nothing can ever resolve. Checking pid liveness alone misses these, because
193
+ * the pid is our own and very much alive.
194
+ *
195
+ * Delegations owned by a different, still-running pid belong to a parallel
196
+ * session and are left untouched.
197
+ */
198
+ function reconcileOrphanedDelegations(document, now = (/* @__PURE__ */ new Date()).toISOString(), isAlive = isProcessAlive, self) {
199
+ const orphaned = [];
200
+ const tasks = document.tasks.map((task) => {
201
+ if (!isDelegationActive(task)) return task;
202
+ const pid = task.delegation?.pid;
203
+ if (pid === void 0) return task;
204
+ const abandonedHere = self !== void 0 && pid === self.pid && !self.liveRequestIds.has(task.delegation.requestId);
205
+ if (!abandonedHere && isAlive(pid)) return task;
206
+ const recovered = {
207
+ ...task,
208
+ status: "pending",
209
+ updatedAt: now,
210
+ delegation: {
211
+ ...task.delegation,
212
+ state: "failed",
213
+ endedAt: now,
214
+ result: {
215
+ status: "failed",
216
+ error: abandonedHere ? ERR_ORPHANED_BY_SESSION : ERR_ORPHANED_BY_RESTART
217
+ }
218
+ }
219
+ };
220
+ orphaned.push(recovered);
221
+ return recovered;
222
+ });
223
+ if (orphaned.length === 0) return {
224
+ document,
225
+ orphaned
226
+ };
227
+ return {
228
+ document: {
229
+ ...document,
230
+ tasks
231
+ },
232
+ orphaned
233
+ };
234
+ }
235
+ //#endregion
236
+ //#region src/services/delegation/index.ts
237
+ const NOTIFY_CUSTOM_TYPE = "doom-task-notify";
238
+ const DEFAULT_STARTED_TIMEOUT_MS = 5e3;
239
+ const DEFAULT_RUN_TIMEOUT_MS = 12e5;
240
+ const DEFAULT_CANCEL_TIMEOUT_MS = 1e4;
241
+ const MAX_RUN_TIMEOUT_GRACE_MS = 6e4;
242
+ const MAX_STORED_OUTPUT = 4e3;
243
+ /**
244
+ * Cap on files rendered into a brief. Exported so the tool schema can state the
245
+ * same number to the model rather than restating it and drifting.
246
+ */
247
+ const MAX_BRIEF_NOTES = 1500;
248
+ const COMPLETED_STATE = "completed";
249
+ const FAILED_STATE = "failed";
250
+ const CANCELLED_STATE = "cancelled";
251
+ const TIMED_OUT_STATUS = "timed_out";
252
+ const DELETED_STATUS = "deleted";
253
+ const TASK_ID_ATTRIBUTE = "task.id";
254
+ const REQUEST_ID_ATTRIBUTE = "delegation.request_id";
255
+ const AGENT_ATTRIBUTE = "delegation.agent_name";
256
+ const PID_ATTRIBUTE = "delegation.pid";
257
+ const CONTEXT_PRESENT_ATTRIBUTE = "delegation.context_present";
258
+ const CONTEXT_FILE_COUNT_ATTRIBUTE = "delegation.context_file_count";
259
+ const CONTEXT_NOTES_LENGTH_ATTRIBUTE = "delegation.context_notes_length";
260
+ const BRIEF_LENGTH_ATTRIBUTE = "delegation.brief_length";
261
+ const TOOL_COUNT_ATTRIBUTE = "delegation.tool_count";
262
+ const DURATION_MS_ATTRIBUTE = "delegation.duration_ms";
263
+ const OUTCOME_ATTRIBUTE = "delegation.outcome";
264
+ const ERR_NO_RUNTIME = "No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.";
265
+ const ERR_CHILD_SESSION = "assign is only available in the main session. Update this task directly instead of re-delegating it.";
266
+ const ERR_CANCEL_UNACKNOWLEDGED = "Subagent did not acknowledge the cancel request";
267
+ function truncate(value, limit = MAX_STORED_OUTPUT) {
268
+ if (!value) return void 0;
269
+ return value.length <= limit ? value : `${value.slice(0, limit)}\n… (truncated)`;
270
+ }
271
+ function messageOf(error) {
272
+ return error instanceof Error ? error.message : String(error);
273
+ }
274
+ /** Normalize the parent context with host-owned path semantics. */
275
+ function briefContext(options, cwd, platform) {
276
+ const files = /* @__PURE__ */ new Set();
277
+ for (const entry of options.relevantFiles ?? []) {
278
+ if (files.size >= 12) break;
279
+ const normalized = platform.formatBriefPath(entry.trim(), cwd);
280
+ if (normalized && normalized !== ".") files.add(normalized);
281
+ }
282
+ return {
283
+ files: [...files],
284
+ notes: truncate(options.priorFindings?.trim(), MAX_BRIEF_NOTES)
285
+ };
286
+ }
287
+ /**
288
+ * Build the brief handed to the subagent.
289
+ *
290
+ * Doom Team owns the child tool surface and the parent owns the task record.
291
+ * Keeping those responsibilities explicit prevents a child from attempting to
292
+ * call a task tool that is not loaded in its runtime, while still giving it a
293
+ * reliable path to ask the parent for a decision.
294
+ *
295
+ * The context pack is the parent's verified discovery handed over. The whole
296
+ * block is omitted when nothing was supplied: this brief is the child's whole
297
+ * starting context, so an empty section header is pure token cost.
298
+ */
299
+ function buildBrief(task, instructions, context) {
300
+ const sections = [`Task #${task.id}: ${task.subject}`];
301
+ if (task.description) sections.push(task.description);
302
+ if (instructions) sections.push(instructions);
303
+ if (context.files.length > 0 || context.notes) {
304
+ const contextLines = ["Parent context — consume before repository discovery:"];
305
+ if (context.files.length > 0) contextLines.push(`- Parent-verified files (read these first with direct reads): ${context.files.join(", ")}`);
306
+ if (context.notes) contextLines.push(`- Established facts (do not re-derive unless direct evidence contradicts them): ${context.notes}`);
307
+ contextLines.push("This pack satisfies initial repository/context exploration. Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.");
308
+ sections.push(contextLines.join("\n"));
309
+ }
310
+ sections.push("Coordination: work directly without changing the task record; ask main through intercom only for blockers or decisions; report changed files and verification when done.");
311
+ return sections.join("\n\n");
312
+ }
313
+ /**
314
+ * Owns the lifecycle of tasks delegated to subagents.
315
+ *
316
+ * Delegation rides Team's injected Cordis service rather than spawning
317
+ * processes directly, so doom-task stays decoupled from the subagent runtime
318
+ * and degrades to a clear error when that service is not loaded.
319
+ *
320
+ * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so
321
+ * a delegation always has a deadline no matter which phase it is in. Losing
322
+ * that pairing is what previously left tasks running forever.
323
+ */
324
+ var DelegationManager = class DelegationManager {
325
+ options;
326
+ progress = /* @__PURE__ */ new Map();
327
+ pendingTasks = /* @__PURE__ */ new Map();
328
+ settlingRequests = /* @__PURE__ */ new Set();
329
+ timers = /* @__PURE__ */ new Map();
330
+ subscriptions = [];
331
+ service;
332
+ constructor(options) {
333
+ this.options = options;
334
+ }
335
+ now() {
336
+ return this.options.now?.() ?? (/* @__PURE__ */ new Date()).toISOString();
337
+ }
338
+ nowMs() {
339
+ return this.options.nowMs?.() ?? Date.now();
340
+ }
341
+ get runTimeoutMs() {
342
+ return this.options.runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;
343
+ }
344
+ report(event, error, attributes) {
345
+ this.options.report?.error(event, error, attributes);
346
+ }
347
+ /** True in a session that is itself a subagent child. */
348
+ get isChildSession() {
349
+ return Boolean(this.options.platform.environment.PI_SUBAGENT_CHILD);
350
+ }
351
+ /** Live progress for a task, for the overlay to render. */
352
+ progressFor(task) {
353
+ const requestId = task.delegation?.requestId;
354
+ return requestId ? this.progress.get(requestId) : void 0;
355
+ }
356
+ /** Displayed runtime duration, rebased from the latest child observation. */
357
+ static elapsedMs(progress, nowMs = Date.now()) {
358
+ const baseline = progress.durationMs ?? 0;
359
+ const observedAt = progress.durationObservedAt ?? nowMs;
360
+ return baseline + Math.max(0, nowMs - observedAt);
361
+ }
362
+ /** Rebind to the active Team service without stacking lifecycle listeners. */
363
+ bind(ctx, service) {
364
+ this.unbind();
365
+ this.service = service;
366
+ this.subscriptions.push(ctx.on(_agimon_ai_doompi_core_delegation.DOOM_DELEGATION_ACCEPTED_EVENT, (event) => {
367
+ this.handleAccepted(event);
368
+ }), ctx.on(_agimon_ai_doompi_core_delegation.DOOM_DELEGATION_STARTED_EVENT, (event) => {
369
+ this.handleStarted(event);
370
+ }), ctx.on(_agimon_ai_doompi_core_delegation.DOOM_DELEGATION_UPDATED_EVENT, (event) => {
371
+ this.handleUpdate(event);
372
+ }), ctx.on(_agimon_ai_doompi_core_delegation.DOOM_DELEGATION_FINISHED_EVENT, (event) => {
373
+ this.handleResponse(event).catch((error) => {
374
+ this.report(TASK_EVENT.delegationResponseFailed, error, { [REQUEST_ID_ATTRIBUTE]: event.requestId });
375
+ });
376
+ }));
377
+ return () => {
378
+ if (this.service === service) this.unbind();
379
+ };
380
+ }
381
+ /** Remove only the cross-package binding; task state and watchdogs remain live. */
382
+ unbind() {
383
+ for (const unsubscribe of this.subscriptions.splice(0)) unsubscribe();
384
+ this.service = void 0;
385
+ }
386
+ /** Items still in flight, surfaced so auto-stop will not kill the harness. */
387
+ listActiveWork() {
388
+ return [...this.pendingTasks.entries()].flatMap(([requestId, pending]) => pending.sessionId ? [{
389
+ id: `task-${pending.taskId}:${requestId}`,
390
+ sessionId: pending.sessionId
391
+ }] : []);
392
+ }
393
+ /**
394
+ * Return tasks nothing can finish to `pending`.
395
+ *
396
+ * The live request set is read inside the mutation so a delegation assigned
397
+ * while the lock was contended is not mistaken for a leftover.
398
+ */
399
+ async reconcile(isCurrent = () => true) {
400
+ const { value } = await this.options.store.mutate((document) => {
401
+ if (!isCurrent()) return { value: [] };
402
+ const result = reconcileOrphanedDelegations(document, this.now(), void 0, {
403
+ pid: this.options.platform.processId,
404
+ liveRequestIds: new Set(this.pendingTasks.keys())
405
+ });
406
+ if (result.orphaned.length === 0) return { value: [] };
407
+ return {
408
+ document: result.document,
409
+ value: result.orphaned
410
+ };
411
+ });
412
+ if (!isCurrent()) return [];
413
+ for (const task of value) this.options.report?.warn(TASK_EVENT.delegationOrphaned, new Error(task.delegation?.result?.error ?? ""), {
414
+ [TASK_ID_ATTRIBUTE]: task.id,
415
+ ...task.delegation?.agent ? { [AGENT_ATTRIBUTE]: task.delegation.agent } : {},
416
+ ...task.delegation?.pid === void 0 ? {} : { [PID_ATTRIBUTE]: task.delegation.pid }
417
+ });
418
+ if (value.length > 0) this.options.onChange?.();
419
+ return value;
420
+ }
421
+ async assign(taskId, options) {
422
+ const agent = options.agent?.trim();
423
+ if (!agent) return {
424
+ ok: false,
425
+ message: "agent required for assign"
426
+ };
427
+ if (this.isChildSession) return {
428
+ ok: false,
429
+ message: ERR_CHILD_SESSION
430
+ };
431
+ if (options.signal?.aborted) return {
432
+ ok: false,
433
+ message: "delegation cancelled before it started"
434
+ };
435
+ const requestId = this.options.platform.createRequestId();
436
+ const startedAt = this.now();
437
+ const sessionId = this.options.getSessionId?.();
438
+ const context = briefContext(options, this.options.cwd, this.options.platform);
439
+ const { value: outcome } = await this.options.store.mutate((current) => {
440
+ const index = current.tasks.findIndex((task) => task.id === taskId);
441
+ if (index === -1) return { value: {
442
+ ok: false,
443
+ message: `#${taskId} not found`
444
+ } };
445
+ const task = current.tasks[index];
446
+ if (task.status === DELETED_STATUS) return { value: {
447
+ ok: false,
448
+ message: `#${taskId} is deleted`
449
+ } };
450
+ if (task.status === COMPLETED_STATE) return { value: {
451
+ ok: false,
452
+ message: `#${taskId} is already completed`
453
+ } };
454
+ if (isDelegationActive(task)) return { value: {
455
+ ok: false,
456
+ message: `#${taskId} is already delegated to ${task.delegation?.agent}`
457
+ } };
458
+ if (isBlocked(current.tasks, task)) return { value: {
459
+ ok: false,
460
+ message: `#${taskId} is blocked by ${(task.blockedBy ?? []).map((id) => `#${id}`).join(", ")}`
461
+ } };
462
+ const delegation = {
463
+ requestId,
464
+ agent,
465
+ state: "requested",
466
+ pid: this.options.platform.processId,
467
+ startedAt,
468
+ ...sessionId ? { sessionId } : {},
469
+ ...options.model ? { model: options.model } : {}
470
+ };
471
+ const tasks = [...current.tasks];
472
+ tasks[index] = {
473
+ ...task,
474
+ owner: agent,
475
+ updatedAt: startedAt,
476
+ delegation
477
+ };
478
+ return {
479
+ document: {
480
+ ...current,
481
+ tasks
482
+ },
483
+ value: {
484
+ ok: true,
485
+ message: "",
486
+ task: tasks[index]
487
+ }
488
+ };
489
+ });
490
+ if (!outcome.ok || !outcome.task) return {
491
+ ok: false,
492
+ message: outcome.message
493
+ };
494
+ const contextNotesLength = context.notes?.length ?? 0;
495
+ this.pendingTasks.set(requestId, {
496
+ taskId,
497
+ sessionId
498
+ });
499
+ this.progress.set(requestId, {
500
+ agent,
501
+ contextFileCount: context.files.length,
502
+ contextNotesLength
503
+ });
504
+ this.armStartedTimeout(requestId);
505
+ this.options.onChange?.();
506
+ const request = {
507
+ requestId,
508
+ taskId,
509
+ agent,
510
+ ...options.inlineAgent ? { inlineAgent: options.inlineAgent } : {},
511
+ prompt: buildBrief(outcome.task, options.instructions, context),
512
+ ...options.context ? { context: options.context } : {},
513
+ cwd: this.options.cwd,
514
+ artifacts: true,
515
+ timeoutMs: this.runTimeoutMs,
516
+ runMode: "detached",
517
+ teamTask: {
518
+ id: String(outcome.task.id),
519
+ subject: outcome.task.subject
520
+ },
521
+ ...options.model ? { model: options.model } : {}
522
+ };
523
+ try {
524
+ const service = this.service;
525
+ if (!service) throw new Error(ERR_NO_RUNTIME);
526
+ service.request(request).catch((error) => {
527
+ this.report(TASK_EVENT.delegationRequestFailed, error, {
528
+ [TASK_ID_ATTRIBUTE]: taskId,
529
+ [REQUEST_ID_ATTRIBUTE]: requestId,
530
+ [AGENT_ATTRIBUTE]: agent
531
+ });
532
+ this.settleDetached(requestId, FAILED_STATE, {
533
+ status: FAILED_STATE,
534
+ error: `Delegation request failed: ${messageOf(error)}`
535
+ });
536
+ });
537
+ } catch (error) {
538
+ this.report(TASK_EVENT.delegationRequestFailed, error, {
539
+ [TASK_ID_ATTRIBUTE]: taskId,
540
+ [REQUEST_ID_ATTRIBUTE]: requestId,
541
+ [AGENT_ATTRIBUTE]: agent
542
+ });
543
+ const detail = messageOf(error);
544
+ await this.settle(requestId, FAILED_STATE, {
545
+ status: FAILED_STATE,
546
+ error: `Delegation request failed: ${detail}`
547
+ });
548
+ return {
549
+ ok: false,
550
+ message: `Could not dispatch #${taskId} to ${agent}: ${detail}`
551
+ };
552
+ }
553
+ this.options.report?.event(TASK_EVENT.delegationAssigned, {
554
+ [TASK_ID_ATTRIBUTE]: taskId,
555
+ [REQUEST_ID_ATTRIBUTE]: requestId,
556
+ [AGENT_ATTRIBUTE]: agent,
557
+ [CONTEXT_PRESENT_ATTRIBUTE]: context.files.length > 0 || contextNotesLength > 0,
558
+ [CONTEXT_FILE_COUNT_ATTRIBUTE]: context.files.length,
559
+ [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: contextNotesLength,
560
+ [BRIEF_LENGTH_ATTRIBUTE]: request.prompt.length
561
+ });
562
+ return {
563
+ ok: true,
564
+ message: `Delegated #${taskId} to ${agent} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end your turn.`
565
+ };
566
+ }
567
+ async cancel(taskId) {
568
+ const task = this.options.store.read().tasks.find((candidate) => candidate.id === taskId);
569
+ if (!task) return {
570
+ ok: false,
571
+ message: `#${taskId} not found`
572
+ };
573
+ if (!task.delegation || !isDelegationActive(task)) return {
574
+ ok: false,
575
+ message: `#${taskId} has no running delegation`
576
+ };
577
+ const { requestId } = task.delegation;
578
+ this.service?.cancel({ requestId });
579
+ this.armCancelTimeout(requestId);
580
+ return {
581
+ ok: true,
582
+ message: `Cancelling delegation for #${taskId} (${task.delegation.agent})`
583
+ };
584
+ }
585
+ /** Settle without awaiting, reporting rather than dropping a failure. */
586
+ settleDetached(requestId, state, result, event = TASK_EVENT.delegationSettleFailed) {
587
+ this.settle(requestId, state, result).catch((error) => {
588
+ this.report(event, error, { [REQUEST_ID_ATTRIBUTE]: requestId });
589
+ });
590
+ }
591
+ /**
592
+ * Fail a delegation that nobody acknowledged.
593
+ *
594
+ * Provider loss or a stalled Team runtime can still leave a dispatched
595
+ * request silent. Without this acknowledgement deadline the task would sit
596
+ * in `requested` forever.
597
+ */
598
+ armStartedTimeout(requestId) {
599
+ this.armTimer(requestId, this.options.startedTimeoutMs ?? DEFAULT_STARTED_TIMEOUT_MS, () => {
600
+ this.settleDetached(requestId, FAILED_STATE, {
601
+ status: FAILED_STATE,
602
+ error: ERR_NO_RUNTIME
603
+ });
604
+ });
605
+ }
606
+ /**
607
+ * Bound a run that already started.
608
+ *
609
+ * The request carries the same budget, so in the normal case the runtime ends
610
+ * the run itself and reports a richer result. The grace period biases toward
611
+ * that answer; this timer only covers a runtime that goes silent, which is
612
+ * precisely the case where no response event will ever arrive.
613
+ */
614
+ armRunTimeout(requestId) {
615
+ const grace = Math.min(MAX_RUN_TIMEOUT_GRACE_MS, this.runTimeoutMs);
616
+ this.armTimer(requestId, this.runTimeoutMs + grace, () => {
617
+ const taskId = this.pendingTasks.get(requestId)?.taskId;
618
+ const agent = this.progress.get(requestId)?.agent;
619
+ const error = /* @__PURE__ */ new Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);
620
+ this.options.report?.warn(TASK_EVENT.delegationTimedOut, error, {
621
+ ...taskId === void 0 ? {} : { [TASK_ID_ATTRIBUTE]: taskId },
622
+ [REQUEST_ID_ATTRIBUTE]: requestId,
623
+ ...agent ? { [AGENT_ATTRIBUTE]: agent } : {}
624
+ });
625
+ this.service?.cancel({
626
+ requestId,
627
+ reason: error.message
628
+ });
629
+ this.settleDetached(requestId, FAILED_STATE, {
630
+ status: TIMED_OUT_STATUS,
631
+ error: error.message
632
+ });
633
+ });
634
+ }
635
+ /**
636
+ * Guarantee a cancel reaches a terminal state.
637
+ *
638
+ * Calling the service is a request, not an outcome: a runtime that has
639
+ * already forgotten the request answers nothing at all. The window still
640
+ * favours a real response, which carries the run's partial output.
641
+ */
642
+ armCancelTimeout(requestId) {
643
+ if (!this.pendingTasks.has(requestId)) return;
644
+ this.armTimer(requestId, this.options.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS, () => {
645
+ this.settleDetached(requestId, CANCELLED_STATE, {
646
+ status: CANCELLED_STATE,
647
+ error: ERR_CANCEL_UNACKNOWLEDGED
648
+ });
649
+ });
650
+ }
651
+ armTimer(requestId, delayMs, onFire) {
652
+ this.clearTimer(requestId);
653
+ const timer = setTimeout(onFire, delayMs);
654
+ timer.unref?.();
655
+ this.timers.set(requestId, timer);
656
+ }
657
+ clearTimer(requestId) {
658
+ const timer = this.timers.get(requestId);
659
+ if (timer) clearTimeout(timer);
660
+ this.timers.delete(requestId);
661
+ }
662
+ /** Runtime acknowledgement moves the request off the short extension-presence watchdog while launch is in flight. */
663
+ handleAccepted(event) {
664
+ if (!this.pendingTasks.has(event.requestId)) return;
665
+ this.armRunTimeout(event.requestId);
666
+ }
667
+ handleStarted(event) {
668
+ const { runId } = event;
669
+ const taskId = this.pendingTasks.get(event.requestId)?.taskId;
670
+ if (taskId === void 0) return;
671
+ this.armRunTimeout(event.requestId);
672
+ const existing = this.progress.get(event.requestId);
673
+ if (existing) this.progress.set(event.requestId, {
674
+ ...existing,
675
+ durationMs: existing.durationMs ?? 0,
676
+ durationObservedAt: existing.durationObservedAt ?? this.nowMs()
677
+ });
678
+ this.options.store.mutate((document) => this.patchDelegation(document, event.requestId, (task, delegation) => ({
679
+ ...task,
680
+ status: task.status === COMPLETED_STATE ? task.status : "in_progress",
681
+ delegation: {
682
+ ...delegation,
683
+ state: "running",
684
+ startedAt: delegation.startedAt ?? this.now(),
685
+ ...runId ? { runId } : {}
686
+ }
687
+ }))).then(() => this.options.onChange?.()).catch((error) => {
688
+ this.report(TASK_EVENT.delegationStartFailed, error, {
689
+ [TASK_ID_ATTRIBUTE]: taskId,
690
+ [REQUEST_ID_ATTRIBUTE]: event.requestId
691
+ });
692
+ });
693
+ }
694
+ handleUpdate(event) {
695
+ const existing = this.progress.get(event.requestId);
696
+ if (!existing) return;
697
+ const observedAt = this.nowMs();
698
+ const currentElapsed = DelegationManager.elapsedMs(existing, observedAt);
699
+ const hasDuration = event.durationMs !== void 0;
700
+ this.progress.set(event.requestId, {
701
+ ...existing,
702
+ currentTool: event.currentTool ?? existing.currentTool,
703
+ toolCount: event.toolCount === void 0 ? existing.toolCount : Math.max(existing.toolCount ?? 0, event.toolCount),
704
+ tokens: event.tokens === void 0 ? existing.tokens : Math.max(existing.tokens ?? 0, event.tokens),
705
+ durationMs: hasDuration ? Math.max(currentElapsed, event.durationMs) : existing.durationMs,
706
+ durationObservedAt: hasDuration ? observedAt : existing.durationObservedAt
707
+ });
708
+ this.options.onChange?.();
709
+ }
710
+ async handleResponse(event) {
711
+ if (!this.pendingTasks.has(event.requestId)) return;
712
+ const state = event.status === COMPLETED_STATE && !event.error ? COMPLETED_STATE : event.status === CANCELLED_STATE ? CANCELLED_STATE : FAILED_STATE;
713
+ await this.settle(event.requestId, state, {
714
+ status: event.status,
715
+ error: event.error,
716
+ output: truncate(event.output),
717
+ outputPath: event.outputPath,
718
+ sessionFile: event.sessionFile,
719
+ durationMs: event.durationMs,
720
+ toolCount: event.toolCount
721
+ });
722
+ }
723
+ /**
724
+ * Apply the terminal state of a delegation and tell the model about it.
725
+ *
726
+ * A cancelled run returns the task to `pending` (the work is still wanted,
727
+ * just not by that agent); a failure marks it `failed` so it stays visible
728
+ * rather than silently rejoining the backlog.
729
+ *
730
+ * The request is claimed in `settlingRequests` while it remains published as
731
+ * active work. It is removed only after the terminal state and model notification
732
+ * have been handed off, so an auto-stop observer cannot end the session between
733
+ * receiving the result and delivering it to the model.
734
+ */
735
+ async settle(requestId, state, result) {
736
+ const pending = this.pendingTasks.get(requestId);
737
+ if (!pending || this.settlingRequests.has(requestId)) return;
738
+ this.settlingRequests.add(requestId);
739
+ this.clearTimer(requestId);
740
+ const { taskId } = pending;
741
+ const progress = this.progress.get(requestId);
742
+ try {
743
+ const endedAt = this.now();
744
+ let task;
745
+ try {
746
+ const { value } = await this.options.store.mutate((document) => this.patchDelegation(document, requestId, (current, delegation) => ({
747
+ ...current,
748
+ status: state === COMPLETED_STATE ? COMPLETED_STATE : state === CANCELLED_STATE ? "pending" : FAILED_STATE,
749
+ updatedAt: endedAt,
750
+ delegation: {
751
+ ...delegation,
752
+ state,
753
+ endedAt,
754
+ ...result ? { result } : {}
755
+ }
756
+ })));
757
+ task = value;
758
+ } catch (error) {
759
+ this.report(TASK_EVENT.delegationSettleFailed, error, {
760
+ [TASK_ID_ATTRIBUTE]: taskId,
761
+ [REQUEST_ID_ATTRIBUTE]: requestId
762
+ });
763
+ }
764
+ const agent = task?.delegation?.agent ?? progress?.agent ?? "subagent";
765
+ const subject = task?.subject ?? `#${taskId}`;
766
+ this.options.report?.event(TASK_EVENT.delegationCompleted, {
767
+ [TASK_ID_ATTRIBUTE]: taskId,
768
+ [REQUEST_ID_ATTRIBUTE]: requestId,
769
+ [AGENT_ATTRIBUTE]: agent,
770
+ [OUTCOME_ATTRIBUTE]: state,
771
+ [CONTEXT_PRESENT_ATTRIBUTE]: (progress?.contextFileCount ?? 0) > 0 || (progress?.contextNotesLength ?? 0) > 0,
772
+ [CONTEXT_FILE_COUNT_ATTRIBUTE]: progress?.contextFileCount ?? 0,
773
+ [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: progress?.contextNotesLength ?? 0,
774
+ ...result?.toolCount === void 0 ? {} : { [TOOL_COUNT_ATTRIBUTE]: result.toolCount },
775
+ ...result?.durationMs === void 0 ? {} : { [DURATION_MS_ATTRIBUTE]: result.durationMs }
776
+ });
777
+ const listComplete = state === COMPLETED_STATE && task !== void 0 && isTaskListComplete(this.options.store.snapshot.tasks);
778
+ this.notifyModel(state, taskId, subject, agent, result, listComplete);
779
+ } finally {
780
+ this.pendingTasks.delete(requestId);
781
+ this.progress.delete(requestId);
782
+ this.settlingRequests.delete(requestId);
783
+ this.options.onChange?.();
784
+ }
785
+ }
786
+ notifyModel(state, taskId, subject, agent, result, listComplete) {
787
+ const notify = this.options.notify;
788
+ if (!notify) return;
789
+ const lines = [state === COMPLETED_STATE ? `Subagent ${agent} completed task #${taskId}: ${subject}` : state === CANCELLED_STATE ? `Subagent ${agent} was cancelled on task #${taskId}: ${subject} (returned to pending)` : `Subagent ${agent} failed task #${taskId}: ${subject}`];
790
+ if (listComplete) lines.push("", "All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.");
791
+ if (result?.error) lines.push(`Error: ${result.error}`);
792
+ if (result?.output) lines.push("", result.output);
793
+ if (result?.outputPath) lines.push("", `Full output: ${result.outputPath}`);
794
+ try {
795
+ notify({
796
+ customType: NOTIFY_CUSTOM_TYPE,
797
+ content: lines.join("\n"),
798
+ display: true
799
+ }, {
800
+ triggerTurn: true,
801
+ deliverAs: "steer"
802
+ });
803
+ } catch (error) {
804
+ this.options.onNotifyError(error, taskId);
805
+ }
806
+ }
807
+ /**
808
+ * Rewrite the task carrying `requestId`, returning the updated task as the mutation value.
809
+ *
810
+ * Terminal delegations are left alone. The document here is the freshest one,
811
+ * read under the store lock, which is the only place the check is meaningful:
812
+ * a `started` event can land after a cancel already settled the run, and
813
+ * without this guard its write would resurrect a delegation that nothing is
814
+ * tracking any more.
815
+ */
816
+ patchDelegation(document, requestId, patch) {
817
+ const index = document.tasks.findIndex((task) => task.delegation?.requestId === requestId);
818
+ if (index === -1) return { value: void 0 };
819
+ const task = document.tasks[index];
820
+ if (!isDelegationActive(task)) return { value: task };
821
+ const updated = patch(task, task.delegation);
822
+ if (updated === task) return { value: task };
823
+ const tasks = [...document.tasks];
824
+ tasks[index] = updated;
825
+ return {
826
+ document: {
827
+ ...document,
828
+ tasks
829
+ },
830
+ value: updated
831
+ };
832
+ }
833
+ dispose() {
834
+ this.unbind();
835
+ this.reset();
836
+ }
837
+ /** Clear one Pi session's transient delegation state without losing service injection. */
838
+ reset() {
839
+ const changed = this.pendingTasks.size > 0 || this.progress.size > 0;
840
+ for (const timer of this.timers.values()) clearTimeout(timer);
841
+ this.timers.clear();
842
+ this.pendingTasks.clear();
843
+ this.settlingRequests.clear();
844
+ this.progress.clear();
845
+ if (changed) this.options.onChange?.();
846
+ }
847
+ };
848
+ //#endregion
849
+ //#region src/services/delegationPlatform/index.ts
850
+ function formatBriefPath(entry, cwd) {
851
+ if (!node_path.default.isAbsolute(entry)) return node_path.default.normalize(entry);
852
+ const relative = node_path.default.relative(cwd, entry);
853
+ return relative && !relative.startsWith("..") ? relative : entry;
854
+ }
855
+ /** Supply Node-owned process and path facilities to the host-neutral manager. */
856
+ function createNodeDelegationPlatform(environment = process.env) {
857
+ return {
858
+ environment,
859
+ processId: process.pid,
860
+ createRequestId: node_crypto.randomUUID,
861
+ formatBriefPath
862
+ };
863
+ }
864
+ //#endregion
865
+ //#region src/services/paths/index.ts
866
+ const STORE_PATH_ENV = "DOOM_TASK_STORE";
867
+ const STORE_DIR_NAME = "doom-task";
868
+ const STORE_FILE_NAME = "tasks.json";
869
+ const DEFAULT_CONFIG_DIR_NAME = ".pi";
870
+ const AGENT_DIR_NAME = "agent";
871
+ const PI_CODING_AGENT_DIR_ENV = "PI_CODING_AGENT_DIR";
872
+ const HOME_ALIAS = "~";
873
+ const HOME_ALIAS_PREFIX = "~/";
874
+ function resolveAgentDirectory(env) {
875
+ const configured = env[PI_CODING_AGENT_DIR_ENV]?.trim();
876
+ if (configured === HOME_ALIAS) return node_os.default.homedir();
877
+ if (configured?.startsWith(HOME_ALIAS_PREFIX)) return node_path.default.join(node_os.default.homedir(), configured.slice(2));
878
+ return configured ? node_path.default.resolve(configured) : node_path.default.join(node_os.default.homedir(), DEFAULT_CONFIG_DIR_NAME, AGENT_DIR_NAME);
879
+ }
880
+ /** Resolve the tree root without relying on extension startup order. */
881
+ function resolveSessionKey(rootSessionId, env = process.env) {
882
+ if (!env[_agimon_ai_doompi_core_child_process.SUBAGENT_CHILD_ENV]) return rootSessionId;
883
+ const parentSessionId = env[_agimon_ai_doompi_core_child_process.SUBAGENT_PARENT_SESSION_ENV]?.trim();
884
+ if (!parentSessionId) throw new Error(`${_agimon_ai_doompi_core_child_process.SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);
885
+ return parentSessionId;
886
+ }
887
+ /** Resolve one root session tree to a task document under the Pi agent directory. */
888
+ function resolveStorePath(_cwd = process.cwd(), env = process.env, sessionKey = "standalone") {
889
+ const override = env[STORE_PATH_ENV]?.trim();
890
+ if (override) return node_path.default.resolve(override);
891
+ const trimmedSessionKey = sessionKey.trim();
892
+ if (!trimmedSessionKey) throw new Error("doom-task session id cannot be blank");
893
+ return node_path.default.join(resolveAgentDirectory(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);
894
+ }
895
+ function lockPathFor(storePath) {
896
+ return `${storePath}.lock`;
897
+ }
898
+ function tempPathFor(storePath, pid = process.pid) {
899
+ return `${storePath}.tmp.${pid}`;
900
+ }
901
+ //#endregion
902
+ //#region src/services/invariants/index.ts
903
+ /**
904
+ * Collapse a malformed snapshot to one row per task id.
905
+ *
906
+ * Normal writes replace tasks in place, but older or externally edited stores
907
+ * can contain both a stale and a current copy. Prefer the copy with the newest
908
+ * ISO update timestamp; equal or missing timestamps use the later array entry.
909
+ * The winning row keeps the id's original position so repair does not reorder
910
+ * an otherwise stable task list.
911
+ */
912
+ function canonicalizeTasks(tasks) {
913
+ const canonical = [];
914
+ const indexById = /* @__PURE__ */ new Map();
915
+ for (const task of tasks) {
916
+ const existingIndex = indexById.get(task.id);
917
+ if (existingIndex === void 0) {
918
+ indexById.set(task.id, canonical.length);
919
+ canonical.push(task);
920
+ continue;
921
+ }
922
+ const existing = canonical[existingIndex];
923
+ if (!existing.updatedAt || !task.updatedAt || task.updatedAt >= existing.updatedAt) canonical[existingIndex] = task;
924
+ }
925
+ return canonical;
926
+ }
927
+ /**
928
+ * Allowed forward transitions per source status.
929
+ *
930
+ * `failed` is recoverable (a delegation can be retried) so it may return to
931
+ * pending or in_progress. `completed` is one-way to `deleted`; `deleted` is a
932
+ * terminal tombstone.
933
+ */
934
+ const VALID_TRANSITIONS = {
935
+ pending: /* @__PURE__ */ new Set([
936
+ "in_progress",
937
+ "completed",
938
+ "failed",
939
+ "deleted"
940
+ ]),
941
+ in_progress: /* @__PURE__ */ new Set([
942
+ "pending",
943
+ "completed",
944
+ "failed",
945
+ "deleted"
946
+ ]),
947
+ failed: /* @__PURE__ */ new Set([
948
+ "pending",
949
+ "in_progress",
950
+ "completed",
951
+ "deleted"
952
+ ]),
953
+ completed: /* @__PURE__ */ new Set(["deleted"]),
954
+ deleted: /* @__PURE__ */ new Set()
955
+ };
956
+ function isTransitionValid(from, to) {
957
+ if (from === to) return true;
958
+ return VALID_TRANSITIONS[from].has(to);
959
+ }
960
+ //#endregion
961
+ //#region src/services/taskStore/index.ts
962
+ const LOCK_TIMEOUT_MS = 2e3;
963
+ const LOCK_STALE_MS = 1e4;
964
+ const LOCK_RETRY_BASE_MS = 10;
965
+ const LOCK_RETRY_MAX_MS = 60;
966
+ const UTF8_ENCODING = "utf8";
967
+ const MISSING_FILE_CODE = "ENOENT";
968
+ const LOCK_EXISTS_CODE = "EEXIST";
969
+ const STORE_PATH_ATTRIBUTE = "store.path";
970
+ function sleep(ms) {
971
+ return new Promise((resolve) => setTimeout(resolve, ms));
972
+ }
973
+ /**
974
+ * Coerce arbitrary parsed JSON into a valid document.
975
+ *
976
+ * A corrupt or truncated store must not take the session down: the worst
977
+ * acceptable outcome is starting from an empty list, never a crash on startup.
978
+ */
979
+ function normalizeDocument(parsed) {
980
+ if (!parsed || typeof parsed !== "object") return emptyDocument();
981
+ const candidate = parsed;
982
+ if (!Array.isArray(candidate.tasks)) return emptyDocument();
983
+ const tasks = canonicalizeTasks(candidate.tasks.filter((task) => Boolean(task) && typeof task === "object" && typeof task.id === "number"));
984
+ const maxId = tasks.reduce((max, task) => Math.max(max, task.id), 0);
985
+ return {
986
+ version: typeof candidate.version === "number" ? candidate.version : 1,
987
+ rev: typeof candidate.rev === "number" ? candidate.rev : 0,
988
+ nextId: typeof candidate.nextId === "number" && candidate.nextId > maxId ? candidate.nextId : maxId + 1,
989
+ tasks
990
+ };
991
+ }
992
+ /**
993
+ * File-backed task store shared by one root session and its delegated children.
994
+ *
995
+ * Durability model: the JSON file is the source of truth. Mutations are
996
+ * read-modify-write under an advisory lock so concurrent delegated processes
997
+ * cannot clobber each other, and writes land via temp-file rename so a
998
+ * crash mid-write can never leave a partial document behind.
999
+ */
1000
+ var TaskStore = class {
1001
+ storePath;
1002
+ cwd;
1003
+ env;
1004
+ cached = emptyDocument();
1005
+ listeners = /* @__PURE__ */ new Set();
1006
+ lockTimeoutMs;
1007
+ report;
1008
+ onCommitted;
1009
+ constructor(options = {}) {
1010
+ this.cwd = options.cwd ?? process.cwd();
1011
+ this.env = options.env ?? process.env;
1012
+ this.storePath = options.storePath ?? resolveStorePath(this.cwd, this.env);
1013
+ this.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;
1014
+ this.report = options.report;
1015
+ this.onCommitted = options.onCommitted;
1016
+ }
1017
+ /** Bind a default store to the current session tree before reading it. */
1018
+ configureSession(sessionKey) {
1019
+ if (this.env["DOOM_TASK_STORE"]?.trim()) return;
1020
+ this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);
1021
+ this.cached = emptyDocument();
1022
+ }
1023
+ /** Last document read from disk, without hitting the filesystem. */
1024
+ get snapshot() {
1025
+ return this.cached;
1026
+ }
1027
+ read() {
1028
+ try {
1029
+ const raw = node_fs.default.readFileSync(this.storePath, UTF8_ENCODING);
1030
+ this.cached = normalizeDocument(JSON.parse(raw));
1031
+ } catch (error) {
1032
+ if (error.code !== MISSING_FILE_CODE) this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });
1033
+ this.cached = emptyDocument();
1034
+ }
1035
+ return this.cached;
1036
+ }
1037
+ async readAsync(shouldApply = () => true) {
1038
+ const storePath = this.storePath;
1039
+ const document = await this.readDocumentAsync(storePath);
1040
+ if (!shouldApply()) return document;
1041
+ this.cached = document;
1042
+ return document;
1043
+ }
1044
+ async readDocumentAsync(storePath = this.storePath) {
1045
+ try {
1046
+ const raw = await node_fs.default.promises.readFile(storePath, UTF8_ENCODING);
1047
+ return normalizeDocument(JSON.parse(raw));
1048
+ } catch (error) {
1049
+ if (error.code !== MISSING_FILE_CODE) this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: storePath });
1050
+ return emptyDocument();
1051
+ }
1052
+ }
1053
+ /**
1054
+ * Apply a mutation under the store lock.
1055
+ *
1056
+ * `mutate` receives the freshest on-disk document and returns either the next
1057
+ * document to commit or `undefined` for a read-only action (list/get), which
1058
+ * skips the write entirely so queries never bump `rev`.
1059
+ */
1060
+ async mutate(mutate) {
1061
+ const release = await this.acquireLock();
1062
+ const outcome = (() => {
1063
+ try {
1064
+ const current = this.read();
1065
+ const mutation = mutate(current);
1066
+ if (!mutation.document) return { result: {
1067
+ document: current,
1068
+ value: mutation.value
1069
+ } };
1070
+ const committed = this.write(mutation.document);
1071
+ return {
1072
+ result: {
1073
+ document: committed,
1074
+ value: mutation.value
1075
+ },
1076
+ notification: {
1077
+ previous: current,
1078
+ committed
1079
+ }
1080
+ };
1081
+ } finally {
1082
+ release();
1083
+ }
1084
+ })();
1085
+ if (outcome.notification) this.notifyCommitted(outcome.notification.previous, outcome.notification.committed);
1086
+ return outcome.result;
1087
+ }
1088
+ notifyCommitted(previous, committed) {
1089
+ try {
1090
+ this.onCommitted?.(previous, committed);
1091
+ } catch (error) {
1092
+ this.report?.error(TASK_EVENT.storeCommitListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });
1093
+ }
1094
+ for (const listener of this.listeners) try {
1095
+ listener(committed);
1096
+ } catch (error) {
1097
+ this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });
1098
+ }
1099
+ }
1100
+ write(document) {
1101
+ const next = {
1102
+ ...document,
1103
+ version: 1,
1104
+ rev: document.rev + 1
1105
+ };
1106
+ node_fs.default.mkdirSync(node_path.default.dirname(this.storePath), { recursive: true });
1107
+ const temp = tempPathFor(this.storePath);
1108
+ node_fs.default.writeFileSync(temp, `${JSON.stringify(next, void 0, 2)}\n`, UTF8_ENCODING);
1109
+ node_fs.default.renameSync(temp, this.storePath);
1110
+ this.cached = next;
1111
+ return next;
1112
+ }
1113
+ async acquireLock() {
1114
+ const lockPath = lockPathFor(this.storePath);
1115
+ node_fs.default.mkdirSync(node_path.default.dirname(this.storePath), { recursive: true });
1116
+ const deadline = Date.now() + this.lockTimeoutMs;
1117
+ for (;;) try {
1118
+ const handle = node_fs.default.openSync(lockPath, "wx");
1119
+ node_fs.default.writeSync(handle, JSON.stringify({
1120
+ pid: process.pid,
1121
+ time: Date.now()
1122
+ }));
1123
+ node_fs.default.closeSync(handle);
1124
+ return () => node_fs.default.rmSync(lockPath, { force: true });
1125
+ } catch (error) {
1126
+ if (error.code !== LOCK_EXISTS_CODE) throw error;
1127
+ if (Date.now() >= deadline) {
1128
+ this.report?.warn(TASK_EVENT.storeLockTimeout, /* @__PURE__ */ new Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`), { [STORE_PATH_ATTRIBUTE]: this.storePath });
1129
+ return () => {};
1130
+ }
1131
+ this.breakStaleLock(lockPath);
1132
+ await sleep(LOCK_RETRY_BASE_MS + Math.random() * LOCK_RETRY_MAX_MS);
1133
+ }
1134
+ }
1135
+ /** Remove a lock left behind by a dead process or one held implausibly long. */
1136
+ breakStaleLock(lockPath) {
1137
+ try {
1138
+ const holder = JSON.parse(node_fs.default.readFileSync(lockPath, UTF8_ENCODING));
1139
+ const expired = typeof holder.time === "number" && Date.now() - holder.time > LOCK_STALE_MS;
1140
+ const dead = typeof holder.pid === "number" && !isProcessAlive(holder.pid);
1141
+ if (!expired && !dead) return false;
1142
+ node_fs.default.unlinkSync(lockPath);
1143
+ return true;
1144
+ } catch (error) {
1145
+ if (error.code !== MISSING_FILE_CODE) this.report?.warn(TASK_EVENT.storeLockBreakFailed, error, { [STORE_PATH_ATTRIBUTE]: lockPath });
1146
+ return false;
1147
+ }
1148
+ }
1149
+ /**
1150
+ * Listen for commits made through this store instance.
1151
+ *
1152
+ * Live cross-process updates use the owning session's direct event bus. This
1153
+ * listener remains for local terminal views and never watches the filesystem.
1154
+ */
1155
+ onExternalChange(listener) {
1156
+ this.listeners.add(listener);
1157
+ return () => this.listeners.delete(listener);
1158
+ }
1159
+ dispose() {
1160
+ this.listeners.clear();
1161
+ }
1162
+ };
1163
+ //#endregion
1164
+ //#region src/schemas/task.ts
1165
+ const TASK_ACTIONS = [
1166
+ "upsert",
1167
+ "list",
1168
+ "get",
1169
+ "delete",
1170
+ "clear",
1171
+ "assign",
1172
+ "cancel"
1173
+ ];
1174
+ const TASK_STATUSES = [
1175
+ "pending",
1176
+ "in_progress",
1177
+ "completed",
1178
+ "failed",
1179
+ "deleted"
1180
+ ];
1181
+ const TASK_CONTEXTS = ["fresh", "fork"];
1182
+ /**
1183
+ * A dependency target: an existing task id, or the `ref` of a task created
1184
+ * earlier in the same call.
1185
+ */
1186
+ const DepTokenSchema = typebox.Type.Union([typebox.Type.Integer(), typebox.Type.String()]);
1187
+ /**
1188
+ * One entry of an upsert. `additionalProperties: false` is load-bearing: pi
1189
+ * validates tool arguments against this schema before `execute` runs, so a
1190
+ * stray `{"action":"update"}` inside an entry is rejected at the boundary.
1191
+ */
1192
+ const TaskItemSchema = typebox.Type.Object({
1193
+ id: typebox.Type.Optional(typebox.Type.Integer({ description: "Existing task id to change. Omit to create. An unknown id fails only that entry; it never creates." })),
1194
+ ref: typebox.Type.Optional(typebox.Type.String({ description: "Temporary name for a task created by this entry, so a LATER entry in this array can list it in blockedBy. Must start with a letter; never stored." })),
1195
+ subject: typebox.Type.Optional(typebox.Type.String({ description: "Short imperative subject. Required when the entry has no id; on an entry with an id it renames." })),
1196
+ description: typebox.Type.Optional(typebox.Type.String({ description: "Long-form detail; becomes the brief handed to the subagent on assign." })),
1197
+ activeForm: typebox.Type.Optional(typebox.Type.String({ description: "Present-continuous label shown while in_progress (e.g. 'writing tests')" })),
1198
+ status: typebox.Type.Optional(typebox.Type.String({
1199
+ enum: [...TASK_STATUSES],
1200
+ description: "New entries default to pending and cannot start deleted; on an entry with an id the transition must be legal."
1201
+ })),
1202
+ blockedBy: typebox.Type.Optional(typebox.Type.Array(DepTokenSchema, { description: "Dependencies for a NEW entry: task ids, or refs of tasks created EARLIER in this array. On an entry with an id use addBlockedBy / removeBlockedBy instead." })),
1203
+ addBlockedBy: typebox.Type.Optional(typebox.Type.Array(DepTokenSchema, { description: "Dependencies to add (ids or earlier refs). Additive; do not resend the full array." })),
1204
+ removeBlockedBy: typebox.Type.Optional(typebox.Type.Array(DepTokenSchema, { description: "Dependencies to remove. Additive; do not resend the full array." })),
1205
+ owner: typebox.Type.Optional(typebox.Type.String({ description: "Owner label; assign sets it to the subagent name." })),
1206
+ metadata: typebox.Type.Optional(typebox.Type.Record(typebox.Type.String(), typebox.Type.Unknown(), { description: "Merged into the task; a null value deletes that key." }))
1207
+ }, { additionalProperties: false });
1208
+ /** One task-to-agent handoff in a native assignment batch. */
1209
+ const TaskAssignmentSchema = typebox.Type.Object({
1210
+ id: typebox.Type.Integer({ description: "Pending, unblocked task id to delegate" }),
1211
+ agent: typebox.Type.String({ description: "Exact discovered subagent name" }),
1212
+ inlineAgent: typebox.Type.Optional(_agimon_ai_doompi_core_delegation.InlineAgentSchema),
1213
+ instructions: typebox.Type.Optional(typebox.Type.String({ description: "Extra instructions appended to this delegated brief" })),
1214
+ relevantFiles: typebox.Type.Optional(typebox.Type.Array(typebox.Type.String(), { description: `Files already read or located, relative to the working directory; at most 12 are used.` })),
1215
+ priorFindings: typebox.Type.Optional(typebox.Type.String({ description: "Established facts this child should consume rather than re-derive" })),
1216
+ model: typebox.Type.Optional(typebox.Type.String({ description: "Model override for this delegated run" })),
1217
+ context: typebox.Type.Optional(typebox.Type.String({
1218
+ enum: [...TASK_CONTEXTS],
1219
+ description: "Starting context for this child: 'fresh' or 'fork'"
1220
+ }))
1221
+ }, { additionalProperties: false });
1222
+ /**
1223
+ * Tool parameters. Every `description` doubles as LLM-facing prompt copy, so
1224
+ * wording changes here change model behaviour.
1225
+ */
1226
+ const TaskParamsSchema = typebox.Type.Object({
1227
+ action: typebox.Type.String({ enum: [...TASK_ACTIONS] }),
1228
+ tasks: typebox.Type.Optional(typebox.Type.Array(TaskItemSchema, {
1229
+ minItems: 1,
1230
+ description: "upsert only. An entry with an id changes that task, an entry without an id creates one. Entries apply in array order, so a later entry can depend on an earlier one by ref."
1231
+ })),
1232
+ assignments: typebox.Type.Optional(typebox.Type.Array(TaskAssignmentSchema, {
1233
+ minItems: 1,
1234
+ description: "Required for assign, one entry per task, including when there is only one."
1235
+ })),
1236
+ id: typebox.Type.Optional(typebox.Type.Integer({ description: "Task id, for get, delete and cancel. Not accepted by upsert or assign: those carry ids inside tasks[] and assignments[] entries." })),
1237
+ status: typebox.Type.Optional(typebox.Type.String({
1238
+ enum: [...TASK_STATUSES],
1239
+ description: "list only: return just the tasks in this status. To SET a status, upsert the task by id."
1240
+ })),
1241
+ includeDeleted: typebox.Type.Optional(typebox.Type.Boolean({ description: "list only: also return deleted tombstones. Default false." }))
1242
+ });
1243
+ //#endregion
1244
+ //#region src/services/reducer/index.ts
1245
+ /** Default board capacity when a caller does not provide a configured limit. */
1246
+ const DEFAULT_REDUCER_MAX_TASKS = 15;
1247
+ /**
1248
+ * A ref must start with a letter, which makes it structurally unconfusable with
1249
+ * a stringified id. That is why resolving a dependency token is just a `typeof`
1250
+ * check with no coercion heuristics.
1251
+ */
1252
+ const REF_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;
1253
+ /**
1254
+ * Does this op represent state that must reach disk?
1255
+ *
1256
+ * The exhaustive switch is the point: a future `Op` variant cannot be added
1257
+ * without declaring its persistence intent, so nothing silently starts or stops
1258
+ * bumping `rev`.
1259
+ */
1260
+ function isCommittingOp(op) {
1261
+ switch (op.kind) {
1262
+ case "error":
1263
+ case "list":
1264
+ case "get": return false;
1265
+ case "upsert": return op.items.some((item) => item.kind === "created" || item.kind === "updated");
1266
+ case "delete":
1267
+ case "clear": return true;
1268
+ }
1269
+ }
1270
+ function errorResult(document, message) {
1271
+ return {
1272
+ document,
1273
+ op: {
1274
+ kind: "error",
1275
+ message
1276
+ }
1277
+ };
1278
+ }
1279
+ function sameNumberList(a, b) {
1280
+ const x = a ?? [];
1281
+ const y = b ?? [];
1282
+ return x.length === y.length && x.every((value, index) => value === y[index]);
1283
+ }
1284
+ function sameRecord(a, b) {
1285
+ return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
1286
+ }
1287
+ /**
1288
+ * Did this update change anything? A no-effect update (status re-set to its
1289
+ * current value, fields re-sent unchanged) reports "No change" rather than
1290
+ * "Updated #N" — without the distinction a model can loop re-issuing the same
1291
+ * call believing it never landed.
1292
+ */
1293
+ function taskChanged(before, after) {
1294
+ return before.subject !== after.subject || before.status !== after.status || before.description !== after.description || before.activeForm !== after.activeForm || before.owner !== after.owner || !sameNumberList(before.blockedBy, after.blockedBy) || !sameRecord(before.metadata, after.metadata);
1295
+ }
1296
+ function withTasks(document, tasks, nextId = document.nextId) {
1297
+ return {
1298
+ ...document,
1299
+ tasks,
1300
+ nextId
1301
+ };
1302
+ }
1303
+ /** Merge incoming metadata over a base; a `null` value deletes its key. */
1304
+ function mergeMetadata(base, incoming) {
1305
+ const merged = { ...base };
1306
+ for (const [key, value] of Object.entries(incoming)) if (value === null) delete merged[key];
1307
+ else merged[key] = value;
1308
+ return Object.keys(merged).length ? merged : void 0;
1309
+ }
1310
+ /** Copy the optional scalar fields an item may set onto a task, in place. */
1311
+ function assignScalars(target, item) {
1312
+ if (item.subject !== void 0) target.subject = item.subject;
1313
+ if (item.description !== void 0) target.description = item.description;
1314
+ if (item.activeForm !== void 0) target.activeForm = item.activeForm;
1315
+ if (item.owner !== void 0) target.owner = item.owner;
1316
+ if (item.metadata !== void 0) {
1317
+ const merged = mergeMetadata(target.metadata, item.metadata);
1318
+ if (merged === void 0) delete target.metadata;
1319
+ else target.metadata = merged;
1320
+ }
1321
+ }
1322
+ function resolveDep(context, field, token) {
1323
+ if (typeof token === "number") return {
1324
+ ok: true,
1325
+ id: token
1326
+ };
1327
+ if (!REF_PATTERN.test(token)) return {
1328
+ ok: false,
1329
+ message: `${field}: "${token}" is not a valid ref; pass an existing task id as a number`
1330
+ };
1331
+ const id = context.refIds.get(token);
1332
+ if (id !== void 0) return {
1333
+ ok: true,
1334
+ id
1335
+ };
1336
+ const failedAt = context.failedRefs.get(token);
1337
+ if (failedAt !== void 0) return {
1338
+ ok: false,
1339
+ message: `${field}: ref "${token}" refers to item[${failedAt}], which failed`
1340
+ };
1341
+ return {
1342
+ ok: false,
1343
+ message: `${field}: unknown ref "${token}" — a ref must be declared by an earlier entry in the same call`
1344
+ };
1345
+ }
1346
+ function fail(message) {
1347
+ return {
1348
+ ok: false,
1349
+ message
1350
+ };
1351
+ }
1352
+ /** Structural checks that apply to every entry, whichever kind it is. */
1353
+ function checkShape(context, item) {
1354
+ if (item.ref !== void 0) {
1355
+ if (item.id !== void 0) return "ref is only valid when creating a task; drop the id, or drop the ref";
1356
+ if (!REF_PATTERN.test(item.ref)) return `ref "${item.ref}" is invalid: a ref must start with a letter and contain only letters, digits, - or _`;
1357
+ if (context.refIds.get(item.ref) !== void 0 || context.failedRefs.has(item.ref)) return `duplicate ref "${item.ref}": it was already declared by an earlier entry`;
1358
+ }
1359
+ }
1360
+ function applyCreateItem(context, item, index, now) {
1361
+ if (item.subject === void 0) return fail("subject is required when the entry has no id");
1362
+ if (!item.subject.trim()) return fail("subject must not be blank");
1363
+ if (item.addBlockedBy !== void 0 || item.removeBlockedBy !== void 0) return fail("addBlockedBy / removeBlockedBy are only for an entry with an id; a new task uses blockedBy");
1364
+ if (item.status === "deleted") return fail("cannot create a task with status deleted; create it, then use action delete");
1365
+ if (context.tasks.filter((task) => task.status !== "deleted").length >= context.maxTasks) return fail(`task limit of ${context.maxTasks} reached; delete completed tasks first before creating new tasks`);
1366
+ const blockedBy = [];
1367
+ for (const token of item.blockedBy ?? []) {
1368
+ const resolved = resolveDep(context, "blockedBy", token);
1369
+ if (!resolved.ok) return fail(resolved.message);
1370
+ const dep = context.tasks.find((task) => task.id === resolved.id);
1371
+ if (!dep) return fail(`blockedBy: #${resolved.id} not found`);
1372
+ if (dep.status === "deleted") return fail(`blockedBy: #${resolved.id} is deleted`);
1373
+ if (!blockedBy.includes(resolved.id)) blockedBy.push(resolved.id);
1374
+ }
1375
+ const created = {
1376
+ id: context.nextId,
1377
+ subject: item.subject,
1378
+ status: item.status ?? "pending",
1379
+ createdAt: now,
1380
+ updatedAt: now
1381
+ };
1382
+ assignScalars(created, item);
1383
+ if (blockedBy.length) created.blockedBy = blockedBy;
1384
+ context.nextId += 1;
1385
+ context.tasks.push(created);
1386
+ if (item.ref) context.refIds.set(item.ref, created.id);
1387
+ return {
1388
+ ok: true,
1389
+ outcome: {
1390
+ index,
1391
+ kind: "created",
1392
+ id: created.id,
1393
+ subject: created.subject,
1394
+ status: created.status,
1395
+ ...item.ref ? { ref: item.ref } : {},
1396
+ ...blockedBy.length ? { blockedBy } : {}
1397
+ }
1398
+ };
1399
+ }
1400
+ function applyUpdateItem(context, item, index, now) {
1401
+ const id = item.id;
1402
+ const at = context.tasks.findIndex((task) => task.id === id);
1403
+ if (at === -1) return fail(`#${id} not found`);
1404
+ if (item.blockedBy !== void 0) return fail("blockedBy is only for a new entry; use addBlockedBy / removeBlockedBy on an entry that has an id");
1405
+ if (!(item.subject !== void 0 || item.description !== void 0 || item.activeForm !== void 0 || item.status !== void 0 || item.owner !== void 0 || item.metadata !== void 0 || Boolean(item.addBlockedBy?.length) || Boolean(item.removeBlockedBy?.length))) return fail("nothing to change: provide at least one of subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy");
1406
+ const current = context.tasks[at];
1407
+ if (item.subject !== void 0 && !item.subject.trim()) return fail("subject must not be blank");
1408
+ let newStatus = current.status;
1409
+ if (item.status !== void 0) {
1410
+ if (!isTransitionValid(current.status, item.status)) return fail(`illegal transition ${current.status} -> ${item.status}`);
1411
+ newStatus = item.status;
1412
+ }
1413
+ let newBlockedBy = current.blockedBy ? [...current.blockedBy] : [];
1414
+ for (const token of item.removeBlockedBy ?? []) {
1415
+ const resolved = resolveDep(context, "removeBlockedBy", token);
1416
+ if (!resolved.ok) return fail(resolved.message);
1417
+ newBlockedBy = newBlockedBy.filter((dep) => dep !== resolved.id);
1418
+ }
1419
+ for (const token of item.addBlockedBy ?? []) {
1420
+ const resolved = resolveDep(context, "addBlockedBy", token);
1421
+ if (!resolved.ok) return fail(resolved.message);
1422
+ if (resolved.id === id) return fail(`cannot block #${id} on itself`);
1423
+ const dep = context.tasks.find((task) => task.id === resolved.id);
1424
+ if (!dep) return fail(`addBlockedBy: #${resolved.id} not found`);
1425
+ if (dep.status === "deleted") return fail(`addBlockedBy: #${resolved.id} is deleted`);
1426
+ if (!newBlockedBy.includes(resolved.id)) newBlockedBy.push(resolved.id);
1427
+ }
1428
+ const updated = {
1429
+ ...current,
1430
+ status: newStatus
1431
+ };
1432
+ assignScalars(updated, item);
1433
+ if (newBlockedBy.length) updated.blockedBy = newBlockedBy;
1434
+ else delete updated.blockedBy;
1435
+ const candidate = [...context.tasks];
1436
+ candidate[at] = updated;
1437
+ if (item.addBlockedBy?.length && detectCycle(candidate, id, newBlockedBy)) return fail("addBlockedBy would create a cycle in the blockedBy graph");
1438
+ const changed = taskChanged(current, updated);
1439
+ if (changed) updated.updatedAt = now;
1440
+ context.tasks = candidate;
1441
+ return {
1442
+ ok: true,
1443
+ outcome: changed ? {
1444
+ index,
1445
+ kind: "updated",
1446
+ id,
1447
+ fromStatus: current.status,
1448
+ toStatus: newStatus
1449
+ } : {
1450
+ index,
1451
+ kind: "unchanged",
1452
+ id,
1453
+ status: newStatus
1454
+ }
1455
+ };
1456
+ }
1457
+ /**
1458
+ * Apply every entry in request order, threading the document.
1459
+ *
1460
+ * Each entry lands completely or not at all: a create whose dependencies fail
1461
+ * is not kept dependency-free, because handing back an unblocked task the
1462
+ * caller asked to be blocked is a lie it may immediately act on.
1463
+ */
1464
+ function applyUpsert(document, items, now, maxTasks) {
1465
+ const context = {
1466
+ tasks: [...document.tasks],
1467
+ nextId: document.nextId,
1468
+ maxTasks,
1469
+ refIds: /* @__PURE__ */ new Map(),
1470
+ failedRefs: /* @__PURE__ */ new Map()
1471
+ };
1472
+ const outcomes = [];
1473
+ let applied = 0;
1474
+ for (const [index, item] of items.entries()) {
1475
+ const shapeError = checkShape(context, item);
1476
+ const result = shapeError ? fail(shapeError) : item.id === void 0 ? applyCreateItem(context, item, index, now) : applyUpdateItem(context, item, index, now);
1477
+ if (result.ok) {
1478
+ outcomes.push(result.outcome);
1479
+ applied += 1;
1480
+ continue;
1481
+ }
1482
+ if (item.ref && REF_PATTERN.test(item.ref) && !context.refIds.has(item.ref)) context.failedRefs.set(item.ref, index);
1483
+ outcomes.push({
1484
+ index,
1485
+ kind: "failed",
1486
+ message: result.message,
1487
+ ...item.id === void 0 ? {} : { id: item.id },
1488
+ ...item.ref ? { ref: item.ref } : {}
1489
+ });
1490
+ }
1491
+ return {
1492
+ document: applied > 0 ? withTasks(document, context.tasks, context.nextId) : document,
1493
+ op: {
1494
+ kind: "upsert",
1495
+ items: outcomes,
1496
+ applied,
1497
+ failed: outcomes.length - applied
1498
+ }
1499
+ };
1500
+ }
1501
+ /**
1502
+ * Pure reducer: (document, action, params) -> (document, op).
1503
+ *
1504
+ * All validation is in-line: structural guards plus state-aware checks
1505
+ * (transition legality, dangling or deleted blockedBy, self-block, cycles,
1506
+ * in-flight delegations). The caller owns persistence and formatting.
1507
+ */
1508
+ function applyTaskMutation(document, action, params, now = (/* @__PURE__ */ new Date()).toISOString(), maxTasks = DEFAULT_REDUCER_MAX_TASKS) {
1509
+ switch (action) {
1510
+ case "upsert": {
1511
+ const items = params.tasks;
1512
+ if (!Array.isArray(items) || items.length === 0) return errorResult(document, "upsert requires a non-empty tasks array, e.g. {\"action\":\"upsert\",\"tasks\":[{\"subject\":\"Write tests\"}]}");
1513
+ if (items.length > 100) return errorResult(document, `upsert accepts at most 100 entries per call (received ${items.length})`);
1514
+ return applyUpsert(document, items, now, maxTasks);
1515
+ }
1516
+ case "list": return {
1517
+ document,
1518
+ op: {
1519
+ kind: "list",
1520
+ includeDeleted: params.includeDeleted === true,
1521
+ ...params.status !== void 0 ? { statusFilter: params.status } : {}
1522
+ }
1523
+ };
1524
+ case "get": {
1525
+ if (params.id === void 0) return errorResult(document, "id required for get");
1526
+ const task = document.tasks.find((candidate) => candidate.id === params.id);
1527
+ if (!task) return errorResult(document, `#${params.id} not found`);
1528
+ return {
1529
+ document,
1530
+ op: {
1531
+ kind: "get",
1532
+ task
1533
+ }
1534
+ };
1535
+ }
1536
+ case "delete": {
1537
+ if (params.id === void 0) return errorResult(document, "id required for delete");
1538
+ const index = document.tasks.findIndex((task) => task.id === params.id);
1539
+ if (index === -1) return errorResult(document, `#${params.id} not found`);
1540
+ const current = document.tasks[index];
1541
+ if (current.status === "deleted") return errorResult(document, `#${current.id} is already deleted`);
1542
+ if (isDelegationActive(current)) return errorResult(document, `#${current.id} has a running delegation — cancel it before deleting`);
1543
+ const tasks = [...document.tasks];
1544
+ tasks[index] = {
1545
+ ...current,
1546
+ status: DELETED_STATUS$1,
1547
+ updatedAt: now
1548
+ };
1549
+ return {
1550
+ document: withTasks(document, tasks),
1551
+ op: {
1552
+ kind: "delete",
1553
+ id: current.id,
1554
+ subject: current.subject
1555
+ }
1556
+ };
1557
+ }
1558
+ case "clear": {
1559
+ const active = document.tasks.filter(isDelegationActive);
1560
+ if (active.length > 0) return errorResult(document, `cannot clear while delegations are running (${active.map((task) => `#${task.id}`).join(", ")}) — cancel them first`);
1561
+ const count = document.tasks.length;
1562
+ return {
1563
+ document: withTasks(document, [], 1),
1564
+ op: {
1565
+ kind: "clear",
1566
+ count
1567
+ }
1568
+ };
1569
+ }
1570
+ }
1571
+ }
1572
+ //#endregion
1573
+ //#region src/services/taskResult/index.ts
1574
+ const MSG_ALL_COMPLETE_CLEAR = "All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.";
1575
+ /**
1576
+ * Steering for a mixed batch. Unlike a batch of spawned subagents, a failed
1577
+ * entry here had no side effect at all, so retrying the failures is the safe
1578
+ * move and the model must be told so or it will do nothing. The hazard is the
1579
+ * other half: resending an applied create would make a second task.
1580
+ */
1581
+ const MSG_UPSERT_PARTIAL = "The applied entries are committed. Resend only the failed entries, corrected — a failed entry changed nothing, so a corrected retry is safe. Do not resend an entry that already applied: an entry without an id creates a second task.";
1582
+ const MSG_ASSIGN_PARTIAL = "Successful assignments are already running. Retry only the failed entries after correcting their task state or arguments; do not resend successful entries.";
1583
+ /** LLM-facing report for a native assignment batch. */
1584
+ function formatAssignmentResults(items) {
1585
+ if (items.length === 1) return items[0].message;
1586
+ const succeeded = items.filter((item) => item.ok).length;
1587
+ const failed = items.length - succeeded;
1588
+ const lines = [`Assigned ${succeeded}/${items.length} tasks${failed > 0 ? `; ${failed} failed` : ""}.`, ...items.map((item) => item.ok ? `- [${item.index}] Delegated #${item.id} to ${item.agent}` : `- [${item.index}] Failed #${item.id} → ${item.agent}: ${item.message}`)];
1589
+ if (failed > 0 && succeeded > 0) lines.push("", MSG_ASSIGN_PARTIAL);
1590
+ if (failed === 0) lines.push("", "All assignments are running independently in the background. Continue non-overlapping work, or end your turn.");
1591
+ return lines.join("\n");
1592
+ }
1593
+ /** `[status] #id subject (activeForm) [agent] ⛓ #dep` — the `list` line format. */
1594
+ function formatListLine(task) {
1595
+ const block = task.blockedBy?.length ? ` ⛓ ${task.blockedBy.map((id) => `#${id}`).join(",")}` : "";
1596
+ const form = task.status === "in_progress" && task.activeForm ? ` (${task.activeForm})` : "";
1597
+ const delegated = task.delegation && task.delegation.state !== "cancelled" ? ` [${task.delegation.agent}]` : "";
1598
+ return `[${task.status}] #${task.id} ${task.subject}${form}${delegated}${block}`;
1599
+ }
1600
+ function formatDelegationLines(task) {
1601
+ const delegation = task.delegation;
1602
+ if (!delegation) return [];
1603
+ const lines = [` delegated to: ${delegation.agent} (${delegation.state})`];
1604
+ if (delegation.model) lines.push(` model: ${delegation.model}`);
1605
+ if (delegation.result?.error) lines.push(` error: ${delegation.result.error}`);
1606
+ if (delegation.result?.outputPath) lines.push(` output file: ${delegation.result.outputPath}`);
1607
+ if (delegation.result?.output) lines.push(` output: ${delegation.result.output}`);
1608
+ return lines;
1609
+ }
1610
+ function formatGetLines(task, document) {
1611
+ const blocks = deriveBlocks(document.tasks).get(task.id) ?? [];
1612
+ const lines = [`#${task.id} [${task.status}] ${task.subject}`];
1613
+ if (task.description) lines.push(` description: ${task.description}`);
1614
+ if (task.activeForm) lines.push(` activeForm: ${task.activeForm}`);
1615
+ if (task.blockedBy?.length) lines.push(` blockedBy: ${task.blockedBy.map((id) => `#${id}`).join(", ")}`);
1616
+ if (blocks.length) lines.push(` blocks: ${blocks.map((id) => `#${id}`).join(", ")}`);
1617
+ if (task.owner) lines.push(` owner: ${task.owner}`);
1618
+ lines.push(...formatDelegationLines(task));
1619
+ return lines.join("\n");
1620
+ }
1621
+ /** One entry's outcome. Batch lines prefix this with `- [n] `. */
1622
+ function formatUpsertItem(item) {
1623
+ switch (item.kind) {
1624
+ case "created": {
1625
+ const ref = item.ref ? ` (ref "${item.ref}")` : "";
1626
+ const deps = item.blockedBy?.length ? ` — blocked by ${item.blockedBy.map((id) => `#${id}`).join(", ")}` : "";
1627
+ return `Created #${item.id}${ref}: ${item.subject} (${item.status})${deps}`;
1628
+ }
1629
+ case "updated": {
1630
+ const transition = item.fromStatus === item.toStatus ? "" : ` (${item.fromStatus} -> ${item.toStatus})`;
1631
+ return `Updated #${item.id}${transition}`;
1632
+ }
1633
+ case "unchanged": return `No change: #${item.id} already matches the requested values (status: ${item.status})`;
1634
+ case "failed": return `Failed${item.id === void 0 ? "" : ` #${item.id}`}: ${item.message}`;
1635
+ }
1636
+ }
1637
+ /**
1638
+ * Pure formatter: `(op, document) -> string`. The switch is closed over `Op`,
1639
+ * so a new reducer variant fails to compile until it is handled here.
1640
+ */
1641
+ function formatContent(op, document) {
1642
+ switch (op.kind) {
1643
+ case "upsert": {
1644
+ const lines = op.items.length === 1 ? [formatUpsertItem(op.items[0])] : [
1645
+ `Upsert applied ${op.applied}/${op.items.length} entries${op.failed > 0 ? `; ${op.failed} failed` : ""}.`,
1646
+ ...op.items.map((item) => `- [${item.index}] ${formatUpsertItem(item)}`),
1647
+ ...op.failed > 0 ? ["", MSG_UPSERT_PARTIAL] : []
1648
+ ];
1649
+ if (op.applied > 0 && isTaskListComplete(document.tasks)) lines.push(MSG_ALL_COMPLETE_CLEAR);
1650
+ return lines.join("\n");
1651
+ }
1652
+ case "delete": return `Deleted #${op.id}: ${op.subject}`;
1653
+ case "clear": return `Closed task list (cleared ${op.count} tasks)`;
1654
+ case "list": {
1655
+ let view = document.tasks;
1656
+ if (!op.includeDeleted) view = view.filter((task) => task.status !== "deleted");
1657
+ if (op.statusFilter) view = view.filter((task) => task.status === op.statusFilter);
1658
+ return view.length === 0 ? "No tasks" : view.map(formatListLine).join("\n");
1659
+ }
1660
+ case "get": return formatGetLines(op.task, document);
1661
+ case "error": return `Error: ${op.message}`;
1662
+ }
1663
+ }
1664
+ /** Build the LLM-facing envelope. `details` carries the post-mutation snapshot. */
1665
+ function buildToolResult(action, params, document, op) {
1666
+ return {
1667
+ content: [{
1668
+ type: "text",
1669
+ text: formatContent(op, document)
1670
+ }],
1671
+ details: {
1672
+ action,
1673
+ params,
1674
+ tasks: document.tasks,
1675
+ nextId: document.nextId,
1676
+ rev: document.rev,
1677
+ ...op.kind === "error" ? { error: op.message } : {},
1678
+ ...op.kind === "upsert" ? { upsert: {
1679
+ applied: op.items.flatMap((item) => item.kind === "failed" ? [] : [item.id]),
1680
+ failed: op.failed
1681
+ } } : {}
1682
+ }
1683
+ };
1684
+ }
1685
+ /** Envelope for a native assignment batch, including ids used by the consolidated TUI result. */
1686
+ function buildAssignmentResult(params, document, text, assignment) {
1687
+ return {
1688
+ content: [{
1689
+ type: "text",
1690
+ text
1691
+ }],
1692
+ details: {
1693
+ action: "assign",
1694
+ params,
1695
+ tasks: document.tasks,
1696
+ nextId: document.nextId,
1697
+ rev: document.rev,
1698
+ assignment
1699
+ }
1700
+ };
1701
+ }
1702
+ /** Envelope for delegation actions, which do not flow through the reducer. */
1703
+ function buildTextResult(action, params, document, text, error) {
1704
+ return {
1705
+ content: [{
1706
+ type: "text",
1707
+ text: error ? `Error: ${error}` : text
1708
+ }],
1709
+ details: {
1710
+ action,
1711
+ params,
1712
+ tasks: document.tasks,
1713
+ nextId: document.nextId,
1714
+ rev: document.rev,
1715
+ ...error ? { error } : {}
1716
+ }
1717
+ };
1718
+ }
1719
+ //#endregion
1720
+ //#region src/services/taskTool/index.ts
1721
+ function output(value) {
1722
+ if (typeof value === "object" && value !== null && "content" in value) return value;
1723
+ return {
1724
+ content: [{
1725
+ type: "text",
1726
+ text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
1727
+ }],
1728
+ details: value
1729
+ };
1730
+ }
1731
+ function failure(error) {
1732
+ return {
1733
+ content: [{
1734
+ type: "text",
1735
+ text: error instanceof Error ? error.message : String(error)
1736
+ }],
1737
+ isError: true
1738
+ };
1739
+ }
1740
+ async function reducerAction(store, action, params, maxTasks) {
1741
+ const { document, value } = await store.mutate((current) => {
1742
+ const result = applyTaskMutation(current, action, params, void 0, maxTasks);
1743
+ return {
1744
+ ...isCommittingOp(result.op) ? { document: result.document } : {},
1745
+ value: result
1746
+ };
1747
+ });
1748
+ if (value.op.kind === "error") throw new Error(value.op.message);
1749
+ return buildToolResult(action, params, document, value.op);
1750
+ }
1751
+ async function assignmentBatch(manager, assignments, signal) {
1752
+ const result = [];
1753
+ for (const [index, assignment] of assignments.entries()) try {
1754
+ const outcome = await manager.assign(assignment.id, {
1755
+ agent: assignment.agent,
1756
+ inlineAgent: assignment.inlineAgent,
1757
+ instructions: assignment.instructions,
1758
+ relevantFiles: assignment.relevantFiles,
1759
+ priorFindings: assignment.priorFindings,
1760
+ model: assignment.model,
1761
+ ...assignment.context === "fork" || assignment.context === "fresh" ? { context: assignment.context } : {},
1762
+ signal
1763
+ });
1764
+ result.push({
1765
+ index,
1766
+ id: assignment.id,
1767
+ agent: assignment.agent,
1768
+ ...outcome
1769
+ });
1770
+ } catch (error) {
1771
+ result.push({
1772
+ index,
1773
+ id: assignment.id,
1774
+ agent: assignment.agent,
1775
+ ok: false,
1776
+ message: String(error)
1777
+ });
1778
+ }
1779
+ return result;
1780
+ }
1781
+ function createHeadlessTaskTool(store, manager, maxTasks) {
1782
+ return {
1783
+ name: "task",
1784
+ label: "Task",
1785
+ description: "Maintain a persistent task graph and delegate ready tasks to background agents.",
1786
+ parameters: TaskParamsSchema,
1787
+ promptSnippet: "Track complex work persistently and delegate ready tasks",
1788
+ executionMode: "serial",
1789
+ async execute(_toolCallId, rawParams, signal, onUpdate) {
1790
+ if (!(0, typebox_value.Check)(TaskParamsSchema, rawParams)) return failure("Invalid task parameters.");
1791
+ const params = rawParams;
1792
+ try {
1793
+ if (params.action === "assign") {
1794
+ if (!params.assignments?.length) throw new Error("assign requires a non-empty assignments[] array");
1795
+ onUpdate?.(output(`Delegating ${params.assignments.length} task${params.assignments.length === 1 ? "" : "s"}...`));
1796
+ const items = await assignmentBatch(manager, params.assignments, signal);
1797
+ const assigned = items.filter((item) => item.ok).map((item) => item.id);
1798
+ const text = formatAssignmentResults(items);
1799
+ if (assigned.length === 0) throw new Error(text);
1800
+ return buildAssignmentResult(params, store.snapshot, text, {
1801
+ assigned,
1802
+ failed: items.length - assigned.length
1803
+ });
1804
+ }
1805
+ if (params.action === "cancel") {
1806
+ const outcome = await manager.cancel(params.id ?? NaN);
1807
+ if (!outcome.ok) throw new Error(outcome.message);
1808
+ return buildTextResult("cancel", params, store.snapshot, outcome.message);
1809
+ }
1810
+ return reducerAction(store, params.action, params, maxTasks);
1811
+ } catch (error) {
1812
+ return failure(error);
1813
+ }
1814
+ }
1815
+ };
1816
+ }
1817
+ //#endregion
1818
+ //#region src/extensions/workspaces/sessions/(backend)/tool/task.mcp.ts
1819
+ var task_mcp_default = (0, _agimon_ai_doompi_core_mcp_facet.defineMcpTool)(({ execution }) => {
1820
+ const store = new TaskStore({
1821
+ cwd: execution.cwd,
1822
+ env: execution.environment
1823
+ });
1824
+ store.configureSession(resolveSessionKey(execution.sessionId, execution.environment));
1825
+ const manager = new DelegationManager({
1826
+ store,
1827
+ cwd: execution.cwd,
1828
+ platform: createNodeDelegationPlatform(execution.environment),
1829
+ getSessionId: () => execution.sessionId,
1830
+ runTimeoutMs: getDelegationTimeoutMs(execution.environment),
1831
+ onNotifyError: (error) => void execution.client.notify({
1832
+ body: String(error),
1833
+ level: "warning"
1834
+ })
1835
+ });
1836
+ const tool = createHeadlessTaskTool(store, manager, getMaxTasks(execution.environment));
1837
+ let initialized;
1838
+ return {
1839
+ ...tool,
1840
+ async execute(...args) {
1841
+ initialized ??= store.readAsync().then(async () => {
1842
+ await manager.reconcile();
1843
+ });
1844
+ await initialized;
1845
+ return tool.execute(...args);
1846
+ }
1847
+ };
1848
+ });
1849
+ //#endregion
1850
+ //#region generated/mcp.ts
1851
+ const at = (value, context) => typeof value === "function" ? value(context) : value;
1852
+ const via = (identity, value) => ({
1853
+ ...identity,
1854
+ ...value
1855
+ });
1856
+ const mcp = (0, _agimon_ai_doompi_core_mcp_facet.defineMcpPlugin)({
1857
+ name: "@agimon-ai/doompi-task",
1858
+ session: (context) => ({ get tools() {
1859
+ return [via({ name: "task" }, at(task_mcp_default, context))];
1860
+ } })
1861
+ });
1862
+ //#endregion
1863
+ exports.default = mcp;
1864
+ exports.mcp = mcp;
1865
+
1866
+ //# sourceMappingURL=mcp.cjs.map