@clawchatsai/connector 0.1.12 → 0.1.14

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
@@ -102,18 +102,42 @@ function getPrebuildKey() {
102
102
  return `linuxmusl-${arch}`;
103
103
  return `${platform}-${arch}`;
104
104
  }
105
+ /**
106
+ * Resolve a package's install root without relying on subpath access to its
107
+ * package.json. Node treats an "exports" map as an allowlist, so
108
+ * require.resolve('<pkg>/package.json') throws for any package that does not
109
+ * explicitly export it. Resolving the main entry is always permitted, so walk
110
+ * up from there to the directory named after the package.
111
+ */
112
+ function resolvePackageRoot(require, pkgName) {
113
+ let entry;
114
+ try {
115
+ entry = require.resolve(pkgName);
116
+ }
117
+ catch {
118
+ return undefined;
119
+ }
120
+ const marker = `${path.sep}${pkgName}${path.sep}`;
121
+ const idx = entry.lastIndexOf(marker);
122
+ if (idx === -1)
123
+ return undefined;
124
+ return entry.slice(0, idx + marker.length - 1);
125
+ }
105
126
  async function ensureNativeModules(ctx) {
106
127
  const pluginDir = path.resolve(__dirname, '..');
107
128
  // Resolve node-datachannel's actual install root (handles npm hoisting).
108
129
  // Writing to <pluginDir>/node_modules/node-datachannel/ would create a
109
130
  // package-shaped directory that lacks package.json + JS, shadowing the
110
131
  // hoisted copy and breaking subpath imports like 'node-datachannel/polyfill'.
132
+ //
133
+ // Resolve via the package's main entry, NOT 'node-datachannel/package.json':
134
+ // node-datachannel's exports map declares only "." and "./polyfill", so asking
135
+ // for the package.json subpath always throws ERR_PACKAGE_PATH_NOT_EXPORTED.
136
+ // That made this function bail out before copying anything on every install;
137
+ // it only appeared to work where a binary already existed from a source build.
111
138
  const require = createRequire(import.meta.url);
112
- let ndcRoot;
113
- try {
114
- ndcRoot = path.dirname(require.resolve('node-datachannel/package.json'));
115
- }
116
- catch {
139
+ const ndcRoot = resolvePackageRoot(require, 'node-datachannel');
140
+ if (!ndcRoot) {
117
141
  ctx.logger.error('[clawchats] node-datachannel package not resolvable; WebRTC unavailable.');
118
142
  return;
119
143
  }
@@ -137,7 +161,12 @@ async function ensureNativeModules(ctx) {
137
161
  ctx.logger.info('[clawchats] node-datachannel ready.');
138
162
  }
139
163
  catch (e) {
140
- ctx.logger.error(`[clawchats] Failed to install prebuilt: ${e.message}`);
164
+ // Surface the manual remedy: the service import fails moments later with an
165
+ // opaque "Cannot find module '../../../build/Release/node_datachannel.node'",
166
+ // which says nothing about what to actually do.
167
+ ctx.logger.error(`[clawchats] Failed to install prebuilt: ${e.message}\n` +
168
+ ` To fix manually:\n mkdir -p ${path.dirname(targetPath)}\n` +
169
+ ` cp ${prebuiltPath} ${targetPath}`);
141
170
  }
142
171
  }
143
172
  const CLAWCHATS_MD_CONTENT = `# ClawChats — Inline File Delivery
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawchatsai/connector",
3
- "version": "0.1.12",
3
+ "version": "0.1.14",
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.
@@ -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) {