@agenticmail/enterprise 0.5.319 → 0.5.320

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 (321) hide show
  1. package/README.md +118 -38
  2. package/dist/agent-heartbeat-3FWNHZFX.js +510 -0
  3. package/dist/agent-heartbeat-4RWHZR7H.js +510 -0
  4. package/dist/agent-heartbeat-6ZGB5ILY.js +510 -0
  5. package/dist/agent-heartbeat-BIVHLKFM.js +510 -0
  6. package/dist/agent-heartbeat-HRKVFK2T.js +510 -0
  7. package/dist/agent-heartbeat-JC5GWVXD.js +510 -0
  8. package/dist/agent-heartbeat-K6A4HMHB.js +510 -0
  9. package/dist/agent-heartbeat-LCDXWFVB.js +510 -0
  10. package/dist/agent-heartbeat-P7HZCZAQ.js +510 -0
  11. package/dist/agent-heartbeat-PUIRSNIO.js +510 -0
  12. package/dist/agent-heartbeat-SN5ILQ6Y.js +510 -0
  13. package/dist/agent-heartbeat-TW5YTDYC.js +510 -0
  14. package/dist/agent-heartbeat-Z2QQXROL.js +510 -0
  15. package/dist/agent-notify-OEQBCZLN.js +43 -0
  16. package/dist/{agent-tools-263HM5QU.js → agent-tools-3W7XLUYA.js} +1 -1
  17. package/dist/agent-tools-4QK7LLNP.js +9 -0
  18. package/dist/agent-tools-54VZGT6L.js +9 -0
  19. package/dist/{agent-tools-AT4D276V.js → agent-tools-AYYDPO27.js} +7 -7
  20. package/dist/{agent-tools-MSTAPX2I.js → agent-tools-F2X47FKF.js} +7 -7
  21. package/dist/{agent-tools-FA26SY5O.js → agent-tools-O6W3QAZL.js} +11 -6
  22. package/dist/agent-tools-OAWVZBMW.js +9 -0
  23. package/dist/agent-tools-QCCU74PN.js +13949 -0
  24. package/dist/chunk-2LHUARN6.js +4929 -0
  25. package/dist/chunk-2WVCNCYC.js +5087 -0
  26. package/dist/{chunk-6PWDS7KY.js → chunk-3FM6YQUK.js} +20 -20
  27. package/dist/chunk-3UAFHUEC.js +212 -0
  28. package/dist/{chunk-WJO57PMO.js → chunk-46GOWZT4.js} +20 -20
  29. package/dist/{chunk-BNRE7TSX.js → chunk-5KYJAUZV.js} +3 -3
  30. package/dist/chunk-6C5PKREN.js +467 -0
  31. package/dist/{chunk-447MTPZF.js → chunk-6ZMLNEHB.js} +3 -3
  32. package/dist/chunk-BPZQT5N5.js +25652 -0
  33. package/dist/chunk-BQM7MBPS.js +1380 -0
  34. package/dist/{chunk-ZRFKGPIU.js → chunk-C52OQNNY.js} +20 -20
  35. package/dist/chunk-C7HGQF4Y.js +25652 -0
  36. package/dist/chunk-CAHNZGGK.js +25656 -0
  37. package/dist/{chunk-FL3CH3ET.js → chunk-CK7R6UHE.js} +51 -27
  38. package/dist/chunk-D36RPWB7.js +25652 -0
  39. package/dist/{chunk-36NM2B4C.js → chunk-DJK2UPFH.js} +63 -93
  40. package/dist/chunk-DM7FTF7W.js +4929 -0
  41. package/dist/chunk-DMD24UFZ.js +5101 -0
  42. package/dist/{chunk-36XNMIHA.js → chunk-DXZGPUAF.js} +20 -20
  43. package/dist/chunk-F46WB5IL.js +5087 -0
  44. package/dist/chunk-F5QG5SQH.js +5087 -0
  45. package/dist/{chunk-JGEVQZDR.js → chunk-FLQ5FLHW.js} +13 -16
  46. package/dist/chunk-H7GP733U.js +5087 -0
  47. package/dist/{chunk-OZSQLOV6.js → chunk-HHBXWB5U.js} +415 -19
  48. package/dist/{chunk-D24JY75H.js → chunk-IMXS4N6W.js} +3 -3
  49. package/dist/{chunk-6PVBV6ZP.js → chunk-JNMDD7JY.js} +3 -3
  50. package/dist/chunk-JTV5LA47.js +1519 -0
  51. package/dist/chunk-KV6G7NZX.js +1519 -0
  52. package/dist/chunk-MU5MEBIK.js +1519 -0
  53. package/dist/chunk-NLT5MC7X.js +465 -0
  54. package/dist/{chunk-GTFZZUXX.js → chunk-NVLYIM4J.js} +51 -27
  55. package/dist/{chunk-6G5SXLXC.js → chunk-NZY2BIZH.js} +63 -93
  56. package/dist/chunk-O42L6G67.js +1519 -0
  57. package/dist/chunk-OCNERGGM.js +4891 -0
  58. package/dist/chunk-OJSNHONE.js +1519 -0
  59. package/dist/{chunk-2TAZJWJN.js → chunk-OWL3QVH7.js} +18 -0
  60. package/dist/{chunk-P3HVY2HS.js → chunk-OWTLNV4Q.js} +382 -7
  61. package/dist/chunk-PCNYEP6T.js +4891 -0
  62. package/dist/{chunk-YL3Z5KPR.js → chunk-PI4AQ4Z6.js} +438 -15
  63. package/dist/chunk-PN3EGTCA.js +194 -0
  64. package/dist/chunk-Q37UKNRC.js +1519 -0
  65. package/dist/chunk-QXTC6J7H.js +5087 -0
  66. package/dist/{chunk-SPBQVNDI.js → chunk-RKERL5LZ.js} +25 -21
  67. package/dist/chunk-RVBK2IOX.js +25652 -0
  68. package/dist/chunk-SAKODCZ5.js +4891 -0
  69. package/dist/{chunk-XV4TU65E.js → chunk-SALGFC5L.js} +51 -27
  70. package/dist/chunk-STGWZ2MS.js +1519 -0
  71. package/dist/chunk-UY3ZVQDP.js +25652 -0
  72. package/dist/chunk-V6OSD62M.js +5087 -0
  73. package/dist/chunk-VP6YAHX4.js +1519 -0
  74. package/dist/chunk-WDYJOEAI.js +5087 -0
  75. package/dist/chunk-WEAFQNOS.js +195 -0
  76. package/dist/chunk-XKUSAZGP.js +5087 -0
  77. package/dist/chunk-Z6K5FKAB.js +548 -0
  78. package/dist/chunk-ZGE3XAXY.js +1519 -0
  79. package/dist/chunk-ZGYVXYQQ.js +3296 -0
  80. package/dist/cli-agent-7TB2BWS6.js +2370 -0
  81. package/dist/cli-agent-AKXFFST2.js +2370 -0
  82. package/dist/cli-agent-DZTKLITB.js +2357 -0
  83. package/dist/cli-agent-FOF7PFEP.js +2357 -0
  84. package/dist/cli-agent-H74M2ZYN.js +2357 -0
  85. package/dist/cli-agent-HORWVPHB.js +2370 -0
  86. package/dist/cli-agent-HSZT6SKF.js +2423 -0
  87. package/dist/cli-agent-JLUQ4ZU6.js +2424 -0
  88. package/dist/cli-agent-MVCDH4HV.js +2370 -0
  89. package/dist/cli-agent-NZXOEPJ2.js +2357 -0
  90. package/dist/cli-agent-PADN3QRC.js +2357 -0
  91. package/dist/cli-agent-QAYEX3BE.js +2441 -0
  92. package/dist/cli-agent-QT64DT5J.js +2370 -0
  93. package/dist/cli-agent-TFL2M6UK.js +2424 -0
  94. package/dist/cli-agent-UIKXATTD.js +2357 -0
  95. package/dist/cli-agent-UJN6FYTO.js +2370 -0
  96. package/dist/cli-agent-VIQAYVY4.js +2357 -0
  97. package/dist/cli-agent-WNWFVOFM.js +2370 -0
  98. package/dist/cli-agent-XBQX67VJ.js +2423 -0
  99. package/dist/cli-agent-ZLSC6FF4.js +2357 -0
  100. package/dist/cli-serve-2IL5DTEY.js +153 -0
  101. package/dist/cli-serve-47N5UKKW.js +153 -0
  102. package/dist/cli-serve-4XGZFUV2.js +140 -0
  103. package/dist/cli-serve-6OT3UEAN.js +140 -0
  104. package/dist/cli-serve-7L6EY5UH.js +153 -0
  105. package/dist/cli-serve-BDGOOOKQ.js +260 -0
  106. package/dist/cli-serve-BFNIW2LF.js +153 -0
  107. package/dist/cli-serve-C7MN6U5Q.js +153 -0
  108. package/dist/cli-serve-CR3OY3IM.js +153 -0
  109. package/dist/cli-serve-DAJFRWQ7.js +153 -0
  110. package/dist/cli-serve-FW6FHFW4.js +153 -0
  111. package/dist/cli-serve-GEEOQS77.js +153 -0
  112. package/dist/cli-serve-H562I3ZK.js +153 -0
  113. package/dist/cli-serve-HDQZF4C4.js +153 -0
  114. package/dist/cli-serve-LICAOMEB.js +140 -0
  115. package/dist/cli-serve-LLGYLWFS.js +153 -0
  116. package/dist/cli-serve-N3OISDNB.js +153 -0
  117. package/dist/cli-serve-TIZ27EVR.js +153 -0
  118. package/dist/cli-serve-TUNI2RCN.js +153 -0
  119. package/dist/cli-serve-WNOZMAWD.js +153 -0
  120. package/dist/cli-validate-Z726VJCN.js +150 -0
  121. package/dist/cli.js +4 -4
  122. package/dist/connection-manager-KAWEUWUR.js +9 -0
  123. package/dist/dashboard/app.js +9 -3
  124. package/dist/dashboard/components/knowledge-link.js +15 -0
  125. package/dist/dashboard/components/settings-help.js +4 -2
  126. package/dist/dashboard/docs/agent-deployment.html +33 -1
  127. package/dist/dashboard/docs/settings-network.html +321 -0
  128. package/dist/dashboard/docs/settings-security.html +347 -0
  129. package/dist/dashboard/docs/settings-tool-security.html +176 -0
  130. package/dist/dashboard/docs/settings.html +36 -16
  131. package/dist/dashboard/pages/agent-detail/deployment.js +39 -6
  132. package/dist/dashboard/pages/agent-detail/tools.js +10 -0
  133. package/dist/dashboard/pages/database-access.js +4 -3
  134. package/dist/dashboard/pages/settings.js +174 -37
  135. package/dist/dashboard/pages/task-pipeline.js +400 -843
  136. package/dist/db-adapter-2T56ORSD.js +7 -0
  137. package/dist/db-adapter-IRHOUMVC.js +7 -0
  138. package/dist/index.js +41 -41
  139. package/dist/microsoft-VREAZ7M2.js +3955 -0
  140. package/dist/routes-3MMLQTB6.js +90 -0
  141. package/dist/routes-4ZUIJ4HE.js +90 -0
  142. package/dist/routes-5MXHKKH4.js +90 -0
  143. package/dist/routes-64NJFK3B.js +90 -0
  144. package/dist/routes-6AKQ2LBV.js +90 -0
  145. package/dist/routes-CRRBUDO4.js +90 -0
  146. package/dist/routes-DIAF3MC3.js +90 -0
  147. package/dist/routes-KMUNU6CY.js +90 -0
  148. package/dist/routes-LRRLXIZR.js +90 -0
  149. package/dist/routes-N647AJYG.js +90 -0
  150. package/dist/routes-SSSELAAR.js +90 -0
  151. package/dist/routes-STERVGKJ.js +90 -0
  152. package/dist/routes-ZEZZACZP.js +90 -0
  153. package/dist/runtime-5EQN4GFM.js +45 -0
  154. package/dist/runtime-5LP7PUD4.js +45 -0
  155. package/dist/runtime-6BULDBR3.js +45 -0
  156. package/dist/runtime-6YEENDN3.js +45 -0
  157. package/dist/runtime-7LQFRG3B.js +45 -0
  158. package/dist/runtime-AMXJU2MB.js +45 -0
  159. package/dist/runtime-D6WSE7FG.js +45 -0
  160. package/dist/runtime-EYVN7NFJ.js +45 -0
  161. package/dist/runtime-F6RPWQVW.js +45 -0
  162. package/dist/runtime-FYMJURFC.js +45 -0
  163. package/dist/runtime-JRNBL4O4.js +45 -0
  164. package/dist/runtime-OM2NIBMI.js +45 -0
  165. package/dist/runtime-QWPVD7CY.js +45 -0
  166. package/dist/runtime-YLIIPTE4.js +45 -0
  167. package/dist/runtime-YU6P22CG.js +45 -0
  168. package/dist/screen-unlock-4RPZBHOI.js +118 -0
  169. package/dist/server-AMCSXINC.js +28 -0
  170. package/dist/server-CU6LVQS4.js +28 -0
  171. package/dist/server-DFYGH2CV.js +28 -0
  172. package/dist/server-EELWOC3X.js +28 -0
  173. package/dist/server-EN5E2OWQ.js +28 -0
  174. package/dist/server-GW2HYJYI.js +28 -0
  175. package/dist/server-J25NCRWJ.js +28 -0
  176. package/dist/server-JDGNOTFV.js +28 -0
  177. package/dist/server-NE5HD5DJ.js +28 -0
  178. package/dist/server-NQOT7W77.js +28 -0
  179. package/dist/server-PWE5PQTR.js +28 -0
  180. package/dist/server-Q2Q32H2B.js +28 -0
  181. package/dist/server-Q77ME7TL.js +28 -0
  182. package/dist/server-WLLH4WST.js +28 -0
  183. package/dist/server-WTUJ2O3F.js +28 -0
  184. package/dist/server-X4CJTHHF.js +28 -0
  185. package/dist/server-XK3ILCJC.js +28 -0
  186. package/dist/server-ZRD3NDJE.js +28 -0
  187. package/dist/setup-44VBAO4J.js +20 -0
  188. package/dist/setup-4ONNQBWB.js +20 -0
  189. package/dist/setup-4OSBXSCL.js +20 -0
  190. package/dist/setup-4QFGRBLZ.js +20 -0
  191. package/dist/setup-6766SGAR.js +20 -0
  192. package/dist/setup-AYY24DKM.js +20 -0
  193. package/dist/setup-B34N4HPU.js +20 -0
  194. package/dist/setup-E2YLC2EY.js +20 -0
  195. package/dist/setup-ER6NXTY5.js +20 -0
  196. package/dist/setup-H2AGCBW5.js +20 -0
  197. package/dist/setup-ICOZRKCX.js +20 -0
  198. package/dist/setup-JFTJH7UF.js +20 -0
  199. package/dist/setup-PRFNI6YW.js +20 -0
  200. package/dist/setup-RAHBMYHE.js +20 -0
  201. package/dist/setup-TXPR5UQX.js +20 -0
  202. package/dist/setup-XCJMELVU.js +20 -0
  203. package/dist/setup-XIYEIFVK.js +20 -0
  204. package/dist/setup-Z4PZSHBI.js +20 -0
  205. package/dist/skills-FR7I5V7H.js +16 -0
  206. package/dist/skills-HCVBA6PK.js +16 -0
  207. package/dist/system-prompts-TM7OA32C.js +913 -0
  208. package/dist/task-queue-O7IVZYUO.js +9 -0
  209. package/dist/transport-encryption-2T7PIXKG.js +25 -0
  210. package/ecosystem.config.cjs +120 -0
  211. package/logs/cloudflared-error.log +61 -0
  212. package/logs/cloudflared-out.log +0 -0
  213. package/logs/enterprise-error.log +0 -0
  214. package/logs/enterprise-out.log +3 -0
  215. package/logs/fola-error.log +0 -0
  216. package/logs/fola-out.log +0 -0
  217. package/logs/john-error.log +8 -0
  218. package/logs/john-out.log +0 -0
  219. package/package.json +1 -1
  220. package/src/agent-tools/tool-resolver.ts +50 -61
  221. package/src/agent-tools/tools/enterprise-database.ts +5 -5
  222. package/src/agent-tools/tools/local/dependency-manager.ts +2 -2
  223. package/src/agent-tools/tools/microsoft/graph-api.ts +137 -26
  224. package/src/agent-tools/tools/microsoft/outlook-mail.ts +392 -100
  225. package/src/agent-tools/tools/microsoft/teams.ts +267 -48
  226. package/src/auth/routes.ts +4 -4
  227. package/src/cli-agent.ts +108 -8
  228. package/src/cli-serve.ts +140 -0
  229. package/src/dashboard/app.js +9 -3
  230. package/src/dashboard/components/knowledge-link.js +15 -0
  231. package/src/dashboard/components/settings-help.js +4 -2
  232. package/src/dashboard/docs/agent-deployment.html +33 -1
  233. package/src/dashboard/docs/settings-network.html +321 -0
  234. package/src/dashboard/docs/settings-security.html +347 -0
  235. package/src/dashboard/docs/settings-tool-security.html +176 -0
  236. package/src/dashboard/docs/settings.html +36 -16
  237. package/src/dashboard/pages/agent-detail/deployment.js +39 -6
  238. package/src/dashboard/pages/agent-detail/tools.js +10 -0
  239. package/src/dashboard/pages/database-access.js +4 -3
  240. package/src/dashboard/pages/settings.js +174 -37
  241. package/src/dashboard/pages/task-pipeline.js +400 -843
  242. package/src/database-access/agent-tools.ts +78 -63
  243. package/src/database-access/connection-manager.ts +13 -2
  244. package/src/database-access/routes.ts +13 -1
  245. package/src/db/adapter.ts +1 -0
  246. package/src/engine/agent-memory.ts +2 -1
  247. package/src/engine/agent-notify.ts +50 -0
  248. package/src/engine/agent-routes.ts +257 -4
  249. package/src/engine/db-adapter.ts +16 -0
  250. package/src/engine/lifecycle.ts +4 -0
  251. package/src/engine/routes.ts +4 -3
  252. package/src/engine/screen-unlock.ts +136 -0
  253. package/src/engine/skills/database-access.ts +78 -0
  254. package/src/engine/skills/index.ts +3 -2
  255. package/src/engine/skills.ts +2 -0
  256. package/src/engine/task-queue-routes.ts +18 -0
  257. package/src/engine/task-queue.ts +15 -2
  258. package/src/middleware/transport-encryption.ts +1 -4
  259. package/src/runtime/agent-loop.ts +4 -0
  260. package/src/runtime/index.ts +15 -6
  261. package/src/server.ts +14 -1
  262. package/src/system-prompts/google/index.ts +1 -2
  263. package/src/system-prompts/index.ts +1 -1
  264. package/src/system-prompts/microsoft/contacts.ts +34 -0
  265. package/src/system-prompts/microsoft/excel.ts +52 -0
  266. package/src/system-prompts/microsoft/index.ts +31 -0
  267. package/src/system-prompts/microsoft/onedrive.ts +41 -0
  268. package/src/system-prompts/microsoft/onenote.ts +36 -0
  269. package/src/system-prompts/microsoft/outlook-calendar.ts +37 -0
  270. package/src/system-prompts/microsoft/outlook-mail.ts +46 -0
  271. package/src/system-prompts/microsoft/planner.ts +37 -0
  272. package/src/system-prompts/microsoft/powerbi.ts +38 -0
  273. package/src/system-prompts/microsoft/powerpoint.ts +35 -0
  274. package/src/system-prompts/microsoft/sharepoint.ts +44 -0
  275. package/src/system-prompts/microsoft/teams.ts +49 -0
  276. package/src/system-prompts/microsoft/todo.ts +37 -0
  277. package/src/types/hono-env.ts +4 -0
  278. package/dist/agent-tools-LRA7PPXG.js +0 -13922
  279. package/dist/agent-tools-VAU5DOQB.js +0 -13910
  280. package/dist/agent-tools-VWV7OWXU.js +0 -13922
  281. package/dist/chunk-2Z7MWTCX.js +0 -4977
  282. package/dist/chunk-3T4XU3VV.js +0 -5010
  283. package/dist/chunk-445QM4NX.js +0 -5061
  284. package/dist/chunk-5TW3Y7DJ.js +0 -1519
  285. package/dist/chunk-6I7VY3LT.js +0 -5060
  286. package/dist/chunk-6W5EK3UP.js +0 -4977
  287. package/dist/chunk-AQMSHJQT.js +0 -5069
  288. package/dist/chunk-ASSQW7HX.js +0 -5051
  289. package/dist/chunk-CIN27FGC.js +0 -5037
  290. package/dist/chunk-CMXY3NUB.js +0 -4977
  291. package/dist/chunk-DRLMRUDP.js +0 -5052
  292. package/dist/chunk-EHI7Z446.js +0 -1519
  293. package/dist/chunk-FEAILFAQ.js +0 -1519
  294. package/dist/chunk-GA3PYBZL.js +0 -1519
  295. package/dist/chunk-GWX63G5J.js +0 -1519
  296. package/dist/chunk-HHMZ4UY6.js +0 -1519
  297. package/dist/chunk-HVQMNF7E.js +0 -4921
  298. package/dist/chunk-HXM7F3YN.js +0 -1519
  299. package/dist/chunk-K6NGOUXG.js +0 -5060
  300. package/dist/chunk-KPG5WINJ.js +0 -4977
  301. package/dist/chunk-LBCUBYDL.js +0 -1519
  302. package/dist/chunk-LIRQSWLR.js +0 -5014
  303. package/dist/chunk-LRCKO5KE.js +0 -1519
  304. package/dist/chunk-M7XL3DJD.js +0 -5069
  305. package/dist/chunk-MHJULEIQ.js +0 -1519
  306. package/dist/chunk-MJGGW6MC.js +0 -106
  307. package/dist/chunk-MMYBDHDB.js +0 -4921
  308. package/dist/chunk-MQT5FXKD.js +0 -1519
  309. package/dist/chunk-OIMPEQF5.js +0 -4977
  310. package/dist/chunk-OOU7JUYE.js +0 -542
  311. package/dist/chunk-OW4GLBHP.js +0 -1519
  312. package/dist/chunk-Q4K4MMLU.js +0 -4977
  313. package/dist/chunk-RUK4CRPF.js +0 -1519
  314. package/dist/chunk-T7H65XQY.js +0 -1519
  315. package/dist/chunk-TQVFWG57.js +0 -5064
  316. package/dist/chunk-UEPK3IMC.js +0 -1519
  317. package/dist/chunk-VUWTXJH6.js +0 -1519
  318. package/dist/chunk-WCPGGSAD.js +0 -1519
  319. package/dist/chunk-WO63NZOJ.js +0 -1519
  320. package/dist/chunk-YPJDRVUM.js +0 -5064
  321. package/dist/chunk-ZROMH5DL.js +0 -4921
