agent-relay 1.3.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (318) hide show
  1. package/README.md +130 -158
  2. package/bin/relay-pty +0 -0
  3. package/bin/relay-pty-darwin-arm64 +0 -0
  4. package/bin/relay-pty-darwin-x64 +0 -0
  5. package/bin/relay-pty-linux-x64 +0 -0
  6. package/deploy/workspace/entrypoint.sh +9 -0
  7. package/dist/bridge/spawner.d.ts +4 -4
  8. package/dist/bridge/spawner.js +58 -92
  9. package/dist/cli/index.d.ts +8 -6
  10. package/dist/cli/index.js +282 -47
  11. package/dist/cloud/api/daemons.js +13 -32
  12. package/dist/cloud/api/onboarding.js +2 -4
  13. package/dist/cloud/api/providers.js +6 -0
  14. package/dist/cloud/config.d.ts +1 -0
  15. package/dist/cloud/config.js +2 -0
  16. package/dist/cloud/db/bulk-ingest.d.ts +2 -1
  17. package/dist/cloud/db/drizzle.d.ts +21 -26
  18. package/dist/cloud/db/drizzle.js +87 -100
  19. package/dist/cloud/db/index.d.ts +6 -5
  20. package/dist/cloud/db/index.js +9 -8
  21. package/dist/cloud/db/schema.d.ts +1049 -1076
  22. package/dist/cloud/db/schema.js +59 -71
  23. package/dist/cloud/server.js +854 -18
  24. package/dist/cloud/services/persistence.d.ts +15 -15
  25. package/dist/cloud/services/persistence.js +14 -14
  26. package/dist/daemon/agent-manager.d.ts +6 -5
  27. package/dist/daemon/agent-manager.js +12 -8
  28. package/dist/daemon/channel-membership-store.d.ts +48 -0
  29. package/dist/daemon/channel-membership-store.js +149 -0
  30. package/dist/daemon/cloud-sync.d.ts +2 -0
  31. package/dist/daemon/cloud-sync.js +4 -0
  32. package/dist/daemon/connection.js +17 -9
  33. package/dist/daemon/router.d.ts +37 -0
  34. package/dist/daemon/router.js +318 -79
  35. package/dist/daemon/server.d.ts +15 -0
  36. package/dist/daemon/server.js +141 -3
  37. package/dist/dashboard/out/404.html +1 -0
  38. package/dist/dashboard/out/_next/static/IxxVRv94L1w3ReRGAiI-k/_buildManifest.js +1 -0
  39. package/dist/dashboard/out/_next/static/IxxVRv94L1w3ReRGAiI-k/_ssgManifest.js +1 -0
  40. package/dist/dashboard/out/_next/static/chunks/116-eacf84a131b80db9.js +1 -0
  41. package/dist/dashboard/out/_next/static/chunks/117-c8afed19e821a35d.js +2 -0
  42. package/dist/dashboard/out/_next/static/chunks/282-980c2eb8fff20123.js +1 -0
  43. package/dist/dashboard/out/_next/static/chunks/532-bace199897eeab37.js +9 -0
  44. package/dist/dashboard/out/_next/static/chunks/64-87ab9cd6bcf2f737.js +1 -0
  45. package/dist/dashboard/out/_next/static/chunks/648-acb2ff9f77cbfbd3.js +1 -0
  46. package/dist/dashboard/out/_next/static/chunks/766-aa7c8c9900ff5f53.js +1 -0
  47. package/dist/dashboard/out/_next/static/chunks/83-4f08122d4e7e79a6.js +1 -0
  48. package/dist/dashboard/out/_next/static/chunks/847-f1f467060f32afff.js +1 -0
  49. package/dist/dashboard/out/_next/static/chunks/891-a024fbe4b619cf6f.js +1 -0
  50. package/dist/dashboard/out/_next/static/chunks/app/_not-found/page-60501fddbafba9dc.js +1 -0
  51. package/dist/dashboard/out/_next/static/chunks/app/app/onboarding/page-f746f29e01fffc43.js +1 -0
  52. package/dist/dashboard/out/_next/static/chunks/app/app/page-ffad986adfcc8b31.js +1 -0
  53. package/dist/dashboard/out/_next/static/chunks/app/cloud/link/page-cfeb437f08a12ed9.js +1 -0
  54. package/dist/dashboard/out/_next/static/chunks/app/connect-repos/page-03ac6f35a6654ea6.js +1 -0
  55. package/dist/dashboard/out/_next/static/chunks/app/history/page-240f91e8b06ba8ac.js +1 -0
  56. package/dist/dashboard/out/_next/static/chunks/app/layout-c0d118c0f92d969c.js +1 -0
  57. package/dist/dashboard/out/_next/static/chunks/app/login/page-6ec54eee75877971.js +1 -0
  58. package/dist/dashboard/out/_next/static/chunks/app/metrics/page-82938ab8fcf44694.js +1 -0
  59. package/dist/dashboard/out/_next/static/chunks/app/page-671037943b2f2e43.js +1 -0
  60. package/dist/dashboard/out/_next/static/chunks/app/pricing/page-0efa024c28ba4597.js +1 -0
  61. package/dist/dashboard/out/_next/static/chunks/app/providers/page-57cbd738c6a73859.js +1 -0
  62. package/dist/dashboard/out/_next/static/chunks/app/providers/setup/[provider]/page-5ab0854472b402b0.js +1 -0
  63. package/dist/dashboard/out/_next/static/chunks/app/signup/page-18a4665665f6be11.js +1 -0
  64. package/dist/dashboard/out/_next/static/chunks/e868780c-48e5f147c90a3a41.js +18 -0
  65. package/dist/dashboard/out/_next/static/chunks/fd9d1056-609918ca7b6280bb.js +1 -0
  66. package/dist/dashboard/out/_next/static/chunks/framework-f66176bb897dc684.js +1 -0
  67. package/dist/dashboard/out/_next/static/chunks/main-5a40a5ae29646e1b.js +1 -0
  68. package/dist/dashboard/out/_next/static/chunks/main-app-6e8e8d3ef4e0192a.js +1 -0
  69. package/dist/dashboard/out/_next/static/chunks/pages/_app-72b849fbd24ac258.js +1 -0
  70. package/dist/dashboard/out/_next/static/chunks/pages/_error-7ba65e1336b92748.js +1 -0
  71. package/dist/dashboard/out/_next/static/chunks/polyfills-42372ed130431b0a.js +1 -0
  72. package/dist/dashboard/out/_next/static/chunks/webpack-1cdd8ed57114d5e1.js +1 -0
  73. package/dist/dashboard/out/_next/static/css/4034f236dd1a3178.css +1 -0
  74. package/dist/dashboard/out/_next/static/css/8f9ed310f454e5a5.css +1 -0
  75. package/dist/dashboard/out/alt-logos/agent-relay-logo-128.png +0 -0
  76. package/dist/dashboard/out/alt-logos/agent-relay-logo-256.png +0 -0
  77. package/dist/dashboard/out/alt-logos/agent-relay-logo-32.png +0 -0
  78. package/dist/dashboard/out/alt-logos/agent-relay-logo-512.png +0 -0
  79. package/dist/dashboard/out/alt-logos/agent-relay-logo-64.png +0 -0
  80. package/dist/dashboard/out/alt-logos/agent-relay-logo.svg +45 -0
  81. package/dist/dashboard/out/alt-logos/logo.svg +38 -0
  82. package/dist/dashboard/out/alt-logos/monogram-logo-128.png +0 -0
  83. package/dist/dashboard/out/alt-logos/monogram-logo-256.png +0 -0
  84. package/dist/dashboard/out/alt-logos/monogram-logo-32.png +0 -0
  85. package/dist/dashboard/out/alt-logos/monogram-logo-512.png +0 -0
  86. package/dist/dashboard/out/alt-logos/monogram-logo-64.png +0 -0
  87. package/dist/dashboard/out/alt-logos/monogram-logo.svg +38 -0
  88. package/dist/dashboard/out/app/onboarding.html +1 -0
  89. package/dist/dashboard/out/app/onboarding.txt +7 -0
  90. package/dist/dashboard/out/app.html +1 -0
  91. package/dist/dashboard/out/app.txt +7 -0
  92. package/dist/dashboard/out/apple-icon.png +0 -0
  93. package/dist/dashboard/out/cloud/link.html +1 -0
  94. package/dist/dashboard/out/cloud/link.txt +7 -0
  95. package/dist/dashboard/out/connect-repos.html +1 -0
  96. package/dist/dashboard/out/connect-repos.txt +7 -0
  97. package/dist/dashboard/out/history.html +1 -0
  98. package/dist/dashboard/out/history.txt +7 -0
  99. package/dist/dashboard/out/index.html +1 -0
  100. package/dist/dashboard/out/index.txt +7 -0
  101. package/dist/dashboard/out/login.html +5 -0
  102. package/dist/dashboard/out/login.txt +7 -0
  103. package/dist/dashboard/out/metrics.html +1 -0
  104. package/dist/dashboard/out/metrics.txt +7 -0
  105. package/dist/dashboard/out/pricing.html +13 -0
  106. package/dist/dashboard/out/pricing.txt +7 -0
  107. package/dist/dashboard/out/providers/setup/claude.html +1 -0
  108. package/dist/dashboard/out/providers/setup/claude.txt +8 -0
  109. package/dist/dashboard/out/providers/setup/codex.html +1 -0
  110. package/dist/dashboard/out/providers/setup/codex.txt +8 -0
  111. package/dist/dashboard/out/providers.html +1 -0
  112. package/dist/dashboard/out/providers.txt +7 -0
  113. package/dist/dashboard/out/signup.html +6 -0
  114. package/dist/dashboard/out/signup.txt +7 -0
  115. package/dist/dashboard-server/metrics.d.ts +105 -0
  116. package/dist/dashboard-server/metrics.js +193 -0
  117. package/dist/dashboard-server/needs-attention.d.ts +24 -0
  118. package/dist/dashboard-server/needs-attention.js +78 -0
  119. package/dist/dashboard-server/server.d.ts +15 -0
  120. package/dist/dashboard-server/server.js +4753 -0
  121. package/dist/dashboard-server/start.d.ts +6 -0
  122. package/dist/dashboard-server/start.js +13 -0
  123. package/dist/dashboard-server/user-bridge.d.ts +132 -0
  124. package/dist/dashboard-server/user-bridge.js +317 -0
  125. package/dist/protocol/channels.d.ts +14 -8
  126. package/dist/protocol/channels.js +1 -1
  127. package/dist/protocol/index.d.ts +1 -0
  128. package/dist/protocol/index.js +1 -0
  129. package/dist/protocol/relay-pty-schemas.d.ts +209 -0
  130. package/dist/protocol/relay-pty-schemas.js +60 -0
  131. package/dist/wrapper/auth-detection.js +8 -1
  132. package/dist/wrapper/base-wrapper.d.ts +11 -1
  133. package/dist/wrapper/base-wrapper.js +67 -6
  134. package/dist/wrapper/client.d.ts +49 -1
  135. package/dist/wrapper/client.js +167 -0
  136. package/dist/wrapper/parser.d.ts +0 -4
  137. package/dist/wrapper/parser.js +38 -10
  138. package/dist/wrapper/pty-wrapper.d.ts +12 -1
  139. package/dist/wrapper/pty-wrapper.js +104 -5
  140. package/dist/wrapper/relay-pty-orchestrator.d.ts +270 -0
  141. package/dist/wrapper/relay-pty-orchestrator.js +970 -0
  142. package/dist/wrapper/shared.d.ts +1 -1
  143. package/dist/wrapper/shared.js +14 -4
  144. package/dist/wrapper/tmux-wrapper.d.ts +13 -1
  145. package/dist/wrapper/tmux-wrapper.js +143 -29
  146. package/package.json +9 -4
  147. package/scripts/postinstall.js +101 -11
  148. package/.trajectories/active/traj_3yx9dy148mge.json +0 -42
  149. package/.trajectories/agent-relay-322-324.md +0 -17
  150. package/.trajectories/completed/2026-01/traj_03zupyv1s7b9.json +0 -49
  151. package/.trajectories/completed/2026-01/traj_03zupyv1s7b9.md +0 -31
  152. package/.trajectories/completed/2026-01/traj_0zacdjl1g4ht.json +0 -125
  153. package/.trajectories/completed/2026-01/traj_0zacdjl1g4ht.md +0 -62
  154. package/.trajectories/completed/2026-01/traj_1dviorhnkcb5.json +0 -65
  155. package/.trajectories/completed/2026-01/traj_1dviorhnkcb5.md +0 -37
  156. package/.trajectories/completed/2026-01/traj_1g7yx6qtg4ai.json +0 -49
  157. package/.trajectories/completed/2026-01/traj_1g7yx6qtg4ai.md +0 -31
  158. package/.trajectories/completed/2026-01/traj_1k5if5snst2e.json +0 -65
  159. package/.trajectories/completed/2026-01/traj_1k5if5snst2e.md +0 -37
  160. package/.trajectories/completed/2026-01/traj_1rp3rges5811.json +0 -49
  161. package/.trajectories/completed/2026-01/traj_1rp3rges5811.md +0 -31
  162. package/.trajectories/completed/2026-01/traj_22bhyulruouw.json +0 -113
  163. package/.trajectories/completed/2026-01/traj_22bhyulruouw.md +0 -57
  164. package/.trajectories/completed/2026-01/traj_2dao7ddgnta0.json +0 -53
  165. package/.trajectories/completed/2026-01/traj_2dao7ddgnta0.md +0 -32
  166. package/.trajectories/completed/2026-01/traj_33iuy72sezbk.json +0 -49
  167. package/.trajectories/completed/2026-01/traj_33iuy72sezbk.md +0 -31
  168. package/.trajectories/completed/2026-01/traj_3t0440mjeunc.json +0 -26
  169. package/.trajectories/completed/2026-01/traj_3t0440mjeunc.md +0 -6
  170. package/.trajectories/completed/2026-01/traj_45x9494d9xnr.json +0 -47
  171. package/.trajectories/completed/2026-01/traj_45x9494d9xnr.md +0 -32
  172. package/.trajectories/completed/2026-01/traj_4aa0bb77s4nh.json +0 -53
  173. package/.trajectories/completed/2026-01/traj_4aa0bb77s4nh.md +0 -32
  174. package/.trajectories/completed/2026-01/traj_4qwd4zmhfwp4.json +0 -49
  175. package/.trajectories/completed/2026-01/traj_4qwd4zmhfwp4.md +0 -31
  176. package/.trajectories/completed/2026-01/traj_5ammh5qtvklq.json +0 -77
  177. package/.trajectories/completed/2026-01/traj_5ammh5qtvklq.md +0 -42
  178. package/.trajectories/completed/2026-01/traj_5lhmzq8rxpqv.json +0 -59
  179. package/.trajectories/completed/2026-01/traj_5lhmzq8rxpqv.md +0 -33
  180. package/.trajectories/completed/2026-01/traj_5vr4e9erb1fs.json +0 -53
  181. package/.trajectories/completed/2026-01/traj_5vr4e9erb1fs.md +0 -32
  182. package/.trajectories/completed/2026-01/traj_6fgiwdoklvym.json +0 -48
  183. package/.trajectories/completed/2026-01/traj_6fgiwdoklvym.md +0 -24
  184. package/.trajectories/completed/2026-01/traj_6mieijqyvaag.json +0 -77
  185. package/.trajectories/completed/2026-01/traj_6mieijqyvaag.md +0 -42
  186. package/.trajectories/completed/2026-01/traj_6unwwmgyj5sq.json +0 -109
  187. package/.trajectories/completed/2026-01/traj_78ffm31jn3uk.json +0 -77
  188. package/.trajectories/completed/2026-01/traj_78ffm31jn3uk.md +0 -42
  189. package/.trajectories/completed/2026-01/traj_7ludwvz45veh.json +0 -209
  190. package/.trajectories/completed/2026-01/traj_7ludwvz45veh.md +0 -97
  191. package/.trajectories/completed/2026-01/traj_94gnp3k30goq.json +0 -66
  192. package/.trajectories/completed/2026-01/traj_94gnp3k30goq.md +0 -36
  193. package/.trajectories/completed/2026-01/traj_9921cuhel0pj.json +0 -48
  194. package/.trajectories/completed/2026-01/traj_9921cuhel0pj.md +0 -24
  195. package/.trajectories/completed/2026-01/traj_a0tqx8biw9c4.json +0 -49
  196. package/.trajectories/completed/2026-01/traj_a0tqx8biw9c4.md +0 -31
  197. package/.trajectories/completed/2026-01/traj_ajs7zqfux4wc.json +0 -49
  198. package/.trajectories/completed/2026-01/traj_ajs7zqfux4wc.md +0 -23
  199. package/.trajectories/completed/2026-01/traj_avqeghu6pz5a.json +0 -40
  200. package/.trajectories/completed/2026-01/traj_avqeghu6pz5a.md +0 -22
  201. package/.trajectories/completed/2026-01/traj_ax8uungxz2qh.json +0 -66
  202. package/.trajectories/completed/2026-01/traj_ax8uungxz2qh.md +0 -36
  203. package/.trajectories/completed/2026-01/traj_c9izbh2snpzf.json +0 -49
  204. package/.trajectories/completed/2026-01/traj_c9izbh2snpzf.md +0 -31
  205. package/.trajectories/completed/2026-01/traj_cpn70dw066nt.json +0 -65
  206. package/.trajectories/completed/2026-01/traj_cpn70dw066nt.md +0 -37
  207. package/.trajectories/completed/2026-01/traj_cvtqhlwcq9s0.json +0 -53
  208. package/.trajectories/completed/2026-01/traj_cvtqhlwcq9s0.md +0 -32
  209. package/.trajectories/completed/2026-01/traj_cxofprm2m2en.json +0 -49
  210. package/.trajectories/completed/2026-01/traj_cxofprm2m2en.md +0 -31
  211. package/.trajectories/completed/2026-01/traj_d2hhz3k0vrhn.json +0 -26
  212. package/.trajectories/completed/2026-01/traj_d2hhz3k0vrhn.md +0 -6
  213. package/.trajectories/completed/2026-01/traj_dcsp9s8y01ra.json +0 -121
  214. package/.trajectories/completed/2026-01/traj_dcsp9s8y01ra.md +0 -29
  215. package/.trajectories/completed/2026-01/traj_dfuvww9pege5.json +0 -59
  216. package/.trajectories/completed/2026-01/traj_dfuvww9pege5.md +0 -37
  217. package/.trajectories/completed/2026-01/traj_erglv2f8t9eh.json +0 -36
  218. package/.trajectories/completed/2026-01/traj_erglv2f8t9eh.md +0 -21
  219. package/.trajectories/completed/2026-01/traj_fhx9irlckht6.json +0 -53
  220. package/.trajectories/completed/2026-01/traj_fhx9irlckht6.md +0 -32
  221. package/.trajectories/completed/2026-01/traj_fqduidx3xbtp.json +0 -101
  222. package/.trajectories/completed/2026-01/traj_fqduidx3xbtp.md +0 -52
  223. package/.trajectories/completed/2026-01/traj_g0fisy9h51mf.json +0 -77
  224. package/.trajectories/completed/2026-01/traj_g0fisy9h51mf.md +0 -42
  225. package/.trajectories/completed/2026-01/traj_gjdre5voouod.json +0 -53
  226. package/.trajectories/completed/2026-01/traj_gjdre5voouod.md +0 -32
  227. package/.trajectories/completed/2026-01/traj_gtlyqtta3x8l.json +0 -25
  228. package/.trajectories/completed/2026-01/traj_gtlyqtta3x8l.md +0 -15
  229. package/.trajectories/completed/2026-01/traj_h4xijiuip3w4.json +0 -101
  230. package/.trajectories/completed/2026-01/traj_h4xijiuip3w4.md +0 -44
  231. package/.trajectories/completed/2026-01/traj_he75f24d1xfm.json +0 -101
  232. package/.trajectories/completed/2026-01/traj_he75f24d1xfm.md +0 -52
  233. package/.trajectories/completed/2026-01/traj_hf81ey93uz6t.json +0 -49
  234. package/.trajectories/completed/2026-01/traj_hf81ey93uz6t.md +0 -31
  235. package/.trajectories/completed/2026-01/traj_hfmki2jr9d4r.json +0 -65
  236. package/.trajectories/completed/2026-01/traj_hfmki2jr9d4r.md +0 -37
  237. package/.trajectories/completed/2026-01/traj_hhxte7w4gjjx.json +0 -22
  238. package/.trajectories/completed/2026-01/traj_hhxte7w4gjjx.md +0 -5
  239. package/.trajectories/completed/2026-01/traj_hpungyhoj6v5.json +0 -53
  240. package/.trajectories/completed/2026-01/traj_hpungyhoj6v5.md +0 -32
  241. package/.trajectories/completed/2026-01/traj_lgtodco7dp1n.json +0 -61
  242. package/.trajectories/completed/2026-01/traj_lgtodco7dp1n.md +0 -36
  243. package/.trajectories/completed/2026-01/traj_lq450ly148uw.json +0 -49
  244. package/.trajectories/completed/2026-01/traj_lq450ly148uw.md +0 -31
  245. package/.trajectories/completed/2026-01/traj_m2xkjv0w2sq7.json +0 -25
  246. package/.trajectories/completed/2026-01/traj_m2xkjv0w2sq7.md +0 -15
  247. package/.trajectories/completed/2026-01/traj_multi_server_arch.md +0 -101
  248. package/.trajectories/completed/2026-01/traj_noq5zbvnrdvz.json +0 -53
  249. package/.trajectories/completed/2026-01/traj_noq5zbvnrdvz.md +0 -32
  250. package/.trajectories/completed/2026-01/traj_ntbs6ppopf46.json +0 -53
  251. package/.trajectories/completed/2026-01/traj_ntbs6ppopf46.md +0 -32
  252. package/.trajectories/completed/2026-01/traj_oszg9flv74pk.json +0 -73
  253. package/.trajectories/completed/2026-01/traj_oszg9flv74pk.md +0 -41
  254. package/.trajectories/completed/2026-01/traj_ozd98si6a7ns.json +0 -48
  255. package/.trajectories/completed/2026-01/traj_ozd98si6a7ns.md +0 -24
  256. package/.trajectories/completed/2026-01/traj_prdza7a5cxp5.json +0 -53
  257. package/.trajectories/completed/2026-01/traj_prdza7a5cxp5.md +0 -32
  258. package/.trajectories/completed/2026-01/traj_psd9ob0j2ru3.json +0 -27
  259. package/.trajectories/completed/2026-01/traj_psd9ob0j2ru3.md +0 -14
  260. package/.trajectories/completed/2026-01/traj_pulomd3y8cvj.json +0 -77
  261. package/.trajectories/completed/2026-01/traj_pulomd3y8cvj.md +0 -42
  262. package/.trajectories/completed/2026-01/traj_qb3twvvywfwi.json +0 -77
  263. package/.trajectories/completed/2026-01/traj_qb3twvvywfwi.md +0 -42
  264. package/.trajectories/completed/2026-01/traj_qft54mi7nfor.json +0 -53
  265. package/.trajectories/completed/2026-01/traj_qft54mi7nfor.md +0 -32
  266. package/.trajectories/completed/2026-01/traj_qx9uhf8whhxo.json +0 -83
  267. package/.trajectories/completed/2026-01/traj_qx9uhf8whhxo.md +0 -47
  268. package/.trajectories/completed/2026-01/traj_rd9toccj18a0.json +0 -59
  269. package/.trajectories/completed/2026-01/traj_rd9toccj18a0.md +0 -37
  270. package/.trajectories/completed/2026-01/traj_rsavt0jipi3c.json +0 -109
  271. package/.trajectories/completed/2026-01/traj_rsavt0jipi3c.md +0 -56
  272. package/.trajectories/completed/2026-01/traj_rt4fiw3ecp50.json +0 -48
  273. package/.trajectories/completed/2026-01/traj_rt4fiw3ecp50.md +0 -16
  274. package/.trajectories/completed/2026-01/traj_st8j35b0hrlc.json +0 -59
  275. package/.trajectories/completed/2026-01/traj_st8j35b0hrlc.md +0 -37
  276. package/.trajectories/completed/2026-01/traj_t1yy8m7hbuxp.json +0 -53
  277. package/.trajectories/completed/2026-01/traj_t1yy8m7hbuxp.md +0 -32
  278. package/.trajectories/completed/2026-01/traj_tmux_orchestrator_analysis.json +0 -84
  279. package/.trajectories/completed/2026-01/traj_tmux_orchestrator_analysis.md +0 -109
  280. package/.trajectories/completed/2026-01/traj_u9n9eqasw16k.json +0 -53
  281. package/.trajectories/completed/2026-01/traj_u9n9eqasw16k.md +0 -32
  282. package/.trajectories/completed/2026-01/traj_ub8csuv3lcv4.json +0 -53
  283. package/.trajectories/completed/2026-01/traj_ub8csuv3lcv4.md +0 -32
  284. package/.trajectories/completed/2026-01/traj_uc29tlso8i9s.json +0 -186
  285. package/.trajectories/completed/2026-01/traj_uc29tlso8i9s.md +0 -86
  286. package/.trajectories/completed/2026-01/traj_ui9b4tqxoa7j.json +0 -77
  287. package/.trajectories/completed/2026-01/traj_ui9b4tqxoa7j.md +0 -42
  288. package/.trajectories/completed/2026-01/traj_v87hypnongqx.json +0 -71
  289. package/.trajectories/completed/2026-01/traj_v87hypnongqx.md +0 -42
  290. package/.trajectories/completed/2026-01/traj_v9dkdoxylyid.json +0 -89
  291. package/.trajectories/completed/2026-01/traj_v9dkdoxylyid.md +0 -47
  292. package/.trajectories/completed/2026-01/traj_wkp2fgzdyinb.json +0 -53
  293. package/.trajectories/completed/2026-01/traj_wkp2fgzdyinb.md +0 -32
  294. package/.trajectories/completed/2026-01/traj_x14t8w8rn7xg.json +0 -20
  295. package/.trajectories/completed/2026-01/traj_x14t8w8rn7xg.md +0 -6
  296. package/.trajectories/completed/2026-01/traj_x721m1j9rzup.json +0 -113
  297. package/.trajectories/completed/2026-01/traj_x721m1j9rzup.md +0 -57
  298. package/.trajectories/completed/2026-01/traj_xjqvmep5ed3h.json +0 -61
  299. package/.trajectories/completed/2026-01/traj_xjqvmep5ed3h.md +0 -36
  300. package/.trajectories/completed/2026-01/traj_xnwbznkvv8ua.json +0 -175
  301. package/.trajectories/completed/2026-01/traj_xnwbznkvv8ua.md +0 -82
  302. package/.trajectories/completed/2026-01/traj_xy9vifpqet80.json +0 -65
  303. package/.trajectories/completed/2026-01/traj_xy9vifpqet80.md +0 -37
  304. package/.trajectories/completed/2026-01/traj_y7aiwijyfmmv.json +0 -49
  305. package/.trajectories/completed/2026-01/traj_y7aiwijyfmmv.md +0 -31
  306. package/.trajectories/completed/2026-01/traj_y7n6hfbf7dmg.json +0 -49
  307. package/.trajectories/completed/2026-01/traj_y7n6hfbf7dmg.md +0 -31
  308. package/.trajectories/completed/2026-01/traj_ysjc8zaeqtd3.json +0 -47
  309. package/.trajectories/completed/2026-01/traj_ysjc8zaeqtd3.md +0 -32
  310. package/.trajectories/completed/2026-01/traj_yvdadtvdgnz3.json +0 -59
  311. package/.trajectories/completed/2026-01/traj_yvdadtvdgnz3.md +0 -37
  312. package/.trajectories/completed/2026-01/traj_yvfkwnkdiso2.json +0 -49
  313. package/.trajectories/completed/2026-01/traj_yvfkwnkdiso2.md +0 -31
  314. package/.trajectories/completed/2026-01/traj_z0vcw1wrzide.json +0 -53
  315. package/.trajectories/completed/2026-01/traj_z0vcw1wrzide.md +0 -32
  316. package/.trajectories/consolidate-settings-panel.md +0 -24
  317. package/.trajectories/gh-cli-user-token.md +0 -26
  318. package/.trajectories/index.json +0 -607
