@remcp/remcp 0.2.44 → 0.2.46

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 (2) hide show
  1. package/package.json +1 -1
  2. package/src/cli/service.mjs +88 -17
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remcp/remcp",
3
- "version": "0.2.44",
3
+ "version": "0.2.46",
4
4
  "description": "ReMCP device client: pair a computer with ReMCP and run the outbound-only agent that hosts the local MCP runtime.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -8,7 +8,7 @@ import { spawnSync } from 'node:child_process';
8
8
  import { PACKAGE_NAME, VERSION } from '../version.mjs';
9
9
 
10
10
  import { saveConfig } from './config.mjs';
11
- import { home, linuxServiceFile, macLogFile, macServiceFile, macServiceLabel, npm, windowsTaskName } from './env.mjs';
11
+ import { configDir, home, linuxServiceFile, macLogFile, macServiceFile, macServiceLabel, npm, windowsTaskName } from './env.mjs';
12
12
  import { output, run } from './shell.mjs';
13
13
 
14
14
  export function servicePlatform() {
@@ -49,21 +49,90 @@ export function macLaunchDomain() {
49
49
  return `gui/${process.getuid()}`;
50
50
  }
51
51
 
52
- export function installMacService(cliPath = globalCliPath()) {
53
- const domain = macLaunchDomain();
54
- const target = `${domain}/${macServiceLabel}`;
52
+ function shellQuote(value) {
53
+ return `'${String(value).replaceAll("'", "'\\''")}'`;
54
+ }
55
+
56
+ function macServicePlist(cliPath) {
55
57
  // launchd wants an absolute path; a symlinked prefix that npm has not materialised yet (or a path
56
58
  // that is about to be replaced by the next install) must not abort the repair — a stale plist is
57
59
  // exactly the loop this function exists to break.
58
60
  const cliScript = fs.existsSync(cliPath) ? fs.realpathSync(cliPath) : path.resolve(cliPath);
61
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict>\n<key>Label</key><string>${macServiceLabel}</string>\n<key>ProgramArguments</key><array><string>${xmlEscape(process.execPath)}</string><string>${xmlEscape(cliScript)}</string><string>start</string></array>\n<key>RunAtLoad</key><true/><key>KeepAlive</key><true/>\n<key>ProcessType</key><string>Background</string>\n<key>StandardOutPath</key><string>${xmlEscape(macLogFile)}</string>\n<key>StandardErrorPath</key><string>${xmlEscape(macLogFile)}</string>\n</dict></plist>\n`;
62
+ }
63
+
64
+ function macJobLoaded(target) {
65
+ return spawnSync('launchctl', ['print', target], { stdio: 'ignore' }).status === 0;
66
+ }
67
+
68
+ function submitMacHelper(kind, lines) {
69
+ fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
70
+ const nonce = `${process.pid}.${Date.now()}`;
71
+ const helperFile = path.join(configDir, `launchd-${kind}-${nonce}.sh`);
72
+ const helperLabel = `${macServiceLabel}.${kind}.${nonce}`;
73
+ const script = [
74
+ '#!/bin/sh',
75
+ 'sleep 1',
76
+ 'status=0',
77
+ ...lines.map(line => `${line} || status=$?`),
78
+ `if [ "$status" -ne 0 ]; then echo "ReMCP launchd ${kind} helper failed with status $status" >> ${shellQuote(macLogFile)}; fi`,
79
+ `rm -f ${shellQuote(helperFile)}`,
80
+ `launchctl remove ${shellQuote(helperLabel)} >/dev/null 2>&1 || true`,
81
+ 'exit 0',
82
+ '',
83
+ ].join('\n');
84
+ fs.writeFileSync(helperFile, script, { mode: 0o700 });
85
+ fs.chmodSync(helperFile, 0o700);
86
+ run('launchctl', ['submit', '-l', helperLabel, '--', '/bin/sh', helperFile]);
87
+ return helperLabel;
88
+ }
89
+
90
+ function scheduleMacServiceReload(domain, target) {
91
+ return submitMacHelper('reload', [
92
+ `launchctl bootout ${shellQuote(target)} >/dev/null 2>&1 || true`,
93
+ `launchctl bootstrap ${shellQuote(domain)} ${shellQuote(macServiceFile)}`,
94
+ `launchctl enable ${shellQuote(target)}`,
95
+ `launchctl kickstart -k ${shellQuote(target)}`,
96
+ ]);
97
+ }
98
+
99
+ function scheduleMacServiceRestart(target) {
100
+ return submitMacHelper('restart', [
101
+ `launchctl kickstart -k ${shellQuote(target)}`,
102
+ ]);
103
+ }
104
+
105
+ export function installMacService(cliPath = globalCliPath(), { restart = true } = {}) {
106
+ const domain = macLaunchDomain();
107
+ const target = `${domain}/${macServiceLabel}`;
108
+ const plist = macServicePlist(cliPath);
109
+ let previous = '';
110
+ try { previous = fs.readFileSync(macServiceFile, 'utf8'); } catch {}
111
+ const loaded = macJobLoaded(target);
112
+
59
113
  fs.mkdirSync(path.dirname(macServiceFile), { recursive: true });
60
114
  fs.mkdirSync(path.dirname(macLogFile), { recursive: true });
61
- const plist = `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict>\n<key>Label</key><string>${macServiceLabel}</string>\n<key>ProgramArguments</key><array><string>${xmlEscape(process.execPath)}</string><string>${xmlEscape(cliScript)}</string><string>start</string></array>\n<key>RunAtLoad</key><true/><key>KeepAlive</key><true/>\n<key>ProcessType</key><string>Background</string>\n<key>StandardOutPath</key><string>${xmlEscape(macLogFile)}</string>\n<key>StandardErrorPath</key><string>${xmlEscape(macLogFile)}</string>\n</dict></plist>\n`;
62
115
  fs.writeFileSync(macServiceFile, plist, { mode: 0o600 });
63
- spawnSync('launchctl', ['bootout', domain, macServiceFile], { stdio: 'ignore' });
116
+
117
+ if (loaded && previous === plist) {
118
+ run('launchctl', ['enable', target]);
119
+ // Never boot out a healthy loaded job just to refresh an in-place npm install. The final
120
+ // kickstart keeps launchd responsible for bringing the replacement agent back.
121
+ if (restart) run('launchctl', ['kickstart', '-k', target]);
122
+ return 'loaded';
123
+ }
124
+
125
+ if (loaded) {
126
+ // A changed Node/npm prefix requires launchd to re-read ProgramArguments. A separate transient
127
+ // launchd job survives booting out com.remcp.agent even when the updater was launched by it.
128
+ scheduleMacServiceReload(domain, target);
129
+ return 'reload-scheduled';
130
+ }
131
+
64
132
  run('launchctl', ['bootstrap', domain, macServiceFile]);
65
133
  run('launchctl', ['enable', target]);
66
- run('launchctl', ['kickstart', '-k', target]);
134
+ if (restart) run('launchctl', ['kickstart', '-k', target]);
135
+ return 'bootstrapped';
67
136
  }
68
137
 
69
138
  export function installWindowsService(cliPath = globalCliPath()) {
@@ -179,11 +248,11 @@ export function ensureServiceIfRecorded(config) {
179
248
  }
180
249
  }
181
250
  } else if (platform === 'darwin') {
182
- // launchd bakes the interpreter and the CLI path into the plist, so a Node manager that moves
183
- // its global prefix leaves the agent launching a file that no longer exists the same loop the
184
- // Linux unit above is repaired for. Reinstalling is idempotent (bootout, bootstrap, enable,
185
- // kickstart) and is what the Windows task already does on every update.
186
- installMacService(cliPath);
251
+ // launchd bakes the interpreter and CLI path into the plist. Repair the file first, but never
252
+ // boot out a loaded agent inline: this updater may itself be a descendant of that LaunchAgent.
253
+ // installMacService either leaves an unchanged loaded job alone, bootstraps an unloaded job, or
254
+ // hands a changed launcher to an independent transient launchd helper.
255
+ installMacService(cliPath, { restart: false });
187
256
  } else if (platform === 'win32') installWindowsService(cliPath);
188
257
  // Upgrade the legacy inferred state only after the supervisor repair succeeded. A failed repair
189
258
  // must not turn a stale artifact into a permanent "managed service" declaration.
@@ -204,12 +273,14 @@ export function restartPersistentServiceIfInstalled(config) {
204
273
  return 'remcp-agent.service';
205
274
  }
206
275
  if (platform === 'darwin' && fs.existsSync(macServiceFile)) {
207
- try {
208
- run('launchctl', ['kickstart', '-k', `${macLaunchDomain()}/${macServiceLabel}`]);
209
- } catch {
276
+ const target = `${macLaunchDomain()}/${macServiceLabel}`;
277
+ if (macJobLoaded(target)) {
278
+ // Never kill a loaded LaunchAgent inline: the caller may itself be a child of that job.
279
+ // A transient helper survives the handoff and performs the restart after this CLI returns.
280
+ scheduleMacServiceRestart(target);
281
+ } else {
210
282
  // A plist can survive while launchd has no loaded job (older installs, logout/login cleanup,
211
- // manual bootout, or a failed previous update). Re-register the job instead of surfacing the
212
- // opaque launchctl 113 error. installMacService is idempotent and rewrites stale Node paths too.
283
+ // manual bootout, or a failed previous update). Re-register it directly.
213
284
  installMacService(globalCliPath());
214
285
  }
215
286
  return macServiceLabel;