macro-agent 0.2.4 → 0.2.6

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 (1002) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +30 -56
  3. package/dist/acp/websocket-server.d.ts +6 -0
  4. package/dist/acp/websocket-server.d.ts.map +1 -1
  5. package/dist/acp/websocket-server.js +13 -0
  6. package/dist/acp/websocket-server.js.map +1 -1
  7. package/dist/acp/websocket-stream.d.ts +30 -0
  8. package/dist/acp/websocket-stream.d.ts.map +1 -0
  9. package/dist/acp/websocket-stream.js +118 -0
  10. package/dist/acp/websocket-stream.js.map +1 -0
  11. package/dist/activity/deduplication.d.ts +85 -0
  12. package/dist/activity/deduplication.d.ts.map +1 -0
  13. package/dist/activity/deduplication.js +149 -0
  14. package/dist/activity/deduplication.js.map +1 -0
  15. package/dist/activity/index.d.ts +16 -0
  16. package/dist/activity/index.d.ts.map +1 -0
  17. package/dist/activity/index.js +17 -0
  18. package/dist/activity/index.js.map +1 -0
  19. package/dist/activity/relevance.d.ts +81 -0
  20. package/dist/activity/relevance.d.ts.map +1 -0
  21. package/dist/activity/relevance.js +161 -0
  22. package/dist/activity/relevance.js.map +1 -0
  23. package/dist/activity/types.d.ts +169 -0
  24. package/dist/activity/types.d.ts.map +1 -0
  25. package/dist/activity/types.js +33 -0
  26. package/dist/activity/types.js.map +1 -0
  27. package/dist/activity/watcher.d.ts +64 -0
  28. package/dist/activity/watcher.d.ts.map +1 -0
  29. package/dist/activity/watcher.js +212 -0
  30. package/dist/activity/watcher.js.map +1 -0
  31. package/dist/adapters/federation.d.ts +8 -1
  32. package/dist/adapters/federation.d.ts.map +1 -1
  33. package/dist/adapters/federation.js +33 -2
  34. package/dist/adapters/federation.js.map +1 -1
  35. package/dist/agent/agent-manager-v2.d.ts.map +1 -1
  36. package/dist/agent/agent-manager-v2.js +189 -67
  37. package/dist/agent/agent-manager-v2.js.map +1 -1
  38. package/dist/agent/agent-manager.d.ts +17 -0
  39. package/dist/agent/agent-manager.d.ts.map +1 -1
  40. package/dist/agent/agent-manager.js.map +1 -1
  41. package/dist/agent/types.d.ts +21 -2
  42. package/dist/agent/types.d.ts.map +1 -1
  43. package/dist/agent/types.js.map +1 -1
  44. package/dist/agent/wake.d.ts +85 -0
  45. package/dist/agent/wake.d.ts.map +1 -0
  46. package/dist/agent/wake.js +278 -0
  47. package/dist/agent/wake.js.map +1 -0
  48. package/dist/api/server.d.ts.map +1 -1
  49. package/dist/api/server.js +41 -25
  50. package/dist/api/server.js.map +1 -1
  51. package/dist/api/types.d.ts +6 -0
  52. package/dist/api/types.d.ts.map +1 -1
  53. package/dist/auth/server-auth.d.ts +43 -0
  54. package/dist/auth/server-auth.d.ts.map +1 -0
  55. package/dist/auth/server-auth.js +80 -0
  56. package/dist/auth/server-auth.js.map +1 -0
  57. package/dist/auth/token.d.ts +4 -0
  58. package/dist/auth/token.d.ts.map +1 -1
  59. package/dist/auth/token.js +7 -6
  60. package/dist/auth/token.js.map +1 -1
  61. package/dist/boot-v2.d.ts +6 -3
  62. package/dist/boot-v2.d.ts.map +1 -1
  63. package/dist/boot-v2.js +44 -25
  64. package/dist/boot-v2.js.map +1 -1
  65. package/dist/cognitive/macro-agent-backend.d.ts.map +1 -1
  66. package/dist/cognitive/macro-agent-backend.js +37 -8
  67. package/dist/cognitive/macro-agent-backend.js.map +1 -1
  68. package/dist/cognitive/team-lifecycle.d.ts +82 -0
  69. package/dist/cognitive/team-lifecycle.d.ts.map +1 -0
  70. package/dist/cognitive/team-lifecycle.js +121 -0
  71. package/dist/cognitive/team-lifecycle.js.map +1 -0
  72. package/dist/cognitive/trajectory-extractor.d.ts +25 -0
  73. package/dist/cognitive/trajectory-extractor.d.ts.map +1 -0
  74. package/dist/cognitive/trajectory-extractor.js +134 -0
  75. package/dist/cognitive/trajectory-extractor.js.map +1 -0
  76. package/dist/cognitive/types.d.ts +24 -0
  77. package/dist/cognitive/types.d.ts.map +1 -1
  78. package/dist/control/control-server.d.ts.map +1 -1
  79. package/dist/control/control-server.js +10 -0
  80. package/dist/control/control-server.js.map +1 -1
  81. package/dist/dispatch/mail-inbound-consumer.d.ts.map +1 -1
  82. package/dist/dispatch/mail-inbound-consumer.js +43 -10
  83. package/dist/dispatch/mail-inbound-consumer.js.map +1 -1
  84. package/dist/index.d.ts +5 -1
  85. package/dist/index.d.ts.map +1 -1
  86. package/dist/index.js +6 -1
  87. package/dist/index.js.map +1 -1
  88. package/dist/lifecycle/handlers/generic.d.ts +27 -0
  89. package/dist/lifecycle/handlers/generic.d.ts.map +1 -0
  90. package/dist/lifecycle/handlers/generic.js +56 -0
  91. package/dist/lifecycle/handlers/generic.js.map +1 -0
  92. package/dist/lifecycle/handlers/index.d.ts +51 -0
  93. package/dist/lifecycle/handlers/index.d.ts.map +1 -0
  94. package/dist/lifecycle/handlers/index.js +110 -0
  95. package/dist/lifecycle/handlers/index.js.map +1 -0
  96. package/dist/lifecycle/handlers/integrator.d.ts +81 -0
  97. package/dist/lifecycle/handlers/integrator.d.ts.map +1 -0
  98. package/dist/lifecycle/handlers/integrator.js +451 -0
  99. package/dist/lifecycle/handlers/integrator.js.map +1 -0
  100. package/dist/lifecycle/handlers/monitor.d.ts +29 -0
  101. package/dist/lifecycle/handlers/monitor.d.ts.map +1 -0
  102. package/dist/lifecycle/handlers/monitor.js +79 -0
  103. package/dist/lifecycle/handlers/monitor.js.map +1 -0
  104. package/dist/lifecycle/handlers/worker.d.ts +56 -0
  105. package/dist/lifecycle/handlers/worker.d.ts.map +1 -0
  106. package/dist/lifecycle/handlers/worker.js +381 -0
  107. package/dist/lifecycle/handlers/worker.js.map +1 -0
  108. package/dist/lifecycle/handlers-v2.d.ts +0 -2
  109. package/dist/lifecycle/handlers-v2.d.ts.map +1 -1
  110. package/dist/lifecycle/handlers-v2.js +4 -55
  111. package/dist/lifecycle/handlers-v2.js.map +1 -1
  112. package/dist/mail/conversation-map.d.ts +33 -0
  113. package/dist/mail/conversation-map.d.ts.map +1 -0
  114. package/dist/mail/conversation-map.js +61 -0
  115. package/dist/mail/conversation-map.js.map +1 -0
  116. package/dist/mail/index.d.ts +11 -0
  117. package/dist/mail/index.d.ts.map +1 -0
  118. package/dist/mail/index.js +11 -0
  119. package/dist/mail/index.js.map +1 -0
  120. package/dist/mail/mail-service.d.ts +85 -0
  121. package/dist/mail/mail-service.d.ts.map +1 -0
  122. package/dist/mail/mail-service.js +121 -0
  123. package/dist/mail/mail-service.js.map +1 -0
  124. package/dist/mail/stores/eventstore-conversation-store.d.ts +40 -0
  125. package/dist/mail/stores/eventstore-conversation-store.d.ts.map +1 -0
  126. package/dist/mail/stores/eventstore-conversation-store.js +131 -0
  127. package/dist/mail/stores/eventstore-conversation-store.js.map +1 -0
  128. package/dist/mail/stores/eventstore-participant-store.d.ts +43 -0
  129. package/dist/mail/stores/eventstore-participant-store.d.ts.map +1 -0
  130. package/dist/mail/stores/eventstore-participant-store.js +145 -0
  131. package/dist/mail/stores/eventstore-participant-store.js.map +1 -0
  132. package/dist/mail/stores/eventstore-thread-store.d.ts +46 -0
  133. package/dist/mail/stores/eventstore-thread-store.d.ts.map +1 -0
  134. package/dist/mail/stores/eventstore-thread-store.js +118 -0
  135. package/dist/mail/stores/eventstore-thread-store.js.map +1 -0
  136. package/dist/mail/stores/eventstore-turn-store.d.ts +47 -0
  137. package/dist/mail/stores/eventstore-turn-store.d.ts.map +1 -0
  138. package/dist/mail/stores/eventstore-turn-store.js +153 -0
  139. package/dist/mail/stores/eventstore-turn-store.js.map +1 -0
  140. package/dist/mail/stores/index.d.ts +12 -0
  141. package/dist/mail/stores/index.d.ts.map +1 -0
  142. package/dist/mail/stores/index.js +12 -0
  143. package/dist/mail/stores/index.js.map +1 -0
  144. package/dist/mail/stores/types.d.ts +146 -0
  145. package/dist/mail/stores/types.d.ts.map +1 -0
  146. package/dist/mail/stores/types.js +13 -0
  147. package/dist/mail/stores/types.js.map +1 -0
  148. package/dist/mail/turn-recorder.d.ts +30 -0
  149. package/dist/mail/turn-recorder.d.ts.map +1 -0
  150. package/dist/mail/turn-recorder.js +98 -0
  151. package/dist/mail/turn-recorder.js.map +1 -0
  152. package/dist/map/adapter/acp-over-map.d.ts +115 -0
  153. package/dist/map/adapter/acp-over-map.d.ts.map +1 -0
  154. package/dist/map/adapter/acp-over-map.js +1024 -0
  155. package/dist/map/adapter/acp-over-map.js.map +1 -0
  156. package/dist/map/adapter/connection-manager.d.ts +150 -0
  157. package/dist/map/adapter/connection-manager.d.ts.map +1 -0
  158. package/dist/map/adapter/connection-manager.js +207 -0
  159. package/dist/map/adapter/connection-manager.js.map +1 -0
  160. package/dist/map/adapter/event-log.d.ts +87 -0
  161. package/dist/map/adapter/event-log.d.ts.map +1 -0
  162. package/dist/map/adapter/event-log.js +122 -0
  163. package/dist/map/adapter/event-log.js.map +1 -0
  164. package/dist/map/adapter/event-translator.d.ts +85 -0
  165. package/dist/map/adapter/event-translator.d.ts.map +1 -0
  166. package/dist/map/adapter/event-translator.js +295 -0
  167. package/dist/map/adapter/event-translator.js.map +1 -0
  168. package/dist/map/adapter/extensions/agent-detection.d.ts +49 -0
  169. package/dist/map/adapter/extensions/agent-detection.d.ts.map +1 -0
  170. package/dist/map/adapter/extensions/agent-detection.js +91 -0
  171. package/dist/map/adapter/extensions/agent-detection.js.map +1 -0
  172. package/dist/map/adapter/extensions/agent-lifecycle.d.ts +82 -0
  173. package/dist/map/adapter/extensions/agent-lifecycle.d.ts.map +1 -0
  174. package/dist/map/adapter/extensions/agent-lifecycle.js +164 -0
  175. package/dist/map/adapter/extensions/agent-lifecycle.js.map +1 -0
  176. package/dist/map/adapter/extensions/cognitive.d.ts +27 -0
  177. package/dist/map/adapter/extensions/cognitive.d.ts.map +1 -0
  178. package/dist/map/adapter/extensions/cognitive.js +158 -0
  179. package/dist/map/adapter/extensions/cognitive.js.map +1 -0
  180. package/dist/map/adapter/extensions/index.d.ts +95 -0
  181. package/dist/map/adapter/extensions/index.d.ts.map +1 -0
  182. package/dist/map/adapter/extensions/index.js +228 -0
  183. package/dist/map/adapter/extensions/index.js.map +1 -0
  184. package/dist/map/adapter/extensions/mcp-bridge.d.ts +57 -0
  185. package/dist/map/adapter/extensions/mcp-bridge.d.ts.map +1 -0
  186. package/dist/map/adapter/extensions/mcp-bridge.js +745 -0
  187. package/dist/map/adapter/extensions/mcp-bridge.js.map +1 -0
  188. package/dist/map/adapter/extensions/resume.d.ts +47 -0
  189. package/dist/map/adapter/extensions/resume.d.ts.map +1 -0
  190. package/dist/map/adapter/extensions/resume.js +59 -0
  191. package/dist/map/adapter/extensions/resume.js.map +1 -0
  192. package/dist/map/adapter/extensions/streams.d.ts +95 -0
  193. package/dist/map/adapter/extensions/streams.d.ts.map +1 -0
  194. package/dist/map/adapter/extensions/streams.js +515 -0
  195. package/dist/map/adapter/extensions/streams.js.map +1 -0
  196. package/dist/map/adapter/extensions/task.d.ts +40 -0
  197. package/dist/map/adapter/extensions/task.d.ts.map +1 -0
  198. package/dist/map/adapter/extensions/task.js +197 -0
  199. package/dist/map/adapter/extensions/task.js.map +1 -0
  200. package/dist/map/adapter/extensions/update-metadata.d.ts +29 -0
  201. package/dist/map/adapter/extensions/update-metadata.d.ts.map +1 -0
  202. package/dist/map/adapter/extensions/update-metadata.js +67 -0
  203. package/dist/map/adapter/extensions/update-metadata.js.map +1 -0
  204. package/dist/map/adapter/extensions/wake.d.ts +60 -0
  205. package/dist/map/adapter/extensions/wake.d.ts.map +1 -0
  206. package/dist/map/adapter/extensions/wake.js +144 -0
  207. package/dist/map/adapter/extensions/wake.js.map +1 -0
  208. package/dist/map/adapter/extensions/workspace-files.d.ts +42 -0
  209. package/dist/map/adapter/extensions/workspace-files.d.ts.map +1 -0
  210. package/dist/map/adapter/extensions/workspace-files.js +338 -0
  211. package/dist/map/adapter/extensions/workspace-files.js.map +1 -0
  212. package/dist/map/adapter/extensions/workspace.d.ts +57 -0
  213. package/dist/map/adapter/extensions/workspace.d.ts.map +1 -0
  214. package/dist/map/adapter/extensions/workspace.js +81 -0
  215. package/dist/map/adapter/extensions/workspace.js.map +1 -0
  216. package/dist/map/adapter/index.d.ts +20 -0
  217. package/dist/map/adapter/index.d.ts.map +1 -0
  218. package/dist/map/adapter/index.js +40 -0
  219. package/dist/map/adapter/index.js.map +1 -0
  220. package/dist/map/adapter/interface.d.ts +450 -0
  221. package/dist/map/adapter/interface.d.ts.map +1 -0
  222. package/dist/map/adapter/interface.js +24 -0
  223. package/dist/map/adapter/interface.js.map +1 -0
  224. package/dist/map/adapter/mail-handler-adapter.d.ts +27 -0
  225. package/dist/map/adapter/mail-handler-adapter.d.ts.map +1 -0
  226. package/dist/map/adapter/mail-handler-adapter.js +292 -0
  227. package/dist/map/adapter/mail-handler-adapter.js.map +1 -0
  228. package/dist/map/adapter/map-adapter.d.ts +200 -0
  229. package/dist/map/adapter/map-adapter.d.ts.map +1 -0
  230. package/dist/map/adapter/map-adapter.js +1199 -0
  231. package/dist/map/adapter/map-adapter.js.map +1 -0
  232. package/dist/map/adapter/rpc-handler.d.ts +263 -0
  233. package/dist/map/adapter/rpc-handler.d.ts.map +1 -0
  234. package/dist/map/adapter/rpc-handler.js +365 -0
  235. package/dist/map/adapter/rpc-handler.js.map +1 -0
  236. package/dist/map/adapter/subscription-manager.d.ts +174 -0
  237. package/dist/map/adapter/subscription-manager.d.ts.map +1 -0
  238. package/dist/map/adapter/subscription-manager.js +248 -0
  239. package/dist/map/adapter/subscription-manager.js.map +1 -0
  240. package/dist/map/adapter/types.d.ts +194 -0
  241. package/dist/map/adapter/types.d.ts.map +1 -0
  242. package/dist/map/adapter/types.js +27 -0
  243. package/dist/map/adapter/types.js.map +1 -0
  244. package/dist/map/adapter/websocket-integration.d.ts +113 -0
  245. package/dist/map/adapter/websocket-integration.d.ts.map +1 -0
  246. package/dist/map/adapter/websocket-integration.js +134 -0
  247. package/dist/map/adapter/websocket-integration.js.map +1 -0
  248. package/dist/map/cascade-action-handler.d.ts.map +1 -1
  249. package/dist/map/cascade-action-handler.js +19 -5
  250. package/dist/map/cascade-action-handler.js.map +1 -1
  251. package/dist/map/federation/envelope.d.ts +98 -0
  252. package/dist/map/federation/envelope.d.ts.map +1 -0
  253. package/dist/map/federation/envelope.js +160 -0
  254. package/dist/map/federation/envelope.js.map +1 -0
  255. package/dist/map/federation/federation-handler.d.ts +50 -0
  256. package/dist/map/federation/federation-handler.d.ts.map +1 -0
  257. package/dist/map/federation/federation-handler.js +306 -0
  258. package/dist/map/federation/federation-handler.js.map +1 -0
  259. package/dist/map/federation/index.d.ts +14 -0
  260. package/dist/map/federation/index.d.ts.map +1 -0
  261. package/dist/map/federation/index.js +13 -0
  262. package/dist/map/federation/index.js.map +1 -0
  263. package/dist/map/federation/types.d.ts +239 -0
  264. package/dist/map/federation/types.d.ts.map +1 -0
  265. package/dist/map/federation/types.js +23 -0
  266. package/dist/map/federation/types.js.map +1 -0
  267. package/dist/map/mail-bridge.d.ts +7 -0
  268. package/dist/map/mail-bridge.d.ts.map +1 -1
  269. package/dist/map/mail-bridge.js +39 -9
  270. package/dist/map/mail-bridge.js.map +1 -1
  271. package/dist/map/server.d.ts.map +1 -1
  272. package/dist/map/server.js +17 -2
  273. package/dist/map/server.js.map +1 -1
  274. package/dist/map/types.d.ts +6 -0
  275. package/dist/map/types.d.ts.map +1 -1
  276. package/dist/mcp/map-client.d.ts +39 -0
  277. package/dist/mcp/map-client.d.ts.map +1 -0
  278. package/dist/mcp/map-client.js +129 -0
  279. package/dist/mcp/map-client.js.map +1 -0
  280. package/dist/mcp/mcp-server.d.ts +72 -0
  281. package/dist/mcp/mcp-server.d.ts.map +1 -0
  282. package/dist/mcp/mcp-server.js +1027 -0
  283. package/dist/mcp/mcp-server.js.map +1 -0
  284. package/dist/mcp/tools/claim_task.d.ts +35 -0
  285. package/dist/mcp/tools/claim_task.d.ts.map +1 -0
  286. package/dist/mcp/tools/claim_task.js +58 -0
  287. package/dist/mcp/tools/claim_task.js.map +1 -0
  288. package/dist/mcp/tools/done-v2.d.ts +0 -1
  289. package/dist/mcp/tools/done-v2.d.ts.map +1 -1
  290. package/dist/mcp/tools/done-v2.js +0 -1
  291. package/dist/mcp/tools/done-v2.js.map +1 -1
  292. package/dist/mcp/tools/done.d.ts +102 -0
  293. package/dist/mcp/tools/done.d.ts.map +1 -0
  294. package/dist/mcp/tools/done.js +253 -0
  295. package/dist/mcp/tools/done.js.map +1 -0
  296. package/dist/mcp/tools/inject_context.d.ts +61 -0
  297. package/dist/mcp/tools/inject_context.d.ts.map +1 -0
  298. package/dist/mcp/tools/inject_context.js +123 -0
  299. package/dist/mcp/tools/inject_context.js.map +1 -0
  300. package/dist/mcp/tools/list_claimable_tasks.d.ts +38 -0
  301. package/dist/mcp/tools/list_claimable_tasks.d.ts.map +1 -0
  302. package/dist/mcp/tools/list_claimable_tasks.js +63 -0
  303. package/dist/mcp/tools/list_claimable_tasks.js.map +1 -0
  304. package/dist/mcp/tools/unclaim_task.d.ts +31 -0
  305. package/dist/mcp/tools/unclaim_task.d.ts.map +1 -0
  306. package/dist/mcp/tools/unclaim_task.js +47 -0
  307. package/dist/mcp/tools/unclaim_task.js.map +1 -0
  308. package/dist/mcp/tools/wait_for_activity.d.ts +60 -0
  309. package/dist/mcp/tools/wait_for_activity.d.ts.map +1 -0
  310. package/dist/mcp/tools/wait_for_activity.js +135 -0
  311. package/dist/mcp/tools/wait_for_activity.js.map +1 -0
  312. package/dist/monitor/health-check-service.d.ts +143 -0
  313. package/dist/monitor/health-check-service.d.ts.map +1 -0
  314. package/dist/monitor/health-check-service.js +240 -0
  315. package/dist/monitor/health-check-service.js.map +1 -0
  316. package/dist/monitor/index.d.ts +14 -0
  317. package/dist/monitor/index.d.ts.map +1 -0
  318. package/dist/monitor/index.js +14 -0
  319. package/dist/monitor/index.js.map +1 -0
  320. package/dist/monitor/stall-detector.d.ts +109 -0
  321. package/dist/monitor/stall-detector.d.ts.map +1 -0
  322. package/dist/monitor/stall-detector.js +152 -0
  323. package/dist/monitor/stall-detector.js.map +1 -0
  324. package/dist/peer/capability-manager.d.ts +56 -0
  325. package/dist/peer/capability-manager.d.ts.map +1 -0
  326. package/dist/peer/capability-manager.js +186 -0
  327. package/dist/peer/capability-manager.js.map +1 -0
  328. package/dist/peer/encapsulation-manager.d.ts +190 -0
  329. package/dist/peer/encapsulation-manager.d.ts.map +1 -0
  330. package/dist/peer/encapsulation-manager.js +486 -0
  331. package/dist/peer/encapsulation-manager.js.map +1 -0
  332. package/dist/peer/federation-manager.d.ts +223 -0
  333. package/dist/peer/federation-manager.d.ts.map +1 -0
  334. package/dist/peer/federation-manager.js +528 -0
  335. package/dist/peer/federation-manager.js.map +1 -0
  336. package/dist/peer/hierarchy-errors.d.ts +208 -0
  337. package/dist/peer/hierarchy-errors.d.ts.map +1 -0
  338. package/dist/peer/hierarchy-errors.js +268 -0
  339. package/dist/peer/hierarchy-errors.js.map +1 -0
  340. package/dist/peer/hierarchy-protocol.d.ts +159 -0
  341. package/dist/peer/hierarchy-protocol.d.ts.map +1 -0
  342. package/dist/peer/hierarchy-protocol.js +142 -0
  343. package/dist/peer/hierarchy-protocol.js.map +1 -0
  344. package/dist/peer/index.d.ts +15 -0
  345. package/dist/peer/index.d.ts.map +1 -0
  346. package/dist/peer/index.js +15 -0
  347. package/dist/peer/index.js.map +1 -0
  348. package/dist/peer/peer-manager.d.ts +99 -0
  349. package/dist/peer/peer-manager.d.ts.map +1 -0
  350. package/dist/peer/peer-manager.js +333 -0
  351. package/dist/peer/peer-manager.js.map +1 -0
  352. package/dist/peer/task-delegation.d.ts +189 -0
  353. package/dist/peer/task-delegation.d.ts.map +1 -0
  354. package/dist/peer/task-delegation.js +303 -0
  355. package/dist/peer/task-delegation.js.map +1 -0
  356. package/dist/peer/transports/index.d.ts +8 -0
  357. package/dist/peer/transports/index.d.ts.map +1 -0
  358. package/dist/peer/transports/index.js +8 -0
  359. package/dist/peer/transports/index.js.map +1 -0
  360. package/dist/peer/transports/local-transport.d.ts +56 -0
  361. package/dist/peer/transports/local-transport.d.ts.map +1 -0
  362. package/dist/peer/transports/local-transport.js +263 -0
  363. package/dist/peer/transports/local-transport.js.map +1 -0
  364. package/dist/peer/transports/websocket-transport.d.ts +86 -0
  365. package/dist/peer/transports/websocket-transport.d.ts.map +1 -0
  366. package/dist/peer/transports/websocket-transport.js +338 -0
  367. package/dist/peer/transports/websocket-transport.js.map +1 -0
  368. package/dist/peer/types.d.ts +268 -0
  369. package/dist/peer/types.d.ts.map +1 -0
  370. package/dist/peer/types.js +36 -0
  371. package/dist/peer/types.js.map +1 -0
  372. package/dist/router/address-resolver.d.ts +102 -0
  373. package/dist/router/address-resolver.d.ts.map +1 -0
  374. package/dist/router/address-resolver.js +198 -0
  375. package/dist/router/address-resolver.js.map +1 -0
  376. package/dist/router/broadcast.d.ts +53 -0
  377. package/dist/router/broadcast.d.ts.map +1 -0
  378. package/dist/router/broadcast.js +75 -0
  379. package/dist/router/broadcast.js.map +1 -0
  380. package/dist/router/channels.d.ts +148 -0
  381. package/dist/router/channels.d.ts.map +1 -0
  382. package/dist/router/channels.js +126 -0
  383. package/dist/router/channels.js.map +1 -0
  384. package/dist/router/index.d.ts +21 -0
  385. package/dist/router/index.d.ts.map +1 -0
  386. package/dist/router/index.js +18 -0
  387. package/dist/router/index.js.map +1 -0
  388. package/dist/router/message-router.d.ts +197 -0
  389. package/dist/router/message-router.d.ts.map +1 -0
  390. package/dist/router/message-router.js +903 -0
  391. package/dist/router/message-router.js.map +1 -0
  392. package/dist/router/message-types.d.ts +183 -0
  393. package/dist/router/message-types.d.ts.map +1 -0
  394. package/dist/router/message-types.js +79 -0
  395. package/dist/router/message-types.js.map +1 -0
  396. package/dist/router/role-resolver.d.ts +67 -0
  397. package/dist/router/role-resolver.d.ts.map +1 -0
  398. package/dist/router/role-resolver.js +106 -0
  399. package/dist/router/role-resolver.js.map +1 -0
  400. package/dist/router/signals.d.ts +253 -0
  401. package/dist/router/signals.d.ts.map +1 -0
  402. package/dist/router/signals.js +53 -0
  403. package/dist/router/signals.js.map +1 -0
  404. package/dist/router/types.d.ts +191 -0
  405. package/dist/router/types.d.ts.map +1 -0
  406. package/dist/router/types.js +34 -0
  407. package/dist/router/types.js.map +1 -0
  408. package/dist/router/wake.d.ts +111 -0
  409. package/dist/router/wake.d.ts.map +1 -0
  410. package/dist/router/wake.js +180 -0
  411. package/dist/router/wake.js.map +1 -0
  412. package/dist/server/combined-server.d.ts +95 -0
  413. package/dist/server/combined-server.d.ts.map +1 -0
  414. package/dist/server/combined-server.js +335 -0
  415. package/dist/server/combined-server.js.map +1 -0
  416. package/dist/steering/index.d.ts +11 -0
  417. package/dist/steering/index.d.ts.map +1 -0
  418. package/dist/steering/index.js +11 -0
  419. package/dist/steering/index.js.map +1 -0
  420. package/dist/steering/inject.d.ts +39 -0
  421. package/dist/steering/inject.d.ts.map +1 -0
  422. package/dist/steering/inject.js +197 -0
  423. package/dist/steering/inject.js.map +1 -0
  424. package/dist/steering/types.d.ts +100 -0
  425. package/dist/steering/types.d.ts.map +1 -0
  426. package/dist/steering/types.js +11 -0
  427. package/dist/steering/types.js.map +1 -0
  428. package/dist/store/backends/index.d.ts +11 -0
  429. package/dist/store/backends/index.d.ts.map +1 -0
  430. package/dist/store/backends/index.js +15 -0
  431. package/dist/store/backends/index.js.map +1 -0
  432. package/dist/store/backends/json-backend.d.ts +23 -0
  433. package/dist/store/backends/json-backend.d.ts.map +1 -0
  434. package/dist/store/backends/json-backend.js +220 -0
  435. package/dist/store/backends/json-backend.js.map +1 -0
  436. package/dist/store/backends/memory-backend.d.ts +12 -0
  437. package/dist/store/backends/memory-backend.d.ts.map +1 -0
  438. package/dist/store/backends/memory-backend.js +205 -0
  439. package/dist/store/backends/memory-backend.js.map +1 -0
  440. package/dist/store/backends/sqlite-backend.d.ts +27 -0
  441. package/dist/store/backends/sqlite-backend.d.ts.map +1 -0
  442. package/dist/store/backends/sqlite-backend.js +231 -0
  443. package/dist/store/backends/sqlite-backend.js.map +1 -0
  444. package/dist/store/backends/tinybase-backend.d.ts +22 -0
  445. package/dist/store/backends/tinybase-backend.d.ts.map +1 -0
  446. package/dist/store/backends/tinybase-backend.js +203 -0
  447. package/dist/store/backends/tinybase-backend.js.map +1 -0
  448. package/dist/store/backends/types.d.ts +175 -0
  449. package/dist/store/backends/types.d.ts.map +1 -0
  450. package/dist/store/backends/types.js +28 -0
  451. package/dist/store/backends/types.js.map +1 -0
  452. package/dist/store/event-store.d.ts +128 -0
  453. package/dist/store/event-store.d.ts.map +1 -0
  454. package/dist/store/event-store.js +1751 -0
  455. package/dist/store/event-store.js.map +1 -0
  456. package/dist/store/instance.d.ts +290 -0
  457. package/dist/store/instance.d.ts.map +1 -0
  458. package/dist/store/instance.js +363 -0
  459. package/dist/store/instance.js.map +1 -0
  460. package/dist/store/migrations.d.ts +41 -0
  461. package/dist/store/migrations.d.ts.map +1 -0
  462. package/dist/store/migrations.js +79 -0
  463. package/dist/store/migrations.js.map +1 -0
  464. package/dist/store/test-utils.d.ts +63 -0
  465. package/dist/store/test-utils.d.ts.map +1 -0
  466. package/dist/store/test-utils.js +63 -0
  467. package/dist/store/test-utils.js.map +1 -0
  468. package/dist/store/types/config.d.ts +16 -0
  469. package/dist/store/types/config.d.ts.map +1 -0
  470. package/dist/store/types/config.js +8 -0
  471. package/dist/store/types/config.js.map +1 -0
  472. package/dist/store/types/conversations.d.ts +91 -0
  473. package/dist/store/types/conversations.d.ts.map +1 -0
  474. package/dist/store/types/conversations.js +8 -0
  475. package/dist/store/types/conversations.js.map +1 -0
  476. package/dist/store/types/sessions.d.ts +44 -0
  477. package/dist/store/types/sessions.d.ts.map +1 -0
  478. package/dist/store/types/sessions.js +9 -0
  479. package/dist/store/types/sessions.js.map +1 -0
  480. package/dist/store/types.d.ts +115 -0
  481. package/dist/store/types.d.ts.map +1 -0
  482. package/dist/store/types.js +6 -0
  483. package/dist/store/types.js.map +1 -0
  484. package/dist/task/backend/index.d.ts +93 -0
  485. package/dist/task/backend/index.d.ts.map +1 -0
  486. package/dist/task/backend/index.js +178 -0
  487. package/dist/task/backend/index.js.map +1 -0
  488. package/dist/task/backend/memory.d.ts +70 -0
  489. package/dist/task/backend/memory.d.ts.map +1 -0
  490. package/dist/task/backend/memory.js +621 -0
  491. package/dist/task/backend/memory.js.map +1 -0
  492. package/dist/task/backend/opentasks/backend.d.ts +140 -0
  493. package/dist/task/backend/opentasks/backend.d.ts.map +1 -0
  494. package/dist/task/backend/opentasks/backend.js +1023 -0
  495. package/dist/task/backend/opentasks/backend.js.map +1 -0
  496. package/dist/task/backend/opentasks/client.d.ts +337 -0
  497. package/dist/task/backend/opentasks/client.d.ts.map +1 -0
  498. package/dist/task/backend/opentasks/client.js +225 -0
  499. package/dist/task/backend/opentasks/client.js.map +1 -0
  500. package/dist/task/backend/opentasks/daemon-manager.d.ts +89 -0
  501. package/dist/task/backend/opentasks/daemon-manager.d.ts.map +1 -0
  502. package/dist/task/backend/opentasks/daemon-manager.js +195 -0
  503. package/dist/task/backend/opentasks/daemon-manager.js.map +1 -0
  504. package/dist/task/backend/opentasks/index.d.ts +21 -0
  505. package/dist/task/backend/opentasks/index.d.ts.map +1 -0
  506. package/dist/task/backend/opentasks/index.js +21 -0
  507. package/dist/task/backend/opentasks/index.js.map +1 -0
  508. package/dist/task/backend/opentasks/mapping.d.ts +48 -0
  509. package/dist/task/backend/opentasks/mapping.d.ts.map +1 -0
  510. package/dist/task/backend/opentasks/mapping.js +77 -0
  511. package/dist/task/backend/opentasks/mapping.js.map +1 -0
  512. package/dist/task/backend/sudocode/__tests__/integration/test-utils.d.ts +54 -0
  513. package/dist/task/backend/sudocode/__tests__/integration/test-utils.d.ts.map +1 -0
  514. package/dist/task/backend/sudocode/__tests__/integration/test-utils.js +88 -0
  515. package/dist/task/backend/sudocode/__tests__/integration/test-utils.js.map +1 -0
  516. package/dist/task/backend/sudocode/backend.d.ts +155 -0
  517. package/dist/task/backend/sudocode/backend.d.ts.map +1 -0
  518. package/dist/task/backend/sudocode/backend.js +942 -0
  519. package/dist/task/backend/sudocode/backend.js.map +1 -0
  520. package/dist/task/backend/sudocode/client.d.ts +303 -0
  521. package/dist/task/backend/sudocode/client.d.ts.map +1 -0
  522. package/dist/task/backend/sudocode/client.js +101 -0
  523. package/dist/task/backend/sudocode/client.js.map +1 -0
  524. package/dist/task/backend/sudocode/index.d.ts +19 -0
  525. package/dist/task/backend/sudocode/index.d.ts.map +1 -0
  526. package/dist/task/backend/sudocode/index.js +17 -0
  527. package/dist/task/backend/sudocode/index.js.map +1 -0
  528. package/dist/task/backend/sudocode/mapping.d.ts +51 -0
  529. package/dist/task/backend/sudocode/mapping.d.ts.map +1 -0
  530. package/dist/task/backend/sudocode/mapping.js +86 -0
  531. package/dist/task/backend/sudocode/mapping.js.map +1 -0
  532. package/dist/task/backend/sudocode/server-client.d.ts +56 -0
  533. package/dist/task/backend/sudocode/server-client.d.ts.map +1 -0
  534. package/dist/task/backend/sudocode/server-client.js +367 -0
  535. package/dist/task/backend/sudocode/server-client.js.map +1 -0
  536. package/dist/task/backend/sudocode/standalone-client.d.ts +91 -0
  537. package/dist/task/backend/sudocode/standalone-client.d.ts.map +1 -0
  538. package/dist/task/backend/sudocode/standalone-client.js +476 -0
  539. package/dist/task/backend/sudocode/standalone-client.js.map +1 -0
  540. package/dist/task/backend/sudocode/sync-policy.d.ts +166 -0
  541. package/dist/task/backend/sudocode/sync-policy.d.ts.map +1 -0
  542. package/dist/task/backend/sudocode/sync-policy.js +221 -0
  543. package/dist/task/backend/sudocode/sync-policy.js.map +1 -0
  544. package/dist/task/backend/sudocode/tools.d.ts +87 -0
  545. package/dist/task/backend/sudocode/tools.d.ts.map +1 -0
  546. package/dist/task/backend/sudocode/tools.js +743 -0
  547. package/dist/task/backend/sudocode/tools.js.map +1 -0
  548. package/dist/task/backend/tool-provider.d.ts +56 -0
  549. package/dist/task/backend/tool-provider.d.ts.map +1 -0
  550. package/dist/task/backend/tool-provider.js +424 -0
  551. package/dist/task/backend/tool-provider.js.map +1 -0
  552. package/dist/task/backend/types.d.ts +297 -0
  553. package/dist/task/backend/types.d.ts.map +1 -0
  554. package/dist/task/backend/types.js +27 -0
  555. package/dist/task/backend/types.js.map +1 -0
  556. package/dist/task/backend/unified-tool-provider.d.ts +57 -0
  557. package/dist/task/backend/unified-tool-provider.d.ts.map +1 -0
  558. package/dist/task/backend/unified-tool-provider.js +623 -0
  559. package/dist/task/backend/unified-tool-provider.js.map +1 -0
  560. package/dist/task/index.d.ts +7 -0
  561. package/dist/task/index.d.ts.map +1 -0
  562. package/dist/task/index.js +7 -0
  563. package/dist/task/index.js.map +1 -0
  564. package/dist/task/retry-policy.d.ts +89 -0
  565. package/dist/task/retry-policy.d.ts.map +1 -0
  566. package/dist/task/retry-policy.js +160 -0
  567. package/dist/task/retry-policy.js.map +1 -0
  568. package/dist/task/task-manager.d.ts +70 -0
  569. package/dist/task/task-manager.d.ts.map +1 -0
  570. package/dist/task/task-manager.js +319 -0
  571. package/dist/task/task-manager.js.map +1 -0
  572. package/dist/task/types.d.ts +72 -0
  573. package/dist/task/types.d.ts.map +1 -0
  574. package/dist/task/types.js +33 -0
  575. package/dist/task/types.js.map +1 -0
  576. package/dist/teams/team-loader.d.ts +2 -1
  577. package/dist/teams/team-loader.d.ts.map +1 -1
  578. package/dist/teams/team-loader.js +2 -1
  579. package/dist/teams/team-loader.js.map +1 -1
  580. package/dist/teams/team-manager.d.ts +101 -0
  581. package/dist/teams/team-manager.d.ts.map +1 -0
  582. package/dist/teams/team-manager.js +260 -0
  583. package/dist/teams/team-manager.js.map +1 -0
  584. package/dist/teams/team-runtime-v2.d.ts +0 -3
  585. package/dist/teams/team-runtime-v2.d.ts.map +1 -1
  586. package/dist/teams/team-runtime-v2.js +31 -93
  587. package/dist/teams/team-runtime-v2.js.map +1 -1
  588. package/dist/teams/team-runtime.d.ts +245 -0
  589. package/dist/teams/team-runtime.d.ts.map +1 -0
  590. package/dist/teams/team-runtime.js +1023 -0
  591. package/dist/teams/team-runtime.js.map +1 -0
  592. package/dist/trigger/router/index.d.ts +11 -0
  593. package/dist/trigger/router/index.d.ts.map +1 -0
  594. package/dist/trigger/router/index.js +10 -0
  595. package/dist/trigger/router/index.js.map +1 -0
  596. package/dist/trigger/router/strategies/ai-router-strategy.d.ts +34 -0
  597. package/dist/trigger/router/strategies/ai-router-strategy.d.ts.map +1 -0
  598. package/dist/trigger/router/strategies/ai-router-strategy.js +359 -0
  599. package/dist/trigger/router/strategies/ai-router-strategy.js.map +1 -0
  600. package/dist/trigger/router/strategies/direct-strategy.d.ts +32 -0
  601. package/dist/trigger/router/strategies/direct-strategy.d.ts.map +1 -0
  602. package/dist/trigger/router/strategies/direct-strategy.js +119 -0
  603. package/dist/trigger/router/strategies/direct-strategy.js.map +1 -0
  604. package/dist/trigger/router/strategies/index.d.ts +11 -0
  605. package/dist/trigger/router/strategies/index.d.ts.map +1 -0
  606. package/dist/trigger/router/strategies/index.js +11 -0
  607. package/dist/trigger/router/strategies/index.js.map +1 -0
  608. package/dist/trigger/router/strategies/role-strategy.d.ts +39 -0
  609. package/dist/trigger/router/strategies/role-strategy.d.ts.map +1 -0
  610. package/dist/trigger/router/strategies/role-strategy.js +207 -0
  611. package/dist/trigger/router/strategies/role-strategy.js.map +1 -0
  612. package/dist/trigger/router/trigger-router.d.ts +54 -0
  613. package/dist/trigger/router/trigger-router.d.ts.map +1 -0
  614. package/dist/trigger/router/trigger-router.js +362 -0
  615. package/dist/trigger/router/trigger-router.js.map +1 -0
  616. package/dist/trigger/router/types.d.ts +225 -0
  617. package/dist/trigger/router/types.d.ts.map +1 -0
  618. package/dist/trigger/router/types.js +10 -0
  619. package/dist/trigger/router/types.js.map +1 -0
  620. package/dist/trigger/sources/cron/cron-service.d.ts.map +1 -1
  621. package/dist/trigger/sources/cron/cron-service.js +6 -3
  622. package/dist/trigger/sources/cron/cron-service.js.map +1 -1
  623. package/dist/trigger/trigger-system.d.ts +77 -0
  624. package/dist/trigger/trigger-system.d.ts.map +1 -0
  625. package/dist/trigger/trigger-system.js +84 -0
  626. package/dist/trigger/trigger-system.js.map +1 -0
  627. package/dist/util/git-safety.d.ts +33 -0
  628. package/dist/util/git-safety.d.ts.map +1 -0
  629. package/dist/util/git-safety.js +94 -0
  630. package/dist/util/git-safety.js.map +1 -0
  631. package/dist/workspace/index.d.ts +0 -1
  632. package/dist/workspace/index.d.ts.map +1 -1
  633. package/dist/workspace/index.js +0 -2
  634. package/dist/workspace/index.js.map +1 -1
  635. package/dist/workspace/landing/direct-push.d.ts.map +1 -1
  636. package/dist/workspace/landing/direct-push.js +22 -7
  637. package/dist/workspace/landing/direct-push.js.map +1 -1
  638. package/dist/workspace/landing/queue-to-branch.d.ts.map +1 -1
  639. package/dist/workspace/landing/queue-to-branch.js +1 -3
  640. package/dist/workspace/landing/queue-to-branch.js.map +1 -1
  641. package/dist/workspace/types.d.ts +0 -13
  642. package/dist/workspace/types.d.ts.map +1 -1
  643. package/dist/workspace/workspace-manager.d.ts +0 -11
  644. package/dist/workspace/workspace-manager.d.ts.map +1 -1
  645. package/dist/workspace/workspace-manager.js +0 -30
  646. package/dist/workspace/workspace-manager.js.map +1 -1
  647. package/package.json +28 -2
  648. package/templates/teams/self-driving/prompts/grinder.md +1 -0
  649. package/templates/teams/self-driving/prompts/judge.md +1 -0
  650. package/templates/teams/self-driving/prompts/planner.md +1 -0
  651. package/templates/teams/self-driving/roles/grinder.yaml +15 -0
  652. package/templates/teams/self-driving/roles/judge.yaml +10 -0
  653. package/templates/teams/self-driving/roles/planner.yaml +16 -0
  654. package/.claude/commands/openspec/apply.md +0 -23
  655. package/.claude/commands/openspec/archive.md +0 -27
  656. package/.claude/commands/openspec/proposal.md +0 -28
  657. package/.claude/settings.json +0 -133
  658. package/.gitattributes +0 -3
  659. package/.opentasks/config.json +0 -9
  660. package/.opentasks/graph.jsonl +0 -0
  661. package/.sessionlog/settings.json +0 -4
  662. package/.sudocode/issues.jsonl +0 -183
  663. package/.sudocode/specs.jsonl +0 -56
  664. package/AGENTS.md +0 -18
  665. package/CLAUDE.md +0 -923
  666. package/docs/architecture.md +0 -508
  667. package/docs/configuration.md +0 -323
  668. package/docs/conflict-recovery.md +0 -472
  669. package/docs/design/task-dispatcher.md +0 -880
  670. package/docs/design-subsystem-extraction.md +0 -627
  671. package/docs/git-cascade-integration-gaps.md +0 -678
  672. package/docs/implementation-details.md +0 -1127
  673. package/docs/implementation-summary.md +0 -448
  674. package/docs/lifecycle-events-design.md +0 -111
  675. package/docs/mail-integration.md +0 -608
  676. package/docs/openhive-capability-summary.md +0 -415
  677. package/docs/openhive-integration.md +0 -415
  678. package/docs/plan-self-driving-support.md +0 -433
  679. package/docs/roadmap-v2-gaps.md +0 -216
  680. package/docs/spec-self-driving-support.md +0 -462
  681. package/docs/team-templates.md +0 -860
  682. package/docs/teams.md +0 -306
  683. package/docs/trigger-system-design.md +0 -333
  684. package/docs/troubleshooting.md +0 -489
  685. package/docs/workspace-interfaces.md +0 -731
  686. package/docs/workspace-redesign-plan.md +0 -302
  687. package/examples/distributed-peer-communication.ts +0 -202
  688. package/examples/local-peer-communication.ts +0 -165
  689. package/index.js +0 -2
  690. package/mvp_docs/agent-execution-system.md +0 -347
  691. package/mvp_docs/agent-interface.md +0 -580
  692. package/mvp_docs/data-structures.md +0 -701
  693. package/mvp_docs/dynamic-meta-orchestration.md +0 -116
  694. package/mvp_docs/multi-agent-interaction-design.md +0 -779
  695. package/mvp_docs/mvp-implementation-plan.md +0 -1148
  696. package/renovate.json5 +0 -6
  697. package/scripts/test-acp-integration.ts +0 -422
  698. package/src/__tests__/boot-v2.test.ts +0 -631
  699. package/src/__tests__/e2e/acp-over-map-live.e2e.test.ts +0 -496
  700. package/src/__tests__/e2e/acp-over-map.e2e.test.ts +0 -457
  701. package/src/__tests__/e2e/agent-lifecycle.e2e.test.ts +0 -770
  702. package/src/__tests__/e2e/auto-sync.e2e.test.ts +0 -257
  703. package/src/__tests__/e2e/bootstrap.e2e.test.ts +0 -319
  704. package/src/__tests__/e2e/cascade-rebase.e2e.test.ts +0 -254
  705. package/src/__tests__/e2e/cc-swarm-bridge.e2e.test.ts +0 -253
  706. package/src/__tests__/e2e/cli-run.e2e.test.ts +0 -167
  707. package/src/__tests__/e2e/cognitive-workspace.e2e.test.ts +0 -282
  708. package/src/__tests__/e2e/dispatch-coordination.e2e.test.ts +0 -495
  709. package/src/__tests__/e2e/dispatch-live.e2e.test.ts +0 -564
  710. package/src/__tests__/e2e/dispatch-opentasks.e2e.test.ts +0 -496
  711. package/src/__tests__/e2e/dispatch-phase2-live.e2e.test.ts +0 -456
  712. package/src/__tests__/e2e/dispatch-phase2.e2e.test.ts +0 -386
  713. package/src/__tests__/e2e/dispatch.e2e.test.ts +0 -376
  714. package/src/__tests__/e2e/done-scenarios.e2e.test.ts +0 -322
  715. package/src/__tests__/e2e/live-agent.e2e.test.ts +0 -1330
  716. package/src/__tests__/e2e/map-server.e2e.test.ts +0 -128
  717. package/src/__tests__/e2e/map-sidecar.e2e.test.ts +0 -139
  718. package/src/__tests__/e2e/opentasks-integration.e2e.test.ts +0 -280
  719. package/src/__tests__/e2e/pull-mode.e2e.test.ts +0 -632
  720. package/src/__tests__/e2e/resume-continue.e2e.test.ts +0 -312
  721. package/src/__tests__/e2e/self-driving-v3.e2e.test.ts +0 -197
  722. package/src/__tests__/e2e/spawn-resolver.e2e.test.ts +0 -200
  723. package/src/__tests__/e2e/swarmkit-integration.e2e.test.ts +0 -562
  724. package/src/__tests__/e2e/swarmkit-live.e2e.test.ts +0 -1049
  725. package/src/__tests__/e2e/trajectory-tracking.e2e.test.ts +0 -258
  726. package/src/__tests__/e2e/trigger-wake.e2e.test.ts +0 -257
  727. package/src/__tests__/e2e/workspace-lifecycle.e2e.test.ts +0 -383
  728. package/src/__tests__/e2e/workspace-v3.e2e.test.ts +0 -413
  729. package/src/acp/__tests__/claude-code-replay.test.ts +0 -225
  730. package/src/acp/__tests__/macro-agent.test.ts +0 -387
  731. package/src/acp/__tests__/session-mapper.test.ts +0 -152
  732. package/src/acp/__tests__/websocket-server.test.ts +0 -194
  733. package/src/acp/claude-code-replay.ts +0 -208
  734. package/src/acp/index.ts +0 -32
  735. package/src/acp/macro-agent.ts +0 -995
  736. package/src/acp/map-bridge.ts +0 -193
  737. package/src/acp/session-mapper.ts +0 -116
  738. package/src/acp/types.ts +0 -99
  739. package/src/acp/websocket-server.ts +0 -213
  740. package/src/adapters/__tests__/federation.test.ts +0 -256
  741. package/src/adapters/__tests__/inbox-adapter.test.ts +0 -316
  742. package/src/adapters/__tests__/tasks-adapter.test.ts +0 -270
  743. package/src/adapters/federation.ts +0 -185
  744. package/src/adapters/inbox-adapter.ts +0 -292
  745. package/src/adapters/inbox-client-adapter.ts +0 -173
  746. package/src/adapters/index.ts +0 -44
  747. package/src/adapters/opentasks-daemon.ts +0 -252
  748. package/src/adapters/tasks-adapter.ts +0 -330
  749. package/src/adapters/types.ts +0 -286
  750. package/src/agent/__tests__/agent-manager-topology.test.ts +0 -73
  751. package/src/agent/__tests__/agent-manager-v2.permission-interception.test.ts +0 -296
  752. package/src/agent/__tests__/agent-manager-v2.permissions.test.ts +0 -233
  753. package/src/agent/__tests__/agent-manager-v2.test.ts +0 -614
  754. package/src/agent/__tests__/agent-store.test.ts +0 -465
  755. package/src/agent/__tests__/task-ref-resolution.test.ts +0 -231
  756. package/src/agent/agent-manager-v2.ts +0 -2021
  757. package/src/agent/agent-manager.ts +0 -386
  758. package/src/agent/agent-store.ts +0 -409
  759. package/src/agent/index.ts +0 -7
  760. package/src/agent/prompts/coordinator-signals.ts +0 -115
  761. package/src/agent/prompts/index.ts +0 -7
  762. package/src/agent/system-prompt.ts +0 -298
  763. package/src/agent/types.ts +0 -459
  764. package/src/agent-detection/__tests__/command-builder.test.ts +0 -336
  765. package/src/agent-detection/__tests__/detector.test.ts +0 -768
  766. package/src/agent-detection/__tests__/registry.test.ts +0 -254
  767. package/src/agent-detection/command-builder.ts +0 -90
  768. package/src/agent-detection/detector.ts +0 -307
  769. package/src/agent-detection/index.ts +0 -36
  770. package/src/agent-detection/registry.ts +0 -200
  771. package/src/agent-detection/types.ts +0 -184
  772. package/src/api/__tests__/server.test.ts +0 -292
  773. package/src/api/index.ts +0 -8
  774. package/src/api/server.ts +0 -380
  775. package/src/api/types.ts +0 -39
  776. package/src/auth/__tests__/token.test.ts +0 -100
  777. package/src/auth/index.ts +0 -1
  778. package/src/auth/token.ts +0 -82
  779. package/src/boot-v2.ts +0 -1343
  780. package/src/cli/__tests__/stable-instance-id.test.ts +0 -57
  781. package/src/cli/acp.ts +0 -101
  782. package/src/cli/inbox-mcp-proxy.ts +0 -56
  783. package/src/cli/index.ts +0 -566
  784. package/src/cli/mcp.ts +0 -305
  785. package/src/cli/parse-args.ts +0 -54
  786. package/src/cli/stable-instance-id.ts +0 -14
  787. package/src/cognitive/__tests__/macro-agent-backend.test.ts +0 -520
  788. package/src/cognitive/__tests__/session-converter.test.ts +0 -423
  789. package/src/cognitive/__tests__/workspace-handler.test.ts +0 -221
  790. package/src/cognitive/analyst-role.ts +0 -59
  791. package/src/cognitive/index.ts +0 -49
  792. package/src/cognitive/macro-agent-backend.ts +0 -370
  793. package/src/cognitive/session-converter.ts +0 -151
  794. package/src/cognitive/types.ts +0 -163
  795. package/src/cognitive/workspace-handler.ts +0 -163
  796. package/src/config/index.ts +0 -9
  797. package/src/config/project-config.ts +0 -294
  798. package/src/control/__tests__/control-resilience.test.ts +0 -251
  799. package/src/control/__tests__/control-socket.test.ts +0 -240
  800. package/src/control/control-client.ts +0 -337
  801. package/src/control/control-server.ts +0 -298
  802. package/src/control/index.ts +0 -17
  803. package/src/control/types.ts +0 -95
  804. package/src/dispatch/CLAUDE.md +0 -129
  805. package/src/dispatch/__tests__/loadout-translation.test.ts +0 -141
  806. package/src/dispatch/__tests__/mail-inbound-consumer.integration.test.ts +0 -519
  807. package/src/dispatch/__tests__/mail-inbound-consumer.test.ts +0 -800
  808. package/src/dispatch/__tests__/mail-inbound-reuse-consumer.test.ts +0 -575
  809. package/src/dispatch/__tests__/permission-evaluator.test.ts +0 -196
  810. package/src/dispatch/__tests__/permission-overlay.test.ts +0 -56
  811. package/src/dispatch/__tests__/permissions-handler.test.ts +0 -168
  812. package/src/dispatch/__tests__/spawn-agent-handler.test.ts +0 -282
  813. package/src/dispatch/loadout-translation.ts +0 -138
  814. package/src/dispatch/mail-inbound-consumer.ts +0 -560
  815. package/src/dispatch/mail-inbound-reuse-consumer.ts +0 -479
  816. package/src/dispatch/permission-evaluator.ts +0 -191
  817. package/src/dispatch/permission-overlay.ts +0 -89
  818. package/src/dispatch/permissions-handler.ts +0 -112
  819. package/src/dispatch/spawn-agent-handler.ts +0 -160
  820. package/src/index.ts +0 -115
  821. package/src/integrations/__tests__/context-builder.test.ts +0 -218
  822. package/src/integrations/__tests__/sessionlog.test.ts +0 -498
  823. package/src/integrations/__tests__/skilltree.test.ts +0 -136
  824. package/src/integrations/context-builder.ts +0 -280
  825. package/src/integrations/sessionlog.ts +0 -194
  826. package/src/integrations/skilltree.ts +0 -184
  827. package/src/lifecycle/__tests__/cascade-consolidation.test.ts +0 -240
  828. package/src/lifecycle/__tests__/handlers-v2.test.ts +0 -565
  829. package/src/lifecycle/cascade.ts +0 -335
  830. package/src/lifecycle/cleanup.ts +0 -373
  831. package/src/lifecycle/handlers-v2.ts +0 -508
  832. package/src/lifecycle/index.ts +0 -76
  833. package/src/lifecycle/types.ts +0 -260
  834. package/src/map/__tests__/cascade-bridge.test.ts +0 -229
  835. package/src/map/__tests__/cascade-diff-server.test.ts +0 -434
  836. package/src/map/__tests__/emit-event.test.ts +0 -71
  837. package/src/map/__tests__/lifecycle-bridge.test.ts +0 -430
  838. package/src/map/__tests__/mail-bridge.test.ts +0 -284
  839. package/src/map/__tests__/permission-forwarding.test.ts +0 -143
  840. package/src/map/__tests__/sidecar-diff-install-smoke.test.ts +0 -90
  841. package/src/map/__tests__/sidecar-integration.test.ts +0 -190
  842. package/src/map/__tests__/task-bridge.test.ts +0 -153
  843. package/src/map/__tests__/trajectory-reporter.test.ts +0 -173
  844. package/src/map/acp-bridge.ts +0 -293
  845. package/src/map/cascade-action-handler.ts +0 -205
  846. package/src/map/cascade-bridge.ts +0 -339
  847. package/src/map/cascade-diff-server.ts +0 -404
  848. package/src/map/cc-swarm-hooks.ts +0 -242
  849. package/src/map/coordination-handler.ts +0 -232
  850. package/src/map/index.ts +0 -18
  851. package/src/map/lifecycle-bridge.ts +0 -236
  852. package/src/map/mail-bridge.ts +0 -215
  853. package/src/map/repo-workspace.ts +0 -82
  854. package/src/map/server.ts +0 -758
  855. package/src/map/sidecar.ts +0 -826
  856. package/src/map/task-bridge.ts +0 -89
  857. package/src/map/trajectory-reporter.ts +0 -124
  858. package/src/map/types.ts +0 -304
  859. package/src/mcp/__tests__/mcp-server-v2.test.ts +0 -236
  860. package/src/mcp/index.ts +0 -6
  861. package/src/mcp/mcp-server-v2.ts +0 -485
  862. package/src/mcp/tools/done-v2.ts +0 -213
  863. package/src/mcp/types.ts +0 -432
  864. package/src/metrics/__tests__/metrics.test.ts +0 -205
  865. package/src/metrics/index.ts +0 -13
  866. package/src/metrics/metrics.ts +0 -151
  867. package/src/metrics/types.ts +0 -63
  868. package/src/roles/__tests__/config-loader.test.ts +0 -540
  869. package/src/roles/builtin/coordinator.ts +0 -75
  870. package/src/roles/builtin/generic.ts +0 -39
  871. package/src/roles/builtin/index.ts +0 -51
  872. package/src/roles/builtin/integrator.ts +0 -62
  873. package/src/roles/builtin/monitor.ts +0 -65
  874. package/src/roles/builtin/worker.ts +0 -134
  875. package/src/roles/capabilities.ts +0 -257
  876. package/src/roles/config-loader.ts +0 -405
  877. package/src/roles/index.ts +0 -141
  878. package/src/roles/registry.ts +0 -713
  879. package/src/roles/types.ts +0 -344
  880. package/src/store/index.ts +0 -8
  881. package/src/store/types/agents.ts +0 -69
  882. package/src/store/types/events.ts +0 -91
  883. package/src/store/types/index.ts +0 -9
  884. package/src/store/types/messages.ts +0 -32
  885. package/src/store/types/primitives.ts +0 -9
  886. package/src/store/types/tasks.ts +0 -124
  887. package/src/teams/__tests__/team-manager-v2.test.ts +0 -425
  888. package/src/teams/__tests__/team-runtime-v2.test.ts +0 -402
  889. package/src/teams/index.ts +0 -29
  890. package/src/teams/seed-defaults.ts +0 -83
  891. package/src/teams/team-loader.ts +0 -476
  892. package/src/teams/team-manager-v2.ts +0 -343
  893. package/src/teams/team-runtime-v2.ts +0 -920
  894. package/src/teams/types.ts +0 -276
  895. package/src/trigger/__tests__/cron-service.test.ts +0 -548
  896. package/src/trigger/__tests__/scheduler.test.ts +0 -371
  897. package/src/trigger/__tests__/system-event-queue.test.ts +0 -147
  898. package/src/trigger/__tests__/trigger-system-v2.test.ts +0 -257
  899. package/src/trigger/__tests__/wake-manager.test.ts +0 -356
  900. package/src/trigger/__tests__/webhook-handler.test.ts +0 -567
  901. package/src/trigger/index.ts +0 -110
  902. package/src/trigger/queue/index.ts +0 -21
  903. package/src/trigger/queue/system-event-queue.ts +0 -232
  904. package/src/trigger/queue/types.ts +0 -149
  905. package/src/trigger/sources/cron/cron-service.ts +0 -499
  906. package/src/trigger/sources/cron/index.ts +0 -41
  907. package/src/trigger/sources/cron/scheduler.ts +0 -344
  908. package/src/trigger/sources/cron/types.ts +0 -333
  909. package/src/trigger/sources/index.ts +0 -10
  910. package/src/trigger/sources/webhook/index.ts +0 -25
  911. package/src/trigger/sources/webhook/types.ts +0 -205
  912. package/src/trigger/sources/webhook/webhook-handler.ts +0 -410
  913. package/src/trigger/strategies/ai-router.ts +0 -170
  914. package/src/trigger/trigger-system-v2.ts +0 -536
  915. package/src/trigger/types.ts +0 -228
  916. package/src/trigger/wake/index.ts +0 -22
  917. package/src/trigger/wake/types.ts +0 -162
  918. package/src/trigger/wake/wake-manager.ts +0 -390
  919. package/src/workspace/__tests__/git-cascade-adapter.test.ts +0 -563
  920. package/src/workspace/__tests__/land-dispatch.test.ts +0 -214
  921. package/src/workspace/__tests__/self-driving-yaml.test.ts +0 -122
  922. package/src/workspace/__tests__/shared-worktree-refcount.test.ts +0 -154
  923. package/src/workspace/__tests__/standalone-mode.test.ts +0 -118
  924. package/src/workspace/__tests__/workspace-manager-v3.test.ts +0 -245
  925. package/src/workspace/__tests__/yaml-schema.test.ts +0 -210
  926. package/src/workspace/config.ts +0 -165
  927. package/src/workspace/git-cascade-adapter.ts +0 -1213
  928. package/src/workspace/index.ts +0 -110
  929. package/src/workspace/landing/__tests__/strategies.test.ts +0 -184
  930. package/src/workspace/landing/direct-push.ts +0 -91
  931. package/src/workspace/landing/index.ts +0 -40
  932. package/src/workspace/landing/merge-to-parent.ts +0 -229
  933. package/src/workspace/landing/optimistic-push.ts +0 -36
  934. package/src/workspace/landing/queue-to-branch.ts +0 -108
  935. package/src/workspace/merge-queue/__tests__/conflict-resolution-git.e2e.test.ts +0 -641
  936. package/src/workspace/merge-queue/__tests__/conflict-resolution.test.ts +0 -707
  937. package/src/workspace/merge-queue/__tests__/merge-queue-concurrent.test.ts +0 -628
  938. package/src/workspace/merge-queue/__tests__/merge-queue-edge-cases.test.ts +0 -1217
  939. package/src/workspace/merge-queue/__tests__/merge-queue.test.ts +0 -506
  940. package/src/workspace/merge-queue/__tests__/real-git-operations.e2e.test.ts +0 -556
  941. package/src/workspace/merge-queue/__tests__/resolver-flow.test.ts +0 -472
  942. package/src/workspace/merge-queue/index.ts +0 -38
  943. package/src/workspace/merge-queue/merge-queue.ts +0 -585
  944. package/src/workspace/merge-queue/schema.ts +0 -98
  945. package/src/workspace/merge-queue/types.ts +0 -316
  946. package/src/workspace/pool/__tests__/worktree-pool.integration.test.ts +0 -1281
  947. package/src/workspace/pool/__tests__/worktree-pool.test.ts +0 -590
  948. package/src/workspace/pool/index.ts +0 -26
  949. package/src/workspace/pool/types.ts +0 -276
  950. package/src/workspace/pool/worktree-pool.ts +0 -659
  951. package/src/workspace/recovery/__tests__/auto-resolve-integration.test.ts +0 -127
  952. package/src/workspace/recovery/__tests__/spawn-resolver.test.ts +0 -139
  953. package/src/workspace/recovery/__tests__/strategies.test.ts +0 -145
  954. package/src/workspace/recovery/abandon.ts +0 -51
  955. package/src/workspace/recovery/auto-resolve.ts +0 -119
  956. package/src/workspace/recovery/defer.ts +0 -23
  957. package/src/workspace/recovery/escalate.ts +0 -30
  958. package/src/workspace/recovery/index.ts +0 -58
  959. package/src/workspace/recovery/spawn-resolver.ts +0 -152
  960. package/src/workspace/recovery/types.ts +0 -54
  961. package/src/workspace/strategies/index.ts +0 -18
  962. package/src/workspace/strategies/optimistic.ts +0 -139
  963. package/src/workspace/strategies/queue.ts +0 -81
  964. package/src/workspace/strategies/registry.ts +0 -89
  965. package/src/workspace/strategies/trunk.ts +0 -123
  966. package/src/workspace/strategies/types.ts +0 -145
  967. package/src/workspace/topology/__tests__/yaml-driven.test.ts +0 -345
  968. package/src/workspace/topology/index.ts +0 -18
  969. package/src/workspace/topology/no-workspace.ts +0 -39
  970. package/src/workspace/topology/types.ts +0 -116
  971. package/src/workspace/topology/yaml-driven.ts +0 -316
  972. package/src/workspace/types-v3.ts +0 -162
  973. package/src/workspace/types.ts +0 -541
  974. package/src/workspace/workspace-manager.ts +0 -1577
  975. package/src/workspace/yaml-schema.ts +0 -216
  976. package/test_fixtures/README.md +0 -425
  977. package/test_fixtures/fixtures/behaviors/coordinators.ts +0 -196
  978. package/test_fixtures/fixtures/behaviors/index.ts +0 -62
  979. package/test_fixtures/fixtures/behaviors/integrators.ts +0 -143
  980. package/test_fixtures/fixtures/behaviors/monitors.ts +0 -199
  981. package/test_fixtures/fixtures/behaviors/workers.ts +0 -348
  982. package/test_fixtures/fixtures/index.ts +0 -7
  983. package/test_fixtures/fixtures/projects/index.ts +0 -23
  984. package/test_fixtures/fixtures/projects/project-with-specs.ts +0 -44
  985. package/test_fixtures/fixtures/projects/typescript-project.ts +0 -200
  986. package/test_fixtures/fixtures/repos/index.ts +0 -6
  987. package/test_fixtures/fixtures/repos/temp-repo-factory.ts +0 -299
  988. package/test_fixtures/fixtures/repos/types.ts +0 -174
  989. package/test_fixtures/harness/assertions/harness-assertions.ts +0 -752
  990. package/test_fixtures/harness/assertions/index.ts +0 -8
  991. package/test_fixtures/harness/index.ts +0 -15
  992. package/test_fixtures/harness/simulator/agent-simulator.ts +0 -768
  993. package/test_fixtures/harness/simulator/behavior-executor.ts +0 -580
  994. package/test_fixtures/harness/simulator/index.ts +0 -14
  995. package/test_fixtures/harness/simulator/types.ts +0 -459
  996. package/test_fixtures/harness/test-harness.ts +0 -770
  997. package/test_fixtures/harness/timing/event-stepper.ts +0 -344
  998. package/test_fixtures/harness/timing/index.ts +0 -8
  999. package/tsconfig.json +0 -21
  1000. package/vitest.config.ts +0 -30
  1001. package/vitest.e2e.config.ts +0 -28
  1002. package/vitest.setup.ts +0 -12
