@clawchatsai/connector 0.1.11 → 0.1.13

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
@@ -13,6 +13,7 @@ import * as fs from 'node:fs';
13
13
  import * as http from 'node:http';
14
14
  import * as os from 'node:os';
15
15
  import * as path from 'node:path';
16
+ import { createRequire } from 'node:module';
16
17
  import { SignalingClient } from './signaling-client.js';
17
18
  import { dispatchRpc } from './shim.js';
18
19
  import { initAuth, handleAuthMessage, cleanupAuth } from './auth-handler.js';
@@ -103,7 +104,20 @@ function getPrebuildKey() {
103
104
  }
104
105
  async function ensureNativeModules(ctx) {
105
106
  const pluginDir = path.resolve(__dirname, '..');
106
- const targetPath = path.join(pluginDir, 'node_modules', 'node-datachannel', 'build', 'Release', 'node_datachannel.node');
107
+ // Resolve node-datachannel's actual install root (handles npm hoisting).
108
+ // Writing to <pluginDir>/node_modules/node-datachannel/ would create a
109
+ // package-shaped directory that lacks package.json + JS, shadowing the
110
+ // hoisted copy and breaking subpath imports like 'node-datachannel/polyfill'.
111
+ const require = createRequire(import.meta.url);
112
+ let ndcRoot;
113
+ try {
114
+ ndcRoot = path.dirname(require.resolve('node-datachannel/package.json'));
115
+ }
116
+ catch {
117
+ ctx.logger.error('[clawchats] node-datachannel package not resolvable; WebRTC unavailable.');
118
+ return;
119
+ }
120
+ const targetPath = path.join(ndcRoot, 'build', 'Release', 'node_datachannel.node');
107
121
  // Already built — nothing to do.
108
122
  if (fs.existsSync(targetPath))
109
123
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawchatsai/connector",
3
- "version": "0.1.11",
3
+ "version": "0.1.13",
4
4
  "type": "module",
5
5
  "description": "ClawChats OpenClaw plugin — P2P tunnel + local API bridge",
6
6
  "main": "dist/index.js",
package/server/gateway.js CHANGED
@@ -33,6 +33,16 @@ export class GatewayClient {
33
33
  // double-fires across retries and cross-path dedup with handleChatEvent.
34
34
  this._syntheticErrorRuns = new Set();
35
35
 
36
+ // Runs that already delivered a reply the user can see (persisted + broadcast).
37
+ // The gateway may report a run-level fault AFTER the reply is delivered — a retried
38
+ // tool call, or a post_turn/gateway_draining fault (see OpenClaw's
39
+ // AGENT_RUN_TERMINAL_RETRY_GRACE_MS deferral). Those describe the run, not the reply,
40
+ // and must never overwrite a message the user already read. Keyed by runId because
41
+ // sessionKey is stable for the whole thread — a late error from turn N must not be
42
+ // confused with a live error from turn N+1. Mirrors the OCPlatform TUI's
43
+ // finalizedRunsWithDisplay guard.
44
+ this._runsWithDeliveredReply = new Set();
45
+
36
46
  // On startup: mark any pending activity log messages from previous crashed/restarted sessions
37
47
  // as interrupted. Without this, stale pending=true rows survive gateway restarts and cause
38
48
  // phantom "thinking..." indicators in the browser on reconnect.
@@ -77,7 +87,7 @@ export class GatewayClient {
77
87
  if (msg.type === 'event' && msg.event === 'connect.challenge') {
78
88
  const identity = loadOrCreateDeviceIdentity(path.join(this.dataDir, 'device-identity.json'));
79
89
  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 || '' });
80
- this.ws.send(JSON.stringify({ type: 'req', id: 'gw-connect-1', method: 'connect', params: { minProtocol: 3, maxProtocol: 3, client: { id: 'gateway-client', version: '0.1.0', platform: 'node', mode: 'backend' }, role: 'operator', scopes: ['operator.read', 'operator.write', 'operator.admin'], device, auth: { token: this.authToken }, caps: ['tool-events'] } }));
90
+ this.ws.send(JSON.stringify({ type: 'req', id: 'gw-connect-1', method: 'connect', params: { minProtocol: 3, maxProtocol: 4, client: { id: 'gateway-client', version: '0.1.0', platform: 'node', mode: 'backend' }, role: 'operator', scopes: ['operator.read', 'operator.write', 'operator.admin'], device, auth: { token: this.authToken }, caps: ['tool-events'] } }));
81
91
  return;
82
92
  }
83
93
  if (msg.type === 'res' && msg.payload?.type === 'hello-ok') { console.log('Gateway handshake complete'); this.connected = true; this.broadcastGatewayStatus(true); }
@@ -90,7 +100,7 @@ export class GatewayClient {
90
100
  }
91
101
 
92
102
  handleChatEvent(params, rawData) {
93
- const { sessionKey, state, message, seq, errorMessage: gwErrorMessage } = params;
103
+ const { sessionKey, state, message, seq, runId, errorMessage: gwErrorMessage } = params;
94
104
  const bareSessionKey = sessionKey.replace(/^agent:[^:]+:/, '');
95
105
 
96
106
  // --- Utility session routing (connector-side) ---
@@ -168,7 +178,8 @@ export class GatewayClient {
168
178
  return;
169
179
  }
170
180
  if (streamEntry?.held?.length > 0) for (const h of streamEntry.held) this.broadcastToBrowsers(h);
171
- this.saveAssistantMessage(sessionKey, message, seq, streamEntry?.thoughtStartOffset); // persist + broadcast message-saved first
181
+ const delivered = this.saveAssistantMessage(sessionKey, message, seq, streamEntry?.thoughtStartOffset); // persist + broadcast message-saved first
182
+ if (delivered && runId) this._runsWithDeliveredReply.add(runId);
172
183
  this.broadcastToBrowsers(rawData); // dual-emit: raw final event
173
184
  if (parsed) {
174
185
  const activity = this._popActivityLogForSession(sessionKey);
@@ -190,6 +201,13 @@ export class GatewayClient {
190
201
  this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'streaming-end', threadId: parsed.threadId, workspace: parsed.workspace, reason: 'aborted', ...(activity || {}) }));
191
202
  }
