@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
@@ -7,14 +7,16 @@ 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';
14
+ import { invitationServerAddress } from './invitation-server.js';
13
15
  async function privateText(file, role) {
14
16
  if (!path.isAbsolute(file))
15
17
  throw new Error('onboarding.file-must-be-absolute');
16
18
  // Name the option and the reason, never the path or contents: this is what a new user acts on.
17
- 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) => {
18
20
  if (e.code === 'ENOENT')
19
21
  throw new Error(`onboarding.${role}-not-found`);
20
22
  if (e.code === 'EPERM' || e.code === 'EACCES')
@@ -25,7 +27,18 @@ async function privateText(file, role) {
25
27
  const info = await handle.stat();
26
28
  if (!info.isFile() || info.size > 16384)
27
29
  throw new Error('onboarding.file-invalid');
28
- 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();
29
42
  }
30
43
  finally {
31
44
  await handle.close();
@@ -108,16 +121,29 @@ async function restrictToCurrentUser(target, directory) {
108
121
  await execFileAsync(system32('icacls.exe'), [target, '/inheritance:r', '/grant:r', `*${sid}:${inherit}(F)`, `*S-1-5-18:${inherit}(F)`], { windowsHide: true })
109
122
  .catch(() => { throw new Error('onboarding.private-acl-failed'); });
110
123
  }
111
- async function outputBlob(file, value, prefix, beforeWrite) {
124
+ const encodeBlob = (value, prefix = 'MURMUR:') => {
125
+ const text = prefix + Buffer.from(JSON.stringify(value)).toString('base64url');
126
+ if (Buffer.byteLength(text + '\n') > 16384)
127
+ throw new Error('onboarding.input-too-large');
128
+ return text;
129
+ };
130
+ async function outputBlob(file, text, beforeWrite, skipOccupied = false) {
112
131
  if (!path.isAbsolute(file))
113
132
  throw new Error('onboarding.output-must-be-absolute');
114
- 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;
115
141
  let written = false;
116
142
  try {
117
143
  // Protect the still-empty output before writing the invitation credential.
118
144
  await protectPrivateFile(file, handle);
119
145
  await beforeWrite?.();
120
- await handle.writeFile(prefix + Buffer.from(JSON.stringify(value)).toString('base64') + '\n');
146
+ await handle.writeFile(text + '\n');
121
147
  await handle.sync();
122
148
  written = true;
123
149
  }
@@ -126,6 +152,7 @@ async function outputBlob(file, value, prefix, beforeWrite) {
126
152
  if (!written)
127
153
  await unlink(file).catch(() => { });
128
154
  }
155
+ return true;
129
156
  }
130
157
  async function locked(c, fn) {
131
158
  // mkdir reports a path only when it created something: never rewrite an existing profile's ACL.
@@ -164,10 +191,10 @@ async function existing(c) {
164
191
  throw e;
165
192
  }
166
193
  }
167
- async function newConfig(agentId, url, token) {
194
+ async function newConfig(agentId, url, auth = {}) {
168
195
  if (!validAgentId(agentId))
169
196
  throw new Error('config.identity-invalid');
170
- return validateConfig({ agentId, subject: `msg.${agentId}`, natsUrl: url, ...(token ? { natsToken: token } : {}),
197
+ return validateConfig({ agentId, subject: `msg.${agentId}`, natsUrl: url, ...auth,
171
198
  keys: { encryption: await createKeyPair(), signing: await createSigningKeyPair() }, peers: {},
172
199
  wake: { enabled: true }, ackSecurity: { emitSigned: true, requireSigned: true } });
173
200
  }
@@ -185,12 +212,46 @@ async function saveChanged(c, previous, next) {
185
212
  }
186
213
  const publicPeer = (c) => ({ agentId: c.agentId, subject: c.subject,
187
214
  encryption: { publicKey: c.keys.encryption.publicKey }, signing: { publicKey: c.keys.signing.publicKey } });
188
- async function readBlob(file, prefix, type) {
189
- const text = await privateText(file, `${type}-file`);
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
+ }
241
+ async function readBlob(input, type) {
242
+ if ((input.file === undefined) === (input.text === undefined))
243
+ throw new Error('onboarding.input-required');
244
+ const text = (input.file !== undefined ? await privateText(input.file, `${type}-file`) : input.text).trim();
245
+ if (Buffer.byteLength(text, 'utf8') > 16384)
246
+ throw new Error('onboarding.input-too-large');
247
+ // Accept existing private files as well as the shared, type-tagged string format.
248
+ const prefix = type === 'reply' && text.startsWith('MURMUR-REPLY:') ? 'MURMUR-REPLY:' : 'MURMUR:';
190
249
  if (!text.startsWith(prefix))
191
250
  throw new Error('onboarding.invalid-blob');
192
251
  const encoded = text.slice(prefix.length);
193
- if (!/^[A-Za-z0-9+/]+={0,2}$/.test(encoded) || Buffer.from(encoded, 'base64').toString('base64') !== encoded)
252
+ const canonical = /^[A-Za-z0-9_-]+$/.test(encoded) && Buffer.from(encoded, 'base64url').toString('base64url') === encoded;
253
+ const legacy = /^[A-Za-z0-9+/]+={0,2}$/.test(encoded) && Buffer.from(encoded, 'base64').toString('base64') === encoded;
254
+ if (!canonical && !legacy)
194
255
  throw new Error('onboarding.invalid-blob');
195
256
  let value;
196
257
  try {
@@ -220,51 +281,84 @@ function addPeer(config, peer) {
220
281
  }
221
282
  export async function initialize(c, options) {
222
283
  await refuseVirtualizedAppData(c.dataDir);
284
+ const supplied = await readBrokerInputs(options);
223
285
  return locked(c, async () => {
224
286
  const previous = await existing(c);
225
287
  if (previous) {
226
- 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])))
227
290
  throw new Error('onboarding.existing-profile-conflict');
228
291
  // Re-running init never rotates keys or replaces credentials.
229
292
  return { schema: 'murmur.init/1', agentId: previous.agentId, dataDir: c.dataDir, serviceName: c.serviceName, existing: true };
230
293
  }
231
- const token = options.tokenFile ? await privateText(options.tokenFile, 'token-file') : undefined;
232
- if (token?.includes('\n') || token?.includes('\r'))
233
- throw new Error('onboarding.token-file-invalid');
234
- const config = await newConfig(options.agentId, options.brokerUrl, token);
294
+ const config = await newConfig(options.agentId, options.brokerUrl, supplied);
235
295
  await saveChanged(c, null, config);
236
296
  return { schema: 'murmur.init/1', agentId: config.agentId, dataDir: c.dataDir, serviceName: c.serviceName, existing: false };
237
297
  });
238
298
  }
239
- export async function invite(c, outFile) {
240
- await validateOutput(c, outFile);
299
+ export async function invite(c, outFile, options = {}) {
300
+ if (outFile !== undefined)
301
+ await validateOutput(c, outFile);
241
302
  const config = await loadConfig(c);
242
- await outputBlob(outFile, { v: 1, type: 'invite', ...publicPeer(config), natsUrl: config.natsUrl, ...(config.natsToken ? { natsToken: config.natsToken } : {}) }, 'MURMUR:');
243
- // The warning names what is actually inside. A person weighs "password" and "identity"
244
- // differently, and the same sentence for both teaches them to ignore it.
303
+ const server = invitationServerAddress(options.brokerUrl ?? config.natsUrl);
304
+ const invitation = encodeBlob({ v: 1, type: 'invite', ...publicPeer(config), natsUrl: server, ...(config.natsToken ? { natsToken: config.natsToken } : {}) });
305
+ if (outFile !== undefined)
306
+ await outputBlob(outFile, invitation);
245
307
  const containsBrokerCredential = !!config.natsToken;
246
- return { schema: 'murmur.invite/1', file: outFile, 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,
247
312
  instruction: containsBrokerCredential
248
- ? 'This file carries the broker address and its credential. Treat it like a password: send it only through a channel you would trust with one. Importing it does not prove pairing.'
249
- : 'This file carries your identity and the broker address. Send it through a channel you trust. Importing it does not prove pairing.' };
313
+ ? 'This Invitation contains a Server access key. Send it personally to your colleague. After exchanging the Reply, check the connection.'
314
+ : 'This Invitation contains your Identity and the Server address. Send it to your colleague. After exchanging the Reply, check the connection.' };
250
315
  }
251
316
  export async function join(c, options) {
252
- await validateOutput(c, options.replyOut);
253
- const incoming = await readBlob(options.inviteFile, 'MURMUR:', 'invite');
317
+ if (options.replyOut !== undefined)
318
+ await validateOutput(c, options.replyOut);
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 };
254
326
  // Before anything is created: a profile the service cannot see must not be written at all.
255
327
  await refuseVirtualizedAppData(c.dataDir);
256
328
  return locked(c, async () => {
257
329
  const previous = await existing(c);
258
- 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]))))
259
332
  throw new Error('onboarding.existing-profile-conflict');
260
- const config = previous ?? await newConfig(options.agentId, incoming.natsUrl, incoming.natsToken);
333
+ const config = previous ?? await newConfig(options.agentId, incoming.natsUrl, auth);
261
334
  const next = addPeer(config, incoming);
262
335
  let backup = null;
263
336
  // Reserve the reply path before changing config: an existing output must not half-import a profile.
264
- await outputBlob(options.replyOut, { v: 1, type: 'reply', ...publicPeer(next) }, 'MURMUR-REPLY:', async () => {
265
- backup = await saveChanged(c, previous, next);
266
- });
267
- return { schema: 'murmur.join/1', agentId: next.agentId, peerId: incoming.agentId, paired: null, replyFile: options.replyOut, backup, restartRequired: true, serviceName: c.serviceName };
337
+ const reply = encodeBlob({ v: 1, type: 'reply', ...publicPeer(next) }, options.connect ? 'MURMUR-REPLY:' : 'MURMUR:');
338
+ const save = async () => { backup = await saveChanged(c, previous, next); };
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
+ }
357
+ else
358
+ await save();
359
+ return { schema: 'murmur.join/1', agentId: next.agentId, peerId: incoming.agentId, paired: null,
360
+ replyFile, reply, backup, restartRequired: false,
361
+ contactsReload: { mechanism: 'config-file', state: 'pending' }, serviceName: c.serviceName };
268
362
  });
