-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbroker.ts
More file actions
executable file
·1584 lines (1362 loc) · 61.6 KB
/
broker.ts
File metadata and controls
executable file
·1584 lines (1362 loc) · 61.6 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
/**
* multiagents broker daemon
*
* A singleton HTTP server on localhost backed by SQLite.
* Tracks registered agent peers, routes messages, manages sessions,
* file locks, ownership zones, and guardrails.
*
* Auto-launched by the MCP server if not already running.
* Run directly: bun broker.ts
*/
import { Database } from "bun:sqlite";
import { normalize } from "node:path";
import {
DEFAULT_BROKER_PORT,
DEFAULT_DB_PATH,
DEFAULT_LOCK_TIMEOUT_MS,
MAX_LOCK_TIMEOUT_MS,
RECONNECT_RECAP_LIMIT,
DEFAULT_GUARDRAILS,
CLEANUP_INTERVAL,
} from "./shared/constants.ts";
import { generatePeerId } from "./shared/utils.ts";
import type {
RegisterRequest,
RegisterResponse,
HeartbeatRequest,
SetSummaryRequest,
ListPeersRequest,
SendMessageRequest,
SendMessageResult,
PollMessagesRequest,
PollMessagesResponse,
SetRoleRequest,
RenamePeerRequest,
CreateSessionRequest,
UpdateSessionRequest,
CreateSlotRequest,
UpdateSlotRequest,
AcquireFileRequest,
AcquireFileResult,
ReleaseFileRequest,
AssignOwnershipRequest,
UpdateGuardrailRequest,
MessageLogOptions,
SignalDoneRequest,
SubmitFeedbackRequest,
ApproveRequest,
ReleaseAgentRequest,
Peer,
Message,
Session,
Slot,
FileLock,
FileOwnership,
AgentType,
SlotCandidate,
KnowledgePutRequest,
KnowledgePutResponse,
KnowledgeEntry,
KnowledgeListRequest,
KnowledgeGetRequest,
KnowledgeDeleteRequest,
} from "./shared/types.ts";
// --- Configuration ---
const PORT = parseInt(process.env.MULTIAGENTS_PORT ?? String(DEFAULT_BROKER_PORT), 10);
const DB_PATH = process.env.MULTIAGENTS_DB ?? DEFAULT_DB_PATH;
// Ensure parent directory exists
const dbDir = DB_PATH.substring(0, DB_PATH.lastIndexOf("/"));
if (dbDir) {
try {
const { mkdirSync } = require("node:fs");
mkdirSync(dbDir, { recursive: true });
} catch {}
}
// --- Database setup ---
const db = new Database(DB_PATH);
db.run("PRAGMA journal_mode = WAL");
db.run("PRAGMA busy_timeout = 3000");
// Original tables
db.run(`
CREATE TABLE IF NOT EXISTS peers (
id TEXT PRIMARY KEY,
pid INTEGER NOT NULL,
cwd TEXT NOT NULL,
git_root TEXT,
tty TEXT,
summary TEXT NOT NULL DEFAULT '',
registered_at TEXT NOT NULL,
last_seen TEXT NOT NULL
)
`);
db.run(`
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
from_id TEXT NOT NULL,
to_id TEXT NOT NULL,
text TEXT NOT NULL,
sent_at TEXT NOT NULL,
delivered INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY (from_id) REFERENCES peers(id),
FOREIGN KEY (to_id) REFERENCES peers(id)
)
`);
// Add new columns to existing tables (idempotent via try/catch)
const alterStatements = [
"ALTER TABLE peers ADD COLUMN session_id TEXT",
"ALTER TABLE peers ADD COLUMN slot_id INTEGER",
"ALTER TABLE peers ADD COLUMN agent_type TEXT DEFAULT 'claude'",
"ALTER TABLE peers ADD COLUMN status TEXT DEFAULT 'idle'",
"ALTER TABLE messages ADD COLUMN session_id TEXT",
"ALTER TABLE messages ADD COLUMN from_slot_id INTEGER",
"ALTER TABLE messages ADD COLUMN to_slot_id INTEGER",
"ALTER TABLE messages ADD COLUMN msg_type TEXT DEFAULT 'chat'",
"ALTER TABLE messages ADD COLUMN delivered_at TEXT",
"ALTER TABLE messages ADD COLUMN held INTEGER DEFAULT 0",
"ALTER TABLE slots ADD COLUMN task_state TEXT DEFAULT 'idle'",
"ALTER TABLE slots ADD COLUMN input_tokens INTEGER DEFAULT 0",
"ALTER TABLE slots ADD COLUMN output_tokens INTEGER DEFAULT 0",
"ALTER TABLE slots ADD COLUMN cache_read_tokens INTEGER DEFAULT 0",
];
for (const stmt of alterStatements) {
try {
db.run(stmt);
} catch {
// Column already exists — ignore
}
}
// New tables
db.run(`
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
project_dir TEXT NOT NULL,
git_root TEXT,
status TEXT DEFAULT 'active',
pause_reason TEXT,
paused_at INTEGER,
config TEXT DEFAULT '{}',
created_at INTEGER NOT NULL,
last_active_at INTEGER NOT NULL
)
`);
db.run(`
CREATE TABLE IF NOT EXISTS slots (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL REFERENCES sessions(id),
agent_type TEXT NOT NULL,
display_name TEXT,
role TEXT,
role_description TEXT,
role_assigned_by TEXT,
peer_id TEXT,
status TEXT DEFAULT 'disconnected',
paused INTEGER DEFAULT 0,
paused_at INTEGER,
task_state TEXT DEFAULT 'idle',
last_peer_pid INTEGER,
last_connected INTEGER,
last_disconnected INTEGER,
context_snapshot TEXT
)
`);
db.run(`
CREATE TABLE IF NOT EXISTS file_locks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
file_path TEXT NOT NULL,
held_by_slot INTEGER NOT NULL,
held_by_peer TEXT NOT NULL,
acquired_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
lock_type TEXT DEFAULT 'exclusive',
purpose TEXT,
UNIQUE(session_id, file_path)
)
`);
db.run(`
CREATE TABLE IF NOT EXISTS file_ownership (
session_id TEXT NOT NULL,
slot_id INTEGER NOT NULL,
path_pattern TEXT NOT NULL,
assigned_at INTEGER NOT NULL,
assigned_by TEXT,
PRIMARY KEY (session_id, path_pattern)
)
`);
db.run(`
CREATE TABLE IF NOT EXISTS guardrail_overrides (
session_id TEXT NOT NULL,
guardrail_id TEXT NOT NULL,
value REAL NOT NULL,
changed_at INTEGER NOT NULL,
changed_by TEXT,
reason TEXT,
PRIMARY KEY (session_id, guardrail_id)
)
`);
db.run(`
CREATE TABLE IF NOT EXISTS guardrail_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
guardrail_id TEXT NOT NULL,
event_type TEXT NOT NULL,
current_usage REAL,
limit_value REAL,
slot_id INTEGER,
timestamp INTEGER NOT NULL,
metadata TEXT
)
`);
db.run(`
CREATE TABLE IF NOT EXISTS plans (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
title TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)
`);
db.run(`
CREATE TABLE IF NOT EXISTS plan_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
plan_id INTEGER NOT NULL REFERENCES plans(id),
parent_id INTEGER,
label TEXT NOT NULL,
status TEXT DEFAULT 'pending',
assigned_to_slot INTEGER,
completed_at INTEGER,
sort_order INTEGER DEFAULT 0
)
`);
db.run(`
CREATE TABLE IF NOT EXISTS knowledge (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
category TEXT NOT NULL DEFAULT 'context',
created_by_slot INTEGER,
created_by_name TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
UNIQUE(session_id, key)
)
`);
// --- Context snapshot builder ---
/** Build a rich context snapshot for a disconnecting peer/slot. */
function buildContextSnapshot(peer: { summary?: string | null; cwd?: string | null }, slotId: number): string {
const slotRow = db.query("SELECT task_state FROM slots WHERE id = ?").get(slotId) as { task_state: string } | null;
// Get plan items assigned to this slot (if any plan exists)
let planItems: { label: string; status: string }[] = [];
try {
const planRow = db.query(
"SELECT pi.label, pi.status FROM plan_items pi JOIN plans p ON pi.plan_id = p.id JOIN slots s ON p.session_id = s.session_id WHERE pi.assigned_to_slot = ? ORDER BY pi.sort_order",
).all(slotId) as { label: string; status: string }[];
planItems = planRow;
} catch { /* plan tables may not have data */ }
return JSON.stringify({
last_summary: peer.summary ?? null,
last_status: "disconnected",
last_cwd: peer.cwd ?? null,
task_state: slotRow?.task_state ?? null,
plan_items: planItems.length > 0 ? planItems : null,
disconnected_at: Date.now(),
});
}
// --- Stale peer cleanup ---
function cleanStalePeers() {
const peers = db.query("SELECT id, pid, summary, cwd FROM peers").all() as { id: string; pid: number; summary: string; cwd: string }[];
const now = Date.now();
for (const peer of peers) {
try {
process.kill(peer.pid, 0);
} catch {
// Disconnect slots for this peer (capture rich snapshot before deleting peer)
const slots = db.query("SELECT id FROM slots WHERE peer_id = ?").all(peer.id) as any[];
for (const slot of slots) {
const snapshot = buildContextSnapshot(peer, slot.id);
db.run(
"UPDATE slots SET status = 'disconnected', peer_id = NULL, last_disconnected = ?, context_snapshot = ? WHERE id = ?",
[now, snapshot, slot.id]
);
}
// Process dead — clean up peer (after snapshot capture)
db.run("DELETE FROM peers WHERE id = ?", [peer.id]);
db.run("DELETE FROM messages WHERE to_id = ? AND delivered = 0", [peer.id]);
// Release file locks held by this peer
db.run("DELETE FROM file_locks WHERE held_by_peer = ?", [peer.id]);
}
}
// Clean expired file locks
db.run("DELETE FROM file_locks WHERE expires_at < ?", [now]);
// Clean orphan peers: alive processes with no session that have been idle for >5 min.
// These are typically multiagents-peer adapters spawned by codex mcp-server
// that outlived their parent process.
const orphans = db.query(
"SELECT id, pid, last_seen FROM peers WHERE session_id IS NULL"
).all() as { id: string; pid: number; last_seen: string }[];
for (const orphan of orphans) {
const idleMs = now - new Date(orphan.last_seen).getTime();
if (idleMs > 5 * 60 * 1000) {
// Kill the orphan process
try { process.kill(orphan.pid, "SIGTERM"); } catch { /* already dead */ }
db.run("DELETE FROM peers WHERE id = ?", [orphan.id]);
}
}
}
cleanStalePeers();
setInterval(cleanStalePeers, CLEANUP_INTERVAL);
// --- Prepared statements ---
const insertPeer = db.prepare(`
INSERT INTO peers (id, pid, cwd, git_root, tty, summary, registered_at, last_seen, session_id, slot_id, agent_type, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
const updateLastSeen = db.prepare(
"UPDATE peers SET last_seen = ? WHERE id = ?"
);
const updateSummary = db.prepare(
"UPDATE peers SET summary = ? WHERE id = ?"
);
const deletePeer = db.prepare(
"DELETE FROM peers WHERE id = ?"
);
const selectAllPeers = db.prepare(
"SELECT * FROM peers"
);
const selectPeersByDirectory = db.prepare(
"SELECT * FROM peers WHERE cwd = ?"
);
const selectPeersByGitRoot = db.prepare(
"SELECT * FROM peers WHERE git_root = ?"
);
const insertMessage = db.prepare(`
INSERT INTO messages (from_id, to_id, text, sent_at, delivered, session_id, from_slot_id, to_slot_id, msg_type, held)
VALUES (?, ?, ?, ?, 0, ?, ?, ?, ?, ?)
`);
const selectUndelivered = db.prepare(
"SELECT * FROM messages WHERE to_id = ? AND delivered = 0 AND held = 0 ORDER BY sent_at ASC"
);
const markDelivered = db.prepare(
"UPDATE messages SET delivered = 1, delivered_at = ? WHERE id = ?"
);
// --- Request handlers ---
function handleRegister(body: RegisterRequest): RegisterResponse {
const agentType: AgentType = body.agent_type ?? "claude";
const id = generatePeerId(agentType);
const now = new Date().toISOString();
const nowMs = Date.now();
// Remove any existing registration for this PID
const existing = db.query("SELECT id FROM peers WHERE pid = ?").get(body.pid) as { id: string } | null;
if (existing) {
deletePeer.run(existing.id);
}
// Explicit slot targeting — when orchestrator passes a specific slot_id
// Resolve session_id: explicit > inferred from the slot's own record.
// This fallback covers sandboxed agents (Codex, Gemini) that may lose
// MULTIAGENTS_SESSION env var but still have MULTIAGENTS_SLOT.
let effectiveSessionId = body.session_id;
if (body.slot_id && !effectiveSessionId) {
const slotRow = db.query("SELECT session_id FROM slots WHERE id = ?").get(body.slot_id) as { session_id: string } | null;
if (slotRow) effectiveSessionId = slotRow.session_id;
}
if (body.slot_id && effectiveSessionId) {
const targetSlot = db.query(
"SELECT * FROM slots WHERE id = ? AND session_id = ?"
).get(body.slot_id, effectiveSessionId) as Slot | null;
if (targetSlot) {
insertPeer.run(id, body.pid, body.cwd, body.git_root, body.tty, body.summary, now, now, effectiveSessionId, targetSlot.id, agentType, "idle");
db.run(
"UPDATE slots SET peer_id = ?, status = 'connected', last_connected = ?, last_peer_pid = ? WHERE id = ?",
[id, nowMs, body.pid, targetSlot.id]
);
const recap = db.query(
"SELECT * FROM messages WHERE session_id = ? AND to_slot_id = ? ORDER BY sent_at DESC LIMIT ?"
).all(effectiveSessionId, targetSlot.id, RECONNECT_RECAP_LIMIT) as Message[];
recap.reverse();
const updatedSlot = db.query("SELECT * FROM slots WHERE id = ?").get(targetSlot.id) as Slot;
return { id, slot: updatedSlot, recap };
}
}
// Reconnect logic — match by role first, then by agent_type
if (body.reconnect && body.session_id) {
let disconnectedSlots = db.query(
"SELECT * FROM slots WHERE session_id = ? AND agent_type = ? AND status = 'disconnected'"
).all(body.session_id, agentType) as Slot[];
// If multiple matches and a role is provided, narrow by role
if (disconnectedSlots.length > 1 && body.role) {
const roleMatches = disconnectedSlots.filter((s) => s.role === body.role);
if (roleMatches.length >= 1) {
disconnectedSlots = roleMatches;
}
}
if (disconnectedSlots.length >= 1) {
// Pick the first match (exact role match preferred, or only candidate)
const slot = disconnectedSlots[0];
if (!slot) {
return { id };
}
insertPeer.run(id, body.pid, body.cwd, body.git_root, body.tty, body.summary, now, now, body.session_id, slot.id, agentType, "idle");
db.run(
"UPDATE slots SET peer_id = ?, status = 'connected', last_connected = ?, last_peer_pid = ? WHERE id = ?",
[id, nowMs, body.pid, slot.id]
);
const recap = db.query(
"SELECT * FROM messages WHERE session_id = ? AND to_slot_id = ? ORDER BY sent_at DESC LIMIT ?"
).all(body.session_id, slot.id, RECONNECT_RECAP_LIMIT) as Message[];
recap.reverse();
const updatedSlot = db.query("SELECT * FROM slots WHERE id = ?").get(slot.id) as Slot;
return { id, slot: updatedSlot, recap };
}
// 0 matches — fall through to create new slot if session exists
}
// Default registration (possibly with session)
let slotResult: Slot | undefined;
let slotId: number | null = null;
if (body.session_id) {
const session = db.query("SELECT id FROM sessions WHERE id = ?").get(body.session_id);
if (session) {
const res = db.run(
"INSERT INTO slots (session_id, agent_type, display_name, role, status, last_connected, last_peer_pid) VALUES (?, ?, ?, ?, 'connected', ?, ?)",
[body.session_id, agentType, body.display_name ?? null, body.role ?? null, nowMs, body.pid]
);
slotId = Number(res.lastInsertRowid);
db.run("UPDATE sessions SET last_active_at = ? WHERE id = ?", [nowMs, body.session_id]);
}
}
insertPeer.run(id, body.pid, body.cwd, body.git_root, body.tty, body.summary, now, now, body.session_id ?? null, slotId, agentType, "idle");
if (slotId !== null) {
db.run("UPDATE slots SET peer_id = ? WHERE id = ?", [id, slotId]);
slotResult = db.query("SELECT * FROM slots WHERE id = ?").get(slotId) as Slot;
}
return slotResult ? { id, slot: slotResult } : { id };
}
function handleHeartbeat(body: HeartbeatRequest): void {
updateLastSeen.run(new Date().toISOString(), body.id);
}
function handleSetSummary(body: SetSummaryRequest): void {
updateSummary.run(body.summary, body.id);
}
function handleListPeers(body: ListPeersRequest): Peer[] {
let peers: Peer[];
switch (body.scope) {
case "machine":
peers = selectAllPeers.all() as Peer[];
break;
case "directory":
peers = selectPeersByDirectory.all(body.cwd) as Peer[];
break;
case "repo":
if (body.git_root) {
peers = selectPeersByGitRoot.all(body.git_root) as Peer[];
} else {
peers = selectPeersByDirectory.all(body.cwd) as Peer[];
}
break;
default:
peers = selectAllPeers.all() as Peer[];
}
// Filter by agent_type
if (body.agent_type && body.agent_type !== "all") {
peers = peers.filter((p) => p.agent_type === body.agent_type);
}
// Filter by session_id
if (body.session_id) {
peers = peers.filter((p) => p.session_id === body.session_id);
}
// Exclude the requesting peer
if (body.exclude_id) {
peers = peers.filter((p) => p.id !== body.exclude_id);
}
// Verify each peer's process is still alive
return peers.filter((p) => {
try {
process.kill(p.pid, 0);
return true;
} catch {
deletePeer.run(p.id);
return false;
}
});
}
function handleSendMessage(body: SendMessageRequest): SendMessageResult {
const now = new Date().toISOString();
let toId = body.to_id;
let toSlotId = body.to_slot_id ?? null;
const msgType = body.msg_type ?? "chat";
const sessionId = body.session_id ?? null;
// Resolve to_slot_id to to_id if needed
if (!toId && toSlotId) {
const slot = db.query("SELECT peer_id FROM slots WHERE id = ?").get(toSlotId) as { peer_id: string | null } | null;
if (!slot) return { ok: false, error: `Slot ${toSlotId} not found` };
// Slot may have no peer_id if managed by CodexDriver — message is stored
// with to_slot_id and picked up by pollBySlot endpoint.
toId = slot.peer_id ?? `__slot_${toSlotId}__`;
}
if (!toId) return { ok: false, error: "No target specified" };
// Allow messages to "orchestrator" and driver-managed slots (no real peer_id)
const isSpecialTarget = toId === "orchestrator" || toId === "__orchestrator__" || toId.startsWith("__slot_");
// Verify target exists (unless targeting orchestrator or driver-managed slot)
if (!isSpecialTarget) {
const target = db.query("SELECT id FROM peers WHERE id = ?").get(toId) as { id: string } | null;
if (!target) return { ok: false, error: `Peer ${toId} not found` };
}
// Determine from_slot_id
let fromSlotId: number | null = null;
const fromPeer = db.query("SELECT slot_id FROM peers WHERE id = ?").get(body.from_id) as { slot_id: number | null } | null;
if (fromPeer) fromSlotId = fromPeer.slot_id;
// Check if target slot is paused
let held = 0;
if (toSlotId) {
const targetSlot = db.query("SELECT paused FROM slots WHERE id = ?").get(toSlotId) as { paused: number } | null;
if (targetSlot?.paused) held = 1;
} else {
// Look up slot from peer
const targetPeer = db.query("SELECT slot_id FROM peers WHERE id = ?").get(toId) as { slot_id: number | null } | null;
if (targetPeer?.slot_id) {
toSlotId = targetPeer.slot_id;
const targetSlot = db.query("SELECT paused FROM slots WHERE id = ?").get(toSlotId) as { paused: number } | null;
if (targetSlot?.paused) held = 1;
}
}
insertMessage.run(body.from_id, toId, body.text, now, sessionId, fromSlotId, toSlotId, msgType, held);
const warning = held ? "Message held — target agent is paused" : undefined;
return { ok: true, warning };
}
function handlePollMessages(body: PollMessagesRequest): PollMessagesResponse {
// Check if the peer's slot is paused
const peer = db.query("SELECT slot_id FROM peers WHERE id = ?").get(body.id) as { slot_id: number | null } | null;
if (peer?.slot_id) {
const slot = db.query("SELECT paused FROM slots WHERE id = ?").get(peer.slot_id) as { paused: number } | null;
if (slot?.paused) {
return { messages: [], paused: true };
}
}
const messages = selectUndelivered.all(body.id) as Message[];
const now = new Date().toISOString();
for (const msg of messages) {
markDelivered.run(now, msg.id);
}
return { messages };
}
/** Poll undelivered messages by slot_id (for driver-managed agents without peer_id). */
function handlePollBySlot(body: { slot_id: number; session_id?: string }): PollMessagesResponse {
const slot = db.query("SELECT paused FROM slots WHERE id = ?").get(body.slot_id) as { paused: number } | null;
if (slot?.paused) return { messages: [], paused: true };
const messages = db.query(
"SELECT * FROM messages WHERE to_slot_id = ? AND delivered = 0 AND held = 0 ORDER BY sent_at ASC"
).all(body.slot_id) as Message[];
const now = new Date().toISOString();
for (const msg of messages) {
markDelivered.run(now, msg.id);
}
return { messages };
}
function handleUnregister(body: { id: string }): { ok: boolean; denied?: boolean; reason?: string; task_state?: string } {
const now = Date.now();
// Look up peer and its slot
const peer = db.query("SELECT slot_id, summary, cwd FROM peers WHERE id = ?").get(body.id) as any;
if (peer?.slot_id) {
// Check task_state gating — in a session, agents can ONLY disconnect when explicitly released
const slot = db.query("SELECT task_state, session_id FROM slots WHERE id = ?").get(peer.slot_id) as any;
if (slot && slot.session_id && slot.task_state !== "released") {
return {
ok: false,
denied: true,
reason: `Cannot disconnect: task_state is '${slot.task_state}'. Only the team lead or orchestrator can release you. Stay active, communicate with your team, and wait for release.`,
task_state: slot.task_state,
};
}
const snapshot = buildContextSnapshot(peer, peer.slot_id);
db.run(
"UPDATE slots SET status = 'disconnected', peer_id = NULL, last_disconnected = ?, context_snapshot = ? WHERE id = ?",
[now, snapshot, peer.slot_id]
);
// Release file locks
db.run("DELETE FROM file_locks WHERE held_by_peer = ?", [body.id]);
}
deletePeer.run(body.id);
return { ok: true };
}
// --- Role & rename ---
function handleSetRole(body: SetRoleRequest): { ok: boolean } {
const slotId = body.slot_id;
if (slotId) {
db.run(
"UPDATE slots SET role = ?, role_description = ?, role_assigned_by = ? WHERE id = ?",
[body.role, body.role_description, body.assigner_id, slotId]
);
}
// Insert system message to target
const now = new Date().toISOString();
const text = JSON.stringify({ role: body.role, role_description: body.role_description });
insertMessage.run(body.assigner_id, body.peer_id, text, now, null, null, slotId ?? null, "role_assignment", 0);
return { ok: true };
}
function handleRenamePeer(body: RenamePeerRequest): { ok: boolean } {
if (body.slot_id) {
db.run("UPDATE slots SET display_name = ? WHERE id = ?", [body.display_name, body.slot_id]);
}
const now = new Date().toISOString();
const text = JSON.stringify({ display_name: body.display_name });
insertMessage.run(body.assigner_id, body.peer_id, text, now, null, null, body.slot_id ?? null, "rename", 0);
return { ok: true };
}
// --- Knowledge Store ---
function handleKnowledgePut(body: KnowledgePutRequest): KnowledgePutResponse {
if (!body.session_id) throw new Error("session_id required");
if (!body.key || !body.key.trim()) throw new Error("key required");
if (!body.value || !body.value.trim()) throw new Error("value required");
const now = Date.now();
const category = body.category ?? "context";
// Check existence first for created/updated distinction, then upsert atomically.
// Both are synchronous bun:sqlite calls in the same event loop tick — no race window.
const existed = db.query("SELECT 1 FROM knowledge WHERE session_id = ? AND key = ?").get(body.session_id, body.key) !== null;
db.run(
`INSERT INTO knowledge (session_id, key, value, category, created_by_slot, created_by_name, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(session_id, key) DO UPDATE SET
value = excluded.value,
category = excluded.category,
created_by_slot = excluded.created_by_slot,
created_by_name = excluded.created_by_name,
updated_at = excluded.updated_at`,
[body.session_id, body.key, body.value, category, body.slot_id ?? null, body.slot_name ?? null, now, now]
);
const entry = db.query("SELECT * FROM knowledge WHERE session_id = ? AND key = ?").get(body.session_id, body.key) as KnowledgeEntry;
return { ok: true, entry, action: existed ? "updated" : "created" };
}
function handleKnowledgeGet(body: KnowledgeGetRequest): KnowledgeEntry | { error: string } {
if (!body.session_id) throw new Error("session_id required");
if (!body.key) throw new Error("key required");
const entry = db.query("SELECT * FROM knowledge WHERE session_id = ? AND key = ?").get(body.session_id, body.key) as KnowledgeEntry | null;
if (!entry) return { error: `No knowledge entry found for key "${body.key}"` };
return entry;
}
function handleKnowledgeList(body: KnowledgeListRequest): KnowledgeEntry[] {
if (!body.session_id) return [];
if (body.category) {
return db.query("SELECT * FROM knowledge WHERE session_id = ? AND category = ? ORDER BY updated_at DESC").all(body.session_id, body.category) as KnowledgeEntry[];
}
return db.query("SELECT * FROM knowledge WHERE session_id = ? ORDER BY updated_at DESC").all(body.session_id) as KnowledgeEntry[];
}
function handleKnowledgeDelete(body: KnowledgeDeleteRequest): { ok: boolean } {
if (!body.session_id) throw new Error("session_id required");
if (!body.key) throw new Error("key required");
db.run("DELETE FROM knowledge WHERE session_id = ? AND key = ?", [body.session_id, body.key]);
return { ok: true };
}
// --- Sessions ---
function handleCreateSession(body: CreateSessionRequest): Session {
const now = Date.now();
db.run(
"INSERT INTO sessions (id, name, project_dir, git_root, status, config, created_at, last_active_at) VALUES (?, ?, ?, ?, 'active', ?, ?, ?)",
[body.id, body.name, body.project_dir, body.git_root ?? null, JSON.stringify(body.config ?? {}), now, now]
);
return db.query("SELECT * FROM sessions WHERE id = ?").get(body.id) as Session;
}
function handleGetSession(body: { id: string }): Session | null {
return (db.query("SELECT * FROM sessions WHERE id = ?").get(body.id) as Session) ?? null;
}
function handleListSessions(): Session[] {
return db.query("SELECT * FROM sessions ORDER BY last_active_at DESC").all() as Session[];
}
function handleDeleteSession(body: { id: string }): { ok: boolean; deleted: { slots: number; messages: number; plans: number; locks: number } } {
const session = db.query("SELECT id FROM sessions WHERE id = ?").get(body.id) as { id: string } | null;
if (!session) return { ok: false, deleted: { slots: 0, messages: 0, plans: 0, locks: 0 } };
// Delete in dependency order: plan_items → plans → messages → file_locks → file_ownership → slots → session
const plans = db.query("SELECT id FROM plans WHERE session_id = ?").all(body.id) as { id: number }[];
for (const plan of plans) {
db.run("DELETE FROM plan_items WHERE plan_id = ?", [plan.id]);
}
const planCount = plans.length;
db.run("DELETE FROM plans WHERE session_id = ?", [body.id]);
const msgResult = db.run("DELETE FROM messages WHERE session_id = ?", [body.id]);
const msgCount = msgResult.changes;
db.run("DELETE FROM file_locks WHERE session_id = ?", [body.id]);
db.run("DELETE FROM file_ownership WHERE session_id = ?", [body.id]);
// Delete peers associated with this session's slots
const slots = db.query("SELECT id, peer_id FROM slots WHERE session_id = ?").all(body.id) as { id: number; peer_id: string | null }[];
for (const slot of slots) {
if (slot.peer_id) {
db.run("DELETE FROM peers WHERE id = ?", [slot.peer_id]);
}
}
const slotResult = db.run("DELETE FROM slots WHERE session_id = ?", [body.id]);
const slotCount = slotResult.changes;
// Delete guardrail overrides and events
db.run("DELETE FROM guardrail_overrides WHERE session_id = ?", [body.id]);
db.run("DELETE FROM guardrail_events WHERE session_id = ?", [body.id]);
// Delete knowledge entries
db.run("DELETE FROM knowledge WHERE session_id = ?", [body.id]);
db.run("DELETE FROM sessions WHERE id = ?", [body.id]);
return { ok: true, deleted: { slots: slotCount, messages: msgCount, plans: planCount, locks: 0 } };
}
function handleUpdateSession(body: UpdateSessionRequest): Session | null {
const fields: string[] = [];
const values: any[] = [];
if (body.status !== undefined) { fields.push("status = ?"); values.push(body.status); }
if (body.pause_reason !== undefined) { fields.push("pause_reason = ?"); values.push(body.pause_reason); }
if (body.paused_at !== undefined) { fields.push("paused_at = ?"); values.push(body.paused_at); }
if (body.config !== undefined) { fields.push("config = ?"); values.push(JSON.stringify(body.config)); }
fields.push("last_active_at = ?");
values.push(Date.now());
values.push(body.id);
if (fields.length > 0) {
db.run(`UPDATE sessions SET ${fields.join(", ")} WHERE id = ?`, values);
}
return (db.query("SELECT * FROM sessions WHERE id = ?").get(body.id) as Session) ?? null;
}
// --- Slots ---
function handleCreateSlot(body: CreateSlotRequest): Slot {
const res = db.run(
"INSERT INTO slots (session_id, agent_type, display_name, role, role_description) VALUES (?, ?, ?, ?, ?)",
[body.session_id, body.agent_type, body.display_name ?? null, body.role ?? null, body.role_description ?? null]
);
return db.query("SELECT * FROM slots WHERE id = ?").get(Number(res.lastInsertRowid)) as Slot;
}
function handleGetSlot(body: { id: number }): Slot | null {
return (db.query("SELECT * FROM slots WHERE id = ?").get(body.id) as Slot) ?? null;
}
function handleListSlots(body: { session_id: string }): Slot[] {
return db.query("SELECT * FROM slots WHERE session_id = ?").all(body.session_id) as Slot[];
}
function handleUpdateSlot(body: UpdateSlotRequest): Slot | null {
const fields: string[] = [];
const values: any[] = [];
if (body.peer_id !== undefined) { fields.push("peer_id = ?"); values.push(body.peer_id); }
if (body.paused !== undefined) { fields.push("paused = ?"); values.push(body.paused ? 1 : 0); }
if (body.paused_at !== undefined) { fields.push("paused_at = ?"); values.push(body.paused_at); }
// Only accept valid slot statuses — reject "archived" or other ghost values
if (body.status !== undefined && (body.status === "connected" || body.status === "disconnected")) {
fields.push("status = ?"); values.push(body.status);
// Auto-set last_disconnected when transitioning to disconnected.
// Without this, the auto-cleanup loop uses last_connected as fallback,
// which makes slots that ran for >5 min look like they've been dead
// for >5 min and get deleted immediately.
if (body.status === "disconnected") {
fields.push("last_disconnected = ?"); values.push(Date.now());
} else {
fields.push("last_connected = ?"); values.push(Date.now());
}
}
if (body.context_snapshot !== undefined) { fields.push("context_snapshot = ?"); values.push(body.context_snapshot); }
if (body.display_name !== undefined) { fields.push("display_name = ?"); values.push(body.display_name); }
if (body.role !== undefined) { fields.push("role = ?"); values.push(body.role); }
if (body.role_description !== undefined) { fields.push("role_description = ?"); values.push(body.role_description); }
if (body.task_state !== undefined) { fields.push("task_state = ?"); values.push(body.task_state); }
if (body.input_tokens !== undefined) { fields.push("input_tokens = input_tokens + ?"); values.push(body.input_tokens); }
if (body.output_tokens !== undefined) { fields.push("output_tokens = output_tokens + ?"); values.push(body.output_tokens); }
if (body.cache_read_tokens !== undefined) { fields.push("cache_read_tokens = cache_read_tokens + ?"); values.push(body.cache_read_tokens); }
if (fields.length > 0) {
values.push(body.id);
db.run(`UPDATE slots SET ${fields.join(", ")} WHERE id = ?`, values);
}
if (body.peer_id !== undefined && body.peer_id !== null) {
const slot = db.query("SELECT session_id FROM slots WHERE id = ?").get(body.id) as { session_id: string } | null;
if (slot) {
db.run("UPDATE peers SET slot_id = ?, session_id = ? WHERE id = ?", [body.id, slot.session_id, body.peer_id]);
}
}
return (db.query("SELECT * FROM slots WHERE id = ?").get(body.id) as Slot) ?? null;
}
/** Delete a slot and its associated file locks, ownership, and orphaned peer. */
function handleDeleteSlot(body: { id: number }): { ok: boolean; deleted: boolean } {
const existing = db.query("SELECT id, peer_id FROM slots WHERE id = ?").get(body.id) as { id: number; peer_id: string | null } | null;
if (!existing) return { ok: true, deleted: false };
// Clean up associated data (file_locks uses "held_by_slot", not "slot_id")
db.run("DELETE FROM file_locks WHERE held_by_slot = ?", [body.id]);
db.run("DELETE FROM file_ownership WHERE slot_id = ?", [body.id]);
// Remove the orphaned peer record if any
if (existing.peer_id) {
db.run("DELETE FROM peers WHERE id = ?", [existing.peer_id]);
}
db.run("DELETE FROM slots WHERE id = ?", [body.id]);
return { ok: true, deleted: true };
}
// --- File locks & ownership ---
function handleAcquireFile(body: AcquireFileRequest): AcquireFileResult {
const now = Date.now();
const timeout = Math.min(body.timeout_ms ?? DEFAULT_LOCK_TIMEOUT_MS, MAX_LOCK_TIMEOUT_MS);
const expiresAt = now + timeout;
// Normalize the file path and strip leading ../ segments
const filePath = normalize(body.file_path).replace(/^(\.\.[/\\])+/, "");
// Check ownership zones — deny if file matches another slot's pattern
const ownerships = db.query(
"SELECT * FROM file_ownership WHERE session_id = ? AND slot_id != ?"
).all(body.session_id, body.slot_id) as FileOwnership[];
for (const own of ownerships) {
if (fileMatchesPattern(filePath, own.path_pattern)) {
const ownerSlot = db.query("SELECT display_name FROM slots WHERE id = ?").get(own.slot_id) as { display_name: string | null } | null;
return {
status: "denied",
owner: ownerSlot?.display_name ?? `slot-${own.slot_id}`,
pattern: own.path_pattern,
message: `File is in ownership zone of ${ownerSlot?.display_name ?? `slot-${own.slot_id}`} (pattern: ${own.path_pattern})`,
};
}
}
// Check existing locks
const existing = db.query(
"SELECT * FROM file_locks WHERE session_id = ? AND file_path = ? AND expires_at > ?"
).get(body.session_id, filePath, now) as FileLock | null;
if (existing) {
if (existing.held_by_slot === body.slot_id) {
// Extend
db.run("UPDATE file_locks SET expires_at = ? WHERE id = ?", [expiresAt, existing.id]);
return { status: "extended", expires_at: expiresAt, message: "Lock extended" };
}
const holderSlot = db.query("SELECT display_name FROM slots WHERE id = ?").get(existing.held_by_slot) as { display_name: string | null } | null;
return {
status: "locked",
held_by: holderSlot?.display_name ?? `slot-${existing.held_by_slot}`,
expires_at: existing.expires_at,
wait_estimate_ms: existing.expires_at - now,
message: `File locked by ${holderSlot?.display_name ?? `slot-${existing.held_by_slot}`}`,
};
}
// Acquire
db.run(
"INSERT INTO file_locks (session_id, file_path, held_by_slot, held_by_peer, acquired_at, expires_at, lock_type, purpose) VALUES (?, ?, ?, ?, ?, ?, 'exclusive', ?)",
[body.session_id, filePath, body.slot_id, body.peer_id, now, expiresAt, body.purpose ?? null]
);
return { status: "acquired", expires_at: expiresAt, message: "Lock acquired" };
}
function handleReleaseFile(body: ReleaseFileRequest): { ok: boolean } {
// Normalize the file path and strip leading ../ segments
const filePath = normalize(body.file_path).replace(/^(\.\.[/\\])+/, "");
db.run(
"DELETE FROM file_locks WHERE session_id = ? AND file_path = ? AND held_by_peer = ?",
[body.session_id, filePath, body.peer_id]
);
return { ok: true };
}
function handleAssignOwnership(body: AssignOwnershipRequest): { ok: boolean; status: string; message?: string } {
for (const pattern of body.path_patterns) {
// Check for overlapping patterns from other slots
const conflict = db.query(
"SELECT * FROM file_ownership WHERE session_id = ? AND slot_id != ? AND path_pattern = ?"
).get(body.session_id, body.slot_id, pattern) as FileOwnership | null;
if (conflict) {
return {
ok: false,
status: "conflict",
message: `Pattern "${pattern}" already assigned to slot ${conflict.slot_id}`,
};
}
}
for (const pattern of body.path_patterns) {
db.run(
"INSERT OR REPLACE INTO file_ownership (session_id, slot_id, path_pattern, assigned_at, assigned_by) VALUES (?, ?, ?, ?, ?)",
[body.session_id, body.slot_id, pattern, Date.now(), body.assigned_by]
);
}
return { ok: true, status: "assigned" };
}
function handleListLocks(body: { session_id: string }): FileLock[] {
const now = Date.now();
return db.query(
"SELECT * FROM file_locks WHERE session_id = ? AND expires_at > ?"
).all(body.session_id, now) as FileLock[];
}
function handleListOwnership(body: { session_id: string }): FileOwnership[] {