@sym-bot/mesh-channel 0.1.21 → 0.1.23

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/server.js CHANGED
@@ -1,325 +1,787 @@
1
- #!/usr/bin/env node
2
- 'use strict';
3
-
4
- // Subcommand dispatch: `sym-mesh-channel init` runs the installer.
5
- if (process.argv[2] === 'init') {
6
- require('./bin/install.js');
7
- return;
8
- }
9
-
10
- /**
11
- * sym-mesh-channel — MCP server that makes Claude Code a peer node on the SYM mesh.
12
- *
13
- * Architecture (MMP Section 13.9: Local Event Interface):
14
- * SymNode (own identity, own SVAF field weights) → relay → mesh
15
- * MCP channel notifications → Claude Code (real-time push)
16
- * MCP tools → SymNode methods (send, observe, recall)
17
- *
18
- * This is a PEER NODE, not a client of the daemon. It has its own identity,
19
- * its own relay connection, and its own SVAF evaluation with engineering-domain
20
- * field weights. Per MMP Section 3: every participant is a peer.
21
- *
22
- * Copyright (c) 2026 SYM.BOT Ltd. Apache 2.0 License.
23
- */
24
-
25
- const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
26
- const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
27
- const {
28
- CallToolRequestSchema,
29
- ListToolsRequestSchema,
30
- } = require('@modelcontextprotocol/sdk/types.js');
31
- const { SymNode } = require('@sym-bot/sym');
32
-
33
- // ── Engineering-domain field weights (SVAF α_f) ──────────────
34
-
35
- const FIELD_WEIGHTS = {
36
- focus: 2.0, // code, architecture, technical decisions
37
- issue: 2.0, // bugs, blockers, technical debt
38
- intent: 1.5, // what needs building
39
- motivation: 1.0, // why it matters
40
- commitment: 1.5, // deadlines, dependencies
41
- perspective: 0.5, // viewpoint — low for engineering
42
- mood: 0.8, // user fatigue affects code quality
43
- };
44
-
45
- // ── SymNode — full peer on the mesh ──────────────────────────
46
-
47
- // Default: hostname-based identity, unique per machine. The old default
48
- // ('claude-code-mac') caused ghost-peer bugs when another machine ran
49
- // without SYM_NODE_NAME set — both machines claimed the same name with
50
- // different nodeIds, creating phantom peers that absorbed messages.
51
- const NODE_NAME = process.env.SYM_NODE_NAME || `claude-${require('os').hostname().toLowerCase().replace(/[^a-z0-9-]/g, '-')}`;
52
-
53
- const node = new SymNode({
54
- name: NODE_NAME,
55
- cognitiveProfile: 'Engineering node. Code, architecture, debugging, technical decisions.',
56
- svafFieldWeights: FIELD_WEIGHTS,
57
- svafFreshnessSeconds: 7200, // 2hr session-length context
58
- relay: process.env.SYM_RELAY_URL || null,
59
- relayToken: process.env.SYM_RELAY_TOKEN || null,
60
- silent: true,
61
- });
62
-
63
- // Identity collision (added in @sym-bot/sym 0.3.68): the relay told us
64
- // another process is holding our nodeId. Don't try to reconnect — that
65
- // caused the peer-flap loop documented in v0.1.2/v0.1.3 commit messages.
66
- // Exit so Claude Code can decide whether to respawn (with the freshness
67
- // window now elapsed) or surface the failure to the user.
68
- node.on('identity-collision', (info) => {
69
- process.stderr.write(
70
- `sym-mesh-channel: identity collision on relay — another process is holding ` +
71
- `nodeId=${info.nodeId} name=${info.name}. Exiting.\n`
72
- );
73
- process.exit(2);
74
- });
75
-
76
- // ── MCP Server ───────────────────────────────────────────────
77
-
78
- const mcp = new Server(
79
- { name: 'sym-mesh', version: '0.1.0' },
80
- {
81
- capabilities: {
82
- tools: {},
83
- experimental: { 'claude/channel': {} },
84
- },
85
- instructions:
86
- `You are a peer node on the SYM mesh (identity: ${NODE_NAME}). ` +
87
- 'Mesh events arrive as <channel> notifications in real-time. ' +
88
- 'When you see a message or CMB from another node, respond via the sym_send tool if actionable. ' +
89
- 'Share observations about the user\'s state via sym_observe. ' +
90
- 'Search mesh memory via sym_recall.',
91
- },
92
- );
93
-
94
- // ── Tools ────────────────────────────────────────────────────
95
-
96
- mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
97
- tools: [
98
- {
99
- name: 'sym_send',
100
- description: 'Send a message to all mesh peers. Stored as a persistent CMB and broadcast via relay.',
101
- inputSchema: {
102
- type: 'object',
103
- properties: { message: { type: 'string', description: 'Message to broadcast' } },
104
- required: ['message'],
105
- },
106
- },
107
- {
108
- name: 'sym_observe',
109
- description: 'Share a structured CAT7 observation with the mesh. Extract fields from what you observe.',
110
- inputSchema: {
111
- type: 'object',
112
- properties: {
113
- focus: { type: 'string' },
114
- issue: { type: 'string' },
115
- intent: { type: 'string' },
116
- motivation: { type: 'string' },
117
- commitment: { type: 'string' },
118
- perspective: { type: 'string' },
119
- mood: {
120
- type: 'object',
121
- properties: {
122
- text: { type: 'string' },
123
- valence: { type: 'number' },
124
- arousal: { type: 'number' },
125
- },
126
- },
127
- },
128
- required: ['focus'],
129
- },
130
- },
131
- {
132
- name: 'sym_recall',
133
- description: 'Search mesh memory for relevant CMBs.',
134
- inputSchema: {
135
- type: 'object',
136
- properties: { query: { type: 'string', description: 'Search query (empty for all)' } },
137
- required: ['query'],
138
- },
139
- },
140
- {
141
- name: 'sym_peers',
142
- description: 'List connected mesh peers.',
143
- inputSchema: { type: 'object', properties: {} },
144
- },
145
- {
146
- name: 'sym_status',
147
- description: 'Get mesh node status — relay connection, peer count, memory count.',
148
- inputSchema: { type: 'object', properties: {} },
149
- },
150
- ],
151
- }));
152
-
153
- mcp.setRequestHandler(CallToolRequestSchema, async (request) => {
154
- const { name, arguments: args } = request.params;
155
-
156
- switch (name) {
157
- case 'sym_send': {
158
- // Direct inter-node message — broadcast as type:'message' frame only.
159
- // Do NOT also persist as a CMB via node.remember(): that caused
160
- // double-delivery on receivers, who saw the same payload arrive once
161
- // as event_type='message' (from this broadcast) and again as
162
- // event_type='cmb' (from CMB gossip replication). One tool, one job:
163
- // sym_send is for ephemeral inter-node messages; sym_observe is for
164
- // structured CAT7 CMBs. Hosts that want both should call both.
165
- //
166
- // Report the actual delivered count (the number of peer transports
167
- // that successfully accepted the broadcast), not peers().length.
168
- // The two can disagree when peers are in _peers but their transports
169
- // are broken counting peers().length would lie about delivery.
170
- // Requires @sym-bot/sym >= 0.3.70 where send() returns the count.
171
- const msg = args.message;
172
- const delivered = node.send(msg);
173
- return { content: [{ type: 'text', text: `Message delivered to ${delivered} peer(s).` }] };
174
- }
175
-
176
- case 'sym_observe': {
177
- const fields = {
178
- focus: args.focus || 'observation',
179
- issue: args.issue || 'none',
180
- intent: args.intent || 'observation',
181
- motivation: args.motivation || '',
182
- commitment: args.commitment || '',
183
- perspective: args.perspective || NODE_NAME,
184
- mood: args.mood || { text: 'neutral', valence: 0, arousal: 0 },
185
- };
186
- const entry = node.remember(fields);
187
- return { content: [{ type: 'text', text: entry ? `Observed: ${entry.key}` : 'Duplicate — already in memory.' }] };
188
- }
189
-
190
- case 'sym_recall': {
191
- const results = node.recall(args.query || '');
192
- if (results.length === 0) {
193
- return { content: [{ type: 'text', text: 'No memories found.' }] };
194
- }
195
- const lines = results.slice(0, 10).map(r => {
196
- const focus = r.cmb?.fields?.focus?.text || r.content || '';
197
- const source = r.source || r.cmb?.createdBy || 'unknown';
198
- const time = r.timestamp ? new Date(r.timestamp).toLocaleString() : '';
199
- return `[${source}] ${time}\n ${focus.slice(0, 150)}`;
200
- });
201
- return { content: [{ type: 'text', text: lines.join('\n\n') }] };
202
- }
203
-
204
- case 'sym_peers': {
205
- const peers = node.peers();
206
- if (peers.length === 0) {
207
- return { content: [{ type: 'text', text: 'No peers connected.' }] };
208
- }
209
- const lines = peers.map(p => `${p.name} via ${p.source || 'unknown'}`);
210
- return { content: [{ type: 'text', text: `${peers.length} peer(s):\n${lines.join('\n')}` }] };
211
- }
212
-
213
- case 'sym_status': {
214
- const s = node.status();
215
- return {
216
- content: [{
217
- type: 'text',
218
- text: `Node: ${NODE_NAME} (${node.nodeId?.slice(0, 8) || '?'})\n` +
219
- `Relay: ${s.relayConnected ? 'connected' : 'disconnected'}\n` +
220
- `Peers: ${s.peerCount || 0}\n` +
221
- `Memories: ${s.memoryCount || 0}`,
222
- }],
223
- };
224
- }
225
-
226
- default:
227
- return { content: [{ type: 'text', text: `Unknown tool: ${name}` }] };
228
- }
229
- });
230
-
231
- // ── Peer Allowlist (optional, defense-in-depth) ─────────────
232
- // SYM_ALLOWED_PEERS is a comma-separated list of peer node names.
233
- // When set, only CMBs and messages from listed peers are pushed to
234
- // Claude's context. When empty/unset, all authenticated peers are
235
- // accepted (SVAF still gates on content relevance).
236
- const ALLOWED_PEERS = (process.env.SYM_ALLOWED_PEERS || '')
237
- .split(',')
238
- .map(s => s.trim())
239
- .filter(Boolean);
240
-
241
- function isPeerAllowed(peerName) {
242
- if (ALLOWED_PEERS.length === 0) return true; // no allowlist = accept all
243
- return ALLOWED_PEERS.includes(peerName);
244
- }
245
-
246
- // ── Mesh Events → Channel Notifications ──────────────────────
247
-
248
- function pushChannel(eventType, data) {
249
- try {
250
- mcp.notification({
251
- method: 'notifications/claude/channel',
252
- params: {
253
- content: typeof data === 'string' ? data : JSON.stringify(data),
254
- meta: { event_type: eventType, source: 'sym-mesh' },
255
- },
256
- });
257
- } catch {}
258
- }
259
-
260
- node.on('cmb-accepted', (entry) => {
261
- // Don't echo back our own CMBs
262
- if (entry.source === NODE_NAME || entry.cmb?.createdBy === NODE_NAME) return;
263
-
264
- const source = entry.source || entry.cmb?.createdBy || 'unknown';
265
-
266
- // Peer allowlist gate (defense-in-depth, see SECURITY.md)
267
- if (!isPeerAllowed(source)) return;
268
-
269
- const focus = entry.cmb?.fields?.focus?.text || entry.content || '';
270
- const mood = entry.cmb?.fields?.mood?.text || '';
271
- pushChannel('cmb', `[${source}] ${focus}${mood && mood !== 'neutral' ? ` (mood: ${mood})` : ''}`);
272
- });
273
-
274
- node.on('message', (from, content) => {
275
- // Peer allowlist gate
276
- if (!isPeerAllowed(from)) return;
277
-
278
- pushChannel('message', `[message from ${from}] ${content}`);
279
- });
280
-
281
- // Peer presence events are intentionally NOT pushed to Claude's context.
282
- // They're high-frequency, low-signal (peers flap on relay reconnects, daemon
283
- // restarts, NAT keepalive blips), and a flood will eat the context window.
284
- // Use sym_peers / sym_status on demand instead. Only CMBs and direct messages
285
- // are surfaced as channel notifications — those carry actual cognitive payload.
286
-
287
- // ── Start ────────────────────────────────────────────────────
288
-
289
- // Clean shutdown — disconnect from the relay before exiting so other peers
290
- // see us leave immediately, and so a fast restart of this MCP doesn't race
291
- // our own zombie connection on the relay (which would trigger the relay's
292
- // duplicate-nodeId replacement path and cause peer flap loops).
293
- //
294
- // Idempotent: Claude Code may send SIGTERM and then SIGKILL; we want the
295
- // first signal to get us cleanly off the relay even if the second one
296
- // arrives before stop() resolves.
297
- let shuttingDown = false;
298
- async function shutdown(signal) {
299
- if (shuttingDown) return;
300
- shuttingDown = true;
301
- try {
302
- await node.stop();
303
- } catch {
304
- // Best effort — we're exiting anyway. Don't block on cleanup errors.
305
- }
306
- process.exit(0);
307
- }
308
-
309
- process.on('SIGTERM', () => shutdown('SIGTERM'));
310
- process.on('SIGINT', () => shutdown('SIGINT'));
311
- process.on('SIGHUP', () => shutdown('SIGHUP'));
312
-
313
- async function main() {
314
- // Start SymNode — connects to relay as a peer
315
- await node.start();
316
-
317
- // Start MCP server — communicates with Claude Code via stdio
318
- const transport = new StdioServerTransport();
319
- await mcp.connect(transport);
320
- }
321
-
322
- main().catch((err) => {
323
- process.stderr.write(`sym-mesh-channel failed: ${err.message}\n`);
324
- process.exit(1);
325
- });
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // Subcommand dispatch: `sym-mesh-channel init` runs the installer.
5
+ if (process.argv[2] === 'init') {
6
+ require('./bin/install.js');
7
+ return;
8
+ }
9
+
10
+ /**
11
+ * sym-mesh-channel — MCP server that makes Claude Code a peer node on the SYM mesh.
12
+ *
13
+ * Architecture (MMP Section 13.9: Local Event Interface):
14
+ * SymNode (own identity, own SVAF field weights) → relay → mesh
15
+ * MCP channel notifications → Claude Code (real-time push)
16
+ * MCP tools → SymNode methods (send, observe, recall)
17
+ *
18
+ * This is a PEER NODE, not a client of the daemon. It has its own identity,
19
+ * its own relay connection, and its own SVAF evaluation with engineering-domain
20
+ * field weights. Per MMP Section 3: every participant is a peer.
21
+ *
22
+ * Copyright (c) 2026 SYM.BOT Ltd. Apache 2.0 License.
23
+ */
24
+
25
+ const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
26
+ const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
27
+ const {
28
+ CallToolRequestSchema,
29
+ ListToolsRequestSchema,
30
+ } = require('@modelcontextprotocol/sdk/types.js');
31
+ const { SymNode } = require('@sym-bot/sym');
32
+
33
+ // Kebab-case validator shared by group-related tools.
34
+ const KEBAB_CASE_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
35
+
36
+ // ── Invite URL parsing (shared by sym_invite_info and the internal
37
+ // validation path for sym_join_group when passed a URL). Exposed as
38
+ // a module-level function so it's trivially unit-testable and the
39
+ // same regex doesn't drift between two call sites.
40
+
41
+ const INVITE_URL_RE = /^([a-z][a-z0-9-]+):\/\/(?:room|group|team)\/([^/?#]+)(?:\/([^?#]+))?(?:\?(.+))?$/i;
42
+
43
+ function parseInviteURL(url) {
44
+ const m = INVITE_URL_RE.exec(url);
45
+ if (!m) {
46
+ return {
47
+ error:
48
+ `Unrecognised invite URL: ${url}\n\n` +
49
+ `Expected shapes:\n` +
50
+ ` sym://group/{name} (LAN-only)\n` +
51
+ ` sym://team/{name}?relay=...&token=... (cross-network via relay)\n` +
52
+ ` melotune://room/{id}/{name} (app-specific room)`,
53
+ };
54
+ }
55
+ const appScheme = m[1].toLowerCase();
56
+ const rawId = decodeURIComponent(m[2]);
57
+ const rawName = m[3] ? decodeURIComponent(m[3]) : rawId;
58
+ const queryStr = m[4] || '';
59
+ const query = Object.fromEntries(
60
+ queryStr.split('&').filter(Boolean).map(kv => {
61
+ const [k, v = ''] = kv.split('=');
62
+ return [decodeURIComponent(k), decodeURIComponent(v)];
63
+ })
64
+ );
65
+ // For sym:// the path element IS the group name. For app-scoped URLs
66
+ // (melotune://, melomove://, etc.) the path is the room id and the
67
+ // group is prefixed with the app name to avoid collisions.
68
+ const serviceType = appScheme === 'sym' ? `_${rawId}._tcp` : `_${appScheme}-${rawId}._tcp`;
69
+ const group = appScheme === 'sym' ? rawId : `${appScheme}-${rawId}`;
70
+ return {
71
+ appScheme,
72
+ group,
73
+ serviceType,
74
+ roomId: rawId,
75
+ roomName: rawName,
76
+ relayUrl: query.relay || null,
77
+ relayToken: query.token || null,
78
+ };
79
+ }
80
+
81
+ // ── Bonjour discovery of live SYM-related service types.
82
+ // Runs `dns-sd -B _services._dns-sd._udp local.` (macOS / Windows with
83
+ // Bonjour) or `avahi-browse -at` (Linux) for 2 seconds, filters to
84
+ // service types that look SYM-ish, and reports them. Pure observation,
85
+ // no node state changes.
86
+
87
+ async function discoverGroups() {
88
+ const { spawn } = require('child_process');
89
+ const platform = process.platform;
90
+
91
+ let cmd, argv;
92
+ if (platform === 'darwin' || platform === 'win32') {
93
+ cmd = 'dns-sd';
94
+ argv = ['-B', '_services._dns-sd._udp', 'local.'];
95
+ } else {
96
+ cmd = 'avahi-browse';
97
+ argv = ['-t', '-a', '-p']; // terminate after cache, all services, parseable
98
+ }
99
+
100
+ return new Promise((resolve) => {
101
+ let child;
102
+ try {
103
+ child = spawn(cmd, argv, { stdio: ['ignore', 'pipe', 'pipe'] });
104
+ } catch (e) {
105
+ return resolve({
106
+ isError: true,
107
+ text:
108
+ `Could not run discovery command '${cmd}': ${e?.message || e}\n\n` +
109
+ (platform === 'linux'
110
+ ? `On Linux, install avahi-utils: sudo apt install avahi-utils`
111
+ : `Bonjour should be built-in on macOS and Windows 10+.`),
112
+ });
113
+ }
114
+ const out = [];
115
+ child.stdout.on('data', (chunk) => out.push(chunk));
116
+ child.on('error', (e) => resolve({ isError: true, text: `Discovery command failed: ${e?.message || e}` }));
117
+
118
+ const timer = setTimeout(() => {
119
+ try { child.kill('SIGTERM'); } catch {}
120
+ }, 2000);
121
+ child.on('close', () => {
122
+ clearTimeout(timer);
123
+ const text = Buffer.concat(out).toString('utf8');
124
+ const typeRe = /_([a-z0-9][a-z0-9-]+)\._tcp/gi;
125
+ const seen = new Set();
126
+ let m;
127
+ while ((m = typeRe.exec(text)) !== null) {
128
+ const full = `_${m[1]}._tcp`;
129
+ // Filter to the SYM protocol family: global sym, named groups, and
130
+ // app-scoped rooms (melotune-<id>, melomove-<id>, etc). Anything
131
+ // that looks like generic infra (_services._dns-sd, _tcp, _udp,
132
+ // printer protocols, etc.) is ignored.
133
+ if (/^_(sym|[a-z]+-[a-z0-9]+|[a-z]+-team|.*-team)\._tcp$/i.test(full)) {
134
+ seen.add(full);
135
+ }
136
+ }
137
+ if (seen.size === 0) {
138
+ return resolve({
139
+ text:
140
+ `No SYM-mesh groups visible on the local network right now.\n\n` +
141
+ `This only shows groups with at least one node currently online. ` +
142
+ `Groups you or teammates have used before are not persisted anywhere ` +
143
+ `(p2p architecture no central directory).\n\n` +
144
+ `Your node is on: ${SERVICE_TYPE} (group "${GROUP}").`,
145
+ });
146
+ }
147
+ const lines = [];
148
+ lines.push(`SYM-mesh groups visible on LAN (${seen.size}):`);
149
+ for (const st of Array.from(seen).sort()) {
150
+ const name = st.replace(/^_/, '').replace(/\._tcp$/, '');
151
+ const isSelf = st === SERVICE_TYPE ? ' (← your current group)' : '';
152
+ lines.push(` ${st} group="${name}"${isSelf}`);
153
+ }
154
+ lines.push('');
155
+ lines.push(`To join one, call sym_join_group with group="<name>".`);
156
+ resolve({ text: lines.join('\n') });
157
+ });
158
+ });
159
+ }
160
+
161
+ // ── Engineering-domain field weights (SVAF α_f) ──────────────
162
+
163
+ const FIELD_WEIGHTS = {
164
+ focus: 2.0, // code, architecture, technical decisions
165
+ issue: 2.0, // bugs, blockers, technical debt
166
+ intent: 1.5, // what needs building
167
+ motivation: 1.0, // why it matters
168
+ commitment: 1.5, // deadlines, dependencies
169
+ perspective: 0.5, // viewpointlow for engineering
170
+ mood: 0.8, // user fatigue affects code quality
171
+ };
172
+
173
+ // ── SymNode full peer on the mesh ──────────────────────────
174
+
175
+ // Default: hostname-based identity, unique per machine. The old default
176
+ // ('claude-code-mac') caused ghost-peer bugs when another machine ran
177
+ // without SYM_NODE_NAME set — both machines claimed the same name with
178
+ // different nodeIds, creating phantom peers that absorbed messages.
179
+ const NODE_NAME = process.env.SYM_NODE_NAME || `claude-${require('os').hostname().toLowerCase().replace(/[^a-z0-9-]/g, '-')}`;
180
+
181
+ // ── Mesh group (MMP §5.8) ──────────────────────────────────
182
+ //
183
+ // LAN isolation by Bonjour service type. `_sym._tcp` is the default
184
+ // (backward compatible). A named group `<foo>` maps to service type
185
+ // `_foo._tcp`. Passing a full `_foo._tcp` service type explicitly also
186
+ // works. Nodes in different groups never discover each other at mDNS.
187
+ // See MeloTune's MoodRoom model for the per-room pattern
188
+ // (`_melotune-{id}._tcp`).
189
+ function resolveServiceType() {
190
+ const explicit = process.env.SYM_SERVICE_TYPE;
191
+ if (explicit) return explicit;
192
+ const group = process.env.SYM_GROUP;
193
+ if (group && group !== 'default') return `_${group}._tcp`;
194
+ return '_sym._tcp';
195
+ }
196
+ // Mutable so sym_join_group can hot-swap the node at runtime without a
197
+ // Claude Code restart. Declaring as `let` rather than `const` is the
198
+ // smallest change that makes hot-swap possible.
199
+ let SERVICE_TYPE = resolveServiceType();
200
+ let GROUP = process.env.SYM_GROUP || (SERVICE_TYPE !== '_sym._tcp'
201
+ ? SERVICE_TYPE.replace(/^_/, '').replace(/\._tcp$/, '')
202
+ : 'default');
203
+ let RELAY_URL = process.env.SYM_RELAY_URL || null;
204
+ let RELAY_TOKEN = process.env.SYM_RELAY_TOKEN || null;
205
+
206
+ let node = new SymNode({
207
+ name: NODE_NAME,
208
+ cognitiveProfile: 'Engineering node. Code, architecture, debugging, technical decisions.',
209
+ svafFieldWeights: FIELD_WEIGHTS,
210
+ svafFreshnessSeconds: 7200, // 2hr session-length context
211
+ discoveryServiceType: SERVICE_TYPE,
212
+ group: GROUP,
213
+ relay: RELAY_URL,
214
+ relayToken: RELAY_TOKEN,
215
+ silent: true,
216
+ });
217
+
218
+ // Event handlers are extracted into a single registration function so the
219
+ // hot-swap path in sym_join_group can re-register them on the new node.
220
+ // The function reads module-level `NODE_NAME`, `isPeerAllowed`, `pushChannel`,
221
+ // `storeMessage`, and `extractCompactHeader` via closure; those don't change
222
+ // across swaps.
223
+ function registerNodeHandlers(n) {
224
+ // Identity collision (added in @sym-bot/sym 0.3.68): the relay told us
225
+ // another process is holding our nodeId. Don't try to reconnect — that
226
+ // caused the peer-flap loop documented in v0.1.2/v0.1.3 commit messages.
227
+ // Exit so Claude Code can decide whether to respawn (with the freshness
228
+ // window now elapsed) or surface the failure to the user.
229
+ n.on('identity-collision', (info) => {
230
+ process.stderr.write(
231
+ `sym-mesh-channel: identity collision on relay another process is holding ` +
232
+ `nodeId=${info.nodeId} name=${info.name}. Exiting.\n`
233
+ );
234
+ process.exit(2);
235
+ });
236
+
237
+ n.on('cmb-accepted', (entry) => {
238
+ if (entry.source === NODE_NAME || entry.cmb?.createdBy === NODE_NAME) return;
239
+ const source = entry.source || entry.cmb?.createdBy || 'unknown';
240
+ if (!isPeerAllowed(source)) return;
241
+ const focus = entry.cmb?.fields?.focus?.text || entry.content || '';
242
+ const mood = entry.cmb?.fields?.mood?.text || '';
243
+ pushChannel('cmb', `[${source}] ${focus}${mood && mood !== 'neutral' ? ` (mood: ${mood})` : ''}`);
244
+ });
245
+
246
+ n.on('message', (from, content) => {
247
+ if (!isPeerAllowed(from)) return;
248
+ const msgId = storeMessage(from, content);
249
+ const header = extractCompactHeader(from, content);
250
+ pushChannel('message', `[${from}] ${header} [${msgId}]`);
251
+ });
252
+ }
253
+
254
+ // ── MCP Server ───────────────────────────────────────────────
255
+
256
+ const mcp = new Server(
257
+ { name: 'sym-mesh', version: '0.1.0' },
258
+ {
259
+ capabilities: {
260
+ tools: {},
261
+ experimental: { 'claude/channel': {} },
262
+ },
263
+ instructions:
264
+ `You are a peer node on the SYM mesh (identity: ${NODE_NAME}). ` +
265
+ 'Mesh events arrive as <channel> notifications in real-time. ' +
266
+ 'When you see a message or CMB from another node, respond via the sym_send tool if actionable. ' +
267
+ 'Share observations about the user\'s state via sym_observe. ' +
268
+ 'Search mesh memory via sym_recall. ' +
269
+ 'Messages arrive as compact headers with [mNNN] IDs — use sym_fetch to read the full content when the header is relevant to your current task.',
270
+ },
271
+ );
272
+
273
+ // ── Tools ────────────────────────────────────────────────────
274
+
275
+ mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
276
+ tools: [
277
+ {
278
+ name: 'sym_send',
279
+ description: 'Send a message to all mesh peers. Stored as a persistent CMB and broadcast via relay.',
280
+ inputSchema: {
281
+ type: 'object',
282
+ properties: { message: { type: 'string', description: 'Message to broadcast' } },
283
+ required: ['message'],
284
+ },
285
+ },
286
+ {
287
+ name: 'sym_observe',
288
+ description: 'Share a structured CAT7 observation with the mesh. Extract fields from what you observe.',
289
+ inputSchema: {
290
+ type: 'object',
291
+ properties: {
292
+ focus: { type: 'string' },
293
+ issue: { type: 'string' },
294
+ intent: { type: 'string' },
295
+ motivation: { type: 'string' },
296
+ commitment: { type: 'string' },
297
+ perspective: { type: 'string' },
298
+ mood: {
299
+ type: 'object',
300
+ properties: {
301
+ text: { type: 'string' },
302
+ valence: { type: 'number' },
303
+ arousal: { type: 'number' },
304
+ },
305
+ },
306
+ },
307
+ required: ['focus'],
308
+ },
309
+ },
310
+ {
311
+ name: 'sym_recall',
312
+ description: 'Search mesh memory for relevant CMBs.',
313
+ inputSchema: {
314
+ type: 'object',
315
+ properties: { query: { type: 'string', description: 'Search query (empty for all)' } },
316
+ required: ['query'],
317
+ },
318
+ },
319
+ {
320
+ name: 'sym_peers',
321
+ description: 'List connected mesh peers.',
322
+ inputSchema: { type: 'object', properties: {} },
323
+ },
324
+ {
325
+ name: 'sym_status',
326
+ description: 'Get mesh node status — relay connection, peer count, memory count.',
327
+ inputSchema: { type: 'object', properties: {} },
328
+ },
329
+ {
330
+ name: 'sym_fetch',
331
+ description: 'Fetch full content of a mesh message by ID. Use when a compact channel notification needs deeper reading.',
332
+ inputSchema: {
333
+ type: 'object',
334
+ properties: { msg_id: { type: 'string', description: 'Message ID (e.g., m007)' } },
335
+ required: ['msg_id'],
336
+ },
337
+ },
338
+ {
339
+ name: 'sym_group_info',
340
+ description: 'Report the mesh group this node is in (MMP §5.8). Shows service type + group name + peer count.',
341
+ inputSchema: { type: 'object', properties: {} },
342
+ },
343
+ {
344
+ name: 'sym_invite_create',
345
+ description: 'Generate a shareable invite URL for a named mesh group. Team leads use this to let teammates join their dev-team mesh. LAN-only invite: pass group only, returns sym://group/{name}. Cross-network invite: pass relay_url + relay_token too, returns sym://team/{name}?relay=...&token=... — teammates on different networks join through the relay.',
346
+ inputSchema: {
347
+ type: 'object',
348
+ properties: {
349
+ group: { type: 'string', description: 'Kebab-case group name, e.g. "backend-team".' },
350
+ relay_url: { type: 'string', description: 'Optional WebSocket relay URL, e.g. wss://sym-relay.onrender.com. Include for cross-network teams.' },
351
+ relay_token: { type: 'string', description: 'Optional relay authentication token (shared secret for this team channel).' },
352
+ },
353
+ required: ['group'],
354
+ },
355
+ },
356
+ {
357
+ name: 'sym_invite_info',
358
+ description: 'Parse a mesh invite URL and return everything the invitee needs to join: group name, service type, and any relay credentials. Read-only; does NOT switch the current node (use sym_join_group for that). Works on LAN group invites (sym://group/{name}), cross-network team invites (sym://team/{name}?relay=&token=), and app-specific room invites (e.g. melotune://room/{id}/{name}).',
359
+ inputSchema: {
360
+ type: 'object',
361
+ properties: { url: { type: 'string', description: 'Invite URL, e.g. sym://group/backend-team' } },
362
+ required: ['url'],
363
+ },
364
+ },
365
+ {
366
+ name: 'sym_join_group',
367
+ description: 'Hot-swap this node into a different mesh group at runtime — no Claude Code restart needed. Stops the current SymNode, reconstructs it with the new group (and optional relay credentials), and restarts it. Teammates on the same group/relay will discover this node via Bonjour (LAN) or the relay (cross-network). To leave a group, pass group="default" which reverts to the global _sym._tcp mesh.',
368
+ inputSchema: {
369
+ type: 'object',
370
+ properties: {
371
+ group: { type: 'string', description: 'Kebab-case group name, e.g. "backend-team". Pass "default" to return to the global mesh.' },
372
+ relay_url: { type: 'string', description: 'Optional WebSocket relay URL for cross-network teams. Leave empty for LAN-only.' },
373
+ relay_token: { type: 'string', description: 'Optional relay authentication token.' },
374
+ },
375
+ required: ['group'],
376
+ },
377
+ },
378
+ {
379
+ name: 'sym_groups_discover',
380
+ description: 'List SYM-mesh groups currently advertising on the local network. Uses Bonjour / mDNS to find service types matching the SYM protocol. Only shows groups with at least one node online right now — there is no central directory of offline-but-known groups. macOS and Windows have Bonjour built in; Linux requires avahi-daemon.',
381
+ inputSchema: { type: 'object', properties: {} },
382
+ },
383
+ ],
384
+ }));
385
+
386
+ mcp.setRequestHandler(CallToolRequestSchema, async (request) => {
387
+ const { name, arguments: args } = request.params;
388
+
389
+ switch (name) {
390
+ case 'sym_send': {
391
+ // Direct inter-node message — broadcast as type:'message' frame only.
392
+ // Do NOT also persist as a CMB via node.remember(): that caused
393
+ // double-delivery on receivers, who saw the same payload arrive once
394
+ // as event_type='message' (from this broadcast) and again as
395
+ // event_type='cmb' (from CMB gossip replication). One tool, one job:
396
+ // sym_send is for ephemeral inter-node messages; sym_observe is for
397
+ // structured CAT7 CMBs. Hosts that want both should call both.
398
+ //
399
+ // Report the actual delivered count (the number of peer transports
400
+ // that successfully accepted the broadcast), not peers().length.
401
+ // The two can disagree when peers are in _peers but their transports
402
+ // are broken — counting peers().length would lie about delivery.
403
+ // Requires @sym-bot/sym >= 0.3.70 where send() returns the count.
404
+ const msg = args.message;
405
+ const delivered = node.send(msg);
406
+ return { content: [{ type: 'text', text: `Message delivered to ${delivered} peer(s).` }] };
407
+ }
408
+
409
+ case 'sym_observe': {
410
+ const fields = {
411
+ focus: args.focus || 'observation',
412
+ issue: args.issue || 'none',
413
+ intent: args.intent || 'observation',
414
+ motivation: args.motivation || '',
415
+ commitment: args.commitment || '',
416
+ perspective: args.perspective || NODE_NAME,
417
+ mood: args.mood || { text: 'neutral', valence: 0, arousal: 0 },
418
+ };
419
+ const entry = node.remember(fields);
420
+ return { content: [{ type: 'text', text: entry ? `Observed: ${entry.key}` : 'Duplicate — already in memory.' }] };
421
+ }
422
+
423
+ case 'sym_recall': {
424
+ const results = node.recall(args.query || '');
425
+ if (results.length === 0) {
426
+ return { content: [{ type: 'text', text: 'No memories found.' }] };
427
+ }
428
+ const lines = results.slice(0, 10).map(r => {
429
+ const focus = r.cmb?.fields?.focus?.text || r.content || '';
430
+ const source = r.source || r.cmb?.createdBy || 'unknown';
431
+ const time = r.timestamp ? new Date(r.timestamp).toLocaleString() : '';
432
+ return `[${source}] ${time}\n ${focus.slice(0, 150)}`;
433
+ });
434
+ return { content: [{ type: 'text', text: lines.join('\n\n') }] };
435
+ }
436
+
437
+ case 'sym_peers': {
438
+ const peers = node.peers();
439
+ if (peers.length === 0) {
440
+ return { content: [{ type: 'text', text: 'No peers connected.' }] };
441
+ }
442
+ const lines = peers.map(p => `${p.name} via ${p.source || 'unknown'}`);
443
+ return { content: [{ type: 'text', text: `${peers.length} peer(s):\n${lines.join('\n')}` }] };
444
+ }
445
+
446
+ case 'sym_fetch': {
447
+ const entry = MESSAGE_STORE.get(args.msg_id);
448
+ if (!entry) {
449
+ return { content: [{ type: 'text', text: `Message ${args.msg_id} not found (expired or invalid ID).` }] };
450
+ }
451
+ return {
452
+ content: [{
453
+ type: 'text',
454
+ text: `[${entry.from}] ${new Date(entry.timestamp).toISOString()}\n\n${entry.content}`,
455
+ }],
456
+ };
457
+ }
458
+
459
+ case 'sym_status': {
460
+ const s = node.status();
461
+ return {
462
+ content: [{
463
+ type: 'text',
464
+ text: `Node: ${NODE_NAME} (${node.nodeId?.slice(0, 8) || '?'})\n` +
465
+ `Group: ${GROUP} (${SERVICE_TYPE})\n` +
466
+ `Relay: ${s.relayConnected ? 'connected' : 'disconnected'}\n` +
467
+ `Peers: ${s.peerCount || 0}\n` +
468
+ `Memories: ${s.memoryCount || 0}`,
469
+ }],
470
+ };
471
+ }
472
+
473
+ case 'sym_group_info': {
474
+ const s = node.status();
475
+ const peers = typeof node.getPeers === 'function' ? node.getPeers() : [];
476
+ const peerLines = peers.length
477
+ ? peers.map(p => ` ${p.name} (${(p.peerId || '').slice(0, 8)}) via ${p.transport || '?'}`).join('\n')
478
+ : ' (no peers in this group)';
479
+ return {
480
+ content: [{
481
+ type: 'text',
482
+ text: `Mesh group (MMP §5.8):\n` +
483
+ ` group: ${GROUP}\n` +
484
+ ` service type: ${SERVICE_TYPE}\n` +
485
+ ` node: ${NODE_NAME} (${node.nodeId?.slice(0, 8) || '?'})\n` +
486
+ ` peers in group: ${s.peerCount || 0}\n` +
487
+ peerLines + `\n\n` +
488
+ `To join a different group, restart the sym-mesh-channel MCP server with env var SYM_GROUP=<name> or SYM_SERVICE_TYPE=<_foo._tcp>.`,
489
+ }],
490
+ };
491
+ }
492
+
493
+ case 'sym_invite_create': {
494
+ const group = args?.group;
495
+ const relayUrl = args?.relay_url;
496
+ const relayToken = args?.relay_token;
497
+ if (!group || typeof group !== 'string') {
498
+ return { content: [{ type: 'text', text: 'Missing required argument: group' }], isError: true };
499
+ }
500
+ if (!KEBAB_CASE_RE.test(group)) {
501
+ return {
502
+ content: [{
503
+ type: 'text',
504
+ text: `Invalid group name: "${group}". Must be kebab-case (lowercase alphanumerics + single hyphens), e.g. "backend-team".`,
505
+ }],
506
+ isError: true,
507
+ };
508
+ }
509
+ // LAN-only flavor: sym://group/{name}
510
+ // Cross-network flavor: sym://team/{name}?relay=...&token=...
511
+ let url;
512
+ let flavor;
513
+ if (relayUrl || relayToken) {
514
+ if (!relayUrl) return { content: [{ type: 'text', text: 'relay_token requires relay_url' }], isError: true };
515
+ const params = [`relay=${encodeURIComponent(relayUrl)}`];
516
+ if (relayToken) params.push(`token=${encodeURIComponent(relayToken)}`);
517
+ url = `sym://team/${group}?${params.join('&')}`;
518
+ flavor = 'cross-network (relay)';
519
+ } else {
520
+ url = `sym://group/${group}`;
521
+ flavor = 'LAN-only (Bonjour)';
522
+ }
523
+ const youRunning = GROUP === group
524
+ ? `You're already on this group — teammates who join will see you.`
525
+ : `You are currently on group "${GROUP}". To be reachable, call sym_join_group with group="${group}" (+ same relay creds if cross-network) before sharing.`;
526
+ return {
527
+ content: [{
528
+ type: 'text',
529
+ text: `Invite URL (${flavor}):\n\n ${url}\n\n` +
530
+ `Share this URL with teammates. Each pastes it into Claude Code and calls sym_join_group (or sym_invite_info for a dry run first).\n\n` +
531
+ youRunning,
532
+ }],
533
+ };
534
+ }
535
+
536
+ case 'sym_invite_info': {
537
+ const url = args?.url;
538
+ if (!url || typeof url !== 'string') {
539
+ return { content: [{ type: 'text', text: 'Missing required argument: url' }], isError: true };
540
+ }
541
+ const parsed = parseInviteURL(url);
542
+ if (parsed.error) {
543
+ return { content: [{ type: 'text', text: parsed.error }], isError: true };
544
+ }
545
+ const { appScheme, group, serviceType, roomId, roomName, relayUrl, relayToken } = parsed;
546
+
547
+ const out = {
548
+ app: appScheme,
549
+ group,
550
+ service_type: serviceType,
551
+ room_id: appScheme === 'sym' ? undefined : roomId,
552
+ room_name: appScheme === 'sym' ? undefined : roomName,
553
+ relay_url: relayUrl || undefined,
554
+ relay_token: relayToken || undefined,
555
+ };
556
+ for (const k of Object.keys(out)) if (out[k] === undefined) delete out[k];
557
+
558
+ const joinCall = {
559
+ group,
560
+ ...(relayUrl && { relay_url: relayUrl }),
561
+ ...(relayToken && { relay_token: relayToken }),
562
+ };
563
+
564
+ return {
565
+ content: [{
566
+ type: 'text',
567
+ text: `Parsed invite: ${url}\n\n` +
568
+ JSON.stringify(out, null, 2) + `\n\n` +
569
+ `To join, call sym_join_group:\n\n ${JSON.stringify(joinCall)}\n\n` +
570
+ `This hot-swaps your node into the ${relayUrl ? 'relay channel' : 'LAN group'} — no Claude Code restart needed.`,
571
+ }],
572
+ };
573
+ }
574
+
575
+ case 'sym_join_group': {
576
+ const group = args?.group;
577
+ const relayUrl = args?.relay_url || null;
578
+ const relayToken = args?.relay_token || null;
579
+ if (!group || typeof group !== 'string') {
580
+ return { content: [{ type: 'text', text: 'Missing required argument: group' }], isError: true };
581
+ }
582
+ if (!KEBAB_CASE_RE.test(group) && group !== 'default') {
583
+ return {
584
+ content: [{ type: 'text', text: `Invalid group name: "${group}". Must be kebab-case or "default".` }],
585
+ isError: true,
586
+ };
587
+ }
588
+
589
+ const newServiceType = group === 'default' ? '_sym._tcp' : `_${group}._tcp`;
590
+ const prevGroup = GROUP;
591
+ const prevServiceType = SERVICE_TYPE;
592
+
593
+ // Stop the current node cleanly so peers see us leave, then construct
594
+ // a fresh one on the new service type. Any failure during restart is
595
+ // reported; the previous node will already be stopped, so the caller
596
+ // is in a known-disconnected state and can retry.
597
+ try {
598
+ await node.stop();
599
+ } catch (e) {
600
+ return {
601
+ content: [{ type: 'text', text: `Failed to stop current node: ${e?.message || e}` }],
602
+ isError: true,
603
+ };
604
+ }
605
+
606
+ const newNode = new SymNode({
607
+ name: NODE_NAME,
608
+ cognitiveProfile: 'Engineering node. Code, architecture, debugging, technical decisions.',
609
+ svafFieldWeights: FIELD_WEIGHTS,
610
+ svafFreshnessSeconds: 7200,
611
+ discoveryServiceType: newServiceType,
612
+ group,
613
+ relay: relayUrl,
614
+ relayToken,
615
+ silent: true,
616
+ });
617
+ registerNodeHandlers(newNode);
618
+
619
+ try {
620
+ await newNode.start();
621
+ } catch (e) {
622
+ return {
623
+ content: [{
624
+ type: 'text',
625
+ text: `Failed to start new node on group "${group}": ${e?.message || e}\n\n` +
626
+ `Previous node already stopped. To recover, call sym_join_group with group="${prevGroup}".`,
627
+ }],
628
+ isError: true,
629
+ };
630
+ }
631
+
632
+ // Swap module-level references only after successful start.
633
+ node = newNode;
634
+ GROUP = group;
635
+ SERVICE_TYPE = newServiceType;
636
+ RELAY_URL = relayUrl;
637
+ RELAY_TOKEN = relayToken;
638
+
639
+ return {
640
+ content: [{
641
+ type: 'text',
642
+ text: `Hot-swapped from group "${prevGroup}" (${prevServiceType}) to "${group}" (${newServiceType}).\n` +
643
+ (relayUrl ? `Relay: ${relayUrl}\n` : '') +
644
+ `Discovering peers on the new service type. Call sym_peers in a moment to see who's online.`,
645
+ }],
646
+ };
647
+ }
648
+
649
+ case 'sym_groups_discover': {
650
+ const result = await discoverGroups();
651
+ return {
652
+ content: [{
653
+ type: 'text',
654
+ text: result.text,
655
+ }],
656
+ isError: result.isError || false,
657
+ };
658
+ }
659
+
660
+ default:
661
+ return { content: [{ type: 'text', text: `Unknown tool: ${name}` }] };
662
+ }
663
+ });
664
+
665
+ // ── Compact Channel — message store for lazy-load (v0.1) ────
666
+ // Per COO spec cmb_compact_channel_v0.1.md: push compact headers,
667
+ // store full content for on-demand sym_fetch retrieval. ~10% token
668
+ // savings on mesh traffic without context loss.
669
+ const MESSAGE_STORE = new Map();
670
+ let msgSeq = 0;
671
+ const MAX_STORED = 200;
672
+
673
+ function storeMessage(from, content) {
674
+ const msgId = `m${String(++msgSeq).padStart(3, '0')}`;
675
+ MESSAGE_STORE.set(msgId, { from, content, timestamp: Date.now() });
676
+ while (MESSAGE_STORE.size > MAX_STORED) {
677
+ const oldest = MESSAGE_STORE.keys().next().value;
678
+ MESSAGE_STORE.delete(oldest);
679
+ }
680
+ return msgId;
681
+ }
682
+
683
+ function extractCompactHeader(from, content) {
684
+ const lines = content.split('\n').filter(l => l.trim());
685
+ const focusMatch = content.match(/focus[=:]\s*([^\n\]]{0,80})/i);
686
+ const bracketMatch = content.match(/\[([^\]]{0,120})\]/);
687
+
688
+ const hasHalt = /\bhalt\b/i.test(content);
689
+ const hasDirective = /\bdirective\b/i.test(content);
690
+ const hasResults = /\bresult|complete|landed|done\b/i.test(content);
691
+ const hasAck = /\back\b/i.test(content);
692
+
693
+ let signal = '';
694
+ if (hasHalt) signal = 'HALT';
695
+ else if (hasDirective) signal = 'DIRECTIVE';
696
+ else if (hasResults) signal = 'RESULT';
697
+ else if (hasAck) signal = 'ACK';
698
+
699
+ const parts = [];
700
+ if (signal) parts.push(signal);
701
+ if (focusMatch) parts.push(`focus=${focusMatch[1].trim()}`);
702
+ else if (bracketMatch) parts.push(bracketMatch[1].trim());
703
+ else if (lines[0]) parts.push(lines[0].slice(0, 100));
704
+
705
+ const approxTokens = Math.round(content.length / 4);
706
+ return parts.join(' | ') + ` (~${approxTokens}tok)`;
707
+ }
708
+
709
+ // ── Peer Allowlist (optional, defense-in-depth) ─────────────
710
+ // SYM_ALLOWED_PEERS is a comma-separated list of peer node names.
711
+ // When set, only CMBs and messages from listed peers are pushed to
712
+ // Claude's context. When empty/unset, all authenticated peers are
713
+ // accepted (SVAF still gates on content relevance).
714
+ const ALLOWED_PEERS = (process.env.SYM_ALLOWED_PEERS || '')
715
+ .split(',')
716
+ .map(s => s.trim())
717
+ .filter(Boolean);
718
+
719
+ function isPeerAllowed(peerName) {
720
+ if (ALLOWED_PEERS.length === 0) return true; // no allowlist = accept all
721
+ return ALLOWED_PEERS.includes(peerName);
722
+ }
723
+
724
+ // ── Mesh Events → Channel Notifications ──────────────────────
725
+
726
+ function pushChannel(eventType, data) {
727
+ try {
728
+ mcp.notification({
729
+ method: 'notifications/claude/channel',
730
+ params: {
731
+ content: typeof data === 'string' ? data : JSON.stringify(data),
732
+ meta: { event_type: eventType, source: 'sym-mesh' },
733
+ },
734
+ });
735
+ } catch {}
736
+ }
737
+
738
+ // All node.on(...) handlers live in registerNodeHandlers(n) above so the
739
+ // hot-swap path in sym_join_group can attach them to a freshly-constructed
740
+ // SymNode without duplicating logic. This call wires up the initial node.
741
+ registerNodeHandlers(node);
742
+
743
+ // Peer presence events are intentionally NOT pushed to Claude's context.
744
+ // They're high-frequency, low-signal (peers flap on relay reconnects, daemon
745
+ // restarts, NAT keepalive blips), and a flood will eat the context window.
746
+ // Use sym_peers / sym_status on demand instead. Only CMBs and direct messages
747
+ // are surfaced as channel notifications — those carry actual cognitive payload.
748
+
749
+ // ── Start ────────────────────────────────────────────────────
750
+
751
+ // Clean shutdown — disconnect from the relay before exiting so other peers
752
+ // see us leave immediately, and so a fast restart of this MCP doesn't race
753
+ // our own zombie connection on the relay (which would trigger the relay's
754
+ // duplicate-nodeId replacement path and cause peer flap loops).
755
+ //
756
+ // Idempotent: Claude Code may send SIGTERM and then SIGKILL; we want the
757
+ // first signal to get us cleanly off the relay even if the second one
758
+ // arrives before stop() resolves.
759
+ let shuttingDown = false;
760
+ async function shutdown(signal) {
761
+ if (shuttingDown) return;
762
+ shuttingDown = true;
763
+ try {
764
+ await node.stop();
765
+ } catch {
766
+ // Best effort — we're exiting anyway. Don't block on cleanup errors.
767
+ }
768
+ process.exit(0);
769
+ }
770
+
771
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
772
+ process.on('SIGINT', () => shutdown('SIGINT'));
773
+ process.on('SIGHUP', () => shutdown('SIGHUP'));
774
+
775
+ async function main() {
776
+ // Start SymNode — connects to relay as a peer
777
+ await node.start();
778
+
779
+ // Start MCP server — communicates with Claude Code via stdio
780
+ const transport = new StdioServerTransport();
781
+ await mcp.connect(transport);
782
+ }
783
+
784
+ main().catch((err) => {
785
+ process.stderr.write(`sym-mesh-channel failed: ${err.message}\n`);
786
+ process.exit(1);
787
+ });