@clawchatsai/connector 0.1.14 → 0.1.15

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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawchatsai/connector",
3
- "version": "0.1.14",
3
+ "version": "0.1.15",
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",
@@ -2,7 +2,6 @@ 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
5
  import { cleanGatewaySession } from '../gateway-cleanup.js';
7
6
 
8
7
  export class ThreadController {
@@ -100,15 +99,9 @@ export class ThreadController {
100
99
  const thread = db.prepare('SELECT * FROM threads WHERE id = ?').get(params.id);
101
100
  if (!thread) return sendError(res, 404, 'Thread not found');
102
101
  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 */ } }
102
+ cleanGatewaySession(thread.session_key); // async, best effort
111
103
  try { fs.rmSync(path.join(this.uploadsDir, params.id), { recursive: true }); } catch { /* ok */ }
112
104
  send(res, 200, { ok: true });
113
105
  }
106
+
114
107
  }
@@ -2,7 +2,7 @@ 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, cleanGatewaySessions } from '../gateway-cleanup.js';
6
6
 
7
7
  export class WorkspaceController {
8
8
  constructor({ getDb, closeDb, getWorkspaces, setWorkspaces, dataDir, broadcast }) {
@@ -70,12 +70,13 @@ export class WorkspaceController {
70
70
  const ws = this.getWorkspaces();
71
71
  if (!ws.workspaces[params.name]) return sendError(res, 404, 'Workspace not found');
72
72
  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
+ let sessionKeys = [];
75
+ 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 */ }
73
76
  this.closeDb(params.name);
74
77
  const dbPath = path.join(this.dataDir, `${params.name}.db`);
75
78
  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
+ cleanGatewaySessions(sessionKeys).then(n => { if (n > 0) console.log(`Cleaned ${n} gateway sessions for workspace: ${params.name}`); });
79
80
  delete ws.workspaces[params.name];
80
81
  if (ws.active === params.name) ws.active = Object.keys(ws.workspaces)[0] || null;
81
82
  this.setWorkspaces(ws);
@@ -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
+ }
package/server/gateway.js CHANGED
@@ -3,6 +3,19 @@ import { WebSocket as WS } from 'ws';
3
3
  import { loadOrCreateDeviceIdentity, buildDeviceAuth } from './bootstrap/identity.js';
4
4
  import { parseSessionKey, extractContent, isSilentReplyExact, isSilentReplyPrefix, sanitizeAssistantContent, syncThreadUnreadCount, generateActivitySummary, writeActivityToDb } from './util/helpers.js';
5
5
 
6
+ /**
7
+ * Cumulative assistant text for a `chat` delta event.
8
+ * Protocol-v4 gateways (2026.9+) send appends in `deltaText`; only the first frame of a
9
+ * run (and any new baseline) carries the full `message` snapshot, which already includes
10
+ * the delta. `replace: true` makes `deltaText` the entire text. Older gateways send the
11
+ * full cumulative `message` on every delta, which the snapshot branch covers.
12
+ */
13
+ export function nextChatText(prev, params) {
14
+ if (params?.message) return extractContent(params.message);
15
+ if (typeof params?.deltaText !== 'string') return prev || '';
16
+ return params.replace ? params.deltaText : (prev || '') + params.deltaText;
17
+ }
18
+
6
19
  export class GatewayClient {
7
20
  constructor({ getDb, getWorkspaces, dataDir, debugLogger, gatewayWsUrl, authToken }) {
8
21
  this.getDb = getDb;
@@ -26,6 +39,9 @@ export class GatewayClient {
26
39
  this.browserClients = new Map();
27
40
  this._externalBroadcastTargets = [];
28
41
  this.streamState = new Map();
42
+ this._utilityText = new Map(); // sessionKey → accumulated delta text for utility sessions
43
+ this._rpc = new Map(); // request id → { resolve, reject, timer } for connector-originated RPCs
44
+ this._rpcSeq = 0;
29
45
  this.activityLogs = new Map();
30
46
  this._pendingTitleGens = new Map();
31
47
  // Runs we've already synthesized a streaming-end{reason:'error'} for
@@ -84,6 +100,16 @@ export class GatewayClient {
84
100
  let msg;
85
101
  try { msg = JSON.parse(data); } catch { console.error('Invalid JSON from gateway:', data); return; }
86
102
 
103
+ // Responses to the connector's own RPCs (request()) are not browser traffic.
104
+ if (msg.type === 'res' && this._rpc.has(msg.id)) {
105
+ const pending = this._rpc.get(msg.id);
106
+ this._rpc.delete(msg.id);
107
+ clearTimeout(pending.timer);
108
+ if (msg.ok) pending.resolve(msg.payload);
109
+ else pending.reject(new Error(msg.error?.message || `${pending.method} failed`));
110
+ return;
111
+ }
112
+
87
113
  if (msg.type === 'event' && msg.event === 'connect.challenge') {
88
114
  const identity = loadOrCreateDeviceIdentity(path.join(this.dataDir, 'device-identity.json'));
89
115
  const device = buildDeviceAuth(identity, { clientId: 'gateway-client', clientMode: 'backend', role: 'operator', scopes: ['operator.read', 'operator.write', 'operator.admin'], token: this.authToken, nonce: msg.payload?.nonce || '' });
@@ -109,7 +135,8 @@ export class GatewayClient {
109
135
  const UTILITY_SESSIONS = { '__clawchats_summarizer': 'summarizer', '__clawchats_semantic': 'semantic', '__clawchats_intelligence': 'intelligence' };
110
136
  const utilityName = UTILITY_SESSIONS[bareSessionKey];
111
137
  if (utilityName) {
112
- const content = extractContent(message);
138
+ const content = state === 'delta' ? this._accumulateChatText(sessionKey, params) : extractContent(message);
139
+ if (state !== 'delta') this._utilityText.delete(sessionKey);
113
140
  if (state === 'delta' && content) {
114
141
  this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'utility-response', session: utilityName, state: 'delta', content }));
115
142
  } else if (state === 'final' || state === 'aborted') {
@@ -127,7 +154,8 @@ export class GatewayClient {
127
154
  if (parsed) {
128
155
  const existing = this.streamState.get(sessionKey) || { buffer: '', threadId: parsed.threadId, state: 'streaming', held: [] };
129
156
  const prevLen = existing.buffer.length; // capture before update — used to advance thoughtStartOffset on first post-tool delta
130
- existing.buffer = extractContent(message); // gateway sends full cumulative content per delta, not chunks
157
+ const prevBuffer = existing.buffer;
158
+ existing.buffer = nextChatText(existing.buffer, params);
131
159
  if (isSilentReplyPrefix(existing.buffer, 'NO_REPLY') || isSilentReplyPrefix(existing.buffer, 'HEARTBEAT_OK')) {
132
160
  existing.held = existing.held || [];
133
161
  existing.held.push(rawData);
@@ -144,7 +172,9 @@ export class GatewayClient {
144
172
  // frontend to clear the bubble. Both happen here — right before the new-segment delta —
145
173
  // so the clear and fill are atomic from the browser's perspective.
146
174
  if (existing.pendingReset) {
147
- existing.thoughtStartOffset = prevLen;
175
+ // A v4 gateway may open the post-tool segment with a fresh snapshot instead of
176
+ // extending the run text; only skip the old text if it's still a prefix.
177
+ existing.thoughtStartOffset = existing.buffer.startsWith(prevBuffer) ? prevLen : 0;
148
178
  existing.pendingReset = false;
149
179
  this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'streaming-reset', threadId: parsed.threadId, workspace: parsed.workspace }));
150
180
  }
@@ -218,6 +248,24 @@ export class GatewayClient {
218
248
  }
219
249
  }
220
250
 
251
+ // Gateway RPC from the connector itself; resolves with the response payload.
252
+ request(method, params = {}, timeoutMs = 15000) {
253
+ return new Promise((resolve, reject) => {
254
+ if (!this.connected || !this.ws || this.ws.readyState !== 1) return reject(new Error('gateway not connected'));
255
+ const id = `cc-rpc-${++this._rpcSeq}`;
256
+ const timer = setTimeout(() => { this._rpc.delete(id); reject(new Error(`${method} timed out`)); }, timeoutMs);
257
+ this._rpc.set(id, { resolve, reject, timer, method });
258
+ this.ws.send(JSON.stringify({ type: 'req', id, method, params }));
259
+ });
260
+ }
261
+
262
+ // Utility sessions keep no streamState entry; accumulate their delta text separately.
263
+ _accumulateChatText(sessionKey, params) {
264
+ const text = nextChatText(this._utilityText.get(sessionKey) || '', params);
265
+ this._utilityText.set(sessionKey, text);
266
+ return text;
267
+ }
268
+
221
269
  // Removes metadata.pending flag from any pending assistant message for a thread.
222
270
  // Called on abort and by _cleanupSilentPending — keeps the SQL in one place.
223
271
  _clearPendingFlag(db, threadId) {
@@ -253,7 +301,10 @@ export class GatewayClient {
253
301
  // Trim to final-answer portion: only text after the last tool call offset.
254
302
  // thoughtStartOffset is passed in from handleChatEvent (captured before streamState.delete).
255
303
  // Intermediate narration lives in activityLog steps; message.content is the clean final answer.
256
- let content = sanitizeAssistantContent(extractContent(message).substring(thoughtStartOffset));
304
+ const fullContent = extractContent(message);
305
+ // Never let a stale segment offset blank the reply (v4 snapshots can be shorter).
306
+ if (thoughtStartOffset > fullContent.length) thoughtStartOffset = 0;
307
+ let content = sanitizeAssistantContent(fullContent.substring(thoughtStartOffset));
257
308
 
258
309
  // Attach media (MEDIA: paths extracted from exec tool args by handleAgentEvent).
259
310
  // Buffer is read before the empty-content guard — media-only responses (no text) must not be dropped.
package/server/index.js CHANGED
@@ -22,7 +22,7 @@ import { handleStatic } from './controllers/static.js';
22
22
  import { handleAgents } from './controllers/agents.js';
23
23
  import { createSettingsHandlers } from './controllers/settings.js';
24
24
  import { createWorkspaceStore } from './store/workspace-store.js';
25
- import { cleanGatewaySession } from './gateway-cleanup.js';
25
+ import { cleanGatewaySession, setGatewayClient } from './gateway-cleanup.js';
26
26
  import { parseSessionKey } from './util/helpers.js';
27
27
  import { send, sendError, parseBody, uuid, matchRoute, setCors } from './util/http.js';
28
28
 
@@ -92,6 +92,7 @@ export function createApp(config = {}) {
92
92
  // Instantiate the gateway client with all dependencies injected
93
93
  const gatewayClient = new GatewayClient({ getDb, getWorkspaces, dataDir: DATA_DIR, debugLogger, gatewayWsUrl: gatewayUrl, authToken: gatewayToken });
94
94
  const broadcast = msg => gatewayClient.broadcastToBrowsers(msg);
95
+ setGatewayClient(gatewayClient);
95
96
 
96
97
  // Instantiate controllers
97
98
  const workspaces = new WorkspaceController({ getDb, closeDb, getWorkspaces, setWorkspaces, dataDir: DATA_DIR, broadcast });