@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.
@@ -0,0 +1,27 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { WebSocketServer } from 'ws';
4
+ import { GatewayClient } from './gateway.js';
5
+
6
+ const logger = { logFrame() {} };
7
+
8
+ test('close() shuts the socket and stops reconnecting (plugin reload drain)', async () => {
9
+ const wss = new WebSocketServer({ port: 0 });
10
+ let connections = 0;
11
+ wss.on('connection', () => { connections++; });
12
+ await new Promise(r => wss.once('listening', r));
13
+ const gw = new GatewayClient({ dataDir: '/tmp', debugLogger: logger, gatewayWsUrl: `ws://127.0.0.1:${wss.address().port}`, authToken: '' });
14
+ gw.connect();
15
+ await new Promise(r => setTimeout(r, 150));
16
+ assert.equal(connections, 1);
17
+
18
+ const pending = gw.request('x').catch(e => e.message); // not connected (no handshake) → rejects
19
+ gw.close();
20
+ assert.equal(gw.ws, null);
21
+ assert.match(await pending, /not connected|stopping/);
22
+
23
+ gw.connect(); // ignored after close
24
+ await new Promise(r => setTimeout(r, 1300)); // longer than the first reconnect delay
25
+ assert.equal(connections, 1);
26
+ await new Promise(r => wss.close(r));
27
+ });
@@ -13,7 +13,16 @@ import { DatabaseSync } from 'node:sqlite';
13
13
  import { WebSocket } from 'ws';
14
14
  import { loadOrCreateDeviceIdentity, buildDeviceAuth } from './bootstrap/identity.js';
15
15
  import { parseSessionKey } from './util/helpers.js';
16
- import { isPushableTitle, withSuffix } from './gateway-sync.js';
16
+
17
+ const PLACEHOLDER_TITLES = new Set(['New chat', '']);
18
+
19
+ function withSuffix(base, n) {
20
+ return n <= 1 ? base : `${base} (${n})`;
21
+ }
22
+
23
+ function isPushableTitle(title) {
24
+ return typeof title === 'string' && !PLACEHOLDER_TITLES.has(title.trim());
25
+ }
17
26
 
18
27
  const SKIP_CONTENT = new Set(['[Response interrupted]']);
19
28
 
package/server/index.js CHANGED
@@ -1,33 +1,24 @@
1
1
  import http from 'node:http';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
- import os from 'node:os';
5
4
  import { fileURLToPath } from 'node:url';
6
- import { WebSocket as WS, WebSocketServer } from 'ws';
5
+ import { WebSocketServer } from 'ws';
7
6
 
8
- import { Database, requestDbStore } from './bootstrap/native.js';
9
- import { GATEWAY_WS_URL, AUTH_TOKEN, getSessionsDirForAgent } from './config.js';
7
+ import { Database } from './bootstrap/native.js';
8
+ import { GATEWAY_WS_URL, AUTH_TOKEN, discoverWorkspaceDir } from './config.js';
10
9
  import { DebugLogger } from './debug.js';
11
10
  import { GatewayClient } from './gateway.js';
12
- import { GatewaySync } from './gateway-sync.js';
13
- import { discoverMemoryConfig } from './providers/memory-config.js';
14
- import { createMemoryProvider } from './providers/memory.js';
15
- import { WorkspaceController } from './controllers/workspaces.js';
16
- import { ThreadController } from './controllers/threads.js';
17
- import { MessageController } from './controllers/messages.js';
18
- import { FileController } from './controllers/files.js';
19
- import { MemoryController } from './controllers/memory.js';
20
11
  import { handleServeFile, handleWorkspaceList, handleWorkspaceFileRead, handleWorkspaceFileWrite, handleWorkspaceFileDelete, handleWorkspaceUpload } from './controllers/filesystem.js';
21
12
  import { handleTranscribe } from './controllers/transcribe.js';
13
+ import { createGatewayMediaHandler } from './controllers/gateway-media.js';
22
14
  import { handleStatic } from './controllers/static.js';
23
15
  import { handleAgents } from './controllers/agents.js';
24
16
  import { createSettingsHandlers } from './controllers/settings.js';
25
17
  import { createWorkspaceStore } from './store/workspace-store.js';
