@clawchatsai/connector 0.1.16 → 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,64 +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 { parseMultipart } from '../util/multipart.js';
5
-
6
- export class FileController {
7
- constructor({ getActiveDb, getWorkspaces, uploadsDir, intelligenceDir }) {
8
- this.getActiveDb = getActiveDb;
9
- this.getWorkspaces = getWorkspaces;
10
- this.uploadsDir = uploadsDir;
11
- this.intelligenceDir = intelligenceDir;
12
- }
13
-
14
- async upload(req, res, params) {
15
- if (!this.getActiveDb().prepare('SELECT id FROM threads WHERE id = ?').get(params.id)) return sendError(res, 404, 'Thread not found');
16
- const files = await parseMultipart(req);
17
- const dir = path.join(this.uploadsDir, params.id);
18
- fs.mkdirSync(dir, { recursive: true });
19
- const savedFiles = [];
20
- for (const file of files) {
21
- const fileId = uuid();
22
- const ext = path.extname(file.filename) || '';
23
- fs.writeFileSync(path.join(dir, fileId + ext), file.data);
24
- savedFiles.push({ id: fileId, filename: file.filename, path: `/api/uploads/${params.id}/${fileId}${ext}`, mimeType: file.mimeType, size: file.data.length });
25
- }
26
- send(res, 200, { files: savedFiles });
27
- }
28
-
29
- serveUpload(req, res, params) {
30
- const base = path.join(this.uploadsDir, params.threadId, params.fileId);
31
- let resolved = base;
32
- if (!fs.existsSync(resolved)) {
33
- try {
34
- const match = fs.readdirSync(path.join(this.uploadsDir, params.threadId)).find(e => e.startsWith(params.fileId.replace(/\.[^.]+$/, '')));
35
- if (match) resolved = path.join(this.uploadsDir, params.threadId, match);
36
- } catch { /* ok */ }
37
- }
38
- if (!fs.existsSync(resolved)) return sendError(res, 404, 'File not found');
39
- const MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.pdf': 'application/pdf', '.txt': 'text/plain', '.json': 'application/json' };
40
- const stat = fs.statSync(resolved);
41
- res.writeHead(200, { 'Content-Type': MIME[path.extname(resolved).toLowerCase()] || 'application/octet-stream', 'Content-Length': stat.size, 'Cache-Control': 'public, max-age=86400', 'Access-Control-Allow-Origin': '*' });
42
- fs.createReadStream(resolved).pipe(res);
43
- }
44
-
45
- _intelligencePath(threadId) {
46
- return path.join(this.intelligenceDir, this.getWorkspaces().active, `${threadId}.json`);
47
- }
48
-
49
- getIntelligence(req, res, params) {
50
- const filePath = this._intelligencePath(params.id);
51
- if (!fs.existsSync(filePath)) return send(res, 200, { versions: [], currentVersion: -1 });
52
- try { return send(res, 200, JSON.parse(fs.readFileSync(filePath, 'utf8'))); }
53
- catch { return send(res, 200, { versions: [], currentVersion: -1 }); }
54
- }
55
-
56
- async saveIntelligence(req, res, params) {
57
- const body = await parseBody(req);
58
- const filePath = this._intelligencePath(params.id);
59
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
60
- const data = { versions: body.versions || [], currentVersion: body.currentVersion ?? -1, updatedAt: Date.now() };
61
- fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
62
- send(res, 200, data);
63
- }
64
- }
@@ -1,86 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { send, sendError } from '../util/http.js';
4
-
5
- export class MemoryController {
6
- constructor({ memoryProvider, memoryFilesDir, memoryConfig }) {
7
- this.provider = memoryProvider;
8
- this.filesDir = memoryFilesDir;
9
- this.config = memoryConfig;
10
- }
11
-
12
- async list(req, res, query) {
13
- const limit = Math.min(parseInt(query.limit) || 20, 100);
14
- try { send(res, 200, await this.provider.list(limit, query.offset || null)); }
15
- catch (err) { send(res, 502, { error: `Failed to reach ${this.provider.name}`, detail: err.message }); }
16
- }
17
-
18
- async search(req, res, query) {
19
- const q = (query.query || '').toLowerCase().trim();
20
- if (!q) return send(res, 400, { error: 'Missing query parameter' });
21
- try { send(res, 200, await this.provider.search(q)); }
22
- catch (err) { send(res, 502, { error: `Failed to reach ${this.provider.name}`, detail: err.message }); }
23
- }
24
-
25
- files(req, res, query) {
26
- const q = (query.query || '').toLowerCase().trim();
27
- const memories = this._parseFiles();
28
- const filtered = q ? memories.filter(m => m.data.toLowerCase().includes(q) || m.title.toLowerCase().includes(q)) : memories;
29
- filtered.sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
30
- send(res, 200, { memories: filtered });
31
- }
32
-
33
- _parseFiles() {
34
- const memories = [];
35
- const scanDir = (dir, prefix = '') => {
36
- let entries;
37
- try { entries = fs.readdirSync(dir); } catch { return; }
38
- for (const entry of entries) {
39
- const fullPath = path.join(dir, entry);
40
- const stat = (() => { try { return fs.statSync(fullPath); } catch { return null; } })();
41
- if (!stat) continue;
42
- if (stat.isDirectory() && !prefix) { scanDir(fullPath, entry + '/'); continue; }
43
- if (!entry.endsWith('.md') || !stat.isFile()) continue;
44
- const content = fs.readFileSync(fullPath, 'utf8');
45
- const basename = entry.replace(/\.md$/, '');
46
- const dateMatch = basename.match(/^(\d{4}-\d{2}-\d{2})/);
47
- if (prefix) {
48
- memories.push({ id: `file:${prefix + basename}`, source: 'file', file: prefix + basename, title: basename, data: content.trim(), createdAt: stat.mtime.toISOString() });
49
- } else {
50
- for (const section of content.split(/^(?=## )/m)) {
51
- const trimmed = section.trim();
52
- if (!trimmed) continue;
53
- const headingMatch = trimmed.match(/^##\s+(.+)/);
54
- const heading = headingMatch ? headingMatch[1].trim() : null;
55
- const body = headingMatch ? trimmed.slice(trimmed.indexOf('\n') + 1).trim() : trimmed;
56
- if (!heading && body.match(/^#\s+/) && body.split('\n').length <= 2) continue;
57
- const title = heading || basename;
58
- memories.push({ id: `file:${basename}:${title}`, source: 'file', file: basename, title, data: heading ? `**${title}**\n${body}` : body, createdAt: dateMatch ? `${dateMatch[1]}T00:00:00Z` : stat.mtime.toISOString() });
59
- }
60
- }
61
- }
62
- };
63
- scanDir(this.filesDir);
64
- return memories;
65
- }
66
-
67
- async update(req, res, params) {
68
- try {
69
- const chunks = [];
70
- for await (const chunk of req) chunks.push(chunk);
71
- const { data } = JSON.parse(Buffer.concat(chunks).toString());
72
- if (!(data || '').trim()) return send(res, 400, { error: 'Missing data field' });
73
- send(res, 200, { ok: true, result: await this.provider.update(params.id, data.trim()) });
74
- } catch (err) { send(res, 502, { error: 'Failed to update memory', detail: err.message }); }
75
- }
76
-
77
- async delete(req, res, params) {
78
- try { send(res, 200, { ok: true, result: await this.provider.delete(params.id) }); }
79
- catch (err) { send(res, 502, { error: `Failed to reach ${this.provider.name}`, detail: err.message }); }
80
- }
81
-
82
- async status(req, res) {
83
- const status = await this.provider.status();
84
- send(res, 200, { provider: this.provider.name, host: this.config.host, port: this.config.port, collection: this.config.collection, backend: status, memoryFilesDir: this.filesDir, memoryFilesDirExists: fs.existsSync(this.filesDir) });
85
- }
86
- }
@@ -1,118 +0,0 @@
1
- import { send, sendError, parseBody } from '../util/http.js';
2
-
3
- export class MessageController {
4
- constructor({ getActiveDb, getWorkspaces, broadcast }) {
5
- this.getActiveDb = getActiveDb;
6
- this.getWorkspaces = getWorkspaces;
7
- this.broadcast = broadcast;
8
- }
9
-
10
- getAll(req, res, params, query) {
11
- const db = this.getActiveDb();
12
- if (!db.prepare('SELECT id FROM threads WHERE id = ?').get(params.id)) return sendError(res, 404, 'Thread not found');
13
- const limit = Math.min(parseInt(query.limit || '100', 10), 500);
14
- const before = query.before ? parseInt(query.before, 10) : null;
15
- const after = query.after ? parseInt(query.after, 10) : null;
16
- let sql = 'SELECT * FROM messages WHERE thread_id = ?';
17
- const sqlParams = [params.id];
18
- if (before) { sql += ' AND timestamp < ?'; sqlParams.push(before); }
19
- if (after) { sql += ' AND timestamp > ?'; sqlParams.push(after); }
20
- const total = db.prepare(sql.replace('SELECT *', 'SELECT COUNT(*) as c')).get(...sqlParams).c;
21
- const rows = db.prepare(sql + ' ORDER BY timestamp DESC LIMIT ?').all(...sqlParams, limit + 1);
22
- const messages = rows.slice(0, limit).reverse();
23
- for (const m of messages) { if (m.metadata) { try { m.metadata = JSON.parse(m.metadata); } catch { /* ok */ } } }
24
- send(res, 200, { messages, hasMore: rows.length > limit });
25
- }
26
-
27
- async create(req, res, params) {
28
- const body = await parseBody(req);
29
- const db = this.getActiveDb();
30
- if (!db.prepare('SELECT id FROM threads WHERE id = ?').get(params.id)) return sendError(res, 404, 'Thread not found');
31
- if (!body.id || !body.role || body.content === undefined || !body.timestamp) return sendError(res, 400, 'Required: id, role, content, timestamp');
32
- const metadata = body.metadata ? JSON.stringify(body.metadata) : null;
33
- const existing = db.prepare('SELECT id, status, metadata FROM messages WHERE id = ?').get(body.id);
34
- if (existing) {
35
- db.prepare('UPDATE messages SET status = ?, content = ?, metadata = ? WHERE id = ?').run(body.status || existing.status, body.content, metadata || existing.metadata, body.id);
36
- } else {
37
- db.prepare('INSERT INTO messages (id, thread_id, role, content, status, metadata, seq, timestamp, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)').run(body.id, params.id, body.role, body.content, body.status || 'sent', metadata, body.seq || null, body.timestamp, Date.now());
38
- db.prepare('UPDATE threads SET updated_at = ? WHERE id = ?').run(Date.now(), params.id);
39
- if (body.role === 'user' && body.content) {
40
- const thread = db.prepare('SELECT title FROM threads WHERE id = ?').get(params.id);
41
- if (thread?.title === 'New chat') {
42
- const title = body.content.replace(/\n.*/s, '').slice(0, 40).trim() + (body.content.length > 40 ? '...' : '');
43
- if (title) {
44
- db.prepare('UPDATE threads SET title = ? WHERE id = ?').run(title, params.id);
45
- this.broadcast(JSON.stringify({ type: 'clawchats', event: 'thread-title-updated', threadId: params.id, workspace: this.getWorkspaces().active, title }));
46
- }
47
- }
48
- }
49
- }
50
- const message = db.prepare('SELECT * FROM messages WHERE id = ?').get(body.id);
51
- if (message?.metadata) { try { message.metadata = JSON.parse(message.metadata); } catch { /* ok */ } }
52
- send(res, existing ? 200 : 201, { message });
53
- }
54
-
55
- delete(req, res, params) {
56
- const db = this.getActiveDb();
57
- if (!db.prepare('SELECT id FROM messages WHERE id = ? AND thread_id = ?').get(params.messageId, params.id)) return sendError(res, 404, 'Message not found');
58
- db.prepare('DELETE FROM messages WHERE id = ?').run(params.messageId);
59
- send(res, 200, { ok: true });
60
- }
61
-
62
- search(req, res, params, query) {
63
- const q = query.q || '';
64
- if (!q) return send(res, 200, { results: [], total: 0 });
65
- const db = this.getActiveDb();
66
- const page = parseInt(query.page || '1', 10);
67
- const limit = Math.min(parseInt(query.limit || '20', 10), 100);
68
- const offset = (page - 1) * limit;
69
- try {
70
- const results = db.prepare(`SELECT m.id as messageId, m.thread_id as threadId, t.title as threadTitle, m.role, snippet(messages_fts, 0, '<mark>', '</mark>', '...', 40) as content, m.timestamp FROM messages_fts JOIN messages m ON messages_fts.rowid = m.rowid JOIN threads t ON m.thread_id = t.id WHERE messages_fts MATCH ? ORDER BY rank LIMIT ? OFFSET ?`).all(q, limit, offset);
71
- const total = db.prepare(`SELECT COUNT(*) as c FROM messages_fts WHERE messages_fts MATCH ?`).get(q).c;
72
- send(res, 200, { results, total });
73
- } catch { send(res, 200, { results: [], total: 0 }); }
74
- }
75
-
76
- export(req, res) {
77
- const db = this.getActiveDb();
78
- const ws = this.getWorkspaces();
79
- const threads = db.prepare('SELECT * FROM threads ORDER BY updated_at DESC').all();
80
- send(res, 200, {
81
- workspace: ws.active,
82
- exportedAt: Date.now(),
83
- threads: threads.map(t => {
84
- const messages = db.prepare('SELECT * FROM messages WHERE thread_id = ? ORDER BY timestamp ASC').all(t.id);
85
- for (const m of messages) { if (m.metadata) { try { m.metadata = JSON.parse(m.metadata); } catch { /* ok */ } } }
86
- return { ...t, messages };
87
- }),
88
- });
89
- }
90
-
91
- async import(req, res) {
92
- const body = await parseBody(req);
93
- const db = this.getActiveDb();
94
- const ws = this.getWorkspaces();
95
- if (!body.threads || !Array.isArray(body.threads)) return sendError(res, 400, 'Expected { threads: [...] }');
96
- let threadsImported = 0, messagesImported = 0;
97
- const insertThread = db.prepare('INSERT OR IGNORE INTO threads (id, session_key, title, pinned, pin_order, model, last_session_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
98
- const insertMsg = db.prepare('INSERT OR IGNORE INTO messages (id, thread_id, role, content, status, metadata, seq, timestamp, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
99
- db.exec('BEGIN');
100
- try {
101
- for (const t of body.threads) {
102
- if (!t.id) continue;
103
- const sessionKey = t.session_key || `agent:main:${ws.active}:chat:${t.id}`;
104
- if (insertThread.run(t.id, sessionKey, t.title || 'Imported chat', t.pinned || 0, t.pin_order || 0, t.model || null, t.last_session_id || null, t.created_at || Date.now(), t.updated_at || Date.now()).changes > 0) threadsImported++;
105
- for (const m of (t.messages || [])) {
106
- if (!m.id || !m.role) continue;
107
- const meta = m.metadata ? (typeof m.metadata === 'string' ? m.metadata : JSON.stringify(m.metadata)) : null;
108
- if (insertMsg.run(m.id, t.id, m.role, m.content || '', m.status || 'sent', meta, m.seq || null, m.timestamp || Date.now(), m.created_at || Date.now()).changes > 0) messagesImported++;
109
- }
110
- }
111
- db.exec('COMMIT');
112
- } catch (e) {
113
- db.exec('ROLLBACK');
114
- throw e;
115
- }
116
- send(res, 200, { ok: true, threadsImported, messagesImported });
117
- }
118
- }
@@ -1,119 +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
-
6
- export class ThreadController {
7
- constructor({ getActiveDb, getWorkspaces, uploadsDir, broadcast, sync }) {
8
- this.getActiveDb = getActiveDb;
9
- this.getWorkspaces = getWorkspaces;
10
- this.uploadsDir = uploadsDir;
11
- this.broadcast = broadcast;
12
- this.sync = sync;
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
- const thread = db.prepare('SELECT * FROM threads WHERE id = ?').get(params.id);
81
- if (!thread) return sendError(res, 404, 'Thread not found');
82
- // Gateway first for synced fields; a suffix may be added to make the title unique.
83
- if (body.title !== undefined && body.title !== thread.title) {
84
- const requested = body.title;
85
- body.title = await this.sync.push(() => this.sync.pushTitle(thread.session_key, requested));
86
- if (body.title !== requested) {
87
- this.broadcast(JSON.stringify({ type: 'clawchats', event: 'thread-title-updated', threadId: params.id, workspace: this.getWorkspaces().active, title: body.title }));
88
- }
89
- }
90
- if (body.pinned !== undefined && !!body.pinned !== !!thread.pinned) {
91
- await this.sync.push(() => this.sync.pushPinned(thread.session_key, body.pinned));
92
- }
93
- const fields = [], values = [];
94
- for (const [col, val] of [['title', body.title], ['model', body.model], ['last_session_id', body.last_session_id], ['unread_count', body.unread_count]]) {
95
- if (val !== undefined) { fields.push(`${col} = ?`); values.push(val); }
96
- }
97
- if (body.pinned !== undefined) { fields.push('pinned = ?'); values.push(body.pinned ? 1 : 0); }
98
- if (body.pin_order !== undefined) { fields.push('pin_order = ?'); values.push(body.pin_order); }
99
- if (body.sort_order !== undefined) { fields.push('sort_order = ?'); values.push(body.sort_order); }
100
- if (body.metadata !== undefined) { fields.push('metadata = ?'); values.push(typeof body.metadata === 'string' ? body.metadata : JSON.stringify(body.metadata)); }
101
- if (fields.length) {
102
- fields.push('updated_at = ?');
103
- values.push(Date.now(), params.id);
104
- db.prepare(`UPDATE threads SET ${fields.join(', ')} WHERE id = ?`).run(...values);
105
- }
106
- send(res, 200, { thread: db.prepare('SELECT * FROM threads WHERE id = ?').get(params.id) });
107
- }
108
-
109
- async delete(req, res, params) {
110
- const db = this.getActiveDb();
111
- const thread = db.prepare('SELECT * FROM threads WHERE id = ?').get(params.id);
112
- if (!thread) return sendError(res, 404, 'Thread not found');
113
- await this.sync.push(() => this.sync.deleteSession(thread.session_key));
114
- db.prepare('DELETE FROM threads WHERE id = ?').run(params.id);
115
- try { fs.rmSync(path.join(this.uploadsDir, params.id), { recursive: true }); } catch { /* ok */ }
116
- send(res, 200, { ok: true });
117
- }
118
-
119
- }
@@ -1,116 +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 } from '../gateway-cleanup.js';
6
-
7
- export class WorkspaceController {
8
- constructor({ getDb, closeDb, getWorkspaces, setWorkspaces, dataDir, broadcast, sync }) {
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
- this.sync = sync;
16
- }
17
-
18
- getAll(req, res) {
19
- const ws = this.getWorkspaces();
20
- const sorted = Object.values(ws.workspaces).sort((a, b) => (a.order ?? 999) - (b.order ?? 999));
21
- for (const workspace of sorted) {
22
- try {
23
- workspace.unread_count = this.getDb(workspace.name).prepare('SELECT COALESCE(SUM(unread_count), 0) as total FROM threads').get().total;
24
- } catch { workspace.unread_count = 0; }
25
- }
26
- send(res, 200, { active: ws.active, workspaces: sorted });
27
- }
28
-
29
- async create(req, res) {
30
- const body = await parseBody(req);
31
- const { name, label } = body;
32
- if (!name || !/^[a-z0-9-]{1,32}$/.test(name)) return sendError(res, 400, 'Name must be [a-z0-9-], 1-32 chars');
33
- const ws = this.getWorkspaces();
34
- if (ws.workspaces[name]) return sendError(res, 409, 'Workspace already exists');
35
- let agent = 'main';
36
- try { agent = validateAgent(body.agent || 'main'); } catch { agent = 'main'; }
37
- // Gateway first: the project's group must exist there before it exists here.
38
- const finalLabel = await this.sync.push(() => this.sync.projectCreated(label || name));
39
- const order = Math.max(-1, ...Object.values(ws.workspaces).map(w => w.order ?? -1)) + 1;
40
- ws.workspaces[name] = { name, label: finalLabel, color: body.color || null, icon: body.icon || null, agent, createdAt: Date.now(), order };
41
- this.setWorkspaces(ws);
42
- this.getDb(name);
43
- send(res, 201, { workspace: ws.workspaces[name] });
44
- }
45
-
46
- async update(req, res, params) {
47
- const body = await parseBody(req);
48
- const ws = this.getWorkspaces();
49
- if (!ws.workspaces[params.name]) return sendError(res, 404, 'Workspace not found');
50
- if (body.label !== undefined && body.label !== ws.workspaces[params.name].label) {
51
- const current = ws.workspaces[params.name].label;
52
- ws.workspaces[params.name].label = await this.sync.push(() => this.sync.projectRenamed(params.name, current, body.label));
53
- }
54
- if (body.color !== undefined) ws.workspaces[params.name].color = body.color;
55
- if (body.icon !== undefined) ws.workspaces[params.name].icon = body.icon;
56
- if (body.lastThread !== undefined) ws.workspaces[params.name].lastThread = body.lastThread;
57
- let migratedThreads = 0;
58
- if (body.agent !== undefined) {
59
- let newAgent;
60
- try { newAgent = validateAgent(body.agent); } catch (e) { return sendError(res, 400, e.message); }
61
- const oldAgent = ws.workspaces[params.name].agent || 'main';
62
- if (newAgent !== oldAgent) {
63
- const db = this.getDb(params.name);
64
- const threads = db.prepare(`SELECT id, session_key FROM threads WHERE session_key LIKE ?`).all(`agent:${oldAgent}:${params.name}:chat:%`);
65
- 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);
66
- for (const t of threads) cleanGatewaySession(t.session_key);
67
- ws.workspaces[params.name].agent = newAgent;
68
- migratedThreads = threads.length;
69
- this.broadcast(JSON.stringify({ type: 'clawchats', event: 'workspace-agent-changed', workspace: params.name, agent: newAgent }));
70
- }
71
- }
72
- this.setWorkspaces(ws);
73
- send(res, 200, { workspace: ws.workspaces[params.name], migratedThreads });
74
- }
75
-
76
- async delete(req, res, params) {
77
- const ws = this.getWorkspaces();
78
- if (!ws.workspaces[params.name]) return sendError(res, 404, 'Workspace not found');
79
- if (Object.keys(ws.workspaces).length <= 1) return sendError(res, 400, 'Cannot delete the only workspace');
80
- let sessionKeys = [];
81
- 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 */ }
82
- // Gateway first: its sessions, then the (now empty) group.
83
- const label = ws.workspaces[params.name].label;
84
- await this.sync.push(async () => {
85
- for (const key of sessionKeys) await this.sync.deleteSession(key);
86
- await this.sync.projectDeleted(label);
87
- });
88
- this.closeDb(params.name);
89
- const dbPath = path.join(this.dataDir, `${params.name}.db`);
90
- for (const suffix of ['', '-wal', '-shm']) { try { fs.unlinkSync(dbPath + suffix); } catch { /* ok */ } }
91
- delete ws.workspaces[params.name];
92
- if (ws.active === params.name) ws.active = Object.keys(ws.workspaces)[0] || null;
93
- this.setWorkspaces(ws);
94
- send(res, 200, { ok: true });
95
- }
96
-
97
- async reorder(req, res) {
98
- const body = await parseBody(req);
99
- if (!Array.isArray(body.order)) return sendError(res, 400, 'order must be an array of workspace names');
100
- const ws = this.getWorkspaces();
101
- const labels = body.order.filter(name => ws.workspaces[name]).map(name => ws.workspaces[name].label);
102
- await this.sync.push(() => this.sync.projectsReordered(labels));
103
- body.order.forEach((name, i) => { if (ws.workspaces[name]) ws.workspaces[name].order = i; });
104
- this.setWorkspaces(ws);
105
- send(res, 200, { ok: true, workspaces: Object.values(ws.workspaces) });
106
- }
107
-
108
- activate(req, res, params) {
109
- const ws = this.getWorkspaces();
110
- if (!ws.workspaces[params.name]) return sendError(res, 404, 'Workspace not found');
111
- ws.active = params.name;
112
- this.setWorkspaces(ws);
113
- this.getDb(params.name);
114
- send(res, 200, { ok: true, workspace: ws.workspaces[params.name] });
115
- }
116
- }
@@ -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
- }