@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
@@ -0,0 +1,128 @@
1
+ import { constants } from 'node:fs';
2
+ import { lstat, mkdir, open, readdir, realpath, rmdir, unlink } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { createHash } from 'node:crypto';
5
+ import * as TOML from '@iarna/toml';
6
+ import { validateConfig } from './config.js';
7
+ import { sameClientFileIdentity } from './file-identity.js';
8
+ import { verifyPrivateFileAccess } from './private-file.js';
9
+ const DAY = 86_400_000;
10
+ const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}';
11
+ const POLICY = { days: 30, minimumCopies: 5 };
12
+ const digest = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
13
+ const identity = (s) => [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs, s.uid, s.mode, s.nlink].map(String);
14
+ async function readFile(file, privateBackup) {
15
+ const before = await lstat(file, { bigint: true });
16
+ if (!before.isFile() || before.nlink !== 1n || before.size > 4n * 1024n * 1024n
17
+ || (process.getuid && before.uid !== BigInt(process.getuid())))
18
+ throw new Error('backups.file-invalid');
19
+ const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
20
+ try {
21
+ const opened = await handle.stat({ bigint: true });
22
+ if (!sameClientFileIdentity(before, opened))
23
+ throw new Error('backups.file-changed');
24
+ if (privateBackup)
25
+ await verifyPrivateFileAccess(file, opened);
26
+ const text = await handle.readFile('utf8');
27
+ const after = await lstat(file, { bigint: true });
28
+ if (digest(identity(before)) !== digest(identity(after)) || !sameClientFileIdentity(after, opened))
29
+ throw new Error('backups.file-changed');
30
+ return { text, fingerprint: [identity(after), digest(text)], modifiedAt: Number(after.mtimeMs), size: Number(after.size) };
31
+ }
32
+ finally {
33
+ await handle.close();
34
+ }
35
+ }
36
+ function validateDocument(text, selection, file) {
37
+ try {
38
+ const value = file.endsWith('.toml') ? TOML.parse(text) : JSON.parse(text);
39
+ if (selection.kind === 'agent')
40
+ validateConfig(value);
41
+ else if (!value || typeof value !== 'object' || Array.isArray(value))
42
+ throw new Error();
43
+ }
44
+ catch {
45
+ throw new Error('backups.config-invalid');
46
+ }
47
+ }
48
+ async function selected(c, selection) {
49
+ if (!['agent', 'client'].includes(selection.kind))
50
+ throw new Error('backups.kind-required');
51
+ if (selection.kind === 'agent' && selection.configFile !== undefined)
52
+ throw new Error('backups.selection-conflict');
53
+ const file = selection.kind === 'agent' ? c?.configPath : selection.configFile;
54
+ if (!file || !path.isAbsolute(file) || path.normalize(file) !== file)
55
+ throw new Error('backups.absolute-config-file-required');
56
+ if (selection.kind === 'client' && !/\.(json|toml)$/.test(file))
57
+ throw new Error('backups.client-format-invalid');
58
+ const directory = await realpath(path.dirname(file));
59
+ if (directory === path.parse(directory).root)
60
+ throw new Error('backups.directory-invalid');
61
+ const info = await lstat(directory, { bigint: true });
62
+ if (!info.isDirectory() || (process.getuid && (info.uid !== BigInt(process.getuid()) || (info.mode & 18n) !== 0n))) {
63
+ throw new Error('backups.directory-invalid');
64
+ }
65
+ // The service's selected path is unchanged. Only cleanup targets use this verified canonical parent.
66
+ const configFile = path.join(directory, path.basename(file));
67
+ const escaped = path.basename(file).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
68
+ const pattern = selection.kind === 'agent' ? new RegExp(`^agent-config\\.backup-${UUID}\\.json$`)
69
+ : new RegExp(`^${escaped}\\.murmur-backup-${UUID}$`);
70
+ return { directory, configFile, pattern, directoryIdentity: identity(info).slice(0, 2),
71
+ lock: selection.kind === 'agent' ? path.join(directory, '.setup-write.lock') : `${configFile}.murmur-lock` };
72
+ }
73
+ async function inspect(c, selection, now) {
74
+ const source = await selected(c, selection), current = await readFile(source.configFile, false);
75
+ validateDocument(current.text, selection, source.configFile);
76
+ const cutoff = Math.floor(now / DAY) * DAY - POLICY.days * DAY;
77
+ const files = [];
78
+ for (const name of (await readdir(source.directory)).filter(name => source.pattern.test(name))) {
79
+ const file = path.join(source.directory, name), snapshot = await readFile(file, true);
80
+ // Corrupted recovery material needs investigation; never automatically classify it as disposable.
81
+ validateDocument(snapshot.text, selection, source.configFile);
82
+ files.push({ path: file, ...snapshot });
83
+ }
84
+ files.sort((a, b) => b.modifiedAt - a.modifiedAt || a.path.localeCompare(b.path));
85
+ const kept = new Set(selection.keepFiles ?? []);
86
+ if ([...kept].some(file => !files.some(item => item.path === file)))
87
+ throw new Error('backups.keep-file-invalid');
88
+ const entries = files.map((file, index) => ({ path: file.path, size: file.size, modifiedAt: new Date(file.modifiedAt).toISOString(),
89
+ action: kept.has(file.path) || index < POLICY.minimumCopies || file.modifiedAt >= cutoff ? 'keep' : 'remove',
90
+ reason: kept.has(file.path) ? 'explicit-keep' : index < POLICY.minimumCopies ? 'newest-five' : file.modifiedAt >= cutoff ? 'recovery-window' : 'outside-retention' }));
91
+ const planId = digest([selection.kind, source.configFile, source.directoryIdentity, current.fingerprint, cutoff,
92
+ files.map(file => [file.path, file.fingerprint]), entries]);
93
+ return { source, files, report: { schema: 'murmur.backup-plan/1', kind: selection.kind, configFile: source.configFile,
94
+ policy: POLICY, cutoff: new Date(cutoff).toISOString(), expiresAt: new Date((Math.floor(now / DAY) + 1) * DAY).toISOString(),
95
+ planId, entries, removable: entries.filter(entry => entry.action === 'remove').length } };
96
+ }
97
+ /** No chmod, lock, directory creation, metadata write or automatic migration during preview. */
98
+ export async function previewBackups(c, selection, now = Date.now()) {
99
+ return (await inspect(c, selection, now)).report;
100
+ }
101
+ /** Explicit deletion requires an unchanged, same-day preview and the existing setup writer's lock. */
102
+ export async function cleanupBackups(c, selection, expectedPlan, now = Date.now()) {
103
+ if (!/^[a-f0-9]{64}$/.test(expectedPlan))
104
+ throw new Error('backups.plan-required');
105
+ const source = await selected(c, selection);
106
+ await mkdir(source.lock, { mode: 0o700 });
107
+ const removed = [];
108
+ try {
109
+ const plan = await inspect(c, selection, now);
110
+ if (plan.report.planId !== expectedPlan)
111
+ throw new Error('backups.plan-stale');
112
+ for (const entry of plan.report.entries.filter(entry => entry.action === 'remove')) {
113
+ const current = await selected(c, selection);
114
+ if (current.directory !== source.directory || digest(current.directoryIdentity) !== digest(source.directoryIdentity))
115
+ throw new Error('backups.directory-changed');
116
+ const saved = plan.files.find(file => file.path === entry.path);
117
+ if (digest((await readFile(entry.path, true)).fingerprint) !== digest(saved.fingerprint))
118
+ throw new Error('backups.plan-stale');
119
+ await unlink(entry.path);
120
+ removed.push(entry.path);
121
+ }
122
+ return { schema: 'murmur.backup-cleanup/1', kind: selection.kind, configFile: plan.report.configFile,
123
+ planId: expectedPlan, removed, retained: plan.report.entries.filter(entry => entry.action === 'keep').map(entry => entry.path) };
124
+ }
125
+ finally {
126
+ await rmdir(source.lock);
127
+ }
128
+ }
@@ -0,0 +1,24 @@
1
+ import type { NatsTlsOptions } from '@murmurv2/core';
2
+ export interface BrokerInputFiles {
3
+ tokenFile?: string;
4
+ userFile?: string;
5
+ passwordFile?: string;
6
+ caFile?: string;
7
+ serverName?: string;
8
+ }
9
+ export interface BrokerAuthConfig {
10
+ natsToken?: string;
11
+ natsUser?: string;
12
+ natsPassword?: string;
13
+ natsTls?: NatsTlsOptions;
14
+ }
15
+ export interface BrokerInputSnapshot {
16
+ config: BrokerAuthConfig;
17
+ proof: string;
18
+ }
19
+ export declare function readBrokerInputsSnapshot(input: BrokerInputFiles): Promise<BrokerInputSnapshot>;
20
+ export declare function readBrokerInputs(input: BrokerInputFiles): Promise<BrokerAuthConfig>;
21
+ /** Recheck persisted TLS paths immediately before a network client consumes them. */
22
+ export declare function validateConfiguredTlsFiles(config: {
23
+ natsTls?: NatsTlsOptions;
24
+ }): Promise<void>;
@@ -0,0 +1,98 @@
1
+ import { verifyPrivateFileAccess } from './private-file.js';
2
+ import { sameClientFileIdentity } from './file-identity.js';
3
+ import { constants } from 'node:fs';
4
+ import { lstat, open } from 'node:fs/promises';
5
+ import { createHash } from 'node:crypto';
6
+ import path from 'node:path';
7
+ async function checkedFile(file, secret, limit) {
8
+ if (!path.isAbsolute(file))
9
+ throw new Error('broker-input.file-must-be-absolute');
10
+ const pathInfo = await lstat(file, { bigint: true });
11
+ if (pathInfo.isSymbolicLink() || !pathInfo.isFile())
12
+ throw new Error('broker-input.file-invalid');
13
+ const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
14
+ try {
15
+ const info = await handle.stat();
16
+ if (!info.isFile() || info.size < 1 || info.size > limit)
17
+ throw new Error('broker-input.file-invalid');
18
+ if (!sameClientFileIdentity(pathInfo, await handle.stat({ bigint: true })))
19
+ throw new Error('broker-input.file-changed');
20
+ if (typeof process.getuid === 'function' && info.uid !== process.getuid())
21
+ throw new Error('broker-input.owner-mismatch');
22
+ if (secret && process.platform === 'win32') {
23
+ try {
24
+ await verifyPrivateFileAccess(file, await handle.stat({ bigint: true }));
25
+ }
26
+ catch {
27
+ throw new Error('broker-input.file-not-private');
28
+ }
29
+ }
30
+ if (secret && process.platform !== 'win32' && (info.mode & 0o077) !== 0)
31
+ throw new Error('broker-input.file-not-private');
32
+ const bytes = Buffer.alloc(limit + 1);
33
+ let offset = 0;
34
+ while (offset < bytes.length) {
35
+ const result = await handle.read(bytes, offset, bytes.length - offset, null);
36
+ if (result.bytesRead === 0)
37
+ break;
38
+ offset += result.bytesRead;
39
+ }
40
+ const after = await handle.stat();
41
+ if (offset > limit || after.dev !== info.dev || after.ino !== info.ino || after.size !== info.size || offset !== info.size)
42
+ throw new Error('broker-input.file-changed');
43
+ const content = bytes.subarray(0, offset), text = content.toString('utf8');
44
+ if (text.includes('\0'))
45
+ throw new Error(secret ? 'broker-input.secret-invalid' : 'broker-input.file-invalid');
46
+ return { text, file, proof: createHash('sha256').update(content).digest('hex') };
47
+ }
48
+ finally {
49
+ await handle.close();
50
+ }
51
+ }
52
+ export async function readBrokerInputsSnapshot(input) {
53
+ if (input.tokenFile && (input.userFile || input.passwordFile))
54
+ throw new Error('nats-auth-methods-conflict');
55
+ if (!!input.userFile !== !!input.passwordFile)
56
+ throw new Error('nats-user-password-pair-required');
57
+ const out = {};
58
+ const proofs = [];
59
+ if (input.tokenFile) {
60
+ const { text, proof } = await checkedFile(input.tokenFile, true, 16 * 1024);
61
+ proofs.push(`token:${proof}`);
62
+ const value = text.replace(/\r?\n$/, '');
63
+ if (!value || /[\r\n]/.test(value))
64
+ throw new Error('broker-input.secret-invalid');
65
+ out.natsToken = value;
66
+ }
67
+ if (input.userFile && input.passwordFile) {
68
+ const [{ text: user, proof: userProof }, { text: password, proof: passwordProof }] = await Promise.all([
69
+ checkedFile(input.userFile, true, 16 * 1024), checkedFile(input.passwordFile, true, 16 * 1024),
70
+ ]);
71
+ proofs.push(`user:${userProof}`, `password:${passwordProof}`);
72
+ const userValue = user.replace(/\r?\n$/, ''), passwordValue = password.replace(/\r?\n$/, '');
73
+ if (!userValue || !passwordValue || /[\r\n]/.test(userValue) || /[\r\n]/.test(passwordValue))
74
+ throw new Error('broker-input.secret-invalid');
75
+ out.natsUser = userValue;
76
+ out.natsPassword = passwordValue;
77
+ }
78
+ if (input.caFile || input.serverName) {
79
+ if (input.caFile)
80
+ proofs.push(`ca:${(await checkedFile(input.caFile, false, 1024 * 1024)).proof}`);
81
+ out.natsTls = { ...(input.caFile ? { caFile: input.caFile } : {}), ...(input.serverName ? { serverName: input.serverName } : {}) };
82
+ }
83
+ proofs.push(`server:${input.serverName ?? ''}`);
84
+ return { config: out, proof: createHash('sha256').update(proofs.join('\0')).digest('hex') };
85
+ }
86
+ export async function readBrokerInputs(input) { return (await readBrokerInputsSnapshot(input)).config; }
87
+ /** Recheck persisted TLS paths immediately before a network client consumes them. */
88
+ export async function validateConfiguredTlsFiles(config) {
89
+ const tls = config.natsTls;
90
+ if (!tls)
91
+ return;
92
+ if (tls.caFile)
93
+ await checkedFile(tls.caFile, false, 1024 * 1024);
94
+ if (tls.certFile)
95
+ await checkedFile(tls.certFile, false, 1024 * 1024);
96
+ if (tls.keyFile)
97
+ await checkedFile(tls.keyFile, true, 1024 * 1024);
98
+ }
@@ -0,0 +1,35 @@
1
+ import { type BrokerInputFiles } from './broker-input.js';
2
+ import type { PlatformAdapter, ServiceContext } from './types.js';
3
+ export interface BrokerMigrationOptions extends BrokerInputFiles {
4
+ brokerUrl: string;
5
+ apply?: boolean;
6
+ }
7
+ export declare function migrateBroker(c: ServiceContext, adapter: PlatformAdapter, options: BrokerMigrationOptions): Promise<{
8
+ schema: string;
9
+ applied: boolean;
10
+ changed: boolean;
11
+ restartRequired: boolean;
12
+ backup: null;
13
+ from: {
14
+ scheme: string;
15
+ auth: string;
16
+ };
17
+ to: {
18
+ scheme: string;
19
+ auth: string;
20
+ };
21
+ } | {
22
+ schema: string;
23
+ applied: boolean;
24
+ changed: boolean;
25
+ restartRequired: boolean;
26
+ backup: string;
27
+ from: {
28
+ scheme: string;
29
+ auth: string;
30
+ };
31
+ to: {
32
+ scheme: string;
33
+ auth: string;
34
+ };
35
+ }>;
@@ -0,0 +1,138 @@
1
+ import { mkdir, realpath, rmdir, unlink } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { isDeepStrictEqual } from 'node:util';
5
+ import { readJsonSnapshot, validateConfig } from './config.js';
6
+ import { readBrokerInputsSnapshot } from './broker-input.js';
7
+ import { restoreExactBackup, writeExactBackup, writeState } from './state.js';
8
+ async function candidate(c, options) {
9
+ const snapshot = await readJsonSnapshot(c.configPath);
10
+ const before = validateConfig(snapshot.value);
11
+ const input = await readBrokerInputsSnapshot(options);
12
+ const afterRaw = { ...snapshot.value, natsUrl: options.brokerUrl };
13
+ delete afterRaw.natsToken;
14
+ delete afterRaw.natsUser;
15
+ delete afterRaw.natsPassword;
16
+ delete afterRaw.natsTls;
17
+ Object.assign(afterRaw, input.config);
18
+ const after = validateConfig(afterRaw);
19
+ return { before, after, configBytes: snapshot.bytes, inputProof: input.proof };
20
+ }
21
+ const authKind = (config) => config.natsToken ? 'token'
22
+ : config.natsUser || config.natsPassword ? 'user-password' : 'none';
23
+ const redactedEndpoint = (config) => ({ scheme: new URL(config.natsUrl).protocol, auth: authKind(config) });
24
+ async function observedDaemonIsAbsent(c, config) {
25
+ let observation;
26
+ try {
27
+ observation = (await readJsonSnapshot(path.join(c.dataDir, 'daemon-observation.json'))).value;
28
+ }
29
+ catch (error) {
30
+ if (error.code === 'ENOENT')
31
+ return;
32
+ throw new Error('migration.runtime-unverifiable');
33
+ }
34
+ if (!observation || observation.schema !== 'murmur.runtime/1' || observation.agentId !== config.agentId
35
+ || !Number.isSafeInteger(observation.pid) || observation.pid < 1 || typeof observation.storePath !== 'string' || !path.isAbsolute(observation.storePath)) {
36
+ throw new Error('migration.runtime-unverifiable');
37
+ }
38
+ try {
39
+ const [observed, expected] = await Promise.all([realpath(observation.storePath), realpath(c.storePath)]);
40
+ if (observed !== expected)
41
+ throw new Error('migration.runtime-unverifiable');
42
+ }
43
+ catch (error) {
44
+ if (error instanceof Error && error.message === 'migration.runtime-unverifiable')
45
+ throw error;
46
+ throw new Error('migration.runtime-unverifiable');
47
+ }
48
+ try {
49
+ process.kill(observation.pid, 0);
50
+ throw new Error('migration.profile-in-use');
51
+ }
52
+ catch (error) {
53
+ if (error instanceof Error && error.message === 'migration.profile-in-use')
54
+ throw error;
55
+ if (error.code !== 'ESRCH')
56
+ throw new Error('migration.runtime-unverifiable');
57
+ }
58
+ }
59
+ async function assertProfileFree(c, adapter, config) {
60
+ await observedDaemonIsAbsent(c, config);
61
+ if (!adapter.profileUsage)
62
+ throw new Error('migration.profile-usage-unavailable');
63
+ let usage;
64
+ try {
65
+ usage = await adapter.profileUsage(c);
66
+ }
67
+ catch {
68
+ throw new Error('migration.profile-usage-unavailable');
69
+ }
70
+ if (!usage || !['free', 'in-use', 'unknown'].includes(usage.state) || typeof usage.reason !== 'string')
71
+ throw new Error('migration.profile-usage-unavailable');
72
+ if (usage.state === 'in-use')
73
+ throw new Error('migration.profile-in-use');
74
+ if (usage.state === 'unknown' && usage.reason === 'profile-usage.profile-hard-linked')
75
+ throw new Error('migration.profile-hard-linked');
76
+ if (usage.state !== 'free')
77
+ throw new Error('migration.profile-usage-unavailable');
78
+ }
79
+ async function restoreAfterWriteFailure(c, backup, original) {
80
+ try {
81
+ await restoreExactBackup(c, backup, c.configPath, original);
82
+ if (!(await readJsonSnapshot(c.configPath)).bytes.equals(original))
83
+ throw new Error('migration.restore-verification-failed');
84
+ await unlink(backup).catch(error => { if (error.code !== 'ENOENT')
85
+ throw error; });
86
+ }
87
+ catch {
88
+ throw new Error('migration.config-write-uncertain');
89
+ }
90
+ throw new Error('migration.config-write-failed');
91
+ }
92
+ export async function migrateBroker(c, adapter, options) {
93
+ if (!options.brokerUrl)
94
+ throw new Error('migration.broker-url-required');
95
+ // Do not silently change path-derived service identity when resolving a Unix alias.
96
+ // Refuse before preview, lock creation or any service operation; the user can
97
+ // inspect the physical path and retain an explicit existing service name.
98
+ if (process.platform !== 'win32' && await realpath(c.dataDir) !== c.dataDir) {
99
+ throw new Error('migration.profile-path-aliased');
100
+ }
101
+ const preview = await candidate(c, options);
102
+ const changed = !isDeepStrictEqual(preview.before, preview.after);
103
+ if (!options.apply)
104
+ return { schema: 'murmur.broker-migration/1', applied: false, changed, restartRequired: changed, backup: null,
105
+ from: redactedEndpoint(preview.before), to: redactedEndpoint(preview.after) };
106
+ if (!changed)
107
+ return { schema: 'murmur.broker-migration/1', applied: false, changed: false, restartRequired: false, backup: null,
108
+ from: redactedEndpoint(preview.before), to: redactedEndpoint(preview.after) };
109
+ const lock = path.join(c.dataDir, '.setup-write.lock');
110
+ await mkdir(lock, { mode: 0o700 });
111
+ try {
112
+ const service = await adapter.status(c);
113
+ if (service.state !== 'stopped' || service.pid !== null)
114
+ throw new Error('migration.service-must-be-stopped');
115
+ await assertProfileFree(c, adapter, preview.before);
116
+ const current = await candidate(c, options);
117
+ if (!current.configBytes.equals(preview.configBytes))
118
+ throw new Error('migration.config-changed');
119
+ if (current.inputProof !== preview.inputProof || !isDeepStrictEqual(current.after, preview.after))
120
+ throw new Error('migration.input-changed');
121
+ // Snapshot evidence is repeated immediately before mutation. A native adapter must
122
+ // independently report this profile free; a stopped service alone is insufficient.
123
+ await assertProfileFree(c, adapter, current.before);
124
+ const backup = path.join(c.dataDir, `agent-config.backup-${randomUUID()}.json`);
125
+ await writeExactBackup(c, backup, current.configBytes);
126
+ try {
127
+ await writeState(c, c.configPath, current.after);
128
+ }
129
+ catch {
130
+ return await restoreAfterWriteFailure(c, backup, current.configBytes);
131
+ }
132
+ return { schema: 'murmur.broker-migration/1', applied: true, changed: true, restartRequired: true, backup,
133
+ from: redactedEndpoint(current.before), to: redactedEndpoint(current.after) };
134
+ }
135
+ finally {
136
+ await rmdir(lock);
137
+ }
138
+ }
@@ -0,0 +1,2 @@
1
+ /** Human stderr only; structured consumers retain the stable error code. */
2
+ export declare function cliErrorText(error: unknown): string;
@@ -0,0 +1,30 @@
1
+ import { safeError } from './config.js';
2
+ /** Human stderr only; structured consumers retain the stable error code. */
3
+ export function cliErrorText(error) {
4
+ const code = safeError(error);
5
+ if (code === 'migration.profile-path-aliased') {
6
+ return code + '\nThe selected profile path contains a filesystem alias. Migration stopped; your files were kept. '
7
+ + 'Find its canonical path with the read-only command in the guide, then retry with that path. '
8
+ + 'Keep the existing service name explicit if the service was registered using an alias. '
9
+ + 'Steps: https://github.com/alexfrmn/murmur/blob/main/docs/setup-onboarding.md#profile-path-aliases';
10
+ }
11
+ if (code === 'migration.profile-hard-linked') {
12
+ return code + '\nA profile file has another hard-link name. Migration stopped; your files were kept. '
13
+ + 'Inspect files with multiple links in the selected profile, then locate their other names on the same volume. '
14
+ + 'After verifying and removing only an unintended link, retry migration. Renaming a file does not separate the links. '
15
+ + 'Read-only inspection steps: https://github.com/alexfrmn/murmur/blob/main/docs/setup-onboarding.md#files-with-more-than-one-name';
16
+ }
17
+ if (code === 'migration.profile-usage-unavailable') {
18
+ return code + '\nMurmur could not inspect every process that might be using this profile. '
19
+ + 'Migration stopped; your files were kept. Closing the tray icon does not stop the service or client integrations. '
20
+ + 'This build cannot force migration when profile use is unknown. '
21
+ + 'Details: https://github.com/alexfrmn/murmur/blob/main/docs/setup-onboarding.md#migrating-an-existing-broker';
22
+ }
23
+ if (code === 'migration.runtime-unverifiable') {
24
+ return code + '\nMurmur could not verify the daemon observation for the selected profile. '
25
+ + 'Migration stopped; your files were kept. Check the selected profile, its daemon observation and process state before retrying. '
26
+ + 'Do not delete the observation or recreate the profile to bypass this check. '
27
+ + 'Details: https://github.com/alexfrmn/murmur/blob/main/docs/setup-onboarding.md#migrating-an-existing-broker';
28
+ }
29
+ return code;
30
+ }
@@ -1,8 +1,12 @@
1
+ import { migrateBroker } from './broker-migration.js';
1
2
  import { configureClient, previewClientConfiguration } from './clients.js';
