@clawchatsai/connector 0.1.15 → 0.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,107 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { send, sendError, parseBody, uuid } from '../util/http.js';
4
- import { syncThreadUnreadCount } from '../util/helpers.js';
5
- import { cleanGatewaySession } from '../gateway-cleanup.js';
6
-
7
- export class ThreadController {
8
- constructor({ getActiveDb, getWorkspaces, uploadsDir, broadcast }) {
9
- this.getActiveDb = getActiveDb;
10
- this.getWorkspaces = getWorkspaces;
11
- this.uploadsDir = uploadsDir;
12
- this.broadcast = broadcast;
13
- }
14
-
15
- getAll(req, res, params, query) {
16
- const db = this.getActiveDb();
17
- const page = parseInt(query.page || '1', 10);
18
- const limit = Math.min(parseInt(query.limit || '50', 10), 200);
19
- const offset = (page - 1) * limit;
20
- const search = query.search || '';
21
- let threads, total;
22
- if (search) {
23
- try {
24
- const matchingIds = db.prepare(`SELECT DISTINCT m.thread_id FROM messages m JOIN messages_fts ON messages_fts.rowid = m.rowid WHERE messages_fts MATCH ?`).all(search).map(r => r.thread_id);
25
- if (!matchingIds.length) return send(res, 200, { threads: [], total: 0, page });
26
- const ph = matchingIds.map(() => '?').join(',');
27
- total = db.prepare(`SELECT COUNT(*) as c FROM threads WHERE id IN (${ph})`).get(...matchingIds).c;
28
- threads = db.prepare(`SELECT t.*, EXISTS(SELECT 1 FROM messages WHERE thread_id = t.id AND role = 'assistant' AND json_extract(metadata, '$.pending') = 1) as has_pending FROM threads t WHERE t.id IN (${ph}) ORDER BY t.pinned DESC, t.sort_order DESC, t.updated_at DESC LIMIT ? OFFSET ?`).all(...matchingIds, limit, offset);
29
- } catch { return send(res, 200, { threads: [], total: 0, page }); }
30
- } else {
31
- total = db.prepare('SELECT COUNT(*) as c FROM threads').get().c;
32
- threads = db.prepare(`SELECT t.*, EXISTS(SELECT 1 FROM messages WHERE thread_id = t.id AND role = 'assistant' AND json_extract(metadata, '$.pending') = 1) as has_pending FROM threads t ORDER BY t.pinned DESC, t.sort_order DESC, t.updated_at DESC LIMIT ? OFFSET ?`).all(limit, offset);
33
- }
34
- send(res, 200, { threads, total, page });
35
- }
36
-
37
- getUnread(req, res) {
38
- const db = this.getActiveDb();
39
- const threads = db.prepare(`SELECT t.id, t.title, t.unread_count, m.content as lastMessage FROM threads t LEFT JOIN messages m ON m.thread_id = t.id WHERE t.unread_count > 0 AND m.timestamp = (SELECT MAX(timestamp) FROM messages WHERE thread_id = t.id) ORDER BY t.updated_at DESC`).all();
40
- for (const t of threads) t.unreadMessageIds = db.prepare('SELECT message_id FROM unread_messages WHERE thread_id = ?').all(t.id).map(r => r.message_id);
41
- send(res, 200, { threads });
42
- }
43
-
44
- async markRead(req, res, params) {
45
- const { messageIds } = await parseBody(req);
46
- if (!Array.isArray(messageIds) || !messageIds.length) return send(res, 400, { error: 'messageIds array required' });
47
- const db = this.getActiveDb();
48
- const ph = messageIds.map(() => '?').join(',');
49
- db.prepare(`DELETE FROM unread_messages WHERE thread_id = ? AND message_id IN (${ph})`).run(params.id, ...messageIds);
50
- const remaining = syncThreadUnreadCount(db, params.id);
51
- this.broadcast(JSON.stringify({ type: 'clawchats', event: 'unread-update', workspace: this.getWorkspaces().active, threadId: params.id, action: 'read', messageIds, unreadCount: remaining, timestamp: Date.now() }));
52
- send(res, 200, { unread_count: remaining });
53
- }
54
-
55
- async create(req, res) {
56
- const body = await parseBody(req);
57
- const db = this.getActiveDb();
58
- const ws = this.getWorkspaces();
59
- const id = body.id || uuid();
60
- const now = Date.now();
61
- const agent = ws.workspaces[ws.active]?.agent || 'main';
62
- try {
63
- db.prepare('INSERT INTO threads (id, session_key, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?)').run(id, `agent:${agent}:${ws.active}:chat:${id}`, 'New chat', now, now);
64
- } catch (e) {
65
- if (e.message.includes('UNIQUE constraint')) return sendError(res, 409, 'Thread already exists');
66
- throw e;
67
- }
68
- send(res, 201, { thread: db.prepare('SELECT * FROM threads WHERE id = ?').get(id) });
69
- }
70
-
71
- get(req, res, params) {
72
- const thread = this.getActiveDb().prepare('SELECT * FROM threads WHERE id = ?').get(params.id);
73
- if (!thread) return sendError(res, 404, 'Thread not found');
74
- send(res, 200, { thread });
75
- }
76
-
77
- async update(req, res, params) {
78
- const body = await parseBody(req);
79
- const db = this.getActiveDb();
80
- if (!db.prepare('SELECT id FROM threads WHERE id = ?').get(params.id)) return sendError(res, 404, 'Thread not found');
81
- const fields = [], values = [];
82
- for (const [col, val] of [['title', body.title], ['model', body.model], ['last_session_id', body.last_session_id], ['unread_count', body.unread_count]]) {
83
- if (val !== undefined) { fields.push(`${col} = ?`); values.push(val); }
84
- }
85
- if (body.pinned !== undefined) { fields.push('pinned = ?'); values.push(body.pinned ? 1 : 0); }
86
- if (body.pin_order !== undefined) { fields.push('pin_order = ?'); values.push(body.pin_order); }
87
- if (body.sort_order !== undefined) { fields.push('sort_order = ?'); values.push(body.sort_order); }
88
- if (body.metadata !== undefined) { fields.push('metadata = ?'); values.push(typeof body.metadata === 'string' ? body.metadata : JSON.stringify(body.metadata)); }
89
- if (fields.length) {
90
- fields.push('updated_at = ?');
91
- values.push(Date.now(), params.id);
92
- db.prepare(`UPDATE threads SET ${fields.join(', ')} WHERE id = ?`).run(...values);
93
- }
94
- send(res, 200, { thread: db.prepare('SELECT * FROM threads WHERE id = ?').get(params.id) });
95
- }
96
-
97
- delete(req, res, params) {
98
- const db = this.getActiveDb();
99
- const thread = db.prepare('SELECT * FROM threads WHERE id = ?').get(params.id);
100
- if (!thread) return sendError(res, 404, 'Thread not found');
101
- db.prepare('DELETE FROM threads WHERE id = ?').run(params.id);
102
- cleanGatewaySession(thread.session_key); // async, best effort
103
- try { fs.rmSync(path.join(this.uploadsDir, params.id), { recursive: true }); } catch { /* ok */ }
104
- send(res, 200, { ok: true });
105
- }
106
-
107
- }
@@ -1,103 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { send, sendError, parseBody } from '../util/http.js';
4
- import { validateAgent } from '../config.js';
5
- import { cleanGatewaySession, cleanGatewaySessions } from '../gateway-cleanup.js';
6
-
7
- export class WorkspaceController {
8
- constructor({ getDb, closeDb, getWorkspaces, setWorkspaces, dataDir, broadcast }) {
9
- this.getDb = getDb;
10
- this.closeDb = closeDb;
11
- this.getWorkspaces = getWorkspaces;
12
- this.setWorkspaces = setWorkspaces;
13
- this.dataDir = dataDir;
14
- this.broadcast = broadcast;
15
- }
16
-
17
- getAll(req, res) {
18
- const ws = this.getWorkspaces();
19
- const sorted = Object.values(ws.workspaces).sort((a, b) => (a.order ?? 999) - (b.order ?? 999));
20
- for (const workspace of sorted) {
21
- try {
22
- workspace.unread_count = this.getDb(workspace.name).prepare('SELECT COALESCE(SUM(unread_count), 0) as total FROM threads').get().total;
23
- } catch { workspace.unread_count = 0; }
24
- }
25
- send(res, 200, { active: ws.active, workspaces: sorted });
26
- }
27
-
28
- async create(req, res) {
29
- const body = await parseBody(req);
30
- const { name, label } = body;
31
- if (!name || !/^[a-z0-9-]{1,32}$/.test(name)) return sendError(res, 400, 'Name must be [a-z0-9-], 1-32 chars');
32
- const ws = this.getWorkspaces();
33
- if (ws.workspaces[name]) return sendError(res, 409, 'Workspace already exists');
34
- let agent = 'main';
35
- try { agent = validateAgent(body.agent || 'main'); } catch { agent = 'main'; }
36
- ws.workspaces[name] = { name, label: label || name, color: body.color || null, icon: body.icon || null, agent, createdAt: Date.now() };
37
- this.setWorkspaces(ws);
38
- this.getDb(name);
39
- send(res, 201, { workspace: ws.workspaces[name] });
40
- }
41
-
42
- async update(req, res, params) {
43
- const body = await parseBody(req);
44
- const ws = this.getWorkspaces();
45
- if (!ws.workspaces[params.name]) return sendError(res, 404, 'Workspace not found');
46
- if (body.label !== undefined) ws.workspaces[params.name].label = body.label;
47
- if (body.color !== undefined) ws.workspaces[params.name].color = body.color;
48
- if (body.icon !== undefined) ws.workspaces[params.name].icon = body.icon;
49
- if (body.lastThread !== undefined) ws.workspaces[params.name].lastThread = body.lastThread;
50
- let migratedThreads = 0;
51
- if (body.agent !== undefined) {
52
- let newAgent;
53
- try { newAgent = validateAgent(body.agent); } catch (e) { return sendError(res, 400, e.message); }
54
- const oldAgent = ws.workspaces[params.name].agent || 'main';
55
- if (newAgent !== oldAgent) {
56
- const db = this.getDb(params.name);
57
- const threads = db.prepare(`SELECT id, session_key FROM threads WHERE session_key LIKE ?`).all(`agent:${oldAgent}:${params.name}:chat:%`);
58
- db.prepare(`UPDATE threads SET session_key = replace(session_key, 'agent:' || ? || ':' || ? || ':chat:', 'agent:' || ? || ':' || ? || ':chat:') WHERE session_key LIKE 'agent:' || ? || ':' || ? || ':chat:%'`).run(oldAgent, params.name, newAgent, params.name, oldAgent, params.name);
59
- for (const t of threads) cleanGatewaySession(t.session_key);
60
- ws.workspaces[params.name].agent = newAgent;
61
- migratedThreads = threads.length;
62
- this.broadcast(JSON.stringify({ type: 'clawchats', event: 'workspace-agent-changed', workspace: params.name, agent: newAgent }));
63
- }
64
- }
65
- this.setWorkspaces(ws);
66
- send(res, 200, { workspace: ws.workspaces[params.name], migratedThreads });
67
- }
68
-
69
- delete(req, res, params) {
70
- const ws = this.getWorkspaces();
71
- if (!ws.workspaces[params.name]) return sendError(res, 404, 'Workspace not found');
72
- if (Object.keys(ws.workspaces).length <= 1) return sendError(res, 400, 'Cannot delete the only workspace');
73
- // Collect the workspace's gateway session keys before its DB is removed.
74
- let sessionKeys = [];
75
- try { sessionKeys = this.getDb(params.name).prepare('SELECT session_key FROM threads WHERE session_key IS NOT NULL').all().map(r => r.session_key); } catch { /* ok */ }
76
- this.closeDb(params.name);
77
- const dbPath = path.join(this.dataDir, `${params.name}.db`);
78
- for (const suffix of ['', '-wal', '-shm']) { try { fs.unlinkSync(dbPath + suffix); } catch { /* ok */ } }
79
- cleanGatewaySessions(sessionKeys).then(n => { if (n > 0) console.log(`Cleaned ${n} gateway sessions for workspace: ${params.name}`); });
80
- delete ws.workspaces[params.name];
81
- if (ws.active === params.name) ws.active = Object.keys(ws.workspaces)[0] || null;
82
- this.setWorkspaces(ws);
83
- send(res, 200, { ok: true });
84
- }
85
-
86
- async reorder(req, res) {
87
- const body = await parseBody(req);
88
- if (!Array.isArray(body.order)) return sendError(res, 400, 'order must be an array of workspace names');
89
- const ws = this.getWorkspaces();
90
- body.order.forEach((name, i) => { if (ws.workspaces[name]) ws.workspaces[name].order = i; });
91
- this.setWorkspaces(ws);
92
- send(res, 200, { ok: true, workspaces: Object.values(ws.workspaces) });
93
- }
94
-
95
- activate(req, res, params) {
96
- const ws = this.getWorkspaces();
97
- if (!ws.workspaces[params.name]) return sendError(res, 404, 'Workspace not found');
98
- ws.active = params.name;
99
- this.setWorkspaces(ws);
100
- this.getDb(params.name);
101
- send(res, 200, { ok: true, workspace: ws.workspaces[params.name] });
102
- }
103
- }
@@ -1,31 +0,0 @@
1
- // Gateway session cleanup for deleted threads/workspaces.
2
- // 2026.9+ gateways keep sessions in SQLite and own their lifecycle, so cleanup goes
3
- // through the `sessions.delete` RPC (same as the Control UI) instead of touching files.
4
-
5
- let _gatewayClient = null;
6
-
7
- export function setGatewayClient(client) {
8
- _gatewayClient = client;
9
- }
10
-
11
- /** Delete one gateway session (row + transcript). Best effort; never throws. */
12
- export async function cleanGatewaySession(sessionKey) {
13
- if (!sessionKey || !_gatewayClient) return false;
14
- try {
15
- await _gatewayClient.request('sessions.delete', { key: sessionKey, deleteTranscript: true });
16
- return true;
17
- } catch (err) {
18
- // A thread that never sent a message has no gateway session; that's fine.
19
- if (!/not found|no session|unknown session/i.test(err.message)) {
20
- console.warn(`cleanGatewaySession(${sessionKey}): ${err.message}`);
21
- }
22
- return false;
23
- }
24
- }
25
-
26
- /** Delete several gateway sessions by exact key. Returns how many were deleted. */
27
- export async function cleanGatewaySessions(sessionKeys) {
28
- let cleaned = 0;
29
- for (const key of sessionKeys) if (await cleanGatewaySession(key)) cleaned++;
30
- return cleaned;
31
- }
@@ -1,52 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import os from 'node:os';
4
-
5
- /**
6
- * Discover memory backend configuration from OpenClaw config + optional env overrides.
7
- * env vars (MEMORY_PROVIDER, QDRANT_HOST, etc.) are read by the plugin host (src/index.ts)
8
- * and passed in via envOverrides to keep env vars out of the server bundle.
9
- *
10
- * This file is intentionally network-free: it only reads local config files.
11
- * The actual provider implementations (Qdrant, Postgres) live in memory.js.
12
- */
13
- export function discoverMemoryConfig(envOverrides = {}) {
14
- const defaults = { provider: 'qdrant', host: 'localhost', port: 6333, collection: null };
15
- let oc = null;
16
- for (const cfgPath of [path.join(os.homedir(), '.openclaw', 'openclaw.json'), '/etc/openclaw/openclaw.json']) {
17
- try { oc = JSON.parse(fs.readFileSync(cfgPath, 'utf8')); break; } catch { /* try next */ }
18
- }
19
-
20
- let cfg = { ...defaults };
21
- if (oc) {
22
- const vs = oc.plugins?.slots?.memory
23
- ? oc.plugins?.entries?.[oc.plugins.slots.memory]?.config?.oss?.vectorStore
24
- : null;
25
- if (vs) {
26
- if (vs.provider) cfg.provider = vs.provider;
27
- if (vs.config?.host) cfg.host = vs.config.host;
28
- if (vs.config?.port) cfg.port = vs.config.port;
29
- if (vs.config?.collectionName) cfg.collection = vs.config.collectionName;
30
- if (vs.config?.user) cfg.pgUser = vs.config.user;
31
- if (vs.config?.password) cfg.pgPassword = vs.config.password;
32
- if (vs.config?.dbname) cfg.pgDbName = vs.config.dbname;
33
- }
34
- const wsDir = oc.agents?.defaults?.workspace;
35
- if (wsDir) cfg.workspaceDir = wsDir;
36
- }
37
-
38
- if (envOverrides.provider) cfg.provider = envOverrides.provider;
39
- if (envOverrides.host) cfg.host = envOverrides.host;
40
- if (envOverrides.port) cfg.port = parseInt(envOverrides.port, 10);
41
- if (envOverrides.collection) cfg.collection = envOverrides.collection;
42
- if (envOverrides.pgUrl) cfg.pgUrl = envOverrides.pgUrl;
43
- if (envOverrides.qdrantUrl && !envOverrides.host) {
44
- try {
45
- const u = new URL(envOverrides.qdrantUrl);
46
- cfg.host = u.hostname;
47
- if (u.port) cfg.port = parseInt(u.port, 10);
48
- } catch { /* ignore */ }
49
- }
50
- if (!cfg.workspaceDir) cfg.workspaceDir = path.join(os.homedir(), '.openclaw', 'workspace');
51
- return cfg;
52
- }
@@ -1,108 +0,0 @@
1
- // Config discovery (file reads only) lives in memory-config.js.
2
- // This file contains only provider implementations (network calls, no file reads).
3
- export { discoverMemoryConfig } from './memory-config.js';
4
-
5
- export async function autoDetectQdrantCollection(config) {
6
- if (config.collection) return config.collection;
7
- try {
8
- const r = await fetch(`http://${config.host}:${config.port}/collections`, { signal: AbortSignal.timeout(3000) });
9
- const data = await r.json();
10
- const found = (data.result?.collections || []).map(c => c.name).find(n => !n.includes('migration'));
11
- if (found) { console.log(`Memory: auto-detected Qdrant collection "${found}"`); return found; }
12
- } catch { /* fall through */ }
13
- console.log('Memory: Qdrant unreachable or no collections, falling back to "memories"');
14
- return 'memories';
15
- }
16
-
17
- function createQdrantProvider(config) {
18
- const baseUrl = `http://${config.host}:${config.port}`;
19
- let collection = config.collection;
20
- return {
21
- name: 'qdrant',
22
- config,
23
- async init() { collection = await autoDetectQdrantCollection(config); config.collection = collection; },
24
- async list(limit, offset) {
25
- const body = { limit, with_payload: true, with_vector: false };
26
- if (offset) body.offset = offset;
27
- const r = await fetch(`${baseUrl}/collections/${collection}/points/scroll`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
28
- const data = await r.json();
29
- return { memories: (data.result?.points || []).map(p => ({ id: p.id, ...p.payload })), next_offset: data.result?.next_page_offset || null };
30
- },
31
- async search(query) {
32
- const q = query.toLowerCase();
33
- const matches = [];
34
- let offset = null;
35
- do {
36
- const body = { limit: 100, with_payload: true, with_vector: false };
37
- if (offset) body.offset = offset;
38
- const r = await fetch(`${baseUrl}/collections/${collection}/points/scroll`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
39
- const data = await r.json();
40
- for (const p of (data.result?.points || [])) { if ((p.payload?.data || '').toLowerCase().includes(q)) matches.push({ id: p.id, ...p.payload }); }
41
- offset = data.result?.next_page_offset || null;
42
- } while (offset);
43
- return { memories: matches, next_offset: null };
44
- },
45
- async update(id, newData) {
46
- const r = await fetch(`${baseUrl}/collections/${collection}/points/payload`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ points: [id], payload: { data: newData } }) });
47
- const data = await r.json();
48
- if (data.status?.error) throw new Error(data.status.error);
49
- return data.result;
50
- },
51
- async delete(id) {
52
- const r = await fetch(`${baseUrl}/collections/${collection}/points/delete`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ points: [id] }) });
53
- return (await r.json()).result;
54
- },
55
- async status() {
56
- try {
57
- const r = await fetch(`${baseUrl}/collections/${collection}`, { signal: AbortSignal.timeout(3000) });
58
- const data = await r.json();
59
- return { reachable: true, pointsCount: data.result?.points_count ?? null };
60
- } catch { return { reachable: false }; }
61
- },
62
- };
63
- }
64
-
65
- function createPgProvider(config) {
66
- let _pool = null;
67
- const table = config.collection || 'memories';
68
- async function getPool() {
69
- if (_pool) return _pool;
70
- let pg;
71
- try { pg = await import('pg'); } catch { throw new Error('pg package not installed. Run: npm install pg'); }
72
- const Pool = pg.default?.Pool || pg.Pool;
73
- _pool = config.pgUrl ? new Pool({ connectionString: config.pgUrl }) : new Pool({ host: config.host, port: config.port || 5432, user: config.pgUser || 'mem0', password: config.pgPassword || '', database: config.pgDbName || 'mem0' });
74
- return _pool;
75
- }
76
- return {
77
- name: 'postgres',
78
- config,
79
- async init() { /* pool created lazily */ },
80
- async list(limit, offset) {
81
- const pool = await getPool();
82
- const off = offset ? parseInt(offset, 10) : 0;
83
- const { rows } = await pool.query(`SELECT id, payload FROM ${table} ORDER BY created_at DESC LIMIT $1 OFFSET $2`, [limit, off]);
84
- return { memories: rows.map(r => ({ id: r.id, ...(typeof r.payload === 'string' ? JSON.parse(r.payload) : r.payload) })), next_offset: rows.length === limit ? off + limit : null };
85
- },
86
- async search(query) {
87
- const pool = await getPool();
88
- const { rows } = await pool.query(`SELECT id, payload FROM ${table} WHERE payload->>'data' ILIKE $1 LIMIT 100`, [`%${query}%`]);
89
- return { memories: rows.map(r => ({ id: r.id, ...(typeof r.payload === 'string' ? JSON.parse(r.payload) : r.payload) })), next_offset: null };
90
- },
91
- async update(id, newData) {
92
- const pool = await getPool();
93
- const { rowCount } = await pool.query(`UPDATE ${table} SET payload = jsonb_set(payload, '{data}', $1::jsonb) WHERE id = $2`, [JSON.stringify(newData), id]);
94
- if (rowCount === 0) throw new Error('Memory not found');
95
- return { updated: true };
96
- },
97
- async delete(id) { const pool = await getPool(); await pool.query(`DELETE FROM ${table} WHERE id = $1`, [id]); return { deleted: true }; },
98
- async status() {
99
- try { const pool = await getPool(); const { rows } = await pool.query(`SELECT COUNT(*) as count FROM ${table}`); return { reachable: true, pointsCount: parseInt(rows[0].count, 10) }; }
100
- catch (err) { return { reachable: false, error: err.message }; }
101
- },
102
- };
103
- }
104
-
105
- export function createMemoryProvider(config) {
106
- if (config.provider === 'postgres' || config.provider === 'pgvector') return createPgProvider(config);
107
- return createQdrantProvider(config);
108
- }
@@ -1,49 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { MAX_PREAMBLE_CHARS, getSessionsDirForAgent } from '../config.js';
4
-
5
- export function buildContextPreamble(db, threadId, lastSessionId, sessionKey) {
6
- let summary = null;
7
- let method = 'raw';
8
-
9
- if (lastSessionId) {
10
- const agentMatch = (sessionKey || '').match(/^agent:([^:]+):/);
11
- const sessionsDir = getSessionsDirForAgent(agentMatch?.[1]);
12
- try {
13
- const lines = fs.readFileSync(path.join(sessionsDir, `${lastSessionId}.jsonl`), 'utf8').split('\n').filter(Boolean);
14
- for (let i = lines.length - 1; i >= 0; i--) {
15
- try {
16
- const entry = JSON.parse(lines[i]);
17
- if (entry.type === 'compaction' && entry.summary) { summary = entry.summary; method = 'compaction'; break; }
18
- } catch { /* skip malformed */ }
19
- }
20
- } catch { /* file not found */ }
21
- }
22
-
23
- let preamble = '';
24
- if (method === 'compaction' && summary) {
25
- preamble += "[CONTEXT RECOVERY — This thread's agent session was reset. Below is a summary of the previous conversation followed by recent messages to restore context.]\n\n";
26
- preamble += '[CONVERSATION SUMMARY]\n' + summary + '\n\n';
27
- const msgs = db.prepare('SELECT role, content, timestamp FROM messages WHERE thread_id = ? ORDER BY timestamp DESC LIMIT 10').all(threadId).reverse();
28
- if (msgs.length) {
29
- preamble += '[RECENT MESSAGES]\n';
30
- for (const m of msgs) {
31
- const ts = new Date(m.timestamp).toISOString().replace('T', ' ').slice(0, 16);
32
- preamble += `${m.role.charAt(0).toUpperCase() + m.role.slice(1)} (${ts}): ${m.content}\n`;
33
- }
34
- }
35
- } else {
36
- preamble += "[CONTEXT RECOVERY — This thread's agent session was reset. Below are recent messages from the previous conversation to restore context.]\n\n";
37
- const msgs = db.prepare('SELECT role, content, timestamp FROM messages WHERE thread_id = ? ORDER BY timestamp DESC LIMIT 25').all(threadId).reverse();
38
- if (msgs.length) {
39
- preamble += '[PREVIOUS MESSAGES]\n';
40
- for (const m of msgs) {
41
- const ts = new Date(m.timestamp).toISOString().replace('T', ' ').slice(0, 16);
42
- preamble += `${m.role.charAt(0).toUpperCase() + m.role.slice(1)} (${ts}): ${m.content}\n`;
43
- }
44
- }
45
- }
46
-
47
- if (preamble.length > MAX_PREAMBLE_CHARS) preamble = preamble.slice(preamble.length - MAX_PREAMBLE_CHARS);
48
- return { preamble, method };
49
- }