@clawchatsai/connector 0.1.15 → 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
@@ -1148,6 +1148,37 @@ async function handleReauth() {
1148
1148
  console.log(' Restart the gateway for changes to take effect: systemctl --user restart openclaw-gateway');
1149
1149
  }
1150
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
+ }
1151
1182
  async function handleStatus() {
1152
1183
  // CLI runs in a separate process — module-level vars are null here.
1153
1184
  // Query the live service via the health endpoint instead.
@@ -1312,6 +1343,9 @@ const plugin = {
1312
1343
  cmd.command('reset')
1313
1344
  .description('Disconnect and remove all ClawChats data')
1314
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)));
1315
1349
  cmd.command('import <path>')
1316
1350
  .description('Import databases and config from a folder (e.g. migrate from old data directory)')
1317
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.15",
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",
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,14 +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 { cleanGatewaySession } from '../gateway-cleanup.js';
6
5
 
7
6
  export class ThreadController {
8
- constructor({ getActiveDb, getWorkspaces, uploadsDir, broadcast }) {
7
+ constructor({ getActiveDb, getWorkspaces, uploadsDir, broadcast, sync }) {
9
8
  this.getActiveDb = getActiveDb;
10
9
  this.getWorkspaces = getWorkspaces;
11
10
  this.uploadsDir = uploadsDir;
12
11
  this.broadcast = broadcast;
12
+ this.sync = sync;
13
13
  }
14
14
 
15
15
  getAll(req, res, params, query) {
@@ -77,7 +77,19 @@ export class ThreadController {
77
77
  async update(req, res, params) {
78
78
  const body = await parseBody(req);
79
79
  const db = this.getActiveDb();
80
- if (!db.prepare('SELECT id FROM threads WHERE id = ?').get(params.id)) return sendError(res, 404, 'Thread not found');
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
+ }
81
93
  const fields = [], values = [];
82
94
  for (const [col, val] of [['title', body.title], ['model', body.model], ['last_session_id', body.last_session_id], ['unread_count', body.unread_count]]) {
83
95
  if (val !== undefined) { fields.push(`${col} = ?`); values.push(val); }
@@ -94,12 +106,12 @@ export class ThreadController {
94
106
  send(res, 200, { thread: db.prepare('SELECT * FROM threads WHERE id = ?').get(params.id) });
95
107
  }
96
108
 
97
- delete(req, res, params) {
109
+ async delete(req, res, params) {
98
110
  const db = this.getActiveDb();
99
111
  const thread = db.prepare('SELECT * FROM threads WHERE id = ?').get(params.id);
100
112
  if (!thread) return sendError(res, 404, 'Thread not found');
113
+ await this.sync.push(() => this.sync.deleteSession(thread.session_key));
101
114
  db.prepare('DELETE FROM threads WHERE id = ?').run(params.id);
102
- cleanGatewaySession(thread.session_key); // async, best effort
103
115
  try { fs.rmSync(path.join(this.uploadsDir, params.id), { recursive: true }); } catch { /* ok */ }
104
116
  send(res, 200, { ok: true });
105
117
  }
@@ -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, cleanGatewaySessions } 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,17 +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');
73
- // Collect the workspace's gateway session keys before its DB is removed.
74
80
  let sessionKeys = [];
75
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
+ });
76
88
  this.closeDb(params.name);
77
89
  const dbPath = path.join(this.dataDir, `${params.name}.db`);
78
90
  for (const suffix of ['', '-wal', '-shm']) { try { fs.unlinkSync(dbPath + suffix); } catch { /* ok */ } }
79
- cleanGatewaySessions(sessionKeys).then(n => { if (n > 0) console.log(`Cleaned ${n} gateway sessions for workspace: ${params.name}`); });
80
91
  delete ws.workspaces[params.name];
81
92
  if (ws.active === params.name) ws.active = Object.keys(ws.workspaces)[0] || null;
82
93
  this.setWorkspaces(ws);
@@ -87,6 +98,8 @@ export class WorkspaceController {
87
98
  const body = await parseBody(req);
88
99
  if (!Array.isArray(body.order)) return sendError(res, 400, 'order must be an array of workspace names');
89
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));
90
103
  body.order.forEach((name, i) => { if (ws.workspaces[name]) ws.workspaces[name].order = i; });
91
104
  this.setWorkspaces(ws);
92
105
  send(res, 200, { ok: true, workspaces: Object.values(ws.workspaces) });