269
363
  }
270
364
  async function clearPeerPoison(c, peerId) {
@@ -287,12 +381,13 @@ async function clearPeerPoison(c, peerId) {
287
381
  return { cleared: null, reason: 'onboarding.poison-reset-failed' };
288
382
  }
289
383
  }
290
- export async function importPeer(c, replyFile) {
291
- const incoming = await readBlob(replyFile, 'MURMUR-REPLY:', 'reply');
384
+ export async function importPeer(c, replyFile, reply) {
385
+ const incoming = await readBlob({ file: replyFile, text: reply }, 'reply');
292
386
  return locked(c, async () => {
293
387
  const previous = await loadConfig(c), next = addPeer(previous, incoming);
294
388
  const backup = await saveChanged(c, previous, next);
295
389
  return { schema: 'murmur.peer/1', peerId: incoming.agentId, paired: null, backup,
296
- poisonReset: await clearPeerPoison(c, incoming.agentId), restartRequired: true };
390
+ poisonReset: await clearPeerPoison(c, incoming.agentId), restartRequired: false,
391
+ contactsReload: { mechanism: 'config-file', state: 'pending' } };
297
392
  });
298
393
  }
@@ -1,33 +1,15 @@
1
1
  import { DatabaseSync } from 'node:sqlite';
