@murmurv2/cli 2.12.0 → 2.14.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 (64) 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 +175 -79
  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/autoreply.d.ts +23 -0
  9. package/runtime/packages/setup/dist/src/autoreply.js +71 -0
  10. package/runtime/packages/setup/dist/src/backups.d.ts +36 -0
  11. package/runtime/packages/setup/dist/src/backups.js +128 -0
  12. package/runtime/packages/setup/dist/src/broker-input.d.ts +24 -0
  13. package/runtime/packages/setup/dist/src/broker-input.js +98 -0
  14. package/runtime/packages/setup/dist/src/broker-migration.d.ts +35 -0
  15. package/runtime/packages/setup/dist/src/broker-migration.js +138 -0
  16. package/runtime/packages/setup/dist/src/cli-error.d.ts +2 -0
  17. package/runtime/packages/setup/dist/src/cli-error.js +30 -0
  18. package/runtime/packages/setup/dist/src/cli.js +113 -10
  19. package/runtime/packages/setup/dist/src/clients.d.ts +33 -81
  20. package/runtime/packages/setup/dist/src/clients.js +159 -25
  21. package/runtime/packages/setup/dist/src/commands.d.ts +1 -0
  22. package/runtime/packages/setup/dist/src/commands.js +18 -6
  23. package/runtime/packages/setup/dist/src/config.d.ts +8 -0
  24. package/runtime/packages/setup/dist/src/config.js +58 -10
  25. package/runtime/packages/setup/dist/src/connect.d.ts +143 -0
  26. package/runtime/packages/setup/dist/src/connect.js +128 -0
  27. package/runtime/packages/setup/dist/src/conversations.d.ts +193 -0
  28. package/runtime/packages/setup/dist/src/conversations.js +674 -0
  29. package/runtime/packages/setup/dist/src/doctor.d.ts +30 -0
  30. package/runtime/packages/setup/dist/src/doctor.js +72 -10
  31. package/runtime/packages/setup/dist/src/installation.d.ts +25 -0
  32. package/runtime/packages/setup/dist/src/installation.js +89 -0
  33. package/runtime/packages/setup/dist/src/message-status.d.ts +1 -0
  34. package/runtime/packages/setup/dist/src/message-status.js +3 -0
  35. package/runtime/packages/setup/dist/src/onboarding.d.ts +11 -6
  36. package/runtime/packages/setup/dist/src/onboarding.js +92 -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 +247 -9
  41. package/runtime/packages/setup/dist/src/platform/linux.js +156 -12
  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 +48 -8
  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 +9 -0
  50. package/runtime/packages/setup/dist/src/status.js +7 -3
  51. package/runtime/packages/setup/dist/src/types.d.ts +11 -1
  52. package/runtime/packages/setup/dist/src/wake-readers.d.ts +12 -0
  53. package/runtime/packages/setup/dist/src/wake-readers.js +65 -0
  54. package/runtime/packages/setup/package.json +1 -1
  55. package/runtime/scripts/auth-security.mjs +93 -0
  56. package/runtime/scripts/codex-app-server-wake.mjs +36 -4
  57. package/runtime/scripts/daemon-contacts.mjs +1 -1
  58. package/runtime/scripts/murmur-auth-token.mjs +140 -0
  59. package/runtime/scripts/murmur-daemon.mjs +27 -8
  60. package/runtime/scripts/murmur-jetstream-advisory.mjs +27 -0
  61. package/runtime/scripts/murmur-shell-send.mjs +7 -3
  62. package/runtime/scripts/owner-review-store.mjs +54 -0
  63. package/runtime/scripts/wake-drain-claude.mjs +124 -7
  64. package/runtime/scripts/wake-monitor.mjs +49 -10
@@ -1,6 +1,6 @@
1
1
  import * as TOML from '@iarna/toml';
2
2
  import { constants } from 'node:fs';
3
- import { lstat, mkdir, open, rename, rmdir, stat, unlink } from 'node:fs/promises';
3
+ import { lstat, mkdir, open, realpath, rename, rmdir, stat, unlink } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
  import { createHash, randomUUID } from 'node:crypto';
6
6
  import { isDeepStrictEqual } from 'node:util';
@@ -10,11 +10,69 @@ import { protectPrivateFile, preparePrivateReplacement } from './private-file.js
10
10
  export { sameClientFileIdentity } from './file-identity.js';
11
11
  const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
