@clawchatsai/connector 0.1.43 → 0.1.44

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.43",
3
+ "version": "0.1.44",
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
@@ -31,7 +31,11 @@ export class GatewayClient {
31
31
  gatewayWsUrl,
32
32
  debugLogger,
33
33
  connectParams: nonce => this._connectParams(nonce, ['approvals']),
34
- onEvent: data => this.broadcastToBrowsers(data),
34
+ onEvent: data => {
35
+ this.broadcastToBrowsers(data);
36
+ // Sharing tells the room's host while a guest run waits on this gateway's owner (peer/sharing.js onApprovalEvent).
37
+ if (this.onApprovalEvent) { try { this.onApprovalEvent(JSON.parse(data)); } catch (e) { console.error('[gateway] approval observer:', e.message); } }
38
+ },
35
39
  });
36
40
  }
37
41
 
package/server/index.js CHANGED
@@ -89,6 +89,7 @@ export function createApp(config = {}) {
89
89
  // Team chats: several agents in one thread (server/team.js).
90
90
  const team = new TeamCoordinator({ store: createTeamStore(() => globalDbCache.get()), request: gwRequest, broadcast, titler: createTitler(config.llm), remote: sharing });
91
91
  gatewayClient.onEvent = msg => { team.onGatewayEvent(msg); sharing?.onGatewayEvent(msg); };
92
+ gatewayClient.onApprovalEvent = msg => sharing?.onApprovalEvent(msg);
92
93
  gatewayClient.onConnected = () => { sharing?.migrateGuestAgents().catch(e => console.warn(`[sharing] guest migration failed: ${e.message}`)); };
93
94
  gatewayClient.lens = new SessionLens({ broadcast, request: gwRequest, extras, team });
94
95
  // Renamed agents: shares re-issued with the new names, copies of rooms here told (peer/sharing.js, team.js).
@@ -504,7 +504,7 @@ export class SharingManager {
504
504
  const done = new Promise(resolve => {
505
505
  const timer = setTimeout(() => { this._runs.delete(runId); resolve({ state: 'error', errorMessage: 'timed out' }); }, TURN_TIMEOUT_MS + 30_000);
506
506
  timer.unref?.();
507
- this._runs.set(runId, { resolve, timer, text: '', emit });
507
+ this._runs.set(runId, { resolve, timer, text: '', emit, sessionKey });
508
508
  });
509
509
  this._turns.set(turnKey, { sessionKey, runId });
510
510
  try {
@@ -521,6 +521,7 @@ export class SharingManager {
521
521
  } finally {
522
522
  const run = this._runs.get(runId);
523
523
  if (run) { clearTimeout(run.timer); this._runs.delete(runId); }
524
+ for (const [id, r] of this._approvalRuns || []) if (r === runId) this._approvalRuns.delete(id);
524
525
  }
525
526
  }
526
527
 
@@ -557,6 +558,7 @@ export class SharingManager {
557
558
  }
558
559
  db.prepare('INSERT OR REPLACE INTO peer_sessions (share_id, room_id, agent_id, session_key) VALUES (?, ?, ?, ?)').run(shareId, roomId, agentId, key);
559
560
  this._guestKeys = null;
561
+ this._changed(); // the room's list of answering sessions grew: the app needs it before the agent asks for an approval
560
562
  return key;
561
563
  }
562
564
 
@@ -570,6 +572,37 @@ export class SharingManager {
570
572
  return '';
571
573
  }
572
574
 
575
+ /**
576
+ * Approval events (owner side, from the approval connection): while a guest run waits for this gateway's owner to
577
+ * approve something, the room's host is told, so its room says what it's waiting for instead of only "responding".
578
+ * Only the kind of thing is sent ("a command", or the action's title), never the command itself or its paths.
579
+ */
580
+ onApprovalEvent(msg) {
581
+ const ev = msg?.event || '';
582
+ const m = /^(exec|plugin|openclaw)\.approval\.(requested|resolved)$/.exec(ev);
583
+ if (!m) return;
584
+ const p = msg.payload || {};
585
+ this._approvalRuns ??= new Map(); // approval id -> run id
586
+ if (m[2] === 'requested') {
587
+ const sessionKey = p.request?.sessionKey;
588
+ const entry = sessionKey && [...this._runs.entries()].find(([, r]) => r.sessionKey === sessionKey);
589
+ if (!entry || !p.id) return;
590
+ const [runId, run] = entry;
591
+ this._approvalRuns.set(p.id, runId);
592
+ const what = m[1] === 'exec' ? 'a command' : String(p.request?.title || 'an action').replace(/[\n\r]/g, ' ').slice(0, 80);
593
+ run.waiting = { what, expiresAtMs: Number(p.expiresAtMs) || null };
594
+ run.emit?.('status', { waiting: 'approval', what, expiresAtMs: run.waiting.expiresAtMs });
595
+ return;
596
+ }
597
+ const runId = p.id && this._approvalRuns.get(p.id);
598
+ if (!runId) return;
599
+ this._approvalRuns.delete(p.id);
600
+ const run = this._runs.get(runId);
601
+ if (!run || [...this._approvalRuns.values()].includes(runId)) return; // another approval of this run is still open
602
+ run.waiting = null;
603
+ run.emit?.('status', { waiting: null });
604
+ }
605
+
573
606
  /** Every gateway event (owner side): finish guest runs, stream their text. */
574
607
  onGatewayEvent(msg) {
575
608
  if (msg?.event !== 'chat') return;
@@ -646,12 +679,15 @@ export class SharingManager {
646
679
  }
647
680
 
648
681
  /** Run a turn on a shared agent. Returns { state, text }; throws with `.partial` on failure. */
649
- async turn(agentId, { turnId, roomId, roomTitle, message }, { onDelta } = {}) {
682
+ async turn(agentId, { turnId, roomId, roomTitle, message }, { onDelta, onStatus } = {}) {
650
683
  const id = SharingManager.parseRemoteId(agentId);
651
684
  if (!id) throw new Error('not a shared agent');
652
685
  const link = await this._link(id.shareId);
653
686
  return link.request('turn', { turnId, agentId: id.remoteId, roomId, roomTitle, message }, {
654
- onEvent: (event, data) => { if (event === 'delta' && typeof data === 'string') onDelta?.(data); },
687
+ onEvent: (event, data) => {
688
+ if (event === 'delta' && typeof data === 'string') onDelta?.(data);
689
+ else if (event === 'status' && data && typeof data === 'object') onStatus?.(data);
690
+ },
655
691
  timeoutMs: TURN_TIMEOUT_MS + 60_000,
656
692
  });
657
693
  }
@@ -172,6 +172,41 @@ test("the sessions answering a host's room are listed per host and room, so thei
172
172
  assert.deepEqual(s.owner.guestSessionKeysFor('gwOther', 'room1'), [], 'another host with the same room id is not this room');
173
173
  });
174
174
 
175
+ test('a guest session being made tells the app, so the room knows it before the agent asks for anything', async () => {
176
+ const s = setup();
177
+ const frames = [];
178
+ s.owner.broadcast = f => frames.push(JSON.parse(f).event);
179
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis-guest', name: 'Jarvis' }], access: 'trusted', dailyCap: 10 });
180
+ s.activate();
181
+ frames.length = 0;
182
+ await s.req.turn('peer:sh1:jarvis-guest', { turnId: 't1', roomId: 'room1', roomTitle: 'Rivers', message: 'hi' });
183
+ const created = s.ownerCalls.findIndex(c => c.method === 'sessions.create');
184
+ assert.ok(created >= 0);
185
+ assert.ok(frames.filter(e => e === 'sharing-changed').length >= 2, 'once for the usage count, once when the session exists');
186
+ assert.ok(s.owner.guestSessionKeysFor('gwH', 'room1').length === 1);
187
+ });
188
+
189
+ test("while a guest run waits for its owner's approval, the requester is told (without the command); decided -> cleared", async () => {
190
+ let hold;
191
+ const s = setup({ reply: () => null }); // the run stays open (nothing final yet)
192
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis-guest', name: 'Jarvis' }], access: 'trusted', dailyCap: 10 });
193
+ s.activate();
194
+ const statuses = [];
195
+ const turn = s.req.turn('peer:sh1:jarvis-guest', { turnId: 't1', roomId: 'room1', roomTitle: 'Rivers', message: 'run: rm -rf /secret/path' }, { onStatus: st => statuses.push(st) });
196
+ for (let i = 0; i < 50 && !s.ownerCalls.some(c => c.method === 'chat.send'); i++) await new Promise(r => setTimeout(r, 10));
197
+ const send = s.ownerCalls.find(c => c.method === 'chat.send').params;
198
+ s.owner.onApprovalEvent({ event: 'exec.approval.requested', payload: { id: 'ap1', request: { sessionKey: send.sessionKey, command: 'rm -rf /secret/path' }, expiresAtMs: 123 } });
199
+ s.owner.onApprovalEvent({ event: 'exec.approval.requested', payload: { id: 'ap-other', request: { sessionKey: 'agent:x:dashboard:unrelated', command: 'ls' }, expiresAtMs: 1 } });
200
+ await new Promise(r => setTimeout(r, 30));
201
+ assert.deepEqual(statuses, [{ waiting: 'approval', what: 'a command', expiresAtMs: 123 }], "only this run's approval, and not its command");
202
+ assert.ok(!JSON.stringify(statuses).includes('secret'));
203
+ s.owner.onApprovalEvent({ event: 'exec.approval.resolved', payload: { id: 'ap1' } });
204
+ await new Promise(r => setTimeout(r, 30));
205
+ assert.deepEqual(statuses.at(-1), { waiting: null });
206
+ s.owner.onGatewayEvent({ event: 'chat', payload: { runId: send.idempotencyKey, state: 'final', message: { content: [{ type: 'text', text: 'done' }] } } });
207
+ assert.equal((await turn).text, 'done');
208
+ });
209
+
175
210
  test('approve → verified on the requester → turn runs in a guest session on the owner, text streams back', async () => {
176
211
  const s = setup();
177
212
  assert.deepEqual(s.req.remoteAgents(), []);
package/server/team.js CHANGED
@@ -291,6 +291,8 @@ export class TeamCoordinator {
291
291
  return { agentId: m.agentId, workKey: null, remote: true, name: known?.name || null, ownerName: known?.ownerName || null, available: !!a };
292
292
  }),
293
293
  running: live ? [...live.running.keys()] : [],
294
+ // Remote agents whose run waits for their owner to approve something: { agentId: { owner, what, expiresAtMs } }.
295
+ waiting: live?.waiting ? Object.fromEntries(live.waiting) : {},
294
296
  queued: live?.queued || 0,
295
297
  people: r.people.map(p => ({ personId: p.personId, name: p.name })),
296
298
  // In a copy: the sessions this gateway's agents answer the host's room in. Their approvals and questions belong to the room.
@@ -695,15 +697,26 @@ export class TeamCoordinator {
695
697
  const delta = (text, done = false) => this.broadcast(JSON.stringify({ type: 'clawchats', event: 'team-remote-delta', roomKey, agentId, runId, text, ...(done ? { done: true } : {}) }));
696
698
  live.running.set(agentId, { remote: true, runId });
697
699
  this._status(roomKey);
700
+ // Its owner's gateway says when the run waits for their approval: the room shows it, and who it's waiting for.
701
+ const owner = this._remoteAgents().find(a => a.agentId === agentId)?.ownerName || this._remoteName(agentId)?.ownerName || null;
702
+ const waiting = w => {
703
+ live.waiting ??= new Map();
704
+ if (w) live.waiting.set(agentId, w); else live.waiting.delete(agentId);
705
+ this.broadcast(JSON.stringify({ type: 'clawchats', event: 'team-remote-status', roomKey, agentId, runId, waiting: w || null }));
706
+ };
698
707
  let result, partial = '';
699
708
  try {
700
709
  this._setSeen(roomKey, agentId, REMOTE_LANE, fresh);
701
710
  result = await this.remote.turn(agentId, { turnId: runId, roomId: roomKey, roomTitle: await this._roomTitle(roomKey), message: this._prompt(self, agents, fresh, mode, earlier) },
702
- { onDelta: text => { partial = text; delta(text); } });
711
+ {
712
+ onDelta: text => { partial = text; delta(text); },
713
+ onStatus: s => waiting(s?.waiting === 'approval' ? { owner, what: String(s.what || 'something').slice(0, 80), expiresAtMs: Number(s.expiresAtMs) || null } : null),
714
+ });
703
715
  } catch (e) {
704
716
  throw Object.assign(e, { partial: (e.partial || partial || '').trim() });
705
717
  } finally {
706
718
  live.running.delete(agentId);
719
+ if (live.waiting?.has(agentId)) waiting(null);
707
720
  delta('', true);
708
721
  this._status(roomKey);
709
722
  }
@@ -837,6 +837,33 @@ test("someone else's messages raise a badge on the room or its copy (chat.inject
837
837
  assert.ok(hostMid >= hostBefore);
838
838
  });
839
839
 
840
+ test("a remote agent waiting for its owner's approval: the room says so (who, what) and clears it when the run ends", async () => {
841
+ let release, seen;
842
+ const remote = {
843
+ remoteAgents: () => [{ agentId: 'peer:sh1:jarvis', name: 'Jarvis · Kamil', ownerName: 'Kamil' }],
844
+ turn: async (agentId, args, { onStatus }) => {
845
+ onStatus({ waiting: 'approval', what: 'a command', expiresAtMs: 99 });
846
+ seen = h.team.room(roomKey).waiting;
847
+ await new Promise(r => (release = r));
848
+ onStatus({ waiting: null });
849
+ return { state: 'final', text: 'ran it' };
850
+ },
851
+ abort: async () => {},
852
+ };
853
+ const h = harness(() => 'ok', { remote });
854
+ const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'peer:sh1:jarvis'] });
855
+ const sent = h.team.send(roomKey, { text: '@Jarvis-Kamil run the tests', userLabel: 'Houman' });
856
+ for (let i = 0; i < 100 && !release; i++) await new Promise(r => setTimeout(r, 10));
857
+ assert.deepEqual(seen, { 'peer:sh1:jarvis': { owner: 'Kamil', what: 'a command', expiresAtMs: 99 } });
858
+ const ev = h.events.filter(e => e.event === 'team-remote-status');
859
+ assert.deepEqual(ev.at(-1).waiting, { owner: 'Kamil', what: 'a command', expiresAtMs: 99 });
860
+ release();
861
+ await sent; await h.settle();
862
+ assert.deepEqual(h.team.room(roomKey).waiting, {}, 'cleared when the run ends');
863
+ assert.equal(h.events.filter(e => e.event === 'team-remote-status').at(-1).waiting, null);
864
+ assert.ok(h.room(roomKey).some(t => t.endsWith('ran it')));
865
+ });
866
+
840
867
  test('the timeline says who joined and left, the same on both sides; agents never see those lines', async () => {
841
868
  const { H, K, settle } = twoGateways();
842
869
  const { roomKey } = await H.team.createRoom({ agentIds: ['dev', 'atlas'] });