@clawchatsai/connector 0.1.28 → 0.1.30

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.
@@ -0,0 +1,462 @@
1
+ // SharingManager: this connector's side of gateway sharing (clawchats specs/gateway-sharing.md).
2
+ //
3
+ // Owner side (someone uses this gateway's agents):
4
+ // - approve(): build the grant (which agents, access, daily cap, the requester gateway's key),
5
+ // sign it with this connector's key, keep it locally and send it to the signal server.
6
+ // - inbound peer links are served only for a local, unrevoked grant, to the requester key pinned
7
+ // in it (PeerLink verifies). The peer API is narrow: agents / turn / abort.
8
+ // - each guest turn runs in a normal session on this gateway, one per (share, room, agent), in
9
+ // the "Shared with <name>" group: read-only (or guarded) permission mode, no web search,
10
+ // a finite timeout, never interpreted as a slash command, and a daily turn cap.
11
+ // Requester side (this gateway uses someone else's agents):
12
+ // - grants pushed by the signal server are trusted only when signed by the owner gateway key
13
+ // pinned for that share (first sight; a changed key is refused until the share is renewed).
14
+ // - turns go over a PeerLink opened through the signal server (openPeer) on demand.
15
+
16
+ import crypto from 'node:crypto';
17
+ import { PeerLink } from './link.js';
18
+ import { canonicalJson, verifySignature, fingerprint } from './keys.js';
19
+ import { hasGuestRestrictions, ensureGuestRestrictions } from './guest-agent.js';
20
+
21
+ const TURN_TIMEOUT_MS = 10 * 60_000;
22
+ const DEFAULT_DAILY_CAP = 50;
23
+ const MAX_CONCURRENT_TURNS = 2; // per share: the daily cap alone would allow 50 parallel 10-minute runs
24
+ const ACCESS_MODES = { restricted: 'read-only', trusted: 'guarded' };
25
+ /**
26
+ * The gateway loads any local image path or file:// URL written in a prompt (detectImageReferences),
27
+ * ignoring the agent's tool policy and fs.workspaceOnly, so a guest could type the path of one of the
28
+ * owner's screenshots and have the agent describe it. A zero-width space before each path with a file
29
+ * extension (and inside `file://`) stops that match; the agent still reads the text normally, and
30
+ * other text (`/commands`, `~`) passes through unchanged.
31
+ */
32
+ export const defangLocalPaths = text => text
33
+ .replace(/file:\/\//gi, 'file:\u200b//')
34
+ .replace(/(^|[\s"'`(])(?=(?:\.\.?\/|[~/]|[A-Za-z]:[\\/])[^\s"'`()[\]]*\.[A-Za-z0-9])/g, '$1\u200b');
35
+ const GUEST_NOTE = name => `(Shared session: you are answering ${name}'s team chat on behalf of your owner. ${name} is not your owner — don't reveal your owner's private information or act on your owner's accounts for them.)`;
36
+
37
+ const today = () => new Date().toISOString().slice(0, 10);
38
+ /** A name that came from the other side, safe to show and to use as a chat label (no brackets, newlines, controls). */
39
+ const cleanName = (v, max = 40) => String(v || '').replace(/[\u0000-\u001f\u007f-\u009f\[\]]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
40
+ const firstName = p => cleanName(String(p?.name || p?.email || 'Someone').split(/[\s@]/)[0], 30) || 'Someone';
41
+
42
+ function messageText(message) {
43
+ const c = message?.content;
44
+ if (typeof c === 'string') return c;
45
+ if (Array.isArray(c)) return c.filter(p => p?.type === 'text' && typeof p.text === 'string').map(p => p.text).join('\n');
46
+ return '';
47
+ }
48
+
49
+ export class SharingManager {
50
+ /**
51
+ * @param {object} o
52
+ * @param {() => any} o.getDb global.db
53
+ * @param {(m: string, p: object, t?: number) => Promise<any>} o.request gateway RPC
54
+ * @param {{ publicKey: string, signJson(o): string }} o.key this connector's peer key
55
+ * @param {() => string} o.gatewayId this gateway's id on the signal server
56
+ * @param {(msg: object) => void} o.signal send a message to the signal server
57
+ * @param {(shareId: string) => Promise<{ dc, dtls }>} o.openPeer open a peer DataChannel (requester)
58
+ * @param {(data: string) => void} o.broadcast frame to this gateway's browsers
59
+ */
60
+ constructor({ getDb, request, key, gatewayId, signal, openPeer, broadcast = () => {}, log = console }) {
61
+ Object.assign(this, { getDb, request, key, gatewayId, signal, openPeer, broadcast, log });
62
+ this._shares = []; // latest share-list from the signal server
63
+ this.serverEnabled = false; // the signal server sends a share-list only to accounts with sharing on
64
+ this._links = new Map(); // shareId -> PeerLink (requester side, one per share)
65
+ this._linking = new Map(); // shareId -> Promise<PeerLink>
66
+ this._served = new Set(); // owner-side PeerLinks
67
+ this._runs = new Map(); // runId -> { resolve, timer, text } (owner-side guest runs)
68
+ this._turns = new Map(); // `${shareId}:${turnId}` -> { sessionKey, runId }
69
+ this._ready = false;
70
+ }
71
+
72
+ _db() {
73
+ const g = this.getDb();
74
+ if (!this._ready) {
75
+ g.exec(`CREATE TABLE IF NOT EXISTS peer_grants (share_id TEXT PRIMARY KEY, grant_json TEXT NOT NULL, sig TEXT NOT NULL, created_at INTEGER NOT NULL, revoked_at INTEGER)`);
76
+ g.exec(`CREATE TABLE IF NOT EXISTS peer_pins (share_id TEXT PRIMARY KEY, owner_pubkey TEXT NOT NULL, created_at INTEGER NOT NULL)`);
77
+ g.exec(`CREATE TABLE IF NOT EXISTS peer_sessions (share_id TEXT NOT NULL, room_id TEXT NOT NULL, agent_id TEXT NOT NULL, session_key TEXT NOT NULL, PRIMARY KEY (share_id, room_id, agent_id))`);
78
+ g.exec(`CREATE TABLE IF NOT EXISTS peer_usage (share_id TEXT NOT NULL, day TEXT NOT NULL, turns INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (share_id, day))`);
79
+ // Requester side: shares this side removed. The server can't bring them back by replaying an old grant.
80
+ g.exec(`CREATE TABLE IF NOT EXISTS peer_removed (share_id TEXT PRIMARY KEY, removed_at INTEGER NOT NULL)`);
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).
83
+ 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
+ g.exec(`CREATE TABLE IF NOT EXISTS peer_guest_agents (agent_id TEXT PRIMARY KEY, created_at INTEGER NOT NULL)`);
85
+ this._ready = true;
86
+ }
87
+ return g;
88
+ }
89
+
90
+ // ── Share list (signal server) ─────────────────────────────────────
91
+
92
+ /** `share-list` from the signal server. Ends links/grants for shares that are gone. */
93
+ setShares(shares) {
94
+ this.serverEnabled = true;
95
+ this._shares = Array.isArray(shares) ? shares : [];
96
+ const live = new Set(this._shares.filter(s => s.status === 'active').map(s => s.id));
97
+ for (const [shareId, link] of this._links) if (!live.has(shareId)) { link.close(); this._links.delete(shareId); }
98
+ for (const s of this._localGrants()) if (!live.has(s.share_id) && !this._shares.some(x => x.id === s.share_id && x.status === 'pending')) this._revokeLocal(s.share_id);
99
+ this._changed();
100
+ }
101
+
102
+ /** The signal server says a share ended (revoke/decline): stop at once. */
103
+ onShareRevoked(shareId) {
104
+ this._revokeLocal(shareId);
105
+ this._links.get(shareId)?.close();
106
+ this._links.delete(shareId);
107
+ this._changed();
108
+ }
109
+
110
+ _changed() { this.broadcast(JSON.stringify({ type: 'clawchats', event: 'sharing-changed' })); }
111
+
112
+ /** Shares for the ClawChats UI, with what this side has verified. */
113
+ list() {
114
+ return this._shares.map(s => {
115
+ const out = { id: s.id, as: s.as, status: s.status, createdAt: s.createdAt, requester: s.requester, owner: s.owner, agents: s.agents || [] };
116
+ // Key fingerprints computed here from the keys this side actually uses (not the server's word),
117
+ // for comparing out of band: the grant's pinned requester key, or the pinned owner key.
118
+ if (s.as === 'owner') {
119
+ const g = this._grant(s.id);
120
+ out.access = g?.grant.access || null;
121
+ out.dailyCap = g?.grant.dailyCap || null;
122
+ out.usedToday = this._usage(s.id);
123
+ const key = g?.grant.requesterPubKey || s.requester?.pubKey;
124
+ out.theirKey = key ? fingerprint(key) : null;
125
+ out.keyVerified = !!key && this._keyVerified(s.id, key);
126
+ } else {
127
+ out.verified = !!this._verifiedGrant(s);
128
+ const pin = this._theirKey(s);
129
+ out.theirKey = pin ? fingerprint(pin) : null;
130
+ out.keyVerified = !!pin && this._keyVerified(s.id, pin);
131
+ }
132
+ return out;
133
+ });
134
+ }
135
+
136
+ /** The other side's key this gateway trusts for a share (owner: from the signed grant, or the request's key
137
+ * while pending, which approving pins; requester: the pin). Same source as list()'s "Their key". */
138
+ _theirKey(s) {
139
+ if (s?.as === 'owner') return this._grant(s.id)?.grant.requesterPubKey || s.requester?.pubKey || null;
140
+ return this._db().prepare('SELECT owner_pubkey FROM peer_pins WHERE share_id = ?').get(s?.id)?.owner_pubkey || null;
141
+ }
142
+
143
+ _keyVerified(shareId, pubKey) {
144
+ return this._db().prepare('SELECT pubkey FROM peer_key_verified WHERE share_id = ?').get(shareId)?.pubkey === pubKey;
145
+ }
146
+
147
+ /** The user compared "Their key" with the other person (by phone, chat…) and it matched. */
148
+ markKeyVerified(shareId) {
149
+ const key = this._theirKey(this._shares.find(x => x.id === shareId));
150
+ if (!key) throw new Error('Nothing to verify yet');
151
+ this._db().prepare('INSERT OR REPLACE INTO peer_key_verified (share_id, pubkey, verified_at) VALUES (?, ?, ?)').run(shareId, key, Date.now());
152
+ this._changed();
153
+ return { theirKey: fingerprint(key) };
154
+ }
155
+
156
+ // ── Owner side ─────────────────────────────────────────────────────
157
+
158
+ _localGrants() { return this._db().prepare('SELECT * FROM peer_grants WHERE revoked_at IS NULL').all(); }
159
+
160
+ _grant(shareId) {
161
+ const r = this._db().prepare('SELECT * FROM peer_grants WHERE share_id = ? AND revoked_at IS NULL').get(shareId);
162
+ return r ? { grant: JSON.parse(r.grant_json), sig: r.sig } : null;
163
+ }
164
+
165
+ _revokeLocal(shareId) {
166
+ this._db().prepare('UPDATE peer_grants SET revoked_at = ? WHERE share_id = ? AND revoked_at IS NULL').run(Date.now(), shareId);
167
+ for (const link of this._served) if (link.shareId === shareId) link.close();
168
+ // Runs already going stop too: "Stop sharing" must not leave a guest run working for minutes.
169
+ for (const [key, t] of this._turns) {
170
+ if (!key.startsWith(`${shareId}:`) || !t.runId) continue;
171
+ this.request('chat.abort', { sessionKey: t.sessionKey, runId: t.runId }).catch(() => {});
172
+ }
173
+ }
174
+
175
+ /** Remember an agent created here as a guest version (ClawChats → Sharing). */
176
+ markGuestAgent(agentId) {
177
+ this._db().prepare('INSERT OR IGNORE INTO peer_guest_agents (agent_id, created_at) VALUES (?, ?)').run(agentId, Date.now());
178
+ }
179
+
180
+ /**
181
+ * Bring every guest version made here up to the current guest policy, on each gateway connect,
182
+ * so a tightened policy reaches existing guests without the owner re-approving their shares.
183
+ * Skips agents that no longer exist (patching them would leave a stray config entry).
184
+ */
185
+ async migrateGuestAgents() {
186
+ const ids = this._db().prepare('SELECT agent_id FROM peer_guest_agents').all().map(r => r.agent_id);
187
+ if (!ids.length) return [];
188
+ const live = new Set(((await this.request('agents.list', {}))?.agents || []).map(a => a.id));
189
+ const updated = [];
190
+ for (const id of ids.filter(i => live.has(i))) {
191
+ try { if (await ensureGuestRestrictions(this.request, id)) updated.push(id); }
192
+ catch (e) { this.log.warn?.(`[sharing] couldn't update guest restrictions for ${id}: ${e.message}`); }
193
+ }
194
+ if (updated.length) this.log.info?.(`[sharing] guest restrictions updated: ${updated.join(', ')}`);
195
+ return updated;
196
+ }
197
+
198
+ /** Approve (or change) a share: sign and store the grant, send it to the signal server. */
199
+ approve(shareId, { agents, access = 'restricted', dailyCap = DEFAULT_DAILY_CAP } = {}) {
200
+ const s = this._shares.find(x => x.id === shareId && x.as === 'owner' && ['pending', 'active'].includes(x.status));
201
+ if (!s) throw new Error('No such request');
202
+ if (!s.requester?.pubKey || !s.requester?.gatewayId) throw new Error("The requester's gateway hasn't connected with sharing support yet");
203
+ const list = (Array.isArray(agents) ? agents : []).filter(a => a && typeof a.id === 'string' && a.id).map(a => ({ id: a.id, name: String(a.name || a.id).slice(0, 80) }));
204
+ if (!list.length) throw new Error('Pick at least one agent');
205
+ if (!ACCESS_MODES[access]) throw new Error('Unknown access level');
206
+ // A changed grant keeps the requester key it was first approved for: the signal server can't swap it.
207
+ const prev = this._db().prepare('SELECT grant_json FROM peer_grants WHERE share_id = ?').get(shareId);
208
+ if (prev && JSON.parse(prev.grant_json).requesterPubKey !== s.requester.pubKey) {
209
+ throw new Error("The requester's gateway key changed since you approved them. Stop sharing and ask them to request again.");
210
+ }
211
+ const grant = {
212
+ v: 1, shareId, ownerGatewayId: this.gatewayId(), requesterGatewayId: s.requester.gatewayId, requesterPubKey: s.requester.pubKey,
213
+ requesterName: cleanName(s.requester.name || s.requester.email, 60) || null,
214
+ agents: list, access, dailyCap: Math.max(1, Math.min(1000, Math.floor(Number(dailyCap) || DEFAULT_DAILY_CAP))), issuedAt: Date.now(),
215
+ };
216
+ const sig = this.key.signJson(grant);
217
+ this._db().prepare('INSERT INTO peer_grants (share_id, grant_json, sig, created_at) VALUES (?, ?, ?, ?) ON CONFLICT(share_id) DO UPDATE SET grant_json = excluded.grant_json, sig = excluded.sig, created_at = excluded.created_at, revoked_at = NULL')
218
+ .run(shareId, JSON.stringify(grant), sig, Date.now());
219
+ // An agent removed from the grant: its links pick up the new list on the next turn.
220
+ this.signal({ type: 'share-grant', shareId, grant, signature: sig });
221
+ this._changed();
222
+ return grant;
223
+ }
224
+
225
+ /** Stop a share from this side (owner or requester). Enforced locally first, then told to the server. */
226
+ revoke(shareId) {
227
+ if (this._shares.find(x => x.id === shareId)?.as === 'requester') {
228
+ this._db().prepare('INSERT OR IGNORE INTO peer_removed (share_id, removed_at) VALUES (?, ?)').run(shareId, Date.now());
229
+ }
230
+ this.onShareRevoked(shareId);
231
+ this.signal({ type: 'share-revoke', shareId });
232
+ }
233
+
234
+ _usage(shareId) {
235
+ return this._db().prepare('SELECT turns FROM peer_usage WHERE share_id = ? AND day = ?').get(shareId, today())?.turns || 0;
236
+ }
237
+
238
+ /** Whether this side would serve a peer connection for the share (checked before any WebRTC setup). */
239
+ acceptsPeer(shareId, requesterGatewayId) {
240
+ const g = this._grant(shareId);
241
+ return !!g && g.grant.requesterGatewayId === requesterGatewayId;
242
+ }
243
+
244
+ /**
245
+ * An inbound peer DataChannel (owner side). Served only for a local unrevoked grant whose
246
+ * requester gateway matches, authenticated against the key pinned in that grant.
247
+ */
248
+ servePeer({ dc, dtls, shareId, requesterGatewayId }) {
249
+ const g = this._grant(shareId);
250
+ if (!g || g.grant.requesterGatewayId !== requesterGatewayId) {
251
+ this.log.warn?.(`[sharing] refused peer link for ${shareId}: no grant`);
252
+ try { dc.close(); } catch { /* gone */ }
253
+ return null;
254
+ }
255
+ const link = new PeerLink({ dc, dtls, role: 'owner', shareId, key: this.key, peerKey: g.grant.requesterPubKey, log: this.log });
256
+ this._served.add(link);
257
+ link.on('closed', () => this._served.delete(link));
258
+ link.handle('agents', async () => ({ agents: this._grant(shareId)?.grant.agents || [] }));
259
+ link.handle('turn', (p, emit) => this._guestTurn(shareId, p, emit));
260
+ link.handle('abort', async p => this._guestAbort(shareId, p?.turnId));
261
+ return link;
262
+ }
263
+
264
+ /** Run one guest turn in this gateway's session for (share, room, agent); stream text back. */
265
+ async _guestTurn(shareId, p, emit) {
266
+ const g = this._grant(shareId);
267
+ if (!g) throw Object.assign(new Error('Sharing has ended'), { code: 'revoked' });
268
+ const { grant } = g;
269
+ const agent = grant.agents.find(a => a.id === p.agentId);
270
+ if (!agent) throw Object.assign(new Error('That agent is not shared'), { code: 'not_shared' });
271
+ const roomId = String(p.roomId || '').slice(0, 200);
272
+ if (!roomId || typeof p.message !== 'string' || !p.message.trim()) throw Object.assign(new Error('Bad turn'), { code: 'bad_request' });
273
+ if (this._usage(shareId) >= grant.dailyCap) throw Object.assign(new Error(`Daily limit reached (${grant.dailyCap} replies)`), { code: 'cap' });
274
+ if ([...this._turns.keys()].filter(k => k.startsWith(`${shareId}:`)).length >= MAX_CONCURRENT_TURNS) {
275
+ throw Object.assign(new Error('Too many replies at once; try again shortly'), { code: 'busy' });
276
+ }
277
+ const turnKey = `${shareId}:${p.turnId || crypto.randomUUID()}`;
278
+ this._turns.set(turnKey, { sessionKey: null, runId: null }); // counts toward the limit from here on
279
+ // Counted before any await, so parallel turns can't both pass the cap.
280
+ 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
+ this._changed(); // the owner's Sharing view shows today's count
282
+ try { return await this._runGuestTurn(shareId, grant, agent, roomId, p, emit, turnKey); }
283
+ finally { this._turns.delete(turnKey); }
284
+ }
285
+
286
+ async _runGuestTurn(shareId, grant, agent, roomId, p, emit, turnKey) {
287
+ const cfg = await this.request('config.get', {}, 30_000);
288
+ // A guest version whose restrictions were edited away (e.g. in the Control UI) isn't served.
289
+ const isGuest = this._db().prepare('SELECT 1 FROM peer_guest_agents WHERE agent_id = ?').get(agent.id);
290
+ if (isGuest && !hasGuestRestrictions(cfg?.parsed?.agents?.entries?.[agent.id]?.tools)) {
291
+ this.log.warn?.(`[sharing] ${agent.id} lost its guest restrictions: refusing turn for ${shareId}`);
292
+ throw Object.assign(new Error(`${agent.name} isn't available right now`), { code: 'unavailable' });
293
+ }
294
+
295
+ // Their full name, as the approval screen shows it ("Shared with Houman Test").
296
+ const name = String(grant.requesterName || 'Someone').replace(/[\n\r]/g, ' ').trim().slice(0, 60) || 'Someone';
297
+ const permissionMode = ACCESS_MODES[grant.access] || 'read-only';
298
+ // Every configured MCP server is off for guest sessions (they act with the owner's accounts).
299
+ const mcpServers = Object.fromEntries(Object.keys(cfg?.parsed?.mcp?.servers || {}).sort().map(n => [n, false]));
300
+ const toolOverrides = { webSearch: false, ...(Object.keys(mcpServers).length ? { mcpServers } : {}) };
301
+ const sessionKey = await this._guestSession(shareId, roomId, agent.id, { name, roomTitle: String(p.roomTitle || 'team chat').slice(0, 80), permissionMode, toolOverrides });
302
+ const runId = `peer-${crypto.randomUUID()}`;
303
+ const done = new Promise(resolve => {
304
+ const timer = setTimeout(() => { this._runs.delete(runId); resolve({ state: 'error', errorMessage: 'timed out' }); }, TURN_TIMEOUT_MS + 30_000);
305
+ timer.unref?.();
306
+ this._runs.set(runId, { resolve, timer, text: '', emit });
307
+ });
308
+ this._turns.set(turnKey, { sessionKey, runId });
309
+ try {
310
+ if (!this._grant(shareId)) throw Object.assign(new Error('Sharing has ended'), { code: 'revoked' }); // revoked while setting up
311
+ await this.request('chat.send', {
312
+ sessionKey, message: defangLocalPaths(`${GUEST_NOTE(name)}\n\n${p.message}`), deliver: false, idempotencyKey: runId,
313
+ timeoutMs: TURN_TIMEOUT_MS, suppressCommandInterpretation: true,
314
+ expectedPermissionMode: permissionMode, expectedToolOverrides: toolOverrides,
315
+ }, 30_000);
316
+ const r = await done;
317
+ if (r.state === 'final') return { state: 'final', text: r.message ? messageText(r.message) : await this._lastReply(sessionKey) };
318
+ if (r.state === 'aborted') return { state: 'aborted', text: r.text || '' };
319
+ throw Object.assign(new Error(r.errorMessage || 'The agent run failed'), { code: 'run_failed', partial: r.text || '' });
320
+ } finally {
321
+ const run = this._runs.get(runId);
322
+ if (run) { clearTimeout(run.timer); this._runs.delete(runId); }
323
+ }
324
+ }
325
+
326
+ async _guestAbort(shareId, turnId) {
327
+ const t = this._turns.get(`${shareId}:${turnId}`);
328
+ if (t) await this.request('chat.abort', { sessionKey: t.sessionKey, runId: t.runId }).catch(() => {});
329
+ return { ok: true };
330
+ }
331
+
332
+ /** The (share, room, agent) session on this gateway: visible to the owner in "Shared with <name>". */
333
+ async _guestSession(shareId, roomId, agentId, { name, roomTitle, permissionMode, toolOverrides }) {
334
+ const db = this._db();
335
+ const row = db.prepare('SELECT session_key FROM peer_sessions WHERE share_id = ? AND room_id = ? AND agent_id = ?').get(shareId, roomId, agentId);
336
+ if (row) {
337
+ // Re-apply the policy each turn: the owner may have changed the access level since.
338
+ await this.request('sessions.patch', { key: row.session_key, permissionMode, toolOverrides }).catch(() => {});
339
+ return row.session_key;
340
+ }
341
+ const key = `agent:${agentId}:dashboard:${crypto.randomUUID()}`;
342
+ // Labels are unique per gateway, and untitled rooms all fall back to "team chat": tag each room.
343
+ const tag = crypto.createHash('sha256').update(`${shareId}|${roomId}`).digest('hex').slice(0, 6);
344
+ const create = label => this.request('sessions.create', {
345
+ key, agentId, permissionMode, toolOverrides, label: label.slice(0, 200), category: `Shared with ${name}`.slice(0, 100),
346
+ });
347
+ try { await create(`${name} · ${roomTitle} · ${tag}`); }
348
+ catch (e) {
349
+ if (!/label already in use/i.test(e.message)) throw e;
350
+ await create(`${name} · ${roomTitle} · ${tag}-${crypto.randomBytes(2).toString('hex')}`);
351
+ }
352
+ db.prepare('INSERT OR REPLACE INTO peer_sessions (share_id, room_id, agent_id, session_key) VALUES (?, ?, ?, ?)').run(shareId, roomId, agentId, key);
353
+ return key;
354
+ }
355
+
356
+ async _lastReply(sessionKey) {
357
+ const h = await this.request('chat.history', { sessionKey, limit: 20 }, 30_000).catch(() => null);
358
+ const msgs = h?.messages || [];
359
+ for (let i = msgs.length - 1; i >= 0; i--) {
360
+ if (msgs[i].role === 'user') return '';
361
+ if (msgs[i].role === 'assistant') { const t = messageText(msgs[i]); if (t.trim()) return t; }
362
+ }
363
+ return '';
364
+ }
365
+
366
+ /** Every gateway event (owner side): finish guest runs, stream their text. */
367
+ onGatewayEvent(msg) {
368
+ if (msg?.event !== 'chat') return;
369
+ const p = msg.payload;
370
+ const run = p?.runId && this._runs.get(p.runId);
371
+ if (!run) return;
372
+ if (p.state === 'delta') {
373
+ if (p.message && !run.text) run.text = messageText(p.message);
374
+ else if (typeof p.deltaText === 'string') run.text = p.replace ? p.deltaText : run.text + p.deltaText;
375
+ run.emit?.('delta', run.text);
376
+ return;
377
+ }
378
+ if (!['final', 'aborted', 'error'].includes(p.state)) return;
379
+ this._runs.delete(p.runId);
380
+ clearTimeout(run.timer);
381
+ run.resolve({ ...p, text: run.text });
382
+ }
383
+
384
+ // ── Requester side ─────────────────────────────────────────────────
385
+
386
+ /** The grant of a share shared with this gateway, if signed by its (pinned) owner key. */
387
+ _verifiedGrant(s) {
388
+ if (s?.as !== 'requester' || s.status !== 'active' || !s.grant || !s.signature || !s.owner?.pubKey) return null;
389
+ if (this._db().prepare('SELECT 1 FROM peer_removed WHERE share_id = ?').get(s.id)) return null;
390
+ if (s.grant.requesterGatewayId !== this.gatewayId() || s.grant.shareId !== s.id || s.grant.requesterPubKey !== this.key.publicKey) return null;
391
+ const db = this._db();
392
+ const pin = db.prepare('SELECT owner_pubkey FROM peer_pins WHERE share_id = ?').get(s.id)?.owner_pubkey;
393
+ if (pin && pin !== s.owner.pubKey) {
394
+ this.log.warn?.(`[sharing] owner key changed for ${s.id} (was ${fingerprint(pin)}, now ${fingerprint(s.owner.pubKey)}): refusing`);
395
+ return null;
396
+ }
397
+ if (!verifySignature(s.owner.pubKey, canonicalJson(s.grant), s.signature)) return null;
398
+ if (!pin) db.prepare('INSERT OR IGNORE INTO peer_pins (share_id, owner_pubkey, created_at) VALUES (?, ?, ?)').run(s.id, s.owner.pubKey, Date.now());
399
+ return s.grant;
400
+ }
401
+
402
+ /** Agents shared with this gateway: [{ agentId: 'peer:<share>:<agent>', name, ownerName, shareId }]. */
403
+ remoteAgents() {
404
+ const out = [];
405
+ for (const s of this._shares) {
406
+ const grant = this._verifiedGrant(s);
407
+ if (!grant) continue;
408
+ const owner = firstName(s.owner);
409
+ for (const a of grant.agents) {
410
+ if (typeof a?.id !== 'string' || !a.id || a.id.length > 100) continue;
411
+ out.push({ agentId: `peer:${s.id}:${a.id}`, name: `${cleanName(a.name || a.id) || 'Agent'} · ${owner}`, ownerName: owner, shareId: s.id, remoteId: a.id });
412
+ }
413
+ }
414
+ return out;
415
+ }
416
+
417
+ static parseRemoteId(agentId) {
418
+ const m = /^peer:([^:]+):(.+)$/.exec(String(agentId || ''));
419
+ return m ? { shareId: m[1], remoteId: m[2] } : null;
420
+ }
421
+
422
+ async _link(shareId) {
423
+ const cur = this._links.get(shareId);
424
+ if (cur?.ready && !cur.closed) return cur;
425
+ if (this._linking.has(shareId)) return this._linking.get(shareId);
426
+ const s = this._shares.find(x => x.id === shareId);
427
+ if (!this._verifiedGrant(s)) throw Object.assign(new Error('This share is not active'), { code: 'revoked' });
428
+ const p = (async () => {
429
+ const { dc, dtls } = await this.openPeer(shareId);
430
+ const link = new PeerLink({ dc, dtls, role: 'requester', shareId, key: this.key, peerKey: s.owner.pubKey, log: this.log });
431
+ await new Promise((resolve, reject) => { link.once('ready', resolve); link.once('closed', () => reject(new Error(`Couldn't reach ${firstName(s.owner)}'s gateway`))); });
432
+ this._links.set(shareId, link);
433
+ link.on('closed', () => { if (this._links.get(shareId) === link) this._links.delete(shareId); });
434
+ return link;
435
+ })().finally(() => this._linking.delete(shareId));
436
+ this._linking.set(shareId, p);
437
+ return p;
438
+ }
439
+
440
+ /** Run a turn on a shared agent. Returns { state, text }; throws with `.partial` on failure. */
441
+ async turn(agentId, { turnId, roomId, roomTitle, message }, { onDelta } = {}) {
442
+ const id = SharingManager.parseRemoteId(agentId);
443
+ if (!id) throw new Error('not a shared agent');
444
+ const link = await this._link(id.shareId);
445
+ return link.request('turn', { turnId, agentId: id.remoteId, roomId, roomTitle, message }, {
446
+ onEvent: (event, data) => { if (event === 'delta' && typeof data === 'string') onDelta?.(data); },
447
+ timeoutMs: TURN_TIMEOUT_MS + 60_000,
448
+ });
449
+ }
450
+
451
+ async abort(agentId, turnId) {
452
+ const id = SharingManager.parseRemoteId(agentId);
453
+ const link = id && this._links.get(id.shareId);
454
+ if (link?.ready) await link.request('abort', { turnId }, { timeoutMs: 10_000 }).catch(() => {});
455
+ }
456
+
457
+ close() {
458
+ for (const l of this._links.values()) l.close();
459
+ for (const l of this._served) l.close();
460
+ this._links.clear();
461
+ }
462
+ }