@clawchatsai/connector 0.1.29 → 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/dist/index.js CHANGED
@@ -71,6 +71,34 @@ let signaling = null;
71
71
  let webrtcPeer = null;
72
72
  let healthServer = null;
73
73
  let _stopRequested = false;
74
+ // Gateway sharing: links this gateway is opening to another gateway (it offers), by share.
75
+ const PEER_OPEN_TIMEOUT_MS = 30_000;
76
+ const peerOpens = new Map();
77
+ /** Open a peer DataChannel to the owner gateway of a share (through the signal server). */
78
+ function openPeerLink(shareId) {
79
+ if (!signaling?.isConnected)
80
+ return Promise.reject(new Error('Not connected to ClawChats'));
81
+ const prev = peerOpens.get(shareId);
82
+ if (prev)
83
+ prev.reject(new Error('superseded'));
84
+ return new Promise((resolve, reject) => {
85
+ const timer = setTimeout(() => { peerOpens.delete(shareId); reject(new Error("Couldn't reach their gateway")); }, PEER_OPEN_TIMEOUT_MS);
86
+ timer.unref?.();
87
+ peerOpens.set(shareId, { resolve, reject, timer });
88
+ signaling.send({ type: 'peer-connect-request', shareId });
89
+ });
90
+ }
91
+ function settlePeerOpen(shareId, outcome) {
92
+ const p = peerOpens.get(shareId);
93
+ if (!p)
94
+ return;
95
+ peerOpens.delete(shareId);
96
+ clearTimeout(p.timer);
97
+ if (outcome instanceof Error)
98
+ p.reject(outcome);
99
+ else
100
+ p.resolve(outcome);
101
+ }
74
102
  // ---------------------------------------------------------------------------
75
103
  // Config helpers
76
104
  // ---------------------------------------------------------------------------
