Elffuss BraidHub

kikocis/clonagent public

main · 1.7 KiBRawPermalink
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.
4const fs = require('fs');
5const path = require('path');
6
7const FILE = path.resolve(__dirname, '..', 'data', 'email-threads.json');
8
9function readAll() {
10 try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); }
11 catch { return {}; }
12}
13function writeAll(map) {
14 fs.mkdirSync(path.dirname(FILE), { recursive: true });
15 fs.writeFileSync(FILE, JSON.stringify(map, null, 2));
16}
17
18function key(agentId, threadId) {
19 return `${agentId}::${threadId}`;
20}
21
22function getSession(agentId, threadId) {
23 return readAll()[key(agentId, threadId)] || null;
24}
25
26function 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
37function 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.
46function 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
59module.exports = { getSession, rememberSession, forgetSession, updateClaudeSessionId };