@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,73 +0,0 @@
1
- /**
2
- * GatewayBridge — persistent WebSocket connection to the local OpenClaw gateway.
3
- *
4
- * Responsibilities:
5
- * 1. Connect to the local gateway using token-only auth (loopback connections
6
- * with valid token skip device identity entirely).
7
- * 2. Broadcast incoming gateway events to all connected DataChannel clients
8
- * via the 'gateway-event' EventEmitter event.
9
- * 3. Reconnect with exponential backoff on disconnect.
10
- */
11
- import { EventEmitter } from 'node:events';
12
- export interface PluginConfig {
13
- userId: string;
14
- serverUrl: string;
15
- apiKey: string;
16
- gatewayId?: string;
17
- gatewayToken?: string;
18
- devicePrivateKey?: string;
19
- schemaVersion: number;
20
- installedAt: string;
21
- totp?: {
22
- secret: string;
23
- algorithm: string;
24
- digits: number;
25
- period: number;
26
- enabledAt: string;
27
- };
28
- google?: {
29
- clientId: string;
30
- authorizedSub: string;
31
- authorizedEmail: string;
32
- };
33
- sessionSecret?: string;
34
- backupCodeHashes?: string[];
35
- totpPending?: {
36
- secret: string;
37
- generatedAt: string;
38
- };
39
- }
40
- export interface BridgeConfig {
41
- gatewayToken: string;
42
- dataDir: string;
43
- }
44
- export declare class GatewayBridge extends EventEmitter {
45
- private readonly gatewayUrl;
46
- private readonly config;
47
- private ws;
48
- private _isConnected;
49
- private destroyed;
50
- private reconnectTimer;
51
- private backoffMs;
52
- constructor(gatewayUrl: string, config: BridgeConfig);
53
- /**
54
- * Initiate the connection. Resolves once the WebSocket has been opened
55
- * (not necessarily after the gateway handshake completes — listen for
56
- * the 'connected' event for that).
57
- */
58
- connect(): Promise<void>;
59
- /**
60
- * Forward a message to the gateway (transparent proxy).
61
- */
62
- send(data: string): void;
63
- /**
64
- * Permanently close the connection and cancel any pending reconnect.
65
- */
66
- disconnect(): void;
67
- get isConnected(): boolean;
68
- private _openSocket;
69
- private _handleMessage;
70
- private _sendConnect;
71
- private _scheduleReconnect;
72
- private _cancelReconnect;
73
- }
@@ -1,255 +0,0 @@
1
- /**
2
- * GatewayBridge — persistent WebSocket connection to the local OpenClaw gateway.
3
- *
4
- * Responsibilities:
5
- * 1. Connect to the local gateway using token-only auth (loopback connections
6
- * with valid token skip device identity entirely).
7
- * 2. Broadcast incoming gateway events to all connected DataChannel clients
8
- * via the 'gateway-event' EventEmitter event.
9
- * 3. Reconnect with exponential backoff on disconnect.
10
- */
11
- import { EventEmitter } from 'node:events';
12
- import * as crypto from 'node:crypto';
13
- import * as fs from 'node:fs';
14
- import * as path from 'node:path';
15
- import { WebSocket } from 'ws';
16
- import { PLUGIN_VERSION } from './index.js';
17
- // Reconnect backoff constants (milliseconds)
18
- const BACKOFF_INITIAL_MS = 1_000;
19
- const BACKOFF_MAX_MS = 30_000;
20
- // Fixed client identity fields
21
- const CLIENT_ID = 'gateway-client';
22
- const CLIENT_MODE = 'backend';
23
- const ROLE = 'operator';
24
- const SCOPES = ['operator.read', 'operator.write', 'operator.admin'];
25
- // ---------------------------------------------------------------------------
26
- // Device Identity — ed25519 key generation + connect payload signing
27
- // Required by OpenClaw ≥2.15 to prevent scope clearing on connect.
28
- // ---------------------------------------------------------------------------
29
- const ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');
30
- function _derivePublicKeyRaw(publicKeyPem) {
31
- const spki = crypto.createPublicKey(publicKeyPem).export({ type: 'spki', format: 'der' });
32
- if (spki.length === ED25519_SPKI_PREFIX.length + 32 &&
33
- spki.subarray(0, ED25519_SPKI_PREFIX.length).equals(ED25519_SPKI_PREFIX)) {
34
- return spki.subarray(ED25519_SPKI_PREFIX.length);
35
- }
36
- return spki;
37
- }
38
- function _fingerprintPublicKey(publicKeyPem) {
39
- return crypto.createHash('sha256').update(_derivePublicKeyRaw(publicKeyPem)).digest('hex');
40
- }
41
- function _base64UrlEncode(buf) {
42
- return buf.toString('base64').replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/g, '');
43
- }
44
- function _loadOrCreateDeviceIdentity(identityPath) {
45
- try {
46
- if (fs.existsSync(identityPath)) {
47
- const parsed = JSON.parse(fs.readFileSync(identityPath, 'utf8'));
48
- if (parsed?.version === 1 && parsed.deviceId && parsed.publicKeyPem && parsed.privateKeyPem) {
49
- return parsed;
50
- }
51
- }
52
- }
53
- catch { /* regenerate */ }
54
- const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
55
- const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }).toString();
56
- const privateKeyPem = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
57
- const identity = {
58
- version: 1,
59
- deviceId: _fingerprintPublicKey(publicKeyPem),
60
- publicKeyPem,
61
- privateKeyPem,
62
- createdAtMs: Date.now(),
63
- };
64
- fs.mkdirSync(path.dirname(identityPath), { recursive: true });
65
- fs.writeFileSync(identityPath, JSON.stringify(identity, null, 2) + '\n', { mode: 0o600 });
66
- return identity;
67
- }
68
- function _buildDeviceAuth(identity, params) {
69
- const signedAt = Date.now();
70
- const payload = [
71
- 'v2', identity.deviceId, params.clientId, params.clientMode,
72
- params.role, params.scopes.join(','), String(signedAt),
73
- params.token || '', params.nonce,
74
- ].join('|');
75
- const privateKey = crypto.createPrivateKey(identity.privateKeyPem);
76
- const signature = _base64UrlEncode(crypto.sign(null, Buffer.from(payload, 'utf8'), privateKey));
77
- const publicKeyB64Url = _base64UrlEncode(_derivePublicKeyRaw(identity.publicKeyPem));
78
- return { id: identity.deviceId, publicKey: publicKeyB64Url, signature, signedAt, nonce: params.nonce };
79
- }
80
- // ---------------------------------------------------------------------------
81
- export class GatewayBridge extends EventEmitter {
82
- gatewayUrl;
83
- config;
84
- ws = null;
85
- _isConnected = false;
86
- destroyed = false;
87
- // Reconnect state
88
- reconnectTimer = null;
89
- backoffMs = BACKOFF_INITIAL_MS;
90
- constructor(gatewayUrl, config) {
91
- super();
92
- this.gatewayUrl = gatewayUrl;
93
- this.config = config;
94
- }
95
- /**
96
- * Initiate the connection. Resolves once the WebSocket has been opened
97
- * (not necessarily after the gateway handshake completes — listen for
98
- * the 'connected' event for that).
99
- */
100
- connect() {
101
- return new Promise((resolve, reject) => {
102
- if (this.destroyed) {
103
- reject(new Error('GatewayBridge has been destroyed'));
104
- return;
105
- }
106
- this._openSocket(resolve, reject);
107
- });
108
- }
109
- /**
110
- * Forward a message to the gateway (transparent proxy).
111
- */
112
- send(data) {
113
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
114
- console.warn('[GatewayBridge] send() called but WebSocket is not open');
115
- return;
116
- }
117
- this.ws.send(data);
118
- }
119
- /**
120
- * Permanently close the connection and cancel any pending reconnect.
121
- */
122
- disconnect() {
123
- this.destroyed = true;
124
- this._cancelReconnect();
125
- if (this.ws) {
126
- this.ws.terminate();
127
- this.ws = null;
128
- }
129
- this._isConnected = false;
130
- }
131
- get isConnected() {
132
- return this._isConnected;
133
- }
134
- // ---------------------------------------------------------------------------
135
- // Private helpers
136
- // ---------------------------------------------------------------------------
137
- _openSocket(resolveConnect = null, rejectConnect = null) {
138
- console.log(`[GatewayBridge] Connecting to ${this.gatewayUrl}`);
139
- const ws = new WebSocket(this.gatewayUrl);
140
- this.ws = ws;
141
- let resolved = false;
142
- ws.on('open', () => {
143
- console.log('[GatewayBridge] WebSocket opened');
144
- if (!resolved && resolveConnect) {
145
- resolved = true;
146
- resolveConnect();
147
- }
148
- });
149
- ws.on('error', (err) => {
150
- console.error('[GatewayBridge] WebSocket error:', err.message);
151
- if (!resolved && rejectConnect) {
152
- resolved = true;
153
- rejectConnect(err);
154
- }
155
- });
156
- ws.on('message', (raw) => {
157
- this._handleMessage(typeof raw === 'string' ? raw : raw.toString('utf8'));
158
- });
159
- ws.on('close', (code, reason) => {
160
- console.log(`[GatewayBridge] WebSocket closed (code=${code} reason=${reason.toString('utf8') || '(none)'})`);
161
- this._isConnected = false;
162
- this.ws = null;
163
- this.emit('disconnected');
164
- if (!this.destroyed) {
165
- this._scheduleReconnect();
166
- }
167
- });
168
- }
169
- _handleMessage(raw) {
170
- // Always broadcast the raw event to connected DataChannel clients first.
171
- this.emit('gateway-event', raw);
172
- // Parse for handshake handling.
173
- let msg;
174
- try {
175
- msg = JSON.parse(raw);
176
- }
177
- catch {
178
- // Non-JSON frame — forward as-is, ignore for handshake purposes.
179
- return;
180
- }
181
- const type = msg['type'];
182
- const event = msg['event'];
183
- // connect.challenge → send signed connect request with device identity
184
- if (type === 'event' && event === 'connect.challenge') {
185
- const payload = msg['payload'];
186
- const nonce = payload?.['nonce'] ?? '';
187
- this._sendConnect(nonce);
188
- return;
189
- }
190
- // hello-ok → handshake complete
191
- if (type === 'res') {
192
- const payload = msg['payload'];
193
- if (payload?.['type'] === 'hello-ok') {
194
- console.log('[GatewayBridge] Gateway handshake complete');
195
- this._isConnected = true;
196
- // Reset backoff on successful connection.
197
- this.backoffMs = BACKOFF_INITIAL_MS;
198
- this.emit('connected');
199
- }
200
- }
201
- }
202
- _sendConnect(nonce) {
203
- const identityPath = path.join(this.config.dataDir, 'device-identity.json');
204
- const identity = _loadOrCreateDeviceIdentity(identityPath);
205
- const device = _buildDeviceAuth(identity, {
206
- clientId: CLIENT_ID,
207
- clientMode: CLIENT_MODE,
208
- role: ROLE,
209
- scopes: SCOPES,
210
- token: this.config.gatewayToken,
211
- nonce,
212
- });
213
- this.send(JSON.stringify({
214
- type: 'req',
215
- id: 'gw-connect-1',
216
- method: 'connect',
217
- params: {
218
- minProtocol: 3,
219
- maxProtocol: 3,
220
- client: {
221
- id: CLIENT_ID,
222
- version: PLUGIN_VERSION,
223
- platform: 'node',
224
- mode: CLIENT_MODE,
225
- },
226
- role: ROLE,
227
- scopes: SCOPES,
228
- device,
229
- auth: { token: this.config.gatewayToken },
230
- caps: ['tool-events'],
231
- },
232
- }));
233
- }
234
- _scheduleReconnect() {
235
- if (this.destroyed)
236
- return;
237
- if (this.reconnectTimer !== null)
238
- return; // already scheduled
239
- console.log(`[GatewayBridge] Reconnecting in ${this.backoffMs}ms`);
240
- this.reconnectTimer = setTimeout(() => {
241
- this.reconnectTimer = null;
242
- if (!this.destroyed) {
243
- this._openSocket();
244
- }
245
- }, this.backoffMs);
246
- // Exponential backoff: double each time, cap at BACKOFF_MAX_MS.
247
- this.backoffMs = Math.min(this.backoffMs * 2, BACKOFF_MAX_MS);
248
- }
249
- _cancelReconnect() {
250
- if (this.reconnectTimer !== null) {
251
- clearTimeout(this.reconnectTimer);
252
- this.reconnectTimer = null;
253
- }
254
- }
255
- }
@@ -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,126 +0,0 @@
1
- import { send, sendError, parseBody } from '../util/http.js';
2
- import { buildContextPreamble } from '../util/context.js';
3
-
4
- export class MessageController {
5
- constructor({ getActiveDb, getWorkspaces, broadcast }) {
6
- this.getActiveDb = getActiveDb;
7
- this.getWorkspaces = getWorkspaces;
8
- this.broadcast = broadcast;
9
- }
10
-
11
- getAll(req, res, params, query) {
12
- const db = this.getActiveDb();
13
- if (!db.prepare('SELECT id FROM threads WHERE id = ?').get(params.id)) return sendError(res, 404, 'Thread not found');
14
- const limit = Math.min(parseInt(query.limit || '100', 10), 500);
15
- const before = query.before ? parseInt(query.before, 10) : null;
16
- const after = query.after ? parseInt(query.after, 10) : null;
17
- let sql = 'SELECT * FROM messages WHERE thread_id = ?';
18
- const sqlParams = [params.id];
19
- if (before) { sql += ' AND timestamp < ?'; sqlParams.push(before); }
20
- if (after) { sql += ' AND timestamp > ?'; sqlParams.push(after); }
21
- const total = db.prepare(sql.replace('SELECT *', 'SELECT COUNT(*) as c')).get(...sqlParams).c;
22
- const rows = db.prepare(sql + ' ORDER BY timestamp DESC LIMIT ?').all(...sqlParams, limit + 1);
23
- const messages = rows.slice(0, limit).reverse();
24
- for (const m of messages) { if (m.metadata) { try { m.metadata = JSON.parse(m.metadata); } catch { /* ok */ } } }
25
- send(res, 200, { messages, hasMore: rows.length > limit });
26
- }
27
-
28
- async create(req, res, params) {
29
- const body = await parseBody(req);
30
- const db = this.getActiveDb();
31
- if (!db.prepare('SELECT id FROM threads WHERE id = ?').get(params.id)) return sendError(res, 404, 'Thread not found');
32
- if (!body.id || !body.role || body.content === undefined || !body.timestamp) return sendError(res, 400, 'Required: id, role, content, timestamp');
33
- const metadata = body.metadata ? JSON.stringify(body.metadata) : null;
34
- const existing = db.prepare('SELECT id, status, metadata FROM messages WHERE id = ?').get(body.id);
35
- if (existing) {
36
- db.prepare('UPDATE messages SET status = ?, content = ?, metadata = ? WHERE id = ?').run(body.status || existing.status, body.content, metadata || existing.metadata, body.id);
37
- } else {
38
- 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());
39
- db.prepare('UPDATE threads SET updated_at = ? WHERE id = ?').run(Date.now(), params.id);
40
- if (body.role === 'user' && body.content) {
41
- const thread = db.prepare('SELECT title FROM threads WHERE id = ?').get(params.id);
42
- if (thread?.title === 'New chat') {
43
- const title = body.content.replace(/\n.*/s, '').slice(0, 40).trim() + (body.content.length > 40 ? '...' : '');
44
- if (title) {
45
- db.prepare('UPDATE threads SET title = ? WHERE id = ?').run(title, params.id);
46
- this.broadcast(JSON.stringify({ type: 'clawchats', event: 'thread-title-updated', threadId: params.id, workspace: this.getWorkspaces().active, title }));
47
- }
48
- }
49
- }
50
- }
51
- const message = db.prepare('SELECT * FROM messages WHERE id = ?').get(body.id);
52
- if (message?.metadata) { try { message.metadata = JSON.parse(message.metadata); } catch { /* ok */ } }
53
- send(res, existing ? 200 : 201, { message });
54
- }
55
-
56
- delete(req, res, params) {
57
- const db = this.getActiveDb();
58
- if (!db.prepare('SELECT id FROM messages WHERE id = ? AND thread_id = ?').get(params.messageId, params.id)) return sendError(res, 404, 'Message not found');
59
- db.prepare('DELETE FROM messages WHERE id = ?').run(params.messageId);
60
- send(res, 200, { ok: true });
61
- }
62
-
63
- contextFill(req, res, params) {
64
- const db = this.getActiveDb();
65
- const thread = db.prepare('SELECT * FROM threads WHERE id = ?').get(params.id);
66
- if (!thread) return sendError(res, 404, 'Thread not found');
67
- send(res, 200, buildContextPreamble(db, params.id, thread.last_session_id, thread.session_key));
68
- }
69
-
70
- search(req, res, params, query) {
71
- const q = query.q || '';
72
- if (!q) return send(res, 200, { results: [], total: 0 });
73
- const db = this.getActiveDb();
74
- const page = parseInt(query.page || '1', 10);
75
- const limit = Math.min(parseInt(query.limit || '20', 10), 100);
76
- const offset = (page - 1) * limit;
77
- try {
78
- 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);
79
- const total = db.prepare(`SELECT COUNT(*) as c FROM messages_fts WHERE messages_fts MATCH ?`).get(q).c;
80
- send(res, 200, { results, total });
81
- } catch { send(res, 200, { results: [], total: 0 }); }
82
- }
83
-
84
- export(req, res) {
85
- const db = this.getActiveDb();
86
- const ws = this.getWorkspaces();
87
- const threads = db.prepare('SELECT * FROM threads ORDER BY updated_at DESC').all();
88
- send(res, 200, {
89
- workspace: ws.active,
90
- exportedAt: Date.now(),
91
- threads: threads.map(t => {
92
- const messages = db.prepare('SELECT * FROM messages WHERE thread_id = ? ORDER BY timestamp ASC').all(t.id);
93
- for (const m of messages) { if (m.metadata) { try { m.metadata = JSON.parse(m.metadata); } catch { /* ok */ } } }
94
- return { ...t, messages };
95
- }),
96
- });
97
- }
98
-
99
- async import(req, res) {
100
- const body = await parseBody(req);
101
- const db = this.getActiveDb();
102
- const ws = this.getWorkspaces();
103
- if (!body.threads || !Array.isArray(body.threads)) return sendError(res, 400, 'Expected { threads: [...] }');
104
- let threadsImported = 0, messagesImported = 0;
105
- 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 (?, ?, ?, ?, ?, ?, ?, ?, ?)');
106
- const insertMsg = db.prepare('INSERT OR IGNORE INTO messages (id, thread_id, role, content, status, metadata, seq, timestamp, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
107
- db.exec('BEGIN');
108
- try {
109
- for (const t of body.threads) {
110
- if (!t.id) continue;
111
- const sessionKey = t.session_key || `agent:main:${ws.active}:chat:${t.id}`;
112
- 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++;
113
- for (const m of (t.messages || [])) {
114
- if (!m.id || !m.role) continue;
115
- const meta = m.metadata ? (typeof m.metadata === 'string' ? m.metadata : JSON.stringify(m.metadata)) : null;
116
- 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++;
117
- }
118
- }
119
- db.exec('COMMIT');
120
- } catch (e) {
121
- db.exec('ROLLBACK');
122
- throw e;
123
- }
124
- send(res, 200, { ok: true, threadsImported, messagesImported });
125
- }
126
- }