agent-relay 1.3.2 → 1.3.3

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