3
+ import { previewBackups, cleanupBackups } from './backups.js';
4
+ import { checkInstallationSelection, selectInstallation, showInstallation } from './installation.js';
2
5
  import { prepareReplyTest, checkReplyTest } from './reply-test.js';
3
6
  import { listOutboxAttention, setOutboxDismissed } from './outbox-attention.js';
4
7
  import { dismissWake } from './wake-attention.js';
5
8
  import { initialize, invite, join, importPeer } from './onboarding.js';
9
+ import { connect, renderConnect } from './connect.js';
6
10
  import { runDoctor } from './doctor.js';
7
11
  import { parseArgs } from 'node:util';
8
12
  import path from 'node:path';
@@ -42,8 +46,13 @@ export async function main(args, adapter = platformAdapter(), input = process.st
42
46
  let parsed;
43
47
  try {
44
48
  parsed = parseArgs({ args, allowPositionals: true, options: {
49
+ kind: { type: 'string' }, 'config-file': { type: 'string' }, 'keep-file': { type: 'string', multiple: true },
50
+ 'installation-file': { type: 'string' }, select: { type: 'boolean' },
45
51
  'msg-id': { type: 'string' }, 'expected-state': { type: 'string' }, 'expected-agent': { type: 'string' },
52
+ 'project-dir': { type: 'string' },
53
+ 'user-file': { type: 'string' }, 'password-file': { type: 'string' }, 'ca-file': { type: 'string' }, 'server-name': { type: 'string' },
46
54
  'agent-id': { type: 'string' }, 'broker-url': { type: 'string' }, broker: { type: 'string' }, 'token-file': { type: 'string' }, 'invite-file': { type: 'string' }, 'reply-file': { type: 'string' }, 'reply-out': { type: 'string' }, out: { type: 'string' },
55
+ invite: { type: 'string' }, 'no-service': { type: 'boolean' }, 'copy-reply': { type: 'boolean' }, 'print-secret': { type: 'boolean' },
47
56
  'invite-stdin': { type: 'boolean' }, 'reply-stdin': { type: 'boolean' },
48
57
  client: { type: 'string' }, replace: { type: 'boolean' }, 'replace-previous': { type: 'boolean' }, 'plan-id': { type: 'string' }, 'test-token': { type: 'string' }, json: { type: 'boolean' }, line: { type: 'boolean' }, limit: { type: 'string' }, peer: { type: 'string' }, timeout: { type: 'string' }, 'data-dir': { type: 'string' }, 'service-name': { type: 'string' }, apply: { type: 'boolean' }, help: { type: 'boolean' },
49
58
  } });
@@ -54,11 +63,15 @@ export async function main(args, adapter = platformAdapter(), input = process.st
54
63
  }
55
64
  const { values, positionals } = parsed;
56
65
  if (values.help || !positionals.length)
57
- return { commands: ['version --json', 'updates check|enable|disable --json', 'init --agent-id ID --broker-url URL [--token-file FILE]', 'invite [--out FILE] [--broker PUBLIC_URL] [--json]', 'join --agent-id ID (--invite-stdin|--invite-file FILE) [--reply-out FILE] [--json]', 'add-peer (--reply-stdin|--reply-file FILE)', 'status --json|--line', 'doctor --json [--peer AGENT] [--timeout MILLISECONDS]', 'logs path --json', 'service install [--replace-previous]|start|stop|uninstall', 'clients detect', 'clients preview --client ID', 'clients configure --client ID [--replace] [--plan-id SHA256]', 'reply-test prepare --peer AGENT', 'reply-test check --test-token TOKEN', 'wake pause|resume [--apply]', 'wake dismiss --msg-id ID --expected-agent ID', 'inbox read [--limit 1..100]', 'inbox mark-read', 'outbox list --json', 'outbox dismiss|restore --msg-id ID --expected-state TOKEN --expected-agent ID', 'mcp serve --data-dir ABSOLUTE'],
66
+ return { commands: ['broker migrate --broker-url URL [--token-file FILE|--user-file FILE --password-file FILE] [--ca-file FILE] [--server-name NAME] [--apply]', 'installation show [--installation-file ABSOLUTE]', 'installation select --data-dir ABSOLUTE [--replace] [--installation-file ABSOLUTE]', 'backups preview|cleanup --kind agent|client [--config-file ABSOLUTE] [--keep-file ABSOLUTE] [--plan-id SHA256]', 'version --json', 'updates check|enable|disable --json', 'init --agent-id ID --broker-url URL [--token-file FILE] [--select]', 'invite [--out FILE] [--broker-url PUBLIC_URL|--broker PUBLIC_URL] [--print-secret] [--json]', 'connect (--invite TEXT_OR_FILE|--invite-file FILE|--invite-stdin) [--agent-id ID] [--data-dir ABSOLUTE] [--reply-out FILE] [--client auto|claude-code|claude-desktop|codex|codex-cli|none] [--no-service] [--copy-reply] [--json]', 'join --agent-id ID (--invite-stdin|--invite-file FILE) [--reply-out FILE] [--select] [--json]', 'add-peer (--reply-stdin|--reply-file FILE)', 'status --json|--line', 'doctor --json [--peer AGENT] [--timeout MILLISECONDS]', 'logs path --json', 'service install [--replace-previous]|start|stop|uninstall', 'clients detect', 'clients preview --client ID [--project-dir ABSOLUTE]', 'clients configure --client ID [--project-dir ABSOLUTE] [--replace] [--plan-id SHA256]', 'reply-test prepare --peer AGENT', 'reply-test check --test-token TOKEN', 'wake pause|resume [--apply]', 'wake dismiss --msg-id ID --expected-agent ID', 'inbox read [--limit 1..100]', 'inbox mark-read', 'outbox list --json', 'outbox dismiss|restore --msg-id ID --expected-state TOKEN --expected-agent ID', 'mcp serve [--data-dir ABSOLUTE]'],
58
67
  options: ['--data-dir ABSOLUTE', '--service-name NAME'], note: 'Windows service mutations require an elevated terminal and the matching native helper.' };
59
68
  const [command, action, extra] = positionals;
60
69
  if (extra)
61
70
  throw new Error('cli.unexpected-argument');
71
+ if (['token-file', 'user-file', 'password-file', 'ca-file', 'server-name'].some(key => values[key] !== undefined)
72
+ && !['init', 'join'].includes(command) && !(command === 'broker' && action === 'migrate')
73
+ || values['broker-url'] !== undefined && !['init', 'invite'].includes(command) && !(command === 'broker' && action === 'migrate'))
74
+ throw new Error('cli.option-not-supported');
62
75
  if (values.line && command !== 'status')
63
76
  throw new Error('cli.line-only-for-status');
64
77
  if (values.line && values.json)
@@ -69,11 +82,23 @@ export async function main(args, adapter = platformAdapter(), input = process.st
69
82
  return checkUpdates();
70
83
  if (command === 'updates' && ['enable', 'disable'].includes(action))
71
84
  return setUpdateChecks(action === 'enable');
72
- const context = resolveContext({ dataDir: values['data-dir'], serviceName: values['service-name'] });
85
+ if (values['project-dir'] !== undefined && !['clients', 'doctor'].includes(command))
86
+ throw new Error('cli.project-dir-only-for-clients-or-doctor');
73
87
  const required = (name) => { const value = values[name]; if (typeof value !== 'string' || !value)
74
88
  throw new Error('cli.required-option:' + name); return value; };
75
- if (command === 'init' && !action)
76
- return initialize(context, { agentId: required('agent-id'), brokerUrl: required('broker-url'), tokenFile: values['token-file'] });
89
+ if (command === 'backups' && ['preview', 'cleanup'].includes(action) && values.kind === 'client') {
90
+ const selection = { kind: 'client', configFile: required('config-file'), keepFiles: values['keep-file'] };
91
+ return action === 'preview' ? previewBackups(null, selection) : cleanupBackups(null, selection, required('plan-id'));
92
+ }
93
+ if (command === 'installation' && action === 'show')
94
+ return showInstallation(values['installation-file']);
95
+ if (command === 'installation' && action === 'select' && values['data-dir'] === undefined)
96
+ throw new Error('cli.required-option:data-dir');
97
+ if (values.select && !['init', 'join'].includes(command))
98
+ throw new Error('cli.select-only-for-init-or-join');
99
+ if ((values.invite !== undefined || values['no-service'] || values['copy-reply']) && command !== 'connect'
100
+ || (values.broker !== undefined || values['print-secret']) && command !== 'invite')
101
+ throw new Error('cli.option-not-supported');
77
102
  const onboardingInput = async (kind) => {
78
103
  if (values[`${kind}-file`] !== undefined && values[`${kind}-stdin`])
79
104
  throw new Error('onboarding.input-conflict');
@@ -95,11 +120,45 @@ export async function main(args, adapter = platformAdapter(), input = process.st
95
120
  }
96
121
  return Buffer.concat(chunks).toString('utf8');
97
122
  };
98
- if (command === 'invite' && !action)
99
- return invite(context, values.out, { brokerUrl: values.broker });
123
+ if (command === 'connect' && !action) {
124
+ if ([values.invite !== undefined, values['invite-file'] !== undefined, !!values['invite-stdin']].filter(Boolean).length !== 1) {
125
+ throw new Error('connect.one-invite-input-required');
126
+ }
127
+ const result = await connect(adapter, {
128
+ agentId: values['agent-id'], dataDir: values['data-dir'], inviteFile: values['invite-file'],
129
+ inviteArgument: values.invite, invitation: values['invite-stdin'] ? await onboardingInput('invite') : undefined,
130
+ replyOut: values['reply-out'], client: values.client, noService: values['no-service'], copyReply: values['copy-reply'],
131
+ });
132
+ return values.json ? result : rawCliOutput(renderConnect(result));
133
+ }
134
+ const context = resolveContext({ dataDir: values['data-dir'], serviceName: values['service-name'], installationFile: values['installation-file'], clientProjectDir: values['project-dir'] });
135
+ if (command === 'backups' && ['preview', 'cleanup'].includes(action)) {
136
+ const kind = required('kind');
137
+ if (kind !== 'agent' && kind !== 'client')
138
+ throw new Error('backups.kind-required');
139
+ const selection = { kind, configFile: values['config-file'], keepFiles: values['keep-file'] };
140
+ return action === 'preview' ? previewBackups(context, selection) : cleanupBackups(context, selection, required('plan-id'));
141
+ }
142
+ if (command === 'installation' && action === 'select')
143
+ return selectInstallation(context, { file: values['installation-file'], replace: values.replace });
144
+ if (values.select)
145
+ checkInstallationSelection(context, { file: values['installation-file'], replace: values.replace });
146
+ const selected = async (result) => values.select ? { ...result, installation: await selectInstallation(context, { file: values['installation-file'], replace: values.replace }) } : result;
147
+ const brokerFiles = { tokenFile: values['token-file'], userFile: values['user-file'], passwordFile: values['password-file'],
148
+ caFile: values['ca-file'], serverName: values['server-name'] };
149
+ if (command === 'broker' && action === 'migrate')
150
+ return migrateBroker(context, adapter, { ...brokerFiles,
151
+ brokerUrl: required('broker-url'), apply: values.apply });
152
+ if (command === 'init' && !action)
153
+ return selected(await initialize(context, { agentId: required('agent-id'), brokerUrl: required('broker-url'), ...brokerFiles }));
154
+ if (command === 'invite' && !action) {
155
+ if (values['broker-url'] !== undefined && values.broker !== undefined)
156
+ throw new Error('cli.broker-options-conflict');
157
+ return invite(context, values.out, { brokerUrl: values['broker-url'] ?? values.broker, printSecret: values['print-secret'] });
158
+ }
100
159
  if (command === 'join' && !action)
101
- return join(context, { agentId: required('agent-id'), inviteFile: values['invite-file'],
102
- invitation: await onboardingInput('invite'), replyOut: values['reply-out'] });
160
+ return selected(await join(context, { agentId: required('agent-id'), inviteFile: values['invite-file'],
161
+ invitation: await onboardingInput('invite'), replyOut: values['reply-out'], ...brokerFiles }));
103
162
  if (command === 'add-peer' && !action)
104
163
  return importPeer(context, values['reply-file'], await onboardingInput('reply'));
105
164
  if (command === 'status' && !action) {
@@ -111,8 +170,6 @@ export async function main(args, adapter = platformAdapter(), input = process.st
111
170
  if (command === 'outbox' && ['dismiss', 'restore'].includes(action))
112
171
  return setOutboxDismissed(context, required('msg-id'), required('expected-state'), required('expected-agent'), action === 'dismiss');
113
172
  if (command === 'mcp' && action === 'serve') {
114
- if (values['data-dir'] === undefined)
115
- throw new Error('cli.required-option:data-dir');
116
173
  process.env.DATA_DIR = context.dataDir;
117
174
  process.env.MURMUR_DATA_DIR = context.dataDir;
118
175
  process.env.MURMUR_STORE_PATH = context.storePath;