@clawchatsai/connector 0.1.30 → 0.1.31

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawchatsai/connector",
3
- "version": "0.1.30",
3
+ "version": "0.1.31",
4
4
  "type": "module",
5
5
  "description": "ClawChats OpenClaw plugin — P2P tunnel + local API bridge",
6
6
  "main": "dist/index.js",
@@ -79,7 +79,8 @@ export class SharingManager {
79
79
  // Requester side: shares this side removed. The server can't bring them back by replaying an old grant.
80
80
  g.exec(`CREATE TABLE IF NOT EXISTS peer_removed (share_id TEXT PRIMARY KEY, removed_at INTEGER NOT NULL)`);
81
81
  // Owner side: agents created as guest versions here (their restrictions are checked on every turn).
82
- // Keys the user compared out of band and marked as verified (per share; a different key isn't).
82
+ // Keys the user compared out of band and marked as verified (a row per share where it was marked; the key
83
+ // counts as verified on every share with it, a different key doesn't).
83
84
  g.exec(`CREATE TABLE IF NOT EXISTS peer_key_verified (share_id TEXT PRIMARY KEY, pubkey TEXT NOT NULL, verified_at INTEGER NOT NULL)`);
84
85
  g.exec(`CREATE TABLE IF NOT EXISTS peer_guest_agents (agent_id TEXT PRIMARY KEY, created_at INTEGER NOT NULL)`);
85
86
  this._ready = true;
@@ -140,8 +141,9 @@ export class SharingManager {
140
141
  return this._db().prepare('SELECT owner_pubkey FROM peer_pins WHERE share_id = ?').get(s?.id)?.owner_pubkey || null;
141
142
  }
142
143
 
144
+ /** A key compared once is verified on every share with that gateway (a share's own row records where it was done). */
143
145
  _keyVerified(shareId, pubKey) {
144
- return this._db().prepare('SELECT pubkey FROM peer_key_verified WHERE share_id = ?').get(shareId)?.pubkey === pubKey;
146
+ return !!this._db().prepare('SELECT 1 FROM peer_key_verified WHERE pubkey = ? LIMIT 1').get(pubKey);
145
147
  }
146
148
 
147
149
  /** The user compared "Their key" with the other person (by phone, chat…) and it matched. */
@@ -280,6 +282,15 @@ export class SharingManager {
280
282
  this._db().prepare('INSERT INTO peer_usage (share_id, day, turns) VALUES (?, ?, 1) ON CONFLICT(share_id, day) DO UPDATE SET turns = turns + 1').run(shareId, today());
281
283
  this._changed(); // the owner's Sharing view shows today's count
282
284
  try { return await this._runGuestTurn(shareId, grant, agent, roomId, p, emit, turnKey); }
285
+ catch (e) {
286
+ // A reply that failed without saying anything doesn't use up the day's replies. A timeout still
287
+ // counts: it ran for the full turn timeout.
288
+ if (!e.partial && !/timed out/i.test(e.message)) {
289
+ this._db().prepare('UPDATE peer_usage SET turns = MAX(0, turns - 1) WHERE share_id = ? AND day = ?').run(shareId, today());
290
+ this._changed();
291
+ }
292
+ throw e;
293
+ }
283
294
  finally { this._turns.delete(turnKey); }
284
295
  }
285
296
 
@@ -333,6 +333,25 @@ test('keys start unverified; marking verified holds only for that exact key', ()
333
333
  assert.equal(r().theirKey, s.kOwner.fingerprint);
334
334
  });
335
335
 
