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