@agimon-ai/doompi-task 0.0.1-alpha.7 → 0.0.1-alpha.71

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 (439) hide show
  1. package/README.md +114 -15
  2. package/dist/api-contracts.cjs +1 -0
  3. package/dist/api-contracts.d.cts +2 -0
  4. package/dist/api-contracts.d.mts +2 -0
  5. package/dist/api-contracts.mjs +1 -0
  6. package/dist/commands.cjs +1 -2
  7. package/dist/commands.d.cts +2 -14
  8. package/dist/commands.d.mts +2 -14
  9. package/dist/commands.mjs +1 -2
  10. package/dist/config.cjs +1 -2
  11. package/dist/config.d.cts +2 -38
  12. package/dist/config.d.mts +2 -38
  13. package/dist/config.mjs +1 -2
  14. package/dist/constants/promptGuidelines.cjs +2 -0
  15. package/dist/constants/promptGuidelines.cjs.map +1 -0
  16. package/dist/constants/promptGuidelines.d.cts +13 -0
  17. package/dist/constants/promptGuidelines.d.cts.map +1 -0
  18. package/dist/constants/promptGuidelines.d.mts +13 -0
  19. package/dist/constants/promptGuidelines.d.mts.map +1 -0
  20. package/dist/constants/promptGuidelines.mjs +2 -0
  21. package/dist/constants/promptGuidelines.mjs.map +1 -0
  22. package/dist/constants/task.cjs +2 -0
  23. package/dist/constants/task.cjs.map +1 -0
  24. package/dist/constants/task.d.cts +4 -0
  25. package/dist/constants/task.d.cts.map +1 -0
  26. package/dist/constants/task.d.mts +4 -0
  27. package/dist/constants/task.d.mts.map +1 -0
  28. package/dist/constants/task.mjs +2 -0
  29. package/dist/constants/task.mjs.map +1 -0
  30. package/dist/controllers/tasksCommand.cjs +2 -0
  31. package/dist/controllers/tasksCommand.cjs.map +1 -0
  32. package/dist/controllers/tasksCommand.d.cts +15 -0
  33. package/dist/controllers/tasksCommand.d.cts.map +1 -0
  34. package/dist/controllers/tasksCommand.d.mts +15 -0
  35. package/dist/controllers/tasksCommand.d.mts.map +1 -0
  36. package/dist/controllers/tasksCommand.mjs +2 -0
  37. package/dist/controllers/tasksCommand.mjs.map +1 -0
  38. package/dist/controllers/webTasksChannel.cjs +2 -0
  39. package/dist/controllers/webTasksChannel.cjs.map +1 -0
  40. package/dist/controllers/webTasksChannel.mjs +2 -0
  41. package/dist/controllers/webTasksChannel.mjs.map +1 -0
  42. package/dist/delegation-manager.cjs +1 -0
  43. package/dist/delegation-manager.d.cts +3 -0
  44. package/dist/delegation-manager.d.mts +3 -0
  45. package/dist/delegation-manager.mjs +1 -0
  46. package/dist/extensions/pi.cjs +2 -1
  47. package/dist/extensions/pi.cjs.map +1 -1
  48. package/dist/extensions/pi.d.cts +6 -2
  49. package/dist/extensions/pi.d.cts.map +1 -0
  50. package/dist/extensions/pi.d.mts +6 -2
  51. package/dist/extensions/pi.d.mts.map +1 -0
  52. package/dist/extensions/pi.mjs +2 -1
  53. package/dist/extensions/pi.mjs.map +1 -1
  54. package/dist/extensions/server.cjs +2 -0
  55. package/dist/extensions/server.cjs.map +1 -0
  56. package/dist/extensions/server.d.cts +5 -0
  57. package/dist/extensions/server.d.cts.map +1 -0
  58. package/dist/extensions/server.d.mts +5 -0
  59. package/dist/extensions/server.d.mts.map +1 -0
  60. package/dist/extensions/server.mjs +2 -0
  61. package/dist/extensions/server.mjs.map +1 -0
  62. package/dist/index.cjs +1 -1
  63. package/dist/index.d.cts +15 -14
  64. package/dist/index.d.mts +15 -14
  65. package/dist/index.mjs +1 -1
  66. package/dist/logSinkTelemetry.cjs +1 -2
  67. package/dist/logSinkTelemetry.d.cts +3 -51
  68. package/dist/logSinkTelemetry.d.mts +3 -51
  69. package/dist/logSinkTelemetry.mjs +1 -2
  70. package/dist/models/task.cjs +2 -0
  71. package/dist/models/task.cjs.map +1 -0
  72. package/dist/{store/types.d.cts → models/task.d.cts} +41 -30
  73. package/dist/models/task.d.cts.map +1 -0
  74. package/dist/{store/types.d.mts → models/task.d.mts} +41 -30
  75. package/dist/models/task.d.mts.map +1 -0
  76. package/dist/{store/types.mjs → models/task.mjs} +1 -1
  77. package/dist/models/task.mjs.map +1 -0
  78. package/dist/models/taskGraph.cjs +2 -0
  79. package/dist/models/taskGraph.cjs.map +1 -0
  80. package/dist/{store → models}/taskGraph.d.cts +7 -8
  81. package/dist/models/taskGraph.d.cts.map +1 -0
  82. package/dist/{store → models}/taskGraph.d.mts +7 -8
  83. package/dist/models/taskGraph.d.mts.map +1 -0
  84. package/dist/models/taskGraph.mjs.map +1 -0
  85. package/dist/schemas/apiContracts.cjs +2 -0
  86. package/dist/schemas/apiContracts.cjs.map +1 -0
  87. package/dist/schemas/apiContracts.d.cts +53 -0
  88. package/dist/schemas/apiContracts.d.cts.map +1 -0
  89. package/dist/schemas/apiContracts.d.mts +53 -0
  90. package/dist/schemas/apiContracts.d.mts.map +1 -0
  91. package/dist/schemas/apiContracts.mjs +2 -0
  92. package/dist/schemas/apiContracts.mjs.map +1 -0
  93. package/dist/schemas/task.cjs +2 -0
  94. package/dist/schemas/task.cjs.map +1 -0
  95. package/dist/{tool/schema.d.cts → schemas/task.d.cts} +46 -29
  96. package/dist/schemas/task.d.cts.map +1 -0
  97. package/dist/{tool/schema.d.mts → schemas/task.d.mts} +46 -29
  98. package/dist/schemas/task.d.mts.map +1 -0
  99. package/dist/schemas/task.mjs +2 -0
  100. package/dist/schemas/task.mjs.map +1 -0
  101. package/dist/services/config/index.cjs +2 -0
  102. package/dist/services/config/index.cjs.map +1 -0
  103. package/dist/services/config/index.d.cts +42 -0
  104. package/dist/services/config/index.d.cts.map +1 -0
  105. package/dist/services/config/index.d.mts +42 -0
  106. package/dist/services/config/index.d.mts.map +1 -0
  107. package/dist/services/config/index.mjs +2 -0
  108. package/dist/services/config/index.mjs.map +1 -0
  109. package/dist/services/contextContribution/index.cjs +3 -0
  110. package/dist/services/contextContribution/index.cjs.map +1 -0
  111. package/dist/services/contextContribution/index.mjs +3 -0
  112. package/dist/services/contextContribution/index.mjs.map +1 -0
  113. package/dist/services/delegation/index.cjs +6 -0
  114. package/dist/services/delegation/index.cjs.map +1 -0
  115. package/dist/{delegation/manager.d.cts → services/delegation/index.d.cts} +52 -49
  116. package/dist/services/delegation/index.d.cts.map +1 -0
  117. package/dist/{delegation/manager.d.mts → services/delegation/index.d.mts} +52 -49
  118. package/dist/services/delegation/index.d.mts.map +1 -0
  119. package/dist/services/delegation/index.mjs +6 -0
  120. package/dist/services/delegation/index.mjs.map +1 -0
  121. package/dist/services/delegationPlatform/index.cjs +2 -0
  122. package/dist/services/delegationPlatform/index.cjs.map +1 -0
  123. package/dist/services/delegationPlatform/index.mjs +2 -0
  124. package/dist/services/delegationPlatform/index.mjs.map +1 -0
  125. package/dist/services/invariants/index.cjs +2 -0
  126. package/dist/services/invariants/index.cjs.map +1 -0
  127. package/dist/services/invariants/index.d.cts +23 -0
  128. package/dist/services/invariants/index.d.cts.map +1 -0
  129. package/dist/services/invariants/index.d.mts +23 -0
  130. package/dist/services/invariants/index.d.mts.map +1 -0
  131. package/dist/services/invariants/index.mjs +2 -0
  132. package/dist/services/invariants/index.mjs.map +1 -0
  133. package/dist/services/logSinkTelemetry/index.cjs +2 -0
  134. package/dist/services/logSinkTelemetry/index.cjs.map +1 -0
  135. package/dist/services/logSinkTelemetry/index.d.cts +23 -0
  136. package/dist/services/logSinkTelemetry/index.d.cts.map +1 -0
  137. package/dist/services/logSinkTelemetry/index.d.mts +23 -0
  138. package/dist/services/logSinkTelemetry/index.d.mts.map +1 -0
  139. package/dist/services/logSinkTelemetry/index.mjs +2 -0
  140. package/dist/services/logSinkTelemetry/index.mjs.map +1 -0
  141. package/dist/services/paths/index.cjs +2 -0
  142. package/dist/services/paths/index.cjs.map +1 -0
  143. package/dist/services/paths/index.d.cts +25 -0
  144. package/dist/services/paths/index.d.cts.map +1 -0
  145. package/dist/services/paths/index.d.mts +25 -0
  146. package/dist/services/paths/index.d.mts.map +1 -0
  147. package/dist/services/paths/index.mjs +2 -0
  148. package/dist/services/paths/index.mjs.map +1 -0
  149. package/dist/services/processLiveness/index.cjs +2 -0
  150. package/dist/services/processLiveness/index.cjs.map +1 -0
  151. package/dist/{store/processLiveness.d.cts → services/processLiveness/index.d.cts} +3 -4
  152. package/dist/services/processLiveness/index.d.cts.map +1 -0
  153. package/dist/{store/processLiveness.d.mts → services/processLiveness/index.d.mts} +3 -4
  154. package/dist/services/processLiveness/index.d.mts.map +1 -0
  155. package/dist/{store/processLiveness.mjs → services/processLiveness/index.mjs} +1 -1
  156. package/dist/services/processLiveness/index.mjs.map +1 -0
  157. package/dist/services/reconcile/index.cjs +2 -0
  158. package/dist/services/reconcile/index.cjs.map +1 -0
  159. package/dist/{store/reconcile.d.cts → services/reconcile/index.d.cts} +8 -9
  160. package/dist/services/reconcile/index.d.cts.map +1 -0
  161. package/dist/{store/reconcile.d.mts → services/reconcile/index.d.mts} +8 -9
  162. package/dist/services/reconcile/index.d.mts.map +1 -0
  163. package/dist/services/reconcile/index.mjs +2 -0
  164. package/dist/services/reconcile/index.mjs.map +1 -0
  165. package/dist/services/reducer/index.cjs +3 -0
  166. package/dist/services/reducer/index.cjs.map +1 -0
  167. package/dist/{store/reducer.d.cts → services/reducer/index.d.cts} +12 -13
  168. package/dist/services/reducer/index.d.cts.map +1 -0
  169. package/dist/{store/reducer.d.mts → services/reducer/index.d.mts} +12 -13
  170. package/dist/services/reducer/index.d.mts.map +1 -0
  171. package/dist/services/reducer/index.mjs +3 -0
  172. package/dist/services/reducer/index.mjs.map +1 -0
  173. package/dist/services/taskNarration/index.cjs +2 -0
  174. package/dist/services/taskNarration/index.cjs.map +1 -0
  175. package/dist/services/taskNarration/index.mjs +2 -0
  176. package/dist/services/taskNarration/index.mjs.map +1 -0
  177. package/dist/services/taskResult/index.cjs +7 -0
  178. package/dist/services/taskResult/index.cjs.map +1 -0
  179. package/dist/services/taskResult/index.d.cts +50 -0
  180. package/dist/services/taskResult/index.d.cts.map +1 -0
  181. package/dist/services/taskResult/index.d.mts +50 -0
  182. package/dist/services/taskResult/index.d.mts.map +1 -0
  183. package/dist/services/taskResult/index.mjs +7 -0
  184. package/dist/services/taskResult/index.mjs.map +1 -0
  185. package/dist/services/taskStore/index.cjs +2 -0
  186. package/dist/services/taskStore/index.cjs.map +1 -0
  187. package/dist/{store/taskStore.d.cts → services/taskStore/index.d.cts} +17 -25
  188. package/dist/services/taskStore/index.d.cts.map +1 -0
  189. package/dist/{store/taskStore.d.mts → services/taskStore/index.d.mts} +17 -25
  190. package/dist/services/taskStore/index.d.mts.map +1 -0
  191. package/dist/services/taskStore/index.mjs +2 -0
  192. package/dist/services/taskStore/index.mjs.map +1 -0
  193. package/dist/store-invariants.cjs +1 -0
  194. package/dist/store-invariants.d.cts +2 -0
  195. package/dist/store-invariants.d.mts +2 -0
  196. package/dist/store-invariants.mjs +1 -0
  197. package/dist/store-paths.cjs +1 -0
  198. package/dist/store-paths.d.cts +2 -0
  199. package/dist/store-paths.d.mts +2 -0
  200. package/dist/store-paths.mjs +1 -0
  201. package/dist/store-process-liveness.cjs +1 -0
  202. package/dist/store-process-liveness.d.cts +2 -0
  203. package/dist/store-process-liveness.d.mts +2 -0
  204. package/dist/store-process-liveness.mjs +1 -0
  205. package/dist/store-reconcile.cjs +1 -0
  206. package/dist/store-reconcile.d.cts +2 -0
  207. package/dist/store-reconcile.d.mts +2 -0
  208. package/dist/store-reconcile.mjs +1 -0
  209. package/dist/store-reducer.cjs +1 -0
  210. package/dist/store-reducer.d.cts +2 -0
  211. package/dist/store-reducer.d.mts +2 -0
  212. package/dist/store-reducer.mjs +1 -0
  213. package/dist/store-task-graph.cjs +1 -0
  214. package/dist/store-task-graph.d.cts +2 -0
  215. package/dist/store-task-graph.d.mts +2 -0
  216. package/dist/store-task-graph.mjs +1 -0
  217. package/dist/store-task-store.cjs +1 -0
  218. package/dist/store-task-store.d.cts +2 -0
  219. package/dist/store-task-store.d.mts +2 -0
  220. package/dist/store-task-store.mjs +1 -0
  221. package/dist/store-types.cjs +1 -0
  222. package/dist/store-types.d.cts +2 -0
  223. package/dist/store-types.d.mts +2 -0
  224. package/dist/store-types.mjs +1 -0
  225. package/dist/tool-prompt-guidelines.cjs +1 -0
  226. package/dist/tool-prompt-guidelines.d.cts +2 -0
  227. package/dist/tool-prompt-guidelines.d.mts +2 -0
  228. package/dist/tool-prompt-guidelines.mjs +1 -0
  229. package/dist/tool-response-envelope.cjs +1 -0
  230. package/dist/tool-response-envelope.d.cts +2 -0
  231. package/dist/tool-response-envelope.d.mts +2 -0
  232. package/dist/tool-response-envelope.mjs +1 -0
  233. package/dist/tool-schema.cjs +1 -0
  234. package/dist/tool-schema.d.cts +3 -0
  235. package/dist/tool-schema.d.mts +3 -0
  236. package/dist/tool-schema.mjs +1 -0
  237. package/dist/tool-task-tool.cjs +1 -0
  238. package/dist/tool-task-tool.d.cts +3 -0
  239. package/dist/tool-task-tool.d.mts +3 -0
  240. package/dist/tool-task-tool.mjs +1 -0
  241. package/dist/tools/task.cjs +3 -0
  242. package/dist/tools/task.cjs.map +1 -0
  243. package/dist/tools/task.d.cts +22 -0
  244. package/dist/tools/task.d.cts.map +1 -0
  245. package/dist/tools/task.d.mts +22 -0
  246. package/dist/tools/task.d.mts.map +1 -0
  247. package/dist/tools/task.mjs +3 -0
  248. package/dist/tools/task.mjs.map +1 -0
  249. package/dist/tui/format.cjs +3 -3
  250. package/dist/tui/format.cjs.map +1 -1
  251. package/dist/tui/format.d.cts +19 -20
  252. package/dist/tui/format.d.cts.map +1 -1
  253. package/dist/tui/format.d.mts +19 -20
  254. package/dist/tui/format.d.mts.map +1 -1
  255. package/dist/tui/format.mjs +3 -3
  256. package/dist/tui/format.mjs.map +1 -1
  257. package/dist/tui/selectors.cjs +1 -1
  258. package/dist/tui/selectors.cjs.map +1 -1
  259. package/dist/tui/selectors.d.cts +20 -14
  260. package/dist/tui/selectors.d.cts.map +1 -1
  261. package/dist/tui/selectors.d.mts +20 -14
  262. package/dist/tui/selectors.d.mts.map +1 -1
  263. package/dist/tui/selectors.mjs +1 -1
  264. package/dist/tui/selectors.mjs.map +1 -1
  265. package/dist/tui/taskOverlay.cjs +1 -1
  266. package/dist/tui/taskOverlay.cjs.map +1 -1
  267. package/dist/tui/taskOverlay.d.cts +4 -5
  268. package/dist/tui/taskOverlay.d.cts.map +1 -1
  269. package/dist/tui/taskOverlay.d.mts +4 -5
  270. package/dist/tui/taskOverlay.d.mts.map +1 -1
  271. package/dist/tui/taskOverlay.mjs +1 -1
  272. package/dist/tui/taskOverlay.mjs.map +1 -1
  273. package/dist/tui/taskSpace.cjs +3 -3
  274. package/dist/tui/taskSpace.cjs.map +1 -1
  275. package/dist/tui/taskSpace.d.cts +9 -10
  276. package/dist/tui/taskSpace.d.cts.map +1 -1
  277. package/dist/tui/taskSpace.d.mts +9 -10
  278. package/dist/tui/taskSpace.d.mts.map +1 -1
  279. package/dist/tui/taskSpace.mjs +3 -3
  280. package/dist/tui/taskSpace.mjs.map +1 -1
  281. package/dist/tui-format.cjs +1 -0
  282. package/dist/tui-format.d.cts +2 -0
  283. package/dist/tui-format.d.mts +2 -0
  284. package/dist/tui-format.mjs +1 -0
  285. package/dist/tui-selectors.cjs +1 -0
  286. package/dist/tui-selectors.d.cts +2 -0
  287. package/dist/tui-selectors.d.mts +2 -0
  288. package/dist/tui-selectors.mjs +1 -0
  289. package/dist/tui-task-overlay.cjs +1 -0
  290. package/dist/tui-task-overlay.d.cts +2 -0
  291. package/dist/tui-task-overlay.d.mts +2 -0
  292. package/dist/tui-task-overlay.mjs +1 -0
  293. package/dist/tui-task-space.cjs +1 -0
  294. package/dist/tui-task-space.d.cts +2 -0
  295. package/dist/tui-task-space.d.mts +2 -0
  296. package/dist/tui-task-space.mjs +1 -0
  297. package/dist/types/delegation.cjs +2 -0
  298. package/dist/types/delegation.cjs.map +1 -0
  299. package/dist/types/delegation.d.cts +5 -0
  300. package/dist/types/delegation.d.cts.map +1 -0
  301. package/dist/types/delegation.d.mts +5 -0
  302. package/dist/types/delegation.d.mts.map +1 -0
  303. package/dist/types/delegation.mjs +2 -0
  304. package/dist/types/delegation.mjs.map +1 -0
  305. package/dist/types/telemetry.cjs +2 -0
  306. package/dist/types/telemetry.cjs.map +1 -0
  307. package/dist/types/telemetry.d.cts +35 -0
  308. package/dist/types/telemetry.d.cts.map +1 -0
  309. package/dist/types/telemetry.d.mts +35 -0
  310. package/dist/types/telemetry.d.mts.map +1 -0
  311. package/dist/types/telemetry.mjs +2 -0
  312. package/dist/types/telemetry.mjs.map +1 -0
  313. package/dist/types/webTasks.cjs +2 -0
  314. package/dist/types/webTasks.cjs.map +1 -0
  315. package/dist/types/webTasks.mjs +2 -0
  316. package/dist/types/webTasks.mjs.map +1 -0
  317. package/package.json +158 -109
  318. package/src/extensions/web.ts +18 -0
  319. package/src/types/webTasks.ts +24 -0
  320. package/src/web/components/TaskDetailDialog.tsx +251 -0
  321. package/src/web/components/TaskToolMessage.tsx +120 -0
  322. package/src/web/components/TasksActivitySection.tsx +200 -0
  323. package/src/web/lib/taskToolFormat.ts +330 -0
  324. package/src/web/stores/tasksStore.ts +114 -0
  325. package/src/web/tsconfig.json +23 -0
  326. package/dist/commands.cjs.map +0 -1
  327. package/dist/commands.d.cts.map +0 -1
  328. package/dist/commands.d.mts.map +0 -1
  329. package/dist/commands.mjs.map +0 -1
  330. package/dist/config.cjs.map +0 -1
  331. package/dist/config.d.cts.map +0 -1
  332. package/dist/config.d.mts.map +0 -1
  333. package/dist/config.mjs.map +0 -1
  334. package/dist/delegation/manager.cjs +0 -6
  335. package/dist/delegation/manager.cjs.map +0 -1
  336. package/dist/delegation/manager.d.cts.map +0 -1
  337. package/dist/delegation/manager.d.mts.map +0 -1
  338. package/dist/delegation/manager.mjs +0 -6
  339. package/dist/delegation/manager.mjs.map +0 -1
  340. package/dist/extension.cjs +0 -3
  341. package/dist/extension.cjs.map +0 -1
  342. package/dist/extension.d.cts +0 -12
  343. package/dist/extension.d.cts.map +0 -1
  344. package/dist/extension.d.mts +0 -12
  345. package/dist/extension.d.mts.map +0 -1
  346. package/dist/extension.mjs +0 -3
  347. package/dist/extension.mjs.map +0 -1
  348. package/dist/extensions/doom.cjs +0 -2
  349. package/dist/extensions/doom.cjs.map +0 -1
  350. package/dist/extensions/doom.d.cts +0 -6
  351. package/dist/extensions/doom.d.cts.map +0 -1
  352. package/dist/extensions/doom.d.mts +0 -7
  353. package/dist/extensions/doom.d.mts.map +0 -1
  354. package/dist/extensions/doom.mjs +0 -2
  355. package/dist/extensions/doom.mjs.map +0 -1
  356. package/dist/logSinkTelemetry.cjs.map +0 -1
  357. package/dist/logSinkTelemetry.d.cts.map +0 -1
  358. package/dist/logSinkTelemetry.d.mts.map +0 -1
  359. package/dist/logSinkTelemetry.mjs.map +0 -1
  360. package/dist/store/invariants.cjs +0 -2
  361. package/dist/store/invariants.cjs.map +0 -1
  362. package/dist/store/invariants.d.cts +0 -14
  363. package/dist/store/invariants.d.cts.map +0 -1
  364. package/dist/store/invariants.d.mts +0 -14
  365. package/dist/store/invariants.d.mts.map +0 -1
  366. package/dist/store/invariants.mjs +0 -2
  367. package/dist/store/invariants.mjs.map +0 -1
  368. package/dist/store/paths.cjs +0 -2
  369. package/dist/store/paths.cjs.map +0 -1
  370. package/dist/store/paths.d.cts +0 -23
  371. package/dist/store/paths.d.cts.map +0 -1
  372. package/dist/store/paths.d.mts +0 -23
  373. package/dist/store/paths.d.mts.map +0 -1
  374. package/dist/store/paths.mjs +0 -2
  375. package/dist/store/paths.mjs.map +0 -1
  376. package/dist/store/processLiveness.cjs +0 -2
  377. package/dist/store/processLiveness.cjs.map +0 -1
  378. package/dist/store/processLiveness.d.cts.map +0 -1
  379. package/dist/store/processLiveness.d.mts.map +0 -1
  380. package/dist/store/processLiveness.mjs.map +0 -1
  381. package/dist/store/reconcile.cjs +0 -2
  382. package/dist/store/reconcile.cjs.map +0 -1
  383. package/dist/store/reconcile.d.cts.map +0 -1
  384. package/dist/store/reconcile.d.mts.map +0 -1
  385. package/dist/store/reconcile.mjs +0 -2
  386. package/dist/store/reconcile.mjs.map +0 -1
  387. package/dist/store/reducer.cjs +0 -3
  388. package/dist/store/reducer.cjs.map +0 -1
  389. package/dist/store/reducer.d.cts.map +0 -1
  390. package/dist/store/reducer.d.mts.map +0 -1
  391. package/dist/store/reducer.mjs +0 -3
  392. package/dist/store/reducer.mjs.map +0 -1
  393. package/dist/store/taskGraph.cjs +0 -2
  394. package/dist/store/taskGraph.cjs.map +0 -1
  395. package/dist/store/taskGraph.d.cts.map +0 -1
  396. package/dist/store/taskGraph.d.mts.map +0 -1
  397. package/dist/store/taskGraph.mjs.map +0 -1
  398. package/dist/store/taskStore.cjs +0 -2
  399. package/dist/store/taskStore.cjs.map +0 -1
  400. package/dist/store/taskStore.d.cts.map +0 -1
  401. package/dist/store/taskStore.d.mts.map +0 -1
  402. package/dist/store/taskStore.mjs +0 -2
  403. package/dist/store/taskStore.mjs.map +0 -1
  404. package/dist/store/types.cjs +0 -2
  405. package/dist/store/types.cjs.map +0 -1
  406. package/dist/store/types.d.cts.map +0 -1
  407. package/dist/store/types.d.mts.map +0 -1
  408. package/dist/store/types.mjs.map +0 -1
  409. package/dist/tool/promptGuidelines.cjs +0 -2
  410. package/dist/tool/promptGuidelines.cjs.map +0 -1
  411. package/dist/tool/promptGuidelines.d.cts +0 -5
  412. package/dist/tool/promptGuidelines.d.cts.map +0 -1
  413. package/dist/tool/promptGuidelines.d.mts +0 -5
  414. package/dist/tool/promptGuidelines.d.mts.map +0 -1
  415. package/dist/tool/promptGuidelines.mjs +0 -2
  416. package/dist/tool/promptGuidelines.mjs.map +0 -1
  417. package/dist/tool/responseEnvelope.cjs +0 -6
  418. package/dist/tool/responseEnvelope.cjs.map +0 -1
  419. package/dist/tool/responseEnvelope.d.cts +0 -39
  420. package/dist/tool/responseEnvelope.d.cts.map +0 -1
  421. package/dist/tool/responseEnvelope.d.mts +0 -39
  422. package/dist/tool/responseEnvelope.d.mts.map +0 -1
  423. package/dist/tool/responseEnvelope.mjs +0 -6
  424. package/dist/tool/responseEnvelope.mjs.map +0 -1
  425. package/dist/tool/schema.cjs +0 -2
  426. package/dist/tool/schema.cjs.map +0 -1
  427. package/dist/tool/schema.d.cts.map +0 -1
  428. package/dist/tool/schema.d.mts.map +0 -1
  429. package/dist/tool/schema.mjs +0 -2
  430. package/dist/tool/schema.mjs.map +0 -1
  431. package/dist/tool/taskTool.cjs +0 -3
  432. package/dist/tool/taskTool.cjs.map +0 -1
  433. package/dist/tool/taskTool.d.cts +0 -17
  434. package/dist/tool/taskTool.d.cts.map +0 -1
  435. package/dist/tool/taskTool.d.mts +0 -17
  436. package/dist/tool/taskTool.d.mts.map +0 -1
  437. package/dist/tool/taskTool.mjs +0 -3
  438. package/dist/tool/taskTool.mjs.map +0 -1
  439. /package/dist/{store → models}/taskGraph.mjs +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["DOOM_DELEGATION_ACCEPTED_EVENT","DOOM_DELEGATION_STARTED_EVENT","DOOM_DELEGATION_UPDATED_EVENT","DOOM_DELEGATION_FINISHED_EVENT","TASK_EVENT","reconcileOrphanedDelegations","isDelegationActive","isBlocked","isTaskListComplete"],"sources":["../../../src/services/delegation/index.ts"],"sourcesContent":["import {\n type DelegationAccepted as DelegationAcceptedPayload,\n DOOM_DELEGATION_ACCEPTED_EVENT,\n DOOM_DELEGATION_FINISHED_EVENT,\n DOOM_DELEGATION_STARTED_EVENT,\n DOOM_DELEGATION_UPDATED_EVENT,\n type DoomDelegationService,\n type DelegationResult,\n type DelegationStarted as DelegationStartedPayload,\n type DelegationUpdate,\n type InlineAgent,\n} from '@agimon-ai/doompi-core/delegation';\nimport type { Context } from '@deepseek-ai/cordis';\n\nimport { isBlocked, isTaskListComplete } from '../../models/taskGraph';\nimport { MAX_BRIEF_FILES } from '../../types/delegation';\nimport { TASK_EVENT, type TaskEventName, type TaskFailureReporter } from '../../types/telemetry';\nimport { reconcileOrphanedDelegations } from '../reconcile';\nimport type { TaskStore } from '../taskStore';\n\nexport { MAX_BRIEF_FILES };\nimport { isDelegationActive, type Task, type TaskDelegation, type TaskDocument } from '../../models/task';\n\nexport const NOTIFY_CUSTOM_TYPE = 'doom-task-notify';\nexport const BACKGROUND_WORK_PROVIDER = 'doom-task';\n\nconst DEFAULT_STARTED_TIMEOUT_MS = 5000;\nconst DEFAULT_RUN_TIMEOUT_MS = 20 * 60 * 1000;\nconst DEFAULT_CANCEL_TIMEOUT_MS = 10_000;\nconst MAX_RUN_TIMEOUT_GRACE_MS = 60_000;\nconst MAX_STORED_OUTPUT = 4000;\n/**\n * Cap on files rendered into a brief. Exported so the tool schema can state the\n * same number to the model rather than restating it and drifting.\n */\nconst MAX_BRIEF_NOTES = 1500;\nconst COMPLETED_STATE = 'completed';\nconst FAILED_STATE = 'failed';\nconst CANCELLED_STATE = 'cancelled';\nconst TIMED_OUT_STATUS = 'timed_out';\nconst DELETED_STATUS: Task['status'] = 'deleted';\n\nconst TASK_ID_ATTRIBUTE = 'task.id';\nconst REQUEST_ID_ATTRIBUTE = 'delegation.request_id';\n// `_name` suffix is load-bearing: the telemetry redactor drops string values\n// whose key has no safe meaning, and a bare `delegation.agent` is dropped.\nconst AGENT_ATTRIBUTE = 'delegation.agent_name';\nconst PID_ATTRIBUTE = 'delegation.pid';\nconst CONTEXT_PRESENT_ATTRIBUTE = 'delegation.context_present';\nconst CONTEXT_FILE_COUNT_ATTRIBUTE = 'delegation.context_file_count';\nconst CONTEXT_NOTES_LENGTH_ATTRIBUTE = 'delegation.context_notes_length';\nconst BRIEF_LENGTH_ATTRIBUTE = 'delegation.brief_length';\nconst TOOL_COUNT_ATTRIBUTE = 'delegation.tool_count';\nconst DURATION_MS_ATTRIBUTE = 'delegation.duration_ms';\nconst OUTCOME_ATTRIBUTE = 'delegation.outcome';\n\ntype SettlementState = typeof COMPLETED_STATE | typeof FAILED_STATE | typeof CANCELLED_STATE;\n\nexport const ERR_NO_RUNTIME =\n 'No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.';\nexport const ERR_CHILD_SESSION =\n 'assign is only available in the main session. Update this task directly instead of re-delegating it.';\nexport const ERR_CANCEL_UNACKNOWLEDGED = 'Subagent did not acknowledge the cancel request';\n\n/** Live progress from a running subagent. Kept in memory: persisting per-tool\n * ticks would rewrite the store file every second for no durable benefit. */\nexport interface DelegationProgress {\n agent: string;\n currentTool?: string;\n toolCount?: number;\n tokens?: number;\n /** Latest child-runtime duration baseline, excluding assignment wait. */\n durationMs?: number;\n /** Wall-clock time at which durationMs was observed or rebased. */\n durationObservedAt?: number;\n /** Assign-time context-pack shape, carried so the completion event can be\n * grouped by it without joining back to the assignment event. */\n contextFileCount?: number;\n contextNotesLength?: number;\n}\n\nexport type DelegationNotifier = (\n message: { customType: string; content: string; display: boolean },\n options?: { triggerTurn?: boolean; deliverAs?: 'steer' | 'followUp' | 'nextTurn' },\n) => void;\n\nexport interface DelegationPlatform {\n readonly environment: Readonly<Record<string, string | undefined>>;\n readonly processId: number;\n readonly createRequestId: () => string;\n readonly formatBriefPath: (entry: string, cwd: string) => string;\n}\n\nexport interface DelegationManagerOptions {\n store: TaskStore;\n cwd: string;\n platform: DelegationPlatform;\n notify?: DelegationNotifier;\n getSessionId?: () => string | undefined;\n onChange?: () => void;\n startedTimeoutMs?: number;\n /** How long a started run may go without reporting a result. */\n runTimeoutMs?: number;\n /** How long to wait for a cancelled run to report back before forcing it. */\n cancelTimeoutMs?: number;\n now?: () => string;\n nowMs?: () => number;\n /** Called when a completion notification could not be delivered. */\n onNotifyError: (error: unknown, taskId: number) => void;\n /** Where other swallowed delegation failures go. */\n report?: TaskFailureReporter;\n}\n\nexport interface AssignOptions {\n agent?: string;\n inlineAgent?: InlineAgent;\n instructions?: string;\n /** Paths the parent already located, rendered into the brief so the child\n * skips rediscovering them. */\n relevantFiles?: string[];\n /** Facts the parent already established, rendered into the brief so the child\n * does not re-derive them. */\n priorFindings?: string;\n model?: string;\n context?: 'fresh' | 'fork';\n signal?: AbortSignal;\n}\n\nexport interface DelegationOutcome {\n ok: boolean;\n message: string;\n}\n\n/** Result of the guarded store mutation that claims a task for delegation. */\ninterface AssignAttempt extends DelegationOutcome {\n task?: Task;\n}\n\ninterface PendingTask {\n readonly taskId: number;\n readonly sessionId?: string;\n}\n\nfunction truncate(value: string | undefined, limit = MAX_STORED_OUTPUT): string | undefined {\n if (!value) return undefined;\n return value.length <= limit ? value : `${value.slice(0, limit)}\\n… (truncated)`;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** The assign-time context pack, normalized once for the brief and the telemetry. */\ninterface BriefContext {\n files: string[];\n notes?: string;\n}\n\n/** Normalize the parent context with host-owned path semantics. */\nfunction briefContext(options: AssignOptions, cwd: string, platform: DelegationPlatform): BriefContext {\n const files = new Set<string>();\n for (const entry of options.relevantFiles ?? []) {\n if (files.size >= MAX_BRIEF_FILES) break;\n const normalized = platform.formatBriefPath(entry.trim(), cwd);\n if (normalized && normalized !== '.') files.add(normalized);\n }\n return { files: [...files], notes: truncate(options.priorFindings?.trim(), MAX_BRIEF_NOTES) };\n}\n\n/**\n * Build the brief handed to the subagent.\n *\n * Doom Team owns the child tool surface and the parent owns the task record.\n * Keeping those responsibilities explicit prevents a child from attempting to\n * call a task tool that is not loaded in its runtime, while still giving it a\n * reliable path to ask the parent for a decision.\n *\n * The context pack is the parent's verified discovery handed over. The whole\n * block is omitted when nothing was supplied: this brief is the child's whole\n * starting context, so an empty section header is pure token cost.\n */\nfunction buildBrief(task: Task, instructions: string | undefined, context: BriefContext): string {\n const sections = [`Task #${task.id}: ${task.subject}`];\n if (task.description) sections.push(task.description);\n if (instructions) sections.push(instructions);\n if (context.files.length > 0 || context.notes) {\n const contextLines = ['Parent context — consume before repository discovery:'];\n if (context.files.length > 0) {\n contextLines.push(`- Parent-verified files (read these first with direct reads): ${context.files.join(', ')}`);\n }\n if (context.notes) {\n contextLines.push(\n `- Established facts (do not re-derive unless direct evidence contradicts them): ${context.notes}`,\n );\n }\n contextLines.push(\n '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.',\n );\n sections.push(contextLines.join('\\n'));\n }\n sections.push(\n 'Coordination: work directly without changing the task record; ask main through intercom only for blockers or decisions; report changed files and verification when done.',\n );\n return sections.join('\\n\\n');\n}\n\n/**\n * Owns the lifecycle of tasks delegated to subagents.\n *\n * Delegation rides Team's injected Cordis service rather than spawning\n * processes directly, so doom-task stays decoupled from the subagent runtime\n * and degrades to a clear error when that service is not loaded.\n *\n * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so\n * a delegation always has a deadline no matter which phase it is in. Losing\n * that pairing is what previously left tasks running forever.\n */\nexport class DelegationManager {\n private readonly options: DelegationManagerOptions;\n private readonly progress = new Map<string, DelegationProgress>();\n private readonly pendingTasks = new Map<string, PendingTask>();\n private readonly settlingRequests = new Set<string>();\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n private readonly subscriptions: Array<() => void> = [];\n private service: DoomDelegationService | undefined;\n\n constructor(options: DelegationManagerOptions) {\n this.options = options;\n }\n\n private now(): string {\n return this.options.now?.() ?? new Date().toISOString();\n }\n\n private nowMs(): number {\n return this.options.nowMs?.() ?? Date.now();\n }\n\n private get runTimeoutMs(): number {\n return this.options.runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;\n }\n\n private report(event: TaskEventName, error: unknown, attributes?: Record<string, string | number | boolean>): void {\n this.options.report?.error(event, error, attributes);\n }\n\n /** True in a session that is itself a subagent child. */\n get isChildSession(): boolean {\n return Boolean(this.options.platform.environment.PI_SUBAGENT_CHILD);\n }\n\n /** Live progress for a task, for the overlay to render. */\n progressFor(task: Task): DelegationProgress | undefined {\n const requestId = task.delegation?.requestId;\n return requestId ? this.progress.get(requestId) : undefined;\n }\n\n /** Displayed runtime duration, rebased from the latest child observation. */\n static elapsedMs(progress: DelegationProgress, nowMs = Date.now()): number {\n const baseline = progress.durationMs ?? 0;\n const observedAt = progress.durationObservedAt ?? nowMs;\n return baseline + Math.max(0, nowMs - observedAt);\n }\n\n /** Rebind to the active Team service without stacking lifecycle listeners. */\n bind(ctx: Context, service: DoomDelegationService): () => void {\n this.unbind();\n this.service = service;\n this.subscriptions.push(\n ctx.on(DOOM_DELEGATION_ACCEPTED_EVENT, (event) => {\n this.handleAccepted(event);\n }),\n ctx.on(DOOM_DELEGATION_STARTED_EVENT, (event) => {\n this.handleStarted(event);\n }),\n ctx.on(DOOM_DELEGATION_UPDATED_EVENT, (event) => {\n this.handleUpdate(event);\n }),\n ctx.on(DOOM_DELEGATION_FINISHED_EVENT, (event) => {\n void this.handleResponse(event).catch((error: unknown) => {\n this.report(TASK_EVENT.delegationResponseFailed, error, { [REQUEST_ID_ATTRIBUTE]: event.requestId });\n });\n }),\n );\n return () => {\n if (this.service === service) this.unbind();\n };\n }\n\n /** Remove only the cross-package binding; task state and watchdogs remain live. */\n unbind(): void {\n for (const unsubscribe of this.subscriptions.splice(0)) unsubscribe();\n this.service = undefined;\n }\n\n /** Items still in flight, surfaced so auto-stop will not kill the harness. */\n listActiveWork(): Array<{ id: string; sessionId: string }> {\n return [...this.pendingTasks.entries()].flatMap(([requestId, pending]) =>\n pending.sessionId ? [{ id: `task-${pending.taskId}:${requestId}`, sessionId: pending.sessionId }] : [],\n );\n }\n\n /**\n * Return tasks nothing can finish to `pending`.\n *\n * The live request set is read inside the mutation so a delegation assigned\n * while the lock was contended is not mistaken for a leftover.\n */\n async reconcile(isCurrent: () => boolean = () => true): Promise<Task[]> {\n const { value } = await this.options.store.mutate((document) => {\n if (!isCurrent()) return { value: [] as Task[] };\n const result = reconcileOrphanedDelegations(document, this.now(), undefined, {\n pid: this.options.platform.processId,\n liveRequestIds: new Set(this.pendingTasks.keys()),\n });\n if (result.orphaned.length === 0) return { value: [] as Task[] };\n return { document: result.document, value: result.orphaned };\n });\n\n if (!isCurrent()) return [];\n for (const task of value) {\n this.options.report?.warn(TASK_EVENT.delegationOrphaned, new Error(task.delegation?.result?.error ?? ''), {\n [TASK_ID_ATTRIBUTE]: task.id,\n ...(task.delegation?.agent ? { [AGENT_ATTRIBUTE]: task.delegation.agent } : {}),\n ...(task.delegation?.pid === undefined ? {} : { [PID_ATTRIBUTE]: task.delegation.pid }),\n });\n }\n\n if (value.length > 0) this.options.onChange?.();\n return value;\n }\n\n async assign(taskId: number, options: AssignOptions): Promise<DelegationOutcome> {\n const agent = options.agent?.trim();\n if (!agent) return { ok: false, message: 'agent required for assign' };\n if (this.isChildSession) return { ok: false, message: ERR_CHILD_SESSION };\n if (options.signal?.aborted) return { ok: false, message: 'delegation cancelled before it started' };\n\n const requestId = this.options.platform.createRequestId();\n const startedAt = this.now();\n const sessionId = this.options.getSessionId?.();\n const context = briefContext(options, this.options.cwd, this.options.platform);\n\n const { value: outcome } = await this.options.store.mutate<AssignAttempt>((current) => {\n const index = current.tasks.findIndex((task) => task.id === taskId);\n if (index === -1) return { value: { ok: false, message: `#${taskId} not found` } };\n\n const task = current.tasks[index];\n if (task.status === DELETED_STATUS) return { value: { ok: false, message: `#${taskId} is deleted` } };\n if (task.status === COMPLETED_STATE) {\n return { value: { ok: false, message: `#${taskId} is already completed` } };\n }\n if (isDelegationActive(task)) {\n return { value: { ok: false, message: `#${taskId} is already delegated to ${task.delegation?.agent}` } };\n }\n if (isBlocked(current.tasks, task)) {\n const blockers = (task.blockedBy ?? []).map((id) => `#${id}`).join(', ');\n return { value: { ok: false, message: `#${taskId} is blocked by ${blockers}` } };\n }\n\n const delegation: TaskDelegation = {\n requestId,\n agent,\n state: 'requested',\n pid: this.options.platform.processId,\n startedAt,\n ...(sessionId ? { sessionId } : {}),\n ...(options.model ? { model: options.model } : {}),\n };\n\n const tasks = [...current.tasks];\n tasks[index] = { ...task, owner: agent, updatedAt: startedAt, delegation };\n return {\n document: { ...current, tasks },\n value: { ok: true, message: '', task: tasks[index] },\n };\n });\n\n if (!outcome.ok || !outcome.task) return { ok: false, message: outcome.message };\n\n const contextNotesLength = context.notes?.length ?? 0;\n this.pendingTasks.set(requestId, { taskId, sessionId });\n this.progress.set(requestId, { agent, contextFileCount: context.files.length, contextNotesLength });\n this.armStartedTimeout(requestId);\n this.options.onChange?.();\n const request = {\n requestId,\n taskId,\n agent,\n ...(options.inlineAgent ? { inlineAgent: options.inlineAgent } : {}),\n prompt: buildBrief(outcome.task, options.instructions, context),\n ...(options.context ? { context: options.context } : {}),\n cwd: this.options.cwd,\n artifacts: true,\n timeoutMs: this.runTimeoutMs,\n runMode: 'detached' as const,\n teamTask: { id: String(outcome.task.id), subject: outcome.task.subject },\n ...(options.model ? { model: options.model } : {}),\n };\n\n try {\n const service = this.service;\n if (!service) throw new Error(ERR_NO_RUNTIME);\n void service.request(request).catch((error: unknown) => {\n this.report(TASK_EVENT.delegationRequestFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n });\n this.settleDetached(requestId, FAILED_STATE, {\n status: FAILED_STATE,\n error: `Delegation request failed: ${messageOf(error)}`,\n });\n });\n } catch (error) {\n this.report(TASK_EVENT.delegationRequestFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n });\n const detail = messageOf(error);\n await this.settle(requestId, FAILED_STATE, {\n status: FAILED_STATE,\n error: `Delegation request failed: ${detail}`,\n });\n return { ok: false, message: `Could not dispatch #${taskId} to ${agent}: ${detail}` };\n }\n\n // Recorded only after the service accepted the request call, so it means a\n // brief actually entered Team's state machine rather than merely being assembled.\n this.options.report?.event(TASK_EVENT.delegationAssigned, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [CONTEXT_PRESENT_ATTRIBUTE]: context.files.length > 0 || contextNotesLength > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: context.files.length,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: contextNotesLength,\n [BRIEF_LENGTH_ATTRIBUTE]: request.prompt.length,\n });\n\n return {\n ok: true,\n 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.`,\n };\n }\n\n async cancel(taskId: number): Promise<DelegationOutcome> {\n const document = this.options.store.read();\n const task = document.tasks.find((candidate) => candidate.id === taskId);\n if (!task) return { ok: false, message: `#${taskId} not found` };\n if (!task.delegation || !isDelegationActive(task)) {\n return { ok: false, message: `#${taskId} has no running delegation` };\n }\n\n const { requestId } = task.delegation;\n this.service?.cancel({ requestId });\n // Only this session can force the outcome; a delegation owned elsewhere\n // gets the request and nothing more.\n this.armCancelTimeout(requestId);\n return { ok: true, message: `Cancelling delegation for #${taskId} (${task.delegation.agent})` };\n }\n\n /** Settle without awaiting, reporting rather than dropping a failure. */\n private settleDetached(\n requestId: string,\n state: SettlementState,\n result: TaskDelegation['result'],\n event: TaskEventName = TASK_EVENT.delegationSettleFailed,\n ): void {\n void this.settle(requestId, state, result).catch((error: unknown) => {\n this.report(event, error, { [REQUEST_ID_ATTRIBUTE]: requestId });\n });\n }\n\n /**\n * Fail a delegation that nobody acknowledged.\n *\n * Provider loss or a stalled Team runtime can still leave a dispatched\n * request silent. Without this acknowledgement deadline the task would sit\n * in `requested` forever.\n */\n private armStartedTimeout(requestId: string): void {\n this.armTimer(requestId, this.options.startedTimeoutMs ?? DEFAULT_STARTED_TIMEOUT_MS, () => {\n this.settleDetached(requestId, FAILED_STATE, { status: FAILED_STATE, error: ERR_NO_RUNTIME });\n });\n }\n\n /**\n * Bound a run that already started.\n *\n * The request carries the same budget, so in the normal case the runtime ends\n * the run itself and reports a richer result. The grace period biases toward\n * that answer; this timer only covers a runtime that goes silent, which is\n * precisely the case where no response event will ever arrive.\n */\n private armRunTimeout(requestId: string): void {\n const grace = Math.min(MAX_RUN_TIMEOUT_GRACE_MS, this.runTimeoutMs);\n this.armTimer(requestId, this.runTimeoutMs + grace, () => {\n const taskId = this.pendingTasks.get(requestId)?.taskId;\n const agent = this.progress.get(requestId)?.agent;\n const error = new Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);\n this.options.report?.warn(TASK_EVENT.delegationTimedOut, error, {\n ...(taskId === undefined ? {} : { [TASK_ID_ATTRIBUTE]: taskId }),\n [REQUEST_ID_ATTRIBUTE]: requestId,\n ...(agent ? { [AGENT_ATTRIBUTE]: agent } : {}),\n });\n this.service?.cancel({ requestId, reason: error.message });\n this.settleDetached(requestId, FAILED_STATE, { status: TIMED_OUT_STATUS, error: error.message });\n });\n }\n\n /**\n * Guarantee a cancel reaches a terminal state.\n *\n * Calling the service is a request, not an outcome: a runtime that has\n * already forgotten the request answers nothing at all. The window still\n * favours a real response, which carries the run's partial output.\n */\n private armCancelTimeout(requestId: string): void {\n if (!this.pendingTasks.has(requestId)) return;\n this.armTimer(requestId, this.options.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS, () => {\n this.settleDetached(requestId, CANCELLED_STATE, {\n status: CANCELLED_STATE,\n error: ERR_CANCEL_UNACKNOWLEDGED,\n });\n });\n }\n\n private armTimer(requestId: string, delayMs: number, onFire: () => void): void {\n this.clearTimer(requestId);\n const timer = setTimeout(onFire, delayMs);\n timer.unref?.();\n this.timers.set(requestId, timer);\n }\n\n private clearTimer(requestId: string): void {\n const timer = this.timers.get(requestId);\n if (timer) clearTimeout(timer);\n this.timers.delete(requestId);\n }\n\n /** Runtime acknowledgement moves the request off the short extension-presence watchdog while launch is in flight. */\n private handleAccepted(event: DelegationAcceptedPayload): void {\n if (!this.pendingTasks.has(event.requestId)) return;\n this.armRunTimeout(event.requestId);\n }\n\n private handleStarted(event: DelegationStartedPayload): void {\n const { runId } = event;\n const taskId = this.pendingTasks.get(event.requestId)?.taskId;\n if (taskId === undefined) return;\n this.armRunTimeout(event.requestId);\n const existing = this.progress.get(event.requestId);\n if (existing) {\n this.progress.set(event.requestId, {\n ...existing,\n durationMs: existing.durationMs ?? 0,\n durationObservedAt: existing.durationObservedAt ?? this.nowMs(),\n });\n }\n\n void this.options.store\n .mutate((document) =>\n this.patchDelegation(document, event.requestId, (task, delegation) => ({\n ...task,\n status: task.status === COMPLETED_STATE ? task.status : 'in_progress',\n delegation: {\n ...delegation,\n state: 'running',\n startedAt: delegation.startedAt ?? this.now(),\n ...(runId ? { runId } : {}),\n },\n })),\n )\n .then(() => this.options.onChange?.())\n .catch((error: unknown) => {\n this.report(TASK_EVENT.delegationStartFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: event.requestId,\n });\n });\n }\n\n private handleUpdate(event: DelegationUpdate): void {\n const existing = this.progress.get(event.requestId);\n if (!existing) return;\n\n const observedAt = this.nowMs();\n const currentElapsed = DelegationManager.elapsedMs(existing, observedAt);\n const hasDuration = event.durationMs !== undefined;\n this.progress.set(event.requestId, {\n // Spread, not field-by-field: anything carried on progress that this\n // event does not report (the assign-time context shape) must survive the\n // first update, or the completion event reports it as absent.\n ...existing,\n currentTool: event.currentTool ?? existing.currentTool,\n toolCount:\n event.toolCount === undefined ? existing.toolCount : Math.max(existing.toolCount ?? 0, event.toolCount),\n tokens: event.tokens === undefined ? existing.tokens : Math.max(existing.tokens ?? 0, event.tokens),\n durationMs: hasDuration ? Math.max(currentElapsed, event.durationMs!) : existing.durationMs,\n durationObservedAt: hasDuration ? observedAt : existing.durationObservedAt,\n });\n this.options.onChange?.();\n }\n\n private async handleResponse(event: DelegationResult): Promise<void> {\n if (!this.pendingTasks.has(event.requestId)) return;\n\n const succeeded = event.status === COMPLETED_STATE && !event.error;\n const state = succeeded ? COMPLETED_STATE : event.status === CANCELLED_STATE ? CANCELLED_STATE : FAILED_STATE;\n await this.settle(event.requestId, state, {\n status: event.status,\n error: event.error,\n output: truncate(event.output),\n outputPath: event.outputPath,\n sessionFile: event.sessionFile,\n durationMs: event.durationMs,\n toolCount: event.toolCount,\n });\n }\n\n /**\n * Apply the terminal state of a delegation and tell the model about it.\n *\n * A cancelled run returns the task to `pending` (the work is still wanted,\n * just not by that agent); a failure marks it `failed` so it stays visible\n * rather than silently rejoining the backlog.\n *\n * The request is claimed in `settlingRequests` while it remains published as\n * active work. It is removed only after the terminal state and model notification\n * have been handed off, so an auto-stop observer cannot end the session between\n * receiving the result and delivering it to the model.\n */\n private async settle(requestId: string, state: SettlementState, result: TaskDelegation['result']): Promise<void> {\n const pending = this.pendingTasks.get(requestId);\n if (!pending || this.settlingRequests.has(requestId)) return;\n this.settlingRequests.add(requestId);\n this.clearTimer(requestId);\n const { taskId } = pending;\n const progress = this.progress.get(requestId);\n\n try {\n const endedAt = this.now();\n let task: Task | undefined;\n try {\n const { value } = await this.options.store.mutate((document) =>\n this.patchDelegation(document, requestId, (current, delegation) => ({\n ...current,\n status: state === COMPLETED_STATE ? COMPLETED_STATE : state === CANCELLED_STATE ? 'pending' : FAILED_STATE,\n updatedAt: endedAt,\n delegation: { ...delegation, state, endedAt, ...(result ? { result } : {}) },\n })),\n );\n task = value;\n } catch (error) {\n this.report(TASK_EVENT.delegationSettleFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n });\n }\n\n const agent = task?.delegation?.agent ?? progress?.agent ?? 'subagent';\n const subject = task?.subject ?? `#${taskId}`;\n\n // Repeats the assign-time context shape so the cost question (\"did packs\n // reduce child tool calls?\") is one grouping rather than a self-join.\n // A run that never started reports neither metric, keeping the medians clean.\n this.options.report?.event(TASK_EVENT.delegationCompleted, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [OUTCOME_ATTRIBUTE]: state,\n [CONTEXT_PRESENT_ATTRIBUTE]: (progress?.contextFileCount ?? 0) > 0 || (progress?.contextNotesLength ?? 0) > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: progress?.contextFileCount ?? 0,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: progress?.contextNotesLength ?? 0,\n ...(result?.toolCount === undefined ? {} : { [TOOL_COUNT_ATTRIBUTE]: result.toolCount }),\n ...(result?.durationMs === undefined ? {} : { [DURATION_MS_ATTRIBUTE]: result.durationMs }),\n });\n const listComplete =\n state === COMPLETED_STATE && task !== undefined && isTaskListComplete(this.options.store.snapshot.tasks);\n this.notifyModel(state, taskId, subject, agent, result, listComplete);\n } finally {\n this.pendingTasks.delete(requestId);\n this.progress.delete(requestId);\n this.settlingRequests.delete(requestId);\n this.options.onChange?.();\n }\n }\n\n private notifyModel(\n state: SettlementState,\n taskId: number,\n subject: string,\n agent: string,\n result: TaskDelegation['result'],\n listComplete: boolean,\n ): void {\n const notify = this.options.notify;\n if (!notify) return;\n\n const headline =\n state === COMPLETED_STATE\n ? `Subagent ${agent} completed task #${taskId}: ${subject}`\n : state === CANCELLED_STATE\n ? `Subagent ${agent} was cancelled on task #${taskId}: ${subject} (returned to pending)`\n : `Subagent ${agent} failed task #${taskId}: ${subject}`;\n\n const lines = [headline];\n if (listComplete) {\n lines.push(\n '',\n 'All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.',\n );\n }\n if (result?.error) lines.push(`Error: ${result.error}`);\n if (result?.output) lines.push('', result.output);\n if (result?.outputPath) lines.push('', `Full output: ${result.outputPath}`);\n\n try {\n notify(\n { customType: NOTIFY_CUSTOM_TYPE, content: lines.join('\\n'), display: true },\n { triggerTurn: true, deliverAs: 'steer' },\n );\n } catch (error) {\n // The delegation state is already committed to the store, so a failed\n // notification costs the model its wake-up, not the result. Report it\n // rather than rethrowing, which would strand the settled run.\n this.options.onNotifyError(error, taskId);\n }\n }\n\n /**\n * Rewrite the task carrying `requestId`, returning the updated task as the mutation value.\n *\n * Terminal delegations are left alone. The document here is the freshest one,\n * read under the store lock, which is the only place the check is meaningful:\n * a `started` event can land after a cancel already settled the run, and\n * without this guard its write would resurrect a delegation that nothing is\n * tracking any more.\n */\n private patchDelegation(\n document: TaskDocument,\n requestId: string,\n patch: (task: Task, delegation: TaskDelegation) => Task,\n ): { document?: TaskDocument; value: Task | undefined } {\n const index = document.tasks.findIndex((task) => task.delegation?.requestId === requestId);\n if (index === -1) return { value: undefined };\n\n const task = document.tasks[index];\n if (!isDelegationActive(task)) return { value: task };\n\n const updated = patch(task, task.delegation!);\n if (updated === task) return { value: task };\n const tasks = [...document.tasks];\n tasks[index] = updated;\n return { document: { ...document, tasks }, value: updated };\n }\n\n dispose(): void {\n this.unbind();\n this.reset();\n }\n\n /** Clear one Pi session's transient delegation state without losing service injection. */\n reset(): void {\n const changed = this.pendingTasks.size > 0 || this.progress.size > 0;\n for (const timer of this.timers.values()) clearTimeout(timer);\n this.timers.clear();\n this.pendingTasks.clear();\n this.settlingRequests.clear();\n this.progress.clear();\n if (changed) this.options.onChange?.();\n }\n}\n"],"mappings":"uPAuBA,MAAa,EAAqB,mBAa5B,EAAkB,YAClB,EAAe,SACf,EAAkB,YAIlB,EAAoB,UACpB,EAAuB,wBAGvB,EAAkB,wBAElB,EAA4B,6BAC5B,EAA+B,gCAC/B,EAAiC,kCAQ1B,EACX,kHACW,EACX,uGACW,EAA4B,kDAiFzC,SAAS,EAAS,EAA2B,EAAQ,IAAuC,CACrF,KACL,OAAO,EAAM,QAAU,EAAQ,EAAQ,GAAG,EAAM,MAAM,EAAG,CAAK,EAAE,gBAClE,CAEA,SAAS,EAAU,EAAwB,CACzC,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D,CASA,SAAS,EAAa,EAAwB,EAAa,EAA4C,CACrG,IAAM,EAAQ,IAAI,IAClB,IAAK,IAAM,KAAS,EAAQ,eAAiB,CAAC,EAAG,CAC/C,GAAI,EAAM,MAAA,GAAyB,MACnC,IAAM,EAAa,EAAS,gBAAgB,EAAM,KAAK,EAAG,CAAG,EACzD,GAAc,IAAe,KAAK,EAAM,IAAI,CAAU,CAC5D,CACA,MAAO,CAAE,MAAO,CAAC,GAAG,CAAK,EAAG,MAAO,EAAS,EAAQ,eAAe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Id,KAAK,QAAQ,cAAc,EAAO,CAAM,CAC1C,CACF,CAWA,gBACE,EACA,EACA,EACsD,CACtD,IAAM,EAAQ,EAAS,MAAM,UAAW,GAAS,EAAK,YAAY,YAAc,CAAS,EACzF,GAAI,IAAU,GAAI,MAAO,CAAE,MAAO,IAAA,EAAU,EAE5C,IAAM,EAAO,EAAS,MAAM,GAC5B,GAAI,CAACF,EAAAA,mBAAmB,CAAI,EAAG,MAAO,CAAE,MAAO,CAAK,EAEpD,IAAM,EAAU,EAAM,EAAM,EAAK,UAAW,EAC5C,GAAI,IAAY,EAAM,MAAO,CAAE,MAAO,CAAK,EAC3C,IAAM,EAAQ,CAAC,GAAG,EAAS,KAAK,EAEhC,MADA,GAAM,GAAS,EACR,CAAE,SAAU,CAAE,GAAG,EAAU,OAAM,EAAG,MAAO,CAAQ,CAC5D,CAEA,SAAgB,CACd,KAAK,OAAO,EACZ,KAAK,MAAM,CACb,CAGA,OAAc,CACZ,IAAM,EAAU,KAAK,aAAa,KAAO,GAAK,KAAK,SAAS,KAAO,EACnE,IAAK,IAAM,KAAS,KAAK,OAAO,OAAO,EAAG,aAAa,CAAK,EAC5D,KAAK,OAAO,MAAM,EAClB,KAAK,aAAa,MAAM,EACxB,KAAK,iBAAiB,MAAM,EAC5B,KAAK,SAAS,MAAM,EAChB,GAAS,KAAK,QAAQ,WAAW,CACvC,CACF"}
