@murmurv2/cli 2.12.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 (57) hide show
  1. package/README.md +65 -24
  2. package/package.json +7 -6
  3. package/runtime/bin/murmur-svc.exe +0 -0
  4. package/runtime/npm-runtime-manifest.json +151 -75
  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 +3 -2
  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.js +67 -10
  17. package/runtime/packages/setup/dist/src/clients.d.ts +28 -76
  18. package/runtime/packages/setup/dist/src/clients.js +159 -25
  19. package/runtime/packages/setup/dist/src/commands.js +3 -3
  20. package/runtime/packages/setup/dist/src/config.d.ts +8 -0
  21. package/runtime/packages/setup/dist/src/config.js +58 -10
  22. package/runtime/packages/setup/dist/src/connect.d.ts +143 -0
  23. package/runtime/packages/setup/dist/src/connect.js +126 -0
  24. package/runtime/packages/setup/dist/src/doctor.d.ts +30 -0
  25. package/runtime/packages/setup/dist/src/doctor.js +72 -10
  26. package/runtime/packages/setup/dist/src/installation.d.ts +25 -0
  27. package/runtime/packages/setup/dist/src/installation.js +89 -0
  28. package/runtime/packages/setup/dist/src/message-status.d.ts +1 -0
  29. package/runtime/packages/setup/dist/src/message-status.js +3 -0
  30. package/runtime/packages/setup/dist/src/onboarding.d.ts +11 -6
  31. package/runtime/packages/setup/dist/src/onboarding.js +92 -21
  32. package/runtime/packages/setup/dist/src/paths.d.ts +7 -0
  33. package/runtime/packages/setup/dist/src/paths.js +39 -24
  34. package/runtime/packages/setup/dist/src/platform/darwin.d.ts +3 -0
  35. package/runtime/packages/setup/dist/src/platform/darwin.js +235 -9
  36. package/runtime/packages/setup/dist/src/platform/linux.js +132 -2
  37. package/runtime/packages/setup/dist/src/platform/profile-usage.d.ts +20 -0
  38. package/runtime/packages/setup/dist/src/platform/profile-usage.js +89 -0
  39. package/runtime/packages/setup/dist/src/platform/windows.js +22 -1
  40. package/runtime/packages/setup/dist/src/private-file.d.ts +4 -1
  41. package/runtime/packages/setup/dist/src/private-file.js +39 -3
  42. package/runtime/packages/setup/dist/src/state.d.ts +4 -0
  43. package/runtime/packages/setup/dist/src/state.js +65 -1
  44. package/runtime/packages/setup/dist/src/status.d.ts +9 -0
  45. package/runtime/packages/setup/dist/src/status.js +7 -3
  46. package/runtime/packages/setup/dist/src/types.d.ts +10 -0
  47. package/runtime/packages/setup/dist/src/wake-readers.d.ts +12 -0
  48. package/runtime/packages/setup/dist/src/wake-readers.js +65 -0
  49. package/runtime/packages/setup/package.json +1 -1
  50. package/runtime/scripts/auth-security.mjs +93 -0
  51. package/runtime/scripts/codex-app-server-wake.mjs +13 -0
  52. package/runtime/scripts/daemon-contacts.mjs +1 -1
  53. package/runtime/scripts/murmur-auth-token.mjs +140 -0
  54. package/runtime/scripts/murmur-daemon.mjs +22 -6
  55. package/runtime/scripts/murmur-jetstream-advisory.mjs +27 -0
  56. package/runtime/scripts/murmur-shell-send.mjs +3 -3
  57. package/runtime/scripts/wake-drain-claude.mjs +124 -7
@@ -7,6 +7,7 @@ import { execFile } from 'node:child_process';
7
7
  import { SQLiteDedupeOutboxStore } from '@murmurv2/core';
8
8
  import { createKeyPair, createSigningKeyPair } from '@murmurv2/security';
9
9
  import { loadConfig, validateConfig, validAgentId } from './config.js';
10
+ import { readBrokerInputs } from './broker-input.js';
10
11
  import { writeState } from './state.js';
11
12
  import { refuseVirtualizedAppData } from './appdata.js';
12
13
  import { protectPrivateFile } from './private-file.js';
