@clawchatsai/connector 0.1.40 → 0.1.42
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 +15 -2
- package/dist/signaling-client.d.ts +3 -1
- package/dist/signaling-client.js +11 -0
- package/package.json +1 -1
- package/server/index.js +2 -2
- package/server/peer/guest-agent.js +17 -9
- package/server/peer/guest-agent.test.js +9 -0
- package/server/peer/sharing.js +29 -5
- package/server/peer/sharing.test.js +25 -0
package/dist/index.js
CHANGED
|
@@ -265,7 +265,7 @@ async function startClawChats(ctx, api) {
|
|
|
265
265
|
// Gateway sharing: the server side signs grants and runs guest turns; the host provides the
|
|
266
266
|
// signal server link and the WebRTC transport.
|
|
267
267
|
peer: {
|
|
268
|
-
gatewayId: () => loadConfig()?.gatewayId || '',
|
|
268
|
+
gatewayId: () => loadConfig()?.gatewayId || signaling?.currentGatewayId || '', // legacy installs have none saved: the session's
|
|
269
269
|
signal: (msg) => signaling?.send(msg),
|
|
270
270
|
openPeer: (shareId) => openPeerLink(shareId),
|
|
271
271
|
},
|
|
@@ -314,7 +314,20 @@ async function startClawChats(ctx, api) {
|
|
|
314
314
|
if (connectionId)
|
|
315
315
|
webrtcPeer?.closePeer(connectionId);
|
|
316
316
|
});
|
|
317
|
-
signaling.on('share-grant-rejected', (shareId) =>
|
|
317
|
+
signaling.on('share-grant-rejected', (shareId) => {
|
|
318
|
+
ctx.logger.warn(`[sharing] signal server rejected the grant for ${shareId}`);
|
|
319
|
+
app?.sharing?.onGrantRejected(shareId); // the owner sees it instead of "Saved"
|
|
320
|
+
});
|
|
321
|
+
// Installed before the setup flow saved the gateway id: log in by userId, then keep the id the server answers with,
|
|
322
|
+
// so the next login uses it and grants carry it. Nothing for the user to do.
|
|
323
|
+
signaling.on('gateway-id', (id) => {
|
|
324
|
+
const cfg = loadConfig();
|
|
325
|
+
if (cfg && !cfg.gatewayId) {
|
|
326
|
+
cfg.gatewayId = id;
|
|
327
|
+
saveConfig(cfg);
|
|
328
|
+
ctx.logger.info(`[clawchats] saved gateway id ${id} (this install had none; it logged in by user id)`);
|
|
329
|
+
}
|
|
330
|
+
});
|
|
318
331
|
signaling.on('connected', () => {
|
|
319
332
|
ctx.logger.info('Connected to signaling server');
|
|
320
333
|
});
|
|
@@ -17,11 +17,13 @@ export declare class SignalingClient extends EventEmitter {
|
|
|
17
17
|
private readonly serverUrl;
|
|
18
18
|
private readonly userId;
|
|
19
19
|
private readonly apiKey;
|
|
20
|
-
private
|
|
20
|
+
private gatewayId?;
|
|
21
21
|
private readonly hostname?;
|
|
22
22
|
/** This connector's Ed25519 public key for gateway sharing (base64 SPKI). */
|
|
23
23
|
private readonly peerPubKey?;
|
|
24
24
|
private ws;
|
|
25
|
+
/** The gateway id this connection logged in as (its config's, else the one the server assigned). */
|
|
26
|
+
get currentGatewayId(): string;
|
|
25
27
|
/** True only after gateway-auth-ok has been received. */
|
|
26
28
|
private _connected;
|
|
27
29
|
/**
|
package/dist/signaling-client.js
CHANGED
|
@@ -38,6 +38,10 @@ export class SignalingClient extends EventEmitter {
|
|
|
38
38
|
/** This connector's Ed25519 public key for gateway sharing (base64 SPKI). */
|
|
39
39
|
peerPubKey;
|
|
40
40
|
ws = null;
|
|
41
|
+
/** The gateway id this connection logged in as (its config's, else the one the server assigned). */
|
|
42
|
+
get currentGatewayId() {
|
|
43
|
+
return this.gatewayId ?? '';
|
|
44
|
+
}
|
|
41
45
|
/** True only after gateway-auth-ok has been received. */
|
|
42
46
|
_connected = false;
|
|
43
47
|
/**
|
|
@@ -197,6 +201,13 @@ export class SignalingClient extends EventEmitter {
|
|
|
197
201
|
const type = msg['type'];
|
|
198
202
|
switch (type) {
|
|
199
203
|
case 'gateway-auth-ok': {
|
|
204
|
+
// A gateway that logs in the legacy way (userId only) is told which gateway row it is; keep it for this
|
|
205
|
+
// session and tell the host so it can save it (index.ts), or sharing would sign grants for owner "".
|
|
206
|
+
const assigned = msg['gatewayId'];
|
|
207
|
+
if (typeof assigned === 'string' && assigned) {
|
|
208
|
+
this.gatewayId ||= assigned;
|
|
209
|
+
this.emit('gateway-id', assigned);
|
|
210
|
+
}
|
|
200
211
|
this._connected = true;
|
|
201
212
|
this.reconnectAttempts = 0;
|
|
202
213
|
this._resetPingWatchdog();
|
package/package.json
CHANGED
package/server/index.js
CHANGED
|
@@ -255,7 +255,7 @@ export function createApp(config = {}) {
|
|
|
255
255
|
if (method === 'GET' && urlPath === '/api/sharing') {
|
|
256
256
|
// Enabled once the signal server has sharing on for this account (it then sends share lists).
|
|
257
257
|
if (!sharing?.serverEnabled) return send(res, 200, { enabled: false, shares: [], remoteAgents: [] });
|
|
258
|
-
return send(res, 200, { enabled: true, fingerprint: peerKey.fingerprint, shares: sharing.list(), remoteAgents: sharing.remoteAgents(), contacts: sharing.contacts(), me: sharing.gatewayId?.() || null });
|
|
258
|
+
return send(res, 200, { enabled: true, fingerprint: peerKey.fingerprint, shares: sharing.list(), remoteAgents: sharing.remoteAgents(), contacts: sharing.contacts(), me: sharing.gatewayId?.() || null, guestAgentIds: [...sharing.guestAgentIds()] });
|
|
259
259
|
}
|
|
260
260
|
// The project a person's chats go to (peer/sharing.js funnel). Keyed by email.
|
|
261
261
|
if (method === 'GET' && urlPath === '/api/sharing/funnel') return send(res, 200, { funnel: sharing?.funnels() || {} });
|
|
@@ -278,7 +278,7 @@ export function createApp(config = {}) {
|
|
|
278
278
|
// Owner asks for a guest version of one of its agents (peer/guest-agent.js); changes this gateway's config.
|
|
279
279
|
const { agentId } = await parseBody(req);
|
|
280
280
|
if (typeof agentId !== 'string' || !agentId) return sendError(res, 400, 'agentId is required');
|
|
281
|
-
try { const r = await createGuestAgent(gwRequest, agentId); sharing.markGuestAgent(r.agentId); return send(res, 200, r); }
|
|
281
|
+
try { const r = await createGuestAgent(gwRequest, agentId, { known: sharing.guestAgentIds() }); sharing.markGuestAgent(r.agentId); return send(res, 200, r); }
|
|
282
282
|
catch (e) { return sendError(res, 400, e.message); }
|
|
283
283
|
}
|
|
284
284
|
if ((p = matchRoute(method, urlPath, 'POST /api/sharing/:id/verify-key'))) {
|
|
@@ -67,7 +67,7 @@ export async function ensureGuestRestrictions(request, agentId) {
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
/** A new agent is only usable once the gateway's config reload picked it up. */
|
|
70
|
-
async function waitForAgent(request, agentId, { tries =
|
|
70
|
+
async function waitForAgent(request, agentId, { tries = 120, ms = 250 } = {}) {
|
|
71
71
|
for (let i = 0; i < tries; i++) {
|
|
72
72
|
if (((await request('agents.list', {}))?.agents || []).some(a => a.id === agentId)) return true;
|
|
73
73
|
await wait(ms);
|
|
@@ -75,29 +75,37 @@ async function waitForAgent(request, agentId, { tries = 40, ms = 250 } = {}) {
|
|
|
75
75
|
return false;
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
-
/**
|
|
79
|
-
export function
|
|
78
|
+
/** Whether an agent is a guest version: called "<name> (guest)", or one this connector made (`known`: their ids). */
|
|
79
|
+
export function isGuestAgent(a, known = new Set()) {
|
|
80
|
+
return /\(guest\)$/.test(agentName(a)) || known.has(a?.id);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The guest version of `agentId` if it already exists. By name ("Jarvis (guest)"), or by the id it was made with
|
|
85
|
+
* ("main-guest"): renaming the original ("main" -> "homiabot") changes the name it looks for, not the guest that
|
|
86
|
+
* already exists. A guest the gateway shows under another name is still found when this connector made it (`known`).
|
|
87
|
+
*/
|
|
88
|
+
export function findGuestAgent(agents, agentId, known = new Set()) {
|
|
80
89
|
const src = agents.find(a => a.id === agentId);
|
|
81
90
|
if (!src) return null;
|
|
82
|
-
// By name ("Jarvis (guest)"), or by the id it was made with ("main-guest"): renaming the original
|
|
83
|
-
// ("main" -> "homiabot") changes the name it looks for, not the guest that already exists.
|
|
84
91
|
return agents.find(a => agentName(a) === guestName(agentName(src)))
|
|
85
|
-
|| agents.find(a => a.id === `${agentId}-guest` &&
|
|
92
|
+
|| agents.find(a => a.id === `${agentId}-guest` && isGuestAgent(a, known))
|
|
93
|
+
|| agents.find(a => a.id.startsWith(`${agentId}-guest-`) && known.has(a.id)) || null;
|
|
86
94
|
}
|
|
87
95
|
|
|
88
96
|
/**
|
|
89
97
|
* Create (or reuse) the guest version of an agent. Returns { agentId, name, created }.
|
|
90
98
|
* @param {(m: string, p: object, t?: number) => Promise<any>} request gateway RPC (operator.admin)
|
|
91
99
|
*/
|
|
92
|
-
export async function createGuestAgent(request, agentId) {
|
|
100
|
+
export async function createGuestAgent(request, agentId, { known = new Set() } = {}) {
|
|
93
101
|
const agents = (await request('agents.list', {}))?.agents || [];
|
|
94
102
|
const src = agents.find(a => a.id === agentId);
|
|
95
103
|
if (!src) throw new Error(`unknown agent: ${agentId}`);
|
|
96
|
-
if (
|
|
104
|
+
if (isGuestAgent(src, known)) {
|
|
97
105
|
await ensureGuestRestrictions(request, src.id); // repairs a guest agent left without them
|
|
98
106
|
return { agentId: src.id, name: agentName(src), created: false };
|
|
99
107
|
}
|
|
100
|
-
const existing = findGuestAgent(agents, agentId);
|
|
108
|
+
const existing = findGuestAgent(agents, agentId, known);
|
|
101
109
|
if (existing) {
|
|
102
110
|
// Repair a guest half-made by an earlier run: restore its restrictions, then the personality a
|
|
103
111
|
// crash between create and copy would have skipped (only missing files; never clobber edits).
|
|
@@ -93,3 +93,12 @@ test('findGuestAgent: the guest made as "main (guest)" is still found after the
|
|
|
93
93
|
// An agent that merely has the id shape isn't taken for a guest.
|
|
94
94
|
assert.equal(findGuestAgent([{ id: 'x', name: 'x' }, { id: 'x-guest', name: 'something else' }], 'x'), null);
|
|
95
95
|
});
|
|
96
|
+
|
|
97
|
+
test('a guest the gateway shows under the original\'s name is still found (and hidden) when this connector made it', async () => {
|
|
98
|
+
const { findGuestAgent, isGuestAgent } = await import('./guest-agent.js');
|
|
99
|
+
const agents = [{ id: 'capy', identity: { name: 'Capy' } }, { id: 'capy-guest', identity: { name: 'Capy' } }, { id: 'capy-guest-2', identity: { name: 'Capy' } }];
|
|
100
|
+
assert.equal(findGuestAgent(agents, 'capy'), null, 'without the connector\'s record it can\'t tell');
|
|
101
|
+
assert.equal(findGuestAgent(agents, 'capy', new Set(['capy-guest']))?.id, 'capy-guest');
|
|
102
|
+
assert.equal(findGuestAgent([agents[0], agents[2]], 'capy', new Set(['capy-guest-2']))?.id, 'capy-guest-2');
|
|
103
|
+
assert.ok(isGuestAgent(agents[1], new Set(['capy-guest'])) && !isGuestAgent(agents[0], new Set(['capy-guest'])));
|
|
104
|
+
});
|
package/server/peer/sharing.js
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
import crypto from 'node:crypto';
|
|
17
17
|
import { PeerLink } from './link.js';
|
|
18
18
|
import { canonicalJson, verifySignature, fingerprint } from './keys.js';
|
|
19
|
-
import { hasGuestRestrictions, ensureGuestRestrictions, findGuestAgent } from './guest-agent.js';
|
|
19
|
+
import { hasGuestRestrictions, ensureGuestRestrictions, findGuestAgent, isGuestAgent } from './guest-agent.js';
|
|
20
20
|
|
|
21
21
|
const TURN_TIMEOUT_MS = 10 * 60_000;
|
|
22
22
|
const DEFAULT_DAILY_CAP = 50;
|
|
@@ -210,6 +210,26 @@ export class SharingManager {
|
|
|
210
210
|
}
|
|
211
211
|
|
|
212
212
|
/** Remember an agent created here as a guest version (ClawChats → Sharing). */
|
|
213
|
+
/**
|
|
214
|
+
* The signal server refused a grant (it never activated the share). The owner is told, and a grant that was only
|
|
215
|
+
* pending is dropped, so both sides agree the share isn't there. A grant for a share that was already active
|
|
216
|
+
* (an edit the server turned down) stays: the share still works as it did.
|
|
217
|
+
*/
|
|
218
|
+
onGrantRejected(shareId) {
|
|
219
|
+
const live = this._shares.find(x => x.id === shareId && x.as === 'owner');
|
|
220
|
+
if (live?.status !== 'active') this._db().prepare('DELETE FROM peer_grants WHERE share_id = ?').run(shareId);
|
|
221
|
+
this.broadcast?.(JSON.stringify({
|
|
222
|
+
type: 'clawchats', event: 'sharing-error', shareId,
|
|
223
|
+
message: live?.status === 'active' ? "The server didn't accept that change. Your sharing is as it was; try again." : "The server didn't accept it. Try again.",
|
|
224
|
+
}));
|
|
225
|
+
this._changed();
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Ids of the guest agents this connector made (the gateway may show them under another name). */
|
|
229
|
+
guestAgentIds() {
|
|
230
|
+
return new Set(this._db().prepare('SELECT agent_id FROM peer_guest_agents').all().map(r => r.agent_id));
|
|
231
|
+
}
|
|
232
|
+
|
|
213
233
|
markGuestAgent(agentId) {
|
|
214
234
|
this._db().prepare('INSERT OR IGNORE INTO peer_guest_agents (agent_id, created_at) VALUES (?, ?)').run(agentId, Date.now());
|
|
215
235
|
}
|
|
@@ -245,8 +265,11 @@ export class SharingManager {
|
|
|
245
265
|
if (prev && JSON.parse(prev.grant_json).requesterPubKey !== s.requester.pubKey) {
|
|
246
266
|
throw new Error("The requester's gateway key changed since you approved them. Stop sharing and ask them to request again.");
|
|
247
267
|
}
|
|
268
|
+
// The signal server only activates a grant signed for this gateway's own id; without one it would say no, silently.
|
|
269
|
+
const ownerGatewayId = this.gatewayId();
|
|
270
|
+
if (!ownerGatewayId) throw new Error("This gateway isn't connected to the signal server yet. Try again in a moment.");
|
|
248
271
|
const grant = {
|
|
249
|
-
v: 1, shareId, ownerGatewayId
|
|
272
|
+
v: 1, shareId, ownerGatewayId, requesterGatewayId: s.requester.gatewayId, requesterPubKey: s.requester.pubKey,
|
|
250
273
|
requesterName: cleanName(s.requester.name || s.requester.email, 60) || null,
|
|
251
274
|
agents: list, access, dailyCap: Math.max(1, Math.min(1000, Math.floor(Number(dailyCap) || DEFAULT_DAILY_CAP))), issuedAt: Date.now(),
|
|
252
275
|
};
|
|
@@ -669,8 +692,9 @@ export class SharingManager {
|
|
|
669
692
|
const shown = id => {
|
|
670
693
|
const a = agents.find(x => x.id === id);
|
|
671
694
|
if (!a) return null;
|
|
672
|
-
|
|
673
|
-
|
|
695
|
+
const known = this.guestAgentIds();
|
|
696
|
+
if (!isGuestAgent(a, known)) return label(a);
|
|
697
|
+
const src = agents.find(o => o.id !== id && findGuestAgent(agents, o.id, known)?.id === id);
|
|
674
698
|
return src ? label(src) : null;
|
|
675
699
|
};
|
|
676
700
|
const reissued = [];
|
|
@@ -759,7 +783,7 @@ export class SharingManager {
|
|
|
759
783
|
const g = this._grantToOwnerOf(remoteAgentId);
|
|
760
784
|
if (!g) return null;
|
|
761
785
|
const agents = (await this.request('agents.list', {}))?.agents || [];
|
|
762
|
-
const guestId = findGuestAgent(agents, localAgentId)?.id;
|
|
786
|
+
const guestId = findGuestAgent(agents, localAgentId, this.guestAgentIds())?.id;
|
|
763
787
|
const shared = g.grant.agents.find(a => a.id === guestId) || g.grant.agents.find(a => a.id === localAgentId);
|
|
764
788
|
if (!shared) return null;
|
|
765
789
|
return this._guestTurn(g.shareId, { turnId, agentId: shared.id, roomId, roomTitle, message, inOwnerRoom: true, byPerson: String(remoteAgentId).startsWith('person:') },
|
|
@@ -135,6 +135,31 @@ test("funnel: a person's chats go to the project chosen for them; renames follow
|
|
|
135
135
|
assert.deepEqual(s.owner.funnels(), { 'h@x.dev': 'Team' });
|
|
136
136
|
});
|
|
137
137
|
|
|
138
|
+
test('a gateway with no id can\'t sign a grant (the server would refuse it silently); a refused grant is dropped and the owner told', async () => {
|
|
139
|
+
const s = setup();
|
|
140
|
+
const frames = [];
|
|
141
|
+
const gid = s.owner.gatewayId;
|
|
142
|
+
s.owner.broadcast = f => frames.push(JSON.parse(f));
|
|
143
|
+
s.owner.gatewayId = () => ''; // a legacy install: logged in by user id, no id saved
|
|
144
|
+
assert.throws(() => s.owner.approve('sh1', { agents: [{ id: 'jarvis-guest', name: 'Jarvis' }] }), /isn't connected to the signal server yet/);
|
|
145
|
+
assert.equal(s.ownerSignals.filter(m => m.type === 'share-grant').length, 0, 'nothing was sent');
|
|
146
|
+
|
|
147
|
+
s.owner.gatewayId = gid;
|
|
148
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis-guest', name: 'Jarvis' }] });
|
|
149
|
+
assert.equal(s.ownerSignals.filter(m => m.type === 'share-grant').at(-1).grant.ownerGatewayId, 'gwK');
|
|
150
|
+
// The server says no while the share is still pending: the local grant goes, and the browser is told.
|
|
151
|
+
s.owner.onGrantRejected('sh1');
|
|
152
|
+
assert.equal(s.owner._db().prepare('SELECT COUNT(*) n FROM peer_grants WHERE share_id = ?').get('sh1').n, 0);
|
|
153
|
+
assert.ok(frames.some(f => f.event === 'sharing-error' && f.shareId === 'sh1' && /Try again/.test(f.message)));
|
|
154
|
+
|
|
155
|
+
// An edit of a share that was already active: refused, but the share keeps working as it did.
|
|
156
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis-guest', name: 'Jarvis' }] });
|
|
157
|
+
s.activate();
|
|
158
|
+
s.owner.onGrantRejected('sh1');
|
|
159
|
+
assert.equal(s.owner._db().prepare('SELECT COUNT(*) n FROM peer_grants WHERE share_id = ?').get('sh1').n, 1);
|
|
160
|
+
assert.ok(frames.at(-2).message.includes('as it was'));
|
|
161
|
+
});
|
|
162
|
+
|
|
138
163
|
test('approve → verified on the requester → turn runs in a guest session on the owner, text streams back', async () => {
|
|
139
164
|
const s = setup();
|
|
140
165
|
assert.deepEqual(s.req.remoteAgents(), []);
|