12
12
  async function selectedClient(c, adapter, clientId) {
13
- const client = (await adapter.detectClients(c)).find(item => item.id === clientId);
13
+ const clients = await adapter.detectClients(c);
14
+ const client = clients.find(item => item.id === clientId);
14
15
  if (!client || !client.installed)
15
16
  throw new Error('client.not-detected');
16
17
  if (!client.configPath || !path.isAbsolute(client.configPath))
17
18
  throw new Error('client.config-path-unverified');
19
+ if (c.clientProjectDir) {
20
+ if (clientId !== 'claude-code')
21
+ throw new Error('client.project-only-for-claude-code');
22
+ if (!path.isAbsolute(c.clientProjectDir) || !(await stat(c.clientProjectDir).catch(() => null))?.isDirectory())
23
+ throw new Error('client.project-directory-required');
24
+ // An inherited global/ancestor hook would still wake other chats. Refuse before
25
+ // writing anything; never silently remove a person's existing integration.
26
+ const parents = new Set([path.dirname(client.configPath)]);
27
+ let parent = path.dirname(c.clientProjectDir);
28
+ while (true) {
29
+ parents.add(parent);
30
+ const next = path.dirname(parent);
31
+ if (next === parent)
32
+ break;
33
+ parent = next;
34
+ }
35
+ // Local settings merge their hooks with project settings. They must not leave
36
+ // a second reader behind even in the selected project itself.
37
+ const local = await readClientFile(path.join(c.clientProjectDir, '.claude', 'settings.local.json'));
38
+ if (local.text.includes('wake-drain-claude'))
39
+ throw new Error('client.inherited-wake-hook-conflict');
40
+ for (const dir of parents) {
41
+ if (dir === c.clientProjectDir)
42
+ throw new Error('client.project-must-be-dedicated');
43
+ for (const name of ['settings.json', 'settings.local.json']) {
44
+ const file = await readClientFile(path.join(dir, '.claude', name));
45
+ if (file.text.includes('wake-drain-claude'))
46
+ throw new Error('client.inherited-wake-hook-conflict');
47
+ }
48
+ }
49
+ // Desktop forwards Chat/user MCP registrations ahead of project entries.
50
+ // Refuse an occupied dedicated name instead of selecting a global identity.
51
+ // Code's local scope lives under projects[path] in the same user file and
52
+ // outranks .mcp.json too. Inspect both path spellings without changing the
53
+ // selected path used for service identity, folder name or wake lane.
54
+ const projectPaths = new Set([c.clientProjectDir, await realpath(c.clientProjectDir)]);
55
+ for (const global of clients.filter(item => ['claude-code', 'claude-desktop'].includes(item.id))) {
56
+ if (!global.configPath || !path.isAbsolute(global.configPath))
57
+ continue;
58
+ const file = await readClientFile(global.configPath);
59
+ const { original, key } = clientDocument(global, file.text);
60
+ if (original[key]?.[mcpEntryName(c)] !== undefined)
61
+ throw new Error('client.inherited-mcp-entry-conflict');
62
+ if (global.id === 'claude-code' && object(original.projects)) {
63
+ for (const projectPath of projectPaths) {
64
+ const local = original.projects[projectPath];
65
+ if (local === undefined)
66
+ continue;
67
+ if (!object(local) || local.mcpServers !== undefined && !object(local.mcpServers))
68
+ throw new Error('client.mcp-table-invalid');
69
+ if (local.mcpServers?.[mcpEntryName(c)] !== undefined)
70
+ throw new Error('client.inherited-mcp-entry-conflict');
71
+ }
72
+ }
73
+ }
74
+ return { ...client, configPath: path.join(c.clientProjectDir, '.mcp.json') };
75
+ }
18
76
  return { ...client, configPath: client.configPath };
19
77
  }
20
78
  async function readClientFile(file) {
@@ -67,15 +125,29 @@ const hookPath = (value) => `"${value.replaceAll('\\', '/')}"`;
67
125
  // Eight hours after each turn instead of the drain's 20-minute default: a message that arrives
68
126
  // during a working day still wakes the session (docs/wake-native.md, known limitation).
69
127
  const WAKE_WINDOW_SECONDS = 28800;
128
+ const projectLane = (c) => c.clientProjectDir
129
+ ? createHash('sha256').update(c.clientProjectDir).digest('hex').slice(0, 8) : null;
130
+ const mcpEntryName = (c) => c.clientProjectDir ? `murmur-${projectLane(c)}` : 'murmur';
70
131
  /** The node wake drain (docs/wake-native.md): polls the store after each turn and wakes the session. */
71
132
  function desiredWakeHook(c) {
72
133
  // Claude Code ends a hook without its own `timeout` after 600 s (hooks reference, asyncRewake);
73
134
  // the entry carries the same window the drain script is asked for, or the script never gets it.
135
+ const lane = projectLane(c);
74
136
  return { type: 'command', asyncRewake: true, timeout: WAKE_WINDOW_SECONDS,
75
- command: `${hookPath(c.nodePath)} --no-warnings ${hookPath(path.join(c.repoRoot, 'scripts', 'wake-drain-claude.mjs'))} --db ${hookPath(c.storePath)} --max-seconds ${WAKE_WINDOW_SECONDS}` };
137
+ command: `${hookPath(c.nodePath)} --no-warnings ${hookPath(path.join(c.repoRoot, 'scripts', 'wake-drain-claude.mjs'))} --db ${hookPath(c.storePath)} --max-seconds ${WAKE_WINDOW_SECONDS}${lane ? ` --session-key ${lane}` : ''}` };
76
138
  }
77
139
  const isMurmurWakeHook = (hook) => object(hook) && typeof hook.command === 'string' && hook.command.includes('wake-drain-claude');