26
- import { cleanGatewaySession, setGatewayClient } from './gateway-cleanup.js';
27
- import { parseSessionKey } from './util/helpers.js';
18
+ import { createExtrasStore } from './store/extras-store.js';
19
+ import { SessionLens } from './session-lens.js';
28
20
  import { send, sendError, parseBody, uuid, matchRoute, setCors } from './util/http.js';
29
21
 
30
- const HOME = os.homedir();
31
22
  // PORT is passed via createApp(config.port); env var is read by plugin host (src/index.ts).
32
23
  const DEFAULT_PORT = 3001;
33
24
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -38,10 +29,8 @@ const PLUGIN_DIR = path.resolve(__dirname, '..');
38
29
  export function createApp(config = {}) {
39
30
  const PORT = config.port || DEFAULT_PORT;
40
31
  const DATA_DIR = config.dataDir || path.join(PLUGIN_DIR, 'data');
41
- const UPLOADS_DIR = config.uploadsDir || path.join(PLUGIN_DIR, 'uploads');
42
32
  const WORKSPACES_FILE = path.join(DATA_DIR, 'workspaces.json');
43
33
  const SETTINGS_FILE = path.join(DATA_DIR, 'settings.json');
44
- const INTELLIGENCE_DIR = path.join(DATA_DIR, 'intelligence');
45
34
 
46
35
  const authToken = config.authToken !== undefined ? config.authToken : AUTH_TOKEN;
47
36
  const gatewayToken = config.gatewayToken !== undefined ? config.gatewayToken : authToken;
@@ -49,22 +38,8 @@ export function createApp(config = {}) {
49
38
  const openaiApiKey = config.openaiApiKey || null;
50
39
 
51
40
  fs.mkdirSync(DATA_DIR, { recursive: true });
52
- fs.mkdirSync(UPLOADS_DIR, { recursive: true });
53
-
54
- // Per-workspace SQLite databases
55
- const dbCache = new Map();
56
- function getDb(workspaceName) {
57
- if (dbCache.has(workspaceName)) return dbCache.get(workspaceName);
58
- const db = new Database(path.join(DATA_DIR, `${workspaceName}.db`));
59
- db.exec('PRAGMA journal_mode = WAL');
60
- db.exec('PRAGMA foreign_keys = ON');
61
- migrate(db);
62
- dbCache.set(workspaceName, db);
63
- return db;
64
- }
65
- function getActiveDb() { return requestDbStore.getStore() || getDb(getWorkspaces().active); }
66
- function closeDb(name) { const db = dbCache.get(name); if (db) { db.close(); dbCache.delete(name); } }
67
- function closeAll() { gatewayClient?.sync?.stop(); for (const db of dbCache.values()) db.close(); dbCache.clear(); globalDbCache.close?.(); }
41
+
42
+ function closeAll() { gatewayClient?.close(); globalDbCache.close?.(); }
68
43
 
69
44
  // Global DB (custom emojis, cross-workspace data)
70
45
  let _globalDb = null;
@@ -74,7 +49,6 @@ export function createApp(config = {}) {
74
49
  _globalDb = new Database(path.join(DATA_DIR, 'global.db'));
75
50
  _globalDb.exec('PRAGMA journal_mode = WAL');
76
51
  _globalDb.exec(`CREATE TABLE IF NOT EXISTS custom_emojis (name TEXT NOT NULL, pack TEXT NOT NULL DEFAULT 'slackmojis', url TEXT NOT NULL, mime_type TEXT, created_at INTEGER DEFAULT (strftime('%s','now')), PRIMARY KEY (name, pack))`);
77
- _globalDb.exec(`CREATE TABLE IF NOT EXISTS prompts (id TEXT PRIMARY KEY, title TEXT NOT NULL, content TEXT NOT NULL, category TEXT DEFAULT '', variables TEXT DEFAULT '[]', created_at INTEGER, updated_at INTEGER)`);
78
52
  return _globalDb;
79
53
  },
80
54
  close() { if (_globalDb) { _globalDb.close(); _globalDb = null; } }
@@ -85,24 +59,19 @@ export function createApp(config = {}) {
85
59
 
86
60
  const debugLogger = new DebugLogger(DATA_DIR);
87
61
 
88
- const memoryConfig = discoverMemoryConfig(config.memoryEnv || {});
89
- const memoryProvider = createMemoryProvider(memoryConfig);
90
- memoryProvider.init().catch(err => console.error('[createApp] Memory provider init error:', err.message));
91
- const MEMORY_FILES_DIR = path.join(memoryConfig.workspaceDir, 'memory');
62
+ const workspaceDir = discoverWorkspaceDir();
92
63
 
93
64
  // Instantiate the gateway client with all dependencies injected
94
- const gatewayClient = new GatewayClient({ getDb, getWorkspaces, dataDir: DATA_DIR, debugLogger, gatewayWsUrl: gatewayUrl, authToken: gatewayToken });
65
+ const gatewayClient = new GatewayClient({ dataDir: DATA_DIR, debugLogger, gatewayWsUrl: gatewayUrl, authToken: gatewayToken });
95
66
  const broadcast = msg => gatewayClient.broadcastToBrowsers(msg);
96
- setGatewayClient(gatewayClient);
97
- const gatewaySync = new GatewaySync({ gateway: gatewayClient, getDb, closeDb, getWorkspaces, setWorkspaces, dataDir: DATA_DIR, uploadsDir: UPLOADS_DIR, broadcast });
98
- gatewayClient.sync = gatewaySync;
67
+ // ClawChats-only data + the gateway↔browser session filter (gateway-native architecture).
68
+ const extras = createExtrasStore(() => globalDbCache.get());
69
+ try { const n = extras.seedFromWorkspaces(getWorkspaces()); if (n) console.log(`[extras] seeded ${n} project style(s) from workspaces.json`); }
70
+ catch (e) { console.error('[extras] style seed failed:', e.message); }
71
+ gatewayClient.lens = new SessionLens({ broadcast, request: (m, p, t) => gatewayClient.request(m, p, t), extras });
99
72
 
100
73
  // Instantiate controllers
101
- const workspaces = new WorkspaceController({ getDb, closeDb, getWorkspaces, setWorkspaces, dataDir: DATA_DIR, broadcast, sync: gatewaySync });
102
- const threads = new ThreadController({ getActiveDb, getWorkspaces, uploadsDir: UPLOADS_DIR, broadcast, sync: gatewaySync });
103
- const messages = new MessageController({ getActiveDb, getWorkspaces, broadcast });
104
- const files = new FileController({ getActiveDb, getWorkspaces, uploadsDir: UPLOADS_DIR, intelligenceDir: INTELLIGENCE_DIR });
105
- const memory = new MemoryController({ memoryProvider, memoryFilesDir: MEMORY_FILES_DIR, memoryConfig });
74
+ const handleGatewayMedia = createGatewayMediaHandler({ gatewayWsUrl: gatewayUrl, gatewayToken });
106
75
 
107
76
  // Settings — file I/O lives in settings.js
108
77
  const { handleGetSettings, handleSaveSettings } = createSettingsHandlers(SETTINGS_FILE);
@@ -118,9 +87,7 @@ export function createApp(config = {}) {
118
87
 
119
88
  // Request handler
120
89
  async function handleRequest(req, res) {
121
- const wsName = req.headers?.['x-workspace'];
122
- const db = wsName ? getDb(wsName) : getActiveDb();
123
- return requestDbStore.run(db, () => route(req, res));
90
+ return route(req, res);
124
91
  }
125
92
 
126
93
  async function route(req, res) {
@@ -138,7 +105,6 @@ export function createApp(config = {}) {
138
105
  }
139
106
 
140
107
  // Unauthenticated routes
141
- if ((p = matchRoute(method, urlPath, 'GET /api/uploads/:threadId/:fileId'))) return files.serveUpload(req, res, p);
142
108
 
143
109
  if (method === 'GET' && urlPath === '/api/emoji') {
144
110
  try { const rows = globalDbCache.get().prepare('SELECT name, pack, url, mime_type FROM custom_emojis ORDER BY created_at DESC').all(); res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'public, max-age=300' }); return res.end(JSON.stringify(rows)); }
@@ -182,38 +148,14 @@ export function createApp(config = {}) {
182
148
  }
183
149
 
184
150
  // File serving & workspace browser
185
- if (method === 'GET' && urlPath === '/api/file') return handleServeFile(req, res, query, memoryConfig);
151
+ if (method === 'GET' && urlPath === '/api/file') return handleServeFile(req, res, query, workspaceDir);
152
+ if (method === 'GET' && urlPath === '/api/gw-media') return handleGatewayMedia(req, res, query);
186
153
  if (method === 'GET' && urlPath === '/api/workspace') return handleWorkspaceList(req, res, query);
187
154
  if (method === 'GET' && urlPath === '/api/workspace/file') return handleWorkspaceFileRead(req, res, query);
188
155
  if (method === 'PUT' && urlPath === '/api/workspace/file') return await handleWorkspaceFileWrite(req, res, query);
189
156
  if (method === 'DELETE' && urlPath === '/api/workspace/file') return handleWorkspaceFileDelete(req, res, query);
190
157
  if (method === 'POST' && urlPath === '/api/workspace/upload') return await handleWorkspaceUpload(req, res, query);
191
158
 
192
- // Memory
193
- if (method === 'GET' && urlPath === '/api/memory/status') return await memory.status(req, res);
194
- if (method === 'GET' && urlPath === '/api/memory/list') return await memory.list(req, res, query);
195
- if (method === 'GET' && urlPath === '/api/memory/search') return await memory.search(req, res, query);
196
- if (method === 'GET' && urlPath === '/api/memory/files') return memory.files(req, res, query);
197
- if ((p = matchRoute(method, urlPath, 'PUT /api/memory/:id'))) return await memory.update(req, res, p);
198
- if ((p = matchRoute(method, urlPath, 'DELETE /api/memory/:id'))) return await memory.delete(req, res, p);
199
-
200
- // Prompt library
201
- if (method === 'GET' && urlPath === '/api/prompts') {
202
- const rows = globalDbCache.get().prepare('SELECT * FROM prompts ORDER BY created_at ASC').all();
203
- return send(res, 200, rows.map(r => ({ id: r.id, title: r.title, content: r.content, category: r.category, variables: JSON.parse(r.variables || '[]'), createdAt: r.created_at, updatedAt: r.updated_at })));
204
- }
205
- if (method === 'PUT' && urlPath === '/api/prompts') {
206
- const body = await parseBody(req);
207
- const prompts = Array.isArray(body) ? body : [];
208
- const db = globalDbCache.get();
209
- const upsert = db.prepare('INSERT OR REPLACE INTO prompts (id, title, content, category, variables, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)');
210
- db.transaction(() => {
211
- db.prepare('DELETE FROM prompts').run();
212
- for (const p of prompts) upsert.run(p.id, p.title, p.content, p.category || '', JSON.stringify(p.variables || []), p.createdAt || Date.now(), p.updatedAt || Date.now());
213
- })();
214
- return send(res, 200, { ok: true });
215
- }
216
-
217
159
  // Settings & misc
218
160
  if (method === 'GET' && urlPath === '/api/settings') return handleGetSettings(req, res);
219
161
  if (method === 'PUT' && urlPath === '/api/settings') return await handleSaveSettings(req, res, parseBody);
@@ -221,54 +163,24 @@ export function createApp(config = {}) {
221
163
  if (method === 'GET' && urlPath === '/api/health') return send(res, 200, { ok: true, workspace: getWorkspaces().active, uptime: process.uptime() });
222
164
  if (method === 'GET' && urlPath === '/api/agents') return handleAgents(req, res);
223
165
 
224
- // Workspaces
225
- if (method === 'GET' && urlPath === '/api/workspaces') return workspaces.getAll(req, res);
226
- if (method === 'POST' && urlPath === '/api/workspaces') return await workspaces.create(req, res);
227
- if ((p = matchRoute(method, urlPath, 'PATCH /api/workspaces/:name'))) return await workspaces.update(req, res, p);
228
- if ((p = matchRoute(method, urlPath, 'DELETE /api/workspaces/:name'))) return await workspaces.delete(req, res, p);
229
- if (method === 'POST' && urlPath === '/api/workspaces/reorder') return await workspaces.reorder(req, res);
230
- if ((p = matchRoute(method, urlPath, 'POST /api/workspaces/:name/activate'))) return workspaces.activate(req, res, p);
231
-
232
- // Threads
233
- if (method === 'GET' && urlPath === '/api/threads') return threads.getAll(req, res, {}, query);
234
- if (method === 'GET' && urlPath === '/api/threads/unread') return threads.getUnread(req, res);
235
- if (method === 'POST' && urlPath === '/api/threads') return await threads.create(req, res);
236
- if ((p = matchRoute(method, urlPath, 'POST /api/threads/:id/mark-read'))) return await threads.markRead(req, res, p);
237
- if ((p = matchRoute(method, urlPath, 'GET /api/threads/:id/messages'))) return messages.getAll(req, res, p, query);
238
- if ((p = matchRoute(method, urlPath, 'POST /api/threads/:id/messages'))) return await messages.create(req, res, p);
239
- if ((p = matchRoute(method, urlPath, 'DELETE /api/threads/:id/messages/:messageId'))) return messages.delete(req, res, p);
240
- if ((p = matchRoute(method, urlPath, 'POST /api/threads/:id/generate-title'))) {
241
- const db = getActiveDb();
242
- const thread = db.prepare('SELECT * FROM threads WHERE id = ?').get(p.id);
243
- if (!thread) return sendError(res, 404, 'Thread not found');
244
- gatewayClient.generateThreadTitle(db, p.id, getWorkspaces().active);
245
- return send(res, 200, { ok: true });
166
+ // ClawChats-only extras (see EXTRAS.md)
167
+ if (method === 'GET' && urlPath === '/api/extras/project-styles') {
168
+ extras.seedFromWorkspaces(getWorkspaces()); // legacy projects renamed by gateway sync keep their style
169
+ return send(res, 200, { styles: extras.getProjectStyles() });
246
170
  }
247
- if ((p = matchRoute(method, urlPath, 'POST /api/threads/:id/upload'))) return await files.upload(req, res, p);
248
- if ((p = matchRoute(method, urlPath, 'GET /api/threads/:id/intelligence'))) return files.getIntelligence(req, res, p);
249
- if ((p = matchRoute(method, urlPath, 'POST /api/threads/:id/intelligence'))) return await files.saveIntelligence(req, res, p);
250
- if ((p = matchRoute(method, urlPath, 'GET /api/threads/:id'))) return threads.get(req, res, p);
251
- if ((p = matchRoute(method, urlPath, 'PATCH /api/threads/:id'))) return await threads.update(req, res, p);
252
- if ((p = matchRoute(method, urlPath, 'DELETE /api/threads/:id'))) return await threads.delete(req, res, p);
253
-
254
- // Search / export / import
255
- if (method === 'GET' && urlPath === '/api/search') return messages.search(req, res, {}, query);
256
- if (method === 'GET' && urlPath === '/api/export') return messages.export(req, res);
257
- if (method === 'POST' && urlPath === '/api/import') return await messages.import(req, res);
258
-
259
- if (method === 'POST' && urlPath === '/api/active-thread') {
171
+ if ((p = matchRoute(method, urlPath, 'PUT /api/extras/project-styles/:name'))) {
260
172
  const body = await parseBody(req);
261
- if (body.threadId && body.workspace) gatewayClient.setActiveThread(null, body.workspace, body.threadId);
262
- return send(res, 200, { ok: true });
173
+ extras.setProjectStyle(p.name, { color: body.color, icon: body.icon });
174
+ broadcast(JSON.stringify({ type: 'clawchats', event: 'project-styles-changed' }));
175
+ return send(res, 200, { styles: extras.getProjectStyles() });
263
176
  }
264
-
265
- if (method === 'POST' && urlPath === '/api/incognito/cleanup') {
266
- const { sessionKey, threadId } = await parseBody(req);
267
- if (sessionKey) cleanGatewaySession(sessionKey);
268
- if (threadId) { try { fs.rmSync(path.join(UPLOADS_DIR, threadId), { recursive: true }); } catch { /* ok */ } }
177
+ if ((p = matchRoute(method, urlPath, 'DELETE /api/extras/project-styles/:name'))) {
178
+ extras.deleteProjectStyle(p.name);
179
+ broadcast(JSON.stringify({ type: 'clawchats', event: 'project-styles-changed' }));
269
180
  return send(res, 200, { ok: true });
270
181
  }
271
182
 
183
+
272
184
  sendError(res, 404, `Not found: ${method} ${urlPath}`);
273
185
  } catch (err) {
274
186
  console.error(`Error handling ${method} ${urlPath}:`, err);
@@ -288,7 +200,6 @@ export function createApp(config = {}) {
288
200
  ws.on('message', async data => {
289
201
  const msgStr = data.toString();
290
202
  debugLogger.logFrame('BR→SRV', msgStr);
291
- let msgToForward = msgStr;
292
203
  try {
293
204
  const msg = JSON.parse(msgStr);
294
205
  if (msg.type === 'req' && msg.method === 'connect') {
@@ -302,34 +213,12 @@ export function createApp(config = {}) {
302
213
  return;
303
214
  }
304
215
  if (msg.type === 'clawchats' || msg.type === 'shellchat') {
305
- if (msg.action === 'active-thread') { gatewayClient.setActiveThread(ws, msg.workspace, msg.threadId); return; }
216
+ if (msg.action === 'active-thread') return; // sent by pre-gateway-native frontends; nothing to track now
306
217
  if (msg.action === 'debug-start') { const r = debugLogger.start(msg.ts, ws); ws.send(JSON.stringify(r.error === 'already-active' ? { type: 'clawchats', event: 'debug-error', error: 'Recording already active in another tab', sessionId: r.sessionId } : { type: 'clawchats', event: 'debug-started', sessionId: r.sessionId })); return; }
307
218
  if (msg.action === 'debug-dump') { const r = debugLogger.saveDump(msg); ws.send(JSON.stringify({ type: 'clawchats', event: 'debug-saved', sessionId: r.sessionId, files: r.files })); return; }
308
219
  }
309
- // Save inline attachments to disk before forwarding to gateway
310
- if (msg.type === 'req' && msg.method === 'chat.send' && msg.params?.attachments?.length > 0) {
311
- const parsed = parseSessionKey(msg.params.sessionKey || '');
312
- const threadId = parsed?.threadId || 'misc';
313
- const uploadDir = path.join(UPLOADS_DIR, threadId);
314
- fs.mkdirSync(uploadDir, { recursive: true });
315
- const extMap = { jpeg: 'jpg', jpg: 'jpg', png: 'png', gif: 'gif', webp: 'webp', pdf: 'pdf', 'svg+xml': 'svg', mp3: 'mp3', mp4: 'mp4', wav: 'wav', webm: 'webm' };
316
- const savedPaths = [];
317
- for (const att of msg.params.attachments) {
318
- if (!att.content || !att.mimeType) continue;
319
- try {
320
- const rawExt = att.mimeType.split('/')[1]?.split(';')[0] || 'bin';
321
- const filePath = path.join(uploadDir, `${Date.now()}_${Math.random().toString(36).slice(2, 6)}.${extMap[rawExt] || rawExt}`);
322
- fs.writeFileSync(filePath, Buffer.from(att.content, 'base64'));
323
- savedPaths.push(filePath);
324
- } catch (err) { console.error('[upload] Failed to save attachment:', err.message); }
325
- }
326
- if (savedPaths.length > 0) {
327
- const note = `\n\n[${savedPaths.length === 1 ? 'Attached file saved on disk' : 'Attached files saved on disk'}:\n${savedPaths.map(p => `- ${p}`).join('\n')}]`;
328
- msgToForward = JSON.stringify({ ...msg, params: { ...msg.params, message: (msg.params.message || '') + note } });
329
- }
330
- }
331
220
  } catch { /* not JSON or not a ClawChats message, forward as-is */ }
332
- gatewayClient.sendToGateway(msgToForward);
221
+ gatewayClient.forwardFromBrowser(msgStr);
333
222
  });
334
223
 
335
224
  ws.on('close', () => { console.log('Browser client disconnected'); debugLogger.handleClientDisconnect(ws); gatewayClient.removeBrowserClient(ws); });
@@ -339,81 +228,21 @@ export function createApp(config = {}) {
339
228
 
340
229
  return {
341
230
  handleRequest,
342
- getDb,
343
- getActiveDb,
344
231
  getWorkspaces,
345
232
  setWorkspaces,
346
233
  shutdown: closeAll,
347
- closeAllDbs: closeAll,
348
234
  gatewayClient,
349
- gatewaySync,
235
+ extras,
350
236
  setupBrowserWs,
351
237
  debugLogger,
352
238
  dataDir: DATA_DIR,
353
239
  };
354
240
  }
355
241
 
356
- // Migration — kept here as it references Database-level constructs shared across modules
357
- function migrate(db) {
358
- db.exec(`
359
- CREATE TABLE IF NOT EXISTS threads (
360
- id TEXT PRIMARY KEY, session_key TEXT UNIQUE NOT NULL, title TEXT DEFAULT 'New chat',
361
- pinned INTEGER DEFAULT 0, pin_order INTEGER DEFAULT 0, model TEXT,
362
- last_session_id TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL
363
- );
364
- CREATE TABLE IF NOT EXISTS messages (
365
- id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, role TEXT NOT NULL, content TEXT NOT NULL,
366
- status TEXT DEFAULT 'sent', metadata TEXT, seq INTEGER, timestamp INTEGER NOT NULL, created_at INTEGER NOT NULL,
367
- FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE
368
- );
369
- CREATE INDEX IF NOT EXISTS idx_messages_thread ON messages(thread_id, timestamp);
370
- CREATE INDEX IF NOT EXISTS idx_messages_dedup ON messages(thread_id, role, timestamp);
371
- `);
372
- try { db.exec('ALTER TABLE threads ADD COLUMN sort_order INTEGER DEFAULT 0'); } catch { /* exists */ }
373
- try { db.exec('ALTER TABLE threads ADD COLUMN unread_count INTEGER DEFAULT 0'); } catch { /* exists */ }
374
- try { db.prepare('ALTER TABLE threads ADD COLUMN metadata TEXT DEFAULT NULL').run(); } catch {}
375
- // When the connector first saw this thread's gateway session (gateway sync). NULL = never
376
- // synced: the thread's state is pushed to the gateway, never pulled or deleted from it.
377
- try { db.exec('ALTER TABLE threads ADD COLUMN gateway_seen_at INTEGER DEFAULT NULL'); } catch { /* exists */ }
378
- db.exec(`CREATE TABLE IF NOT EXISTS unread_messages (thread_id TEXT NOT NULL, message_id TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (thread_id, message_id), FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE)`);
379
- db.exec('CREATE INDEX IF NOT EXISTS idx_unread_thread ON unread_messages(thread_id)');
380
- ensureFts(db);
381
- }
382
-
383
- function createFts(db) {
384
- db.exec(`CREATE VIRTUAL TABLE messages_fts USING fts5(content, content=messages, content_rowid=rowid, tokenize='porter unicode61 tokenchars x27')`);
385
- db.exec(`CREATE TRIGGER messages_ai AFTER INSERT ON messages BEGIN INSERT INTO messages_fts(rowid, content) VALUES (new.rowid, new.content); END`);
386
- db.exec(`CREATE TRIGGER messages_ad AFTER DELETE ON messages BEGIN INSERT INTO messages_fts(messages_fts, rowid, content) VALUES('delete', old.rowid, old.content); END`);
387
- db.exec(`CREATE TRIGGER messages_au AFTER UPDATE ON messages BEGIN INSERT INTO messages_fts(messages_fts, rowid, content) VALUES('delete', old.rowid, old.content); INSERT INTO messages_fts(rowid, content) VALUES (new.rowid, new.content); END`);
388
- }
389
-
390
- function dropFts(db) {
391
- db.exec('DROP TABLE IF EXISTS messages_fts; DROP TRIGGER IF EXISTS messages_ai; DROP TRIGGER IF EXISTS messages_ad; DROP TRIGGER IF EXISTS messages_au;');
392
- }
393
-
394
- function ensureFts(db) {
395
- const hasFts = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='messages_fts'").get();
396
- if (!hasFts) {
397
- try { createFts(db); db.prepare("INSERT INTO messages_fts(messages_fts) VALUES('rebuild')").run(); }
398
- catch (e) { console.error('[DB] messages_fts creation failed:', e.message); }
399
- return;
400
- }
401
- const schema = db.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name='messages_fts'").get();
402
- if (schema && !schema.sql.includes('tokenchars')) {
403
- console.log('[DB] Upgrading messages_fts tokenizer...');
404
- try { dropFts(db); createFts(db); db.prepare("INSERT INTO messages_fts(messages_fts) VALUES('rebuild')").run(); console.log('[DB] Upgrade complete'); }
405
- catch (e) { console.error('[DB] Upgrade failed:', e.message); dropFts(db); }
406
- } else {
407
- try { db.prepare("INSERT INTO messages_fts(messages_fts) VALUES('integrity-check')").run(); }
408
- catch { try { db.prepare("INSERT INTO messages_fts(messages_fts) VALUES('rebuild')").run(); } catch (e) { console.error('[DB] FTS rebuild failed:', e.message); dropFts(db); } }
409
- }
410
- }
411
-
412
242
  // Standalone mode (node server/index.js or via isDirectRun check in bundle)
413
243
  const isDirectRun = import.meta.url === `file://${process.argv[1]}`;
414
244
  if (isDirectRun) {
415
245
  const app = createApp();
416
- app.getActiveDb();
417
246
 
418
247
  const server = http.createServer(app.handleRequest);
419
248
  const wss = new WebSocketServer({ noServer: true });