@@ -229,6 +257,13 @@ async function startClawChats(ctx, api) {
229
257
  authToken: process.env.CLAWCHATS_AUTH_TOKEN || '', // P2P: DataChannel is the auth boundary
230
258
  gatewayToken, // For WS auth to local OpenClaw gateway
231
259
  llm: api.runtime?.llm, // host-run completions (chat-title fallback, /api/title)
260
+ // Gateway sharing: the server side signs grants and runs guest turns; the host provides the
261
+ // signal server link and the WebRTC transport.
262
+ peer: {
263
+ gatewayId: () => loadConfig()?.gatewayId || '',
264
+ signal: (msg) => signaling?.send(msg),
265
+ openPeer: (shareId) => openPeerLink(shareId),
266
+ },
232
267
  openaiApiKey: (() => {
233
268
  // Resolve OpenAI API key: openclaw config → env var
234
269
  try {
@@ -265,7 +300,16 @@ async function startClawChats(ctx, api) {
265
300
  signaling = new SignalingClient(config.serverUrl, config.userId, config.apiKey, {
266
301
  gatewayId: config.gatewayId,
267
302
  hostname: _hostname,
303
+ peerPubKey: app.peerKey?.publicKey,
304
+ });
305
+ // Gateway sharing: share list and revocations from the signal server
306
+ signaling.on('share-list', (shares) => app?.sharing?.setShares(shares));
307
+ signaling.on('share-revoked', ({ shareId, connectionId }) => {
308
+ app?.sharing?.onShareRevoked(shareId);
309
+ if (connectionId)
310
+ webrtcPeer?.closePeer(connectionId);
268
311
  });
312
+ signaling.on('share-grant-rejected', (shareId) => ctx.logger.warn(`[sharing] signal server rejected the grant for ${shareId}`));
269
313
  signaling.on('connected', () => {
270
314
  ctx.logger.info('Connected to signaling server');
271
315
  });
@@ -285,6 +329,36 @@ async function startClawChats(ctx, api) {
285
329
  setupDataChannelHandler(dc, connectionId, ctx);
286
330
  signaling?.reportConnectionCount(webrtcPeer?.activeCount ?? 0);
287
331
  });
332
+ // Gateway sharing: a DataChannel with another gateway. Never on the browser path.
333
+ webrtcPeer.on('peer-datachannel', (dc, info) => {
334
+ if (info.role === 'owner' && info.peer) {
335
+ ctx.logger.info(`[sharing] peer link from ${info.peer.requesterGatewayId} (share ${info.peer.shareId})`);
336
+ app?.sharing?.servePeer({ dc, dtls: info.dtls, shareId: info.peer.shareId, requesterGatewayId: info.peer.requesterGatewayId });
337
+ return;
338
+ }
339
+ for (const [shareId, p] of peerOpens)
340
+ if (p.connectionId === info.connectionId)
341
+ settlePeerOpen(shareId, { dc, dtls: info.dtls });
342
+ });
343
+ signaling.on('peer-connect-ready', async ({ shareId, connectionId, iceServers }) => {
344
+ const p = peerOpens.get(shareId);
345
+ if (!p || !webrtcPeer)
346
+ return;
347
+ p.connectionId = connectionId;
348
+ try {
349
+ const offer = await webrtcPeer.createOffer(connectionId, iceServers);
350
+ signaling?.send({ type: 'ice-offer', connectionId, sdp: offer.sdp, candidates: offer.candidates });
351
+ }
352
+ catch (e) {
353
+ settlePeerOpen(shareId, new Error(`peer offer failed: ${e.message}`));
354
+ }
355
+ });
356
+ signaling.on('peer-connect-rejected', ({ shareId, reason }) => {
357
+ settlePeerOpen(shareId, new Error(reason === 'owner_offline' ? 'Their gateway is offline' : `Peer link refused (${reason})`));
358
+ });
359
+ signaling.on('ice-answer', ({ connectionId, sdp, candidates }) => {
360
+ webrtcPeer?.handleAnswer(connectionId, sdp, candidates).catch(e => ctx.logger.warn(`[sharing] answer failed: ${e.message}`));
361
+ });
288
362
  webrtcPeer.on('datachannel-closed', (connectionId) => {
289
363
  ctx.logger.info(`Browser disconnected: ${connectionId}`);
290
364
  connectedClients.delete(connectionId);
@@ -294,6 +368,12 @@ async function startClawChats(ctx, api) {
294
368
  signaling.on('ice-offer', async (offer) => {
295
369
  if (!webrtcPeer)
296
370
  return;
371
+ const peer = offer.peer;
372
+ // Another gateway: no WebRTC setup at all unless this side holds a grant for it.
373
+ if (peer && !app?.sharing?.acceptsPeer(peer.shareId, peer.requesterGatewayId)) {
374
+ ctx.logger.warn(`Refused peer offer for share ${peer.shareId}: no grant`);
375
+ return;
376
+ }
297
377
  try {
298
378
  const answer = await webrtcPeer.handleOffer(offer);
299
379
  signaling?.sendIceAnswer(answer.connectionId, answer.sdp, answer.candidates);
@@ -365,7 +445,9 @@ async function stopClawChats(ctx) {
365
445
  catch { /* already closed */ }
366
446
  connectedClients.delete(id);
367
447
  }
368
- // 2. Close all WebRTC peer connections
448
+ // 2. Close all WebRTC peer connections (browsers and gateway-sharing links)
449
+ for (const [shareId] of peerOpens)
450
+ settlePeerOpen(shareId, new Error('connector stopping'));
369
451
  webrtcPeer?.closeAll();
370
452
  webrtcPeer = null;
371
453
  // 3. Disconnect from signaling server
@@ -19,6 +19,8 @@ export declare class SignalingClient extends EventEmitter {
19
19
  private readonly apiKey;
20
20
  private readonly gatewayId?;
21
21
  private readonly hostname?;
22
+ /** This connector's Ed25519 public key for gateway sharing (base64 SPKI). */
23
+ private readonly peerPubKey?;
22
24
  private ws;
23
25
  /** True only after gateway-auth-ok has been received. */
24
26
  private _connected;
@@ -36,6 +38,7 @@ export declare class SignalingClient extends EventEmitter {
36
38
  constructor(serverUrl: string, userId: string, apiKey: string, opts?: {
37
39
  gatewayId?: string;
38
40
  hostname?: string;
41
+ peerPubKey?: string;
39
42
  });
40
43
  /** Returns true when gateway-auth-ok has been received on the current socket. */
41
44
  get isConnected(): boolean;
@@ -63,6 +66,8 @@ export declare class SignalingClient extends EventEmitter {
63
66
  * Send a trickle ICE candidate from the plugin to a browser via signaling.
64
67
  */
65
68
  sendIceCandidate(connectionId: string, candidate: unknown): void;
69
+ /** Gateway sharing messages (share-grant, share-revoke, peer-connect-request, ice-offer to a peer). */
70
+ send(payload: Record<string, unknown>): void;
66
71
  private _openSocket;
67
72
  private _handleMessage;
68
73
  private _send;
@@ -35,6 +35,8 @@ export class SignalingClient extends EventEmitter {
35
35
  apiKey;
36
36
  gatewayId;
37
37
  hostname;
38
+ /** This connector's Ed25519 public key for gateway sharing (base64 SPKI). */
39
+ peerPubKey;
38
40
  ws = null;
39
41
  /** True only after gateway-auth-ok has been received. */
40
42
  _connected = false;
@@ -56,6 +58,7 @@ export class SignalingClient extends EventEmitter {
56
58
  this.apiKey = apiKey;
57
59
  this.gatewayId = opts?.gatewayId;
58
60
  this.hostname = opts?.hostname;
61
+ this.peerPubKey = opts?.peerPubKey;
59
62
  }
60
63
  // -------------------------------------------------------------------------
61
64
  // Public API
@@ -106,6 +109,10 @@ export class SignalingClient extends EventEmitter {
106
109
  sendIceCandidate(connectionId, candidate) {
107
110
  this._send({ type: 'ice-candidate', connectionId, candidate });
108
111
  }
112
+ /** Gateway sharing messages (share-grant, share-revoke, peer-connect-request, ice-offer to a peer). */
113
+ send(payload) {
114
+ this._send(payload);
115
+ }
109
116
  // -------------------------------------------------------------------------
110
117
  // Internal — socket lifecycle
111
118
  // -------------------------------------------------------------------------
@@ -138,6 +145,7 @@ export class SignalingClient extends EventEmitter {
138
145
  pluginVersion: PLUGIN_VERSION,
139
146
  ...(this.gatewayId ? { gatewayId: this.gatewayId } : {}),
140
147
  ...(this.hostname ? { hostname: this.hostname } : {}),
148
+ ...(this.peerPubKey ? { peerPubKey: this.peerPubKey } : {}),
141
149
  });
142
150
  // Resolve the connect() promise: the socket is open and auth is in flight
143
151
  settle();
@@ -210,10 +218,31 @@ export class SignalingClient extends EventEmitter {
210
218
  connectionId: msg['connectionId'] ?? '',
211
219
  sdp: msg['sdp'] ?? '',
212
220
  candidates: msg['candidates'] ?? [],
221
+ ...(msg['peer'] ? { peer: msg['peer'] } : {}),
213
222
  };
214
223
  this.emit('ice-offer', offer);
215
224
  break;
216
225
  }
226
+ // ── Gateway sharing (signal server sharing.js) ──
227
+ case 'share-list':
228
+ this.emit('share-list', msg['shares'] ?? []);
229
+ break;
230
+ case 'share-revoked':
231
+ this.emit('share-revoked', { shareId: msg['shareId'], connectionId: msg['connectionId'] });
232
+ break;
233
+ case 'share-grant-rejected':
234
+ this.emit('share-grant-rejected', msg['shareId']);
235
+ break;
236
+ case 'peer-connect-ready':
237
+ this.emit('peer-connect-ready', { shareId: msg['shareId'], connectionId: msg['connectionId'], iceServers: msg['iceServers'] ?? [] });
238
+ break;
239
+ case 'peer-connect-rejected':
240
+ this.emit('peer-connect-rejected', { shareId: msg['shareId'], reason: msg['reason'] ?? 'rejected' });
241
+ break;
242
+ case 'ice-answer':
243
+ // Only for links this gateway opened to another gateway (it is the offerer there).
244
+ this.emit('ice-answer', { connectionId: msg['connectionId'], sdp: msg['sdp'] ?? '', candidates: msg['candidates'] ?? [] });
245
+ break;
217
246
  case 'ice-servers': {
218
247
  // ICE server config (STUN/TURN) arrives before the offer for a connection.
219
248
  const connectionId = msg['connectionId'] ?? '';
@@ -12,6 +12,24 @@ export interface IceOffer {
12
12
  connectionId: string;
13
13
  sdp: string;
14
14
  candidates: unknown[];
15
+ /** Set when another gateway is the offerer (gateway sharing). */
16
+ peer?: {
17
+ shareId: string;
18
+ requesterGatewayId: string;
19
+ };
20
+ }
21
+ /** Gateway sharing: a DataChannel to another gateway, with the DTLS fingerprints each side signs. */
22
+ export interface PeerChannelInfo {
23
+ connectionId: string;
24
+ role: 'owner' | 'requester';
25
+ peer?: {
26
+ shareId: string;
27
+ requesterGatewayId: string;
28
+ };
29
+ dtls: {
30
+ local: string;
31
+ remote: string;
32
+ };
15
33
  }
16
34
  export interface IceServers {
17
35
  connectionId: string;
@@ -31,6 +49,8 @@ export declare class WebRTCPeerManager extends EventEmitter {
31
49
  private pendingIceServers;
32
50
  private peerConnections;
33
51
  private activeChannels;
52
+ /** Gateway-sharing connections: never handed to the browser path, not counted as devices. */
53
+ private peerInfo;
34
54
  constructor();
35
55
  setIceServers(data: IceServers): void;
36
56
  handleOffer(offer: IceOffer): Promise<{
@@ -38,8 +58,21 @@ export declare class WebRTCPeerManager extends EventEmitter {
38
58
  sdp: string;
39
59
  candidates: unknown[];
40
60
  }>;
61
+ /**
62
+ * Gateway sharing: open a connection to another gateway (this side offers). The DataChannel is
63
+ * emitted as 'peer-datachannel' once open, after handleAnswer() has applied the other side's answer.
64
+ */
65
+ createOffer(connectionId: string, iceServers: any[]): Promise<{
66
+ sdp: string;
67
+ candidates: unknown[];
68
+ }>;
69
+ /** Gateway sharing: the other gateway's answer to createOffer(). */
70
+ handleAnswer(connectionId: string, sdp: string, candidates: unknown[]): Promise<void>;
71
+ /** Close a gateway-sharing connection (e.g. the share was revoked). */
72
+ closePeer(connectionId: string): void;
41
73
  handleIceCandidate(connectionId: string, candidate: unknown): void;
42
74
  closeAll(): void;
75
+ /** Browser connections (gateway-sharing links aren't devices). */
43
76
  get activeCount(): number;
44
77
  private _handleDataChannel;
45
78
  }
@@ -10,6 +10,17 @@
10
10
  import { EventEmitter } from 'node:events';
11
11
  import { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, } from 'node-datachannel/polyfill';
12
12
  // ---------------------------------------------------------------------------
13
+ // Public interfaces
14
+ // ---------------------------------------------------------------------------
15
+ const MAX_PENDING_ICE = 200;
16
+ const MAX_PEER_CONNECTIONS_PER_SHARE = 3;
17
+ const PEER_OPEN_TIMEOUT_MS = 30_000;
18
+ /** sha-256 DTLS fingerprint from an SDP ("" when absent). */
19
+ function sdpFingerprint(sdp) {
20
+ const m = /^a=fingerprint:sha-256\s+([0-9A-Fa-f:]+)\s*$/m.exec(String(sdp || ''));
21
+ return m ? m[1].toUpperCase() : '';
22
+ }
23
+ // ---------------------------------------------------------------------------
13
24
  // Internal helpers
14
25
  // ---------------------------------------------------------------------------
15
26
  function wrapDataChannel(dc) {
@@ -61,12 +72,17 @@ export class WebRTCPeerManager extends EventEmitter {
61
72
  pendingIceServers = new Map();
62
73
  peerConnections = new Map();
63
74
  activeChannels = new Map();
75
+ /** Gateway-sharing connections: never handed to the browser path, not counted as devices. */
76
+ peerInfo = new Map();
64
77
  constructor() {
65
78
  super();
66
79
  }
67
80
  setIceServers(data) {
68
81
  console.log(`[WebRTCPeerManager] Storing ICE servers for connection ${data.connectionId}`);
69
82
  this.pendingIceServers.set(data.connectionId, data.iceServers);
83
+ // Entries for offers that never come would otherwise pile up.
84
+ while (this.pendingIceServers.size > MAX_PENDING_ICE)
85
+ this.pendingIceServers.delete(this.pendingIceServers.keys().next().value);
70
86
  }
71
87
  async handleOffer(offer) {
72
88
  const { connectionId, sdp, candidates } = offer;
@@ -86,6 +102,12 @@ export class WebRTCPeerManager extends EventEmitter {
86
102
  return { connectionId, sdp: answer.sdp, candidates: [] };
87
103
  }
88
104
  console.log(`[WebRTCPeerManager] Handling ICE offer for connection ${connectionId}`);
105
+ // Another gateway dialling in: a few connections per share, and only ones that open soon.
106
+ if (offer.peer) {
107
+ const same = [...this.peerInfo.values()].filter(i => i.role === 'owner' && i.peer?.shareId === offer.peer.shareId).length;
108
+ if (same >= MAX_PEER_CONNECTIONS_PER_SHARE)
109
+ throw new Error(`too many peer connections for share ${offer.peer.shareId}`);
110
+ }
89
111
  const iceServers = this.pendingIceServers.get(connectionId) ?? [
90
112
  { urls: 'stun:stun.l.google.com:19302' },
91
113
  ];
@@ -101,6 +123,12 @@ export class WebRTCPeerManager extends EventEmitter {
101
123
  });
102
124
  const pc = new RTCPeerConnection({ iceServers: normalized });
103
125
  this.peerConnections.set(connectionId, pc);
126
+ if (offer.peer) {
127
+ this.peerInfo.set(connectionId, { connectionId, role: 'owner', peer: offer.peer, dtls: { local: '', remote: sdpFingerprint(sdp) } });
128
+ const t = setTimeout(() => { if (!this.activeChannels.has(connectionId))
129
+ this.closePeer(connectionId); }, PEER_OPEN_TIMEOUT_MS);
130
+ t.unref?.();
131
+ }
104
132
  // W3C-standard ondatachannel
105
133
  pc.ondatachannel = (event) => {
106
134
  const channel = event.channel;
@@ -129,6 +157,9 @@ export class WebRTCPeerManager extends EventEmitter {
129
157
  // Create and set local answer
130
158
  const answer = await pc.createAnswer();
131
159
  await pc.setLocalDescription(answer);
160
+ const info = this.peerInfo.get(connectionId);
161
+ if (info)
162
+ info.dtls.local = sdpFingerprint(pc.localDescription?.sdp || answer.sdp);
132
163
  console.log(`[WebRTCPeerManager] Answer created for connection ${connectionId}`);
133
164
  return {
134
165
  connectionId,
@@ -136,6 +167,54 @@ export class WebRTCPeerManager extends EventEmitter {
136
167
  candidates: [],
137
168
  };
138
169
  }
170
+ /**
171
+ * Gateway sharing: open a connection to another gateway (this side offers). The DataChannel is
172
+ * emitted as 'peer-datachannel' once open, after handleAnswer() has applied the other side's answer.
173
+ */
174
+ async createOffer(connectionId, iceServers) {
175
+ const normalized = (iceServers?.length ? iceServers : [{ urls: 'stun:stun.l.google.com:19302' }]).flatMap((s) => {
176
+ const urls = Array.isArray(s.urls) ? s.urls : [s.urls];
177
+ return urls.map((url) => ({ urls: url, ...(s.username && { username: s.username }), ...(s.credential && { credential: s.credential }) }));
178
+ });
179
+ const pc = new RTCPeerConnection({ iceServers: normalized });
180
+ this.peerConnections.set(connectionId, pc);
181
+ pc.onicecandidate = (event) => {
182
+ if (event.candidate)
183
+ this.emit('ice-candidate-local', { connectionId, candidate: event.candidate.toJSON ? event.candidate.toJSON() : event.candidate });
184
+ };
185
+ const dc = pc.createDataChannel('clawchats-peer');
186
+ const offer = await pc.createOffer();
187
+ await pc.setLocalDescription(offer);
188
+ this.peerInfo.set(connectionId, { connectionId, role: 'requester', dtls: { local: sdpFingerprint(pc.localDescription?.sdp || offer.sdp), remote: '' } });
189
+ dc.onopen = () => this._handleDataChannel(dc, connectionId);
190
+ return { sdp: pc.localDescription?.sdp || offer.sdp, candidates: [] };
191
+ }
192
+ /** Gateway sharing: the other gateway's answer to createOffer(). */
193
+ async handleAnswer(connectionId, sdp, candidates) {
194
+ const pc = this.peerConnections.get(connectionId);
195
+ const info = this.peerInfo.get(connectionId);
196
+ if (!pc || info?.role !== 'requester')
197
+ return;
198
+ info.dtls.remote = sdpFingerprint(sdp);
199
+ await pc.setRemoteDescription(new RTCSessionDescription({ sdp, type: 'answer' }));
200
+ for (const c of candidates || []) {
201
+ try {
202
+ await pc.addIceCandidate(new RTCIceCandidate(c));
203
+ }
204
+ catch { /* ignore */ }
205
+ }
206
+ }
207
+ /** Close a gateway-sharing connection (e.g. the share was revoked). */
208
+ closePeer(connectionId) {
209
+ this.activeChannels.get(connectionId)?.close();
210
+ try {
211
+ this.peerConnections.get(connectionId)?.close();
212
+ }
213
+ catch { /* gone */ }
214
+ this.peerConnections.delete(connectionId);
215
+ this.peerInfo.delete(connectionId);
216
+ this.pendingIceServers.delete(connectionId);
217
+ }
139
218
  handleIceCandidate(connectionId, candidate) {
140
219
  const pc = this.peerConnections.get(connectionId);
141
220
  if (!pc) {
@@ -163,9 +242,15 @@ export class WebRTCPeerManager extends EventEmitter {
163
242
  }
164
243
  this.peerConnections.clear();
165
244
  this.pendingIceServers.clear();
245
+ this.peerInfo.clear();
166
246
  }
247
+ /** Browser connections (gateway-sharing links aren't devices). */
167
248
  get activeCount() {
168
- return this.activeChannels.size;
249
+ let n = 0;
250
+ for (const id of this.activeChannels.keys())
251
+ if (!this.peerInfo.has(id))
252
+ n++;
253
+ return n;
169
254
  }
170
255
  _handleDataChannel(dc, connectionId) {
171
256
  console.log(`[WebRTCPeerManager] DataChannel opened for connection ${connectionId}`);
@@ -182,8 +267,14 @@ export class WebRTCPeerManager extends EventEmitter {
182
267
  catch { /* already closed */ }
183
268
  this.peerConnections.delete(connectionId);
184
269
  }
185
- this.emit('datachannel-closed', connectionId);
270
+ const info = this.peerInfo.get(connectionId);
271
+ this.peerInfo.delete(connectionId);
272
+ this.emit(info ? 'peer-datachannel-closed' : 'datachannel-closed', connectionId);
186
273
  });
187
- this.emit('datachannel', channel, connectionId);
274
+ const info = this.peerInfo.get(connectionId);
275
+ if (info)
276
+ this.emit('peer-datachannel', channel, info);
277
+ else
278
+ this.emit('datachannel', channel, connectionId);
188
279
  }
189
280
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawchatsai/connector",
3
- "version": "0.1.29",
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",
package/server/gateway.js CHANGED
@@ -98,7 +98,7 @@ export class GatewayClient {
98
98
  this.ws.send(JSON.stringify({ type: 'req', id: 'gw-connect-1', method: 'connect', params: this._connectParams(msg.payload?.nonce || '', ['tool-events']) }));
99
99
  return;
100
100
  }
101
- if (msg.type === 'res' && msg.payload?.type === 'hello-ok') { console.log('Gateway handshake complete'); this.connected = true; this.broadcastGatewayStatus(true); this.sync?.onConnected(); this.request('sessions.subscribe', {}).catch(e => console.warn(`[lens] sessions.subscribe failed: ${e.message}`)); this.lens?.seed().catch(e => console.warn(`[lens] seed failed: ${e.message}`)); }
101
+ if (msg.type === 'res' && msg.payload?.type === 'hello-ok') { console.log('Gateway handshake complete'); this.connected = true; this.broadcastGatewayStatus(true); this.sync?.onConnected(); this.onConnected?.(); this.request('sessions.subscribe', {}).catch(e => console.warn(`[lens] sessions.subscribe failed: ${e.message}`)); this.lens?.seed().catch(e => console.warn(`[lens] seed failed: ${e.message}`)); }
102
102
  // Session events arrive through the connector's own subscription; the lens filters them
103
103
  // for the browser (session.message only for chats a browser subscribed to).
104
104
  if (msg.type === 'event' && (msg.event === 'sessions.changed' || msg.event === 'session.message')) {
package/server/index.js CHANGED
@@ -21,6 +21,9 @@ import { createExtrasStore } from './store/extras-store.js';
21
21
  import { createTeamStore } from './store/team-store.js';
22
22
  import { SessionLens } from './session-lens.js';
23
23
  import { TeamCoordinator } from './team.js';
24
+ import { SharingManager } from './peer/sharing.js';
25
+ import { loadOrCreatePeerKey } from './peer/keys.js';
26
+ import { createGuestAgent } from './peer/guest-agent.js';
24
27
  import { send, sendError, parseBody, uuid, matchRoute, setCors } from './util/http.js';
25
28
 
26
29
  // PORT is passed via createApp(config.port); env var is read by plugin host (src/index.ts).
@@ -45,7 +48,7 @@ export function createApp(config = {}) {
45
48
 
46
49
  fs.mkdirSync(DATA_DIR, { recursive: true });
47
50
 
48
- function closeAll() { gatewayClient?.close(); globalDbCache.close?.(); }
51
+ function closeAll() { sharing?.close(); gatewayClient?.close(); globalDbCache.close?.(); }
49
52
 
50
53
  // Global DB (custom emojis, cross-workspace data)
51
54
  let _globalDb = null;
@@ -75,9 +78,17 @@ export function createApp(config = {}) {
75
78
  try { const n = extras.seedFromWorkspaces(getWorkspaces()); if (n) console.log(`[extras] seeded ${n} project style(s) from workspaces.json`); }
76
79
  catch (e) { console.error('[extras] style seed failed:', e.message); }
77
80
  const gwRequest = (m, p, t) => gatewayClient.request(m, p, t);
81
+ // Gateway sharing (server/peer/): other people's agents in team chats, and ours in theirs. The
82
+ // plugin host (src/index.ts) supplies the signal server link and the peer transport (config.peer).
83
+ const peerKey = loadOrCreatePeerKey(DATA_DIR);
84
+ const sharing = config.peer ? new SharingManager({
85
+ getDb: () => globalDbCache.get(), request: gwRequest, key: peerKey, broadcast,
86
+ gatewayId: config.peer.gatewayId, signal: config.peer.signal, openPeer: config.peer.openPeer,
87
+ }) : null;
78
88
  // Team chats: several agents in one thread (server/team.js).
79
- const team = new TeamCoordinator({ store: createTeamStore(() => globalDbCache.get()), request: gwRequest, broadcast, titler: createTitler(config.llm) });
80
- gatewayClient.onEvent = msg => team.onGatewayEvent(msg);
89
+ const team = new TeamCoordinator({ store: createTeamStore(() => globalDbCache.get()), request: gwRequest, broadcast, titler: createTitler(config.llm), remote: sharing });
90
+ gatewayClient.onEvent = msg => { team.onGatewayEvent(msg); sharing?.onGatewayEvent(msg); };
91
+ gatewayClient.onConnected = () => { sharing?.migrateGuestAgents().catch(e => console.warn(`[sharing] guest migration failed: ${e.message}`)); };
81
92
  gatewayClient.lens = new SessionLens({ broadcast, request: gwRequest, extras, team });
82
93
 
83
94
  // A session's working root, for relative file links (gateway resolveSessionWorkspaceRoots:
@@ -230,6 +241,35 @@ export function createApp(config = {}) {
230
241
  return send(res, 200, { ok: true });
231
242
  }
232
243
 
244
+ // Gateway sharing (server/peer/sharing.js). Approve/revoke happen here, behind this gateway's TOTP.
245
+ if (method === 'GET' && urlPath === '/api/sharing') {
246
+ // Enabled once the signal server has sharing on for this account (it then sends share lists).
247
+ if (!sharing?.serverEnabled) return send(res, 200, { enabled: false, shares: [], remoteAgents: [] });
248
+ return send(res, 200, { enabled: true, fingerprint: peerKey.fingerprint, shares: sharing.list(), remoteAgents: sharing.remoteAgents() });
249
+ }
250
+ if ((p = matchRoute(method, urlPath, 'POST /api/sharing/:id/approve'))) {
251
+ if (!sharing) return sendError(res, 404, 'Sharing is not available');
252
+ try { return send(res, 200, { grant: sharing.approve(p.id, await parseBody(req)) }); }
253
+ catch (e) { return sendError(res, 400, e.message); }
254
+ }
255
+ if (method === 'POST' && urlPath === '/api/sharing/guest-agent') {
256
+ // Owner asks for a guest version of one of its agents (peer/guest-agent.js); changes this gateway's config.
257
+ const { agentId } = await parseBody(req);
258
+ if (typeof agentId !== 'string' || !agentId) return sendError(res, 400, 'agentId is required');
259
+ try { const r = await createGuestAgent(gwRequest, agentId); sharing.markGuestAgent(r.agentId); return send(res, 200, r); }
260
+ catch (e) { return sendError(res, 400, e.message); }
261
+ }
262
+ if ((p = matchRoute(method, urlPath, 'POST /api/sharing/:id/verify-key'))) {
263
+ if (!sharing) return sendError(res, 404, 'Sharing is not available');
264
+ try { return send(res, 200, sharing.markKeyVerified(p.id)); }
265
+ catch (e) { return sendError(res, 400, e.message); }
266
+ }
267
+ if ((p = matchRoute(method, urlPath, 'POST /api/sharing/:id/revoke'))) {
268
+ if (!sharing) return sendError(res, 404, 'Sharing is not available');
269
+ sharing.revoke(p.id);
270
+ return send(res, 200, { ok: true });
271
+ }
272
+
233
273
  // Team chats (server/team.js; EXTRAS.md). Room keys contain ':' and are URL-encoded.
234
274
  if (method === 'GET' && urlPath === '/api/team') return send(res, 200, { rooms: team.rooms() });
235
275
  if (method === 'POST' && urlPath === '/api/team') {
@@ -328,6 +368,8 @@ export function createApp(config = {}) {
328
368
  gatewayClient,
329
369
  extras,
330
370
  team,
371
+ sharing,
372
+ peerKey,
331
373
  setupBrowserWs,
332
374
  debugLogger,
333
375
  dataDir: DATA_DIR,