@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
@@ -1,6 +1,6 @@
1
1
  import type { PlatformAdapter, ServiceContext } from './types.js';
2
2
  /** Observe the configured directory only; this does not prove a live daemon's log destination. */
3
- export declare function readLogPath(context: ServiceContext): Promise<{
3
+ export declare function readLogPath(context: ServiceContext, adapter?: PlatformAdapter): Promise<{
4
4
  schema: string;
5
5
  agentId: string;
6
6
  dataDir: string;
@@ -30,6 +30,8 @@ export declare function readInbox(context: ServiceContext, limit?: number): Prom
30
30
  readCursor: number | null;
31
31
  unread: number | null;
32
32
  messages: {
33
+ assistantRead: boolean | null;
34
+ wake_error: string | null;
33
35
  unread: boolean | null;
34
36
  }[];
35
37
  }>;
@@ -2,12 +2,17 @@ import path from 'node:path';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { constants } from 'node:fs';
4
4
  import { access, mkdir, realpath, rmdir, stat } from 'node:fs/promises';
5
- import { loadConfig, readJson } from './config.js';
5
+ import { loadConfig, readJson, safeError } from './config.js';
6
6
  import { readStatus } from './status.js';
7
+ import { assistantRead, wakeColumns, personalInboxSql } from './message-status.js';
7
8
  import { writeState } from './state.js';
8
9
  /** Observe the configured directory only; this does not prove a live daemon's log destination. */
9
- export async function readLogPath(context) {
10
+ export async function readLogPath(context, adapter) {
10
11
  const config = await loadConfig(context);
12
+ if (adapter?.logDirectory) {
13
+ return { schema: 'murmur.logs/1', agentId: config.agentId, dataDir: context.dataDir,
14
+ serviceName: context.serviceName, logDir: await adapter.logDirectory(context), source: 'native' };
15
+ }
11
16
  try {
12
17
  const dataDir = await realpath(context.dataDir);
13
18
  const logDir = await realpath(context.logDir);
@@ -53,8 +58,12 @@ export async function setWakeEnabled(context, adapter, enabled, apply = false) {
53
58
  let applyError = null;
54
59
  if (apply) {
55
60
  try {
56
- await adapter.stop(context);
57
- await adapter.start(context);
61
+ if ((await readStatus({ context, adapter })).service.state === 'running-unmanaged')
62
+ applyError = 'service.running-unmanaged';
63
+ else {
64
+ await adapter.stop(context);
65
+ await adapter.start(context);
66
+ }
58
67
  }
59
68
  catch {
60
69
  applyError = 'wake.service-apply-failed';
@@ -99,15 +108,17 @@ export async function readInbox(context, limit = 20) {
99
108
  cursor = state.rowid;
100
109
  }
101
110
  catch { /* Reading messages must not invent or repair read state. */ }
102
- const unread = cursor === null ? null : Number(db.prepare("SELECT COUNT(*) AS n FROM local_messages WHERE direction='inbound' AND rowid>?").get(cursor).n);
111
+ const unread = cursor === null ? null : Number(db.prepare(`SELECT COUNT(*) AS n FROM local_messages WHERE direction='inbound' AND ${personalInboxSql} AND rowid>?`).get(cursor).n);
103
112
  const rows = db.prepare(`SELECT rowid,conversation_id AS conversationId,msg_id AS msgId,sender,text,
104
113
  created_at AS createdAt,transport,channel_id AS channelId,sender_member_id AS senderMemberId,
105
- addressee_member_id AS addresseeMemberId FROM local_messages WHERE direction='inbound'
114
+ addressee_member_id AS addresseeMemberId,${wakeColumns(db)} FROM local_messages WHERE direction='inbound' AND ${personalInboxSql}
106
115
  ORDER BY created_at DESC,rowid DESC LIMIT ?`).all(limit);
107
116
  db.exec('COMMIT');
108
117
  return { schema: 'murmur.inbox/1', agentId: config.agentId, readCursor: cursor,
109
118
  unread,
110
- messages: rows.map(({ rowid, ...row }) => ({ ...row, unread: cursor === null ? null : Number(rowid) > cursor })) };
119
+ messages: rows.map(({ rowid, ...row }) => ({ ...row, assistantRead: assistantRead(row.wake_status),
120
+ wake_error: row.wake_error ? safeError(row.wake_error) : null,
121
+ unread: cursor === null ? null : Number(rowid) > cursor })) };
111
122
  }
112
123
  finally {
113
124
  db.close();
@@ -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,5 +49,11 @@ 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;
58
+ /** CLI presentation only; JSON consumers retain the stable, secret-free codes. */
59
+ export declare function humanError(error: unknown): string;
@@ -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).
@@ -68,3 +96,84 @@ export function safeError(error) {
68
96
  }
69
97
  return "operation-failed";
70
98
  }
99
+ /** CLI presentation only; JSON consumers retain the stable, secret-free codes. */
100
+ export function humanError(error) {
101
+ const code = safeError(error);
102
+ if (code === 'onboarding.invite-public-server-required') {
103
+ return 'This Invitation needs a public Server address. Ask for its public address and pass it with --broker.';
104
+ }
105
+ if (code === 'onboarding.invite-server-address-invalid') {
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.';
107
+ }
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.',
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.',
130
+ 'wake.selection-invalid': 'Choose a message and the expected Identity, then try again.',
131
+ 'wake.identity-changed': 'The selected Identity has changed. Check its name before dismissing this alert.',
132
+ 'wake.dismiss-not-eligible': 'This alert cannot be dismissed here. Check the message status and the selected Identity.',
133
+ 'wake.store-invalid': 'Choose the original message history owned by your account, then try again.',
134
+ 'onboarding.input-required': 'Provide the Invitation or Reply using standard input or choose its saved file.',
135
+ 'onboarding.input-conflict': 'Choose one source for the Invitation or Reply: standard input or a saved file.',
136
+ 'onboarding.stdin-required': 'Send the Invitation or Reply through standard input, or choose its saved file.',
137
+ 'onboarding.input-too-large': 'This Invitation or Reply is too long. Ask your colleague to send a new one.',
138
+ 'onboarding.file-invalid': 'This file cannot be used. Choose the saved Invitation or Reply your colleague sent.',
139
+ 'onboarding.invalid-blob': 'This Invitation or Reply is incomplete or damaged. Copy the whole line your colleague sent.',
140
+ 'onboarding.invalid-peer': 'This is not the expected Invitation or Reply. Ask your colleague to send the correct one.',
141
+ 'onboarding.invalid-peer-key': 'The Contact details are damaged. Ask your colleague for a new Invitation or Reply.',
142
+ 'onboarding.invalid-broker': 'The Invitation has invalid Server details. Ask your colleague for a new Invitation.',
143
+ 'onboarding.self-peer': 'This is your own Identity. Ask your colleague to send their Reply.',
144
+ 'onboarding.peer-key-conflict': 'This Contact has different Identity details. Verify the change with your colleague before replacing the Contact.',
145
+ 'onboarding.existing-profile-conflict': 'Another Identity already uses this folder. Choose that Identity or an empty folder.',
146
+ 'onboarding.file-must-be-absolute': 'Choose the input file using its full path.',
147
+ 'onboarding.output-must-be-absolute': 'Choose the destination file using its full path.',
148
+ 'onboarding.output-parent-required': 'Choose an existing folder to save the Invitation or Reply.',
149
+ 'onboarding.output-inside-profile': 'Choose a destination outside the folder containing your Identity settings.',
150
+ 'onboarding.token-file-invalid': 'The Server access key must be one line. Ask for the correct key and save it again.',
151
+ 'onboarding.private-acl-failed': 'The file could not be protected. Choose a private folder you can write to and try again.',
152
+ 'onboarding.user-sid-unavailable': 'Your account could not be verified. Sign in again and retry.',
153
+ 'onboarding.poison-reset-failed': 'The Contact was saved, but waiting messages could not be prepared. Check the connection and retry.',
154
+ 'config.missing': 'Set up your Identity or choose its existing folder, then try again.',
155
+ 'config.identity-invalid': 'Choose an Identity name using letters, numbers, hyphens or underscores.',
156
+ 'config.broker-url-invalid': 'Enter a valid Server address supplied by your colleague and try again.',
157
+ 'service.running-unmanaged': 'This Service is running outside this app. Manage it where it was started.',
158
+ 'service.previous-installation': 'A Service from a previous Murmur version uses this name. Replace it with: service install --replace-previous.',
159
+ 'service.foreign-image': 'Another program already uses this Service name; Murmur will not change or remove it.',
160
+ 'cli.unknown-command': 'This command is not available. Run with --help to choose an action.',
161
+ 'cli.unknown-option': 'This option is not available. Run with --help to check the command.',
162
+ 'cli.invalid-arguments': 'The command is incomplete. Run with --help to check the required options.',
163
+ };
164
+ if (Object.hasOwn(messages, code))
165
+ return messages[code];
166
+ if (/^onboarding\.(invite|reply|token)-file-not-found$/.test(code))
167
+ return 'The selected file was not found. Choose the saved Invitation, Reply or Server access key again.';
168
+ if (/^onboarding\.(invite|reply|token)-file-access-denied$/.test(code))
169
+ return 'The selected file cannot be opened. Choose a file your account can read.';
170
+ if (code.startsWith('cli.required-option:'))
171
+ return 'A required option is missing. Run with --help to complete the command.';
172
+ if (code.startsWith('system.EEXIST'))
173
+ return 'The destination already exists or another setup is in progress. Choose a new destination or wait for setup to finish.';
174
+ if (/^system\.(EACCES|EPERM)/.test(code))
175
+ return 'Access was denied. Choose a folder your account can read and write.';
176
+ if (code === 'database is locked')
177
+ return 'Your messages are busy with another action. Wait a moment and try again.';
178
+ return 'This action could not be completed. Check your settings and use --json to share diagnostics with your support contact.';
179
+ }
@@ -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";
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";
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";
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";
119
+ configPath: string;
120
+ backup: string | null;
121
+ } | {
122
+ client: "claude-code" | "claude-desktop" | "codex-cli" | "codex-desktop";
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;
@@ -0,0 +1,126 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { hostname, userInfo } from 'node:os';
3
+ import { configureClient } from './clients.js';
4
+ import { safeError, validAgentId } from './config.js';
5
+ import { join } from './onboarding.js';
6
+ import { defaultProfileDir, resolveContext } from './paths.js';
7
+ import { readStatus } from './status.js';
8
+ const automaticClients = new Set(['claude-code', 'codex-cli', 'codex-desktop']);
9
+ const clientIds = new Map([
10
+ ['claude-code', 'claude-code'], ['claude-desktop', 'claude-desktop'],
11
+ ['codex-cli', 'codex-cli'], ['codex', 'codex-desktop'],
12
+ ]);
13
+ function defaultAgentId() {
14
+ let username = '';
15
+ try {
16
+ username = userInfo().username;
17
+ }
18
+ catch { /* OS account lookup is optional. */ }
19
+ const slug = (value) => value.toLowerCase().replace(/[^a-z0-9]+/g, '-')
20
+ .replace(/^-+/, '').slice(0, 122).replace(/-+$/, '');
21
+ return 'agent-' + (slug(username) || slug(hostname()) || 'peer');
22
+ }
23
+ async function startService(context, adapter, skip) {
24
+ if (skip)
25
+ return { ok: null, state: 'skipped', error: null, hint: null };
26
+ const status = async () => (await readStatus({ context, adapter })).service.state;
27
+ let state = await status();
28
+ let phase = 'install';
29
+ try {
30
+ if (state === 'running-unmanaged')
31
+ throw new Error('service.running-unmanaged');
32
+ if (state !== 'running') {
33
+ await adapter.install(context);
34
+ phase = 'start';
35
+ await adapter.start(context);
36
+ state = await status();
37
+ if (state !== 'running') {
38
+ phase = 'verify';
39
+ throw new Error('service.running-unverified');
40
+ }
41
+ }
42
+ return { ok: true, state, error: null, hint: null };
43
+ }
44
+ catch (error) {
45
+ const hint = state === 'running-unmanaged'
46
+ ? 'This profile is already running outside the service manager. Stop that instance before installing a service.'
47
+ : phase === 'verify'
48
+ ? 'Run murmur doctor for this profile to check whether the service started.'
49
+ : `Run murmur service ${phase} --data-dir with the profile path shown above after checking your service manager.`
50
+ + (adapter.manager === 'windows-service' ? ' On Windows, run that service command as Administrator.' : '');
51
+ return { ok: false, state: await status(), error: safeError(error), hint };
52
+ }
53
+ }
54
+ async function wireClients(context, adapter, selection) {
55
+ if (selection === 'none')
56
+ return { state: 'skipped', results: [], hint: null };
57
+ let ids;
58
+ try {
59
+ ids = selection === 'auto'
60
+ ? [...new Set((await adapter.detectClients(context)).filter(row => row.installed && automaticClients.has(row.id)).map(row => row.id))]
61
+ : [clientIds.get(selection)];
62
+ }
63
+ catch {
64
+ return { state: 'failed', results: [], hint: 'Client detection failed. Run murmur clients detect for this profile to check again.' };
65
+ }
66
+ if (!ids.length)
67
+ return { state: 'not-detected', results: [], hint: 'No supported AI client was detected. Install one, then rerun connect or run murmur clients detect.' };
68
+ const results = [];
69
+ for (const client of ids) {
70
+ try {
71
+ const result = await configureClient(context, adapter, client);
72
+ results.push({ ...result, state: 'configured', error: null, hint: null });
73
+ }
74
+ catch (error) {
75
+ const code = safeError(error);
76
+ const hint = ['client.murmur-entry-conflict', 'client.wake-hook-conflict'].includes(code)
77
+ ? `Existing settings were kept. Review them, then use murmur clients configure --client ${client} --replace with this profile if you want to replace them.`
78
+ : 'Check whether the client is installed and its settings are accessible, then run murmur clients detect for this profile.';
79
+ results.push({ client, state: 'failed', error: code, hint });
80
+ }
81
+ }
82
+ return { state: results.every(row => row.state === 'configured') ? 'configured' : 'needs-attention', results, hint: null };
83
+ }
84
+ async function copyReply(reply) {
85
+ const tools = process.platform === 'darwin' ? [['/usr/bin/pbcopy', []]]
86
+ : process.platform === 'win32' ? [['clip.exe', []]]
87
+ : process.platform === 'linux' ? [['wl-copy', []], ['xclip', ['-selection', 'clipboard']]] : [];
88
+ for (const [command, args] of tools) {
89
+ const copied = await new Promise((resolve) => {
90
+ const child = execFile(command, args, { timeout: 3000, windowsHide: true }, error => resolve(!error));
91
+ child.stdin?.on('error', () => { });
92
+ child.stdin?.end(reply);
93
+ });
94
+ if (copied)
95
+ return true;
96
+ }
97
+ return false;
98
+ }
99
+ export async function connect(adapter, options) {
100
+ const selection = options.client ?? 'auto';
101
+ if (!['auto', 'none'].includes(selection) && !clientIds.has(selection))
102
+ throw new Error('connect.invalid-client');
103
+ const agentId = options.agentId ?? defaultAgentId();
104
+ if (!validAgentId(agentId))
105
+ throw new Error('config.identity-invalid');
106
+ const context = resolveContext({ dataDir: options.dataDir ?? defaultProfileDir(agentId) });
107
+ const joined = await join(context, { ...options, agentId, connect: true });
108
+ const service = await startService(context, adapter, !!options.noService);
109
+ const clients = await wireClients(context, adapter, selection);
110
+ const copiedToClipboard = !!options.copyReply && await copyReply(joined.reply);
111
+ return { ...joined, schema: 'murmur.connect/1', dataDir: context.dataDir, service, clients, copiedToClipboard };
112
+ }
113
+ export function renderConnect(result) {
114
+ return [
115
+ `Murmur identity: ${result.agentId} (${result.dataDir})`,
116
+ `Inviter: ${result.peerId} (connection not yet verified)`,
117
+ `Service: ${result.service.state}${result.service.error ? ` (${result.service.error})` : ''}`,
118
+ result.service.hint,
119
+ `AI clients: ${result.clients.state}`,
120
+ result.clients.hint,
121
+ ...result.clients.results.map(row => ` ${row.client}: ${row.state}${row.hint ? `. ${row.hint}` : ''}`),
122
+ `Reply saved to ${result.replyFile}${result.copiedToClipboard ? ' and copied to the clipboard' : ''}.`,
123
+ '', result.reply, '',
124
+ 'Send this MURMUR-REPLY line back to the person who invited you. Restart your AI client to see murmur tools.',
125
+ ].filter(line => line !== null).join('\n');
126
+ }
@@ -7,6 +7,27 @@ export interface DoctorOptions {
7
7
  peer?: string;
8
8
  timeoutMs?: number;
9
9
  }
10
+ export declare function evaluatePeers(list: Array<{
11
+ agentId: string;
12
+ paired: boolean | null;
13
+ }>, peer?: string): {
14
+ state?: string;
15
+ reason?: string;
16
+ detail: string;
17
+ fixHint?: string;
18
+ };
19
+ /**
20
+ * How a silent probe reads. A daemon older than 2.11.0 never answers one, so silence alone is
21
+ * not the same finding as an unreachable peer (#292). A signed message this store persisted
22
+ * from that peer recently proves the transport in one direction; without that evidence the
23
+ * timeout stays a failure, and null tells the caller to let it through as one.
24
+ */
25
+ export declare function evaluateSilentPeer(peer: string, lastInboundAt: string | null, now?: number): {
26
+ state: string;
27
+ reason: string;
28
+ detail: string;
29
+ fixHint: string;
30
+ } | null;
10
31
  export declare function probeRoundtrip(c: ServiceContext, config: AgentConfig, peerId: string, connection: NatsConnection, timeoutMs: number): Promise<{
11
32
  msgId: string;
12
33
  replyMsgId: string;
@@ -17,6 +38,27 @@ export declare function runDoctor({ context, adapter, peer, timeoutMs }: DoctorO
17
38
  schema: string;
18
39
  generatedAt: string;
19
40
  agentId: string | null;
41
+ peerCheck: {
42
+ peerId: string;
43
+ state: "connected" | "failed" | "not-checked";
44
+ lastExchangeAt: string | null;
45
+ requestMsgId: string | null;
46
+ replyMsgId: string | null;
47
+ reason: string | null;
48
+ } | null;
49
+ wakeFault: {
50
+ reason: string;
51
+ fixHint: string;
52
+ } | null;
53
+ wakeReaders: {
54
+ active: number | null;
55
+ measuredAt: string;
56
+ unknownReason: string;
57
+ } | {
58
+ active: number;
59
+ measuredAt: string;
60
+ unknownReason: null;
61
+ };
20
62
  stages: Record<string, unknown>[];
21
63
  summary: {
22
64
  worst: string;