@@ -1,22 +1,18 @@
1
- import { TaskFailureReporter } from "../logSinkTelemetry.cjs";
2
- import { Task } from "../store/types.cjs";
3
- import { TaskStore } from "../store/taskStore.cjs";
4
- import { InlineAgent } from "@agimon-ai/doompi-extension-contracts/subagent-tool";
5
- import { EventBusLike } from "@agimon-ai/doompi-extension-contracts/protocol";
6
- //#region src/delegation/manager.d.ts
7
- declare const NOTIFY_CUSTOM_TYPE = "doom-task-notify";
8
- declare const BACKGROUND_WORK_PROVIDER = "doom-task";
9
- /**
10
- * Cap on files rendered into a brief. Exported so the tool schema can state the
11
- * same number to the model rather than restating it and drifting.
12
- */
13
- declare const MAX_BRIEF_FILES = 12;
14
- declare const ERR_NO_RUNTIME = "No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.";
15
- declare const ERR_CHILD_SESSION = "assign is only available in the main session. Update this task directly instead of re-delegating it.";
16
- declare const ERR_CANCEL_UNACKNOWLEDGED = "Subagent did not acknowledge the cancel request";
1
+ import { Task } from "../../models/task.cjs";
2
+ import { TaskFailureReporter } from "../../types/telemetry.cjs";
3
+ import { TaskStore } from "../taskStore/index.cjs";
4
+ import { MAX_BRIEF_FILES } from "../../types/delegation.cjs";
5
+ import { DoomDelegationService, InlineAgent } from "@agimon-ai/doompi-core/delegation";
6
+ import { Context } from "@deepseek-ai/cordis";
7
+ //#region src/services/delegation/index.d.ts
8
+ export declare const NOTIFY_CUSTOM_TYPE = "doom-task-notify";
9
+ export declare const BACKGROUND_WORK_PROVIDER = "doom-task";
10
+ export declare const ERR_NO_RUNTIME = "No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.";
11
+ export declare const ERR_CHILD_SESSION = "assign is only available in the main session. Update this task directly instead of re-delegating it.";
12
+ export declare const ERR_CANCEL_UNACKNOWLEDGED = "Subagent did not acknowledge the cancel request";
17
13
  /** Live progress from a running subagent. Kept in memory: persisting per-tool
18
14
  * ticks would rewrite the store file every second for no durable benefit. */