78
- /** Plan the Stop hook edit; only Murmur's own wake hook is ever added, kept or replaced. */
140
+ const wakeGroups = (value) => Array.isArray(value) && value.every(group => object(group) && Array.isArray(group.hooks));
141
+ // The drain path inside a hook command, quoted or bare. Outside Stop it is the only part we
142
+ // rewrite, so flags and timeouts a person chose keep working.
143
+ const wakeScript = /"[^"]*wake-drain-claude[^"]*"|[^\s"]*wake-drain-claude[^\s"]*/;
144
+ const wakeScriptOf = (command) => command.match(wakeScript)?.[0].replaceAll('"', '').replaceAll('\\', '/');
145
+ /**
146
+ * Plan the Stop hook edit; only Murmur's own wake hook is ever added, kept or replaced.
147
+ * Hooks under other events keep their own flags and are only repointed at the script this
148
+ * runtime ships, so one settings file never runs two versions of the drain against the same
149
+ * session cursors (#294). Their events are reported, because they were written by hand.
150
+ */
79
151
  function planWakeHook(c, text) {
80
152
  let settings;
81
153
  try {
@@ -85,16 +157,29 @@ function planWakeHook(c, text) {
85
157
  throw new Error('client.settings-parse-failed');
86
158
  }
87
159
  if (!object(settings) || (settings.hooks !== undefined && !object(settings.hooks))
88
- || (settings.hooks?.Stop !== undefined && (!Array.isArray(settings.hooks.Stop)
89
- || !settings.hooks.Stop.every((group) => object(group) && Array.isArray(group.hooks)))))
160
+ || (settings.hooks?.Stop !== undefined && !wakeGroups(settings.hooks.Stop)))
90
161
  throw new Error('client.hooks-invalid');
91
162
  const entry = desiredWakeHook(c), groups = settings.hooks?.Stop ?? [];
92
163
  const ours = groups.flatMap(group => group.hooks.filter(isMurmurWakeHook));
93
- if (ours.length === 1 && isDeepStrictEqual(ours[0], entry))
94
- return { action: 'unchanged', next: settings };
164
+ const drain = path.join(c.repoRoot, 'scripts', 'wake-drain-claude.mjs');
165
+ const installed = drain.replaceAll('\\', '/');
166
+ // An event we cannot read as hook groups is left alone entirely: it is not ours to reshape.
167
+ const others = Object.entries(settings.hooks ?? {}).filter(([event, value]) => event !== 'Stop' && wakeGroups(value));
168
+ const repointed = others.filter(([, value]) => value
169
+ .some(group => group.hooks.some((hook) => isMurmurWakeHook(hook) && wakeScriptOf(hook.command) !== installed)))
170
+ .map(([event]) => String(event));
171
+ if (ours.length === 1 && isDeepStrictEqual(ours[0], entry) && !repointed.length) {
172
+ return { action: 'unchanged', next: settings, repointed };
173
+ }
95
174
  const kept = groups.map(group => ({ ...group, hooks: group.hooks.filter((hook) => !isMurmurWakeHook(hook)) })).filter(group => group.hooks.length);
96
- const next = { ...settings, hooks: { ...settings.hooks, Stop: [...kept, { hooks: [entry] }] } };
97
- return { action: ours.length ? 'replace' : 'add', next };
175
+ const hooks = { ...settings.hooks, Stop: [...kept, { hooks: [entry] }] };
176
+ for (const [event, value] of others) {
177
+ if (!repointed.includes(event))
178
+ continue;
179
+ hooks[event] = value.map(group => ({ ...group, hooks: group.hooks.map((hook) => isMurmurWakeHook(hook) ? { ...hook, command: hook.command.replace(wakeScript, hookPath(drain)) } : hook) }));
180
+ }
181
+ const next = { ...settings, hooks };
182
+ return { action: ours.length || repointed.length ? 'replace' : 'add', next, repointed };
98
183
  }
99
184
  /** Write settings.json the same guarded way as the MCP entry: lock, private backup, atomic rename. */
100
185
  async function configureWakeHook(c, file, before) {
@@ -105,9 +190,9 @@ async function configureWakeHook(c, file, before) {
105
190
  const current = await readClientFile(file);
106
191
  if (!isDeepStrictEqual(current, before))
107
192
  throw new Error('client.plan-stale');
108
- const { action, next } = planWakeHook(c, current.text);
193
+ const { action, next, repointed } = planWakeHook(c, current.text);
109
194
  if (action === 'unchanged')
110
- return { settingsPath: file, action, changed: false, backup: null };
195
+ return { settingsPath: file, action, changed: false, backup: null, repointed };
111
196
  const serialized = JSON.stringify(next, null, 2) + '\n';
112
197
  const backup = current.existed ? `${file}.murmur-backup-${randomUUID()}` : null;
113
198
  if (backup) {
@@ -139,21 +224,42 @@ async function configureWakeHook(c, file, before) {
139
224
  finally {
140
225
  await unlink(temporary).catch(() => { });
141
226
  }
142
- return { settingsPath: file, action, changed: true, backup };
227
+ return { settingsPath: file, action, changed: true, backup, repointed };
143
228
  }
144
229
  finally {
145
230
  await rmdir(lock);
146
231
  }
147
232
  }
148
233
  function desiredEntry(c) {
234
+ const lane = projectLane(c);
149
235
  return { command: c.nodePath, args: [path.join(c.repoRoot, 'packages', 'mcp-server', 'dist', 'src', 'index.js')],
150
- env: { DATA_DIR: c.dataDir, MURMUR_STORE_PATH: c.storePath } };
236
+ env: { DATA_DIR: c.dataDir, MURMUR_DATA_DIR: c.dataDir, MURMUR_STORE_PATH: c.storePath,
237
+ MURMUR_CHANNEL_ROSTER_PATH: path.join(c.dataDir, 'channel-roster.db'),
238
+ ...(lane ? { MURMUR_WAKE_SESSION_KEY: lane } : {}) } };
239
+ }
240
+ function mcpChange(c, original, key) {
241
+ const entry = desiredEntry(c), name = mcpEntryName(c), previous = original[key]?.[name];
242
+ const servers = { ...original[key] }, legacy = servers.murmur;
243
+ // Only migrate the old project registration for this exact profile. Other
244
+ // servers and identities remain intact, and replacement keeps a raw backup.
245
+ const legacyOwned = !!c.clientProjectDir && object(legacy) && object(legacy.env)
246
+ && legacy.env.DATA_DIR === c.dataDir && legacy.env.MURMUR_STORE_PATH === c.storePath
247
+ && typeof legacy.command === 'string' && Array.isArray(legacy.args) && legacy.args.length === 1
248
+ && typeof legacy.args[0] === 'string' && /[/\\]packages[/\\]mcp-server[/\\]dist[/\\]src[/\\]index\.js$/.test(legacy.args[0]);
249
+ if (legacyOwned)
250
+ delete servers.murmur;
251
+ servers[name] = entry;
252
+ const action = legacyOwned ? 'replace' : isDeepStrictEqual(previous, entry) ? 'unchanged' : previous === undefined ? 'add' : 'replace';
253
+ return { entry, name, action, next: { ...original, [key]: servers } };
151
254
  }
152
255
  async function planFor(c, client, current, settings) {
153
256
  const config = await loadConfig(c), { original, key } = clientDocument(client, current.text);
154
- const entry = desiredEntry(c), previous = original[key]?.murmur;
155
- const entryAction = isDeepStrictEqual(previous, entry) ? 'unchanged' : previous === undefined ? 'add' : 'replace';
156
- const wakeHook = settings && { settingsPath: claudeSettingsPath(client.configPath), action: planWakeHook(c, settings.text).action };
257
+ const { entry, name, action: entryAction } = mcpChange(c, original, key);
258
+ const plannedHook = settings && planWakeHook(c, settings.text);
259
+ // The preview names the hand-written events it would repoint, so the person reads them before
260
+ // confirming rather than finding a changed command afterwards (#294).
261
+ const wakeHook = plannedHook && { settingsPath: claudeSettingsPath(client.configPath), action: plannedHook.action,
262
+ ...(plannedHook.repointed.length ? { repointed: plannedHook.repointed } : {}) };
157
263
  // The plan's action speaks for both files: an app that sees 'replace' asks the person and
158
264
  // passes --replace, so a Stop hook written by an earlier version (no timeout, #273) is
159
265
  // upgraded instead of failing with client.wake-hook-conflict while the MCP entry is unchanged.
@@ -161,9 +267,38 @@ async function planFor(c, client, current, settings) {
161
267
  // Bind confirmation to the target, exact bytes and selected identity/runtime.
162
268
  // No existing commands, environment values, auth or config contents leave the engine.
163
269
  const planId = createHash('sha256').update(JSON.stringify([client.id, client.configPath, current,
164
- config.agentId, config.keys.signing.publicKey, config.keys.encryption.publicKey, entry, settings ?? null])).digest('hex');
270
+ config.agentId, config.keys.signing.publicKey, config.keys.encryption.publicKey, name, entry, settings ?? null])).digest('hex');
165
271
  return { schema: 'murmur.client-plan/1', client: client.id, configPath: client.configPath,
166
- agentId: config.agentId, dataDir: c.dataDir, action, planId, configExisted: current.existed, restartRequired: true, ...(wakeHook ? { wakeHook } : {}) };
272
+ agentId: config.agentId, dataDir: c.dataDir, serverName: name, action, planId, configExisted: current.existed, restartRequired: true, ...(wakeHook ? { wakeHook } : {}) };
273
+ }
274
+ /**
275
+ * Read-only: what Claude Code carries for this profile, for doctor's wake stage (#293).
276
+ * `current` means the installed Stop hook is exactly the one this runtime writes; it says
277
+ * nothing about a live session having been woken, which is a separate proof.
278
+ */
279
+ export async function claudeWakeHookState(c, adapter) {
280
+ const client = await selectedClient(c, adapter, 'claude-code').catch(() => null);
281
+ if (!client?.configPath)
282
+ return 'absent';
283
+ const settings = await readClientFile(claudeSettingsPath(client.configPath)).catch(() => null);
284
+ if (!settings?.existed)
285
+ return 'absent';
286
+ let parsed;
287
+ try {
288
+ parsed = settings.text.trim() ? JSON.parse(settings.text) : {};
289
+ }
290
+ catch {
291
+ return 'absent';
292
+ }
293
+ if (!object(parsed) || !object(parsed.hooks) || !wakeGroups(parsed.hooks.Stop))
294
+ return 'absent';
295
+ // One settings file serves every profile on the machine, so only a hook that names this
296
+ // profile's store says anything about this doctor run; another profile's is not ours to judge.
297
+ const ours = parsed.hooks.Stop.flatMap(group => group.hooks.filter(isMurmurWakeHook))
298
+ .filter(hook => hook.command.includes(hookPath(c.storePath)));
299
+ if (!ours.length)
300
+ return 'absent';
301
+ return ours.some(hook => isDeepStrictEqual(hook, desiredWakeHook(c))) ? 'current' : 'outdated';
167
302
  }
