peer-bridge 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.ko.md +134 -0
  3. package/README.md +161 -2
  4. package/adapters/antigravity/bin/agy-hook.mjs +24 -0
  5. package/adapters/antigravity/hooks.json +23 -0
  6. package/adapters/antigravity/mcp_config.json +8 -0
  7. package/adapters/antigravity/plugin.json +4 -0
  8. package/adapters/antigravity/rules/AGENTS.md +6 -0
  9. package/adapters/antigravity/skills/peer-bridge/SKILL.md +19 -0
  10. package/adapters/claude/.claude-plugin/plugin.json +5 -0
  11. package/adapters/claude/.mcp.json +8 -0
  12. package/adapters/claude/bin/cc-hook.mjs +20 -0
  13. package/adapters/claude/hooks/hooks.json +46 -0
  14. package/adapters/claude/skills/peer-bridge/SKILL.md +18 -0
  15. package/adapters/codex/bin/codex-hook.mjs +10 -0
  16. package/adapters/codex/config.toml.example +5 -0
  17. package/adapters/codex/hooks.json +44 -0
  18. package/adapters/codex/skills/peer-bridge/SKILL.md +12 -0
  19. package/adapters/gemini/bin/gemini-hook.mjs +10 -0
  20. package/adapters/gemini/settings.json +51 -0
  21. package/adapters/gemini/skills/peer-bridge/SKILL.md +12 -0
  22. package/adapters/paseo/SKILL.md +24 -0
  23. package/bin/pbridge-mcp.mjs +37 -0
  24. package/bin/pbridge-tui.mjs +7 -0
  25. package/bin/pbridge.mjs +5 -0
  26. package/bin/pbridged.mjs +16 -0
  27. package/package.json +42 -4
  28. package/src/adapters/antigravity/hooks.mjs +207 -0
  29. package/src/adapters/claude/hooks.mjs +204 -0
  30. package/src/adapters/codex/hooks.mjs +142 -0
  31. package/src/adapters/gemini/hooks.mjs +159 -0
  32. package/src/adapters/installer.mjs +328 -0
  33. package/src/cli/main.mjs +729 -0
  34. package/src/client/rpc.mjs +243 -0
  35. package/src/config.mjs +154 -0
  36. package/src/daemon/broker.mjs +1799 -0
  37. package/src/daemon/resolver.mjs +200 -0
  38. package/src/daemon/server.mjs +221 -0
  39. package/src/index.mjs +53 -0
  40. package/src/mcp/server.mjs +668 -0
  41. package/src/orchestrator/workflows.mjs +496 -0
  42. package/src/project.mjs +81 -0
  43. package/src/protocol.mjs +203 -0
  44. package/src/runtime/conv-api.mjs +101 -0
  45. package/src/runtime/host-discovery.mjs +635 -0
  46. package/src/runtime/native-claude.mjs +88 -0
  47. package/src/runtime/paseo.mjs +289 -0
  48. package/src/runtime/workers.mjs +751 -0
  49. package/src/storage/db.mjs +704 -0
  50. package/src/tui/render.mjs +472 -0
  51. package/src/tui/viewer.mjs +443 -0