192
203
  } else if (state === 'error') {
204
+ // Late run-level fault for a run that already delivered its reply — drop it.
205
+ // Emitting streaming-end{reason:'error'} here makes the browser replace the
206
+ // rendered answer with an error bubble, destroying a message the user already read.
207
+ if (runId && this._runsWithDeliveredReply.has(runId)) {
208
+ console.log(`[clawchats] ignoring late error for run ${runId} — reply already delivered`);
209
+ return;
210
+ }
193
211
  const parsed = parseSessionKey(sessionKey);
194
212
  this.saveErrorMarker(sessionKey, message);
195
213
  this.broadcastToBrowsers(rawData); // dual-emit
@@ -221,13 +239,16 @@ export class GatewayClient {
221
239
  // Caller broadcasts streaming-end { reason: 'silent' } — no event emitted here.
222
240
  }
223
241
 
242
+ // Returns true when a reply was actually persisted for this run, false on every
243
+ // early-out. handleChatEvent uses the result to decide whether the run counts as
244
+ // having delivered a visible reply.
224
245
  saveAssistantMessage(sessionKey, message, seq, thoughtStartOffset = 0) {
225
246
  const parsed = parseSessionKey(sessionKey);
226
- if (!parsed) return;
247
+ if (!parsed) return false;
227
248
  const ws = this.getWorkspaces();
228
- if (!ws.workspaces[parsed.workspace]) { console.log(`Ignoring response for deleted workspace: ${parsed.workspace}`); return; }
249
+ if (!ws.workspaces[parsed.workspace]) { console.log(`Ignoring response for deleted workspace: ${parsed.workspace}`); return false; }
229
250
  const db = this.getDb(parsed.workspace);
230
- if (!db.prepare('SELECT id FROM threads WHERE id = ?').get(parsed.threadId)) { console.log(`Ignoring response for deleted thread: ${parsed.threadId}`); return; }
251
+ if (!db.prepare('SELECT id FROM threads WHERE id = ?').get(parsed.threadId)) { console.log(`Ignoring response for deleted thread: ${parsed.threadId}`); return false; }
231
252
 
232
253
  // Trim to final-answer portion: only text after the last tool call offset.
233
254
  // thoughtStartOffset is passed in from handleChatEvent (captured before streamState.delete).
@@ -256,7 +277,7 @@ export class GatewayClient {
256
277
  // If a pending row exists, always proceed to update it (even with empty content) so the
257
278
  // pending flag is cleared. Without this, tool-only responses (no post-tool text) leave
258
279
  // pending=true forever, and the startup cleanup marks them '[Response interrupted]'.
259
- if (!content?.trim() && pendingPaths.length === 0 && !pendingMsg) { console.log(`Skipping empty assistant response for thread ${parsed.threadId}`); return; }
280
+ if (!content?.trim() && pendingPaths.length === 0 && !pendingMsg) { console.log(`Skipping empty assistant response for thread ${parsed.threadId}`); return false; }
260
281
  let messageId;
261
282
 
262
283
  if (pendingMsg) {
@@ -285,6 +306,9 @@ export class GatewayClient {
285
306
  const msgCount = db.prepare('SELECT COUNT(*) as c FROM messages WHERE thread_id = ?').get(parsed.threadId).c;
286
307
  if (msgCount === 2 || threadInfo?.title === 'New chat') this.generateThreadTitle(db, parsed.threadId, parsed.workspace, true);
287
308
  } catch (e) { console.error('Failed to save assistant message:', e.message); }
309
+ // The message row is written above the try block, so it is persisted even if the
310
+ // follow-up bookkeeping/broadcast throws — the reply was delivered either way.
311
+ return true;
288
312
  }
289
313
 
290
314
  saveErrorMarker(sessionKey, message) {
@@ -453,7 +477,10 @@ export class GatewayClient {
453
477
  // broadcast is gated off upstream), handleChatEvent won't fire a
454
478
  // streaming-end and the UI stays locked on "thinking…" forever. Synthesize
455
479
  // one here so the frontend's existing error path (`reason: 'error'`) runs.
456
- if (data?.phase === 'error' && !this.streamState.has(sessionKey) && !this._syntheticErrorRuns.has(runId)) {
480
+ // `!streamState.has(sessionKey)` is also true for a run that finished cleanly (the entry
481
+ // is deleted on every terminal state), so the delivered-reply check is what distinguishes
482
+ // "never produced a reply" from "already delivered one".
483
+ if (data?.phase === 'error' && !this.streamState.has(sessionKey) && !this._syntheticErrorRuns.has(runId) && !this._runsWithDeliveredReply.has(runId)) {
457
484
  this._syntheticErrorRuns.add(runId);
458
485
  const parsed = parseSessionKey(sessionKey);
459
486
  if (parsed) {