| 1 | // Receives live events from host-relay and broadcasts to clients via SSE. |
| 2 | // To wire this up, run host-relay with CONSOLE_URL=http://localhost:3300 |
| 3 | // (or run a second relay just for ClonAgent on a different port). |
| 4 | const express = require('express'); |
| 5 | const fs = require('fs'); |
| 6 | const path = require('path'); |
| 7 | const threadStore = require('../lib/email-thread-store'); |
| 8 | const agentSessions = require('../lib/agent-sessions'); |
| 9 | // Lazy-require to avoid circular deps — poller requires relay-client which requires this |
| 10 | let poller = null; |
| 11 | function getPoller() { if (!poller) poller = require('../lib/gmail-poller'); return poller; } |
| 12 | |
| 13 | const router = express.Router(); |
| 14 | const DATA_DIR = path.resolve(__dirname, '..', 'data'); |
| 15 | const SESSIONS_FILE = path.join(DATA_DIR, 'activity-sessions.json'); |
| 16 | const MAX_SESSIONS = 100; |
| 17 | const MAX_EVENTS_PER_SESSION = 500; |
| 18 | |
| 19 | const subscribers = new Map(); // sessionId|"*" -> Set<res> |
| 20 | |
| 21 | function readSessions() { |
| 22 | try { return JSON.parse(fs.readFileSync(SESSIONS_FILE, 'utf8')); } |
| 23 | catch { return []; } |
| 24 | } |
| 25 | function writeSessions(s) { |
| 26 | fs.mkdirSync(DATA_DIR, { recursive: true }); |
| 27 | fs.writeFileSync(SESSIONS_FILE, JSON.stringify(s.slice(0, MAX_SESSIONS), null, 2)); |
| 28 | } |
| 29 | function upsertSession(session) { |
| 30 | const all = readSessions(); |
| 31 | const i = all.findIndex(s => s.id === session.id); |
| 32 | const now = new Date().toISOString(); |
| 33 | const merged = { |
| 34 | status: 'running', events: [], |
| 35 | ...(i >= 0 ? all[i] : {}), |
| 36 | ...session, |
| 37 | created_at: (i >= 0 ? all[i].created_at : null) || session.created_at || now, |
| 38 | updated_at: now, |
| 39 | }; |
| 40 | if (i >= 0) all[i] = merged; else all.unshift(merged); |
| 41 | writeSessions(all); |
| 42 | return merged; |
| 43 | } |
| 44 | function appendEvent(sessionId, event) { |
| 45 | const all = readSessions(); |
| 46 | const i = all.findIndex(s => s.id === sessionId); |
| 47 | if (i < 0) return null; |
| 48 | const ev = { ...event, received_at: new Date().toISOString() }; |
| 49 | all[i].events = [...(all[i].events || []), ev].slice(-MAX_EVENTS_PER_SESSION); |
| 50 | all[i].updated_at = ev.received_at; |
| 51 | writeSessions(all); |
| 52 | return ev; |
| 53 | } |
| 54 | function broadcast(sessionId, payload) { |
| 55 | const data = `data: ${JSON.stringify(payload)}\n\n`; |
| 56 | for (const key of [sessionId, '*']) { |
| 57 | const subs = subscribers.get(key); |
| 58 | if (!subs) continue; |
| 59 | for (const res of subs) { try { res.write(data); } catch {} } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | // ─── List sessions / get one ─────────────────────────────────────────────── |
| 64 | router.get('/', (req, res) => { |
| 65 | const all = readSessions(); |
| 66 | const summary = all.map(s => ({ |
| 67 | id: s.id, |
| 68 | agentId: s.agentId || s.agent_id, |
| 69 | status: s.status, |
| 70 | description: s.description || s.task?.slice(0, 100) || '', |
| 71 | created_at: s.created_at, |
| 72 | updated_at: s.updated_at, |
| 73 | eventCount: (s.events || []).length, |
| 74 | })); |
| 75 | res.json(summary); |
| 76 | }); |
| 77 | |
| 78 | router.get('/:id', (req, res) => { |
| 79 | const s = readSessions().find(x => x.id === req.params.id); |
| 80 | if (!s) return res.status(404).json({ error: 'not found' }); |
| 81 | res.json(s); |
| 82 | }); |
| 83 | |
| 84 | // ─── Ingest endpoints (called by host-relay) ─────────────────────────────── |
| 85 | router.post('/sessions', (req, res) => { |
| 86 | const session = upsertSession(req.body); |
| 87 | broadcast('*', { type: 'session:upsert', session: { id: session.id, status: session.status } }); |
| 88 | res.json({ ok: true, session }); |
| 89 | }); |
| 90 | |
| 91 | router.post('/sessions/:id/events', (req, res) => { |
| 92 | const event = appendEvent(req.params.id, req.body); |
| 93 | if (!event) return res.status(404).json({ error: 'session not found' }); |
| 94 | |
| 95 | const body = req.body || {}; |
| 96 | const relayId = req.params.id; |
| 97 | |
| 98 | // Capture real Claude session UUID from init event → enables proper --resume |
| 99 | if (body.type === 'system' && body.subtype === 'init' && body.session_id) { |
| 100 | threadStore.updateClaudeSessionId(relayId, body.session_id); |
| 101 | // Also store on the scheduler/executor session record |
| 102 | const sessData = require('../lib/agent-sessions'); |
| 103 | // Find which agent owns this relay session and which role |
| 104 | try { |
| 105 | const all = JSON.parse(require('fs').readFileSync( |
| 106 | require('path').resolve(__dirname, '..', 'data', 'agent-sessions.json'), 'utf8')); |
| 107 | for (const [agentId, sess] of Object.entries(all)) { |
| 108 | if (sess.schedulerRelayId === relayId) |
| 109 | agentSessions.set(agentId, { schedulerClaudeId: body.session_id }); |
| 110 | if (sess.executorRelayId === relayId) |
| 111 | agentSessions.set(agentId, { executorClaudeId: body.session_id }); |
| 112 | } |
| 113 | } catch { /* no sessions file yet */ } |
| 114 | } |
| 115 | |
| 116 | // Extract cost from Claude CLI result event |
| 117 | if (body.type === 'result' && body.cost_usd != null) { |
| 118 | const all = readSessions(); |
| 119 | const i = all.findIndex(s => s.id === relayId); |
| 120 | if (i >= 0) { |
| 121 | all[i].cost_usd = parseFloat(((all[i].cost_usd || 0) + Number(body.cost_usd)).toFixed(6)); |
| 122 | all[i].status = body.subtype === 'error' ? 'error' : 'done'; |
| 123 | all[i].updated_at = new Date().toISOString(); |
| 124 | writeSessions(all); |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | // When session ends, mark the role as idle so the next email/task can launch |
| 129 | if (body.type === 'session_end' || body.type === 'session_error') { |
| 130 | getPoller().onSessionEnd(relayId); |
| 131 | } |
| 132 | |
| 133 | broadcast(req.params.id, { type: 'event', sessionId: req.params.id, event }); |
| 134 | broadcast('*', { type: 'event', sessionId: req.params.id, event }); |
| 135 | res.json({ ok: true }); |
| 136 | }); |
| 137 | |
| 138 | router.post('/sessions/:id/status', (req, res) => { |
| 139 | const all = readSessions(); |
| 140 | const i = all.findIndex(s => s.id === req.params.id); |
| 141 | if (i < 0) return res.status(404).json({ error: 'not found' }); |
| 142 | all[i].status = req.body.status || all[i].status; |
| 143 | all[i].updated_at = new Date().toISOString(); |
| 144 | writeSessions(all); |
| 145 | broadcast('*', { type: 'session:status', sessionId: req.params.id, status: all[i].status }); |
| 146 | res.json({ ok: true }); |
| 147 | }); |
| 148 | |
| 149 | // ─── SSE stream ──────────────────────────────────────────────────────────── |
| 150 | router.get('/stream/:id', sse); |
| 151 | router.get('/stream', sse); |
| 152 | |
| 153 | function sse(req, res) { |
| 154 | const key = req.params.id || '*'; |
| 155 | res.set({ |
| 156 | 'Content-Type': 'text/event-stream', |
| 157 | 'Cache-Control': 'no-cache', |
| 158 | Connection: 'keep-alive', |
| 159 | }); |
| 160 | res.write(': connected\n\n'); |
| 161 | if (!subscribers.has(key)) subscribers.set(key, new Set()); |
| 162 | subscribers.get(key).add(res); |
| 163 | const ping = setInterval(() => { try { res.write(': ping\n\n'); } catch {} }, 30000); |
| 164 | req.on('close', () => { clearInterval(ping); subscribers.get(key)?.delete(res); }); |
| 165 | } |
| 166 | |
| 167 | module.exports = router; |