state.js (831B)
1 const fs = require('fs'); 2 const path = require('path'); 3 4 const STATE_DIR = path.join(__dirname, '..', 'data', 'repo', 'conversations'); 5 6 function filePath(userId) { 7 return path.join(STATE_DIR, `${userId}.json`); 8 } 9 10 function load(userId) { 11 const fp = filePath(userId); 12 if (!fs.existsSync(fp)) return []; 13 try { 14 return JSON.parse(fs.readFileSync(fp, 'utf8')); 15 } catch { 16 return []; 17 } 18 } 19 20 function save(userId, history) { 21 fs.mkdirSync(STATE_DIR, { recursive: true }); 22 fs.writeFileSync(filePath(userId), JSON.stringify(history, null, 2), 'utf8'); 23 } 24 25 // Appends a message and persists. Returns the full updated history. 26 function append(userId, role, content) { 27 const history = load(userId); 28 history.push({ role, content }); 29 save(userId, history); 30 return history; 31 } 32 33 module.exports = { load, save, append };