@clawchatsai/connector 0.1.14 → 0.1.16

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.
package/dist/index.js CHANGED
@@ -46,7 +46,6 @@ let _stopRequested = false;
46
46
  let _imageRestrictedModels = [];
47
47
  /** True if session.reset config risks wiping ClawChats history (daily reset or short idle). */
48
48
  let _sessionResetWarning = false;
49
- let _uploadsDir = null;
50
49
  // ---------------------------------------------------------------------------
51
50
  // Config helpers
52
51
  // ---------------------------------------------------------------------------
@@ -264,7 +263,6 @@ async function startClawChats(ctx, api) {
264
263
  // 4. Import server.js and create app instance with plugin paths
265
264
  const dataDir = path.join(ctx.stateDir, 'clawchats', 'data');
266
265
  const uploadsDir = path.join(ctx.stateDir, 'clawchats', 'uploads');
267
- _uploadsDir = uploadsDir;
268
266
  // Dynamic import of server.js (plain JS, no type declarations)
269
267
  // @ts-expect-error — server/index.js is plain JS with no .d.ts
270
268
  const serverModule = await import('../server/index.js');
@@ -441,63 +439,6 @@ async function stopClawChats(ctx) {
441
439
  * Injecting a minimal placeholder ensures the agent run proceeds.
442
440
  */
443
441
  // Track which ClawChats thread sessions have received the capability note (once per session).
444
- function normalizeGatewayPayload(raw) {
445
- try {
446
- const parsed = JSON.parse(raw);
447
- if (parsed.method === 'chat.send' && typeof parsed.params?.message === 'string') {
448
- // Warn user in-chat if they're sending image attachments to an image-restricted model.
449
- // The warning is appended to the message so the AI echoes it back — impossible to miss.
450
- if (Array.isArray(parsed.params?.attachments) &&
451
- parsed.params.attachments.length > 0 &&
452
- _imageRestrictedModels.length > 0) {
453
- parsed.params.message = (parsed.params.message || '').trimEnd() +
454
- '\n\n[⚠️ ClawChats: image attachment not delivered — your model config is missing "image" input support. ' +
455
- 'Fix: add "image" to the input array for your model in ~/.openclaw/openclaw.json, then restart the gateway.]';
456
- return JSON.stringify(parsed);
457
- }
458
- // Fix image-only messages: inject placeholder so gateway doesn't reject empty body.
459
- if (Array.isArray(parsed.params?.attachments) &&
460
- parsed.params.attachments.length > 0 &&
461
- !parsed.params.message?.trim()) {
462
- parsed.params.message = '[Image]';
463
- return JSON.stringify(parsed);
464
- }
465
- // Save inline base64 attachments to disk so the agent can reference them as file paths.
466
- // Runs before capability note so a gateway restart doesn't prevent path injection.
467
- if (Array.isArray(parsed.params?.attachments) && parsed.params.attachments.length > 0 && _uploadsDir) {
468
- const skMatch = (parsed.params.sessionKey || '').match(/^agent:[^:]+:[^:]+:chat:([^:]+)$/);
469
- const threadId = skMatch?.[1] || 'misc';
470
- const uploadDir = path.join(_uploadsDir, threadId);
471
- 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' };
472
- const savedPaths = [];
473
- for (const att of parsed.params.attachments) {
474
- if (!att.content || !att.mimeType)
475
- continue;
476
- try {
477
- const rawExt = att.mimeType.split('/')[1]?.split(';')[0] || 'bin';
478
- const ext = extMap[rawExt] || rawExt;
479
- const fileId = `${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
480
- const filePath = path.join(uploadDir, `${fileId}.${ext}`);
481
- fs.mkdirSync(uploadDir, { recursive: true });
482
- fs.writeFileSync(filePath, Buffer.from(att.content, 'base64'));
483
- savedPaths.push(filePath);
484
- }
485
- catch { /* skip attachment on error */ }
486
- }
487
- if (savedPaths.length > 0) {
488
- const label = savedPaths.length === 1 ? 'Attached file saved on disk' : 'Attached files saved on disk';
489
- parsed.params.message = parsed.params.message.trimEnd() +
490
- `\n\n[${label}:\n${savedPaths.map((p) => `- ${p}`).join('\n')}]`;
491
- return JSON.stringify(parsed);
492
- }
493
- }
494
- }
495
- }
496
- catch {
497
- // Not JSON or unexpected shape — pass through unchanged
498
- }
499
- return raw;
500
- }
501
442
  // DataChannel message handler (spec section 6.4)
502
443
  // ---------------------------------------------------------------------------
503
444
  function setupDataChannelHandler(dc, connectionId, ctx) {
@@ -666,7 +607,7 @@ function processAuthenticatedMessage(dc, connectionId, msg, ctx) {
666
607
  }
667
608
  }
668
609
  catch { /* ignore parse/db errors */ }
669
- app.gatewayClient.sendToGateway(normalizeGatewayPayload(_gwPayload));
610
+ app.gatewayClient.sendToGateway(_gwPayload);
670
611
  }
671
612
  break;
672
613
  case 'gateway-msg-chunk': {
@@ -696,7 +637,7 @@ function processAuthenticatedMessage(dc, connectionId, msg, ctx) {
696
637
  gatewayMsgChunkBuffers.delete(chunkId);
697
638
  const fullPayload = buf.chunks.join('');
698
639
  if (app?.gatewayClient) {
699
- app.gatewayClient.sendToGateway(normalizeGatewayPayload(fullPayload));
640
+ app.gatewayClient.sendToGateway(fullPayload);
700
641
  }
701
642
  }
702
643
  break;
@@ -1207,6 +1148,37 @@ async function handleReauth() {
1207
1148
  console.log(' Restart the gateway for changes to take effect: systemctl --user restart openclaw-gateway');
1208
1149
  }
1209
1150
  }
1151
+ async function handleExportHistory(api, mode) {
1152
+ if (mode !== undefined && mode !== 'check') {
1153
+ console.error(`Unknown option "${mode}". Use: ocplatform clawchats export-history [check]`);
1154
+ process.exitCode = 1;
1155
+ return;
1156
+ }
1157
+ const gwCfg = api.config;
1158
+ const gw = gwCfg?.['gateway'];
1159
+ const token = gw?.['auth']?.['token'] || loadConfig()?.gatewayToken || '';
1160
+ if (!token) {
1161
+ console.error('No gateway token found. Is ClawChats set up? (ocplatform clawchats setup <token>)');
1162
+ process.exitCode = 1;
1163
+ return;
1164
+ }
1165
+ const port = gw?.['port'] || 18789;
1166
+ // @ts-expect-error — server/ is plain JS with no .d.ts
1167
+ const serverModule = await import('../server/history-export.js');
1168
+ try {
1169
+ await serverModule.exportHistory({
1170
+ dataDir: path.join(CONFIG_DIR, 'data'),
1171
+ stateDir: path.dirname(CONFIG_DIR),
1172
+ gatewayUrl: process.env.GATEWAY_WS_URL || `ws://127.0.0.1:${port}`,
1173
+ token,
1174
+ check: mode === 'check',
1175
+ });
1176
+ }
1177
+ catch (err) {
1178
+ console.error(`export-history failed: ${err.message}`);
1179
+ process.exitCode = 1;
1180
+ }
1181
+ }
1210
1182
  async function handleStatus() {
1211
1183
  // CLI runs in a separate process — module-level vars are null here.
1212
1184
  // Query the live service via the health endpoint instead.
@@ -1371,6 +1343,9 @@ const plugin = {
1371
1343
  cmd.command('reset')
1372
1344
  .description('Disconnect and remove all ClawChats data')
1373
1345
  .action(() => handleReset());
1346
+ cmd.command('export-history [check]')
1347
+ .description('Export ClawChats chats the gateway has no history for, for the gateway importer ("check" = report only)')
1348
+ .action((mode) => handleExportHistory(api, mode === undefined ? undefined : String(mode)));
1374
1349
  cmd.command('import <path>')
1375
1350
  .description('Import databases and config from a folder (e.g. migrate from old data directory)')
1376
1351
  .action((srcPath) => handleImport(String(srcPath)));
@@ -0,0 +1,29 @@
1
+ /** Persisted ClawChats plugin config (~/.ocplatform/clawchats/config.json). */
2
+ export interface PluginConfig {
3
+ userId: string;
4
+ serverUrl: string;
5
+ apiKey: string;
6
+ gatewayId?: string;
7
+ gatewayToken?: string;
8
+ devicePrivateKey?: string;
9
+ schemaVersion: number;
10
+ installedAt: string;
11
+ totp?: {
12
+ secret: string;
13
+ algorithm: string;
14
+ digits: number;
15
+ period: number;
16
+ enabledAt: string;
17
+ };
18
+ google?: {
19
+ clientId: string;
20
+ authorizedSub: string;
21
+ authorizedEmail: string;
22
+ };
23
+ sessionSecret?: string;
24
+ backupCodeHashes?: string[];
25
+ totpPending?: {
26
+ secret: string;
27
+ generatedAt: string;
28
+ };
29
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawchatsai/connector",
3
- "version": "0.1.14",
3
+ "version": "0.1.16",
4
4
  "type": "module",
5
5
  "description": "ClawChats OpenClaw plugin — P2P tunnel + local API bridge",
6
6
  "main": "dist/index.js",
@@ -30,7 +30,10 @@
30
30
  "openclaw": {
31
31
  "extensions": [
32
32
  "./dist/index.js"
33
- ]
33
+ ],
34
+ "install": {
35
+ "minHostVersion": ">=2026.9.7"
36
+ }
34
37
  },
35
38
  "devDependencies": {
36
39
  "@types/ws": "^8.0.0",
package/server/config.js CHANGED
@@ -4,7 +4,6 @@ import os from 'node:os';
4
4
  import { fileURLToPath } from 'node:url';
5
5
 
6
6
  export const HOME = os.homedir();
7
- export const MAX_PREAMBLE_CHARS = 50000;
8
7
 
9
8
  // Resolve __dirname for ESM (esbuild inlines this correctly)
10
9
  const __filename = fileURLToPath(import.meta.url);
@@ -1,5 +1,4 @@
1
1
  import { send, sendError, parseBody } from '../util/http.js';
2
- import { buildContextPreamble } from '../util/context.js';
3
2
 
4
3
  export class MessageController {
5
4
  constructor({ getActiveDb, getWorkspaces, broadcast }) {
@@ -60,13 +59,6 @@ export class MessageController {
60
59
  send(res, 200, { ok: true });
61
60
  }
62
61
 
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
62
  search(req, res, params, query) {
71
63
  const q = query.q || '';
72
64
  if (!q) return send(res, 200, { results: [], total: 0 });
@@ -2,15 +2,14 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { send, sendError, parseBody, uuid } from '../util/http.js';
4
4
  import { syncThreadUnreadCount } from '../util/helpers.js';
5
- import { getSessionsDirForAgent } from '../config.js';
6
- import { cleanGatewaySession } from '../gateway-cleanup.js';
7
5
 
8
6
  export class ThreadController {
9
- constructor({ getActiveDb, getWorkspaces, uploadsDir, broadcast }) {
7
+ constructor({ getActiveDb, getWorkspaces, uploadsDir, broadcast, sync }) {
10
8
  this.getActiveDb = getActiveDb;
11
9
  this.getWorkspaces = getWorkspaces;
12
10
  this.uploadsDir = uploadsDir;
13
11
  this.broadcast = broadcast;
12
+ this.sync = sync;
14
13
  }
15
14
 
16
15
  getAll(req, res, params, query) {
@@ -78,7 +77,19 @@ export class ThreadController {
78
77
  async update(req, res, params) {
79
78
  const body = await parseBody(req);
80
79
  const db = this.getActiveDb();
81
- if (!db.prepare('SELECT id FROM threads WHERE id = ?').get(params.id)) return sendError(res, 404, 'Thread not found');
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
+ }
82
93
  const fields = [], values = [];
83
94
  for (const [col, val] of [['title', body.title], ['model', body.model], ['last_session_id', body.last_session_id], ['unread_count', body.unread_count]]) {
84
95
  if (val !== undefined) { fields.push(`${col} = ?`); values.push(val); }
@@ -95,20 +106,14 @@ export class ThreadController {
95
106
  send(res, 200, { thread: db.prepare('SELECT * FROM threads WHERE id = ?').get(params.id) });
96
107
  }
97
108
 
98
- delete(req, res, params) {
109
+ async delete(req, res, params) {
99
110
  const db = this.getActiveDb();
100
111
  const thread = db.prepare('SELECT * FROM threads WHERE id = ?').get(params.id);
101
112
  if (!thread) return sendError(res, 404, 'Thread not found');
113
+ await this.sync.push(() => this.sync.deleteSession(thread.session_key));
102
114
  db.prepare('DELETE FROM threads WHERE id = ?').run(params.id);
103
- const agentMatch = (thread.session_key || '').match(/^agent:([^:]+):/);
104
- const sessionsDir = getSessionsDirForAgent(agentMatch?.[1]);
105
- let sessionIdToDelete = thread.last_session_id;
106
- if (!sessionIdToDelete) {
107
- try { sessionIdToDelete = JSON.parse(fs.readFileSync(path.join(sessionsDir, 'sessions.json'), 'utf8'))[thread.session_key]?.sessionId; } catch { /* ok */ }
108
- }
109
- cleanGatewaySession(thread.session_key);
110
- if (sessionIdToDelete) { try { fs.unlinkSync(path.join(sessionsDir, `${sessionIdToDelete}.jsonl`)); } catch { /* ok */ } }
111
115
  try { fs.rmSync(path.join(this.uploadsDir, params.id), { recursive: true }); } catch { /* ok */ }
112
116
  send(res, 200, { ok: true });
113
117
  }
118
+
114
119
  }
@@ -2,16 +2,17 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { send, sendError, parseBody } from '../util/http.js';
4
4
  import { validateAgent } from '../config.js';
5
- import { cleanGatewaySession, cleanGatewaySessionsByPrefix } from '../gateway-cleanup.js';
5
+ import { cleanGatewaySession } from '../gateway-cleanup.js';
6
6
 
7
7
  export class WorkspaceController {
8
- constructor({ getDb, closeDb, getWorkspaces, setWorkspaces, dataDir, broadcast }) {
8
+ constructor({ getDb, closeDb, getWorkspaces, setWorkspaces, dataDir, broadcast, sync }) {
9
9
  this.getDb = getDb;
10
10
  this.closeDb = closeDb;
11
11
  this.getWorkspaces = getWorkspaces;
12
12
  this.setWorkspaces = setWorkspaces;
13
13
  this.dataDir = dataDir;
14
14
  this.broadcast = broadcast;
15
+ this.sync = sync;
15
16
  }
16
17
 
17
18
  getAll(req, res) {
@@ -33,7 +34,10 @@ export class WorkspaceController {
33
34
  if (ws.workspaces[name]) return sendError(res, 409, 'Workspace already exists');
34
35
  let agent = 'main';
35
36
  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
+ // 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 };
37
41
  this.setWorkspaces(ws);
38
42
  this.getDb(name);
39
43
  send(res, 201, { workspace: ws.workspaces[name] });
@@ -43,7 +47,10 @@ export class WorkspaceController {
43
47
  const body = await parseBody(req);
44
48
  const ws = this.getWorkspaces();
45
49
  if (!ws.workspaces[params.name]) return sendError(res, 404, 'Workspace not found');
46
- if (body.label !== undefined) ws.workspaces[params.name].label = body.label;
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
+ }
47
54
  if (body.color !== undefined) ws.workspaces[params.name].color = body.color;
48
55
  if (body.icon !== undefined) ws.workspaces[params.name].icon = body.icon;
49
56
  if (body.lastThread !== undefined) ws.workspaces[params.name].lastThread = body.lastThread;
@@ -66,16 +73,21 @@ export class WorkspaceController {
66
73
  send(res, 200, { workspace: ws.workspaces[params.name], migratedThreads });
67
74
  }
68
75
 
69
- delete(req, res, params) {
76
+ async delete(req, res, params) {
70
77
  const ws = this.getWorkspaces();
71
78
  if (!ws.workspaces[params.name]) return sendError(res, 404, 'Workspace not found');
72
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
+ });
73
88
  this.closeDb(params.name);
74
89
  const dbPath = path.join(this.dataDir, `${params.name}.db`);
75
90
  for (const suffix of ['', '-wal', '-shm']) { try { fs.unlinkSync(dbPath + suffix); } catch { /* ok */ } }
76
- const wsAgent = ws.workspaces[params.name]?.agent || 'main';
77
- const cleaned = cleanGatewaySessionsByPrefix(`agent:${wsAgent}:${params.name}:chat:`);
78
- if (cleaned > 0) console.log(`Cleaned ${cleaned} gateway sessions for workspace: ${params.name}`);
79
91
  delete ws.workspaces[params.name];
80
92
  if (ws.active === params.name) ws.active = Object.keys(ws.workspaces)[0] || null;
81
93
  this.setWorkspaces(ws);
@@ -86,6 +98,8 @@ export class WorkspaceController {
86
98
  const body = await parseBody(req);
87
99
  if (!Array.isArray(body.order)) return sendError(res, 400, 'order must be an array of workspace names');
88
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));
89
103
  body.order.forEach((name, i) => { if (ws.workspaces[name]) ws.workspaces[name].order = i; });
90
104
  this.setWorkspaces(ws);
91
105
  send(res, 200, { ok: true, workspaces: Object.values(ws.workspaces) });
@@ -1,47 +1,31 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { getSessionsDirForAgent } from './config.js';
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
4
 
5
- export function cleanGatewaySession(sessionKey) {
6
- try {
7
- const agentMatch = (sessionKey || '').match(/^agent:([^:]+):/);
8
- const sessionsDir = getSessionsDirForAgent(agentMatch?.[1]);
9
- const sessionsPath = path.join(sessionsDir, 'sessions.json');
10
- const store = JSON.parse(fs.readFileSync(sessionsPath, 'utf8'));
11
- const entry = store[sessionKey];
12
- if (!entry) return null;
13
- if (entry.sessionId) {
14
- try { fs.unlinkSync(path.join(sessionsDir, `${entry.sessionId}.jsonl`)); } catch { /* ok */ }
15
- }
16
- const sessionId = entry.sessionId || null;
17
- delete store[sessionKey];
18
- fs.writeFileSync(sessionsPath, JSON.stringify(store, null, 2));
19
- return sessionId;
20
- } catch (err) {
21
- console.warn(`cleanGatewaySession(${sessionKey}):`, err.message);
22
- return null;
23
- }
5
+ let _gatewayClient = null;
6
+
7
+ export function setGatewayClient(client) {
8
+ _gatewayClient = client;
24
9
  }
25
10
 
26
- export function cleanGatewaySessionsByPrefix(prefix) {
11
+ /** Delete one gateway session (row + transcript). Best effort; never throws. */
12
+ export async function cleanGatewaySession(sessionKey) {
13
+ if (!sessionKey || !_gatewayClient) return false;
27
14
  try {
28
- const agentMatch = (prefix || '').match(/^agent:([^:]+):/);
29
- const sessionsDir = getSessionsDirForAgent(agentMatch?.[1]);
30
- const sessionsPath = path.join(sessionsDir, 'sessions.json');
31
- const store = JSON.parse(fs.readFileSync(sessionsPath, 'utf8'));
32
- let cleaned = 0;
33
- for (const key of Object.keys(store)) {
34
- if (!key.startsWith(prefix)) continue;
35
- if (store[key]?.sessionId) {
36
- try { fs.unlinkSync(path.join(sessionsDir, `${store[key].sessionId}.jsonl`)); } catch { /* ok */ }
37
- }
38
- delete store[key];
39
- cleaned++;
40
- }
41
- if (cleaned > 0) fs.writeFileSync(sessionsPath, JSON.stringify(store, null, 2));
42
- return cleaned;
15
+ await _gatewayClient.request('sessions.delete', { key: sessionKey, deleteTranscript: true });
16
+ return true;
43
17
  } catch (err) {
44
- console.warn(`cleanGatewaySessionsByPrefix(${prefix}):`, err.message);
45
- return 0;
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;
46
23
  }
47
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
+ }