@@ -0,0 +1,4753 @@
1
+ import express from 'express';
2
+ import { WebSocketServer, WebSocket } from 'ws';
3
+ import http from 'http';
4
+ import path from 'path';
5
+ import fs from 'fs';
6
+ import os from 'os';
7
+ import crypto from 'crypto';
8
+ import { exec } from 'child_process';
9
+ import { fileURLToPath } from 'url';
10
+ import { SqliteStorageAdapter } from '../storage/sqlite-adapter.js';
11
+ import { RelayClient } from '../wrapper/client.js';
12
+ import { UserBridge } from './user-bridge.js';
13
+ import { computeNeedsAttention } from './needs-attention.js';
14
+ import { computeSystemMetrics, formatPrometheusMetrics } from './metrics.js';
15
+ import { MultiProjectClient } from '../bridge/multi-project-client.js';
16
+ import { AgentSpawner } from '../bridge/spawner.js';
17
+ import { listTrajectorySteps, getTrajectoryStatus, getTrajectoryHistory } from '../trajectory/integration.js';
18
+ import { loadTeamsConfig } from '../bridge/teams-config.js';
19
+ import { getMemoryMonitor } from '../resiliency/memory-monitor.js';
20
+ import { detectWorkspacePath } from '../utils/project-namespace.js';
21
+ import { startCLIAuth, getAuthSession, cancelAuthSession, submitAuthCode, completeAuthSession, getSupportedProviders, } from '../daemon/cli-auth.js';
22
+ import { HealthWorkerManager, getHealthPort } from '../health-worker-manager.js';
23
+ /**
24
+ * Initialize cloud persistence for session tracking.
25
+ *
26
+ * Activation modes:
27
+ * 1. Local dev: Set RELAY_CLOUD_ENABLED=true and DATABASE_URL
28
+ * 2. Cloud deployment: Plan-based - user must have Pro+ subscription
29
+ * (enforced at cloud API level when linking daemon or enabling workspace)
30
+ *
31
+ * Session persistence (Pro+ feature) enables:
32
+ * - [[SUMMARY]] blocks saved to PostgreSQL
33
+ * - [[SESSION_END]] markers for session tracking
34
+ * - Session recovery and agent handoff
35
+ *
36
+ * @see canUseSessionPersistence in services/planLimits.ts
37
+ */
38
+ async function initCloudPersistence(workspaceId) {
39
+ // Local dev mode: simple env var check
40
+ // Cloud mode: plan check happens at API level (daemon linking, workspace config)
41
+ if (process.env.RELAY_CLOUD_ENABLED !== 'true') {
42
+ return null;
43
+ }
44
+ try {
45
+ // Dynamic import to avoid loading cloud dependencies unless enabled
46
+ const { getDb } = await import('../cloud/db/drizzle.js');
47
+ const { agentSessions, agentSummaries } = await import('../cloud/db/schema.js');
48
+ const { eq } = await import('drizzle-orm');
49
+ const db = getDb();
50
+ console.log('[dashboard] Cloud persistence enabled');
51
+ // Track active sessions per agent with timestamps for TTL cleanup
52
+ const SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
53
+ const MAX_SESSIONS = 10000;
54
+ const agentSessionIds = new Map();
55
+ // Track pending session creation to prevent race conditions
56
+ const pendingSessionCreation = new Map();
57
+ // Periodic cleanup of stale sessions (every 5 minutes)
58
+ const cleanupInterval = setInterval(() => {
59
+ const now = Date.now();
60
+ let evicted = 0;
61
+ for (const [name, { lastActivity }] of agentSessionIds.entries()) {
62
+ if (now - lastActivity > SESSION_TTL_MS) {
63
+ agentSessionIds.delete(name);
64
+ evicted++;
65
+ }
66
+ }
67
+ if (evicted > 0) {
68
+ console.log(`[cloud] Evicted ${evicted} stale session entries`);
69
+ }
70
+ }, 5 * 60 * 1000);
71
+ // Don't keep process alive just for cleanup
72
+ cleanupInterval.unref();
73
+ // Helper to get or create session with race protection
74
+ const getOrCreateSession = async (agentName) => {
75
+ // Check cache first
76
+ const cached = agentSessionIds.get(agentName);
77
+ if (cached) {
78
+ return cached.id;
79
+ }
80
+ // Check if creation is already in progress
81
+ const pending = pendingSessionCreation.get(agentName);
82
+ if (pending) {
83
+ return pending;
84
+ }
85
+ // Create session with mutex
86
+ const creationPromise = (async () => {
87
+ try {
88
+ // Double-check cache after acquiring "lock"
89
+ const rechecked = agentSessionIds.get(agentName);
90
+ if (rechecked) {
91
+ return rechecked.id;
92
+ }
93
+ // Enforce max size - evict oldest if needed
94
+ if (agentSessionIds.size >= MAX_SESSIONS) {
95
+ let oldest = null;
96
+ for (const [name, { lastActivity }] of agentSessionIds.entries()) {
97
+ if (!oldest || lastActivity < oldest.time) {
98
+ oldest = { name, time: lastActivity };
99
+ }
100
+ }
101
+ if (oldest) {
102
+ agentSessionIds.delete(oldest.name);
103
+ console.log(`[cloud] Evicted oldest session for ${oldest.name} (max sessions reached)`);
104
+ }
105
+ }
106
+ // Create a new session with null safety
107
+ const result = await db.insert(agentSessions).values({
108
+ workspaceId,
109
+ agentName,
110
+ status: 'active',
111
+ startedAt: new Date(),
112
+ }).returning();
113
+ const session = result[0];
114
+ if (!session) {
115
+ throw new Error(`Failed to create session for agent ${agentName}`);
116
+ }
117
+ // Update cache
118
+ agentSessionIds.set(agentName, { id: session.id, lastActivity: Date.now() });
119
+ return session.id;
120
+ }
121
+ finally {
122
+ pendingSessionCreation.delete(agentName);
123
+ }
124
+ })();
125
+ pendingSessionCreation.set(agentName, creationPromise);
126
+ return creationPromise;
127
+ };
128
+ return {
129
+ onSummary: async (agentName, event) => {
130
+ try {
131
+ // Get or create session with race protection
132
+ const sessionId = await getOrCreateSession(agentName);
133
+ // Update activity timestamp
134
+ agentSessionIds.set(agentName, { id: sessionId, lastActivity: Date.now() });
135
+ // Insert summary
136
+ await db.insert(agentSummaries).values({
137
+ sessionId,
138
+ agentName,
139
+ summary: event.summary,
140
+ createdAt: new Date(),
141
+ });
142
+ console.log(`[cloud] Saved summary for ${agentName}: ${event.summary.currentTask || 'no task'}`);
143
+ }
144
+ catch (err) {
145
+ console.error(`[cloud] Failed to save summary for ${agentName}:`, err);
146
+ }
147
+ },
148
+ onSessionEnd: async (agentName, event) => {
149
+ try {
150
+ const cached = agentSessionIds.get(agentName);
151
+ if (cached) {
152
+ // Update session as ended
153
+ await db.update(agentSessions)
154
+ .set({
155
+ status: 'ended',
156
+ endedAt: new Date(),
157
+ endMarker: event.marker,
158
+ })
159
+ .where(eq(agentSessions.id, cached.id));
160
+ agentSessionIds.delete(agentName);
161
+ console.log(`[cloud] Session ended for ${agentName}: ${event.marker.summary || 'no summary'}`);
162
+ }
163
+ }
164
+ catch (err) {
165
+ console.error(`[cloud] Failed to end session for ${agentName}:`, err);
166
+ }
167
+ },
168
+ destroy: () => {
169
+ clearInterval(cleanupInterval);
170
+ agentSessionIds.clear();
171
+ pendingSessionCreation.clear();
172
+ console.log('[cloud] Cloud persistence handler destroyed');
173
+ },
174
+ };
175
+ }
176
+ catch (err) {
177
+ console.warn('[dashboard] Cloud persistence not available:', err);
178
+ return null;
179
+ }
180
+ }
181
+ const __filename = fileURLToPath(import.meta.url);
182
+ const __dirname = path.dirname(__filename);
183
+ /**
184
+ * Search for files in a directory matching a query pattern.
185
+ * Uses a simple recursive search with common ignore patterns.
186
+ */
187
+ async function searchFiles(rootDir, query, limit) {
188
+ const results = [];
189
+ const queryLower = query.toLowerCase();
190
+ // Directories to ignore
191
+ const ignoreDirs = new Set([
192
+ 'node_modules', '.git', 'dist', 'build', '.next', 'coverage',
193
+ '__pycache__', '.venv', 'venv', '.cache', '.turbo', '.vercel',
194
+ '.nuxt', '.output', 'vendor', 'target', '.idea', '.vscode'
195
+ ]);
196
+ // File patterns to ignore
197
+ const ignorePatterns = [
198
+ /\.lock$/,
199
+ /\.log$/,
200
+ /\.min\.(js|css)$/,
201
+ /\.map$/,
202
+ /\.d\.ts$/,
203
+ /\.pyc$/,
204
+ ];
205
+ const shouldIgnore = (name, isDir) => {
206
+ if (isDir)
207
+ return ignoreDirs.has(name);
208
+ return ignorePatterns.some(pattern => pattern.test(name));
209
+ };
210
+ const matchesQuery = (filePath, fileName) => {
211
+ if (!query)
212
+ return true;
213
+ const pathLower = filePath.toLowerCase();
214
+ const nameLower = fileName.toLowerCase();
215
+ // If query contains '/', match against full path
216
+ if (queryLower.includes('/')) {
217
+ return pathLower.includes(queryLower);
218
+ }
219
+ // Otherwise match against file name or path segments
220
+ return nameLower.includes(queryLower) || pathLower.includes(queryLower);
221
+ };
222
+ const searchDir = async (dir, relativePath = '') => {
223
+ if (results.length >= limit)
224
+ return;
225
+ try {
226
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
227
+ // Sort: directories first, then alphabetically
228
+ entries.sort((a, b) => {
229
+ if (a.isDirectory() !== b.isDirectory()) {
230
+ return a.isDirectory() ? -1 : 1;
231
+ }
232
+ return a.name.localeCompare(b.name);
233
+ });
234
+ for (const entry of entries) {
235
+ if (results.length >= limit)
236
+ break;
237
+ const entryPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
238
+ const fullPath = path.join(dir, entry.name);
239
+ if (shouldIgnore(entry.name, entry.isDirectory()))
240
+ continue;
241
+ if (matchesQuery(entryPath, entry.name)) {
242
+ results.push({
243
+ path: entryPath,
244
+ name: entry.name,
245
+ isDirectory: entry.isDirectory(),
246
+ });
247
+ }
248
+ // Recurse into directories
249
+ if (entry.isDirectory() && results.length < limit) {
250
+ await searchDir(fullPath, entryPath);
251
+ }
252
+ }
253
+ }
254
+ catch (err) {
255
+ // Ignore permission errors, etc.
256
+ console.warn(`[searchFiles] Error reading ${dir}:`, err);
257
+ }
258
+ };
259
+ await searchDir(rootDir);
260
+ return results;
261
+ }
262
+ export async function startDashboard(portOrOptions, dataDirArg, teamDirArg, dbPathArg) {
263
+ // Handle overloaded signatures
264
+ const options = typeof portOrOptions === 'number'
265
+ ? { port: portOrOptions, dataDir: dataDirArg, teamDir: teamDirArg, dbPath: dbPathArg }
266
+ : portOrOptions;
267
+ const { port, dataDir, teamDir, dbPath, enableSpawner, projectRoot, tmuxSession } = options;
268
+ console.log('Starting dashboard...');
269
+ const disableStorage = process.env.RELAY_DISABLE_STORAGE === 'true';
270
+ const storage = disableStorage
271
+ ? undefined
272
+ : new SqliteStorageAdapter({
273
+ dbPath: dbPath ?? path.join(dataDir, 'dashboard.db'),
274
+ });
275
+ const defaultWorkspaceId = process.env.RELAY_WORKSPACE_ID ?? process.env.AGENT_RELAY_WORKSPACE_ID;
276
+ const resolveWorkspaceId = (req) => {
277
+ const fromQuery = req.query.workspaceId;
278
+ const fromBody = req.body?.workspaceId;
279
+ const fromHeader = req.headers['x-workspace-id'];
280
+ return fromQuery || fromBody || fromHeader || defaultWorkspaceId;
281
+ };
282
+ const loadChannelRecords = async (workspaceId) => {
283
+ const map = new Map();
284
+ if (!storage) {
285
+ return map;
286
+ }
287
+ const stored = await storage.getMessages({ order: 'asc' });
288
+ const ensureRecord = (id) => {
289
+ let record = map.get(id);
290
+ if (!record) {
291
+ record = {
292
+ id,
293
+ visibility: 'public',
294
+ status: 'active',
295
+ lastActivityAt: 0,
296
+ members: new Set(),
297
+ };
298
+ if (id.startsWith('dm:')) {
299
+ const participants = id.split(':').slice(1).filter(Boolean);
300
+ if (participants.length > 0) {
301
+ participants.forEach((participant) => record.members.add(participant));
302
+ record.dmParticipants = participants;
303
+ }
304
+ }
305
+ map.set(id, record);
306
+ }
307
+ return record;
308
+ };
309
+ const addMember = (record, member) => {
310
+ if (!member)
311
+ return;
312
+ record.members.add(member);
313
+ };
314
+ for (const msg of stored) {
315
+ const target = msg.to;
316
+ if (!target || (!target.startsWith('#') && !target.startsWith('dm:'))) {
317
+ continue;
318
+ }
319
+ const data = msg.data;
320
+ const messageWorkspaceId = typeof data?._workspaceId === 'string' ? data._workspaceId : undefined;
321
+ if (workspaceId && messageWorkspaceId && messageWorkspaceId !== workspaceId) {
322
+ continue;
323
+ }
324
+ const record = ensureRecord(target);
325
+ const timestamp = typeof msg.ts === 'number' ? msg.ts : Date.now();
326
+ const channelCreate = data?._channelCreate;
327
+ if (channelCreate) {
328
+ record.createdAt = record.createdAt ?? timestamp;
329
+ record.createdBy = channelCreate.createdBy ?? record.createdBy;
330
+ if (channelCreate.description) {
331
+ record.description = String(channelCreate.description);
332
+ }
333
+ record.visibility = channelCreate.isPrivate ? 'private' : 'public';
334
+ }
335
+ const stateChange = data?._channelState;
336
+ if (stateChange) {
337
+ record.status = stateChange === 'archived' ? 'archived' : 'active';
338
+ record.lastActivityAt = Math.max(record.lastActivityAt, timestamp);
339
+ }
340
+ const membership = data?._channelMembership;
341
+ if (membership?.member) {
342
+ if (membership.action === 'leave') {
343
+ record.members.delete(membership.member);
344
+ }
345
+ else {
346
+ addMember(record, membership.member);
347
+ }
348
+ record.lastActivityAt = Math.max(record.lastActivityAt, timestamp);
349
+ }
350
+ const isChannelMessage = Boolean(data?._isChannelMessage);
351
+ if (isChannelMessage) {
352
+ addMember(record, msg.from);
353
+ record.lastActivityAt = Math.max(record.lastActivityAt, timestamp);
354
+ record.lastMessage = {
355
+ content: msg.body,
356
+ from: msg.from || '__system__',
357
+ timestamp: new Date(timestamp).toISOString(),
358
+ };
359
+ if (target.startsWith('dm:') && !record.dmParticipants) {
360
+ const participants = target.split(':').slice(1).filter(Boolean);
361
+ if (participants.length > 0) {
362
+ participants.forEach((participant) => record.members.add(participant));
363
+ record.dmParticipants = participants;
364
+ }
365
+ }
366
+ }
367
+ }
368
+ return map;
369
+ };
370
+ const loadPersistedChannelsForUser = async (username, workspaceId) => {
371
+ const channelMap = await loadChannelRecords(workspaceId);
372
+ const result = [];
373
+ for (const record of channelMap.values()) {
374
+ if (record.status === 'archived') {
375
+ continue;
376
+ }
377
+ if (record.members.has(username)) {
378
+ result.push(record.id);
379
+ }
380
+ }
381
+ if (!result.includes('#general')) {
382
+ result.unshift('#general');
383
+ }
384
+ return result;
385
+ };
386
+ const persistChannelMembershipEvent = async (channel, member, action, options) => {
387
+ if (!storage)
388
+ return;
389
+ const data = {
390
+ _channelMembership: {
391
+ member,
392
+ action,
393
+ invitedBy: options?.invitedBy,
394
+ },
395
+ };
396
+ const workspaceToStore = options?.workspaceId ?? defaultWorkspaceId;
397
+ if (workspaceToStore) {
398
+ data._workspaceId = workspaceToStore;
399
+ }
400
+ await storage.saveMessage({
401
+ id: `channel-membership-${crypto.randomUUID()}`,
402
+ ts: Date.now(),
403
+ from: '__system__',
404
+ to: channel,
405
+ topic: undefined,
406
+ kind: 'state',
407
+ body: `${action}:${member}`,
408
+ data,
409
+ status: 'read',
410
+ is_urgent: false,
411
+ is_broadcast: true,
412
+ }).catch((err) => {
413
+ console.error('[channels] Failed to persist membership event', err);
414
+ });
415
+ await notifyDaemonOfMembershipUpdate(channel, member, action, workspaceToStore).catch((err) => {
416
+ console.error('[channels] Failed to notify daemon of membership update', err);
417
+ });
418
+ };
419
+ // Initialize spawner if enabled
420
+ // Use detectWorkspacePath to find the actual repo directory in cloud workspaces
421
+ const workspacePath = detectWorkspacePath(projectRoot || dataDir);
422
+ console.log(`[dashboard] Workspace path: ${workspacePath}`);
423
+ // Pass dashboard port to spawner so spawned agents can call spawn/release APIs for nested spawning
424
+ const spawner = enableSpawner
425
+ ? new AgentSpawner(workspacePath, tmuxSession, port)
426
+ : undefined;
427
+ // Initialize cloud persistence and memory monitoring if enabled (RELAY_CLOUD_ENABLED=true)
428
+ if (spawner) {
429
+ // Use workspace ID from env or generate from project root
430
+ const workspaceId = process.env.RELAY_WORKSPACE_ID ||
431
+ crypto.createHash('sha256').update(projectRoot || dataDir).digest('hex').slice(0, 36);
432
+ initCloudPersistence(workspaceId).then((cloudHandler) => {
433
+ if (cloudHandler) {
434
+ spawner.setCloudPersistence(cloudHandler);
435
+ }
436
+ }).catch((err) => {
437
+ console.warn('[dashboard] Failed to initialize cloud persistence:', err);
438
+ });
439
+ // Initialize memory monitoring for cloud deployments
440
+ // Memory monitoring is enabled by default when cloud is enabled
441
+ if (process.env.RELAY_CLOUD_ENABLED === 'true' || process.env.RELAY_MEMORY_MONITORING === 'true') {
442
+ try {
443
+ const memoryMonitor = getMemoryMonitor({
444
+ checkIntervalMs: 10000, // Check every 10 seconds
445
+ enableTrendAnalysis: true,
446
+ enableProactiveAlerts: true,
447
+ });
448
+ memoryMonitor.start();
449
+ console.log('[dashboard] Memory monitoring enabled');
450
+ // Register existing workers with memory monitor
451
+ const workers = spawner.getActiveWorkers();
452
+ for (const worker of workers) {
453
+ if (worker.pid) {
454
+ memoryMonitor.register(worker.name, worker.pid);
455
+ }
456
+ }
457
+ }
458
+ catch (err) {
459
+ console.warn('[dashboard] Failed to initialize memory monitoring:', err);
460
+ }
461
+ }
462
+ }
463
+ process.on('uncaughtException', (err) => {
464
+ console.error('Uncaught Exception:', err);
465
+ });
466
+ process.on('unhandledRejection', (reason, promise) => {
467
+ console.error('Unhandled Rejection at:', promise, 'reason:', reason);
468
+ });
469
+ const app = express();
470
+ const server = http.createServer(app);
471
+ // Use noServer mode to manually route upgrade requests
472
+ // This prevents the bug where multiple WebSocketServers attached to the same
473
+ // HTTP server cause conflicts - each one's upgrade handler fires and the ones
474
+ // that don't match the path call abortHandshake(400), writing raw HTTP to the socket
475
+ const wss = new WebSocketServer({
476
+ noServer: true,
477
+ perMessageDeflate: false,
478
+ skipUTF8Validation: true,
479
+ maxPayload: 100 * 1024 * 1024 // 100MB
480
+ });
481
+ const wssBridge = new WebSocketServer({
482
+ noServer: true,
483
+ perMessageDeflate: false,
484
+ skipUTF8Validation: true,
485
+ maxPayload: 100 * 1024 * 1024
486
+ });
487
+ const wssLogs = new WebSocketServer({
488
+ noServer: true,
489
+ perMessageDeflate: false,
490
+ skipUTF8Validation: true,
491
+ maxPayload: 100 * 1024 * 1024
492
+ });
493
+ const wssPresence = new WebSocketServer({
494
+ noServer: true,
495
+ perMessageDeflate: false,
496
+ skipUTF8Validation: true,
497
+ maxPayload: 1024 * 1024 // 1MB - presence messages are small
498
+ });
499
+ // Track log subscriptions: agentName -> Set of WebSocket clients
500
+ const logSubscriptions = new Map();
501
+ // Track alive status for ping/pong keepalive on main dashboard connections
502
+ // This prevents TCP/proxy timeouts from killing idle workspace connections
503
+ const mainClientAlive = new WeakMap();
504
+ // Track alive status for ping/pong keepalive on bridge connections
505
+ const bridgeClientAlive = new WeakMap();
506
+ // Ping interval for main dashboard WebSocket connections (30 seconds)
507
+ // Aligns with heartbeat timeout (5s heartbeat * 6 multiplier = 30s)
508
+ const MAIN_PING_INTERVAL_MS = 30000;
509
+ const mainPingInterval = setInterval(() => {
510
+ wss.clients.forEach((ws) => {
511
+ if (mainClientAlive.get(ws) === false) {
512
+ // Client didn't respond to last ping - close gracefully
513
+ console.log('[dashboard] Main WebSocket client unresponsive, closing gracefully');
514
+ ws.close(1000, 'unresponsive');
515
+ return;
516
+ }
517
+ // Mark as not alive until we get a pong
518
+ mainClientAlive.set(ws, false);
519
+ ws.ping();
520
+ });
521
+ }, MAIN_PING_INTERVAL_MS);
522
+ // Ping interval for bridge WebSocket connections (30 seconds)
523
+ const BRIDGE_PING_INTERVAL_MS = 30000;
524
+ const bridgePingInterval = setInterval(() => {
525
+ wssBridge.clients.forEach((ws) => {
526
+ if (bridgeClientAlive.get(ws) === false) {
527
+ console.log('[dashboard] Bridge WebSocket client unresponsive, closing gracefully');
528
+ ws.close(1000, 'unresponsive');
529
+ return;
530
+ }
531
+ bridgeClientAlive.set(ws, false);
532
+ ws.ping();
533
+ });
534
+ }, BRIDGE_PING_INTERVAL_MS);
535
+ // Clean up ping intervals on server close
536
+ wss.on('close', () => {
537
+ clearInterval(mainPingInterval);
538
+ });
539
+ wssBridge.on('close', () => {
540
+ clearInterval(bridgePingInterval);
541
+ });
542
+ const onlineUsers = new Map();
543
+ // Validation helpers for presence
544
+ const isValidUsername = (username) => {
545
+ if (typeof username !== 'string')
546
+ return false;
547
+ // Username should be 1-39 chars, alphanumeric with hyphens (GitHub username rules)
548
+ return /^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,37}[a-zA-Z0-9])?$/.test(username);
549
+ };
550
+ const isValidAvatarUrl = (url) => {
551
+ if (url === undefined || url === null)
552
+ return true;
553
+ if (typeof url !== 'string')
554
+ return false;
555
+ // Must be a valid HTTPS URL from GitHub or similar known providers
556
+ try {
557
+ const parsed = new URL(url);
558
+ return parsed.protocol === 'https:' &&
559
+ (parsed.hostname === 'avatars.githubusercontent.com' ||
560
+ parsed.hostname === 'github.com' ||
561
+ parsed.hostname.endsWith('.githubusercontent.com'));
562
+ }
563
+ catch {
564
+ return false;
565
+ }
566
+ };
567
+ // Manually handle upgrade requests and route to correct WebSocketServer
568
+ server.on('upgrade', (request, socket, head) => {
569
+ const pathname = new URL(request.url || '', `http://${request.headers.host}`).pathname;
570
+ if (pathname === '/ws') {
571
+ wss.handleUpgrade(request, socket, head, (ws) => {
572
+ wss.emit('connection', ws, request);
573
+ });
574
+ }
575
+ else if (pathname === '/ws/bridge') {
576
+ wssBridge.handleUpgrade(request, socket, head, (ws) => {
577
+ wssBridge.emit('connection', ws, request);
578
+ });
579
+ }
580
+ else if (pathname === '/ws/logs' || pathname.startsWith('/ws/logs/')) {
581
+ wssLogs.handleUpgrade(request, socket, head, (ws) => {
582
+ wssLogs.emit('connection', ws, request);
583
+ });
584
+ }
585
+ else if (pathname === '/ws/presence') {
586
+ wssPresence.handleUpgrade(request, socket, head, (ws) => {
587
+ wssPresence.emit('connection', ws, request);
588
+ });
589
+ }
590
+ else {
591
+ // Unknown path - destroy socket
592
+ socket.destroy();
593
+ }
594
+ });
595
+ // Server-level error handlers
596
+ wss.on('error', (err) => {
597
+ console.error('[dashboard] WebSocket server error:', err);
598
+ });
599
+ wssBridge.on('error', (err) => {
600
+ console.error('[dashboard] Bridge WebSocket server error:', err);
601
+ });
602
+ wssLogs.on('error', (err) => {
603
+ console.error('[dashboard] Logs WebSocket server error:', err);
604
+ });
605
+ wssPresence.on('error', (err) => {
606
+ console.error('[dashboard] Presence WebSocket server error:', err);
607
+ });
608
+ if (storage) {
609
+ await storage.init();
610
+ }
611
+ // Request logger for debugging
612
+ app.use((req, res, next) => {
613
+ if (req.path.startsWith('/api/channels')) {
614
+ console.log(`[dashboard] ${req.method} ${req.path} - incoming request`);
615
+ }
616
+ next();
617
+ });
618
+ // Increase JSON body limit for base64 image uploads (10MB)
619
+ app.use(express.json({ limit: '10mb' }));
620
+ // Create attachments directory in user's home directory (~/.relay/attachments)
621
+ // This keeps attachments out of source control while still accessible to agents
622
+ const attachmentsDir = path.join(os.homedir(), '.relay', 'attachments');
623
+ if (!fs.existsSync(attachmentsDir)) {
624
+ fs.mkdirSync(attachmentsDir, { recursive: true });
625
+ }
626
+ // Also keep uploads dir for backwards compatibility (URL-based serving)
627
+ const uploadsDir = path.join(dataDir, 'uploads');
628
+ if (!fs.existsSync(uploadsDir)) {
629
+ fs.mkdirSync(uploadsDir, { recursive: true });
630
+ }
631
+ // Auto-evict old attachments (older than 7 days)
632
+ const ATTACHMENT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
633
+ const evictOldAttachments = async () => {
634
+ try {
635
+ const files = await fs.promises.readdir(attachmentsDir);
636
+ const now = Date.now();
637
+ let evictedCount = 0;
638
+ for (const file of files) {
639
+ const filePath = path.join(attachmentsDir, file);
640
+ try {
641
+ const stat = await fs.promises.stat(filePath);
642
+ if (stat.isFile() && (now - stat.mtimeMs) > ATTACHMENT_MAX_AGE_MS) {
643
+ await fs.promises.unlink(filePath);
644
+ evictedCount++;
645
+ }
646
+ }
647
+ catch (_err) {
648
+ // Ignore errors for individual files (may have been deleted)
649
+ }
650
+ }
651
+ if (evictedCount > 0) {
652
+ console.log(`[dashboard] Evicted ${evictedCount} old attachment(s)`);
653
+ }
654
+ }
655
+ catch (err) {
656
+ console.error('[dashboard] Failed to evict old attachments:', err);
657
+ }
658
+ };
659
+ // Run eviction on startup and every hour
660
+ evictOldAttachments();
661
+ const evictionInterval = setInterval(evictOldAttachments, 60 * 60 * 1000); // 1 hour
662
+ // Clean up interval on process exit
663
+ process.on('beforeExit', () => {
664
+ clearInterval(evictionInterval);
665
+ });
666
+ // Serve uploaded files statically
667
+ app.use('/uploads', express.static(uploadsDir));
668
+ // Serve attachments from ~/.relay/attachments
669
+ app.use('/attachments', express.static(attachmentsDir));
670
+ // In-memory attachment registry (for current session)
671
+ // Attachments are also stored on disk, so this is just for quick lookups
672
+ const attachmentRegistry = new Map();
673
+ // Serve dashboard static files at root (built with `next build` in src/dashboard)
674
+ // __dirname is dist/dashboard-server, dashboard is at ../dashboard/out (relative to dist)
675
+ // But in source it's at ../dashboard/out (relative to src/dashboard-server)
676
+ const dashboardDistDir = path.join(__dirname, '..', 'dashboard', 'out');
677
+ const dashboardSourceDir = path.join(__dirname, '..', '..', 'src', 'dashboard', 'out');
678
+ // Check which path exists (dist or src)
679
+ const dashboardDir = fs.existsSync(dashboardDistDir) ? dashboardDistDir : dashboardSourceDir;
680
+ if (fs.existsSync(dashboardDir)) {
681
+ console.log(`[dashboard] Serving from: ${dashboardDir}`);
682
+ // Serve Next.js static export with .html extension handling
683
+ app.use(express.static(dashboardDir, { extensions: ['html'] }));
684
+ // Fallback for Next.js pages (e.g., /metrics -> /metrics.html)
685
+ // These are needed when a route exists as both a directory and .html file
686
+ app.get('/metrics', (req, res) => {
687
+ res.sendFile(path.join(dashboardDir, 'metrics.html'));
688
+ });
689
+ app.get('/app', (req, res) => {
690
+ res.sendFile(path.join(dashboardDir, 'app.html'));
691
+ });
692
+ }
693
+ else {
694
+ console.error('[dashboard] Dashboard not found at:', dashboardDistDir, 'or', dashboardSourceDir);
695
+ }
696
+ // Relay clients for sending messages from dashboard
697
+ // Map of senderName -> RelayClient for per-user connections
698
+ const socketPath = path.join(dataDir, 'relay.sock');
699
+ const relayClients = new Map();
700
+ const notifyDaemonOfMembershipUpdate = async (channel, member, action, workspaceId) => {
701
+ const client = await getRelayClient('Dashboard');
702
+ if (!client || client.state !== 'READY') {
703
+ return;
704
+ }
705
+ client.sendMessage('_router', '', 'state', {
706
+ _channelMembershipUpdate: {
707
+ channel,
708
+ member,
709
+ action,
710
+ workspaceId,
711
+ },
712
+ });
713
+ };
714
+ // Track pending client connections to prevent race conditions
715
+ const pendingConnections = new Map();
716
+ // Get or create a relay client for a specific sender
717
+ const getRelayClient = async (senderName = 'Dashboard', entityType) => {
718
+ // Check if we already have a connected client for this sender
719
+ const existing = relayClients.get(senderName);
720
+ if (existing && existing.state === 'READY') {
721
+ return existing;
722
+ }
723
+ // Check if there's already a pending connection for this sender
724
+ const pending = pendingConnections.get(senderName);
725
+ if (pending) {
726
+ return pending;
727
+ }
728
+ // Only attempt connection if socket exists (daemon is running)
729
+ if (!fs.existsSync(socketPath)) {
730
+ console.log('[dashboard] Relay socket not found, messaging disabled');
731
+ return undefined;
732
+ }
733
+ // Create connection promise to prevent race conditions
734
+ const connectionPromise = (async () => {
735
+ // Create new client for this sender
736
+ // Default to 'user' entityType for non-Dashboard senders (human users)
737
+ const resolvedEntityType = entityType ?? (senderName === 'Dashboard' ? undefined : 'user');
738
+ const client = new RelayClient({
739
+ socketPath,
740
+ agentName: senderName,
741
+ entityType: resolvedEntityType,
742
+ cli: 'dashboard',
743
+ reconnect: true,
744
+ maxReconnectAttempts: 5,
745
+ });
746
+ client.onError = (err) => {
747
+ console.error(`[dashboard] Relay client error for ${senderName}:`, err.message);
748
+ };
749
+ client.onStateChange = (state) => {
750
+ console.log(`[dashboard] Relay client for ${senderName} state: ${state}`);
751
+ // Clean up disconnected clients
752
+ if (state === 'DISCONNECTED') {
753
+ relayClients.delete(senderName);
754
+ }
755
+ };
756
+ // Set up channel message handler to forward messages to presence WebSocket
757
+ // This enables cloud users to receive channel messages via the presence bridge
758
+ client.onChannelMessage = (from, channel, body, envelope) => {
759
+ console.log(`[dashboard] *** CHANNEL MESSAGE RECEIVED *** for ${senderName}: ${from} -> ${channel}`);
760
+ // Broadcast to presence WebSocket clients so cloud can forward to its users
761
+ // Include the target user so cloud knows who to forward to
762
+ broadcastChannelMessage({
763
+ type: 'channel_message',
764
+ targetUser: senderName,
765
+ channel,
766
+ from,
767
+ body,
768
+ thread: envelope?.payload?.thread,
769
+ mentions: envelope?.payload?.mentions,
770
+ timestamp: new Date().toISOString(),
771
+ });
772
+ };
773
+ try {
774
+ await client.connect();
775
+ relayClients.set(senderName, client);
776
+ console.log(`[dashboard] Connected to relay daemon as ${senderName}`);
777
+ return client;
778
+ }
779
+ catch (err) {
780
+ console.error(`[dashboard] Failed to connect to relay daemon as ${senderName}:`, err);
781
+ return undefined;
782
+ }
783
+ finally {
784
+ // Clean up pending connection
785
+ pendingConnections.delete(senderName);
786
+ }
787
+ })();
788
+ // Store the pending connection
789
+ pendingConnections.set(senderName, connectionPromise);
790
+ return connectionPromise;
791
+ };
792
+ // Start default relay client connection (non-blocking)
793
+ // Use '_DashboardUI' to avoid conflicts with agents named 'Dashboard'
794
+ getRelayClient('_DashboardUI').catch(() => { });
795
+ // User bridge for human-to-human and human-to-agent messaging
796
+ const userBridge = new UserBridge({
797
+ socketPath,
798
+ createRelayClient: async (options) => {
799
+ const client = new RelayClient({
800
+ socketPath: options.socketPath,
801
+ agentName: options.agentName,
802
+ entityType: options.entityType,
803
+ displayName: options.displayName,
804
+ avatarUrl: options.avatarUrl,
805
+ cli: 'dashboard',
806
+ reconnect: true,
807
+ maxReconnectAttempts: 5,
808
+ });
809
+ client.onError = (err) => {
810
+ console.error(`[user-bridge] Relay client error for ${options.agentName}:`, err.message);
811
+ };
812
+ await client.connect();
813
+ return client;
814
+ },
815
+ loadPersistedChannels: (username) => loadPersistedChannelsForUser(username, defaultWorkspaceId),
816
+ });
817
+ // Bridge client for cross-project messaging
818
+ let bridgeClient;
819
+ let bridgeClientConnecting = false;
820
+ const connectBridgeClient = async () => {
821
+ if (bridgeClient || bridgeClientConnecting)
822
+ return;
823
+ // Check if bridge-state.json exists and has projects
824
+ const bridgeStatePath = path.join(dataDir, 'bridge-state.json');
825
+ if (!fs.existsSync(bridgeStatePath)) {
826
+ return;
827
+ }
828
+ try {
829
+ const bridgeState = JSON.parse(fs.readFileSync(bridgeStatePath, 'utf-8'));
830
+ if (!bridgeState.connected || !bridgeState.projects?.length) {
831
+ return;
832
+ }
833
+ bridgeClientConnecting = true;
834
+ // Build project configs from bridge state
835
+ const projectConfigs = bridgeState.projects.map((p) => {
836
+ // Compute socket path for each project
837
+ const projectHash = crypto.createHash('sha256').update(p.path).digest('hex').slice(0, 12);
838
+ const projectDataDir = path.join(path.dirname(dataDir), projectHash);
839
+ const socketPath = path.join(projectDataDir, 'relay.sock');
840
+ return {
841
+ id: p.id,
842
+ path: p.path,
843
+ socketPath,
844
+ leadName: p.lead?.name || 'Lead',
845
+ cli: 'dashboard-bridge',
846
+ };
847
+ });
848
+ // Filter to projects with existing sockets
849
+ const validConfigs = projectConfigs.filter((p) => fs.existsSync(p.socketPath));
850
+ if (validConfigs.length === 0) {
851
+ bridgeClientConnecting = false;
852
+ return;
853
+ }
854
+ bridgeClient = new MultiProjectClient(validConfigs, {
855
+ agentName: '__DashboardBridge__', // Unique name to avoid conflict with CLI bridge
856
+ reconnect: true,
857
+ });
858
+ bridgeClient.onProjectStateChange = (projectId, connected) => {
859
+ console.log(`[dashboard-bridge] Project ${projectId} ${connected ? 'connected' : 'disconnected'}`);
860
+ };
861
+ await bridgeClient.connect();
862
+ console.log('[dashboard] Bridge client connected to', validConfigs.length, 'project(s)');
863
+ bridgeClientConnecting = false;
864
+ }
865
+ catch (err) {
866
+ console.error('[dashboard] Failed to connect bridge client:', err);
867
+ bridgeClient = undefined;
868
+ bridgeClientConnecting = false;
869
+ }
870
+ };
871
+ // Start bridge client connection (non-blocking)
872
+ connectBridgeClient().catch(() => { });
873
+ // Helper to check if an agent is online (seen within heartbeat timeout window)
874
+ // Uses 30 second threshold to align with heartbeat timeout (5s * 6 multiplier)
875
+ const isAgentOnline = (agentName) => {
876
+ if (agentName === '*')
877
+ return true; // Broadcast always allowed
878
+ const agentsPath = path.join(teamDir, 'agents.json');
879
+ if (!fs.existsSync(agentsPath))
880
+ return false;
881
+ try {
882
+ const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
883
+ const agent = data.agents?.find((a) => a.name === agentName);
884
+ if (!agent || !agent.lastSeen)
885
+ return false;
886
+ const thirtySecondsAgo = Date.now() - 30 * 1000;
887
+ return new Date(agent.lastSeen).getTime() > thirtySecondsAgo;
888
+ }
889
+ catch {
890
+ return false;
891
+ }
892
+ };
893
+ const isUserOnline = (username) => {
894
+ if (username === '*')
895
+ return true;
896
+ return onlineUsers.has(username) || userBridge.isUserRegistered(username);
897
+ };
898
+ const isRecipientOnline = (name) => (isAgentOnline(name) || isUserOnline(name));
899
+ // Helper to get team members from teams.json, agents.json, and spawner's active workers
900
+ const getTeamMembers = (teamName) => {
901
+ const members = new Set();
902
+ // Check teams.json first - this is the source of truth for team definitions
903
+ const teamsConfig = loadTeamsConfig(projectRoot || dataDir);
904
+ if (teamsConfig && teamsConfig.team === teamName) {
905
+ for (const agent of teamsConfig.agents) {
906
+ members.add(agent.name);
907
+ }
908
+ }
909
+ // Check spawner's active workers (they have accurate team info for spawned agents)
910
+ if (spawner) {
911
+ const activeWorkers = spawner.getActiveWorkers();
912
+ for (const worker of activeWorkers) {
913
+ if (worker.team === teamName) {
914
+ members.add(worker.name);
915
+ }
916
+ }
917
+ }
918
+ // Also check agents.json for persisted team info
919
+ const agentsPath = path.join(teamDir, 'agents.json');
920
+ if (fs.existsSync(agentsPath)) {
921
+ try {
922
+ const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
923
+ for (const agent of (data.agents || [])) {
924
+ if (agent.team === teamName) {
925
+ members.add(agent.name);
926
+ }
927
+ }
928
+ }
929
+ catch {
930
+ // Ignore parse errors
931
+ }
932
+ }
933
+ return Array.from(members);
934
+ };
935
+ // API endpoint to send messages
936
+ app.post('/api/send', async (req, res) => {
937
+ const { to, message, thread, attachments: attachmentIds, from: senderName } = req.body;
938
+ if (!to || !message) {
939
+ return res.status(400).json({ error: 'Missing "to" or "message" field' });
940
+ }
941
+ // Check if this is a team mention (team:teamName)
942
+ const teamMatch = to.match(/^team:(.+)$/);
943
+ let targets;
944
+ if (teamMatch) {
945
+ const teamName = teamMatch[1];
946
+ const members = getTeamMembers(teamName);
947
+ if (members.length === 0) {
948
+ return res.status(404).json({ error: `No agents found in team "${teamName}"` });
949
+ }
950
+ // Filter to only online members
951
+ targets = members.filter(isAgentOnline);
952
+ if (targets.length === 0) {
953
+ return res.status(404).json({ error: `No online agents in team "${teamName}"` });
954
+ }
955
+ }
956
+ else {
957
+ // Fail fast if target agent is offline (except broadcasts)
958
+ if (to !== '*' && !isRecipientOnline(to)) {
959
+ return res.status(404).json({ error: `Recipient "${to}" is not online` });
960
+ }
961
+ targets = [to];
962
+ }
963
+ // Always use '_DashboardUI' client to avoid name conflicts with user agents
964
+ // (underscore prefix indicates system client, prevents collision if user names an agent "Dashboard")
965
+ // The sender name is preserved in message history/logs but not used for the relay connection
966
+ const relayClient = await getRelayClient('_DashboardUI');
967
+ if (!relayClient || relayClient.state !== 'READY') {
968
+ return res.status(503).json({ error: 'Relay daemon not connected' });
969
+ }
970
+ try {
971
+ // Resolve attachments if provided
972
+ let attachments;
973
+ if (attachmentIds && Array.isArray(attachmentIds) && attachmentIds.length > 0) {
974
+ attachments = [];
975
+ for (const id of attachmentIds) {
976
+ const attachment = attachmentRegistry.get(id);
977
+ if (attachment) {
978
+ attachments.push(attachment);
979
+ }
980
+ }
981
+ }
982
+ // Include attachments, channel context, and sender info in the message data field
983
+ // For broadcasts (to='*'), include channel: 'general' so replies can be routed back
984
+ // For dashboard messages, include senderName so frontend can display actual user instead of '_DashboardUI'
985
+ const isBroadcast = targets.length === 1 && targets[0] === '*';
986
+ const messageData = {};
987
+ if (attachments && attachments.length > 0) {
988
+ messageData.attachments = attachments;
989
+ }
990
+ if (isBroadcast) {
991
+ messageData.channel = 'general';
992
+ }
993
+ // Include actual sender name for dashboard messages (relay client uses '_DashboardUI' but
994
+ // we want the real user's name displayed in message history)
995
+ if (senderName) {
996
+ messageData.senderName = senderName;
997
+ }
998
+ const hasMessageData = Object.keys(messageData).length > 0;
999
+ // Send to all targets (single agent, team members, or broadcast)
1000
+ let allSent = true;
1001
+ for (const target of targets) {
1002
+ const sent = relayClient.sendMessage(target, message, 'message', hasMessageData ? messageData : undefined, thread);
1003
+ if (!sent) {
1004
+ allSent = false;
1005
+ console.error(`[dashboard] Failed to send message to ${target}`);
1006
+ }
1007
+ }
1008
+ if (allSent) {
1009
+ // Broadcast updated data to all connected clients so they see the sent message
1010
+ broadcastData().catch((err) => console.error('[dashboard] Failed to broadcast after send:', err));
1011
+ res.json({ success: true, sentTo: targets.length > 1 ? targets : targets[0] });
1012
+ }
1013
+ else {
1014
+ res.status(500).json({ error: 'Failed to send message to some recipients' });
1015
+ }
1016
+ }
1017
+ catch (err) {
1018
+ console.error('[dashboard] Failed to send message:', err);
1019
+ res.status(500).json({ error: 'Failed to send message' });
1020
+ }
1021
+ });
1022
+ // API endpoint to send messages via bridge (cross-project)
1023
+ app.post('/api/bridge/send', async (req, res) => {
1024
+ const { projectId, to, message } = req.body;
1025
+ if (!projectId || !to || !message) {
1026
+ return res.status(400).json({ error: 'Missing "projectId", "to", or "message" field' });
1027
+ }
1028
+ // Try to connect bridge client if not connected
1029
+ if (!bridgeClient) {
1030
+ await connectBridgeClient();
1031
+ if (!bridgeClient) {
1032
+ return res.status(503).json({ error: 'Bridge not connected. Is the bridge command running?' });
1033
+ }
1034
+ }
1035
+ try {
1036
+ const sent = bridgeClient.sendToProject(projectId, to, message);
1037
+ if (sent) {
1038
+ res.json({ success: true });
1039
+ }
1040
+ else {
1041
+ res.status(500).json({ error: `Failed to send message to ${projectId}:${to}` });
1042
+ }
1043
+ }
1044
+ catch (err) {
1045
+ console.error('[dashboard] Failed to send bridge message:', err);
1046
+ res.status(500).json({ error: 'Failed to send bridge message' });
1047
+ }
1048
+ });
1049
+ // API endpoint to upload attachments (images/screenshots)
1050
+ app.post('/api/upload', async (req, res) => {
1051
+ const { filename, mimeType, data } = req.body;
1052
+ // Validate required fields
1053
+ if (!filename || !mimeType || !data) {
1054
+ return res.status(400).json({
1055
+ success: false,
1056
+ error: 'Missing required fields: filename, mimeType, data',
1057
+ });
1058
+ }
1059
+ // Validate mime type (only allow images for now)
1060
+ const allowedTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/svg+xml'];
1061
+ if (!allowedTypes.includes(mimeType)) {
1062
+ return res.status(400).json({
1063
+ success: false,
1064
+ error: `Invalid file type. Allowed types: ${allowedTypes.join(', ')}`,
1065
+ });
1066
+ }
1067
+ try {
1068
+ // Decode base64 data
1069
+ const base64Data = data.replace(/^data:[^;]+;base64,/, '');
1070
+ const buffer = Buffer.from(base64Data, 'base64');
1071
+ // Generate unique ID and filename for the attachment
1072
+ const attachmentId = crypto.randomUUID();
1073
+ const timestamp = Date.now();
1074
+ const ext = mimeType.split('/')[1].replace('svg+xml', 'svg');
1075
+ // Use format: {messageId}-{timestamp}.{ext} for unique, identifiable filenames
1076
+ const safeFilename = `${attachmentId.substring(0, 8)}-${timestamp}.${ext}`;
1077
+ // Save to ~/.relay/attachments/ directory for agents to access
1078
+ const attachmentFilePath = path.join(attachmentsDir, safeFilename);
1079
+ fs.writeFileSync(attachmentFilePath, buffer);
1080
+ // Create attachment record with file path for agents
1081
+ const attachment = {
1082
+ id: attachmentId,
1083
+ filename: filename,
1084
+ mimeType: mimeType,
1085
+ size: buffer.length,
1086
+ url: `/attachments/${safeFilename}`,
1087
+ // Include absolute file path so agents can read the file directly
1088
+ filePath: attachmentFilePath,
1089
+ // Include base64 data for agents that can't access the file
1090
+ data: data,
1091
+ };
1092
+ // Store in registry for lookup when sending messages
1093
+ attachmentRegistry.set(attachmentId, attachment);
1094
+ console.log(`[dashboard] Uploaded attachment: ${filename} (${buffer.length} bytes) -> ${attachmentFilePath}`);
1095
+ res.json({
1096
+ success: true,
1097
+ attachment: {
1098
+ id: attachment.id,
1099
+ filename: attachment.filename,
1100
+ mimeType: attachment.mimeType,
1101
+ size: attachment.size,
1102
+ url: attachment.url,
1103
+ filePath: attachment.filePath,
1104
+ },
1105
+ });
1106
+ }
1107
+ catch (err) {
1108
+ console.error('[dashboard] Upload failed:', err);
1109
+ res.status(500).json({
1110
+ success: false,
1111
+ error: 'Failed to upload file',
1112
+ });
1113
+ }
1114
+ });
1115
+ // API endpoint to get attachment by ID
1116
+ app.get('/api/attachment/:id', (req, res) => {
1117
+ const { id } = req.params;
1118
+ const attachment = attachmentRegistry.get(id);
1119
+ if (!attachment) {
1120
+ return res.status(404).json({ error: 'Attachment not found' });
1121
+ }
1122
+ res.json({
1123
+ success: true,
1124
+ attachment: {
1125
+ id: attachment.id,
1126
+ filename: attachment.filename,
1127
+ mimeType: attachment.mimeType,
1128
+ size: attachment.size,
1129
+ url: attachment.url,
1130
+ filePath: attachment.filePath,
1131
+ },
1132
+ });
1133
+ });
1134
+ const getTeamData = () => {
1135
+ // Try team.json first (file-based team mode)
1136
+ const teamPath = path.join(teamDir, 'team.json');
1137
+ if (fs.existsSync(teamPath)) {
1138
+ try {
1139
+ return JSON.parse(fs.readFileSync(teamPath, 'utf-8'));
1140
+ }
1141
+ catch (e) {
1142
+ console.error('Failed to read team.json', e);
1143
+ }
1144
+ }
1145
+ // Fall back to agents.json (daemon mode - live connected agents)
1146
+ const agentsPath = path.join(teamDir, 'agents.json');
1147
+ if (fs.existsSync(agentsPath)) {
1148
+ try {
1149
+ const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
1150
+ // Convert agents.json format to team.json format
1151
+ return {
1152
+ agents: data.agents.map((a) => ({
1153
+ name: a.name,
1154
+ role: 'Agent',
1155
+ cli: a.cli ?? 'Unknown',
1156
+ lastSeen: a.lastSeen ?? a.connectedAt,
1157
+ lastActive: a.lastSeen ?? a.connectedAt,
1158
+ team: a.team,
1159
+ })),
1160
+ };
1161
+ }
1162
+ catch (e) {
1163
+ console.error('Failed to read agents.json', e);
1164
+ }
1165
+ }
1166
+ return null;
1167
+ };
1168
+ const parseInbox = (agentName) => {
1169
+ const inboxPath = path.join(dataDir, agentName, 'inbox.md');
1170
+ if (!fs.existsSync(inboxPath))
1171
+ return [];
1172
+ try {
1173
+ const content = fs.readFileSync(inboxPath, 'utf-8');
1174
+ const messages = [];
1175
+ // Split by "## Message from "
1176
+ const parts = content.split('## Message from ');
1177
+ parts.forEach((part, index) => {
1178
+ if (!part.trim())
1179
+ return;
1180
+ const firstLineEnd = part.indexOf('\n');
1181
+ if (firstLineEnd === -1)
1182
+ return;
1183
+ const header = part.substring(0, firstLineEnd).trim(); // "Sender | Timestamp" or just "Sender"
1184
+ const body = part.substring(firstLineEnd).trim();
1185
+ // Handle potential " | " in header
1186
+ let sender = header;
1187
+ let timestamp = new Date().toISOString();
1188
+ if (header.includes('|')) {
1189
+ const split = header.split('|');
1190
+ sender = split[0].trim();
1191
+ timestamp = split.slice(1).join('|').trim();
1192
+ }
1193
+ messages.push({
1194
+ from: sender,
1195
+ to: agentName,
1196
+ content: body,
1197
+ timestamp: timestamp,
1198
+ id: `${agentName}-${index}-${Date.now()}`
1199
+ });
1200
+ });
1201
+ return messages;
1202
+ }
1203
+ catch (e) {
1204
+ console.error(`Failed to read inbox for ${agentName}`, e);
1205
+ return [];
1206
+ }
1207
+ };
1208
+ // Helper to check if an agent name is internal/system (should be hidden from UI)
1209
+ // Convention: agent names starting with __ are internal (e.g., __spawner__, __DashboardBridge__)
1210
+ const isInternalAgent = (name) => {
1211
+ return name.startsWith('__');
1212
+ };
1213
+ const mapStoredMessages = (rows) => rows
1214
+ // Filter out messages from/to internal system agents (e.g., __spawner__)
1215
+ .filter((row) => !isInternalAgent(row.from) && !isInternalAgent(row.to))
1216
+ .map((row) => {
1217
+ // Extract attachments, channel, and senderName from the data field if present
1218
+ let attachments;
1219
+ let channel;
1220
+ let effectiveFrom = row.from;
1221
+ if (row.data && typeof row.data === 'object') {
1222
+ if ('attachments' in row.data) {
1223
+ attachments = row.data.attachments;
1224
+ }
1225
+ if ('channel' in row.data) {
1226
+ channel = row.data.channel;
1227
+ }
1228
+ // For dashboard messages sent via _DashboardUI, use the actual sender name
1229
+ // This provides proper attribution in message history
1230
+ if ('senderName' in row.data && row.from === '_DashboardUI') {
1231
+ effectiveFrom = row.data.senderName;
1232
+ }
1233
+ }
1234
+ return {
1235
+ from: effectiveFrom,
1236
+ to: row.to,
1237
+ content: row.body,
1238
+ timestamp: new Date(row.ts).toISOString(),
1239
+ id: row.id,
1240
+ thread: row.thread,
1241
+ isBroadcast: row.is_broadcast,
1242
+ replyCount: row.replyCount,
1243
+ status: row.status,
1244
+ attachments,
1245
+ channel,
1246
+ };
1247
+ });
1248
+ const getMessages = async (agents) => {
1249
+ if (storage) {
1250
+ const rows = await storage.getMessages({ limit: 100, order: 'desc' });
1251
+ // Dashboard expects oldest first
1252
+ return mapStoredMessages(rows).reverse();
1253
+ }
1254
+ // Fallback to file-based inbox parsing
1255
+ let allMessages = [];
1256
+ agents.forEach((a) => {
1257
+ const msgs = parseInbox(a.name);
1258
+ allMessages = [...allMessages, ...msgs];
1259
+ });
1260
+ return allMessages;
1261
+ };
1262
+ const formatDuration = (startMs, endMs) => {
1263
+ const end = endMs ?? Date.now();
1264
+ const durationMs = end - startMs;
1265
+ const minutes = Math.floor(durationMs / 60000);
1266
+ const hours = Math.floor(minutes / 60);
1267
+ if (hours > 0) {
1268
+ return `${hours}h ${minutes % 60}m`;
1269
+ }
1270
+ return `${minutes}m`;
1271
+ };
1272
+ const getRecentSessions = async () => {
1273
+ if (storage && storage instanceof SqliteStorageAdapter) {
1274
+ const sessions = await storage.getRecentSessions(20);
1275
+ return sessions.map(s => ({
1276
+ id: s.id,
1277
+ agentName: s.agentName,
1278
+ cli: s.cli,
1279
+ startedAt: new Date(s.startedAt).toISOString(),
1280
+ endedAt: s.endedAt ? new Date(s.endedAt).toISOString() : undefined,
1281
+ duration: formatDuration(s.startedAt, s.endedAt),
1282
+ messageCount: s.messageCount,
1283
+ summary: s.summary,
1284
+ isActive: !s.endedAt, // Active if no end time
1285
+ closedBy: s.closedBy,
1286
+ }));
1287
+ }
1288
+ return [];
1289
+ };
1290
+ const getAgentSummaries = async () => {
1291
+ if (storage && storage instanceof SqliteStorageAdapter) {
1292
+ const summaries = await storage.getAllAgentSummaries();
1293
+ return summaries.map(s => ({
1294
+ agentName: s.agentName,
1295
+ lastUpdated: new Date(s.lastUpdated).toISOString(),
1296
+ currentTask: s.currentTask,
1297
+ completedTasks: s.completedTasks,
1298
+ context: s.context,
1299
+ }));
1300
+ }
1301
+ return [];
1302
+ };
1303
+ const getAllData = async () => {
1304
+ const team = getTeamData();
1305
+ if (!team)
1306
+ return { agents: [], messages: [], activity: [], sessions: [], summaries: [] };
1307
+ const agentsMap = new Map();
1308
+ const allMessages = await getMessages(team.agents);
1309
+ // Initialize agents from config
1310
+ team.agents.forEach((a) => {
1311
+ agentsMap.set(a.name, {
1312
+ name: a.name,
1313
+ role: a.role,
1314
+ cli: a.cli ?? 'Unknown',
1315
+ messageCount: 0,
1316
+ status: 'Idle',
1317
+ lastSeen: a.lastSeen,
1318
+ lastActive: a.lastActive,
1319
+ needsAttention: false,
1320
+ team: a.team,
1321
+ });
1322
+ });
1323
+ // Inject online human users (connected via dashboard WebSocket) into agentsMap
1324
+ // These users are tracked in onlineUsers for presence but need to appear in the agents list
1325
+ // with cli: 'dashboard' so they show up in the sidebar for DM conversations
1326
+ for (const [username, state] of onlineUsers) {
1327
+ const existing = agentsMap.get(username);
1328
+ if (existing) {
1329
+ // Update existing entry to ensure cli: 'dashboard' for proper human/agent separation
1330
+ // This fixes the bug where users appear as both human AND agent if they have a stale
1331
+ // entry in agents.json with a different cli value
1332
+ existing.cli = 'dashboard';
1333
+ existing.status = 'online';
1334
+ existing.avatarUrl = state.info.avatarUrl || existing.avatarUrl;
1335
+ }
1336
+ else {
1337
+ agentsMap.set(username, {
1338
+ name: username,
1339
+ role: 'User',
1340
+ cli: 'dashboard',
1341
+ messageCount: 0,
1342
+ status: 'online',
1343
+ lastSeen: state.info.lastSeen,
1344
+ lastActive: state.info.lastSeen,
1345
+ needsAttention: false,
1346
+ avatarUrl: state.info.avatarUrl,
1347
+ });
1348
+ }
1349
+ }
1350
+ // Update inbox counts if fallback mode; if storage, count messages addressed to agent
1351
+ if (storage) {
1352
+ for (const msg of allMessages) {
1353
+ const agent = agentsMap.get(msg.to);
1354
+ if (agent) {
1355
+ agent.messageCount = (agent.messageCount ?? 0) + 1;
1356
+ }
1357
+ }
1358
+ }
1359
+ else {
1360
+ // Sort by timestamp
1361
+ allMessages.sort((a, b) => {
1362
+ return new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime();
1363
+ });
1364
+ }
1365
+ // Derive status from messages sent BY agents
1366
+ // We scan all messages; if M is from A, we check if it is a STATUS message
1367
+ // Note: lastActive is updated from messages, but lastSeen comes from the registry
1368
+ // (heartbeat-based) and should NOT be overwritten by message timestamps
1369
+ allMessages.forEach(m => {
1370
+ const agent = agentsMap.get(m.from);
1371
+ if (agent) {
1372
+ agent.lastActive = m.timestamp;
1373
+ // Don't overwrite lastSeen - it comes from registry (heartbeat/connection tracking)
1374
+ if (m.content.startsWith('STATUS:')) {
1375
+ agent.status = m.content.substring(7).trim(); // remove "STATUS:"
1376
+ }
1377
+ }
1378
+ });
1379
+ // Detect agents with unanswered inbound messages (needs attention)
1380
+ const needsAttentionAgents = computeNeedsAttention(allMessages.map((m) => ({
1381
+ from: m.from,
1382
+ to: m.to,
1383
+ timestamp: m.timestamp,
1384
+ thread: m.thread,
1385
+ isBroadcast: m.isBroadcast,
1386
+ })));
1387
+ needsAttentionAgents.forEach((agentName) => {
1388
+ const agent = agentsMap.get(agentName);
1389
+ if (agent) {
1390
+ agent.needsAttention = true;
1391
+ }
1392
+ });
1393
+ // Read processing state from daemon
1394
+ const processingStatePath = path.join(teamDir, 'processing-state.json');
1395
+ if (fs.existsSync(processingStatePath)) {
1396
+ try {
1397
+ const processingData = JSON.parse(fs.readFileSync(processingStatePath, 'utf-8'));
1398
+ const processingAgents = processingData.processingAgents || {};
1399
+ for (const [agentName, state] of Object.entries(processingAgents)) {
1400
+ const agent = agentsMap.get(agentName);
1401
+ if (agent && state && typeof state === 'object') {
1402
+ agent.isProcessing = true;
1403
+ agent.processingStartedAt = state.startedAt;
1404
+ }
1405
+ }
1406
+ }
1407
+ catch (_err) {
1408
+ // Ignore errors reading processing state - it's optional
1409
+ }
1410
+ }
1411
+ // Mark spawned agents with isSpawned flag and team
1412
+ if (spawner) {
1413
+ const activeWorkers = spawner.getActiveWorkers();
1414
+ for (const worker of activeWorkers) {
1415
+ const agent = agentsMap.get(worker.name);
1416
+ if (agent) {
1417
+ agent.isSpawned = true;
1418
+ if (worker.team) {
1419
+ agent.team = worker.team;
1420
+ }
1421
+ }
1422
+ }
1423
+ }
1424
+ // Set team from teams.json for agents that don't have a team yet
1425
+ // This ensures agents defined in teams.json are associated with their team
1426
+ // even if they weren't spawned via auto-spawn
1427
+ const teamsConfig = loadTeamsConfig(projectRoot || dataDir);
1428
+ if (teamsConfig) {
1429
+ for (const teamAgent of teamsConfig.agents) {
1430
+ const agent = agentsMap.get(teamAgent.name);
1431
+ if (agent && !agent.team) {
1432
+ agent.team = teamsConfig.team;
1433
+ }
1434
+ }
1435
+ }
1436
+ // Fetch sessions and summaries in parallel
1437
+ const [sessions, summaries] = await Promise.all([
1438
+ getRecentSessions(),
1439
+ getAgentSummaries(),
1440
+ ]);
1441
+ // Filter and separate agents from human users:
1442
+ // 1. Exclude "Dashboard" (internal agent, not a real team member)
1443
+ // 2. Exclude offline agents (no lastSeen or lastSeen > threshold)
1444
+ // 3. Exclude agents without a known CLI (these are improperly registered or stale)
1445
+ // 4. Separate human users (cli === 'dashboard') from AI agents
1446
+ const now = Date.now();
1447
+ // 30 seconds - aligns with heartbeat timeout (5s heartbeat * 6 multiplier = 30s)
1448
+ // This ensures agents disappear quickly after they stop responding to heartbeats
1449
+ const OFFLINE_THRESHOLD_MS = 30 * 1000;
1450
+ // First pass: filter out invalid/offline entries
1451
+ const validEntries = Array.from(agentsMap.values())
1452
+ .filter(agent => {
1453
+ // Exclude Dashboard
1454
+ if (agent.name === 'Dashboard')
1455
+ return false;
1456
+ // Exclude agents starting with __ (internal/system agents)
1457
+ if (agent.name.startsWith('__'))
1458
+ return false;
1459
+ // Exclude agents without a proper CLI (improperly registered or stale)
1460
+ if (!agent.cli || agent.cli === 'Unknown')
1461
+ return false;
1462
+ // Exclude offline agents (no lastSeen or too old)
1463
+ if (!agent.lastSeen)
1464
+ return false;
1465
+ const lastSeenTime = new Date(agent.lastSeen).getTime();
1466
+ if (now - lastSeenTime > OFFLINE_THRESHOLD_MS)
1467
+ return false;
1468
+ return true;
1469
+ });
1470
+ // Separate AI agents from human users
1471
+ const filteredAgents = validEntries
1472
+ .filter(agent => agent.cli !== 'dashboard')
1473
+ .map(agent => ({
1474
+ ...agent,
1475
+ isHuman: false,
1476
+ }));
1477
+ const humanUsers = validEntries
1478
+ .filter(agent => agent.cli === 'dashboard')
1479
+ .map(agent => ({
1480
+ ...agent,
1481
+ isHuman: true,
1482
+ }));
1483
+ return {
1484
+ agents: filteredAgents,
1485
+ users: humanUsers,
1486
+ messages: allMessages,
1487
+ activity: allMessages, // For now, activity log is just the message log
1488
+ sessions,
1489
+ summaries,
1490
+ };
1491
+ };
1492
+ // Track clients that are still initializing (haven't received first data yet)
1493
+ // This prevents race conditions where broadcastData sends before initial data is sent
1494
+ const initializingClients = new WeakSet();
1495
+ const broadcastData = async () => {
1496
+ try {
1497
+ const data = await getAllData();
1498
+ const payload = JSON.stringify(data);
1499
+ // Guard against empty/invalid payloads
1500
+ if (!payload || payload.length === 0) {
1501
+ console.warn('[dashboard] Skipping broadcast - empty payload');
1502
+ return;
1503
+ }
1504
+ wss.clients.forEach(client => {
1505
+ // Skip clients that are still being initialized by the connection handler
1506
+ if (initializingClients.has(client)) {
1507
+ return;
1508
+ }
1509
+ if (client.readyState === WebSocket.OPEN) {
1510
+ try {
1511
+ client.send(payload);
1512
+ }
1513
+ catch (err) {
1514
+ console.error('[dashboard] Failed to send to client:', err);
1515
+ }
1516
+ }
1517
+ });
1518
+ }
1519
+ catch (err) {
1520
+ console.error('[dashboard] Failed to broadcast data:', err);
1521
+ }
1522
+ };
1523
+ // Bridge data functions - defined before connection handlers
1524
+ const getBridgeData = async () => {
1525
+ const bridgeStatePath = path.join(dataDir, 'bridge-state.json');
1526
+ if (fs.existsSync(bridgeStatePath)) {
1527
+ try {
1528
+ const bridgeState = JSON.parse(fs.readFileSync(bridgeStatePath, 'utf-8'));
1529
+ // Enrich each project with actual agent data from their team directories
1530
+ if (bridgeState.projects && Array.isArray(bridgeState.projects)) {
1531
+ for (const project of bridgeState.projects) {
1532
+ if (project.path) {
1533
+ // Get project's data directory
1534
+ const crypto = await import('crypto');
1535
+ const projectHash = crypto.createHash('sha256').update(project.path).digest('hex').slice(0, 12);
1536
+ const projectDataDir = path.join(path.dirname(dataDir), projectHash);
1537
+ const projectTeamDir = path.join(projectDataDir, 'team');
1538
+ const agentsPath = path.join(projectTeamDir, 'agents.json');
1539
+ // Read actual connected agents
1540
+ if (fs.existsSync(agentsPath)) {
1541
+ try {
1542
+ const agentsData = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
1543
+ if (agentsData.agents && Array.isArray(agentsData.agents)) {
1544
+ // Filter to only show online agents (seen within 30 seconds - aligns with heartbeat timeout)
1545
+ const thirtySecondsAgo = Date.now() - 30 * 1000;
1546
+ project.agents = agentsData.agents
1547
+ .filter((a) => {
1548
+ if (!a.lastSeen)
1549
+ return false;
1550
+ return new Date(a.lastSeen).getTime() > thirtySecondsAgo;
1551
+ })
1552
+ .map((a) => ({
1553
+ name: a.name,
1554
+ status: 'active',
1555
+ cli: a.cli,
1556
+ lastSeen: a.lastSeen,
1557
+ }));
1558
+ // Update lead status based on actual agents
1559
+ if (project.lead) {
1560
+ const leadAgent = project.agents.find((a) => a.name.toLowerCase() === project.lead.name.toLowerCase());
1561
+ project.lead.connected = !!leadAgent;
1562
+ }
1563
+ }
1564
+ }
1565
+ catch (e) {
1566
+ console.error(`Failed to read agents for ${project.path}:`, e);
1567
+ }
1568
+ }
1569
+ }
1570
+ }
1571
+ }
1572
+ return bridgeState;
1573
+ }
1574
+ catch {
1575
+ return { projects: [], messages: [], connected: false };
1576
+ }
1577
+ }
1578
+ return { projects: [], messages: [], connected: false };
1579
+ };
1580
+ const broadcastBridgeData = async () => {
1581
+ try {
1582
+ const data = await getBridgeData();
1583
+ const payload = JSON.stringify(data);
1584
+ // Guard against empty/invalid payloads
1585
+ if (!payload || payload.length === 0) {
1586
+ console.warn('[dashboard] Skipping bridge broadcast - empty payload');
1587
+ return;
1588
+ }
1589
+ wssBridge.clients.forEach(client => {
1590
+ if (client.readyState === WebSocket.OPEN) {
1591
+ try {
1592
+ client.send(payload);
1593
+ }
1594
+ catch (err) {
1595
+ console.error('[dashboard] Failed to send to bridge client:', err);
1596
+ }
1597
+ }
1598
+ });
1599
+ }
1600
+ catch (err) {
1601
+ console.error('[dashboard] Failed to broadcast bridge data:', err);
1602
+ }
1603
+ };
1604
+ // Handle new WebSocket connections - send initial data immediately
1605
+ wss.on('connection', async (ws, req) => {
1606
+ console.log('[dashboard] WebSocket client connected from:', req.socket.remoteAddress);
1607
+ // Mark client as alive initially for ping/pong keepalive
1608
+ mainClientAlive.set(ws, true);
1609
+ // Handle pong responses (keep connection alive)
1610
+ ws.on('pong', () => {
1611
+ mainClientAlive.set(ws, true);
1612
+ });
1613
+ // Mark as initializing to prevent broadcastData from sending before we do
1614
+ initializingClients.add(ws);
1615
+ try {
1616
+ const data = await getAllData();
1617
+ const payload = JSON.stringify(data);
1618
+ // Guard against empty/invalid payloads
1619
+ if (!payload || payload.length === 0) {
1620
+ console.warn('[dashboard] Skipping initial send - empty payload');
1621
+ return;
1622
+ }
1623
+ if (ws.readyState === WebSocket.OPEN) {
1624
+ console.log('[dashboard] Sending initial data, size:', payload.length, 'first 200 chars:', payload.substring(0, 200));
1625
+ ws.send(payload);
1626
+ console.log('[dashboard] Initial data sent successfully');
1627
+ }
1628
+ else {
1629
+ console.warn('[dashboard] WebSocket not open, state:', ws.readyState);
1630
+ }
1631
+ }
1632
+ catch (err) {
1633
+ console.error('[dashboard] Failed to send initial data:', err);
1634
+ }
1635
+ finally {
1636
+ // Now allow broadcastData to send to this client
1637
+ initializingClients.delete(ws);
1638
+ }
1639
+ ws.on('error', (err) => {
1640
+ console.error('[dashboard] WebSocket client error:', err);
1641
+ });
1642
+ ws.on('close', (code, reason) => {
1643
+ console.log('[dashboard] WebSocket client disconnected, code:', code, 'reason:', reason?.toString() || 'none');
1644
+ });
1645
+ });
1646
+ // Handle bridge WebSocket connections
1647
+ wssBridge.on('connection', async (ws) => {
1648
+ console.log('[dashboard] Bridge WebSocket client connected');
1649
+ // Mark client as alive initially for ping/pong keepalive
1650
+ bridgeClientAlive.set(ws, true);
1651
+ // Handle pong responses (keep connection alive)
1652
+ ws.on('pong', () => {
1653
+ bridgeClientAlive.set(ws, true);
1654
+ });
1655
+ try {
1656
+ const data = await getBridgeData();
1657
+ const payload = JSON.stringify(data);
1658
+ if (ws.readyState === WebSocket.OPEN) {
1659
+ ws.send(payload);
1660
+ }
1661
+ }
1662
+ catch (err) {
1663
+ console.error('[dashboard] Failed to send initial bridge data:', err);
1664
+ }
1665
+ ws.on('error', (err) => {
1666
+ console.error('[dashboard] Bridge WebSocket client error:', err);
1667
+ });
1668
+ ws.on('close', (code, reason) => {
1669
+ console.log('[dashboard] Bridge WebSocket client disconnected, code:', code, 'reason:', reason?.toString() || 'none');
1670
+ });
1671
+ });
1672
+ // Track alive status for ping/pong keepalive on log connections
1673
+ const logClientAlive = new WeakMap();
1674
+ // Ping interval for log WebSocket connections (30 seconds)
1675
+ // This prevents TCP/proxy timeouts from killing idle connections
1676
+ const LOG_PING_INTERVAL_MS = 30000;
1677
+ const logPingInterval = setInterval(() => {
1678
+ wssLogs.clients.forEach((ws) => {
1679
+ if (logClientAlive.get(ws) === false) {
1680
+ // Client didn't respond to last ping - close gracefully
1681
+ console.log('[dashboard] Logs WebSocket client unresponsive, closing gracefully');
1682
+ ws.close(1000, 'unresponsive');
1683
+ return;
1684
+ }
1685
+ // Mark as not alive until we get a pong
1686
+ logClientAlive.set(ws, false);
1687
+ ws.ping();
1688
+ });
1689
+ }, LOG_PING_INTERVAL_MS);
1690
+ // Clean up ping interval on server close
1691
+ wssLogs.on('close', () => {
1692
+ clearInterval(logPingInterval);
1693
+ });
1694
+ // Handle logs WebSocket connections for live log streaming
1695
+ wssLogs.on('connection', (ws, req) => {
1696
+ console.log('[dashboard] Logs WebSocket client connected');
1697
+ const clientSubscriptions = new Set();
1698
+ // Mark client as alive initially
1699
+ logClientAlive.set(ws, true);
1700
+ // Handle pong responses (keep connection alive)
1701
+ ws.on('pong', () => {
1702
+ logClientAlive.set(ws, true);
1703
+ });
1704
+ // Helper to check if agent is daemon-connected (from agents.json)
1705
+ const isDaemonConnected = (agentName) => {
1706
+ const agentsPath = path.join(teamDir, 'agents.json');
1707
+ if (!fs.existsSync(agentsPath))
1708
+ return false;
1709
+ try {
1710
+ const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
1711
+ return data.agents?.some((a) => a.name === agentName) ?? false;
1712
+ }
1713
+ catch {
1714
+ return false;
1715
+ }
1716
+ };
1717
+ // Helper to subscribe to an agent
1718
+ const subscribeToAgent = (agentName) => {
1719
+ const isSpawned = spawner?.hasWorker(agentName) ?? false;
1720
+ const isDaemon = isDaemonConnected(agentName);
1721
+ // Check if agent exists (either spawned or daemon-connected)
1722
+ if (!isSpawned && !isDaemon) {
1723
+ ws.send(JSON.stringify({
1724
+ type: 'error',
1725
+ agent: agentName,
1726
+ error: `Agent ${agentName} not found`,
1727
+ }));
1728
+ // Close with custom code 4404 to signal "agent not found" - client should not reconnect
1729
+ ws.close(4404, 'Agent not found');
1730
+ return false;
1731
+ }
1732
+ // Add to subscriptions
1733
+ clientSubscriptions.add(agentName);
1734
+ if (!logSubscriptions.has(agentName)) {
1735
+ logSubscriptions.set(agentName, new Set());
1736
+ }
1737
+ logSubscriptions.get(agentName).add(ws);
1738
+ console.log(`[dashboard] Client subscribed to logs for: ${agentName} (spawned: ${isSpawned}, daemon: ${isDaemon})`);
1739
+ if (isSpawned && spawner) {
1740
+ // Send initial log history for spawned agents (5000 lines to match xterm scrollback capacity)
1741
+ const lines = spawner.getWorkerOutput(agentName, 5000);
1742
+ ws.send(JSON.stringify({
1743
+ type: 'history',
1744
+ agent: agentName,
1745
+ lines: lines || [],
1746
+ }));
1747
+ }
1748
+ else {
1749
+ // For daemon-connected agents, explain that PTY output isn't available
1750
+ ws.send(JSON.stringify({
1751
+ type: 'history',
1752
+ agent: agentName,
1753
+ lines: [`[${agentName} is a daemon-connected agent - PTY output not available. Showing relay messages only.]`],
1754
+ }));
1755
+ }
1756
+ ws.send(JSON.stringify({
1757
+ type: 'subscribed',
1758
+ agent: agentName,
1759
+ }));
1760
+ return true;
1761
+ };
1762
+ // Check if agent name is in URL path: /ws/logs/:agentName
1763
+ const pathname = new URL(req.url || '', `http://${req.headers.host}`).pathname;
1764
+ const pathMatch = pathname.match(/^\/ws\/logs\/(.+)$/);
1765
+ if (pathMatch) {
1766
+ const agentName = decodeURIComponent(pathMatch[1]);
1767
+ subscribeToAgent(agentName);
1768
+ }
1769
+ ws.on('message', (data) => {
1770
+ try {
1771
+ const msg = JSON.parse(data.toString());
1772
+ // Subscribe to agent logs
1773
+ if (msg.subscribe && typeof msg.subscribe === 'string') {
1774
+ subscribeToAgent(msg.subscribe);
1775
+ }
1776
+ // Unsubscribe from agent logs
1777
+ if (msg.unsubscribe && typeof msg.unsubscribe === 'string') {
1778
+ const agentName = msg.unsubscribe;
1779
+ clientSubscriptions.delete(agentName);
1780
+ logSubscriptions.get(agentName)?.delete(ws);
1781
+ console.log(`[dashboard] Client unsubscribed from logs for: ${agentName}`);
1782
+ ws.send(JSON.stringify({
1783
+ type: 'unsubscribed',
1784
+ agent: agentName,
1785
+ }));
1786
+ }
1787
+ // Handle interactive terminal input
1788
+ if (msg.type === 'input' && typeof msg.data === 'string') {
1789
+ // Get agent name from message or use first subscribed agent
1790
+ const agentName = msg.agent || [...clientSubscriptions][0];
1791
+ if (!agentName) {
1792
+ ws.send(JSON.stringify({
1793
+ type: 'error',
1794
+ error: 'No agent subscribed for input',
1795
+ }));
1796
+ return;
1797
+ }
1798
+ // Check if this is a spawned agent (we can only send input to spawned agents)
1799
+ if (spawner?.hasWorker(agentName)) {
1800
+ const success = spawner.sendWorkerInput(agentName, msg.data);
1801
+ if (!success) {
1802
+ console.warn(`[dashboard] Failed to send input to agent ${agentName}`);
1803
+ }
1804
+ }
1805
+ else {
1806
+ // Daemon-connected agents don't support direct input
1807
+ ws.send(JSON.stringify({
1808
+ type: 'error',
1809
+ agent: agentName,
1810
+ error: 'Interactive input not supported for daemon-connected agents',
1811
+ }));
1812
+ }
1813
+ }
1814
+ }
1815
+ catch (err) {
1816
+ console.error('[dashboard] Invalid logs WebSocket message:', err);
1817
+ }
1818
+ });
1819
+ ws.on('error', (err) => {
1820
+ console.error('[dashboard] Logs WebSocket client error:', err);
1821
+ });
1822
+ ws.on('close', (code, reason) => {
1823
+ // Clean up subscriptions on disconnect
1824
+ for (const agentName of clientSubscriptions) {
1825
+ logSubscriptions.get(agentName)?.delete(ws);
1826
+ }
1827
+ const reasonStr = reason?.toString() || 'no reason';
1828
+ console.log(`[dashboard] Logs WebSocket client disconnected (code: ${code}, reason: ${reasonStr})`);
1829
+ });
1830
+ });
1831
+ // Deduplication for log output - prevent same content from being broadcast multiple times
1832
+ // Key: agentName -> Set of recent content hashes (rolling window)
1833
+ const recentLogHashes = new Map();
1834
+ const MAX_LOG_HASH_WINDOW = 50; // Keep last 50 hashes per agent
1835
+ // Simple hash function for log dedup
1836
+ const hashLogContent = (content) => {
1837
+ // Normalize whitespace and create a simple hash
1838
+ const normalized = content.replace(/\s+/g, ' ').trim().slice(0, 200);
1839
+ let hash = 0;
1840
+ for (let i = 0; i < normalized.length; i++) {
1841
+ const char = normalized.charCodeAt(i);
1842
+ hash = ((hash << 5) - hash) + char;
1843
+ hash = hash & hash;
1844
+ }
1845
+ return hash.toString(36);
1846
+ };
1847
+ // Function to broadcast log output to subscribed clients
1848
+ const broadcastLogOutput = (agentName, output) => {
1849
+ const clients = logSubscriptions.get(agentName);
1850
+ if (!clients || clients.size === 0)
1851
+ return;
1852
+ // Skip empty or whitespace-only output
1853
+ const trimmed = output.trim();
1854
+ if (!trimmed)
1855
+ return;
1856
+ // Dedup: Check if we've recently broadcast this content
1857
+ const hash = hashLogContent(output);
1858
+ let agentHashes = recentLogHashes.get(agentName);
1859
+ if (!agentHashes) {
1860
+ agentHashes = new Set();
1861
+ recentLogHashes.set(agentName, agentHashes);
1862
+ }
1863
+ if (agentHashes.has(hash)) {
1864
+ // Already broadcast this content recently, skip
1865
+ return;
1866
+ }
1867
+ // Add to rolling window
1868
+ agentHashes.add(hash);
1869
+ if (agentHashes.size > MAX_LOG_HASH_WINDOW) {
1870
+ // Remove oldest entry (first in Set iteration order)
1871
+ const oldest = agentHashes.values().next().value;
1872
+ if (oldest !== undefined) {
1873
+ agentHashes.delete(oldest);
1874
+ }
1875
+ }
1876
+ const payload = JSON.stringify({
1877
+ type: 'output',
1878
+ agent: agentName,
1879
+ data: output,
1880
+ timestamp: new Date().toISOString(),
1881
+ });
1882
+ for (const client of clients) {
1883
+ if (client.readyState === WebSocket.OPEN) {
1884
+ client.send(payload);
1885
+ }
1886
+ }
1887
+ };
1888
+ // Expose broadcastLogOutput for PTY wrappers to call
1889
+ global.__broadcastLogOutput = broadcastLogOutput;
1890
+ // ===== Presence WebSocket Handler =====
1891
+ // Helper to broadcast to all presence clients
1892
+ const broadcastPresence = (message, exclude) => {
1893
+ const payload = JSON.stringify(message);
1894
+ wssPresence.clients.forEach((client) => {
1895
+ if (client !== exclude && client.readyState === WebSocket.OPEN) {
1896
+ client.send(payload);
1897
+ }
1898
+ });
1899
+ };
1900
+ // Helper to broadcast channel messages to all presence clients
1901
+ // This is used by fallback relay clients to forward messages to cloud-connected users
1902
+ const broadcastChannelMessage = (message) => {
1903
+ const payload = JSON.stringify(message);
1904
+ wssPresence.clients.forEach((client) => {
1905
+ if (client.readyState === WebSocket.OPEN) {
1906
+ client.send(payload);
1907
+ }
1908
+ });
1909
+ };
1910
+ // Helper to get online users list (without ws references)
1911
+ const getOnlineUsersList = () => {
1912
+ return Array.from(onlineUsers.values()).map((state) => state.info);
1913
+ };
1914
+ // Heartbeat to detect dead connections (30 seconds)
1915
+ const PRESENCE_HEARTBEAT_INTERVAL = 30000;
1916
+ const presenceHealth = new WeakMap();
1917
+ const presenceHeartbeat = setInterval(() => {
1918
+ wssPresence.clients.forEach((ws) => {
1919
+ const health = presenceHealth.get(ws);
1920
+ if (!health) {
1921
+ presenceHealth.set(ws, { isAlive: true });
1922
+ return;
1923
+ }
1924
+ if (!health.isAlive) {
1925
+ ws.terminate();
1926
+ return;
1927
+ }
1928
+ health.isAlive = false;
1929
+ ws.ping();
1930
+ });
1931
+ }, PRESENCE_HEARTBEAT_INTERVAL);
1932
+ wssPresence.on('close', () => {
1933
+ clearInterval(presenceHeartbeat);
1934
+ });
1935
+ wssPresence.on('connection', (ws) => {
1936
+ // Initialize health tracking (no log - too noisy)
1937
+ presenceHealth.set(ws, { isAlive: true });
1938
+ ws.on('pong', () => {
1939
+ const health = presenceHealth.get(ws);
1940
+ if (health)
1941
+ health.isAlive = true;
1942
+ });
1943
+ let clientUsername;
1944
+ ws.on('message', (data) => {
1945
+ try {
1946
+ const msg = JSON.parse(data.toString());
1947
+ if (msg.type === 'presence') {
1948
+ if (msg.action === 'join' && msg.user?.username) {
1949
+ const username = msg.user.username;
1950
+ const avatarUrl = msg.user.avatarUrl;
1951
+ // Validate inputs
1952
+ if (!isValidUsername(username)) {
1953
+ console.warn(`[dashboard] Invalid username rejected: ${username}`);
1954
+ return;
1955
+ }
1956
+ if (!isValidAvatarUrl(avatarUrl)) {
1957
+ console.warn(`[dashboard] Invalid avatar URL rejected for user ${username}`);
1958
+ return;
1959
+ }
1960
+ clientUsername = username;
1961
+ const now = new Date().toISOString();
1962
+ // Check if user already has connections (multi-tab support)
1963
+ const existing = onlineUsers.get(username);
1964
+ if (existing) {
1965
+ // Add this connection to existing user
1966
+ existing.connections.add(ws);
1967
+ existing.info.lastSeen = now;
1968
+ // Only log at milestones to reduce noise
1969
+ const count = existing.connections.size;
1970
+ if (count === 2 || count === 5 || count === 10 || count % 50 === 0) {
1971
+ console.log(`[dashboard] User ${username} has ${count} connections`);
1972
+ }
1973
+ }
1974
+ else {
1975
+ // New user - create presence state
1976
+ onlineUsers.set(username, {
1977
+ info: {
1978
+ username,
1979
+ avatarUrl,
1980
+ connectedAt: now,
1981
+ lastSeen: now,
1982
+ },
1983
+ connections: new Set([ws]),
1984
+ });
1985
+ console.log(`[dashboard] User ${username} came online`);
1986
+ // Register user with relay daemon for messaging
1987
+ userBridge.registerUser(username, ws, { avatarUrl }).catch((err) => {
1988
+ console.error(`[dashboard] Failed to register user ${username} with relay:`, err);
1989
+ });
1990
+ // Broadcast join to all other clients (only for truly new users)
1991
+ broadcastPresence({
1992
+ type: 'presence_join',
1993
+ user: {
1994
+ username,
1995
+ avatarUrl,
1996
+ connectedAt: now,
1997
+ lastSeen: now,
1998
+ },
1999
+ }, ws);
2000
+ }
2001
+ // Send current online users list to the new client
2002
+ ws.send(JSON.stringify({
2003
+ type: 'presence_list',
2004
+ users: getOnlineUsersList(),
2005
+ }));
2006
+ }
2007
+ else if (msg.action === 'leave') {
2008
+ // Security: Only allow leaving your own username
2009
+ // Must have authenticated first
2010
+ if (!clientUsername) {
2011
+ console.warn(`[dashboard] Security: Unauthenticated leave attempt`);
2012
+ return;
2013
+ }
2014
+ if (msg.username !== clientUsername) {
2015
+ console.warn(`[dashboard] Security: User ${clientUsername} tried to remove ${msg.username}`);
2016
+ return;
2017
+ }
2018
+ // Remove this connection from the user's set
2019
+ const username = clientUsername; // Narrow type for TypeScript
2020
+ const userState = onlineUsers.get(username);
2021
+ if (userState) {
2022
+ userState.connections.delete(ws);
2023
+ // Only broadcast leave if no more connections
2024
+ if (userState.connections.size === 0) {
2025
+ onlineUsers.delete(username);
2026
+ console.log(`[dashboard] User ${username} went offline`);
2027
+ broadcastPresence({
2028
+ type: 'presence_leave',
2029
+ username,
2030
+ });
2031
+ }
2032
+ else {
2033
+ console.log(`[dashboard] User ${username} closed tab (${userState.connections.size} remaining)`);
2034
+ }
2035
+ }
2036
+ }
2037
+ }
2038
+ else if (msg.type === 'typing') {
2039
+ // Must have authenticated first
2040
+ if (!clientUsername) {
2041
+ console.warn(`[dashboard] Security: Unauthenticated typing attempt`);
2042
+ return;
2043
+ }
2044
+ // Validate typing message comes from authenticated user
2045
+ if (msg.username !== clientUsername) {
2046
+ console.warn(`[dashboard] Security: Typing message username mismatch`);
2047
+ return;
2048
+ }
2049
+ // Update last seen
2050
+ const username = clientUsername; // Narrow type for TypeScript
2051
+ const userState = onlineUsers.get(username);
2052
+ if (userState) {
2053
+ userState.info.lastSeen = new Date().toISOString();
2054
+ }
2055
+ // Broadcast typing indicator to all other clients
2056
+ broadcastPresence({
2057
+ type: 'typing',
2058
+ username,
2059
+ avatarUrl: userState?.info.avatarUrl,
2060
+ isTyping: msg.isTyping,
2061
+ }, ws);
2062
+ }
2063
+ else if (msg.type === 'channel_join') {
2064
+ // Join a channel
2065
+ if (!clientUsername) {
2066
+ console.warn(`[dashboard] Security: Unauthenticated channel_join attempt`);
2067
+ return;
2068
+ }
2069
+ if (!msg.channel || typeof msg.channel !== 'string') {
2070
+ console.warn(`[dashboard] Invalid channel_join: missing channel`);
2071
+ return;
2072
+ }
2073
+ userBridge.joinChannel(clientUsername, msg.channel).then((success) => {
2074
+ ws.send(JSON.stringify({
2075
+ type: 'channel_joined',
2076
+ channel: msg.channel,
2077
+ success,
2078
+ }));
2079
+ }).catch((err) => {
2080
+ console.error(`[dashboard] Channel join error:`, err);
2081
+ ws.send(JSON.stringify({
2082
+ type: 'channel_joined',
2083
+ channel: msg.channel,
2084
+ success: false,
2085
+ error: err.message,
2086
+ }));
2087
+ });
2088
+ }
2089
+ else if (msg.type === 'channel_leave') {
2090
+ // Leave a channel
2091
+ if (!clientUsername) {
2092
+ console.warn(`[dashboard] Security: Unauthenticated channel_leave attempt`);
2093
+ return;
2094
+ }
2095
+ if (!msg.channel || typeof msg.channel !== 'string') {
2096
+ console.warn(`[dashboard] Invalid channel_leave: missing channel`);
2097
+ return;
2098
+ }
2099
+ userBridge.leaveChannel(clientUsername, msg.channel).then((success) => {
2100
+ ws.send(JSON.stringify({
2101
+ type: 'channel_left',
2102
+ channel: msg.channel,
2103
+ success,
2104
+ }));
2105
+ }).catch((err) => {
2106
+ console.error(`[dashboard] Channel leave error:`, err);
2107
+ });
2108
+ }
2109
+ else if (msg.type === 'channel_message') {
2110
+ // Send message to channel
2111
+ if (!clientUsername) {
2112
+ console.warn(`[dashboard] Security: Unauthenticated channel_message attempt`);
2113
+ return;
2114
+ }
2115
+ if (!msg.channel || typeof msg.channel !== 'string') {
2116
+ console.warn(`[dashboard] Invalid channel_message: missing channel`);
2117
+ return;
2118
+ }
2119
+ if (!msg.body || typeof msg.body !== 'string') {
2120
+ console.warn(`[dashboard] Invalid channel_message: missing body`);
2121
+ return;
2122
+ }
2123
+ userBridge.sendChannelMessage(clientUsername, msg.channel, msg.body, {
2124
+ thread: msg.thread,
2125
+ }).catch((err) => {
2126
+ console.error(`[dashboard] Channel message error:`, err);
2127
+ });
2128
+ }
2129
+ else if (msg.type === 'direct_message') {
2130
+ // Send direct message to user or agent
2131
+ if (!clientUsername) {
2132
+ console.warn(`[dashboard] Security: Unauthenticated direct_message attempt`);
2133
+ return;
2134
+ }
2135
+ if (!msg.to || typeof msg.to !== 'string') {
2136
+ console.warn(`[dashboard] Invalid direct_message: missing 'to'`);
2137
+ return;
2138
+ }
2139
+ if (!msg.body || typeof msg.body !== 'string') {
2140
+ console.warn(`[dashboard] Invalid direct_message: missing body`);
2141
+ return;
2142
+ }
2143
+ userBridge.sendDirectMessage(clientUsername, msg.to, msg.body, {
2144
+ thread: msg.thread,
2145
+ }).catch((err) => {
2146
+ console.error(`[dashboard] Direct message error:`, err);
2147
+ });
2148
+ }
2149
+ }
2150
+ catch (err) {
2151
+ console.error('[dashboard] Invalid presence message:', err);
2152
+ }
2153
+ });
2154
+ ws.on('error', (err) => {
2155
+ console.error('[dashboard] Presence WebSocket client error:', err);
2156
+ });
2157
+ ws.on('close', () => {
2158
+ // Clean up on disconnect with multi-tab support
2159
+ if (clientUsername) {
2160
+ const userState = onlineUsers.get(clientUsername);
2161
+ if (userState) {
2162
+ userState.connections.delete(ws);
2163
+ // Only broadcast leave if no more connections
2164
+ if (userState.connections.size === 0) {
2165
+ onlineUsers.delete(clientUsername);
2166
+ console.log(`[dashboard] User ${clientUsername} disconnected`);
2167
+ // Unregister from relay daemon
2168
+ userBridge.unregisterUser(clientUsername);
2169
+ broadcastPresence({
2170
+ type: 'presence_leave',
2171
+ username: clientUsername,
2172
+ });
2173
+ }
2174
+ else {
2175
+ console.log(`[dashboard] User ${clientUsername} closed connection (${userState.connections.size} remaining)`);
2176
+ }
2177
+ }
2178
+ }
2179
+ });
2180
+ });
2181
+ app.get('/api/data', (req, res) => {
2182
+ getAllData().then((data) => res.json(data)).catch((err) => {
2183
+ console.error('Failed to fetch dashboard data', err);
2184
+ res.status(500).json({ error: 'Failed to load data' });
2185
+ });
2186
+ });
2187
+ // ===== Channel API =====
2188
+ /**
2189
+ * GET /api/channels - Get list of channels the user has joined
2190
+ */
2191
+ app.get('/api/channels', async (req, res) => {
2192
+ const username = req.query.username;
2193
+ const workspaceId = resolveWorkspaceId(req);
2194
+ if (!storage) {
2195
+ if (!username) {
2196
+ return res.status(400).json({ error: 'username query param required' });
2197
+ }
2198
+ const channels = userBridge.getUserChannels(username);
2199
+ return res.json({
2200
+ channels: channels.map((id) => ({
2201
+ id,
2202
+ name: id.startsWith('#') ? id.slice(1) : id,
2203
+ visibility: 'public',
2204
+ status: 'active',
2205
+ createdAt: new Date().toISOString(),
2206
+ createdBy: username,
2207
+ memberCount: 0,
2208
+ unreadCount: 0,
2209
+ hasMentions: false,
2210
+ isDm: id.startsWith('dm:'),
2211
+ })),
2212
+ archivedChannels: [],
2213
+ });
2214
+ }
2215
+ try {
2216
+ const channelMap = await loadChannelRecords(workspaceId);
2217
+ const activeChannels = [];
2218
+ const archivedChannels = [];
2219
+ for (const record of channelMap.values()) {
2220
+ const isMember = !username || record.members.has(username) || record.id === '#general';
2221
+ if (!isMember) {
2222
+ continue;
2223
+ }
2224
+ const channel = {
2225
+ id: record.id,
2226
+ name: record.id.startsWith('#') ? record.id.slice(1) : record.id,
2227
+ description: record.description,
2228
+ visibility: record.visibility,
2229
+ status: record.status,
2230
+ createdAt: record.createdAt ? new Date(record.createdAt).toISOString() : new Date(record.lastActivityAt || Date.now()).toISOString(),
2231
+ createdBy: record.createdBy || '__system__',
2232
+ lastActivityAt: record.lastActivityAt ? new Date(record.lastActivityAt).toISOString() : undefined,
2233
+ memberCount: record.members.size,
2234
+ unreadCount: 0,
2235
+ hasMentions: false,
2236
+ lastMessage: record.lastMessage,
2237
+ isDm: record.id.startsWith('dm:'),
2238
+ dmParticipants: record.dmParticipants,
2239
+ };
2240
+ if (record.status === 'archived') {
2241
+ archivedChannels.push(channel);
2242
+ }
2243
+ else {
2244
+ activeChannels.push(channel);
2245
+ }
2246
+ }
2247
+ return res.json({
2248
+ channels: activeChannels,
2249
+ archivedChannels,
2250
+ });
2251
+ }
2252
+ catch (err) {
2253
+ console.error('[channels] Failed to load channels', err);
2254
+ return res.status(500).json({ error: 'Failed to load channels' });
2255
+ }
2256
+ });
2257
+ /**
2258
+ * POST /api/channels - Create a new channel
2259
+ */
2260
+ app.post('/api/channels', express.json(), async (req, res) => {
2261
+ const { name, description, isPrivate, invites } = req.body;
2262
+ const workspaceId = resolveWorkspaceId(req);
2263
+ const username = req.query.username || req.body.username || 'Dashboard';
2264
+ if (!name) {
2265
+ return res.status(400).json({ error: 'name is required' });
2266
+ }
2267
+ // Normalize channel name
2268
+ const channelId = name.startsWith('#') ? name : `#${name}`;
2269
+ try {
2270
+ // Join the creator to the channel
2271
+ // Note: userBridge.joinChannel triggers router's persistChannelMembership via protocol
2272
+ // We only persist here for dashboard-initiated creates (no daemon connection)
2273
+ await userBridge.joinChannel(username, channelId);
2274
+ await persistChannelMembershipEvent(channelId, username, 'join', { workspaceId });
2275
+ // Handle invites if provided
2276
+ if (invites) {
2277
+ const inviteList = invites.split(',').map((s) => s.trim()).filter(Boolean);
2278
+ for (const invitee of inviteList) {
2279
+ // userBridge.joinChannel handles persistence via protocol
2280
+ await userBridge.joinChannel(invitee, channelId);
2281
+ await persistChannelMembershipEvent(channelId, invitee, 'invite', { invitedBy: username, workspaceId });
2282
+ }
2283
+ }
2284
+ // Persist channel creation as a system message
2285
+ if (storage) {
2286
+ await storage.saveMessage({
2287
+ id: `channel-create-${crypto.randomUUID()}`,
2288
+ ts: Date.now(),
2289
+ from: '__system__',
2290
+ to: channelId,
2291
+ topic: undefined,
2292
+ kind: 'state', // channel creation stored as state
2293
+ body: `Channel created by ${username}`,
2294
+ data: {
2295
+ _channelCreate: {
2296
+ createdBy: username,
2297
+ description,
2298
+ isPrivate: isPrivate ?? false,
2299
+ },
2300
+ ...(workspaceId ? { _workspaceId: workspaceId } : {}),
2301
+ },
2302
+ status: 'read',
2303
+ is_urgent: false,
2304
+ is_broadcast: true,
2305
+ });
2306
+ }
2307
+ res.json({
2308
+ channel: {
2309
+ id: channelId,
2310
+ name: name.startsWith('#') ? name.slice(1) : name,
2311
+ description,
2312
+ isPrivate: isPrivate ?? false,
2313
+ createdBy: username,
2314
+ },
2315
+ });
2316
+ }
2317
+ catch (err) {
2318
+ console.error('[channels] Failed to create channel:', err);
2319
+ res.status(500).json({ error: err.message || 'Failed to create channel' });
2320
+ }
2321
+ });
2322
+ /**
2323
+ * POST /api/channels/invite - Invite members to a channel
2324
+ */
2325
+ app.post('/api/channels/invite', express.json(), async (req, res) => {
2326
+ const { channel, invites, invitedBy } = req.body;
2327
+ const workspaceId = resolveWorkspaceId(req);
2328
+ if (!channel || !invites) {
2329
+ return res.status(400).json({ error: 'channel and invites are required' });
2330
+ }
2331
+ const channelId = channel.startsWith('#') ? channel : `#${channel}`;
2332
+ const inviteList = invites.split(',').map((s) => s.trim()).filter(Boolean);
2333
+ try {
2334
+ const results = [];
2335
+ for (const invitee of inviteList) {
2336
+ let success = false;
2337
+ let reason;
2338
+ if (userBridge.isUserRegistered(invitee)) {
2339
+ success = await userBridge.joinChannel(invitee, channelId);
2340
+ if (!success) {
2341
+ reason = 'join_failed';
2342
+ }
2343
+ }
2344
+ else {
2345
+ success = true;
2346
+ reason = 'pending';
2347
+ }
2348
+ await persistChannelMembershipEvent(channelId, invitee, 'invite', {
2349
+ invitedBy,
2350
+ workspaceId,
2351
+ });
2352
+ results.push({ username: invitee, success, reason });
2353
+ }
2354
+ res.json({ channel: channelId, invited: results });
2355
+ }
2356
+ catch (err) {
2357
+ console.error('[channels] Failed to invite to channel:', err);
2358
+ res.status(500).json({ error: err.message || 'Failed to invite members' });
2359
+ }
2360
+ });
2361
+ /**
2362
+ * GET /api/channels/users - Get list of registered users
2363
+ */
2364
+ app.get('/api/channels/users', (_req, res) => {
2365
+ const users = userBridge.getRegisteredUsers();
2366
+ res.json({ users });
2367
+ });
2368
+ /**
2369
+ * POST /api/channels/join - Join a channel
2370
+ */
2371
+ app.post('/api/channels/join', express.json(), async (req, res) => {
2372
+ console.log('[channels] POST /api/channels/join received:', req.body);
2373
+ const { username, channel } = req.body;
2374
+ if (!username || !channel) {
2375
+ console.log('[channels] Join: missing username or channel');
2376
+ return res.status(400).json({ error: 'username and channel required' });
2377
+ }
2378
+ const workspaceId = resolveWorkspaceId(req);
2379
+ const channelId = channel.startsWith('#') ? channel : `#${channel}`;
2380
+ let success = false;
2381
+ // Step 1: Try userBridge (for users connected via local WebSocket)
2382
+ const isLocalUser = userBridge.isUserRegistered(username);
2383
+ console.log(`[channels] Join: isLocalUser=${isLocalUser}`);
2384
+ if (isLocalUser) {
2385
+ console.log(`[channels] Calling userBridge.joinChannel(${username}, ${channelId})`);
2386
+ success = await userBridge.joinChannel(username, channelId);
2387
+ console.log(`[channels] userBridge.joinChannel returned: ${success}`);
2388
+ }
2389
+ // Step 2: If not local or userBridge failed, use relay client fallback
2390
+ if (!success) {
2391
+ console.log('[channels] Using relay client fallback for join');
2392
+ try {
2393
+ const client = await getRelayClient(username);
2394
+ console.log(`[channels] Got relay client: ${client ? `state=${client.state}` : 'null'}`);
2395
+ if (client && client.state === 'READY') {
2396
+ success = client.joinChannel(channelId, username);
2397
+ console.log(`[channels] relay client joinChannel returned: ${success}`);
2398
+ }
2399
+ else {
2400
+ console.log('[channels] Relay client not ready or null');
2401
+ }
2402
+ }
2403
+ catch (err) {
2404
+ console.log(`[channels] Relay client error: ${err.message}`);
2405
+ }
2406
+ }
2407
+ if (success) {
2408
+ await persistChannelMembershipEvent(channelId, username, 'join', { workspaceId });
2409
+ }
2410
+ console.log(`[channels] Join final result: success=${success}`);
2411
+ res.json({ success, channel: channelId });
2412
+ });
2413
+ /**
2414
+ * POST /api/channels/leave - Leave a channel
2415
+ */
2416
+ app.post('/api/channels/leave', express.json(), async (req, res) => {
2417
+ const { username, channel } = req.body;
2418
+ if (!username || !channel) {
2419
+ return res.status(400).json({ error: 'username and channel required' });
2420
+ }
2421
+ const workspaceId = resolveWorkspaceId(req);
2422
+ try {
2423
+ const success = await userBridge.leaveChannel(username, channel);
2424
+ if (success) {
2425
+ await persistChannelMembershipEvent(channel, username, 'leave', { workspaceId });
2426
+ }
2427
+ res.json({ success, channel });
2428
+ }
2429
+ catch (err) {
2430
+ res.status(500).json({ error: err.message });
2431
+ }
2432
+ });
2433
+ /**
2434
+ * POST /api/channels/admin-join - Add a member to a channel (admin operation)
2435
+ * Used by cloud server to sync channel memberships for agents
2436
+ */
2437
+ app.post('/api/channels/admin-join', express.json(), async (req, res) => {
2438
+ const { channel, member } = req.body;
2439
+ if (!channel || !member) {
2440
+ return res.status(400).json({ error: 'channel and member required' });
2441
+ }
2442
+ const workspaceId = resolveWorkspaceId(req);
2443
+ try {
2444
+ console.log(`[channels] Admin join: ${member} -> ${channel}`);
2445
+ const success = await userBridge.adminJoinChannel(channel, member);
2446
+ if (success) {
2447
+ await persistChannelMembershipEvent(channel, member, 'join', { workspaceId });
2448
+ }
2449
+ // Check if member is connected (warning for unconnected members)
2450
+ let warning;
2451
+ const connectedAgentsPath = path.join(teamDir, 'connected-agents.json');
2452
+ try {
2453
+ if (fs.existsSync(connectedAgentsPath)) {
2454
+ const data = JSON.parse(fs.readFileSync(connectedAgentsPath, 'utf-8'));
2455
+ const connectedAgents = data.agents || [];
2456
+ const connectedUsers = data.users || [];
2457
+ const allConnected = [...connectedAgents, ...connectedUsers];
2458
+ // Case-insensitive check
2459
+ const isConnected = allConnected.some((name) => name.toLowerCase() === member.toLowerCase());
2460
+ if (!isConnected) {
2461
+ warning = `Member "${member}" is not currently connected to the daemon. Messages sent to this channel will not be delivered until the agent connects.`;
2462
+ console.log(`[channels] Warning: ${member} added to ${channel} but not connected`);
2463
+ }
2464
+ }
2465
+ }
2466
+ catch {
2467
+ // Ignore errors reading connected-agents.json
2468
+ }
2469
+ res.json({ success, channel, member, warning });
2470
+ }
2471
+ catch (err) {
2472
+ console.error('[channels] Admin join failed:', err.message);
2473
+ res.status(500).json({ error: err.message });
2474
+ }
2475
+ });
2476
+ /**
2477
+ * POST /api/channels/admin-remove - Remove a member from a channel (admin operation)
2478
+ * Used by dashboard to remove members from channels
2479
+ */
2480
+ app.post('/api/channels/admin-remove', express.json(), async (req, res) => {
2481
+ const { channel, member } = req.body;
2482
+ if (!channel || !member) {
2483
+ return res.status(400).json({ error: 'channel and member required' });
2484
+ }
2485
+ const workspaceId = resolveWorkspaceId(req);
2486
+ try {
2487
+ console.log(`[channels] Admin remove: ${member} <- ${channel}`);
2488
+ const success = await userBridge.adminRemoveMember(channel, member);
2489
+ if (success) {
2490
+ await persistChannelMembershipEvent(channel, member, 'leave', { workspaceId });
2491
+ }
2492
+ res.json({ success, channel, member });
2493
+ }
2494
+ catch (err) {
2495
+ console.error('[channels] Admin remove failed:', err.message);
2496
+ res.status(500).json({ error: err.message });
2497
+ }
2498
+ });
2499
+ /**
2500
+ * GET /api/channels/:channel/members - Get members of a channel
2501
+ */
2502
+ app.get('/api/channels/:channel/members', async (req, res) => {
2503
+ const channelId = req.params.channel.startsWith('#') ? req.params.channel : `#${req.params.channel}`;
2504
+ const workspaceId = resolveWorkspaceId(req);
2505
+ try {
2506
+ // Get persisted members from storage
2507
+ const channelMap = await loadChannelRecords(workspaceId);
2508
+ const record = channelMap.get(channelId);
2509
+ // Get online agents from agents.json
2510
+ const agentsPath = path.join(teamDir, 'agents.json');
2511
+ const onlineAgents = [];
2512
+ const thirtySecondsAgo = Date.now() - 30 * 1000;
2513
+ if (fs.existsSync(agentsPath)) {
2514
+ try {
2515
+ const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
2516
+ for (const agent of (data.agents || [])) {
2517
+ if (agent.lastSeen && new Date(agent.lastSeen).getTime() > thirtySecondsAgo) {
2518
+ onlineAgents.push(agent.name);
2519
+ }
2520
+ }
2521
+ }
2522
+ catch {
2523
+ // Ignore parse errors
2524
+ }
2525
+ }
2526
+ // Get connected users from userBridge
2527
+ const connectedUsers = userBridge.getRegisteredUsers();
2528
+ // Build member list
2529
+ const memberSet = new Set();
2530
+ // Add persisted members
2531
+ if (record?.members) {
2532
+ for (const member of record.members) {
2533
+ memberSet.add(member);
2534
+ }
2535
+ }
2536
+ // For #general, also add all connected agents and users
2537
+ if (channelId === '#general') {
2538
+ for (const agent of onlineAgents) {
2539
+ memberSet.add(agent);
2540
+ }
2541
+ for (const user of connectedUsers) {
2542
+ memberSet.add(user);
2543
+ }
2544
+ }
2545
+ // Build response with entity type info
2546
+ const members = Array.from(memberSet).map((name) => {
2547
+ const isOnlineAgent = onlineAgents.includes(name);
2548
+ const isOnlineUser = connectedUsers.includes(name);
2549
+ return {
2550
+ id: name,
2551
+ displayName: name,
2552
+ entityType: isOnlineUser ? 'user' : 'agent',
2553
+ role: 'member',
2554
+ status: isOnlineAgent || isOnlineUser ? 'online' : 'offline',
2555
+ joinedAt: new Date().toISOString(),
2556
+ };
2557
+ });
2558
+ return res.json({ members });
2559
+ }
2560
+ catch (err) {
2561
+ console.error('[channels] Failed to get channel members:', err);
2562
+ return res.status(500).json({ error: err.message || 'Failed to get channel members' });
2563
+ }
2564
+ });
2565
+ /**
2566
+ * GET /api/channels/:channel/messages - Get persisted messages for a channel
2567
+ */
2568
+ app.get('/api/channels/:channel/messages', async (req, res) => {
2569
+ if (!storage) {
2570
+ return res.status(503).json({ error: 'Storage not configured' });
2571
+ }
2572
+ const channelId = req.params.channel;
2573
+ const limit = req.query.limit ? parseInt(req.query.limit, 10) : 200;
2574
+ const beforeTs = req.query.before ? parseInt(req.query.before, 10) : undefined;
2575
+ const workspaceId = resolveWorkspaceId(req);
2576
+ try {
2577
+ const query = {
2578
+ to: channelId,
2579
+ limit,
2580
+ order: 'desc',
2581
+ };
2582
+ if (beforeTs) {
2583
+ query.sinceTs = beforeTs;
2584
+ }
2585
+ let messages = await storage.getMessages(query);
2586
+ // Only include channel messages for this workspace
2587
+ messages = messages.filter((m) => {
2588
+ const data = m.data;
2589
+ if (workspaceId && data?._workspaceId && data._workspaceId !== workspaceId) {
2590
+ return false;
2591
+ }
2592
+ return Boolean(data?._isChannelMessage);
2593
+ });
2594
+ // Sort ascending for UI
2595
+ messages.sort((a, b) => a.ts - b.ts);
2596
+ res.json({
2597
+ messages: messages.map((m) => ({
2598
+ id: m.id,
2599
+ channelId: channelId,
2600
+ from: m.from,
2601
+ fromEntityType: 'user',
2602
+ content: m.body,
2603
+ timestamp: new Date(m.ts).toISOString(),
2604
+ threadId: m.thread || undefined,
2605
+ isRead: true,
2606
+ })),
2607
+ hasMore: messages.length === limit,
2608
+ });
2609
+ }
2610
+ catch (err) {
2611
+ console.error('[channels] Failed to fetch channel messages', err);
2612
+ res.status(500).json({ error: 'Failed to fetch channel messages' });
2613
+ }
2614
+ });
2615
+ /**
2616
+ * POST /api/channels/subscribe - Subscribe a cloud user to channel messages
2617
+ * This creates a relay client for the user so they receive channel messages
2618
+ */
2619
+ app.post('/api/channels/subscribe', express.json(), async (req, res) => {
2620
+ const { username, channels, workspaceId } = req.body;
2621
+ console.log(`[channel-debug] SUBSCRIBE request: username=${username}, channels=${JSON.stringify(channels)}`);
2622
+ if (!username) {
2623
+ return res.status(400).json({ error: 'username required' });
2624
+ }
2625
+ try {
2626
+ // Get or create a relay client for this user
2627
+ const client = await getRelayClient(username);
2628
+ if (!client) {
2629
+ console.log(`[channel-debug] SUBSCRIBE failed: could not create relay client for ${username}`);
2630
+ return res.status(503).json({ error: 'Could not connect to daemon' });
2631
+ }
2632
+ // Wait for client to be ready
2633
+ let attempts = 0;
2634
+ while (client.state !== 'READY' && attempts < 50) {
2635
+ await new Promise((r) => setTimeout(r, 100));
2636
+ attempts++;
2637
+ }
2638
+ if (client.state !== 'READY') {
2639
+ console.log(`[channel-debug] SUBSCRIBE failed: client not ready for ${username}`);
2640
+ return res.status(503).json({ error: 'Relay client not ready' });
2641
+ }
2642
+ // Join the user to their channels
2643
+ const joinedChannels = [];
2644
+ const channelList = channels || ['#general'];
2645
+ for (const channel of channelList) {
2646
+ const channelId = channel.startsWith('#') ? channel : `#${channel}`;
2647
+ const joined = client.joinChannel(channelId, username);
2648
+ if (joined) {
2649
+ joinedChannels.push(channelId);
2650
+ }
2651
+ }
2652
+ console.log(`[channel-debug] SUBSCRIBE success: ${username} joined ${joinedChannels.join(', ')}`);
2653
+ res.json({ success: true, channels: joinedChannels });
2654
+ }
2655
+ catch (err) {
2656
+ console.log(`[channel-debug] SUBSCRIBE error: ${err.message}`);
2657
+ res.status(500).json({ error: err.message });
2658
+ }
2659
+ });
2660
+ /**
2661
+ * POST /api/channels/message - Send a message to a channel
2662
+ */
2663
+ app.post('/api/channels/message', express.json(), async (req, res) => {
2664
+ // Build marker - if you don't see this, you're running old code
2665
+ console.log('[channel-msg] === BUILD v3 === Handler called');
2666
+ const { username, channel, body, thread } = req.body;
2667
+ console.log(`[channel-msg] Request: username=${username}, channel=${channel}`);
2668
+ if (!username || !channel || !body) {
2669
+ console.log('[channel-msg] Missing required fields');
2670
+ return res.status(400).json({ error: 'username, channel, and body required' });
2671
+ }
2672
+ const workspaceId = resolveWorkspaceId(req);
2673
+ const channelId = channel.startsWith('#') ? channel : `#${channel}`;
2674
+ // SIMPLE APPROACH: Always try relay client first for sending
2675
+ // userBridge is only useful for users connected via local WebSocket
2676
+ // For cloud-proxied requests, we need to use relay client directly
2677
+ let success = false;
2678
+ // Step 1: Check if user is registered with userBridge (local mode)
2679
+ const isLocalUser = userBridge.isUserRegistered(username);
2680
+ console.log(`[channel-msg] Is local user: ${isLocalUser}`);
2681
+ if (isLocalUser) {
2682
+ // Local user - use userBridge
2683
+ console.log('[channel-msg] Using userBridge (local user)');
2684
+ success = await userBridge.sendChannelMessage(username, channelId, body, {
2685
+ thread,
2686
+ data: workspaceId ? { _workspaceId: workspaceId } : undefined,
2687
+ });
2688
+ console.log(`[channel-msg] userBridge result: ${success}`);
2689
+ }
2690
+ // Step 2: If not local or userBridge failed, use relay client
2691
+ if (!success) {
2692
+ console.log('[channel-msg] Using relay client fallback');
2693
+ try {
2694
+ const client = await getRelayClient(username);
2695
+ console.log(`[channel-msg] Got relay client: ${client ? `state=${client.state}` : 'null'}`);
2696
+ if (client && client.state === 'READY') {
2697
+ // Join the channel first (idempotent)
2698
+ const joinResult = client.joinChannel(channelId, username);
2699
+ console.log(`[channel-msg] Join channel result: ${joinResult}`);
2700
+ // Send the message
2701
+ success = client.sendChannelMessage(channelId, body, {
2702
+ thread,
2703
+ data: workspaceId ? { _workspaceId: workspaceId } : undefined,
2704
+ });
2705
+ console.log(`[channel-msg] sendChannelMessage result: ${success}`);
2706
+ }
2707
+ else {
2708
+ console.log('[channel-msg] Relay client not ready or null');
2709
+ }
2710
+ }
2711
+ catch (err) {
2712
+ console.log(`[channel-msg] Relay client error: ${err.message}`);
2713
+ }
2714
+ }
2715
+ console.log(`[channel-msg] Final result: success=${success}`);
2716
+ res.json({ success });
2717
+ });
2718
+ /**
2719
+ * POST /api/channels/archive - Mark a channel as archived (persisted in storage)
2720
+ */
2721
+ app.post('/api/channels/archive', express.json(), async (req, res) => {
2722
+ if (!storage) {
2723
+ return res.status(503).json({ error: 'Storage not configured' });
2724
+ }
2725
+ const { channel } = req.body;
2726
+ if (!channel) {
2727
+ return res.status(400).json({ error: 'channel required' });
2728
+ }
2729
+ const workspaceId = resolveWorkspaceId(req);
2730
+ try {
2731
+ await storage.saveMessage({
2732
+ id: `state-${Date.now()}`,
2733
+ ts: Date.now(),
2734
+ from: '__system__',
2735
+ to: channel,
2736
+ topic: undefined,
2737
+ kind: 'message',
2738
+ body: 'STATE:archived',
2739
+ data: {
2740
+ _channelState: 'archived',
2741
+ ...(workspaceId ? { _workspaceId: workspaceId } : {}),
2742
+ },
2743
+ status: 'read',
2744
+ is_urgent: false,
2745
+ is_broadcast: true,
2746
+ });
2747
+ res.json({ success: true });
2748
+ }
2749
+ catch (err) {
2750
+ console.error('[channels] Failed to archive channel', err);
2751
+ res.status(500).json({ error: 'Failed to archive channel' });
2752
+ }
2753
+ });
2754
+ /**
2755
+ * POST /api/channels/unarchive - Mark a channel as active (persisted in storage)
2756
+ */
2757
+ app.post('/api/channels/unarchive', express.json(), async (req, res) => {
2758
+ if (!storage) {
2759
+ return res.status(503).json({ error: 'Storage not configured' });
2760
+ }
2761
+ const { channel } = req.body;
2762
+ if (!channel) {
2763
+ return res.status(400).json({ error: 'channel required' });
2764
+ }
2765
+ const workspaceId = resolveWorkspaceId(req);
2766
+ try {
2767
+ await storage.saveMessage({
2768
+ id: `state-${Date.now()}`,
2769
+ ts: Date.now(),
2770
+ from: '__system__',
2771
+ to: channel,
2772
+ topic: undefined,
2773
+ kind: 'message',
2774
+ body: 'STATE:active',
2775
+ data: {
2776
+ _channelState: 'active',
2777
+ ...(workspaceId ? { _workspaceId: workspaceId } : {}),
2778
+ },
2779
+ status: 'read',
2780
+ is_urgent: false,
2781
+ is_broadcast: true,
2782
+ });
2783
+ res.json({ success: true });
2784
+ }
2785
+ catch (err) {
2786
+ console.error('[channels] Failed to unarchive channel', err);
2787
+ res.status(500).json({ error: 'Failed to unarchive channel' });
2788
+ }
2789
+ });
2790
+ /**
2791
+ * POST /api/dm - Send a direct message
2792
+ */
2793
+ app.post('/api/dm', express.json(), async (req, res) => {
2794
+ const { from, to, body, thread } = req.body;
2795
+ if (!from || !to || !body) {
2796
+ return res.status(400).json({ error: 'from, to, and body required' });
2797
+ }
2798
+ try {
2799
+ const success = await userBridge.sendDirectMessage(from, to, body, { thread });
2800
+ res.json({ success });
2801
+ }
2802
+ catch (err) {
2803
+ res.status(500).json({ error: err.message });
2804
+ }
2805
+ });
2806
+ // ===== Health Check API =====
2807
+ /**
2808
+ * GET /health - Health check endpoint for monitoring
2809
+ * Returns 200 if the daemon is healthy
2810
+ */
2811
+ app.get('/health', async (req, res) => {
2812
+ const uptime = process.uptime();
2813
+ const memUsage = process.memoryUsage();
2814
+ const socketExists = fs.existsSync(socketPath);
2815
+ // Check relay client connectivity (check if default Dashboard client is connected)
2816
+ const defaultClient = relayClients.get('Dashboard');
2817
+ const relayConnected = defaultClient?.state === 'READY';
2818
+ // If socket doesn't exist, daemon may not be running properly
2819
+ if (!socketExists) {
2820
+ return res.status(503).json({
2821
+ status: 'unhealthy',
2822
+ reason: 'Relay socket not found',
2823
+ uptime,
2824
+ memoryMB: Math.round(memUsage.heapUsed / 1024 / 1024),
2825
+ });
2826
+ }
2827
+ res.json({
2828
+ status: 'healthy',
2829
+ uptime,
2830
+ memoryMB: Math.round(memUsage.heapUsed / 1024 / 1024),
2831
+ relayConnected,
2832
+ websocketClients: wss.clients.size,
2833
+ });
2834
+ });
2835
+ /**
2836
+ * GET /api/health - Alternative health endpoint (same as /health)
2837
+ */
2838
+ app.get('/api/health', async (req, res) => {
2839
+ const uptime = process.uptime();
2840
+ const memUsage = process.memoryUsage();
2841
+ const socketExists = fs.existsSync(socketPath);
2842
+ const defaultClient = relayClients.get('Dashboard');
2843
+ const relayConnected = defaultClient?.state === 'READY';
2844
+ if (!socketExists) {
2845
+ return res.status(503).json({
2846
+ status: 'unhealthy',
2847
+ reason: 'Relay socket not found',
2848
+ uptime,
2849
+ memoryMB: Math.round(memUsage.heapUsed / 1024 / 1024),
2850
+ });
2851
+ }
2852
+ res.json({
2853
+ status: 'healthy',
2854
+ uptime,
2855
+ memoryMB: Math.round(memUsage.heapUsed / 1024 / 1024),
2856
+ relayConnected,
2857
+ websocketClients: wss.clients.size,
2858
+ });
2859
+ });
2860
+ /**
2861
+ * GET /keep-alive - Keep-alive endpoint for Fly.io idle prevention
2862
+ * Called by cloud server when workspace has active agents running.
2863
+ * This inbound request counts as activity for Fly.io's request-based
2864
+ * concurrency tracking, preventing the machine from being idled.
2865
+ */
2866
+ app.get('/keep-alive', (req, res) => {
2867
+ // Count online agents (seen within last 30 seconds)
2868
+ let activeAgents = 0;
2869
+ const agentsPath = path.join(teamDir, 'agents.json');
2870
+ if (fs.existsSync(agentsPath)) {
2871
+ try {
2872
+ const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
2873
+ const thirtySecondsAgo = Date.now() - 30 * 1000;
2874
+ activeAgents = (data.agents || []).filter((a) => {
2875
+ if (!a.lastSeen)
2876
+ return false;
2877
+ return new Date(a.lastSeen).getTime() > thirtySecondsAgo;
2878
+ }).length;
2879
+ }
2880
+ catch {
2881
+ // Ignore parse errors
2882
+ }
2883
+ }
2884
+ res.json({
2885
+ ok: true,
2886
+ activeAgents,
2887
+ timestamp: Date.now(),
2888
+ });
2889
+ });
2890
+ // ===== CLI Auth API (for workspace-based provider authentication) =====
2891
+ /**
2892
+ * POST /auth/cli/:provider/start - Start CLI auth flow
2893
+ * Body: { useDeviceFlow?: boolean, userId?: string }
2894
+ *
2895
+ * When userId is provided, credentials are stored per-user at /data/users/{userId}/.{provider}/
2896
+ * This allows multiple users to share a workspace with their own CLI credentials.
2897
+ */
2898
+ app.post('/auth/cli/:provider/start', async (req, res) => {
2899
+ const { provider } = req.params;
2900
+ const { useDeviceFlow, userId } = req.body || {};
2901
+ try {
2902
+ const session = await startCLIAuth(provider, { useDeviceFlow, userId });
2903
+ res.json({
2904
+ sessionId: session.id,
2905
+ status: session.status,
2906
+ authUrl: session.authUrl,
2907
+ });
2908
+ }
2909
+ catch (err) {
2910
+ res.status(400).json({
2911
+ error: err instanceof Error ? err.message : 'Failed to start CLI auth',
2912
+ });
2913
+ }
2914
+ });
2915
+ /**
2916
+ * GET /auth/cli/:provider/status/:sessionId - Get auth session status
2917
+ */
2918
+ app.get('/auth/cli/:provider/status/:sessionId', (req, res) => {
2919
+ const { sessionId } = req.params;
2920
+ const session = getAuthSession(sessionId);
2921
+ if (!session) {
2922
+ return res.status(404).json({ error: 'Session not found' });
2923
+ }
2924
+ res.json({
2925
+ status: session.status,
2926
+ authUrl: session.authUrl,
2927
+ error: session.error,
2928
+ });
2929
+ });
2930
+ /**
2931
+ * GET /auth/cli/:provider/creds/:sessionId - Get credentials from completed auth
2932
+ */
2933
+ app.get('/auth/cli/:provider/creds/:sessionId', (req, res) => {
2934
+ const { sessionId } = req.params;
2935
+ const session = getAuthSession(sessionId);
2936
+ if (!session) {
2937
+ return res.status(404).json({ error: 'Session not found' });
2938
+ }
2939
+ if (session.status !== 'success') {
2940
+ return res.status(400).json({ error: 'Auth not complete', status: session.status });
2941
+ }
2942
+ res.json({
2943
+ token: session.token,
2944
+ refreshToken: session.refreshToken,
2945
+ expiresAt: session.tokenExpiresAt?.toISOString(),
2946
+ });
2947
+ });
2948
+ /**
2949
+ * POST /auth/cli/:provider/cancel/:sessionId - Cancel auth session
2950
+ */
2951
+ app.post('/auth/cli/:provider/cancel/:sessionId', (req, res) => {
2952
+ const { sessionId } = req.params;
2953
+ const cancelled = cancelAuthSession(sessionId);
2954
+ if (!cancelled) {
2955
+ return res.status(404).json({ error: 'Session not found' });
2956
+ }
2957
+ res.json({ success: true });
2958
+ });
2959
+ /**
2960
+ * POST /auth/cli/:provider/code/:sessionId - Submit auth code to PTY
2961
+ * Used when OAuth returns a code that must be pasted into the CLI
2962
+ */
2963
+ app.post('/auth/cli/:provider/code/:sessionId', async (req, res) => {
2964
+ const { provider, sessionId } = req.params;
2965
+ const { code } = req.body;
2966
+ console.log('[cli-auth] Auth code submission received', { provider, sessionId, codeLength: code?.length });
2967
+ if (!code || typeof code !== 'string') {
2968
+ return res.status(400).json({ error: 'Auth code is required' });
2969
+ }
2970
+ try {
2971
+ const result = await submitAuthCode(sessionId, code);
2972
+ console.log('[cli-auth] Auth code submission result', { provider, sessionId, result });
2973
+ if (!result.success) {
2974
+ // Use 400 for all errors since they can be retried
2975
+ return res.status(400).json({
2976
+ error: result.error || 'Session not found or process not running',
2977
+ needsRestart: result.needsRestart ?? true,
2978
+ });
2979
+ }
2980
+ // Wait a few seconds for CLI to process and write credentials
2981
+ // The 1s delay in submitAuthCode + CLI processing time means credentials
2982
+ // should be available within 3-5 seconds
2983
+ let sessionStatus = 'waiting_auth';
2984
+ for (let i = 0; i < 10; i++) {
2985
+ await new Promise(resolve => setTimeout(resolve, 500));
2986
+ const session = getAuthSession(sessionId);
2987
+ if (session?.status === 'success') {
2988
+ sessionStatus = 'success';
2989
+ console.log('[cli-auth] Credentials found after code submission', { provider, sessionId, attempt: i + 1 });
2990
+ break;
2991
+ }
2992
+ if (session?.status === 'error') {
2993
+ sessionStatus = 'error';
2994
+ break;
2995
+ }
2996
+ }
2997
+ res.json({
2998
+ success: true,
2999
+ message: 'Auth code submitted',
3000
+ status: sessionStatus,
3001
+ });
3002
+ }
3003
+ catch (err) {
3004
+ console.error('[cli-auth] Auth code submission error', { provider, sessionId, error: String(err) });
3005
+ return res.status(500).json({
3006
+ error: 'Internal error submitting auth code. Please try again.',
3007
+ needsRestart: true,
3008
+ });
3009
+ }
3010
+ });
3011
+ /**
3012
+ * POST /auth/cli/:provider/complete/:sessionId - Complete auth
3013
+ * For providers like Claude: just polls for credentials
3014
+ * For providers like Codex: accepts authCode (redirect URL) and extracts the code
3015
+ */
3016
+ app.post('/auth/cli/:provider/complete/:sessionId', async (req, res) => {
3017
+ const { sessionId } = req.params;
3018
+ const { authCode } = req.body || {};
3019
+ // If authCode provided, try to extract code and submit it
3020
+ if (authCode && typeof authCode === 'string') {
3021
+ let code = authCode;
3022
+ // If it's a URL, extract the code parameter
3023
+ if (authCode.startsWith('http')) {
3024
+ try {
3025
+ const url = new URL(authCode);
3026
+ const codeParam = url.searchParams.get('code');
3027
+ if (codeParam) {
3028
+ code = codeParam;
3029
+ }
3030
+ }
3031
+ catch {
3032
+ // Not a valid URL, use as-is
3033
+ }
3034
+ }
3035
+ // Submit the code to the CLI process
3036
+ const submitResult = await submitAuthCode(sessionId, code);
3037
+ if (!submitResult.success) {
3038
+ return res.status(400).json({
3039
+ error: submitResult.error,
3040
+ needsRestart: submitResult.needsRestart,
3041
+ });
3042
+ }
3043
+ // Wait a moment for credentials to be written
3044
+ await new Promise(resolve => setTimeout(resolve, 2000));
3045
+ }
3046
+ // Poll for credentials
3047
+ const result = await completeAuthSession(sessionId);
3048
+ if (!result.success) {
3049
+ return res.status(400).json({ error: result.error });
3050
+ }
3051
+ res.json({ success: true, message: 'Authentication complete' });
3052
+ });
3053
+ /**
3054
+ * GET /auth/cli/providers - List supported providers
3055
+ */
3056
+ app.get('/auth/cli/providers', (req, res) => {
3057
+ res.json({ providers: getSupportedProviders() });
3058
+ });
3059
+ /**
3060
+ * GET /auth/cli/openai/check - Check if OpenAI/Codex is authenticated
3061
+ * Used by the codex-auth CLI helper to detect when auth completes
3062
+ */
3063
+ app.get('/auth/cli/openai/check', async (req, res) => {
3064
+ try {
3065
+ // Get userId from query params for per-user credential checking
3066
+ // Multiple users can share a workspace, each with their own CLI credentials
3067
+ const userId = req.query.userId;
3068
+ let credPath;
3069
+ if (userId) {
3070
+ // Per-user credential path: /data/users/{userId}/.codex/auth.json
3071
+ const dataDir = process.env.AGENT_RELAY_DATA_DIR || '/data';
3072
+ credPath = path.join(dataDir, 'users', userId, '.codex', 'auth.json');
3073
+ }
3074
+ else {
3075
+ // Fallback to workspace-wide path for backwards compatibility
3076
+ const homedir = process.env.HOME || '/home/workspace';
3077
+ credPath = path.join(homedir, '.codex', 'auth.json');
3078
+ }
3079
+ if (!fs.existsSync(credPath)) {
3080
+ return res.json({ authenticated: false });
3081
+ }
3082
+ const creds = JSON.parse(fs.readFileSync(credPath, 'utf-8'));
3083
+ // Check if we have a valid access token or API key
3084
+ // Codex stores tokens in a nested 'tokens' object: { tokens: { access_token, refresh_token } }
3085
+ const hasToken = !!(creds.access_token ||
3086
+ creds.token ||
3087
+ creds.api_key ||
3088
+ creds.OPENAI_API_KEY ||
3089
+ creds.tokens?.access_token ||
3090
+ creds.tokens?.refresh_token);
3091
+ res.json({ authenticated: hasToken });
3092
+ }
3093
+ catch (_error) {
3094
+ // File doesn't exist or is invalid
3095
+ res.json({ authenticated: false });
3096
+ }
3097
+ });
3098
+ // ===== Metrics API =====
3099
+ /**
3100
+ * GET /api/metrics - JSON format metrics for dashboard
3101
+ */
3102
+ app.get('/api/metrics', async (req, res) => {
3103
+ try {
3104
+ // Read agent registry for message counts
3105
+ const agentsPath = path.join(teamDir, 'agents.json');
3106
+ let agentRecords = [];
3107
+ if (fs.existsSync(agentsPath)) {
3108
+ const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
3109
+ agentRecords = (data.agents || []).map((a) => ({
3110
+ name: a.name,
3111
+ messagesSent: a.messagesSent ?? 0,
3112
+ messagesReceived: a.messagesReceived ?? 0,
3113
+ firstSeen: a.firstSeen ?? new Date().toISOString(),
3114
+ lastSeen: a.lastSeen ?? new Date().toISOString(),
3115
+ }));
3116
+ }
3117
+ // Get messages for throughput calculation
3118
+ const team = getTeamData();
3119
+ const messages = team ? await getMessages(team.agents) : [];
3120
+ // Get session data for lifecycle metrics
3121
+ const sessions = storage?.getSessions
3122
+ ? await storage.getSessions({ limit: 100 })
3123
+ : [];
3124
+ const metrics = computeSystemMetrics(agentRecords, messages, sessions);
3125
+ res.json(metrics);
3126
+ }
3127
+ catch (err) {
3128
+ console.error('Failed to compute metrics', err);
3129
+ res.status(500).json({ error: 'Failed to compute metrics' });
3130
+ }
3131
+ });
3132
+ /**
3133
+ * GET /api/metrics/prometheus - Prometheus exposition format
3134
+ */
3135
+ app.get('/api/metrics/prometheus', async (req, res) => {
3136
+ try {
3137
+ // Read agent registry for message counts
3138
+ const agentsPath = path.join(teamDir, 'agents.json');
3139
+ let agentRecords = [];
3140
+ if (fs.existsSync(agentsPath)) {
3141
+ const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
3142
+ agentRecords = (data.agents || []).map((a) => ({
3143
+ name: a.name,
3144
+ messagesSent: a.messagesSent ?? 0,
3145
+ messagesReceived: a.messagesReceived ?? 0,
3146
+ firstSeen: a.firstSeen ?? new Date().toISOString(),
3147
+ lastSeen: a.lastSeen ?? new Date().toISOString(),
3148
+ }));
3149
+ }
3150
+ // Get messages for throughput calculation
3151
+ const team = getTeamData();
3152
+ const messages = team ? await getMessages(team.agents) : [];
3153
+ // Get session data for lifecycle metrics
3154
+ const sessions = storage?.getSessions
3155
+ ? await storage.getSessions({ limit: 100 })
3156
+ : [];
3157
+ const metrics = computeSystemMetrics(agentRecords, messages, sessions);
3158
+ const prometheusOutput = formatPrometheusMetrics(metrics);
3159
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
3160
+ res.send(prometheusOutput);
3161
+ }
3162
+ catch (err) {
3163
+ console.error('Failed to compute Prometheus metrics', err);
3164
+ res.status(500).send('# Error computing metrics\n');
3165
+ }
3166
+ });
3167
+ // ===== Agent Memory Metrics API =====
3168
+ /**
3169
+ * GET /api/metrics/agents - Detailed agent memory and resource metrics
3170
+ */
3171
+ app.get('/api/metrics/agents', async (req, res) => {
3172
+ try {
3173
+ const agents = [];
3174
+ // Get metrics from spawner's active workers
3175
+ if (spawner) {
3176
+ const activeWorkers = spawner.getActiveWorkers();
3177
+ for (const worker of activeWorkers) {
3178
+ // Get memory usage via /proc filesystem
3179
+ let rssBytes = 0;
3180
+ const cpuPercent = 0;
3181
+ if (worker.pid) {
3182
+ try {
3183
+ // Use /proc filesystem instead of ps command (not available in all containers)
3184
+ const statusPath = `/proc/${worker.pid}/status`;
3185
+ if (fs.existsSync(statusPath)) {
3186
+ const status = fs.readFileSync(statusPath, 'utf8');
3187
+ // Parse VmRSS (Resident Set Size) from /proc/[pid]/status
3188
+ const rssMatch = status.match(/VmRSS:\s+(\d+)\s+kB/);
3189
+ if (rssMatch) {
3190
+ rssBytes = parseInt(rssMatch[1], 10) * 1024; // Convert kB to bytes
3191
+ }
3192
+ }
3193
+ // Note: CPU percentage requires sampling /proc/[pid]/stat over time
3194
+ // which is more complex. Leaving at 0 for now.
3195
+ }
3196
+ catch {
3197
+ // Process may have exited or /proc not accessible
3198
+ }
3199
+ }
3200
+ agents.push({
3201
+ name: worker.name,
3202
+ pid: worker.pid,
3203
+ status: worker.pid ? 'running' : 'unknown',
3204
+ rssBytes,
3205
+ cpuPercent,
3206
+ trend: 'unknown',
3207
+ alertLevel: rssBytes > 1024 * 1024 * 1024 ? 'critical' :
3208
+ rssBytes > 512 * 1024 * 1024 ? 'warning' : 'normal',
3209
+ highWatermark: rssBytes,
3210
+ uptimeMs: worker.spawnedAt ? Date.now() - worker.spawnedAt : 0,
3211
+ startedAt: worker.spawnedAt ? new Date(worker.spawnedAt).toISOString() : undefined,
3212
+ });
3213
+ }
3214
+ }
3215
+ // Also check agents.json for registered agents that may not be spawned
3216
+ const agentsPath = path.join(teamDir, 'agents.json');
3217
+ if (fs.existsSync(agentsPath)) {
3218
+ const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
3219
+ const registeredAgents = data.agents || [];
3220
+ for (const agent of registeredAgents) {
3221
+ if (!agents.find(a => a.name === agent.name)) {
3222
+ // Check if recently active (within 30 seconds)
3223
+ const lastSeen = agent.lastSeen ? new Date(agent.lastSeen).getTime() : 0;
3224
+ const isActive = Date.now() - lastSeen < 30000;
3225
+ if (isActive) {
3226
+ agents.push({
3227
+ name: agent.name,
3228
+ status: 'active',
3229
+ alertLevel: 'normal',
3230
+ });
3231
+ }
3232
+ }
3233
+ }
3234
+ }
3235
+ res.json({
3236
+ agents,
3237
+ system: {
3238
+ totalMemory: os.totalmem(),
3239
+ freeMemory: os.freemem(),
3240
+ heapUsed: process.memoryUsage().heapUsed,
3241
+ },
3242
+ });
3243
+ }
3244
+ catch (err) {
3245
+ console.error('Failed to get agent metrics', err);
3246
+ res.status(500).json({ error: 'Failed to get agent metrics' });
3247
+ }
3248
+ });
3249
+ /**
3250
+ * GET /api/metrics/health - System health and crash insights
3251
+ */
3252
+ app.get('/api/metrics/health', async (req, res) => {
3253
+ try {
3254
+ // Calculate health score based on available data
3255
+ let healthScore = 100;
3256
+ const issues = [];
3257
+ const recommendations = [];
3258
+ const crashes = [];
3259
+ const alerts = [];
3260
+ let agentCount = 0;
3261
+ const totalCrashes24h = 0;
3262
+ let totalAlerts24h = 0;
3263
+ // Get spawned agent count
3264
+ if (spawner) {
3265
+ const workers = spawner.getActiveWorkers();
3266
+ agentCount = workers.length;
3267
+ // Check for high memory usage
3268
+ for (const worker of workers) {
3269
+ if (worker.pid) {
3270
+ try {
3271
+ const { execSync } = await import('child_process');
3272
+ const output = execSync(`ps -o rss= -p ${worker.pid}`, {
3273
+ encoding: 'utf8',
3274
+ timeout: 3000,
3275
+ }).trim();
3276
+ const rssBytes = parseInt(output, 10) * 1024;
3277
+ if (rssBytes > 1.5 * 1024 * 1024 * 1024) {
3278
+ // > 1.5GB
3279
+ healthScore -= 20;
3280
+ issues.push({
3281
+ severity: 'critical',
3282
+ message: `Agent "${worker.name}" is using ${Math.round(rssBytes / 1024 / 1024)}MB of memory`,
3283
+ });
3284
+ totalAlerts24h++;
3285
+ alerts.push({
3286
+ id: `alert-${Date.now()}-${worker.name}`,
3287
+ agentName: worker.name,
3288
+ alertType: 'oom_imminent',
3289
+ message: `Memory usage critical: ${Math.round(rssBytes / 1024 / 1024)}MB`,
3290
+ createdAt: new Date().toISOString(),
3291
+ });
3292
+ }
3293
+ else if (rssBytes > 1024 * 1024 * 1024) {
3294
+ // > 1GB
3295
+ healthScore -= 10;
3296
+ issues.push({
3297
+ severity: 'high',
3298
+ message: `Agent "${worker.name}" memory usage is elevated (${Math.round(rssBytes / 1024 / 1024)}MB)`,
3299
+ });
3300
+ }
3301
+ }
3302
+ catch {
3303
+ // Process may have exited
3304
+ }
3305
+ }
3306
+ }
3307
+ }
3308
+ // Check registered agents
3309
+ const agentsPath = path.join(teamDir, 'agents.json');
3310
+ if (fs.existsSync(agentsPath)) {
3311
+ const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
3312
+ const registeredAgents = data.agents || [];
3313
+ const activeAgents = registeredAgents.filter((a) => {
3314
+ const lastSeen = a.lastSeen ? new Date(a.lastSeen).getTime() : 0;
3315
+ return Date.now() - lastSeen < 30000;
3316
+ });
3317
+ agentCount = Math.max(agentCount, activeAgents.length);
3318
+ }
3319
+ // Generate recommendations based on issues
3320
+ if (issues.some(i => i.severity === 'critical')) {
3321
+ recommendations.push('Consider restarting agents with high memory usage');
3322
+ recommendations.push('Monitor system resources closely');
3323
+ }
3324
+ if (agentCount === 0) {
3325
+ recommendations.push('No active agents detected - start agents to begin monitoring');
3326
+ }
3327
+ // Clamp health score
3328
+ healthScore = Math.max(0, Math.min(100, healthScore));
3329
+ // Generate summary
3330
+ let summary;
3331
+ if (healthScore >= 90) {
3332
+ summary = 'System is healthy. All agents operating normally.';
3333
+ }
3334
+ else if (healthScore >= 70) {
3335
+ summary = 'Some issues detected. Review warnings and recommendations.';
3336
+ }
3337
+ else if (healthScore >= 50) {
3338
+ summary = 'Multiple issues detected. Action recommended.';
3339
+ }
3340
+ else {
3341
+ summary = 'Critical issues detected. Immediate action required.';
3342
+ }
3343
+ res.json({
3344
+ healthScore,
3345
+ summary,
3346
+ issues,
3347
+ recommendations,
3348
+ crashes,
3349
+ alerts,
3350
+ stats: {
3351
+ totalCrashes24h,
3352
+ totalAlerts24h,
3353
+ agentCount,
3354
+ },
3355
+ });
3356
+ }
3357
+ catch (err) {
3358
+ console.error('Failed to compute health metrics', err);
3359
+ res.status(500).json({ error: 'Failed to compute health metrics' });
3360
+ }
3361
+ });
3362
+ // ===== File Search API =====
3363
+ /**
3364
+ * GET /api/files - Search for files in the repository
3365
+ * Query params:
3366
+ * - q: Search query (file path pattern)
3367
+ * - limit: Max number of results (default 15)
3368
+ *
3369
+ * This endpoint searches for files in the project root directory
3370
+ * to support @-file autocomplete in the message composer.
3371
+ */
3372
+ app.get('/api/files', async (req, res) => {
3373
+ const query = req.query.q || '';
3374
+ const limit = Math.min(parseInt(req.query.limit, 10) || 15, 50);
3375
+ // Get project root (parent of dataDir, or use projectRoot if available)
3376
+ const searchRoot = options.projectRoot || path.dirname(dataDir);
3377
+ try {
3378
+ const results = await searchFiles(searchRoot, query, limit);
3379
+ res.json({ files: results, query, searchRoot: path.basename(searchRoot) });
3380
+ }
3381
+ catch (err) {
3382
+ console.error('[api] File search error:', err);
3383
+ res.status(500).json({ error: 'Failed to search files', files: [] });
3384
+ }
3385
+ });
3386
+ // Bridge API endpoint - returns multi-project data
3387
+ // This is a placeholder that returns empty data when not in bridge mode
3388
+ // The actual bridge data comes from MultiProjectClient when running `agent-relay bridge`
3389
+ app.get('/api/bridge', async (req, res) => {
3390
+ try {
3391
+ // Check if bridge state file exists (written by bridge command)
3392
+ const bridgeStatePath = path.join(dataDir, 'bridge-state.json');
3393
+ if (fs.existsSync(bridgeStatePath)) {
3394
+ const bridgeData = JSON.parse(fs.readFileSync(bridgeStatePath, 'utf-8'));
3395
+ res.json(bridgeData);
3396
+ }
3397
+ else {
3398
+ // No bridge running - return empty state
3399
+ res.json({
3400
+ projects: [],
3401
+ messages: [],
3402
+ connected: false,
3403
+ });
3404
+ }
3405
+ }
3406
+ catch (err) {
3407
+ console.error('Failed to fetch bridge data', err);
3408
+ res.status(500).json({ error: 'Failed to load bridge data' });
3409
+ }
3410
+ });
3411
+ // ===== Conversation History API =====
3412
+ /**
3413
+ * GET /api/history/sessions - List all sessions with filters
3414
+ * Query params:
3415
+ * - agent: Filter by agent name
3416
+ * - since: Filter sessions started after this timestamp (ms)
3417
+ * - limit: Max number of sessions (default 50)
3418
+ */
3419
+ app.get('/api/history/sessions', async (req, res) => {
3420
+ if (!storage) {
3421
+ return res.status(503).json({ error: 'Storage not configured' });
3422
+ }
3423
+ try {
3424
+ const query = {};
3425
+ if (req.query.agent && typeof req.query.agent === 'string') {
3426
+ query.agentName = req.query.agent;
3427
+ }
3428
+ if (req.query.since) {
3429
+ query.since = parseInt(req.query.since, 10);
3430
+ }
3431
+ query.limit = req.query.limit ? parseInt(req.query.limit, 10) : 50;
3432
+ const sessions = storage.getSessions
3433
+ ? await storage.getSessions(query)
3434
+ : [];
3435
+ const result = sessions.map(s => ({
3436
+ id: s.id,
3437
+ agentName: s.agentName,
3438
+ cli: s.cli,
3439
+ startedAt: new Date(s.startedAt).toISOString(),
3440
+ endedAt: s.endedAt ? new Date(s.endedAt).toISOString() : undefined,
3441
+ duration: formatDuration(s.startedAt, s.endedAt),
3442
+ messageCount: s.messageCount,
3443
+ summary: s.summary,
3444
+ isActive: !s.endedAt,
3445
+ closedBy: s.closedBy,
3446
+ }));
3447
+ res.json({ sessions: result });
3448
+ }
3449
+ catch (err) {
3450
+ console.error('Failed to fetch sessions', err);
3451
+ res.status(500).json({ error: 'Failed to fetch sessions' });
3452
+ }
3453
+ });
3454
+ /**
3455
+ * GET /api/history/messages - Get messages with filters
3456
+ * Query params:
3457
+ * - from: Filter by sender
3458
+ * - to: Filter by recipient
3459
+ * - thread: Filter by thread ID
3460
+ * - since: Filter messages after this timestamp (ms)
3461
+ * - limit: Max number of messages (default 100)
3462
+ * - order: 'asc' or 'desc' (default 'desc')
3463
+ * - search: Search in message body (basic substring match)
3464
+ */
3465
+ app.get('/api/history/messages', async (req, res) => {
3466
+ if (!storage) {
3467
+ return res.status(503).json({ error: 'Storage not configured' });
3468
+ }
3469
+ try {
3470
+ const query = {};
3471
+ if (req.query.from && typeof req.query.from === 'string') {
3472
+ query.from = req.query.from;
3473
+ }
3474
+ if (req.query.to && typeof req.query.to === 'string') {
3475
+ query.to = req.query.to;
3476
+ }
3477
+ if (req.query.thread && typeof req.query.thread === 'string') {
3478
+ query.thread = req.query.thread;
3479
+ }
3480
+ if (req.query.since) {
3481
+ query.sinceTs = parseInt(req.query.since, 10);
3482
+ }
3483
+ query.limit = req.query.limit ? parseInt(req.query.limit, 10) : 100;
3484
+ query.order = req.query.order || 'desc';
3485
+ let messages = await storage.getMessages(query);
3486
+ // Filter out messages from/to internal system agents (e.g., __spawner__)
3487
+ messages = messages.filter(m => !isInternalAgent(m.from) && !isInternalAgent(m.to));
3488
+ // Client-side search filter (basic substring match)
3489
+ const searchTerm = req.query.search;
3490
+ if (searchTerm && searchTerm.trim()) {
3491
+ const lowerSearch = searchTerm.toLowerCase();
3492
+ messages = messages.filter(m => m.body.toLowerCase().includes(lowerSearch) ||
3493
+ m.from.toLowerCase().includes(lowerSearch) ||
3494
+ m.to.toLowerCase().includes(lowerSearch));
3495
+ }
3496
+ const result = messages.map(m => ({
3497
+ id: m.id,
3498
+ from: m.from,
3499
+ to: m.to,
3500
+ content: m.body,
3501
+ timestamp: new Date(m.ts).toISOString(),
3502
+ thread: m.thread,
3503
+ isBroadcast: m.is_broadcast,
3504
+ isUrgent: m.is_urgent,
3505
+ status: m.status,
3506
+ }));
3507
+ res.json({ messages: result });
3508
+ }
3509
+ catch (err) {
3510
+ console.error('Failed to fetch messages', err);
3511
+ res.status(500).json({ error: 'Failed to fetch messages' });
3512
+ }
3513
+ });
3514
+ /**
3515
+ * GET /api/history/conversations - Get unique conversations (agent pairs)
3516
+ * Returns list of agent pairs that have exchanged messages
3517
+ */
3518
+ app.get('/api/history/conversations', async (req, res) => {
3519
+ if (!storage) {
3520
+ return res.status(503).json({ error: 'Storage not configured' });
3521
+ }
3522
+ try {
3523
+ // Get all messages to build conversation list
3524
+ const messages = await storage.getMessages({ limit: 1000, order: 'desc' });
3525
+ // Build unique conversation pairs
3526
+ const conversationMap = new Map();
3527
+ for (const msg of messages) {
3528
+ // Skip broadcasts for conversation pairing
3529
+ if (msg.to === '*' || msg.is_broadcast)
3530
+ continue;
3531
+ // Skip messages from/to internal system agents (e.g., __spawner__)
3532
+ if (isInternalAgent(msg.from) || isInternalAgent(msg.to))
3533
+ continue;
3534
+ // Create normalized key (sorted participants)
3535
+ const participants = [msg.from, msg.to].sort();
3536
+ const key = participants.join(':');
3537
+ const existing = conversationMap.get(key);
3538
+ if (existing) {
3539
+ existing.messageCount++;
3540
+ }
3541
+ else {
3542
+ conversationMap.set(key, {
3543
+ participants,
3544
+ lastMessage: msg.body.substring(0, 100),
3545
+ lastTimestamp: new Date(msg.ts).toISOString(),
3546
+ messageCount: 1,
3547
+ });
3548
+ }
3549
+ }
3550
+ // Convert to array sorted by last timestamp
3551
+ const conversations = Array.from(conversationMap.values())
3552
+ .sort((a, b) => new Date(b.lastTimestamp).getTime() - new Date(a.lastTimestamp).getTime());
3553
+ res.json({ conversations });
3554
+ }
3555
+ catch (err) {
3556
+ console.error('Failed to fetch conversations', err);
3557
+ res.status(500).json({ error: 'Failed to fetch conversations' });
3558
+ }
3559
+ });
3560
+ /**
3561
+ * GET /api/history/message/:id - Get a single message by ID
3562
+ */
3563
+ app.get('/api/history/message/:id', async (req, res) => {
3564
+ if (!storage) {
3565
+ return res.status(503).json({ error: 'Storage not configured' });
3566
+ }
3567
+ try {
3568
+ const { id } = req.params;
3569
+ const message = storage.getMessageById
3570
+ ? await storage.getMessageById(id)
3571
+ : null;
3572
+ if (!message) {
3573
+ return res.status(404).json({ error: 'Message not found' });
3574
+ }
3575
+ res.json({
3576
+ id: message.id,
3577
+ from: message.from,
3578
+ to: message.to,
3579
+ content: message.body,
3580
+ timestamp: new Date(message.ts).toISOString(),
3581
+ thread: message.thread,
3582
+ isBroadcast: message.is_broadcast,
3583
+ isUrgent: message.is_urgent,
3584
+ status: message.status,
3585
+ data: message.data,
3586
+ });
3587
+ }
3588
+ catch (err) {
3589
+ console.error('Failed to fetch message', err);
3590
+ res.status(500).json({ error: 'Failed to fetch message' });
3591
+ }
3592
+ });
3593
+ /**
3594
+ * GET /api/history/stats - Get storage statistics
3595
+ */
3596
+ app.get('/api/history/stats', async (req, res) => {
3597
+ if (!storage) {
3598
+ return res.status(503).json({ error: 'Storage not configured' });
3599
+ }
3600
+ try {
3601
+ // Get stats from SQLite adapter if available
3602
+ if (storage instanceof SqliteStorageAdapter) {
3603
+ const stats = await storage.getStats();
3604
+ const sessions = await storage.getSessions({ limit: 1000 });
3605
+ // Calculate additional stats
3606
+ const activeSessions = sessions.filter(s => !s.endedAt).length;
3607
+ const uniqueAgents = new Set(sessions.map(s => s.agentName)).size;
3608
+ res.json({
3609
+ messageCount: stats.messageCount,
3610
+ sessionCount: stats.sessionCount,
3611
+ activeSessions,
3612
+ uniqueAgents,
3613
+ oldestMessageDate: stats.oldestMessageTs
3614
+ ? new Date(stats.oldestMessageTs).toISOString()
3615
+ : null,
3616
+ });
3617
+ }
3618
+ else {
3619
+ // Basic stats for other adapters
3620
+ const messages = await storage.getMessages({ limit: 1 });
3621
+ res.json({
3622
+ messageCount: messages.length > 0 ? 'unknown' : 0,
3623
+ sessionCount: 'unknown',
3624
+ activeSessions: 'unknown',
3625
+ uniqueAgents: 'unknown',
3626
+ });
3627
+ }
3628
+ }
3629
+ catch (err) {
3630
+ console.error('Failed to fetch stats', err);
3631
+ res.status(500).json({ error: 'Failed to fetch stats' });
3632
+ }
3633
+ });
3634
+ // ===== Agent Logs API =====
3635
+ /**
3636
+ * GET /api/logs/:name - Get historical logs for a spawned agent
3637
+ * Query params:
3638
+ * - limit: Max lines to return (default 500)
3639
+ * - raw: If 'true', return raw output instead of cleaned lines
3640
+ */
3641
+ app.get('/api/logs/:name', (req, res) => {
3642
+ if (!spawner) {
3643
+ return res.status(503).json({ error: 'Spawner not enabled' });
3644
+ }
3645
+ const { name } = req.params;
3646
+ const limit = req.query.limit ? parseInt(req.query.limit, 10) : 500;
3647
+ const raw = req.query.raw === 'true';
3648
+ // Check if worker exists
3649
+ if (!spawner.hasWorker(name)) {
3650
+ return res.status(404).json({ error: `Agent ${name} not found` });
3651
+ }
3652
+ try {
3653
+ if (raw) {
3654
+ const output = spawner.getWorkerRawOutput(name);
3655
+ res.json({
3656
+ name,
3657
+ raw: true,
3658
+ output: output || '',
3659
+ timestamp: new Date().toISOString(),
3660
+ });
3661
+ }
3662
+ else {
3663
+ const lines = spawner.getWorkerOutput(name, limit);
3664
+ res.json({
3665
+ name,
3666
+ raw: false,
3667
+ lines: lines || [],
3668
+ lineCount: lines?.length || 0,
3669
+ timestamp: new Date().toISOString(),
3670
+ });
3671
+ }
3672
+ }
3673
+ catch (err) {
3674
+ console.error(`Failed to get logs for ${name}:`, err);
3675
+ res.status(500).json({ error: 'Failed to get logs' });
3676
+ }
3677
+ });
3678
+ /**
3679
+ * GET /api/logs - List all agents with available logs
3680
+ */
3681
+ app.get('/api/logs', (req, res) => {
3682
+ if (!spawner) {
3683
+ return res.status(503).json({ error: 'Spawner not enabled' });
3684
+ }
3685
+ try {
3686
+ const workers = spawner.getActiveWorkers();
3687
+ const agents = workers.map(w => ({
3688
+ name: w.name,
3689
+ cli: w.cli,
3690
+ pid: w.pid,
3691
+ spawnedAt: new Date(w.spawnedAt).toISOString(),
3692
+ hasLogs: true,
3693
+ }));
3694
+ res.json({ agents });
3695
+ }
3696
+ catch (err) {
3697
+ console.error('Failed to list agents with logs:', err);
3698
+ res.status(500).json({ error: 'Failed to list agents' });
3699
+ }
3700
+ });
3701
+ // ===== Agent Status API =====
3702
+ /**
3703
+ * GET /api/agents/:name/online - Check if an agent is online
3704
+ * Used by wrappers to wait for spawned agents before sending tasks.
3705
+ */
3706
+ app.get('/api/agents/:name/online', (req, res) => {
3707
+ const { name } = req.params;
3708
+ const online = isAgentOnline(name);
3709
+ res.json({ name, online });
3710
+ });
3711
+ // ===== Agent Spawn API =====
3712
+ /**
3713
+ * POST /api/spawn - Spawn a new agent
3714
+ * Body: { name: string, cli?: string, task?: string, team?: string, spawnerName?, cwd?, interactive?, shadowMode?, shadowAgent?, shadowOf?, shadowTriggers?, shadowSpeakOn? }
3715
+ */
3716
+ app.post('/api/spawn', async (req, res) => {
3717
+ if (!spawner) {
3718
+ return res.status(503).json({
3719
+ success: false,
3720
+ error: 'Spawner not enabled. Start dashboard with enableSpawner: true',
3721
+ });
3722
+ }
3723
+ const { name, cli = 'claude', task = '', team, spawnerName, cwd, interactive, shadowMode, shadowAgent, shadowOf, shadowTriggers, shadowSpeakOn, userId, } = req.body;
3724
+ if (!name || typeof name !== 'string') {
3725
+ return res.status(400).json({
3726
+ success: false,
3727
+ error: 'Missing required field: name',
3728
+ });
3729
+ }
3730
+ try {
3731
+ const request = {
3732
+ name,
3733
+ cli,
3734
+ task,
3735
+ team: team || undefined, // Optional team name
3736
+ spawnerName: spawnerName || undefined, // For policy enforcement
3737
+ cwd: cwd || undefined, // Working directory
3738
+ interactive, // Disables auto-accept for auth setup flows
3739
+ shadowMode,
3740
+ shadowAgent,
3741
+ shadowOf,
3742
+ shadowTriggers,
3743
+ shadowSpeakOn,
3744
+ userId: typeof userId === 'string' ? userId : undefined,
3745
+ };
3746
+ const result = await spawner.spawn(request);
3747
+ if (result.success) {
3748
+ // Broadcast update to WebSocket clients
3749
+ broadcastData().catch(() => { });
3750
+ }
3751
+ res.json(result);
3752
+ }
3753
+ catch (err) {
3754
+ console.error('[api] Spawn error:', err);
3755
+ res.status(500).json({
3756
+ success: false,
3757
+ name,
3758
+ error: err.message,
3759
+ });
3760
+ }
3761
+ });
3762
+ /**
3763
+ * POST /api/spawn/architect - Spawn an Architect agent for bridge mode
3764
+ * Body: { cli?: string }
3765
+ */
3766
+ app.post('/api/spawn/architect', async (req, res) => {
3767
+ if (!spawner) {
3768
+ return res.status(503).json({
3769
+ success: false,
3770
+ error: 'Spawner not enabled. Start dashboard with enableSpawner: true',
3771
+ });
3772
+ }
3773
+ const { cli = 'claude' } = req.body;
3774
+ // Check if Architect already exists
3775
+ const activeWorkers = spawner.getActiveWorkers();
3776
+ if (activeWorkers.some(w => w.name.toLowerCase() === 'architect')) {
3777
+ return res.status(409).json({
3778
+ success: false,
3779
+ error: 'Architect agent already running',
3780
+ });
3781
+ }
3782
+ // Get bridge state for project context
3783
+ const bridgeStatePath = path.join(dataDir, 'bridge-state.json');
3784
+ let projectContext = 'No bridge projects connected.';
3785
+ if (fs.existsSync(bridgeStatePath)) {
3786
+ try {
3787
+ const bridgeState = JSON.parse(fs.readFileSync(bridgeStatePath, 'utf-8'));
3788
+ if (bridgeState.projects && bridgeState.projects.length > 0) {
3789
+ projectContext = bridgeState.projects
3790
+ .map((p) => `- ${p.id}: ${p.path} (Lead: ${p.lead?.name || 'none'})`)
3791
+ .join('\n');
3792
+ }
3793
+ }
3794
+ catch (e) {
3795
+ console.error('[api] Failed to read bridge state:', e);
3796
+ }
3797
+ }
3798
+ // Build the architect prompt
3799
+ const architectPrompt = `You are the Architect, a cross-project coordinator overseeing multiple codebases.
3800
+
3801
+ ## Connected Projects
3802
+ ${projectContext}
3803
+
3804
+ ## Your Role
3805
+ - Coordinate high-level work across all projects
3806
+ - Assign tasks to project leads
3807
+ - Ensure consistency and resolve cross-project dependencies
3808
+ - Review overall architecture decisions
3809
+
3810
+ ## Cross-Project Messaging
3811
+
3812
+ Use this syntax to message agents in specific projects:
3813
+
3814
+ \`\`\`
3815
+ ->relay:project-id:AgentName <<<
3816
+ Your message to this agent>>>
3817
+
3818
+ ->relay:project-id:* <<<
3819
+ Broadcast to all agents in a project>>>
3820
+
3821
+ ->relay:*:* <<<
3822
+ Broadcast to ALL agents in ALL projects>>>
3823
+ \`\`\`
3824
+
3825
+ ## Getting Started
3826
+ 1. Check in with each project lead to understand current status
3827
+ 2. Identify cross-project dependencies
3828
+ 3. Coordinate work across teams
3829
+
3830
+ Start by greeting the project leads and asking for status updates.`;
3831
+ try {
3832
+ const result = await spawner.spawn({
3833
+ name: 'Architect',
3834
+ cli,
3835
+ task: architectPrompt,
3836
+ });
3837
+ if (result.success) {
3838
+ broadcastData().catch(() => { });
3839
+ }
3840
+ res.json(result);
3841
+ }
3842
+ catch (err) {
3843
+ console.error('[api] Architect spawn error:', err);
3844
+ res.status(500).json({
3845
+ success: false,
3846
+ name: 'Architect',
3847
+ error: err.message,
3848
+ });
3849
+ }
3850
+ });
3851
+ /**
3852
+ * GET /api/spawned - List active spawned agents
3853
+ *
3854
+ * Returns agents from two sources:
3855
+ * 1. Spawner's active workers (in-memory tracking)
3856
+ * 2. Daemon's agents.json registry (persisted, survives restarts)
3857
+ *
3858
+ * This fallback ensures docker deployments show agents even after
3859
+ * container restarts when spawner's in-memory state is lost but
3860
+ * agents have reconnected to the daemon.
3861
+ */
3862
+ app.get('/api/spawned', (req, res) => {
3863
+ // Collect agents from all available sources
3864
+ const agentsByName = new Map();
3865
+ // Source 1: Spawner's active workers (authoritative for spawned agents)
3866
+ if (spawner) {
3867
+ for (const worker of spawner.getActiveWorkers()) {
3868
+ agentsByName.set(worker.name, {
3869
+ name: worker.name,
3870
+ cli: worker.cli,
3871
+ pid: worker.pid,
3872
+ spawnedAt: worker.spawnedAt,
3873
+ task: worker.task,
3874
+ team: worker.team,
3875
+ source: 'spawner',
3876
+ });
3877
+ }
3878
+ }
3879
+ // Source 2: Daemon's agents.json registry (fallback for docker restarts)
3880
+ // Only include agents not already tracked by spawner
3881
+ const agentsPath = path.join(teamDir, 'agents.json');
3882
+ if (fs.existsSync(agentsPath)) {
3883
+ try {
3884
+ const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
3885
+ const registeredAgents = data.agents || [];
3886
+ const thirtySecondsAgo = Date.now() - 30 * 1000;
3887
+ for (const agent of registeredAgents) {
3888
+ // Skip if already tracked by spawner
3889
+ if (agentsByName.has(agent.name))
3890
+ continue;
3891
+ // Only include recently active agents (within 30s heartbeat window)
3892
+ const lastSeen = agent.lastSeen ? new Date(agent.lastSeen).getTime() : 0;
3893
+ if (lastSeen < thirtySecondsAgo)
3894
+ continue;
3895
+ agentsByName.set(agent.name, {
3896
+ name: agent.name,
3897
+ cli: agent.cli || 'unknown',
3898
+ spawnedAt: agent.connectedAt ? new Date(agent.connectedAt).getTime() : undefined,
3899
+ team: agent.team,
3900
+ source: 'daemon',
3901
+ });
3902
+ }
3903
+ }
3904
+ catch (err) {
3905
+ console.error('[api/spawned] Failed to read agents.json:', err);
3906
+ }
3907
+ }
3908
+ const agents = Array.from(agentsByName.values());
3909
+ res.json({
3910
+ success: true,
3911
+ agents,
3912
+ // Include source info for debugging
3913
+ sources: {
3914
+ spawnerEnabled: !!spawner,
3915
+ daemonAgentsFile: fs.existsSync(agentsPath),
3916
+ },
3917
+ });
3918
+ });
3919
+ /**
3920
+ * DELETE /api/spawned/:name - Release a spawned agent
3921
+ */
3922
+ app.delete('/api/spawned/:name', async (req, res) => {
3923
+ if (!spawner) {
3924
+ return res.status(503).json({
3925
+ success: false,
3926
+ error: 'Spawner not enabled',
3927
+ });
3928
+ }
3929
+ const { name } = req.params;
3930
+ try {
3931
+ const released = await spawner.release(name);
3932
+ if (released) {
3933
+ broadcastData().catch(() => { });
3934
+ }
3935
+ res.json({
3936
+ success: released,
3937
+ name,
3938
+ error: released ? undefined : `Agent ${name} not found`,
3939
+ });
3940
+ }
3941
+ catch (err) {
3942
+ console.error('[api] Release error:', err);
3943
+ res.status(500).json({
3944
+ success: false,
3945
+ name,
3946
+ error: err.message,
3947
+ });
3948
+ }
3949
+ });
3950
+ /**
3951
+ * POST /api/agents/by-name/:name/interrupt - Send ESC sequence to interrupt an agent
3952
+ *
3953
+ * Sends ESC ESC (0x1b 0x1b) to the agent's PTY to interrupt the current operation.
3954
+ * This is useful for breaking agents out of stuck loops without terminating them.
3955
+ */
3956
+ app.post('/api/agents/by-name/:name/interrupt', (req, res) => {
3957
+ if (!spawner) {
3958
+ return res.status(503).json({
3959
+ success: false,
3960
+ error: 'Spawner not enabled',
3961
+ });
3962
+ }
3963
+ const { name } = req.params;
3964
+ // Check if agent exists
3965
+ if (!spawner.hasWorker(name)) {
3966
+ return res.status(404).json({
3967
+ success: false,
3968
+ error: `Agent ${name} not found or not spawned`,
3969
+ });
3970
+ }
3971
+ try {
3972
+ // Send ESC ESC sequence to interrupt the agent
3973
+ // ESC = 0x1b in hexadecimal
3974
+ const success = spawner.sendWorkerInput(name, '\x1b\x1b');
3975
+ if (success) {
3976
+ console.log(`[api] Sent interrupt (ESC ESC) to agent ${name}`);
3977
+ res.json({
3978
+ success: true,
3979
+ message: `Interrupt signal sent to ${name}`,
3980
+ });
3981
+ }
3982
+ else {
3983
+ res.status(500).json({
3984
+ success: false,
3985
+ error: `Failed to send interrupt to ${name}`,
3986
+ });
3987
+ }
3988
+ }
3989
+ catch (err) {
3990
+ console.error('[api] Interrupt error:', err);
3991
+ res.status(500).json({
3992
+ success: false,
3993
+ error: err.message,
3994
+ });
3995
+ }
3996
+ });
3997
+ /**
3998
+ * GET /api/trajectory - Get current trajectory status
3999
+ */
4000
+ app.get('/api/trajectory', async (_req, res) => {
4001
+ try {
4002
+ const status = await getTrajectoryStatus();
4003
+ res.json({
4004
+ success: true,
4005
+ ...status,
4006
+ });
4007
+ }
4008
+ catch (err) {
4009
+ console.error('[api] Trajectory status error:', err);
4010
+ res.status(500).json({
4011
+ success: false,
4012
+ error: err.message,
4013
+ });
4014
+ }
4015
+ });
4016
+ /**
4017
+ * GET /api/trajectory/steps - List trajectory steps
4018
+ */
4019
+ app.get('/api/trajectory/steps', async (req, res) => {
4020
+ try {
4021
+ const trajectoryId = req.query.trajectoryId;
4022
+ const result = await listTrajectorySteps(trajectoryId);
4023
+ if (result.success) {
4024
+ res.json({
4025
+ success: true,
4026
+ steps: result.steps,
4027
+ });
4028
+ }
4029
+ else {
4030
+ res.status(500).json({
4031
+ success: false,
4032
+ steps: [],
4033
+ error: result.error,
4034
+ });
4035
+ }
4036
+ }
4037
+ catch (err) {
4038
+ console.error('[api] Trajectory steps error:', err);
4039
+ res.status(500).json({
4040
+ success: false,
4041
+ steps: [],
4042
+ error: err.message,
4043
+ });
4044
+ }
4045
+ });
4046
+ /**
4047
+ * GET /api/trajectory/history - List all trajectories (completed and active)
4048
+ */
4049
+ app.get('/api/trajectory/history', async (_req, res) => {
4050
+ try {
4051
+ const result = await getTrajectoryHistory();
4052
+ if (result.success) {
4053
+ res.json({
4054
+ success: true,
4055
+ trajectories: result.trajectories,
4056
+ });
4057
+ }
4058
+ else {
4059
+ res.status(500).json({
4060
+ success: false,
4061
+ trajectories: [],
4062
+ error: result.error,
4063
+ });
4064
+ }
4065
+ }
4066
+ catch (err) {
4067
+ console.error('[api] Trajectory history error:', err);
4068
+ res.status(500).json({
4069
+ success: false,
4070
+ trajectories: [],
4071
+ error: err.message,
4072
+ });
4073
+ }
4074
+ });
4075
+ // ===== Settings API =====
4076
+ /**
4077
+ * GET /api/settings - Get all workspace settings with documentation
4078
+ */
4079
+ app.get('/api/settings', async (_req, res) => {
4080
+ try {
4081
+ const { readRelayConfig, shouldStoreInRepo, getTrajectoriesStorageDescription } = await import('../trajectory/config.js');
4082
+ const config = readRelayConfig();
4083
+ res.json({
4084
+ success: true,
4085
+ settings: {
4086
+ trajectories: {
4087
+ storeInRepo: shouldStoreInRepo(),
4088
+ storageLocation: getTrajectoriesStorageDescription(),
4089
+ description: 'Trajectories record the journey of agent work using the PDERO paradigm (Plan, Design, Execute, Review, Observe). They capture decisions, phase transitions, and retrospectives.',
4090
+ benefits: [
4091
+ 'Track why decisions were made, not just what was built',
4092
+ 'Enable session recovery when agents crash or context is lost',
4093
+ 'Provide learning data for future agents working on similar tasks',
4094
+ 'Create an audit trail of agent work for review',
4095
+ ],
4096
+ learnMore: 'https://pdero.com',
4097
+ optInReason: 'Enable "Store in repo" to version-control your trajectories alongside your code. This is useful for teams who want to review agent decision-making processes.',
4098
+ },
4099
+ },
4100
+ config,
4101
+ });
4102
+ }
4103
+ catch (err) {
4104
+ console.error('[api] Settings error:', err);
4105
+ res.status(500).json({
4106
+ success: false,
4107
+ error: err.message,
4108
+ });
4109
+ }
4110
+ });
4111
+ /**
4112
+ * GET /api/settings/trajectory - Get trajectory storage settings
4113
+ */
4114
+ app.get('/api/settings/trajectory', async (_req, res) => {
4115
+ try {
4116
+ const { readRelayConfig, shouldStoreInRepo, getTrajectoriesStorageDescription } = await import('../trajectory/config.js');
4117
+ const config = readRelayConfig();
4118
+ res.json({
4119
+ success: true,
4120
+ settings: {
4121
+ storeInRepo: shouldStoreInRepo(),
4122
+ storageLocation: getTrajectoriesStorageDescription(),
4123
+ },
4124
+ config: config.trajectories || {},
4125
+ // Documentation for the UI
4126
+ documentation: {
4127
+ title: 'Trajectory Storage',
4128
+ description: 'Trajectories record the journey of agent work using the PDERO paradigm (Plan, Design, Execute, Review, Observe).',
4129
+ whatIsIt: 'A trajectory captures not just what an agent built, but WHY it made specific decisions. This includes phase transitions, key decisions with reasoning, and retrospective summaries.',
4130
+ benefits: [
4131
+ 'Understand agent decision-making for code review',
4132
+ 'Enable session recovery if agents crash',
4133
+ 'Train future agents on your codebase patterns',
4134
+ 'Create audit trails of AI work',
4135
+ ],
4136
+ storeInRepoExplanation: 'When enabled, trajectories are stored in .trajectories/ in your repo and can be committed to source control. When disabled (default), they are stored in your user directory (~/.config/agent-relay/trajectories/).',
4137
+ learnMore: 'https://pdero.com',
4138
+ },
4139
+ });
4140
+ }
4141
+ catch (err) {
4142
+ console.error('[api] Settings trajectory error:', err);
4143
+ res.status(500).json({
4144
+ success: false,
4145
+ error: err.message,
4146
+ });
4147
+ }
4148
+ });
4149
+ /**
4150
+ * PUT /api/settings/trajectory - Update trajectory storage settings
4151
+ *
4152
+ * Body: { storeInRepo: boolean }
4153
+ *
4154
+ * This writes to .relay/config.json in the project root
4155
+ */
4156
+ app.put('/api/settings/trajectory', async (req, res) => {
4157
+ try {
4158
+ const { storeInRepo } = req.body;
4159
+ if (typeof storeInRepo !== 'boolean') {
4160
+ return res.status(400).json({
4161
+ success: false,
4162
+ error: 'storeInRepo must be a boolean',
4163
+ });
4164
+ }
4165
+ const { getRelayConfigPath, readRelayConfig } = await import('../trajectory/config.js');
4166
+ const { getProjectPaths } = await import('../utils/project-namespace.js');
4167
+ const { projectRoot: _projectRoot } = getProjectPaths();
4168
+ // Read existing config
4169
+ const config = readRelayConfig();
4170
+ // Update trajectory settings
4171
+ config.trajectories = {
4172
+ ...config.trajectories,
4173
+ storeInRepo,
4174
+ };
4175
+ // Ensure .relay directory exists
4176
+ const configPath = getRelayConfigPath();
4177
+ const configDir = path.dirname(configPath);
4178
+ if (!fs.existsSync(configDir)) {
4179
+ fs.mkdirSync(configDir, { recursive: true });
4180
+ }
4181
+ // Write updated config
4182
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
4183
+ res.json({
4184
+ success: true,
4185
+ settings: {
4186
+ storeInRepo,
4187
+ storageLocation: storeInRepo ? 'repo (.trajectories/)' : 'user (~/.config/agent-relay/trajectories/)',
4188
+ },
4189
+ });
4190
+ }
4191
+ catch (err) {
4192
+ console.error('[api] Settings trajectory update error:', err);
4193
+ res.status(500).json({
4194
+ success: false,
4195
+ error: err.message,
4196
+ });
4197
+ }
4198
+ });
4199
+ const decisions = new Map();
4200
+ /**
4201
+ * GET /api/decisions - List all pending decisions
4202
+ */
4203
+ app.get('/api/decisions', (_req, res) => {
4204
+ const allDecisions = Array.from(decisions.values())
4205
+ .sort((a, b) => {
4206
+ const urgencyOrder = { critical: 0, high: 1, medium: 2, low: 3 };
4207
+ return urgencyOrder[a.urgency] - urgencyOrder[b.urgency];
4208
+ });
4209
+ res.json({ success: true, decisions: allDecisions });
4210
+ });
4211
+ /**
4212
+ * POST /api/decisions - Create a new decision request
4213
+ * Body: { agentName, title, description, options?, urgency, category, expiresAt?, context? }
4214
+ */
4215
+ app.post('/api/decisions', (req, res) => {
4216
+ const { agentName, title, description, options, urgency, category, expiresAt, context } = req.body;
4217
+ if (!agentName || !title || !urgency || !category) {
4218
+ return res.status(400).json({
4219
+ success: false,
4220
+ error: 'Missing required fields: agentName, title, urgency, category',
4221
+ });
4222
+ }
4223
+ const decision = {
4224
+ id: `decision-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
4225
+ agentName,
4226
+ title,
4227
+ description: description || '',
4228
+ options,
4229
+ urgency,
4230
+ category,
4231
+ createdAt: new Date().toISOString(),
4232
+ expiresAt,
4233
+ context,
4234
+ };
4235
+ decisions.set(decision.id, decision);
4236
+ // Broadcast to WebSocket clients
4237
+ broadcastData().catch(() => { });
4238
+ res.json({ success: true, decision });
4239
+ });
4240
+ /**
4241
+ * POST /api/decisions/:id/approve - Approve/resolve a decision
4242
+ * Body: { optionId?: string, response?: string }
4243
+ */
4244
+ app.post('/api/decisions/:id/approve', async (req, res) => {
4245
+ const { id } = req.params;
4246
+ const { optionId, response } = req.body;
4247
+ const decision = decisions.get(id);
4248
+ if (!decision) {
4249
+ return res.status(404).json({ success: false, error: 'Decision not found' });
4250
+ }
4251
+ // Send response to the agent via relay
4252
+ const agentName = decision.agentName;
4253
+ let responseMessage = `DECISION APPROVED: ${decision.title}`;
4254
+ if (optionId && decision.options) {
4255
+ const option = decision.options.find(o => o.id === optionId);
4256
+ if (option) {
4257
+ responseMessage += `\nSelected: ${option.label}`;
4258
+ }
4259
+ }
4260
+ if (response) {
4261
+ responseMessage += `\nResponse: ${response}`;
4262
+ }
4263
+ // Try to send message to agent
4264
+ try {
4265
+ const client = await getRelayClient('_DashboardUI');
4266
+ if (client) {
4267
+ await client.sendMessage(agentName, responseMessage, 'message');
4268
+ }
4269
+ }
4270
+ catch (err) {
4271
+ console.warn('[api] Could not send decision response to agent:', err);
4272
+ }
4273
+ decisions.delete(id);
4274
+ broadcastData().catch(() => { });
4275
+ res.json({ success: true, message: 'Decision approved' });
4276
+ });
4277
+ /**
4278
+ * POST /api/decisions/:id/reject - Reject a decision
4279
+ * Body: { reason?: string }
4280
+ */
4281
+ app.post('/api/decisions/:id/reject', async (req, res) => {
4282
+ const { id } = req.params;
4283
+ const { reason } = req.body;
4284
+ const decision = decisions.get(id);
4285
+ if (!decision) {
4286
+ return res.status(404).json({ success: false, error: 'Decision not found' });
4287
+ }
4288
+ // Send rejection to the agent
4289
+ const agentName = decision.agentName;
4290
+ let responseMessage = `DECISION REJECTED: ${decision.title}`;
4291
+ if (reason) {
4292
+ responseMessage += `\nReason: ${reason}`;
4293
+ }
4294
+ try {
4295
+ const client = await getRelayClient('_DashboardUI');
4296
+ if (client) {
4297
+ await client.sendMessage(agentName, responseMessage, 'message');
4298
+ }
4299
+ }
4300
+ catch (err) {
4301
+ console.warn('[api] Could not send decision rejection to agent:', err);
4302
+ }
4303
+ decisions.delete(id);
4304
+ broadcastData().catch(() => { });
4305
+ res.json({ success: true, message: 'Decision rejected' });
4306
+ });
4307
+ /**
4308
+ * DELETE /api/decisions/:id - Delete/dismiss a decision
4309
+ */
4310
+ app.delete('/api/decisions/:id', (_req, res) => {
4311
+ const { id } = _req.params;
4312
+ if (!decisions.has(id)) {
4313
+ return res.status(404).json({ success: false, error: 'Decision not found' });
4314
+ }
4315
+ decisions.delete(id);
4316
+ broadcastData().catch(() => { });
4317
+ res.json({ success: true, message: 'Decision dismissed' });
4318
+ });
4319
+ /**
4320
+ * GET /api/fleet/servers - Get fleet server overview
4321
+ * Returns local daemon info + any connected bridge servers
4322
+ * Note: When bridge is active, local agents are already included in bridge project agents,
4323
+ * so we don't add a separate "Local Daemon" entry to avoid double-counting.
4324
+ */
4325
+ app.get('/api/fleet/servers', async (_req, res) => {
4326
+ const servers = [];
4327
+ const localAgents = spawner?.getActiveWorkers() || [];
4328
+ const agentStatuses = await loadAgentStatuses();
4329
+ let hasBridgeProjects = false;
4330
+ // Check for bridge connections first
4331
+ const bridgeStatePath = path.join(dataDir, 'bridge-state.json');
4332
+ if (fs.existsSync(bridgeStatePath)) {
4333
+ try {
4334
+ const bridgeState = JSON.parse(fs.readFileSync(bridgeStatePath, 'utf-8'));
4335
+ if (bridgeState.projects && bridgeState.projects.length > 0) {
4336
+ hasBridgeProjects = true;
4337
+ for (const project of bridgeState.projects) {
4338
+ // Enrich with actual online agents from agents.json (same logic as getBridgeData)
4339
+ // This fixes the bug where stale agents were counted
4340
+ let projectAgents = [];
4341
+ if (project.path) {
4342
+ const projectHash = crypto.createHash('sha256').update(project.path).digest('hex').slice(0, 12);
4343
+ const projectDataDir = path.join(path.dirname(dataDir), projectHash);
4344
+ const projectTeamDir = path.join(projectDataDir, 'team');
4345
+ const agentsPath = path.join(projectTeamDir, 'agents.json');
4346
+ if (fs.existsSync(agentsPath)) {
4347
+ try {
4348
+ const agentsData = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
4349
+ if (agentsData.agents && Array.isArray(agentsData.agents)) {
4350
+ // Filter to only show online agents (seen within 30 seconds)
4351
+ const thirtySecondsAgo = Date.now() - 30 * 1000;
4352
+ projectAgents = agentsData.agents
4353
+ .filter((a) => {
4354
+ if (!a.lastSeen)
4355
+ return false;
4356
+ return new Date(a.lastSeen).getTime() > thirtySecondsAgo;
4357
+ })
4358
+ .map((a) => ({
4359
+ name: a.name,
4360
+ status: 'online',
4361
+ }));
4362
+ }
4363
+ }
4364
+ catch (e) {
4365
+ console.warn(`[api] Failed to read agents for ${project.path}:`, e);
4366
+ }
4367
+ }
4368
+ }
4369
+ servers.push({
4370
+ id: project.id,
4371
+ name: project.name || project.path.split('/').pop() || project.id,
4372
+ status: project.connected ? 'healthy' : 'offline',
4373
+ agents: projectAgents,
4374
+ cpuUsage: 0,
4375
+ memoryUsage: 0,
4376
+ activeConnections: project.connected ? 1 : 0,
4377
+ uptime: 0,
4378
+ lastHeartbeat: project.lastSeen || new Date().toISOString(),
4379
+ });
4380
+ }
4381
+ }
4382
+ }
4383
+ catch (err) {
4384
+ console.warn('[api] Failed to read bridge state:', err);
4385
+ }
4386
+ }
4387
+ // Only add local daemon entry if we don't have bridge projects
4388
+ // (otherwise local agents are already counted in the bridge project)
4389
+ if (!hasBridgeProjects) {
4390
+ servers.push({
4391
+ id: 'local',
4392
+ name: 'Local Daemon',
4393
+ status: 'healthy',
4394
+ agents: localAgents.map(a => ({
4395
+ name: a.name,
4396
+ status: agentStatuses[a.name]?.status || 'unknown',
4397
+ })),
4398
+ cpuUsage: Math.random() * 30, // Mock - would come from actual metrics
4399
+ memoryUsage: Math.random() * 50,
4400
+ activeConnections: wss.clients.size,
4401
+ uptime: process.uptime(),
4402
+ lastHeartbeat: new Date().toISOString(),
4403
+ });
4404
+ }
4405
+ res.json({ success: true, servers });
4406
+ });
4407
+ /**
4408
+ * GET /api/fleet/stats - Get aggregate fleet statistics
4409
+ */
4410
+ app.get('/api/fleet/stats', async (_req, res) => {
4411
+ const localAgents = spawner?.getActiveWorkers() || [];
4412
+ const agentStatuses = await loadAgentStatuses();
4413
+ const totalAgents = localAgents.length;
4414
+ let onlineAgents = 0;
4415
+ let busyAgents = 0;
4416
+ for (const agent of localAgents) {
4417
+ const status = agentStatuses[agent.name]?.status;
4418
+ if (status === 'online')
4419
+ onlineAgents++;
4420
+ if (status === 'busy')
4421
+ busyAgents++;
4422
+ }
4423
+ res.json({
4424
+ success: true,
4425
+ stats: {
4426
+ totalAgents,
4427
+ onlineAgents,
4428
+ busyAgents,
4429
+ pendingDecisions: decisions.size,
4430
+ activeTasks: Array.from(tasks.values()).filter(t => t.status === 'assigned' || t.status === 'in_progress').length,
4431
+ },
4432
+ });
4433
+ });
4434
+ const tasks = new Map();
4435
+ /**
4436
+ * GET /api/tasks - List all tasks
4437
+ */
4438
+ app.get('/api/tasks', (req, res) => {
4439
+ const status = req.query.status;
4440
+ const agentName = req.query.agent;
4441
+ let allTasks = Array.from(tasks.values());
4442
+ if (status) {
4443
+ allTasks = allTasks.filter(t => t.status === status);
4444
+ }
4445
+ if (agentName) {
4446
+ allTasks = allTasks.filter(t => t.agentName === agentName);
4447
+ }
4448
+ // Sort by priority and creation time
4449
+ allTasks.sort((a, b) => {
4450
+ const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
4451
+ const priorityDiff = priorityOrder[a.priority] - priorityOrder[b.priority];
4452
+ if (priorityDiff !== 0)
4453
+ return priorityDiff;
4454
+ return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
4455
+ });
4456
+ res.json({ success: true, tasks: allTasks });
4457
+ });
4458
+ /**
4459
+ * POST /api/tasks - Create and assign a task
4460
+ * Body: { agentName, title, description, priority }
4461
+ */
4462
+ app.post('/api/tasks', async (req, res) => {
4463
+ const { agentName, title, description, priority } = req.body;
4464
+ if (!agentName || !title || !priority) {
4465
+ return res.status(400).json({
4466
+ success: false,
4467
+ error: 'Missing required fields: agentName, title, priority',
4468
+ });
4469
+ }
4470
+ const task = {
4471
+ id: `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
4472
+ agentName,
4473
+ title,
4474
+ description: description || '',
4475
+ priority,
4476
+ status: 'assigned',
4477
+ createdAt: new Date().toISOString(),
4478
+ assignedAt: new Date().toISOString(),
4479
+ };
4480
+ tasks.set(task.id, task);
4481
+ // Send task to agent via relay
4482
+ try {
4483
+ const client = await getRelayClient('_DashboardUI');
4484
+ if (client) {
4485
+ const taskMessage = `TASK ASSIGNED [${priority.toUpperCase()}]: ${title}\n\n${description || 'No additional details.'}`;
4486
+ await client.sendMessage(agentName, taskMessage, 'message');
4487
+ }
4488
+ }
4489
+ catch (err) {
4490
+ console.warn('[api] Could not send task to agent:', err);
4491
+ }
4492
+ broadcastData().catch(() => { });
4493
+ res.json({ success: true, task });
4494
+ });
4495
+ /**
4496
+ * PATCH /api/tasks/:id - Update task status
4497
+ * Body: { status, result? }
4498
+ */
4499
+ app.patch('/api/tasks/:id', (req, res) => {
4500
+ const { id } = req.params;
4501
+ const { status, result } = req.body;
4502
+ const task = tasks.get(id);
4503
+ if (!task) {
4504
+ return res.status(404).json({ success: false, error: 'Task not found' });
4505
+ }
4506
+ if (status) {
4507
+ task.status = status;
4508
+ if (status === 'completed' || status === 'failed') {
4509
+ task.completedAt = new Date().toISOString();
4510
+ }
4511
+ }
4512
+ if (result !== undefined) {
4513
+ task.result = result;
4514
+ }
4515
+ tasks.set(id, task);
4516
+ broadcastData().catch(() => { });
4517
+ res.json({ success: true, task });
4518
+ });
4519
+ /**
4520
+ * DELETE /api/tasks/:id - Cancel/delete a task
4521
+ */
4522
+ app.delete('/api/tasks/:id', async (req, res) => {
4523
+ const { id } = req.params;
4524
+ const task = tasks.get(id);
4525
+ if (!task) {
4526
+ return res.status(404).json({ success: false, error: 'Task not found' });
4527
+ }
4528
+ // Notify agent of cancellation if task is still active
4529
+ if (task.status === 'pending' || task.status === 'assigned' || task.status === 'in_progress') {
4530
+ try {
4531
+ const client = await getRelayClient('_DashboardUI');
4532
+ if (client) {
4533
+ await client.sendMessage(task.agentName, `TASK CANCELLED: ${task.title}`, 'message');
4534
+ }
4535
+ }
4536
+ catch (err) {
4537
+ console.warn('[api] Could not send task cancellation to agent:', err);
4538
+ }
4539
+ }
4540
+ tasks.delete(id);
4541
+ broadcastData().catch(() => { });
4542
+ res.json({ success: true, message: 'Task cancelled' });
4543
+ });
4544
+ // ===== Beads Integration API =====
4545
+ /**
4546
+ * POST /api/beads - Create a bead (task/issue) via the bd CLI
4547
+ */
4548
+ app.post('/api/beads', async (req, res) => {
4549
+ const { title, assignee, priority, type, description: _description } = req.body;
4550
+ if (!title || typeof title !== 'string') {
4551
+ return res.status(400).json({ success: false, error: 'Title is required' });
4552
+ }
4553
+ // Build bd create command
4554
+ const args = ['create', `--title="${title.replace(/"/g, '\\"')}"`];
4555
+ if (assignee) {
4556
+ args.push(`--assignee=${assignee}`);
4557
+ }
4558
+ if (priority !== undefined && priority !== null) {
4559
+ args.push(`--priority=${priority}`);
4560
+ }
4561
+ if (type && ['task', 'bug', 'feature'].includes(type)) {
4562
+ args.push(`--type=${type}`);
4563
+ }
4564
+ const cmd = `bd ${args.join(' ')}`;
4565
+ console.log('[api/beads] Creating bead:', cmd);
4566
+ // Execute bd create command
4567
+ exec(cmd, { cwd: dataDir }, (error, stdout, stderr) => {
4568
+ if (error) {
4569
+ console.error('[api/beads] bd create failed:', stderr || error.message);
4570
+ return res.status(500).json({
4571
+ success: false,
4572
+ error: stderr || error.message || 'Failed to create bead',
4573
+ });
4574
+ }
4575
+ // Parse bead ID from output (bd create outputs the ID)
4576
+ const output = stdout.trim();
4577
+ // bd create typically outputs: "Created beads-xxx: title"
4578
+ const idMatch = output.match(/Created\s+(beads-\w+)/i) || output.match(/(beads-\w+)/);
4579
+ const beadId = idMatch ? idMatch[1] : `beads-${Date.now()}`;
4580
+ console.log('[api/beads] Created bead:', beadId);
4581
+ res.json({
4582
+ success: true,
4583
+ bead: {
4584
+ id: beadId,
4585
+ title,
4586
+ assignee,
4587
+ priority,
4588
+ type: type || 'task',
4589
+ },
4590
+ });
4591
+ });
4592
+ });
4593
+ /**
4594
+ * POST /api/relay/send - Send a relay message to an agent
4595
+ */
4596
+ app.post('/api/relay/send', async (req, res) => {
4597
+ const { to, content, thread } = req.body;
4598
+ if (!to || typeof to !== 'string') {
4599
+ return res.status(400).json({ success: false, error: 'Recipient (to) is required' });
4600
+ }
4601
+ if (!content || typeof content !== 'string') {
4602
+ return res.status(400).json({ success: false, error: 'Message content is required' });
4603
+ }
4604
+ try {
4605
+ const client = await getRelayClient('_DashboardUI');
4606
+ if (!client) {
4607
+ return res.status(503).json({
4608
+ success: false,
4609
+ error: 'Relay client not available',
4610
+ });
4611
+ }
4612
+ const messageId = await client.sendMessage(to, content, thread ? 'message' : 'message');
4613
+ console.log('[api/relay/send] Sent message to', to, ':', messageId);
4614
+ res.json({
4615
+ success: true,
4616
+ messageId: messageId || `msg-${Date.now()}`,
4617
+ });
4618
+ }
4619
+ catch (err) {
4620
+ console.error('[api/relay/send] Failed to send message:', err);
4621
+ res.status(500).json({
4622
+ success: false,
4623
+ error: err instanceof Error ? err.message : 'Failed to send message',
4624
+ });
4625
+ }
4626
+ });
4627
+ // Helper to load agent statuses
4628
+ async function loadAgentStatuses() {
4629
+ const agentsFile = path.join(dataDir, 'agents.json');
4630
+ try {
4631
+ if (fs.existsSync(agentsFile)) {
4632
+ const data = JSON.parse(fs.readFileSync(agentsFile, 'utf-8'));
4633
+ const result = {};
4634
+ for (const agent of data.agents || []) {
4635
+ result[agent.name] = { status: agent.status || 'offline' };
4636
+ }
4637
+ return result;
4638
+ }
4639
+ }
4640
+ catch (err) {
4641
+ console.warn('[api] Failed to load agent statuses:', err);
4642
+ }
4643
+ return {};
4644
+ }
4645
+ // Watch for changes
4646
+ if (storage) {
4647
+ setInterval(() => {
4648
+ broadcastData().catch((err) => console.error('Broadcast failed', err));
4649
+ broadcastBridgeData().catch((err) => console.error('Bridge broadcast failed', err));
4650
+ }, 1000);
4651
+ }
4652
+ else {
4653
+ let fsWait = null;
4654
+ let bridgeFsWait = null;
4655
+ try {
4656
+ if (fs.existsSync(dataDir)) {
4657
+ console.log(`Watching ${dataDir} for changes...`);
4658
+ fs.watch(dataDir, { recursive: true }, (eventType, filename) => {
4659
+ if (filename && (filename.endsWith('inbox.md') || filename.endsWith('team.json') || filename.endsWith('agents.json') || filename.endsWith('processing-state.json'))) {
4660
+ // Debounce
4661
+ if (fsWait)
4662
+ return;
4663
+ fsWait = setTimeout(() => {
4664
+ fsWait = null;
4665
+ broadcastData();
4666
+ }, 100);
4667
+ }
4668
+ // Watch for bridge state changes
4669
+ if (filename && filename.endsWith('bridge-state.json')) {
4670
+ if (bridgeFsWait)
4671
+ return;
4672
+ bridgeFsWait = setTimeout(() => {
4673
+ bridgeFsWait = null;
4674
+ broadcastBridgeData();
4675
+ }, 100);
4676
+ }
4677
+ });
4678
+ }
4679
+ else {
4680
+ console.warn(`Data directory ${dataDir} does not exist yet.`);
4681
+ }
4682
+ }
4683
+ catch (e) {
4684
+ console.error('Watch failed:', e);
4685
+ }
4686
+ }
4687
+ // Try to find an available port, starting from the requested port
4688
+ const findAvailablePort = async (startPort, maxAttempts = 10) => {
4689
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
4690
+ const portToTry = startPort + attempt;
4691
+ const isAvailable = await new Promise((resolve) => {
4692
+ const testServer = http.createServer();
4693
+ testServer.once('error', () => resolve(false));
4694
+ testServer.once('listening', () => {
4695
+ testServer.close();
4696
+ resolve(true);
4697
+ });
4698
+ testServer.listen(portToTry);
4699
+ });
4700
+ if (isAvailable) {
4701
+ return portToTry;
4702
+ }
4703
+ console.log(`Port ${portToTry} in use, trying ${portToTry + 1}...`);
4704
+ }
4705
+ throw new Error(`Could not find available port after trying ${startPort}-${startPort + maxAttempts - 1}`);
4706
+ };
4707
+ const availablePort = await findAvailablePort(port);
4708
+ if (availablePort !== port) {
4709
+ console.log(`Requested dashboard port ${port} is busy; switching to ${availablePort}.`);
4710
+ }
4711
+ return new Promise((resolve, reject) => {
4712
+ server.listen(availablePort, async () => {
4713
+ console.log(`Dashboard running at http://localhost:${availablePort} (build: cloud-channels-v2)`);
4714
+ console.log(`Monitoring: ${dataDir}`);
4715
+ // Set the dashboard port on spawner so spawned agents can use the API for nested spawns
4716
+ if (spawner) {
4717
+ spawner.setDashboardPort(availablePort);
4718
+ }
4719
+ // Start health worker on separate thread for reliable health checks
4720
+ // This ensures health checks respond even when main event loop is blocked
4721
+ const healthPort = getHealthPort(availablePort);
4722
+ const healthWorker = new HealthWorkerManager({ port: healthPort }, {
4723
+ getUptime: () => process.uptime(),
4724
+ getMemoryMB: () => Math.round(process.memoryUsage().heapUsed / 1024 / 1024),
4725
+ getRelayConnected: () => {
4726
+ const defaultClient = relayClients.get('Dashboard');
4727
+ return defaultClient?.state === 'READY';
4728
+ },
4729
+ getAgentCount: () => relayClients.size,
4730
+ getStatus: () => {
4731
+ const socketExists = fs.existsSync(socketPath);
4732
+ if (!socketExists)
4733
+ return 'degraded';
4734
+ const defaultClient = relayClients.get('Dashboard');
4735
+ return defaultClient?.state === 'READY' ? 'healthy' : 'busy';
4736
+ },
4737
+ });
4738
+ try {
4739
+ await healthWorker.start();
4740
+ console.log(`Health check worker running at http://localhost:${healthPort}/health`);
4741
+ }
4742
+ catch (err) {
4743
+ console.warn('[dashboard] Failed to start health worker, using main thread health check:', err);
4744
+ }
4745
+ resolve(availablePort);
4746
+ });
4747
+ server.on('error', (err) => {
4748
+ console.error('Server error:', err);
4749
+ reject(err);
4750
+ });
4751
+ });
4752
+ }
4753
+ //# sourceMappingURL=server.js.map