@@ -0,0 +1,548 @@
1
+ import {
2
+ __esm
3
+ } from "./chunk-KFQGP6VL.js";
4
+
5
+ // src/engine/task-queue.ts
6
+ import { randomUUID } from "crypto";
7
+ function safeJson(v, fallback) {
8
+ if (!v || typeof v !== "string") return fallback;
9
+ try {
10
+ return JSON.parse(v);
11
+ } catch {
12
+ return fallback;
13
+ }
14
+ }
15
+ var TaskQueueManager;
16
+ var init_task_queue = __esm({
17
+ "src/engine/task-queue.ts"() {
18
+ TaskQueueManager = class {
19
+ tasks = /* @__PURE__ */ new Map();
20
+ listeners = /* @__PURE__ */ new Set();
21
+ db;
22
+ initialized = false;
23
+ constructor(db) {
24
+ this.db = db;
25
+ }
26
+ async init() {
27
+ if (this.initialized) return;
28
+ if (this.db) {
29
+ if (!this.db.all && this.db.query) this.db.all = this.db.query.bind(this.db);
30
+ if (!this.db.get && this.db.query) this.db.get = async (sql, params) => {
31
+ const rows = await this.db.query(sql, params);
32
+ return rows?.[0] ?? null;
33
+ };
34
+ try {
35
+ await this.db.run(`CREATE TABLE IF NOT EXISTS task_pipeline (
36
+ id TEXT PRIMARY KEY,
37
+ org_id TEXT NOT NULL,
38
+ assigned_to TEXT NOT NULL,
39
+ assigned_to_name TEXT NOT NULL DEFAULT '',
40
+ created_by TEXT NOT NULL DEFAULT 'system',
41
+ created_by_name TEXT NOT NULL DEFAULT '',
42
+ title TEXT NOT NULL,
43
+ description TEXT NOT NULL DEFAULT '',
44
+ category TEXT NOT NULL DEFAULT 'custom',
45
+ tags TEXT NOT NULL DEFAULT '[]',
46
+ status TEXT NOT NULL DEFAULT 'created',
47
+ priority TEXT NOT NULL DEFAULT 'normal',
48
+ progress INTEGER NOT NULL DEFAULT 0,
49
+ created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
50
+ assigned_at TEXT,
51
+ started_at TEXT,
52
+ completed_at TEXT,
53
+ estimated_duration_ms INTEGER,
54
+ actual_duration_ms INTEGER,
55
+ result TEXT,
56
+ error TEXT,
57
+ parent_task_id TEXT,
58
+ related_agent_ids TEXT NOT NULL DEFAULT '[]',
59
+ session_id TEXT,
60
+ model TEXT,
61
+ fallback_model TEXT,
62
+ model_used TEXT,
63
+ tokens_used INTEGER NOT NULL DEFAULT 0,
64
+ cost_usd REAL NOT NULL DEFAULT 0,
65
+ chain_id TEXT,
66
+ chain_seq INTEGER NOT NULL DEFAULT 0,
67
+ delegated_from TEXT,
68
+ delegated_to TEXT,
69
+ delegation_type TEXT,
70
+ customer_context TEXT,
71
+ activity_log TEXT NOT NULL DEFAULT '[]',
72
+ source TEXT
73
+ )`);
74
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_task_pipeline_org ON task_pipeline(org_id)`);
75
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_task_pipeline_agent ON task_pipeline(assigned_to)`);
76
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_task_pipeline_status ON task_pipeline(status)`);
77
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_task_pipeline_created ON task_pipeline(created_at)`);
78
+ for (const col of [
79
+ ["chain_id", "TEXT"],
80
+ ["chain_seq", "INTEGER DEFAULT 0"],
81
+ ["delegated_from", "TEXT"],
82
+ ["delegated_to", "TEXT"],
83
+ ["delegation_type", "TEXT"],
84
+ ["customer_context", "TEXT"],
85
+ ["activity_log", "TEXT DEFAULT '[]'"],
86
+ ["source", "TEXT"],
87
+ ["delivery_context", "TEXT"]
88
+ ]) {
89
+ try {
90
+ await this.db.run(`ALTER TABLE task_pipeline ADD COLUMN ${col[0]} ${col[1]}`);
91
+ } catch {
92
+ }
93
+ }
94
+ try {
95
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_task_pipeline_chain ON task_pipeline(chain_id)`);
96
+ } catch {
97
+ }
98
+ const cutoff = new Date(Date.now() - 24 * 60 * 60 * 1e3).toISOString();
99
+ const rows = await this.db.all(`SELECT * FROM task_pipeline WHERE status IN ('created','assigned','in_progress') OR created_at > ? ORDER BY created_at DESC LIMIT 500`, [cutoff]);
100
+ for (const row of rows || []) {
101
+ this.tasks.set(row.id, this.rowToTask(row));
102
+ }
103
+ } catch (e) {
104
+ console.error("[TaskQueue] DB init error:", e.message);
105
+ }
106
+ }
107
+ this.initialized = true;
108
+ }
109
+ /**
110
+ * Sync active tasks from database into memory.
111
+ * Called by the task poller before each cycle to catch externally-added or reset tasks.
112
+ */
113
+ async syncFromDb() {
114
+ if (!this.db) return;
115
+ try {
116
+ const rows = await this.db.all(
117
+ `SELECT * FROM task_pipeline WHERE status IN ('created','assigned','in_progress') ORDER BY created_at DESC LIMIT 200`
118
+ );
119
+ if (!rows) return;
120
+ let added = 0;
121
+ for (const row of rows) {
122
+ const existing = this.tasks.get(row.id);
123
+ const dbTask = this.rowToTask(row);
124
+ if (!existing) {
125
+ this.tasks.set(row.id, dbTask);
126
+ added++;
127
+ } else if (existing.status !== dbTask.status || existing.sessionId !== dbTask.sessionId) {
128
+ this.tasks.set(row.id, dbTask);
129
+ }
130
+ }
131
+ if (added > 0) console.log(`[TaskQueue] syncFromDb: added ${added} tasks from DB`);
132
+ } catch (e) {
133
+ console.error("[TaskQueue] syncFromDb error:", e.message);
134
+ }
135
+ }
136
+ // ─── CRUD ─────────────────────────────────────────────
137
+ async createTask(opts) {
138
+ await this.init();
139
+ const now = (/* @__PURE__ */ new Date()).toISOString();
140
+ const task = {
141
+ id: randomUUID(),
142
+ orgId: opts.orgId,
143
+ assignedTo: opts.assignedTo,
144
+ assignedToName: opts.assignedToName,
145
+ createdBy: opts.createdBy || "system",
146
+ createdByName: opts.createdByName || "System",
147
+ title: opts.title,
148
+ description: opts.description || "",
149
+ category: opts.category || "custom",
150
+ tags: opts.tags || [],
151
+ status: "created",
152
+ priority: opts.priority || "normal",
153
+ progress: 0,
154
+ createdAt: now,
155
+ assignedAt: null,
156
+ startedAt: null,
157
+ completedAt: null,
158
+ estimatedDurationMs: opts.estimatedDurationMs || null,
159
+ actualDurationMs: null,
160
+ result: null,
161
+ error: null,
162
+ parentTaskId: opts.parentTaskId || null,
163
+ relatedAgentIds: opts.relatedAgentIds || [],
164
+ sessionId: opts.sessionId || null,
165
+ model: opts.model || null,
166
+ fallbackModel: opts.fallbackModel || null,
167
+ modelUsed: null,
168
+ tokensUsed: 0,
169
+ costUsd: 0,
170
+ chainId: opts.chainId || randomUUID(),
171
+ chainSeq: opts.chainSeq || 0,
172
+ delegatedFrom: opts.delegatedFrom || null,
173
+ delegatedTo: null,
174
+ delegationType: opts.delegationType || null,
175
+ customerContext: opts.customerContext || null,
176
+ source: opts.source || null,
177
+ deliveryContext: opts.deliveryContext || null,
178
+ activityLog: [{ ts: now, type: "created", agent: opts.createdBy || "system", detail: "Task created" }]
179
+ };
180
+ this.tasks.set(task.id, task);
181
+ await this.persist(task);
182
+ this.emit({ type: "task_created", task, timestamp: now });
183
+ return task;
184
+ }
185
+ /**
186
+ * Delegate a task from one agent to another, creating a new linked task in the chain.
187
+ */
188
+ async delegateTask(taskId, opts) {
189
+ const source = this.tasks.get(taskId);
190
+ if (!source) return null;
191
+ const now = (/* @__PURE__ */ new Date()).toISOString();
192
+ source.activityLog.push({ ts: now, type: "delegated", agent: source.assignedTo, detail: `Delegated to ${opts.toAgentName} (${opts.delegationType || "delegation"})` });
193
+ const delegated = await this.createTask({
194
+ orgId: source.orgId,
195
+ assignedTo: opts.toAgent,
196
+ assignedToName: opts.toAgentName,
197
+ createdBy: source.assignedTo,
198
+ createdByName: source.assignedToName,
199
+ title: opts.title || source.title,
200
+ description: opts.description || source.description,
201
+ category: source.category,
202
+ tags: [...source.tags],
203
+ priority: opts.priority || source.priority,
204
+ parentTaskId: source.parentTaskId || void 0,
205
+ relatedAgentIds: [.../* @__PURE__ */ new Set([...source.relatedAgentIds, source.assignedTo])],
206
+ chainId: source.chainId || void 0,
207
+ chainSeq: (source.chainSeq || 0) + 1,
208
+ delegatedFrom: source.id,
209
+ delegationType: opts.delegationType || "delegation",
210
+ customerContext: source.customerContext,
211
+ deliveryContext: source.deliveryContext
212
+ });
213
+ source.delegatedTo = delegated.id;
214
+ await this.persist(source);
215
+ this.emit({ type: "task_updated", task: source, timestamp: now });
216
+ return delegated;
217
+ }
218
+ /**
219
+ * Get full task chain by chainId — all tasks in a delegation flow.
220
+ */
221
+ getTaskChain(chainId) {
222
+ const chain = [];
223
+ for (const t of this.tasks.values()) {
224
+ if (t.chainId === chainId) chain.push(t);
225
+ }
226
+ return chain.sort((a, b) => (a.chainSeq || 0) - (b.chainSeq || 0));
227
+ }
228
+ async updateTask(taskId, updates) {
229
+ await this.init();
230
+ const task = this.tasks.get(taskId);
231
+ if (!task) return null;
232
+ const now = (/* @__PURE__ */ new Date()).toISOString();
233
+ if (updates.status === "assigned" && !task.assignedAt) {
234
+ task.assignedAt = now;
235
+ task.activityLog.push({ ts: now, type: "assigned", agent: task.assignedTo, detail: "Task assigned" });
236
+ }
237
+ if (updates.status === "in_progress" && !task.startedAt) {
238
+ task.startedAt = now;
239
+ task.activityLog.push({ ts: now, type: "started", agent: task.assignedTo, detail: "Work started" });
240
+ }
241
+ if (updates.progress !== void 0 && updates.progress !== task.progress) {
242
+ task.activityLog.push({ ts: now, type: "progress", agent: task.assignedTo, detail: `Progress: ${updates.progress}%` });
243
+ }
244
+ if (updates.status === "completed" || updates.status === "failed" || updates.status === "cancelled") {
245
+ task.completedAt = now;
246
+ if (task.startedAt) task.actualDurationMs = new Date(now).getTime() - new Date(task.startedAt).getTime();
247
+ if (updates.status === "completed") {
248
+ task.progress = 100;
249
+ const dur = task.actualDurationMs ? ` in ${Math.round(task.actualDurationMs / 1e3)}s` : "";
250
+ const tokens = updates.tokensUsed ? ` (${updates.tokensUsed.toLocaleString()} tokens` + (updates.costUsd ? `, $${updates.costUsd.toFixed(4)}` : "") + ")" : "";
251
+ task.activityLog.push({ ts: now, type: "completed", agent: task.assignedTo, detail: `Task completed${dur}${tokens}` });
252
+ }
253
+ if (updates.status === "failed") {
254
+ task.activityLog.push({ ts: now, type: "failed", agent: task.assignedTo, detail: `Task failed: ${updates.error || "Unknown error"}` });
255
+ }
256
+ if (updates.status === "cancelled") {
257
+ task.activityLog.push({ ts: now, type: "cancelled", agent: task.assignedTo, detail: "Task cancelled" });
258
+ }
259
+ }
260
+ Object.assign(task, updates);
261
+ await this.persist(task);
262
+ const eventType = updates.status === "completed" ? "task_completed" : updates.status === "failed" ? "task_failed" : updates.status === "cancelled" ? "task_cancelled" : updates.progress !== void 0 ? "task_progress" : "task_updated";
263
+ this.emit({ type: eventType, task, timestamp: now });
264
+ return task;
265
+ }
266
+ getTask(taskId) {
267
+ return this.tasks.get(taskId);
268
+ }
269
+ // ─── Queries ──────────────────────────────────────────
270
+ getActiveTasks(orgId) {
271
+ const active = [];
272
+ for (const t of this.tasks.values()) {
273
+ if (t.status === "created" || t.status === "assigned" || t.status === "in_progress") {
274
+ if (!orgId || t.orgId === orgId) active.push(t);
275
+ }
276
+ }
277
+ return active.sort((a, b) => {
278
+ const pri = { urgent: 0, high: 1, normal: 2, low: 3 };
279
+ return pri[a.priority] - pri[b.priority] || new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
280
+ });
281
+ }
282
+ getAllTasks(orgId, limit = 100) {
283
+ const all = [];
284
+ for (const t of this.tasks.values()) {
285
+ if (!orgId || t.orgId === orgId) all.push(t);
286
+ }
287
+ return all.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()).slice(0, limit);
288
+ }
289
+ getAgentTasks(agentId, includeCompleted = false) {
290
+ const res = [];
291
+ for (const t of this.tasks.values()) {
292
+ if (t.assignedTo === agentId) {
293
+ if (includeCompleted || t.status === "created" || t.status === "assigned" || t.status === "in_progress") {
294
+ res.push(t);
295
+ }
296
+ }
297
+ }
298
+ return res.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
299
+ }
300
+ async getTaskBySessionId(sessionId) {
301
+ if (this.db) {
302
+ try {
303
+ const row = await this.db.get(
304
+ `SELECT * FROM task_pipeline WHERE session_id = ? AND status = 'in_progress' ORDER BY created_at DESC LIMIT 1`,
305
+ [sessionId]
306
+ );
307
+ return row ? this.rowToTask(row) : null;
308
+ } catch {
309
+ }
310
+ }
311
+ for (const task of this.tasks.values()) {
312
+ if (task.sessionId === sessionId && task.status === "in_progress") return task;
313
+ }
314
+ return null;
315
+ }
316
+ async getTaskHistory(orgId, limit = 50, offset = 0) {
317
+ if (this.db) {
318
+ try {
319
+ const rows = await this.db.all(
320
+ `SELECT * FROM task_pipeline WHERE org_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?`,
321
+ [orgId, limit, offset]
322
+ );
323
+ return (rows || []).map((r) => this.rowToTask(r));
324
+ } catch {
325
+ }
326
+ }
327
+ return this.getAllTasks(orgId, limit);
328
+ }
329
+ async getPipelineStats(orgId) {
330
+ const stats = {
331
+ created: 0,
332
+ assigned: 0,
333
+ inProgress: 0,
334
+ completed: 0,
335
+ failed: 0,
336
+ cancelled: 0,
337
+ total: 0,
338
+ todayCompleted: 0,
339
+ todayFailed: 0,
340
+ todayCreated: 0,
341
+ avgDurationMs: 0,
342
+ totalCost: 0,
343
+ totalTokens: 0,
344
+ topAgents: []
345
+ };
346
+ const todayStart = /* @__PURE__ */ new Date();
347
+ todayStart.setHours(0, 0, 0, 0);
348
+ const todayMs = todayStart.getTime();
349
+ let durationSum = 0;
350
+ let durationCount = 0;
351
+ const agentMap = /* @__PURE__ */ new Map();
352
+ for (const t of this.tasks.values()) {
353
+ if (orgId && t.orgId !== orgId) continue;
354
+ stats.total++;
355
+ if (t.status === "created") stats.created++;
356
+ else if (t.status === "assigned") stats.assigned++;
357
+ else if (t.status === "in_progress") stats.inProgress++;
358
+ else if (t.status === "completed") stats.completed++;
359
+ else if (t.status === "failed") stats.failed++;
360
+ else if (t.status === "cancelled") stats.cancelled++;
361
+ const createdMs = new Date(t.createdAt).getTime();
362
+ if (createdMs >= todayMs) stats.todayCreated++;
363
+ if (t.completedAt && new Date(t.completedAt).getTime() >= todayMs) {
364
+ if (t.status === "completed") stats.todayCompleted++;
365
+ if (t.status === "failed") stats.todayFailed++;
366
+ }
367
+ if (t.actualDurationMs) {
368
+ durationSum += t.actualDurationMs;
369
+ durationCount++;
370
+ }
371
+ stats.totalCost += t.costUsd || 0;
372
+ stats.totalTokens += t.tokensUsed || 0;
373
+ if (t.assignedTo) {
374
+ if (!agentMap.has(t.assignedTo)) agentMap.set(t.assignedTo, { name: t.assignedToName || t.assignedTo, completed: 0, active: 0 });
375
+ const a = agentMap.get(t.assignedTo);
376
+ if (t.status === "completed") a.completed++;
377
+ if (t.status === "in_progress" || t.status === "assigned") a.active++;
378
+ }
379
+ }
380
+ stats.avgDurationMs = durationCount > 0 ? Math.round(durationSum / durationCount) : 0;
381
+ stats.topAgents = Array.from(agentMap.entries()).map(([agent, d]) => ({ agent, ...d })).sort((a, b) => b.completed + b.active - (a.completed + a.active)).slice(0, 5);
382
+ if (this.db) {
383
+ try {
384
+ const todayISO = todayStart.toISOString();
385
+ const dbToday = await this.db.get(
386
+ `SELECT COUNT(*) FILTER (WHERE status='completed' AND completed_at >= ?) as dc,
387
+ COUNT(*) FILTER (WHERE status='failed' AND completed_at >= ?) as df,
388
+ COUNT(*) FILTER (WHERE created_at >= ?) as dn
389
+ FROM task_pipeline` + (orgId ? ` WHERE org_id = ?` : ""),
390
+ orgId ? [todayISO, todayISO, todayISO, orgId] : [todayISO, todayISO, todayISO]
391
+ ).catch(() => null);
392
+ if (!dbToday || dbToday.dc === void 0) {
393
+ const r1 = await this.db.get(`SELECT COUNT(*) as c FROM task_pipeline WHERE status='completed' AND completed_at >= ?`, [todayISO]).catch(() => null);
394
+ const r2 = await this.db.get(`SELECT COUNT(*) as c FROM task_pipeline WHERE status='failed' AND completed_at >= ?`, [todayISO]).catch(() => null);
395
+ const r3 = await this.db.get(`SELECT COUNT(*) as c FROM task_pipeline WHERE created_at >= ?`, [todayISO]).catch(() => null);
396
+ if (r1?.c > stats.todayCompleted) stats.todayCompleted = r1.c;
397
+ if (r2?.c > stats.todayFailed) stats.todayFailed = r2.c;
398
+ if (r3?.c > stats.todayCreated) stats.todayCreated = r3.c;
399
+ } else {
400
+ if (dbToday.dc > stats.todayCompleted) stats.todayCompleted = dbToday.dc;
401
+ if (dbToday.df > stats.todayFailed) stats.todayFailed = dbToday.df;
402
+ if (dbToday.dn > stats.todayCreated) stats.todayCreated = dbToday.dn;
403
+ }
404
+ } catch {
405
+ }
406
+ }
407
+ return stats;
408
+ }
409
+ // ─── SSE Subscriptions ────────────────────────────────
410
+ subscribe(listener) {
411
+ this.listeners.add(listener);
412
+ return () => {
413
+ this.listeners.delete(listener);
414
+ };
415
+ }
416
+ /** URL to notify when tasks change (for standalone agents → enterprise SSE relay) */
417
+ webhookUrl = null;
418
+ emit(event) {
419
+ for (const l of this.listeners) {
420
+ try {
421
+ l(event);
422
+ } catch {
423
+ }
424
+ }
425
+ if (this.webhookUrl) {
426
+ fetch(this.webhookUrl, {
427
+ method: "POST",
428
+ headers: { "Content-Type": "application/json" },
429
+ body: JSON.stringify(event),
430
+ signal: AbortSignal.timeout(3e3)
431
+ }).catch(() => {
432
+ });
433
+ }
434
+ }
435
+ // ─── Persistence ──────────────────────────────────────
436
+ async persist(task) {
437
+ if (!this.db) return;
438
+ try {
439
+ await this.db.run(`INSERT INTO task_pipeline (
440
+ id, org_id, assigned_to, assigned_to_name, created_by, created_by_name,
441
+ title, description, category, tags, status, priority, progress,
442
+ created_at, assigned_at, started_at, completed_at,
443
+ estimated_duration_ms, actual_duration_ms, result, error,
444
+ parent_task_id, related_agent_ids, session_id,
445
+ model, fallback_model, model_used, tokens_used, cost_usd,
446
+ chain_id, chain_seq, delegated_from, delegated_to, delegation_type,
447
+ customer_context, activity_log, source, delivery_context
448
+ ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
449
+ ON CONFLICT (id) DO UPDATE SET
450
+ status=EXCLUDED.status, priority=EXCLUDED.priority, progress=EXCLUDED.progress,
451
+ assigned_at=EXCLUDED.assigned_at, started_at=EXCLUDED.started_at, completed_at=EXCLUDED.completed_at,
452
+ actual_duration_ms=EXCLUDED.actual_duration_ms, result=EXCLUDED.result, error=EXCLUDED.error,
453
+ model_used=EXCLUDED.model_used, tokens_used=EXCLUDED.tokens_used, cost_usd=EXCLUDED.cost_usd,
454
+ session_id=EXCLUDED.session_id, title=EXCLUDED.title, description=EXCLUDED.description,
455
+ delegated_to=EXCLUDED.delegated_to, activity_log=EXCLUDED.activity_log`, [
456
+ task.id,
457
+ task.orgId,
458
+ task.assignedTo,
459
+ task.assignedToName,
460
+ task.createdBy,
461
+ task.createdByName,
462
+ task.title,
463
+ task.description,
464
+ task.category,
465
+ JSON.stringify(task.tags),
466
+ task.status,
467
+ task.priority,
468
+ task.progress,
469
+ task.createdAt,
470
+ task.assignedAt,
471
+ task.startedAt,
472
+ task.completedAt,
473
+ task.estimatedDurationMs,
474
+ task.actualDurationMs,
475
+ task.result ? JSON.stringify(task.result) : null,
476
+ task.error,
477
+ task.parentTaskId,
478
+ JSON.stringify(task.relatedAgentIds),
479
+ task.sessionId,
480
+ task.model,
481
+ task.fallbackModel,
482
+ task.modelUsed,
483
+ task.tokensUsed,
484
+ task.costUsd,
485
+ task.chainId,
486
+ task.chainSeq,
487
+ task.delegatedFrom,
488
+ task.delegatedTo,
489
+ task.delegationType,
490
+ task.customerContext ? JSON.stringify(task.customerContext) : null,
491
+ JSON.stringify(task.activityLog || []),
492
+ task.source,
493
+ task.deliveryContext ? JSON.stringify(task.deliveryContext) : null
494
+ ]);
495
+ } catch (e) {
496
+ console.error("[TaskQueue] persist error:", e.message);
497
+ }
498
+ }
499
+ rowToTask(row) {
500
+ return {
501
+ id: row.id,
502
+ orgId: row.org_id,
503
+ assignedTo: row.assigned_to,
504
+ assignedToName: row.assigned_to_name || "",
505
+ createdBy: row.created_by || "system",
506
+ createdByName: row.created_by_name || "",
507
+ title: row.title,
508
+ description: row.description || "",
509
+ category: row.category || "custom",
510
+ tags: safeJson(row.tags, []),
511
+ status: row.status,
512
+ priority: row.priority || "normal",
513
+ progress: row.progress || 0,
514
+ createdAt: row.created_at,
515
+ assignedAt: row.assigned_at || null,
516
+ startedAt: row.started_at || null,
517
+ completedAt: row.completed_at || null,
518
+ estimatedDurationMs: row.estimated_duration_ms || null,
519
+ actualDurationMs: row.actual_duration_ms || null,
520
+ result: safeJson(row.result, null),
521
+ error: row.error || null,
522
+ parentTaskId: row.parent_task_id || null,
523
+ relatedAgentIds: safeJson(row.related_agent_ids, []),
524
+ sessionId: row.session_id || null,
525
+ model: row.model || null,
526
+ fallbackModel: row.fallback_model || null,
527
+ modelUsed: row.model_used || null,
528
+ tokensUsed: row.tokens_used || 0,
529
+ costUsd: row.cost_usd || 0,
530
+ chainId: row.chain_id || null,
531
+ chainSeq: row.chain_seq || 0,
532
+ delegatedFrom: row.delegated_from || null,
533
+ delegatedTo: row.delegated_to || null,
534
+ delegationType: row.delegation_type || null,
535
+ customerContext: safeJson(row.customer_context, null),
536
+ source: row.source || null,
537
+ deliveryContext: safeJson(row.delivery_context, null),
538
+ activityLog: safeJson(row.activity_log, [])
539
+ };
540
+ }
541
+ };
542
+ }
543
+ });
544
+
545
+ export {
546
+ TaskQueueManager,
547
+ init_task_queue
548
+ };