@@ -1,2021 +0,0 @@
1
- /**
2
- * AgentManager V2 — Uses AgentStore + InboxAdapter + TasksAdapter
3
- *
4
- * Replaces EventStore/MessageRouter dependencies with the adapter layer.
5
- * Messages flow through agent-inbox, tasks through opentasks,
6
- * agent lifecycle state in AgentStore (minimal SQLite).
7
- *
8
- * @module agent/agent-manager-v2
9
- */
10
-
11
- import { nanoid } from "nanoid";
12
- import {
13
- uniqueNamesGenerator,
14
- adjectives,
15
- animals,
16
- } from "unique-names-generator";
17
- import {
18
- AgentFactory,
19
- type Session,
20
- type AgentHandle,
21
- type ExtendedSessionUpdate,
22
- type PermissionMode,
23
- } from "acp-factory";
24
- import {
25
- AgentStore,
26
- type AgentRecord,
27
- type SessionRecord,
28
- } from "./agent-store.js";
29
- import type {
30
- AgentId,
31
- TaskId,
32
- Timestamp,
33
- Agent,
34
- AgentState,
35
- } from "../store/types/index.js";
36
- import type {
37
- SpawnAgentOptions,
38
- SpawnedAgent,
39
- AgentFilter,
40
- AgentHierarchy,
41
- AgentHierarchyNode,
42
- HierarchyOptions,
43
- ActiveSession,
44
- AgentStopReason,
45
- HeadManagerOptions,
46
- SystemPromptContext,
47
- AgentLifecycleCallback,
48
- AgentLifecycleEvent,
49
- AgentConfig,
50
- ContinueAgentOptions,
51
- MCPServerConfig,
52
- } from "./types.js";
53
- import { AgentManagerError } from "./types.js";
54
- import type { RoleRegistry, Capability } from "../roles/types.js";
55
- import { AGENT_CAPABILITIES } from "../roles/capabilities.js";
56
- import { DefaultRoleRegistry } from "../roles/registry.js";
57
- import { generateSystemPrompt } from "./system-prompt.js";
58
- import type { WorkspaceManager, Workspace } from "../workspace/types.js";
59
- import {
60
- terminateWithChangeConsolidation,
61
- type WorkspaceProvider,
62
- type CascadeAgentManager,
63
- } from "../lifecycle/cascade.js";
64
- import { AgentTokenManager } from "../auth/token.js";
65
- import type { InboxAdapter } from "../adapters/types.js";
66
- import type { TasksAdapter } from "../adapters/types.js";
67
- import type { AgentManager, SpawnInterceptor } from "./agent-manager.js";
68
- import { getPermissionOverlay } from "../dispatch/permission-overlay.js";
69
- import { evaluatePermission } from "../dispatch/permission-evaluator.js";
70
-
71
- // ─────────────────────────────────────────────────────────────────
72
- // Helper
73
- // ─────────────────────────────────────────────────────────────────
74
-
75
- /**
76
- * Derive the canonical Claude Code tool name from a `permission_request`
77
- * `toolCall` object.
78
- *
79
- * Why this is needed: claude-agent-acp's `toolInfoFromToolUse` mangles
80
- * built-in tool names into display titles (e.g., `Read /tmp/x` instead of
81
- * `Read`). MCP tools use their fully-qualified `mcp__server__tool` name as
82
- * the title. The `kind` field (Claude SDK's tool category) is the
83
- * cleanest signal for built-ins, with the input shape disambiguating
84
- * within a category (e.g., `edit` covers Write/Edit/MultiEdit — we look
85
- * at `old_string`/`edits` to pick which).
86
- *
87
- * Pure: no side effects; safe to call from the prompt iterator.
88
- */
89
- function deriveToolName(toolCall: {
90
- title?: string;
91
- kind?: string;
92
- rawInput?: unknown;
93
- } | undefined): string {
94
- const title = toolCall?.title ?? "";
95
- const kind = toolCall?.kind ?? "";
96
- // MCP tools — title is the canonical name.
97
- if (title.startsWith("mcp__")) return title.split(/\s/)[0] ?? "";
98
- const input =
99
- toolCall?.rawInput && typeof toolCall.rawInput === "object"
100
- ? (toolCall.rawInput as Record<string, unknown>)
101
- : {};
102
- switch (kind) {
103
- case "read":
104
- return "Read";
105
- case "execute":
106
- return "Bash";
107
- case "edit":
108
- if ("edits" in input) return "MultiEdit";
109
- if ("old_string" in input) return "Edit";
110
- return "Write";
111
- case "search":
112
- return "path" in input ? "Grep" : "Glob";
113
- case "think":
114
- return "Task";
115
- case "switch_mode":
116
- return "ExitPlanMode";
117
- }
118
- // Fallback: first whitespace-delimited token of the title (Read/Write/
119
- // Edit cases not caught above; built-ins newer than this matrix).
120
- return title.split(/\s/)[0] ?? "";
121
- }
122
-
123
- function getSpawnCapability(childRole: string): Capability {
124
- const baseRole = childRole.split(".")[0];
125
- switch (baseRole) {
126
- case "worker":
127
- return AGENT_CAPABILITIES.SPAWN_WORKER;
128
- case "integrator":
129
- return AGENT_CAPABILITIES.SPAWN_INTEGRATOR;
130
- case "monitor":
131
- return AGENT_CAPABILITIES.SPAWN_MONITOR;
132
- case "coordinator":
133
- return AGENT_CAPABILITIES.SPAWN_CUSTOM;
134
- default:
135
- return `agent.spawn.${childRole}` as Capability;
136
- }
137
- }
138
-
139
- function generateName(): string {
140
- return uniqueNamesGenerator({
141
- dictionaries: [adjectives, animals],
142
- separator: "-",
143
- length: 2,
144
- });
145
- }
146
-
147
- // ─────────────────────────────────────────────────────────────────
148
- // Configuration
149
- // ─────────────────────────────────────────────────────────────────
150
-
151
- /** Minimal health check interface (monitor module removed in V2) */
152
- interface HealthCheckService {
153
- startForCoordinator(agentId: string): void;
154
- stopForCoordinator(agentId: string): void;
155
- }
156
-
157
- export interface AgentManagerV2Config {
158
- defaultPermissionMode?: PermissionMode;
159
- defaultAgentType?: string;
160
- defaultCwd?: string;
161
- workspaceManager?: WorkspaceManager;
162
- roleRegistry?: RoleRegistry;
163
- healthCheckService?: HealthCheckService;
164
- agentTokenManager?: AgentTokenManager;
165
- serverUrl?: string;
166
- serverToken?: string;
167
- /** Control socket path for MCP subprocess lifecycle RPC */
168
- controlSocketPath?: string;
169
- /**
170
- * Default opentasks resource ID hosted on the OpenHive hub. When set,
171
- * spawn paths build `taskRef = { resource_id: <this>, node_id: task_id }`
172
- * automatically from `SpawnAgentOptions.task_id` (for any spawn where
173
- * `resolveTaskRef` returned undefined AND the caller didn't supply an
174
- * explicit `taskRef`).
175
- *
176
- * Operators set this once at swarm registration for the common
177
- * single-graph case. Multi-graph deployments should use `resolveTaskRef`
178
- * instead.
179
- */
180
- taskResourceId?: string;
181
-
182
- /**
183
- * Multi-graph resolver. Called at every spawn; return a `TaskRef` to set
184
- * the binding or `undefined` to fall through to the `taskResourceId`
185
- * default. Explicit `SpawnAgentOptions.taskRef` always wins over both.
186
- *
187
- * Keep cheap — runs per-spawn.
188
- */
189
- resolveTaskRef?: (
190
- spawnOptions: SpawnAgentOptions
191
- ) => import("git-cascade/events").TaskRef | undefined;
192
- }
193
-
194
- // ─────────────────────────────────────────────────────────────────
195
- // Factory
196
- // ─────────────────────────────────────────────────────────────────
197
-
198
- export function createAgentManagerV2(
199
- agentStore: AgentStore,
200
- inboxAdapter: InboxAdapter,
201
- tasksAdapter: TasksAdapter,
202
- config: AgentManagerV2Config = {}
203
- ): AgentManager {
204
- const {
205
- defaultPermissionMode = "auto-approve",
206
- defaultAgentType = "claude-code",
207
- defaultCwd = process.cwd(),
208
- workspaceManager,
209
- roleRegistry = new DefaultRoleRegistry(),
210
- healthCheckService,
211
- serverUrl,
212
- serverToken,
213
- agentTokenManager,
214
- controlSocketPath,
215
- taskResourceId,
216
- resolveTaskRef,
217
- } = config;
218
-
219
- // In-memory state
220
- const activeSessions = new Map<AgentId, ActiveSession>();
221
- const agentWorkspaces = new Map<AgentId, Workspace>();
222
- const lifecycleListeners = new Set<AgentLifecycleCallback>();
223
- let spawnInterceptor: SpawnInterceptor | null = null;
224
- let isShuttingDown = false;
225
- let mapServerUrl: string | undefined;
226
-
227
- // Swarmkit integration configs (set via late-binding setters from boot-v2)
228
- let minimemConfig: { enabled: boolean; dir?: string; provider?: string; global?: boolean } | undefined;
229
- let skilltreeConfig: { enabled: boolean; basePath?: string; defaultProfile?: string } | undefined;
230
- let sessionlogConfig: { enabled: boolean; sync?: string } | undefined;
231
- // Compiled skill loadouts per role (populated by team runtime)
232
- const skillLoadouts = new Map<string, string>();
233
- // MAP sidecar reference for trajectory reporting (set via setSidecar)
234
- let sidecarRef: { connected: boolean; reportCheckpoint(cp: any): Promise<any> } | null = null;
235
-
236
- // TopologyPolicy for workspace allocation (Phase 3+); set via setTopologyPolicy.
237
- // When null, createWorkspaceForRole falls back to legacy role-name dispatch.
238
- let topologyPolicy:
239
- | import('../workspace/topology/types.js').TopologyPolicy
240
- | null = null;
241
-
242
- // ── Helpers ──────────────────────────────────────────────────
243
-
244
- function notifyLifecycle(event: AgentLifecycleEvent): void {
245
- for (const listener of lifecycleListeners) {
246
- try {
247
- listener(event);
248
- } catch {
249
- // Ignore listener errors
250
- }
251
- }
252
- }
253
-
254
- function agentRecordToAgent(record: AgentRecord): Agent {
255
- const session = agentStore.getSession(record.id as AgentId);
256
- return {
257
- id: record.id,
258
- name: record.name,
259
- session_id: session?.session_id ?? "",
260
- parent: record.parent_id,
261
- lineage: record.lineage,
262
- state: record.state,
263
- stop_reason: record.stop_reason as Agent["stop_reason"],
264
- task: record.task,
265
- task_id: record.task_id,
266
- role: record.role,
267
- team_instance: record.team,
268
- config: (record.config as Agent["config"]) ?? {},
269
- cwd: record.cwd,
270
- plan: [],
271
- metadata: record.metadata,
272
- created_at: record.created_at,
273
- started_at: record.started_at,
274
- stopped_at: record.stopped_at,
275
- last_activity_at: record.last_activity_at,
276
- };
277
- }
278
-
279
- function buildMcpServerConfig(opts: {
280
- agentId: string;
281
- parentId: string;
282
- taskId: string;
283
- cwd: string;
284
- permissionMode: string;
285
- lineage?: string[];
286
- sessionId?: string;
287
- streamId?: string;
288
- }): MCPServerConfig {
289
- const env: Record<string, string> = {
290
- MACRO_AGENT_ID: opts.agentId,
291
- MACRO_PARENT_ID: opts.parentId,
292
- MACRO_TASK_ID: opts.taskId,
293
- MACRO_AGENT_CWD: opts.cwd,
294
- MACRO_PERMISSION_MODE: opts.permissionMode,
295
- MACRO_STREAM_ID: opts.streamId ?? "",
296
- // Point to inbox socket for agent-inbox MCP tools
297
- INBOX_SOCKET_PATH: inboxAdapter.socketPath,
298
- // Control socket for lifecycle RPC (spawn, terminate, etc.)
299
- MACRO_CONTROL_SOCKET_PATH: controlSocketPath ?? "",
300
- // Base directory for AgentStore + inbox in MCP subprocess
301
- MACRO_BASE_DIR: controlSocketPath
302
- ? controlSocketPath.replace(/\/control\.sock$/, "")
303
- : "",
304
- // opentasks client auto-discovers its socket
305
- };
306
-
307
- if (serverUrl) {
308
- env.MACRO_SERVER_URL = serverUrl;
309
- env.MACRO_AGENT_LINEAGE = JSON.stringify(opts.lineage ?? []);
310
- env.MACRO_SESSION_ID = opts.sessionId ?? "";
311
- if (serverToken) env.MACRO_SERVER_TOKEN = serverToken;
312
- if (agentTokenManager) {
313
- env.MACRO_AGENT_TOKEN = agentTokenManager.createToken(opts.agentId);
314
- }
315
- }
316
-
317
- // Use node with local dist path to ensure we run V2 MCP server,
318
- // not a globally installed V1 version.
319
- const mcpEntryPoint = new URL("../../dist/cli/mcp.js", import.meta.url).pathname;
320
-
321
- return {
322
- name: "macro-agent",
323
- command: "node",
324
- args: [mcpEntryPoint],
325
- env,
326
- };
327
- }
328
-
329
- // ── Workspace Helper ─────────────────────────────────────────
330
-
331
- /**
332
- * Execute a TopologyPolicy decision against the WorkspaceManager.
333
- *
334
- * Translates declarative `WorkspaceDecision` into concrete workspace
335
- * allocations. Returns a `Workspace` compatible with the legacy shape
336
- * so the rest of AgentManagerV2 doesn't need to change.
337
- */
338
- async function executeWorkspaceDecision(
339
- agentId: AgentId,
340
- decision: import('../workspace/topology/types.js').WorkspaceDecision,
341
- role?: string,
342
- spawnOptions?: SpawnAgentOptions
343
- ): Promise<Workspace | undefined> {
344
- if (!workspaceManager) return undefined;
345
-
346
- switch (decision.kind) {
347
- case 'none':
348
- case 'share-parent-cwd':
349
- return undefined;
350
-
351
- case 'share-with-agent': {
352
- const worktree = workspaceManager.allocateWorktree({
353
- agentId,
354
- sharedWithAgent: decision.agentId,
355
- });
356
- return {
357
- agentId,
358
- path: worktree.path,
359
- branch: worktree.currentStream
360
- ? `stream/${worktree.currentStream}`
361
- : 'unknown',
362
- streamId: worktree.currentStream ?? '',
363
- role: 'v3', // V3 path — bypass legacy worker task/merge-queue flows
364
- createdAt: worktree.createdAt,
365
- };
366
- }
367
-
368
- case 'attach-to-stream': {
369
- // Record even if no worktree — the topology needs the stream↔role
370
- // mapping for event-driven features like on_parent_advanced.
371
- const attachPolicy = topologyPolicy as unknown as {
372
- recordAgentStream?: (a: string, s: string, role?: string) => void;
373
- };
374
- attachPolicy.recordAgentStream?.(agentId, decision.streamId, role);
375
-
376
- if (!decision.allocateWorktree) {
377
- return undefined;
378
- }
379
- const worktree = workspaceManager.allocateWorktree({
380
- agentId,
381
- streamId: decision.streamId,
382
- });
383
- return {
384
- agentId,
385
- path: worktree.path,
386
- branch: `stream/${decision.streamId}`,
387
- streamId: decision.streamId,
388
- role: 'v3', // V3 path — attach-to-team-root
389
- createdAt: worktree.createdAt,
390
- };
391
- }
392
-
393
- case 'new-stream': {
394
- // If the spawning agent has a taskRef and the streamSpec doesn't
395
- // already carry one, weave it into metadata so the resulting stream
396
- // binds to the OpenTasks node. Explicit streamSpec.metadata.task_ref
397
- // wins.
398
- const taskRef = spawnOptions?.taskRef;
399
- const existingMeta = decision.streamSpec.metadata as
400
- | Record<string, unknown>
401
- | undefined;
402
- const streamSpec = taskRef && !existingMeta?.task_ref
403
- ? {
404
- ...decision.streamSpec,
405
- metadata: { ...(existingMeta ?? {}), task_ref: taskRef },
406
- }
407
- : decision.streamSpec;
408
- const streamId = workspaceManager.createStreamV3(streamSpec);
409
- // Record the mapping in the topology if it supports it (for share-with lookup).
410
- const policy = topologyPolicy as unknown as {
411
- recordAgentStream?: (a: string, s: string, role?: string) => void;
412
- };
413
- policy.recordAgentStream?.(agentId, streamId, role);
414
-
415
- if (!decision.allocateWorktree) {
416
- return undefined;
417
- }
418
- const worktree = workspaceManager.allocateWorktree({
419
- agentId,
420
- streamId,
421
- });
422
- return {
423
- agentId,
424
- path: worktree.path,
425
- branch: `stream/${streamId}`,
426
- streamId,
427
- role: 'v3', // V3 path — new-stream
428
- createdAt: worktree.createdAt,
429
- };
430
- }
431
- }
432
- }
433
-
434
- async function createWorkspaceForRole(
435
- agentId: AgentId,
436
- role: string,
437
- options: SpawnAgentOptions
438
- ): Promise<Workspace | undefined> {
439
- if (!workspaceManager) return undefined;
440
-
441
- // V3 path — TopologyPolicy-driven. Set by boot-v2 when team YAML has
442
- // `macro_agent.workspace`. When set, this takes precedence over the legacy
443
- // capability/role-name dispatch below.
444
- if (topologyPolicy) {
445
- const decision = await topologyPolicy.onAgentSpawn({
446
- agentId,
447
- role,
448
- parentAgentId: options.parent ?? undefined,
449
- parentStreamId: options.streamId,
450
- teamStreamId: (() => {
451
- const stream = (
452
- topologyPolicy as { getAgentStream?: (a: AgentId) => string | null }
453
- ).getAgentStream?.(agentId);
454
- return stream ?? undefined;
455
- })(),
456
- workspaceManager,
457
- getAgentByRole: (r: string) => {
458
- for (const [aid, ws] of agentWorkspaces) {
459
- const rec = agentStore.getAgent(aid);
460
- if (rec?.role === r) return aid;
461
- }
462
- return null;
463
- },
464
- });
465
- return executeWorkspaceDecision(agentId, decision, role, options);
466
- }
467
-
468
- // Capability-based dispatch for programmatic callers that don't use
469
- // team YAML. This is the supported path for libraries that construct
470
- // WorkspaceManager + GitCascadeAdapter directly and spawn agents with
471
- // explicit `capabilities` + `streamId` arguments. It coexists with the
472
- // V3 topology path above.
473
- return capabilityBasedDispatch(agentId, options, workspaceManager);
474
- }
475
-
476
- /**
477
- * Capability-based workspace allocation for programmatic callers.
478
- *
479
- * Matches on `workspace.stream` / `workspace.integrate` / `workspace.worktree`
480
- * capabilities + corresponding streamId/streamConfig args. Delegates to the
481
- * role-shaped WorkspaceManager methods (createWorkerWorkspace,
482
- * createIntegratorWorkspace, createCoordinatorWorkspace).
483
- *
484
- * Not used by team-YAML-driven teams — those go through TopologyPolicy above.
485
- */
486
- async function capabilityBasedDispatch(
487
- agentId: AgentId,
488
- options: SpawnAgentOptions,
489
- ws: WorkspaceManager
490
- ): Promise<Workspace | undefined> {
491
- const capabilities = options.capabilities ?? [];
492
- const streamId = options.streamId;
493
- // Merge taskRef (if set at spawn time) into streamConfig.metadata so that
494
- // adapter.createStream → x-cascade/stream.opened carries the binding to
495
- // OpenTasks. Explicit streamConfig.metadata.task_ref wins if already set.
496
- const streamConfig = options.streamConfig
497
- ? options.taskRef &&
498
- !(options.streamConfig.metadata &&
499
- (options.streamConfig.metadata as Record<string, unknown>).task_ref)
500
- ? {
501
- ...options.streamConfig,
502
- metadata: {
503
- ...(options.streamConfig.metadata ?? {}),
504
- task_ref: options.taskRef,
505
- },
506
- }
507
- : options.streamConfig
508
- : undefined;
509
- const gitCascadeTaskId = options.gitCascadeTaskId;
510
-
511
- if (capabilities.includes("workspace.stream") && streamConfig) {
512
- const newStreamId = ws.createIntegrationStream(agentId, streamConfig);
513
- return ws.createCoordinatorWorkspace(agentId, newStreamId);
514
- }
515
-
516
- if (capabilities.includes("workspace.integrate") && streamId) {
517
- return ws.createIntegratorWorkspace(agentId, streamId);
518
- }
519
-
520
- if (capabilities.includes("workspace.worktree") && streamId) {
521
- const taskId = gitCascadeTaskId ?? agentId;
522
- return ws.createWorkerWorkspace(agentId, taskId, streamId);
523
- }
524
-
525
- // No matching capability — agent inherits parent cwd (no workspace)
526
- return undefined;
527
- }
528
-
529
- // ── Core Lifecycle ───────────────────────────────────────────
530
-
531
- async function spawn(rawOptions: SpawnAgentOptions): Promise<SpawnedAgent> {
532
- if (isShuttingDown) {
533
- throw new AgentManagerError(
534
- "Cannot spawn agent during shutdown",
535
- "SHUTDOWN_IN_PROGRESS"
536
- );
537
- }
538
-
539
- // Apply spawn interceptor (set by TeamRuntime)
540
- const interceptedOptions = spawnInterceptor
541
- ? await spawnInterceptor(rawOptions)
542
- : rawOptions;
543
-
544
- // Resolve taskRef with three-level precedence:
545
- // 1. Explicit `options.taskRef` (caller knows exactly what graph).
546
- // 2. `resolveTaskRef(opts)` (multi-graph deployments decide per spawn).
547
- // 3. `taskResourceId` + `options.task_id` (single-graph default).
548
- // If none resolves, spawn proceeds with no taskRef — cascade events
549
- // land without a task binding (hub back-fills from first commit that
550
- // carries one, if any).
551
- let resolvedTaskRef = interceptedOptions.taskRef;
552
- if (!resolvedTaskRef && resolveTaskRef) {
553
- try {
554
- resolvedTaskRef = resolveTaskRef(interceptedOptions);
555
- } catch (err) {
556
- // Resolver failures must not block spawn. Log + fall through.
557
- // eslint-disable-next-line no-console
558
- console.warn(
559
- "[agent-manager-v2] resolveTaskRef threw; falling back to taskResourceId default:",
560
- err instanceof Error ? err.message : err
561
- );
562
- }
563
- }
564
- if (!resolvedTaskRef && taskResourceId && interceptedOptions.task_id) {
565
- resolvedTaskRef = {
566
- resource_id: taskResourceId,
567
- node_id: String(interceptedOptions.task_id),
568
- };
569
- }
570
- const options = resolvedTaskRef === interceptedOptions.taskRef
571
- ? interceptedOptions
572
- : { ...interceptedOptions, taskRef: resolvedTaskRef };
573
-
574
- const {
575
- task,
576
- task_id,
577
- parent,
578
- cwd = defaultCwd,
579
- permissionMode = defaultPermissionMode,
580
- askForAllTools = false,
581
- subscribeParent = true,
582
- topics = [],
583
- config: agentConfig,
584
- agentType = defaultAgentType,
585
- customPrompt,
586
- interactionPatterns,
587
- role,
588
- team_instance,
589
- capabilities,
590
- } = options;
591
-
592
- // Generate IDs
593
- const agentId = `agent_${nanoid(12)}` as AgentId;
594
- const taskId = (task_id ?? `task_${nanoid(12)}`) as TaskId;
595
- const sessionId = `session_${nanoid(12)}`;
596
- const name = generateName();
597
-
598
- // Validate parent exists
599
- if (parent) {
600
- const parentRecord = agentStore.getAgent(parent);
601
- if (!parentRecord) {
602
- throw new AgentManagerError(
603
- `Parent agent ${parent} not found`,
604
- "AGENT_NOT_FOUND",
605
- parent
606
- );
607
- }
608
-
609
- // Check spawn capability
610
- if (role) {
611
- const requiredCap = getSpawnCapability(role);
612
- const parentRole = parentRecord.role;
613
- if (
614
- !roleRegistry.hasCapability(parentRole, requiredCap) &&
615
- !roleRegistry.hasCapability(parentRole, AGENT_CAPABILITIES.SPAWN_CUSTOM)
616
- ) {
617
- throw new AgentManagerError(
618
- `Parent ${parent} (role: ${parentRole}) lacks capability ${requiredCap}`,
619
- "CAPABILITY_DENIED",
620
- parent
621
- );
622
- }
623
- }
624
- }
625
-
626
- // Compute lineage
627
- const lineage: AgentId[] = [];
628
- if (parent) {
629
- const parentRecord = agentStore.getAgent(parent);
630
- if (parentRecord) {
631
- lineage.push(...parentRecord.lineage, parent);
632
- }
633
- }
634
-
635
- // Generate system prompt
636
- const resolvedRole = role
637
- ? roleRegistry.resolveRole(role)
638
- : undefined;
639
- const systemPromptContext: SystemPromptContext = {
640
- agentId,
641
- task,
642
- taskId,
643
- parentId: parent ?? null,
644
- isHeadManager: !parent,
645
- lineage,
646
- role,
647
- };
648
- let systemPrompt = generateSystemPrompt(systemPromptContext);
649
- if (customPrompt) {
650
- systemPrompt += `\n\n## Role Instructions\n\n${customPrompt}`;
651
- } else if (resolvedRole?.systemPrompt) {
652
- systemPrompt += `\n\n## Role Instructions\n\n${resolvedRole.systemPrompt}`;
653
- }
654
- if (interactionPatterns?.length) {
655
- systemPrompt += `\n\n${interactionPatterns.join("\n\n")}`;
656
- }
657
-
658
- // Persist agent in store. Stash taskRef in metadata so done()'s
659
- // lifecycle context can read it without separate plumbing — this is the
660
- // path that makes per-commit task_ref binding work end-to-end.
661
- const now = Date.now() as Timestamp;
662
- const agentRecord: AgentRecord = {
663
- id: agentId,
664
- name,
665
- role: role ?? (parent ? "worker" : "coordinator"),
666
- state: "running",
667
- parent_id: parent ?? null,
668
- lineage,
669
- team: team_instance,
670
- scope: team_instance ?? "default",
671
- task: task ?? "",
672
- task_id: taskId,
673
- cwd,
674
- capabilities: capabilities ?? resolvedRole?.capabilities ?? [],
675
- created_at: now,
676
- started_at: now,
677
- config: agentConfig as Record<string, unknown>,
678
- metadata: {
679
- ...(options.taskRef ? { task_ref: options.taskRef } : {}),
680
- // Persist isolatedSettings so resume() applies the same agentMeta
681
- // policy without needing the original SpawnAgentOptions.
682
- ...(options.isolatedSettings ? { isolatedSettings: true } : {}),
683
- },
684
- };
685
- agentStore.putAgent(agentRecord);
686
-
687
- let handle: AgentHandle | undefined;
688
- let workspace: Workspace | undefined;
689
-
690
- try {
691
- // Spawn process via acp-factory
692
- const env: Record<string, string> = {
693
- ...agentConfig?.env,
694
- };
695
-
696
- // Configure cc-swarm to connect to macro-agent's local MAP server.
697
- // These env vars are read by cc-swarm hooks in the Claude Code process
698
- // (not the MCP subprocess), so they must be in the agent process env.
699
- if (mapServerUrl) {
700
- env.SWARM_MAP_SERVER = mapServerUrl;
701
- env.SWARM_MAP_ENABLED = "true";
702
- env.SWARM_MAP_SCOPE = `swarm:${agentId}`;
703
- env.SWARM_SESSIONLOG_ENABLED = "true";
704
- env.SWARM_SESSIONLOG_SYNC = "metrics";
705
- }
706
-
707
- handle = await AgentFactory.spawn(agentType, {
708
- permissionMode,
709
- env,
710
- });
711
-
712
- // Create workspace if applicable
713
- workspace = await createWorkspaceForRole(agentId, role ?? "", options);
714
- if (workspace) {
715
- agentWorkspaces.set(agentId, workspace);
716
-
717
- // Create and claim git-cascade task for workers
718
- if (
719
- workspace.role === "worker" &&
720
- workspace.streamId &&
721
- workspaceManager
722
- ) {
723
- const dpTaskId = options.gitCascadeTaskId ?? agentId;
724
- workspaceManager.createTask(workspace.streamId, {
725
- title: task ?? `Task for ${agentId}`,
726
- });
727
- workspaceManager.claimTask(dpTaskId, agentId, workspace.path);
728
- }
729
-
730
- agentStore.updateAgent(agentId, {
731
- cwd: workspace.path,
732
- workspace_path: workspace.path,
733
- workspace_stream_id: workspace.streamId,
734
- });
735
- }
736
-
737
- const effectiveCwd = workspace?.path ?? cwd;
738
-
739
- // Build MCP server config
740
- const macroAgentMcp = buildMcpServerConfig({
741
- agentId,
742
- parentId: parent ?? "",
743
- taskId,
744
- cwd: effectiveCwd,
745
- permissionMode,
746
- lineage,
747
- sessionId,
748
- streamId: workspace?.streamId,
749
- });
750
-
751
- // Convert to acp-factory format
752
- const mcpServers = [
753
- {
754
- name: macroAgentMcp.name,
755
- command: macroAgentMcp.command,
756
- args: macroAgentMcp.args ?? [],
757
- env: Object.entries(macroAgentMcp.env ?? {}).map(([k, v]) => ({
758
- name: k,
759
- value: v,
760
- })),
761
- },
762
- ...(agentConfig?.mcpServers?.map((s) => ({
763
- name: s.name,
764
- command: s.command,
765
- args: s.args ?? [],
766
- env: Object.entries(s.env ?? {}).map(([k, v]) => ({
767
- name: k,
768
- value: v,
769
- })),
770
- })) ?? []),
771
- ];
772
-
773
- // Always-on subsystem MCP servers (the "trinity"). The macro-agent
774
- // architecture docs describe agent-inbox + opentasks as separate MCP
775
- // servers available to spawned workers, but until this entry block
776
- // existed they were only reachable when host-level Claude plugins
777
- // happened to have wired them. That left mail-inbound workers
778
- // (`parent: null` + `isolatedSettings: true`) without inbox/tasks
779
- // tools — see openhive-2 docs/LOADOUTS_DESIGN.md "Loadout-provided
780
- // MCP servers" live finding 2026-05-03.
781
- //
782
- // Registering them here makes them per-spawn defaults independent
783
- // of host configuration. Caller-supplied `agentConfig.mcpServers`
784
- // remains additive (Option C / "hybrid"): the trinity is always
785
- // there, callers can layer more on top.
786
-
787
- // agent-inbox — exposes send_message, check_inbox, read_thread,
788
- // list_agents via the InboxMcpProxy stdio bridge.
789
- if (inboxAdapter.socketPath) {
790
- const inboxProxyEntry = new URL(
791
- "../../dist/cli/inbox-mcp-proxy.js",
792
- import.meta.url,
793
- ).pathname;
794
- mcpServers.push({
795
- name: "agent-inbox",
796
- command: "node",
797
- args: [inboxProxyEntry],
798
- env: [
799
- { name: "INBOX_SOCKET_PATH", value: inboxAdapter.socketPath },
800
- { name: "MACRO_AGENT_ID", value: agentId },
801
- ],
802
- } as any);
803
- }
804
-
805
- // opentasks — exposes task, link, annotate, query via the
806
- // `opentasks mcp` CLI subcommand. The package's dist/mcp/stdio.js
807
- // is an exports-only module (no auto-start); the CLI's `mcp`
808
- // subcommand is what actually wires StdioServerTransport. Conditional
809
- // on tasksAdapter.connected — when the daemon isn't running, skip
810
- // rather than mount a server that would fail at every tool call.
811
- if (tasksAdapter.connected) {
812
- const opentasksCliEntry = new URL(
813
- "opentasks/dist/cli.js",
814
- import.meta.url,
815
- ).pathname;
816
- mcpServers.push({
817
- name: "opentasks",
818
- command: "node",
819
- args: [opentasksCliEntry, "mcp"],
820
- env: [],
821
- } as any);
822
- }
823
-
824
- // Register minimem MCP server (agent-type independent — works for any MCP-capable agent)
825
- if (minimemConfig?.enabled) {
826
- mcpServers.push({
827
- name: "minimem",
828
- command: "minimem",
829
- args: [
830
- "mcp",
831
- "--dir", minimemConfig.dir ?? ".swarm/minimem/",
832
- "--provider", minimemConfig.provider ?? "auto",
833
- ...(minimemConfig.global ? ["--global"] : []),
834
- ],
835
- env: [],
836
- } as any);
837
- }
838
-
839
- // Build agentMeta. Two layers:
840
- //
841
- // 1. `settingSources: []` — when the caller requests isolated
842
- // settings (mail-inbound dispatch workers via
843
- // SpawnAgentOptions.isolatedSettings), strip user/project/local
844
- // setting sources so the worker doesn't load the host's
845
- // claude-code-swarm / oh-my-claudecode / etc plugin MCP servers
846
- // — those plugins assume host-shaped environment (sockets,
847
- // daemons) and hang at session/new MCP-init when missing.
848
- // Interactive `multiagent` callers leave this false so their
849
- // installed plugins load normally.
850
- //
851
- // 2. `settings.permissions` — when the caller passes
852
- // SpawnAgentOptions.permissions (e.g., from a materialized
853
- // loadout), wire the rules inline via the Claude Agent SDK's
854
- // session-level settings pass-through. Verified live: `deny`
855
- // wins even over `permissionMode: "auto-approve"`. Inline
856
- // wiring avoids file collisions when concurrent workers share
857
- // a CWD (no `.claude/settings.json` written to disk).
858
- //
859
- // SDK contract pinned by the boundary test in
860
- // `src/agent/__tests__/agent-manager-v2.permissions.test.ts` —
861
- // it captures the literal `agentMeta` argument passed to
862
- // `handle.createSession` and asserts both `settingSources: []`
863
- // AND `settings.permissions` are present together (the
864
- // interaction between filesystem-stripping and inline
865
- // reconciliation that the SDK's docs don't fully spell out).
866
- // If a future SDK version changes how `settings` reconciles
867
- // with empty `settingSources`, that test will catch it.
868
- //
869
- // `ask` rules collapse based on `fullAutonomous`:
870
- // - fullAutonomous: true → ask → allow (autonomous worker
871
- // opts to proceed when there's no human to answer)
872
- // - fullAutonomous: false → ask → deny (safe default;
873
- // autonomous workers shouldn't make judgment calls)
874
- const claudeCodeOptions: Record<string, any> = {};
875
- if (options.isolatedSettings || permissionMode === "interactive") {
876
- claudeCodeOptions.settingSources = [];
877
- }
878
- if (options.permissions) {
879
- const { allow = [], deny = [], ask = [] } = options.permissions;
880
- const finalAllow = options.fullAutonomous ? [...allow, ...ask] : [...allow];
881
- const finalDeny = options.fullAutonomous ? [...deny] : [...deny, ...ask];
882
- claudeCodeOptions.settings = {
883
- permissions: {
884
- ...(finalAllow.length ? { allow: finalAllow } : {}),
885
- ...(finalDeny.length ? { deny: finalDeny } : {}),
886
- },
887
- };
888
- }
889
- // P3 spike: when an agent should funnel every tool call through the host
890
- // (so the prompt-iterator handler can apply runtime overlays), set
891
- // `ask: ['*']` on settings.permissions. The SDK then consults canUseTool
892
- // for every tool, which emits `permission_request` session updates.
893
- // Used for dispatch-target agents (mail+reuse, ACP+reuse) that need
894
- // dynamic enforcement; chat agents and parented children stay on
895
- // their session's static rules.
896
- if (options.askForAllTools) {
897
- const existingPerms =
898
- claudeCodeOptions.settings?.permissions ?? {};
899
- claudeCodeOptions.settings = {
900
- ...claudeCodeOptions.settings,
901
- permissions: {
902
- ...existingPerms,
903
- ask: ["*"],
904
- },
905
- };
906
- }
907
-
908
- // 3. Runtime permission overlay enforcement lives in the prompt
909
- // iterator (see `prompt()` below), NOT here at spawn time.
910
- //
911
- // Background: an earlier design installed a Claude SDK PreToolUse
912
- // hook here that closed over the per-process permission-overlay
913
- // registry. That mechanism was verified broken: function callbacks
914
- // inside arrays don't survive JSON.stringify across the
915
- // macro-agent → claude-agent-acp stdio JSON-RPC boundary, so the
916
- // hook arrived as `null` at the SDK and silently no-op'd.
917
- //
918
- // The current design uses ACP's `permission_request` session
919
- // update path instead. When an agent is spawned with
920
- // `askForAllTools: true` + `permissionMode: 'interactive'`, the
921
- // SDK consults `canUseTool` on every tool call, claude-agent-acp
922
- // converts that into a `client.requestPermission` call, and
923
- // acp-factory emits it as a `permission_request` session update.
924
- // The prompt iterator below intercepts those updates, evaluates
925
- // against the overlay, and responds via `respondPermission`.
926
- // See `docs/PERMISSION_OVERLAY_ACP_DESIGN.md` for the full design.
927
-
928
- const agentMeta = Object.keys(claudeCodeOptions).length > 0
929
- ? { claudeCode: { options: claudeCodeOptions } }
930
- : undefined;
931
-
932
- // Build capabilities context + skill-tree loadout for system prompt
933
- // Matches cc-swarm's context injection pattern (role-aware, tool-specific)
934
- let contextSuffix = "";
935
- try {
936
- const { buildCapabilitiesContext } = await import("../integrations/context-builder.js");
937
- contextSuffix = buildCapabilitiesContext({
938
- role: parent ? (role ?? "worker") : null, // null = orchestrator, string = spawned agent
939
- teamName: team_instance ?? undefined,
940
- minimem: minimemConfig
941
- ? { enabled: minimemConfig.enabled, status: "ready" }
942
- : undefined,
943
- skilltree: skilltreeConfig
944
- ? { enabled: skilltreeConfig.enabled, status: "ready", profile: skilltreeConfig.defaultProfile }
945
- : undefined,
946
- sessionlog: sessionlogConfig
947
- ? { enabled: sessionlogConfig.enabled, sync: sessionlogConfig.sync }
948
- : undefined,
949
- mesh: mapServerUrl ? { enabled: false } : undefined, // mesh state from config
950
- map: mapServerUrl
951
- ? { enabled: true, scope: `swarm:${agentId}`, status: "connected" }
952
- : undefined,
953
- opentasks: tasksAdapter.connected
954
- ? { enabled: true, status: "connected" }
955
- : undefined,
956
- inbox: { enabled: true },
957
- });
958
- } catch { /* context builder not available */ }
959
-
960
- // Inject skill-tree loadout if available for this role
961
- const roleLoadout = role ? skillLoadouts.get(role) : undefined;
962
- if (roleLoadout) {
963
- contextSuffix += `\n\n## Skills\n\n${roleLoadout}`;
964
- }
965
-
966
- // Merge context into system prompt
967
- const enrichedPrompt = contextSuffix
968
- ? `${systemPrompt ?? ""}\n\n${contextSuffix}`.trim()
969
- : systemPrompt;
970
-
971
- // Create session
972
- const session = await handle.createSession(effectiveCwd, {
973
- mcpServers,
974
- systemPrompt: enrichedPrompt ?? systemPrompt,
975
- ...(agentMeta && { agentMeta }),
976
- } as any);
977
-
978
- // Store session record
979
- agentStore.putSession({
980
- agent_id: agentId,
981
- session_id: sessionId,
982
- provider_session_id: session.id,
983
- created_at: now,
984
- });
985
-
986
- // Update agent with provider session ID. Merge with existing metadata
987
- // so fields set at spawn time (e.g. task_ref) aren't clobbered.
988
- const existingMeta = agentStore.getAgent(agentId)?.metadata ?? {};
989
- agentStore.updateAgent(agentId, {
990
- metadata: { ...existingMeta, provider_session_id: session.id },
991
- });
992
-
993
- // Register agent in inbox
994
- await inboxAdapter.registerAgent(agentId, {
995
- name,
996
- role: role ?? "worker",
997
- scope: team_instance ?? "default",
998
- });
999
-
1000
- // Track active session
1001
- const activeSession: ActiveSession = {
1002
- agentId,
1003
- handle,
1004
- session,
1005
- createdAt: now,
1006
- isPrompting: false,
1007
- };
1008
- activeSessions.set(agentId, activeSession);
1009
-
1010
- // Notify lifecycle
1011
- const agent = agentRecordToAgent(agentStore.getAgent(agentId)!);
1012
- notifyLifecycle({ type: "spawned", agent });
1013
- notifyLifecycle({ type: "started", agent });
1014
-
1015
- // Start health monitoring for coordinators
1016
- if (healthCheckService && role === "coordinator") {
1017
- healthCheckService.startForCoordinator(agentId);
1018
- }
1019
-
1020
- return {
1021
- id: agentId,
1022
- session_id: sessionId,
1023
- agent,
1024
- session,
1025
- workspace,
1026
- streamId: workspace?.streamId,
1027
- };
1028
- } catch (err) {
1029
- // Cleanup on failure
1030
- if (handle) {
1031
- try {
1032
- await handle.close();
1033
- } catch {
1034
- /* ignore */
1035
- }
1036
- }
1037
- agentStore.updateAgent(agentId, {
1038
- state: "failed",
1039
- stop_reason: "failed",
1040
- stopped_at: Date.now(),
1041
- });
1042
- throw err;
1043
- }
1044
- }
1045
-
1046
- async function terminate(
1047
- agentId: AgentId,
1048
- reason: AgentStopReason
1049
- ): Promise<void> {
1050
- const record = agentStore.getAgent(agentId);
1051
- if (!record) {
1052
- throw new AgentManagerError(
1053
- `Agent ${agentId} not found`,
1054
- "AGENT_NOT_FOUND",
1055
- agentId
1056
- );
1057
- }
1058
-
1059
- // Close active session
1060
- const activeSession = activeSessions.get(agentId);
1061
- if (activeSession) {
1062
- try {
1063
- await activeSession.handle.close();
1064
- } catch {
1065
- /* ignore close errors */
1066
- }
1067
- activeSessions.delete(agentId);
1068
- }
1069
-
1070
- // Stop health monitoring
1071
- if (healthCheckService && record.role === "coordinator") {
1072
- healthCheckService.stopForCoordinator(agentId);
1073
- }
1074
-
1075
- // Land the worker's work if completed with a workspace.
1076
- //
1077
- // V3 path (preferred): look up the role's YAML landing strategy via
1078
- // TopologyPolicy.getRoleConfig and dispatch through
1079
- // WorkspaceManager.land(). This fires cascade events (stream.merged or
1080
- // queue.added) so the hub sees the work. Landing = 'none' short-circuits.
1081
- //
1082
- // Legacy fallback: if no TopologyPolicy is wired or it can't resolve a
1083
- // landing for this role, submit to the legacy MergeQueue as before.
1084
- // Keeps pre-V3 programmatic callers + tests that bypass YAML working.
1085
- if (
1086
- workspaceManager &&
1087
- agentWorkspaces.has(agentId) &&
1088
- reason === "completed"
1089
- ) {
1090
- const ws = agentWorkspaces.get(agentId)!;
1091
- if (ws.role === "worker" && ws.streamId) {
1092
- const roleConfig = topologyPolicy?.getRoleConfig?.(record.role);
1093
- const yamlLandingName = roleConfig?.landing;
1094
- const usingV3Landing =
1095
- typeof yamlLandingName === "string" && yamlLandingName.length > 0;
1096
-
1097
- if (usingV3Landing) {
1098
- try {
1099
- const taskRef = (record.metadata as Record<string, unknown> | undefined)
1100
- ?.task_ref as { resource_id: string; node_id: string } | undefined;
1101
- await workspaceManager.land({
1102
- agentId,
1103
- streamId: ws.streamId,
1104
- sourceWorktree: ws.path,
1105
- strategyName: yamlLandingName,
1106
- strategyConfig: roleConfig?.landing_config,
1107
- taskRef,
1108
- // Dispatcher overwrites this with `this`; placeholder keeps the
1109
- // type satisfied without a cast.
1110
- workspaceManager,
1111
- });
1112
- } catch {
1113
- // Non-fatal landing failure — agent still terminates; conflicts
1114
- // and strategy errors surface via WorkspaceEvent emission and
1115
- // the strategy's own logs.
1116
- }
1117
- } else {
1118
- try {
1119
- const mergeQueue = workspaceManager.getMergeQueue();
1120
- if (mergeQueue) {
1121
- mergeQueue.submit({
1122
- streamId: ws.streamId,
1123
- workerBranch: ws.branch,
1124
- taskId: record.task_id ?? agentId,
1125
- workerAgentId: agentId,
1126
- });
1127
- }
1128
- } catch {
1129
- // Non-fatal merge queue submission failure
1130
- }
1131
- }
1132
- }
1133
- }
1134
-
1135
- // Deallocate workspace
1136
- if (workspaceManager && agentWorkspaces.has(agentId)) {
1137
- try {
1138
- workspaceManager.deallocateWorkspace(agentId);
1139
- } catch {
1140
- /* ignore */
1141
- }
1142
- agentWorkspaces.delete(agentId);
1143
- }
1144
-
1145
- // Revoke auth token
1146
- if (agentTokenManager) {
1147
- agentTokenManager.revokeToken(agentId);
1148
- }
1149
-
1150
- // Notify parent via inbox
1151
- if (record.parent_id) {
1152
- try {
1153
- await inboxAdapter.send(
1154
- agentId,
1155
- record.parent_id,
1156
- {
1157
- type: "event",
1158
- event: "agent_stopped",
1159
- data: {
1160
- agentId,
1161
- reason,
1162
- taskId: record.task_id,
1163
- role: record.role,
1164
- },
1165
- },
1166
- { importance: "high", threadTag: `lifecycle:${agentId}` }
1167
- );
1168
- } catch {
1169
- // Non-fatal inbox notification failure
1170
- }
1171
- }
1172
-
1173
- // Deregister from inbox
1174
- await inboxAdapter.deregisterAgent(agentId);
1175
-
1176
- // Update agent state
1177
- agentStore.updateAgent(agentId, {
1178
- state: "stopped" as AgentState,
1179
- stop_reason: reason as any,
1180
- stopped_at: Date.now(),
1181
- });
1182
-
1183
- // Emit final trajectory checkpoint with phase: "ended"
1184
- if (sidecarRef?.connected) {
1185
- try {
1186
- const session = agentStore.getSession(agentId);
1187
- sidecarRef.reportCheckpoint({
1188
- id: `${session?.session_id ?? agentId}-ended`,
1189
- session_id: session?.session_id ?? agentId,
1190
- agent: record.name ?? agentId,
1191
- branch: null,
1192
- files_touched: [],
1193
- checkpoints_count: 0,
1194
- metadata: { phase: "ended", reason },
1195
- }).catch(() => {});
1196
- } catch {
1197
- // best effort
1198
- }
1199
- }
1200
-
1201
- // Notify lifecycle
1202
- const updatedAgent = agentRecordToAgent(agentStore.getAgent(agentId)!);
1203
- notifyLifecycle({ type: "stopped", agent: updatedAgent, reason });
1204
-
1205
- // Cascade termination to children
1206
- const children = agentStore.getChildren(agentId);
1207
- for (const child of children) {
1208
- if (child.state === "running" || child.state === "spawning") {
1209
- const wsProvider: WorkspaceProvider = {
1210
- getWorkspace: (id: AgentId) => agentWorkspaces.get(id) ?? null,
1211
- };
1212
- const cascadeAdapter: CascadeAgentManager = {
1213
- getChildren: (id: AgentId) =>
1214
- agentStore
1215
- .getChildren(id)
1216
- .map((r) => agentRecordToAgent(r)),
1217
- terminate: (id: AgentId, r: AgentStopReason) => terminate(id, r),
1218
- };
1219
- const parentTaskRef = (record.metadata as Record<string, unknown> | undefined)
1220
- ?.task_ref as { resource_id: string; node_id: string } | undefined;
1221
- await terminateWithChangeConsolidation(
1222
- child.id as AgentId,
1223
- agentId,
1224
- cascadeAdapter,
1225
- wsProvider,
1226
- undefined,
1227
- workspaceManager ?? undefined,
1228
- parentTaskRef
1229
- );
1230
- }
1231
- }
1232
- }
1233
-
1234
- async function resume(
1235
- agentId: AgentId,
1236
- overridePermissionMode?: PermissionMode
1237
- ): Promise<SpawnedAgent> {
1238
- if (isShuttingDown) {
1239
- throw new AgentManagerError(
1240
- "Cannot resume agent during shutdown",
1241
- "SHUTDOWN_IN_PROGRESS"
1242
- );
1243
- }
1244
-
1245
- const record = agentStore.getAgent(agentId);
1246
- if (!record) {
1247
- throw new AgentManagerError(
1248
- `Agent ${agentId} not found`,
1249
- "AGENT_NOT_FOUND",
1250
- agentId
1251
- );
1252
- }
1253
-
1254
- if (activeSessions.has(agentId)) {
1255
- throw new AgentManagerError(
1256
- `Agent ${agentId} already has active session`,
1257
- "ALREADY_RUNNING",
1258
- agentId
1259
- );
1260
- }
1261
-
1262
- const permMode = overridePermissionMode ?? defaultPermissionMode;
1263
- const agentCwd = record.cwd || defaultCwd;
1264
-
1265
- const handle = await AgentFactory.spawn(defaultAgentType, {
1266
- permissionMode: permMode,
1267
- });
1268
-
1269
- const macroAgentMcp = buildMcpServerConfig({
1270
- agentId,
1271
- parentId: record.parent_id ?? "",
1272
- taskId: record.task_id ?? "",
1273
- cwd: agentCwd,
1274
- permissionMode: permMode,
1275
- lineage: record.lineage,
1276
- });
1277
-
1278
- const mcpServers = [
1279
- {
1280
- name: macroAgentMcp.name,
1281
- command: macroAgentMcp.command,
1282
- args: macroAgentMcp.args ?? [],
1283
- env: Object.entries(macroAgentMcp.env ?? {}).map(([k, v]) => ({
1284
- name: k,
1285
- value: v,
1286
- })),
1287
- },
1288
- ];
1289
-
1290
- // Strip user/project/local setting sources for isolated workers (the
1291
- // metadata flag is set at spawn time when SpawnAgentOptions.isolatedSettings
1292
- // was true) or interactive mode. See spawn() for the rationale.
1293
- const isIsolated = (record.metadata as Record<string, unknown> | undefined)?.isolatedSettings === true;
1294
- const agentMeta =
1295
- isIsolated || permMode === "interactive"
1296
- ? { claudeCode: { options: { settingSources: [] } } }
1297
- : undefined;
1298
-
1299
- // Try to load existing session or create new
1300
- const sessionRecord = agentStore.getSession(agentId);
1301
- let session: Session;
1302
-
1303
- if (sessionRecord?.provider_session_id) {
1304
- session = await handle.loadSession(
1305
- sessionRecord.provider_session_id,
1306
- agentCwd,
1307
- mcpServers as any,
1308
- agentMeta ? { agentMeta } : undefined
1309
- );
1310
- } else {
1311
- session = await handle.createSession(agentCwd, {
1312
- mcpServers,
1313
- ...(agentMeta && { agentMeta }),
1314
- });
1315
- }
1316
-
1317
- const now = Date.now() as Timestamp;
1318
- activeSessions.set(agentId, {
1319
- agentId,
1320
- handle,
1321
- session,
1322
- createdAt: now,
1323
- isPrompting: false,
1324
- });
1325
-
1326
- agentStore.updateAgent(agentId, {
1327
- state: "running",
1328
- started_at: now,
1329
- });
1330
- agentStore.putSession({
1331
- agent_id: agentId,
1332
- session_id: sessionRecord?.session_id ?? `session_${nanoid(12)}`,
1333
- provider_session_id: session.id,
1334
- created_at: now,
1335
- });
1336
-
1337
- const agent = agentRecordToAgent(agentStore.getAgent(agentId)!);
1338
-
1339
- // Re-publish the agent to subscribers (local MAP server, hub lifecycle
1340
- // bridge, team auto-join listeners) so a resumed agent is a first-class
1341
- // registered agent — not just an in-memory handle. Without this, the hub
1342
- // never re-registers the agent after cold-start; ACP routing works but
1343
- // the hub's "Registered Agents" view stays empty and capabilities never
1344
- // propagate back through `map/agents/register`.
1345
- //
1346
- // Spawn semantics are correct here: the process is new, the session is
1347
- // (re)loaded, and subscribers treat it as a fresh registration. Paired
1348
- // with the `stopped` event that fired on the prior termination, this
1349
- // keeps the bridge's `registered` map consistent.
1350
- notifyLifecycle({ type: "spawned", agent });
1351
- notifyLifecycle({ type: "started", agent });
1352
-
1353
- return {
1354
- id: agentId,
1355
- session_id: sessionRecord?.session_id ?? "",
1356
- agent,
1357
- session,
1358
- };
1359
- }
1360
-
1361
- async function continueAgent(
1362
- agentId: AgentId,
1363
- options?: ContinueAgentOptions
1364
- ): Promise<SpawnedAgent> {
1365
- const record = agentStore.getAgent(agentId);
1366
- if (!record) {
1367
- throw new AgentManagerError(
1368
- `Agent ${agentId} not found`,
1369
- "AGENT_NOT_FOUND",
1370
- agentId
1371
- );
1372
- }
1373
-
1374
- const contextLines: string[] = [];
1375
- if (options?.additionalContext) {
1376
- contextLines.push(options.additionalContext);
1377
- }
1378
- contextLines.push(`## Prior Session Context`);
1379
- contextLines.push(`Continuing from agent ${agentId}.`);
1380
-
1381
- const resumeContext = contextLines.join("\n");
1382
- const taskDescription =
1383
- options?.task ?? record.task ?? `Continue work from ${agentId}`;
1384
-
1385
- return spawn({
1386
- task: taskDescription,
1387
- role: record.role,
1388
- parent: record.parent_id ?? undefined,
1389
- cwd: record.cwd || defaultCwd,
1390
- customPrompt: resumeContext,
1391
- });
1392
- }
1393
-
1394
- async function forkAgent(
1395
- sourceAgentId: AgentId,
1396
- options?: { name?: string; prompt?: string; cwd?: string }
1397
- ): Promise<SpawnedAgent> {
1398
- if (isShuttingDown) {
1399
- throw new AgentManagerError(
1400
- "Cannot fork during shutdown",
1401
- "SHUTDOWN_IN_PROGRESS"
1402
- );
1403
- }
1404
-
1405
- const record = agentStore.getAgent(sourceAgentId);
1406
- if (!record) {
1407
- throw new AgentManagerError(
1408
- `Agent ${sourceAgentId} not found`,
1409
- "AGENT_NOT_FOUND",
1410
- sourceAgentId
1411
- );
1412
- }
1413
-
1414
- const activeSession = activeSessions.get(sourceAgentId);
1415
- const sessionRecord = agentStore.getSession(sourceAgentId);
1416
- if (!activeSession && !sessionRecord?.provider_session_id) {
1417
- throw new AgentManagerError(
1418
- `Agent ${sourceAgentId} has no session to fork`,
1419
- "FORK_NOT_SUPPORTED",
1420
- sourceAgentId
1421
- );
1422
- }
1423
-
1424
- const forkCwd = options?.cwd ?? record.cwd ?? defaultCwd;
1425
-
1426
- // Get forked session ID
1427
- let forkedProviderSessionId: string;
1428
- if (activeSession) {
1429
- const forkedSession = await activeSession.session.forkWithFlush();
1430
- forkedProviderSessionId = forkedSession.id;
1431
- } else {
1432
- forkedProviderSessionId = sessionRecord!.provider_session_id!;
1433
- }
1434
-
1435
- // Spawn new process
1436
- const handle = await AgentFactory.spawn(defaultAgentType, {
1437
- permissionMode: defaultPermissionMode,
1438
- });
1439
-
1440
- const agentId = `agent_${nanoid(12)}` as AgentId;
1441
- const taskId = `task_${nanoid(12)}` as TaskId;
1442
- const sessionId = `session_${nanoid(12)}`;
1443
- const name = options?.name ?? generateName();
1444
- const now = Date.now() as Timestamp;
1445
-
1446
- // Persist forked agent
1447
- agentStore.putAgent({
1448
- id: agentId,
1449
- name,
1450
- role: record.role,
1451
- state: "running",
1452
- parent_id: record.parent_id,
1453
- lineage: record.lineage,
1454
- team: record.team,
1455
- scope: record.scope,
1456
- task: options?.prompt ?? `[Fork of ${sourceAgentId}]`,
1457
- task_id: taskId,
1458
- cwd: forkCwd,
1459
- capabilities: record.capabilities,
1460
- created_at: now,
1461
- started_at: now,
1462
- metadata: { fork_of: sourceAgentId },
1463
- });
1464
-
1465
- const macroAgentMcp = buildMcpServerConfig({
1466
- agentId,
1467
- parentId: record.parent_id ?? "",
1468
- taskId,
1469
- cwd: forkCwd,
1470
- permissionMode: defaultPermissionMode,
1471
- lineage: record.lineage,
1472
- sessionId,
1473
- });
1474
-
1475
- const session = await handle.loadSession(
1476
- forkedProviderSessionId,
1477
- forkCwd,
1478
- [
1479
- {
1480
- name: macroAgentMcp.name,
1481
- command: macroAgentMcp.command,
1482
- args: macroAgentMcp.args ?? [],
1483
- env: Object.entries(macroAgentMcp.env ?? {}).map(([k, v]) => ({
1484
- name: k,
1485
- value: v,
1486
- })),
1487
- },
1488
- ] as any
1489
- );
1490
-
1491
- agentStore.putSession({
1492
- agent_id: agentId,
1493
- session_id: sessionId,
1494
- provider_session_id: session.id,
1495
- created_at: now,
1496
- });
1497
-
1498
- await inboxAdapter.registerAgent(agentId, {
1499
- name,
1500
- role: record.role,
1501
- scope: record.scope,
1502
- });
1503
-
1504
- activeSessions.set(agentId, {
1505
- agentId,
1506
- handle,
1507
- session,
1508
- createdAt: now,
1509
- isPrompting: false,
1510
- });
1511
-
1512
- const agent = agentRecordToAgent(agentStore.getAgent(agentId)!);
1513
- notifyLifecycle({ type: "spawned", agent });
1514
- notifyLifecycle({ type: "started", agent });
1515
-
1516
- return { id: agentId, session_id: sessionId, agent, session };
1517
- }
1518
-
1519
- // ── Query Methods ──────────────────────────────────────────
1520
-
1521
- function get(agentId: AgentId): Agent | null {
1522
- const record = agentStore.getAgent(agentId);
1523
- return record ? agentRecordToAgent(record) : null;
1524
- }
1525
-
1526
- function list(filter?: AgentFilter): Agent[] {
1527
- const records = agentStore.listAgents({
1528
- state: filter?.state,
1529
- parent_id: filter?.parent,
1530
- });
1531
-
1532
- let result = records.map(agentRecordToAgent);
1533
-
1534
- if (filter?.task_id) {
1535
- result = result.filter((a) => a.task_id === filter.task_id);
1536
- }
1537
- if (filter?.headManagersOnly) {
1538
- result = result.filter((a) => !a.parent);
1539
- }
1540
-
1541
- return result;
1542
- }
1543
-
1544
- function getChildren(agentId: AgentId): Agent[] {
1545
- return agentStore.getChildren(agentId).map(agentRecordToAgent);
1546
- }
1547
-
1548
- function getHierarchy(
1549
- agentId: AgentId,
1550
- options?: HierarchyOptions
1551
- ): AgentHierarchy | null {
1552
- const record = agentStore.getAgent(agentId);
1553
- if (!record) return null;
1554
-
1555
- function buildTree(
1556
- id: AgentId,
1557
- depth: number
1558
- ): AgentHierarchyNode {
1559
- const agent = agentRecordToAgent(agentStore.getAgent(id)!);
1560
- const maxDepth = options?.depth;
1561
- const children =
1562
- maxDepth !== undefined && depth >= maxDepth
1563
- ? []
1564
- : agentStore
1565
- .getChildren(id)
1566
- .map((c) => buildTree(c.id as AgentId, depth + 1));
1567
-
1568
- return { agent, children };
1569
- }
1570
-
1571
- const root = buildTree(agentId, 0);
1572
-
1573
- function countNodes(node: AgentHierarchyNode): number {
1574
- return 1 + node.children.reduce((sum, c) => sum + countNodes(c), 0);
1575
- }
1576
-
1577
- function maxDepth(node: AgentHierarchyNode, d: number): number {
1578
- if (node.children.length === 0) return d;
1579
- return Math.max(...node.children.map((c) => maxDepth(c, d + 1)));
1580
- }
1581
-
1582
- return {
1583
- root,
1584
- depth: maxDepth(root, 0),
1585
- totalAgents: countNodes(root),
1586
- };
1587
- }
1588
-
1589
- // ── Head Manager ─────────────────────────────────────────────
1590
-
1591
- async function getOrCreateHeadManager(
1592
- options: HeadManagerOptions
1593
- ): Promise<SpawnedAgent> {
1594
- // Check for an existing head manager matching this cwd that ALSO has a
1595
- // live session in this process. The activeSessions check has to be inside
1596
- // the predicate (not after .find) — the agentStore is persistent across
1597
- // process restarts, so without this filter we'd match stale "running"
1598
- // records from previous processes whose sessions are gone, then fall
1599
- // through to spawn() and create a duplicate coordinator.
1600
- const existing = agentStore
1601
- .listAgents({ parent_id: null, state: "running" })
1602
- .find(
1603
- (a) =>
1604
- a.cwd === options.cwd &&
1605
- activeSessions.has(a.id as AgentId),
1606
- );
1607
-
1608
- if (existing) {
1609
- const sessionEntry = activeSessions.get(existing.id as AgentId)!;
1610
- const storedSession = agentStore.getSession(existing.id as AgentId);
1611
- return {
1612
- id: existing.id as AgentId,
1613
- session_id: storedSession?.session_id ?? sessionEntry.session.id ?? "",
1614
- agent: agentRecordToAgent(existing),
1615
- session: sessionEntry.session,
1616
- };
1617
- }
1618
-
1619
- return spawn({
1620
- task: "Head manager",
1621
- parent: null,
1622
- cwd: options.cwd,
1623
- permissionMode: options.permissionMode,
1624
- customPrompt: options.systemPrompt,
1625
- role: "coordinator",
1626
- topics: options.topics,
1627
- });
1628
- }
1629
-
1630
- function listHeadManagers(): Agent[] {
1631
- return agentStore
1632
- .listAgents({ parent_id: null })
1633
- .map(agentRecordToAgent);
1634
- }
1635
-
1636
- /**
1637
- * Look up the spawned-agent shape for any agent that's still alive in this
1638
- * process (any role, not just coordinators). Returns null if the agent
1639
- * doesn't exist, isn't running, or has no live session in `activeSessions`.
1640
- *
1641
- * Used by the ACP layer to bind a session to a specific agent when the MAP
1642
- * stream targets one explicitly — preserving the routing intent that
1643
- * cwd-based head-manager lookup would otherwise lose in multi-coordinator
1644
- * scenarios.
1645
- */
1646
- function getActiveAgentSession(agentId: AgentId): SpawnedAgent | null {
1647
- if (!activeSessions.has(agentId)) return null;
1648
- const record = agentStore.getAgent(agentId);
1649
- if (!record || record.state !== "running") return null;
1650
- const sessionEntry = activeSessions.get(agentId)!;
1651
- const storedSession = agentStore.getSession(agentId);
1652
- return {
1653
- id: agentId,
1654
- session_id: storedSession?.session_id ?? sessionEntry.session.id ?? "",
1655
- agent: agentRecordToAgent(record),
1656
- session: sessionEntry.session,
1657
- };
1658
- }
1659
-
1660
- // ── Session Interaction ──────────────────────────────────────
1661
-
1662
- async function* prompt(
1663
- agentId: AgentId,
1664
- message: string
1665
- ): AsyncIterable<ExtendedSessionUpdate> {
1666
- const activeSession = activeSessions.get(agentId);
1667
- if (!activeSession) {
1668
- throw new AgentManagerError(
1669
- `No active session for agent ${agentId}`,
1670
- "SESSION_NOT_FOUND",
1671
- agentId
1672
- );
1673
- }
1674
-
1675
- activeSession.isPrompting = true;
1676
- try {
1677
- // Permission overlay enforcement — for agents in dispatch context
1678
- // (mail-inbound + ACP reuse targets), the dispatch consumer sets a
1679
- // per-agent overlay before driving prompt(). When set, `permission_request`
1680
- // session updates are intercepted here, evaluated against the overlay,
1681
- // and answered via `respondToPermission`. The update is NOT yielded
1682
- // to the consumer in that case — dispatch enforcement is internal.
1683
- //
1684
- // When no overlay is set (the common case — chat agents, sub-agents
1685
- // spawned by parents, etc.), permission_request updates are yielded
1686
- // through unchanged so chat surfaces' UI permission dialogs (the
1687
- // swarmcraft PermissionDialog rendered via the openhive-acp-service
1688
- // WS subscription) keep working.
1689
- //
1690
- // See `docs/PERMISSION_OVERLAY_ACP_DESIGN.md` for the rationale and
1691
- // a diagram of the four-process flow.
1692
- for await (const update of activeSession.session.prompt(message)) {
1693
- const u = update as {
1694
- sessionUpdate?: string;
1695
- requestId?: string;
1696
- toolCall?: { title?: string; kind?: string; rawInput?: unknown };
1697
- options?: Array<{ kind?: string; optionId?: string }>;
1698
- };
1699
- if (u?.sessionUpdate === "permission_request") {
1700
- const overlay = getPermissionOverlay(agentId);
1701
- // No overlay → pass through to the consumer (chat UI, etc.).
1702
- if (!overlay) {
1703
- yield update;
1704
- continue;
1705
- }
1706
- let optionId: string | undefined;
1707
- try {
1708
- const toolName = deriveToolName(u.toolCall);
1709
- const toolInput = u.toolCall?.rawInput ?? {};
1710
- const decision = evaluatePermission(toolName, toolInput, overlay)
1711
- .decision;
1712
- const wantedKind =
1713
- decision === "deny" ? "reject_once" : "allow_once";
1714
- const opt =
1715
- u.options?.find((o) => o.kind === wantedKind) ??
1716
- u.options?.find(
1717
- (o) =>
1718
- o.kind === (decision === "deny" ? "reject_always" : "allow_always"),
1719
- );
1720
- optionId = opt?.optionId;
1721
- } catch {
1722
- // Fail closed: on registry/evaluator error, deny.
1723
- optionId = u.options?.find((o) => o.kind === "reject_once")?.optionId;
1724
- }
1725
- if (u.requestId && optionId) {
1726
- try {
1727
- (activeSession.session as any).respondToPermission?.(
1728
- u.requestId,
1729
- optionId,
1730
- );
1731
- } catch (err) {
1732
- console.warn(
1733
- `[perm-overlay] respondToPermission failed agent=${agentId} req=${u.requestId}: ${(err as Error).message}`,
1734
- );
1735
- }
1736
- }
1737
- // Don't yield permission_request to the consumer — dispatch-internal.
1738
- continue;
1739
- }
1740
- yield update;
1741
- }
1742
- } finally {
1743
- activeSession.isPrompting = false;
1744
- agentStore.updateAgent(agentId, {
1745
- last_activity_at: Date.now(),
1746
- });
1747
- }
1748
- }
1749
-
1750
- async function promptUntilDone(
1751
- agentId: AgentId,
1752
- message: string,
1753
- options?: {
1754
- maxFollowUps?: number;
1755
- onUpdate?: (update: ExtendedSessionUpdate) => void;
1756
- }
1757
- ): Promise<{
1758
- doneCalled: boolean;
1759
- doneStatus?: string;
1760
- updates: ExtendedSessionUpdate[];
1761
- }> {
1762
- const maxFollowUps = options?.maxFollowUps ?? 2;
1763
- const allUpdates: ExtendedSessionUpdate[] = [];
1764
- let doneCalled = false;
1765
- let doneStatus: string | undefined;
1766
-
1767
- let currentMessage = message;
1768
-
1769
- for (let attempt = 0; attempt <= maxFollowUps; attempt++) {
1770
- for await (const update of prompt(agentId, currentMessage)) {
1771
- allUpdates.push(update);
1772
- options?.onUpdate?.(update);
1773
-
1774
- // Detect done() tool call from session updates.
1775
- // acp-factory uses { sessionUpdate: "tool_call", title: "mcp__macro-agent__done" }
1776
- const uAny = update as any;
1777
-
1778
- // Check title field (primary detection)
1779
- if (
1780
- (uAny.sessionUpdate === "tool_call" || uAny.sessionUpdate === "tool_call_update") &&
1781
- typeof uAny.title === "string" &&
1782
- uAny.title.endsWith("__done")
1783
- ) {
1784
- doneCalled = true;
1785
- // Extract status from rawInput (may arrive across multiple updates —
1786
- // first update has rawInput={}, subsequent has full input)
1787
- try {
1788
- const raw = uAny.rawInput;
1789
- const input =
1790
- typeof raw === "string" ? JSON.parse(raw) :
1791
- typeof raw === "object" ? raw :
1792
- uAny.input;
1793
- if (input?.status) {
1794
- doneStatus = input.status;
1795
- }
1796
- } catch {
1797
- // Best effort — rawInput may not be parseable yet
1798
- }
1799
- }
1800
-
1801
- // Fallback: check older format
1802
- if (
1803
- uAny.type === "result" &&
1804
- uAny.subtype === "tool_result" &&
1805
- uAny.toolName === "done"
1806
- ) {
1807
- doneCalled = true;
1808
- doneStatus = uAny.result?.status;
1809
- }
1810
- }
1811
-
1812
- if (doneCalled) break;
1813
-
1814
- if (attempt < maxFollowUps) {
1815
- currentMessage =
1816
- "Please call the done() tool to signal that you have completed your work.";
1817
- }
1818
- }
1819
-
1820
- // Auto-terminate when done() was called and the handler signaled shouldTerminate.
1821
- // This closes the lifecycle gap: without this, agents stay in "running" state
1822
- // after calling done() because nothing triggers terminate().
1823
- if (doneCalled) {
1824
- const reason = doneStatus === "completed" ? "completed" : (doneStatus ?? "failed");
1825
- try {
1826
- await terminate(agentId, reason as any);
1827
- } catch {
1828
- // Best effort — agent may already be stopping
1829
- }
1830
- }
1831
-
1832
- return { doneCalled, doneStatus, updates: allUpdates };
1833
- }
1834
-
1835
- function getSession(agentId: AgentId): Session | null {
1836
- return activeSessions.get(agentId)?.session ?? null;
1837
- }
1838
-
1839
- function hasActiveSession(agentId: AgentId): boolean {
1840
- return activeSessions.has(agentId);
1841
- }
1842
-
1843
- function isPrompting(agentId: AgentId): boolean {
1844
- return activeSessions.get(agentId)?.isPrompting ?? false;
1845
- }
1846
-
1847
- async function supportsInjection(agentId: AgentId): Promise<boolean> {
1848
- const session = activeSessions.get(agentId)?.session;
1849
- if (!session) return false;
1850
- return typeof (session as any).supportsInject === "function"
1851
- ? (session as any).supportsInject()
1852
- : false;
1853
- }
1854
-
1855
- function isProcessRunning(agentId: AgentId): boolean {
1856
- const session = activeSessions.get(agentId);
1857
- if (!session) return false;
1858
- return typeof (session as any).handle?.isRunning === "function"
1859
- ? (session as any).handle.isRunning()
1860
- : true;
1861
- }
1862
-
1863
- function respondToPermission(
1864
- agentId: AgentId,
1865
- requestId: string,
1866
- optionId: string
1867
- ): boolean {
1868
- const session = activeSessions.get(agentId)?.session;
1869
- if (!session) return false;
1870
- return (session as any).respondToPermission?.(requestId, optionId) ?? false;
1871
- }
1872
-
1873
- function cancelPermission(agentId: AgentId, requestId: string): boolean {
1874
- const session = activeSessions.get(agentId)?.session;
1875
- if (!session) return false;
1876
- return (session as any).cancelPermission?.(requestId) ?? false;
1877
- }
1878
-
1879
- function setPermissionMode(
1880
- agentId: AgentId,
1881
- mode: PermissionMode
1882
- ): boolean {
1883
- const session = activeSessions.get(agentId);
1884
- if (!session) return false;
1885
- if (typeof (session.handle as any).setPermissionMode === "function") {
1886
- (session.handle as any).setPermissionMode(mode);
1887
- return true;
1888
- }
1889
- return false;
1890
- }
1891
-
1892
- function getPermissionMode(agentId: AgentId): PermissionMode | null {
1893
- const session = activeSessions.get(agentId);
1894
- if (!session) return null;
1895
- return typeof (session.handle as any).getPermissionMode === "function"
1896
- ? (session.handle as any).getPermissionMode()
1897
- : null;
1898
- }
1899
-
1900
- // ── Lifecycle Callbacks ──────────────────────────────────────
1901
-
1902
- function onLifecycleEvent(
1903
- callback: AgentLifecycleCallback
1904
- ): () => void {
1905
- lifecycleListeners.add(callback);
1906
- return () => lifecycleListeners.delete(callback);
1907
- }
1908
-
1909
- function setSpawnInterceptorFn(
1910
- interceptor: SpawnInterceptor | null
1911
- ): void {
1912
- spawnInterceptor = interceptor;
1913
- }
1914
-
1915
- function getRoleRegistry(): RoleRegistry {
1916
- return roleRegistry;
1917
- }
1918
-
1919
- // ── Legacy stubs ─────────────────────────────────────────────
1920
- // These methods exist for backward compatibility but are no-ops
1921
- // since messaging and task management are now in subsystems.
1922
-
1923
- function setOpenTasksSocketPath(_socketPath: string): void {
1924
- // No-op: opentasks client auto-discovers socket
1925
- }
1926
-
1927
- function setMapServerUrl(url: string): void {
1928
- mapServerUrl = url;
1929
- }
1930
-
1931
- function setIntegrationConfigs(configs: {
1932
- minimem?: typeof minimemConfig;
1933
- skilltree?: typeof skilltreeConfig;
1934
- sessionlog?: typeof sessionlogConfig;
1935
- }): void {
1936
- if (configs.minimem) minimemConfig = configs.minimem;
1937
- if (configs.skilltree) skilltreeConfig = configs.skilltree;
1938
- if (configs.sessionlog) sessionlogConfig = configs.sessionlog;
1939
- }
1940
-
1941
- function setSkillLoadout(role: string, content: string): void {
1942
- skillLoadouts.set(role, content);
1943
- }
1944
-
1945
- function setSidecar(sidecar: { connected: boolean; reportCheckpoint(cp: any): Promise<any> } | null): void {
1946
- sidecarRef = sidecar;
1947
- }
1948
-
1949
- function setTopologyPolicyFn(
1950
- policy: import('../workspace/topology/types.js').TopologyPolicy | null
1951
- ): void {
1952
- topologyPolicy = policy;
1953
- }
1954
-
1955
- function setMailServices(): void {
1956
- // No-op: agent-inbox handles conversation tracking
1957
- }
1958
-
1959
- // ── Cleanup ──────────────────────────────────────────────────
1960
-
1961
- async function close(): Promise<void> {
1962
- isShuttingDown = true;
1963
-
1964
- for (const [agentId, session] of activeSessions) {
1965
- try {
1966
- await session.handle.close();
1967
- } catch {
1968
- /* ignore */
1969
- }
1970
- agentStore.updateAgent(agentId, {
1971
- state: "stopped",
1972
- stop_reason: "cancelled",
1973
- stopped_at: Date.now(),
1974
- });
1975
- }
1976
- activeSessions.clear();
1977
- agentWorkspaces.clear();
1978
- lifecycleListeners.clear();
1979
-
1980
- // Note: isShuttingDown stays true after close() to prevent further spawns
1981
- }
1982
-
1983
- // ── Return AgentManager interface ────────────────────────────
1984
-
1985
- return {
1986
- spawn,
1987
- terminate,
1988
- resume,
1989
- continueAgent,
1990
- forkAgent,
1991
- get,
1992
- list,
1993
- getChildren,
1994
- getHierarchy,
1995
- getOrCreateHeadManager,
1996
- listHeadManagers,
1997
- getActiveAgentSession,
1998
- prompt,
1999
- promptUntilDone,
2000
- getSession,
2001
- hasActiveSession,
2002
- isPrompting,
2003
- supportsInjection,
2004
- isProcessRunning,
2005
- respondToPermission,
2006
- cancelPermission,
2007
- setPermissionMode,
2008
- getPermissionMode,
2009
- onLifecycleEvent,
2010
- setSpawnInterceptor: setSpawnInterceptorFn,
2011
- getRoleRegistry,
2012
- setOpenTasksSocketPath,
2013
- setMapServerUrl,
2014
- setIntegrationConfigs,
2015
- setSkillLoadout,
2016
- setSidecar,
2017
- setTopologyPolicy: setTopologyPolicyFn,
2018
- setMailServices,
2019
- close,
2020
- } as AgentManager;
2021
- }