@murmurv2/cli 2.11.0 → 2.13.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.
Files changed (69) hide show
  1. package/README.md +85 -19
  2. package/package.json +8 -6
  3. package/runtime/bin/murmur-svc.exe +0 -0
  4. package/runtime/npm-runtime-manifest.json +193 -81
  5. package/runtime/package.json +1 -1
  6. package/runtime/packages/mcp-server/dist/src/agent-config.js +1 -0
  7. package/runtime/packages/setup/bin/murmur.mjs +6 -3
  8. package/runtime/packages/setup/dist/src/backups.d.ts +36 -0
  9. package/runtime/packages/setup/dist/src/backups.js +128 -0
  10. package/runtime/packages/setup/dist/src/broker-input.d.ts +24 -0
  11. package/runtime/packages/setup/dist/src/broker-input.js +98 -0
  12. package/runtime/packages/setup/dist/src/broker-migration.d.ts +35 -0
  13. package/runtime/packages/setup/dist/src/broker-migration.js +138 -0
  14. package/runtime/packages/setup/dist/src/cli-error.d.ts +2 -0
  15. package/runtime/packages/setup/dist/src/cli-error.js +30 -0
  16. package/runtime/packages/setup/dist/src/cli.d.ts +1 -1
  17. package/runtime/packages/setup/dist/src/cli.js +111 -14
  18. package/runtime/packages/setup/dist/src/clients.d.ts +28 -76
  19. package/runtime/packages/setup/dist/src/clients.js +166 -26
  20. package/runtime/packages/setup/dist/src/commands.d.ts +3 -1
  21. package/runtime/packages/setup/dist/src/commands.js +18 -7
  22. package/runtime/packages/setup/dist/src/config.d.ts +10 -0
  23. package/runtime/packages/setup/dist/src/config.js +119 -10
  24. package/runtime/packages/setup/dist/src/connect.d.ts +143 -0
  25. package/runtime/packages/setup/dist/src/connect.js +126 -0
  26. package/runtime/packages/setup/dist/src/doctor.d.ts +42 -0
  27. package/runtime/packages/setup/dist/src/doctor.js +89 -10
  28. package/runtime/packages/setup/dist/src/installation.d.ts +25 -0
  29. package/runtime/packages/setup/dist/src/installation.js +89 -0
  30. package/runtime/packages/setup/dist/src/invitation-server.d.ts +2 -0
  31. package/runtime/packages/setup/dist/src/invitation-server.js +45 -0
  32. package/runtime/packages/setup/dist/src/message-status.d.ts +5 -0
  33. package/runtime/packages/setup/dist/src/message-status.js +13 -0
  34. package/runtime/packages/setup/dist/src/onboarding.d.ts +28 -10
  35. package/runtime/packages/setup/dist/src/onboarding.js +129 -34
  36. package/runtime/packages/setup/dist/src/outbox-attention.js +3 -21
  37. package/runtime/packages/setup/dist/src/paths.d.ts +7 -0
  38. package/runtime/packages/setup/dist/src/paths.js +39 -24
  39. package/runtime/packages/setup/dist/src/platform/darwin.d.ts +3 -0
  40. package/runtime/packages/setup/dist/src/platform/darwin.js +241 -9
  41. package/runtime/packages/setup/dist/src/platform/linux.js +152 -17
  42. package/runtime/packages/setup/dist/src/platform/profile-usage.d.ts +20 -0
  43. package/runtime/packages/setup/dist/src/platform/profile-usage.js +89 -0
  44. package/runtime/packages/setup/dist/src/platform/windows.js +89 -4
  45. package/runtime/packages/setup/dist/src/private-file.d.ts +4 -1
  46. package/runtime/packages/setup/dist/src/private-file.js +39 -3
  47. package/runtime/packages/setup/dist/src/state.d.ts +4 -0
  48. package/runtime/packages/setup/dist/src/state.js +65 -1
  49. package/runtime/packages/setup/dist/src/status.d.ts +26 -2
  50. package/runtime/packages/setup/dist/src/status.js +84 -20
  51. package/runtime/packages/setup/dist/src/types.d.ts +21 -1
  52. package/runtime/packages/setup/dist/src/verdict.js +4 -2
  53. package/runtime/packages/setup/dist/src/wake-attention.d.ts +11 -0
  54. package/runtime/packages/setup/dist/src/wake-attention.js +44 -0
  55. package/runtime/packages/setup/dist/src/wake-readers.d.ts +12 -0
  56. package/runtime/packages/setup/dist/src/wake-readers.js +65 -0
  57. package/runtime/packages/setup/package.json +1 -1
  58. package/runtime/scripts/auth-security.mjs +93 -0
  59. package/runtime/scripts/codex-app-server-wake.mjs +182 -32
  60. package/runtime/scripts/daemon-contacts.mjs +56 -0
  61. package/runtime/scripts/daemon-flush-tick.mjs +25 -0
  62. package/runtime/scripts/daemon-link-watch.mjs +60 -0
  63. package/runtime/scripts/daemon-observation.mjs +74 -18
  64. package/runtime/scripts/murmur-auth-token.mjs +140 -0
  65. package/runtime/scripts/murmur-daemon.mjs +66 -36
  66. package/runtime/scripts/murmur-jetstream-advisory.mjs +27 -0
  67. package/runtime/scripts/murmur-shell-send.mjs +3 -3
  68. package/runtime/scripts/wake-drain-claude.mjs +193 -39
  69. package/runtime/scripts/wake-monitor.mjs +46 -18