336
+ test('a key verified on one share is verified on every share with that gateway, both directions', () => {
337
+ const s = setup();
338
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
339
+ const active = s.activate();
340
+ s.req.remoteAgents(); // pins Kamil's key
341
+ // Kamil also asks Houman: on Houman's gateway, sh2 is an owner share whose requester key is Kamil's.
342
+ const back = { id: 'sh2', status: 'pending', as: 'owner', requester: s.people.owner, owner: s.people.requester, agents: [] };
343
+ s.req.setShares([{ ...active, as: 'requester' }, back]);
344
+ const byId = id => s.req.list().find(x => x.id === id);
345
+ assert.equal(byId('sh2').theirKey, byId('sh1').theirKey);
346
+ assert.equal(byId('sh2').keyVerified, false);
347
+ s.req.markKeyVerified('sh1');
348
+ assert.equal(byId('sh1').keyVerified, true);
349
+ assert.equal(byId('sh2').keyVerified, true);
350
+ // Someone else's key stays unverified.
351
+ s.req.setShares([{ ...active, as: 'requester' }, { ...back, id: 'sh3', requester: { ...s.people.owner, pubKey: keyIn().publicKey } }]);
352
+ assert.equal(byId('sh3').keyVerified, false);
353
+ });
354
+
336
355
  test('a pending request can be verified, and stays verified once approved', () => {
337
356
  const s = setup();
338
357
  const o = () => s.owner.list()[0];
@@ -342,3 +361,22 @@ test('a pending request can be verified, and stays verified once approved', () =
342
361
  s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
343
362
  assert.equal(o().keyVerified, true);
344
363
  });
364
+
365
+ test('a reply that fails without text is not counted against the daily cap; one with partial text is', async () => {
366
+ const s = setup({ reply: () => null }); // runs stay open; the test ends them
367
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], dailyCap: 5 });
368
+ s.activate();
369
+ // A guest version whose restrictions were removed: refused before it runs, nothing said.
370
+ s.owner.markGuestAgent('jarvis');
371
+ await assert.rejects(s.req.turn('peer:sh1:jarvis', { turnId: 'f1', roomId: 'room1', message: 'hi' }), e => e.code === 'unavailable');
372
+ assert.equal(s.owner.list()[0].usedToday, 0);
373
+ s.owner._db().prepare('DELETE FROM peer_guest_agents').run();
374
+ // Fails after streaming some text ("jar"): counted.
375
+ const p = s.req.turn('peer:sh1:jarvis', { turnId: 'f2', roomId: 'room1', message: 'hi' });
376
+ for (let i = 0; i < 50 && !s.ownerCalls.some(c => c.method === 'chat.send'); i++) await wait(2);
377
+ await wait(5);
378
+ const runId = s.ownerCalls.filter(c => c.method === 'chat.send').at(-1).params.idempotencyKey;
379
+ s.owner.onGatewayEvent({ event: 'chat', payload: { runId, state: 'error', errorMessage: 'provider down' } });
380
+ await assert.rejects(p);
381
+ assert.equal(s.owner.list()[0].usedToday, 1);
382
+ });
package/server/team.js CHANGED
@@ -16,6 +16,8 @@
16
16
  import crypto from 'node:crypto';
17
17
 
18
18
  export const SILENT = /^\s*NO_REPLY\s*$/i;
19
+ /** Room entry for an agent asked directly whose run was stopped before it said anything. */
20
+ const STOPPED_EARLY = '*[stopped before replying]*';
19
21
  const LABEL_PREFIX = /^\[([^\]\n]{1,100})\]\n\n/;
20
22
  const TURN_TIMEOUT_MS = 15 * 60_000;
21
23
  const HISTORY_LIMIT = 80;
