| 1 | // Maps an email thread (per agent) to its Claude session id, so follow-up |
| 2 | // emails in the same conversation continue the same agent session instead of |
| 3 | // spawning a fresh one. Persisted in data/email-threads.json. |
| 4 | const fs = require('fs'); |
| 5 | const path = require('path'); |
| 6 | |
| 7 | const FILE = path.resolve(__dirname, '..', 'data', 'email-threads.json'); |
| 8 | |
| 9 | function readAll() { |
| 10 | try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } |
| 11 | catch { return {}; } |
| 12 | } |
| 13 | function writeAll(map) { |
| 14 | fs.mkdirSync(path.dirname(FILE), { recursive: true }); |
| 15 | fs.writeFileSync(FILE, JSON.stringify(map, null, 2)); |
| 16 | } |
| 17 | |
| 18 | function key(agentId, threadId) { |
| 19 | return `${agentId}::${threadId}`; |
| 20 | } |
| 21 | |
| 22 | function getSession(agentId, threadId) { |
| 23 | return readAll()[key(agentId, threadId)] || null; |
| 24 | } |
| 25 | |
| 26 | function rememberSession(agentId, threadId, sessionId) { |
| 27 | const all = readAll(); |
| 28 | all[key(agentId, threadId)] = { |
| 29 | sessionId, |
| 30 | threadId, |
| 31 | agentId, |
| 32 | updatedAt: new Date().toISOString(), |
| 33 | }; |
| 34 | writeAll(all); |
| 35 | } |
| 36 | |
| 37 | function forgetSession(agentId, threadId) { |
| 38 | const all = readAll(); |
| 39 | delete all[key(agentId, threadId)]; |
| 40 | writeAll(all); |
| 41 | } |
| 42 | |
| 43 | // Called by activity route when Claude's init event arrives with the real session UUID. |
| 44 | // Finds the thread entry that was launched with relaySessionId and updates it |
| 45 | // with the Claude UUID so future --resume calls use a valid UUID. |
| 46 | function updateClaudeSessionId(relaySessionId, claudeSessionId) { |
| 47 | const all = readAll(); |
| 48 | for (const entry of Object.values(all)) { |
| 49 | if (entry.sessionId === relaySessionId) { |
| 50 | entry.claudeSessionId = claudeSessionId; |
| 51 | entry.updatedAt = new Date().toISOString(); |
| 52 | writeAll(all); |
| 53 | return true; |
| 54 | } |
| 55 | } |
| 56 | return false; |
| 57 | } |
| 58 | |
| 59 | module.exports = { getSession, rememberSession, forgetSession, updateClaudeSessionId }; |