2
- import { createHash } from 'node:crypto';
2
+ import { outboxAttentionToken as tokenFor, readOutboxDismissals } from '@murmurv2/core';
3
3
  import { mkdir, rmdir } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
- import { loadConfig, readJson, safeError, validAgentId } from './config.js';
5
+ import { loadConfig, safeError, validAgentId } from './config.js';
6
6
  import { writeState } from './state.js';
7
7
  const stateFile = (c) => path.join(c.dataDir, 'outbox-attention.json');
8
8
  const validId = (v) => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,150}$/.test(v);
9
9
  const validToken = (v) => typeof v === 'string' && /^[a-f0-9]{64}$/.test(v);
10
10
  const columns = `msg_id AS msgId,subject,attempts,created_at AS createdAt,updated_at AS failedAt,last_error AS error,version,
11
11
  json_extract(envelope_json,'$.recipients[0]') AS peer`;
12
- const tokenFor = (row) => createHash('sha256').update(JSON.stringify([
13
- row.msgId, row.subject, row.attempts, row.createdAt, row.failedAt, row.error, row.version, row.peer,
14
- ])).digest('hex');
15
- async function saved(c, agentId) {
16
- let value;
17
- try {
18
- value = await readJson(stateFile(c));
19
- }
20
- catch (error) {
21
- if (error.code === 'ENOENT')
22
- return { schema: 'murmur.outbox-dismissals/1', agentId, records: [] };
23
- throw new Error('outbox.dismissals-unreadable');
24
- }
25
- if (value?.schema !== 'murmur.outbox-dismissals/1' || value.agentId !== agentId || !Array.isArray(value.records)
26
- || value.records.length > 1000 || value.records.some((r) => !validId(r?.msgId) || !validToken(r?.token))
27
- || new Set(value.records.map((r) => r.msgId)).size !== value.records.length)
28
- throw new Error('outbox.dismissals-invalid');
29
- return value;
30
- }
12
+ const saved = (c, agentId) => readOutboxDismissals(stateFile(c), agentId);
31
13
  /** Metadata only. A dismissal never changes transport state or implies delivery. */
32
14
  export async function readOutboxAttention(c, agentId, db) {
33
15
  const state = await saved(c, agentId), ignored = new Map(state.records.map(r => [r.msgId, r.token]));
@@ -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[];