168
303
  /** Read-only preview: even a missing parent directory is not created. */
169
304
  export async function previewClientConfiguration(c, adapter, clientId) {
@@ -203,14 +338,13 @@ async function configureMcpEntry(c, client, replace, expectedPlan, settings) {
203
338
  const plan = expectedPlan === undefined ? undefined : await planFor(c, client, current, settings);
204
339
  if (plan && plan.planId !== expectedPlan)
205
340
  throw new Error('client.plan-stale');
206
- const { original, key, parse } = clientDocument(client, text), entry = desiredEntry(c);
207
- const confirmed = plan ? { planId: plan.planId, agentId: plan.agentId, dataDir: plan.dataDir } : {};
208
- const previous = original[key]?.murmur;
209
- if (isDeepStrictEqual(previous, entry))
341
+ const { original, key, parse } = clientDocument(client, text);
342
+ const { name, action, next } = mcpChange(c, original, key);
343
+ const confirmed = { ...(plan ? { planId: plan.planId, agentId: plan.agentId, dataDir: plan.dataDir } : {}), serverName: name };
344
+ if (action === 'unchanged')
210
345
  return { schema: 'murmur.client/1', client: clientId, configPath: file, changed: false, backup: null, restartRequired: true, ...confirmed };
211
- if (previous !== undefined && !replace)
346
+ if (action === 'replace' && !replace)
212
347
  throw new Error('client.murmur-entry-conflict');
213
- const next = { ...original, [key]: { ...original[key], murmur: entry } };
214
348
  const serialized = client.format === 'json' ? JSON.stringify(next, null, 2) + '\n' : TOML.stringify(next);
215
349
  if (!isDeepStrictEqual(parse(serialized), next))
216
350
  throw new Error('client.config-roundtrip-failed');
@@ -19,6 +19,7 @@ export declare function setWakeEnabled(context: ServiceContext, adapter: Platfor
19
19
  }>;
20
20
  /** Explicit read action only; merely displaying status never consumes unread state. */
21
21
  export declare function markInboxRead(context: ServiceContext): Promise<{
22
+ conversations?: object | undefined;
22
23
  schema: string;
23
24
  agentId: string;
24
25
  rowid: number;
@@ -4,8 +4,9 @@ import { constants } from 'node:fs';
4
4
  import { access, mkdir, realpath, rmdir, stat } from 'node:fs/promises';
5
5
  import { loadConfig, readJson, safeError } from './config.js';
6
6
  import { readStatus } from './status.js';
7
- import { assistantRead, wakeColumns } from './message-status.js';
7
+ import { assistantRead, wakeColumns, personalInboxSql } from './message-status.js';
8
8
  import { writeState } from './state.js';
9
+ import { withSetupLock } from './conversations.js';
9
10
  /** Observe the configured directory only; this does not prove a live daemon's log destination. */
10
11
  export async function readLogPath(context, adapter) {
11
12
  const config = await loadConfig(context);
@@ -81,9 +82,20 @@ export async function markInboxRead(context) {
81
82
  const db = new DatabaseSync(context.storePath, { readOnly: true });
82
83
  try {
83
84
  const rowid = Number(db.prepare("SELECT COALESCE(MAX(rowid),0) AS rowid FROM local_messages WHERE direction='inbound'").get().rowid);
84
- const state = { schema: 'murmur.read/1', agentId: config.agentId, rowid };
85
- await writeState(context, path.join(context.dataDir, 'read-state.json'), state);
86
- return state;
85
+ const file = path.join(context.dataDir, 'read-state.json');
86
+ // Per-conversation marks of the desktop app survive a profile-wide mark-read; both writers share the lock.
87
+ return await withSetupLock(context, async () => {
88
+ let conversations;
89
+ try {
90
+ const old = await readJson(file);
91
+ if (old?.schema === 'murmur.read/1' && old.agentId === config.agentId)
92
+ conversations = old.conversations;
93
+ }
94
+ catch { }
95
+ const state = { schema: 'murmur.read/1', agentId: config.agentId, rowid, ...(conversations && typeof conversations === 'object' ? { conversations } : {}) };
96
+ await writeState(context, file, state);
97
+ return state;
98
+ });
87
99
  }
88
100
  finally {
89
101
  db.close();
@@ -108,10 +120,10 @@ export async function readInbox(context, limit = 20) {
108
120
  cursor = state.rowid;
109
121
  }
110
122
  catch { /* Reading messages must not invent or repair read state. */ }
111
- const unread = cursor === null ? null : Number(db.prepare("SELECT COUNT(*) AS n FROM local_messages WHERE direction='inbound' AND rowid>?").get(cursor).n);
123
+ const unread = cursor === null ? null : Number(db.prepare(`SELECT COUNT(*) AS n FROM local_messages WHERE direction='inbound' AND ${personalInboxSql} AND COALESCE(transport,'')<>'desktop-note' AND rowid>?`).get(cursor).n);
112
124
  const rows = db.prepare(`SELECT rowid,conversation_id AS conversationId,msg_id AS msgId,sender,text,
113
125
  created_at AS createdAt,transport,channel_id AS channelId,sender_member_id AS senderMemberId,
114
- addressee_member_id AS addresseeMemberId,${wakeColumns(db)} FROM local_messages WHERE direction='inbound'
126
+ addressee_member_id AS addresseeMemberId,${wakeColumns(db)} FROM local_messages WHERE direction='inbound' AND ${personalInboxSql} AND COALESCE(transport,'')<>'desktop-note'
115
127
  ORDER BY created_at DESC,rowid DESC LIMIT ?`).all(limit);
116
128
  db.exec('COMMIT');
117
129
  return { schema: 'murmur.inbox/1', agentId: config.agentId, readCursor: cursor,
@@ -1,3 +1,4 @@
1
+ import { type NatsTlsOptions } from "@murmurv2/core";
1
2
  import type { ServiceContext } from "./types.js";
2
3
  export interface PeerConfig {
3
4
  subject: string;
@@ -16,6 +17,9 @@ export interface AgentConfig {
16
17
  subject: string;
17
18
  natsUrl: string;
18
19
  natsToken?: string;
20
+ natsUser?: string;
21
+ natsPassword?: string;
22
+ natsTls?: NatsTlsOptions;
19
23
  keys: {
20
24
  encryption: {
21
25
  publicKey: string;
@@ -45,6 +49,10 @@ export declare const validAgentId: (v: unknown) => v is string;
45
49
  export declare function validateConfig(input: unknown): AgentConfig;
46
50
  /** Read-only: status and doctor never chmod, initialize, or migrate user state. */
47
51
  export declare function readJson(file: string): Promise<any>;
52
+ export declare function readJsonSnapshot(file: string): Promise<{
53
+ value: any;
54
+ bytes: Buffer;
55
+ }>;
48
56
  export declare function loadConfig(context: ServiceContext): Promise<AgentConfig>;
49
57
  export declare function safeError(error: unknown): string;
50
58
  /** CLI presentation only; JSON consumers retain the stable, secret-free codes. */
@@ -1,3 +1,6 @@
1
+ import { ErrorCode } from "nats";
2
+ import path from "node:path";
3
+ import { buildNatsTransportOptions } from "@murmurv2/core";
1
4
  import { constants } from "node:fs";
2
5
  import { open } from "node:fs/promises";
3
6
  const object = (v) => !!v && typeof v === "object" && !Array.isArray(v);
@@ -6,15 +9,21 @@ const validKey = (v) => typeof v === "string" && Buffer.from(v, "base64").length
6
9
  export function validateConfig(input) {
7
10
  if (!object(input) || !validAgentId(input.agentId) || input.subject !== `msg.${input.agentId}`)
8
11
  throw new Error("config.identity-invalid");
9
- let url;
10
- try {
11
- url = new URL(input.natsUrl);
12
- }
13
- catch {
14
- throw new Error("config.broker-url-invalid");
15
- }
16
- if (!["nats:", "tls:"].includes(url.protocol) || url.username || url.password || url.search || url.hash)
12
+ if (typeof input.natsUrl !== "string")
17
13
  throw new Error("config.broker-url-invalid");
14
+ const tls = input.natsTls;
15
+ if (tls !== undefined && !object(tls))
16
+ throw new Error("config.broker-tls-invalid");
17
+ for (const value of [input.natsToken, input.natsUser, input.natsPassword])
18
+ if (value !== undefined && (typeof value !== "string" || !value || /[\r\n\0]/.test(value)))
19
+ throw new Error("config.broker-auth-invalid");
20
+ if (object(tls))
21
+ for (const key of ["caFile", "certFile", "keyFile"]) {
22
+ const value = tls[key];
23
+ if (value !== undefined && (typeof value !== "string" || !path.isAbsolute(value)))
24
+ throw new Error("config.broker-tls-file-invalid");
25
+ }
26
+ buildNatsTransportOptions({ url: input.natsUrl, token: input.natsToken, user: input.natsUser, password: input.natsPassword, tls: tls });
18
27
  for (const kind of ["encryption", "signing"]) {
19
28
  if (!validKey(input.keys?.[kind]?.publicKey) || !validKey(input.keys?.[kind]?.privateKey))
20
29
  throw new Error("config.keys-invalid");
@@ -30,6 +39,9 @@ export function validateConfig(input) {
30
39
  }
31
40
  /** Read-only: status and doctor never chmod, initialize, or migrate user state. */
32
41
  export async function readJson(file) {
42
+ return (await readJsonSnapshot(file)).value;
43
+ }
44
+ export async function readJsonSnapshot(file) {
33
45
  const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
34
46
  try {
35
47
  const stat = await handle.stat();
@@ -37,7 +49,19 @@ export async function readJson(file) {
37
49
  throw new Error("config.file-invalid");
38
50
  if (typeof process.getuid === "function" && stat.uid !== process.getuid())
39
51
  throw new Error("config.owner-mismatch");
40
- return JSON.parse(await handle.readFile("utf8"));
52
+ const bytes = Buffer.alloc(4 * 1024 * 1024 + 1);
53
+ let offset = 0;
54
+ while (offset < bytes.length) {
55
+ const result = await handle.read(bytes, offset, bytes.length - offset, null);
56
+ if (result.bytesRead === 0)
57
+ break;
58
+ offset += result.bytesRead;
59
+ }
60
+ const after = await handle.stat();
61
+ if (offset > 4 * 1024 * 1024 || after.dev !== stat.dev || after.ino !== stat.ino || after.size !== stat.size || offset !== stat.size)
62
+ throw new Error("config.file-changed");
63
+ const exact = bytes.subarray(0, offset);
64
+ return { value: JSON.parse(exact.toString("utf8")), bytes: Buffer.from(exact) };
41
65
  }
42
66
  finally {
43
67
  await handle.close();
@@ -58,7 +82,11 @@ export function safeError(error) {
58
82
  if (value === "database is locked")
59
83
  return value;
60
84
  // Neither command output nor transport errors may leak tokens/message content.
61
- if (/^[a-zA-Z][a-zA-Z0-9_.:-]{0,150}$/.test(value))
85
+ const natsPolicy = new Set(["nats-url-invalid", "nats-url-scheme-invalid", "nats-url-embedded-credentials-rejected", "nats-url-components-invalid",
86
+ "nats-auth-methods-conflict", "nats-user-password-pair-required", "nats-plaintext-non-loopback-rejected", "nats-tls-options-require-tls-url",
87
+ "nats-tls-server-name-required-for-ip", "nats-tls-server-name-invalid", "nats-tls-option-unsupported", "nats-tls-file-invalid",
88
+ "nats-tls-cert-key-pair-required", "nats-tls-handshake-first-invalid"]);
89
+ if (new Set(Object.values(ErrorCode)).has(value) || natsPolicy.has(value) || /^(?!nats-)[a-z][a-z0-9]*(?:[.-][a-z0-9_-]+)+(?::[a-zA-Z0-9_.-]+)?$/.test(value))
62
90
  return value;
63
91
  // System error messages embed paths; their errno code and syscall alone are safe and actionable
64
92
  // (an unreadable invite file must not surface as a bare operation-failed).
@@ -78,6 +106,26 @@ export function humanError(error) {
78
106
  return 'Enter a valid public Server address with --broker, such as nats://server.example.com:4222. Do not include an access key in the address.';
79
107
  }
80
108
  const messages = {
109
+ 'client.inherited-mcp-entry-conflict': 'A global Claude connection already uses this folder connection name. Review that registration before connecting; no settings were changed.',
110
+ 'migration.profile-usage-unavailable': 'This account cannot prove that the selected profile is unused. Stop its clients and obtain a complete native inspection; no configuration was changed.',
111
+ 'migration.service-must-be-stopped': 'Stop the selected service before applying a broker migration. The migration command never stops services.',
112
+ 'migration.profile-in-use': 'The selected profile is still in use. Close its clients before applying a broker migration.',
113
+ 'broker-input.file-not-private': 'Credential input files must be private to your account.',
114
+ 'nats-user-password-pair-required': 'Supply both --user-file and --password-file for user/password authentication.',
115
+ 'client.inherited-wake-hook-conflict': 'A global or parent-folder Murmur hook already wakes chats. Review and remove that older hook before connecting a dedicated folder; no settings were changed.',
116
+ 'client.project-directory-required': 'Create and select a dedicated folder for your Murmur conversation, then try again.',
117
+ 'client.project-must-be-dedicated': 'Choose a dedicated Murmur folder, not the assistant configuration home.',
118
+ 'client.project-only-for-claude-code': 'The dedicated folder connection is available for Claude Code, including the Code tab in Claude.',
119
+ 'installation.descriptor-missing': 'No installation is selected. Initialize with --data-dir ABSOLUTE --select, or select an existing profile with installation select --data-dir ABSOLUTE.',
120
+ 'installation.profile-missing': 'The selected profile is missing. Select its existing absolute folder; Murmur will not create a replacement identity.',
121
+ 'installation.identity-changed': 'The selected folder now contains a different Identity. Inspect it and explicitly select the correct installation.',
122
+ 'installation.selection-conflict': 'Another installation is selected. Use --data-dir for this command, or installation select --replace to change the registered choice.',
123
+ 'installation.ambiguous': 'The installation descriptor names multiple profiles. Explicitly select one profile; Murmur will not guess.',
124
+ 'installation.store-conflict': 'A store environment variable points outside the selected profile. Remove the conflicting override or select that profile explicitly.',
125
+ 'backups.plan-stale': 'The backup list or configuration changed, or the preview expired. Run backups preview again before cleanup.',
126
+ 'backups.permissions-invalid': 'A backup is not private to this account. Inspect its owner and permissions; cleanup did not repair them.',
127
+ 'backups.config-invalid': 'The current configuration or a backup is damaged. Restore or inspect it before deleting recovery copies.',
128
+ 'backups.keep-file-invalid': 'Choose an exact backup path from the preview for --keep-file.',
81
129
  'accepted-turn-unobservable': 'The Assistant accepted this message, but its outcome cannot be checked. Inspect its session before dismissing the alert; do not send the instruction again.',
82
130
  'wake.selection-invalid': 'Choose a message and the expected Identity, then try again.',
83
131
  'wake.identity-changed': 'The selected Identity has changed. Check its name before dismissing this alert.',
@@ -0,0 +1,143 @@
1
+ import type { PlatformAdapter } from './types.js';
2
+ export declare function connect(adapter: PlatformAdapter, options: {
3
+ agentId?: string;
4
+ dataDir?: string;
5
+ inviteFile?: string;
6
+ invitation?: string;
7
+ inviteArgument?: string;
8
+ replyOut?: string;
9
+ client?: string;
10
+ noService?: boolean;
11
+ copyReply?: boolean;
12
+ }): Promise<{
13
+ schema: string;
14
+ dataDir: string;
15
+ service: {
16
+ ok: null;
17
+ state: string;
18
+ error: null;
19
+ hint: null;
20
+ } | {
21
+ ok: boolean;
22
+ state: "running";
23
+ error: null;
24
+ hint: null;
25
+ } | {
26
+ ok: boolean;
27
+ state: "running" | "running-unmanaged" | "stopped" | "failed" | "unknown";
28
+ error: string;
29
+ hint: string;
30
+ };
31
+ clients: {
32
+ state: string;
33
+ results: never[];
34
+ hint: string;
35
+ } | {
36
+ state: string;
37
+ results: ({
38
+ state: string;
39
+ error: null;
40
+ hint: null;
41
+ serverName: string;
42
+ planId?: string | undefined;
43
+ agentId?: string | undefined;
44
+ dataDir?: string | undefined;
45
+ schema: string;
46
+ client: "claude-code" | "claude-desktop" | "codex-cli" | "codex-desktop" | "cursor" | "gemini";
47
+ configPath: string;
48
+ changed: boolean;
49
+ backup: null;
50
+ restartRequired: boolean;
51
+ } | {
52
+ state: string;
53
+ error: null;
54
+ hint: null;
55
+ restartRequired: boolean;
56
+ instruction: string;
57
+ serverName: string;
58
+ planId?: string | undefined;
59
+ agentId?: string | undefined;
60
+ dataDir?: string | undefined;
61
+ schema: string;
62
+ client: "claude-code" | "claude-desktop" | "codex-cli" | "codex-desktop" | "cursor" | "gemini";
63
+ configPath: string;
64
+ changed: boolean;
65
+ backup: string | null;
66
+ } | {
67
+ state: string;
68
+ error: null;
69
+ hint: null;
70
+ changed: boolean;
71
+ wakeHook: {
72
+ settingsPath: string;
73
+ action: "unchanged";
74
+ changed: boolean;
75
+ backup: null;
76
+ repointed: string[];
77
+ } | {
78
+ settingsPath: string;
79
+ action: "replace" | "add";
80
+ changed: boolean;
81
+ backup: string | null;
82
+ repointed: string[];
83
+ };
84
+ serverName: string;
85
+ planId?: string | undefined;
86
+ agentId?: string | undefined;
87
+ dataDir?: string | undefined;
88
+ schema: string;
89
+ client: "claude-code" | "claude-desktop" | "codex-cli" | "codex-desktop" | "cursor" | "gemini";
90
+ configPath: string;
91
+ backup: null;
92
+ restartRequired: boolean;
93
+ } | {
94
+ state: string;
95
+ error: null;
96
+ hint: null;
97
+ changed: boolean;
98
+ wakeHook: {
99
+ settingsPath: string;
100
+ action: "unchanged";
101
+ changed: boolean;
102
+ backup: null;
103
+ repointed: string[];
104
+ } | {
105
+ settingsPath: string;
106
+ action: "replace" | "add";
107
+ changed: boolean;
108
+ backup: string | null;
109
+ repointed: string[];
110
+ };
111
+ restartRequired: boolean;
112
+ instruction: string;
113
+ serverName: string;
114
+ planId?: string | undefined;
115
+ agentId?: string | undefined;
116
+ dataDir?: string | undefined;
117
+ schema: string;
118
+ client: "claude-code" | "claude-desktop" | "codex-cli" | "codex-desktop" | "cursor" | "gemini";
119
+ configPath: string;
120
+ backup: string | null;
121
+ } | {
122
+ client: "claude-code" | "claude-desktop" | "codex-cli" | "codex-desktop" | "cursor" | "gemini";
123
+ state: string;
124
+ error: string;
125
+ hint: string;
126
+ })[];
127
+ hint: null;
128
+ };
129
+ copiedToClipboard: boolean;
130
+ agentId: string;
131
+ peerId: any;
132
+ paired: null;
133
+ replyFile: string | null;
134
+ reply: string;
135
+ backup: null;
136
+ restartRequired: boolean;
137
+ contactsReload: {
138
+ mechanism: string;
139
+ state: string;
140
+ };
141
+ serviceName: string;
142
+ }>;
143
+ export declare function renderConnect(result: Awaited<ReturnType<typeof connect>>): string;