@@ -0,0 +1,56 @@
1
+ import { AgentConfigCache } from '@murmurv2/mcp-server/dist/src/agent-config.js';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+
4
+ const key = value => typeof value === 'string' && Buffer.from(value, 'base64').length === 32
5
+ && Buffer.from(value, 'base64').toString('base64') === value;
6
+ const contactId = value => /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(value);
7
+
8
+ /** The config file's atomic replacement is the cross-platform reload trigger.
9
+ * Share MCP's owner/path/identity/runtime pinning. Failed reads cannot introduce
10
+ * new trust: keep the last valid Contacts available and report the failure. */
11
+ export function createDaemonContacts(configPath, log = () => {}) {
12
+ const cache = new AgentConfigCache(configPath);
13
+ const initial = cache.read();
14
+ const config = { ...initial, peers: {} };
15
+ let applied, failure, invalidSignature = '[]';
16
+ let diagnostic = { state: 'current', count: 0, invalidCount: 0,
17
+ lastSuccessAt: null, lastError: null, lastErrorAt: null };
18
+ const refresh = (force = false) => {
19
+ try {
20
+ const next = cache.read(force);
21
+ if (applied === next && !failure) return config.peers;
22
+ const invalid = [];
23
+ const peers = Object.fromEntries(Object.entries(next.peers).filter(([id, peer]) => {
24
+ if (contactId(id) && peer && typeof peer.subject === 'string' && /^[A-Za-z0-9_.:-]+$/.test(peer.subject)
25
+ && key(peer.encryption?.publicKey) && key(peer.signing?.publicKey)) return true;
26
+ invalid.push(contactId(id) ? id : null);
27
+ return false;
28
+ }));
29
+ const signature = JSON.stringify(invalid.sort());
30
+ const changed = !isDeepStrictEqual(config.peers, peers);
31
+ config.peers = peers;
32
+ const at = new Date().toISOString();
33
+ diagnostic = { state: invalid.length ? 'partial' : 'current', count: Object.keys(peers).length,
34
+ invalidCount: invalid.length, lastSuccessAt: at,
35
+ lastError: invalid.length ? 'agent-config-peer-invalid' : null,
36
+ lastErrorAt: invalid.length ? signature !== invalidSignature || failure ? at : diagnostic.lastErrorAt : null };
37
+ if (invalid.length && (signature !== invalidSignature || failure))
38
+ log('warn', 'Invalid Contacts skipped', { reason: 'agent-config-peer-invalid', contacts: invalid, count: invalid.length });
39
+ // MCP may change ctime by protecting the same file. Compare content, not
40
+ // cache object identity, before claiming that Contacts changed.
41
+ if ((applied && changed) || failure) log('info', 'Contacts reloaded', { count: diagnostic.count });
42
+ invalidSignature = signature;
43
+ applied = next; failure = undefined;
44
+ return config.peers;
45
+ } catch (error) {
46
+ const reason = /^agent-config-[a-z-]+$/.test(error?.message) ? error.message : 'agent-config-unavailable-retry-or-restart';
47
+ if (failure !== reason) log('error', 'Contacts reload failed', { reason });
48
+ diagnostic = { ...diagnostic, state: 'retained', lastError: reason,
49
+ lastErrorAt: failure === reason ? diagnostic.lastErrorAt : new Date().toISOString() };
50
+ failure = reason;
51
+ return config.peers;
52
+ }
53
+ };
54
+ refresh();
55
+ return { config, refresh, diagnostics: () => ({ ...diagnostic }) };
56
+ }
@@ -0,0 +1,25 @@
1
+ // One pass of the daemon delivery loop. Outbound letters and notifications keep flowing
2
+ // while an assistant works: a wake turn can last many minutes, and awaiting it here held
3
+ // every reply in the outbox until the turn ended or timed out (24.09, the Mac sat on a
4
+ // ping from 11:29 to 11:36). WakeMonitor.drain() is single-flight, so starting it on
5
+ // every tick only kicks the running dispatcher; its rows stay durable across restarts.
6
+ export async function flushTick({ flushOutbox, flushNotify, drainWake, log }) {
7
+ try {
8
+ await flushOutbox();
9
+ } catch (err) {
10
+ log("error", "Outbox flush error", { error: err instanceof Error ? err.message : String(err) });
11
+ }
12
+
13
+ try {
14
+ await flushNotify();
15
+ } catch (err) {
16
+ log("error", "Notify flush error", { error: err instanceof Error ? err.message : String(err) });
17
+ }
18
+
19
+ // #105 — retry tick. With no drain running this reads the table: deliveries whose
20
+ // backoff has elapsed and rows a previous process left behind. A running drain is
21
+ // only nudged; such rows wait until it frees its conversations.
22
+ Promise.resolve()
23
+ .then(drainWake)
24
+ .catch((err) => log("error", "Wake retry drain error", { error: err instanceof Error ? err.message : String(err) }));
25
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Exit when the server link is gone (#276).
3
+ *
4
+ * A daemon whose broker connection has closed for good, or has been lost longer than the
5
+ * operator allows, keeps its PID and its supervisor's "healthy" while delivering nothing.
6
+ * This watch turns that into a non-zero exit so systemd, launchd or the Windows Service
7
+ * manager restart the daemon and the failure becomes visible in their status.
8
+ *
9
+ * - `exitOnClosed` (default on): the connection reported `closed` — auth abort after a
10
+ * rotated token, reconnect attempts exhausted — and will never come back by itself.
11
+ * - `maxDisconnectedMs` (default 0 = off): the link has been lost longer than this.
12
+ */
13
+ export function createLinkWatch({ observation, maxDisconnectedMs = 0, exitOnClosed = true, intervalMs, log = () => {}, onLost, now = () => Date.now() }) {
14
+ const limit = Number.isFinite(maxDisconnectedMs) && maxDisconnectedMs > 0 ? Math.floor(maxDisconnectedMs) : 0;
15
+ const enabled = exitOnClosed || limit > 0;
16
+ const period = intervalMs ?? (limit > 0 ? Math.max(1000, Math.min(30000, Math.floor(limit / 4))) : 5000);
17
+ let timer;
18
+ let fired = false;
19
+
20
+ const fire = (reason, data) => {
21
+ if (fired) return true;
22
+ fired = true;
23
+ log("fatal", "Server link is gone; exiting so the supervisor restarts the daemon", { reason, ...data });
24
+ onLost?.(reason);
25
+ return true;
26
+ };
27
+
28
+ const check = () => {
29
+ if (fired) return true;
30
+ if (!enabled) return false;
31
+ const broker = observation.broker();
32
+ if (exitOnClosed && broker.state === "closed") {
33
+ return fire("broker.link-closed", { lastError: broker.lastError, disconnectedAt: broker.disconnectedAt });
34
+ }
35
+ if (limit > 0) {
36
+ const disconnectedForMs = observation.disconnectedForMs(now());
37
+ if (disconnectedForMs > limit) {
38
+ return fire("broker.link-lost", { disconnectedAt: broker.disconnectedAt, disconnectedForMs, maxDisconnectedMs: limit,
39
+ reconnectAttempts: broker.reconnectAttempts });
40
+ }
41
+ }
42
+ return false;
43
+ };
44
+
45
+ return {
46
+ enabled,
47
+ maxDisconnectedMs: limit,
48
+ intervalMs: period,
49
+ start() {
50
+ if (!enabled || timer) return;
51
+ timer = setInterval(check, period);
52
+ timer.unref();
53
+ },
54
+ stop() {
55
+ if (timer) clearInterval(timer);
56
+ timer = undefined;
57
+ },
58
+ check,
59
+ };
60
+ }
@@ -3,38 +3,94 @@ import { realpath } from "node:fs/promises";
3
3
  import { writePrivateJson } from "./secure-state.mjs";
4
4
 
5
5
  /** Non-secret, PID/store-bound liveness evidence for the read-only setup CLI. */
6
- export function createDaemonObservation({ dataDir, storePath, agentId, wake, log = () => {} }) {
6
+ export function createDaemonObservation({ dataDir, storePath, agentId, wake, contacts = () => null, log = () => {} }) {
7
7
  const startedAt = new Date().toISOString();
8
8
  const snapshot = { schema: "murmur.runtime/1", agentId, pid: process.pid, startedAt,
9
9
  storePath: null, measuredAt: null, wake: { ...wake, lastFault: null, lastFaultAt: null },
10
- broker: { state: "unknown", connectedAt: null, lastError: null, lastErrorAt: null } };
11
- let writing = false;
10
+ broker: { state: "disconnected", connectedAt: null, disconnectedAt: startedAt, reconnectAttempts: 0,
11
+ lastError: "broker.connecting", lastErrorAt: startedAt } };
12
+ const knownReasons = ["broker.unauthorized", "broker.permission-denied", "broker.connection-refused", "broker.name-unresolved",
13
+ "broker.timeout", "broker.connection-failed", "broker.stale-connection", "broker.closed"];
14
+ const safeReason = (value) => knownReasons.includes(value) ? value : "broker.connection-failed";
15
+ let writes = Promise.resolve();
12
16
  let timer;
13
- const write = async () => {
14
- if (writing) return;
15
- writing = true;
17
+ const write = () => writes = writes.then(async () => {
16
18
  try {
17
19
  snapshot.storePath = await realpath(storePath);
18
20
  snapshot.measuredAt = new Date().toISOString();
21
+ snapshot.contacts = contacts();
19
22
  await writePrivateJson(path.join(dataDir, "daemon-observation.json"), snapshot);
20
23
  } catch { log("warn", "Daemon observation write failed", { reason: "runtime.observation-write-failed" }); }
21
- finally { writing = false; }
22
- };
24
+ });
23
25
  return {
24
- async start() { await write(); timer = setInterval(() => { void write(); }, 5000); timer.unref(); },
25
- async connected() { snapshot.broker.state = "connected"; snapshot.broker.connectedAt = new Date().toISOString(); await write(); },
26
+ async start() {
27
+ log("info", "Connecting to server", { reason: "broker.connecting" });
28
+ await write(); timer = setInterval(() => { void write(); }, 5000); timer.unref();
29
+ },
30
+ async connected() {
31
+ const broker = snapshot.broker;
32
+ broker.state = "connected"; broker.connectedAt = new Date().toISOString();
33
+ broker.disconnectedAt = null; broker.reconnectAttempts = 0;
34
+ await write();
35
+ },
26
36
  onStatus(event) {
27
- if (event.type === "disconnect") {
28
- snapshot.broker.state = "disconnected";
29
- snapshot.broker.lastError = "broker.disconnected";
30
- snapshot.broker.lastErrorAt = new Date().toISOString();
37
+ const broker = snapshot.broker;
38
+ const at = new Date().toISOString();
39
+ if (event.type === "connect_error") {
40
+ const reason = safeReason(event.data?.reason);
41
+ broker.state = reason === "broker.unauthorized" ? "unauthorized" : "disconnected";
42
+ broker.lastError = reason;
43
+ broker.lastErrorAt = at;
44
+ if (broker.disconnectedAt === null) broker.disconnectedAt = at;
45
+ log("warn", "Server connection failed; will retry", { reason });
46
+ } else if (event.type === "disconnect") {
47
+ broker.state = "disconnected";
48
+ broker.lastError = "broker.disconnected";
49
+ broker.lastErrorAt = at;
50
+ if (broker.disconnectedAt === null) broker.disconnectedAt = at;
51
+ broker.reconnectAttempts = 0;
52
+ } else if (event.type === "reconnecting") {
53
+ // #276 — every failed reconnect attempt is counted here; the broker logs them rate-limited.
54
+ if (broker.state === "connected") broker.state = "disconnected";
55
+ if (broker.disconnectedAt === null) {
56
+ broker.disconnectedAt = typeof event.data?.disconnectedAt === "string" ? event.data.disconnectedAt : at;
57
+ }
58
+ broker.reconnectAttempts = Number.isSafeInteger(event.data?.attempts) ? event.data.attempts : broker.reconnectAttempts + 1;
59
+ broker.lastError = "broker.reconnecting";
60
+ broker.lastErrorAt = at;
61
+ } else if (event.type === "error" || event.type === "staleConnection") {
62
+ const reason = safeReason(event.data?.reason);
63
+ broker.lastError = reason;
64
+ broker.lastErrorAt = at;
65
+ if (reason === "broker.unauthorized" && broker.state !== "connected") broker.state = "unauthorized";
66
+ } else if (event.type === "closed") {
67
+ // The client gave up (auth abort, attempts exhausted): nothing reconnects this process.
68
+ const reason = safeReason(event.data?.reason);
69
+ broker.state = "closed";
70
+ broker.lastError = reason;
71
+ broker.lastErrorAt = at;
72
+ if (broker.disconnectedAt === null) broker.disconnectedAt = at;
73
+ log("error", "Server connection closed for good; it will not reconnect on its own", { reason });
31
74
  } else if (event.type === "reconnect") {
32
- snapshot.broker.state = "connected";
33
- snapshot.broker.connectedAt = new Date().toISOString();
75
+ broker.state = "connected";
76
+ broker.connectedAt = at;
77
+ broker.disconnectedAt = null;
78
+ broker.reconnectAttempts = 0;
34
79
  }
35
- void write();
80
+ return write();
81
+ },
82
+ /** Read-only copy of the broker part of the snapshot. */
83
+ broker() { return { ...snapshot.broker }; },
84
+ /** Milliseconds since the server link was lost; 0 while connected. */
85
+ disconnectedForMs(now = Date.now()) {
86
+ const broker = snapshot.broker;
87
+ if (broker.state === "connected" || !broker.disconnectedAt) return 0;
88
+ return Math.max(0, now - Date.parse(broker.disconnectedAt));
36
89
  },
37
90
  observeLog(level, message, data) {
91
+ // This verdict was already committed to its message row. Let status follow
92
+ // that row (including an explicit CLI dismissal), not a sticky runtime fault.
93
+ if (message === 'WakeMonitor wake dead-lettered' && data?.error === 'accepted-turn-unobservable') return;
38
94
  // Preserve a monitor crash even when SQLite could not record the failed wake.
39
95
  // Never persist hook commands, stdout, message text or arbitrary error strings.
40
96
  if ((level === "error" || level === "fatal") && message.startsWith("WakeMonitor")) {
@@ -43,6 +99,6 @@ export function createDaemonObservation({ dataDir, storePath, agentId, wake, log
43
99
  return write();
44
100
  }
45
101
  },
46
- stop() { if (timer) clearInterval(timer); },
102
+ async stop() { if (timer) clearInterval(timer); await writes; },
47
103
  };
48
104
  }
@@ -0,0 +1,140 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * murmur-auth-token.mjs — Mint and verify roster-backed MURMUR-AUTH bearer tokens.
4
+ * Private keys are read only from 0600 files; never pass private keys on argv.
5
+ */
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import {
10
+ decodeAuthToken,
11
+ encodeAuthToken,
12
+ formatAddress,
13
+ parseAddress,
14
+ signAuthToken,
15
+ verifyAuthToken,
16
+ } from "@murmurv2/federation";
17
+ import { readPrivateJson } from "./secure-state.mjs";
18
+ import { loadRosterStoreFromBundle } from "./auth-security.mjs";
19
+
20
+ const HERE = fileURLToPath(import.meta.url);
21
+
22
+ function parseArgs(argv) {
23
+ const [subcommand, ...rest] = argv;
24
+ const opts = {};
25
+ for (let i = 0; i < rest.length; i++) {
26
+ const arg = rest[i];
27
+ if (!arg.startsWith("--")) throw new Error(`Unexpected argument: ${arg}`);
28
+ const key = arg.slice(2);
29
+ if (key === "token-stdin") {
30
+ opts.tokenStdin = true;
31
+ continue;
32
+ }
33
+ const val = rest[++i];
34
+ if (!val || val.startsWith("--")) throw new Error(`Missing value for --${key}`);
35
+ opts[key] = val;
36
+ }
37
+ return { subcommand, opts };
38
+ }
39
+
40
+ export async function runAuthTokenCli(argv, stdinText = null) {
41
+ const { subcommand, opts } = parseArgs(argv);
42
+ if (subcommand === "mint") {
43
+ for (const req of ["issuer", "subject", "audience", "signing-key-file"]) {
44
+ if (!opts[req]) throw new Error(`Missing --${req}`);
45
+ }
46
+ const ttlSec = opts["ttl-seconds"] ? Number(opts["ttl-seconds"]) : 3600;
47
+ if (!Number.isInteger(ttlSec) || ttlSec <= 0 || ttlSec > 365 * 86400) {
48
+ throw new Error("Invalid --ttl-seconds");
49
+ }
50
+ const scopes = (opts.scopes ?? "murmur:send").split(",").map((s) => s.trim()).filter(Boolean);
51
+ const keyMaterial = await readPrivateJson(path.resolve(opts["signing-key-file"]));
52
+ const signingPrivateKey = keyMaterial?.signingPrivateKey ?? keyMaterial?.keys?.signing?.privateKey;
53
+ if (typeof signingPrivateKey !== "string" || signingPrivateKey.length === 0) {
54
+ throw new Error("signing-key-file missing signingPrivateKey");
55
+ }
56
+ const nowMs = opts.now ? Date.parse(opts.now) : Date.now();
57
+ if (!Number.isFinite(nowMs)) throw new Error("Invalid --now");
58
+ const localOrg = opts["local-org"] ?? "local";
59
+ const issuedAt = new Date(nowMs).toISOString();
60
+ const expiresAt = new Date(nowMs + ttlSec * 1000).toISOString();
61
+ const signed = await signAuthToken(
62
+ {
63
+ issuer: parseAddress(opts.issuer, localOrg),
64
+ subject: parseAddress(opts.subject, localOrg),
65
+ audience: parseAddress(opts.audience, localOrg),
66
+ scopes,
67
+ issuedAt,
68
+ expiresAt,
69
+ ...(opts.nonce ? { nonce: opts.nonce } : {}),
70
+ },
71
+ signingPrivateKey,
72
+ );
73
+ const token = encodeAuthToken(signed);
74
+ return {
75
+ exitCode: 0,
76
+ output: {
77
+ ok: true,
78
+ issuer: formatAddress(signed.issuer),
79
+ subject: formatAddress(signed.subject),
80
+ audience: formatAddress(signed.audience),
81
+ scopes: signed.scopes,
82
+ issuedAt: signed.issuedAt,
83
+ expiresAt: signed.expiresAt,
84
+ token,
85
+ },
86
+ };
87
+ }
88
+
89
+ if (subcommand === "verify") {
90
+ if (!opts["roster-file"]) throw new Error("Missing --roster-file");
91
+ const rawToken = (opts["token-file"]
92
+ ? fs.readFileSync(path.resolve(opts["token-file"]), "utf8")
93
+ : opts.tokenStdin
94
+ ? (stdinText ?? fs.readFileSync(0, "utf8"))
95
+ : "").trim();
96
+ if (!rawToken) throw new Error("Supply --token-stdin or --token-file");
97
+ const rosters = await loadRosterStoreFromBundle(path.resolve(opts["roster-file"]));
98
+ let decoded;
99
+ try {
100
+ decoded = decodeAuthToken(rawToken);
101
+ } catch {
102
+ return { exitCode: 1, output: { accepted: false, reason: "malformed" } };
103
+ }
104
+ const localOrg = opts["local-org"] ?? "local";
105
+ const scopes = opts.scopes ? opts.scopes.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
106
+ const verdict = await verifyAuthToken(decoded, rosters, {
107
+ ...(opts.audience ? { audience: parseAddress(opts.audience, localOrg) } : {}),
108
+ ...(opts.subject ? { requiredSubject: parseAddress(opts.subject, localOrg) } : {}),
109
+ ...(scopes ? { requiredScopes: scopes } : {}),
110
+ ...(opts.now ? { now: opts.now } : {}),
111
+ });
112
+ return {
113
+ exitCode: verdict.accepted ? 0 : 1,
114
+ output: verdict.accepted
115
+ ? {
116
+ accepted: true,
117
+ issuer: formatAddress(decoded.issuer),
118
+ subject: formatAddress(decoded.subject),
119
+ audience: formatAddress(decoded.audience),
120
+ scopes: decoded.scopes,
121
+ expiresAt: decoded.expiresAt,
122
+ }
123
+ : verdict,
124
+ };
125
+ }
126
+
127
+ throw new Error("Usage: node scripts/murmur-auth-token.mjs <mint|verify> [options]");
128
+ }
129
+
130
+ if (process.argv[1] && path.resolve(process.argv[1]) === HERE) {
131
+ runAuthTokenCli(process.argv.slice(2))
132
+ .then(({ exitCode, output }) => {
133
+ console.log(JSON.stringify(output));
134
+ process.exitCode = exitCode;
135
+ })
136
+ .catch((err) => {
137
+ console.error(JSON.stringify({ ok: false, error: err.message }));
138
+ process.exitCode = 1;
139
+ });
140
+ }
@@ -13,6 +13,8 @@ import {
13
13
  SQLiteMessageStore,
14
14
  stableAckPayload,
15
15
  stableEnvelopePayload,
16
+ resolveInstallation,
17
+ installationStorePath,
16
18
  } from "@murmurv2/core";
17
19
  import { decryptPayload, signEnvelope, verifyEnvelopeSignature } from "@murmurv2/security";
18
20
  import { NotifyQueue, flushNotifyQueue, normalizeNotifyTargets, enqueuePeerNotification } from "./notify-router.mjs";
@@ -20,9 +22,13 @@ import { createChannelThreadStartBindingResolver, createCodexAppServerInjector }
20
22
  import { startJetStreamAdvisoryDlqIfEnabled } from "./murmur-jetstream-advisory.mjs";
21
23
  import { WakeMonitor, createAuditShellHook, createShellHook, normalizeWakeConfig } from "./wake-monitor.mjs";
22
24
  import { SessionLeaseStore, createNativeLeaseGate } from "./lease.mjs";
23
- import { ensurePrivateDirectory, readPrivateJson, setPrivateUmask } from "./secure-state.mjs";
25
+ import { ensurePrivateDirectory, setPrivateUmask } from "./secure-state.mjs";
26
+ import { createDaemonContacts } from "./daemon-contacts.mjs";
27
+ import { flushTick } from "./daemon-flush-tick.mjs";
24
28
  import { createDaemonObservation } from "./daemon-observation.mjs";
29
+ import { createLinkWatch } from "./daemon-link-watch.mjs";
25
30
  import { normalizeAckSecurity } from "./ack-security.mjs";
31
+ import { createDaemonInboundAuthorizer } from "./auth-security.mjs";
26
32
  import { classifyVerifiedDoctorMessage, createDoctorResponder } from "./doctor-protocol.mjs";
27
33
  // vault-guard: optional content policy hook (not included in OSS release)
28
34
 
@@ -35,21 +41,30 @@ const log = (level, msg, data) => {
35
41
  observeLog(level, msg, data);
36
42
  };
37
43
 
38
- const dataDir = process.env.DATA_DIR || ".data";
44
+ const { dataDir } = resolveInstallation({ env: process.env, requireConfig: true });
45
+ // Hooks inherit this process's pinned choice even if a person later selects another installation.
46
+ process.env.DATA_DIR = dataDir;
47
+ process.env.MURMUR_DATA_DIR = dataDir;
39
48
  const configPath = path.join(dataDir, "agent-config.json");
40
49
 
41
50
  let config;
51
+ let contacts;
42
52
  try {
43
53
  await ensurePrivateDirectory(dataDir);
44
- config = await readPrivateJson(configPath);
54
+ contacts = createDaemonContacts(configPath, log);
55
+ config = contacts.config;
45
56
  } catch (err) {
46
57
  log("fatal", "Cannot load agent config", { path: configPath, error: err.message });
47
58
  log("info", "Run: node scripts/agent-config-init.mjs");
48
59
  process.exit(1);
49
60
  }
50
61
 
51
- const { agentId, natsUrl, natsToken, subject, peers, keys } = config;
52
- const dbPath = path.join(dataDir, "murmur.db");
62
+ const { agentId, natsUrl, natsToken, natsUser, natsPassword, natsTls, subject, keys } = config;
63
+ const dbPath = installationStorePath(dataDir, 'murmur.db', process.env.MURMUR_STORE_PATH);
64
+ // Refuse conflicting installation paths before any SQLite store is opened.
65
+ const channelRosterConfig = config.channelRoster || {};
66
+ const channelRosterEnabled = channelRosterConfig.enabled ?? process.env.MURMUR_CHANNEL_ROSTER === "1";
67
+ const channelRosterPath = channelRosterConfig.path || installationStorePath(dataDir, 'channel-roster.db', process.env.MURMUR_CHANNEL_ROSTER_PATH);
53
68
  const flushIntervalMs = Number(process.env.FLUSH_INTERVAL_MS) || 2000;
54
69
  const jetstreamConfig = config.jetstream || {};
55
70
  const jetstreamEnabled = jetstreamConfig.enabled ?? process.env.MURMUR_JETSTREAM === "1";
@@ -80,6 +95,7 @@ const ackSecurityConfig = config.ackSecurity || {};
80
95
  const ackPolicy = normalizeAckSecurity(config, process.env, log);
81
96
  const emitSignedAcks = ackPolicy.emitSigned;
82
97
  const requireSignedAcks = ackPolicy.requireSigned;
98
+ const authPolicy = await createDaemonInboundAuthorizer({ config, env: process.env, dataDir, log });
83
99
  const maxAckAgeMs = optionalPositiveInteger(
84
100
  "ack-max-age-ms",
85
101
  firstDefined(ackSecurityConfig.maxAgeMs, process.env.MURMUR_ACK_MAX_AGE_MS),
@@ -125,6 +141,7 @@ log("info", "Daemon starting", {
125
141
  ...ackPolicy,
126
142
  maxAgeMs: maxAckAgeMs,
127
143
  },
144
+ authz: authPolicy.summary,
128
145
  ackWindow,
129
146
  wake: { enabled: wakeConfig.enabled, mode: wakeConfig.mode, hookConfigured: Boolean(config.onReceive) },
130
147
  notifyTargets: effectiveNotifyTargets.map((t) => `${t.type}:${t.channel}`),
@@ -150,9 +167,6 @@ const nativeLeaseGate = leaseStore
150
167
  : null;
151
168
  if (scopedChannelsEnabled) log("info", "Scoped-channels native lease gate enabled", { ttlMs: nativeLeaseTtlMs });
152
169
 
153
- const channelRosterConfig = config.channelRoster || {};
154
- const channelRosterEnabled = channelRosterConfig.enabled ?? process.env.MURMUR_CHANNEL_ROSTER === "1";
155
- const channelRosterPath = channelRosterConfig.path || process.env.MURMUR_CHANNEL_ROSTER_PATH || path.join(dataDir, "channel-roster.db");
156
170
  const channelRosterStore = channelRosterEnabled ? new ChannelRosterStore(channelRosterPath) : null;
157
171
  const subjectRoutes = channelSubjectRoutes(subject, agentId, config.subjectScoping);
158
172
  if (subjectRoutes.length > 1) {
@@ -169,17 +183,35 @@ const threadStartBindingResolver = channelRosterStore
169
183
  : null;
170
184
  const nativeConfigured = wakeConfig.mode === "codex_app_server" || Object.values(wakeConfig.peers).some((peer) => peer.mode === "codex_app_server");
171
185
  const observation = createDaemonObservation({ dataDir, storePath: dbPath, agentId, log,
186
+ contacts: () => contacts.diagnostics(),
172
187
  wake: { enabled: wakeConfig.enabled, mode: nativeConfigured ? "monitor" : config.onReceive ? "hook" : "none",
173
188
  // A custom shell command's identity cannot be inferred from arbitrary text.
174
189
  responder: nativeConfigured ? "codex" : config.onReceive ? null : "none" } });
175
190
  observeLog = observation.observeLog;
191
+ // #276 — a link that closed for good, or stayed lost longer than allowed, ends the process
192
+ // with a non-zero code so the supervisor restarts it and the failure is visible.
193
+ const maxDisconnectedMs = Number(config.maxDisconnectedMs ?? process.env.MURMUR_MAX_DISCONNECTED_MS) || 0;
194
+ const exitOnClosed = config.exitOnClosed !== false && process.env.MURMUR_EXIT_ON_CLOSED !== "0";
195
+ const linkWatch = createLinkWatch({ observation, maxDisconnectedMs, exitOnClosed, log,
196
+ onLost: (reason) => { void shutdown(reason, 3); } });
197
+ if (linkWatch.enabled) log("info", "Server link watch enabled", { exitOnClosed, maxDisconnectedMs: linkWatch.maxDisconnectedMs });
176
198
  // #108 — Codex threads are remembered per (peer, conversation) in the message store.
177
199
  const codexAppServerInjector = createCodexAppServerInjector({ log, resolveThreadStartBinding: threadStartBindingResolver, threadStore: msgStore });
178
200
  if (channelRosterEnabled) log("info", "Channel roster thread-start binding enabled", { channelRosterPath });
179
201
  const broker = new NatsBroker({
202
+ // Observe every initial failure. NATS waitOnFirstConnect otherwise hides all
203
+ // errors inside an unresolved connect promise, before status() is available.
204
+ // Keep the daemon's existing unbounded startup recovery in our observable loop.
205
+ waitOnFirstConnect: false,
206
+ connectMaxAttempts: Infinity,
207
+ connectBaseBackoffMs: 2000,
180
208
  url: natsUrl,
181
209
  token: natsToken,
210
+ user: natsUser,
211
+ password: natsPassword,
212
+ tls: natsTls,
182
213
  jetstream: jetstreamEnabled,
214
+ jetstreamProvisioning: jetstreamConfig.provisioning,
183
215
  stream: jetstreamEnabled ? jetstreamStream : undefined,
184
216
  streamSubjects: jetstreamSubjects,
185
217
  jetstreamMaxDeliver,
@@ -193,7 +225,7 @@ const signAck = async (unsignedAck) => ({
193
225
  });
194
226
 
195
227
  const verifyAck = async (ack) => {
196
- const peer = peers[ack.senderAgentId];
228
+ const peer = contacts.refresh()[ack.senderAgentId];
197
229
  if (!peer?.signing?.publicKey) return "key-unavailable";
198
230
  return verifyEnvelopeSignature(stableAckPayload(ack), ack.signature, peer.signing.publicKey);
199
231
  };
@@ -247,7 +279,9 @@ const proxyWakeMonitor = new WakeMonitor({
247
279
 
248
280
  const onMessage = async (envelope) => {
249
281
  const senderId = envelope.senderAgentId;
250
- const peer = peers[senderId];
282
+ let peer;
283
+ try { peer = contacts.refresh()[senderId]; }
284
+ catch { throw new Error('contacts-unavailable:retry'); }
251
285
 
252
286
  if (!peer) {
253
287
  // Отказ обязан быть виден ПРИНИМАЮЩЕЙ стороне. Бросок уходит в
@@ -383,48 +417,40 @@ let running = true;
383
417
 
384
418
  const flushLoop = async () => {
385
419
  while (running) {
386
- try {
387
- await broker.flushOutbox({ outbox: store, maxAttempts: 5, ackTimeoutMs, ackWindow });
388
- } catch (err) {
389
- log("error", "Outbox flush error", { error: err.message });
390
- }
391
-
392
- try {
393
- await flushNotifyQueue({ queue: notifyQueue, log, limit: 100 });
394
- } catch (err) {
395
- log("error", "Notify flush error", { error: err.message });
396
- }
397
-
398
- // #105 — retry tick: deliveries whose backoff has elapsed, and anything a previous
399
- // process left behind, are picked up from the table here.
400
- try {
401
- await wakeMonitor.drain();
402
- } catch (err) {
403
- log("error", "Wake retry drain error", { error: err.message });
404
- }
405
-
420
+ // A rejected config replacement keeps the last valid Contacts and reports
421
+ // its own diagnostic. Contact refresh must not gate queued deliveries.
422
+ contacts.refresh();
423
+ await flushTick({
424
+ flushOutbox: () => broker.flushOutbox({ outbox: store, maxAttempts: 5, ackTimeoutMs, ackWindow }),
425
+ flushNotify: () => flushNotifyQueue({ queue: notifyQueue, log, limit: 100 }),
426
+ drainWake: () => wakeMonitor.drain(),
427
+ log,
428
+ });
406
429
  await sleep(flushIntervalMs);
407
430
  }
408
431
  };
409
432
 
410
- const shutdown = async (signal) => {
411
- log("info", "Shutdown signal received, draining NATS", { signal });
433
+ const shutdown = async (signal, exitCode = 0) => {
434
+ log("info", "Shutdown signal received, draining NATS", { signal, exitCode });
412
435
  running = false;
413
- observation.stop();
436
+ linkWatch.stop();
437
+ await observation.stop();
414
438
  try {
415
439
  await broker.close();
416
440
  } catch (err) {
417
441
  log("error", "Broker close error", { error: err.message });
418
442
  }
419
- log("info", "Daemon stopped", { agentId });
420
- process.exit(0);
443
+ log("info", "Daemon stopped", { agentId, exitCode });
444
+ process.exit(exitCode);
421
445
  };
422
446
 
423
447
  process.on("SIGTERM", () => shutdown("SIGTERM"));
424
448
  process.on("SIGINT", () => shutdown("SIGINT"));
449
+ if (process.platform !== "win32") process.on("SIGHUP", () => { contacts.refresh(true); });
425
450
 
426
451
  try {
427
452
  await observation.start();
453
+ linkWatch.start();
428
454
  await broker.connect();
429
455
  await observation.connected();
430
456
  log("info", "NATS connected", { url: natsUrl });
@@ -435,6 +461,7 @@ try {
435
461
  consumerId: agentId,
436
462
  dedupe: store,
437
463
  onMessage,
464
+ ...(authPolicy.authorize ? { authorize: authPolicy.authorize } : {}),
438
465
  ...(emitSignedAcks ? { signAck } : {}),
439
466
  });
440
467
  log("info", "Subscribed", route);
@@ -494,6 +521,7 @@ try {
494
521
  const ackReceipts = typeof store.claimAckNonce === "function" ? store : undefined;
495
522
  await broker.startAckCorrelation({
496
523
  outbox: store,
524
+ recoverFirstContact: true,
497
525
  ackReceipts,
498
526
  ackSubject: `ack.${agentId}`,
499
527
  consumerId: `${agentId}-ack`,
@@ -517,6 +545,8 @@ try {
517
545
  broker,
518
546
  outbox: store,
519
547
  jetstreamEnabled,
548
+ advisoryDlq: jetstreamConfig.advisoryDlq,
549
+ provisioning: jetstreamConfig.provisioning,
520
550
  log,
521
551
  });
522
552
 
@@ -537,7 +567,7 @@ try {
537
567
  hint: "set onReceive (shell hook), or wake.peers[<agentId>].mode=codex_app_server (native wake), in agent-config.json",
538
568
  });
539
569
  }
540
- log("info", "Daemon ready", { agentId, peers: Object.keys(peers), wake: wakeStatus });
570
+ log("info", "Daemon ready", { agentId, peers: Object.keys(config.peers), wake: wakeStatus });
541
571
  } catch (err) {
542
572
  log("fatal", "Daemon startup failed", { error: err.message });
543
573
  await broker.close().catch(() => {});