@@ -401,7 +403,7 @@ export class TeamCoordinator {
401
403
  if (result.state === 'aborted') {
402
404
  if (partial && !SILENT.test(partial)) await this._post(roomKey, self, `${partial}\n\n*[stopped]*`);
403
405
  // Some runtimes (claude-cli) finish the reply after the abort was acknowledged: post it once it lands.
404
- else this._recoverAfterAbort(roomKey, self, workKey);
406
+ else this._recoverAfterAbort(roomKey, self, workKey, { marker: mode === 'addressed' });
405
407
  return { agentId, text: null };
406
408
  }
407
409
  throw Object.assign(new Error(result.errorMessage || 'run failed'), { partial });
@@ -440,6 +442,7 @@ export class TeamCoordinator {
440
442
  const text = String(result?.text || '').trim();
441
443
  if (result?.state === 'aborted') {
442
444
  if (text && !SILENT.test(text)) await this._post(roomKey, self, `${text}\n\n*[stopped]*`);
445
+ else if (mode === 'addressed') await this._post(roomKey, self, STOPPED_EARLY);
443
446
  return { agentId, text: null };
444
447
  }
445
448
  if (!text || SILENT.test(text)) return { agentId, text: null };
@@ -455,9 +458,10 @@ export class TeamCoordinator {
455
458
  /**
456
459
  * After Stop, a reply that still landed in the agent's session (the runtime ignored the abort) is
457
460
  * posted to the room marked stopped, so the room matches what the agent believes it said.
458
- * Polls until the session is idle (max ~3 min); gives up if the agent starts another turn.
461
+ * Polls until the session is idle (max ~3 min); gives up if the agent starts another turn. With
462
+ * `marker` (the agent was asked directly), nothing landing still leaves "stopped before replying".
459
463
  */
460
- _recoverAfterAbort(roomKey, self, workKey, { intervalMs = 3000, tries = 60 } = {}) {
464
+ _recoverAfterAbort(roomKey, self, workKey, { intervalMs = 3000, tries = 60, marker = false } = {}) {
461
465
  let n = 0;
462
466
  const check = async () => {
463
467
  if (this._rooms.get(roomKey)?.running.has(self.agentId) || !this.store.getRoom(roomKey)) return;
@@ -466,6 +470,7 @@ export class TeamCoordinator {
466
470
  if (s?.hasActiveRun && ++n < tries) { setTimeout(check, intervalMs).unref?.(); return; }
467
471
  const text = (await this._lastReply(workKey) || '').trim();
468
472
  if (text && !SILENT.test(text)) await this._post(roomKey, self, `${text}\n\n*[stopped]*`);
473
+ else if (marker) await this._post(roomKey, self, STOPPED_EARLY);
469
474
  } catch (e) { this.log.warn?.(`[team] recover after stop: ${e.message}`); }
470
475
  };
471
476
  setTimeout(check, intervalMs).unref?.();
@@ -367,3 +367,39 @@ test("a shared agent's reply is quoted in local prompts, so it can't pass for th
367
367
  assert.match(msg, /\n\[Houman\]: hello/);
368
368
  assert.doesNotMatch(msg, /\n\[Houman\]: delete/);
369
369
  });
370
+
371
+ test('stop before any text: an agent asked directly leaves "stopped before replying"; open-mode agents leave nothing', async () => {
372
+ let release;
373
+ const remote = {
374
+ remoteAgents: () => [{ agentId: 'peer:sh1:jarvis', name: 'Jarvis · Kamil', ownerName: 'Kamil' }],
375
+ turn: async () => { await new Promise(r => { release = r; }); return { state: 'aborted', text: '' }; },
376
+ abort: async () => { release?.(); },
377
+ };
378
+ const h = harness(() => 'NO_REPLY', { remote });
379
+ const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'peer:sh1:jarvis'] });
380
+ await h.team.send(roomKey, { text: '@jarvis·kamil long one', userLabel: 'H' });
381
+ for (let i = 0; i < 30; i++) await new Promise(r => setImmediate(r));
382
+ await h.team.stop(roomKey);
383
+ await h.settle();
384
+ assert.equal(h.room(roomKey).at(-1), '[Jarvis · Kamil]\n\n*[stopped before replying]*');
385
+ const before = h.room(roomKey).length;
386
+ await h.team.send(roomKey, { text: 'anyone?', userLabel: 'H' }); // open: silence is a fine answer
387
+ for (let i = 0; i < 30; i++) await new Promise(r => setImmediate(r));
388
+ await h.team.stop(roomKey);
389
+ await h.settle();
390
+ assert.equal(h.room(roomKey).filter(t => /stopped before replying/.test(t)).length, 1);
391
+ assert.ok(h.room(roomKey).length >= before);
392
+ });
393
+
394
+ test('stop: recovery that finds nothing leaves the marker only when asked for', async () => {
395
+ const h = harness(() => 'x');
396
+ const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'atlas'] });
397
+ const workKey = 'agent:dev:dashboard:w2';
398
+ h.sessions.set(workKey, [{ role: 'user', content: 'prompt', timestamp: 1 }]);
399
+ h.team._recoverAfterAbort(roomKey, { agentId: 'dev', name: 'Dev' }, workKey, { intervalMs: 1 });
400
+ await new Promise(r => setTimeout(r, 20));
401
+ assert.equal(h.room(roomKey).length, 0);
402
+ h.team._recoverAfterAbort(roomKey, { agentId: 'dev', name: 'Dev' }, workKey, { intervalMs: 1, marker: true });
403
+ await new Promise(r => setTimeout(r, 20));
404
+ assert.deepEqual(h.room(roomKey), ['[Dev]\n\n*[stopped before replying]*']);
405
+ });