Elffuss BraidHub

kikocis/clonagent public

main · 2.9 KiBRawPermalink
1// Per-user chat session persistence (data/chat-sessions.json).
2// Each session: { id, userId, title, messages, createdAt, updatedAt }.
3const fs = require('fs');
4const path = require('path');
5const crypto = require('crypto');
6
7const FILE = path.resolve(__dirname, '..', 'data', 'chat-sessions.json');
8const MAX_SESSIONS_PER_USER = 100;
9const MAX_MESSAGES_PER_SESSION = 200;
10
11function readAll() {
12 try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); }
13 catch { return []; }
14}
15
16function writeAll(list) {
17 fs.mkdirSync(path.dirname(FILE), { recursive: true });
18 fs.writeFileSync(FILE, JSON.stringify(list, null, 2));
19}
20
21function newId() { return crypto.randomBytes(8).toString('hex'); }
22
23function listSessions(userId) {
24 return readAll()
25 .filter(s => s.userId === userId)
26 .sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''))
27 .map(s => ({
28 id: s.id, title: s.title,
29 messageCount: (s.messages || []).length,
30 createdAt: s.createdAt, updatedAt: s.updatedAt,
31 }));
32}
33
34function getSession(id, userId) {
35 return readAll().find(s => s.id === id && s.userId === userId) || null;
36}
37
38function deriveTitle(messages) {
39 const firstUser = messages.find(m => m.role === 'user');
40 if (!firstUser) return 'Nueva conversación';
41 const text = (firstUser.content || '').replace(/\s+/g, ' ').trim();
42 return text.slice(0, 60) + (text.length > 60 ? '…' : '');
43}
44
45function saveSession({ id, userId, messages, title }) {
46 const now = new Date().toISOString();
47 const all = readAll();
48 const i = all.findIndex(s => s.id === id);
49 // Keep last N messages only
50 const trimmed = messages.slice(-MAX_MESSAGES_PER_SESSION);
51 let session;
52 if (i >= 0) {
53 session = {
54 ...all[i],
55 messages: trimmed,
56 title: title || all[i].title || deriveTitle(trimmed),
57 updatedAt: now,
58 };
59 all[i] = session;
60 } else {
61 session = {
62 id: id || newId(),
63 userId,
64 title: title || deriveTitle(trimmed),
65 messages: trimmed,
66 createdAt: now,
67 updatedAt: now,
68 };
69 all.unshift(session);
70 }
71 // Cap per-user sessions
72 const keep = new Set();
73 const userSessions = all.filter(s => s.userId === userId)
74 .sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''))
75 .slice(0, MAX_SESSIONS_PER_USER)
76 .map(s => s.id);
77 userSessions.forEach(x => keep.add(x));
78 const pruned = all.filter(s => s.userId !== userId || keep.has(s.id));
79 writeAll(pruned);
80 return session;
81}
82
83function deleteSession(id, userId) {
84 const all = readAll().filter(s => !(s.id === id && s.userId === userId));
85 writeAll(all);
86}
87
88function renameSession(id, userId, title) {
89 const all = readAll();
90 const i = all.findIndex(s => s.id === id && s.userId === userId);
91 if (i < 0) return null;
92 all[i] = { ...all[i], title, updatedAt: new Date().toISOString() };
93 writeAll(all);
94 return all[i];
95}
96
97module.exports = {
98 newId, listSessions, getSession, saveSession, deleteSession, renameSession,
99};