murmur-it 0.2.10 → 0.2.11
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/CHANGELOG.md +48 -1
- package/adapters/hummin/murmur.ts +86 -4
- package/adapters/opencode/murmur.ts +78 -3
- package/dist/broker.js +30 -11
- package/dist/cli-identity.js +25 -0
- package/dist/cli.js +2 -22
- package/dist/core.js +206 -13
- package/dist/hooks.js +4 -3
- package/dist/machine.js +205 -0
- package/dist/mcp.js +3 -2
- package/dist/store.js +44 -6
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,52 @@ All notable changes to murmur are documented here. The format follows [Keep a Ch
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [0.2.11] - 2026-11-17
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
|
|
11
|
+
- A session of another machine no longer looks dead to the broker, and the sessions of a machine that rebooted no longer keep their handles.
|
|
12
|
+
|
|
13
|
+
**What changed**
|
|
14
|
+
|
|
15
|
+
- Every host reference (pid and start time) carries the machine it runs on: `machine`, its boot id, and `machineName`, its host name, only as a label and never compared for identity. The boot id is `/proc/sys/kernel/random/boot_id` plus `:` and the pid namespace number (`/proc/self/ns/pid`) on Linux, so a container is another machine (the bare boot id where the link cannot be read), and `/usr/sbin/sysctl -n kern.bootsessionuuid` with a one second limit on macOS.
|
|
16
|
+
- The broker takes a machine only as a uuid, optionally followed by `:` and 1 to 20 digits, and keeps it in lower case; a name only as 1 to 255 printable characters. Anything else reads as absent.
|
|
17
|
+
- A session of the broker's own machine is judged by the process table as before. A session of another machine is alive while a connection of its host (pid, start, machine) is open, for a lease of 12 hours after its last session event (SessionStart, a prompt, a stop; SessionEnd ends it at once), or for 60 seconds after the broker starts, while the MCP servers reconnect (20 tries, 250 ms apart: `RECONNECT_ATTEMPTS` and `RECONNECT_DELAY_MS` in `src/mcp.ts`). Receiving messages does not renew the lease; the connection does.
|
|
18
|
+
- Two sessions in one folder on two machines get distinct handles (`claude-guard`, `claude-guard-2`) and show as two peers. A title cannot take the handle of a live session of another machine. A pid and start that collide across machines or boots do not match. A crashed session of this machine is no longer a sibling: restarting in its folder and naming the new session carries the groups.
|
|
19
|
+
- A session that comes back after another took its handle (an ended row revived by its next event) never shares it: it takes the next free handle, and the queue and groups stay with the holder.
|
|
20
|
+
- A session event also carries `machineFingerprint` (the first 32 hex characters of sha256("murmur-machine:" + the id the system keeps for itself): `/etc/machine-id`, else `/var/lib/dbus/machine-id`, on Linux; the IOPlatformUUID of `/usr/sbin/ioreg -rd1 -c IOPlatformExpertDevice` on macOS) and `machineUptime` (seconds since boot, from `/proc/uptime` or `kern.boottime`). The raw id never leaves the machine, and no client is shown a fingerprint. An id that is not 32 lower case hex characters (a systemd placeholder such as `uninitialized`, an id baked into an image) gives no fingerprint, so such a machine ends nothing and the lease applies; the opencode and hummin adapters carry the same check, and the fingerprint is not even read when there is no boot id.
|
|
21
|
+
- A reboot is a new boot id for the same fingerprint and the same host name. The old sessions of that machine end at once when they were last heard from before the new boot (the uptime), none of their hosts is connected, and the broker is past its 60 second startup grace. A resumed session with the same CLI id keeps its row.
|
|
22
|
+
- A host name alone is no evidence: two machines can share one (`raspberrypi`, `localhost`, two Macs called `Mac`), have different fingerprints, and are never read as each other's reboot. A quiet one keeps its handle, groups, queue and native transport.
|
|
23
|
+
- Nothing ends when the fingerprint is missing on the event or on the row, when the host name changed, when there is no uptime, or while the old host is connected: the lease applies.
|
|
24
|
+
- An event without a machine (a boot id read that failed this once) leaves the machine and label its session had. An event with a machine but no label or fingerprint keeps those of the same machine.
|
|
25
|
+
- A client that gains a machine id, or whose boot id read failed once, finds the row of its own process only when the CLI ids do not conflict, when the folders are equal if the event and the row both carry one, when no live process of the broker's machine has that pid and start, and when the candidates are of one machine: an event without a machine whose pid and start match rows of two machines takes neither. The lookup an MCP server makes by its host applies the same tests as the event it belongs to, so a lookup adopts no row that the event itself would not.
|
|
26
|
+
- A broker that could not read its own boot id at start tries again every minute. Once it can, the rows clients wrote under that id while it was read as another machine become its own (machine, label and fingerprint cleared) and the process table judges them from then on.
|
|
27
|
+
- The hooks, the MCP server, the CLI and the opencode and hummin adapters send the fields, each reading them once per process (a hook is a new process per event, so a read that failed yields a sparse event, handled as above).
|
|
28
|
+
- Sessions are matched by pid, start and machine (`host_machine`, `host_label` and `host_fingerprint`, nullable columns added to an existing database when it opens; NULL is the broker's own machine). The fields are additive and the broker never checks `v`, so a new client works against an old broker, which ignores them.
|
|
29
|
+
|
|
30
|
+
**Limits**
|
|
31
|
+
|
|
32
|
+
- A crashed session of another machine keeps its handle for the 12 hour lease; so does one of the broker's own machine that sends a boot id while the broker cannot read its own. A container that restarts gets a new pid namespace, so its old session is another machine's and holds its handle for the lease.
|
|
33
|
+
- Two clones of one image share a machine id and a host name: the connected one stays and a hook-only one ends. Remedy: `systemd-machine-id-setup`, or distinct host names.
|
|
34
|
+
- Any client on the bus can claim any machine and keep a handle alive by renewing a lease. It can end a connection-less session of another machine only by presenting that machine's fingerprint and host name with a new boot id and an uptime that predates the session's last event. The token is still the trust boundary: whoever holds it is on the bus.
|
|
35
|
+
- An upgraded hook adopts the row of its old process while that process's MCP server is connected. A clear or a resume that mints a new CLI id in that window, or a change of folder, opens a second row. The case left is an old row without a CLI id, with the same pid and the same `ps lstart` second on two machines started from one image, when the two folders are equal or when the event or the row carries none (a missing folder is not a difference).
|
|
36
|
+
- A hook and an MCP server of one session that run in different pid namespaces (a wrapper that starts the hook under `unshare` or `bwrap`), or where only one of them can read `/proc/self/ns/pid`, send different machine ids. When the host process is alive in the broker's process table, the session splits into two rows with two handles (`claude-guard` and `claude-guard-2`). Remedy: run the hooks in the pid namespace of the CLI.
|
|
37
|
+
- Two containers are one machine, and colliding pids one session, only when they share one pid namespace (or cannot read the link, so both send the bare boot id). A container with its own pid namespace is another machine, as above. Containers of one image that share a host name and a machine id and show a per container uptime (lxcfs) look like reboots of each other: the older one's connection-less sessions end. Give each container its own host name.
|
|
38
|
+
- A client that predates the fields sends none and is judged by the process table, so a session of another machine that runs an old client still looks dead, shares a handle with a new session and is carried along by a rename again (the fix below protects only sessions the broker sees alive).
|
|
39
|
+
|
|
40
|
+
**Upgrade steps**
|
|
41
|
+
|
|
42
|
+
1. Update murmur on the broker's machine and on every machine whose sessions reach it, then restart their running sessions: a hook that sends the machine next to an MCP server that does not splits one session in two until it restarts.
|
|
43
|
+
2. Nothing to migrate: an existing database gains the columns when it opens.
|
|
44
|
+
3. Give each clone of an image its own machine id (`systemd-machine-id-setup`) or its own host name.
|
|
45
|
+
4. On macOS, check that `/usr/sbin/sysctl -n kern.bootsessionuuid` and `/usr/sbin/ioreg -rd1 -c IOPlatformExpertDevice` print a uuid and an `IOPlatformUUID` line.
|
|
46
|
+
|
|
47
|
+
- The native transport of a handle two sessions hold is no longer replaced by the second session's registration, and the first `SessionEnd` no longer deletes it.
|
|
48
|
+
|
|
49
|
+
- Naming a session no longer carries other sessions along. The broker judges a session alive from its own process table, so a session of another machine looks dead and its handle reads free: a second live session was given the same handle, and when one of them took its title (or was renamed with `murmur_name`) the whole identity was renamed: every session on the old handle moved, their earlier messages changed sender, and the MCP connections of the others followed. While another session that has not ended holds the old handle, only the renamed session moves, the others keep their handle, history, groups and native transport, and only the renamed session's own MCP connection follows. A lone session renaming itself still carries its history, groups and transport, and so does an ended sibling that held the same handle.
|
|
50
|
+
|
|
51
|
+
The consequence, plainly: after a rename away from a shared handle the renamed session starts with no history, no group memberships, no role and an empty inbox. Everything recorded under the old handle (messages, queued deliveries, groups, the role, the native transport) stays with the session that keeps it, because nothing records which session wrote an old message; replies to a message the renamed session sent before the split go to the session that stayed. A connection that names no host (a CLI or adapter connection bound by handle) also stays with the old handle. A sibling is a session that is alive (see the machine entry above): a session of this machine that crashed without a SessionEnd is not, so restarting in its folder and naming the new session carries the groups; a client that sends no machine and runs on another machine still counts as dead.
|
|
52
|
+
|
|
7
53
|
## [0.2.10] - 2026-11-05
|
|
8
54
|
|
|
9
55
|
### Added
|
|
@@ -181,7 +227,8 @@ All notable changes to murmur are documented here. The format follows [Keep a Ch
|
|
|
181
227
|
- Limits: send rate, duplicate window, thread and inbox caps.
|
|
182
228
|
- 283 tests at 100 percent lines and branches, and an end-to-end rig that replayed the live 3-peer scenario.
|
|
183
229
|
|
|
184
|
-
[Unreleased]: https://github.com/rennf93/murmur/compare/v0.2.
|
|
230
|
+
[Unreleased]: https://github.com/rennf93/murmur/compare/v0.2.11...HEAD
|
|
231
|
+
[0.2.11]: https://github.com/rennf93/murmur/releases/tag/v0.2.11
|
|
185
232
|
[0.2.10]: https://github.com/rennf93/murmur/releases/tag/v0.2.10
|
|
186
233
|
[0.2.9]: https://github.com/rennf93/murmur/releases/tag/v0.2.9
|
|
187
234
|
[0.2.8]: https://github.com/rennf93/murmur/releases/tag/v0.2.8
|
|
@@ -23,9 +23,10 @@
|
|
|
23
23
|
*/
|
|
24
24
|
|
|
25
25
|
import { execFileSync } from "node:child_process";
|
|
26
|
-
import {
|
|
26
|
+
import { createHash } from "node:crypto";
|
|
27
|
+
import { readFileSync, readlinkSync } from "node:fs";
|
|
27
28
|
import { connect, type Socket } from "node:net";
|
|
28
|
-
import { homedir } from "node:os";
|
|
29
|
+
import { homedir, hostname } from "node:os";
|
|
29
30
|
import { join } from "node:path";
|
|
30
31
|
import { Type } from "typebox";
|
|
31
32
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
@@ -41,7 +42,7 @@ const RECONNECT_MS = 5000;
|
|
|
41
42
|
const REQUEST_TIMEOUT_MS = 30_000;
|
|
42
43
|
|
|
43
44
|
type Json = Record<string, unknown>;
|
|
44
|
-
interface Host { hostPid: number; hostStart: string }
|
|
45
|
+
interface Host { hostPid: number; hostStart: string; machine?: string; machineName?: string; machineFingerprint?: string; readonly machineUptime?: number }
|
|
45
46
|
|
|
46
47
|
// ---------------------------------------------------------------------------
|
|
47
48
|
// socket client (request/reply by id, events to a callback)
|
|
@@ -139,6 +140,8 @@ function openClient(onEvent: (f: Json) => void, onClose: () => void): Promise<Cl
|
|
|
139
140
|
});
|
|
140
141
|
}
|
|
141
142
|
|
|
143
|
+
let machineOnce: { machine?: string; machineName?: string } | undefined;
|
|
144
|
+
|
|
142
145
|
function readHost(): Host {
|
|
143
146
|
// hostStart must match what the broker computes: ps lstart under LC_ALL=C
|
|
144
147
|
let hostStart = "";
|
|
@@ -150,7 +153,86 @@ function readHost(): Host {
|
|
|
150
153
|
} catch {
|
|
151
154
|
// broker will treat the host as unverifiable
|
|
152
155
|
}
|
|
153
|
-
|
|
156
|
+
// Read once per process: a later failing read must not change what this process said before.
|
|
157
|
+
machineOnce ??= machineRef();
|
|
158
|
+
const machine = machineOnce;
|
|
159
|
+
return {
|
|
160
|
+
hostPid: process.pid,
|
|
161
|
+
hostStart,
|
|
162
|
+
...machine,
|
|
163
|
+
// Read when a message is serialized, so the broker sees the uptime of that moment.
|
|
164
|
+
get machineUptime(): number | undefined {
|
|
165
|
+
return machine.machine === undefined ? undefined : machineUptime();
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Seconds since this machine booted (src/machine.ts readUptime).
|
|
171
|
+
function machineUptime(): number | undefined {
|
|
172
|
+
try {
|
|
173
|
+
if (process.platform === "linux") {
|
|
174
|
+
const seconds = Number.parseFloat(readFileSync("/proc/uptime", "utf8"));
|
|
175
|
+
return Number.isFinite(seconds) && seconds >= 0 ? Math.floor(seconds) : undefined;
|
|
176
|
+
}
|
|
177
|
+
if (process.platform === "darwin") {
|
|
178
|
+
const out = execFileSync("/usr/sbin/sysctl", ["-n", "kern.boottime"], { encoding: "utf8", timeout: 1000 });
|
|
179
|
+
const booted = /sec\s*=\s*(\d+)/.exec(out)?.[1];
|
|
180
|
+
return booted === undefined ? undefined : Math.max(0, Math.floor(Date.now() / 1000) - Number(booted));
|
|
181
|
+
}
|
|
182
|
+
} catch {
|
|
183
|
+
// no uptime
|
|
184
|
+
}
|
|
185
|
+
return undefined;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// What the broker keeps with a host (src/machine.ts): the boot id, and the host
|
|
189
|
+
// name as a label; neither when there is no boot id, so the broker reads this
|
|
190
|
+
// as an old client of its own machine.
|
|
191
|
+
// A hash that names the machine across reboots (src/machine.ts readFingerprint):
|
|
192
|
+
// the raw system id never leaves the machine.
|
|
193
|
+
function machineFingerprint(): string | undefined {
|
|
194
|
+
const attempt = (read: () => string): string => {
|
|
195
|
+
try {
|
|
196
|
+
return read();
|
|
197
|
+
} catch {
|
|
198
|
+
return "";
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
let raw = "";
|
|
202
|
+
if (process.platform === "linux") {
|
|
203
|
+
raw = attempt(() => readFileSync("/etc/machine-id", "utf8").trim());
|
|
204
|
+
raw = /^[0-9a-f]{32}$/.test(raw) ? raw : attempt(() => readFileSync("/var/lib/dbus/machine-id", "utf8").trim());
|
|
205
|
+
raw = /^[0-9a-f]{32}$/.test(raw) ? raw : "";
|
|
206
|
+
} else if (process.platform === "darwin") {
|
|
207
|
+
raw = attempt(() => /"IOPlatformUUID"\s*=\s*"([0-9a-f-]{36})"/i.exec(execFileSync("/usr/sbin/ioreg", ["-rd1", "-c", "IOPlatformExpertDevice"], { encoding: "utf8", timeout: 1000 }))?.[1] ?? "");
|
|
208
|
+
}
|
|
209
|
+
return raw === "" ? undefined : createHash("sha256").update("murmur-machine:" + raw).digest("hex").slice(0, 32);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function machineRef(): { machine?: string; machineName?: string; machineFingerprint?: string } {
|
|
213
|
+
try {
|
|
214
|
+
const raw =
|
|
215
|
+
process.platform === "linux"
|
|
216
|
+
? readFileSync("/proc/sys/kernel/random/boot_id", "utf8")
|
|
217
|
+
: process.platform === "darwin"
|
|
218
|
+
? execFileSync("/usr/sbin/sysctl", ["-n", "kern.bootsessionuuid"], { encoding: "utf8", timeout: 1000 })
|
|
219
|
+
: "";
|
|
220
|
+
const uuid = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i.exec(raw);
|
|
221
|
+
if (uuid !== null) {
|
|
222
|
+
// On Linux the pid namespace is part of the machine: a process table is one machine's.
|
|
223
|
+
let namespace = "";
|
|
224
|
+
try {
|
|
225
|
+
namespace = process.platform === "linux" ? (/\[(\d+)\]/.exec(readlinkSync("/proc/self/ns/pid"))?.[1] ?? "") : "";
|
|
226
|
+
} catch {
|
|
227
|
+
// no namespace to read
|
|
228
|
+
}
|
|
229
|
+
const fingerprint = machineFingerprint();
|
|
230
|
+
return { machine: uuid[0].toLowerCase() + (namespace === "" ? "" : ":" + namespace), machineName: hostname(), ...(fingerprint !== undefined ? { machineFingerprint: fingerprint } : {}) };
|
|
231
|
+
}
|
|
232
|
+
} catch {
|
|
233
|
+
// no boot id
|
|
234
|
+
}
|
|
235
|
+
return {};
|
|
154
236
|
}
|
|
155
237
|
|
|
156
238
|
function text(s: string, isError = false): { content: { type: "text"; text: string }[]; details: undefined; isError?: boolean } {
|
|
@@ -3,9 +3,10 @@
|
|
|
3
3
|
// and the murmur_* tools talk over the calling session's connection.
|
|
4
4
|
import { tool, type Plugin } from '@opencode-ai/plugin';
|
|
5
5
|
import { execFileSync } from 'node:child_process';
|
|
6
|
-
import {
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { readFileSync, readlinkSync } from 'node:fs';
|
|
7
8
|
import { connect, type Socket } from 'node:net';
|
|
8
|
-
import { homedir } from 'node:os';
|
|
9
|
+
import { homedir, hostname } from 'node:os';
|
|
9
10
|
import { join } from 'node:path';
|
|
10
11
|
|
|
11
12
|
const HOME = process.env.MURMUR_HOME || join(homedir(), '.murmur');
|
|
@@ -20,7 +21,81 @@ try {
|
|
|
20
21
|
} catch {
|
|
21
22
|
// leave empty; the broker will refuse the announce and we retry quietly
|
|
22
23
|
}
|
|
23
|
-
|
|
24
|
+
// What the broker keeps with a host (src/machine.ts): the boot id, and the host
|
|
25
|
+
// name as a label; neither when there is no boot id, so the broker reads this
|
|
26
|
+
// as an old client of its own machine.
|
|
27
|
+
// A hash that names the machine across reboots (src/machine.ts readFingerprint):
|
|
28
|
+
// the raw system id never leaves the machine.
|
|
29
|
+
function machineFingerprint(): string | undefined {
|
|
30
|
+
const attempt = (read: () => string): string => {
|
|
31
|
+
try {
|
|
32
|
+
return read();
|
|
33
|
+
} catch {
|
|
34
|
+
return '';
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
let raw = '';
|
|
38
|
+
if (process.platform === 'linux') {
|
|
39
|
+
raw = attempt(() => readFileSync('/etc/machine-id', 'utf8').trim());
|
|
40
|
+
raw = /^[0-9a-f]{32}$/.test(raw) ? raw : attempt(() => readFileSync('/var/lib/dbus/machine-id', 'utf8').trim());
|
|
41
|
+
raw = /^[0-9a-f]{32}$/.test(raw) ? raw : '';
|
|
42
|
+
} else if (process.platform === 'darwin') {
|
|
43
|
+
raw = attempt(() => /"IOPlatformUUID"\s*=\s*"([0-9a-f-]{36})"/i.exec(execFileSync('/usr/sbin/ioreg', ['-rd1', '-c', 'IOPlatformExpertDevice'], { encoding: 'utf8', timeout: 1000 }))?.[1] ?? '');
|
|
44
|
+
}
|
|
45
|
+
return raw === '' ? undefined : createHash('sha256').update('murmur-machine:' + raw).digest('hex').slice(0, 32);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function machineRef(): { machine?: string; machineName?: string; machineFingerprint?: string } {
|
|
49
|
+
try {
|
|
50
|
+
const raw =
|
|
51
|
+
process.platform === 'linux'
|
|
52
|
+
? readFileSync('/proc/sys/kernel/random/boot_id', 'utf8')
|
|
53
|
+
: process.platform === 'darwin'
|
|
54
|
+
? execFileSync('/usr/sbin/sysctl', ['-n', 'kern.bootsessionuuid'], { encoding: 'utf8', timeout: 1000 })
|
|
55
|
+
: '';
|
|
56
|
+
const uuid = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i.exec(raw);
|
|
57
|
+
if (uuid !== null) {
|
|
58
|
+
// On Linux the pid namespace is part of the machine: a process table is one machine's.
|
|
59
|
+
let namespace = '';
|
|
60
|
+
try {
|
|
61
|
+
namespace = process.platform === 'linux' ? (/\[(\d+)\]/.exec(readlinkSync('/proc/self/ns/pid'))?.[1] ?? '') : '';
|
|
62
|
+
} catch {
|
|
63
|
+
// no namespace to read
|
|
64
|
+
}
|
|
65
|
+
const fingerprint = machineFingerprint();
|
|
66
|
+
return { machine: uuid[0].toLowerCase() + (namespace === '' ? '' : ':' + namespace), machineName: hostname(), ...(fingerprint !== undefined ? { machineFingerprint: fingerprint } : {}) };
|
|
67
|
+
}
|
|
68
|
+
} catch {
|
|
69
|
+
// no boot id
|
|
70
|
+
}
|
|
71
|
+
return {};
|
|
72
|
+
}
|
|
73
|
+
// Seconds since this machine booted, read when a message is serialized (src/machine.ts readUptime).
|
|
74
|
+
function machineUptime(): number | undefined {
|
|
75
|
+
try {
|
|
76
|
+
if (process.platform === 'linux') {
|
|
77
|
+
const seconds = Number.parseFloat(readFileSync('/proc/uptime', 'utf8'));
|
|
78
|
+
return Number.isFinite(seconds) && seconds >= 0 ? Math.floor(seconds) : undefined;
|
|
79
|
+
}
|
|
80
|
+
if (process.platform === 'darwin') {
|
|
81
|
+
const out = execFileSync('/usr/sbin/sysctl', ['-n', 'kern.boottime'], { encoding: 'utf8', timeout: 1000 });
|
|
82
|
+
const booted = /sec\s*=\s*(\d+)/.exec(out)?.[1];
|
|
83
|
+
return booted === undefined ? undefined : Math.max(0, Math.floor(Date.now() / 1000) - Number(booted));
|
|
84
|
+
}
|
|
85
|
+
} catch {
|
|
86
|
+
// no uptime
|
|
87
|
+
}
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
const machine = machineRef();
|
|
91
|
+
const host = {
|
|
92
|
+
hostPid: process.pid,
|
|
93
|
+
hostStart,
|
|
94
|
+
...machine,
|
|
95
|
+
get machineUptime(): number | undefined {
|
|
96
|
+
return machine.machine === undefined ? undefined : machineUptime();
|
|
97
|
+
},
|
|
98
|
+
};
|
|
24
99
|
|
|
25
100
|
type Pending = { resolve: (v: any) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> };
|
|
26
101
|
|
package/dist/broker.js
CHANGED
|
@@ -2,6 +2,7 @@ import { chmodSync, existsSync, unlinkSync } from 'node:fs';
|
|
|
2
2
|
import { createConnection, createServer } from 'node:net';
|
|
3
3
|
import { StringDecoder } from 'node:string_decoder';
|
|
4
4
|
import { readToken } from './config.js';
|
|
5
|
+
import { parseWireMachine, validBootId } from './machine.js';
|
|
5
6
|
import { fullOf } from './core.js';
|
|
6
7
|
import { nativeSend } from './native.js';
|
|
7
8
|
import { ProofWatcher } from './proof.js';
|
|
@@ -100,7 +101,13 @@ function reqHost(value) {
|
|
|
100
101
|
throw badRequest('host must be an object');
|
|
101
102
|
}
|
|
102
103
|
const rec = value;
|
|
103
|
-
|
|
104
|
+
// A machine that is not a boot id in shape reads as absent, and the label, the
|
|
105
|
+
// uptime and the fingerprint mean something only next to one.
|
|
106
|
+
return {
|
|
107
|
+
hostPid: reqNumber(rec, 'hostPid'),
|
|
108
|
+
hostStart: reqString(rec, 'hostStart'),
|
|
109
|
+
...parseWireMachine(rec),
|
|
110
|
+
};
|
|
104
111
|
}
|
|
105
112
|
function reqEnum(rec, key, allowed) {
|
|
106
113
|
const value = rec[key];
|
|
@@ -142,7 +149,7 @@ export class Broker {
|
|
|
142
149
|
this.nativeSendFn = opts.nativeSend ?? nativeSend;
|
|
143
150
|
this.wakeFn = opts.wake ?? defaultWake;
|
|
144
151
|
this.core.hasTools = (handle) => this.presence.has(handle);
|
|
145
|
-
this.core.hostConnected = (host) => [...this.conns].some((c) => c.live && c.host
|
|
152
|
+
this.core.hostConnected = (host) => [...this.conns].some((c) => c.live && c.host !== null && this.atRow(c.host, host));
|
|
146
153
|
this.proof = new ProofWatcher((messageId, recipient) => this.onProof(messageId, recipient), opts.proofPollMs);
|
|
147
154
|
}
|
|
148
155
|
static async start(opts) {
|
|
@@ -436,6 +443,7 @@ export class Broker {
|
|
|
436
443
|
const role = optString(rec, 'role');
|
|
437
444
|
const host = rec.host === undefined ? undefined : reqHost(rec.host);
|
|
438
445
|
const ancestors = optNumberArray(rec, 'ancestors');
|
|
446
|
+
const machine = validBootId(rec.machine);
|
|
439
447
|
const client = optEnum(rec, 'client', CLI_NAMES) ?? 'other';
|
|
440
448
|
const cwd = optString(rec, 'cwd');
|
|
441
449
|
const owner = optBool(rec, 'owner') === true;
|
|
@@ -453,7 +461,7 @@ export class Broker {
|
|
|
453
461
|
if (owner) {
|
|
454
462
|
resolved = this.ownerHandle();
|
|
455
463
|
if (ancestors !== undefined) {
|
|
456
|
-
conn.via = this.core.sessionForAncestors(ancestors)?.handle ?? null;
|
|
464
|
+
conn.via = this.core.sessionForAncestors(ancestors, machine)?.handle ?? null;
|
|
457
465
|
}
|
|
458
466
|
}
|
|
459
467
|
else if (host !== undefined) {
|
|
@@ -468,10 +476,10 @@ export class Broker {
|
|
|
468
476
|
return { handle: '', owner: false };
|
|
469
477
|
}
|
|
470
478
|
resolved = handle === undefined ? session.handle : this.core.renameSession(session, handle);
|
|
471
|
-
this.rebind(session.handle, resolved);
|
|
479
|
+
this.rebind(session.handle, resolved, session);
|
|
472
480
|
}
|
|
473
481
|
else if (ancestors !== undefined && handle === undefined) {
|
|
474
|
-
resolved = this.core.sessionForAncestors(ancestors)?.handle ?? this.ownerHandle();
|
|
482
|
+
resolved = this.core.sessionForAncestors(ancestors, machine)?.handle ?? this.ownerHandle();
|
|
475
483
|
}
|
|
476
484
|
else if (handle !== undefined) {
|
|
477
485
|
resolved = this.core.register({ handle }).handle;
|
|
@@ -508,6 +516,14 @@ export class Broker {
|
|
|
508
516
|
this.bind(conn, handle, false);
|
|
509
517
|
return null;
|
|
510
518
|
}
|
|
519
|
+
// A connection's host reference against a stored session host: pid, start
|
|
520
|
+
// and machine (null is this broker's own machine).
|
|
521
|
+
atRow(ref, row) {
|
|
522
|
+
return ref.hostPid === row.hostPid && ref.hostStart === row.hostStart && this.core.machineKey(ref) === row.hostMachine;
|
|
523
|
+
}
|
|
524
|
+
sameRef(a, b) {
|
|
525
|
+
return a.hostPid === b.hostPid && a.hostStart === b.hostStart && this.core.machineKey(a) === this.core.machineKey(b);
|
|
526
|
+
}
|
|
511
527
|
async handleSession(conn, rec) {
|
|
512
528
|
const event = reqEnum(rec, 'event', HOOK_EVENTS);
|
|
513
529
|
const client = reqEnum(rec, 'client', CLI_NAMES);
|
|
@@ -527,7 +543,7 @@ export class Broker {
|
|
|
527
543
|
native = { socketPath: reqString(nat, 'socketPath'), token: reqString(nat, 'token') };
|
|
528
544
|
}
|
|
529
545
|
// A title can rename the session, so find the name it had before.
|
|
530
|
-
const before = (cliSessionId === null ? null : this.store.sessionByCliId(client, cliSessionId)) ?? this.
|
|
546
|
+
const before = (cliSessionId === null ? null : this.store.sessionByCliId(client, cliSessionId)) ?? this.core.sessionForHost(host, undefined, { cliSessionId, ...(cwd !== undefined ? { cwd } : {}) });
|
|
531
547
|
const session = this.core.sessionEvent({
|
|
532
548
|
event,
|
|
533
549
|
client,
|
|
@@ -540,7 +556,7 @@ export class Broker {
|
|
|
540
556
|
...(native !== undefined ? { native } : {}),
|
|
541
557
|
});
|
|
542
558
|
if (before !== null) {
|
|
543
|
-
this.rebind(before.handle, session.handle);
|
|
559
|
+
this.rebind(before.handle, session.handle, session);
|
|
544
560
|
}
|
|
545
561
|
conn.listening = listen;
|
|
546
562
|
conn.host = host;
|
|
@@ -548,7 +564,7 @@ export class Broker {
|
|
|
548
564
|
// MCP servers of this session that registered before it announced itself.
|
|
549
565
|
for (const other of this.conns) {
|
|
550
566
|
const pending = other.pendingHost;
|
|
551
|
-
if (pending !== null &&
|
|
567
|
+
if (pending !== null && this.sameRef(pending.host, host)) {
|
|
552
568
|
this.bind(other, session.handle, other.live);
|
|
553
569
|
}
|
|
554
570
|
}
|
|
@@ -1122,12 +1138,15 @@ export class Broker {
|
|
|
1122
1138
|
// A session's name changed: connections still bound to the old one (its MCP
|
|
1123
1139
|
// server, an adapter) follow it, unless another live session still holds
|
|
1124
1140
|
// it. Ended sessions left on the old name do not count.
|
|
1125
|
-
|
|
1126
|
-
|
|
1141
|
+
// While another session still holds the old name, only the connections of
|
|
1142
|
+
// the renamed session's own process follow.
|
|
1143
|
+
rebind(from, to, moved) {
|
|
1144
|
+
const shared = this.core.holdsHandle(from);
|
|
1145
|
+
if (from === to || (!shared && !this.core.claimable(from, null))) {
|
|
1127
1146
|
return;
|
|
1128
1147
|
}
|
|
1129
1148
|
for (const conn of this.conns) {
|
|
1130
|
-
if (conn.handle === from) {
|
|
1149
|
+
if (conn.handle === from && (!shared || (conn.host !== null && this.atRow(conn.host, moved)))) {
|
|
1131
1150
|
this.bind(conn, to, conn.live);
|
|
1132
1151
|
}
|
|
1133
1152
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { thisMachineRef } from './machine.js';
|
|
2
|
+
import { currentHost } from './proc.js';
|
|
3
|
+
// The register messages a shell command sends. Each says which machine its
|
|
4
|
+
// pids belong to (src/machine.ts), because the broker may run on another.
|
|
5
|
+
export const OWNER_DISPLAY = 'renn (owner)';
|
|
6
|
+
export function identityMessage(asHandle, speaker) {
|
|
7
|
+
if (asHandle !== null) {
|
|
8
|
+
return { type: 'register', handle: asHandle, clientKind: 'cli' };
|
|
9
|
+
}
|
|
10
|
+
if (speaker === 'owner') {
|
|
11
|
+
return {
|
|
12
|
+
type: 'register',
|
|
13
|
+
owner: true,
|
|
14
|
+
display: OWNER_DISPLAY,
|
|
15
|
+
clientKind: 'cli',
|
|
16
|
+
ancestors: currentHost()?.ancestors ?? [],
|
|
17
|
+
...thisMachineRef(),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
return { type: 'register', clientKind: 'cli', ancestors: currentHost()?.ancestors ?? [], ...thisMachineRef() };
|
|
21
|
+
}
|
|
22
|
+
// The register that names the session of a host process, on this machine.
|
|
23
|
+
export function nameMessage(handle, host) {
|
|
24
|
+
return { type: 'register', clientKind: 'cli', handle, host: { hostPid: host.hostPid, hostStart: host.hostStart, ...thisMachineRef() } };
|
|
25
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -5,10 +5,10 @@ import { connectBroker, isBrokerDown } from './client.js';
|
|
|
5
5
|
import { ensureHome, getPaths, isRemoteHome, readToken } from './config.js';
|
|
6
6
|
import { HOOK_CLIENTS, runHook } from './hooks.js';
|
|
7
7
|
import { INSTALL_CLIENTS, installClient } from './install.js';
|
|
8
|
+
import { OWNER_DISPLAY, identityMessage, nameMessage } from './cli-identity.js';
|
|
8
9
|
import { currentHost } from './proc.js';
|
|
9
10
|
import { HANDLE_RE, MurmurError } from './protocol.js';
|
|
10
11
|
const OWNER_HANDLE = 'renn';
|
|
11
|
-
const OWNER_DISPLAY = 'renn (owner)';
|
|
12
12
|
const SEND_USAGE = 'usage: murmur send <targets> <body...> [--as <handle>] [--mode <mode>] [--refs <a,b>] [--thread <id>]';
|
|
13
13
|
const REPLY_USAGE = 'usage: murmur reply <message id> <body...> [--as <handle>] [--verdict agree|disagree|info|choice] [--refs <a,b>]';
|
|
14
14
|
const NAME_USAGE = 'usage: murmur name <handle> (renames the agent session this runs in)';
|
|
@@ -209,21 +209,6 @@ function readAllStdin() {
|
|
|
209
209
|
});
|
|
210
210
|
});
|
|
211
211
|
}
|
|
212
|
-
function identityMessage(asHandle, speaker) {
|
|
213
|
-
if (asHandle !== null) {
|
|
214
|
-
return { type: 'register', handle: asHandle, clientKind: 'cli' };
|
|
215
|
-
}
|
|
216
|
-
if (speaker === 'owner') {
|
|
217
|
-
return {
|
|
218
|
-
type: 'register',
|
|
219
|
-
owner: true,
|
|
220
|
-
display: OWNER_DISPLAY,
|
|
221
|
-
clientKind: 'cli',
|
|
222
|
-
ancestors: currentHost()?.ancestors ?? [],
|
|
223
|
-
};
|
|
224
|
-
}
|
|
225
|
-
return { type: 'register', clientKind: 'cli', ancestors: currentHost()?.ancestors ?? [] };
|
|
226
|
-
}
|
|
227
212
|
// Splits --flag value pairs from positionals. Null (after printing why)
|
|
228
213
|
// when a flag is missing its value.
|
|
229
214
|
function parseFlags(args, flags, usage, name, err) {
|
|
@@ -374,12 +359,7 @@ async function cmdName(args, out, err) {
|
|
|
374
359
|
}
|
|
375
360
|
const client = await connectCli();
|
|
376
361
|
try {
|
|
377
|
-
const msg =
|
|
378
|
-
type: 'register',
|
|
379
|
-
clientKind: 'cli',
|
|
380
|
-
handle,
|
|
381
|
-
host: { hostPid: host.hostPid, hostStart: host.hostStart },
|
|
382
|
-
};
|
|
362
|
+
const msg = nameMessage(handle, host);
|
|
383
363
|
const result = await client.request(msg);
|
|
384
364
|
out(result.handle + '\n');
|
|
385
365
|
return 0;
|
package/dist/core.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { basename } from 'node:path';
|
|
2
|
+
import { thisMachine } from './machine.js';
|
|
2
3
|
import { isAlive, liveTable } from './proc.js';
|
|
3
4
|
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
5
|
export { HANDLE_RE };
|
|
@@ -10,6 +11,14 @@ const UNREAD_STATES = ['queued', 'sent', 'delivered'];
|
|
|
10
11
|
// are never acked fill the cap and block every later reply to the asker.
|
|
11
12
|
const BACKLOG_STATES = ['queued', 'sent'];
|
|
12
13
|
const OFFLINE_AFTER_MS = 5 * 60 * 1000;
|
|
14
|
+
// A session of another machine counts as alive this long after its last event
|
|
15
|
+
// (its hooks only fire on a prompt or a stop, so an idle session is quiet).
|
|
16
|
+
const REMOTE_LEASE_MS = 12 * 60 * 60 * 1000;
|
|
17
|
+
// After a broker start the connections that kept sessions of other machines
|
|
18
|
+
// alive are gone until their MCP servers reconnect, which they do within 5
|
|
19
|
+
// seconds (20 attempts, 250 ms apart); a minute covers that twelve times over
|
|
20
|
+
// and is short enough not to hold the handle of a session that is really gone.
|
|
21
|
+
const STARTUP_GRACE_MS = 60 * 1000;
|
|
13
22
|
// A session title as a handle: lowercase, runs of anything else become one
|
|
14
23
|
// hyphen, trimmed, cut to the handle limit. Not necessarily a valid handle.
|
|
15
24
|
export function slugify(title) {
|
|
@@ -124,11 +133,103 @@ export class MurmurCore {
|
|
|
124
133
|
// Process table source for session liveness, asked only for the pids that
|
|
125
134
|
// matter; injectable for tests.
|
|
126
135
|
procTable;
|
|
127
|
-
|
|
136
|
+
// Where the boot id of the machine this broker runs on is read ('' when
|
|
137
|
+
// unreadable): its host references are judged by the process table, every
|
|
138
|
+
// other machine's by a connection, a lease or the startup grace. A function
|
|
139
|
+
// is read each time, since the broker retries a read that failed at start.
|
|
140
|
+
machineSource;
|
|
141
|
+
// The own machine as last read, to see it appear.
|
|
142
|
+
seenMachine;
|
|
143
|
+
startedAt;
|
|
144
|
+
constructor(store, events, now, procTable, machine) {
|
|
128
145
|
this.store = store;
|
|
129
146
|
this.events = events;
|
|
130
147
|
this.nowFn = now ?? Date.now;
|
|
131
148
|
this.procTable = procTable ?? ((pids) => liveTable(pids));
|
|
149
|
+
this.machineSource = typeof machine === 'function' ? machine : machine === undefined ? thisMachine : () => machine;
|
|
150
|
+
this.seenMachine = this.machineSource();
|
|
151
|
+
this.startedAt = this.nowMs();
|
|
152
|
+
}
|
|
153
|
+
// The boot id of this broker's machine. A broker that could not read it at
|
|
154
|
+
// start and now can finds rows that clients wrote under that id while it was
|
|
155
|
+
// taken for another machine: they are its own, so they are re-keyed once, and
|
|
156
|
+
// the process table judges them from then on.
|
|
157
|
+
ownMachine() {
|
|
158
|
+
const read = this.machineSource();
|
|
159
|
+
if (read !== this.seenMachine) {
|
|
160
|
+
// No row is keyed to '', so losing the id re-keys nothing.
|
|
161
|
+
this.store.rekeyMachine(read);
|
|
162
|
+
this.seenMachine = read;
|
|
163
|
+
}
|
|
164
|
+
return read;
|
|
165
|
+
}
|
|
166
|
+
// The machine a host reference names as stored (its boot id): null for this
|
|
167
|
+
// broker's own machine and for a client that sends none (an old client, or one
|
|
168
|
+
// that cannot read a boot id). A broker with no boot id of its own takes every
|
|
169
|
+
// client that sends one for another machine, so handles are never shared.
|
|
170
|
+
// Two names are one machine when their boot ids are; the host name is never
|
|
171
|
+
// compared.
|
|
172
|
+
machineKey(host) {
|
|
173
|
+
const own = this.ownMachine();
|
|
174
|
+
return host.machine === undefined || host.machine === own ? null : host.machine;
|
|
175
|
+
}
|
|
176
|
+
// The machine, label and fingerprint to store on an event of a known session.
|
|
177
|
+
// An event that carries no machine at all (a client whose boot id read
|
|
178
|
+
// failed) leaves what the session had; one that carries a machine sets it, and
|
|
179
|
+
// keeps the label and the fingerprint when it carries none for the same
|
|
180
|
+
// machine.
|
|
181
|
+
machineFields(row, host) {
|
|
182
|
+
if (host.machine === undefined && row.hostMachine !== null) {
|
|
183
|
+
return {};
|
|
184
|
+
}
|
|
185
|
+
const key = this.machineKey(host);
|
|
186
|
+
const same = key === row.hostMachine;
|
|
187
|
+
return {
|
|
188
|
+
hostMachine: key,
|
|
189
|
+
hostLabel: this.labelOf(host) ?? (same ? row.hostLabel : null),
|
|
190
|
+
hostFingerprint: this.fingerprintOf(host) ?? (same ? row.hostFingerprint : null),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
// The fingerprint stored with a machine other than this broker's.
|
|
194
|
+
fingerprintOf(host) {
|
|
195
|
+
return this.machineKey(host) === null ? null : (host.machineFingerprint ?? null);
|
|
196
|
+
}
|
|
197
|
+
// The host name label stored with a machine other than this broker's.
|
|
198
|
+
labelOf(host) {
|
|
199
|
+
return this.machineKey(host) === null ? null : (host.machineName ?? null);
|
|
200
|
+
}
|
|
201
|
+
// The session of this host process. A client that gains a machine id (an
|
|
202
|
+
// upgrade) finds the row an old client of the same process wrote without one,
|
|
203
|
+
// and a client that sends none (its boot id read failed this once) finds the
|
|
204
|
+
// row that carries one, in both cases only when no live process of this
|
|
205
|
+
// machine has that pid and start and the CLI ids do not conflict (an event and
|
|
206
|
+
// a row that both carry one and differ are two sessions). The row takes the
|
|
207
|
+
// machine of the event when it has one, so one session never becomes two. An
|
|
208
|
+
// event and a row that both carry a folder and differ are two sessions too:
|
|
209
|
+
// the same pid and start second can come up on two machines started from one
|
|
210
|
+
// image.
|
|
211
|
+
rowAt(host, cliSessionId = null, cwd) {
|
|
212
|
+
const key = this.machineKey(host);
|
|
213
|
+
const row = this.store.sessionByHost(host.hostPid, host.hostStart, key);
|
|
214
|
+
if (row !== null) {
|
|
215
|
+
return row;
|
|
216
|
+
}
|
|
217
|
+
// The rows of this pid and start that could be this session: rows of one
|
|
218
|
+
// machine only, since the host of an event without a machine could be any.
|
|
219
|
+
const rows = this.store.sessionsOfHost(host.hostPid, host.hostStart).filter((r) => key === null || r.hostMachine === null);
|
|
220
|
+
const table = rows.length === 0 ? new Map() : this.safeProcTable([host.hostPid]);
|
|
221
|
+
const found = rows.filter((r) => r.state !== 'ended' &&
|
|
222
|
+
!(cliSessionId !== null && r.cliSessionId !== null && r.cliSessionId !== cliSessionId) &&
|
|
223
|
+
!(cwd !== undefined && r.cwd !== null && r.cwd !== cwd) &&
|
|
224
|
+
!isAlive(table, r.hostPid, r.hostStart));
|
|
225
|
+
const other = found[0];
|
|
226
|
+
if (other === undefined || found.some((r) => r.hostMachine !== other.hostMachine)) {
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
229
|
+
if (key !== null) {
|
|
230
|
+
this.store.updateSession(other.id, { hostMachine: key, hostLabel: this.labelOf(host), hostFingerprint: this.fingerprintOf(host) });
|
|
231
|
+
}
|
|
232
|
+
return this.store.sessionById(other.id);
|
|
132
233
|
}
|
|
133
234
|
nowMs() {
|
|
134
235
|
return this.nowFn();
|
|
@@ -513,6 +614,7 @@ export class MurmurCore {
|
|
|
513
614
|
// online before any; then a live connection; then the legacy hook state;
|
|
514
615
|
// then the five minute window over last_seen_at, then presumed-offline.
|
|
515
616
|
status(live) {
|
|
617
|
+
this.ownMachine();
|
|
516
618
|
const ts = this.nowMs();
|
|
517
619
|
const byHandle = new Map();
|
|
518
620
|
for (const row of this.store.listSessions()) {
|
|
@@ -655,7 +757,9 @@ export class MurmurCore {
|
|
|
655
757
|
sessionEvent(arg) {
|
|
656
758
|
const ts = this.nowMs();
|
|
657
759
|
let row = arg.cliSessionId === null ? null : this.store.sessionByCliId(arg.client, arg.cliSessionId);
|
|
658
|
-
row ??= this.
|
|
760
|
+
row ??= this.rowAt(arg.host, arg.cliSessionId, arg.cwd);
|
|
761
|
+
// Before a new row takes a handle, so it can have the handle of a session that a reboot ended.
|
|
762
|
+
this.endRebootedSessions(row?.id ?? -1, arg.host, ts);
|
|
659
763
|
if (row === null) {
|
|
660
764
|
const explicit = arg.handle !== undefined && this.claimable(arg.handle, null);
|
|
661
765
|
const slug = arg.title === undefined ? '' : slugify(arg.title);
|
|
@@ -671,6 +775,9 @@ export class MurmurCore {
|
|
|
671
775
|
handle,
|
|
672
776
|
hostPid: arg.host.hostPid,
|
|
673
777
|
hostStart: arg.host.hostStart,
|
|
778
|
+
hostMachine: this.machineKey(arg.host),
|
|
779
|
+
hostLabel: this.labelOf(arg.host),
|
|
780
|
+
hostFingerprint: this.fingerprintOf(arg.host),
|
|
674
781
|
transcriptPath: arg.transcriptPath ?? null,
|
|
675
782
|
cwd: arg.cwd ?? null,
|
|
676
783
|
now: ts,
|
|
@@ -681,10 +788,18 @@ export class MurmurCore {
|
|
|
681
788
|
}
|
|
682
789
|
}
|
|
683
790
|
else {
|
|
791
|
+
// A session that comes back after another took its handle must not share it.
|
|
792
|
+
if (row.state === 'ended' && arg.event !== 'session-end' && this.liveHolders(row.handle, row.id).length > 0) {
|
|
793
|
+
const handle = this.allocateHandle(arg.client, arg.cwd ?? row.cwd ?? undefined);
|
|
794
|
+
this.ensurePeer(handle);
|
|
795
|
+
this.store.reassignSession(row.id, row.handle, handle, false);
|
|
796
|
+
row = this.store.sessionById(row.id);
|
|
797
|
+
}
|
|
684
798
|
this.store.updateSession(row.id, {
|
|
685
799
|
client: arg.client,
|
|
686
800
|
hostPid: arg.host.hostPid,
|
|
687
801
|
hostStart: arg.host.hostStart,
|
|
802
|
+
...this.machineFields(row, arg.host),
|
|
688
803
|
updatedAt: ts,
|
|
689
804
|
...(arg.cliSessionId !== null ? { cliSessionId: arg.cliSessionId } : {}),
|
|
690
805
|
...(arg.transcriptPath !== undefined ? { transcriptPath: arg.transcriptPath } : {}),
|
|
@@ -701,10 +816,14 @@ export class MurmurCore {
|
|
|
701
816
|
fresh = this.followTitle(fresh, arg.title);
|
|
702
817
|
}
|
|
703
818
|
if (arg.native !== undefined) {
|
|
704
|
-
this.
|
|
819
|
+
if (!this.sharesHandle(fresh)) {
|
|
820
|
+
this.store.upsertNativeTransport(fresh.handle, arg.native.socketPath, arg.native.token, ts);
|
|
821
|
+
}
|
|
705
822
|
}
|
|
706
823
|
if (arg.event === 'session-end') {
|
|
707
|
-
this.
|
|
824
|
+
if (!this.sharesHandle(fresh)) {
|
|
825
|
+
this.store.deleteNativeTransport(fresh.handle);
|
|
826
|
+
}
|
|
708
827
|
}
|
|
709
828
|
return fresh;
|
|
710
829
|
}
|
|
@@ -721,11 +840,46 @@ export class MurmurCore {
|
|
|
721
840
|
this.store.upsertPeer(current.handle, title, null, false, this.nowMs());
|
|
722
841
|
return current;
|
|
723
842
|
}
|
|
843
|
+
// An event that carries a boot id other than the one stored for sessions of
|
|
844
|
+
// the same machine means that machine rebooted, which ended every process on
|
|
845
|
+
// it: those sessions end at once. The same machine is the same fingerprint
|
|
846
|
+
// (a hash of the id the system keeps for itself) and the same host name label:
|
|
847
|
+
// a host name alone is no evidence, two machines can share one (raspberrypi,
|
|
848
|
+
// localhost) and then each one's events would look like a reboot of the other.
|
|
849
|
+
// Without a fingerprint on the event or on the row, or with a changed host
|
|
850
|
+
// name, nothing says it is the same machine and the lease applies. The old
|
|
851
|
+
// sessions must also have been last heard from before the new boot (the
|
|
852
|
+
// uptime), and none of their hosts may be connected. While the broker has just
|
|
853
|
+
// started, connections are still coming back and nothing can be told from
|
|
854
|
+
// their absence.
|
|
855
|
+
endRebootedSessions(id, host, ts) {
|
|
856
|
+
const key = this.machineKey(host);
|
|
857
|
+
const label = this.labelOf(host);
|
|
858
|
+
const fingerprint = this.fingerprintOf(host);
|
|
859
|
+
if (key === null || label === null || fingerprint === null) {
|
|
860
|
+
return;
|
|
861
|
+
}
|
|
862
|
+
if (host.machineUptime === undefined || ts - this.startedAt <= STARTUP_GRACE_MS) {
|
|
863
|
+
return;
|
|
864
|
+
}
|
|
865
|
+
const bootedAt = ts - host.machineUptime * 1000;
|
|
866
|
+
for (const old of this.store.rebootedSessions(fingerprint, label, key, id)) {
|
|
867
|
+
if (this.hostConnected(old) || old.updatedAt >= bootedAt) {
|
|
868
|
+
continue;
|
|
869
|
+
}
|
|
870
|
+
this.store.updateSession(old.id, { state: 'ended', stateAt: ts });
|
|
871
|
+
if (!this.sharesHandle(old)) {
|
|
872
|
+
this.store.deleteNativeTransport(old.handle);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
}
|
|
724
876
|
// The session running under this exact host process, if one announced
|
|
725
877
|
// itself. With create, a missing session is made on the spot (an MCP
|
|
726
|
-
// server whose hooks never ran still gets an identity).
|
|
727
|
-
|
|
728
|
-
|
|
878
|
+
// server whose hooks never ran still gets an identity). With match, the CLI
|
|
879
|
+
// id and the folder of the event it is a lookup for, so that a lookup adopts
|
|
880
|
+
// no row that the event itself would not.
|
|
881
|
+
sessionForHost(host, create, match) {
|
|
882
|
+
const row = this.rowAt(host, match?.cliSessionId ?? null, match?.cwd);
|
|
729
883
|
if (row !== null || create === undefined) {
|
|
730
884
|
return row;
|
|
731
885
|
}
|
|
@@ -733,10 +887,11 @@ export class MurmurCore {
|
|
|
733
887
|
}
|
|
734
888
|
// The nearest live session whose host is one of these ancestors (nearest
|
|
735
889
|
// first), or null: a shell command run by an agent speaks as its session.
|
|
736
|
-
sessionForAncestors(ancestors) {
|
|
890
|
+
sessionForAncestors(ancestors, machine) {
|
|
891
|
+
const at = this.machineKey({ ...(machine !== undefined ? { machine } : {}) });
|
|
737
892
|
const candidates = this.store
|
|
738
893
|
.listSessions()
|
|
739
|
-
.filter((row) => row.state !== 'ended' && ancestors.includes(row.hostPid));
|
|
894
|
+
.filter((row) => row.state !== 'ended' && row.hostMachine === at && ancestors.includes(row.hostPid));
|
|
740
895
|
const table = this.safeProcTable(candidates.map((row) => row.hostPid));
|
|
741
896
|
const live = candidates.filter((row) => this.alive(table, row));
|
|
742
897
|
for (const pid of ancestors) {
|
|
@@ -767,12 +922,19 @@ export class MurmurCore {
|
|
|
767
922
|
if (!this.claimable(handle, row.id)) {
|
|
768
923
|
throw new MurmurError('bad_request', 'handle ' + handle + ' is taken by a live session or the owner');
|
|
769
924
|
}
|
|
770
|
-
|
|
925
|
+
// A handle can still be held by several sessions at once (a client that
|
|
926
|
+
// sends no machine id looks dead to this broker when it runs elsewhere).
|
|
927
|
+
// Renaming the identity would carry them all along and rewrite their
|
|
928
|
+
// history, so while another live session holds the old handle, only this
|
|
929
|
+
// session moves.
|
|
930
|
+
const others = this.store.sessionsForHandle(row.handle).filter((r) => r.id !== row.id);
|
|
931
|
+
const shared = this.liveHolders(row.handle, row.id).length > 0;
|
|
932
|
+
if (!shared && this.store.getPeer(handle) === null) {
|
|
771
933
|
this.store.renamePeer(row.handle, handle);
|
|
772
934
|
return handle;
|
|
773
935
|
}
|
|
774
|
-
|
|
775
|
-
this.store.reassignSession(row.id, row.handle, handle);
|
|
936
|
+
this.ensurePeer(handle);
|
|
937
|
+
this.store.reassignSession(row.id, row.handle, handle, !shared);
|
|
776
938
|
if (others.length === 0 && !this.store.peerHasHistory(row.handle)) {
|
|
777
939
|
this.store.deletePeer(row.handle);
|
|
778
940
|
}
|
|
@@ -795,9 +957,28 @@ export class MurmurCore {
|
|
|
795
957
|
}
|
|
796
958
|
return removed;
|
|
797
959
|
}
|
|
960
|
+
// True when a session that has not ended holds the handle, whether or not
|
|
961
|
+
// this machine can see its process.
|
|
962
|
+
holdsHandle(handle) {
|
|
963
|
+
this.ownMachine();
|
|
964
|
+
return this.liveHolders(handle, null).length > 0;
|
|
965
|
+
}
|
|
966
|
+
// True while another live session holds this session's handle:
|
|
967
|
+
// the handle's one native transport is theirs too, so neither may replace
|
|
968
|
+
// or delete it.
|
|
969
|
+
sharesHandle(row) {
|
|
970
|
+
return this.liveHolders(row.handle, row.id).length > 0;
|
|
971
|
+
}
|
|
972
|
+
// The live sessions holding the handle, other than exceptId.
|
|
973
|
+
liveHolders(handle, exceptId) {
|
|
974
|
+
const rows = this.store.sessionsForHandle(handle).filter((r) => r.id !== exceptId && r.state !== 'ended');
|
|
975
|
+
const table = this.safeProcTable(rows.map((r) => r.hostPid));
|
|
976
|
+
return rows.filter((r) => this.alive(table, r));
|
|
977
|
+
}
|
|
798
978
|
// A handle can be claimed when it is valid, not the owner's, and no live
|
|
799
979
|
// session other than exceptId holds it.
|
|
800
980
|
claimable(handle, exceptId) {
|
|
981
|
+
this.ownMachine();
|
|
801
982
|
if (!HANDLE_RE.test(handle)) {
|
|
802
983
|
return false;
|
|
803
984
|
}
|
|
@@ -821,8 +1002,20 @@ export class MurmurCore {
|
|
|
821
1002
|
}
|
|
822
1003
|
return handle;
|
|
823
1004
|
}
|
|
1005
|
+
// A session of this machine is alive while its process is, as the process
|
|
1006
|
+
// table shows it. This broker cannot see the process of another machine's
|
|
1007
|
+
// session, so that one is alive while a connection of its host is open or for
|
|
1008
|
+
// a lease after its last event. Callers pass sessions that have not ended.
|
|
824
1009
|
alive(table, row) {
|
|
825
|
-
|
|
1010
|
+
if (this.hostConnected(row)) {
|
|
1011
|
+
return true;
|
|
1012
|
+
}
|
|
1013
|
+
if (row.hostMachine === null) {
|
|
1014
|
+
return isAlive(table, row.hostPid, row.hostStart);
|
|
1015
|
+
}
|
|
1016
|
+
// Right after this broker starts no connection has come back yet, so every
|
|
1017
|
+
// session of another machine counts as alive until they have had time to.
|
|
1018
|
+
return this.nowMs() - row.updatedAt <= REMOTE_LEASE_MS || this.nowMs() - this.startedAt <= STARTUP_GRACE_MS;
|
|
826
1019
|
}
|
|
827
1020
|
safeProcTable(pids) {
|
|
828
1021
|
try {
|
package/dist/hooks.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { closeSync, fstatSync, openSync, readSync } from 'node:fs';
|
|
2
2
|
import { connectBroker } from './client.js';
|
|
3
3
|
import { getPaths, readToken } from './config.js';
|
|
4
|
+
import { readUptime, thisMachineRef } from './machine.js';
|
|
4
5
|
import { currentHost } from './proc.js';
|
|
5
6
|
export const HOOK_CLIENTS = ['claude', 'codex', 'gemini', 'zcode'];
|
|
6
7
|
// Hard cap on the broker interaction. A hook runs inline inside a session
|
|
@@ -32,7 +33,7 @@ export async function runHook(event, stdinText, env, opts) {
|
|
|
32
33
|
conn.close();
|
|
33
34
|
}, HOOK_DEADLINE_MS);
|
|
34
35
|
try {
|
|
35
|
-
const { handle } = await conn.request(sessionMessage(event, client, input, host, env));
|
|
36
|
+
const { handle } = await conn.request(sessionMessage(event, client, input, host, env, opts?.machine ?? thisMachineRef(), opts?.uptime ?? readUptime()));
|
|
36
37
|
if (event === 'session-end') {
|
|
37
38
|
return { exitCode: 0, stdout: '' };
|
|
38
39
|
}
|
|
@@ -55,13 +56,13 @@ export async function runHook(event, stdinText, env, opts) {
|
|
|
55
56
|
return { exitCode: 0, stdout: '' };
|
|
56
57
|
}
|
|
57
58
|
}
|
|
58
|
-
function sessionMessage(event, client, input, host, env) {
|
|
59
|
+
function sessionMessage(event, client, input, host, env, machine, uptime) {
|
|
59
60
|
const msg = {
|
|
60
61
|
type: 'session',
|
|
61
62
|
event,
|
|
62
63
|
client,
|
|
63
64
|
cliSessionId: input.sessionId,
|
|
64
|
-
host: { hostPid: host.hostPid, hostStart: host.hostStart },
|
|
65
|
+
host: { hostPid: host.hostPid, hostStart: host.hostStart, ...machine, ...(machine.machine !== undefined && uptime !== undefined ? { machineUptime: uptime } : {}) },
|
|
65
66
|
};
|
|
66
67
|
// zcode hands hooks a synthetic transcript it deletes afterwards, so it
|
|
67
68
|
// cannot serve as delivery proof.
|
package/dist/machine.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { readFileSync, readlinkSync } from 'node:fs';
|
|
4
|
+
import { hostname } from 'node:os';
|
|
5
|
+
// A host reference is a pid and a start time, which only mean something on the
|
|
6
|
+
// machine that ran the process. `machine` names that machine and rides along
|
|
7
|
+
// with every host reference: the boot id, a uuid per machine and boot (a
|
|
8
|
+
// rebooted machine or a clone is another machine). `machineName`, the host
|
|
9
|
+
// name, is only a label: it is never compared for sameness (a host name can
|
|
10
|
+
// change while a machine runs), and only tells the broker that a machine it
|
|
11
|
+
// knew rebooted. A client that cannot read a boot id sends neither field and
|
|
12
|
+
// is judged as one of the broker's own machine, as before this existed.
|
|
13
|
+
const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
|
|
14
|
+
// A machine from the wire: a boot id, optionally followed by `:` and the number
|
|
15
|
+
// of its pid namespace (Linux).
|
|
16
|
+
const MACHINE_FULL = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(:[0-9]{1,20})?$/i;
|
|
17
|
+
// What a machine field may hold where it enters the broker.
|
|
18
|
+
const FIELD = /^[^\u0000-\u001f\u007f]{1,255}$/;
|
|
19
|
+
// The boot uuid inside Linux's /proc/sys/kernel/random/boot_id or macOS's
|
|
20
|
+
// `sysctl -n kern.bootsessionuuid` (also with its `name: ` prefix), lower
|
|
21
|
+
// case; empty when the text holds none.
|
|
22
|
+
export function parseBootId(text) {
|
|
23
|
+
return UUID.exec(text)?.[0].toLowerCase() ?? '';
|
|
24
|
+
}
|
|
25
|
+
// Linux reads /proc, macOS asks sysctl by absolute path with a one second
|
|
26
|
+
// limit (the one thing to confirm on a Mac: `sysctl -n kern.bootsessionuuid`
|
|
27
|
+
// prints a uuid). Anything else, or a failure, has no boot id.
|
|
28
|
+
export const SYSCTL_OPTIONS = { encoding: 'utf8', timeout: 1000, stdio: ['ignore', 'pipe', 'ignore'] };
|
|
29
|
+
const defaultRead = (path) => readFileSync(path, 'utf8');
|
|
30
|
+
const defaultRun = (cmd, args) => execFileSync(cmd, args, SYSCTL_OPTIONS);
|
|
31
|
+
export function readBootId(platform = process.platform, readFile = defaultRead, run = defaultRun) {
|
|
32
|
+
try {
|
|
33
|
+
if (platform === 'linux') {
|
|
34
|
+
return parseBootId(readFile('/proc/sys/kernel/random/boot_id'));
|
|
35
|
+
}
|
|
36
|
+
if (platform === 'darwin') {
|
|
37
|
+
return parseBootId(run('/usr/sbin/sysctl', ['-n', 'kern.bootsessionuuid']));
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
// No boot id.
|
|
42
|
+
}
|
|
43
|
+
return '';
|
|
44
|
+
}
|
|
45
|
+
// The machine id: the boot id, or '' when there is none. The host name is not
|
|
46
|
+
// part of it (it is only the label of machineRef), so it is not consulted.
|
|
47
|
+
export function machineId(_name = hostname(), bootId = readBootId()) {
|
|
48
|
+
return bootId;
|
|
49
|
+
}
|
|
50
|
+
// Seconds since this machine booted: /proc/uptime on Linux, the boot time that
|
|
51
|
+
// `sysctl -n kern.boottime` prints (`{ sec = 1700000000, usec = 0 } ...`) on
|
|
52
|
+
// macOS; undefined when it cannot be read. Sent with a session event so the
|
|
53
|
+
// broker can tell that a machine booted after the last time it heard from the
|
|
54
|
+
// old sessions it holds under the same host name (src/core.ts).
|
|
55
|
+
export function readUptime(platform = process.platform, readFile = defaultRead, run = defaultRun, nowMs = Date.now()) {
|
|
56
|
+
try {
|
|
57
|
+
if (platform === 'linux') {
|
|
58
|
+
const seconds = Number.parseFloat(readFile('/proc/uptime'));
|
|
59
|
+
return Number.isFinite(seconds) && seconds >= 0 ? Math.floor(seconds) : undefined;
|
|
60
|
+
}
|
|
61
|
+
if (platform === 'darwin') {
|
|
62
|
+
const booted = /sec\s*=\s*(\d+)/.exec(run('/usr/sbin/sysctl', ['-n', 'kern.boottime']))?.[1];
|
|
63
|
+
return booted === undefined ? undefined : Math.max(0, Math.floor(nowMs / 1000) - Number(booted));
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
// No uptime.
|
|
68
|
+
}
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
// A machine uptime from the wire: finite seconds, 0 to 10 years.
|
|
72
|
+
export function validUptime(value) {
|
|
73
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 315_360_000 ? value : undefined;
|
|
74
|
+
}
|
|
75
|
+
// The number inside `/proc/self/ns/pid` (`pid:[4026531836]`): the pid namespace
|
|
76
|
+
// of this process, empty when there is none to read (not Linux, or no access).
|
|
77
|
+
// A process table is only one machine's if its processes share this number.
|
|
78
|
+
export function readPidNamespace(platform = process.platform, readLink = (path) => readlinkSync(path)) {
|
|
79
|
+
try {
|
|
80
|
+
return platform === 'linux' ? (/\[(\d+)\]/.exec(readLink('/proc/self/ns/pid'))?.[1] ?? '') : '';
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return '';
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// What tells one machine from a lookalike across reboots: a hash of the id the
|
|
87
|
+
// system keeps for itself (Linux `/etc/machine-id`, else
|
|
88
|
+
// `/var/lib/dbus/machine-id`; macOS the IOPlatformUUID `ioreg` prints). The raw
|
|
89
|
+
// id never leaves the machine: the value is the first 32 hex characters of
|
|
90
|
+
// sha256("murmur-machine:" + id). Unreadable or empty: undefined, and the
|
|
91
|
+
// broker then never reads a boot id change as a reboot.
|
|
92
|
+
// The id systemd keeps in /etc/machine-id: 32 lower case hex characters. A
|
|
93
|
+
// placeholder (`uninitialized`) or one baked into an image names no machine.
|
|
94
|
+
const SYSTEM_ID = /^[0-9a-f]{32}$/;
|
|
95
|
+
const IOREG_UUID = /"IOPlatformUUID"\s*=\s*"([0-9a-f-]{36})"/i;
|
|
96
|
+
export function readFingerprint(platform = process.platform, readFile = defaultRead, run = defaultRun) {
|
|
97
|
+
const attempt = (read) => {
|
|
98
|
+
try {
|
|
99
|
+
return read();
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return '';
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
let raw = '';
|
|
106
|
+
if (platform === 'linux') {
|
|
107
|
+
raw = attempt(() => readFile('/etc/machine-id').trim());
|
|
108
|
+
raw = SYSTEM_ID.test(raw) ? raw : attempt(() => readFile('/var/lib/dbus/machine-id').trim());
|
|
109
|
+
raw = SYSTEM_ID.test(raw) ? raw : '';
|
|
110
|
+
}
|
|
111
|
+
else if (platform === 'darwin') {
|
|
112
|
+
raw = attempt(() => IOREG_UUID.exec(run('/usr/sbin/ioreg', ['-rd1', '-c', 'IOPlatformExpertDevice']))?.[1] ?? '');
|
|
113
|
+
}
|
|
114
|
+
return raw === '' ? undefined : createHash('sha256').update('murmur-machine:' + raw).digest('hex').slice(0, 32);
|
|
115
|
+
}
|
|
116
|
+
// What a client puts next to its host reference: the boot id and the host
|
|
117
|
+
// name, or nothing when there is no boot id.
|
|
118
|
+
export function machineRef(bootId = readBootId(), name = hostname(), pidNamespace = readPidNamespace(), fingerprint = readFingerprint) {
|
|
119
|
+
if (bootId === '') {
|
|
120
|
+
return {};
|
|
121
|
+
}
|
|
122
|
+
const read = fingerprint();
|
|
123
|
+
return {
|
|
124
|
+
machine: pidNamespace === '' ? bootId : bootId + ':' + pidNamespace,
|
|
125
|
+
machineName: name,
|
|
126
|
+
...(read != null ? { machineFingerprint: read } : {}),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
// A read that happens once: a later failing read cannot change what a process
|
|
130
|
+
// said before.
|
|
131
|
+
export function once(read) {
|
|
132
|
+
let value;
|
|
133
|
+
return () => {
|
|
134
|
+
value ??= { v: read() };
|
|
135
|
+
return value.v;
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
// A read kept once it has worked: a failed read is tried again, at most once
|
|
139
|
+
// per `retryMs`, so a boot id that could not be read at start (a sysctl that
|
|
140
|
+
// timed out) is picked up later, while a good value is never replaced.
|
|
141
|
+
export function onceOk(read, ok, retryMs, now = Date.now) {
|
|
142
|
+
let good;
|
|
143
|
+
let last;
|
|
144
|
+
return () => {
|
|
145
|
+
if (good !== undefined) {
|
|
146
|
+
return good.v;
|
|
147
|
+
}
|
|
148
|
+
if (last === undefined || now() - last.at >= retryMs) {
|
|
149
|
+
const v = read();
|
|
150
|
+
last = { v, at: now() };
|
|
151
|
+
if (ok(v)) {
|
|
152
|
+
good = { v };
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return last.v;
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
// This machine's reference: read once it has worked, tried again every minute
|
|
159
|
+
// while it has not.
|
|
160
|
+
export function machineReader(read = machineRef, now = Date.now) {
|
|
161
|
+
return onceOk(read, (ref) => ref.machine !== undefined, 60_000, now);
|
|
162
|
+
}
|
|
163
|
+
export const thisMachineRef = machineReader();
|
|
164
|
+
// The machine of a reference (boot id, with the pid namespace on Linux), or ''
|
|
165
|
+
// when it has none.
|
|
166
|
+
export function machineOf(ref) {
|
|
167
|
+
return ref.machine ?? '';
|
|
168
|
+
}
|
|
169
|
+
// This machine's id, or '' when it has none.
|
|
170
|
+
export function thisMachine() {
|
|
171
|
+
return machineOf(thisMachineRef());
|
|
172
|
+
}
|
|
173
|
+
// A machine from the wire: a uuid, lower case, optionally followed by `:` and
|
|
174
|
+
// 1 to 20 digits; undefined for anything else, so one machine is one value
|
|
175
|
+
// however a client writes it.
|
|
176
|
+
export function validBootId(value) {
|
|
177
|
+
return typeof value === 'string' && MACHINE_FULL.test(value) ? value.toLowerCase() : undefined;
|
|
178
|
+
}
|
|
179
|
+
// A fingerprint from the wire: 32 lower case hex characters, else undefined.
|
|
180
|
+
export function validFingerprint(value) {
|
|
181
|
+
return typeof value === 'string' && /^[0-9a-f]{32}$/.test(value) ? value : undefined;
|
|
182
|
+
}
|
|
183
|
+
// What a session event may say about its machine, from the wire: the machine
|
|
184
|
+
// (a boot id, lower case), and, next to it only, the host name as a label, the
|
|
185
|
+
// uptime and the fingerprint. Anything that is not of its shape reads as absent.
|
|
186
|
+
export function parseWireMachine(rec) {
|
|
187
|
+
const machine = validBootId(rec.machine);
|
|
188
|
+
if (machine === undefined) {
|
|
189
|
+
return {};
|
|
190
|
+
}
|
|
191
|
+
const machineName = validField(rec.machineName);
|
|
192
|
+
const machineUptime = validUptime(rec.machineUptime);
|
|
193
|
+
const machineFingerprint = validFingerprint(rec.machineFingerprint);
|
|
194
|
+
return {
|
|
195
|
+
machine,
|
|
196
|
+
...(machineName !== undefined ? { machineName } : {}),
|
|
197
|
+
...(machineUptime !== undefined ? { machineUptime } : {}),
|
|
198
|
+
...(machineFingerprint !== undefined ? { machineFingerprint } : {}),
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
// A machine field from the wire: undefined unless it is 1 to 255 printable
|
|
202
|
+
// characters without a line break.
|
|
203
|
+
export function validField(value) {
|
|
204
|
+
return typeof value === 'string' && FIELD.test(value) ? value : undefined;
|
|
205
|
+
}
|
package/dist/mcp.js
CHANGED
|
@@ -5,6 +5,7 @@ import { z } from 'zod';
|
|
|
5
5
|
import { connectBroker } from './client.js';
|
|
6
6
|
import { getPaths, isRemoteHome, readToken } from './config.js';
|
|
7
7
|
import { nativeSend } from './native.js';
|
|
8
|
+
import { thisMachineRef } from './machine.js';
|
|
8
9
|
import { currentHost } from './proc.js';
|
|
9
10
|
import { HANDLE_RE, MurmurError, WAIT_DEFAULT_MS, WAIT_MAX_MS, noticeText } from './protocol.js';
|
|
10
11
|
// MCP stdio server exposing the murmur broker to agent sessions. Every tool
|
|
@@ -36,11 +37,11 @@ export function clientFromEnv(env) {
|
|
|
36
37
|
}
|
|
37
38
|
return 'other';
|
|
38
39
|
}
|
|
39
|
-
export function identityFor(host, env, cwd) {
|
|
40
|
+
export function identityFor(host, env, cwd, machine = thisMachineRef()) {
|
|
40
41
|
if (host === null) {
|
|
41
42
|
return {};
|
|
42
43
|
}
|
|
43
|
-
return { host: { hostPid: host.hostPid, hostStart: host.hostStart }, client: clientFromEnv(env), cwd };
|
|
44
|
+
return { host: { hostPid: host.hostPid, hostStart: host.hostStart, ...machine }, client: clientFromEnv(env), cwd };
|
|
44
45
|
}
|
|
45
46
|
export function buildMcpServer(client, identity = {}) {
|
|
46
47
|
const server = new McpServer({ name: 'murmur', version: VERSION }, { instructions: INSTRUCTIONS });
|
package/dist/store.js
CHANGED
|
@@ -85,6 +85,9 @@ CREATE INDEX IF NOT EXISTS idx_sessions_host ON sessions (host_pid, host_start,
|
|
|
85
85
|
const ADDED_COLUMNS = [
|
|
86
86
|
['messages', 'via', 'TEXT'],
|
|
87
87
|
['sessions', 'pinned', 'INTEGER NOT NULL DEFAULT 0'],
|
|
88
|
+
['sessions', 'host_machine', 'TEXT'],
|
|
89
|
+
['sessions', 'host_label', 'TEXT'],
|
|
90
|
+
['sessions', 'host_fingerprint', 'TEXT'],
|
|
88
91
|
];
|
|
89
92
|
// Delivery states that still count as unread for inbox purposes.
|
|
90
93
|
const UNREAD_STATES_SQL = "('queued','sent','delivered')";
|
|
@@ -108,6 +111,9 @@ function toSessionRow(r) {
|
|
|
108
111
|
handle: r.handle,
|
|
109
112
|
hostPid: r.host_pid,
|
|
110
113
|
hostStart: r.host_start,
|
|
114
|
+
hostMachine: r.host_machine,
|
|
115
|
+
hostLabel: r.host_label,
|
|
116
|
+
hostFingerprint: r.host_fingerprint,
|
|
111
117
|
transcriptPath: r.transcript_path,
|
|
112
118
|
cwd: r.cwd,
|
|
113
119
|
state: r.state,
|
|
@@ -447,19 +453,48 @@ export class Store {
|
|
|
447
453
|
.get(client, cliSessionId);
|
|
448
454
|
return rec === undefined ? null : toSessionRow(rec);
|
|
449
455
|
}
|
|
450
|
-
// The newest session recorded for this exact host process
|
|
451
|
-
|
|
456
|
+
// The newest session recorded for this exact host process: pid, start and
|
|
457
|
+
// machine (null is the broker's own machine).
|
|
458
|
+
sessionByHost(hostPid, hostStart, hostMachine) {
|
|
459
|
+
const rec = this.stmt('SELECT * FROM sessions WHERE host_pid = ? AND host_start = ? AND host_machine IS ? ORDER BY updated_at DESC, id DESC LIMIT 1')
|
|
460
|
+
.get(hostPid, hostStart, hostMachine);
|
|
461
|
+
return rec === undefined ? null : toSessionRow(rec);
|
|
462
|
+
}
|
|
463
|
+
// The newest session recorded for this pid and start on any machine.
|
|
464
|
+
sessionOfHost(hostPid, hostStart) {
|
|
452
465
|
const rec = this.stmt('SELECT * FROM sessions WHERE host_pid = ? AND host_start = ? ORDER BY updated_at DESC, id DESC LIMIT 1')
|
|
453
466
|
.get(hostPid, hostStart);
|
|
454
467
|
return rec === undefined ? null : toSessionRow(rec);
|
|
455
468
|
}
|
|
469
|
+
// Every session recorded for this pid and start on any machine, newest first.
|
|
470
|
+
sessionsOfHost(hostPid, hostStart) {
|
|
471
|
+
const recs = this.stmt('SELECT * FROM sessions WHERE host_pid = ? AND host_start = ? ORDER BY updated_at DESC, id DESC').all(hostPid, hostStart);
|
|
472
|
+
return recs.map(toSessionRow);
|
|
473
|
+
}
|
|
474
|
+
// The sessions that have not ended, of the machine with this fingerprint and
|
|
475
|
+
// host name label, recorded under a boot id other than `machine`: a reboot
|
|
476
|
+
// ended them.
|
|
477
|
+
rebootedSessions(fingerprint, label, machine, exceptId) {
|
|
478
|
+
const recs = this.stmt("SELECT * FROM sessions WHERE host_fingerprint = ? AND host_label = ? AND host_machine IS NOT NULL AND host_machine != ? AND id != ? AND (state IS NULL OR state != 'ended')").all(fingerprint, label, machine, exceptId);
|
|
479
|
+
return recs.map(toSessionRow);
|
|
480
|
+
}
|
|
481
|
+
// The sessions recorded under this machine are the broker's own: it learned
|
|
482
|
+
// its boot id after they were written. Their machine, label and fingerprint
|
|
483
|
+
// go back to the own-machine form (NULL), which the process table judges.
|
|
484
|
+
rekeyMachine(machine) {
|
|
485
|
+
this.stmt('UPDATE sessions SET host_machine = NULL, host_label = NULL, host_fingerprint = NULL WHERE host_machine = ?').run(machine);
|
|
486
|
+
}
|
|
456
487
|
// Points one session at another, existing handle and moves its native
|
|
457
488
|
// transport along.
|
|
458
|
-
|
|
489
|
+
// The target's old transport is stale once the session takes the handle; the
|
|
490
|
+
// session's own transport follows unless the old handle keeps another session.
|
|
491
|
+
reassignSession(id, fromHandle, toHandle, moveTransport = true) {
|
|
459
492
|
const move = this.db.transaction(() => {
|
|
460
493
|
this.stmt('UPDATE sessions SET handle = ? WHERE id = ?').run(toHandle, id);
|
|
461
494
|
this.stmt('DELETE FROM native_transports WHERE owner = ?').run(toHandle);
|
|
462
|
-
|
|
495
|
+
if (moveTransport) {
|
|
496
|
+
this.stmt('UPDATE native_transports SET owner = ? WHERE owner = ?').run(toHandle, fromHandle);
|
|
497
|
+
}
|
|
463
498
|
});
|
|
464
499
|
move();
|
|
465
500
|
}
|
|
@@ -492,8 +527,8 @@ export class Store {
|
|
|
492
527
|
return recs.map(toSessionRow);
|
|
493
528
|
}
|
|
494
529
|
insertSession(arg) {
|
|
495
|
-
const info = this.stmt(`INSERT INTO sessions (client, cli_session_id, handle, host_pid, host_start, transcript_path, cwd, state, state_at, started_at, updated_at)
|
|
496
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?)`).run(arg.client, arg.cliSessionId, arg.handle, arg.hostPid, arg.hostStart, arg.transcriptPath, arg.cwd, arg.now, arg.now);
|
|
530
|
+
const info = this.stmt(`INSERT INTO sessions (client, cli_session_id, handle, host_pid, host_start, host_machine, host_label, host_fingerprint, transcript_path, cwd, state, state_at, started_at, updated_at)
|
|
531
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?)`).run(arg.client, arg.cliSessionId, arg.handle, arg.hostPid, arg.hostStart, arg.hostMachine, arg.hostLabel, arg.hostFingerprint, arg.transcriptPath, arg.cwd, arg.now, arg.now);
|
|
497
532
|
return Number(info.lastInsertRowid);
|
|
498
533
|
}
|
|
499
534
|
// Applies only the keys present in the patch.
|
|
@@ -503,6 +538,9 @@ export class Store {
|
|
|
503
538
|
['cliSessionId', 'cli_session_id'],
|
|
504
539
|
['hostPid', 'host_pid'],
|
|
505
540
|
['hostStart', 'host_start'],
|
|
541
|
+
['hostMachine', 'host_machine'],
|
|
542
|
+
['hostLabel', 'host_label'],
|
|
543
|
+
['hostFingerprint', 'host_fingerprint'],
|
|
506
544
|
['transcriptPath', 'transcript_path'],
|
|
507
545
|
['cwd', 'cwd'],
|
|
508
546
|
['state', 'state'],
|