@clawchatsai/connector 0.1.42 → 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 +1 -1
- package/server/gateway.js +5 -1
- package/server/index.js +1 -0
- package/server/peer/sharing.js +48 -3
- package/server/peer/sharing.test.js +47 -0
- package/server/team.js +16 -1
- package/server/team.test.js +27 -0
package/package.json
CHANGED
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 =>
|
|
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).
|
package/server/peer/sharing.js
CHANGED
|
@@ -394,6 +394,15 @@ export class SharingManager {
|
|
|
394
394
|
}
|
|
395
395
|
|
|
396
396
|
/** The room (and who asked) behind a guest session of this gateway, or null. */
|
|
397
|
+
/** Sessions here answering `roomId` of the room hosted by `hostGatewayId` (hidden from the list while a copy exists). */
|
|
398
|
+
guestSessionKeysFor(hostGatewayId, roomId) {
|
|
399
|
+
const keys = [];
|
|
400
|
+
for (const r of this._db().prepare('SELECT p.session_key, g.grant_json FROM peer_sessions p JOIN peer_grants g ON g.share_id = p.share_id WHERE p.room_id = ?').all(roomId)) {
|
|
401
|
+
try { if (JSON.parse(r.grant_json).requesterGatewayId === hostGatewayId) keys.push(r.session_key); } catch { /* unreadable grant */ }
|
|
402
|
+
}
|
|
403
|
+
return keys;
|
|
404
|
+
}
|
|
405
|
+
|
|
397
406
|
guestSessionOf(key) {
|
|
398
407
|
if (!this._guestKeys) {
|
|
399
408
|
this._guestKeys = new Map();
|
|
@@ -495,7 +504,7 @@ export class SharingManager {
|
|
|
495
504
|
const done = new Promise(resolve => {
|
|
496
505
|
const timer = setTimeout(() => { this._runs.delete(runId); resolve({ state: 'error', errorMessage: 'timed out' }); }, TURN_TIMEOUT_MS + 30_000);
|
|
497
506
|
timer.unref?.();
|
|
498
|
-
this._runs.set(runId, { resolve, timer, text: '', emit });
|
|
507
|
+
this._runs.set(runId, { resolve, timer, text: '', emit, sessionKey });
|
|
499
508
|
});
|
|
500
509
|
this._turns.set(turnKey, { sessionKey, runId });
|
|
501
510
|
try {
|
|
@@ -512,6 +521,7 @@ export class SharingManager {
|
|
|
512
521
|
} finally {
|
|
513
522
|
const run = this._runs.get(runId);
|
|
514
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);
|
|
515
525
|
}
|
|
516
526
|
}
|
|
517
527
|
|
|
@@ -548,6 +558,7 @@ export class SharingManager {
|
|
|
548
558
|
}
|
|
549
559
|
db.prepare('INSERT OR REPLACE INTO peer_sessions (share_id, room_id, agent_id, session_key) VALUES (?, ?, ?, ?)').run(shareId, roomId, agentId, key);
|
|
550
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
|
|
551
562
|
return key;
|
|
552
563
|
}
|
|
553
564
|
|
|
@@ -561,6 +572,37 @@ export class SharingManager {
|
|
|
561
572
|
return '';
|
|
562
573
|
}
|
|
563
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
|
+
|
|
564
606
|
/** Every gateway event (owner side): finish guest runs, stream their text. */
|
|
565
607
|
onGatewayEvent(msg) {
|
|
566
608
|
if (msg?.event !== 'chat') return;
|
|
@@ -637,12 +679,15 @@ export class SharingManager {
|
|
|
637
679
|
}
|
|
638
680
|
|
|
639
681
|
/** Run a turn on a shared agent. Returns { state, text }; throws with `.partial` on failure. */
|
|
640
|
-
async turn(agentId, { turnId, roomId, roomTitle, message }, { onDelta } = {}) {
|
|
682
|
+
async turn(agentId, { turnId, roomId, roomTitle, message }, { onDelta, onStatus } = {}) {
|
|
641
683
|
const id = SharingManager.parseRemoteId(agentId);
|
|
642
684
|
if (!id) throw new Error('not a shared agent');
|
|
643
685
|
const link = await this._link(id.shareId);
|
|
644
686
|
return link.request('turn', { turnId, agentId: id.remoteId, roomId, roomTitle, message }, {
|
|
645
|
-
onEvent: (event, 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
|
+
},
|
|
646
691
|
timeoutMs: TURN_TIMEOUT_MS + 60_000,
|
|
647
692
|
});
|
|
648
693
|
}
|
|
@@ -160,6 +160,53 @@ test('a gateway with no id can\'t sign a grant (the server would refuse it silen
|
|
|
160
160
|
assert.ok(frames.at(-2).message.includes('as it was'));
|
|
161
161
|
});
|
|
162
162
|
|
|
163
|
+
test("the sessions answering a host's room are listed per host and room, so their approvals can show in the room", async () => {
|
|
164
|
+
const s = setup();
|
|
165
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis-guest', name: 'Jarvis' }], access: 'trusted', dailyCap: 10 });
|
|
166
|
+
s.activate();
|
|
167
|
+
await s.req.turn('peer:sh1:jarvis-guest', { turnId: 't1', roomId: 'room1', roomTitle: 'Rivers', message: 'hi' });
|
|
168
|
+
await s.req.turn('peer:sh1:jarvis-guest', { turnId: 't2', roomId: 'room2', roomTitle: 'Lakes', message: 'hi' });
|
|
169
|
+
const key = s.ownerCalls.find(c => c.method === 'sessions.create').params.key;
|
|
170
|
+
assert.deepEqual(s.owner.guestSessionKeysFor('gwH', 'room1'), [key]);
|
|
171
|
+
assert.deepEqual(s.owner.guestSessionKeysFor('gwH', 'room3'), []);
|
|
172
|
+
assert.deepEqual(s.owner.guestSessionKeysFor('gwOther', 'room1'), [], 'another host with the same room id is not this room');
|
|
173
|
+
});
|
|
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
|
+
|
|
163
210
|
test('approve → verified on the requester → turn runs in a guest session on the owner, text streams back', async () => {
|
|
164
211
|
const s = setup();
|
|
165
212
|
assert.deepEqual(s.req.remoteAgents(), []);
|
package/server/team.js
CHANGED
|
@@ -291,8 +291,12 @@ 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 })),
|
|
298
|
+
// In a copy: the sessions this gateway's agents answer the host's room in. Their approvals and questions belong to the room.
|
|
299
|
+
...(r.host ? { answeringKeys: this.remote?.guestSessionKeysFor?.(r.host.gatewayId, r.host.roomId) || [] } : {}),
|
|
296
300
|
...(r.host ? this._replicaPublic(r) : {}),
|
|
297
301
|
};
|
|
298
302
|
}
|
|
@@ -693,15 +697,26 @@ export class TeamCoordinator {
|
|
|
693
697
|
const delta = (text, done = false) => this.broadcast(JSON.stringify({ type: 'clawchats', event: 'team-remote-delta', roomKey, agentId, runId, text, ...(done ? { done: true } : {}) }));
|
|
694
698
|
live.running.set(agentId, { remote: true, runId });
|
|
695
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
|
+
};
|
|
696
707
|
let result, partial = '';
|
|
697
708
|
try {
|
|
698
709
|
this._setSeen(roomKey, agentId, REMOTE_LANE, fresh);
|
|
699
710
|
result = await this.remote.turn(agentId, { turnId: runId, roomId: roomKey, roomTitle: await this._roomTitle(roomKey), message: this._prompt(self, agents, fresh, mode, earlier) },
|
|
700
|
-
{
|
|
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
|
+
});
|
|
701
715
|
} catch (e) {
|
|
702
716
|
throw Object.assign(e, { partial: (e.partial || partial || '').trim() });
|
|
703
717
|
} finally {
|
|
704
718
|
live.running.delete(agentId);
|
|
719
|
+
if (live.waiting?.has(agentId)) waiting(null);
|
|
705
720
|
delta('', true);
|
|
706
721
|
this._status(roomKey);
|
|
707
722
|
}
|
package/server/team.test.js
CHANGED
|
@@ -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'] });
|