Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
1299 lines (1209 loc) · 52.9 KB
/
Copy pathserver.ts
File metadata and controls
1299 lines (1209 loc) · 52.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
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
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
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
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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bun
/**
* claude-peers MCP server
*
* Spawned by Claude Code as a stdio MCP server (one per instance).
* Connects to the shared broker daemon for peer discovery and messaging.
* Declares claude/channel capability to push inbound messages immediately.
*
* Usage:
* claude --dangerously-load-development-channels server:claude-peers
*
* With .mcp.json:
* { "claude-peers": { "command": "bun", "args": ["./server.ts"] } }
*/
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
ListToolsRequestSchema,
CallToolRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import type {
PeerId,
Peer,
RegisterResponse,
PollMessagesResponse,
Message,
BroadcastResponse,
} from "./shared/types.ts";
import { createLogger } from "./shared/log.ts";
import { getGitBranch, getRecentFiles } from "./shared/summarize.ts";
// --- Configuration ---
const BROKER_PORT = parseInt(process.env.CLAUDE_PEERS_PORT ?? "7899", 10);
const BROKER_URL = `http://127.0.0.1:${BROKER_PORT}`;
const POLL_INTERVAL_MS = 1000;
const HEARTBEAT_INTERVAL_MS = 15_000;
const BROKER_SCRIPT = new URL("./broker.ts", import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, "$1");
const MAX_CONSECUTIVE_FAILURES = 5;
const RECONNECT_DELAY_MS = 2000;
// --- Broker communication ---
async function brokerFetch<T>(path: string, body: unknown): Promise<T> {
const res = await fetch(`${BROKER_URL}${path}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) {
const err = await res.text();
throw new Error(`Broker error (${path}): ${res.status} ${err}`);
}
return res.json() as Promise<T>;
}
async function isBrokerAlive(): Promise<boolean> {
try {
const res = await fetch(`${BROKER_URL}/health`, { signal: AbortSignal.timeout(2000) });
return res.ok;
} catch {
return false;
}
}
async function ensureBroker(): Promise<void> {
if (await isBrokerAlive()) {
log.info("Broker already running");
return;
}
log.info("Starting broker daemon...");
const proc = Bun.spawn(["bun", BROKER_SCRIPT], {
stdio: ["ignore", "ignore", "inherit"],
// Detach so the broker survives if this MCP server exits
// On macOS/Linux, the broker will keep running
});
// Unref so this process can exit without waiting for the broker
proc.unref();
// Wait for it to come up
for (let i = 0; i < 30; i++) {
await new Promise((r) => setTimeout(r, 200));
if (await isBrokerAlive()) {
log.info("Broker started");
return;
}
}
throw new Error("Failed to start broker daemon after 6 seconds");
}
// --- Logging ---
const log = createLogger("server");
async function getGitRoot(cwd: string): Promise<string | null> {
try {
const proc = Bun.spawn(["git", "rev-parse", "--show-toplevel"], {
cwd,
stdout: "pipe",
stderr: "ignore",
});
const text = await new Response(proc.stdout).text();
const code = await proc.exited;
if (code === 0) {
return text.trim();
}
} catch {
// not a git repo
}
return null;
}
function getTty(): string | null {
if (process.platform === "win32") return null;
try {
// Try to get the parent's tty from the process tree
const ppid = process.ppid;
if (ppid) {
const proc = Bun.spawnSync(["ps", "-o", "tty=", "-p", String(ppid)]);
const tty = new TextDecoder().decode(proc.stdout).trim();
if (tty && tty !== "?" && tty !== "??") {
return tty;
}
}
} catch {
// ignore
}
return null;
}
// --- State ---
let myId: PeerId | null = null;
let myName: string = "";
let myCwd = process.cwd();
let myGitRoot: string | null = null;
let mySummary: string = "";
async function buildContextSnapshot(): Promise<string> {
const branch = await getGitBranch(myCwd);
const recentFiles = await getRecentFiles(myCwd, 5);
return JSON.stringify({ branch, recent_files: recentFiles, summary: mySummary, cwd: myCwd });
}
let consecutivePollFailures = 0;
let reconnectPromise: Promise<void> | null = null;
let isPolling = false;
// --- MCP Server ---
const mcp = new Server(
{ name: "claude-peers", version: "0.1.0" },
{
capabilities: {
experimental: { "claude/channel": {} },
tools: {},
},
instructions: `You are connected to the claude-peers network. Other Claude Code instances on this machine can see you and send you messages. You have been automatically assigned a name (e.g. "claude-1") that other peers see.
IMPORTANT: When you receive a <channel source="claude-peers" ...> message, RESPOND IMMEDIATELY. Pause what you are doing, reply using send_message, then resume your work.
CRITICAL RULES FOR REPLYING:
1. Put your ENTIRE response into the send_message call. The recipient can ONLY see what you put in send_message — they cannot see your terminal output. Never split between a brief message and terminal text.
2. Use Markdown formatting in your messages: **bold**, *italic*, inline code, code blocks, headings (##), lists (- item). This makes your replies readable in the dashboard.
3. For multi-step tasks, send progress updates as separate messages:
- First: "Starting [task]..."
- During: "Progress: [status]"
- Done: "Completed. Here's the result: [details]"
4. Include all relevant context: what you did, what changed, any errors, next steps.
5. If you call tools (set_summary, etc.), also mention what you did in your send_message reply so the recipient sees the full picture.
Read the from_name (or from_id), from_summary, from_cwd attributes to understand who sent the message. Reply by calling send_message with their from_id or from_name.
Available tools:
- list_peers: Discover other Claude Code instances (scope: machine/directory/repo). Shows name, id, cwd, summary.
- send_message: Send a message to another instance by peer ID or name
- broadcast_message: Send a message to all peers matching a scope (machine/directory/repo)
- set_name: Change your display name (default: claude-N)
- set_summary: Set a 1-2 sentence summary of what you're working on (visible to other peers)
- check_messages: Manually check for new messages
- ack_message: Acknowledge receipt of a message (use message_id from channel notification)
- check_acks: See if your sent messages have been acknowledged
- message_history: Retrieve past conversation with a specific peer
- set_status: Set your presence (online/away/busy)
When you start, proactively call set_summary to describe what you're working on. This helps other instances understand your context.`,
}
);
// --- Tool definitions ---
const TOOLS = [
{
name: "list_peers",
description:
"List other Claude Code instances running on this machine. Returns their ID, working directory, git repo, and summary.",
inputSchema: {
type: "object" as const,
properties: {
scope: {
type: "string" as const,
enum: ["machine", "directory", "repo"],
description:
'Scope of peer discovery. "machine" = all instances on this computer. "directory" = same working directory. "repo" = same git repository (including worktrees or subdirectories).',
},
},
required: ["scope"],
},
},
{
name: "send_message",
description:
"Send a message to another Claude Code instance by name or ID. The message will be pushed into their session immediately via channel notification.",
inputSchema: {
type: "object" as const,
properties: {
to_id: {
type: "string" as const,
description: "The peer name (e.g. 'claude-1') or ID of the target instance",
},
message: {
type: "string" as const,
description: "The message to send",
},
},
required: ["to_id", "message"],
},
},
{
name: "set_name",
description:
"Change your display name. Default is claude-N (auto-assigned). Other peers see this name when listing peers or receiving messages.",
inputSchema: {
type: "object" as const,
properties: {
name: {
type: "string" as const,
description: "Your new display name",
},
},
required: ["name"],
},
},
{
name: "set_summary",
description:
"Set a brief summary (1-2 sentences) of what you are currently working on. This is visible to other Claude Code instances when they list peers.",
inputSchema: {
type: "object" as const,
properties: {
summary: {
type: "string" as const,
description: "A 1-2 sentence summary of your current work",
},
},
required: ["summary"],
},
},
{
name: "check_messages",
description:
"Manually check for new messages from other Claude Code instances. Messages are normally pushed automatically via channel notifications, but you can use this as a fallback.",
inputSchema: {
type: "object" as const,
properties: {},
},
},
{
name: "broadcast_message",
description:
"Send a message to all Claude Code instances matching a scope. 'machine' sends to everyone, 'directory' to peers in the same working directory, 'repo' to peers in the same git repository.",
inputSchema: {
type: "object" as const,
properties: {
scope: {
type: "string" as const,
enum: ["machine", "directory", "repo"],
description: "Who to broadcast to",
},
message: {
type: "string" as const,
description: "The message to broadcast",
},
},
required: ["scope", "message"],
},
},
{
name: "ack_message",
description:
"Acknowledge receipt of a message. Use the message_id from the channel notification meta.",
inputSchema: {
type: "object" as const,
properties: {
message_id: {
type: "number" as const,
description: "The ID of the message to acknowledge",
},
},
required: ["message_id"],
},
},
{
name: "check_acks",
description:
"Check if messages you sent have been acknowledged by their recipients.",
inputSchema: {
type: "object" as const,
properties: {
limit: {
type: "number" as const,
description: "Maximum number of recent messages to check (default: 20)",
},
},
},
},
{
name: "message_history",
description: "Retrieve past messages between you and another peer in the current session.",
inputSchema: {
type: "object" as const,
properties: {
peer_id: { type: "string" as const, description: "The peer name or ID to get history with" },
limit: { type: "number" as const, description: "Max messages to return (default: 50)" },
},
required: ["peer_id"],
},
},
{
name: "set_status",
description: "Set your presence status. Visible to other peers and the dashboard.",
inputSchema: {
type: "object" as const,
properties: {
status: {
type: "string" as const,
enum: ["online", "away", "busy"],
description: "Your presence status",
},
},
required: ["status"],
},
},
{
name: "create_task",
description: "Create a task and optionally assign it to another peer. The assignee will receive a notification message.",
inputSchema: {
type: "object" as const,
properties: {
title: { type: "string" as const, description: "Task title (max 200 chars)" },
description: { type: "string" as const, description: "Optional task description" },
assignee: { type: "string" as const, description: "Peer name or ID to assign the task to (optional)" },
},
required: ["title"],
},
},
{
name: "complete_task",
description: "Mark a task as completed, optionally with a result message. The task creator will be notified.",
inputSchema: {
type: "object" as const,
properties: {
task_id: { type: "string" as const, description: "The ID of the task to complete" },
result: { type: "string" as const, description: "Optional result or summary of what was done" },
},
required: ["task_id"],
},
},
{
name: "list_tasks",
description: "List tasks in the current session. Can filter by status (pending/completed).",
inputSchema: {
type: "object" as const,
properties: {
status: { type: "string" as const, enum: ["pending", "completed"], description: "Filter by task status" },
},
},
},
{
name: "set_active_files",
description: "Report which files you are currently editing. Other peers editing the same files will be flagged as conflicts. Call this when you start or stop editing files.",
inputSchema: {
type: "object" as const,
properties: {
files: {
type: "array" as const,
items: { type: "string" as const },
description: "List of file paths you are currently editing. Pass empty array to clear.",
},
},
required: ["files"],
},
},
{
name: "pin_message",
description: "Pin or unpin a message. Pinned messages stay visible at the top of the dashboard chat.",
inputSchema: {
type: "object" as const,
properties: {
message_id: { type: "number" as const, description: "The message ID to pin/unpin" },
pinned: { type: "boolean" as const, description: "true to pin, false to unpin (default: true)" },
},
required: ["message_id"],
},
},
{
name: "react",
description: "Add or remove an emoji reaction on a message. Lightweight feedback without a full reply.",
inputSchema: {
type: "object" as const,
properties: {
message_id: { type: "number" as const, description: "The message ID to react to" },
emoji: { type: "string" as const, description: "Emoji to react with: 👍 👀 ✅ ⚠️ ❌ 🎉 ❤️ 🤔" },
remove: { type: "boolean" as const, description: "true to remove the reaction (default: false)" },
},
required: ["message_id", "emoji"],
},
},
{
name: "request_approval",
description: "Request approval from another peer before taking a potentially dangerous action. The approver receives a notification and can accept or reject.",
inputSchema: {
type: "object" as const,
properties: {
approver: { type: "string" as const, description: "Peer name or ID to request approval from" },
action: { type: "string" as const, description: "Description of the action you want to take" },
},
required: ["approver", "action"],
},
},
{
name: "respond_approval",
description: "Accept or reject an approval request from another peer.",
inputSchema: {
type: "object" as const,
properties: {
approval_id: { type: "string" as const, description: "The approval request ID" },
approved: { type: "boolean" as const, description: "true to approve, false to reject" },
reason: { type: "string" as const, description: "Optional reason for the decision" },
},
required: ["approval_id", "approved"],
},
},
{
name: "session_report",
description: "Generate a structured markdown report of the current session: participants, tasks, messages, activity log.",
inputSchema: {
type: "object" as const,
properties: {},
},
},
// --- Structured Messages ---
{
name: "send_structured",
description: "Send a typed, structured message to another peer. Forces clarity by requiring specific fields based on message type. Types: question (ask with expected answer format), decision (record a choice with rationale), context_share (share current work context), review_request (request code review), handoff (transfer work).",
inputSchema: {
type: "object" as const,
properties: {
to_id: { type: "string" as const, description: "Peer name or ID" },
msg_type: { type: "string" as const, enum: ["question", "decision", "context_share", "review_request", "handoff"], description: "Message type" },
question: { type: "string" as const, description: "For question type: the question" },
expected_format: { type: "string" as const, description: "For question type: expected answer format" },
context: { type: "string" as const, description: "For question type: additional context" },
decision: { type: "string" as const, description: "For decision type: the decision made" },
rationale: { type: "string" as const, description: "For decision type: reasoning behind the decision" },
alternatives_rejected: { type: "array" as const, items: { type: "string" as const }, description: "For decision type: alternatives that were rejected" },
summary: { type: "string" as const, description: "For context_share type: summary of current work" },
files_changed: { type: "array" as const, items: { type: "string" as const }, description: "For context_share type: files changed" },
constraints: { type: "array" as const, items: { type: "string" as const }, description: "For context_share type: constraints to be aware of" },
current_task: { type: "string" as const, description: "For context_share type: current task" },
file_path: { type: "string" as const, description: "For review_request type: file to review" },
description: { type: "string" as const, description: "For review_request type: what to review" },
acceptance_criteria: { type: "string" as const, description: "For review_request type: acceptance criteria" },
work_completed: { type: "string" as const, description: "For handoff type: work completed" },
remaining_work: { type: "string" as const, description: "For handoff type: remaining work" },
files_modified: { type: "array" as const, items: { type: "string" as const }, description: "For handoff type: files modified" },
decisions_made: { type: "array" as const, items: { type: "string" as const }, description: "For handoff type: decisions made" },
blockers: { type: "array" as const, items: { type: "string" as const }, description: "For handoff type: blockers" },
},
required: ["to_id", "msg_type"],
},
},
// --- Decisions Board ---
{
name: "post_decision",
description: "Record an architectural decision on the shared decisions board. Other peers in your group can query this to stay aligned. Decisions are keyed — posting the same key updates the existing decision.",
inputSchema: {
type: "object" as const,
properties: {
key: { type: "string" as const, description: "Decision key, e.g. 'auth_strategy', 'db_orm', 'api_format'" },
value: { type: "string" as const, description: "The decision value, e.g. 'JWT with refresh tokens'" },
rationale: { type: "string" as const, description: "Why this decision was made" },
category: { type: "string" as const, description: "Category for grouping, e.g. 'architecture', 'tooling', 'conventions'. Default: 'general'" },
},
required: ["key", "value", "rationale"],
},
},
{
name: "query_decisions",
description: "Query the shared decisions board. Returns all active decisions, optionally filtered by key or category. Always check decisions before making architectural choices.",
inputSchema: {
type: "object" as const,
properties: {
key: { type: "string" as const, description: "Optional: look up a specific decision key" },
category: { type: "string" as const, description: "Optional: filter by category" },
},
},
},
// --- Verification Protocol ---
{
name: "request_verification",
description: "Ask another peer to verify a specific claim. The verifier receives the claim, evidence requirements, and relevant files, and responds with verified/failed + proof. Use this before acting on assumptions.",
inputSchema: {
type: "object" as const,
properties: {
to_id: { type: "string" as const, description: "Peer name or ID of the verifier" },
claim: { type: "string" as const, description: "The specific claim to verify, e.g. 'function parseConfig in config.ts returns a Config object'" },
evidence_needed: { type: "string" as const, description: "What evidence would confirm or deny the claim" },
files_to_check: { type: "array" as const, items: { type: "string" as const }, description: "File paths the verifier should check" },
},
required: ["to_id", "claim", "evidence_needed"],
},
},
{
name: "respond_verification",
description: "Respond to a verification request with your findings.",
inputSchema: {
type: "object" as const,
properties: {
verification_id: { type: "string" as const, description: "The verification ID from the request" },
status: { type: "string" as const, enum: ["verified", "failed"], description: "Whether the claim was verified or failed" },
response: { type: "string" as const, description: "Your verification findings" },
evidence: { type: "string" as const, description: "Evidence supporting your response" },
},
required: ["verification_id", "status", "response"],
},
},
// --- Consensus Protocol ---
{
name: "create_proposal",
description: "Propose a decision that requires peer votes before being finalized. Broadcasts to all group peers. Auto-resolves when the vote threshold is reached.",
inputSchema: {
type: "object" as const,
properties: {
title: { type: "string" as const, description: "Proposal title" },
description: { type: "string" as const, description: "Detailed proposal description" },
required_votes: { type: "number" as const, description: "Number of approvals needed (default: 2, max: 20)" },
},
required: ["title", "description"],
},
},
{
name: "vote_proposal",
description: "Vote on an open proposal. Cannot vote on your own proposals.",
inputSchema: {
type: "object" as const,
properties: {
proposal_id: { type: "string" as const, description: "The proposal ID" },
vote: { type: "string" as const, enum: ["approve", "reject"], description: "Your vote" },
reason: { type: "string" as const, description: "Reason for your vote" },
},
required: ["proposal_id", "vote"],
},
},
];
// --- Tool handlers ---
mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: TOOLS,
}));
mcp.setRequestHandler(CallToolRequestSchema, async (req) => {
const { name, arguments: args } = req.params;
switch (name) {
case "list_peers": {
const scope = (args as { scope: string }).scope as "machine" | "directory" | "repo";
try {
const peers = await brokerFetch<Peer[]>("/list-peers", {
scope,
cwd: myCwd,
git_root: myGitRoot,
exclude_id: myId,
});
if (peers.length === 0) {
return {
content: [
{
type: "text" as const,
text: `No other Claude Code instances found (scope: ${scope}).`,
},
],
};
}
const lines = peers.map((p) => {
const parts = [
`Name: ${p.name || p.id}`,
`ID: ${p.id}`,
`CWD: ${p.cwd}`,
];
if (p.git_root) parts.push(`Repo: ${p.git_root}`);
if (p.summary) parts.push(`Summary: ${p.summary}`);
parts.push(`Group: ${p.group_id ? p.group_id : "lobby"}`);
parts.push(`Last seen: ${p.last_seen}`);
return parts.join("\n ");
});
return {
content: [
{
type: "text" as const,
text: `Found ${peers.length} peer(s) (scope: ${scope}):\n\n${lines.join("\n\n")}`,
},
],
};
} catch (e) {
return {
content: [
{
type: "text" as const,
text: `Error listing peers: ${e instanceof Error ? e.message : String(e)}`,
},
],
isError: true,
};
}
}
case "send_message": {
const { to_id, message } = args as { to_id: string; message: string };
if (!myId) {
return {
content: [{ type: "text" as const, text: "Not registered with broker yet" }],
isError: true,
};
}
try {
// Resolve name to ID if needed
let resolvedId = to_id;
const peers = await brokerFetch<Peer[]>("/list-peers", { scope: "machine", cwd: myCwd, git_root: myGitRoot });
const byName = peers.find((p) => p.name === to_id);
if (byName) resolvedId = byName.id;
// Auto-attach context snapshot
let contextSnapshot: string | undefined;
try { contextSnapshot = await buildContextSnapshot(); } catch { /* non-critical */ }
const result = await brokerFetch<{ ok: boolean; error?: string }>("/send-message", {
from_id: myId,
to_id: resolvedId,
text: message,
context_snapshot: contextSnapshot,
});
if (!result.ok) {
return {
content: [{ type: "text" as const, text: `Failed to send: ${result.error}` }],
isError: true,
};
}
const targetLabel = byName ? byName.name : resolvedId;
return {
content: [{ type: "text" as const, text: `Message sent to ${targetLabel}` }],
};
} catch (e) {
return {
content: [
{
type: "text" as const,
text: `Error sending message: ${e instanceof Error ? e.message : String(e)}`,
},
],
isError: true,
};
}
}
case "set_name": {
const { name } = args as { name: string };
if (!myId) {
return { content: [{ type: "text" as const, text: "Not registered with broker yet" }], isError: true };
}
try {
const result = await brokerFetch<{ ok: boolean; error?: string }>("/set-name", { id: myId, name });
if (!result.ok) {
return { content: [{ type: "text" as const, text: `Failed: ${result.error}` }], isError: true };
}
myName = name;
process.stderr.write(`\x1b]0;${myName}\x07`);
return { content: [{ type: "text" as const, text: `Name changed to "${name}"` }] };
} catch (e) {
return { content: [{ type: "text" as const, text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
}
}
case "set_summary": {
const { summary } = args as { summary: string };
if (!myId) {
return {
content: [{ type: "text" as const, text: "Not registered with broker yet" }],
isError: true,
};
}
try {
await brokerFetch("/set-summary", { id: myId, summary });
mySummary = summary;
return {
content: [{ type: "text" as const, text: `Summary updated: "${summary}"` }],
};
} catch (e) {
return {
content: [
{
type: "text" as const,
text: `Error setting summary: ${e instanceof Error ? e.message : String(e)}`,
},
],
isError: true,
};
}
}
case "check_messages": {
if (!myId) {
return {
content: [{ type: "text" as const, text: "Not registered with broker yet" }],
isError: true,
};
}
try {
const result = await brokerFetch<PollMessagesResponse>("/poll-messages", { id: myId });
if (result.messages.length === 0) {
return {
content: [{ type: "text" as const, text: "No new messages." }],
};
}
const lines = result.messages.map(
(m) => `From ${m.from_id} (${m.sent_at}):\n${m.text}`
);
return {
content: [
{
type: "text" as const,
text: `${result.messages.length} new message(s):\n\n${lines.join("\n\n---\n\n")}`,
},
],
};
} catch (e) {
return {
content: [
{
type: "text" as const,
text: `Error checking messages: ${e instanceof Error ? e.message : String(e)}`,
},
],
isError: true,
};
}
}
case "broadcast_message": {
const { scope, message } = args as { scope: "machine" | "directory" | "repo"; message: string };
if (!myId) {
return { content: [{ type: "text" as const, text: "Not registered with broker yet" }], isError: true };
}
try {
const result = await brokerFetch<BroadcastResponse>("/broadcast", {
from_id: myId, scope, cwd: myCwd, git_root: myGitRoot, text: message,
});
if (!result.ok) {
return { content: [{ type: "text" as const, text: `Failed to broadcast: ${result.error}` }], isError: true };
}
return { content: [{ type: "text" as const, text: `Broadcast sent to ${result.sent_to} peer(s) (scope: ${scope})` }] };
} catch (e) {
return { content: [{ type: "text" as const, text: `Error broadcasting: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
}
}
case "ack_message": {
const { message_id } = args as { message_id: number };
if (!myId) {
return { content: [{ type: "text" as const, text: "Not registered with broker yet" }], isError: true };
}
try {
const result = await brokerFetch<{ ok: boolean; error?: string }>("/ack-message", { id: myId, message_id });
if (!result.ok) {
return { content: [{ type: "text" as const, text: `Failed to ack: ${result.error}` }], isError: true };
}
return { content: [{ type: "text" as const, text: `Message ${message_id} acknowledged` }] };
} catch (e) {
return { content: [{ type: "text" as const, text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
}
}
case "check_acks": {
const limit = (args as { limit?: number }).limit ?? 20;
if (!myId) {
return { content: [{ type: "text" as const, text: "Not registered with broker yet" }], isError: true };
}
try {
const result = await brokerFetch<{ messages: Array<{ id: number; to_id: string; text: string; sent_at: string; acknowledged: boolean }> }>("/check-acks", { from_id: myId, limit });
if (result.messages.length === 0) {
return { content: [{ type: "text" as const, text: "No sent messages found." }] };
}
const lines = result.messages.map((m) => {
const status = m.acknowledged ? "[ACK]" : "[pending]";
return `${status} To ${m.to_id} (${m.sent_at}): ${m.text.slice(0, 60)}`;
});
return { content: [{ type: "text" as const, text: lines.join("\n") }] };
} catch (e) {
return { content: [{ type: "text" as const, text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
}
}
case "message_history": {
const { peer_id, limit } = args as { peer_id: string; limit?: number };
if (!myId) {
return { content: [{ type: "text" as const, text: "Not registered with broker yet" }], isError: true };
}
try {
// Resolve name to ID
let resolvedId = peer_id;
const peers = await brokerFetch<Peer[]>("/list-peers", { scope: "machine", cwd: myCwd, git_root: myGitRoot });
const byName = peers.find((p) => p.name === peer_id);
if (byName) resolvedId = byName.id;
const result = await brokerFetch<{ messages: Array<{ from_id: string; to_id: string; text: string; sent_at: string }> }>(
"/message-history", { peer_a: myId, peer_b: resolvedId, limit: limit ?? 50 }
);
if (result.messages.length === 0) {
return { content: [{ type: "text" as const, text: "No message history with this peer." }] };
}
const nm: Record<string, string> = {};
peers.forEach((p) => { nm[p.id] = p.name || p.id; });
nm[myId] = myName || myId;
const lines = result.messages.map((m) =>
`[${m.sent_at}] ${nm[m.from_id] || m.from_id} → ${nm[m.to_id] || m.to_id}: ${m.text}`
);
return { content: [{ type: "text" as const, text: lines.join("\n") }] };
} catch (e) {
return { content: [{ type: "text" as const, text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
}
}
case "set_status": {
const { status } = args as { status: string };
if (!myId) {
return { content: [{ type: "text" as const, text: "Not registered with broker yet" }], isError: true };
}
try {
await brokerFetch("/set-status", { id: myId, status });
return { content: [{ type: "text" as const, text: `Status set to "${status}"` }] };
} catch (e) {
return { content: [{ type: "text" as const, text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
}
}
case "create_task": {
const { title, description, assignee } = args as { title: string; description?: string; assignee?: string };
if (!myId) return { content: [{ type: "text" as const, text: "Not registered with broker yet" }], isError: true };
try {
let assigneeId = assignee;
if (assignee) {
const peers = await brokerFetch<Peer[]>("/list-peers", { scope: "machine", cwd: myCwd, git_root: myGitRoot });
const byName = peers.find((p) => p.name === assignee);
if (byName) assigneeId = byName.id;
}
const result = await brokerFetch<{ ok: boolean; id?: string; error?: string }>("/create-task", {
title, description: description || "", creator_id: myId, assignee_id: assigneeId,
});
if (!result.ok) return { content: [{ type: "text" as const, text: `Failed: ${result.error}` }], isError: true };
return { content: [{ type: "text" as const, text: `Task created (${result.id})${assigneeId ? ` and assigned to ${assignee}` : ""}` }] };
} catch (e) {
return { content: [{ type: "text" as const, text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
}
}
case "complete_task": {
const { task_id, result } = args as { task_id: string; result?: string };
if (!myId) return { content: [{ type: "text" as const, text: "Not registered with broker yet" }], isError: true };
try {
const res = await brokerFetch<{ ok: boolean; error?: string }>("/complete-task", { task_id, peer_id: myId, result });
if (!res.ok) return { content: [{ type: "text" as const, text: `Failed: ${res.error}` }], isError: true };
return { content: [{ type: "text" as const, text: `Task ${task_id} marked as completed` }] };
} catch (e) {
return { content: [{ type: "text" as const, text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
}
}
case "list_tasks": {
if (!myId) return { content: [{ type: "text" as const, text: "Not registered with broker yet" }], isError: true };
try {
const status = (args as { status?: string }).status;
const result = await brokerFetch<{ tasks: any[] }>("/list-tasks", { peer_id: myId, status });
if (result.tasks.length === 0) return { content: [{ type: "text" as const, text: "No tasks found." }] };
const peers = await brokerFetch<Peer[]>("/list-peers", { scope: "machine", cwd: myCwd, git_root: myGitRoot });
const nm: Record<string, string> = {};
peers.forEach((p) => { nm[p.id] = p.name || p.id; });
nm[myId] = myName || myId;
const lines = result.tasks.map((t: any) => {
const assignee = t.assignee_id ? (nm[t.assignee_id] || t.assignee_id) : "unassigned";
const st = t.status === "completed" ? "[done]" : "[pending]";
return `${st} ${t.id}: ${t.title} (assignee: ${assignee})`;
});
return { content: [{ type: "text" as const, text: lines.join("\n") }] };
} catch (e) {
return { content: [{ type: "text" as const, text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
}
}
case "set_active_files": {
const { files } = args as { files: string[] };
if (!myId) return { content: [{ type: "text" as const, text: "Not registered with broker yet" }], isError: true };
try {
const result = await brokerFetch<{ ok: boolean; conflicts?: Array<{ file: string; peer_name: string }> }>("/set-active-files", { id: myId, files });
if (result.conflicts && result.conflicts.length > 0) {
const warnings = result.conflicts.map((c) => ` - ${c.file} (also edited by ${c.peer_name})`);
return { content: [{ type: "text" as const, text: `Active files updated. CONFLICTS detected:\n${warnings.join("\n")}` }] };
}
return { content: [{ type: "text" as const, text: `Active files updated (${files.length} file${files.length !== 1 ? "s" : ""})` }] };
} catch (e) {
return { content: [{ type: "text" as const, text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
}
}
case "pin_message": {
const { message_id, pinned } = args as { message_id: number; pinned?: boolean };
if (!myId) return { content: [{ type: "text" as const, text: "Not registered with broker yet" }], isError: true };
try {
const result = await brokerFetch<{ ok: boolean; error?: string }>("/pin-message", { message_id, pinned: pinned !== false });
if (!result.ok) return { content: [{ type: "text" as const, text: `Failed: ${result.error}` }], isError: true };
return { content: [{ type: "text" as const, text: `Message ${message_id} ${pinned !== false ? "pinned" : "unpinned"}` }] };
} catch (e) {
return { content: [{ type: "text" as const, text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
}
}
case "react": {
const { message_id, emoji, remove } = args as { message_id: number; emoji: string; remove?: boolean };
if (!myId) return { content: [{ type: "text" as const, text: "Not registered with broker yet" }], isError: true };
try {
const result = await brokerFetch<{ ok: boolean; error?: string }>("/react", { message_id, peer_id: myId, emoji, remove: remove === true });
if (!result.ok) return { content: [{ type: "text" as const, text: `Failed: ${result.error}` }], isError: true };
return { content: [{ type: "text" as const, text: `${remove ? "Removed" : "Added"} ${emoji} reaction` }] };
} catch (e) {
return { content: [{ type: "text" as const, text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
}
}
case "request_approval": {
const { approver, action } = args as { approver: string; action: string };
if (!myId) return { content: [{ type: "text" as const, text: "Not registered with broker yet" }], isError: true };
try {
let approverId = approver;
const peers = await brokerFetch<Peer[]>("/list-peers", { scope: "machine", cwd: myCwd, git_root: myGitRoot });
const byName = peers.find((p) => p.name === approver);
if (byName) approverId = byName.id;
const result = await brokerFetch<{ ok: boolean; id?: string; error?: string }>("/request-approval", {
requester_id: myId, approver_id: approverId, action_description: action,
});
if (!result.ok) return { content: [{ type: "text" as const, text: `Failed: ${result.error}` }], isError: true };
return { content: [{ type: "text" as const, text: `Approval requested (ID: ${result.id}). Waiting for ${approver} to respond.` }] };
} catch (e) {
return { content: [{ type: "text" as const, text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
}
}
case "respond_approval": {
const { approval_id, approved, reason } = args as { approval_id: string; approved: boolean; reason?: string };
if (!myId) return { content: [{ type: "text" as const, text: "Not registered with broker yet" }], isError: true };
try {
const result = await brokerFetch<{ ok: boolean; error?: string }>("/respond-approval", {
approval_id, peer_id: myId, approved, reason,
});
if (!result.ok) return { content: [{ type: "text" as const, text: `Failed: ${result.error}` }], isError: true };
return { content: [{ type: "text" as const, text: `Approval ${approved ? "granted" : "rejected"}${reason ? `: ${reason}` : ""}` }] };
} catch (e) {
return { content: [{ type: "text" as const, text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
}
}
case "session_report": {
try {
const result = await brokerFetch<{ report: string }>("/session-report", {});
return { content: [{ type: "text" as const, text: result.report }] };
} catch (e) {
return { content: [{ type: "text" as const, text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
}
}
// --- Structured Messages ---
case "send_structured": {