murmur-it 0.0.0-stage → 0.2.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.
package/dist/broker.js ADDED
@@ -0,0 +1,1050 @@
1
+ import { chmodSync, existsSync, unlinkSync } from 'node:fs';
2
+ import { createConnection, createServer } from 'node:net';
3
+ import { StringDecoder } from 'node:string_decoder';
4
+ import { readToken } from './config.js';
5
+ import { fullOf } from './core.js';
6
+ import { nativeSend } from './native.js';
7
+ import { ProofWatcher } from './proof.js';
8
+ import { defaultWake } from './wake.js';
9
+ import { LineReader, MurmurError, NOTIFY_BATCH_MS, PROTOCOL_VERSION, WAIT_MAX_MS, encodeLine, renderDelivery, replyFooter, } from './protocol.js';
10
+ const CLIENT_KINDS = ['mcp', 'cli', 'hook', 'adapter'];
11
+ const HOOK_EVENTS = ['session-start', 'prompt', 'stop', 'session-end'];
12
+ const CLI_NAMES = ['claude', 'codex', 'gemini', 'zcode', 'opencode', 'hummin', 'other'];
13
+ const DELIVERY_MODES = ['push', 'notify', 'silent'];
14
+ const VERDICTS = ['agree', 'disagree', 'info'];
15
+ const GROUP_ACTIONS = ['create', 'list', 'add', 'remove', 'delete'];
16
+ const WAIT_UNTILS = ['all_replied', 'any_replied'];
17
+ // Wire guard: no single request line may exceed 1 MiB.
18
+ const MAX_LINE_BYTES = 1024 * 1024;
19
+ function badRequest(message) {
20
+ return new MurmurError('bad_request', message);
21
+ }
22
+ function reqString(rec, key) {
23
+ const value = rec[key];
24
+ if (typeof value !== 'string') {
25
+ throw badRequest(key + ' must be a string');
26
+ }
27
+ return value;
28
+ }
29
+ function optString(rec, key) {
30
+ if (rec[key] === undefined) {
31
+ return undefined;
32
+ }
33
+ return reqString(rec, key);
34
+ }
35
+ function reqNumber(rec, key) {
36
+ const value = rec[key];
37
+ if (typeof value !== 'number') {
38
+ throw badRequest(key + ' must be a number');
39
+ }
40
+ return value;
41
+ }
42
+ function reqNumberOrNull(rec, key) {
43
+ const value = rec[key];
44
+ if (value === null) {
45
+ return null;
46
+ }
47
+ return reqNumber(rec, key);
48
+ }
49
+ function reqBool(rec, key) {
50
+ const value = rec[key];
51
+ if (typeof value !== 'boolean') {
52
+ throw badRequest(key + ' must be a boolean');
53
+ }
54
+ return value;
55
+ }
56
+ function reqStringArray(rec, key) {
57
+ const value = rec[key];
58
+ if (!Array.isArray(value)) {
59
+ throw badRequest(key + ' must be an array of strings');
60
+ }
61
+ for (const item of value) {
62
+ if (typeof item !== 'string') {
63
+ throw badRequest(key + ' must be an array of strings');
64
+ }
65
+ }
66
+ return value;
67
+ }
68
+ function optStringArray(rec, key) {
69
+ if (rec[key] === undefined) {
70
+ return undefined;
71
+ }
72
+ return reqStringArray(rec, key);
73
+ }
74
+ function reqNumberArray(rec, key) {
75
+ const value = rec[key];
76
+ if (!Array.isArray(value)) {
77
+ throw badRequest(key + ' must be an array of numbers');
78
+ }
79
+ for (const item of value) {
80
+ if (typeof item !== 'number') {
81
+ throw badRequest(key + ' must be an array of numbers');
82
+ }
83
+ }
84
+ return value;
85
+ }
86
+ function optNumberArray(rec, key) {
87
+ if (rec[key] === undefined) {
88
+ return undefined;
89
+ }
90
+ return reqNumberArray(rec, key);
91
+ }
92
+ function optBool(rec, key) {
93
+ if (rec[key] === undefined) {
94
+ return undefined;
95
+ }
96
+ return reqBool(rec, key);
97
+ }
98
+ function reqHost(value) {
99
+ if (typeof value !== 'object' || value === null) {
100
+ throw badRequest('host must be an object');
101
+ }
102
+ const rec = value;
103
+ return { hostPid: reqNumber(rec, 'hostPid'), hostStart: reqString(rec, 'hostStart') };
104
+ }
105
+ function reqEnum(rec, key, allowed) {
106
+ const value = rec[key];
107
+ if (typeof value !== 'string' || !allowed.includes(value)) {
108
+ throw badRequest(key + ' must be one of: ' + allowed.join(', '));
109
+ }
110
+ return value;
111
+ }
112
+ function optEnum(rec, key, allowed) {
113
+ if (rec[key] === undefined) {
114
+ return undefined;
115
+ }
116
+ return reqEnum(rec, key, allowed);
117
+ }
118
+ export class Broker {
119
+ server;
120
+ paths;
121
+ store;
122
+ core;
123
+ nativeSendFn;
124
+ wakeFn;
125
+ proof;
126
+ // Live bindings: handle to its long-lived connection (mcp or adapter).
127
+ presence = new Map();
128
+ conns = new Set();
129
+ // Recipient to pending notification payloads, one flush timer per recipient.
130
+ notifyQueue = new Map();
131
+ // Thread id to waiters registered against that thread.
132
+ waiters = new Map();
133
+ stopped = false;
134
+ stopPromise = null;
135
+ constructor(opts, server) {
136
+ this.server = server;
137
+ this.paths = opts.paths;
138
+ this.store = opts.store;
139
+ this.core = opts.core;
140
+ this.nativeSendFn = opts.nativeSend ?? nativeSend;
141
+ this.wakeFn = opts.wake ?? defaultWake;
142
+ this.proof = new ProofWatcher((messageId, recipient) => this.onProof(messageId, recipient), opts.proofPollMs);
143
+ }
144
+ static async start(opts) {
145
+ const server = createServer();
146
+ let broker = null;
147
+ // Attached before listen so no connection can arrive unhandled.
148
+ server.on('connection', (socket) => {
149
+ if (broker === null) {
150
+ socket.destroy();
151
+ return;
152
+ }
153
+ broker.onConnection(socket);
154
+ });
155
+ await clearStaleSocket(opts.paths.socketPath);
156
+ await new Promise((resolve, reject) => {
157
+ server.once('error', reject);
158
+ server.listen(opts.paths.socketPath, () => resolve());
159
+ });
160
+ try {
161
+ chmodSync(opts.paths.socketPath, 0o600);
162
+ }
163
+ catch (err) {
164
+ server.close();
165
+ throw new Error('murmur: cannot set mode 0600 on socket ' + opts.paths.socketPath + ': ' + err.message);
166
+ }
167
+ // Yield two macrotask turns before the instance exists: a client that
168
+ // dials the socket in this window is accepted and then destroyed by the
169
+ // guard above, so it retries against a fully started broker instead of a
170
+ // half-built one.
171
+ for (let i = 0; i < 2; i += 1) {
172
+ await new Promise((resolve) => {
173
+ setImmediate(resolve);
174
+ });
175
+ }
176
+ broker = new Broker(opts, server);
177
+ // Server errors after a successful listen are rare; swallow them so an
178
+ // idle accept failure cannot crash the process. Connection cleanup runs
179
+ // through each socket's own close handler.
180
+ server.on('error', () => {
181
+ // no-op
182
+ });
183
+ return broker;
184
+ }
185
+ async stop() {
186
+ if (this.stopPromise !== null) {
187
+ return this.stopPromise;
188
+ }
189
+ this.stopPromise = this.stopInner();
190
+ return this.stopPromise;
191
+ }
192
+ async stopInner() {
193
+ this.stopped = true;
194
+ this.proof.stop();
195
+ for (const set of this.waiters.values()) {
196
+ for (const waiter of set) {
197
+ clearTimeout(waiter.timer);
198
+ waiter.conn.waiters.delete(waiter);
199
+ }
200
+ }
201
+ this.waiters.clear();
202
+ for (const entry of this.notifyQueue.values()) {
203
+ clearTimeout(entry.timer);
204
+ }
205
+ this.notifyQueue.clear();
206
+ for (const conn of [...this.conns]) {
207
+ conn.socket.destroy();
208
+ }
209
+ this.conns.clear();
210
+ this.presence.clear();
211
+ await new Promise((resolve) => {
212
+ this.server.close(() => resolve());
213
+ });
214
+ }
215
+ // Connection lifecycle.
216
+ onConnection(socket) {
217
+ const conn = {
218
+ socket,
219
+ decoder: new StringDecoder('utf8'),
220
+ reader: new LineReader(),
221
+ authenticated: false,
222
+ handle: null,
223
+ live: false,
224
+ listening: false,
225
+ pendingHost: null,
226
+ pendingBytes: 0,
227
+ waiters: new Set(),
228
+ chain: Promise.resolve(),
229
+ };
230
+ this.conns.add(conn);
231
+ socket.on('data', (chunk) => {
232
+ this.onSocketData(conn, chunk);
233
+ });
234
+ socket.on('error', () => {
235
+ // Socket errors surface as a close; cleanup happens there.
236
+ });
237
+ socket.on('close', () => {
238
+ this.onSocketClose(conn);
239
+ });
240
+ }
241
+ onSocketData(conn, chunk) {
242
+ // Byte exact line length guard: every complete line in this chunk, plus
243
+ // the trailing partial line, must stay under 1 MiB.
244
+ let offset = 0;
245
+ for (;;) {
246
+ const nl = chunk.indexOf(0x0a, offset);
247
+ if (nl === -1) {
248
+ break;
249
+ }
250
+ if (conn.pendingBytes + (nl - offset) > MAX_LINE_BYTES) {
251
+ this.rejectOversizedLine(conn);
252
+ return;
253
+ }
254
+ conn.pendingBytes = 0;
255
+ offset = nl + 1;
256
+ }
257
+ conn.pendingBytes += chunk.byteLength - offset;
258
+ if (conn.pendingBytes > MAX_LINE_BYTES) {
259
+ this.rejectOversizedLine(conn);
260
+ return;
261
+ }
262
+ const text = conn.decoder.write(chunk);
263
+ for (const line of conn.reader.feed(text)) {
264
+ conn.chain = conn.chain.then(() => this.dispatchLine(conn, line));
265
+ }
266
+ }
267
+ rejectOversizedLine(conn) {
268
+ this.replyErr(conn.socket, 0, 'internal', 'line exceeds the 1 MiB limit');
269
+ conn.socket.destroy();
270
+ }
271
+ onSocketClose(conn) {
272
+ this.conns.delete(conn);
273
+ for (const waiter of [...conn.waiters]) {
274
+ clearTimeout(waiter.timer);
275
+ this.removeWaiter(waiter);
276
+ }
277
+ if (conn.handle !== null && this.presence.get(conn.handle) === conn) {
278
+ this.presence.delete(conn.handle);
279
+ }
280
+ // Stamp nothing on close; only register refreshes last_seen_at. Only a
281
+ // long-lived connection going away means the peer went away.
282
+ if (conn.handle !== null && conn.live && !this.stopped) {
283
+ this.notifyPeerOffline(conn.handle);
284
+ }
285
+ }
286
+ async dispatchLine(conn, line) {
287
+ if (this.stopped || conn.socket.destroyed) {
288
+ return;
289
+ }
290
+ let parsed;
291
+ try {
292
+ parsed = JSON.parse(line);
293
+ }
294
+ catch (err) {
295
+ this.replyErr(conn.socket, 0, 'bad_request', 'line is not valid JSON: ' + err.message);
296
+ return;
297
+ }
298
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
299
+ this.replyErr(conn.socket, 0, 'bad_request', 'line must be a JSON object');
300
+ return;
301
+ }
302
+ const rec = parsed;
303
+ const id = typeof rec.id === 'number' ? rec.id : 0;
304
+ if (!conn.authenticated) {
305
+ this.handleAuthLine(conn, rec, id);
306
+ return;
307
+ }
308
+ try {
309
+ await this.handleMessage(conn, rec, id);
310
+ }
311
+ catch (err) {
312
+ if (err instanceof MurmurError) {
313
+ this.replyErr(conn.socket, id, err.code, err.message);
314
+ }
315
+ else {
316
+ this.replyErr(conn.socket, id, 'internal', err instanceof Error ? err.message : String(err));
317
+ }
318
+ }
319
+ }
320
+ handleAuthLine(conn, rec, id) {
321
+ const type = typeof rec.type === 'string' ? rec.type : '';
322
+ if (type !== 'auth') {
323
+ this.replyErr(conn.socket, id, 'auth_required', 'authenticate with a token before anything else');
324
+ conn.socket.destroy();
325
+ return;
326
+ }
327
+ let expected;
328
+ try {
329
+ expected = readToken(this.paths);
330
+ }
331
+ catch (err) {
332
+ const code = err instanceof MurmurError ? err.code : 'internal';
333
+ this.replyErr(conn.socket, id, code, err instanceof Error ? err.message : String(err));
334
+ conn.socket.destroy();
335
+ return;
336
+ }
337
+ const token = rec.token;
338
+ if (typeof token !== 'string' || token !== expected) {
339
+ this.replyErr(conn.socket, id, 'bad_token', 'invalid token');
340
+ conn.socket.destroy();
341
+ return;
342
+ }
343
+ conn.authenticated = true;
344
+ this.replyOk(conn.socket, id, null);
345
+ }
346
+ // Dispatch by type. Every handler path is inside the caller's try, so an
347
+ // unexpected throw lands in the wrap: MurmurError keeps its code, anything
348
+ // else becomes internal.
349
+ async handleMessage(conn, rec, id) {
350
+ const type = typeof rec.type === 'string' ? rec.type : '';
351
+ switch (type) {
352
+ case 'auth':
353
+ throw badRequest('connection is already authenticated');
354
+ case 'register':
355
+ this.replyOk(conn.socket, id, this.handleRegister(conn, rec));
356
+ return;
357
+ case 'hook':
358
+ this.replyOk(conn.socket, id, this.handleHook(conn, rec));
359
+ return;
360
+ case 'session': {
361
+ const result = await this.handleSession(conn, rec);
362
+ this.replyOk(conn.socket, id, result);
363
+ return;
364
+ }
365
+ case 'delivered':
366
+ this.replyOk(conn.socket, id, this.handleDelivered(conn, rec));
367
+ return;
368
+ case 'native-register':
369
+ this.replyOk(conn.socket, id, this.handleNativeRegister(rec));
370
+ return;
371
+ case 'send': {
372
+ const result = await this.handleSend(conn, rec);
373
+ this.replyOk(conn.socket, id, result);
374
+ return;
375
+ }
376
+ case 'reply': {
377
+ const result = await this.handleReply(conn, rec);
378
+ this.replyOk(conn.socket, id, result);
379
+ return;
380
+ }
381
+ case 'ack':
382
+ this.replyOk(conn.socket, id, this.handleAck(conn, rec));
383
+ return;
384
+ case 'read':
385
+ this.replyOk(conn.socket, id, this.handleRead(conn, rec));
386
+ return;
387
+ case 'inbox':
388
+ this.replyOk(conn.socket, id, this.handleInbox(conn, rec));
389
+ return;
390
+ case 'thread':
391
+ this.replyOk(conn.socket, id, this.handleThread(rec));
392
+ return;
393
+ case 'collect':
394
+ this.replyOk(conn.socket, id, this.handleCollect(rec));
395
+ return;
396
+ case 'wait':
397
+ // Replies itself: immediately when met, otherwise from a timer.
398
+ this.handleWait(conn, rec, id);
399
+ return;
400
+ case 'groups':
401
+ this.replyOk(conn.socket, id, this.handleGroups(rec));
402
+ return;
403
+ case 'status':
404
+ this.replyOk(conn.socket, id, this.handleStatus());
405
+ return;
406
+ case 'fetch-push':
407
+ this.replyOk(conn.socket, id, this.handleFetchPush(rec));
408
+ return;
409
+ default:
410
+ throw badRequest('unknown message type: ' + String(rec.type));
411
+ }
412
+ }
413
+ // Handlers.
414
+ // See RegisterMessage for the identity rules.
415
+ handleRegister(conn, rec) {
416
+ const kind = reqEnum(rec, 'clientKind', CLIENT_KINDS);
417
+ const handle = optString(rec, 'handle');
418
+ const display = optString(rec, 'display');
419
+ const role = optString(rec, 'role');
420
+ const host = rec.host === undefined ? undefined : reqHost(rec.host);
421
+ const ancestors = optNumberArray(rec, 'ancestors');
422
+ const client = optEnum(rec, 'client', CLI_NAMES) ?? 'other';
423
+ const cwd = optString(rec, 'cwd');
424
+ const owner = optBool(rec, 'owner') === true;
425
+ const live = kind === 'mcp' || kind === 'adapter';
426
+ let resolved;
427
+ if (owner) {
428
+ resolved = this.ownerHandle();
429
+ }
430
+ else if (host !== undefined) {
431
+ const session = this.core.sessionForHost(host);
432
+ if (session === null) {
433
+ if (handle !== undefined) {
434
+ throw badRequest('this session has not announced itself yet (no hook has run); name it after its first prompt');
435
+ }
436
+ // No hook announced this host yet: bind when one does, or on first use.
437
+ conn.live = live;
438
+ conn.pendingHost = { host, client, ...(cwd !== undefined ? { cwd } : {}) };
439
+ return { handle: '', owner: false };
440
+ }
441
+ resolved = handle === undefined ? session.handle : this.core.renameSession(session, handle);
442
+ }
443
+ else if (ancestors !== undefined && handle === undefined) {
444
+ resolved = this.core.sessionForAncestors(ancestors)?.handle ?? this.ownerHandle();
445
+ }
446
+ else if (handle !== undefined) {
447
+ resolved = this.core.register({ handle }).handle;
448
+ }
449
+ else {
450
+ throw badRequest('register needs a handle, a host, ancestors or owner');
451
+ }
452
+ if (display !== undefined || role !== undefined) {
453
+ const peer = this.store.getPeer(resolved);
454
+ this.store.upsertPeer(resolved, display ?? null, role ?? null, peer?.isOwner === true, Date.now());
455
+ }
456
+ this.bind(conn, resolved, live);
457
+ this.core.touchSeen(resolved);
458
+ return { handle: resolved, owner: this.store.getPeer(resolved)?.isOwner === true };
459
+ }
460
+ ownerHandle() {
461
+ const owner = this.store.listPeers().find((peer) => peer.isOwner);
462
+ if (owner === undefined) {
463
+ throw badRequest('no owner peer; run murmur init');
464
+ }
465
+ return owner.handle;
466
+ }
467
+ handleHook(conn, rec) {
468
+ const event = reqEnum(rec, 'event', HOOK_EVENTS);
469
+ const handle = reqString(rec, 'handle');
470
+ // sessionHint rides on the wire; core.hookState has no use for it.
471
+ optString(rec, 'sessionHint');
472
+ // hookState creates the peer row when the handle is new (ensurePeer).
473
+ this.core.hookState(handle, event);
474
+ this.bind(conn, handle, false);
475
+ return null;
476
+ }
477
+ async handleSession(conn, rec) {
478
+ const event = reqEnum(rec, 'event', HOOK_EVENTS);
479
+ const client = reqEnum(rec, 'client', CLI_NAMES);
480
+ const cliSessionId = rec.cliSessionId === null ? null : reqString(rec, 'cliSessionId');
481
+ const host = reqHost(rec.host);
482
+ const transcriptPath = optString(rec, 'transcriptPath');
483
+ const cwd = optString(rec, 'cwd');
484
+ const handle = optString(rec, 'handle');
485
+ const listen = optBool(rec, 'listen') === true;
486
+ let native;
487
+ if (rec.native !== undefined) {
488
+ if (typeof rec.native !== 'object' || rec.native === null) {
489
+ throw badRequest('native must be an object');
490
+ }
491
+ const nat = rec.native;
492
+ native = { socketPath: reqString(nat, 'socketPath'), token: reqString(nat, 'token') };
493
+ }
494
+ const session = this.core.sessionEvent({
495
+ event,
496
+ client,
497
+ cliSessionId,
498
+ host,
499
+ ...(transcriptPath !== undefined ? { transcriptPath } : {}),
500
+ ...(cwd !== undefined ? { cwd } : {}),
501
+ ...(handle !== undefined ? { handle } : {}),
502
+ ...(native !== undefined ? { native } : {}),
503
+ });
504
+ conn.listening = listen;
505
+ this.bind(conn, session.handle, listen);
506
+ // MCP servers of this session that registered before it announced itself.
507
+ for (const other of this.conns) {
508
+ const pending = other.pendingHost;
509
+ if (pending !== null && pending.host.hostPid === host.hostPid && pending.host.hostStart === host.hostStart) {
510
+ this.bind(other, session.handle, other.live);
511
+ }
512
+ }
513
+ if (event === 'session-end') {
514
+ this.notifyPeerOffline(session.handle);
515
+ return { handle: session.handle };
516
+ }
517
+ this.proof.recheck(session.handle);
518
+ if (event === 'session-start' || listen) {
519
+ // A session that comes (back) up gets what waited for it.
520
+ await this.pushQueued(session.handle);
521
+ }
522
+ return { handle: session.handle };
523
+ }
524
+ // An adapter reports that its session accepted these pushed messages.
525
+ handleDelivered(conn, rec) {
526
+ const handle = this.requireBoundHandle(conn);
527
+ const ids = reqNumberArray(rec, 'ids');
528
+ const delivered = [];
529
+ for (const messageId of ids) {
530
+ if (this.markDeliveredHop(messageId, handle)) {
531
+ delivered.push(messageId);
532
+ }
533
+ }
534
+ return { delivered };
535
+ }
536
+ handleNativeRegister(rec) {
537
+ const handle = reqString(rec, 'handle');
538
+ const socketPath = reqString(rec, 'socketPath');
539
+ const token = reqString(rec, 'token');
540
+ this.core.registerNative({ handle, socketPath, token });
541
+ return null;
542
+ }
543
+ async handleSend(conn, rec) {
544
+ const sender = this.requireBoundHandle(conn);
545
+ const threadId = reqNumberOrNull(rec, 'threadId');
546
+ const to = reqStringArray(rec, 'to');
547
+ const body = reqString(rec, 'body');
548
+ const references = optStringArray(rec, 'references');
549
+ const mode = optEnum(rec, 'mode', DELIVERY_MODES);
550
+ const arg = {
551
+ threadId,
552
+ to,
553
+ body,
554
+ };
555
+ if (references !== undefined) {
556
+ arg.references = references;
557
+ }
558
+ if (mode !== undefined) {
559
+ arg.mode = mode;
560
+ }
561
+ const { result, pushes } = this.core.send(sender, arg);
562
+ // Pushes run before the reply so the sender sees the states they left.
563
+ await this.executePushes(pushes);
564
+ result.deliveries = this.core.deliveriesOf(result.messageId);
565
+ if (mode === 'notify') {
566
+ for (const delivery of result.deliveries) {
567
+ if (delivery.recipient === sender) {
568
+ continue;
569
+ }
570
+ this.enqueueNotification(delivery.recipient, {
571
+ kind: 'reply_arrived',
572
+ threadId: result.threadId,
573
+ fromHandle: sender,
574
+ detail: 'new message from ' + sender + ' in thread ' + String(result.threadId),
575
+ });
576
+ }
577
+ }
578
+ this.checkWaiters(result.threadId);
579
+ return result;
580
+ }
581
+ async handleReply(conn, rec) {
582
+ const sender = this.requireBoundHandle(conn);
583
+ const messageId = reqNumber(rec, 'messageId');
584
+ const body = reqString(rec, 'body');
585
+ const verdict = optEnum(rec, 'verdict', VERDICTS);
586
+ const references = optStringArray(rec, 'references');
587
+ const arg = { messageId, body };
588
+ if (verdict !== undefined) {
589
+ arg.verdict = verdict;
590
+ }
591
+ if (references !== undefined) {
592
+ arg.references = references;
593
+ }
594
+ const { result, pushes } = this.core.reply(sender, arg);
595
+ // The reply itself travels to every participant; notify mode leaves
596
+ // them a small note instead.
597
+ await this.executePushes(pushes);
598
+ const notify = this.store.messageById(result.messageId)?.mode === 'notify';
599
+ for (const target of notify ? pushes : []) {
600
+ this.enqueueNotification(target.recipient, {
601
+ kind: 'reply_arrived',
602
+ threadId: result.threadId,
603
+ fromHandle: sender,
604
+ detail: 'reply from ' + sender + ' in thread ' + String(result.threadId),
605
+ });
606
+ }
607
+ this.checkWaiters(result.threadId);
608
+ return result;
609
+ }
610
+ handleAck(conn, rec) {
611
+ const handle = this.requireBoundHandle(conn);
612
+ const ids = reqNumberArray(rec, 'ids');
613
+ // Mirror core.ack's eligibility filter (a delivery row for this handle in
614
+ // delivered or sent) so the reply can carry the acknowledged ids, which
615
+ // is the shape AckResult promises.
616
+ const acknowledged = [];
617
+ const threadIds = new Set();
618
+ for (const messageId of ids) {
619
+ const message = this.store.messageById(messageId);
620
+ if (message === null) {
621
+ continue;
622
+ }
623
+ const delivery = this.store.getDeliveries(messageId).find((d) => d.recipient === handle);
624
+ if (delivery === undefined || (delivery.state !== 'delivered' && delivery.state !== 'sent')) {
625
+ continue;
626
+ }
627
+ acknowledged.push(messageId);
628
+ threadIds.add(message.threadId);
629
+ }
630
+ this.core.ack(handle, ids);
631
+ for (const threadId of threadIds) {
632
+ this.checkWaiters(threadId);
633
+ }
634
+ return { acknowledged };
635
+ }
636
+ handleRead(conn, rec) {
637
+ const handle = this.requireBoundHandle(conn);
638
+ const ids = reqNumberArray(rec, 'ids');
639
+ const messages = this.core.read(handle, ids);
640
+ for (const message of messages) {
641
+ this.checkWaiters(message.threadId);
642
+ }
643
+ return { messages };
644
+ }
645
+ handleInbox(conn, rec) {
646
+ const handle = this.requireBoundHandle(conn);
647
+ const unreadOnly = reqBool(rec, 'unreadOnly');
648
+ return this.core.inbox(handle, unreadOnly);
649
+ }
650
+ handleThread(rec) {
651
+ const threadId = reqNumber(rec, 'threadId');
652
+ const sinceSeq = reqNumberOrNull(rec, 'sinceSeq');
653
+ return this.core.threadView(threadId, sinceSeq, reqBool(rec, 'full'));
654
+ }
655
+ handleCollect(rec) {
656
+ const threadId = reqNumber(rec, 'threadId');
657
+ return this.core.collect(threadId);
658
+ }
659
+ handleGroups(rec) {
660
+ const action = reqEnum(rec, 'action', GROUP_ACTIONS);
661
+ const name = optString(rec, 'name');
662
+ const members = optStringArray(rec, 'members');
663
+ if (name === undefined) {
664
+ return this.core.groups(action);
665
+ }
666
+ if (members === undefined) {
667
+ return this.core.groups(action, name);
668
+ }
669
+ return this.core.groups(action, name, members);
670
+ }
671
+ handleStatus() {
672
+ return this.core.status((handle) => ({ online: this.presence.has(handle) }));
673
+ }
674
+ handleFetchPush(rec) {
675
+ const handle = reqString(rec, 'handle');
676
+ const limit = reqNumber(rec, 'limit');
677
+ if (!Number.isInteger(limit) || limit < 0) {
678
+ throw badRequest('limit must be a non-negative integer');
679
+ }
680
+ // Everything the pull hands out was queued, so each one tells its
681
+ // sender it finally arrived.
682
+ const result = this.core.pendingPush(handle, limit);
683
+ for (const message of result.messages) {
684
+ this.enqueueNotification(message.sender, {
685
+ kind: 'queued_delivered',
686
+ threadId: message.threadId,
687
+ fromHandle: handle,
688
+ detail: 'queued message ' + String(message.id) + ' in thread ' + String(message.threadId) +
689
+ ' was delivered to ' + handle,
690
+ });
691
+ this.checkWaiters(message.threadId);
692
+ }
693
+ return result;
694
+ }
695
+ // Push execution after core.send and core.reply, best transport first:
696
+ // an adapter listening in the recipient's session, then the session's
697
+ // native messaging socket, then the CLI's own command transport. A target
698
+ // no transport takes stays queued and surfaces through the hook pull.
699
+ // sent means a transport accepted it; delivered needs evidence from the
700
+ // receiving side (adapter ack, transcript proof, hook pull, read).
701
+ async executePushes(pushes) {
702
+ for (const target of pushes) {
703
+ if (this.stopped) {
704
+ return;
705
+ }
706
+ if (target.kind === 'queued') {
707
+ continue;
708
+ }
709
+ await this.pushOne(target.message.id, target.message.threadId, target.recipient, target.text, {
710
+ message: target.message,
711
+ mode: 'push',
712
+ footer: target.footer,
713
+ text: target.text,
714
+ });
715
+ }
716
+ }
717
+ async pushOne(messageId, threadId, recipient, text, payload) {
718
+ const listener = this.presence.get(recipient);
719
+ if (listener !== undefined && listener.listening && !listener.socket.destroyed) {
720
+ const event = { v: PROTOCOL_VERSION, type: 'event', event: 'push', payload };
721
+ this.writeLine(listener.socket, encodeLine(event));
722
+ this.markSent(messageId, threadId, recipient);
723
+ return;
724
+ }
725
+ const session = this.liveSessionOf(recipient);
726
+ const transcript = session?.transcriptPath ?? null;
727
+ const offset = transcript === null ? 0 : ProofWatcher.offsetOf(transcript);
728
+ let accepted = false;
729
+ const transport = this.store.getNativeTransport(recipient);
730
+ if (transport !== null) {
731
+ try {
732
+ accepted = (await this.nativeSendFn(transport.socketPath, transport.token, text)).ok;
733
+ }
734
+ catch {
735
+ // A throwing transport counts as a failed send: leave queued.
736
+ }
737
+ }
738
+ else if (session !== null) {
739
+ accepted = await this.wakeFn(session, text).catch(() => false);
740
+ }
741
+ if (!accepted || this.stopped) {
742
+ return;
743
+ }
744
+ this.markSent(messageId, threadId, recipient);
745
+ if (transcript !== null) {
746
+ this.proof.watch(messageId, recipient, transcript, offset);
747
+ }
748
+ }
749
+ // Pushes every queued push-mode message waiting for this handle, oldest
750
+ // first, through whatever transport it has now.
751
+ async pushQueued(handle) {
752
+ const waiting = this.store.pendingPushFor(handle, 50).reverse();
753
+ for (const { message } of waiting) {
754
+ const recipients = this.store.getDeliveries(message.id).map((d) => d.recipient);
755
+ const full = fullOf(message);
756
+ const text = renderDelivery(full, message.deliveredBody, recipients);
757
+ await this.pushOne(message.id, message.threadId, handle, text, { message: full, mode: 'push', footer: replyFooter(full), text });
758
+ }
759
+ }
760
+ liveSessionOf(handle) {
761
+ return this.store.sessionsForHandle(handle).find((row) => row.state !== 'ended') ?? null;
762
+ }
763
+ markSent(messageId, threadId, recipient) {
764
+ const delivery = this.store.getDeliveries(messageId).find((d) => d.recipient === recipient);
765
+ if (delivery === undefined || delivery.state !== 'queued') {
766
+ return;
767
+ }
768
+ this.store.updateDelivery(messageId, recipient, { state: 'sent', sentAt: Date.now() });
769
+ this.checkWaiters(threadId);
770
+ }
771
+ onProof(messageId, recipient) {
772
+ if (!this.stopped) {
773
+ this.markDeliveredHop(messageId, recipient);
774
+ }
775
+ }
776
+ // queued or sent to delivered, with the queued_delivered notice to the
777
+ // sender when the message had been waiting. False when not applicable.
778
+ markDeliveredHop(messageId, recipient) {
779
+ const message = this.store.messageById(messageId);
780
+ const delivery = this.store.getDeliveries(messageId).find((d) => d.recipient === recipient);
781
+ if (message === null || delivery === undefined || (delivery.state !== 'queued' && delivery.state !== 'sent')) {
782
+ return false;
783
+ }
784
+ this.store.markDelivered(messageId, recipient, Date.now());
785
+ if (delivery.state === 'queued') {
786
+ this.enqueueNotification(message.sender, {
787
+ kind: 'queued_delivered',
788
+ threadId: message.threadId,
789
+ fromHandle: recipient,
790
+ detail: 'queued message ' + String(messageId) + ' in thread ' + String(message.threadId) + ' was delivered to ' + recipient,
791
+ });
792
+ }
793
+ this.checkWaiters(message.threadId);
794
+ return true;
795
+ }
796
+ // Notifications.
797
+ enqueueNotification(recipient, payload) {
798
+ if (this.stopped) {
799
+ return;
800
+ }
801
+ let entry = this.notifyQueue.get(recipient);
802
+ if (entry === undefined) {
803
+ entry = {
804
+ payloads: [],
805
+ timer: setTimeout(() => this.flushNotifications(recipient), NOTIFY_BATCH_MS),
806
+ };
807
+ this.notifyQueue.set(recipient, entry);
808
+ }
809
+ entry.payloads.push(payload);
810
+ }
811
+ flushNotifications(recipient) {
812
+ const entry = this.notifyQueue.get(recipient);
813
+ if (entry === undefined) {
814
+ return;
815
+ }
816
+ this.notifyQueue.delete(recipient);
817
+ clearTimeout(entry.timer);
818
+ if (this.stopped || entry.payloads.length === 0) {
819
+ return;
820
+ }
821
+ const event = {
822
+ v: PROTOCOL_VERSION,
823
+ type: 'event',
824
+ event: 'notification',
825
+ payload: entry.payloads,
826
+ };
827
+ const peer = this.presence.get(recipient);
828
+ if (peer !== undefined && peer.listening && !peer.socket.destroyed) {
829
+ this.writeLine(peer.socket, encodeLine(event));
830
+ return;
831
+ }
832
+ // No listening adapter: fall back to the native transport as plain text
833
+ // when one exists, otherwise drop the batch (the data stays in the DB).
834
+ const transport = this.store.getNativeTransport(recipient);
835
+ if (transport === null) {
836
+ return;
837
+ }
838
+ const text = '[murmur notice] ' + entry.payloads.map((p) => p.detail).join('; ');
839
+ this.nativeSendFn(transport.socketPath, transport.token, text).catch(() => {
840
+ // Notifications are best effort; the data stays in the DB.
841
+ });
842
+ }
843
+ // On disconnect: the peers still waiting on this handle learn it went
844
+ // offline. A notified peer is the sender of a message the departed handle
845
+ // has not yet consumed (queued or sent delivery), one per thread per sender.
846
+ notifyPeerOffline(handle) {
847
+ const seen = new Set();
848
+ for (const row of this.store.inboxFor(handle, false).messages) {
849
+ const delivery = this.store.getDeliveries(row.id).find((d) => d.recipient === handle);
850
+ if (delivery === undefined || (delivery.state !== 'queued' && delivery.state !== 'sent')) {
851
+ continue;
852
+ }
853
+ if (row.sender === handle) {
854
+ continue;
855
+ }
856
+ const key = String(row.threadId) + '\u0000' + row.sender;
857
+ if (seen.has(key)) {
858
+ continue;
859
+ }
860
+ seen.add(key);
861
+ this.enqueueNotification(row.sender, {
862
+ kind: 'peer_offline',
863
+ threadId: row.threadId,
864
+ fromHandle: handle,
865
+ detail: 'peer ' + handle + ' went offline with undelivered messages in thread ' + String(row.threadId),
866
+ });
867
+ }
868
+ }
869
+ // Waiters.
870
+ handleWait(conn, rec, id) {
871
+ const until = reqEnum(rec, 'until', WAIT_UNTILS);
872
+ const timeoutMs = reqNumber(rec, 'timeoutMs');
873
+ if (timeoutMs < 0) {
874
+ throw badRequest('timeoutMs must not be negative');
875
+ }
876
+ if (timeoutMs > WAIT_MAX_MS) {
877
+ throw badRequest('timeoutMs exceeds the cap of ' + String(WAIT_MAX_MS) + 'ms');
878
+ }
879
+ const threadId = reqNumber(rec, 'threadId');
880
+ if (this.conditionHolds(threadId, until)) {
881
+ this.replyOk(conn.socket, id, {
882
+ threadId,
883
+ conditionMet: true,
884
+ timedOut: false,
885
+ matrix: this.matrixFor(threadId),
886
+ });
887
+ return;
888
+ }
889
+ const waiter = {
890
+ conn,
891
+ id,
892
+ threadId,
893
+ until,
894
+ timer: setTimeout(() => this.resolveTimedOut(waiter), timeoutMs),
895
+ };
896
+ conn.waiters.add(waiter);
897
+ let set = this.waiters.get(threadId);
898
+ if (set === undefined) {
899
+ set = new Set();
900
+ this.waiters.set(threadId, set);
901
+ }
902
+ set.add(waiter);
903
+ }
904
+ // The condition is evaluated against the thread's latest ask: all_replied
905
+ // wants every recipient delivery replied, any_replied wants at least one.
906
+ // An ask with no recipients (or no ask at all) never holds.
907
+ conditionHolds(threadId, until) {
908
+ const ask = this.store.latestAsk(threadId);
909
+ if (ask === null) {
910
+ return false;
911
+ }
912
+ const deliveries = this.store.getDeliveries(ask.id);
913
+ if (deliveries.length === 0) {
914
+ return false;
915
+ }
916
+ if (until === 'any_replied') {
917
+ return deliveries.some((d) => d.state === 'replied');
918
+ }
919
+ return deliveries.every((d) => d.state === 'replied');
920
+ }
921
+ // The collect matrix for a WaitResult. A thread without messages or without
922
+ // an ask collects nothing, which degrades to an empty matrix.
923
+ matrixFor(threadId) {
924
+ try {
925
+ return this.core.collect(threadId).recipients;
926
+ }
927
+ catch (err) {
928
+ if (err instanceof MurmurError) {
929
+ return [];
930
+ }
931
+ throw err;
932
+ }
933
+ }
934
+ // Called after every mutation the broker drives (sends, replies, acks,
935
+ // reads, fetch-push, push state hops), which together cover every append
936
+ // and state change in the process, so a waiter resolves as soon as the
937
+ // condition starts to hold.
938
+ checkWaiters(threadId) {
939
+ const set = this.waiters.get(threadId);
940
+ if (set === undefined) {
941
+ return;
942
+ }
943
+ for (const waiter of [...set]) {
944
+ if (this.stopped) {
945
+ return;
946
+ }
947
+ if (!this.conditionHolds(threadId, waiter.until)) {
948
+ continue;
949
+ }
950
+ this.removeWaiter(waiter);
951
+ clearTimeout(waiter.timer);
952
+ this.replyOk(waiter.conn.socket, waiter.id, {
953
+ threadId,
954
+ conditionMet: true,
955
+ timedOut: false,
956
+ matrix: this.matrixFor(threadId),
957
+ });
958
+ }
959
+ }
960
+ resolveTimedOut(waiter) {
961
+ this.removeWaiter(waiter);
962
+ if (this.stopped) {
963
+ return;
964
+ }
965
+ try {
966
+ this.replyOk(waiter.conn.socket, waiter.id, {
967
+ threadId: waiter.threadId,
968
+ conditionMet: false,
969
+ timedOut: true,
970
+ matrix: this.matrixFor(waiter.threadId),
971
+ });
972
+ }
973
+ catch {
974
+ // Never let a timer callback crash the process.
975
+ }
976
+ }
977
+ removeWaiter(waiter) {
978
+ const set = this.waiters.get(waiter.threadId);
979
+ if (set !== undefined) {
980
+ set.delete(waiter);
981
+ if (set.size === 0) {
982
+ this.waiters.delete(waiter.threadId);
983
+ }
984
+ }
985
+ waiter.conn.waiters.delete(waiter);
986
+ }
987
+ // Presence and replies.
988
+ // Sets the connection's identity. Only long-lived connections take the
989
+ // presence slot, so a short CLI or hook connection never unseats a live
990
+ // session's MCP server or adapter.
991
+ bind(conn, handle, live) {
992
+ if (conn.handle !== null && this.presence.get(conn.handle) === conn) {
993
+ this.presence.delete(conn.handle);
994
+ }
995
+ conn.handle = handle;
996
+ conn.live = live;
997
+ conn.pendingHost = null;
998
+ if (live) {
999
+ this.presence.set(handle, conn);
1000
+ }
1001
+ }
1002
+ requireBoundHandle(conn) {
1003
+ if (conn.handle === null && conn.pendingHost !== null) {
1004
+ const { host, client, cwd } = conn.pendingHost;
1005
+ const session = this.core.sessionForHost(host, { client, ...(cwd !== undefined ? { cwd } : {}) });
1006
+ this.bind(conn, session.handle, conn.live);
1007
+ }
1008
+ if (conn.handle === null) {
1009
+ throw badRequest('no handle is registered on this connection');
1010
+ }
1011
+ return conn.handle;
1012
+ }
1013
+ replyOk(socket, id, result) {
1014
+ this.writeLine(socket, encodeLine({ v: PROTOCOL_VERSION, id, ok: true, result }));
1015
+ }
1016
+ replyErr(socket, id, code, message) {
1017
+ this.writeLine(socket, encodeLine({ v: PROTOCOL_VERSION, id, ok: false, error: { code, message } }));
1018
+ }
1019
+ writeLine(socket, line) {
1020
+ if (socket.destroyed) {
1021
+ return;
1022
+ }
1023
+ try {
1024
+ socket.write(line);
1025
+ }
1026
+ catch {
1027
+ // The socket died mid-write; the close handler finishes cleanup.
1028
+ }
1029
+ }
1030
+ }
1031
+ // A socket file left by a broker that died without cleanup blocks listen
1032
+ // with EADDRINUSE. Remove it when nothing answers on it; refuse when a live
1033
+ // broker does.
1034
+ async function clearStaleSocket(socketPath) {
1035
+ if (!existsSync(socketPath)) {
1036
+ return;
1037
+ }
1038
+ const answered = await new Promise((resolve) => {
1039
+ const probe = createConnection(socketPath);
1040
+ probe.once('connect', () => {
1041
+ probe.destroy();
1042
+ resolve(true);
1043
+ });
1044
+ probe.once('error', () => resolve(false));
1045
+ });
1046
+ if (answered) {
1047
+ throw new Error('murmur: a broker is already listening on ' + socketPath);
1048
+ }
1049
+ unlinkSync(socketPath);
1050
+ }