@clawchatsai/connector 0.1.13 → 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 +37 -67
- package/package.json +5 -2
- package/server/controllers/threads.js +2 -9
- package/server/controllers/workspaces.js +5 -4
- package/server/gateway-cleanup.js +24 -40
- package/server/gateway.js +55 -4
- package/server/index.js +2 -1
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
|
// ---------------------------------------------------------------------------
|
|
@@ -102,18 +101,42 @@ function getPrebuildKey() {
|
|
|
102
101
|
return `linuxmusl-${arch}`;
|
|
103
102
|
return `${platform}-${arch}`;
|
|
104
103
|
}
|
|
104
|
+
/**
|
|
105
|
+
* Resolve a package's install root without relying on subpath access to its
|
|
106
|
+
* package.json. Node treats an "exports" map as an allowlist, so
|
|
107
|
+
* require.resolve('<pkg>/package.json') throws for any package that does not
|
|
108
|
+
* explicitly export it. Resolving the main entry is always permitted, so walk
|
|
109
|
+
* up from there to the directory named after the package.
|
|
110
|
+
*/
|
|
111
|
+
function resolvePackageRoot(require, pkgName) {
|
|
112
|
+
let entry;
|
|
113
|
+
try {
|
|
114
|
+
entry = require.resolve(pkgName);
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
const marker = `${path.sep}${pkgName}${path.sep}`;
|
|
120
|
+
const idx = entry.lastIndexOf(marker);
|
|
121
|
+
if (idx === -1)
|
|
122
|
+
return undefined;
|
|
123
|
+
return entry.slice(0, idx + marker.length - 1);
|
|
124
|
+
}
|
|
105
125
|
async function ensureNativeModules(ctx) {
|
|
106
126
|
const pluginDir = path.resolve(__dirname, '..');
|
|
107
127
|
// Resolve node-datachannel's actual install root (handles npm hoisting).
|
|
108
128
|
// Writing to <pluginDir>/node_modules/node-datachannel/ would create a
|
|
109
129
|
// package-shaped directory that lacks package.json + JS, shadowing the
|
|
110
130
|
// hoisted copy and breaking subpath imports like 'node-datachannel/polyfill'.
|
|
131
|
+
//
|
|
132
|
+
// Resolve via the package's main entry, NOT 'node-datachannel/package.json':
|
|
133
|
+
// node-datachannel's exports map declares only "." and "./polyfill", so asking
|
|
134
|
+
// for the package.json subpath always throws ERR_PACKAGE_PATH_NOT_EXPORTED.
|
|
135
|
+
// That made this function bail out before copying anything on every install;
|
|
136
|
+
// it only appeared to work where a binary already existed from a source build.
|
|
111
137
|
const require = createRequire(import.meta.url);
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
ndcRoot = path.dirname(require.resolve('node-datachannel/package.json'));
|
|
115
|
-
}
|
|
116
|
-
catch {
|
|
138
|
+
const ndcRoot = resolvePackageRoot(require, 'node-datachannel');
|
|
139
|
+
if (!ndcRoot) {
|
|
117
140
|
ctx.logger.error('[clawchats] node-datachannel package not resolvable; WebRTC unavailable.');
|
|
118
141
|
return;
|
|
119
142
|
}
|
|
@@ -137,7 +160,12 @@ async function ensureNativeModules(ctx) {
|
|
|
137
160
|
ctx.logger.info('[clawchats] node-datachannel ready.');
|
|
138
161
|
}
|
|
139
162
|
catch (e) {
|
|
140
|
-
|
|
163
|
+
// Surface the manual remedy: the service import fails moments later with an
|
|
164
|
+
// opaque "Cannot find module '../../../build/Release/node_datachannel.node'",
|
|
165
|
+
// which says nothing about what to actually do.
|
|
166
|
+
ctx.logger.error(`[clawchats] Failed to install prebuilt: ${e.message}\n` +
|
|
167
|
+
` To fix manually:\n mkdir -p ${path.dirname(targetPath)}\n` +
|
|
168
|
+
` cp ${prebuiltPath} ${targetPath}`);
|
|
141
169
|
}
|
|
142
170
|
}
|
|
143
171
|
const CLAWCHATS_MD_CONTENT = `# ClawChats — Inline File Delivery
|
|
@@ -235,7 +263,6 @@ async function startClawChats(ctx, api) {
|
|
|
235
263
|
// 4. Import server.js and create app instance with plugin paths
|
|
236
264
|
const dataDir = path.join(ctx.stateDir, 'clawchats', 'data');
|
|
237
265
|
const uploadsDir = path.join(ctx.stateDir, 'clawchats', 'uploads');
|
|
238
|
-
_uploadsDir = uploadsDir;
|
|
239
266
|
// Dynamic import of server.js (plain JS, no type declarations)
|
|
240
267
|
// @ts-expect-error — server/index.js is plain JS with no .d.ts
|
|
241
268
|
const serverModule = await import('../server/index.js');
|
|
@@ -412,63 +439,6 @@ async function stopClawChats(ctx) {
|
|
|
412
439
|
* Injecting a minimal placeholder ensures the agent run proceeds.
|
|
413
440
|
*/
|
|
414
441
|
// Track which ClawChats thread sessions have received the capability note (once per session).
|
|
415
|
-
function normalizeGatewayPayload(raw) {
|
|
416
|
-
try {
|
|
417
|
-
const parsed = JSON.parse(raw);
|
|
418
|
-
if (parsed.method === 'chat.send' && typeof parsed.params?.message === 'string') {
|
|
419
|
-
// Warn user in-chat if they're sending image attachments to an image-restricted model.
|
|
420
|
-
// The warning is appended to the message so the AI echoes it back — impossible to miss.
|
|
421
|
-
if (Array.isArray(parsed.params?.attachments) &&
|
|
422
|
-
parsed.params.attachments.length > 0 &&
|
|
423
|
-
_imageRestrictedModels.length > 0) {
|
|
424
|
-
parsed.params.message = (parsed.params.message || '').trimEnd() +
|
|
425
|
-
'\n\n[⚠️ ClawChats: image attachment not delivered — your model config is missing "image" input support. ' +
|
|
426
|
-
'Fix: add "image" to the input array for your model in ~/.openclaw/openclaw.json, then restart the gateway.]';
|
|
427
|
-
return JSON.stringify(parsed);
|
|
428
|
-
}
|
|
429
|
-
// Fix image-only messages: inject placeholder so gateway doesn't reject empty body.
|
|
430
|
-
if (Array.isArray(parsed.params?.attachments) &&
|
|
431
|
-
parsed.params.attachments.length > 0 &&
|
|
432
|
-
!parsed.params.message?.trim()) {
|
|
433
|
-
parsed.params.message = '[Image]';
|
|
434
|
-
return JSON.stringify(parsed);
|
|
435
|
-
}
|
|
436
|
-
// Save inline base64 attachments to disk so the agent can reference them as file paths.
|
|
437
|
-
// Runs before capability note so a gateway restart doesn't prevent path injection.
|
|
438
|
-
if (Array.isArray(parsed.params?.attachments) && parsed.params.attachments.length > 0 && _uploadsDir) {
|
|
439
|
-
const skMatch = (parsed.params.sessionKey || '').match(/^agent:[^:]+:[^:]+:chat:([^:]+)$/);
|
|
440
|
-
const threadId = skMatch?.[1] || 'misc';
|
|
441
|
-
const uploadDir = path.join(_uploadsDir, threadId);
|
|
442
|
-
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' };
|
|
443
|
-
const savedPaths = [];
|
|
444
|
-
for (const att of parsed.params.attachments) {
|
|
445
|
-
if (!att.content || !att.mimeType)
|
|
446
|
-
continue;
|
|
447
|
-
try {
|
|
448
|
-
const rawExt = att.mimeType.split('/')[1]?.split(';')[0] || 'bin';
|
|
449
|
-
const ext = extMap[rawExt] || rawExt;
|
|
450
|
-
const fileId = `${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
|
|
451
|
-
const filePath = path.join(uploadDir, `${fileId}.${ext}`);
|
|
452
|
-
fs.mkdirSync(uploadDir, { recursive: true });
|
|
453
|
-
fs.writeFileSync(filePath, Buffer.from(att.content, 'base64'));
|
|
454
|
-
savedPaths.push(filePath);
|
|
455
|
-
}
|
|
456
|
-
catch { /* skip attachment on error */ }
|
|
457
|
-
}
|
|
458
|
-
if (savedPaths.length > 0) {
|
|
459
|
-
const label = savedPaths.length === 1 ? 'Attached file saved on disk' : 'Attached files saved on disk';
|
|
460
|
-
parsed.params.message = parsed.params.message.trimEnd() +
|
|
461
|
-
`\n\n[${label}:\n${savedPaths.map((p) => `- ${p}`).join('\n')}]`;
|
|
462
|
-
return JSON.stringify(parsed);
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
}
|
|
467
|
-
catch {
|
|
468
|
-
// Not JSON or unexpected shape — pass through unchanged
|
|
469
|
-
}
|
|
470
|
-
return raw;
|
|
471
|
-
}
|
|
472
442
|
// DataChannel message handler (spec section 6.4)
|
|
473
443
|
// ---------------------------------------------------------------------------
|
|
474
444
|
function setupDataChannelHandler(dc, connectionId, ctx) {
|
|
@@ -637,7 +607,7 @@ function processAuthenticatedMessage(dc, connectionId, msg, ctx) {
|
|
|
637
607
|
}
|
|
638
608
|
}
|
|
639
609
|
catch { /* ignore parse/db errors */ }
|
|
640
|
-
app.gatewayClient.sendToGateway(
|
|
610
|
+
app.gatewayClient.sendToGateway(_gwPayload);
|
|
641
611
|
}
|
|
642
612
|
break;
|
|
643
613
|
case 'gateway-msg-chunk': {
|
|
@@ -667,7 +637,7 @@ function processAuthenticatedMessage(dc, connectionId, msg, ctx) {
|
|
|
667
637
|
gatewayMsgChunkBuffers.delete(chunkId);
|
|
668
638
|
const fullPayload = buf.chunks.join('');
|
|
669
639
|
if (app?.gatewayClient) {
|
|
670
|
-
app.gatewayClient.sendToGateway(
|
|
640
|
+
app.gatewayClient.sendToGateway(fullPayload);
|
|
671
641
|
}
|
|
672
642
|
}
|
|
673
643
|
break;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clawchatsai/connector",
|
|
3
|
-
"version": "0.1.
|
|
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
|
-
|
|
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,
|
|
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
|
-
|
|
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
|
-
|
|
2
|
-
|
|
3
|
-
|
|
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
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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
|
-
|
|
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
|
-
|
|
29
|
-
|
|
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
|
-
|
|
45
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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 });
|