@dolusoft/claude-collab 1.9.6 → 1.10.0

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/cli.js CHANGED
@@ -2,8 +2,8 @@
2
2
  import { Command } from 'commander';
3
3
  import { WebSocket, WebSocketServer } from 'ws';
4
4
  import { v4 } from 'uuid';
5
- import { createSocket } from 'dgram';
6
- import { tmpdir, networkInterfaces } from 'os';
5
+ import dgram from 'dgram';
6
+ import os, { tmpdir } from 'os';
7
7
  import { EventEmitter } from 'events';
8
8
  import { execFile, spawn } from 'child_process';
9
9
  import { unlinkSync } from 'fs';
@@ -19,79 +19,121 @@ function serialize(msg) {
19
19
  function parse(data) {
20
20
  return JSON.parse(data);
21
21
  }
22
- var PEER_DISCOVERY_PORT = 9998;
23
- var BROADCAST_INTERVAL_MS = 3e3;
24
- function getBroadcastAddresses() {
25
- const addrs = /* @__PURE__ */ new Set(["255.255.255.255"]);
26
- for (const ifaces of Object.values(networkInterfaces())) {
27
- for (const iface of ifaces ?? []) {
28
- if (iface.family !== "IPv4" || iface.internal) continue;
29
- const ip = iface.address.split(".").map(Number);
30
- const mask = iface.netmask.split(".").map(Number);
31
- const broadcast = ip.map((b, i) => b | ~mask[i] & 255).join(".");
32
- addrs.add(broadcast);
33
- }
34
- }
35
- return [...addrs];
36
- }
37
- var PeerBroadcaster = class {
22
+ var MULTICAST_ADDR = "239.255.42.42";
23
+ var MULTICAST_PORT = 11776;
24
+ var HEARTBEAT_INTERVAL_MS = 5e3;
25
+ var PEER_TIMEOUT_MS = 2e4;
26
+ var MulticastDiscovery = class extends EventEmitter {
38
27
  socket = null;
39
- timer = null;
40
- start(name, port) {
41
- if (this.socket) return;
42
- const socket = createSocket({ type: "udp4", reuseAddr: true });
28
+ heartbeatTimer = null;
29
+ timeoutTimer = null;
30
+ peers = /* @__PURE__ */ new Map();
31
+ myName = "";
32
+ myWsPort = 0;
33
+ start(name, wsPort) {
34
+ this.myName = name;
35
+ this.myWsPort = wsPort;
36
+ const socket = dgram.createSocket({ type: "udp4", reuseAddr: true });
43
37
  this.socket = socket;
44
38
  socket.on("error", (err) => {
45
- console.error("[peer-broadcaster] error:", err.message);
39
+ console.error("[multicast] socket error:", err.message);
46
40
  });
47
- socket.bind(0, () => {
48
- socket.setBroadcast(true);
49
- const send = () => {
50
- if (!this.socket) return;
51
- const msg = Buffer.from(JSON.stringify({ type: "claude-collab-peer", name, port }));
52
- for (const addr of getBroadcastAddresses()) {
53
- socket.send(msg, 0, msg.length, PEER_DISCOVERY_PORT, addr, (err) => {
54
- if (err) console.error(`[peer-broadcaster] send to ${addr} error:`, err.message);
55
- });
56
- }
57
- };
58
- send();
59
- this.timer = setInterval(send, BROADCAST_INTERVAL_MS);
41
+ socket.on("message", (buf, rinfo) => {
42
+ try {
43
+ const msg = JSON.parse(buf.toString());
44
+ this.handleMessage(msg, rinfo.address);
45
+ } catch {
46
+ }
47
+ });
48
+ socket.bind(MULTICAST_PORT, () => {
49
+ try {
50
+ socket.addMembership(MULTICAST_ADDR);
51
+ socket.setMulticastTTL(1);
52
+ socket.setMulticastLoopback(false);
53
+ } catch (err) {
54
+ console.error("[multicast] membership error:", err);
55
+ }
56
+ this.announce();
57
+ this.heartbeatTimer = setInterval(() => this.announce(), HEARTBEAT_INTERVAL_MS);
58
+ this.timeoutTimer = setInterval(() => this.checkTimeouts(), 5e3);
60
59
  });
61
60
  }
62
61
  stop() {
63
- if (this.timer) {
64
- clearInterval(this.timer);
65
- this.timer = null;
62
+ if (this.heartbeatTimer) {
63
+ clearInterval(this.heartbeatTimer);
64
+ this.heartbeatTimer = null;
65
+ }
66
+ if (this.timeoutTimer) {
67
+ clearInterval(this.timeoutTimer);
68
+ this.timeoutTimer = null;
66
69
  }
67
70
  if (this.socket) {
68
- this.socket.close();
71
+ this.sendMessage({ type: "LEAVE", name: this.myName });
72
+ try {
73
+ this.socket.dropMembership(MULTICAST_ADDR);
74
+ this.socket.close();
75
+ } catch {
76
+ }
69
77
  this.socket = null;
70
78
  }
79
+ this.peers.clear();
71
80
  }
72
- };
73
- function watchForPeer(onFound) {
74
- const socket = createSocket({ type: "udp4", reuseAddr: true });
75
- socket.on("error", (err) => {
76
- console.error("[peer-listener] bind failed on port", PEER_DISCOVERY_PORT, "\u2014", err.message);
77
- });
78
- socket.on("message", (msg, rinfo) => {
79
- try {
80
- const data = JSON.parse(msg.toString());
81
- if (data.type === "claude-collab-peer" && typeof data.name === "string" && typeof data.port === "number") {
82
- onFound({ name: data.name, host: rinfo.address, port: data.port });
81
+ resolveLocalIp() {
82
+ const interfaces = os.networkInterfaces();
83
+ for (const iface of Object.values(interfaces)) {
84
+ if (!iface) continue;
85
+ for (const addr of iface) {
86
+ if (addr.family === "IPv4" && !addr.internal) return addr.address;
83
87
  }
84
- } catch {
85
88
  }
86
- });
87
- socket.bind(PEER_DISCOVERY_PORT, "0.0.0.0");
88
- return () => {
89
- try {
90
- socket.close();
91
- } catch {
89
+ return "127.0.0.1";
90
+ }
91
+ // ---------------------------------------------------------------------------
92
+ // Private
93
+ // ---------------------------------------------------------------------------
94
+ announce() {
95
+ this.sendMessage({ type: "ANNOUNCE", name: this.myName, wsPort: this.myWsPort });
96
+ }
97
+ sendMessage(msg) {
98
+ if (!this.socket) return;
99
+ const buf = Buffer.from(JSON.stringify(msg));
100
+ this.socket.send(buf, MULTICAST_PORT, MULTICAST_ADDR, (err) => {
101
+ if (err) console.error("[multicast] send error:", err.message);
102
+ });
103
+ }
104
+ handleMessage(msg, fromIp) {
105
+ if (msg.type === "ANNOUNCE") {
106
+ if (msg.name === this.myName) return;
107
+ const existing = this.peers.get(msg.name);
108
+ if (!existing) {
109
+ const peer = { name: msg.name, ip: fromIp, wsPort: msg.wsPort, lastSeen: Date.now() };
110
+ this.peers.set(msg.name, peer);
111
+ this.emit("peer-found", { name: peer.name, ip: peer.ip, wsPort: peer.wsPort });
112
+ console.error(`[multicast] discovered peer: ${msg.name} @ ${fromIp}:${msg.wsPort}`);
113
+ } else {
114
+ existing.lastSeen = Date.now();
115
+ existing.ip = fromIp;
116
+ existing.wsPort = msg.wsPort;
117
+ }
118
+ } else if (msg.type === "LEAVE") {
119
+ if (this.peers.has(msg.name)) {
120
+ this.peers.delete(msg.name);
121
+ this.emit("peer-lost", msg.name);
122
+ console.error(`[multicast] peer left: ${msg.name}`);
123
+ }
92
124
  }
93
- };
94
- }
125
+ }
126
+ checkTimeouts() {
127
+ const now = Date.now();
128
+ for (const [name, peer] of this.peers) {
129
+ if (now - peer.lastSeen > PEER_TIMEOUT_MS) {
130
+ this.peers.delete(name);
131
+ this.emit("peer-lost", name);
132
+ console.error(`[multicast] peer timed out: ${name}`);
133
+ }
134
+ }
135
+ }
136
+ };
95
137
  var CS_CONINJECT = `
96
138
  using System;
97
139
  using System.Collections.Generic;
@@ -333,8 +375,7 @@ var P2PNode = class {
333
375
  answerWaiters = /* @__PURE__ */ new Map();
334
376
  // Answers queued for offline peers: peerName → AnswerMsg (delivered on reconnect)
335
377
  pendingOutboundAnswers = /* @__PURE__ */ new Map();
336
- broadcaster = null;
337
- stopPeerWatcher = null;
378
+ discovery = null;
338
379
  boundPort = 0;
339
380
  // ---------------------------------------------------------------------------
340
381
  // ICollabClient implementation
@@ -477,8 +518,8 @@ var P2PNode = class {
477
518
  return entries.sort((a, b) => a.askedAt.localeCompare(b.askedAt));
478
519
  }
479
520
  async disconnect() {
480
- this.stopPeerWatcher?.();
481
- this.broadcaster?.stop();
521
+ this.discovery?.stop();
522
+ this.discovery = null;
482
523
  for (const ws of this.peerConnections.values()) ws.close();
483
524
  this.peerConnections.clear();
484
525
  this.wsToName.clear();
@@ -549,14 +590,14 @@ var P2PNode = class {
549
590
  // Private: discovery + outbound connections
550
591
  // ---------------------------------------------------------------------------
551
592
  startDiscovery() {
552
- this.broadcaster = new PeerBroadcaster();
553
- this.broadcaster.start(this.myName, this.boundPort);
554
- this.stopPeerWatcher = watchForPeer((peer) => {
555
- if (peer.name === this.myName) return;
593
+ const discovery = new MulticastDiscovery();
594
+ this.discovery = discovery;
595
+ discovery.on("peer-found", (peer) => {
556
596
  if (this.peerConnections.has(peer.name)) return;
557
597
  if (this.connectingPeers.has(peer.name)) return;
558
- this.connectToPeer(peer.name, peer.host, peer.port);
598
+ this.connectToPeer(peer.name, peer.ip, peer.wsPort);
559
599
  });
600
+ discovery.start(this.myName, this.boundPort);
560
601
  }
561
602
  connectToPeer(peerName, host, port) {
562
603
  this.connectingPeers.add(peerName);
@@ -973,7 +1014,7 @@ async function addFirewallRule(port) {
973
1014
  "name=claude-collab-discovery",
974
1015
  "protocol=UDP",
975
1016
  "dir=in",
976
- "localport=9998",
1017
+ "localport=11776",
977
1018
  "action=allow"
978
1019
  ]);
979
1020
  } catch {
@@ -1115,6 +1156,84 @@ function registerFirewallCloseTool(server, client) {
1115
1156
  }
1116
1157
  );
1117
1158
  }
1159
+ var PEER_FIND_DESCRIPTION = `Discover and connect to peers on the LAN automatically.
1160
+
1161
+ WHAT IT DOES:
1162
+ 1. Opens your firewall so peers can connect inbound to you (UAC popup)
1163
+ 2. Waits 30 seconds while multicast discovery finds peers
1164
+ 3. Closes the firewall (UAC popup) \u2014 established connections persist
1165
+
1166
+ WHEN TO USE:
1167
+ - First time setup: everyone on the team calls peer_find
1168
+ - Adding a new peer to an existing session: only the NEW peer calls peer_find
1169
+ (existing peers will connect to them automatically \u2014 no action needed from others)
1170
+ - After a disconnect/restart: the reconnecting peer calls peer_find
1171
+
1172
+ HOW NEW PEERS JOIN AN EXISTING SESSION:
1173
+ Existing peers always listen for multicast announcements in the background.
1174
+ When you call peer_find, they hear your announcement and connect OUTBOUND to you.
1175
+ Outbound connections do not require a firewall rule on their side.
1176
+ You only need your own firewall open to accept those inbound connections.
1177
+
1178
+ NOTE: Two UAC popups will appear \u2014 one to open, one to close after the wait.`;
1179
+ function registerPeerFindTool(server, client) {
1180
+ server.tool(
1181
+ "peer_find",
1182
+ PEER_FIND_DESCRIPTION,
1183
+ {
1184
+ wait_seconds: z.number().min(10).max(120).optional().describe("How long to wait for peers in seconds (default: 30)")
1185
+ },
1186
+ async ({ wait_seconds = 30 }) => {
1187
+ const port = client.getInfo().port;
1188
+ if (!port) {
1189
+ return {
1190
+ content: [{ type: "text", text: "P2P node is not running yet. Try again in a moment." }],
1191
+ isError: true
1192
+ };
1193
+ }
1194
+ try {
1195
+ await addFirewallRule(port);
1196
+ } catch (err) {
1197
+ const msg = err instanceof Error ? err.message : String(err);
1198
+ return {
1199
+ content: [{ type: "text", text: `Failed to open firewall: ${msg}` }],
1200
+ isError: true
1201
+ };
1202
+ }
1203
+ const peersAtStart = new Set(client.getInfo().connectedPeers);
1204
+ await new Promise((resolve) => setTimeout(resolve, wait_seconds * 1e3));
1205
+ try {
1206
+ await removeFirewallRule(port);
1207
+ } catch {
1208
+ }
1209
+ const allPeers = client.getInfo().connectedPeers;
1210
+ const newPeers = allPeers.filter((p) => !peersAtStart.has(p));
1211
+ if (allPeers.length === 0) {
1212
+ return {
1213
+ content: [{
1214
+ type: "text",
1215
+ text: [
1216
+ `No peers found after ${wait_seconds}s.`,
1217
+ ``,
1218
+ `Make sure other peers are also running peer_find at the same time,`,
1219
+ `and that all machines are on the same LAN.`
1220
+ ].join("\n")
1221
+ }]
1222
+ };
1223
+ }
1224
+ const lines = [
1225
+ `Firewall closed. Connected peers (${allPeers.length}):`,
1226
+ ...allPeers.map((p) => ` \u2022 ${p}${newPeers.includes(p) ? " (new)" : ""}`),
1227
+ ``,
1228
+ `Connections will persist until a peer disconnects or restarts.`,
1229
+ `If a peer disconnects, they call peer_find again \u2014 no action needed from you.`
1230
+ ];
1231
+ return {
1232
+ content: [{ type: "text", text: lines.join("\n") }]
1233
+ };
1234
+ }
1235
+ );
1236
+ }
1118
1237
 
1119
1238
  // src/presentation/mcp/server.ts
1120
1239
  function createMcpServer(options) {
@@ -1129,6 +1248,7 @@ function createMcpServer(options) {
1129
1248
  registerHistoryTool(server, client);
1130
1249
  registerFirewallOpenTool(server, client);
1131
1250
  registerFirewallCloseTool(server, client);
1251
+ registerPeerFindTool(server, client);
1132
1252
  return server;
1133
1253
  }
1134
1254
  async function startMcpServer(options) {