agent-relay 1.3.0 → 1.3.2

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 (240) hide show
  1. package/.trajectories/active/traj_3yx9dy148mge.json +42 -0
  2. package/.trajectories/completed/2026-01/traj_1g7yx6qtg4ai.json +49 -0
  3. package/.trajectories/completed/2026-01/traj_1g7yx6qtg4ai.md +31 -0
  4. package/.trajectories/completed/2026-01/traj_4qwd4zmhfwp4.json +49 -0
  5. package/.trajectories/completed/2026-01/traj_4qwd4zmhfwp4.md +31 -0
  6. package/.trajectories/completed/2026-01/traj_6unwwmgyj5sq.json +109 -0
  7. package/.trajectories/completed/2026-01/traj_a0tqx8biw9c4.json +49 -0
  8. package/.trajectories/completed/2026-01/traj_a0tqx8biw9c4.md +31 -0
  9. package/.trajectories/completed/2026-01/traj_ax8uungxz2qh.json +66 -0
  10. package/.trajectories/completed/2026-01/traj_ax8uungxz2qh.md +36 -0
  11. package/.trajectories/completed/2026-01/traj_c9izbh2snpzf.json +49 -0
  12. package/.trajectories/completed/2026-01/traj_c9izbh2snpzf.md +31 -0
  13. package/.trajectories/completed/2026-01/traj_cpn70dw066nt.json +65 -0
  14. package/.trajectories/completed/2026-01/traj_cpn70dw066nt.md +37 -0
  15. package/.trajectories/completed/2026-01/traj_erglv2f8t9eh.json +36 -0
  16. package/.trajectories/completed/2026-01/traj_erglv2f8t9eh.md +21 -0
  17. package/.trajectories/completed/2026-01/traj_he75f24d1xfm.json +101 -0
  18. package/.trajectories/completed/2026-01/traj_he75f24d1xfm.md +52 -0
  19. package/.trajectories/completed/2026-01/traj_lgtodco7dp1n.json +61 -0
  20. package/.trajectories/completed/2026-01/traj_lgtodco7dp1n.md +36 -0
  21. package/.trajectories/completed/2026-01/traj_oszg9flv74pk.json +73 -0
  22. package/.trajectories/completed/2026-01/traj_oszg9flv74pk.md +41 -0
  23. package/.trajectories/completed/2026-01/traj_pulomd3y8cvj.json +77 -0
  24. package/.trajectories/completed/2026-01/traj_pulomd3y8cvj.md +42 -0
  25. package/.trajectories/completed/2026-01/traj_rsavt0jipi3c.json +109 -0
  26. package/.trajectories/completed/2026-01/traj_rsavt0jipi3c.md +56 -0
  27. package/.trajectories/completed/2026-01/traj_x721m1j9rzup.json +113 -0
  28. package/.trajectories/completed/2026-01/traj_x721m1j9rzup.md +57 -0
  29. package/.trajectories/completed/2026-01/traj_xjqvmep5ed3h.json +61 -0
  30. package/.trajectories/completed/2026-01/traj_xjqvmep5ed3h.md +36 -0
  31. package/.trajectories/completed/2026-01/traj_y7n6hfbf7dmg.json +49 -0
  32. package/.trajectories/completed/2026-01/traj_y7n6hfbf7dmg.md +31 -0
  33. package/.trajectories/completed/2026-01/traj_yvfkwnkdiso2.json +49 -0
  34. package/.trajectories/completed/2026-01/traj_yvfkwnkdiso2.md +31 -0
  35. package/.trajectories/index.json +140 -1
  36. package/TRAIL_GIT_AUTH_FIX.md +113 -0
  37. package/deploy/workspace/codex.config.toml +1 -1
  38. package/deploy/workspace/entrypoint.sh +20 -79
  39. package/deploy/workspace/gh-relay +156 -0
  40. package/deploy/workspace/git-credential-relay +5 -1
  41. package/dist/bridge/multi-project-client.js +13 -10
  42. package/dist/bridge/spawner.d.ts +2 -0
  43. package/dist/bridge/spawner.js +19 -1
  44. package/dist/bridge/types.d.ts +2 -0
  45. package/dist/cli/index.d.ts +1 -1
  46. package/dist/cli/index.js +115 -69
  47. package/dist/cloud/api/admin.js +16 -3
  48. package/dist/cloud/api/codex-auth-helper.js +28 -8
  49. package/dist/cloud/api/consensus.d.ts +13 -0
  50. package/dist/cloud/api/consensus.js +259 -0
  51. package/dist/cloud/api/daemons.js +205 -1
  52. package/dist/cloud/api/git.js +37 -7
  53. package/dist/cloud/api/onboarding.js +4 -1
  54. package/dist/cloud/api/provider-env.d.ts +5 -0
  55. package/dist/cloud/api/provider-env.js +27 -0
  56. package/dist/cloud/api/providers.js +2 -0
  57. package/dist/cloud/api/test-helpers.js +130 -0
  58. package/dist/cloud/api/workspaces.js +38 -3
  59. package/dist/cloud/db/bulk-ingest.d.ts +88 -0
  60. package/dist/cloud/db/bulk-ingest.js +268 -0
  61. package/dist/cloud/db/drizzle.d.ts +33 -0
  62. package/dist/cloud/db/drizzle.js +174 -2
  63. package/dist/cloud/db/index.d.ts +24 -5
  64. package/dist/cloud/db/index.js +19 -4
  65. package/dist/cloud/db/schema.d.ts +397 -3
  66. package/dist/cloud/db/schema.js +75 -1
  67. package/dist/cloud/provisioner/index.d.ts +8 -0
  68. package/dist/cloud/provisioner/index.js +256 -50
  69. package/dist/cloud/server.js +47 -3
  70. package/dist/cloud/services/index.d.ts +1 -0
  71. package/dist/cloud/services/index.js +2 -0
  72. package/dist/cloud/services/nango.d.ts +3 -4
  73. package/dist/cloud/services/nango.js +11 -33
  74. package/dist/cloud/services/workspace-keepalive.d.ts +76 -0
  75. package/dist/cloud/services/workspace-keepalive.js +234 -0
  76. package/dist/config/relay-config.d.ts +23 -0
  77. package/dist/config/relay-config.js +23 -0
  78. package/dist/daemon/agent-manager.d.ts +20 -1
  79. package/dist/daemon/agent-manager.js +47 -0
  80. package/dist/daemon/agent-registry.js +4 -4
  81. package/dist/daemon/agent-signing.d.ts +158 -0
  82. package/dist/daemon/agent-signing.js +523 -0
  83. package/dist/daemon/api.js +18 -1
  84. package/dist/daemon/cli-auth.d.ts +4 -1
  85. package/dist/daemon/cli-auth.js +55 -11
  86. package/dist/daemon/cloud-sync.d.ts +47 -1
  87. package/dist/daemon/cloud-sync.js +152 -3
  88. package/dist/daemon/connection.d.ts +28 -0
  89. package/dist/daemon/connection.js +98 -15
  90. package/dist/daemon/consensus-integration.d.ts +167 -0
  91. package/dist/daemon/consensus-integration.js +371 -0
  92. package/dist/daemon/consensus.d.ts +271 -0
  93. package/dist/daemon/consensus.js +632 -0
  94. package/dist/daemon/delivery-tracker.d.ts +34 -0
  95. package/dist/daemon/delivery-tracker.js +104 -0
  96. package/dist/daemon/enhanced-features.d.ts +118 -0
  97. package/dist/daemon/enhanced-features.js +178 -0
  98. package/dist/daemon/index.d.ts +4 -0
  99. package/dist/daemon/index.js +5 -0
  100. package/dist/daemon/rate-limiter.d.ts +68 -0
  101. package/dist/daemon/rate-limiter.js +130 -0
  102. package/dist/daemon/router.d.ts +18 -11
  103. package/dist/daemon/router.js +55 -111
  104. package/dist/daemon/server.d.ts +13 -1
  105. package/dist/daemon/server.js +71 -9
  106. package/dist/daemon/sync-queue.d.ts +116 -0
  107. package/dist/daemon/sync-queue.js +361 -0
  108. package/dist/health-worker-manager.d.ts +62 -0
  109. package/dist/health-worker-manager.js +144 -0
  110. package/dist/health-worker.d.ts +9 -0
  111. package/dist/health-worker.js +79 -0
  112. package/dist/index.d.ts +2 -1
  113. package/dist/index.js +5 -1
  114. package/dist/memory/context-compaction.d.ts +156 -0
  115. package/dist/memory/context-compaction.js +453 -0
  116. package/dist/memory/index.d.ts +1 -0
  117. package/dist/memory/index.js +1 -0
  118. package/dist/protocol/channels.js +4 -4
  119. package/dist/protocol/framing.d.ts +72 -10
  120. package/dist/protocol/framing.js +194 -25
  121. package/dist/storage/adapter.d.ts +8 -1
  122. package/dist/storage/adapter.js +11 -0
  123. package/dist/storage/batched-sqlite-adapter.d.ts +71 -0
  124. package/dist/storage/batched-sqlite-adapter.js +183 -0
  125. package/dist/storage/dead-letter-queue.d.ts +196 -0
  126. package/dist/storage/dead-letter-queue.js +427 -0
  127. package/dist/storage/dlq-adapter.d.ts +195 -0
  128. package/dist/storage/dlq-adapter.js +664 -0
  129. package/dist/trajectory/config.d.ts +32 -14
  130. package/dist/trajectory/config.js +38 -16
  131. package/dist/trajectory/integration.js +217 -64
  132. package/dist/utils/git-remote.d.ts +47 -0
  133. package/dist/utils/git-remote.js +125 -0
  134. package/dist/utils/id-generator.d.ts +35 -0
  135. package/dist/utils/id-generator.js +60 -0
  136. package/dist/utils/index.d.ts +1 -0
  137. package/dist/utils/index.js +1 -0
  138. package/dist/utils/precompiled-patterns.d.ts +110 -0
  139. package/dist/utils/precompiled-patterns.js +322 -0
  140. package/dist/wrapper/auth-detection.js +1 -1
  141. package/dist/wrapper/base-wrapper.d.ts +36 -0
  142. package/dist/wrapper/base-wrapper.js +48 -2
  143. package/dist/wrapper/client.d.ts +14 -4
  144. package/dist/wrapper/client.js +84 -31
  145. package/dist/wrapper/idle-detector.d.ts +102 -0
  146. package/dist/wrapper/idle-detector.js +279 -0
  147. package/dist/wrapper/parser.d.ts +4 -0
  148. package/dist/wrapper/parser.js +19 -1
  149. package/dist/wrapper/pty-wrapper.d.ts +7 -1
  150. package/dist/wrapper/pty-wrapper.js +51 -27
  151. package/dist/wrapper/tmux-wrapper.d.ts +12 -1
  152. package/dist/wrapper/tmux-wrapper.js +65 -17
  153. package/package.json +5 -5
  154. package/scripts/run-migrations.js +43 -0
  155. package/scripts/verify-schema.js +134 -0
  156. package/tests/benchmarks/protocol.bench.ts +310 -0
  157. package/dist/dashboard/out/404.html +0 -1
  158. package/dist/dashboard/out/_next/static/T1tgCqVWHFIkV7ClEtzD7/_buildManifest.js +0 -1
  159. package/dist/dashboard/out/_next/static/T1tgCqVWHFIkV7ClEtzD7/_ssgManifest.js +0 -1
  160. package/dist/dashboard/out/_next/static/chunks/116-2502180def231162.js +0 -1
  161. package/dist/dashboard/out/_next/static/chunks/117-f7b8ab0809342e77.js +0 -2
  162. package/dist/dashboard/out/_next/static/chunks/282-980c2eb8fff20123.js +0 -1
  163. package/dist/dashboard/out/_next/static/chunks/532-bace199897eeab37.js +0 -9
  164. package/dist/dashboard/out/_next/static/chunks/648-5cc6e1921389a58a.js +0 -1
  165. package/dist/dashboard/out/_next/static/chunks/766-b54f0853794b78c3.js +0 -1
  166. package/dist/dashboard/out/_next/static/chunks/83-b51836037078006c.js +0 -1
  167. package/dist/dashboard/out/_next/static/chunks/891-6cd50de1224f70bb.js +0 -1
  168. package/dist/dashboard/out/_next/static/chunks/899-bb19a9b3d9b39ea6.js +0 -1
  169. package/dist/dashboard/out/_next/static/chunks/app/_not-found/page-53b8a69f76db17d0.js +0 -1
  170. package/dist/dashboard/out/_next/static/chunks/app/app/onboarding/page-8939b0fc700f7eca.js +0 -1
  171. package/dist/dashboard/out/_next/static/chunks/app/app/page-5af1b6b439858aa6.js +0 -1
  172. package/dist/dashboard/out/_next/static/chunks/app/connect-repos/page-f45ecbc3e06134fc.js +0 -1
  173. package/dist/dashboard/out/_next/static/chunks/app/history/page-8c8bed33beb2bf1c.js +0 -1
  174. package/dist/dashboard/out/_next/static/chunks/app/layout-2433bb48965f4333.js +0 -1
  175. package/dist/dashboard/out/_next/static/chunks/app/login/page-16f3b49e55b1e0ed.js +0 -1
  176. package/dist/dashboard/out/_next/static/chunks/app/metrics/page-ac39dc0cc3c26fa7.js +0 -1
  177. package/dist/dashboard/out/_next/static/chunks/app/page-4a5938c18a11a654.js +0 -1
  178. package/dist/dashboard/out/_next/static/chunks/app/pricing/page-982a7000fee44014.js +0 -1
  179. package/dist/dashboard/out/_next/static/chunks/app/providers/page-ac3a6ac433fd6001.js +0 -1
  180. package/dist/dashboard/out/_next/static/chunks/app/providers/setup/[provider]/page-09f9caae98a18c09.js +0 -1
  181. package/dist/dashboard/out/_next/static/chunks/app/signup/page-547dd0ca55ecd0ba.js +0 -1
  182. package/dist/dashboard/out/_next/static/chunks/e868780c-48e5f147c90a3a41.js +0 -18
  183. package/dist/dashboard/out/_next/static/chunks/fd9d1056-609918ca7b6280bb.js +0 -1
  184. package/dist/dashboard/out/_next/static/chunks/framework-f66176bb897dc684.js +0 -1
  185. package/dist/dashboard/out/_next/static/chunks/main-2ee6beb2ae96d210.js +0 -1
  186. package/dist/dashboard/out/_next/static/chunks/main-app-5d692157a8eb1fd9.js +0 -1
  187. package/dist/dashboard/out/_next/static/chunks/pages/_app-72b849fbd24ac258.js +0 -1
  188. package/dist/dashboard/out/_next/static/chunks/pages/_error-7ba65e1336b92748.js +0 -1
  189. package/dist/dashboard/out/_next/static/chunks/polyfills-42372ed130431b0a.js +0 -1
  190. package/dist/dashboard/out/_next/static/chunks/webpack-1cdd8ed57114d5e1.js +0 -1
  191. package/dist/dashboard/out/_next/static/css/85d2af9c7ac74d62.css +0 -1
  192. package/dist/dashboard/out/_next/static/css/fe4b28883eeff359.css +0 -1
  193. package/dist/dashboard/out/alt-logos/agent-relay-logo-128.png +0 -0
  194. package/dist/dashboard/out/alt-logos/agent-relay-logo-256.png +0 -0
  195. package/dist/dashboard/out/alt-logos/agent-relay-logo-32.png +0 -0
  196. package/dist/dashboard/out/alt-logos/agent-relay-logo-512.png +0 -0
  197. package/dist/dashboard/out/alt-logos/agent-relay-logo-64.png +0 -0
  198. package/dist/dashboard/out/alt-logos/agent-relay-logo.svg +0 -45
  199. package/dist/dashboard/out/alt-logos/logo.svg +0 -38
  200. package/dist/dashboard/out/alt-logos/monogram-logo-128.png +0 -0
  201. package/dist/dashboard/out/alt-logos/monogram-logo-256.png +0 -0
  202. package/dist/dashboard/out/alt-logos/monogram-logo-32.png +0 -0
  203. package/dist/dashboard/out/alt-logos/monogram-logo-512.png +0 -0
  204. package/dist/dashboard/out/alt-logos/monogram-logo-64.png +0 -0
  205. package/dist/dashboard/out/alt-logos/monogram-logo.svg +0 -38
  206. package/dist/dashboard/out/app/onboarding.html +0 -1
  207. package/dist/dashboard/out/app/onboarding.txt +0 -7
  208. package/dist/dashboard/out/app.html +0 -1
  209. package/dist/dashboard/out/app.txt +0 -7
  210. package/dist/dashboard/out/apple-icon.png +0 -0
  211. package/dist/dashboard/out/connect-repos.html +0 -1
  212. package/dist/dashboard/out/connect-repos.txt +0 -7
  213. package/dist/dashboard/out/history.html +0 -1
  214. package/dist/dashboard/out/history.txt +0 -7
  215. package/dist/dashboard/out/index.html +0 -1
  216. package/dist/dashboard/out/index.txt +0 -7
  217. package/dist/dashboard/out/login.html +0 -6
  218. package/dist/dashboard/out/login.txt +0 -7
  219. package/dist/dashboard/out/metrics.html +0 -1
  220. package/dist/dashboard/out/metrics.txt +0 -7
  221. package/dist/dashboard/out/pricing.html +0 -13
  222. package/dist/dashboard/out/pricing.txt +0 -7
  223. package/dist/dashboard/out/providers/setup/claude.html +0 -1
  224. package/dist/dashboard/out/providers/setup/claude.txt +0 -8
  225. package/dist/dashboard/out/providers/setup/codex.html +0 -1
  226. package/dist/dashboard/out/providers/setup/codex.txt +0 -8
  227. package/dist/dashboard/out/providers.html +0 -1
  228. package/dist/dashboard/out/providers.txt +0 -7
  229. package/dist/dashboard/out/signup.html +0 -6
  230. package/dist/dashboard/out/signup.txt +0 -7
  231. package/dist/dashboard-server/metrics.d.ts +0 -105
  232. package/dist/dashboard-server/metrics.js +0 -193
  233. package/dist/dashboard-server/needs-attention.d.ts +0 -24
  234. package/dist/dashboard-server/needs-attention.js +0 -78
  235. package/dist/dashboard-server/server.d.ts +0 -15
  236. package/dist/dashboard-server/server.js +0 -3776
  237. package/dist/dashboard-server/start.d.ts +0 -6
  238. package/dist/dashboard-server/start.js +0 -13
  239. package/dist/dashboard-server/user-bridge.d.ts +0 -103
  240. package/dist/dashboard-server/user-bridge.js +0 -189
