@sym-bot/mesh-channel 0.3.4 → 0.3.5
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/.claude-plugin/marketplace.json +40 -40
- package/.claude-plugin/plugin.json +39 -39
- package/.mcp.json +14 -14
- package/CHANGELOG.md +574 -546
- package/LICENSE +201 -201
- package/README.md +361 -361
- package/SECURITY.md +89 -89
- package/bin/install.js +603 -603
- package/package.json +49 -49
- package/server.js +916 -886
package/server.js
CHANGED
|
@@ -1,886 +1,916 @@
|
|
|
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. 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, // viewpoint — low 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
|
-
const moodSuffix = mood && mood !== 'neutral' ? ` (mood: ${mood})` : '';
|
|
244
|
-
// Store the rendered CMB body so the agent can sym_fetch it by [mNNN] ID
|
|
245
|
-
//
|
|
246
|
-
//
|
|
247
|
-
//
|
|
248
|
-
//
|
|
249
|
-
const
|
|
250
|
-
const
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
//
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
},
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
const
|
|
522
|
-
if (
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
return { content: [{ type: 'text', text:
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
case '
|
|
535
|
-
const
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
const
|
|
545
|
-
if (
|
|
546
|
-
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
}
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
const
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
const
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
};
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
const
|
|
812
|
-
.
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
}
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
//
|
|
837
|
-
//
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
//
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
//
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
} catch {
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
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. 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, // viewpoint — low 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
|
+
const moodSuffix = mood && mood !== 'neutral' ? ` (mood: ${mood})` : '';
|
|
244
|
+
// Store the rendered CMB body so the agent can sym_fetch it by [mNNN] ID.
|
|
245
|
+
// When the CMB carries an opaque payload alongside CAT7 fields, append a
|
|
246
|
+
// PAYLOAD section to the stored body so sym_fetch returns it intact;
|
|
247
|
+
// header gains a [+payload Nb] indicator so the receiver knows there's
|
|
248
|
+
// structured data beyond CAT7 and should sym_fetch to consume it.
|
|
249
|
+
const payload = entry.cmb?.payload;
|
|
250
|
+
const hasPayload = payload !== undefined && payload !== null;
|
|
251
|
+
let body = entry.content || focus;
|
|
252
|
+
let payloadSuffix = '';
|
|
253
|
+
if (hasPayload) {
|
|
254
|
+
const serialized = (() => {
|
|
255
|
+
try { return JSON.stringify(payload, null, 2); }
|
|
256
|
+
catch { return String(payload); }
|
|
257
|
+
})();
|
|
258
|
+
body = `${body}\n\n---PAYLOAD---\n${serialized}`;
|
|
259
|
+
payloadSuffix = ` [+payload ${serialized.length}b]`;
|
|
260
|
+
}
|
|
261
|
+
const msgId = storeMessage(source, body);
|
|
262
|
+
pushChannel('cmb', `[${source}] ${focus}${moodSuffix}${payloadSuffix} [${msgId}]`);
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
n.on('message', (from, content) => {
|
|
266
|
+
if (!isPeerAllowed(from)) return;
|
|
267
|
+
const msgId = storeMessage(from, content);
|
|
268
|
+
const header = extractCompactHeader(from, content);
|
|
269
|
+
pushChannel('message', `[${from}] ${header} [${msgId}]`);
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// ── MCP Server ───────────────────────────────────────────────
|
|
274
|
+
|
|
275
|
+
// Base instructions shown to the agent at every MCP initialize.
|
|
276
|
+
const BASE_INSTRUCTIONS =
|
|
277
|
+
`You are a peer node on the SYM mesh (identity: ${NODE_NAME}). ` +
|
|
278
|
+
'Mesh events arrive as <channel> notifications in real-time. ' +
|
|
279
|
+
'When you see a CMB from another node, respond via sym_send targeted at that node by name if the reply is for that specific peer (MMP §4.4.4 targeted CMB). ' +
|
|
280
|
+
'Share observations about your own state with the whole mesh via sym_observe (MMP §9.2 receiver-autonomous SVAF evaluation). ' +
|
|
281
|
+
'Both sym_send and sym_observe emit CAT7 CMBs; receivers run SVAF and, if admitted, remix-store with lineage pointing back to your CMB. ' +
|
|
282
|
+
'Search mesh memory via sym_recall. ' +
|
|
283
|
+
'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.';
|
|
284
|
+
|
|
285
|
+
// Final startup step (MMP §4.2 O2 — rejoin-without-replay). The SymNode
|
|
286
|
+
// constructor builds the memory-store index from disk, so the primer is
|
|
287
|
+
// available synchronously without needing node.start(). Appending it to
|
|
288
|
+
// the MCP instructions payload means a fresh Claude Code session wakes
|
|
289
|
+
// with prior remix memory — own observations plus peer observations
|
|
290
|
+
// admitted by SVAF — already loaded into context, zero first-turn
|
|
291
|
+
// sym_recall overhead.
|
|
292
|
+
//
|
|
293
|
+
// MCP SDK reads `instructions` at Server construction time (storing it in
|
|
294
|
+
// a private field) and emits it only on initialize-response; mutations on
|
|
295
|
+
// the public property after construction are ignored. Compute once, pass in.
|
|
296
|
+
let primerText = '';
|
|
297
|
+
try {
|
|
298
|
+
const primer = node.buildStartupPrimer();
|
|
299
|
+
if (primer && primer.count > 0) primerText = `\n\n${primer.text}`;
|
|
300
|
+
} catch (err) {
|
|
301
|
+
process.stderr.write(`sym-mesh-channel startup primer skipped: ${err?.message || err}\n`);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const mcp = new Server(
|
|
305
|
+
{ name: 'sym-mesh', version: '0.1.0' },
|
|
306
|
+
{
|
|
307
|
+
capabilities: {
|
|
308
|
+
tools: {},
|
|
309
|
+
experimental: { 'claude/channel': {} },
|
|
310
|
+
},
|
|
311
|
+
instructions: BASE_INSTRUCTIONS + primerText,
|
|
312
|
+
},
|
|
313
|
+
);
|
|
314
|
+
|
|
315
|
+
// ── Tools ────────────────────────────────────────────────────
|
|
316
|
+
|
|
317
|
+
mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
318
|
+
tools: [
|
|
319
|
+
{
|
|
320
|
+
name: 'sym_send',
|
|
321
|
+
description:
|
|
322
|
+
'Send a structured CAT7 CMB to a specific mesh peer (targeted) or to all peers (broadcast, when "to" is omitted). ' +
|
|
323
|
+
'Receivers evaluate the CMB per-field via SVAF (MMP §9.2) and, if admitted, remix-store it with lineage pointing back to this CMB. ' +
|
|
324
|
+
'Use sym_send when the CMB is for a specific peer (e.g. a peer-review gating request directed at the reviewer role); ' +
|
|
325
|
+
'use sym_observe when sharing your own state with the whole mesh.',
|
|
326
|
+
inputSchema: {
|
|
327
|
+
type: 'object',
|
|
328
|
+
properties: {
|
|
329
|
+
focus: { type: 'string', description: 'The task anchor / what this CMB is about. Required.' },
|
|
330
|
+
issue: { type: 'string' },
|
|
331
|
+
intent: { type: 'string' },
|
|
332
|
+
motivation: { type: 'string' },
|
|
333
|
+
commitment: { type: 'string' },
|
|
334
|
+
perspective: { type: 'string' },
|
|
335
|
+
mood: {
|
|
336
|
+
type: 'object',
|
|
337
|
+
properties: {
|
|
338
|
+
text: { type: 'string' },
|
|
339
|
+
valence: { type: 'number' },
|
|
340
|
+
arousal: { type: 'number' },
|
|
341
|
+
},
|
|
342
|
+
},
|
|
343
|
+
to: {
|
|
344
|
+
type: 'string',
|
|
345
|
+
description:
|
|
346
|
+
'Target peer: either the peer display name (e.g. "claude-research-win") or the full nodeId. ' +
|
|
347
|
+
'Call sym_peers first if unsure which peers are connected. Omit to broadcast to all peers.',
|
|
348
|
+
},
|
|
349
|
+
payload: {
|
|
350
|
+
description:
|
|
351
|
+
'Optional opaque payload riding alongside CAT7 fields. Use when carrying data beyond ' +
|
|
352
|
+
'CAT7 — e.g. an LLM request/response substrate protocol puts the prompt + request_id ' +
|
|
353
|
+
'in `payload` rather than smuggling JSON through `motivation` (which is reserved for ' +
|
|
354
|
+
'CAT7 semantics). Receivers see the payload via sym_fetch on the channel notification. ' +
|
|
355
|
+
'Any JSON-serializable value.',
|
|
356
|
+
},
|
|
357
|
+
},
|
|
358
|
+
required: ['focus'],
|
|
359
|
+
},
|
|
360
|
+
},
|
|
361
|
+
{
|
|
362
|
+
name: 'sym_observe',
|
|
363
|
+
description:
|
|
364
|
+
'Broadcast a structured CAT7 observation about your own state to all mesh peers. ' +
|
|
365
|
+
'Receivers run SVAF (MMP §9.2) and admitted CMBs are remix-stored with lineage. ' +
|
|
366
|
+
'Equivalent to sym_send with "to" omitted — kept as a separate tool because self-observation is the common case and does not need peer selection.',
|
|
367
|
+
inputSchema: {
|
|
368
|
+
type: 'object',
|
|
369
|
+
properties: {
|
|
370
|
+
focus: { type: 'string' },
|
|
371
|
+
issue: { type: 'string' },
|
|
372
|
+
intent: { type: 'string' },
|
|
373
|
+
motivation: { type: 'string' },
|
|
374
|
+
commitment: { type: 'string' },
|
|
375
|
+
perspective: { type: 'string' },
|
|
376
|
+
mood: {
|
|
377
|
+
type: 'object',
|
|
378
|
+
properties: {
|
|
379
|
+
text: { type: 'string' },
|
|
380
|
+
valence: { type: 'number' },
|
|
381
|
+
arousal: { type: 'number' },
|
|
382
|
+
},
|
|
383
|
+
},
|
|
384
|
+
payload: {
|
|
385
|
+
description:
|
|
386
|
+
'Optional opaque payload riding alongside CAT7 fields. Use when broadcasting data ' +
|
|
387
|
+
'beyond CAT7 (e.g. llm-capability-advertise carrying served_capabilities). ' +
|
|
388
|
+
'Any JSON-serializable value.',
|
|
389
|
+
},
|
|
390
|
+
},
|
|
391
|
+
required: ['focus'],
|
|
392
|
+
},
|
|
393
|
+
},
|
|
394
|
+
{
|
|
395
|
+
name: 'sym_recall',
|
|
396
|
+
description: 'Search mesh memory for relevant CMBs.',
|
|
397
|
+
inputSchema: {
|
|
398
|
+
type: 'object',
|
|
399
|
+
properties: { query: { type: 'string', description: 'Search query (empty for all)' } },
|
|
400
|
+
required: ['query'],
|
|
401
|
+
},
|
|
402
|
+
},
|
|
403
|
+
{
|
|
404
|
+
name: 'sym_peers',
|
|
405
|
+
description: 'List connected mesh peers.',
|
|
406
|
+
inputSchema: { type: 'object', properties: {} },
|
|
407
|
+
},
|
|
408
|
+
{
|
|
409
|
+
name: 'sym_status',
|
|
410
|
+
description: 'Get mesh node status — relay connection, peer count, memory count.',
|
|
411
|
+
inputSchema: { type: 'object', properties: {} },
|
|
412
|
+
},
|
|
413
|
+
{
|
|
414
|
+
name: 'sym_fetch',
|
|
415
|
+
description: 'Fetch full content of a mesh message by ID. Use when a compact channel notification needs deeper reading.',
|
|
416
|
+
inputSchema: {
|
|
417
|
+
type: 'object',
|
|
418
|
+
properties: { msg_id: { type: 'string', description: 'Message ID (e.g., m007)' } },
|
|
419
|
+
required: ['msg_id'],
|
|
420
|
+
},
|
|
421
|
+
},
|
|
422
|
+
{
|
|
423
|
+
name: 'sym_group_info',
|
|
424
|
+
description: 'Report the mesh group this node is in (MMP §5.8). Shows service type + group name + peer count.',
|
|
425
|
+
inputSchema: { type: 'object', properties: {} },
|
|
426
|
+
},
|
|
427
|
+
{
|
|
428
|
+
name: 'sym_invite_create',
|
|
429
|
+
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.',
|
|
430
|
+
inputSchema: {
|
|
431
|
+
type: 'object',
|
|
432
|
+
properties: {
|
|
433
|
+
group: { type: 'string', description: 'Kebab-case group name, e.g. "backend-team".' },
|
|
434
|
+
relay_url: { type: 'string', description: 'Optional WebSocket relay URL, e.g. wss://sym-relay.onrender.com. Include for cross-network teams.' },
|
|
435
|
+
relay_token: { type: 'string', description: 'Optional relay authentication token (shared secret for this team channel).' },
|
|
436
|
+
},
|
|
437
|
+
required: ['group'],
|
|
438
|
+
},
|
|
439
|
+
},
|
|
440
|
+
{
|
|
441
|
+
name: 'sym_invite_info',
|
|
442
|
+
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}).',
|
|
443
|
+
inputSchema: {
|
|
444
|
+
type: 'object',
|
|
445
|
+
properties: { url: { type: 'string', description: 'Invite URL, e.g. sym://group/backend-team' } },
|
|
446
|
+
required: ['url'],
|
|
447
|
+
},
|
|
448
|
+
},
|
|
449
|
+
{
|
|
450
|
+
name: 'sym_join_group',
|
|
451
|
+
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.',
|
|
452
|
+
inputSchema: {
|
|
453
|
+
type: 'object',
|
|
454
|
+
properties: {
|
|
455
|
+
group: { type: 'string', description: 'Kebab-case group name, e.g. "backend-team". Pass "default" to return to the global mesh.' },
|
|
456
|
+
relay_url: { type: 'string', description: 'Optional WebSocket relay URL for cross-network teams. Leave empty for LAN-only.' },
|
|
457
|
+
relay_token: { type: 'string', description: 'Optional relay authentication token.' },
|
|
458
|
+
},
|
|
459
|
+
required: ['group'],
|
|
460
|
+
},
|
|
461
|
+
},
|
|
462
|
+
{
|
|
463
|
+
name: 'sym_groups_discover',
|
|
464
|
+
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.',
|
|
465
|
+
inputSchema: { type: 'object', properties: {} },
|
|
466
|
+
},
|
|
467
|
+
],
|
|
468
|
+
}));
|
|
469
|
+
|
|
470
|
+
mcp.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
471
|
+
const { name, arguments: args } = request.params;
|
|
472
|
+
|
|
473
|
+
switch (name) {
|
|
474
|
+
case 'sym_send': {
|
|
475
|
+
// Emit a structured CAT7 CMB per MMP §4.2. When args.to names a peer,
|
|
476
|
+
// route as a targeted send (§4.4.4); otherwise broadcast. Receivers
|
|
477
|
+
// run SVAF (§9.2) and remix-store on accept — no separate "message"
|
|
478
|
+
// frame path, no raw-text channel.
|
|
479
|
+
const fields = {
|
|
480
|
+
focus: args.focus || 'directive',
|
|
481
|
+
issue: args.issue || 'none',
|
|
482
|
+
intent: args.intent || 'directive',
|
|
483
|
+
motivation: args.motivation || '',
|
|
484
|
+
commitment: args.commitment || '',
|
|
485
|
+
perspective: args.perspective || NODE_NAME,
|
|
486
|
+
mood: args.mood || { text: 'neutral', valence: 0, arousal: 0 },
|
|
487
|
+
};
|
|
488
|
+
|
|
489
|
+
let targetPeerId = null;
|
|
490
|
+
if (args.to) {
|
|
491
|
+
const peers = node.peers();
|
|
492
|
+
// Exact full-nodeId match first (unambiguous).
|
|
493
|
+
const byNodeId = peers.filter(p => p.peerId === args.to);
|
|
494
|
+
// Name match second.
|
|
495
|
+
const byName = peers.filter(p => p.name === args.to);
|
|
496
|
+
// Short-id prefix match last (for human-typed 8-char prefixes).
|
|
497
|
+
const byPrefix = peers.filter(p => p.id === args.to);
|
|
498
|
+
|
|
499
|
+
let matches;
|
|
500
|
+
if (byNodeId.length > 0) matches = byNodeId;
|
|
501
|
+
else if (byName.length > 0) matches = byName;
|
|
502
|
+
else if (byPrefix.length > 0) matches = byPrefix;
|
|
503
|
+
else matches = [];
|
|
504
|
+
|
|
505
|
+
if (matches.length === 0) {
|
|
506
|
+
return {
|
|
507
|
+
content: [{ type: 'text', text: `Peer "${args.to}" not connected. Call sym_peers to see connected peers.` }],
|
|
508
|
+
isError: true,
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
if (matches.length > 1) {
|
|
512
|
+
const names = matches.map(p => `${p.name} (${p.peerId})`).join(', ');
|
|
513
|
+
return {
|
|
514
|
+
content: [{ type: 'text', text: `Peer "${args.to}" is ambiguous — matches: ${names}. Pass the full nodeId.` }],
|
|
515
|
+
isError: true,
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
targetPeerId = matches[0].peerId;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
const sendOpts = {};
|
|
522
|
+
if (targetPeerId) sendOpts.to = targetPeerId;
|
|
523
|
+
if (args.payload !== undefined && args.payload !== null) sendOpts.payload = args.payload;
|
|
524
|
+
const entry = node.remember(fields, sendOpts);
|
|
525
|
+
if (!entry) {
|
|
526
|
+
return { content: [{ type: 'text', text: 'Duplicate — CMB already in memory, not re-broadcast.' }] };
|
|
527
|
+
}
|
|
528
|
+
const summary = targetPeerId
|
|
529
|
+
? `Sent CMB ${entry.key} to ${args.to}`
|
|
530
|
+
: `Broadcast CMB ${entry.key} to all peers`;
|
|
531
|
+
return { content: [{ type: 'text', text: summary }] };
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
case 'sym_observe': {
|
|
535
|
+
const fields = {
|
|
536
|
+
focus: args.focus || 'observation',
|
|
537
|
+
issue: args.issue || 'none',
|
|
538
|
+
intent: args.intent || 'observation',
|
|
539
|
+
motivation: args.motivation || '',
|
|
540
|
+
commitment: args.commitment || '',
|
|
541
|
+
perspective: args.perspective || NODE_NAME,
|
|
542
|
+
mood: args.mood || { text: 'neutral', valence: 0, arousal: 0 },
|
|
543
|
+
};
|
|
544
|
+
const observeOpts = {};
|
|
545
|
+
if (args.payload !== undefined && args.payload !== null) observeOpts.payload = args.payload;
|
|
546
|
+
const entry = node.remember(fields, observeOpts);
|
|
547
|
+
return { content: [{ type: 'text', text: entry ? `Observed: ${entry.key}` : 'Duplicate — already in memory.' }] };
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
case 'sym_recall': {
|
|
551
|
+
const results = node.recall(args.query || '');
|
|
552
|
+
if (results.length === 0) {
|
|
553
|
+
return { content: [{ type: 'text', text: 'No memories found.' }] };
|
|
554
|
+
}
|
|
555
|
+
const lines = results.slice(0, 10).map(r => {
|
|
556
|
+
const focus = r.cmb?.fields?.focus?.text || r.content || '';
|
|
557
|
+
const source = r.source || r.cmb?.createdBy || 'unknown';
|
|
558
|
+
const time = r.timestamp ? new Date(r.timestamp).toLocaleString() : '';
|
|
559
|
+
return `[${source}] ${time}\n ${focus.slice(0, 150)}`;
|
|
560
|
+
});
|
|
561
|
+
return { content: [{ type: 'text', text: lines.join('\n\n') }] };
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
case 'sym_peers': {
|
|
565
|
+
const peers = node.peers();
|
|
566
|
+
if (peers.length === 0) {
|
|
567
|
+
return { content: [{ type: 'text', text: 'No peers connected.' }] };
|
|
568
|
+
}
|
|
569
|
+
const lines = peers.map(p => `${p.name} via ${p.source || 'unknown'}`);
|
|
570
|
+
return { content: [{ type: 'text', text: `${peers.length} peer(s):\n${lines.join('\n')}` }] };
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
case 'sym_fetch': {
|
|
574
|
+
const entry = MESSAGE_STORE.get(args.msg_id);
|
|
575
|
+
if (!entry) {
|
|
576
|
+
return { content: [{ type: 'text', text: `Message ${args.msg_id} not found (expired or invalid ID).` }] };
|
|
577
|
+
}
|
|
578
|
+
return {
|
|
579
|
+
content: [{
|
|
580
|
+
type: 'text',
|
|
581
|
+
text: `[${entry.from}] ${new Date(entry.timestamp).toISOString()}\n\n${entry.content}`,
|
|
582
|
+
}],
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
case 'sym_status': {
|
|
587
|
+
const s = node.status();
|
|
588
|
+
return {
|
|
589
|
+
content: [{
|
|
590
|
+
type: 'text',
|
|
591
|
+
text: `Node: ${NODE_NAME} (${node.nodeId?.slice(0, 8) || '?'})\n` +
|
|
592
|
+
`Group: ${GROUP} (${SERVICE_TYPE})\n` +
|
|
593
|
+
`Relay: ${s.relayConnected ? 'connected' : 'disconnected'}\n` +
|
|
594
|
+
`Peers: ${s.peerCount || 0}\n` +
|
|
595
|
+
`Memories: ${s.memoryCount || 0}`,
|
|
596
|
+
}],
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
case 'sym_group_info': {
|
|
601
|
+
const s = node.status();
|
|
602
|
+
const peers = typeof node.getPeers === 'function' ? node.getPeers() : [];
|
|
603
|
+
const peerLines = peers.length
|
|
604
|
+
? peers.map(p => ` ${p.name} (${(p.peerId || '').slice(0, 8)}) via ${p.transport || '?'}`).join('\n')
|
|
605
|
+
: ' (no peers in this group)';
|
|
606
|
+
return {
|
|
607
|
+
content: [{
|
|
608
|
+
type: 'text',
|
|
609
|
+
text: `Mesh group (MMP §5.8):\n` +
|
|
610
|
+
` group: ${GROUP}\n` +
|
|
611
|
+
` service type: ${SERVICE_TYPE}\n` +
|
|
612
|
+
` node: ${NODE_NAME} (${node.nodeId?.slice(0, 8) || '?'})\n` +
|
|
613
|
+
` peers in group: ${s.peerCount || 0}\n` +
|
|
614
|
+
peerLines + `\n\n` +
|
|
615
|
+
`To join a different group, restart the sym-mesh-channel MCP server with env var SYM_GROUP=<name> or SYM_SERVICE_TYPE=<_foo._tcp>.`,
|
|
616
|
+
}],
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
case 'sym_invite_create': {
|
|
621
|
+
const group = args?.group;
|
|
622
|
+
const relayUrl = args?.relay_url;
|
|
623
|
+
const relayToken = args?.relay_token;
|
|
624
|
+
if (!group || typeof group !== 'string') {
|
|
625
|
+
return { content: [{ type: 'text', text: 'Missing required argument: group' }], isError: true };
|
|
626
|
+
}
|
|
627
|
+
if (!KEBAB_CASE_RE.test(group)) {
|
|
628
|
+
return {
|
|
629
|
+
content: [{
|
|
630
|
+
type: 'text',
|
|
631
|
+
text: `Invalid group name: "${group}". Must be kebab-case (lowercase alphanumerics + single hyphens), e.g. "backend-team".`,
|
|
632
|
+
}],
|
|
633
|
+
isError: true,
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
// LAN-only flavor: sym://group/{name}
|
|
637
|
+
// Cross-network flavor: sym://team/{name}?relay=...&token=...
|
|
638
|
+
let url;
|
|
639
|
+
let flavor;
|
|
640
|
+
if (relayUrl || relayToken) {
|
|
641
|
+
if (!relayUrl) return { content: [{ type: 'text', text: 'relay_token requires relay_url' }], isError: true };
|
|
642
|
+
const params = [`relay=${encodeURIComponent(relayUrl)}`];
|
|
643
|
+
if (relayToken) params.push(`token=${encodeURIComponent(relayToken)}`);
|
|
644
|
+
url = `sym://team/${group}?${params.join('&')}`;
|
|
645
|
+
flavor = 'cross-network (relay)';
|
|
646
|
+
} else {
|
|
647
|
+
url = `sym://group/${group}`;
|
|
648
|
+
flavor = 'LAN-only (Bonjour)';
|
|
649
|
+
}
|
|
650
|
+
const youRunning = GROUP === group
|
|
651
|
+
? `You're already on this group — teammates who join will see you.`
|
|
652
|
+
: `You are currently on group "${GROUP}". To be reachable, call sym_join_group with group="${group}" (+ same relay creds if cross-network) before sharing.`;
|
|
653
|
+
return {
|
|
654
|
+
content: [{
|
|
655
|
+
type: 'text',
|
|
656
|
+
text: `Invite URL (${flavor}):\n\n ${url}\n\n` +
|
|
657
|
+
`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` +
|
|
658
|
+
youRunning,
|
|
659
|
+
}],
|
|
660
|
+
};
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
case 'sym_invite_info': {
|
|
664
|
+
const url = args?.url;
|
|
665
|
+
if (!url || typeof url !== 'string') {
|
|
666
|
+
return { content: [{ type: 'text', text: 'Missing required argument: url' }], isError: true };
|
|
667
|
+
}
|
|
668
|
+
const parsed = parseInviteURL(url);
|
|
669
|
+
if (parsed.error) {
|
|
670
|
+
return { content: [{ type: 'text', text: parsed.error }], isError: true };
|
|
671
|
+
}
|
|
672
|
+
const { appScheme, group, serviceType, roomId, roomName, relayUrl, relayToken } = parsed;
|
|
673
|
+
|
|
674
|
+
const out = {
|
|
675
|
+
app: appScheme,
|
|
676
|
+
group,
|
|
677
|
+
service_type: serviceType,
|
|
678
|
+
room_id: appScheme === 'sym' ? undefined : roomId,
|
|
679
|
+
room_name: appScheme === 'sym' ? undefined : roomName,
|
|
680
|
+
relay_url: relayUrl || undefined,
|
|
681
|
+
relay_token: relayToken || undefined,
|
|
682
|
+
};
|
|
683
|
+
for (const k of Object.keys(out)) if (out[k] === undefined) delete out[k];
|
|
684
|
+
|
|
685
|
+
const joinCall = {
|
|
686
|
+
group,
|
|
687
|
+
...(relayUrl && { relay_url: relayUrl }),
|
|
688
|
+
...(relayToken && { relay_token: relayToken }),
|
|
689
|
+
};
|
|
690
|
+
|
|
691
|
+
return {
|
|
692
|
+
content: [{
|
|
693
|
+
type: 'text',
|
|
694
|
+
text: `Parsed invite: ${url}\n\n` +
|
|
695
|
+
JSON.stringify(out, null, 2) + `\n\n` +
|
|
696
|
+
`To join, call sym_join_group:\n\n ${JSON.stringify(joinCall)}\n\n` +
|
|
697
|
+
`This hot-swaps your node into the ${relayUrl ? 'relay channel' : 'LAN group'} — no Claude Code restart needed.`,
|
|
698
|
+
}],
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
case 'sym_join_group': {
|
|
703
|
+
const group = args?.group;
|
|
704
|
+
const relayUrl = args?.relay_url || null;
|
|
705
|
+
const relayToken = args?.relay_token || null;
|
|
706
|
+
if (!group || typeof group !== 'string') {
|
|
707
|
+
return { content: [{ type: 'text', text: 'Missing required argument: group' }], isError: true };
|
|
708
|
+
}
|
|
709
|
+
if (!KEBAB_CASE_RE.test(group) && group !== 'default') {
|
|
710
|
+
return {
|
|
711
|
+
content: [{ type: 'text', text: `Invalid group name: "${group}". Must be kebab-case or "default".` }],
|
|
712
|
+
isError: true,
|
|
713
|
+
};
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
const newServiceType = group === 'default' ? '_sym._tcp' : `_${group}._tcp`;
|
|
717
|
+
const prevGroup = GROUP;
|
|
718
|
+
const prevServiceType = SERVICE_TYPE;
|
|
719
|
+
|
|
720
|
+
// Stop the current node cleanly so peers see us leave, then construct
|
|
721
|
+
// a fresh one on the new service type. Any failure during restart is
|
|
722
|
+
// reported; the previous node will already be stopped, so the caller
|
|
723
|
+
// is in a known-disconnected state and can retry.
|
|
724
|
+
try {
|
|
725
|
+
await node.stop();
|
|
726
|
+
} catch (e) {
|
|
727
|
+
return {
|
|
728
|
+
content: [{ type: 'text', text: `Failed to stop current node: ${e?.message || e}` }],
|
|
729
|
+
isError: true,
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
const newNode = new SymNode({
|
|
734
|
+
name: NODE_NAME,
|
|
735
|
+
cognitiveProfile: 'Engineering node. Code, architecture, debugging, technical decisions.',
|
|
736
|
+
svafFieldWeights: FIELD_WEIGHTS,
|
|
737
|
+
svafFreshnessSeconds: 7200,
|
|
738
|
+
discoveryServiceType: newServiceType,
|
|
739
|
+
group,
|
|
740
|
+
relay: relayUrl,
|
|
741
|
+
relayToken,
|
|
742
|
+
silent: true,
|
|
743
|
+
});
|
|
744
|
+
registerNodeHandlers(newNode);
|
|
745
|
+
|
|
746
|
+
try {
|
|
747
|
+
await newNode.start();
|
|
748
|
+
} catch (e) {
|
|
749
|
+
return {
|
|
750
|
+
content: [{
|
|
751
|
+
type: 'text',
|
|
752
|
+
text: `Failed to start new node on group "${group}": ${e?.message || e}\n\n` +
|
|
753
|
+
`Previous node already stopped. To recover, call sym_join_group with group="${prevGroup}".`,
|
|
754
|
+
}],
|
|
755
|
+
isError: true,
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
// Swap module-level references only after successful start.
|
|
760
|
+
node = newNode;
|
|
761
|
+
GROUP = group;
|
|
762
|
+
SERVICE_TYPE = newServiceType;
|
|
763
|
+
RELAY_URL = relayUrl;
|
|
764
|
+
RELAY_TOKEN = relayToken;
|
|
765
|
+
|
|
766
|
+
return {
|
|
767
|
+
content: [{
|
|
768
|
+
type: 'text',
|
|
769
|
+
text: `Hot-swapped from group "${prevGroup}" (${prevServiceType}) to "${group}" (${newServiceType}).\n` +
|
|
770
|
+
(relayUrl ? `Relay: ${relayUrl}\n` : '') +
|
|
771
|
+
`Discovering peers on the new service type. Call sym_peers in a moment to see who's online.`,
|
|
772
|
+
}],
|
|
773
|
+
};
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
case 'sym_groups_discover': {
|
|
777
|
+
const result = await discoverGroups();
|
|
778
|
+
return {
|
|
779
|
+
content: [{
|
|
780
|
+
type: 'text',
|
|
781
|
+
text: result.text,
|
|
782
|
+
}],
|
|
783
|
+
isError: result.isError || false,
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
default:
|
|
788
|
+
return { content: [{ type: 'text', text: `Unknown tool: ${name}` }] };
|
|
789
|
+
}
|
|
790
|
+
});
|
|
791
|
+
|
|
792
|
+
// ── Compact Channel — message store for lazy-load (v0.1) ────
|
|
793
|
+
// Per COO spec cmb_compact_channel_v0.1.md: push compact headers,
|
|
794
|
+
// store full content for on-demand sym_fetch retrieval. ~10% token
|
|
795
|
+
// savings on mesh traffic without context loss.
|
|
796
|
+
const MESSAGE_STORE = new Map();
|
|
797
|
+
let msgSeq = 0;
|
|
798
|
+
const MAX_STORED = 200;
|
|
799
|
+
|
|
800
|
+
function storeMessage(from, content) {
|
|
801
|
+
const msgId = `m${String(++msgSeq).padStart(3, '0')}`;
|
|
802
|
+
MESSAGE_STORE.set(msgId, { from, content, timestamp: Date.now() });
|
|
803
|
+
while (MESSAGE_STORE.size > MAX_STORED) {
|
|
804
|
+
const oldest = MESSAGE_STORE.keys().next().value;
|
|
805
|
+
MESSAGE_STORE.delete(oldest);
|
|
806
|
+
}
|
|
807
|
+
return msgId;
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
function extractCompactHeader(from, content) {
|
|
811
|
+
const lines = content.split('\n').filter(l => l.trim());
|
|
812
|
+
const focusMatch = content.match(/focus[=:]\s*([^\n\]]{0,80})/i);
|
|
813
|
+
const bracketMatch = content.match(/\[([^\]]{0,120})\]/);
|
|
814
|
+
|
|
815
|
+
const hasHalt = /\bhalt\b/i.test(content);
|
|
816
|
+
const hasDirective = /\bdirective\b/i.test(content);
|
|
817
|
+
const hasResults = /\bresult|complete|landed|done\b/i.test(content);
|
|
818
|
+
const hasAck = /\back\b/i.test(content);
|
|
819
|
+
|
|
820
|
+
let signal = '';
|
|
821
|
+
if (hasHalt) signal = 'HALT';
|
|
822
|
+
else if (hasDirective) signal = 'DIRECTIVE';
|
|
823
|
+
else if (hasResults) signal = 'RESULT';
|
|
824
|
+
else if (hasAck) signal = 'ACK';
|
|
825
|
+
|
|
826
|
+
const parts = [];
|
|
827
|
+
if (signal) parts.push(signal);
|
|
828
|
+
if (focusMatch) parts.push(`focus=${focusMatch[1].trim()}`);
|
|
829
|
+
else if (bracketMatch) parts.push(bracketMatch[1].trim());
|
|
830
|
+
else if (lines[0]) parts.push(lines[0].slice(0, 100));
|
|
831
|
+
|
|
832
|
+
const approxTokens = Math.round(content.length / 4);
|
|
833
|
+
return parts.join(' | ') + ` (~${approxTokens}tok)`;
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
// ── Peer Allowlist (optional, defense-in-depth) ─────────────
|
|
837
|
+
// SYM_ALLOWED_PEERS is a comma-separated list of peer node names.
|
|
838
|
+
// When set, only CMBs and messages from listed peers are pushed to
|
|
839
|
+
// Claude's context. When empty/unset, all authenticated peers are
|
|
840
|
+
// accepted (SVAF still gates on content relevance).
|
|
841
|
+
const ALLOWED_PEERS = (process.env.SYM_ALLOWED_PEERS || '')
|
|
842
|
+
.split(',')
|
|
843
|
+
.map(s => s.trim())
|
|
844
|
+
.filter(Boolean);
|
|
845
|
+
|
|
846
|
+
function isPeerAllowed(peerName) {
|
|
847
|
+
if (ALLOWED_PEERS.length === 0) return true; // no allowlist = accept all
|
|
848
|
+
return ALLOWED_PEERS.includes(peerName);
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
// ── Mesh Events → Channel Notifications ──────────────────────
|
|
852
|
+
|
|
853
|
+
function pushChannel(eventType, data) {
|
|
854
|
+
try {
|
|
855
|
+
mcp.notification({
|
|
856
|
+
method: 'notifications/claude/channel',
|
|
857
|
+
params: {
|
|
858
|
+
content: typeof data === 'string' ? data : JSON.stringify(data),
|
|
859
|
+
meta: { event_type: eventType, source: 'sym-mesh' },
|
|
860
|
+
},
|
|
861
|
+
});
|
|
862
|
+
} catch {}
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
// All node.on(...) handlers live in registerNodeHandlers(n) above so the
|
|
866
|
+
// hot-swap path in sym_join_group can attach them to a freshly-constructed
|
|
867
|
+
// SymNode without duplicating logic. This call wires up the initial node.
|
|
868
|
+
registerNodeHandlers(node);
|
|
869
|
+
|
|
870
|
+
// Peer presence events are intentionally NOT pushed to Claude's context.
|
|
871
|
+
// They're high-frequency, low-signal (peers flap on relay reconnects, daemon
|
|
872
|
+
// restarts, NAT keepalive blips), and a flood will eat the context window.
|
|
873
|
+
// Use sym_peers / sym_status on demand instead. Only CMBs and direct messages
|
|
874
|
+
// are surfaced as channel notifications — those carry actual cognitive payload.
|
|
875
|
+
|
|
876
|
+
// ── Start ────────────────────────────────────────────────────
|
|
877
|
+
|
|
878
|
+
// Clean shutdown — disconnect from the relay before exiting so other peers
|
|
879
|
+
// see us leave immediately, and so a fast restart of this MCP doesn't race
|
|
880
|
+
// our own zombie connection on the relay (which would trigger the relay's
|
|
881
|
+
// duplicate-nodeId replacement path and cause peer flap loops).
|
|
882
|
+
//
|
|
883
|
+
// Idempotent: Claude Code may send SIGTERM and then SIGKILL; we want the
|
|
884
|
+
// first signal to get us cleanly off the relay even if the second one
|
|
885
|
+
// arrives before stop() resolves.
|
|
886
|
+
let shuttingDown = false;
|
|
887
|
+
async function shutdown(signal) {
|
|
888
|
+
if (shuttingDown) return;
|
|
889
|
+
shuttingDown = true;
|
|
890
|
+
try {
|
|
891
|
+
await node.stop();
|
|
892
|
+
} catch {
|
|
893
|
+
// Best effort — we're exiting anyway. Don't block on cleanup errors.
|
|
894
|
+
}
|
|
895
|
+
process.exit(0);
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
899
|
+
process.on('SIGINT', () => shutdown('SIGINT'));
|
|
900
|
+
process.on('SIGHUP', () => shutdown('SIGHUP'));
|
|
901
|
+
|
|
902
|
+
async function main() {
|
|
903
|
+
// Start SymNode — connects to relay as a peer. The startup primer is
|
|
904
|
+
// computed at module-load time (see BASE_INSTRUCTIONS above) and is
|
|
905
|
+
// already embedded in the MCP server's initialize-response payload.
|
|
906
|
+
await node.start();
|
|
907
|
+
|
|
908
|
+
// Start MCP server — communicates with Claude Code via stdio
|
|
909
|
+
const transport = new StdioServerTransport();
|
|
910
|
+
await mcp.connect(transport);
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
main().catch((err) => {
|
|
914
|
+
process.stderr.write(`sym-mesh-channel failed: ${err.message}\n`);
|
|
915
|
+
process.exit(1);
|
|
916
|
+
});
|