19
- interface DelegationProgress {
15
+ export interface DelegationProgress {
20
16
  agent: string;
21
17
  currentTool?: string;
22
18
  toolCount?: number;
@@ -30,23 +26,26 @@ interface DelegationProgress {
30
26
  contextFileCount?: number;
31
27
  contextNotesLength?: number;
32
28
  }
33
- interface DelegationNotifier {
34
- (message: {
35
- customType: string;
36
- content: string;
37
- display: boolean;
38
- }, options?: {
39
- triggerTurn?: boolean;
40
- deliverAs?: 'steer' | 'followUp' | 'nextTurn';
41
- }): void;
29
+ export type DelegationNotifier = (message: {
30
+ customType: string;
31
+ content: string;
32
+ display: boolean;
33
+ }, options?: {
34
+ triggerTurn?: boolean;
35
+ deliverAs?: 'steer' | 'followUp' | 'nextTurn';
36
+ }) => void;
37
+ export interface DelegationPlatform {
38
+ readonly environment: Readonly<Record<string, string | undefined>>;
39
+ readonly processId: number;
40
+ readonly createRequestId: () => string;
41
+ readonly formatBriefPath: (entry: string, cwd: string) => string;
42
42
  }
43
- interface DelegationManagerOptions {
44
- events: EventBusLike;
43
+ export interface DelegationManagerOptions {
45
44
  store: TaskStore;
46
45
  cwd: string;
46
+ platform: DelegationPlatform;
47
47
  notify?: DelegationNotifier;
48
48
  getSessionId?: () => string | undefined;
49
- env?: NodeJS.ProcessEnv;
50
49
  onChange?: () => void;
51
50
  startedTimeoutMs?: number;
52
51
  /** How long a started run may go without reporting a result. */
@@ -60,7 +59,7 @@ interface DelegationManagerOptions {
60
59
  /** Where other swallowed delegation failures go. */
61
60
  report?: TaskFailureReporter;
62
61
  }
63
- interface AssignOptions {
62
+ export interface AssignOptions {
64
63
  agent?: string;
65
64
  inlineAgent?: InlineAgent;
66
65
  instructions?: string;
@@ -74,32 +73,32 @@ interface AssignOptions {
74
73
  context?: 'fresh' | 'fork';
75
74
  signal?: AbortSignal;
76
75
  }
77
- interface DelegationOutcome {
76
+ export interface DelegationOutcome {
78
77
  ok: boolean;
79
78
  message: string;
80
79
  }
81
80
  /**
82
81
  * Owns the lifecycle of tasks delegated to subagents.
83
82
  *
84
- * Delegation rides the Doom Team event bus rather than spawning
83
+ * Delegation rides Team's injected Cordis service rather than spawning
85
84
  * processes directly, so doom-task stays decoupled from the subagent runtime
86
- * and degrades to a clear error when that runtime is not loaded.
85
+ * and degrades to a clear error when that service is not loaded.
87
86
  *
88
87
  * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so
89
88
  * a delegation always has a deadline no matter which phase it is in. Losing
90
89
  * that pairing is what previously left tasks running forever.
91
90
  */
92
- declare class DelegationManager {
91
+ export declare class DelegationManager {
93
92
  private readonly options;
94
93
  private readonly progress;
95
94
  private readonly pendingTasks;
95
+ private readonly settlingRequests;
96
96
  private readonly timers;
97
97
  private readonly subscriptions;
98
- private protocol;
98
+ private service;
99
99
  constructor(options: DelegationManagerOptions);
100
100
  private now;
101
101
  private nowMs;
102
- private get env();
103
102
  private get runTimeoutMs();
104
103
  private report;
105
104
  /** True in a session that is itself a subagent child. */
@@ -108,8 +107,10 @@ declare class DelegationManager {
108
107
  progressFor(task: Task): DelegationProgress | undefined;
109
108
  /** Displayed runtime duration, rebased from the latest child observation. */
110
109
  static elapsedMs(progress: DelegationProgress, nowMs?: number): number;
111
- /** Idempotent: a session restart re-subscribes without stacking handlers. */
112
- start(): void;
110
+ /** Rebind to the active Team service without stacking lifecycle listeners. */
111
+ bind(ctx: Context, service: DoomDelegationService): () => void;
112
+ /** Remove only the cross-package binding; task state and watchdogs remain live. */
113
+ unbind(): void;
113
114
  /** Items still in flight, surfaced so auto-stop will not kill the harness. */
114
115
  listActiveWork(): Array<{
115
116
  id: string;
@@ -121,7 +122,7 @@ declare class DelegationManager {
121
122
  * The live request set is read inside the mutation so a delegation assigned
122
123
  * while the lock was contended is not mistaken for a leftover.
123
124
  */
124
- reconcile(): Promise<Task[]>;
125
+ reconcile(isCurrent?: () => boolean): Promise<Task[]>;
125
126
  assign(taskId: number, options: AssignOptions): Promise<DelegationOutcome>;
126
127
  cancel(taskId: number): Promise<DelegationOutcome>;
127
128
  /** Settle without awaiting, reporting rather than dropping a failure. */
@@ -129,9 +130,9 @@ declare class DelegationManager {
129
130
  /**
130
131
  * Fail a delegation that nobody acknowledged.
131
132
  *
132
- * The bus cannot be probed for listeners, so silence is the only available
133
- * signal that the subagents runtime is absent. Without this the task would
134
- * sit in `requested` forever.
133
+ * Provider loss or a stalled Team runtime can still leave a dispatched
134
+ * request silent. Without this acknowledgement deadline the task would sit
135
+ * in `requested` forever.
135
136
  */
136
137
  private armStartedTimeout;
137
138
  /**
@@ -146,7 +147,7 @@ declare class DelegationManager {
146
147
  /**
147
148
  * Guarantee a cancel reaches a terminal state.
148
149
  *
149
- * Emitting the cancel event is a request, not an outcome: a runtime that has
150
+ * Calling the service is a request, not an outcome: a runtime that has
150
151
  * already forgotten the request answers nothing at all. The window still
151
152
  * favours a real response, which carries the run's partial output.
152
153
  */
@@ -165,10 +166,10 @@ declare class DelegationManager {
165
166
  * just not by that agent); a failure marks it `failed` so it stays visible
166
167
  * rather than silently rejoining the backlog.
167
168
  *
168
- * Dropping the pending entry first makes this single-shot: a response racing
169
- * the watchdog cannot settle the same run twice. A failed write therefore
170
- * must not abort the rest — the model still gets told, the run stops counting
171
- * as active work, and `reconcile` repairs the file at the next session start.
169
+ * The request is claimed in `settlingRequests` while it remains published as
170
+ * active work. It is removed only after the terminal state and model notification
171
+ * have been handed off, so an auto-stop observer cannot end the session between
172
+ * receiving the result and delivering it to the model.
172
173
  */
173
174
  private settle;
174
175
  private notifyModel;
@@ -183,7 +184,9 @@ declare class DelegationManager {
183
184
  */
184
185
  private patchDelegation;
185
186
  dispose(): void;
187
+ /** Clear one Pi session's transient delegation state without losing service injection. */
188
+ reset(): void;
186
189
  }
187
190
  //#endregion
188
- export { AssignOptions, BACKGROUND_WORK_PROVIDER, DelegationManager, DelegationManagerOptions, DelegationNotifier, DelegationOutcome, DelegationProgress, ERR_CANCEL_UNACKNOWLEDGED, ERR_CHILD_SESSION, ERR_NO_RUNTIME, MAX_BRIEF_FILES, NOTIFY_CUSTOM_TYPE };
189
- //# sourceMappingURL=manager.d.cts.map
191
+ export { MAX_BRIEF_FILES };
192
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/services/delegation/index.ts"],"mappings":";;;;;;;qBAuBa;qBACA;qBAkCA;qBAEA;qBAEA;;;iBAII;EACf;EACA;EACA;EACA;;EAEA;;EAEA;;;EAGA;EACA;;YAGU,sBACV;EAAW;EAAoB;EAAiB;GAChD;EAAY;EAAuB;;iBAGpB;WACN,aAAa,SAAS;WACtB;WACA;WACA,kBAAkB,eAAe;;iBAG3B;EACf,OAAO;EACP;EACA,UAAU;EACV,SAAS;EACT;EACA;EACA;;EAEA;;EAEA;EACA;EACA;;EAEA,gBAAgB,gBAAgB;;EAEhC,SAAS;;iBAGM;EACf;EACA,cAAc;EACd;;;EAGA;;;EAGA;EACA;EACA;EACA,SAAS;;iBAGM;EACf;EACA;;;;;;;;;;;;;qBAuFW;mBACM;mBACA;mBACA;mBACA;mBACA;mBACA;UACT;EAER,YAAY,SAAS;UAIb;UAIA;cAII;UAIJ;;MAKJ;;EAKJ,YAAY,MAAM,OAAO;;SAMlB,UAAU,UAAU,oBAAoB;;EAO/C,KAAK,KAAK,SAAS,SAAS;;EAyB5B;;EAMA,kBAAkB;IAAQ;IAAY;;;;;;;;EAYhC,UAAU,4BAAwC,QAAQ;EAwB1D,OAAO,gBAAgB,SAAS,gBAAgB,QAAQ;EAkHxD,OAAO,iBAAiB,QAAQ;;UAiB9B;;;;;;;;UAkBA;;;;;;;;;UAcA;;;;;;;;UAuBA;UAUA;UAOA;;UAOA;UAKA;UAoCA;UAsBM;;;;;;;;;;;;;UA4BA;UAwDN;;;;;;;;;;UAmDA;EAkBR;;EAMA"}
@@ -1,22 +1,18 @@
1
- import { TaskFailureReporter } from "../logSinkTelemetry.mjs";
2
- import { Task } from "../store/types.mjs";
3
- import { TaskStore } from "../store/taskStore.mjs";
4
- import { EventBusLike } from "@agimon-ai/doompi-extension-contracts/protocol";
5
- import { InlineAgent } from "@agimon-ai/doompi-extension-contracts/subagent-tool";
6
- //#region src/delegation/manager.d.ts
7
- declare const NOTIFY_CUSTOM_TYPE = "doom-task-notify";
8
- declare const BACKGROUND_WORK_PROVIDER = "doom-task";
9
- /**
10
- * Cap on files rendered into a brief. Exported so the tool schema can state the
11
- * same number to the model rather than restating it and drifting.
12
- */
13
- declare const MAX_BRIEF_FILES = 12;
14
- declare const ERR_NO_RUNTIME = "No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.";
15
- declare const ERR_CHILD_SESSION = "assign is only available in the main session. Update this task directly instead of re-delegating it.";
16
- declare const ERR_CANCEL_UNACKNOWLEDGED = "Subagent did not acknowledge the cancel request";
1
+ import { Task } from "../../models/task.mjs";
2
+ import { TaskFailureReporter } from "../../types/telemetry.mjs";
3
+ import { TaskStore } from "../taskStore/index.mjs";
4
+ import { MAX_BRIEF_FILES } from "../../types/delegation.mjs";
5
+ import { DoomDelegationService, InlineAgent } from "@agimon-ai/doompi-core/delegation";
6
+ import { Context } from "@deepseek-ai/cordis";
7
+ //#region src/services/delegation/index.d.ts
8
+ export declare const NOTIFY_CUSTOM_TYPE = "doom-task-notify";
9
+ export declare const BACKGROUND_WORK_PROVIDER = "doom-task";
10
+ export declare const ERR_NO_RUNTIME = "No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.";
11
+ export declare const ERR_CHILD_SESSION = "assign is only available in the main session. Update this task directly instead of re-delegating it.";
12
+ export declare const ERR_CANCEL_UNACKNOWLEDGED = "Subagent did not acknowledge the cancel request";
17
13
  /** Live progress from a running subagent. Kept in memory: persisting per-tool
18
14
  * ticks would rewrite the store file every second for no durable benefit. */
19
- interface DelegationProgress {
15
+ export interface DelegationProgress {
20
16
  agent: string;
21
17
  currentTool?: string;
22
18
  toolCount?: number;
@@ -30,23 +26,26 @@ interface DelegationProgress {
30
26
  contextFileCount?: number;
31
27
  contextNotesLength?: number;
32
28
  }
33
- interface DelegationNotifier {
34
- (message: {
35
- customType: string;
36
- content: string;
37
- display: boolean;
38
- }, options?: {
39
- triggerTurn?: boolean;
40
- deliverAs?: 'steer' | 'followUp' | 'nextTurn';
41
- }): void;
29
+ export type DelegationNotifier = (message: {
30
+ customType: string;
31
+ content: string;
32
+ display: boolean;
33
+ }, options?: {
34
+ triggerTurn?: boolean;
35
+ deliverAs?: 'steer' | 'followUp' | 'nextTurn';
36
+ }) => void;
37
+ export interface DelegationPlatform {
38
+ readonly environment: Readonly<Record<string, string | undefined>>;
39
+ readonly processId: number;
40
+ readonly createRequestId: () => string;
41
+ readonly formatBriefPath: (entry: string, cwd: string) => string;
42
42
  }
43
- interface DelegationManagerOptions {
44
- events: EventBusLike;
43
+ export interface DelegationManagerOptions {
45
44
  store: TaskStore;
46
45
  cwd: string;
46
+ platform: DelegationPlatform;
47
47
  notify?: DelegationNotifier;
48
48
  getSessionId?: () => string | undefined;
49
- env?: NodeJS.ProcessEnv;
50
49
  onChange?: () => void;
51
50
  startedTimeoutMs?: number;
52
51
  /** How long a started run may go without reporting a result. */
@@ -60,7 +59,7 @@ interface DelegationManagerOptions {
60
59
  /** Where other swallowed delegation failures go. */
61
60
  report?: TaskFailureReporter;
62
61
  }
63
- interface AssignOptions {
62
+ export interface AssignOptions {
64
63
  agent?: string;
65
64
  inlineAgent?: InlineAgent;
66
65
  instructions?: string;
@@ -74,32 +73,32 @@ interface AssignOptions {
74
73
  context?: 'fresh' | 'fork';
75
74
  signal?: AbortSignal;
76
75
  }
77
- interface DelegationOutcome {
76
+ export interface DelegationOutcome {
78
77
  ok: boolean;
79
78
  message: string;
80
79
  }
81
80
  /**
82
81
  * Owns the lifecycle of tasks delegated to subagents.
83
82
  *
84
- * Delegation rides the Doom Team event bus rather than spawning
83
+ * Delegation rides Team's injected Cordis service rather than spawning
85
84
  * processes directly, so doom-task stays decoupled from the subagent runtime
86
- * and degrades to a clear error when that runtime is not loaded.
85
+ * and degrades to a clear error when that service is not loaded.
87
86
  *
88
87
  * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so
89
88
  * a delegation always has a deadline no matter which phase it is in. Losing
90
89
  * that pairing is what previously left tasks running forever.
91
90
  */
92
- declare class DelegationManager {
91
+ export declare class DelegationManager {
93
92
  private readonly options;
94
93
  private readonly progress;
95
94
  private readonly pendingTasks;
95
+ private readonly settlingRequests;
96
96
  private readonly timers;
97
97
  private readonly subscriptions;
98
- private protocol;
98
+ private service;
99
99
  constructor(options: DelegationManagerOptions);
100
100
  private now;
101
101
  private nowMs;
102
- private get env();
103
102
  private get runTimeoutMs();
104
103
  private report;
105
104
  /** True in a session that is itself a subagent child. */
@@ -108,8 +107,10 @@ declare class DelegationManager {
108
107
  progressFor(task: Task): DelegationProgress | undefined;
109
108
  /** Displayed runtime duration, rebased from the latest child observation. */
110
109
  static elapsedMs(progress: DelegationProgress, nowMs?: number): number;
111
- /** Idempotent: a session restart re-subscribes without stacking handlers. */
112
- start(): void;
110
+ /** Rebind to the active Team service without stacking lifecycle listeners. */
111
+ bind(ctx: Context, service: DoomDelegationService): () => void;
112
+ /** Remove only the cross-package binding; task state and watchdogs remain live. */
113
+ unbind(): void;
113
114
  /** Items still in flight, surfaced so auto-stop will not kill the harness. */
114
115
  listActiveWork(): Array<{
115
116
  id: string;
@@ -121,7 +122,7 @@ declare class DelegationManager {
121
122
  * The live request set is read inside the mutation so a delegation assigned
122
123
  * while the lock was contended is not mistaken for a leftover.
123
124
  */
124
- reconcile(): Promise<Task[]>;
125
+ reconcile(isCurrent?: () => boolean): Promise<Task[]>;
125
126
  assign(taskId: number, options: AssignOptions): Promise<DelegationOutcome>;
126
127
  cancel(taskId: number): Promise<DelegationOutcome>;
127
128
  /** Settle without awaiting, reporting rather than dropping a failure. */
@@ -129,9 +130,9 @@ declare class DelegationManager {
129
130
  /**
130
131
  * Fail a delegation that nobody acknowledged.
131
132
  *
132
- * The bus cannot be probed for listeners, so silence is the only available
133
- * signal that the subagents runtime is absent. Without this the task would
134
- * sit in `requested` forever.
133
+ * Provider loss or a stalled Team runtime can still leave a dispatched
134
+ * request silent. Without this acknowledgement deadline the task would sit
135
+ * in `requested` forever.
135
136
  */
136
137
  private armStartedTimeout;
137
138
  /**
@@ -146,7 +147,7 @@ declare class DelegationManager {
146
147
  /**
147
148
  * Guarantee a cancel reaches a terminal state.
148
149
  *
149
- * Emitting the cancel event is a request, not an outcome: a runtime that has
150
+ * Calling the service is a request, not an outcome: a runtime that has
150
151
  * already forgotten the request answers nothing at all. The window still
151
152
  * favours a real response, which carries the run's partial output.
152
153
  */
@@ -165,10 +166,10 @@ declare class DelegationManager {
165
166
  * just not by that agent); a failure marks it `failed` so it stays visible
166
167
  * rather than silently rejoining the backlog.
167
168
  *
168
- * Dropping the pending entry first makes this single-shot: a response racing
169
- * the watchdog cannot settle the same run twice. A failed write therefore
170
- * must not abort the rest — the model still gets told, the run stops counting
171
- * as active work, and `reconcile` repairs the file at the next session start.
169
+ * The request is claimed in `settlingRequests` while it remains published as
170
+ * active work. It is removed only after the terminal state and model notification
171
+ * have been handed off, so an auto-stop observer cannot end the session between
172
+ * receiving the result and delivering it to the model.
172
173
  */
173
174
  private settle;
174
175
  private notifyModel;
@@ -183,7 +184,9 @@ declare class DelegationManager {
183
184
  */
184
185
  private patchDelegation;
185
186
  dispose(): void;
187
+ /** Clear one Pi session's transient delegation state without losing service injection. */
188
+ reset(): void;
186
189
  }
187
190
  //#endregion
188
- export { AssignOptions, BACKGROUND_WORK_PROVIDER, DelegationManager, DelegationManagerOptions, DelegationNotifier, DelegationOutcome, DelegationProgress, ERR_CANCEL_UNACKNOWLEDGED, ERR_CHILD_SESSION, ERR_NO_RUNTIME, MAX_BRIEF_FILES, NOTIFY_CUSTOM_TYPE };
189
- //# sourceMappingURL=manager.d.mts.map
191
+ export { MAX_BRIEF_FILES };
192
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/delegation/index.ts"],"mappings":";;;;;;;qBAuBa;qBACA;qBAkCA;qBAEA;qBAEA;;;iBAII;EACf;EACA;EACA;EACA;;EAEA;;EAEA;;;EAGA;EACA;;YAGU,sBACV;EAAW;EAAoB;EAAiB;GAChD;EAAY;EAAuB;;iBAGpB;WACN,aAAa,SAAS;WACtB;WACA;WACA,kBAAkB,eAAe;;iBAG3B;EACf,OAAO;EACP;EACA,UAAU;EACV,SAAS;EACT;EACA;EACA;;EAEA;;EAEA;EACA;EACA;;EAEA,gBAAgB,gBAAgB;;EAEhC,SAAS;;iBAGM;EACf;EACA,cAAc;EACd;;;EAGA;;;EAGA;EACA;EACA;EACA,SAAS;;iBAGM;EACf;EACA;;;;;;;;;;;;;qBAuFW;mBACM;mBACA;mBACA;mBACA;mBACA;mBACA;UACT;EAER,YAAY,SAAS;UAIb;UAIA;cAII;UAIJ;;MAKJ;;EAKJ,YAAY,MAAM,OAAO;;SAMlB,UAAU,UAAU,oBAAoB;;EAO/C,KAAK,KAAK,SAAS,SAAS;;EAyB5B;;EAMA,kBAAkB;IAAQ;IAAY;;;;;;;;EAYhC,UAAU,4BAAwC,QAAQ;EAwB1D,OAAO,gBAAgB,SAAS,gBAAgB,QAAQ;EAkHxD,OAAO,iBAAiB,QAAQ;;UAiB9B;;;;;;;;UAkBA;;;;;;;;;UAcA;;;;;;;;UAuBA;UAUA;UAOA;;UAOA;UAKA;UAoCA;UAsBM;;;;;;;;;;;;;UA4BA;UAwDN;;;;;;;;;;UAmDA;EAkBR;;EAMA"}
@@ -0,0 +1,6 @@
1
+ import{isBlocked as e,isTaskListComplete as t}from"../../models/taskGraph.mjs";import{MAX_BRIEF_FILES as n}from"../../types/delegation.mjs";import{TASK_EVENT as r}from"../../types/telemetry.mjs";import{isDelegationActive as i}from"../../models/task.mjs";import{reconcileOrphanedDelegations as a}from"../reconcile/index.mjs";import{DOOM_DELEGATION_ACCEPTED_EVENT as o,DOOM_DELEGATION_FINISHED_EVENT as s,DOOM_DELEGATION_STARTED_EVENT as c,DOOM_DELEGATION_UPDATED_EVENT as l}from"@agimon-ai/doompi-core/delegation";const u=`doom-task-notify`,d=`doom-task`,f=`completed`,p=`failed`,m=`cancelled`,h=`task.id`,g=`delegation.request_id`,_=`delegation.agent_name`,v=`delegation.context_present`,y=`delegation.context_file_count`,b=`delegation.context_notes_length`,x=`No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.`,S=`assign is only available in the main session. Update this task directly instead of re-delegating it.`,C=`Subagent did not acknowledge the cancel request`;function w(e,t=4e3){if(e)return e.length<=t?e:`${e.slice(0,t)}\n… (truncated)`}function T(e){return e instanceof Error?e.message:String(e)}function E(e,t,n){let r=new Set;for(let i of e.relevantFiles??[]){if(r.size>=12)break;let e=n.formatBriefPath(i.trim(),t);e&&e!==`.`&&r.add(e)}return{files:[...r],notes:w(e.priorFindings?.trim(),1500)}}function D(e,t,n){let r=[`Task #${e.id}: ${e.subject}`];if(e.description&&r.push(e.description),t&&r.push(t),n.files.length>0||n.notes){let e=[`Parent context — consume before repository discovery:`];n.files.length>0&&e.push(`- Parent-verified files (read these first with direct reads): ${n.files.join(`, `)}`),n.notes&&e.push(`- Established facts (do not re-derive unless direct evidence contradicts them): ${n.notes}`),e.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.`),r.push(e.join(`
2
+ `))}return r.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.`),r.join(`
3
+
4
+ `)}var O=class n{options;progress=new Map;pendingTasks=new Map;settlingRequests=new Set;timers=new Map;subscriptions=[];service;constructor(e){this.options=e}now(){return this.options.now?.()??new Date().toISOString()}nowMs(){return this.options.nowMs?.()??Date.now()}get runTimeoutMs(){return this.options.runTimeoutMs??12e5}report(e,t,n){this.options.report?.error(e,t,n)}get isChildSession(){return!!this.options.platform.environment.PI_SUBAGENT_CHILD}progressFor(e){let t=e.delegation?.requestId;return t?this.progress.get(t):void 0}static elapsedMs(e,t=Date.now()){let n=e.durationMs??0,r=e.durationObservedAt??t;return n+Math.max(0,t-r)}bind(e,t){return this.unbind(),this.service=t,this.subscriptions.push(e.on(o,e=>{this.handleAccepted(e)}),e.on(c,e=>{this.handleStarted(e)}),e.on(l,e=>{this.handleUpdate(e)}),e.on(s,e=>{this.handleResponse(e).catch(t=>{this.report(r.delegationResponseFailed,t,{[g]:e.requestId})})})),()=>{this.service===t&&this.unbind()}}unbind(){for(let e of this.subscriptions.splice(0))e();this.service=void 0}listActiveWork(){return[...this.pendingTasks.entries()].flatMap(([e,t])=>t.sessionId?[{id:`task-${t.taskId}:${e}`,sessionId:t.sessionId}]:[])}async reconcile(e=()=>!0){let{value:t}=await this.options.store.mutate(t=>{if(!e())return{value:[]};let n=a(t,this.now(),void 0,{pid:this.options.platform.processId,liveRequestIds:new Set(this.pendingTasks.keys())});return n.orphaned.length===0?{value:[]}:{document:n.document,value:n.orphaned}});if(!e())return[];for(let e of t)this.options.report?.warn(r.delegationOrphaned,Error(e.delegation?.result?.error??``),{[h]:e.id,...e.delegation?.agent?{[_]:e.delegation.agent}:{},...e.delegation?.pid===void 0?{}:{"delegation.pid":e.delegation.pid}});return t.length>0&&this.options.onChange?.(),t}async assign(t,n){let a=n.agent?.trim();if(!a)return{ok:!1,message:`agent required for assign`};if(this.isChildSession)return{ok:!1,message:S};if(n.signal?.aborted)return{ok:!1,message:`delegation cancelled before it started`};let o=this.options.platform.createRequestId(),s=this.now(),c=this.options.getSessionId?.(),l=E(n,this.options.cwd,this.options.platform),{value:u}=await this.options.store.mutate(r=>{let l=r.tasks.findIndex(e=>e.id===t);if(l===-1)return{value:{ok:!1,message:`#${t} not found`}};let u=r.tasks[l];if(u.status===`deleted`)return{value:{ok:!1,message:`#${t} is deleted`}};if(u.status===f)return{value:{ok:!1,message:`#${t} is already completed`}};if(i(u))return{value:{ok:!1,message:`#${t} is already delegated to ${u.delegation?.agent}`}};if(e(r.tasks,u))return{value:{ok:!1,message:`#${t} is blocked by ${(u.blockedBy??[]).map(e=>`#${e}`).join(`, `)}`}};let d={requestId:o,agent:a,state:`requested`,pid:this.options.platform.processId,startedAt:s,...c?{sessionId:c}:{},...n.model?{model:n.model}:{}},p=[...r.tasks];return p[l]={...u,owner:a,updatedAt:s,delegation:d},{document:{...r,tasks:p},value:{ok:!0,message:``,task:p[l]}}});if(!u.ok||!u.task)return{ok:!1,message:u.message};let d=l.notes?.length??0;this.pendingTasks.set(o,{taskId:t,sessionId:c}),this.progress.set(o,{agent:a,contextFileCount:l.files.length,contextNotesLength:d}),this.armStartedTimeout(o),this.options.onChange?.();let m={requestId:o,taskId:t,agent:a,...n.inlineAgent?{inlineAgent:n.inlineAgent}:{},prompt:D(u.task,n.instructions,l),...n.context?{context:n.context}:{},cwd:this.options.cwd,artifacts:!0,timeoutMs:this.runTimeoutMs,runMode:`detached`,teamTask:{id:String(u.task.id),subject:u.task.subject},...n.model?{model:n.model}:{}};try{let e=this.service;if(!e)throw Error(x);e.request(m).catch(e=>{this.report(r.delegationRequestFailed,e,{[h]:t,[g]:o,[_]:a}),this.settleDetached(o,p,{status:p,error:`Delegation request failed: ${T(e)}`})})}catch(e){this.report(r.delegationRequestFailed,e,{[h]:t,[g]:o,[_]:a});let n=T(e);return await this.settle(o,p,{status:p,error:`Delegation request failed: ${n}`}),{ok:!1,message:`Could not dispatch #${t} to ${a}: ${n}`}}return this.options.report?.event(r.delegationAssigned,{[h]:t,[g]:o,[_]:a,[v]:l.files.length>0||d>0,[y]:l.files.length,[b]:d,"delegation.brief_length":m.prompt.length}),{ok:!0,message:`Delegated #${t} to ${a} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end your turn.`}}async cancel(e){let t=this.options.store.read().tasks.find(t=>t.id===e);if(!t)return{ok:!1,message:`#${e} not found`};if(!t.delegation||!i(t))return{ok:!1,message:`#${e} has no running delegation`};let{requestId:n}=t.delegation;return this.service?.cancel({requestId:n}),this.armCancelTimeout(n),{ok:!0,message:`Cancelling delegation for #${e} (${t.delegation.agent})`}}settleDetached(e,t,n,i=r.delegationSettleFailed){this.settle(e,t,n).catch(t=>{this.report(i,t,{[g]:e})})}armStartedTimeout(e){this.armTimer(e,this.options.startedTimeoutMs??5e3,()=>{this.settleDetached(e,p,{status:p,error:x})})}armRunTimeout(e){let t=Math.min(6e4,this.runTimeoutMs);this.armTimer(e,this.runTimeoutMs+t,()=>{let t=this.pendingTasks.get(e)?.taskId,n=this.progress.get(e)?.agent,i=Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);this.options.report?.warn(r.delegationTimedOut,i,{...t===void 0?{}:{[h]:t},[g]:e,...n?{[_]:n}:{}}),this.service?.cancel({requestId:e,reason:i.message}),this.settleDetached(e,p,{status:`timed_out`,error:i.message})})}armCancelTimeout(e){this.pendingTasks.has(e)&&this.armTimer(e,this.options.cancelTimeoutMs??1e4,()=>{this.settleDetached(e,m,{status:m,error:C})})}armTimer(e,t,n){this.clearTimer(e);let r=setTimeout(n,t);r.unref?.(),this.timers.set(e,r)}clearTimer(e){let t=this.timers.get(e);t&&clearTimeout(t),this.timers.delete(e)}handleAccepted(e){this.pendingTasks.has(e.requestId)&&this.armRunTimeout(e.requestId)}handleStarted(e){let{runId:t}=e,n=this.pendingTasks.get(e.requestId)?.taskId;if(n===void 0)return;this.armRunTimeout(e.requestId);let i=this.progress.get(e.requestId);i&&this.progress.set(e.requestId,{...i,durationMs:i.durationMs??0,durationObservedAt:i.durationObservedAt??this.nowMs()}),this.options.store.mutate(n=>this.patchDelegation(n,e.requestId,(e,n)=>({...e,status:e.status===f?e.status:`in_progress`,delegation:{...n,state:`running`,startedAt:n.startedAt??this.now(),...t?{runId:t}:{}}}))).then(()=>this.options.onChange?.()).catch(t=>{this.report(r.delegationStartFailed,t,{[h]:n,[g]:e.requestId})})}handleUpdate(e){let t=this.progress.get(e.requestId);if(!t)return;let r=this.nowMs(),i=n.elapsedMs(t,r),a=e.durationMs!==void 0;this.progress.set(e.requestId,{...t,currentTool:e.currentTool??t.currentTool,toolCount:e.toolCount===void 0?t.toolCount:Math.max(t.toolCount??0,e.toolCount),tokens:e.tokens===void 0?t.tokens:Math.max(t.tokens??0,e.tokens),durationMs:a?Math.max(i,e.durationMs):t.durationMs,durationObservedAt:a?r:t.durationObservedAt}),this.options.onChange?.()}async handleResponse(e){if(!this.pendingTasks.has(e.requestId))return;let t=e.status===f&&!e.error?f:e.status===m?m:p;await this.settle(e.requestId,t,{status:e.status,error:e.error,output:w(e.output),outputPath:e.outputPath,sessionFile:e.sessionFile,durationMs:e.durationMs,toolCount:e.toolCount})}async settle(e,n,i){let a=this.pendingTasks.get(e);if(!a||this.settlingRequests.has(e))return;this.settlingRequests.add(e),this.clearTimer(e);let{taskId:o}=a,s=this.progress.get(e);try{let a=this.now(),c;try{let{value:t}=await this.options.store.mutate(t=>this.patchDelegation(t,e,(e,t)=>({...e,status:n===f?f:n===m?`pending`:p,updatedAt:a,delegation:{...t,state:n,endedAt:a,...i?{result:i}:{}}})));c=t}catch(t){this.report(r.delegationSettleFailed,t,{[h]:o,[g]:e})}let l=c?.delegation?.agent??s?.agent??`subagent`,u=c?.subject??`#${o}`;this.options.report?.event(r.delegationCompleted,{[h]:o,[g]:e,[_]:l,"delegation.outcome":n,[v]:(s?.contextFileCount??0)>0||(s?.contextNotesLength??0)>0,[y]:s?.contextFileCount??0,[b]:s?.contextNotesLength??0,...i?.toolCount===void 0?{}:{"delegation.tool_count":i.toolCount},...i?.durationMs===void 0?{}:{"delegation.duration_ms":i.durationMs}});let d=n===f&&c!==void 0&&t(this.options.store.snapshot.tasks);this.notifyModel(n,o,u,l,i,d)}finally{this.pendingTasks.delete(e),this.progress.delete(e),this.settlingRequests.delete(e),this.options.onChange?.()}}notifyModel(e,t,n,r,i,a){let o=this.options.notify;if(!o)return;let s=[e===f?`Subagent ${r} completed task #${t}: ${n}`:e===m?`Subagent ${r} was cancelled on task #${t}: ${n} (returned to pending)`:`Subagent ${r} failed task #${t}: ${n}`];a&&s.push(``,`All tasks are completed. Review the full task list once more, then close it with task {"action":"clear"}.`),i?.error&&s.push(`Error: ${i.error}`),i?.output&&s.push(``,i.output),i?.outputPath&&s.push(``,`Full output: ${i.outputPath}`);try{o({customType:u,content:s.join(`
5
+ `),display:!0},{triggerTurn:!0,deliverAs:`steer`})}catch(e){this.options.onNotifyError(e,t)}}patchDelegation(e,t,n){let r=e.tasks.findIndex(e=>e.delegation?.requestId===t);if(r===-1)return{value:void 0};let a=e.tasks[r];if(!i(a))return{value:a};let o=n(a,a.delegation);if(o===a)return{value:a};let s=[...e.tasks];return s[r]=o,{document:{...e,tasks:s},value:o}}dispose(){this.unbind(),this.reset()}reset(){let e=this.pendingTasks.size>0||this.progress.size>0;for(let e of this.timers.values())clearTimeout(e);this.timers.clear(),this.pendingTasks.clear(),this.settlingRequests.clear(),this.progress.clear(),e&&this.options.onChange?.()}};export{d as BACKGROUND_WORK_PROVIDER,O as DelegationManager,C as ERR_CANCEL_UNACKNOWLEDGED,S as ERR_CHILD_SESSION,x as ERR_NO_RUNTIME,n as MAX_BRIEF_FILES,u as NOTIFY_CUSTOM_TYPE};
6
+ //# sourceMappingURL=index.mjs.map