@@ -15,7 +16,7 @@ async function privateText(file, role) {
15
16
  if (!path.isAbsolute(file))
16
17
  throw new Error('onboarding.file-must-be-absolute');
17
18
  // Name the option and the reason, never the path or contents: this is what a new user acts on.
18
- const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)).catch((e) => {
19
+ const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)).catch((e) => {
19
20
  if (e.code === 'ENOENT')
20
21
  throw new Error(`onboarding.${role}-not-found`);
21
22
  if (e.code === 'EPERM' || e.code === 'EACCES')
@@ -26,7 +27,18 @@ async function privateText(file, role) {
26
27
  const info = await handle.stat();
27
28
  if (!info.isFile() || info.size > 16384)
28
29
  throw new Error('onboarding.file-invalid');
29
- return (await handle.readFile('utf8')).trim();
30
+ // Bound the read even if the file grows after stat.
31
+ const buffer = Buffer.alloc(16385);
32
+ let size = 0;
33
+ while (size < buffer.length) {
34
+ const { bytesRead } = await handle.read(buffer, size, buffer.length - size, null);
35
+ if (!bytesRead)
36
+ break;
37
+ size += bytesRead;
38
+ }
39
+ if (size > 16384)
40
+ throw new Error('onboarding.input-too-large');
41
+ return buffer.subarray(0, size).toString('utf8').trim();
30
42
  }
31
43
  finally {
32
44
  await handle.close();
@@ -109,16 +121,23 @@ async function restrictToCurrentUser(target, directory) {
109
121
  await execFileAsync(system32('icacls.exe'), [target, '/inheritance:r', '/grant:r', `*${sid}:${inherit}(F)`, `*S-1-5-18:${inherit}(F)`], { windowsHide: true })
110
122
  .catch(() => { throw new Error('onboarding.private-acl-failed'); });
111
123
  }
112
- const encodeBlob = (value) => {
113
- const text = 'MURMUR:' + Buffer.from(JSON.stringify(value)).toString('base64url');
124
+ const encodeBlob = (value, prefix = 'MURMUR:') => {
125
+ const text = prefix + Buffer.from(JSON.stringify(value)).toString('base64url');
114
126
  if (Buffer.byteLength(text + '\n') > 16384)
115
127
  throw new Error('onboarding.input-too-large');
116
128
  return text;
117
129
  };
118
- async function outputBlob(file, text, beforeWrite) {
130
+ async function outputBlob(file, text, beforeWrite, skipOccupied = false) {
119
131
  if (!path.isAbsolute(file))
120
132
  throw new Error('onboarding.output-must-be-absolute');
121
- const handle = await open(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
133
+ const handle = await open(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600)
134
+ .catch((error) => {
135
+ if (skipOccupied && error.code === 'EEXIST')
136
+ return null;
137
+ throw error;
138
+ });
139
+ if (!handle)
140
+ return false;
122
141
  let written = false;
123
142
  try {
124
143
  // Protect the still-empty output before writing the invitation credential.
@@ -133,6 +152,7 @@ async function outputBlob(file, text, beforeWrite) {
133
152
  if (!written)
134
153
  await unlink(file).catch(() => { });
135
154
  }
155
+ return true;
136
156
  }
137
157
  async function locked(c, fn) {
138
158
  // mkdir reports a path only when it created something: never rewrite an existing profile's ACL.
@@ -171,10 +191,10 @@ async function existing(c) {
171
191
  throw e;
172
192
  }
173
193
  }
174
- async function newConfig(agentId, url, token) {
194
+ async function newConfig(agentId, url, auth = {}) {
175
195
  if (!validAgentId(agentId))
176
196
  throw new Error('config.identity-invalid');
177
- return validateConfig({ agentId, subject: `msg.${agentId}`, natsUrl: url, ...(token ? { natsToken: token } : {}),
197
+ return validateConfig({ agentId, subject: `msg.${agentId}`, natsUrl: url, ...auth,
178
198
  keys: { encryption: await createKeyPair(), signing: await createSigningKeyPair() }, peers: {},
179
199
  wake: { enabled: true }, ackSecurity: { emitSigned: true, requireSigned: true } });
180
200
  }
@@ -192,6 +212,32 @@ async function saveChanged(c, previous, next) {
192
212
  }
193
213
  const publicPeer = (c) => ({ agentId: c.agentId, subject: c.subject,
194
214
  encryption: { publicKey: c.keys.encryption.publicKey }, signing: { publicKey: c.keys.signing.publicKey } });
215
+ async function connectInviteText(options) {
216
+ let text = options.invitation ?? options.inviteArgument ?? '';
217
+ if (options.inviteFile !== undefined)
218
+ text = await privateText(path.resolve(options.inviteFile), 'invite-file');
219
+ // Text with line breaks cannot be a normal CLI file argument. A single-line
220
+ // argument may instead name an existing file (including a relative path).
221
+ else if (options.inviteArgument && !/[\x00-\x1f\x7f]/.test(text) && Buffer.byteLength(text) < 4096) {
222
+ const file = path.resolve(text);
223
+ try {
224
+ text = await privateText(file, 'invite-file');
225
+ }
226
+ catch (error) {
227
+ if (!(error instanceof Error && error.message === 'onboarding.invite-file-not-found')
228
+ && !['ENAMETOOLONG', 'ENOTDIR', 'EINVAL'].includes(error.code ?? ''))
229
+ throw error;
230
+ }
231
+ }
232
+ if (Buffer.byteLength(text) > 16384)
233
+ throw new Error('onboarding.input-too-large');
234
+ const tokens = [...new Set(text.match(/MURMUR:[A-Za-z0-9+/=_-]+/g) ?? [])];
235
+ if (tokens.length > 1)
236
+ throw new Error('connect.multiple-invitations');
237
+ if (!tokens.length)
238
+ throw new Error('onboarding.invalid-blob');
239
+ return tokens[0];
240
+ }
195
241
  async function readBlob(input, type) {
196
242
  if ((input.file === undefined) === (input.text === undefined))
197
243
  throw new Error('onboarding.input-required');
@@ -235,18 +281,17 @@ function addPeer(config, peer) {
235
281
  }
236
282
  export async function initialize(c, options) {
237
283
  await refuseVirtualizedAppData(c.dataDir);
284
+ const supplied = await readBrokerInputs(options);
238
285
  return locked(c, async () => {
239
286
  const previous = await existing(c);
240
287
  if (previous) {
241
- if (previous.agentId !== options.agentId || previous.natsUrl !== options.brokerUrl)
288
+ if (previous.agentId !== options.agentId || previous.natsUrl !== options.brokerUrl
289
+ || Object.keys(supplied).some(key => !isDeepStrictEqual(previous[key], supplied[key])))
242
290
  throw new Error('onboarding.existing-profile-conflict');
243
291
  // Re-running init never rotates keys or replaces credentials.
244
292
  return { schema: 'murmur.init/1', agentId: previous.agentId, dataDir: c.dataDir, serviceName: c.serviceName, existing: true };
245
293
  }
246
- const token = options.tokenFile ? await privateText(options.tokenFile, 'token-file') : undefined;
247
- if (token?.includes('\n') || token?.includes('\r'))
248
- throw new Error('onboarding.token-file-invalid');
249
- const config = await newConfig(options.agentId, options.brokerUrl, token);
294
+ const config = await newConfig(options.agentId, options.brokerUrl, supplied);
250
295
  await saveChanged(c, null, config);
251
296
  return { schema: 'murmur.init/1', agentId: config.agentId, dataDir: c.dataDir, serviceName: c.serviceName, existing: false };
252
297
  });
@@ -260,7 +305,10 @@ export async function invite(c, outFile, options = {}) {
260
305
  if (outFile !== undefined)
261
306
  await outputBlob(outFile, invitation);
262
307
  const containsBrokerCredential = !!config.natsToken;
263
- return { schema: 'murmur.invite/1', file: outFile ?? null, invitation, containsBrokerCredential,
308
+ const secretRedacted = outFile !== undefined && !options.printSecret;
309
+ return { schema: 'murmur.invite/1', file: outFile ?? null,
310
+ ...(outFile !== undefined ? { outFile, secretRedacted } : {}),
311
+ ...(!secretRedacted ? { invitation } : {}), containsBrokerCredential,
264
312
  instruction: containsBrokerCredential
265
313
  ? 'This Invitation contains a Server access key. Send it personally to your colleague. After exchanging the Reply, check the connection.'
266
314
  : 'This Invitation contains your Identity and the Server address. Send it to your colleague. After exchanging the Reply, check the connection.' };
@@ -268,25 +316,48 @@ export async function invite(c, outFile, options = {}) {
268
316
  export async function join(c, options) {
269
317
  if (options.replyOut !== undefined)
270
318
  await validateOutput(c, options.replyOut);
271
- const incoming = await readBlob({ file: options.inviteFile, text: options.invitation }, 'invite');
319
+ const incoming = await readBlob(options.connect
320
+ ? { text: await connectInviteText(options) }
321
+ : { file: options.inviteFile, text: options.invitation }, 'invite');
322
+ const supplied = await readBrokerInputs(options);
323
+ if (incoming.natsToken && (supplied.natsUser || supplied.natsPassword || supplied.natsToken && supplied.natsToken !== incoming.natsToken))
324
+ throw new Error('nats-auth-methods-conflict');
325
+ const auth = { ...(incoming.natsToken ? { natsToken: incoming.natsToken } : {}), ...supplied };
272
326
  // Before anything is created: a profile the service cannot see must not be written at all.
273
327
  await refuseVirtualizedAppData(c.dataDir);
274
328
  return locked(c, async () => {
275
329
  const previous = await existing(c);
276
- if (previous && (previous.agentId !== options.agentId || previous.natsUrl !== incoming.natsUrl))
330
+ if (previous && (previous.agentId !== options.agentId || previous.natsUrl !== incoming.natsUrl
331
+ || Object.keys(auth).some(key => !isDeepStrictEqual(previous[key], auth[key]))))
277
332
  throw new Error('onboarding.existing-profile-conflict');
278
- const config = previous ?? await newConfig(options.agentId, incoming.natsUrl, incoming.natsToken);
333
+ const config = previous ?? await newConfig(options.agentId, incoming.natsUrl, auth);
279
334
  const next = addPeer(config, incoming);
280
335
  let backup = null;
281
336
  // Reserve the reply path before changing config: an existing output must not half-import a profile.
282
- const reply = encodeBlob({ v: 1, type: 'reply', ...publicPeer(next) });
337
+ const reply = encodeBlob({ v: 1, type: 'reply', ...publicPeer(next) }, options.connect ? 'MURMUR-REPLY:' : 'MURMUR:');
283
338
  const save = async () => { backup = await saveChanged(c, previous, next); };
284
- if (options.replyOut !== undefined)
285
- await outputBlob(options.replyOut, reply, save);
339
+ let replyFile = options.replyOut ?? null;
340
+ if (replyFile !== null)
341
+ await outputBlob(replyFile, reply, save);
342
+ else if (options.connect) {
343
+ const stem = path.join(path.dirname(c.dataDir), `${next.agentId}-reply`);
344
+ // The profile parent now exists. Reserve without overwriting even a
345
+ // symlink or an unrelated file with the suggested name.
346
+ for (let attempt = 1; attempt <= 100; attempt++) {
347
+ const candidate = stem + (attempt === 1 ? '' : `-${attempt}`) + '.txt';
348
+ await validateOutput(c, candidate);
349
+ if (await outputBlob(candidate, reply, save, true)) {
350
+ replyFile = candidate;
351
+ break;
352
+ }
353
+ }
354
+ if (replyFile === null)
355
+ throw new Error('connect.reply-output-occupied');
356
+ }
286
357
  else
287
358
  await save();
288
359
  return { schema: 'murmur.join/1', agentId: next.agentId, peerId: incoming.agentId, paired: null,
289
- replyFile: options.replyOut ?? null, reply, backup, restartRequired: false,
360
+ replyFile, reply, backup, restartRequired: false,
290
361
  contactsReload: { mechanism: 'config-file', state: 'pending' }, serviceName: c.serviceName };
291
362
  });
292
363
  }
@@ -1,4 +1,7 @@
1
1
  import type { ServiceContext } from "./types.js";
2
+ /** Homebrew resolves process.execPath into a versioned Cellar. Persist a stable
3
+ * executable only when it is executable and resolves to this very same Node. */
4
+ export declare function stableNodeExecutable(executable: string, platform?: NodeJS.Platform, inspect?: (candidate: string) => string): string;
2
5
  export declare function resolveContext(options?: {
3
6
  dataDir?: string;
4
7
  repoRoot?: string;
@@ -7,4 +10,8 @@ export declare function resolveContext(options?: {
7
10
  platform?: NodeJS.Platform;
8
11
  home?: string;
9
12
  env?: NodeJS.ProcessEnv;
13
+ installationFile?: string;
14
+ clientProjectDir?: string;
10
15
  }): ServiceContext;
16
+ /** New CLI profiles live beside, not inside, any selected installation. */
17
+ export declare function defaultProfileDir(agentId: string, platform?: NodeJS.Platform, home?: string, env?: NodeJS.ProcessEnv): string;
@@ -2,40 +2,55 @@ import path from "node:path";
2
2
  import { homedir } from "node:os";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { createHash } from "node:crypto";
5
+ import { accessSync, constants, realpathSync } from "node:fs";
6
+ import { resolveInstallation } from '@murmurv2/core';
7
+ /** Homebrew resolves process.execPath into a versioned Cellar. Persist a stable
8
+ * executable only when it is executable and resolves to this very same Node. */
9
+ export function stableNodeExecutable(executable, platform = process.platform, inspect = (candidate) => { accessSync(candidate, constants.X_OK); return realpathSync(candidate); }) {
10
+ if (platform !== "darwin")
11
+ return executable;
12
+ const brew = /^(\/opt\/homebrew|\/usr\/local)\/Cellar\/(node(?:@\d+)?)\/[^/]+\/bin\/node$/.exec(executable);
13
+ if (!brew)
14
+ return executable;
15
+ const [, prefix, formula] = brew;
16
+ const candidates = formula === "node" ? [`${prefix}/bin/node`, `${prefix}/opt/node/bin/node`]
17
+ : [`${prefix}/opt/${formula}/bin/node`];
18
+ for (const candidate of candidates) {
19
+ try {
20
+ if (inspect(candidate) === executable)
21
+ return candidate;
22
+ }
23
+ catch { /* missing or different installation */ }
24
+ }
25
+ return executable;
26
+ }
5
27
  export function resolveContext(options = {}) {
6
28
  const env = options.env ?? process.env;
7
29
  const platform = options.platform ?? process.platform;
8
30
  const home = options.home ?? homedir();
9
31
  const paths = platform === "win32" ? path.win32 : path.posix;
10
- const defaultDir = platform === "darwin" ? paths.join(home, "Library", "Application Support", "Murmur")
11
- : platform === "win32" ? paths.join(env.LOCALAPPDATA || paths.join(home, "AppData", "Local"), "Murmur")
12
- : paths.join(env.XDG_STATE_HOME || paths.join(home, ".local", "state"), "murmur");
13
- let selected = options.dataDir;
14
- if (selected === undefined) {
15
- if (env.DATA_DIR !== undefined) {
16
- if (!env.DATA_DIR)
17
- throw new Error("config.data-dir-empty");
18
- if (env.MURMUR_DATA_DIR && paths.normalize(env.DATA_DIR) !== paths.normalize(env.MURMUR_DATA_DIR))
19
- throw new Error("config.data-dir-conflict");
20
- selected = env.DATA_DIR;
21
- }
22
- else
23
- selected = env.MURMUR_DATA_DIR ?? defaultDir;
24
- }
25
- const dataDir = paths.normalize(selected);
26
- if (!paths.isAbsolute(dataDir))
27
- throw new Error("config.data-dir-must-be-absolute");
28
- // The default service name hashes the path as written (see AGENTS.md), and shell completion appends
29
- // a separator to folders: refuse it rather than silently select a second service for one profile.
30
- if (dataDir.length > paths.parse(dataDir).root.length && /[\\/]$/.test(dataDir))
31
- throw new Error("profile.trailing-separator");
32
+ const { dataDir } = resolveInstallation({ ...options, platform, home, env });
32
33
  const repoRoot = paths.normalize(options.repoRoot ?? fileURLToPath(new URL("../../../../", import.meta.url))).replace(/[\\/]$/, "");
33
- const nodePath = paths.normalize(options.nodePath ?? process.execPath);
34
+ const nodePath = paths.normalize(options.nodePath ?? stableNodeExecutable(process.execPath, platform));
34
35
  if (!paths.isAbsolute(repoRoot) || !paths.isAbsolute(nodePath))
35
36
  throw new Error("config.runtime-path-must-be-absolute");
36
37
  const serviceName = options.serviceName ?? `murmur-${createHash("sha256").update(dataDir).digest("hex").slice(0, 12)}`;
37
38
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,100}$/.test(serviceName))
38
39
  throw new Error("config.invalid-service-name");
40
+ const clientProjectDir = options.clientProjectDir;
41
+ if (clientProjectDir !== undefined && (!paths.isAbsolute(clientProjectDir) || paths.normalize(clientProjectDir) !== clientProjectDir
42
+ || /[\x00-\x1f\x7f]/.test(clientProjectDir)))
43
+ throw new Error("client.project-path-invalid");
39
44
  return { dataDir, repoRoot, nodePath, serviceName, configPath: paths.join(dataDir, "agent-config.json"),
40
- storePath: paths.join(dataDir, "murmur.db"), logDir: paths.join(dataDir, "logs") };
45
+ storePath: paths.join(dataDir, "murmur.db"), logDir: paths.join(dataDir, "logs"),
46
+ ...(clientProjectDir !== undefined ? { clientProjectDir } : {}) };
47
+ }
48
+ /** New CLI profiles live beside, not inside, any selected installation. */
49
+ export function defaultProfileDir(agentId, platform = process.platform, home = homedir(), env = process.env) {
50
+ if (platform === 'win32')
51
+ return path.win32.join(env.LOCALAPPDATA || path.win32.join(home, 'AppData', 'Local'), 'Murmur', 'profiles', agentId);
52
+ if (platform === 'darwin')
53
+ return path.posix.join(home, 'Library', 'Application Support', 'Murmur', 'profiles', agentId);
54
+ const dataHome = env.XDG_DATA_HOME && path.posix.isAbsolute(env.XDG_DATA_HOME) ? env.XDG_DATA_HOME : path.posix.join(home, '.local', 'share');
55
+ return path.posix.join(dataHome, 'murmur', 'profiles', agentId);
41
56
  }
@@ -3,6 +3,7 @@ export interface CommandResult {
3
3
  code: number;
4
4
  stdout: string;
5
5
  stderr: string;
6
+ pid?: number;
6
7
  }
7
8
  export type CommandRunner = (file: string, args: string[]) => Promise<CommandResult>;
8
9
  export interface DarwinOptions {
@@ -10,6 +11,8 @@ export interface DarwinOptions {
10
11
  uid?: number;
11
12
  env?: NodeJS.ProcessEnv;
12
13
  run?: CommandRunner;
14
+ /** Uses a larger, still bounded output buffer for the profile-wide lsof probe. */
15
+ profileRun?: CommandRunner;
13
16
  applicationDirs?: string[];
14
17
  /** Fully replaces executable search roots, primarily for hermetic tests. */
15
18
  executableDirs?: string[];
@@ -4,6 +4,7 @@ import * as fs from "node:fs/promises";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { randomUUID } from "node:crypto";
7
+ import { classifyProfilePath, ProfileUsageUnknown, verifiedProfileRoot } from "./profile-usage.js";
7
8
  const marker = "<!-- Managed by Murmur setup: darwin-v1 -->";
8
9
  const launchctl = "/bin/launchctl";
9
10
  const xml = (s) => s.replace(/[&<>"']/g, c => ({
@@ -22,7 +23,7 @@ function validate(ctx) {
22
23
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(ctx.serviceName)) {
23
24
  throw new Error("darwin-invalid-service-name");
24
25
  }
25
- // The current daemon resolves both paths from DATA_DIR, ignoring STORE_PATH.
26
+ // The daemon pins DATA_DIR and requires derived store paths to agree.
26
27
  // Refuse an inconsistent context instead of starting against the wrong DB.
27
28
  if (ctx.configPath !== path.join(ctx.dataDir, "agent-config.json") ||
28
29
  ctx.storePath !== path.join(ctx.dataDir, "murmur.db") ||
@@ -30,15 +31,17 @@ function validate(ctx) {
30
31
  throw new Error("darwin-daemon-path-contract-mismatch");
31
32
  }
32
33
  }
33
- const defaultRun = (file, args) => new Promise(resolve => {
34
- execFile(file, args, {
35
- encoding: "utf8", timeout: 8_000, maxBuffer: 512 * 1024,
34
+ const commandRunner = (maxBuffer) => (file, args) => new Promise(resolve => {
35
+ const child = execFile(file, args, {
36
+ encoding: "utf8", timeout: 8_000, maxBuffer,
36
37
  env: { ...process.env, LC_ALL: "C", TZ: "UTC" },
37
38
  }, (error, stdout, stderr) => resolve({
38
39
  code: error ? (typeof error.code === "number" ? error.code : -1) : 0,
39
- stdout: String(stdout), stderr: String(stderr),
40
+ stdout: String(stdout), stderr: String(stderr), pid: child.pid,
40
41
  }));
41
42
  });
43
+ const defaultRun = commandRunner(512 * 1024);
44
+ const defaultProfileRun = commandRunner(8 * 1024 * 1024);
42
45
  const absent = (r) => r.code !== 0 &&
43
46
  /Could not find service|Could not find specified service/.test(r.stderr + r.stdout);
44
47
  const baseSnapshot = () => ({
@@ -62,6 +65,7 @@ export function createDarwinAdapter(options = {}) {
62
65
  throw new Error("darwin-invalid-user-id");
63
66
  const env = options.env ?? process.env;
64
67
  const run = options.run ?? defaultRun;
68
+ const profileRun = options.profileRun ?? options.run ?? defaultProfileRun;
65
69
  const domain = `gui/${uid}`;
66
70
  const plistPath = (ctx) => path.join(home, "Library", "LaunchAgents", `${ctx.serviceName}.plist`);
67
71
  const target = (ctx) => `${domain}/${ctx.serviceName}`;
@@ -70,6 +74,8 @@ export function createDarwinAdapter(options = {}) {
70
74
  const args = [ctx.nodePath, path.join(ctx.repoRoot, "scripts", "murmur-daemon.mjs")];
71
75
  const environment = {
72
76
  DATA_DIR: ctx.dataDir,
77
+ MURMUR_DATA_DIR: ctx.dataDir,
78
+ MURMUR_CHANNEL_ROSTER_PATH: path.join(ctx.dataDir, "channel-roster.db"),
73
79
  MURMUR_STORE_PATH: ctx.storePath,
74
80
  PATH: [path.dirname(ctx.nodePath), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"].join(":"),
75
81
  };
@@ -129,6 +135,190 @@ export function createDarwinAdapter(options = {}) {
129
135
  }
130
136
  return null;
131
137
  }
138
+ const usageUnknown = (reason = "profile-usage.probe-unavailable") => ({ state: "unknown", reason });
139
+ function lsofSnapshot(output) {
140
+ if (output.includes("\0") || !output.endsWith("\n"))
141
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
142
+ const lines = output.split("\n");
143
+ if (lines.at(-1) === "")
144
+ lines.pop();
145
+ if (lines.some(line => line === ""))
146
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
147
+ const records = [];
148
+ let pid = null, descriptor = null, type = null;
149
+ let processHasRecord = false;
150
+ const seen = new Set();
151
+ for (const line of lines) {
152
+ if (line.startsWith("p")) {
153
+ if (descriptor !== null || type !== null || pid !== null && !processHasRecord || !/^p[1-9]\d*$/.test(line)) {
154
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
155
+ }
156
+ pid = Number(line.slice(1));
157
+ if (!Number.isSafeInteger(pid) || seen.has(pid))
158
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
159
+ seen.add(pid);
160
+ processHasRecord = false;
161
+ }
162
+ else if (line.startsWith("f")) {
163
+ if (pid === null || descriptor !== null || type !== null || line.length < 2 || /[\0\r\n]/.test(line)) {
164
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
165
+ }
166
+ descriptor = line.slice(1);
167
+ }
168
+ else if (line.startsWith("t")) {
169
+ if (pid === null || descriptor === null || type !== null || line.length < 2 || /[\0\r\n]/.test(line)) {
170
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
171
+ }
172
+ type = line.slice(1);
173
+ }
174
+ else if (line.startsWith("n")) {
175
+ if (pid === null || descriptor === null || type === null) {
176
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
177
+ }
178
+ // Apple's process_netpolicy() sets NPOLICY but no name. Native lsof also
179
+ // emits unnamed NEXUS FDs; XNU gives that Skywalk controller its own
180
+ // fileops, separate from vnodes. Darwin process_pipe_common() leaves
181
+ // NAME empty when an anonymous pipe has no peer handle or byte count.
182
+ // PIPE is distinct from a filesystem FIFO. Only these numeric FD types may
183
+ // have an empty n; missing n, other empty types and pseudo-FDs refuse.
184
+ // https://github.com/apple-opensource/lsof/blob/da09c8c6436286e5bd8c400b42e86b54404f12a7/lsof/dialects/darwin/libproc/dnetpolicy.c
185
+ // https://github.com/apple-oss-distributions/xnu/blob/f6217f891ac0bb64f3d375211650a4c1ff8ca1ea/bsd/skywalk/nexus/nexus_syscalls.c
186
+ // https://github.com/lsof-org/lsof/blob/1ebf257c64db1b2ece5e4d5e922ed711c692f161/lib/dialects/darwin/dfile.c#L306-L340
187
+ if (line.length === 1 && !((type === "NPOLICY" || type === "NEXUS" || type === "PIPE") && /^\d+$/.test(descriptor))) {
188
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
189
+ }
190
+ records.push({ pid, descriptor, type, name: line.slice(1) });
191
+ descriptor = type = null;
192
+ processHasRecord = true;
193
+ }
194
+ else {
195
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
196
+ }
197
+ }
198
+ if (descriptor !== null || type !== null || pid !== null && !processHasRecord) {
199
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
200
+ }
201
+ return { pids: seen, records };
202
+ }
203
+ function processSnapshot(result) {
204
+ if (result.code !== 0 || result.stderr.trim() !== "" || !Number.isSafeInteger(result.pid) || result.pid <= 0) {
205
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
206
+ }
207
+ const observations = new Map();
208
+ const lines = result.stdout.split("\n");
209
+ if (lines.at(-1) === "")
210
+ lines.pop();
211
+ for (const line of lines) {
212
+ const match = /^\s*([1-9]\d*)\s+(\d+)\s+(\S+)\s+(.+?)\s*$/.exec(line);
213
+ if (!match)
214
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
215
+ const pid = Number(match[1]), uid = Number(match[2]);
216
+ if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(uid) || observations.has(pid)) {
217
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
218
+ }
219
+ observations.set(pid, { uid, start: match[4], zombie: match[3].startsWith("Z") });
220
+ }
221
+ // /bin/ps is setuid-root on macOS, so its exact child PID may have UID 0.
222
+ // Verify and remove only that exact observer from the full process set.
223
+ if (!observations.has(result.pid) || !observations.has(process.pid)) {
224
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
225
+ }
226
+ observations.delete(result.pid);
227
+ for (const anchor of new Set([1, process.ppid])) {
228
+ if (!observations.has(anchor))
229
+ throw new ProfileUsageUnknown("profile-usage.process-visibility-incomplete");
230
+ }
231
+ return observations;
232
+ }
233
+ async function profileUsage(ctx) {
234
+ validate(ctx);
235
+ try {
236
+ const profile = await verifiedProfileRoot(ctx);
237
+ let control;
238
+ try {
239
+ control = await fs.open(ctx.configPath, constants.O_RDONLY | constants.O_NOFOLLOW);
240
+ const [opened, selected, canonical] = await Promise.all([
241
+ control.stat(), fs.lstat(ctx.configPath), fs.realpath(ctx.configPath),
242
+ ]);
243
+ const currentUid = process.getuid?.();
244
+ if (currentUid === undefined || !opened.isFile() || !selected.isFile() || selected.isSymbolicLink()
245
+ || opened.uid !== currentUid || selected.uid !== currentUid
246
+ || (opened.mode & 0o077) !== 0 || (selected.mode & 0o077) !== 0
247
+ || opened.dev !== selected.dev || opened.ino !== selected.ino || canonical !== ctx.configPath)
248
+ return usageUnknown();
249
+ // Apple's lsof 4.91 makes every +D entry a required search argument,
250
+ // so an unopened entry forces exit 1. Scan all processes and prove
251
+ // lsof coverage with stable ps snapshots around the observation.
252
+ const psArgs = ["-axo", "pid=,uid=,stat=,lstart="];
253
+ const before = processSnapshot(await profileRun("/bin/ps", psArgs));
254
+ const result = await profileRun("/usr/sbin/lsof", ["-n", "-P", "-Fpftn"]);
255
+ if (result.code !== 0 || result.stderr.trim() !== "")
256
+ return usageUnknown();
257
+ const snapshot = lsofSnapshot(result.stdout);
258
+ const after = processSnapshot(await profileRun("/bin/ps", psArgs));
259
+ const stable = new Set();
260
+ if (before.size !== after.size)
261
+ return usageUnknown("profile-usage.process-unverifiable");
262
+ for (const [pid, first] of before) {
263
+ const second = after.get(pid);
264
+ if (!second || first.uid !== second.uid || first.start !== second.start || first.zombie !== second.zombie) {
265
+ return usageUnknown("profile-usage.process-unverifiable");
266
+ }
267
+ if (!first.zombie)
268
+ stable.add(pid);
269
+ }
270
+ if ([...stable].some(pid => !snapshot.pids.has(pid))) {
271
+ return usageUnknown("profile-usage.process-unverifiable");
272
+ }
273
+ let controlSeen = false, held = false;
274
+ const filesystemTypes = new Set(["REG", "DIR", "LINK"]);
275
+ const otherTypes = new Set(["ATALK", "BLK", "CHR", "FIFO", "FSEVENTS", "IPv4", "IPv6", "KQUEUE",
276
+ "NPOLICY", "NEXUS", "PIPE", "PSXSEM", "PSXSHM", "key", "ndrv", "ppp", "rte", "sock", "systm", "unix",
277
+ "vsock", "vsockp"]);
278
+ const classifications = new Map();
279
+ for (const record of snapshot.records) {
280
+ if (!filesystemTypes.has(record.type)) {
281
+ if (!otherTypes.has(record.type))
282
+ return usageUnknown("profile-usage.process-unverifiable");
283
+ continue;
284
+ }
285
+ let classificationPromise = classifications.get(record.name);
286
+ if (!classificationPromise) {
287
+ classificationPromise = classifyProfilePath(profile.root, record.name);
288
+ classifications.set(record.name, classificationPromise);
289
+ }
290
+ const classification = await classificationPromise;
291
+ if (classification === "unknown")
292
+ return usageUnknown("profile-usage.process-unverifiable");
293
+ if (classification === "outside")
294
+ continue;
295
+ if (record.pid === process.pid) {
296
+ const [recordPath, recordInfo] = await Promise.all([fs.realpath(record.name), fs.stat(record.name)]);
297
+ if (recordPath === canonical && recordInfo.dev === opened.dev && recordInfo.ino === opened.ino)
298
+ controlSeen = true;
299
+ }
300
+ else {
301
+ held = true;
302
+ }
303
+ }
304
+ if (!controlSeen)
305
+ return usageUnknown("profile-usage.control-unobserved");
306
+ if (held)
307
+ return { state: "in-use", reason: "profile-usage.open-file" };
308
+ const profileAfter = await verifiedProfileRoot(ctx);
309
+ if (profileAfter.root !== profile.root || profileAfter.proof !== profile.proof) {
310
+ return usageUnknown("profile-usage.profile-changed");
311
+ }
312
+ return { state: "free", reason: "profile-usage.no-open-files" };
313
+ }
314
+ finally {
315
+ await control?.close();
316
+ }
317
+ }
318
+ catch (error) {
319
+ return usageUnknown(error instanceof ProfileUsageUnknown ? error.reason : undefined);
320
+ }
321
+ }
132
322
  async function status(ctx) {
133
323
  validate(ctx);
134
324
  const value = baseSnapshot();
@@ -219,7 +409,20 @@ export function createDarwinAdapter(options = {}) {
219
409
  if (loaded.code !== 0)
220
410
  throw new Error("darwin-cannot-inspect-service-before-stop");
221
411
  requireSameLoadedPath(ctx, loaded);
222
- if (await readOwned(ctx) !== plist(ctx))
412
+ let owned = await readOwned(ctx);
413
+ // Upgrading from a Cellar-bound Node must still allow Stop before Install.
414
+ // Accept only the known Homebrew spelling change; all profile/runtime fields
415
+ // and the ownership marker must otherwise match byte for byte.
416
+ const oldNode = owned?.match(/<key>ProgramArguments<\/key><array><string>((?:\/opt\/homebrew|\/usr\/local)\/Cellar\/(node(?:@\d+)?)\/[^<\/]+\/bin\/node)<\/string>/);
417
+ if (oldNode) {
418
+ const prefix = oldNode[1].split('/Cellar/')[0], formula = oldNode[2];
419
+ const stable = [`${prefix}/opt/${formula}/bin/node`, ...(formula === 'node' ? [`${prefix}/bin/node`] : [])];
420
+ if (stable.includes(ctx.nodePath))
421
+ owned = owned
422
+ .replace(`<array><string>${oldNode[1]}</string>`, `<array><string>${xml(ctx.nodePath)}</string>`)
423
+ .replace(`<key>PATH</key><string>${path.dirname(oldNode[1])}:`, `<key>PATH</key><string>${path.dirname(ctx.nodePath)}:`);
424
+ }
425
+ if (owned !== plist(ctx))
223
426
  throw new Error("darwin-stop-profile-mismatch");
224
427
  const result = await run(launchctl, ["bootout", target(ctx)]);
225
428
  if (result.code !== 0 && !absent(result))
@@ -258,15 +461,38 @@ export function createDarwinAdapter(options = {}) {
258
461
  // Do not guess a writable MCP target for non-default Claude profiles.
259
462
  // Shared setup may resolve it by a client-supported configuration query.
260
463
  const claudeConfig = env.CLAUDE_CONFIG_DIR ? null : path.join(home, ".claude.json");
464
+ const claudeDesktop = await hasApp(["Claude.app"], "com.anthropic.claudefordesktop");
465
+ async function hasBundledClaudeCode() {
466
+ if (!claudeDesktop)
467
+ return false;
468
+ const root = path.join(home, "Library", "Application Support", "Claude", "claude-code");
469
+ const directories = async (dir) => (await fs.readdir(dir, { withFileTypes: true }).catch(() => []))
470
+ .filter(entry => entry.isDirectory()).map(entry => path.join(dir, entry.name));
471
+ // Known desktop layouts: version/claude and version/build/claude.app/Contents/MacOS/claude.
472
+ // Inspect metadata only; never run a discovered binary or recurse through user files.
473
+ for (const version of await directories(root)) {
474
+ const builds = [version, ...await directories(version)];
475
+ for (const build of builds)
476
+ for (const candidate of [path.join(build, "claude"),
477
+ path.join(build, "claude.app", "Contents", "MacOS", "claude")]) {
478
+ if (await accessible(candidate, constants.X_OK) && await fs.stat(candidate).then(s => s.isFile(), () => false))
479
+ return true;
480
+ }
481
+ }
482
+ return false;
483
+ }
484
+ const claudeCli = await hasExecutable("claude");
485
+ const bundledCode = !claudeCli && await hasBundledClaudeCode();
261
486
  return [
262
- { id: "claude-code", installed: await hasExecutable("claude"), configPath: claudeConfig, format: "json",
487
+ { id: "claude-code", installed: claudeCli || bundledCode, configPath: claudeConfig, format: "json",
488
+ ...(bundledCode ? { detail: "Claude Code in the Claude desktop application" } : {}),
263
489
  ...(claudeConfig === null ? { detail: "Custom CLAUDE_CONFIG_DIR detected; MCP config target requires client verification" } : {}) },
264
- { id: "claude-desktop", installed: await hasApp(["Claude.app"], "com.anthropic.claudefordesktop"), configPath: path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json"), format: "json" },
490
+ { id: "claude-desktop", installed: claudeDesktop, configPath: path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json"), format: "json" },
265
491
  { id: "codex-cli", installed: await hasExecutable("codex"), configPath: codexConfig, format: "toml" },
266
492
  { id: "codex-desktop", installed: await hasApp(["Codex.app", "ChatGPT.app"], "com.openai.codex"), configPath: codexConfig, format: "toml" },
267
493
  ];
268
494
  }
269
- return { manager: "launchd", status, install, start, stop, detectClients,
495
+ return { manager: "launchd", status, install, start, stop, detectClients, profileUsage,
270
496
  async observeStore(ctx, pid) {
271
497
  validate(ctx);
272
498
  if (!Number.isSafeInteger(pid) || pid <= 0)