@@ -1,3776 +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
- /**
23
- * Initialize cloud persistence for session tracking.
24
- *
25
- * Activation modes:
26
- * 1. Local dev: Set RELAY_CLOUD_ENABLED=true and DATABASE_URL
27
- * 2. Cloud deployment: Plan-based - user must have Pro+ subscription
28
- * (enforced at cloud API level when linking daemon or enabling workspace)
29
- *
30
- * Session persistence (Pro+ feature) enables:
31
- * - [[SUMMARY]] blocks saved to PostgreSQL
32
- * - [[SESSION_END]] markers for session tracking
33
- * - Session recovery and agent handoff
34
- *
35
- * @see canUseSessionPersistence in services/planLimits.ts
36
- */
37
- async function initCloudPersistence(workspaceId) {
38
- // Local dev mode: simple env var check
39
- // Cloud mode: plan check happens at API level (daemon linking, workspace config)
40
- if (process.env.RELAY_CLOUD_ENABLED !== 'true') {
41
- return null;
42
- }
43
- try {
44
- // Dynamic import to avoid loading cloud dependencies unless enabled
45
- const { getDb } = await import('../cloud/db/drizzle.js');
46
- const { agentSessions, agentSummaries } = await import('../cloud/db/schema.js');
47
- const { eq } = await import('drizzle-orm');
48
- const db = getDb();
49
- console.log('[dashboard] Cloud persistence enabled');
50
- // Track active sessions per agent with timestamps for TTL cleanup
51
- const SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
52
- const MAX_SESSIONS = 10000;
53
- const agentSessionIds = new Map();
54
- // Track pending session creation to prevent race conditions
55
- const pendingSessionCreation = new Map();
56
- // Periodic cleanup of stale sessions (every 5 minutes)
57
- const cleanupInterval = setInterval(() => {
58
- const now = Date.now();
59
- let evicted = 0;
60
- for (const [name, { lastActivity }] of agentSessionIds.entries()) {
61
- if (now - lastActivity > SESSION_TTL_MS) {
62
- agentSessionIds.delete(name);
63
- evicted++;
64
- }
65
- }
66
- if (evicted > 0) {
67
- console.log(`[cloud] Evicted ${evicted} stale session entries`);
68
- }
69
- }, 5 * 60 * 1000);
70
- // Don't keep process alive just for cleanup
71
- cleanupInterval.unref();
72
- // Helper to get or create session with race protection
73
- const getOrCreateSession = async (agentName) => {
74
- // Check cache first
75
- const cached = agentSessionIds.get(agentName);
76
- if (cached) {
77
- return cached.id;
78
- }
79
- // Check if creation is already in progress
80
- const pending = pendingSessionCreation.get(agentName);
81
- if (pending) {
82
- return pending;
83
- }
84
- // Create session with mutex
85
- const creationPromise = (async () => {
86
- try {
87
- // Double-check cache after acquiring "lock"
88
- const rechecked = agentSessionIds.get(agentName);
89
- if (rechecked) {
90
- return rechecked.id;
91
- }
92
- // Enforce max size - evict oldest if needed
93
- if (agentSessionIds.size >= MAX_SESSIONS) {
94
- let oldest = null;
95
- for (const [name, { lastActivity }] of agentSessionIds.entries()) {
96
- if (!oldest || lastActivity < oldest.time) {
97
- oldest = { name, time: lastActivity };
98
- }
99
- }
100
- if (oldest) {
101
- agentSessionIds.delete(oldest.name);
102
- console.log(`[cloud] Evicted oldest session for ${oldest.name} (max sessions reached)`);
103
- }
104
- }
105
- // Create a new session with null safety
106
- const result = await db.insert(agentSessions).values({
107
- workspaceId,
108
- agentName,
109
- status: 'active',
110
- startedAt: new Date(),
111
- }).returning();
112
- const session = result[0];
113
- if (!session) {
114
- throw new Error(`Failed to create session for agent ${agentName}`);
115
- }
116
- // Update cache
117
- agentSessionIds.set(agentName, { id: session.id, lastActivity: Date.now() });
118
- return session.id;
119
- }
120
- finally {
121
- pendingSessionCreation.delete(agentName);
122
- }
123
- })();
124
- pendingSessionCreation.set(agentName, creationPromise);
125
- return creationPromise;
126
- };
127
- return {
128
- onSummary: async (agentName, event) => {
129
- try {
130
- // Get or create session with race protection
131
- const sessionId = await getOrCreateSession(agentName);
132
- // Update activity timestamp
133
- agentSessionIds.set(agentName, { id: sessionId, lastActivity: Date.now() });
134
- // Insert summary
135
- await db.insert(agentSummaries).values({
136
- sessionId,
137
- agentName,
138
- summary: event.summary,
139
- createdAt: new Date(),
140
- });
141
- console.log(`[cloud] Saved summary for ${agentName}: ${event.summary.currentTask || 'no task'}`);
142
- }
143
- catch (err) {
144
- console.error(`[cloud] Failed to save summary for ${agentName}:`, err);
145
- }
146
- },
147
- onSessionEnd: async (agentName, event) => {
148
- try {
149
- const cached = agentSessionIds.get(agentName);
150
- if (cached) {
151
- // Update session as ended
152
- await db.update(agentSessions)
153
- .set({
154
- status: 'ended',
155
- endedAt: new Date(),
156
- endMarker: event.marker,
157
- })
158
- .where(eq(agentSessions.id, cached.id));
159
- agentSessionIds.delete(agentName);
160
- console.log(`[cloud] Session ended for ${agentName}: ${event.marker.summary || 'no summary'}`);
161
- }
162
- }
163
- catch (err) {
164
- console.error(`[cloud] Failed to end session for ${agentName}:`, err);
165
- }
166
- },
167
- destroy: () => {
168
- clearInterval(cleanupInterval);
169
- agentSessionIds.clear();
170
- pendingSessionCreation.clear();
171
- console.log('[cloud] Cloud persistence handler destroyed');
172
- },
173
- };
174
- }
175
- catch (err) {
176
- console.warn('[dashboard] Cloud persistence not available:', err);
177
- return null;
178
- }
179
- }
180
- const __filename = fileURLToPath(import.meta.url);
181
- const __dirname = path.dirname(__filename);
182
- /**
183
- * Search for files in a directory matching a query pattern.
184
- * Uses a simple recursive search with common ignore patterns.
185
- */
186
- async function searchFiles(rootDir, query, limit) {
187
- const results = [];
188
- const queryLower = query.toLowerCase();
189
- // Directories to ignore
190
- const ignoreDirs = new Set([
191
- 'node_modules', '.git', 'dist', 'build', '.next', 'coverage',
192
- '__pycache__', '.venv', 'venv', '.cache', '.turbo', '.vercel',
193
- '.nuxt', '.output', 'vendor', 'target', '.idea', '.vscode'
194
- ]);
195
- // File patterns to ignore
196
- const ignorePatterns = [
197
- /\.lock$/,
198
- /\.log$/,
199
- /\.min\.(js|css)$/,
200
- /\.map$/,
201
- /\.d\.ts$/,
202
- /\.pyc$/,
203
- ];
204
- const shouldIgnore = (name, isDir) => {
205
- if (isDir)
206
- return ignoreDirs.has(name);
207
- return ignorePatterns.some(pattern => pattern.test(name));
208
- };
209
- const matchesQuery = (filePath, fileName) => {
210
- if (!query)
211
- return true;
212
- const pathLower = filePath.toLowerCase();
213
- const nameLower = fileName.toLowerCase();
214
- // If query contains '/', match against full path
215
- if (queryLower.includes('/')) {
216
- return pathLower.includes(queryLower);
217
- }
218
- // Otherwise match against file name or path segments
219
- return nameLower.includes(queryLower) || pathLower.includes(queryLower);
220
- };
221
- const searchDir = async (dir, relativePath = '') => {
222
- if (results.length >= limit)
223
- return;
224
- try {
225
- const entries = await fs.promises.readdir(dir, { withFileTypes: true });
226
- // Sort: directories first, then alphabetically
227
- entries.sort((a, b) => {
228
- if (a.isDirectory() !== b.isDirectory()) {
229
- return a.isDirectory() ? -1 : 1;
230
- }
231
- return a.name.localeCompare(b.name);
232
- });
233
- for (const entry of entries) {
234
- if (results.length >= limit)
235
- break;
236
- const entryPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
237
- const fullPath = path.join(dir, entry.name);
238
- if (shouldIgnore(entry.name, entry.isDirectory()))
239
- continue;
240
- if (matchesQuery(entryPath, entry.name)) {
241
- results.push({
242
- path: entryPath,
243
- name: entry.name,
244
- isDirectory: entry.isDirectory(),
245
- });
246
- }
247
- // Recurse into directories
248
- if (entry.isDirectory() && results.length < limit) {
249
- await searchDir(fullPath, entryPath);
250
- }
251
- }
252
- }
253
- catch (err) {
254
- // Ignore permission errors, etc.
255
- console.warn(`[searchFiles] Error reading ${dir}:`, err);
256
- }
257
- };
258
- await searchDir(rootDir);
259
- return results;
260
- }
261
- export async function startDashboard(portOrOptions, dataDirArg, teamDirArg, dbPathArg) {
262
- // Handle overloaded signatures
263
- const options = typeof portOrOptions === 'number'
264
- ? { port: portOrOptions, dataDir: dataDirArg, teamDir: teamDirArg, dbPath: dbPathArg }
265
- : portOrOptions;
266
- const { port, dataDir, teamDir, dbPath, enableSpawner, projectRoot, tmuxSession } = options;
267
- console.log('Starting dashboard...');
268
- const storage = dbPath
269
- ? new SqliteStorageAdapter({ dbPath })
270
- : undefined;
271
- // Initialize spawner if enabled
272
- // Use detectWorkspacePath to find the actual repo directory in cloud workspaces
273
- const workspacePath = detectWorkspacePath(projectRoot || dataDir);
274
- console.log(`[dashboard] Workspace path: ${workspacePath}`);
275
- // Pass dashboard port to spawner so spawned agents can call spawn/release APIs for nested spawning
276
- const spawner = enableSpawner
277
- ? new AgentSpawner(workspacePath, tmuxSession, port)
278
- : undefined;
279
- // Initialize cloud persistence and memory monitoring if enabled (RELAY_CLOUD_ENABLED=true)
280
- if (spawner) {
281
- // Use workspace ID from env or generate from project root
282
- const workspaceId = process.env.RELAY_WORKSPACE_ID ||
283
- crypto.createHash('sha256').update(projectRoot || dataDir).digest('hex').slice(0, 36);
284
- initCloudPersistence(workspaceId).then((cloudHandler) => {
285
- if (cloudHandler) {
286
- spawner.setCloudPersistence(cloudHandler);
287
- }
288
- }).catch((err) => {
289
- console.warn('[dashboard] Failed to initialize cloud persistence:', err);
290
- });
291
- // Initialize memory monitoring for cloud deployments
292
- // Memory monitoring is enabled by default when cloud is enabled
293
- if (process.env.RELAY_CLOUD_ENABLED === 'true' || process.env.RELAY_MEMORY_MONITORING === 'true') {
294
- try {
295
- const memoryMonitor = getMemoryMonitor({
296
- checkIntervalMs: 10000, // Check every 10 seconds
297
- enableTrendAnalysis: true,
298
- enableProactiveAlerts: true,
299
- });
300
- memoryMonitor.start();
301
- console.log('[dashboard] Memory monitoring enabled');
302
- // Register existing workers with memory monitor
303
- const workers = spawner.getActiveWorkers();
304
- for (const worker of workers) {
305
- if (worker.pid) {
306
- memoryMonitor.register(worker.name, worker.pid);
307
- }
308
- }
309
- }
310
- catch (err) {
311
- console.warn('[dashboard] Failed to initialize memory monitoring:', err);
312
- }
313
- }
314
- }
315
- process.on('uncaughtException', (err) => {
316
- console.error('Uncaught Exception:', err);
317
- });
318
- process.on('unhandledRejection', (reason, promise) => {
319
- console.error('Unhandled Rejection at:', promise, 'reason:', reason);
320
- });
321
- const app = express();
322
- const server = http.createServer(app);
323
- // Use noServer mode to manually route upgrade requests
324
- // This prevents the bug where multiple WebSocketServers attached to the same
325
- // HTTP server cause conflicts - each one's upgrade handler fires and the ones
326
- // that don't match the path call abortHandshake(400), writing raw HTTP to the socket
327
- const wss = new WebSocketServer({
328
- noServer: true,
329
- perMessageDeflate: false,
330
- skipUTF8Validation: true,
331
- maxPayload: 100 * 1024 * 1024 // 100MB
332
- });
333
- const wssBridge = new WebSocketServer({
334
- noServer: true,
335
- perMessageDeflate: false,
336
- skipUTF8Validation: true,
337
- maxPayload: 100 * 1024 * 1024
338
- });
339
- const wssLogs = new WebSocketServer({
340
- noServer: true,
341
- perMessageDeflate: false,
342
- skipUTF8Validation: true,
343
- maxPayload: 100 * 1024 * 1024
344
- });
345
- const wssPresence = new WebSocketServer({
346
- noServer: true,
347
- perMessageDeflate: false,
348
- skipUTF8Validation: true,
349
- maxPayload: 1024 * 1024 // 1MB - presence messages are small
350
- });
351
- // Track log subscriptions: agentName -> Set of WebSocket clients
352
- const logSubscriptions = new Map();
353
- // Track alive status for ping/pong keepalive on main dashboard connections
354
- // This prevents TCP/proxy timeouts from killing idle workspace connections
355
- const mainClientAlive = new WeakMap();
356
- // Track alive status for ping/pong keepalive on bridge connections
357
- const bridgeClientAlive = new WeakMap();
358
- // Ping interval for main dashboard WebSocket connections (30 seconds)
359
- // Aligns with heartbeat timeout (5s heartbeat * 6 multiplier = 30s)
360
- const MAIN_PING_INTERVAL_MS = 30000;
361
- const mainPingInterval = setInterval(() => {
362
- wss.clients.forEach((ws) => {
363
- if (mainClientAlive.get(ws) === false) {
364
- // Client didn't respond to last ping - close gracefully
365
- console.log('[dashboard] Main WebSocket client unresponsive, closing gracefully');
366
- ws.close(1000, 'unresponsive');
367
- return;
368
- }
369
- // Mark as not alive until we get a pong
370
- mainClientAlive.set(ws, false);
371
- ws.ping();
372
- });
373
- }, MAIN_PING_INTERVAL_MS);
374
- // Ping interval for bridge WebSocket connections (30 seconds)
375
- const BRIDGE_PING_INTERVAL_MS = 30000;
376
- const bridgePingInterval = setInterval(() => {
377
- wssBridge.clients.forEach((ws) => {
378
- if (bridgeClientAlive.get(ws) === false) {
379
- console.log('[dashboard] Bridge WebSocket client unresponsive, closing gracefully');
380
- ws.close(1000, 'unresponsive');
381
- return;
382
- }
383
- bridgeClientAlive.set(ws, false);
384
- ws.ping();
385
- });
386
- }, BRIDGE_PING_INTERVAL_MS);
387
- // Clean up ping intervals on server close
388
- wss.on('close', () => {
389
- clearInterval(mainPingInterval);
390
- });
391
- wssBridge.on('close', () => {
392
- clearInterval(bridgePingInterval);
393
- });
394
- const onlineUsers = new Map();
395
- // Validation helpers for presence
396
- const isValidUsername = (username) => {
397
- if (typeof username !== 'string')
398
- return false;
399
- // Username should be 1-39 chars, alphanumeric with hyphens (GitHub username rules)
400
- return /^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,37}[a-zA-Z0-9])?$/.test(username);
401
- };
402
- const isValidAvatarUrl = (url) => {
403
- if (url === undefined || url === null)
404
- return true;
405
- if (typeof url !== 'string')
406
- return false;
407
- // Must be a valid HTTPS URL from GitHub or similar known providers
408
- try {
409
- const parsed = new URL(url);
410
- return parsed.protocol === 'https:' &&
411
- (parsed.hostname === 'avatars.githubusercontent.com' ||
412
- parsed.hostname === 'github.com' ||
413
- parsed.hostname.endsWith('.githubusercontent.com'));
414
- }
415
- catch {
416
- return false;
417
- }
418
- };
419
- // Manually handle upgrade requests and route to correct WebSocketServer
420
- server.on('upgrade', (request, socket, head) => {
421
- const pathname = new URL(request.url || '', `http://${request.headers.host}`).pathname;
422
- if (pathname === '/ws') {
423
- wss.handleUpgrade(request, socket, head, (ws) => {
424
- wss.emit('connection', ws, request);
425
- });
426
- }
427
- else if (pathname === '/ws/bridge') {
428
- wssBridge.handleUpgrade(request, socket, head, (ws) => {
429
- wssBridge.emit('connection', ws, request);
430
- });
431
- }
432
- else if (pathname === '/ws/logs' || pathname.startsWith('/ws/logs/')) {
433
- wssLogs.handleUpgrade(request, socket, head, (ws) => {
434
- wssLogs.emit('connection', ws, request);
435
- });
436
- }
437
- else if (pathname === '/ws/presence') {
438
- wssPresence.handleUpgrade(request, socket, head, (ws) => {
439
- wssPresence.emit('connection', ws, request);
440
- });
441
- }
442
- else {
443
- // Unknown path - destroy socket
444
- socket.destroy();
445
- }
446
- });
447
- // Server-level error handlers
448
- wss.on('error', (err) => {
449
- console.error('[dashboard] WebSocket server error:', err);
450
- });
451
- wssBridge.on('error', (err) => {
452
- console.error('[dashboard] Bridge WebSocket server error:', err);
453
- });
454
- wssLogs.on('error', (err) => {
455
- console.error('[dashboard] Logs WebSocket server error:', err);
456
- });
457
- wssPresence.on('error', (err) => {
458
- console.error('[dashboard] Presence WebSocket server error:', err);
459
- });
460
- if (storage) {
461
- await storage.init();
462
- }
463
- // Increase JSON body limit for base64 image uploads (10MB)
464
- app.use(express.json({ limit: '10mb' }));
465
- // Create attachments directory in user's home directory (~/.relay/attachments)
466
- // This keeps attachments out of source control while still accessible to agents
467
- const attachmentsDir = path.join(os.homedir(), '.relay', 'attachments');
468
- if (!fs.existsSync(attachmentsDir)) {
469
- fs.mkdirSync(attachmentsDir, { recursive: true });
470
- }
471
- // Also keep uploads dir for backwards compatibility (URL-based serving)
472
- const uploadsDir = path.join(dataDir, 'uploads');
473
- if (!fs.existsSync(uploadsDir)) {
474
- fs.mkdirSync(uploadsDir, { recursive: true });
475
- }
476
- // Auto-evict old attachments (older than 7 days)
477
- const ATTACHMENT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
478
- const evictOldAttachments = async () => {
479
- try {
480
- const files = await fs.promises.readdir(attachmentsDir);
481
- const now = Date.now();
482
- let evictedCount = 0;
483
- for (const file of files) {
484
- const filePath = path.join(attachmentsDir, file);
485
- try {
486
- const stat = await fs.promises.stat(filePath);
487
- if (stat.isFile() && (now - stat.mtimeMs) > ATTACHMENT_MAX_AGE_MS) {
488
- await fs.promises.unlink(filePath);
489
- evictedCount++;
490
- }
491
- }
492
- catch (_err) {
493
- // Ignore errors for individual files (may have been deleted)
494
- }
495
- }
496
- if (evictedCount > 0) {
497
- console.log(`[dashboard] Evicted ${evictedCount} old attachment(s)`);
498
- }
499
- }
500
- catch (err) {
501
- console.error('[dashboard] Failed to evict old attachments:', err);
502
- }
503
- };
504
- // Run eviction on startup and every hour
505
- evictOldAttachments();
506
- const evictionInterval = setInterval(evictOldAttachments, 60 * 60 * 1000); // 1 hour
507
- // Clean up interval on process exit
508
- process.on('beforeExit', () => {
509
- clearInterval(evictionInterval);
510
- });
511
- // Serve uploaded files statically
512
- app.use('/uploads', express.static(uploadsDir));
513
- // Serve attachments from ~/.relay/attachments
514
- app.use('/attachments', express.static(attachmentsDir));
515
- // In-memory attachment registry (for current session)
516
- // Attachments are also stored on disk, so this is just for quick lookups
517
- const attachmentRegistry = new Map();
518
- // Serve dashboard static files at root (built with `next build` in src/dashboard)
519
- // __dirname is dist/dashboard-server, dashboard is at ../dashboard/out (relative to dist)
520
- // But in source it's at ../dashboard/out (relative to src/dashboard-server)
521
- const dashboardDistDir = path.join(__dirname, '..', 'dashboard', 'out');
522
- const dashboardSourceDir = path.join(__dirname, '..', '..', 'src', 'dashboard', 'out');
523
- // Check which path exists (dist or src)
524
- const dashboardDir = fs.existsSync(dashboardDistDir) ? dashboardDistDir : dashboardSourceDir;
525
- if (fs.existsSync(dashboardDir)) {
526
- console.log(`[dashboard] Serving from: ${dashboardDir}`);
527
- // Serve Next.js static export with .html extension handling
528
- app.use(express.static(dashboardDir, { extensions: ['html'] }));
529
- // Fallback for Next.js pages (e.g., /metrics -> /metrics.html)
530
- app.get('/metrics', (req, res) => {
531
- res.sendFile(path.join(dashboardDir, 'metrics.html'));
532
- });
533
- }
534
- else {
535
- console.error('[dashboard] Dashboard not found at:', dashboardDistDir, 'or', dashboardSourceDir);
536
- }
537
- // Relay clients for sending messages from dashboard
538
- // Map of senderName -> RelayClient for per-user connections
539
- const socketPath = path.join(dataDir, 'relay.sock');
540
- const relayClients = new Map();
541
- // Track pending client connections to prevent race conditions
542
- const pendingConnections = new Map();
543
- // Get or create a relay client for a specific sender
544
- const getRelayClient = async (senderName = 'Dashboard') => {
545
- // Check if we already have a connected client for this sender
546
- const existing = relayClients.get(senderName);
547
- if (existing && existing.state === 'READY') {
548
- return existing;
549
- }
550
- // Check if there's already a pending connection for this sender
551
- const pending = pendingConnections.get(senderName);
552
- if (pending) {
553
- return pending;
554
- }
555
- // Only attempt connection if socket exists (daemon is running)
556
- if (!fs.existsSync(socketPath)) {
557
- console.log('[dashboard] Relay socket not found, messaging disabled');
558
- return undefined;
559
- }
560
- // Create connection promise to prevent race conditions
561
- const connectionPromise = (async () => {
562
- // Create new client for this sender
563
- const client = new RelayClient({
564
- socketPath,
565
- agentName: senderName,
566
- cli: 'dashboard',
567
- reconnect: true,
568
- maxReconnectAttempts: 5,
569
- });
570
- client.onError = (err) => {
571
- console.error(`[dashboard] Relay client error for ${senderName}:`, err.message);
572
- };
573
- client.onStateChange = (state) => {
574
- console.log(`[dashboard] Relay client for ${senderName} state: ${state}`);
575
- // Clean up disconnected clients
576
- if (state === 'DISCONNECTED') {
577
- relayClients.delete(senderName);
578
- }
579
- };
580
- try {
581
- await client.connect();
582
- relayClients.set(senderName, client);
583
- console.log(`[dashboard] Connected to relay daemon as ${senderName}`);
584
- return client;
585
- }
586
- catch (err) {
587
- console.error(`[dashboard] Failed to connect to relay daemon as ${senderName}:`, err);
588
- return undefined;
589
- }
590
- finally {
591
- // Clean up pending connection
592
- pendingConnections.delete(senderName);
593
- }
594
- })();
595
- // Store the pending connection
596
- pendingConnections.set(senderName, connectionPromise);
597
- return connectionPromise;
598
- };
599
- // Start default relay client connection (non-blocking)
600
- getRelayClient('Dashboard').catch(() => { });
601
- // User bridge for human-to-human and human-to-agent messaging
602
- const userBridge = new UserBridge({
603
- socketPath,
604
- createRelayClient: async (options) => {
605
- const client = new RelayClient({
606
- socketPath: options.socketPath,
607
- agentName: options.agentName,
608
- entityType: options.entityType,
609
- cli: 'dashboard',
610
- reconnect: true,
611
- maxReconnectAttempts: 5,
612
- });
613
- client.onError = (err) => {
614
- console.error(`[user-bridge] Relay client error for ${options.agentName}:`, err.message);
615
- };
616
- await client.connect();
617
- return client;
618
- },
619
- });
620
- // Bridge client for cross-project messaging
621
- let bridgeClient;
622
- let bridgeClientConnecting = false;
623
- const connectBridgeClient = async () => {
624
- if (bridgeClient || bridgeClientConnecting)
625
- return;
626
- // Check if bridge-state.json exists and has projects
627
- const bridgeStatePath = path.join(dataDir, 'bridge-state.json');
628
- if (!fs.existsSync(bridgeStatePath)) {
629
- return;
630
- }
631
- try {
632
- const bridgeState = JSON.parse(fs.readFileSync(bridgeStatePath, 'utf-8'));
633
- if (!bridgeState.connected || !bridgeState.projects?.length) {
634
- return;
635
- }
636
- bridgeClientConnecting = true;
637
- // Build project configs from bridge state
638
- const projectConfigs = bridgeState.projects.map((p) => {
639
- // Compute socket path for each project
640
- const projectHash = crypto.createHash('sha256').update(p.path).digest('hex').slice(0, 12);
641
- const projectDataDir = path.join(path.dirname(dataDir), projectHash);
642
- const socketPath = path.join(projectDataDir, 'relay.sock');
643
- return {
644
- id: p.id,
645
- path: p.path,
646
- socketPath,
647
- leadName: p.lead?.name || 'Lead',
648
- cli: 'dashboard-bridge',
649
- };
650
- });
651
- // Filter to projects with existing sockets
652
- const validConfigs = projectConfigs.filter((p) => fs.existsSync(p.socketPath));
653
- if (validConfigs.length === 0) {
654
- bridgeClientConnecting = false;
655
- return;
656
- }
657
- bridgeClient = new MultiProjectClient(validConfigs, {
658
- agentName: '__DashboardBridge__', // Unique name to avoid conflict with CLI bridge
659
- reconnect: true,
660
- });
661
- bridgeClient.onProjectStateChange = (projectId, connected) => {
662
- console.log(`[dashboard-bridge] Project ${projectId} ${connected ? 'connected' : 'disconnected'}`);
663
- };
664
- await bridgeClient.connect();
665
- console.log('[dashboard] Bridge client connected to', validConfigs.length, 'project(s)');
666
- bridgeClientConnecting = false;
667
- }
668
- catch (err) {
669
- console.error('[dashboard] Failed to connect bridge client:', err);
670
- bridgeClient = undefined;
671
- bridgeClientConnecting = false;
672
- }
673
- };
674
- // Start bridge client connection (non-blocking)
675
- connectBridgeClient().catch(() => { });
676
- // Helper to check if an agent is online (seen within heartbeat timeout window)
677
- // Uses 30 second threshold to align with heartbeat timeout (5s * 6 multiplier)
678
- const isAgentOnline = (agentName) => {
679
- if (agentName === '*')
680
- return true; // Broadcast always allowed
681
- const agentsPath = path.join(teamDir, 'agents.json');
682
- if (!fs.existsSync(agentsPath))
683
- return false;
684
- try {
685
- const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
686
- const agent = data.agents?.find((a) => a.name === agentName);
687
- if (!agent || !agent.lastSeen)
688
- return false;
689
- const thirtySecondsAgo = Date.now() - 30 * 1000;
690
- return new Date(agent.lastSeen).getTime() > thirtySecondsAgo;
691
- }
692
- catch {
693
- return false;
694
- }
695
- };
696
- // Helper to get team members from teams.json, agents.json, and spawner's active workers
697
- const getTeamMembers = (teamName) => {
698
- const members = new Set();
699
- // Check teams.json first - this is the source of truth for team definitions
700
- const teamsConfig = loadTeamsConfig(projectRoot || dataDir);
701
- if (teamsConfig && teamsConfig.team === teamName) {
702
- for (const agent of teamsConfig.agents) {
703
- members.add(agent.name);
704
- }
705
- }
706
- // Check spawner's active workers (they have accurate team info for spawned agents)
707
- if (spawner) {
708
- const activeWorkers = spawner.getActiveWorkers();
709
- for (const worker of activeWorkers) {
710
- if (worker.team === teamName) {
711
- members.add(worker.name);
712
- }
713
- }
714
- }
715
- // Also check agents.json for persisted team info
716
- const agentsPath = path.join(teamDir, 'agents.json');
717
- if (fs.existsSync(agentsPath)) {
718
- try {
719
- const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
720
- for (const agent of (data.agents || [])) {
721
- if (agent.team === teamName) {
722
- members.add(agent.name);
723
- }
724
- }
725
- }
726
- catch {
727
- // Ignore parse errors
728
- }
729
- }
730
- return Array.from(members);
731
- };
732
- // API endpoint to send messages
733
- app.post('/api/send', async (req, res) => {
734
- const { to, message, thread, attachments: attachmentIds, from: senderName } = req.body;
735
- if (!to || !message) {
736
- return res.status(400).json({ error: 'Missing "to" or "message" field' });
737
- }
738
- // Check if this is a team mention (team:teamName)
739
- const teamMatch = to.match(/^team:(.+)$/);
740
- let targets;
741
- if (teamMatch) {
742
- const teamName = teamMatch[1];
743
- const members = getTeamMembers(teamName);
744
- if (members.length === 0) {
745
- return res.status(404).json({ error: `No agents found in team "${teamName}"` });
746
- }
747
- // Filter to only online members
748
- targets = members.filter(isAgentOnline);
749
- if (targets.length === 0) {
750
- return res.status(404).json({ error: `No online agents in team "${teamName}"` });
751
- }
752
- }
753
- else {
754
- // Fail fast if target agent is offline (except broadcasts)
755
- if (to !== '*' && !isAgentOnline(to)) {
756
- return res.status(404).json({ error: `Agent "${to}" is not online` });
757
- }
758
- targets = [to];
759
- }
760
- // Get or create relay client for this sender (defaults to 'Dashboard' for non-cloud mode)
761
- const relayClient = await getRelayClient(senderName || 'Dashboard');
762
- if (!relayClient || relayClient.state !== 'READY') {
763
- return res.status(503).json({ error: 'Relay daemon not connected' });
764
- }
765
- try {
766
- // Resolve attachments if provided
767
- let attachments;
768
- if (attachmentIds && Array.isArray(attachmentIds) && attachmentIds.length > 0) {
769
- attachments = [];
770
- for (const id of attachmentIds) {
771
- const attachment = attachmentRegistry.get(id);
772
- if (attachment) {
773
- attachments.push(attachment);
774
- }
775
- }
776
- }
777
- // Include attachments and channel context in the message data field
778
- // For broadcasts (to='*'), include channel: 'general' so replies can be routed back
779
- const isBroadcast = targets.length === 1 && targets[0] === '*';
780
- const messageData = {};
781
- if (attachments && attachments.length > 0) {
782
- messageData.attachments = attachments;
783
- }
784
- if (isBroadcast) {
785
- messageData.channel = 'general';
786
- }
787
- const hasMessageData = Object.keys(messageData).length > 0;
788
- // Send to all targets (single agent, team members, or broadcast)
789
- let allSent = true;
790
- for (const target of targets) {
791
- const sent = relayClient.sendMessage(target, message, 'message', hasMessageData ? messageData : undefined, thread);
792
- if (!sent) {
793
- allSent = false;
794
- console.error(`[dashboard] Failed to send message to ${target}`);
795
- }
796
- }
797
- if (allSent) {
798
- // Broadcast updated data to all connected clients so they see the sent message
799
- broadcastData().catch((err) => console.error('[dashboard] Failed to broadcast after send:', err));
800
- res.json({ success: true, sentTo: targets.length > 1 ? targets : targets[0] });
801
- }
802
- else {
803
- res.status(500).json({ error: 'Failed to send message to some recipients' });
804
- }
805
- }
806
- catch (err) {
807
- console.error('[dashboard] Failed to send message:', err);
808
- res.status(500).json({ error: 'Failed to send message' });
809
- }
810
- });
811
- // API endpoint to send messages via bridge (cross-project)
812
- app.post('/api/bridge/send', async (req, res) => {
813
- const { projectId, to, message } = req.body;
814
- if (!projectId || !to || !message) {
815
- return res.status(400).json({ error: 'Missing "projectId", "to", or "message" field' });
816
- }
817
- // Try to connect bridge client if not connected
818
- if (!bridgeClient) {
819
- await connectBridgeClient();
820
- if (!bridgeClient) {
821
- return res.status(503).json({ error: 'Bridge not connected. Is the bridge command running?' });
822
- }
823
- }
824
- try {
825
- const sent = bridgeClient.sendToProject(projectId, to, message);
826
- if (sent) {
827
- res.json({ success: true });
828
- }
829
- else {
830
- res.status(500).json({ error: `Failed to send message to ${projectId}:${to}` });
831
- }
832
- }
833
- catch (err) {
834
- console.error('[dashboard] Failed to send bridge message:', err);
835
- res.status(500).json({ error: 'Failed to send bridge message' });
836
- }
837
- });
838
- // API endpoint to upload attachments (images/screenshots)
839
- app.post('/api/upload', async (req, res) => {
840
- const { filename, mimeType, data } = req.body;
841
- // Validate required fields
842
- if (!filename || !mimeType || !data) {
843
- return res.status(400).json({
844
- success: false,
845
- error: 'Missing required fields: filename, mimeType, data',
846
- });
847
- }
848
- // Validate mime type (only allow images for now)
849
- const allowedTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/svg+xml'];
850
- if (!allowedTypes.includes(mimeType)) {
851
- return res.status(400).json({
852
- success: false,
853
- error: `Invalid file type. Allowed types: ${allowedTypes.join(', ')}`,
854
- });
855
- }
856
- try {
857
- // Decode base64 data
858
- const base64Data = data.replace(/^data:[^;]+;base64,/, '');
859
- const buffer = Buffer.from(base64Data, 'base64');
860
- // Generate unique ID and filename for the attachment
861
- const attachmentId = crypto.randomUUID();
862
- const timestamp = Date.now();
863
- const ext = mimeType.split('/')[1].replace('svg+xml', 'svg');
864
- // Use format: {messageId}-{timestamp}.{ext} for unique, identifiable filenames
865
- const safeFilename = `${attachmentId.substring(0, 8)}-${timestamp}.${ext}`;
866
- // Save to ~/.relay/attachments/ directory for agents to access
867
- const attachmentFilePath = path.join(attachmentsDir, safeFilename);
868
- fs.writeFileSync(attachmentFilePath, buffer);
869
- // Create attachment record with file path for agents
870
- const attachment = {
871
- id: attachmentId,
872
- filename: filename,
873
- mimeType: mimeType,
874
- size: buffer.length,
875
- url: `/attachments/${safeFilename}`,
876
- // Include absolute file path so agents can read the file directly
877
- filePath: attachmentFilePath,
878
- // Include base64 data for agents that can't access the file
879
- data: data,
880
- };
881
- // Store in registry for lookup when sending messages
882
- attachmentRegistry.set(attachmentId, attachment);
883
- console.log(`[dashboard] Uploaded attachment: ${filename} (${buffer.length} bytes) -> ${attachmentFilePath}`);
884
- res.json({
885
- success: true,
886
- attachment: {
887
- id: attachment.id,
888
- filename: attachment.filename,
889
- mimeType: attachment.mimeType,
890
- size: attachment.size,
891
- url: attachment.url,
892
- filePath: attachment.filePath,
893
- },
894
- });
895
- }
896
- catch (err) {
897
- console.error('[dashboard] Upload failed:', err);
898
- res.status(500).json({
899
- success: false,
900
- error: 'Failed to upload file',
901
- });
902
- }
903
- });
904
- // API endpoint to get attachment by ID
905
- app.get('/api/attachment/:id', (req, res) => {
906
- const { id } = req.params;
907
- const attachment = attachmentRegistry.get(id);
908
- if (!attachment) {
909
- return res.status(404).json({ error: 'Attachment not found' });
910
- }
911
- res.json({
912
- success: true,
913
- attachment: {
914
- id: attachment.id,
915
- filename: attachment.filename,
916
- mimeType: attachment.mimeType,
917
- size: attachment.size,
918
- url: attachment.url,
919
- filePath: attachment.filePath,
920
- },
921
- });
922
- });
923
- const getTeamData = () => {
924
- // Try team.json first (file-based team mode)
925
- const teamPath = path.join(teamDir, 'team.json');
926
- if (fs.existsSync(teamPath)) {
927
- try {
928
- return JSON.parse(fs.readFileSync(teamPath, 'utf-8'));
929
- }
930
- catch (e) {
931
- console.error('Failed to read team.json', e);
932
- }
933
- }
934
- // Fall back to agents.json (daemon mode - live connected agents)
935
- const agentsPath = path.join(teamDir, 'agents.json');
936
- if (fs.existsSync(agentsPath)) {
937
- try {
938
- const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
939
- // Convert agents.json format to team.json format
940
- return {
941
- agents: data.agents.map((a) => ({
942
- name: a.name,
943
- role: 'Agent',
944
- cli: a.cli ?? 'Unknown',
945
- lastSeen: a.lastSeen ?? a.connectedAt,
946
- lastActive: a.lastSeen ?? a.connectedAt,
947
- team: a.team,
948
- })),
949
- };
950
- }
951
- catch (e) {
952
- console.error('Failed to read agents.json', e);
953
- }
954
- }
955
- return null;
956
- };
957
- const parseInbox = (agentName) => {
958
- const inboxPath = path.join(dataDir, agentName, 'inbox.md');
959
- if (!fs.existsSync(inboxPath))
960
- return [];
961
- try {
962
- const content = fs.readFileSync(inboxPath, 'utf-8');
963
- const messages = [];
964
- // Split by "## Message from "
965
- const parts = content.split('## Message from ');
966
- parts.forEach((part, index) => {
967
- if (!part.trim())
968
- return;
969
- const firstLineEnd = part.indexOf('\n');
970
- if (firstLineEnd === -1)
971
- return;
972
- const header = part.substring(0, firstLineEnd).trim(); // "Sender | Timestamp" or just "Sender"
973
- const body = part.substring(firstLineEnd).trim();
974
- // Handle potential " | " in header
975
- let sender = header;
976
- let timestamp = new Date().toISOString();
977
- if (header.includes('|')) {
978
- const split = header.split('|');
979
- sender = split[0].trim();
980
- timestamp = split.slice(1).join('|').trim();
981
- }
982
- messages.push({
983
- from: sender,
984
- to: agentName,
985
- content: body,
986
- timestamp: timestamp,
987
- id: `${agentName}-${index}-${Date.now()}`
988
- });
989
- });
990
- return messages;
991
- }
992
- catch (e) {
993
- console.error(`Failed to read inbox for ${agentName}`, e);
994
- return [];
995
- }
996
- };
997
- // Helper to check if an agent name is internal/system (should be hidden from UI)
998
- // Convention: agent names starting with __ are internal (e.g., __spawner__, __DashboardBridge__)
999
- const isInternalAgent = (name) => {
1000
- return name.startsWith('__');
1001
- };
1002
- const mapStoredMessages = (rows) => rows
1003
- // Filter out messages from/to internal system agents (e.g., __spawner__)
1004
- .filter((row) => !isInternalAgent(row.from) && !isInternalAgent(row.to))
1005
- .map((row) => {
1006
- // Extract attachments and channel from the data field if present
1007
- let attachments;
1008
- let channel;
1009
- if (row.data && typeof row.data === 'object') {
1010
- if ('attachments' in row.data) {
1011
- attachments = row.data.attachments;
1012
- }
1013
- if ('channel' in row.data) {
1014
- channel = row.data.channel;
1015
- }
1016
- }
1017
- return {
1018
- from: row.from,
1019
- to: row.to,
1020
- content: row.body,
1021
- timestamp: new Date(row.ts).toISOString(),
1022
- id: row.id,
1023
- thread: row.thread,
1024
- isBroadcast: row.is_broadcast,
1025
- replyCount: row.replyCount,
1026
- status: row.status,
1027
- attachments,
1028
- channel,
1029
- };
1030
- });
1031
- const getMessages = async (agents) => {
1032
- if (storage) {
1033
- const rows = await storage.getMessages({ limit: 100, order: 'desc' });
1034
- // Dashboard expects oldest first
1035
- return mapStoredMessages(rows).reverse();
1036
- }
1037
- // Fallback to file-based inbox parsing
1038
- let allMessages = [];
1039
- agents.forEach((a) => {
1040
- const msgs = parseInbox(a.name);
1041
- allMessages = [...allMessages, ...msgs];
1042
- });
1043
- return allMessages;
1044
- };
1045
- const formatDuration = (startMs, endMs) => {
1046
- const end = endMs ?? Date.now();
1047
- const durationMs = end - startMs;
1048
- const minutes = Math.floor(durationMs / 60000);
1049
- const hours = Math.floor(minutes / 60);
1050
- if (hours > 0) {
1051
- return `${hours}h ${minutes % 60}m`;
1052
- }
1053
- return `${minutes}m`;
1054
- };
1055
- const getRecentSessions = async () => {
1056
- if (storage && storage instanceof SqliteStorageAdapter) {
1057
- const sessions = await storage.getRecentSessions(20);
1058
- return sessions.map(s => ({
1059
- id: s.id,
1060
- agentName: s.agentName,
1061
- cli: s.cli,
1062
- startedAt: new Date(s.startedAt).toISOString(),
1063
- endedAt: s.endedAt ? new Date(s.endedAt).toISOString() : undefined,
1064
- duration: formatDuration(s.startedAt, s.endedAt),
1065
- messageCount: s.messageCount,
1066
- summary: s.summary,
1067
- isActive: !s.endedAt, // Active if no end time
1068
- closedBy: s.closedBy,
1069
- }));
1070
- }
1071
- return [];
1072
- };
1073
- const getAgentSummaries = async () => {
1074
- if (storage && storage instanceof SqliteStorageAdapter) {
1075
- const summaries = await storage.getAllAgentSummaries();
1076
- return summaries.map(s => ({
1077
- agentName: s.agentName,
1078
- lastUpdated: new Date(s.lastUpdated).toISOString(),
1079
- currentTask: s.currentTask,
1080
- completedTasks: s.completedTasks,
1081
- context: s.context,
1082
- }));
1083
- }
1084
- return [];
1085
- };
1086
- const getAllData = async () => {
1087
- const team = getTeamData();
1088
- if (!team)
1089
- return { agents: [], messages: [], activity: [], sessions: [], summaries: [] };
1090
- const agentsMap = new Map();
1091
- const allMessages = await getMessages(team.agents);
1092
- // Initialize agents from config
1093
- team.agents.forEach((a) => {
1094
- agentsMap.set(a.name, {
1095
- name: a.name,
1096
- role: a.role,
1097
- cli: a.cli ?? 'Unknown',
1098
- messageCount: 0,
1099
- status: 'Idle',
1100
- lastSeen: a.lastSeen,
1101
- lastActive: a.lastActive,
1102
- needsAttention: false,
1103
- team: a.team,
1104
- });
1105
- });
1106
- // Update inbox counts if fallback mode; if storage, count messages addressed to agent
1107
- if (storage) {
1108
- for (const msg of allMessages) {
1109
- const agent = agentsMap.get(msg.to);
1110
- if (agent) {
1111
- agent.messageCount = (agent.messageCount ?? 0) + 1;
1112
- }
1113
- }
1114
- }
1115
- else {
1116
- // Sort by timestamp
1117
- allMessages.sort((a, b) => {
1118
- return new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime();
1119
- });
1120
- }
1121
- // Derive status from messages sent BY agents
1122
- // We scan all messages; if M is from A, we check if it is a STATUS message
1123
- // Note: lastActive is updated from messages, but lastSeen comes from the registry
1124
- // (heartbeat-based) and should NOT be overwritten by message timestamps
1125
- allMessages.forEach(m => {
1126
- const agent = agentsMap.get(m.from);
1127
- if (agent) {
1128
- agent.lastActive = m.timestamp;
1129
- // Don't overwrite lastSeen - it comes from registry (heartbeat/connection tracking)
1130
- if (m.content.startsWith('STATUS:')) {
1131
- agent.status = m.content.substring(7).trim(); // remove "STATUS:"
1132
- }
1133
- }
1134
- });
1135
- // Detect agents with unanswered inbound messages (needs attention)
1136
- const needsAttentionAgents = computeNeedsAttention(allMessages.map((m) => ({
1137
- from: m.from,
1138
- to: m.to,
1139
- timestamp: m.timestamp,
1140
- thread: m.thread,
1141
- isBroadcast: m.isBroadcast,
1142
- })));
1143
- needsAttentionAgents.forEach((agentName) => {
1144
- const agent = agentsMap.get(agentName);
1145
- if (agent) {
1146
- agent.needsAttention = true;
1147
- }
1148
- });
1149
- // Read processing state from daemon
1150
- const processingStatePath = path.join(teamDir, 'processing-state.json');
1151
- if (fs.existsSync(processingStatePath)) {
1152
- try {
1153
- const processingData = JSON.parse(fs.readFileSync(processingStatePath, 'utf-8'));
1154
- const processingAgents = processingData.processingAgents || {};
1155
- for (const [agentName, state] of Object.entries(processingAgents)) {
1156
- const agent = agentsMap.get(agentName);
1157
- if (agent && state && typeof state === 'object') {
1158
- agent.isProcessing = true;
1159
- agent.processingStartedAt = state.startedAt;
1160
- }
1161
- }
1162
- }
1163
- catch (_err) {
1164
- // Ignore errors reading processing state - it's optional
1165
- }
1166
- }
1167
- // Mark spawned agents with isSpawned flag and team
1168
- if (spawner) {
1169
- const activeWorkers = spawner.getActiveWorkers();
1170
- for (const worker of activeWorkers) {
1171
- const agent = agentsMap.get(worker.name);
1172
- if (agent) {
1173
- agent.isSpawned = true;
1174
- if (worker.team) {
1175
- agent.team = worker.team;
1176
- }
1177
- }
1178
- }
1179
- }
1180
- // Set team from teams.json for agents that don't have a team yet
1181
- // This ensures agents defined in teams.json are associated with their team
1182
- // even if they weren't spawned via auto-spawn
1183
- const teamsConfig = loadTeamsConfig(projectRoot || dataDir);
1184
- if (teamsConfig) {
1185
- for (const teamAgent of teamsConfig.agents) {
1186
- const agent = agentsMap.get(teamAgent.name);
1187
- if (agent && !agent.team) {
1188
- agent.team = teamsConfig.team;
1189
- }
1190
- }
1191
- }
1192
- // Fetch sessions and summaries in parallel
1193
- const [sessions, summaries] = await Promise.all([
1194
- getRecentSessions(),
1195
- getAgentSummaries(),
1196
- ]);
1197
- // Filter and separate agents from human users:
1198
- // 1. Exclude "Dashboard" (internal agent, not a real team member)
1199
- // 2. Exclude offline agents (no lastSeen or lastSeen > threshold)
1200
- // 3. Exclude agents without a known CLI (these are improperly registered or stale)
1201
- // 4. Separate human users (cli === 'dashboard') from AI agents
1202
- const now = Date.now();
1203
- // 30 seconds - aligns with heartbeat timeout (5s heartbeat * 6 multiplier = 30s)
1204
- // This ensures agents disappear quickly after they stop responding to heartbeats
1205
- const OFFLINE_THRESHOLD_MS = 30 * 1000;
1206
- // First pass: filter out invalid/offline entries
1207
- const validEntries = Array.from(agentsMap.values())
1208
- .filter(agent => {
1209
- // Exclude Dashboard
1210
- if (agent.name === 'Dashboard')
1211
- return false;
1212
- // Exclude agents starting with __ (internal/system agents)
1213
- if (agent.name.startsWith('__'))
1214
- return false;
1215
- // Exclude agents without a proper CLI (improperly registered or stale)
1216
- if (!agent.cli || agent.cli === 'Unknown')
1217
- return false;
1218
- // Exclude offline agents (no lastSeen or too old)
1219
- if (!agent.lastSeen)
1220
- return false;
1221
- const lastSeenTime = new Date(agent.lastSeen).getTime();
1222
- if (now - lastSeenTime > OFFLINE_THRESHOLD_MS)
1223
- return false;
1224
- return true;
1225
- });
1226
- // Separate AI agents from human users
1227
- const filteredAgents = validEntries
1228
- .filter(agent => agent.cli !== 'dashboard')
1229
- .map(agent => ({
1230
- ...agent,
1231
- isHuman: false,
1232
- }));
1233
- const humanUsers = validEntries
1234
- .filter(agent => agent.cli === 'dashboard')
1235
- .map(agent => ({
1236
- ...agent,
1237
- isHuman: true,
1238
- }));
1239
- return {
1240
- agents: filteredAgents,
1241
- users: humanUsers,
1242
- messages: allMessages,
1243
- activity: allMessages, // For now, activity log is just the message log
1244
- sessions,
1245
- summaries,
1246
- };
1247
- };
1248
- // Track clients that are still initializing (haven't received first data yet)
1249
- // This prevents race conditions where broadcastData sends before initial data is sent
1250
- const initializingClients = new WeakSet();
1251
- const broadcastData = async () => {
1252
- try {
1253
- const data = await getAllData();
1254
- const payload = JSON.stringify(data);
1255
- // Guard against empty/invalid payloads
1256
- if (!payload || payload.length === 0) {
1257
- console.warn('[dashboard] Skipping broadcast - empty payload');
1258
- return;
1259
- }
1260
- wss.clients.forEach(client => {
1261
- // Skip clients that are still being initialized by the connection handler
1262
- if (initializingClients.has(client)) {
1263
- return;
1264
- }
1265
- if (client.readyState === WebSocket.OPEN) {
1266
- try {
1267
- client.send(payload);
1268
- }
1269
- catch (err) {
1270
- console.error('[dashboard] Failed to send to client:', err);
1271
- }
1272
- }
1273
- });
1274
- }
1275
- catch (err) {
1276
- console.error('[dashboard] Failed to broadcast data:', err);
1277
- }
1278
- };
1279
- // Bridge data functions - defined before connection handlers
1280
- const getBridgeData = async () => {
1281
- const bridgeStatePath = path.join(dataDir, 'bridge-state.json');
1282
- if (fs.existsSync(bridgeStatePath)) {
1283
- try {
1284
- const bridgeState = JSON.parse(fs.readFileSync(bridgeStatePath, 'utf-8'));
1285
- // Enrich each project with actual agent data from their team directories
1286
- if (bridgeState.projects && Array.isArray(bridgeState.projects)) {
1287
- for (const project of bridgeState.projects) {
1288
- if (project.path) {
1289
- // Get project's data directory
1290
- const crypto = await import('crypto');
1291
- const projectHash = crypto.createHash('sha256').update(project.path).digest('hex').slice(0, 12);
1292
- const projectDataDir = path.join(path.dirname(dataDir), projectHash);
1293
- const projectTeamDir = path.join(projectDataDir, 'team');
1294
- const agentsPath = path.join(projectTeamDir, 'agents.json');
1295
- // Read actual connected agents
1296
- if (fs.existsSync(agentsPath)) {
1297
- try {
1298
- const agentsData = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
1299
- if (agentsData.agents && Array.isArray(agentsData.agents)) {
1300
- // Filter to only show online agents (seen within 30 seconds - aligns with heartbeat timeout)
1301
- const thirtySecondsAgo = Date.now() - 30 * 1000;
1302
- project.agents = agentsData.agents
1303
- .filter((a) => {
1304
- if (!a.lastSeen)
1305
- return false;
1306
- return new Date(a.lastSeen).getTime() > thirtySecondsAgo;
1307
- })
1308
- .map((a) => ({
1309
- name: a.name,
1310
- status: 'active',
1311
- cli: a.cli,
1312
- lastSeen: a.lastSeen,
1313
- }));
1314
- // Update lead status based on actual agents
1315
- if (project.lead) {
1316
- const leadAgent = project.agents.find((a) => a.name.toLowerCase() === project.lead.name.toLowerCase());
1317
- project.lead.connected = !!leadAgent;
1318
- }
1319
- }
1320
- }
1321
- catch (e) {
1322
- console.error(`Failed to read agents for ${project.path}:`, e);
1323
- }
1324
- }
1325
- }
1326
- }
1327
- }
1328
- return bridgeState;
1329
- }
1330
- catch {
1331
- return { projects: [], messages: [], connected: false };
1332
- }
1333
- }
1334
- return { projects: [], messages: [], connected: false };
1335
- };
1336
- const broadcastBridgeData = async () => {
1337
- try {
1338
- const data = await getBridgeData();
1339
- const payload = JSON.stringify(data);
1340
- // Guard against empty/invalid payloads
1341
- if (!payload || payload.length === 0) {
1342
- console.warn('[dashboard] Skipping bridge broadcast - empty payload');
1343
- return;
1344
- }
1345
- wssBridge.clients.forEach(client => {
1346
- if (client.readyState === WebSocket.OPEN) {
1347
- try {
1348
- client.send(payload);
1349
- }
1350
- catch (err) {
1351
- console.error('[dashboard] Failed to send to bridge client:', err);
1352
- }
1353
- }
1354
- });
1355
- }
1356
- catch (err) {
1357
- console.error('[dashboard] Failed to broadcast bridge data:', err);
1358
- }
1359
- };
1360
- // Handle new WebSocket connections - send initial data immediately
1361
- wss.on('connection', async (ws, req) => {
1362
- console.log('[dashboard] WebSocket client connected from:', req.socket.remoteAddress);
1363
- // Mark client as alive initially for ping/pong keepalive
1364
- mainClientAlive.set(ws, true);
1365
- // Handle pong responses (keep connection alive)
1366
- ws.on('pong', () => {
1367
- mainClientAlive.set(ws, true);
1368
- });
1369
- // Mark as initializing to prevent broadcastData from sending before we do
1370
- initializingClients.add(ws);
1371
- try {
1372
- const data = await getAllData();
1373
- const payload = JSON.stringify(data);
1374
- // Guard against empty/invalid payloads
1375
- if (!payload || payload.length === 0) {
1376
- console.warn('[dashboard] Skipping initial send - empty payload');
1377
- return;
1378
- }
1379
- if (ws.readyState === WebSocket.OPEN) {
1380
- console.log('[dashboard] Sending initial data, size:', payload.length, 'first 200 chars:', payload.substring(0, 200));
1381
- ws.send(payload);
1382
- console.log('[dashboard] Initial data sent successfully');
1383
- }
1384
- else {
1385
- console.warn('[dashboard] WebSocket not open, state:', ws.readyState);
1386
- }
1387
- }
1388
- catch (err) {
1389
- console.error('[dashboard] Failed to send initial data:', err);
1390
- }
1391
- finally {
1392
- // Now allow broadcastData to send to this client
1393
- initializingClients.delete(ws);
1394
- }
1395
- ws.on('error', (err) => {
1396
- console.error('[dashboard] WebSocket client error:', err);
1397
- });
1398
- ws.on('close', (code, reason) => {
1399
- console.log('[dashboard] WebSocket client disconnected, code:', code, 'reason:', reason?.toString() || 'none');
1400
- });
1401
- });
1402
- // Handle bridge WebSocket connections
1403
- wssBridge.on('connection', async (ws) => {
1404
- console.log('[dashboard] Bridge WebSocket client connected');
1405
- // Mark client as alive initially for ping/pong keepalive
1406
- bridgeClientAlive.set(ws, true);
1407
- // Handle pong responses (keep connection alive)
1408
- ws.on('pong', () => {
1409
- bridgeClientAlive.set(ws, true);
1410
- });
1411
- try {
1412
- const data = await getBridgeData();
1413
- const payload = JSON.stringify(data);
1414
- if (ws.readyState === WebSocket.OPEN) {
1415
- ws.send(payload);
1416
- }
1417
- }
1418
- catch (err) {
1419
- console.error('[dashboard] Failed to send initial bridge data:', err);
1420
- }
1421
- ws.on('error', (err) => {
1422
- console.error('[dashboard] Bridge WebSocket client error:', err);
1423
- });
1424
- ws.on('close', (code, reason) => {
1425
- console.log('[dashboard] Bridge WebSocket client disconnected, code:', code, 'reason:', reason?.toString() || 'none');
1426
- });
1427
- });
1428
- // Track alive status for ping/pong keepalive on log connections
1429
- const logClientAlive = new WeakMap();
1430
- // Ping interval for log WebSocket connections (30 seconds)
1431
- // This prevents TCP/proxy timeouts from killing idle connections
1432
- const LOG_PING_INTERVAL_MS = 30000;
1433
- const logPingInterval = setInterval(() => {
1434
- wssLogs.clients.forEach((ws) => {
1435
- if (logClientAlive.get(ws) === false) {
1436
- // Client didn't respond to last ping - close gracefully
1437
- console.log('[dashboard] Logs WebSocket client unresponsive, closing gracefully');
1438
- ws.close(1000, 'unresponsive');
1439
- return;
1440
- }
1441
- // Mark as not alive until we get a pong
1442
- logClientAlive.set(ws, false);
1443
- ws.ping();
1444
- });
1445
- }, LOG_PING_INTERVAL_MS);
1446
- // Clean up ping interval on server close
1447
- wssLogs.on('close', () => {
1448
- clearInterval(logPingInterval);
1449
- });
1450
- // Handle logs WebSocket connections for live log streaming
1451
- wssLogs.on('connection', (ws, req) => {
1452
- console.log('[dashboard] Logs WebSocket client connected');
1453
- const clientSubscriptions = new Set();
1454
- // Mark client as alive initially
1455
- logClientAlive.set(ws, true);
1456
- // Handle pong responses (keep connection alive)
1457
- ws.on('pong', () => {
1458
- logClientAlive.set(ws, true);
1459
- });
1460
- // Helper to check if agent is daemon-connected (from agents.json)
1461
- const isDaemonConnected = (agentName) => {
1462
- const agentsPath = path.join(teamDir, 'agents.json');
1463
- if (!fs.existsSync(agentsPath))
1464
- return false;
1465
- try {
1466
- const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
1467
- return data.agents?.some((a) => a.name === agentName) ?? false;
1468
- }
1469
- catch {
1470
- return false;
1471
- }
1472
- };
1473
- // Helper to subscribe to an agent
1474
- const subscribeToAgent = (agentName) => {
1475
- const isSpawned = spawner?.hasWorker(agentName) ?? false;
1476
- const isDaemon = isDaemonConnected(agentName);
1477
- // Check if agent exists (either spawned or daemon-connected)
1478
- if (!isSpawned && !isDaemon) {
1479
- ws.send(JSON.stringify({
1480
- type: 'error',
1481
- agent: agentName,
1482
- error: `Agent ${agentName} not found`,
1483
- }));
1484
- // Close with custom code 4404 to signal "agent not found" - client should not reconnect
1485
- ws.close(4404, 'Agent not found');
1486
- return false;
1487
- }
1488
- // Add to subscriptions
1489
- clientSubscriptions.add(agentName);
1490
- if (!logSubscriptions.has(agentName)) {
1491
- logSubscriptions.set(agentName, new Set());
1492
- }
1493
- logSubscriptions.get(agentName).add(ws);
1494
- console.log(`[dashboard] Client subscribed to logs for: ${agentName} (spawned: ${isSpawned}, daemon: ${isDaemon})`);
1495
- if (isSpawned && spawner) {
1496
- // Send initial log history for spawned agents (5000 lines to match xterm scrollback capacity)
1497
- const lines = spawner.getWorkerOutput(agentName, 5000);
1498
- ws.send(JSON.stringify({
1499
- type: 'history',
1500
- agent: agentName,
1501
- lines: lines || [],
1502
- }));
1503
- }
1504
- else {
1505
- // For daemon-connected agents, explain that PTY output isn't available
1506
- ws.send(JSON.stringify({
1507
- type: 'history',
1508
- agent: agentName,
1509
- lines: [`[${agentName} is a daemon-connected agent - PTY output not available. Showing relay messages only.]`],
1510
- }));
1511
- }
1512
- ws.send(JSON.stringify({
1513
- type: 'subscribed',
1514
- agent: agentName,
1515
- }));
1516
- return true;
1517
- };
1518
- // Check if agent name is in URL path: /ws/logs/:agentName
1519
- const pathname = new URL(req.url || '', `http://${req.headers.host}`).pathname;
1520
- const pathMatch = pathname.match(/^\/ws\/logs\/(.+)$/);
1521
- if (pathMatch) {
1522
- const agentName = decodeURIComponent(pathMatch[1]);
1523
- subscribeToAgent(agentName);
1524
- }
1525
- ws.on('message', (data) => {
1526
- try {
1527
- const msg = JSON.parse(data.toString());
1528
- // Subscribe to agent logs
1529
- if (msg.subscribe && typeof msg.subscribe === 'string') {
1530
- subscribeToAgent(msg.subscribe);
1531
- }
1532
- // Unsubscribe from agent logs
1533
- if (msg.unsubscribe && typeof msg.unsubscribe === 'string') {
1534
- const agentName = msg.unsubscribe;
1535
- clientSubscriptions.delete(agentName);
1536
- logSubscriptions.get(agentName)?.delete(ws);
1537
- console.log(`[dashboard] Client unsubscribed from logs for: ${agentName}`);
1538
- ws.send(JSON.stringify({
1539
- type: 'unsubscribed',
1540
- agent: agentName,
1541
- }));
1542
- }
1543
- // Handle interactive terminal input
1544
- if (msg.type === 'input' && typeof msg.data === 'string') {
1545
- // Get agent name from message or use first subscribed agent
1546
- const agentName = msg.agent || [...clientSubscriptions][0];
1547
- if (!agentName) {
1548
- ws.send(JSON.stringify({
1549
- type: 'error',
1550
- error: 'No agent subscribed for input',
1551
- }));
1552
- return;
1553
- }
1554
- // Check if this is a spawned agent (we can only send input to spawned agents)
1555
- if (spawner?.hasWorker(agentName)) {
1556
- const success = spawner.sendWorkerInput(agentName, msg.data);
1557
- if (!success) {
1558
- console.warn(`[dashboard] Failed to send input to agent ${agentName}`);
1559
- }
1560
- }
1561
- else {
1562
- // Daemon-connected agents don't support direct input
1563
- ws.send(JSON.stringify({
1564
- type: 'error',
1565
- agent: agentName,
1566
- error: 'Interactive input not supported for daemon-connected agents',
1567
- }));
1568
- }
1569
- }
1570
- }
1571
- catch (err) {
1572
- console.error('[dashboard] Invalid logs WebSocket message:', err);
1573
- }
1574
- });
1575
- ws.on('error', (err) => {
1576
- console.error('[dashboard] Logs WebSocket client error:', err);
1577
- });
1578
- ws.on('close', (code, reason) => {
1579
- // Clean up subscriptions on disconnect
1580
- for (const agentName of clientSubscriptions) {
1581
- logSubscriptions.get(agentName)?.delete(ws);
1582
- }
1583
- const reasonStr = reason?.toString() || 'no reason';
1584
- console.log(`[dashboard] Logs WebSocket client disconnected (code: ${code}, reason: ${reasonStr})`);
1585
- });
1586
- });
1587
- // Deduplication for log output - prevent same content from being broadcast multiple times
1588
- // Key: agentName -> Set of recent content hashes (rolling window)
1589
- const recentLogHashes = new Map();
1590
- const MAX_LOG_HASH_WINDOW = 50; // Keep last 50 hashes per agent
1591
- // Simple hash function for log dedup
1592
- const hashLogContent = (content) => {
1593
- // Normalize whitespace and create a simple hash
1594
- const normalized = content.replace(/\s+/g, ' ').trim().slice(0, 200);
1595
- let hash = 0;
1596
- for (let i = 0; i < normalized.length; i++) {
1597
- const char = normalized.charCodeAt(i);
1598
- hash = ((hash << 5) - hash) + char;
1599
- hash = hash & hash;
1600
- }
1601
- return hash.toString(36);
1602
- };
1603
- // Function to broadcast log output to subscribed clients
1604
- const broadcastLogOutput = (agentName, output) => {
1605
- const clients = logSubscriptions.get(agentName);
1606
- if (!clients || clients.size === 0)
1607
- return;
1608
- // Skip empty or whitespace-only output
1609
- const trimmed = output.trim();
1610
- if (!trimmed)
1611
- return;
1612
- // Dedup: Check if we've recently broadcast this content
1613
- const hash = hashLogContent(output);
1614
- let agentHashes = recentLogHashes.get(agentName);
1615
- if (!agentHashes) {
1616
- agentHashes = new Set();
1617
- recentLogHashes.set(agentName, agentHashes);
1618
- }
1619
- if (agentHashes.has(hash)) {
1620
- // Already broadcast this content recently, skip
1621
- return;
1622
- }
1623
- // Add to rolling window
1624
- agentHashes.add(hash);
1625
- if (agentHashes.size > MAX_LOG_HASH_WINDOW) {
1626
- // Remove oldest entry (first in Set iteration order)
1627
- const oldest = agentHashes.values().next().value;
1628
- if (oldest !== undefined) {
1629
- agentHashes.delete(oldest);
1630
- }
1631
- }
1632
- const payload = JSON.stringify({
1633
- type: 'output',
1634
- agent: agentName,
1635
- data: output,
1636
- timestamp: new Date().toISOString(),
1637
- });
1638
- for (const client of clients) {
1639
- if (client.readyState === WebSocket.OPEN) {
1640
- client.send(payload);
1641
- }
1642
- }
1643
- };
1644
- // Expose broadcastLogOutput for PTY wrappers to call
1645
- global.__broadcastLogOutput = broadcastLogOutput;
1646
- // ===== Presence WebSocket Handler =====
1647
- // Helper to broadcast to all presence clients
1648
- const broadcastPresence = (message, exclude) => {
1649
- const payload = JSON.stringify(message);
1650
- wssPresence.clients.forEach((client) => {
1651
- if (client !== exclude && client.readyState === WebSocket.OPEN) {
1652
- client.send(payload);
1653
- }
1654
- });
1655
- };
1656
- // Helper to get online users list (without ws references)
1657
- const getOnlineUsersList = () => {
1658
- return Array.from(onlineUsers.values()).map((state) => state.info);
1659
- };
1660
- // Heartbeat to detect dead connections (30 seconds)
1661
- const PRESENCE_HEARTBEAT_INTERVAL = 30000;
1662
- const presenceHealth = new WeakMap();
1663
- const presenceHeartbeat = setInterval(() => {
1664
- wssPresence.clients.forEach((ws) => {
1665
- const health = presenceHealth.get(ws);
1666
- if (!health) {
1667
- presenceHealth.set(ws, { isAlive: true });
1668
- return;
1669
- }
1670
- if (!health.isAlive) {
1671
- ws.terminate();
1672
- return;
1673
- }
1674
- health.isAlive = false;
1675
- ws.ping();
1676
- });
1677
- }, PRESENCE_HEARTBEAT_INTERVAL);
1678
- wssPresence.on('close', () => {
1679
- clearInterval(presenceHeartbeat);
1680
- });
1681
- wssPresence.on('connection', (ws) => {
1682
- // Initialize health tracking (no log - too noisy)
1683
- presenceHealth.set(ws, { isAlive: true });
1684
- ws.on('pong', () => {
1685
- const health = presenceHealth.get(ws);
1686
- if (health)
1687
- health.isAlive = true;
1688
- });
1689
- let clientUsername;
1690
- ws.on('message', (data) => {
1691
- try {
1692
- const msg = JSON.parse(data.toString());
1693
- if (msg.type === 'presence') {
1694
- if (msg.action === 'join' && msg.user?.username) {
1695
- const username = msg.user.username;
1696
- const avatarUrl = msg.user.avatarUrl;
1697
- // Validate inputs
1698
- if (!isValidUsername(username)) {
1699
- console.warn(`[dashboard] Invalid username rejected: ${username}`);
1700
- return;
1701
- }
1702
- if (!isValidAvatarUrl(avatarUrl)) {
1703
- console.warn(`[dashboard] Invalid avatar URL rejected for user ${username}`);
1704
- return;
1705
- }
1706
- clientUsername = username;
1707
- const now = new Date().toISOString();
1708
- // Check if user already has connections (multi-tab support)
1709
- const existing = onlineUsers.get(username);
1710
- if (existing) {
1711
- // Add this connection to existing user
1712
- existing.connections.add(ws);
1713
- existing.info.lastSeen = now;
1714
- // Only log at milestones to reduce noise
1715
- const count = existing.connections.size;
1716
- if (count === 2 || count === 5 || count === 10 || count % 50 === 0) {
1717
- console.log(`[dashboard] User ${username} has ${count} connections`);
1718
- }
1719
- }
1720
- else {
1721
- // New user - create presence state
1722
- onlineUsers.set(username, {
1723
- info: {
1724
- username,
1725
- avatarUrl,
1726
- connectedAt: now,
1727
- lastSeen: now,
1728
- },
1729
- connections: new Set([ws]),
1730
- });
1731
- console.log(`[dashboard] User ${username} came online`);
1732
- // Register user with relay daemon for messaging
1733
- userBridge.registerUser(username, ws, { avatarUrl }).catch((err) => {
1734
- console.error(`[dashboard] Failed to register user ${username} with relay:`, err);
1735
- });
1736
- // Broadcast join to all other clients (only for truly new users)
1737
- broadcastPresence({
1738
- type: 'presence_join',
1739
- user: {
1740
- username,
1741
- avatarUrl,
1742
- connectedAt: now,
1743
- lastSeen: now,
1744
- },
1745
- }, ws);
1746
- }
1747
- // Send current online users list to the new client
1748
- ws.send(JSON.stringify({
1749
- type: 'presence_list',
1750
- users: getOnlineUsersList(),
1751
- }));
1752
- }
1753
- else if (msg.action === 'leave') {
1754
- // Security: Only allow leaving your own username
1755
- // Must have authenticated first
1756
- if (!clientUsername) {
1757
- console.warn(`[dashboard] Security: Unauthenticated leave attempt`);
1758
- return;
1759
- }
1760
- if (msg.username !== clientUsername) {
1761
- console.warn(`[dashboard] Security: User ${clientUsername} tried to remove ${msg.username}`);
1762
- return;
1763
- }
1764
- // Remove this connection from the user's set
1765
- const username = clientUsername; // Narrow type for TypeScript
1766
- const userState = onlineUsers.get(username);
1767
- if (userState) {
1768
- userState.connections.delete(ws);
1769
- // Only broadcast leave if no more connections
1770
- if (userState.connections.size === 0) {
1771
- onlineUsers.delete(username);
1772
- console.log(`[dashboard] User ${username} went offline`);
1773
- broadcastPresence({
1774
- type: 'presence_leave',
1775
- username,
1776
- });
1777
- }
1778
- else {
1779
- console.log(`[dashboard] User ${username} closed tab (${userState.connections.size} remaining)`);
1780
- }
1781
- }
1782
- }
1783
- }
1784
- else if (msg.type === 'typing') {
1785
- // Must have authenticated first
1786
- if (!clientUsername) {
1787
- console.warn(`[dashboard] Security: Unauthenticated typing attempt`);
1788
- return;
1789
- }
1790
- // Validate typing message comes from authenticated user
1791
- if (msg.username !== clientUsername) {
1792
- console.warn(`[dashboard] Security: Typing message username mismatch`);
1793
- return;
1794
- }
1795
- // Update last seen
1796
- const username = clientUsername; // Narrow type for TypeScript
1797
- const userState = onlineUsers.get(username);
1798
- if (userState) {
1799
- userState.info.lastSeen = new Date().toISOString();
1800
- }
1801
- // Broadcast typing indicator to all other clients
1802
- broadcastPresence({
1803
- type: 'typing',
1804
- username,
1805
- avatarUrl: userState?.info.avatarUrl,
1806
- isTyping: msg.isTyping,
1807
- }, ws);
1808
- }
1809
- else if (msg.type === 'channel_join') {
1810
- // Join a channel
1811
- if (!clientUsername) {
1812
- console.warn(`[dashboard] Security: Unauthenticated channel_join attempt`);
1813
- return;
1814
- }
1815
- if (!msg.channel || typeof msg.channel !== 'string') {
1816
- console.warn(`[dashboard] Invalid channel_join: missing channel`);
1817
- return;
1818
- }
1819
- userBridge.joinChannel(clientUsername, msg.channel).then((success) => {
1820
- ws.send(JSON.stringify({
1821
- type: 'channel_joined',
1822
- channel: msg.channel,
1823
- success,
1824
- }));
1825
- }).catch((err) => {
1826
- console.error(`[dashboard] Channel join error:`, err);
1827
- ws.send(JSON.stringify({
1828
- type: 'channel_joined',
1829
- channel: msg.channel,
1830
- success: false,
1831
- error: err.message,
1832
- }));
1833
- });
1834
- }
1835
- else if (msg.type === 'channel_leave') {
1836
- // Leave a channel
1837
- if (!clientUsername) {
1838
- console.warn(`[dashboard] Security: Unauthenticated channel_leave attempt`);
1839
- return;
1840
- }
1841
- if (!msg.channel || typeof msg.channel !== 'string') {
1842
- console.warn(`[dashboard] Invalid channel_leave: missing channel`);
1843
- return;
1844
- }
1845
- userBridge.leaveChannel(clientUsername, msg.channel).then((success) => {
1846
- ws.send(JSON.stringify({
1847
- type: 'channel_left',
1848
- channel: msg.channel,
1849
- success,
1850
- }));
1851
- }).catch((err) => {
1852
- console.error(`[dashboard] Channel leave error:`, err);
1853
- });
1854
- }
1855
- else if (msg.type === 'channel_message') {
1856
- // Send message to channel
1857
- if (!clientUsername) {
1858
- console.warn(`[dashboard] Security: Unauthenticated channel_message attempt`);
1859
- return;
1860
- }
1861
- if (!msg.channel || typeof msg.channel !== 'string') {
1862
- console.warn(`[dashboard] Invalid channel_message: missing channel`);
1863
- return;
1864
- }
1865
- if (!msg.body || typeof msg.body !== 'string') {
1866
- console.warn(`[dashboard] Invalid channel_message: missing body`);
1867
- return;
1868
- }
1869
- userBridge.sendChannelMessage(clientUsername, msg.channel, msg.body, {
1870
- thread: msg.thread,
1871
- }).catch((err) => {
1872
- console.error(`[dashboard] Channel message error:`, err);
1873
- });
1874
- }
1875
- else if (msg.type === 'direct_message') {
1876
- // Send direct message to user or agent
1877
- if (!clientUsername) {
1878
- console.warn(`[dashboard] Security: Unauthenticated direct_message attempt`);
1879
- return;
1880
- }
1881
- if (!msg.to || typeof msg.to !== 'string') {
1882
- console.warn(`[dashboard] Invalid direct_message: missing 'to'`);
1883
- return;
1884
- }
1885
- if (!msg.body || typeof msg.body !== 'string') {
1886
- console.warn(`[dashboard] Invalid direct_message: missing body`);
1887
- return;
1888
- }
1889
- userBridge.sendDirectMessage(clientUsername, msg.to, msg.body, {
1890
- thread: msg.thread,
1891
- }).catch((err) => {
1892
- console.error(`[dashboard] Direct message error:`, err);
1893
- });
1894
- }
1895
- }
1896
- catch (err) {
1897
- console.error('[dashboard] Invalid presence message:', err);
1898
- }
1899
- });
1900
- ws.on('error', (err) => {
1901
- console.error('[dashboard] Presence WebSocket client error:', err);
1902
- });
1903
- ws.on('close', () => {
1904
- // Clean up on disconnect with multi-tab support
1905
- if (clientUsername) {
1906
- const userState = onlineUsers.get(clientUsername);
1907
- if (userState) {
1908
- userState.connections.delete(ws);
1909
- // Only broadcast leave if no more connections
1910
- if (userState.connections.size === 0) {
1911
- onlineUsers.delete(clientUsername);
1912
- console.log(`[dashboard] User ${clientUsername} disconnected`);
1913
- // Unregister from relay daemon
1914
- userBridge.unregisterUser(clientUsername);
1915
- broadcastPresence({
1916
- type: 'presence_leave',
1917
- username: clientUsername,
1918
- });
1919
- }
1920
- else {
1921
- console.log(`[dashboard] User ${clientUsername} closed connection (${userState.connections.size} remaining)`);
1922
- }
1923
- }
1924
- }
1925
- });
1926
- });
1927
- app.get('/api/data', (req, res) => {
1928
- getAllData().then((data) => res.json(data)).catch((err) => {
1929
- console.error('Failed to fetch dashboard data', err);
1930
- res.status(500).json({ error: 'Failed to load data' });
1931
- });
1932
- });
1933
- // ===== Channel API =====
1934
- /**
1935
- * GET /api/channels - Get list of channels the user has joined
1936
- */
1937
- app.get('/api/channels', (req, res) => {
1938
- const username = req.query.username;
1939
- if (!username) {
1940
- return res.status(400).json({ error: 'username query param required' });
1941
- }
1942
- const channels = userBridge.getUserChannels(username);
1943
- res.json({ channels });
1944
- });
1945
- /**
1946
- * GET /api/channels/users - Get list of registered users
1947
- */
1948
- app.get('/api/channels/users', (_req, res) => {
1949
- const users = userBridge.getRegisteredUsers();
1950
- res.json({ users });
1951
- });
1952
- /**
1953
- * POST /api/channels/join - Join a channel
1954
- */
1955
- app.post('/api/channels/join', express.json(), async (req, res) => {
1956
- const { username, channel } = req.body;
1957
- if (!username || !channel) {
1958
- return res.status(400).json({ error: 'username and channel required' });
1959
- }
1960
- try {
1961
- const success = await userBridge.joinChannel(username, channel);
1962
- res.json({ success, channel });
1963
- }
1964
- catch (err) {
1965
- res.status(500).json({ error: err.message });
1966
- }
1967
- });
1968
- /**
1969
- * POST /api/channels/leave - Leave a channel
1970
- */
1971
- app.post('/api/channels/leave', express.json(), async (req, res) => {
1972
- const { username, channel } = req.body;
1973
- if (!username || !channel) {
1974
- return res.status(400).json({ error: 'username and channel required' });
1975
- }
1976
- try {
1977
- const success = await userBridge.leaveChannel(username, channel);
1978
- res.json({ success, channel });
1979
- }
1980
- catch (err) {
1981
- res.status(500).json({ error: err.message });
1982
- }
1983
- });
1984
- /**
1985
- * POST /api/channels/message - Send a message to a channel
1986
- */
1987
- app.post('/api/channels/message', express.json(), async (req, res) => {
1988
- const { username, channel, body, thread } = req.body;
1989
- if (!username || !channel || !body) {
1990
- return res.status(400).json({ error: 'username, channel, and body required' });
1991
- }
1992
- try {
1993
- const success = await userBridge.sendChannelMessage(username, channel, body, { thread });
1994
- res.json({ success });
1995
- }
1996
- catch (err) {
1997
- res.status(500).json({ error: err.message });
1998
- }
1999
- });
2000
- /**
2001
- * POST /api/dm - Send a direct message
2002
- */
2003
- app.post('/api/dm', express.json(), async (req, res) => {
2004
- const { from, to, body, thread } = req.body;
2005
- if (!from || !to || !body) {
2006
- return res.status(400).json({ error: 'from, to, and body required' });
2007
- }
2008
- try {
2009
- const success = await userBridge.sendDirectMessage(from, to, body, { thread });
2010
- res.json({ success });
2011
- }
2012
- catch (err) {
2013
- res.status(500).json({ error: err.message });
2014
- }
2015
- });
2016
- // ===== Health Check API =====
2017
- /**
2018
- * GET /health - Health check endpoint for monitoring
2019
- * Returns 200 if the daemon is healthy
2020
- */
2021
- app.get('/health', async (req, res) => {
2022
- const uptime = process.uptime();
2023
- const memUsage = process.memoryUsage();
2024
- const socketExists = fs.existsSync(socketPath);
2025
- // Check relay client connectivity (check if default Dashboard client is connected)
2026
- const defaultClient = relayClients.get('Dashboard');
2027
- const relayConnected = defaultClient?.state === 'READY';
2028
- // If socket doesn't exist, daemon may not be running properly
2029
- if (!socketExists) {
2030
- return res.status(503).json({
2031
- status: 'unhealthy',
2032
- reason: 'Relay socket not found',
2033
- uptime,
2034
- memoryMB: Math.round(memUsage.heapUsed / 1024 / 1024),
2035
- });
2036
- }
2037
- res.json({
2038
- status: 'healthy',
2039
- uptime,
2040
- memoryMB: Math.round(memUsage.heapUsed / 1024 / 1024),
2041
- relayConnected,
2042
- websocketClients: wss.clients.size,
2043
- });
2044
- });
2045
- /**
2046
- * GET /api/health - Alternative health endpoint (same as /health)
2047
- */
2048
- app.get('/api/health', async (req, res) => {
2049
- const uptime = process.uptime();
2050
- const memUsage = process.memoryUsage();
2051
- const socketExists = fs.existsSync(socketPath);
2052
- const defaultClient = relayClients.get('Dashboard');
2053
- const relayConnected = defaultClient?.state === 'READY';
2054
- if (!socketExists) {
2055
- return res.status(503).json({
2056
- status: 'unhealthy',
2057
- reason: 'Relay socket not found',
2058
- uptime,
2059
- memoryMB: Math.round(memUsage.heapUsed / 1024 / 1024),
2060
- });
2061
- }
2062
- res.json({
2063
- status: 'healthy',
2064
- uptime,
2065
- memoryMB: Math.round(memUsage.heapUsed / 1024 / 1024),
2066
- relayConnected,
2067
- websocketClients: wss.clients.size,
2068
- });
2069
- });
2070
- // ===== CLI Auth API (for workspace-based provider authentication) =====
2071
- /**
2072
- * POST /auth/cli/:provider/start - Start CLI auth flow
2073
- * Body: { useDeviceFlow?: boolean }
2074
- */
2075
- app.post('/auth/cli/:provider/start', async (req, res) => {
2076
- const { provider } = req.params;
2077
- const { useDeviceFlow } = req.body || {};
2078
- try {
2079
- const session = await startCLIAuth(provider, { useDeviceFlow });
2080
- res.json({
2081
- sessionId: session.id,
2082
- status: session.status,
2083
- authUrl: session.authUrl,
2084
- });
2085
- }
2086
- catch (err) {
2087
- res.status(400).json({
2088
- error: err instanceof Error ? err.message : 'Failed to start CLI auth',
2089
- });
2090
- }
2091
- });
2092
- /**
2093
- * GET /auth/cli/:provider/status/:sessionId - Get auth session status
2094
- */
2095
- app.get('/auth/cli/:provider/status/:sessionId', (req, res) => {
2096
- const { sessionId } = req.params;
2097
- const session = getAuthSession(sessionId);
2098
- if (!session) {
2099
- return res.status(404).json({ error: 'Session not found' });
2100
- }
2101
- res.json({
2102
- status: session.status,
2103
- authUrl: session.authUrl,
2104
- error: session.error,
2105
- });
2106
- });
2107
- /**
2108
- * GET /auth/cli/:provider/creds/:sessionId - Get credentials from completed auth
2109
- */
2110
- app.get('/auth/cli/:provider/creds/:sessionId', (req, res) => {
2111
- const { sessionId } = req.params;
2112
- const session = getAuthSession(sessionId);
2113
- if (!session) {
2114
- return res.status(404).json({ error: 'Session not found' });
2115
- }
2116
- if (session.status !== 'success') {
2117
- return res.status(400).json({ error: 'Auth not complete', status: session.status });
2118
- }
2119
- res.json({
2120
- token: session.token,
2121
- refreshToken: session.refreshToken,
2122
- expiresAt: session.tokenExpiresAt?.toISOString(),
2123
- });
2124
- });
2125
- /**
2126
- * POST /auth/cli/:provider/cancel/:sessionId - Cancel auth session
2127
- */
2128
- app.post('/auth/cli/:provider/cancel/:sessionId', (req, res) => {
2129
- const { sessionId } = req.params;
2130
- const cancelled = cancelAuthSession(sessionId);
2131
- if (!cancelled) {
2132
- return res.status(404).json({ error: 'Session not found' });
2133
- }
2134
- res.json({ success: true });
2135
- });
2136
- /**
2137
- * POST /auth/cli/:provider/code/:sessionId - Submit auth code to PTY
2138
- * Used when OAuth returns a code that must be pasted into the CLI
2139
- */
2140
- app.post('/auth/cli/:provider/code/:sessionId', async (req, res) => {
2141
- const { provider, sessionId } = req.params;
2142
- const { code } = req.body;
2143
- console.log('[cli-auth] Auth code submission received', { provider, sessionId, codeLength: code?.length });
2144
- if (!code || typeof code !== 'string') {
2145
- return res.status(400).json({ error: 'Auth code is required' });
2146
- }
2147
- try {
2148
- const result = await submitAuthCode(sessionId, code);
2149
- console.log('[cli-auth] Auth code submission result', { provider, sessionId, result });
2150
- if (!result.success) {
2151
- // Use 400 for all errors since they can be retried
2152
- return res.status(400).json({
2153
- error: result.error || 'Session not found or process not running',
2154
- needsRestart: result.needsRestart ?? true,
2155
- });
2156
- }
2157
- // Wait a few seconds for CLI to process and write credentials
2158
- // The 1s delay in submitAuthCode + CLI processing time means credentials
2159
- // should be available within 3-5 seconds
2160
- let sessionStatus = 'waiting_auth';
2161
- for (let i = 0; i < 10; i++) {
2162
- await new Promise(resolve => setTimeout(resolve, 500));
2163
- const session = getAuthSession(sessionId);
2164
- if (session?.status === 'success') {
2165
- sessionStatus = 'success';
2166
- console.log('[cli-auth] Credentials found after code submission', { provider, sessionId, attempt: i + 1 });
2167
- break;
2168
- }
2169
- if (session?.status === 'error') {
2170
- sessionStatus = 'error';
2171
- break;
2172
- }
2173
- }
2174
- res.json({
2175
- success: true,
2176
- message: 'Auth code submitted',
2177
- status: sessionStatus,
2178
- });
2179
- }
2180
- catch (err) {
2181
- console.error('[cli-auth] Auth code submission error', { provider, sessionId, error: String(err) });
2182
- return res.status(500).json({
2183
- error: 'Internal error submitting auth code. Please try again.',
2184
- needsRestart: true,
2185
- });
2186
- }
2187
- });
2188
- /**
2189
- * POST /auth/cli/:provider/complete/:sessionId - Complete auth
2190
- * For providers like Claude: just polls for credentials
2191
- * For providers like Codex: accepts authCode (redirect URL) and extracts the code
2192
- */
2193
- app.post('/auth/cli/:provider/complete/:sessionId', async (req, res) => {
2194
- const { sessionId } = req.params;
2195
- const { authCode } = req.body || {};
2196
- // If authCode provided, try to extract code and submit it
2197
- if (authCode && typeof authCode === 'string') {
2198
- let code = authCode;
2199
- // If it's a URL, extract the code parameter
2200
- if (authCode.startsWith('http')) {
2201
- try {
2202
- const url = new URL(authCode);
2203
- const codeParam = url.searchParams.get('code');
2204
- if (codeParam) {
2205
- code = codeParam;
2206
- }
2207
- }
2208
- catch {
2209
- // Not a valid URL, use as-is
2210
- }
2211
- }
2212
- // Submit the code to the CLI process
2213
- const submitResult = await submitAuthCode(sessionId, code);
2214
- if (!submitResult.success) {
2215
- return res.status(400).json({
2216
- error: submitResult.error,
2217
- needsRestart: submitResult.needsRestart,
2218
- });
2219
- }
2220
- // Wait a moment for credentials to be written
2221
- await new Promise(resolve => setTimeout(resolve, 2000));
2222
- }
2223
- // Poll for credentials
2224
- const result = await completeAuthSession(sessionId);
2225
- if (!result.success) {
2226
- return res.status(400).json({ error: result.error });
2227
- }
2228
- res.json({ success: true, message: 'Authentication complete' });
2229
- });
2230
- /**
2231
- * GET /auth/cli/providers - List supported providers
2232
- */
2233
- app.get('/auth/cli/providers', (req, res) => {
2234
- res.json({ providers: getSupportedProviders() });
2235
- });
2236
- /**
2237
- * GET /auth/cli/openai/check - Check if OpenAI/Codex is authenticated
2238
- * Used by the codex-auth CLI helper to detect when auth completes
2239
- */
2240
- app.get('/auth/cli/openai/check', async (req, res) => {
2241
- try {
2242
- // Codex stores credentials at ~/.codex/auth.json
2243
- const homedir = process.env.HOME || '/home/workspace';
2244
- const credPath = path.join(homedir, '.codex', 'auth.json');
2245
- if (!fs.existsSync(credPath)) {
2246
- return res.json({ authenticated: false });
2247
- }
2248
- const creds = JSON.parse(fs.readFileSync(credPath, 'utf-8'));
2249
- // Check if we have a valid access token or API key
2250
- const hasToken = !!(creds.access_token || creds.token || creds.api_key || creds.OPENAI_API_KEY);
2251
- res.json({ authenticated: hasToken });
2252
- }
2253
- catch (error) {
2254
- // File doesn't exist or is invalid
2255
- res.json({ authenticated: false });
2256
- }
2257
- });
2258
- // ===== Metrics API =====
2259
- /**
2260
- * GET /api/metrics - JSON format metrics for dashboard
2261
- */
2262
- app.get('/api/metrics', async (req, res) => {
2263
- try {
2264
- // Read agent registry for message counts
2265
- const agentsPath = path.join(teamDir, 'agents.json');
2266
- let agentRecords = [];
2267
- if (fs.existsSync(agentsPath)) {
2268
- const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
2269
- agentRecords = (data.agents || []).map((a) => ({
2270
- name: a.name,
2271
- messagesSent: a.messagesSent ?? 0,
2272
- messagesReceived: a.messagesReceived ?? 0,
2273
- firstSeen: a.firstSeen ?? new Date().toISOString(),
2274
- lastSeen: a.lastSeen ?? new Date().toISOString(),
2275
- }));
2276
- }
2277
- // Get messages for throughput calculation
2278
- const team = getTeamData();
2279
- const messages = team ? await getMessages(team.agents) : [];
2280
- // Get session data for lifecycle metrics
2281
- const sessions = storage?.getSessions
2282
- ? await storage.getSessions({ limit: 100 })
2283
- : [];
2284
- const metrics = computeSystemMetrics(agentRecords, messages, sessions);
2285
- res.json(metrics);
2286
- }
2287
- catch (err) {
2288
- console.error('Failed to compute metrics', err);
2289
- res.status(500).json({ error: 'Failed to compute metrics' });
2290
- }
2291
- });
2292
- /**
2293
- * GET /api/metrics/prometheus - Prometheus exposition format
2294
- */
2295
- app.get('/api/metrics/prometheus', async (req, res) => {
2296
- try {
2297
- // Read agent registry for message counts
2298
- const agentsPath = path.join(teamDir, 'agents.json');
2299
- let agentRecords = [];
2300
- if (fs.existsSync(agentsPath)) {
2301
- const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
2302
- agentRecords = (data.agents || []).map((a) => ({
2303
- name: a.name,
2304
- messagesSent: a.messagesSent ?? 0,
2305
- messagesReceived: a.messagesReceived ?? 0,
2306
- firstSeen: a.firstSeen ?? new Date().toISOString(),
2307
- lastSeen: a.lastSeen ?? new Date().toISOString(),
2308
- }));
2309
- }
2310
- // Get messages for throughput calculation
2311
- const team = getTeamData();
2312
- const messages = team ? await getMessages(team.agents) : [];
2313
- // Get session data for lifecycle metrics
2314
- const sessions = storage?.getSessions
2315
- ? await storage.getSessions({ limit: 100 })
2316
- : [];
2317
- const metrics = computeSystemMetrics(agentRecords, messages, sessions);
2318
- const prometheusOutput = formatPrometheusMetrics(metrics);
2319
- res.setHeader('Content-Type', 'text/plain; charset=utf-8');
2320
- res.send(prometheusOutput);
2321
- }
2322
- catch (err) {
2323
- console.error('Failed to compute Prometheus metrics', err);
2324
- res.status(500).send('# Error computing metrics\n');
2325
- }
2326
- });
2327
- // ===== Agent Memory Metrics API =====
2328
- /**
2329
- * GET /api/metrics/agents - Detailed agent memory and resource metrics
2330
- */
2331
- app.get('/api/metrics/agents', async (req, res) => {
2332
- try {
2333
- const agents = [];
2334
- // Get metrics from spawner's active workers
2335
- if (spawner) {
2336
- const activeWorkers = spawner.getActiveWorkers();
2337
- for (const worker of activeWorkers) {
2338
- // Get memory usage via /proc filesystem
2339
- let rssBytes = 0;
2340
- const cpuPercent = 0;
2341
- if (worker.pid) {
2342
- try {
2343
- // Use /proc filesystem instead of ps command (not available in all containers)
2344
- const statusPath = `/proc/${worker.pid}/status`;
2345
- if (fs.existsSync(statusPath)) {
2346
- const status = fs.readFileSync(statusPath, 'utf8');
2347
- // Parse VmRSS (Resident Set Size) from /proc/[pid]/status
2348
- const rssMatch = status.match(/VmRSS:\s+(\d+)\s+kB/);
2349
- if (rssMatch) {
2350
- rssBytes = parseInt(rssMatch[1], 10) * 1024; // Convert kB to bytes
2351
- }
2352
- }
2353
- // Note: CPU percentage requires sampling /proc/[pid]/stat over time
2354
- // which is more complex. Leaving at 0 for now.
2355
- }
2356
- catch {
2357
- // Process may have exited or /proc not accessible
2358
- }
2359
- }
2360
- agents.push({
2361
- name: worker.name,
2362
- pid: worker.pid,
2363
- status: worker.pid ? 'running' : 'unknown',
2364
- rssBytes,
2365
- cpuPercent,
2366
- trend: 'unknown',
2367
- alertLevel: rssBytes > 1024 * 1024 * 1024 ? 'critical' :
2368
- rssBytes > 512 * 1024 * 1024 ? 'warning' : 'normal',
2369
- highWatermark: rssBytes,
2370
- uptimeMs: worker.spawnedAt ? Date.now() - worker.spawnedAt : 0,
2371
- startedAt: worker.spawnedAt ? new Date(worker.spawnedAt).toISOString() : undefined,
2372
- });
2373
- }
2374
- }
2375
- // Also check agents.json for registered agents that may not be spawned
2376
- const agentsPath = path.join(teamDir, 'agents.json');
2377
- if (fs.existsSync(agentsPath)) {
2378
- const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
2379
- const registeredAgents = data.agents || [];
2380
- for (const agent of registeredAgents) {
2381
- if (!agents.find(a => a.name === agent.name)) {
2382
- // Check if recently active (within 30 seconds)
2383
- const lastSeen = agent.lastSeen ? new Date(agent.lastSeen).getTime() : 0;
2384
- const isActive = Date.now() - lastSeen < 30000;
2385
- if (isActive) {
2386
- agents.push({
2387
- name: agent.name,
2388
- status: 'active',
2389
- alertLevel: 'normal',
2390
- });
2391
- }
2392
- }
2393
- }
2394
- }
2395
- res.json({
2396
- agents,
2397
- system: {
2398
- totalMemory: os.totalmem(),
2399
- freeMemory: os.freemem(),
2400
- heapUsed: process.memoryUsage().heapUsed,
2401
- },
2402
- });
2403
- }
2404
- catch (err) {
2405
- console.error('Failed to get agent metrics', err);
2406
- res.status(500).json({ error: 'Failed to get agent metrics' });
2407
- }
2408
- });
2409
- /**
2410
- * GET /api/metrics/health - System health and crash insights
2411
- */
2412
- app.get('/api/metrics/health', async (req, res) => {
2413
- try {
2414
- // Calculate health score based on available data
2415
- let healthScore = 100;
2416
- const issues = [];
2417
- const recommendations = [];
2418
- const crashes = [];
2419
- const alerts = [];
2420
- let agentCount = 0;
2421
- const totalCrashes24h = 0;
2422
- let totalAlerts24h = 0;
2423
- // Get spawned agent count
2424
- if (spawner) {
2425
- const workers = spawner.getActiveWorkers();
2426
- agentCount = workers.length;
2427
- // Check for high memory usage
2428
- for (const worker of workers) {
2429
- if (worker.pid) {
2430
- try {
2431
- const { execSync } = await import('child_process');
2432
- const output = execSync(`ps -o rss= -p ${worker.pid}`, {
2433
- encoding: 'utf8',
2434
- timeout: 3000,
2435
- }).trim();
2436
- const rssBytes = parseInt(output, 10) * 1024;
2437
- if (rssBytes > 1.5 * 1024 * 1024 * 1024) {
2438
- // > 1.5GB
2439
- healthScore -= 20;
2440
- issues.push({
2441
- severity: 'critical',
2442
- message: `Agent "${worker.name}" is using ${Math.round(rssBytes / 1024 / 1024)}MB of memory`,
2443
- });
2444
- totalAlerts24h++;
2445
- alerts.push({
2446
- id: `alert-${Date.now()}-${worker.name}`,
2447
- agentName: worker.name,
2448
- alertType: 'oom_imminent',
2449
- message: `Memory usage critical: ${Math.round(rssBytes / 1024 / 1024)}MB`,
2450
- createdAt: new Date().toISOString(),
2451
- });
2452
- }
2453
- else if (rssBytes > 1024 * 1024 * 1024) {
2454
- // > 1GB
2455
- healthScore -= 10;
2456
- issues.push({
2457
- severity: 'high',
2458
- message: `Agent "${worker.name}" memory usage is elevated (${Math.round(rssBytes / 1024 / 1024)}MB)`,
2459
- });
2460
- }
2461
- }
2462
- catch {
2463
- // Process may have exited
2464
- }
2465
- }
2466
- }
2467
- }
2468
- // Check registered agents
2469
- const agentsPath = path.join(teamDir, 'agents.json');
2470
- if (fs.existsSync(agentsPath)) {
2471
- const data = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
2472
- const registeredAgents = data.agents || [];
2473
- const activeAgents = registeredAgents.filter((a) => {
2474
- const lastSeen = a.lastSeen ? new Date(a.lastSeen).getTime() : 0;
2475
- return Date.now() - lastSeen < 30000;
2476
- });
2477
- agentCount = Math.max(agentCount, activeAgents.length);
2478
- }
2479
- // Generate recommendations based on issues
2480
- if (issues.some(i => i.severity === 'critical')) {
2481
- recommendations.push('Consider restarting agents with high memory usage');
2482
- recommendations.push('Monitor system resources closely');
2483
- }
2484
- if (agentCount === 0) {
2485
- recommendations.push('No active agents detected - start agents to begin monitoring');
2486
- }
2487
- // Clamp health score
2488
- healthScore = Math.max(0, Math.min(100, healthScore));
2489
- // Generate summary
2490
- let summary;
2491
- if (healthScore >= 90) {
2492
- summary = 'System is healthy. All agents operating normally.';
2493
- }
2494
- else if (healthScore >= 70) {
2495
- summary = 'Some issues detected. Review warnings and recommendations.';
2496
- }
2497
- else if (healthScore >= 50) {
2498
- summary = 'Multiple issues detected. Action recommended.';
2499
- }
2500
- else {
2501
- summary = 'Critical issues detected. Immediate action required.';
2502
- }
2503
- res.json({
2504
- healthScore,
2505
- summary,
2506
- issues,
2507
- recommendations,
2508
- crashes,
2509
- alerts,
2510
- stats: {
2511
- totalCrashes24h,
2512
- totalAlerts24h,
2513
- agentCount,
2514
- },
2515
- });
2516
- }
2517
- catch (err) {
2518
- console.error('Failed to compute health metrics', err);
2519
- res.status(500).json({ error: 'Failed to compute health metrics' });
2520
- }
2521
- });
2522
- // ===== File Search API =====
2523
- /**
2524
- * GET /api/files - Search for files in the repository
2525
- * Query params:
2526
- * - q: Search query (file path pattern)
2527
- * - limit: Max number of results (default 15)
2528
- *
2529
- * This endpoint searches for files in the project root directory
2530
- * to support @-file autocomplete in the message composer.
2531
- */
2532
- app.get('/api/files', async (req, res) => {
2533
- const query = req.query.q || '';
2534
- const limit = Math.min(parseInt(req.query.limit, 10) || 15, 50);
2535
- // Get project root (parent of dataDir, or use projectRoot if available)
2536
- const searchRoot = options.projectRoot || path.dirname(dataDir);
2537
- try {
2538
- const results = await searchFiles(searchRoot, query, limit);
2539
- res.json({ files: results, query, searchRoot: path.basename(searchRoot) });
2540
- }
2541
- catch (err) {
2542
- console.error('[api] File search error:', err);
2543
- res.status(500).json({ error: 'Failed to search files', files: [] });
2544
- }
2545
- });
2546
- // Bridge API endpoint - returns multi-project data
2547
- // This is a placeholder that returns empty data when not in bridge mode
2548
- // The actual bridge data comes from MultiProjectClient when running `agent-relay bridge`
2549
- app.get('/api/bridge', async (req, res) => {
2550
- try {
2551
- // Check if bridge state file exists (written by bridge command)
2552
- const bridgeStatePath = path.join(dataDir, 'bridge-state.json');
2553
- if (fs.existsSync(bridgeStatePath)) {
2554
- const bridgeData = JSON.parse(fs.readFileSync(bridgeStatePath, 'utf-8'));
2555
- res.json(bridgeData);
2556
- }
2557
- else {
2558
- // No bridge running - return empty state
2559
- res.json({
2560
- projects: [],
2561
- messages: [],
2562
- connected: false,
2563
- });
2564
- }
2565
- }
2566
- catch (err) {
2567
- console.error('Failed to fetch bridge data', err);
2568
- res.status(500).json({ error: 'Failed to load bridge data' });
2569
- }
2570
- });
2571
- // ===== Conversation History API =====
2572
- /**
2573
- * GET /api/history/sessions - List all sessions with filters
2574
- * Query params:
2575
- * - agent: Filter by agent name
2576
- * - since: Filter sessions started after this timestamp (ms)
2577
- * - limit: Max number of sessions (default 50)
2578
- */
2579
- app.get('/api/history/sessions', async (req, res) => {
2580
- if (!storage) {
2581
- return res.status(503).json({ error: 'Storage not configured' });
2582
- }
2583
- try {
2584
- const query = {};
2585
- if (req.query.agent && typeof req.query.agent === 'string') {
2586
- query.agentName = req.query.agent;
2587
- }
2588
- if (req.query.since) {
2589
- query.since = parseInt(req.query.since, 10);
2590
- }
2591
- query.limit = req.query.limit ? parseInt(req.query.limit, 10) : 50;
2592
- const sessions = storage.getSessions
2593
- ? await storage.getSessions(query)
2594
- : [];
2595
- const result = sessions.map(s => ({
2596
- id: s.id,
2597
- agentName: s.agentName,
2598
- cli: s.cli,
2599
- startedAt: new Date(s.startedAt).toISOString(),
2600
- endedAt: s.endedAt ? new Date(s.endedAt).toISOString() : undefined,
2601
- duration: formatDuration(s.startedAt, s.endedAt),
2602
- messageCount: s.messageCount,
2603
- summary: s.summary,
2604
- isActive: !s.endedAt,
2605
- closedBy: s.closedBy,
2606
- }));
2607
- res.json({ sessions: result });
2608
- }
2609
- catch (err) {
2610
- console.error('Failed to fetch sessions', err);
2611
- res.status(500).json({ error: 'Failed to fetch sessions' });
2612
- }
2613
- });
2614
- /**
2615
- * GET /api/history/messages - Get messages with filters
2616
- * Query params:
2617
- * - from: Filter by sender
2618
- * - to: Filter by recipient
2619
- * - thread: Filter by thread ID
2620
- * - since: Filter messages after this timestamp (ms)
2621
- * - limit: Max number of messages (default 100)
2622
- * - order: 'asc' or 'desc' (default 'desc')
2623
- * - search: Search in message body (basic substring match)
2624
- */
2625
- app.get('/api/history/messages', async (req, res) => {
2626
- if (!storage) {
2627
- return res.status(503).json({ error: 'Storage not configured' });
2628
- }
2629
- try {
2630
- const query = {};
2631
- if (req.query.from && typeof req.query.from === 'string') {
2632
- query.from = req.query.from;
2633
- }
2634
- if (req.query.to && typeof req.query.to === 'string') {
2635
- query.to = req.query.to;
2636
- }
2637
- if (req.query.thread && typeof req.query.thread === 'string') {
2638
- query.thread = req.query.thread;
2639
- }
2640
- if (req.query.since) {
2641
- query.sinceTs = parseInt(req.query.since, 10);
2642
- }
2643
- query.limit = req.query.limit ? parseInt(req.query.limit, 10) : 100;
2644
- query.order = req.query.order || 'desc';
2645
- let messages = await storage.getMessages(query);
2646
- // Filter out messages from/to internal system agents (e.g., __spawner__)
2647
- messages = messages.filter(m => !isInternalAgent(m.from) && !isInternalAgent(m.to));
2648
- // Client-side search filter (basic substring match)
2649
- const searchTerm = req.query.search;
2650
- if (searchTerm && searchTerm.trim()) {
2651
- const lowerSearch = searchTerm.toLowerCase();
2652
- messages = messages.filter(m => m.body.toLowerCase().includes(lowerSearch) ||
2653
- m.from.toLowerCase().includes(lowerSearch) ||
2654
- m.to.toLowerCase().includes(lowerSearch));
2655
- }
2656
- const result = messages.map(m => ({
2657
- id: m.id,
2658
- from: m.from,
2659
- to: m.to,
2660
- content: m.body,
2661
- timestamp: new Date(m.ts).toISOString(),
2662
- thread: m.thread,
2663
- isBroadcast: m.is_broadcast,
2664
- isUrgent: m.is_urgent,
2665
- status: m.status,
2666
- }));
2667
- res.json({ messages: result });
2668
- }
2669
- catch (err) {
2670
- console.error('Failed to fetch messages', err);
2671
- res.status(500).json({ error: 'Failed to fetch messages' });
2672
- }
2673
- });
2674
- /**
2675
- * GET /api/history/conversations - Get unique conversations (agent pairs)
2676
- * Returns list of agent pairs that have exchanged messages
2677
- */
2678
- app.get('/api/history/conversations', async (req, res) => {
2679
- if (!storage) {
2680
- return res.status(503).json({ error: 'Storage not configured' });
2681
- }
2682
- try {
2683
- // Get all messages to build conversation list
2684
- const messages = await storage.getMessages({ limit: 1000, order: 'desc' });
2685
- // Build unique conversation pairs
2686
- const conversationMap = new Map();
2687
- for (const msg of messages) {
2688
- // Skip broadcasts for conversation pairing
2689
- if (msg.to === '*' || msg.is_broadcast)
2690
- continue;
2691
- // Skip messages from/to internal system agents (e.g., __spawner__)
2692
- if (isInternalAgent(msg.from) || isInternalAgent(msg.to))
2693
- continue;
2694
- // Create normalized key (sorted participants)
2695
- const participants = [msg.from, msg.to].sort();
2696
- const key = participants.join(':');
2697
- const existing = conversationMap.get(key);
2698
- if (existing) {
2699
- existing.messageCount++;
2700
- }
2701
- else {
2702
- conversationMap.set(key, {
2703
- participants,
2704
- lastMessage: msg.body.substring(0, 100),
2705
- lastTimestamp: new Date(msg.ts).toISOString(),
2706
- messageCount: 1,
2707
- });
2708
- }
2709
- }
2710
- // Convert to array sorted by last timestamp
2711
- const conversations = Array.from(conversationMap.values())
2712
- .sort((a, b) => new Date(b.lastTimestamp).getTime() - new Date(a.lastTimestamp).getTime());
2713
- res.json({ conversations });
2714
- }
2715
- catch (err) {
2716
- console.error('Failed to fetch conversations', err);
2717
- res.status(500).json({ error: 'Failed to fetch conversations' });
2718
- }
2719
- });
2720
- /**
2721
- * GET /api/history/message/:id - Get a single message by ID
2722
- */
2723
- app.get('/api/history/message/:id', async (req, res) => {
2724
- if (!storage) {
2725
- return res.status(503).json({ error: 'Storage not configured' });
2726
- }
2727
- try {
2728
- const { id } = req.params;
2729
- const message = storage.getMessageById
2730
- ? await storage.getMessageById(id)
2731
- : null;
2732
- if (!message) {
2733
- return res.status(404).json({ error: 'Message not found' });
2734
- }
2735
- res.json({
2736
- id: message.id,
2737
- from: message.from,
2738
- to: message.to,
2739
- content: message.body,
2740
- timestamp: new Date(message.ts).toISOString(),
2741
- thread: message.thread,
2742
- isBroadcast: message.is_broadcast,
2743
- isUrgent: message.is_urgent,
2744
- status: message.status,
2745
- data: message.data,
2746
- });
2747
- }
2748
- catch (err) {
2749
- console.error('Failed to fetch message', err);
2750
- res.status(500).json({ error: 'Failed to fetch message' });
2751
- }
2752
- });
2753
- /**
2754
- * GET /api/history/stats - Get storage statistics
2755
- */
2756
- app.get('/api/history/stats', async (req, res) => {
2757
- if (!storage) {
2758
- return res.status(503).json({ error: 'Storage not configured' });
2759
- }
2760
- try {
2761
- // Get stats from SQLite adapter if available
2762
- if (storage instanceof SqliteStorageAdapter) {
2763
- const stats = await storage.getStats();
2764
- const sessions = await storage.getSessions({ limit: 1000 });
2765
- // Calculate additional stats
2766
- const activeSessions = sessions.filter(s => !s.endedAt).length;
2767
- const uniqueAgents = new Set(sessions.map(s => s.agentName)).size;
2768
- res.json({
2769
- messageCount: stats.messageCount,
2770
- sessionCount: stats.sessionCount,
2771
- activeSessions,
2772
- uniqueAgents,
2773
- oldestMessageDate: stats.oldestMessageTs
2774
- ? new Date(stats.oldestMessageTs).toISOString()
2775
- : null,
2776
- });
2777
- }
2778
- else {
2779
- // Basic stats for other adapters
2780
- const messages = await storage.getMessages({ limit: 1 });
2781
- res.json({
2782
- messageCount: messages.length > 0 ? 'unknown' : 0,
2783
- sessionCount: 'unknown',
2784
- activeSessions: 'unknown',
2785
- uniqueAgents: 'unknown',
2786
- });
2787
- }
2788
- }
2789
- catch (err) {
2790
- console.error('Failed to fetch stats', err);
2791
- res.status(500).json({ error: 'Failed to fetch stats' });
2792
- }
2793
- });
2794
- // ===== Agent Logs API =====
2795
- /**
2796
- * GET /api/logs/:name - Get historical logs for a spawned agent
2797
- * Query params:
2798
- * - limit: Max lines to return (default 500)
2799
- * - raw: If 'true', return raw output instead of cleaned lines
2800
- */
2801
- app.get('/api/logs/:name', (req, res) => {
2802
- if (!spawner) {
2803
- return res.status(503).json({ error: 'Spawner not enabled' });
2804
- }
2805
- const { name } = req.params;
2806
- const limit = req.query.limit ? parseInt(req.query.limit, 10) : 500;
2807
- const raw = req.query.raw === 'true';
2808
- // Check if worker exists
2809
- if (!spawner.hasWorker(name)) {
2810
- return res.status(404).json({ error: `Agent ${name} not found` });
2811
- }
2812
- try {
2813
- if (raw) {
2814
- const output = spawner.getWorkerRawOutput(name);
2815
- res.json({
2816
- name,
2817
- raw: true,
2818
- output: output || '',
2819
- timestamp: new Date().toISOString(),
2820
- });
2821
- }
2822
- else {
2823
- const lines = spawner.getWorkerOutput(name, limit);
2824
- res.json({
2825
- name,
2826
- raw: false,
2827
- lines: lines || [],
2828
- lineCount: lines?.length || 0,
2829
- timestamp: new Date().toISOString(),
2830
- });
2831
- }
2832
- }
2833
- catch (err) {
2834
- console.error(`Failed to get logs for ${name}:`, err);
2835
- res.status(500).json({ error: 'Failed to get logs' });
2836
- }
2837
- });
2838
- /**
2839
- * GET /api/logs - List all agents with available logs
2840
- */
2841
- app.get('/api/logs', (req, res) => {
2842
- if (!spawner) {
2843
- return res.status(503).json({ error: 'Spawner not enabled' });
2844
- }
2845
- try {
2846
- const workers = spawner.getActiveWorkers();
2847
- const agents = workers.map(w => ({
2848
- name: w.name,
2849
- cli: w.cli,
2850
- pid: w.pid,
2851
- spawnedAt: new Date(w.spawnedAt).toISOString(),
2852
- hasLogs: true,
2853
- }));
2854
- res.json({ agents });
2855
- }
2856
- catch (err) {
2857
- console.error('Failed to list agents with logs:', err);
2858
- res.status(500).json({ error: 'Failed to list agents' });
2859
- }
2860
- });
2861
- // ===== Agent Spawn API =====
2862
- /**
2863
- * POST /api/spawn - Spawn a new agent
2864
- * Body: { name: string, cli?: string, task?: string, team?: string, shadowMode?, shadowAgent?, shadowOf?, shadowTriggers?, shadowSpeakOn? }
2865
- */
2866
- app.post('/api/spawn', async (req, res) => {
2867
- if (!spawner) {
2868
- return res.status(503).json({
2869
- success: false,
2870
- error: 'Spawner not enabled. Start dashboard with enableSpawner: true',
2871
- });
2872
- }
2873
- const { name, cli = 'claude', task = '', team, interactive, shadowMode, shadowAgent, shadowOf, shadowTriggers, shadowSpeakOn, } = req.body;
2874
- if (!name || typeof name !== 'string') {
2875
- return res.status(400).json({
2876
- success: false,
2877
- error: 'Missing required field: name',
2878
- });
2879
- }
2880
- try {
2881
- const request = {
2882
- name,
2883
- cli,
2884
- task,
2885
- team: team || undefined, // Optional team name
2886
- interactive, // Disables auto-accept for auth setup flows
2887
- shadowMode,
2888
- shadowAgent,
2889
- shadowOf,
2890
- shadowTriggers,
2891
- shadowSpeakOn,
2892
- };
2893
- const result = await spawner.spawn(request);
2894
- if (result.success) {
2895
- // Broadcast update to WebSocket clients
2896
- broadcastData().catch(() => { });
2897
- }
2898
- res.json(result);
2899
- }
2900
- catch (err) {
2901
- console.error('[api] Spawn error:', err);
2902
- res.status(500).json({
2903
- success: false,
2904
- name,
2905
- error: err.message,
2906
- });
2907
- }
2908
- });
2909
- /**
2910
- * POST /api/spawn/architect - Spawn an Architect agent for bridge mode
2911
- * Body: { cli?: string }
2912
- */
2913
- app.post('/api/spawn/architect', async (req, res) => {
2914
- if (!spawner) {
2915
- return res.status(503).json({
2916
- success: false,
2917
- error: 'Spawner not enabled. Start dashboard with enableSpawner: true',
2918
- });
2919
- }
2920
- const { cli = 'claude' } = req.body;
2921
- // Check if Architect already exists
2922
- const activeWorkers = spawner.getActiveWorkers();
2923
- if (activeWorkers.some(w => w.name.toLowerCase() === 'architect')) {
2924
- return res.status(409).json({
2925
- success: false,
2926
- error: 'Architect agent already running',
2927
- });
2928
- }
2929
- // Get bridge state for project context
2930
- const bridgeStatePath = path.join(dataDir, 'bridge-state.json');
2931
- let projectContext = 'No bridge projects connected.';
2932
- if (fs.existsSync(bridgeStatePath)) {
2933
- try {
2934
- const bridgeState = JSON.parse(fs.readFileSync(bridgeStatePath, 'utf-8'));
2935
- if (bridgeState.projects && bridgeState.projects.length > 0) {
2936
- projectContext = bridgeState.projects
2937
- .map((p) => `- ${p.id}: ${p.path} (Lead: ${p.lead?.name || 'none'})`)
2938
- .join('\n');
2939
- }
2940
- }
2941
- catch (e) {
2942
- console.error('[api] Failed to read bridge state:', e);
2943
- }
2944
- }
2945
- // Build the architect prompt
2946
- const architectPrompt = `You are the Architect, a cross-project coordinator overseeing multiple codebases.
2947
-
2948
- ## Connected Projects
2949
- ${projectContext}
2950
-
2951
- ## Your Role
2952
- - Coordinate high-level work across all projects
2953
- - Assign tasks to project leads
2954
- - Ensure consistency and resolve cross-project dependencies
2955
- - Review overall architecture decisions
2956
-
2957
- ## Cross-Project Messaging
2958
-
2959
- Use this syntax to message agents in specific projects:
2960
-
2961
- \`\`\`
2962
- ->relay:project-id:AgentName <<<
2963
- Your message to this agent>>>
2964
-
2965
- ->relay:project-id:* <<<
2966
- Broadcast to all agents in a project>>>
2967
-
2968
- ->relay:*:* <<<
2969
- Broadcast to ALL agents in ALL projects>>>
2970
- \`\`\`
2971
-
2972
- ## Getting Started
2973
- 1. Check in with each project lead to understand current status
2974
- 2. Identify cross-project dependencies
2975
- 3. Coordinate work across teams
2976
-
2977
- Start by greeting the project leads and asking for status updates.`;
2978
- try {
2979
- const result = await spawner.spawn({
2980
- name: 'Architect',
2981
- cli,
2982
- task: architectPrompt,
2983
- });
2984
- if (result.success) {
2985
- broadcastData().catch(() => { });
2986
- }
2987
- res.json(result);
2988
- }
2989
- catch (err) {
2990
- console.error('[api] Architect spawn error:', err);
2991
- res.status(500).json({
2992
- success: false,
2993
- name: 'Architect',
2994
- error: err.message,
2995
- });
2996
- }
2997
- });
2998
- /**
2999
- * GET /api/spawned - List active spawned agents
3000
- */
3001
- app.get('/api/spawned', (req, res) => {
3002
- if (!spawner) {
3003
- return res.status(503).json({
3004
- success: false,
3005
- error: 'Spawner not enabled',
3006
- agents: [],
3007
- });
3008
- }
3009
- const agents = spawner.getActiveWorkers();
3010
- res.json({
3011
- success: true,
3012
- agents,
3013
- });
3014
- });
3015
- /**
3016
- * DELETE /api/spawned/:name - Release a spawned agent
3017
- */
3018
- app.delete('/api/spawned/:name', async (req, res) => {
3019
- if (!spawner) {
3020
- return res.status(503).json({
3021
- success: false,
3022
- error: 'Spawner not enabled',
3023
- });
3024
- }
3025
- const { name } = req.params;
3026
- try {
3027
- const released = await spawner.release(name);
3028
- if (released) {
3029
- broadcastData().catch(() => { });
3030
- }
3031
- res.json({
3032
- success: released,
3033
- name,
3034
- error: released ? undefined : `Agent ${name} not found`,
3035
- });
3036
- }
3037
- catch (err) {
3038
- console.error('[api] Release error:', err);
3039
- res.status(500).json({
3040
- success: false,
3041
- name,
3042
- error: err.message,
3043
- });
3044
- }
3045
- });
3046
- /**
3047
- * GET /api/trajectory - Get current trajectory status
3048
- */
3049
- app.get('/api/trajectory', async (_req, res) => {
3050
- try {
3051
- const status = await getTrajectoryStatus();
3052
- res.json({
3053
- success: true,
3054
- ...status,
3055
- });
3056
- }
3057
- catch (err) {
3058
- console.error('[api] Trajectory status error:', err);
3059
- res.status(500).json({
3060
- success: false,
3061
- error: err.message,
3062
- });
3063
- }
3064
- });
3065
- /**
3066
- * GET /api/trajectory/steps - List trajectory steps
3067
- */
3068
- app.get('/api/trajectory/steps', async (req, res) => {
3069
- try {
3070
- const trajectoryId = req.query.trajectoryId;
3071
- const result = await listTrajectorySteps(trajectoryId);
3072
- if (result.success) {
3073
- res.json({
3074
- success: true,
3075
- steps: result.steps,
3076
- });
3077
- }
3078
- else {
3079
- res.status(500).json({
3080
- success: false,
3081
- steps: [],
3082
- error: result.error,
3083
- });
3084
- }
3085
- }
3086
- catch (err) {
3087
- console.error('[api] Trajectory steps error:', err);
3088
- res.status(500).json({
3089
- success: false,
3090
- steps: [],
3091
- error: err.message,
3092
- });
3093
- }
3094
- });
3095
- /**
3096
- * GET /api/trajectory/history - List all trajectories (completed and active)
3097
- */
3098
- app.get('/api/trajectory/history', async (_req, res) => {
3099
- try {
3100
- const result = await getTrajectoryHistory();
3101
- if (result.success) {
3102
- res.json({
3103
- success: true,
3104
- trajectories: result.trajectories,
3105
- });
3106
- }
3107
- else {
3108
- res.status(500).json({
3109
- success: false,
3110
- trajectories: [],
3111
- error: result.error,
3112
- });
3113
- }
3114
- }
3115
- catch (err) {
3116
- console.error('[api] Trajectory history error:', err);
3117
- res.status(500).json({
3118
- success: false,
3119
- trajectories: [],
3120
- error: err.message,
3121
- });
3122
- }
3123
- });
3124
- // ===== Settings API =====
3125
- /**
3126
- * GET /api/settings - Get all workspace settings with documentation
3127
- */
3128
- app.get('/api/settings', async (_req, res) => {
3129
- try {
3130
- const { readRelayConfig, shouldStoreInRepo, getTrajectoriesStorageDescription } = await import('../trajectory/config.js');
3131
- const config = readRelayConfig();
3132
- res.json({
3133
- success: true,
3134
- settings: {
3135
- trajectories: {
3136
- storeInRepo: shouldStoreInRepo(),
3137
- storageLocation: getTrajectoriesStorageDescription(),
3138
- description: 'Trajectories record the journey of agent work using the PDERO paradigm (Plan, Design, Execute, Review, Observe). They capture decisions, phase transitions, and retrospectives.',
3139
- benefits: [
3140
- 'Track why decisions were made, not just what was built',
3141
- 'Enable session recovery when agents crash or context is lost',
3142
- 'Provide learning data for future agents working on similar tasks',
3143
- 'Create an audit trail of agent work for review',
3144
- ],
3145
- learnMore: 'https://pdero.com',
3146
- 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.',
3147
- },
3148
- },
3149
- config,
3150
- });
3151
- }
3152
- catch (err) {
3153
- console.error('[api] Settings error:', err);
3154
- res.status(500).json({
3155
- success: false,
3156
- error: err.message,
3157
- });
3158
- }
3159
- });
3160
- /**
3161
- * GET /api/settings/trajectory - Get trajectory storage settings
3162
- */
3163
- app.get('/api/settings/trajectory', async (_req, res) => {
3164
- try {
3165
- const { readRelayConfig, shouldStoreInRepo, getTrajectoriesStorageDescription } = await import('../trajectory/config.js');
3166
- const config = readRelayConfig();
3167
- res.json({
3168
- success: true,
3169
- settings: {
3170
- storeInRepo: shouldStoreInRepo(),
3171
- storageLocation: getTrajectoriesStorageDescription(),
3172
- },
3173
- config: config.trajectories || {},
3174
- // Documentation for the UI
3175
- documentation: {
3176
- title: 'Trajectory Storage',
3177
- description: 'Trajectories record the journey of agent work using the PDERO paradigm (Plan, Design, Execute, Review, Observe).',
3178
- 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.',
3179
- benefits: [
3180
- 'Understand agent decision-making for code review',
3181
- 'Enable session recovery if agents crash',
3182
- 'Train future agents on your codebase patterns',
3183
- 'Create audit trails of AI work',
3184
- ],
3185
- 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/).',
3186
- learnMore: 'https://pdero.com',
3187
- },
3188
- });
3189
- }
3190
- catch (err) {
3191
- console.error('[api] Settings trajectory error:', err);
3192
- res.status(500).json({
3193
- success: false,
3194
- error: err.message,
3195
- });
3196
- }
3197
- });
3198
- /**
3199
- * PUT /api/settings/trajectory - Update trajectory storage settings
3200
- *
3201
- * Body: { storeInRepo: boolean }
3202
- *
3203
- * This writes to .relay/config.json in the project root
3204
- */
3205
- app.put('/api/settings/trajectory', async (req, res) => {
3206
- try {
3207
- const { storeInRepo } = req.body;
3208
- if (typeof storeInRepo !== 'boolean') {
3209
- return res.status(400).json({
3210
- success: false,
3211
- error: 'storeInRepo must be a boolean',
3212
- });
3213
- }
3214
- const { getRelayConfigPath, readRelayConfig } = await import('../trajectory/config.js');
3215
- const { getProjectPaths } = await import('../utils/project-namespace.js');
3216
- const { projectRoot: _projectRoot } = getProjectPaths();
3217
- // Read existing config
3218
- const config = readRelayConfig();
3219
- // Update trajectory settings
3220
- config.trajectories = {
3221
- ...config.trajectories,
3222
- storeInRepo,
3223
- };
3224
- // Ensure .relay directory exists
3225
- const configPath = getRelayConfigPath();
3226
- const configDir = path.dirname(configPath);
3227
- if (!fs.existsSync(configDir)) {
3228
- fs.mkdirSync(configDir, { recursive: true });
3229
- }
3230
- // Write updated config
3231
- fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
3232
- res.json({
3233
- success: true,
3234
- settings: {
3235
- storeInRepo,
3236
- storageLocation: storeInRepo ? 'repo (.trajectories/)' : 'user (~/.config/agent-relay/trajectories/)',
3237
- },
3238
- });
3239
- }
3240
- catch (err) {
3241
- console.error('[api] Settings trajectory update error:', err);
3242
- res.status(500).json({
3243
- success: false,
3244
- error: err.message,
3245
- });
3246
- }
3247
- });
3248
- const decisions = new Map();
3249
- /**
3250
- * GET /api/decisions - List all pending decisions
3251
- */
3252
- app.get('/api/decisions', (_req, res) => {
3253
- const allDecisions = Array.from(decisions.values())
3254
- .sort((a, b) => {
3255
- const urgencyOrder = { critical: 0, high: 1, medium: 2, low: 3 };
3256
- return urgencyOrder[a.urgency] - urgencyOrder[b.urgency];
3257
- });
3258
- res.json({ success: true, decisions: allDecisions });
3259
- });
3260
- /**
3261
- * POST /api/decisions - Create a new decision request
3262
- * Body: { agentName, title, description, options?, urgency, category, expiresAt?, context? }
3263
- */
3264
- app.post('/api/decisions', (req, res) => {
3265
- const { agentName, title, description, options, urgency, category, expiresAt, context } = req.body;
3266
- if (!agentName || !title || !urgency || !category) {
3267
- return res.status(400).json({
3268
- success: false,
3269
- error: 'Missing required fields: agentName, title, urgency, category',
3270
- });
3271
- }
3272
- const decision = {
3273
- id: `decision-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
3274
- agentName,
3275
- title,
3276
- description: description || '',
3277
- options,
3278
- urgency,
3279
- category,
3280
- createdAt: new Date().toISOString(),
3281
- expiresAt,
3282
- context,
3283
- };
3284
- decisions.set(decision.id, decision);
3285
- // Broadcast to WebSocket clients
3286
- broadcastData().catch(() => { });
3287
- res.json({ success: true, decision });
3288
- });
3289
- /**
3290
- * POST /api/decisions/:id/approve - Approve/resolve a decision
3291
- * Body: { optionId?: string, response?: string }
3292
- */
3293
- app.post('/api/decisions/:id/approve', async (req, res) => {
3294
- const { id } = req.params;
3295
- const { optionId, response } = req.body;
3296
- const decision = decisions.get(id);
3297
- if (!decision) {
3298
- return res.status(404).json({ success: false, error: 'Decision not found' });
3299
- }
3300
- // Send response to the agent via relay
3301
- const agentName = decision.agentName;
3302
- let responseMessage = `DECISION APPROVED: ${decision.title}`;
3303
- if (optionId && decision.options) {
3304
- const option = decision.options.find(o => o.id === optionId);
3305
- if (option) {
3306
- responseMessage += `\nSelected: ${option.label}`;
3307
- }
3308
- }
3309
- if (response) {
3310
- responseMessage += `\nResponse: ${response}`;
3311
- }
3312
- // Try to send message to agent
3313
- try {
3314
- const client = await getRelayClient('Dashboard');
3315
- if (client) {
3316
- await client.sendMessage(agentName, responseMessage, 'message');
3317
- }
3318
- }
3319
- catch (err) {
3320
- console.warn('[api] Could not send decision response to agent:', err);
3321
- }
3322
- decisions.delete(id);
3323
- broadcastData().catch(() => { });
3324
- res.json({ success: true, message: 'Decision approved' });
3325
- });
3326
- /**
3327
- * POST /api/decisions/:id/reject - Reject a decision
3328
- * Body: { reason?: string }
3329
- */
3330
- app.post('/api/decisions/:id/reject', async (req, res) => {
3331
- const { id } = req.params;
3332
- const { reason } = req.body;
3333
- const decision = decisions.get(id);
3334
- if (!decision) {
3335
- return res.status(404).json({ success: false, error: 'Decision not found' });
3336
- }
3337
- // Send rejection to the agent
3338
- const agentName = decision.agentName;
3339
- let responseMessage = `DECISION REJECTED: ${decision.title}`;
3340
- if (reason) {
3341
- responseMessage += `\nReason: ${reason}`;
3342
- }
3343
- try {
3344
- const client = await getRelayClient('Dashboard');
3345
- if (client) {
3346
- await client.sendMessage(agentName, responseMessage, 'message');
3347
- }
3348
- }
3349
- catch (err) {
3350
- console.warn('[api] Could not send decision rejection to agent:', err);
3351
- }
3352
- decisions.delete(id);
3353
- broadcastData().catch(() => { });
3354
- res.json({ success: true, message: 'Decision rejected' });
3355
- });
3356
- /**
3357
- * DELETE /api/decisions/:id - Delete/dismiss a decision
3358
- */
3359
- app.delete('/api/decisions/:id', (_req, res) => {
3360
- const { id } = _req.params;
3361
- if (!decisions.has(id)) {
3362
- return res.status(404).json({ success: false, error: 'Decision not found' });
3363
- }
3364
- decisions.delete(id);
3365
- broadcastData().catch(() => { });
3366
- res.json({ success: true, message: 'Decision dismissed' });
3367
- });
3368
- /**
3369
- * GET /api/fleet/servers - Get fleet server overview
3370
- * Returns local daemon info + any connected bridge servers
3371
- * Note: When bridge is active, local agents are already included in bridge project agents,
3372
- * so we don't add a separate "Local Daemon" entry to avoid double-counting.
3373
- */
3374
- app.get('/api/fleet/servers', async (_req, res) => {
3375
- const servers = [];
3376
- const localAgents = spawner?.getActiveWorkers() || [];
3377
- const agentStatuses = await loadAgentStatuses();
3378
- let hasBridgeProjects = false;
3379
- // Check for bridge connections first
3380
- const bridgeStatePath = path.join(dataDir, 'bridge-state.json');
3381
- if (fs.existsSync(bridgeStatePath)) {
3382
- try {
3383
- const bridgeState = JSON.parse(fs.readFileSync(bridgeStatePath, 'utf-8'));
3384
- if (bridgeState.projects && bridgeState.projects.length > 0) {
3385
- hasBridgeProjects = true;
3386
- for (const project of bridgeState.projects) {
3387
- // Enrich with actual online agents from agents.json (same logic as getBridgeData)
3388
- // This fixes the bug where stale agents were counted
3389
- let projectAgents = [];
3390
- if (project.path) {
3391
- const projectHash = crypto.createHash('sha256').update(project.path).digest('hex').slice(0, 12);
3392
- const projectDataDir = path.join(path.dirname(dataDir), projectHash);
3393
- const projectTeamDir = path.join(projectDataDir, 'team');
3394
- const agentsPath = path.join(projectTeamDir, 'agents.json');
3395
- if (fs.existsSync(agentsPath)) {
3396
- try {
3397
- const agentsData = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));
3398
- if (agentsData.agents && Array.isArray(agentsData.agents)) {
3399
- // Filter to only show online agents (seen within 30 seconds)
3400
- const thirtySecondsAgo = Date.now() - 30 * 1000;
3401
- projectAgents = agentsData.agents
3402
- .filter((a) => {
3403
- if (!a.lastSeen)
3404
- return false;
3405
- return new Date(a.lastSeen).getTime() > thirtySecondsAgo;
3406
- })
3407
- .map((a) => ({
3408
- name: a.name,
3409
- status: 'online',
3410
- }));
3411
- }
3412
- }
3413
- catch (e) {
3414
- console.warn(`[api] Failed to read agents for ${project.path}:`, e);
3415
- }
3416
- }
3417
- }
3418
- servers.push({
3419
- id: project.id,
3420
- name: project.name || project.path.split('/').pop() || project.id,
3421
- status: project.connected ? 'healthy' : 'offline',
3422
- agents: projectAgents,
3423
- cpuUsage: 0,
3424
- memoryUsage: 0,
3425
- activeConnections: project.connected ? 1 : 0,
3426
- uptime: 0,
3427
- lastHeartbeat: project.lastSeen || new Date().toISOString(),
3428
- });
3429
- }
3430
- }
3431
- }
3432
- catch (err) {
3433
- console.warn('[api] Failed to read bridge state:', err);
3434
- }
3435
- }
3436
- // Only add local daemon entry if we don't have bridge projects
3437
- // (otherwise local agents are already counted in the bridge project)
3438
- if (!hasBridgeProjects) {
3439
- servers.push({
3440
- id: 'local',
3441
- name: 'Local Daemon',
3442
- status: 'healthy',
3443
- agents: localAgents.map(a => ({
3444
- name: a.name,
3445
- status: agentStatuses[a.name]?.status || 'unknown',
3446
- })),
3447
- cpuUsage: Math.random() * 30, // Mock - would come from actual metrics
3448
- memoryUsage: Math.random() * 50,
3449
- activeConnections: wss.clients.size,
3450
- uptime: process.uptime(),
3451
- lastHeartbeat: new Date().toISOString(),
3452
- });
3453
- }
3454
- res.json({ success: true, servers });
3455
- });
3456
- /**
3457
- * GET /api/fleet/stats - Get aggregate fleet statistics
3458
- */
3459
- app.get('/api/fleet/stats', async (_req, res) => {
3460
- const localAgents = spawner?.getActiveWorkers() || [];
3461
- const agentStatuses = await loadAgentStatuses();
3462
- const totalAgents = localAgents.length;
3463
- let onlineAgents = 0;
3464
- let busyAgents = 0;
3465
- for (const agent of localAgents) {
3466
- const status = agentStatuses[agent.name]?.status;
3467
- if (status === 'online')
3468
- onlineAgents++;
3469
- if (status === 'busy')
3470
- busyAgents++;
3471
- }
3472
- res.json({
3473
- success: true,
3474
- stats: {
3475
- totalAgents,
3476
- onlineAgents,
3477
- busyAgents,
3478
- pendingDecisions: decisions.size,
3479
- activeTasks: Array.from(tasks.values()).filter(t => t.status === 'assigned' || t.status === 'in_progress').length,
3480
- },
3481
- });
3482
- });
3483
- const tasks = new Map();
3484
- /**
3485
- * GET /api/tasks - List all tasks
3486
- */
3487
- app.get('/api/tasks', (req, res) => {
3488
- const status = req.query.status;
3489
- const agentName = req.query.agent;
3490
- let allTasks = Array.from(tasks.values());
3491
- if (status) {
3492
- allTasks = allTasks.filter(t => t.status === status);
3493
- }
3494
- if (agentName) {
3495
- allTasks = allTasks.filter(t => t.agentName === agentName);
3496
- }
3497
- // Sort by priority and creation time
3498
- allTasks.sort((a, b) => {
3499
- const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
3500
- const priorityDiff = priorityOrder[a.priority] - priorityOrder[b.priority];
3501
- if (priorityDiff !== 0)
3502
- return priorityDiff;
3503
- return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
3504
- });
3505
- res.json({ success: true, tasks: allTasks });
3506
- });
3507
- /**
3508
- * POST /api/tasks - Create and assign a task
3509
- * Body: { agentName, title, description, priority }
3510
- */
3511
- app.post('/api/tasks', async (req, res) => {
3512
- const { agentName, title, description, priority } = req.body;
3513
- if (!agentName || !title || !priority) {
3514
- return res.status(400).json({
3515
- success: false,
3516
- error: 'Missing required fields: agentName, title, priority',
3517
- });
3518
- }
3519
- const task = {
3520
- id: `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
3521
- agentName,
3522
- title,
3523
- description: description || '',
3524
- priority,
3525
- status: 'assigned',
3526
- createdAt: new Date().toISOString(),
3527
- assignedAt: new Date().toISOString(),
3528
- };
3529
- tasks.set(task.id, task);
3530
- // Send task to agent via relay
3531
- try {
3532
- const client = await getRelayClient('Dashboard');
3533
- if (client) {
3534
- const taskMessage = `TASK ASSIGNED [${priority.toUpperCase()}]: ${title}\n\n${description || 'No additional details.'}`;
3535
- await client.sendMessage(agentName, taskMessage, 'message');
3536
- }
3537
- }
3538
- catch (err) {
3539
- console.warn('[api] Could not send task to agent:', err);
3540
- }
3541
- broadcastData().catch(() => { });
3542
- res.json({ success: true, task });
3543
- });
3544
- /**
3545
- * PATCH /api/tasks/:id - Update task status
3546
- * Body: { status, result? }
3547
- */
3548
- app.patch('/api/tasks/:id', (req, res) => {
3549
- const { id } = req.params;
3550
- const { status, result } = req.body;
3551
- const task = tasks.get(id);
3552
- if (!task) {
3553
- return res.status(404).json({ success: false, error: 'Task not found' });
3554
- }
3555
- if (status) {
3556
- task.status = status;
3557
- if (status === 'completed' || status === 'failed') {
3558
- task.completedAt = new Date().toISOString();
3559
- }
3560
- }
3561
- if (result !== undefined) {
3562
- task.result = result;
3563
- }
3564
- tasks.set(id, task);
3565
- broadcastData().catch(() => { });
3566
- res.json({ success: true, task });
3567
- });
3568
- /**
3569
- * DELETE /api/tasks/:id - Cancel/delete a task
3570
- */
3571
- app.delete('/api/tasks/:id', async (req, res) => {
3572
- const { id } = req.params;
3573
- const task = tasks.get(id);
3574
- if (!task) {
3575
- return res.status(404).json({ success: false, error: 'Task not found' });
3576
- }
3577
- // Notify agent of cancellation if task is still active
3578
- if (task.status === 'pending' || task.status === 'assigned' || task.status === 'in_progress') {
3579
- try {
3580
- const client = await getRelayClient('Dashboard');
3581
- if (client) {
3582
- await client.sendMessage(task.agentName, `TASK CANCELLED: ${task.title}`, 'message');
3583
- }
3584
- }
3585
- catch (err) {
3586
- console.warn('[api] Could not send task cancellation to agent:', err);
3587
- }
3588
- }
3589
- tasks.delete(id);
3590
- broadcastData().catch(() => { });
3591
- res.json({ success: true, message: 'Task cancelled' });
3592
- });
3593
- // ===== Beads Integration API =====
3594
- /**
3595
- * POST /api/beads - Create a bead (task/issue) via the bd CLI
3596
- */
3597
- app.post('/api/beads', async (req, res) => {
3598
- const { title, assignee, priority, type, description: _description } = req.body;
3599
- if (!title || typeof title !== 'string') {
3600
- return res.status(400).json({ success: false, error: 'Title is required' });
3601
- }
3602
- // Build bd create command
3603
- const args = ['create', `--title="${title.replace(/"/g, '\\"')}"`];
3604
- if (assignee) {
3605
- args.push(`--assignee=${assignee}`);
3606
- }
3607
- if (priority !== undefined && priority !== null) {
3608
- args.push(`--priority=${priority}`);
3609
- }
3610
- if (type && ['task', 'bug', 'feature'].includes(type)) {
3611
- args.push(`--type=${type}`);
3612
- }
3613
- const cmd = `bd ${args.join(' ')}`;
3614
- console.log('[api/beads] Creating bead:', cmd);
3615
- // Execute bd create command
3616
- exec(cmd, { cwd: dataDir }, (error, stdout, stderr) => {
3617
- if (error) {
3618
- console.error('[api/beads] bd create failed:', stderr || error.message);
3619
- return res.status(500).json({
3620
- success: false,
3621
- error: stderr || error.message || 'Failed to create bead',
3622
- });
3623
- }
3624
- // Parse bead ID from output (bd create outputs the ID)
3625
- const output = stdout.trim();
3626
- // bd create typically outputs: "Created beads-xxx: title"
3627
- const idMatch = output.match(/Created\s+(beads-\w+)/i) || output.match(/(beads-\w+)/);
3628
- const beadId = idMatch ? idMatch[1] : `beads-${Date.now()}`;
3629
- console.log('[api/beads] Created bead:', beadId);
3630
- res.json({
3631
- success: true,
3632
- bead: {
3633
- id: beadId,
3634
- title,
3635
- assignee,
3636
- priority,
3637
- type: type || 'task',
3638
- },
3639
- });
3640
- });
3641
- });
3642
- /**
3643
- * POST /api/relay/send - Send a relay message to an agent
3644
- */
3645
- app.post('/api/relay/send', async (req, res) => {
3646
- const { to, content, thread } = req.body;
3647
- if (!to || typeof to !== 'string') {
3648
- return res.status(400).json({ success: false, error: 'Recipient (to) is required' });
3649
- }
3650
- if (!content || typeof content !== 'string') {
3651
- return res.status(400).json({ success: false, error: 'Message content is required' });
3652
- }
3653
- try {
3654
- const client = await getRelayClient('Dashboard');
3655
- if (!client) {
3656
- return res.status(503).json({
3657
- success: false,
3658
- error: 'Relay client not available',
3659
- });
3660
- }
3661
- const messageId = await client.sendMessage(to, content, thread ? 'message' : 'message');
3662
- console.log('[api/relay/send] Sent message to', to, ':', messageId);
3663
- res.json({
3664
- success: true,
3665
- messageId: messageId || `msg-${Date.now()}`,
3666
- });
3667
- }
3668
- catch (err) {
3669
- console.error('[api/relay/send] Failed to send message:', err);
3670
- res.status(500).json({
3671
- success: false,
3672
- error: err instanceof Error ? err.message : 'Failed to send message',
3673
- });
3674
- }
3675
- });
3676
- // Helper to load agent statuses
3677
- async function loadAgentStatuses() {
3678
- const agentsFile = path.join(dataDir, 'agents.json');
3679
- try {
3680
- if (fs.existsSync(agentsFile)) {
3681
- const data = JSON.parse(fs.readFileSync(agentsFile, 'utf-8'));
3682
- const result = {};
3683
- for (const agent of data.agents || []) {
3684
- result[agent.name] = { status: agent.status || 'offline' };
3685
- }
3686
- return result;
3687
- }
3688
- }
3689
- catch (err) {
3690
- console.warn('[api] Failed to load agent statuses:', err);
3691
- }
3692
- return {};
3693
- }
3694
- // Watch for changes
3695
- if (storage) {
3696
- setInterval(() => {
3697
- broadcastData().catch((err) => console.error('Broadcast failed', err));
3698
- broadcastBridgeData().catch((err) => console.error('Bridge broadcast failed', err));
3699
- }, 1000);
3700
- }
3701
- else {
3702
- let fsWait = null;
3703
- let bridgeFsWait = null;
3704
- try {
3705
- if (fs.existsSync(dataDir)) {
3706
- console.log(`Watching ${dataDir} for changes...`);
3707
- fs.watch(dataDir, { recursive: true }, (eventType, filename) => {
3708
- if (filename && (filename.endsWith('inbox.md') || filename.endsWith('team.json') || filename.endsWith('agents.json') || filename.endsWith('processing-state.json'))) {
3709
- // Debounce
3710
- if (fsWait)
3711
- return;
3712
- fsWait = setTimeout(() => {
3713
- fsWait = null;
3714
- broadcastData();
3715
- }, 100);
3716
- }
3717
- // Watch for bridge state changes
3718
- if (filename && filename.endsWith('bridge-state.json')) {
3719
- if (bridgeFsWait)
3720
- return;
3721
- bridgeFsWait = setTimeout(() => {
3722
- bridgeFsWait = null;
3723
- broadcastBridgeData();
3724
- }, 100);
3725
- }
3726
- });
3727
- }
3728
- else {
3729
- console.warn(`Data directory ${dataDir} does not exist yet.`);
3730
- }
3731
- }
3732
- catch (e) {
3733
- console.error('Watch failed:', e);
3734
- }
3735
- }
3736
- // Try to find an available port, starting from the requested port
3737
- const findAvailablePort = async (startPort, maxAttempts = 10) => {
3738
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
3739
- const portToTry = startPort + attempt;
3740
- const isAvailable = await new Promise((resolve) => {
3741
- const testServer = http.createServer();
3742
- testServer.once('error', () => resolve(false));
3743
- testServer.once('listening', () => {
3744
- testServer.close();
3745
- resolve(true);
3746
- });
3747
- testServer.listen(portToTry);
3748
- });
3749
- if (isAvailable) {
3750
- return portToTry;
3751
- }
3752
- console.log(`Port ${portToTry} in use, trying ${portToTry + 1}...`);
3753
- }
3754
- throw new Error(`Could not find available port after trying ${startPort}-${startPort + maxAttempts - 1}`);
3755
- };
3756
- const availablePort = await findAvailablePort(port);
3757
- if (availablePort !== port) {
3758
- console.log(`Requested dashboard port ${port} is busy; switching to ${availablePort}.`);
3759
- }
3760
- return new Promise((resolve, reject) => {
3761
- server.listen(availablePort, () => {
3762
- console.log(`Dashboard running at http://localhost:${availablePort}`);
3763
- console.log(`Monitoring: ${dataDir}`);
3764
- // Set the dashboard port on spawner so spawned agents can use the API for nested spawns
3765
- if (spawner) {
3766
- spawner.setDashboardPort(availablePort);
3767
- }
3768
- resolve(availablePort);
3769
- });
3770
- server.on('error', (err) => {
3771
- console.error('Server error:', err);
3772
- reject(err);
3773
- });
3774
- });
3775
- }
3776
- //# sourceMappingURL=server.js.map