@sagentlab/navarch-runtime 0.1.184 → 0.1.187

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.
@@ -0,0 +1,773 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.SERVICE_CONFIG_ENVIRONMENT = exports.CREDENTIALS_REJECTED_EXIT_CODE = exports.DEFAULT_STOP_TIMEOUT_SECONDS = exports.SERVICE_ENV = void 0;
7
+ exports.serviceEnvNameAllowed = serviceEnvNameAllowed;
8
+ exports.defaultServiceHost = defaultServiceHost;
9
+ exports.serviceManagerFor = serviceManagerFor;
10
+ exports.serviceNameFor = serviceNameFor;
11
+ exports.servicePaths = servicePaths;
12
+ exports.parseEnvFile = parseEnvFile;
13
+ exports.formatEnvFile = formatEnvFile;
14
+ exports.sanitizeServicePath = sanitizeServicePath;
15
+ exports.captureServiceEnv = captureServiceEnv;
16
+ exports.applyServiceEnvFile = applyServiceEnvFile;
17
+ exports.resolveStableNodePath = resolveStableNodePath;
18
+ exports.resolveServiceRuntime = resolveServiceRuntime;
19
+ exports.buildLaunchdPlist = buildLaunchdPlist;
20
+ exports.buildSystemdUnit = buildSystemdUnit;
21
+ exports.writeServiceHalt = writeServiceHalt;
22
+ exports.installService = installService;
23
+ exports.uninstallService = uninstallService;
24
+ exports.restartService = restartService;
25
+ exports.serviceStatus = serviceStatus;
26
+ const node_child_process_1 = require("node:child_process");
27
+ const node_crypto_1 = require("node:crypto");
28
+ const node_fs_1 = require("node:fs");
29
+ const node_os_1 = __importDefault(require("node:os"));
30
+ const node_path_1 = __importDefault(require("node:path"));
31
+ const node_util_1 = require("node:util");
32
+ const machine_store_cjs_1 = require("./machine-store.cjs");
33
+ const version_cjs_1 = require("./version.cjs");
34
+ /**
35
+ * `navarch-runtime service` — keeps one agent running across reboots by
36
+ * registering `supervise` with the operating system's own service manager:
37
+ * a per-user LaunchAgent on macOS, a systemd user unit on Linux.
38
+ *
39
+ * The service is deliberately user-level, never root. Coding-agent CLIs keep
40
+ * their sign-in in the user's home directory and (on macOS) login keychain,
41
+ * which a system daemon cannot read.
42
+ */
43
+ const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
44
+ /** Set by the service definition only, so a hand-run `supervise` is unaffected. */
45
+ exports.SERVICE_ENV = "NAVARCH_SERVICE";
46
+ exports.DEFAULT_STOP_TIMEOUT_SECONDS = 300;
47
+ /** Seconds the service manager waits before restarting a crashed supervisor. */
48
+ const RESTART_DELAY_SECONDS = 30;
49
+ /**
50
+ * The runtime's "this machine's identity is gone" exit code (cli.cts). A
51
+ * restart cannot fix a removed agent or a revoked token, so neither service
52
+ * manager may restart on it.
53
+ */
54
+ exports.CREDENTIALS_REJECTED_EXIT_CODE = 78;
55
+ const LAUNCHD_LABEL_PREFIX = "com.sagentlab.navarch.";
56
+ const SYSTEMD_UNIT_PREFIX = "navarch-agent-";
57
+ const SERVICE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/;
58
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
59
+ /**
60
+ * The only `NAVARCH_*` names a service environment may carry: operator
61
+ * configuration that `loadConfig` reads (the README's configuration table),
62
+ * plus the Pi adapter's local endpoint override. This is an allow-list on
63
+ * purpose. The runtime also injects `NAVARCH_*` values into session processes
64
+ * (git and conversation credentials, lease ids, MCP authorization, delivery
65
+ * markers), so an install run from inside a session would otherwise freeze
66
+ * another lease's bearer token into the service. A new per-session variable
67
+ * stays out by default; a new configuration name must be added here (a test
68
+ * compares this list with config.cts).
69
+ *
70
+ * Deliberately absent: enrollment input, machine identity (machine.json is
71
+ * the source of truth and `connect` may replace it), `NAVARCH_CONFIG_DIR`
72
+ * (the service passes --config-dir), and the per-process markers
73
+ * `NAVARCH_SUPERVISED` and `NAVARCH_SERVICE`.
74
+ */
75
+ exports.SERVICE_CONFIG_ENVIRONMENT = new Set([
76
+ "NAVARCH_ACP_BIN",
77
+ "NAVARCH_ACP_EXTRA_ARGS",
78
+ "NAVARCH_AGENT",
79
+ "NAVARCH_ANTIGRAVITY_BIN",
80
+ "NAVARCH_ANTIGRAVITY_EXTRA_ARGS",
81
+ "NAVARCH_API_BASE",
82
+ "NAVARCH_AUTO_UPDATE",
83
+ "NAVARCH_BROWSER_PROBE",
84
+ "NAVARCH_CAPABILITIES",
85
+ "NAVARCH_CLAUDE_BIN",
86
+ "NAVARCH_CLAUDE_EXTRA_ARGS",
87
+ "NAVARCH_CODEX_BIN",
88
+ "NAVARCH_CODEX_EXTRA_ARGS",
89
+ "NAVARCH_CONVERSATION_MIRROR",
90
+ "NAVARCH_CONVERSATION_POLL_MS",
91
+ "NAVARCH_CONVERSATION_TURN_TIMEOUT_MS",
92
+ "NAVARCH_DEPENDENCY_CACHE",
93
+ "NAVARCH_DEPENDENCY_CACHE_TIMEOUT_MS",
94
+ "NAVARCH_DOCKER_IMAGE",
95
+ "NAVARCH_GEMINI_BIN",
96
+ "NAVARCH_GEMINI_EXTRA_ARGS",
97
+ "NAVARCH_GIT_AUTHOR_EMAIL",
98
+ "NAVARCH_GIT_AUTHOR_NAME",
99
+ "NAVARCH_GUARD_EXTRA_ROOTS",
100
+ "NAVARCH_HEARTBEAT_INTERVAL_MS",
101
+ "NAVARCH_LEASE_HEARTBEAT_INTERVAL_MS",
102
+ "NAVARCH_LIVE_STEERING",
103
+ "NAVARCH_MAX_SESSIONS",
104
+ "NAVARCH_MCP_CONFIG_PATH",
105
+ "NAVARCH_MUSE_BIN",
106
+ "NAVARCH_MUSE_EXTRA_ARGS",
107
+ "NAVARCH_NAVI_CONVERSATIONS",
108
+ "NAVARCH_NAVI_WORKSPACE_CHAT",
109
+ "NAVARCH_OPENCODE_BIN",
110
+ "NAVARCH_OPENCODE_EXTRA_ARGS",
111
+ "NAVARCH_OPENCODE_STARTUP_TIMEOUT_MS",
112
+ "NAVARCH_OWNER_ZONE",
113
+ "NAVARCH_PI_BIN",
114
+ "NAVARCH_PI_EXTRA_ARGS",
115
+ "NAVARCH_PI_LOCAL_BASE_URL",
116
+ "NAVARCH_POLL_INTERVAL_MS",
117
+ "NAVARCH_QODER_BIN",
118
+ "NAVARCH_QODER_EXTRA_ARGS",
119
+ "NAVARCH_RUNTIMES",
120
+ "NAVARCH_SANDBOX_EGRESS_NETWORK",
121
+ "NAVARCH_SANDBOX_MODE",
122
+ "NAVARCH_SANDBOX_PROFILE",
123
+ "NAVARCH_SESSION_IDLE_TIMEOUT_MS",
124
+ "NAVARCH_SESSION_TIMEOUT_MS",
125
+ "NAVARCH_UPDATE_CHANNEL",
126
+ "NAVARCH_USAGE_LIMITS",
127
+ "NAVARCH_WORKSPACE_ROOT",
128
+ "NAVARCH_WORKTREE_CLEANUP_INTERVAL_MS",
129
+ "NAVARCH_WORKTREE_GUARD",
130
+ "NAVARCH_WORKTREE_STALE_AFTER_MS",
131
+ ]);
132
+ /**
133
+ * Whether a variable may be written to, or applied from, a service
134
+ * environment file: every `NAVARCH_*` name must be on the allow-list above;
135
+ * other valid names (PATH, locale, an operator's `--env` copies) pass.
136
+ */
137
+ function serviceEnvNameAllowed(name) {
138
+ return ENV_NAME.test(name) && (!name.startsWith("NAVARCH_") || exports.SERVICE_CONFIG_ENVIRONMENT.has(name));
139
+ }
140
+ /**
141
+ * Non-secret variables a service manager does not provide but that change how
142
+ * agent CLIs, git, and Node behave: locale, proxies, certificate bundles, and
143
+ * the tools' own state directories.
144
+ */
145
+ const CAPTURED_ENVIRONMENT = [
146
+ "LANG",
147
+ "LC_ALL",
148
+ "LC_CTYPE",
149
+ "HTTP_PROXY",
150
+ "HTTPS_PROXY",
151
+ "ALL_PROXY",
152
+ "NO_PROXY",
153
+ "http_proxy",
154
+ "https_proxy",
155
+ "all_proxy",
156
+ "no_proxy",
157
+ "NODE_EXTRA_CA_CERTS",
158
+ "SSL_CERT_FILE",
159
+ "CODEX_HOME",
160
+ "CLAUDE_CONFIG_DIR",
161
+ "XDG_CONFIG_HOME",
162
+ "XDG_DATA_HOME",
163
+ "XDG_CACHE_HOME",
164
+ "XDG_STATE_HOME",
165
+ ];
166
+ /**
167
+ * Credentials an agent CLI may read from the shell. They are copied only when
168
+ * named with `--env`; when one is set but not copied, install says so, because
169
+ * "works in my terminal, fails as a service" is otherwise hard to diagnose.
170
+ */
171
+ const CREDENTIAL_ENVIRONMENT = [
172
+ "ANTHROPIC_API_KEY",
173
+ "ANTHROPIC_AUTH_TOKEN",
174
+ "ANTHROPIC_BASE_URL",
175
+ "OPENAI_API_KEY",
176
+ "OPENAI_BASE_URL",
177
+ "GEMINI_API_KEY",
178
+ "GOOGLE_API_KEY",
179
+ "OPENROUTER_API_KEY",
180
+ "DEEPSEEK_API_KEY",
181
+ "GH_TOKEN",
182
+ "GITHUB_TOKEN",
183
+ ];
184
+ const defaultRunner = async (file, args) => {
185
+ const result = await execFileAsync(file, args, { maxBuffer: 4 * 1024 * 1024 });
186
+ return { stdout: result.stdout, stderr: result.stderr };
187
+ };
188
+ function defaultServiceHost() {
189
+ const user = node_os_1.default.userInfo();
190
+ return {
191
+ platform: process.platform,
192
+ env: process.env,
193
+ homeDir: node_os_1.default.homedir(),
194
+ uid: user.uid,
195
+ username: user.username,
196
+ execPath: process.execPath,
197
+ packageDir: node_path_1.default.resolve(__dirname, ".."),
198
+ run: defaultRunner,
199
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
200
+ };
201
+ }
202
+ function serviceManagerFor(platform) {
203
+ if (platform === "darwin")
204
+ return "launchd";
205
+ if (platform === "linux")
206
+ return "systemd";
207
+ throw new Error(`navarch-runtime service supports macOS (launchd) and Linux (systemd), not ${platform}. ` +
208
+ "Run `supervise` under this system's own service or task scheduler instead.");
209
+ }
210
+ /**
211
+ * Names the service after its config directory, which is already unique per
212
+ * agent instance (runtime/README.md "Running multiple agents on one machine").
213
+ */
214
+ function serviceNameFor(configDir, homeDir, override) {
215
+ if (override !== undefined) {
216
+ if (!SERVICE_NAME.test(override)) {
217
+ throw new Error("--service-name may contain only letters, digits, '.', '_' and '-', and must start with a letter or digit.");
218
+ }
219
+ return override;
220
+ }
221
+ if (node_path_1.default.resolve(configDir) === node_path_1.default.resolve(homeDir, ".navarch"))
222
+ return "default";
223
+ const slug = node_path_1.default
224
+ .basename(node_path_1.default.resolve(configDir))
225
+ .replace(/[^A-Za-z0-9._-]+/g, "-")
226
+ .replace(/^[^A-Za-z0-9]+|-+$/g, "")
227
+ .slice(0, 63);
228
+ return slug || "agent";
229
+ }
230
+ function servicePaths(configDir, name, host) {
231
+ const manager = serviceManagerFor(host.platform);
232
+ const shared = {
233
+ manager,
234
+ name,
235
+ envFile: node_path_1.default.join(configDir, "service.env"),
236
+ haltedPath: node_path_1.default.join(configDir, "service-halted.json"),
237
+ };
238
+ if (manager === "launchd") {
239
+ const id = `${LAUNCHD_LABEL_PREFIX}${name}`;
240
+ return {
241
+ ...shared,
242
+ id,
243
+ definitionPath: node_path_1.default.join(host.homeDir, "Library", "LaunchAgents", `${id}.plist`),
244
+ logPath: node_path_1.default.join(configDir, "logs", "service.log"),
245
+ };
246
+ }
247
+ const id = `${SYSTEMD_UNIT_PREFIX}${name}.service`;
248
+ const xdgConfig = host.env.XDG_CONFIG_HOME || node_path_1.default.join(host.homeDir, ".config");
249
+ return { ...shared, id, definitionPath: node_path_1.default.join(xdgConfig, "systemd", "user", id), logPath: null };
250
+ }
251
+ // ---------------------------------------------------------------------------
252
+ // service.env
253
+ // ---------------------------------------------------------------------------
254
+ /** Parses `NAME=value` lines; `#` comments and one pair of surrounding quotes are allowed. */
255
+ function parseEnvFile(text) {
256
+ const values = {};
257
+ for (const rawLine of text.split(/\r?\n/)) {
258
+ const line = rawLine.trim();
259
+ if (!line || line.startsWith("#"))
260
+ continue;
261
+ const separator = line.indexOf("=");
262
+ if (separator <= 0)
263
+ continue;
264
+ const name = line.slice(0, separator).trim().replace(/^export\s+/, "");
265
+ if (!ENV_NAME.test(name))
266
+ continue;
267
+ let value = line.slice(separator + 1).trim();
268
+ const quote = value[0];
269
+ if (value.length >= 2 && (quote === '"' || quote === "'") && value.endsWith(quote)) {
270
+ value = value.slice(1, -1);
271
+ }
272
+ values[name] = value;
273
+ }
274
+ return values;
275
+ }
276
+ function formatEnvValue(value) {
277
+ // The parser strips one surrounding pair of quotes and outer whitespace, so
278
+ // protect a value that would otherwise lose either.
279
+ if (/^\s|\s$|^(['"]).*\1$/.test(value) && value.length > 0) {
280
+ return value.includes('"') ? `'${value}'` : `"${value}"`;
281
+ }
282
+ return value;
283
+ }
284
+ function formatEnvFile(values) {
285
+ const header = [
286
+ "# Environment for this Navarch agent's service. `service install` rewrites",
287
+ "# PATH, NAVARCH_* settings and the locale/proxy entries from the shell it",
288
+ "# runs in; other entries are kept. Only NAVARCH_* names the runtime reads as",
289
+ "# configuration are written or applied. Restart the service after editing.",
290
+ ];
291
+ const lines = Object.keys(values)
292
+ .sort()
293
+ .map((name) => `${name}=${formatEnvValue(values[name] ?? "")}`);
294
+ return `${[...header, ...lines].join("\n")}\n`;
295
+ }
296
+ /**
297
+ * Drops PATH entries that only exist because this command ran through `npx`
298
+ * or an npm script: per-invocation cache directories and the `node_modules/.bin`
299
+ * of whatever directory the operator happened to be in.
300
+ */
301
+ function sanitizeServicePath(pathValue) {
302
+ const seen = new Set();
303
+ return pathValue
304
+ .split(node_path_1.default.delimiter)
305
+ .filter((entry) => {
306
+ if (!entry || !node_path_1.default.isAbsolute(entry) || seen.has(entry))
307
+ return false;
308
+ seen.add(entry);
309
+ const normalized = entry.replace(/[/\\]+$/, "");
310
+ if (/[/\\]_npx[/\\]/.test(normalized))
311
+ return false;
312
+ if (/[/\\]node_modules[/\\]\.bin$/.test(normalized))
313
+ return false;
314
+ if (/[/\\]node-gyp-bin$/.test(normalized))
315
+ return false;
316
+ return true;
317
+ })
318
+ .join(node_path_1.default.delimiter);
319
+ }
320
+ function isManagedEnvName(name) {
321
+ return name === "PATH" || name.startsWith("NAVARCH_") || CAPTURED_ENVIRONMENT.includes(name);
322
+ }
323
+ /**
324
+ * Builds the service's environment file from the installing shell. Managed
325
+ * names (PATH, allow-listed NAVARCH_*, locale/proxy) always mirror this shell so a stale
326
+ * `NAVARCH_AGENT` from an earlier install cannot outlive a re-enrollment;
327
+ * anything else already in the file — hand-added keys, earlier `--env`
328
+ * copies — is preserved.
329
+ */
330
+ function captureServiceEnv(env, existing, extraNames = []) {
331
+ const values = {};
332
+ for (const [name, value] of Object.entries(existing)) {
333
+ if (!isManagedEnvName(name))
334
+ values[name] = value;
335
+ }
336
+ const usable = (value) => typeof value === "string" && value.length > 0 && !/[\r\n]/.test(value);
337
+ const servicePath = sanitizeServicePath(env.PATH ?? "");
338
+ if (servicePath)
339
+ values.PATH = servicePath;
340
+ for (const [name, value] of Object.entries(env)) {
341
+ if (!name.startsWith("NAVARCH_") || !exports.SERVICE_CONFIG_ENVIRONMENT.has(name))
342
+ continue;
343
+ if (usable(value))
344
+ values[name] = value;
345
+ }
346
+ for (const name of CAPTURED_ENVIRONMENT) {
347
+ if (usable(env[name]))
348
+ values[name] = env[name];
349
+ }
350
+ const missing = [];
351
+ for (const name of extraNames) {
352
+ if (!serviceEnvNameAllowed(name)) {
353
+ throw new Error(name.startsWith("NAVARCH_")
354
+ ? `--env cannot copy '${name}' into the service: it is not a NAVARCH_* configuration setting (machine identity, enrollment input, or a per-session value).`
355
+ : `--env cannot copy '${name}' into the service: it is not a valid environment variable name.`);
356
+ }
357
+ if (usable(env[name]))
358
+ values[name] = env[name];
359
+ else
360
+ missing.push(name);
361
+ }
362
+ const uncapturedCredentials = CREDENTIAL_ENVIRONMENT.filter((name) => usable(env[name]) && values[name] === undefined);
363
+ return { values, missing, uncapturedCredentials };
364
+ }
365
+ /**
366
+ * Applies a service environment file to this process. File values win: under
367
+ * a service manager the inherited environment is only a bare default.
368
+ * `NAVARCH_*` names outside SERVICE_CONFIG_ENVIRONMENT are ignored.
369
+ */
370
+ async function applyServiceEnvFile(file, env = process.env) {
371
+ const values = parseEnvFile(await node_fs_1.promises.readFile(file, "utf8"));
372
+ for (const [name, value] of Object.entries(values)) {
373
+ // The capture rule again, so a file written by an earlier runtime or
374
+ // edited by hand cannot re-export a per-session credential.
375
+ if (!serviceEnvNameAllowed(name))
376
+ continue;
377
+ env[name] = value;
378
+ }
379
+ }
380
+ // ---------------------------------------------------------------------------
381
+ // Stable executable paths
382
+ // ---------------------------------------------------------------------------
383
+ /**
384
+ * `process.execPath` is fully resolved, so under Homebrew or a version manager
385
+ * it names one exact Node build and disappears on the next upgrade. Prefer the
386
+ * PATH entry that currently points at it, which survives upgrades.
387
+ */
388
+ async function resolveStableNodePath(execPath, pathValue) {
389
+ const target = await node_fs_1.promises.realpath(execPath).catch(() => execPath);
390
+ for (const dir of pathValue.split(node_path_1.default.delimiter)) {
391
+ if (!dir || !node_path_1.default.isAbsolute(dir))
392
+ continue;
393
+ const candidate = node_path_1.default.join(dir, node_path_1.default.basename(execPath));
394
+ if (candidate === execPath)
395
+ return execPath;
396
+ const resolved = await node_fs_1.promises.realpath(candidate).catch(() => null);
397
+ if (resolved === target)
398
+ return candidate;
399
+ }
400
+ return execPath;
401
+ }
402
+ function isNpxCachePath(dir) {
403
+ return /[/\\]_npx[/\\]/.test(dir);
404
+ }
405
+ /**
406
+ * Returns the `navarch.cjs` the service should start. A package running from
407
+ * the npx cache is copied under the config directory first: npm may purge that
408
+ * cache at any time, which would leave the service pointing at nothing after a
409
+ * reboot. Published packages bundle their dependencies, so the package
410
+ * directory is self-contained. Installed or source checkouts are used in place.
411
+ */
412
+ async function resolveServiceRuntime(configDir, host) {
413
+ const inPlace = node_path_1.default.join(host.packageDir, "bin", "navarch.cjs");
414
+ if (!isNpxCachePath(host.packageDir))
415
+ return { binPath: inPlace, copied: false };
416
+ const root = node_path_1.default.join(configDir, "service-runtime");
417
+ const targetDir = node_path_1.default.join(root, version_cjs_1.RUNTIME_VERSION);
418
+ const binPath = node_path_1.default.join(targetDir, "bin", "navarch.cjs");
419
+ const runs = () => host.run(host.execPath, [binPath, "--help"]).then(() => true, () => false);
420
+ if (!(await runs())) {
421
+ await node_fs_1.promises.mkdir(root, { recursive: true, mode: 0o700 });
422
+ const staging = node_path_1.default.join(root, `.staging-${(0, node_crypto_1.randomUUID)()}`);
423
+ try {
424
+ await node_fs_1.promises.cp(host.packageDir, staging, { recursive: true, verbatimSymlinks: true });
425
+ await node_fs_1.promises.rm(targetDir, { recursive: true, force: true });
426
+ await node_fs_1.promises.rename(staging, targetDir);
427
+ }
428
+ finally {
429
+ await node_fs_1.promises.rm(staging, { recursive: true, force: true });
430
+ }
431
+ if (!(await runs()))
432
+ throw new Error(`The runtime copied to ${targetDir} does not start.`);
433
+ }
434
+ // Keep earlier copies available to their installed definitions until uninstall.
435
+ return { binPath, copied: true };
436
+ }
437
+ function superviseArguments(input) {
438
+ return [input.nodePath, input.binPath, "supervise", "--config-dir", input.configDir, "--env-file", input.envFile];
439
+ }
440
+ function xml(value) {
441
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
442
+ }
443
+ function buildLaunchdPlist(input) {
444
+ const args = superviseArguments(input)
445
+ .map((arg) => `\t\t<string>${xml(arg)}</string>`)
446
+ .join("\n");
447
+ const log = input.logPath
448
+ ? `\t<key>StandardOutPath</key>\n\t<string>${xml(input.logPath)}</string>\n` +
449
+ `\t<key>StandardErrorPath</key>\n\t<string>${xml(input.logPath)}</string>\n`
450
+ : "";
451
+ // KeepAlive restarts only a failed exit. A drained SIGTERM stop exits 0, and
452
+ // in service mode `supervise` also exits 0 once its credentials are
453
+ // rejected, so neither is restarted (launchd cannot exempt one exit code).
454
+ return `<?xml version="1.0" encoding="UTF-8"?>
455
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
456
+ <plist version="1.0">
457
+ <dict>
458
+ <key>Label</key>
459
+ <string>${xml(input.id)}</string>
460
+ <key>ProgramArguments</key>
461
+ <array>
462
+ ${args}
463
+ </array>
464
+ <key>EnvironmentVariables</key>
465
+ <dict>
466
+ <key>${exports.SERVICE_ENV}</key>
467
+ <string>launchd</string>
468
+ </dict>
469
+ <key>WorkingDirectory</key>
470
+ <string>${xml(input.homeDir)}</string>
471
+ <key>RunAtLoad</key>
472
+ <true/>
473
+ <key>KeepAlive</key>
474
+ <dict>
475
+ <key>SuccessfulExit</key>
476
+ <false/>
477
+ </dict>
478
+ <key>ThrottleInterval</key>
479
+ <integer>${RESTART_DELAY_SECONDS}</integer>
480
+ <key>ExitTimeOut</key>
481
+ <integer>${input.stopTimeoutSeconds}</integer>
482
+ ${log}</dict>
483
+ </plist>
484
+ `;
485
+ }
486
+ /** Quotes one ExecStart argument; `%` and `$` are systemd specifiers/expansions. */
487
+ function systemdQuote(value) {
488
+ const escaped = value
489
+ .replace(/\\/g, "\\\\")
490
+ .replace(/"/g, '\\"')
491
+ .replace(/%/g, "%%")
492
+ .replace(/\$/g, () => "$$");
493
+ return `"${escaped}"`;
494
+ }
495
+ function buildSystemdUnit(input) {
496
+ // KillMode=mixed sends SIGTERM to the supervisor only, which forwards it so
497
+ // the worker drains its sessions; the default would signal every agent
498
+ // process in the unit at once.
499
+ return `[Unit]
500
+ Description=Navarch agent (${input.id.replace(/\.service$/, "")})
501
+
502
+ [Service]
503
+ Type=simple
504
+ ExecStart=${superviseArguments(input).map(systemdQuote).join(" ")}
505
+ Environment=${exports.SERVICE_ENV}=systemd
506
+ WorkingDirectory=${input.homeDir}
507
+ Restart=on-failure
508
+ RestartSec=${RESTART_DELAY_SECONDS}
509
+ RestartPreventExitStatus=${exports.CREDENTIALS_REJECTED_EXIT_CODE}
510
+ KillMode=mixed
511
+ TimeoutStopSec=${input.stopTimeoutSeconds}
512
+
513
+ [Install]
514
+ WantedBy=default.target
515
+ `;
516
+ }
517
+ /** Records why a service stopped for good, so `service status` can say so. */
518
+ async function writeServiceHalt(configDir, reason) {
519
+ const halt = { reason, at: new Date().toISOString() };
520
+ await node_fs_1.promises.writeFile(node_path_1.default.join(configDir, "service-halted.json"), `${JSON.stringify(halt, null, 2)}\n`, { mode: 0o600 });
521
+ }
522
+ async function readServiceHalt(file) {
523
+ try {
524
+ const parsed = JSON.parse(await node_fs_1.promises.readFile(file, "utf8"));
525
+ return typeof parsed.reason === "string" && typeof parsed.at === "string"
526
+ ? { reason: parsed.reason, at: parsed.at }
527
+ : null;
528
+ }
529
+ catch {
530
+ return null;
531
+ }
532
+ }
533
+ function failureText(error) {
534
+ const stderr = error?.stderr;
535
+ if (typeof stderr === "string" && stderr.trim())
536
+ return stderr.trim();
537
+ return error instanceof Error ? error.message : String(error);
538
+ }
539
+ async function writeFileAtomic(file, content, mode) {
540
+ await node_fs_1.promises.mkdir(node_path_1.default.dirname(file), { recursive: true });
541
+ const temp = `${file}.${(0, node_crypto_1.randomUUID)()}.tmp`;
542
+ await node_fs_1.promises.writeFile(temp, content, { mode });
543
+ await node_fs_1.promises.chmod(temp, mode);
544
+ await node_fs_1.promises.rename(temp, file);
545
+ }
546
+ /**
547
+ * Refuses to replace a definition that serves another config directory: two
548
+ * directories with the same basename would otherwise silently share one
549
+ * service, and the first agent would stop being started.
550
+ */
551
+ async function assertDefinitionOwned(paths, configDir) {
552
+ const existing = await node_fs_1.promises.readFile(paths.definitionPath, "utf8").catch((error) => {
553
+ if (error.code === "ENOENT")
554
+ return null;
555
+ throw error;
556
+ });
557
+ if (existing === null)
558
+ return false;
559
+ const lines = existing.split(/\r?\n/);
560
+ const owned = paths.manager === "launchd"
561
+ ? lines.some((line, index) => line.trim() === "<string>--config-dir</string>" &&
562
+ lines[index + 1]?.trim() === `<string>${xml(configDir)}</string>`)
563
+ : lines.some((line) => line.startsWith("ExecStart=") &&
564
+ line.endsWith(` "--config-dir" ${systemdQuote(configDir)} "--env-file" ${systemdQuote(paths.envFile)}`));
565
+ if (owned)
566
+ return true;
567
+ throw new Error(`${paths.definitionPath} already exists for a different config directory. ` +
568
+ "Pass --service-name <name> to give this agent its own service.");
569
+ }
570
+ function launchdDomain(uid) {
571
+ return `gui/${uid}`;
572
+ }
573
+ async function launchdLoaded(host, id) {
574
+ return host.run("launchctl", ["print", `${launchdDomain(host.uid)}/${id}`]).then((result) => result.stdout, () => null);
575
+ }
576
+ /** Unloads a launchd service and waits for its drain; true when it was loaded. */
577
+ async function launchdStop(host, id, stopTimeoutSeconds) {
578
+ if ((await launchdLoaded(host, id)) === null)
579
+ return false;
580
+ await host.run("launchctl", ["bootout", `${launchdDomain(host.uid)}/${id}`]).catch(() => undefined);
581
+ // bootout can return while the supervisor is still draining sessions, and a
582
+ // bootstrap issued before it is gone fails, so wait for the old job to go.
583
+ const deadline = Date.now() + (stopTimeoutSeconds + 15) * 1000;
584
+ while ((await launchdLoaded(host, id)) !== null) {
585
+ if (Date.now() > deadline) {
586
+ throw new Error(`The running service ${id} did not stop within ${stopTimeoutSeconds + 15} seconds.`);
587
+ }
588
+ await host.sleep(500);
589
+ }
590
+ return true;
591
+ }
592
+ async function launchdStart(host, paths) {
593
+ const domain = launchdDomain(host.uid);
594
+ const hasGuiSession = await host.run("launchctl", ["print", domain]).then(() => true, () => false);
595
+ if (!hasGuiSession) {
596
+ return {
597
+ started: false,
598
+ notes: [
599
+ `${host.username} has no desktop login session right now, so the service was not started. ` +
600
+ "It starts the next time this user logs in at the Mac.",
601
+ ],
602
+ };
603
+ }
604
+ // A label disabled earlier (launchctl disable) would silently refuse to load.
605
+ await host.run("launchctl", ["enable", `${domain}/${paths.id}`]).catch(() => undefined);
606
+ let lastError;
607
+ for (let attempt = 0; attempt < 5; attempt++) {
608
+ try {
609
+ await host.run("launchctl", ["bootstrap", domain, paths.definitionPath]);
610
+ return { started: true, notes: [] };
611
+ }
612
+ catch (error) {
613
+ lastError = error;
614
+ await host.sleep(1000);
615
+ }
616
+ }
617
+ throw new Error(`launchctl could not load ${paths.definitionPath}: ${failureText(lastError)}`);
618
+ }
619
+ async function systemdStart(host, paths) {
620
+ const notes = [];
621
+ try {
622
+ await host.run("systemctl", ["--user", "daemon-reload"]);
623
+ await host.run("systemctl", ["--user", "enable", paths.id]);
624
+ await host.run("systemctl", ["--user", "restart", paths.id]);
625
+ }
626
+ catch (error) {
627
+ throw new Error(`systemctl --user could not start ${paths.id}: ${failureText(error)}. ` +
628
+ "This needs a systemd user session (log in as this user directly rather than through su).");
629
+ }
630
+ // Without lingering, a user's units start at their first login and stop at
631
+ // their last logout — not what "restart after reboot" means on a server.
632
+ const lingering = await host
633
+ .run("loginctl", ["show-user", host.username, "--property=Linger", "--value"])
634
+ .then((result) => result.stdout.trim() === "yes", () => false);
635
+ if (lingering)
636
+ return { started: true, startsAtBoot: true, notes };
637
+ const enabled = await host.run("loginctl", ["enable-linger", host.username]).then(() => true, () => false);
638
+ if (!enabled) {
639
+ notes.push(`To start at boot without logging in, run: sudo loginctl enable-linger ${host.username}`);
640
+ }
641
+ return { started: true, startsAtBoot: enabled, notes };
642
+ }
643
+ async function installService(options, host = defaultServiceHost()) {
644
+ const configDir = node_path_1.default.resolve(options.configDir);
645
+ const stopTimeoutSeconds = options.stopTimeoutSeconds ?? exports.DEFAULT_STOP_TIMEOUT_SECONDS;
646
+ if (!Number.isInteger(stopTimeoutSeconds) || stopTimeoutSeconds < 10 || stopTimeoutSeconds > 3600) {
647
+ throw new Error("--stop-timeout must be a whole number of seconds between 10 and 3600.");
648
+ }
649
+ const manager = serviceManagerFor(host.platform);
650
+ if (host.uid === 0) {
651
+ throw new Error("Install the service as the user whose coding-agent sign-in it should use, not as root.");
652
+ }
653
+ if (!(await (0, machine_store_cjs_1.loadMachineIdentity)(configDir))) {
654
+ throw new Error(`${configDir} has no machine.json. Run \`connect\` with this --config-dir first; the service starts the agent it enrolled.`);
655
+ }
656
+ const paths = servicePaths(configDir, serviceNameFor(configDir, host.homeDir, options.serviceName), host);
657
+ await assertDefinitionOwned(paths, configDir);
658
+ // Prepare everything that can fail before touching a running service.
659
+ const existingEnv = await node_fs_1.promises.readFile(paths.envFile, "utf8").then(parseEnvFile, () => ({}));
660
+ const captured = captureServiceEnv(host.env, existingEnv, options.extraEnv);
661
+ const runtime = await resolveServiceRuntime(configDir, host);
662
+ const nodePath = await resolveStableNodePath(host.execPath, captured.values.PATH ?? "");
663
+ const definitionInput = {
664
+ id: paths.id,
665
+ nodePath,
666
+ binPath: runtime.binPath,
667
+ configDir,
668
+ envFile: paths.envFile,
669
+ homeDir: host.homeDir,
670
+ logPath: paths.logPath,
671
+ stopTimeoutSeconds,
672
+ };
673
+ const definition = manager === "launchd" ? buildLaunchdPlist(definitionInput) : buildSystemdUnit(definitionInput);
674
+ if (manager === "launchd")
675
+ await launchdStop(host, paths.id, stopTimeoutSeconds);
676
+ await writeFileAtomic(paths.envFile, formatEnvFile(captured.values), 0o600);
677
+ if (paths.logPath)
678
+ await node_fs_1.promises.mkdir(node_path_1.default.dirname(paths.logPath), { recursive: true, mode: 0o700 });
679
+ await writeFileAtomic(paths.definitionPath, definition, 0o644);
680
+ await node_fs_1.promises.rm(paths.haltedPath, { force: true });
681
+ const base = {
682
+ ...paths,
683
+ runtimeCopied: runtime.copied,
684
+ missingEnv: captured.missing,
685
+ uncapturedCredentials: captured.uncapturedCredentials,
686
+ };
687
+ if (manager === "launchd") {
688
+ const start = await launchdStart(host, paths);
689
+ // A LaunchAgent belongs to a login session: it starts at login, not boot.
690
+ return { ...base, started: start.started, startsAtBoot: false, notes: start.notes };
691
+ }
692
+ const start = await systemdStart(host, paths);
693
+ return { ...base, started: start.started, startsAtBoot: start.startsAtBoot, notes: start.notes };
694
+ }
695
+ /** Stops and removes the service. The config directory and its identity are left alone. */
696
+ async function uninstallService(options, host = defaultServiceHost()) {
697
+ const configDir = node_path_1.default.resolve(options.configDir);
698
+ const paths = servicePaths(configDir, serviceNameFor(configDir, host.homeDir, options.serviceName), host);
699
+ if (!(await assertDefinitionOwned(paths, configDir)))
700
+ return { ...paths, removed: false };
701
+ if (paths.manager === "launchd") {
702
+ await launchdStop(host, paths.id, options.stopTimeoutSeconds ?? exports.DEFAULT_STOP_TIMEOUT_SECONDS);
703
+ }
704
+ else {
705
+ try {
706
+ await host.run("systemctl", ["--user", "disable", "--now", paths.id]);
707
+ }
708
+ catch (error) {
709
+ throw new Error(`systemctl --user could not stop and disable ${paths.id}: ${failureText(error)}`);
710
+ }
711
+ }
712
+ await node_fs_1.promises.rm(paths.definitionPath, { force: true });
713
+ await node_fs_1.promises.rm(node_path_1.default.join(configDir, "service-runtime"), { recursive: true, force: true });
714
+ await node_fs_1.promises.rm(paths.haltedPath, { force: true });
715
+ if (paths.manager === "systemd")
716
+ await host.run("systemctl", ["--user", "daemon-reload"]);
717
+ return { ...paths, removed: true };
718
+ }
719
+ /**
720
+ * Restarts an installed service without rewriting it — the way to apply a
721
+ * hand edit to service.env. The stop drains active sessions like any other.
722
+ */
723
+ async function restartService(options, host = defaultServiceHost()) {
724
+ const configDir = node_path_1.default.resolve(options.configDir);
725
+ const paths = servicePaths(configDir, serviceNameFor(configDir, host.homeDir, options.serviceName), host);
726
+ if (!(await assertDefinitionOwned(paths, configDir))) {
727
+ throw new Error(`No service is installed for ${configDir}. Run \`service install\` first.`);
728
+ }
729
+ await node_fs_1.promises.rm(paths.haltedPath, { force: true });
730
+ if (paths.manager === "launchd") {
731
+ await launchdStop(host, paths.id, options.stopTimeoutSeconds ?? exports.DEFAULT_STOP_TIMEOUT_SECONDS);
732
+ return { ...paths, ...(await launchdStart(host, paths)) };
733
+ }
734
+ try {
735
+ await host.run("systemctl", ["--user", "restart", paths.id]);
736
+ }
737
+ catch (error) {
738
+ throw new Error(`systemctl --user could not restart ${paths.id}: ${failureText(error)}`);
739
+ }
740
+ return { ...paths, started: true, notes: [] };
741
+ }
742
+ async function serviceStatus(options, host = defaultServiceHost()) {
743
+ const configDir = node_path_1.default.resolve(options.configDir);
744
+ const paths = servicePaths(configDir, serviceNameFor(configDir, host.homeDir, options.serviceName), host);
745
+ const installed = await node_fs_1.promises.access(paths.definitionPath).then(() => true, () => false);
746
+ const halted = await readServiceHalt(paths.haltedPath);
747
+ let state = "not loaded";
748
+ let pid = null;
749
+ let lastExitCode = null;
750
+ if (paths.manager === "launchd") {
751
+ const printed = await launchdLoaded(host, paths.id);
752
+ if (printed !== null) {
753
+ const pidMatch = /^\s*pid = (\d+)\s*$/m.exec(printed);
754
+ const exitMatch = /^\s*last exit code = (\d+)/m.exec(printed);
755
+ pid = pidMatch ? Number(pidMatch[1]) : null;
756
+ lastExitCode = exitMatch ? Number(exitMatch[1]) : null;
757
+ state = pid !== null ? "running" : "stopped";
758
+ }
759
+ }
760
+ else {
761
+ const shown = await host
762
+ .run("systemctl", ["--user", "show", paths.id, "--property=LoadState,ActiveState,MainPID,ExecMainStatus"])
763
+ .then((result) => parseEnvFile(result.stdout), () => null);
764
+ if (shown && shown.LoadState === "loaded") {
765
+ const mainPid = Number(shown.MainPID);
766
+ pid = Number.isInteger(mainPid) && mainPid > 0 ? mainPid : null;
767
+ state = shown.ActiveState === "active" ? "running" : shown.ActiveState === "inactive" ? "stopped" : (shown.ActiveState ?? "unknown");
768
+ const exit = Number(shown.ExecMainStatus);
769
+ lastExitCode = pid === null && Number.isInteger(exit) ? exit : null;
770
+ }
771
+ }
772
+ return { ...paths, installed, state, pid, lastExitCode, halted };
773
+ }