@@ -0,0 +1,668 @@
1
+ import readline from 'node:readline';
2
+ import {
3
+ callRpc,
4
+ isDaemonRunning,
5
+ startDaemonDetached,
6
+ subscribeChannel,
7
+ } from '../client/rpc.mjs';
8
+ import { getConfig } from '../config.mjs';
9
+
10
+ const SERVER_VERSION = '0.4.0';
11
+
12
+ const MCP_TOOLS = [
13
+ {
14
+ name: 'list_peers',
15
+ description:
16
+ 'List active AI peer sessions registered with peer-bridge (Claude Code, Antigravity, Codex, Gemini CLI, Paseo).',
17
+ inputSchema: {
18
+ type: 'object',
19
+ properties: {
20
+ runtime: {
21
+ type: 'string',
22
+ enum: ['all', 'cc', 'agy', 'codex', 'gemini', 'paseo'],
23
+ description: 'Filter by runtime ("all" returns every runtime).',
24
+ },
25
+ include_offline: {
26
+ type: 'boolean',
27
+ description: 'Include closed/detached/archived peers.',
28
+ },
29
+ include_native_claude: {
30
+ type: 'boolean',
31
+ description: 'Also scan native ~/.claude sessions and teams.',
32
+ },
33
+ },
34
+ },
35
+ },
36
+ {
37
+ name: 'send_peer_message',
38
+ description:
39
+ 'Send a prompt or reply to another AI peer session by name, short ID, or <runtime>:<name> handle.',
40
+ inputSchema: {
41
+ type: 'object',
42
+ properties: {
43
+ to: {
44
+ type: 'string',
45
+ description: 'Target peer handle, name, or ID prefix (e.g. "agy:ui-review", "backend").',
46
+ },
47
+ message: {
48
+ type: 'string',
49
+ description: 'Message content to deliver to the target peer.',
50
+ },
51
+ from: {
52
+ type: 'string',
53
+ description: 'Optional sender handle override.',
54
+ },
55
+ thread_id: {
56
+ type: 'string',
57
+ description: 'Existing thread ID to continue a conversation.',
58
+ },
59
+ reply_expected: {
60
+ type: 'boolean',
61
+ description: 'Set false for final notifications/acks to prevent ping-pong loops.',
62
+ },
63
+ max_hops: {
64
+ type: 'number',
65
+ description: 'Maximum hops allowed on this thread (default 6).',
66
+ },
67
+ wait_reply: {
68
+ type: 'boolean',
69
+ description: 'Wait for a synchronous response from managed headless workers.',
70
+ },
71
+ },
72
+ required: ['to', 'message'],
73
+ },
74
+ },
75
+ {
76
+ name: 'spawn_peer',
77
+ description:
78
+ 'Dynamically spawn a new Antigravity, Claude Code, Codex, Gemini CLI, or Paseo peer session.',
79
+ inputSchema: {
80
+ type: 'object',
81
+ properties: {
82
+ runtime: {
83
+ type: 'string',
84
+ enum: ['agy', 'cc', 'codex', 'gemini', 'paseo'],
85
+ description: 'Runtime to spawn.',
86
+ },
87
+ name: {
88
+ type: 'string',
89
+ description: 'Human-readable peer name (e.g. "e2e-verifier").',
90
+ },
91
+ cwd: {
92
+ type: 'string',
93
+ description: 'Working directory for the spawned session.',
94
+ },
95
+ model: {
96
+ type: 'string',
97
+ description: 'Model alias or full model ID.',
98
+ },
99
+ initial_prompt: {
100
+ type: 'string',
101
+ description: 'Optional initial prompt sent immediately after spawn.',
102
+ },
103
+ mode: {
104
+ type: 'string',
105
+ enum: ['headless', 'pane'],
106
+ description: 'Execution mode (default "headless").',
107
+ },
108
+ auto_close_on_finish: {
109
+ type: 'boolean',
110
+ description: 'Automatically close the worker after completing its task.',
111
+ },
112
+ },
113
+ required: ['runtime', 'name'],
114
+ },
115
+ },
116
+ {
117
+ name: 'close_peer',
118
+ description:
119
+ 'Close, archive, detach, or delete a peer session (ownership safety protects attached user sessions).',
120
+ inputSchema: {
121
+ type: 'object',
122
+ properties: {
123
+ target: {
124
+ type: 'string',
125
+ description: 'Target peer handle, name, or ID prefix.',
126
+ },
127
+ policy: {
128
+ type: 'string',
129
+ enum: ['graceful', 'archive', 'delete', 'detach'],
130
+ description: 'Close policy (default "archive" for spawned, "detach" for attached).',
131
+ },
132
+ force: {
133
+ type: 'boolean',
134
+ description: 'Override ownership protection for attached sessions.',
135
+ },
136
+ reason: {
137
+ type: 'string',
138
+ description: 'Optional closure reason.',
139
+ },
140
+ },
141
+ required: ['target'],
142
+ },
143
+ },
144
+ {
145
+ name: 'wait_peer_messages',
146
+ description:
147
+ 'Block until an incoming peer message arrives for the specified session or timeout expires.',
148
+ inputSchema: {
149
+ type: 'object',
150
+ properties: {
151
+ target: {
152
+ type: 'string',
153
+ description: 'Registered peer handle or name.',
154
+ },
155
+ session_id: {
156
+ type: 'string',
157
+ description: 'Session or conversation ID to wait on.',
158
+ },
159
+ timeout_ms: {
160
+ type: 'number',
161
+ description: 'Maximum wait time in milliseconds (default 30000).',
162
+ },
163
+ },
164
+ },
165
+ },
166
+ {
167
+ name: 'delegate_task',
168
+ description:
169
+ 'Delegate a structured Task Contract (request_id, expected_artifacts, notify_on_finish callback) to a peer session.',
170
+ inputSchema: {
171
+ type: 'object',
172
+ properties: {
173
+ to: { type: 'string', description: 'Target peer handle, name, or ID prefix.' },
174
+ prompt: { type: 'string', description: 'Detailed task instructions.' },
175
+ title: { type: 'string', description: 'Short task title.' },
176
+ request_id: { type: 'string', description: 'Optional caller-specified request ID.' },
177
+ expected_artifacts: {
178
+ type: 'array',
179
+ items: { type: 'string' },
180
+ description: 'Expected output file paths (relative to cwd or absolute).',
181
+ },
182
+ acceptance_criteria: {
183
+ type: 'array',
184
+ items: { type: 'string' },
185
+ description: 'Optional acceptance criteria checklist.',
186
+ },
187
+ require_artifacts: {
188
+ type: 'boolean',
189
+ description: 'Fail task automatically if expected_artifacts are missing on completion.',
190
+ },
191
+ notify_on_finish: {
192
+ type: 'boolean',
193
+ description: 'Send completion callback to callback_to when task finishes (default true).',
194
+ },
195
+ callback_to: {
196
+ type: 'string',
197
+ description: 'Peer handle to receive the completion callback (defaults to sender).',
198
+ },
199
+ cwd: { type: 'string', description: 'Base working directory for artifact verification.' },
200
+ wait: { type: 'boolean', description: 'Wait synchronously for task completion.' },
201
+ timeout_ms: { type: 'number', description: 'Timeout in milliseconds (default 180000).' },
202
+ },
203
+ required: ['to', 'prompt'],
204
+ },
205
+ },
206
+ {
207
+ name: 'complete_task',
208
+ description:
209
+ 'Mark a delegated Task Contract (request_id) completed, failed, or cancelled, verifying expected artifacts and firing notify_on_finish callback.',
210
+ inputSchema: {
211
+ type: 'object',
212
+ properties: {
213
+ request_id: { type: 'string', description: 'Task Contract request_id.' },
214
+ status: {
215
+ type: 'string',
216
+ enum: ['completed', 'failed', 'cancelled'],
217
+ description: 'Terminal status (default "completed").',
218
+ },
219
+ summary: { type: 'string', description: 'Summary of results produced.' },
220
+ error: { type: 'string', description: 'Error reason when status is "failed".' },
221
+ },
222
+ required: ['request_id'],
223
+ },
224
+ },
225
+ {
226
+ name: 'get_task_status',
227
+ description:
228
+ 'Retrieve one Task Contract by request_id or list tasks filtered by workflow_id/status.',
229
+ inputSchema: {
230
+ type: 'object',
231
+ properties: {
232
+ request_id: { type: 'string', description: 'Specific task request_id.' },
233
+ workflow_id: { type: 'string', description: 'Filter tasks belonging to a workflow.' },
234
+ status: { type: 'string', description: 'Filter by task status.' },
235
+ limit: { type: 'number', description: 'Maximum rows when listing.' },
236
+ },
237
+ },
238
+ },
239
+ {
240
+ name: 'run_workflow',
241
+ description:
242
+ 'Execute or inspect a multi-AI collaboration workflow template ("cross-review" or "fanout-join").',
243
+ inputSchema: {
244
+ type: 'object',
245
+ properties: {
246
+ action: {
247
+ type: 'string',
248
+ enum: ['run', 'status', 'list', 'wait'],
249
+ description: 'Workflow operation (default "run").',
250
+ },
251
+ workflow_id: { type: 'string', description: 'Workflow ID for status/wait.' },
252
+ template: {
253
+ type: 'string',
254
+ enum: ['cross-review', 'fanout-join'],
255
+ description: 'Collaboration workflow template.',
256
+ },
257
+ name: { type: 'string', description: 'Optional human-readable workflow name.' },
258
+ author: { description: 'Author peer handle or { spawn: {...} } (cross-review).' },
259
+ reviewer: { description: 'Reviewer peer handle or { spawn: {...} } (cross-review).' },
260
+ prompt: { type: 'string', description: 'Primary task prompt (cross-review).' },
261
+ max_rounds: { type: 'number', description: 'Maximum review rounds (default 2, max 5).' },
262
+ expected_artifacts: { type: 'array', items: { type: 'string' } },
263
+ require_artifacts: { type: 'boolean' },
264
+ tasks: {
265
+ type: 'array',
266
+ description: 'Parallel branch specs for fanout-join.',
267
+ },
268
+ join_to: { description: 'Optional synthesis peer handle for fanout-join.' },
269
+ join_spawn: { type: 'object', description: 'Optional spawn spec for join synthesizer.' },
270
+ join_prompt: { type: 'string', description: 'Custom synthesis prompt.' },
271
+ coordinator: { type: 'string', description: 'Peer handle to notify on workflow completion.' },
272
+ notify_on_finish: { type: 'boolean' },
273
+ auto_close: { type: 'boolean' },
274
+ async: { type: 'boolean', description: 'Run asynchronously in background.' },
275
+ cwd: { type: 'string' },
276
+ timeout_ms: { type: 'number' },
277
+ },
278
+ },
279
+ },
280
+ ];
281
+
282
+ function escapeXmlAttr(value) {
283
+ return String(value ?? '')
284
+ .replace(/&/g, '&amp;')
285
+ .replace(/"/g, '&quot;')
286
+ .replace(/</g, '&lt;')
287
+ .replace(/>/g, '&gt;');
288
+ }
289
+
290
+ export function startMcpServer(options = {}) {
291
+ const runtime = options.runtime || 'agy';
292
+ const enableChannel = Boolean(options.enableChannel);
293
+ const peerName = options.peerName || null;
294
+ const sessionId = options.sessionId || null;
295
+ const cwd = options.cwd || process.cwd();
296
+ const autoStartDaemon =
297
+ options.autoStartDaemon !== undefined
298
+ ? Boolean(options.autoStartDaemon)
299
+ : process.env.PBRIDGE_AUTO_START !== '0';
300
+ const config = getConfig(options.config || {});
301
+ const inputStream = options.input || process.stdin;
302
+ const outputStream = options.output || process.stdout;
303
+
304
+ let registeredPeer = null;
305
+ let channelSub = null;
306
+ let closed = false;
307
+
308
+ const sendJsonRpc = (obj) => {
309
+ if (closed || outputStream.destroyed) return;
310
+ outputStream.write(`${JSON.stringify(obj)}\n`);
311
+ };
312
+
313
+ const ensureDaemon = async () => {
314
+ if (await isDaemonRunning({ config })) return;
315
+ if (autoStartDaemon) {
316
+ await startDaemonDetached({ config });
317
+ }
318
+ };
319
+
320
+ const setupChannelIfEnabled = async () => {
321
+ if (!enableChannel || channelSub || closed) return;
322
+ await ensureDaemon();
323
+ const resolvedSessionId =
324
+ sessionId || process.env.CLAUDE_SESSION_ID || `cc-mcp-${process.ppid}`;
325
+ const resolvedName =
326
+ peerName ||
327
+ process.env.PBRIDGE_PEER_NAME ||
328
+ (sessionId ? `cc-${String(sessionId).slice(0, 8)}` : `cc-${process.ppid}`);
329
+
330
+ const reg = await callRpc(
331
+ 'peer.register',
332
+ {
333
+ runtime: 'cc',
334
+ name: resolvedName,
335
+ session_id: resolvedSessionId,
336
+ origin: 'attached',
337
+ exec_mode: 'interactive',
338
+ state: 'idle',
339
+ cwd,
340
+ pid: process.ppid,
341
+ },
342
+ { config },
343
+ );
344
+ registeredPeer = reg.peer;
345
+
346
+ const sub = subscribeChannel(
347
+ { peer_id: registeredPeer.peer_id },
348
+ (ev) => {
349
+ if (!ev) return;
350
+ if (ev.event === 'message') {
351
+ const from = ev.envelope?.from
352
+ ? `${ev.envelope.from.runtime}:${ev.envelope.from.name}`
353
+ : 'peer';
354
+ sendJsonRpc({
355
+ jsonrpc: '2.0',
356
+ method: 'notifications/claude/channel',
357
+ params: {
358
+ content: ev.formatted_xml || ev.envelope?.body || '',
359
+ meta: {
360
+ source: 'peer-bridge',
361
+ msg_id: ev.envelope?.msg_id || '',
362
+ thread_id: ev.envelope?.thread_id || '',
363
+ from,
364
+ },
365
+ },
366
+ });
367
+ } else if (ev.event === 'system') {
368
+ const action = ev.system?.action || 'notice';
369
+ const reason = ev.system?.reason || '';
370
+ sendJsonRpc({
371
+ jsonrpc: '2.0',
372
+ method: 'notifications/claude/channel',
373
+ params: {
374
+ content: `<peer-system action="${escapeXmlAttr(action)}">${reason}</peer-system>`,
375
+ meta: {
376
+ source: 'peer-bridge',
377
+ kind: 'system',
378
+ action,
379
+ },
380
+ },
381
+ });
382
+ }
383
+ },
384
+ { config },
385
+ );
386
+ channelSub = sub;
387
+ await sub.ready;
388
+ };
389
+
390
+ const handleToolCall = async (name, args = {}) => {
391
+ await ensureDaemon();
392
+ const defaultFrom =
393
+ registeredPeer?.handle ||
394
+ (sessionId ? `${runtime}:${sessionId}` : null) ||
395
+ `${runtime}:mcp`;
396
+
397
+ switch (name) {
398
+ case 'list_peers': {
399
+ const rt = args.runtime && args.runtime !== 'all' ? args.runtime : null;
400
+ return callRpc(
401
+ 'peer.list',
402
+ {
403
+ runtime: rt,
404
+ include_offline: Boolean(args.include_offline),
405
+ include_native_claude: Boolean(args.include_native_claude),
406
+ },
407
+ { config },
408
+ );
409
+ }
410
+ case 'send_peer_message': {
411
+ return callRpc(
412
+ 'message.send',
413
+ {
414
+ to: args.to,
415
+ body: args.message,
416
+ from: args.from || defaultFrom,
417
+ thread_id: args.thread_id || undefined,
418
+ reply_expected:
419
+ args.reply_expected !== undefined ? Boolean(args.reply_expected) : true,
420
+ max_hops: args.max_hops !== undefined ? Number(args.max_hops) : undefined,
421
+ wait_reply: Boolean(args.wait_reply),
422
+ },
423
+ { config },
424
+ );
425
+ }
426
+ case 'spawn_peer': {
427
+ return callRpc(
428
+ 'peer.spawn',
429
+ {
430
+ runtime: args.runtime,
431
+ name: args.name,
432
+ cwd: args.cwd || cwd,
433
+ model: args.model || undefined,
434
+ initial_prompt: args.initial_prompt || undefined,
435
+ mode: args.mode || 'headless',
436
+ auto_close_on_finish: Boolean(args.auto_close_on_finish),
437
+ spawned_by: registeredPeer?.handle || defaultFrom,
438
+ },
439
+ { config },
440
+ );
441
+ }
442
+ case 'close_peer': {
443
+ return callRpc(
444
+ 'peer.close',
445
+ {
446
+ target: args.target,
447
+ policy: args.policy || undefined,
448
+ force: Boolean(args.force),
449
+ reason: args.reason || undefined,
450
+ },
451
+ { config },
452
+ );
453
+ }
454
+ case 'wait_peer_messages': {
455
+ const timeoutMs = Number(args.timeout_ms ?? 30_000);
456
+ return callRpc(
457
+ 'message.wait',
458
+ {
459
+ target: args.target || (!args.session_id ? registeredPeer?.handle : undefined),
460
+ session_id: args.session_id || undefined,
461
+ runtime,
462
+ timeout_ms: timeoutMs,
463
+ },
464
+ { config, timeoutMs: timeoutMs + 5_000 },
465
+ );
466
+ }
467
+ case 'delegate_task': {
468
+ const timeoutMs = Number(args.timeout_ms ?? 180_000);
469
+ return callRpc(
470
+ 'task.create',
471
+ {
472
+ to: args.to,
473
+ from: args.from || defaultFrom,
474
+ prompt: args.prompt,
475
+ title: args.title || undefined,
476
+ request_id: args.request_id || undefined,
477
+ expected_artifacts: args.expected_artifacts || [],
478
+ acceptance_criteria: args.acceptance_criteria || [],
479
+ require_artifacts: Boolean(args.require_artifacts),
480
+ notify_on_finish: args.notify_on_finish !== false,
481
+ callback_to: args.callback_to || registeredPeer?.handle || defaultFrom,
482
+ cwd: args.cwd || cwd,
483
+ wait: Boolean(args.wait),
484
+ timeout_ms: timeoutMs,
485
+ },
486
+ { config, timeoutMs: args.wait ? timeoutMs + 5_000 : 30_000 },
487
+ );
488
+ }
489
+ case 'complete_task': {
490
+ return callRpc(
491
+ 'task.complete',
492
+ {
493
+ request_id: args.request_id,
494
+ status: args.status || 'completed',
495
+ summary: args.summary || undefined,
496
+ error: args.error || undefined,
497
+ },
498
+ { config },
499
+ );
500
+ }
501
+ case 'get_task_status': {
502
+ if (args.request_id) {
503
+ return callRpc('task.get', { request_id: args.request_id }, { config });
504
+ }
505
+ return callRpc(
506
+ 'task.list',
507
+ {
508
+ workflow_id: args.workflow_id || undefined,
509
+ status: args.status || undefined,
510
+ limit: args.limit || 50,
511
+ },
512
+ { config },
513
+ );
514
+ }
515
+ case 'run_workflow': {
516
+ const action = args.action || 'run';
517
+ if (action === 'status') {
518
+ return callRpc('workflow.get', { workflow_id: args.workflow_id }, { config });
519
+ }
520
+ if (action === 'list') {
521
+ return callRpc('workflow.list', { template: args.template || undefined }, { config });
522
+ }
523
+ if (action === 'wait') {
524
+ const timeoutMs = Number(args.timeout_ms ?? 300_000);
525
+ return callRpc(
526
+ 'workflow.wait',
527
+ { workflow_id: args.workflow_id, timeout_ms: timeoutMs },
528
+ { config, timeoutMs: timeoutMs + 5_000 },
529
+ );
530
+ }
531
+ const timeoutMs = Number(args.timeout_ms ?? 300_000);
532
+ return callRpc(
533
+ 'workflow.run',
534
+ {
535
+ ...args,
536
+ cwd: args.cwd || cwd,
537
+ coordinator: args.coordinator || registeredPeer?.handle || undefined,
538
+ },
539
+ { config, timeoutMs: args.async ? 30_000 : timeoutMs + 10_000 },
540
+ );
541
+ }
542
+ default:
543
+ throw new Error(`Unknown MCP tool: ${name}`);
544
+ }
545
+ };
546
+
547
+ const cleanup = () => {
548
+ if (closed) return;
549
+ closed = true;
550
+ try {
551
+ channelSub?.close();
552
+ } catch {
553
+ // ignore
554
+ }
555
+ channelSub = null;
556
+ try {
557
+ rl.close();
558
+ } catch {
559
+ // ignore
560
+ }
561
+ };
562
+
563
+ const rl = readline.createInterface({ input: inputStream, crlfDelay: Infinity });
564
+
565
+ rl.on('line', async (line) => {
566
+ const trimmed = line.trim();
567
+ if (!trimmed) return;
568
+ let msg;
569
+ try {
570
+ msg = JSON.parse(trimmed);
571
+ } catch {
572
+ return;
573
+ }
574
+
575
+ if (msg.method === 'initialize') {
576
+ const capabilities = { tools: {} };
577
+ if (enableChannel) {
578
+ capabilities.experimental = { 'claude/channel': {} };
579
+ }
580
+ sendJsonRpc({
581
+ jsonrpc: '2.0',
582
+ id: msg.id,
583
+ result: {
584
+ protocolVersion: msg.params?.protocolVersion || '2024-11-05',
585
+ capabilities,
586
+ serverInfo: { name: 'peer-bridge', version: SERVER_VERSION },
587
+ instructions:
588
+ 'Use peer-bridge tools (list_peers, send_peer_message, spawn_peer, close_peer) to collaborate with external AI peer sessions. When receiving <peer-message reply-expected="false">, do not send a follow-up reply.',
589
+ },
590
+ });
591
+ return;
592
+ }
593
+
594
+ if (msg.method === 'notifications/initialized') {
595
+ try {
596
+ await setupChannelIfEnabled();
597
+ } catch (err) {
598
+ process.stderr.write(`peer-bridge MCP channel init warning: ${err.message}\n`);
599
+ }
600
+ return;
601
+ }
602
+
603
+ if (msg.method === 'ping') {
604
+ sendJsonRpc({ jsonrpc: '2.0', id: msg.id, result: {} });
605
+ return;
606
+ }
607
+
608
+ if (msg.method === 'tools/list') {
609
+ sendJsonRpc({
610
+ jsonrpc: '2.0',
611
+ id: msg.id,
612
+ result: { tools: MCP_TOOLS },
613
+ });
614
+ return;
615
+ }
616
+
617
+ if (msg.method === 'tools/call') {
618
+ const toolName = msg.params?.name;
619
+ const toolArgs = msg.params?.arguments || {};
620
+ try {
621
+ const result = await handleToolCall(toolName, toolArgs);
622
+ sendJsonRpc({
623
+ jsonrpc: '2.0',
624
+ id: msg.id,
625
+ result: {
626
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
627
+ },
628
+ });
629
+ } catch (err) {
630
+ sendJsonRpc({
631
+ jsonrpc: '2.0',
632
+ id: msg.id,
633
+ result: {
634
+ isError: true,
635
+ content: [{ type: 'text', text: `[${err.code || 'ERROR'}] ${err.message}` }],
636
+ },
637
+ });
638
+ }
639
+ return;
640
+ }
641
+
642
+ if (msg.id !== undefined) {
643
+ sendJsonRpc({
644
+ jsonrpc: '2.0',
645
+ id: msg.id,
646
+ error: { code: -32601, message: `Method not found: ${msg.method}` },
647
+ });
648
+ }
649
+ });
650
+
651
+ rl.on('close', cleanup);
652
+
653
+ if (options.attachSignals !== false) {
654
+ process.on('SIGINT', () => {
655
+ cleanup();
656
+ process.exit(0);
657
+ });
658
+ process.on('SIGTERM', () => {
659
+ cleanup();
660
+ process.exit(0);
661
+ });
662
+ }
663
+
664
+ return {
665
+ close: cleanup,
666
+ getRegisteredPeer: () => registeredPeer,
667
+ };
668
+ }