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/core.js ADDED
@@ -0,0 +1,779 @@
1
+ import { basename } from 'node:path';
2
+ import { isAlive, liveTable } from './proc.js';
3
+ import { DUP_WINDOW_MS, HANDLE_RE, MurmurError, RATE_MAX_SENDS, RATE_WINDOW_MS, THREAD_CAP, UNREAD_CAP, firstLine, renderDelivery, replyFooter, truncateForDelivery, } from './protocol.js';
4
+ export { HANDLE_RE };
5
+ const GROUP_NAME_RE = /^@?[a-z0-9][a-z0-9-]{1,31}$/;
6
+ const VERDICTS = ['agree', 'disagree', 'info'];
7
+ const UNREAD_STATES = ['queued', 'sent', 'delivered'];
8
+ const OFFLINE_AFTER_MS = 5 * 60 * 1000;
9
+ // Linear interpolation over an ascending list. Null for an empty list.
10
+ // fraction 0.5 gives the median, 0.95 the p95.
11
+ export function percentile(sortedValues, fraction) {
12
+ if (sortedValues.length === 0) {
13
+ return null;
14
+ }
15
+ const pos = (sortedValues.length - 1) * fraction;
16
+ const lo = Math.floor(pos);
17
+ const hi = Math.ceil(pos);
18
+ const loValue = sortedValues[lo];
19
+ const hiValue = sortedValues[hi];
20
+ if (loValue === undefined || hiValue === undefined) {
21
+ return null;
22
+ }
23
+ if (lo === hi) {
24
+ return loValue;
25
+ }
26
+ return loValue + (hiValue - loValue) * (pos - lo);
27
+ }
28
+ function parseRefs(json) {
29
+ try {
30
+ const parsed = JSON.parse(json);
31
+ if (Array.isArray(parsed)) {
32
+ return parsed.filter((v) => typeof v === 'string');
33
+ }
34
+ }
35
+ catch {
36
+ // The store always writes valid JSON; unparsable refs degrade to none.
37
+ }
38
+ return [];
39
+ }
40
+ function parseVerdict(value) {
41
+ if (value === 'agree' || value === 'disagree' || value === 'info') {
42
+ return value;
43
+ }
44
+ return null;
45
+ }
46
+ function normalizeHookState(value) {
47
+ if (value === 'busy' || value === 'idle') {
48
+ return value;
49
+ }
50
+ return null;
51
+ }
52
+ function freshestOf(a, b) {
53
+ if (a === null) {
54
+ return b;
55
+ }
56
+ if (b === null) {
57
+ return a;
58
+ }
59
+ return Math.max(a, b);
60
+ }
61
+ function stripGroupPrefix(name) {
62
+ return name.startsWith('@') ? name.slice(1) : name;
63
+ }
64
+ function summaryOf(row) {
65
+ return {
66
+ id: row.id,
67
+ threadId: row.threadId,
68
+ seq: row.seq,
69
+ sender: row.sender,
70
+ firstLine: firstLine(row.body),
71
+ truncated: row.truncated,
72
+ references: parseRefs(row.refsJson),
73
+ isReply: row.isReply,
74
+ inReplyTo: row.inReplyTo,
75
+ verdict: parseVerdict(row.verdict),
76
+ createdAt: row.createdAt,
77
+ };
78
+ }
79
+ export function fullOf(row) {
80
+ return { ...summaryOf(row), body: row.body };
81
+ }
82
+ function deliveryInfoOf(row) {
83
+ return {
84
+ recipient: row.recipient,
85
+ state: row.state,
86
+ sentAt: row.sentAt,
87
+ deliveredAt: row.deliveredAt,
88
+ ackedAt: row.ackedAt,
89
+ repliedAt: row.repliedAt,
90
+ latencyMs: row.latencyMs,
91
+ };
92
+ }
93
+ export class MurmurCore {
94
+ store;
95
+ events;
96
+ nowFn;
97
+ // Sliding send-rate window per sender and duplicate fingerprints. Both are
98
+ // in-memory by design: limits reset when the broker restarts.
99
+ sendTimes = new Map();
100
+ dupTimes = new Map();
101
+ // Current hook presence. The peers table columns hook_state and
102
+ // last_hook_activity_at have no writer method in Store, so hook events are
103
+ // tracked here for the process lifetime and status() falls back to the
104
+ // persisted row values when no override exists.
105
+ hookOverrides = new Map();
106
+ // Process table source for session liveness, asked only for the pids that
107
+ // matter; injectable for tests.
108
+ procTable;
109
+ constructor(store, events, now, procTable) {
110
+ this.store = store;
111
+ this.events = events;
112
+ this.nowFn = now ?? Date.now;
113
+ this.procTable = procTable ?? ((pids) => liveTable(pids));
114
+ }
115
+ nowMs() {
116
+ return this.nowFn();
117
+ }
118
+ register(arg) {
119
+ if (!HANDLE_RE.test(arg.handle)) {
120
+ throw new MurmurError('bad_request', 'invalid handle: ' + arg.handle);
121
+ }
122
+ if (arg.existing !== undefined && arg.existing !== arg.handle) {
123
+ if (this.store.getPeer(arg.existing) === null) {
124
+ throw new MurmurError('unknown_handle', 'unknown handle: ' + arg.existing);
125
+ }
126
+ try {
127
+ this.store.renamePeer(arg.existing, arg.handle);
128
+ }
129
+ catch (err) {
130
+ // renamePeer rejects a target handle that is already occupied.
131
+ throw new MurmurError('bad_request', err instanceof Error ? err.message : 'rename failed');
132
+ }
133
+ }
134
+ // Owner is never granted here; owner rows are only created by init.
135
+ this.store.upsertPeer(arg.handle, arg.display ?? null, arg.role ?? null, false, this.nowMs());
136
+ return { handle: arg.handle, owner: false };
137
+ }
138
+ // Expands groups to their members, validates every handle, dedups while
139
+ // preserving order, and rejects an empty result. @name is always a group;
140
+ // a bare name is a handle, or a group when no peer has that handle.
141
+ resolveRecipients(to) {
142
+ const out = [];
143
+ const seen = new Set();
144
+ const add = (handle) => {
145
+ if (this.store.getPeer(handle) === null) {
146
+ throw new MurmurError('unknown_handle', 'unknown handle: ' + handle);
147
+ }
148
+ if (!seen.has(handle)) {
149
+ seen.add(handle);
150
+ out.push(handle);
151
+ }
152
+ };
153
+ for (const entry of to) {
154
+ const stripped = stripGroupPrefix(entry);
155
+ const group = this.store.listGroups().find((g) => g.name === stripped);
156
+ if (!entry.startsWith('@') && (group === undefined || this.store.getPeer(entry) !== null)) {
157
+ add(entry);
158
+ continue;
159
+ }
160
+ if (group === undefined) {
161
+ throw new MurmurError('unknown_group', 'unknown group: ' + stripped);
162
+ }
163
+ for (const member of group.members) {
164
+ add(member);
165
+ }
166
+ }
167
+ if (out.length === 0) {
168
+ throw new MurmurError('bad_request', 'no recipients resolved');
169
+ }
170
+ return out;
171
+ }
172
+ // Rate, duplicate and cap checks for one intended send. A send that passes
173
+ // every check consumes one rate slot and one duplicate fingerprint; a send
174
+ // rejected by any check consumes none.
175
+ checkLimits(sender, body, recipients, threadId) {
176
+ const ts = this.nowMs();
177
+ const times = this.sendTimes.get(sender) ?? [];
178
+ const recent = times.filter((t) => ts - t < RATE_WINDOW_MS);
179
+ if (recent.length >= RATE_MAX_SENDS) {
180
+ throw new MurmurError('rate_limited', 'sender ' + sender + ' already sent ' + String(recent.length) + ' messages within ' + String(RATE_WINDOW_MS) + 'ms');
181
+ }
182
+ const fingerprint = sender + '\u0000' + body + '\u0000' + JSON.stringify(recipients);
183
+ const dups = this.dupTimes.get(fingerprint) ?? [];
184
+ const freshDups = dups.filter((t) => ts - t < DUP_WINDOW_MS);
185
+ if (freshDups.length > 0) {
186
+ throw new MurmurError('duplicate', 'identical message from ' + sender + ' already sent within ' + String(DUP_WINDOW_MS) + 'ms');
187
+ }
188
+ if (threadId !== null && this.store.messageCount(threadId) >= THREAD_CAP) {
189
+ throw new MurmurError('cap_thread', 'thread ' + String(threadId) + ' already holds ' + String(THREAD_CAP) + ' messages');
190
+ }
191
+ for (const recipient of recipients) {
192
+ const unread = this.store.deliveryStatesForRecipient(recipient, UNREAD_STATES);
193
+ if (unread >= UNREAD_CAP) {
194
+ throw new MurmurError('cap_inbox', 'recipient ' + recipient + ' already has ' + String(unread) + ' unread deliveries');
195
+ }
196
+ }
197
+ recent.push(ts);
198
+ this.sendTimes.set(sender, recent);
199
+ freshDups.push(ts);
200
+ this.dupTimes.set(fingerprint, freshDups);
201
+ }
202
+ send(sender, arg) {
203
+ const mode = arg.mode ?? 'push';
204
+ const recipients = this.resolveRecipients(arg.to);
205
+ this.checkLimits(sender, arg.body, recipients, arg.threadId);
206
+ const ts = this.nowMs();
207
+ let threadId;
208
+ if (arg.threadId === null) {
209
+ threadId = this.store.createThread(sender, ts);
210
+ }
211
+ else {
212
+ if (this.store.messageCount(arg.threadId) === 0) {
213
+ throw new MurmurError('unknown_thread', 'unknown thread: ' + String(arg.threadId));
214
+ }
215
+ threadId = arg.threadId;
216
+ }
217
+ const truncation = truncateForDelivery(arg.body);
218
+ const appended = this.store.appendMessage({
219
+ threadId,
220
+ sender,
221
+ body: arg.body,
222
+ deliveredBody: truncation.delivered,
223
+ truncated: truncation.truncated,
224
+ refs: arg.references ?? [],
225
+ mode,
226
+ isReply: false,
227
+ inReplyTo: null,
228
+ verdict: null,
229
+ createdAt: ts,
230
+ });
231
+ this.store.addDeliveries(appended.id, recipients, ts);
232
+ this.events.onAppend({ threadId, messageId: appended.id, isReply: false, sender });
233
+ const row = this.store.messageById(appended.id);
234
+ if (row === null) {
235
+ throw new MurmurError('internal', 'appended message vanished: ' + String(appended.id));
236
+ }
237
+ const deliveries = this.store.getDeliveries(appended.id).map(deliveryInfoOf);
238
+ return {
239
+ result: { messageId: appended.id, threadId, seq: appended.seq, deliveries },
240
+ pushes: this.pushesFor(row, recipients, mode),
241
+ };
242
+ }
243
+ deliveriesOf(messageId) {
244
+ return this.store.getDeliveries(messageId).map(deliveryInfoOf);
245
+ }
246
+ pushesFor(row, recipients, mode) {
247
+ const message = fullOf(row);
248
+ const footer = replyFooter(message);
249
+ const text = renderDelivery(message, row.deliveredBody, recipients);
250
+ return recipients.map((recipient) => ({
251
+ recipient,
252
+ kind: this.pushKindFor(recipient, mode),
253
+ message,
254
+ footer,
255
+ text,
256
+ }));
257
+ }
258
+ // Native transport row means the broker can hand the message to the
259
+ // recipient's own messaging socket; otherwise a push still travels over
260
+ // the recipient's live client connection. Non-push modes stay queued and
261
+ // only surface through notifications or the hook pull.
262
+ pushKindFor(recipient, mode) {
263
+ if (mode !== 'push') {
264
+ return 'queued';
265
+ }
266
+ return this.store.getNativeTransport(recipient) !== null ? 'native' : 'connection';
267
+ }
268
+ // A reply reaches everyone in the thread (every sender and every recipient
269
+ // so far, minus the replier) in the parent's delivery mode, so peers see
270
+ // each other's answers without anyone relaying them.
271
+ reply(sender, arg) {
272
+ if (arg.verdict !== undefined && !VERDICTS.includes(arg.verdict)) {
273
+ throw new MurmurError('bad_request', 'invalid verdict: ' + arg.verdict);
274
+ }
275
+ const parent = this.store.messageById(arg.messageId);
276
+ if (parent === null) {
277
+ throw new MurmurError('unknown_message', 'unknown message: ' + String(arg.messageId));
278
+ }
279
+ const participants = new Set(this.store.threadRecipientHandles(parent.threadId));
280
+ for (const row of this.store.threadMessages(parent.threadId, null)) {
281
+ participants.add(row.sender);
282
+ }
283
+ participants.delete(sender);
284
+ const recipients = [...participants].filter((handle) => this.store.getPeer(handle) !== null);
285
+ this.checkLimits(sender, arg.body, recipients, parent.threadId);
286
+ const mode = parent.mode;
287
+ const ts = this.nowMs();
288
+ const truncation = truncateForDelivery(arg.body);
289
+ const appended = this.store.appendMessage({
290
+ threadId: parent.threadId,
291
+ sender,
292
+ body: arg.body,
293
+ deliveredBody: truncation.delivered,
294
+ truncated: truncation.truncated,
295
+ refs: arg.references ?? [],
296
+ mode,
297
+ isReply: true,
298
+ inReplyTo: parent.id,
299
+ verdict: arg.verdict ?? null,
300
+ createdAt: ts,
301
+ });
302
+ // The sender's own delivery row on the parent message closes the loop:
303
+ // replied, with latency measured from the parent's creation.
304
+ const latencyMs = ts - parent.createdAt;
305
+ for (const delivery of this.store.getDeliveries(parent.id)) {
306
+ if (delivery.recipient !== sender) {
307
+ continue;
308
+ }
309
+ this.store.markReplied(parent.id, sender, ts, latencyMs);
310
+ this.events.onStateChange({
311
+ threadId: parent.threadId,
312
+ recipient: sender,
313
+ from: delivery.state,
314
+ to: 'replied',
315
+ });
316
+ }
317
+ this.store.addDeliveries(appended.id, recipients, ts);
318
+ this.events.onAppend({ threadId: parent.threadId, messageId: appended.id, isReply: true, sender });
319
+ const row = this.store.messageById(appended.id);
320
+ return {
321
+ result: { messageId: appended.id, threadId: parent.threadId, seq: appended.seq },
322
+ pushes: this.pushesFor(row, recipients, mode),
323
+ };
324
+ }
325
+ // Marks acknowledged each id with a delivery row for this handle that sits
326
+ // in delivered or sent. Returns the count actually acknowledged.
327
+ ack(handle, ids) {
328
+ const ts = this.nowMs();
329
+ let count = 0;
330
+ for (const id of ids) {
331
+ const message = this.store.messageById(id);
332
+ if (message === null) {
333
+ continue;
334
+ }
335
+ const delivery = this.store.getDeliveries(id).find((d) => d.recipient === handle);
336
+ if (delivery === undefined || (delivery.state !== 'delivered' && delivery.state !== 'sent')) {
337
+ continue;
338
+ }
339
+ this.store.markAcked(id, handle, ts);
340
+ this.events.onStateChange({
341
+ threadId: message.threadId,
342
+ recipient: handle,
343
+ from: delivery.state,
344
+ to: 'acknowledged',
345
+ });
346
+ count += 1;
347
+ }
348
+ return count;
349
+ }
350
+ // Full bodies for the requested messages the handle was addressed in,
351
+ // moving queued or sent deliveries to delivered on the way.
352
+ read(handle, ids) {
353
+ const ts = this.nowMs();
354
+ const out = [];
355
+ for (const row of this.store.readMessages(handle, ids)) {
356
+ const delivery = this.store.getDeliveries(row.id).find((d) => d.recipient === handle);
357
+ if (delivery !== undefined && (delivery.state === 'queued' || delivery.state === 'sent')) {
358
+ this.store.markDelivered(row.id, handle, ts);
359
+ this.events.onStateChange({
360
+ threadId: row.threadId,
361
+ recipient: handle,
362
+ from: delivery.state,
363
+ to: 'delivered',
364
+ });
365
+ }
366
+ out.push(fullOf(row));
367
+ }
368
+ return out;
369
+ }
370
+ // Messages delivered to the handle, grouped by thread, most recently
371
+ // active thread first. Per-thread unread counts come from the current
372
+ // delivery states, so the sum matches unreadTotal in both filter modes.
373
+ inbox(handle, unreadOnly) {
374
+ const { messages, unreadTotal } = this.store.inboxFor(handle, unreadOnly);
375
+ const byThread = new Map();
376
+ for (const row of messages) {
377
+ const existing = byThread.get(row.threadId);
378
+ if (existing === undefined) {
379
+ byThread.set(row.threadId, [row]);
380
+ }
381
+ else {
382
+ existing.push(row);
383
+ }
384
+ }
385
+ const threads = [];
386
+ for (const [threadId, rows] of byThread) {
387
+ let unread = 0;
388
+ let latestSeq = -1;
389
+ const summaries = [];
390
+ for (const row of rows) {
391
+ const delivery = this.store.getDeliveries(row.id).find((d) => d.recipient === handle);
392
+ if (delivery !== undefined && UNREAD_STATES.includes(delivery.state)) {
393
+ unread += 1;
394
+ }
395
+ summaries.push(summaryOf(row));
396
+ if (row.seq > latestSeq) {
397
+ latestSeq = row.seq;
398
+ }
399
+ }
400
+ threads.push({ threadId, latestSeq, unread, messages: summaries });
401
+ }
402
+ threads.sort((a, b) => b.latestSeq - a.latestSeq);
403
+ return { handle, unreadTotal, threads };
404
+ }
405
+ threadView(threadId, sinceSeq, full = true) {
406
+ const all = this.store.threadMessages(threadId, null);
407
+ if (all.length === 0) {
408
+ throw new MurmurError('unknown_thread', 'unknown thread: ' + String(threadId));
409
+ }
410
+ const last = all[all.length - 1];
411
+ const latestSeq = last === undefined ? 0 : last.seq;
412
+ const rows = sinceSeq === null ? all : this.store.threadMessages(threadId, sinceSeq);
413
+ return { threadId, latestSeq, messages: rows.map(full ? fullOf : summaryOf) };
414
+ }
415
+ // Matrix for the thread's latest ask: each recipient's delivery state,
416
+ // their verdict and reply latency when they answered the ask in the
417
+ // thread, and their all-time reply latency percentiles.
418
+ collect(threadId) {
419
+ const all = this.store.threadMessages(threadId, null);
420
+ if (all.length === 0) {
421
+ throw new MurmurError('unknown_thread', 'unknown thread: ' + String(threadId));
422
+ }
423
+ const ask = this.store.latestAsk(threadId);
424
+ if (ask === null) {
425
+ throw new MurmurError('bad_request', 'thread ' + String(threadId) + ' has no ask yet');
426
+ }
427
+ const recipients = [];
428
+ const seen = new Set();
429
+ for (const delivery of this.store.getDeliveries(ask.id)) {
430
+ if (seen.has(delivery.recipient)) {
431
+ continue;
432
+ }
433
+ seen.add(delivery.recipient);
434
+ // Latest reply by this recipient aimed at this ask, if any.
435
+ let reply = null;
436
+ for (const row of all) {
437
+ if (row.isReply && row.sender === delivery.recipient && row.inReplyTo === ask.id) {
438
+ reply = row;
439
+ }
440
+ }
441
+ const latencies = this.store.replyLatencies(delivery.recipient).sort((a, b) => a - b);
442
+ recipients.push({
443
+ recipient: delivery.recipient,
444
+ state: delivery.state,
445
+ verdict: reply === null ? null : parseVerdict(reply.verdict),
446
+ repliedLatencyMs: reply === null ? null : delivery.latencyMs,
447
+ p50ReplyMs: percentile(latencies, 0.5),
448
+ p95ReplyMs: percentile(latencies, 0.95),
449
+ });
450
+ }
451
+ const verdictTally = { agree: 0, disagree: 0, info: 0 };
452
+ for (const row of all) {
453
+ if (!row.isReply) {
454
+ continue;
455
+ }
456
+ const verdict = parseVerdict(row.verdict);
457
+ if (verdict !== null) {
458
+ verdictTally[verdict] += 1;
459
+ }
460
+ }
461
+ return { threadId, askMessageId: ask.id, recipients, verdictTally };
462
+ }
463
+ // Presence per peer, first match wins: a live session (its host process
464
+ // is running) reports busy or idle from its last lifecycle event, or
465
+ // online before any; then a live connection; then the legacy hook state;
466
+ // then the five minute window over last_seen_at, then presumed-offline.
467
+ status(live) {
468
+ const ts = this.nowMs();
469
+ const byHandle = new Map();
470
+ for (const row of this.store.listSessions()) {
471
+ const held = byHandle.get(row.handle);
472
+ if (held === undefined) {
473
+ byHandle.set(row.handle, [row]);
474
+ }
475
+ else {
476
+ held.push(row);
477
+ }
478
+ }
479
+ const table = this.safeProcTable([...byHandle.values()].flat().filter((row) => row.state !== 'ended').map((row) => row.hostPid));
480
+ const peers = [];
481
+ for (const peer of this.store.listPeers()) {
482
+ const override = this.hookOverrides.get(peer.handle);
483
+ const hookState = override !== undefined ? override.state : normalizeHookState(peer.hookState);
484
+ const hookAt = override !== undefined ? override.at : peer.lastHookActivityAt;
485
+ const sessions = byHandle.get(peer.handle) ?? [];
486
+ const session = sessions.find((row) => row.state !== 'ended' && isAlive(table, row.hostPid, row.hostStart));
487
+ let presence;
488
+ let busySince = null;
489
+ let idleSince = null;
490
+ if (session !== undefined && session.state === 'busy') {
491
+ presence = 'busy';
492
+ busySince = session.stateAt;
493
+ }
494
+ else if (session !== undefined && session.state === 'idle') {
495
+ presence = 'idle';
496
+ idleSince = session.stateAt;
497
+ }
498
+ else if (session !== undefined || live(peer.handle).online) {
499
+ presence = 'online';
500
+ }
501
+ else if (hookState === 'busy') {
502
+ presence = 'busy';
503
+ busySince = hookAt;
504
+ }
505
+ else if (hookState === 'idle') {
506
+ presence = 'idle';
507
+ idleSince = hookAt;
508
+ }
509
+ else if (peer.lastSeenAt === null || ts - peer.lastSeenAt > OFFLINE_AFTER_MS) {
510
+ presence = 'offline';
511
+ }
512
+ else {
513
+ presence = 'presumed-offline';
514
+ }
515
+ const lastActivity = freshestOf(freshestOf(peer.lastSeenAt, hookAt), sessions[0]?.updatedAt ?? null);
516
+ peers.push({
517
+ handle: peer.handle,
518
+ display: peer.display,
519
+ role: peer.role,
520
+ isOwner: peer.isOwner,
521
+ presence,
522
+ client: sessions[0]?.client ?? null,
523
+ busySince,
524
+ idleSince,
525
+ lastActivityAgeMs: lastActivity === null ? null : ts - lastActivity,
526
+ unread: this.store.deliveryStatesForRecipient(peer.handle, UNREAD_STATES),
527
+ });
528
+ }
529
+ return { now: ts, peers };
530
+ }
531
+ // Group membership only. Threads and message history never reference
532
+ // groups, so deleting one touches neither.
533
+ groups(action, name, members) {
534
+ const ts = this.nowMs();
535
+ switch (action) {
536
+ case 'create': {
537
+ if (name === undefined || !GROUP_NAME_RE.test(name)) {
538
+ throw new MurmurError('bad_request', 'invalid group name: ' + String(name));
539
+ }
540
+ const stripped = stripGroupPrefix(name);
541
+ if (this.store.listGroups().some((g) => g.name === stripped)) {
542
+ throw new MurmurError('bad_request', 'group already exists: ' + stripped);
543
+ }
544
+ this.store.createGroup(stripped, ts);
545
+ break;
546
+ }
547
+ case 'delete': {
548
+ this.store.deleteGroup(this.requireGroup(name));
549
+ break;
550
+ }
551
+ case 'add':
552
+ case 'remove': {
553
+ const group = this.requireGroup(name);
554
+ const handles = this.requireMembers(members);
555
+ for (const handle of handles) {
556
+ if (this.store.getPeer(handle) === null) {
557
+ throw new MurmurError('unknown_handle', 'unknown handle: ' + handle);
558
+ }
559
+ }
560
+ if (action === 'add') {
561
+ const found = this.store.listGroups().find((g) => g.name === group);
562
+ const current = found === undefined ? new Set() : new Set(found.members);
563
+ for (const handle of handles) {
564
+ // Adding an existing member is a no-op, not an error.
565
+ if (!current.has(handle)) {
566
+ this.store.addMember(group, handle, ts);
567
+ }
568
+ }
569
+ }
570
+ else {
571
+ for (const handle of handles) {
572
+ // Removing a non-member is a no-op, not an error.
573
+ this.store.removeMember(group, handle);
574
+ }
575
+ }
576
+ break;
577
+ }
578
+ case 'list':
579
+ break;
580
+ }
581
+ return this.store.listGroups().map((g) => ({
582
+ name: g.name,
583
+ members: [...g.members].sort(),
584
+ createdAt: g.createdAt,
585
+ }));
586
+ }
587
+ requireGroup(name) {
588
+ if (name === undefined) {
589
+ throw new MurmurError('bad_request', 'group name required');
590
+ }
591
+ const stripped = stripGroupPrefix(name);
592
+ if (!this.store.listGroups().some((g) => g.name === stripped)) {
593
+ throw new MurmurError('unknown_group', 'unknown group: ' + stripped);
594
+ }
595
+ return stripped;
596
+ }
597
+ requireMembers(members) {
598
+ if (members === undefined || members.length === 0) {
599
+ throw new MurmurError('bad_request', 'members required');
600
+ }
601
+ return members;
602
+ }
603
+ // A lifecycle event from a hook or an adapter. Finds the session by the
604
+ // CLI's own session id (so resume keeps the handle), else by the host
605
+ // process (so clear, which mints a new id in the same process, keeps it
606
+ // too), else creates it. Returns the session and its handle.
607
+ sessionEvent(arg) {
608
+ const ts = this.nowMs();
609
+ let row = arg.cliSessionId === null ? null : this.store.sessionByCliId(arg.client, arg.cliSessionId);
610
+ row ??= this.store.sessionByHost(arg.host.hostPid, arg.host.hostStart);
611
+ if (row === null) {
612
+ const handle = arg.handle !== undefined && this.claimable(arg.handle, null) ? arg.handle : this.allocateHandle(arg.client, arg.cwd);
613
+ this.ensurePeer(handle);
614
+ const id = this.store.insertSession({
615
+ client: arg.client,
616
+ cliSessionId: arg.cliSessionId,
617
+ handle,
618
+ hostPid: arg.host.hostPid,
619
+ hostStart: arg.host.hostStart,
620
+ transcriptPath: arg.transcriptPath ?? null,
621
+ cwd: arg.cwd ?? null,
622
+ now: ts,
623
+ });
624
+ row = this.store.sessionById(id);
625
+ }
626
+ else {
627
+ this.store.updateSession(row.id, {
628
+ client: arg.client,
629
+ hostPid: arg.host.hostPid,
630
+ hostStart: arg.host.hostStart,
631
+ updatedAt: ts,
632
+ ...(arg.cliSessionId !== null ? { cliSessionId: arg.cliSessionId } : {}),
633
+ ...(arg.transcriptPath !== undefined ? { transcriptPath: arg.transcriptPath } : {}),
634
+ ...(arg.cwd !== undefined ? { cwd: arg.cwd } : {}),
635
+ });
636
+ if (arg.handle !== undefined && arg.handle !== row.handle && this.claimable(arg.handle, row.id)) {
637
+ this.renameSession(row, arg.handle);
638
+ }
639
+ }
640
+ const state = arg.event === 'prompt' ? 'busy' : arg.event === 'session-end' ? 'ended' : 'idle';
641
+ this.store.updateSession(row.id, { state, stateAt: ts });
642
+ const fresh = this.store.sessionById(row.id);
643
+ if (arg.native !== undefined) {
644
+ this.store.upsertNativeTransport(fresh.handle, arg.native.socketPath, arg.native.token, ts);
645
+ }
646
+ if (arg.event === 'session-end') {
647
+ this.store.deleteNativeTransport(fresh.handle);
648
+ }
649
+ return fresh;
650
+ }
651
+ // The session running under this exact host process, if one announced
652
+ // itself. With create, a missing session is made on the spot (an MCP
653
+ // server whose hooks never ran still gets an identity).
654
+ sessionForHost(host, create) {
655
+ const row = this.store.sessionByHost(host.hostPid, host.hostStart);
656
+ if (row !== null || create === undefined) {
657
+ return row;
658
+ }
659
+ return this.sessionEvent({ event: 'session-start', client: create.client, cliSessionId: null, host, ...(create.cwd !== undefined ? { cwd: create.cwd } : {}) });
660
+ }
661
+ // The nearest live session whose host is one of these ancestors (nearest
662
+ // first), or null: a shell command run by an agent speaks as its session.
663
+ sessionForAncestors(ancestors) {
664
+ const candidates = this.store
665
+ .listSessions()
666
+ .filter((row) => row.state !== 'ended' && ancestors.includes(row.hostPid));
667
+ const table = this.safeProcTable(candidates.map((row) => row.hostPid));
668
+ const live = candidates.filter((row) => isAlive(table, row.hostPid, row.hostStart));
669
+ for (const pid of ancestors) {
670
+ const match = live.find((row) => row.hostPid === pid);
671
+ if (match !== undefined) {
672
+ return match;
673
+ }
674
+ }
675
+ return null;
676
+ }
677
+ // Gives the session a new name. A free name renames the identity with all
678
+ // its history; a name held by a peer with no live session is taken over
679
+ // (the session joins that identity, its groups and inbox); a live or
680
+ // owner handle is refused.
681
+ renameSession(row, handle) {
682
+ if (!HANDLE_RE.test(handle)) {
683
+ throw new MurmurError('bad_request', 'invalid handle: ' + handle);
684
+ }
685
+ if (handle === row.handle) {
686
+ return handle;
687
+ }
688
+ if (!this.claimable(handle, row.id)) {
689
+ throw new MurmurError('bad_request', 'handle ' + handle + ' is taken by a live session or the owner');
690
+ }
691
+ if (this.store.getPeer(handle) === null) {
692
+ this.store.renamePeer(row.handle, handle);
693
+ return handle;
694
+ }
695
+ const others = this.store.sessionsForHandle(row.handle).filter((r) => r.id !== row.id);
696
+ this.store.reassignSession(row.id, row.handle, handle);
697
+ if (others.length === 0 && !this.store.peerHasHistory(row.handle)) {
698
+ this.store.deletePeer(row.handle);
699
+ }
700
+ return handle;
701
+ }
702
+ // A handle can be claimed when it is valid, not the owner's, and no live
703
+ // session other than exceptId holds it.
704
+ claimable(handle, exceptId) {
705
+ if (!HANDLE_RE.test(handle)) {
706
+ return false;
707
+ }
708
+ const peer = this.store.getPeer(handle);
709
+ if (peer !== null && peer.isOwner) {
710
+ return false;
711
+ }
712
+ const holders = this.store.sessionsForHandle(handle).filter((r) => r.id !== exceptId && r.state !== 'ended');
713
+ const table = this.safeProcTable(holders.map((r) => r.hostPid));
714
+ return !holders.some((r) => isAlive(table, r.hostPid, r.hostStart));
715
+ }
716
+ // <client>-<cwd basename>, then -2, -3, ... until no live session holds
717
+ // it. A handle whose sessions are all gone is reused, so a restarted
718
+ // session in the same folder rejoins its groups.
719
+ allocateHandle(client, cwd) {
720
+ const folder = cwd === undefined ? '' : basename(cwd).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
721
+ const base = (folder.length > 0 ? client + '-' + folder : client).slice(0, 28).replace(/-+$/, '');
722
+ let handle = base;
723
+ for (let n = 2; !this.claimable(handle, null); n += 1) {
724
+ handle = base + '-' + String(n);
725
+ }
726
+ return handle;
727
+ }
728
+ safeProcTable(pids) {
729
+ try {
730
+ return this.procTable(pids);
731
+ }
732
+ catch {
733
+ return new Map();
734
+ }
735
+ }
736
+ // Records a hook lifecycle event. prompt means the session is working
737
+ // (busy); session-start and stop leave it idle. Fires nothing.
738
+ hookState(handle, event) {
739
+ this.ensurePeer(handle);
740
+ const state = event === 'prompt' ? 'busy' : 'idle';
741
+ this.hookOverrides.set(handle, { state, at: this.nowMs() });
742
+ }
743
+ registerNative(arg) {
744
+ this.ensurePeer(arg.handle);
745
+ this.store.upsertNativeTransport(arg.handle, arg.socketPath, arg.token, this.nowMs());
746
+ }
747
+ // The hook injection pull: queued push-mode messages, newest first,
748
+ // marked delivered as they are handed out, each with its rendered text.
749
+ pendingPush(handle, limit) {
750
+ const ts = this.nowMs();
751
+ const messages = [];
752
+ const texts = [];
753
+ for (const { message: row } of this.store.pendingPushFor(handle, limit)) {
754
+ this.store.markDelivered(row.id, handle, ts);
755
+ this.events.onStateChange({ threadId: row.threadId, recipient: handle, from: 'queued', to: 'delivered' });
756
+ const message = fullOf(row);
757
+ messages.push(message);
758
+ texts.push(renderDelivery(message, row.deliveredBody, this.store.getDeliveries(row.id).map((d) => d.recipient)));
759
+ }
760
+ return { messages, texts };
761
+ }
762
+ // Stamps last_seen_at on authenticated activity. upsertPeer refreshes
763
+ // display, role and last_seen_at, so the current values are passed back
764
+ // to keep them intact.
765
+ touchSeen(handle) {
766
+ const peer = this.store.getPeer(handle);
767
+ if (peer === null) {
768
+ return;
769
+ }
770
+ this.store.upsertPeer(handle, peer.display, peer.role, peer.isOwner, this.nowMs());
771
+ }
772
+ // Creates the peer row only when it is missing; an existing row is left
773
+ // untouched so its display, role and last_seen_at survive.
774
+ ensurePeer(handle) {
775
+ if (this.store.getPeer(handle) === null) {
776
+ this.store.upsertPeer(handle, null, null, false, this.nowMs());
777
+ }
778
+ }
779
+ }