@sagentlab/navarch-runtime 0.1.183 → 0.1.186
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.
- package/README.md +78 -0
- package/dist/browser-evidence.cjs +2 -1
- package/dist/browser-probe.cjs +2 -1
- package/dist/cli.cjs +164 -13
- package/dist/local-browser.cjs +2 -1
- package/dist/service.cjs +773 -0
- package/dist/version.cjs +8 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -290,6 +290,7 @@ The from-source flow — `git clone` + `./install.sh` + `node bin/navarch.cjs
|
|
|
290
290
|
| `start [--agent claude-code\|codex\|antigravity\|opencode\|acp\|qoder\|muse\|pi-local]` | Runs the daemon. A start-time agent choice overrides the saved choice. |
|
|
291
291
|
| `supervise [--agent claude-code\|codex\|antigravity\|opencode\|acp\|qoder\|muse\|pi-local]` | Runs the daemon under the update supervisor, enabling drain-safe automatic updates and rollback. |
|
|
292
292
|
| `doctor [--agent claude-code\|codex\|antigravity\|opencode\|acp\|qoder\|muse\|pi-local]` | Prints resolved config + Docker/registration status; no side effects. |
|
|
293
|
+
| `service install\|restart\|uninstall\|status [--config-dir <path>]` | Runs `supervise` as a launchd (macOS) or systemd (Linux) user service that starts again after a restart or crash. See [Running as a service](#running-as-a-service). |
|
|
293
294
|
|
|
294
295
|
### Running multiple agents on one machine
|
|
295
296
|
|
|
@@ -315,6 +316,83 @@ files. A supervisor also pins its starting identity into replacement workers,
|
|
|
315
316
|
so an accidental later edit to `machine.json` cannot change that running
|
|
316
317
|
instance during an automatic-update handoff.
|
|
317
318
|
|
|
319
|
+
### Running as a service
|
|
320
|
+
|
|
321
|
+
`supervise` is a foreground process: it stops when its terminal closes or the
|
|
322
|
+
machine restarts. `service install` hands it to the operating system's service
|
|
323
|
+
manager so the agent comes back on its own.
|
|
324
|
+
|
|
325
|
+
```sh
|
|
326
|
+
npx @sagentlab/navarch-runtime connect <enrollment options> --config-dir ~/.navarch/pebble
|
|
327
|
+
npx @sagentlab/navarch-runtime@latest service install --config-dir ~/.navarch/pebble
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
`connect … --install-service` does both in one command. The "Connect an agent"
|
|
331
|
+
panel generates the two-line form when **Keep it running after a restart** is
|
|
332
|
+
ticked. Run `service install` in the shell you would have run `supervise` in,
|
|
333
|
+
with the same `NAVARCH_*` prefix: it records that environment for the service.
|
|
334
|
+
Stop a `supervise` you started by hand for the same config directory first; two
|
|
335
|
+
processes must never serve one agent.
|
|
336
|
+
|
|
337
|
+
| | macOS | Linux |
|
|
338
|
+
|---|---|---|
|
|
339
|
+
| Service manager | launchd LaunchAgent | systemd user unit |
|
|
340
|
+
| Definition | `~/Library/LaunchAgents/com.sagentlab.navarch.<name>.plist` | `~/.config/systemd/user/navarch-agent-<name>.service` |
|
|
341
|
+
| Starts | when the user logs in | at boot, once lingering is enabled |
|
|
342
|
+
| Logs | `<config-dir>/logs/service.log` | `journalctl --user -u navarch-agent-<name>` |
|
|
343
|
+
|
|
344
|
+
`<name>` is the config directory's name (`pebble` above); pass
|
|
345
|
+
`--service-name` to choose another. One service serves one config directory.
|
|
346
|
+
|
|
347
|
+
The service is user-level on purpose. Coding-agent CLIs keep their sign-in in
|
|
348
|
+
the user's home directory and, on macOS, the login keychain, which a root
|
|
349
|
+
daemon cannot read. Two consequences:
|
|
350
|
+
|
|
351
|
+
- **macOS:** a LaunchAgent starts at login, not at boot. For a Mac that must
|
|
352
|
+
come back unattended, turn on automatic login for that user (System Settings
|
|
353
|
+
→ Users & Groups). FileVault asks for a password before any user service can
|
|
354
|
+
start.
|
|
355
|
+
- **Linux:** `service install` runs `loginctl enable-linger <user>` so the unit
|
|
356
|
+
starts at boot without a login. Where that needs privileges it prints the
|
|
357
|
+
`sudo` command to run once.
|
|
358
|
+
|
|
359
|
+
What `service install` sets up:
|
|
360
|
+
|
|
361
|
+
- **A fixed runtime path.** A runtime started through `npx` lives in npm's
|
|
362
|
+
cache, which npm may purge. That package is copied to
|
|
363
|
+
`<config-dir>/service-runtime/<version>` and the service starts from there
|
|
364
|
+
with an absolute Node path. Automatic updates work as usual: the supervisor
|
|
365
|
+
still activates the verified release recorded in `active-runtime.json`.
|
|
366
|
+
- **`<config-dir>/service.env`** (mode 0600), read by `supervise --env-file`.
|
|
367
|
+
A service manager starts processes with a bare environment, so install saves
|
|
368
|
+
the shell's `PATH` (so `claude`, `codex`, `git`, and `gh` resolve), the
|
|
369
|
+
`NAVARCH_*` configuration settings (the allow-list `SERVICE_CONFIG_ENVIRONMENT`
|
|
370
|
+
in `src/service.cts`), and locale, proxy, and certificate variables. Each install rewrites those
|
|
371
|
+
from the current shell; anything else in the file is kept. Other `NAVARCH_*`
|
|
372
|
+
names are never written there or read back from it: machine identity,
|
|
373
|
+
enrollment tokens, and the credentials and lease ids the runtime gives a
|
|
374
|
+
session, so an install run from inside a Navarch session does not copy them.
|
|
375
|
+
- **API keys are not copied unless you name them.** If an agent CLI reads a
|
|
376
|
+
key from the environment, pass `--env ANTHROPIC_API_KEY,GH_TOKEN` or add the
|
|
377
|
+
line to `service.env` yourself. Install lists the credential variables it saw
|
|
378
|
+
and left out.
|
|
379
|
+
- **Restart rules.** A crash is restarted after 30 seconds. A stop
|
|
380
|
+
(`SIGTERM`, shutdown) drains active sessions for up to `--stop-timeout`
|
|
381
|
+
seconds (default 300) and is not restarted until the next login or boot.
|
|
382
|
+
- **No restart loop on a removed agent.** When Navarch rejects the machine's
|
|
383
|
+
credentials (the agent was removed or its token revoked) the service stops
|
|
384
|
+
for good and records why in `<config-dir>/service-halted.json`;
|
|
385
|
+
`service status` shows it. Re-enroll with a fresh `connect` command and run
|
|
386
|
+
`service install` again.
|
|
387
|
+
|
|
388
|
+
`service status` prints the service manager's view and exits 0 only while the
|
|
389
|
+
service is running. `service restart` restarts it without rewriting anything;
|
|
390
|
+
use it after editing `service.env`. `service uninstall` stops and removes the
|
|
391
|
+
service and leaves the config directory and machine identity in place.
|
|
392
|
+
|
|
393
|
+
Windows is not supported; run `supervise` under Task Scheduler or a service
|
|
394
|
+
wrapper there.
|
|
395
|
+
|
|
318
396
|
## Live steering
|
|
319
397
|
|
|
320
398
|
A person can send a message to a session that is already running, from the
|
|
@@ -16,6 +16,7 @@ const playwright_1 = require("playwright");
|
|
|
16
16
|
const zod_1 = require("zod");
|
|
17
17
|
const local_browser_cjs_1 = require("./local-browser.cjs");
|
|
18
18
|
const playwright_server_cjs_1 = require("./playwright-server.cjs");
|
|
19
|
+
const version_cjs_1 = require("./version.cjs");
|
|
19
20
|
const node_child_process_1 = require("node:child_process");
|
|
20
21
|
const node_util_1 = require("node:util");
|
|
21
22
|
const node_path_1 = __importDefault(require("node:path"));
|
|
@@ -103,7 +104,7 @@ async function startBrowserEvidence(options) {
|
|
|
103
104
|
browser = await (options.launch?.() ?? launchCaptureBrowser());
|
|
104
105
|
}
|
|
105
106
|
catch {
|
|
106
|
-
throw new Error(
|
|
107
|
+
throw new Error(`Runtime browser could not start. On the agent host run ${version_cjs_1.BROWSER_INSTALL_COMMAND}. Check host browser permissions; do not change the task repository or CI to install capture tooling.`);
|
|
107
108
|
}
|
|
108
109
|
for (const viewport of ["desktop", "mobile"]) {
|
|
109
110
|
assertActive();
|
package/dist/browser-probe.cjs
CHANGED
|
@@ -17,6 +17,7 @@ const node_path_1 = __importDefault(require("node:path"));
|
|
|
17
17
|
const codex_cjs_1 = require("./adapters/codex.cjs");
|
|
18
18
|
const browser_evidence_cjs_1 = require("./browser-evidence.cjs");
|
|
19
19
|
const logger_cjs_1 = require("./logger.cjs");
|
|
20
|
+
const version_cjs_1 = require("./version.cjs");
|
|
20
21
|
const worktree_guard_cjs_1 = require("./worktree-guard.cjs");
|
|
21
22
|
const log = (0, logger_cjs_1.createLogger)("browser-probe");
|
|
22
23
|
exports.BROWSER_CAPABILITY = "browser-use";
|
|
@@ -68,7 +69,7 @@ async function probeBrowserCapability(config, deps = {}) {
|
|
|
68
69
|
return {
|
|
69
70
|
status: "failed",
|
|
70
71
|
reason: truncate(`Headless Chromium could not start on this machine: ${summarizeLaunchFailure(String(error))} ` +
|
|
71
|
-
|
|
72
|
+
`Run \`${version_cjs_1.BROWSER_INSTALL_COMMAND}\`, then restart the agent.`),
|
|
72
73
|
checked_at: now().toISOString(),
|
|
73
74
|
};
|
|
74
75
|
}
|
package/dist/cli.cjs
CHANGED
|
@@ -24,16 +24,16 @@ const supervisor_cjs_1 = require("./supervisor.cjs");
|
|
|
24
24
|
const worktree_janitor_cjs_1 = require("./worktree-janitor.cjs");
|
|
25
25
|
const browser_evidence_cjs_1 = require("./browser-evidence.cjs");
|
|
26
26
|
const browser_probe_cjs_1 = require("./browser-probe.cjs");
|
|
27
|
+
const service_cjs_1 = require("./service.cjs");
|
|
27
28
|
const log = (0, logger_cjs_1.createLogger)("cli");
|
|
28
29
|
const PACKAGE_NAME = "@sagentlab/navarch-runtime";
|
|
29
30
|
/** Accepted `--agent` ids as usage metavariables, generated from one source of truth. */
|
|
30
31
|
const AGENT_TYPE_USAGE = config_cjs_1.RUNTIME_AGENT_TYPES.join("|");
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
const CREDENTIALS_REJECTED_EXIT_CODE = 78;
|
|
32
|
+
// CREDENTIALS_REJECTED_EXIT_CODE (service.cts) is the exit code for "this
|
|
33
|
+
// machine's identity is gone". It is deliberately outside the supervisor's
|
|
34
|
+
// restart codes (75 update, 76 remote restart): respawning cannot fix a
|
|
35
|
+
// revoked or removed credential, so the supervisor must exit too, and an
|
|
36
|
+
// installed service must not restart it either.
|
|
37
37
|
/** Include a control-plane response's safe error detail in top-level CLI failures. */
|
|
38
38
|
function describeCliError(err) {
|
|
39
39
|
const message = err instanceof Error ? err.message : String(err);
|
|
@@ -132,6 +132,7 @@ function modelFromFlags(flags, agentType, identity) {
|
|
|
132
132
|
function parseArgs(argv) {
|
|
133
133
|
const [command, ...rest] = argv;
|
|
134
134
|
const flags = {};
|
|
135
|
+
const positionals = [];
|
|
135
136
|
for (let i = 0; i < rest.length; i++) {
|
|
136
137
|
const arg = rest[i];
|
|
137
138
|
if (arg?.startsWith("--")) {
|
|
@@ -145,8 +146,11 @@ function parseArgs(argv) {
|
|
|
145
146
|
flags[key] = "true";
|
|
146
147
|
}
|
|
147
148
|
}
|
|
149
|
+
else if (arg !== undefined) {
|
|
150
|
+
positionals.push(arg);
|
|
151
|
+
}
|
|
148
152
|
}
|
|
149
|
-
return { command: command ?? "help", flags };
|
|
153
|
+
return { command: command ?? "help", flags, positionals };
|
|
150
154
|
}
|
|
151
155
|
/**
|
|
152
156
|
* `navarch-runtime register` — the one command that prints the machine
|
|
@@ -224,7 +228,12 @@ async function connectCommand(flags) {
|
|
|
224
228
|
.map((s) => s.trim())
|
|
225
229
|
.filter(Boolean);
|
|
226
230
|
const agentType = agentFromFlag(flags) ?? config.agentType;
|
|
231
|
+
const installAsService = flags["install-service"] !== undefined;
|
|
227
232
|
modelFromFlags(flags, agentType); // Validate before consuming an enrollment token.
|
|
233
|
+
// Likewise refuse an impossible service request while the token is still unused.
|
|
234
|
+
const serviceOptions = installAsService ? serviceInstallOptions(flags, config.configDir) : undefined;
|
|
235
|
+
if (installAsService)
|
|
236
|
+
(0, service_cjs_1.serviceManagerFor)(process.platform);
|
|
228
237
|
const client = new api_cjs_1.NavarchApiClient({ baseUrl: apiBase });
|
|
229
238
|
const result = await client.connectMachine({
|
|
230
239
|
enrollment_token: enrollmentToken,
|
|
@@ -246,7 +255,123 @@ async function connectCommand(flags) {
|
|
|
246
255
|
console.log("Machine connected.");
|
|
247
256
|
console.log(` machine_id: ${result.machine_id}`);
|
|
248
257
|
console.log(` token: ${result.token}`);
|
|
249
|
-
|
|
258
|
+
if (!serviceOptions) {
|
|
259
|
+
console.log(`\nStored in ${config.configDir}/machine.json (mode 0600). Run \`${superviseInvocation(config.configDir)}\` to begin serving tasks.`);
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
console.log(`\nStored in ${config.configDir}/machine.json (mode 0600).\n`);
|
|
263
|
+
try {
|
|
264
|
+
await installAndReportService(serviceOptions);
|
|
265
|
+
}
|
|
266
|
+
catch (err) {
|
|
267
|
+
// The enrollment token is spent, so point at the one step left to retry.
|
|
268
|
+
throw new Error(`The machine is connected, but its service was not installed: ${describeCliError(err)} ` +
|
|
269
|
+
`Do not run \`connect\` again. Fix the cause, then run \`${serviceInvocation("install", config.configDir)}\`, ` +
|
|
270
|
+
`or run \`${superviseInvocation(config.configDir)}\` in a terminal.`);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
function serviceInvocation(action, configDir) {
|
|
274
|
+
return `${invocation(`service ${action}`)} --config-dir ${configDir}`;
|
|
275
|
+
}
|
|
276
|
+
/** The config directory for `service`, resolved without loading adapter config. */
|
|
277
|
+
function serviceConfigDir(flags) {
|
|
278
|
+
return node_path_1.default.resolve(flags["config-dir"] ?? process.env.NAVARCH_CONFIG_DIR ?? node_path_1.default.join(node_os_1.default.homedir(), ".navarch"));
|
|
279
|
+
}
|
|
280
|
+
function serviceInstallOptions(flags, configDir) {
|
|
281
|
+
const stopTimeout = flags["stop-timeout"];
|
|
282
|
+
return {
|
|
283
|
+
configDir,
|
|
284
|
+
serviceName: flags["service-name"],
|
|
285
|
+
extraEnv: (flags.env ?? "").split(",").map((name) => name.trim()).filter(Boolean),
|
|
286
|
+
stopTimeoutSeconds: stopTimeout === undefined ? undefined : Number(stopTimeout),
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
function describeServiceState(status) {
|
|
290
|
+
if (status.pid !== null)
|
|
291
|
+
return `running (pid ${status.pid})`;
|
|
292
|
+
return status.lastExitCode === null ? status.state : `${status.state} (last exit code ${status.lastExitCode})`;
|
|
293
|
+
}
|
|
294
|
+
function serviceLogHint(status) {
|
|
295
|
+
return status.logPath ?? `journalctl --user -u ${status.id} -f`;
|
|
296
|
+
}
|
|
297
|
+
async function installAndReportService(options) {
|
|
298
|
+
const installed = await (0, service_cjs_1.installService)(options);
|
|
299
|
+
console.log(`Service installed: ${installed.id} (${installed.manager})`);
|
|
300
|
+
console.log(` definition: ${installed.definitionPath}`);
|
|
301
|
+
console.log(` environment: ${installed.envFile}`);
|
|
302
|
+
console.log(` logs: ${serviceLogHint(installed)}`);
|
|
303
|
+
if (installed.started) {
|
|
304
|
+
// Loading a service is not the same as it staying up: give the supervisor
|
|
305
|
+
// a moment, then report what the service manager actually sees.
|
|
306
|
+
await new Promise((resolve) => setTimeout(resolve, 2_000));
|
|
307
|
+
const status = await (0, service_cjs_1.serviceStatus)(options);
|
|
308
|
+
console.log(` state: ${describeServiceState(status)}`);
|
|
309
|
+
if (status.pid === null) {
|
|
310
|
+
log.warn(`the service is not running; check ${serviceLogHint(installed)}`);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
else {
|
|
314
|
+
console.log(" state: not started");
|
|
315
|
+
}
|
|
316
|
+
console.log(installed.startsAtBoot
|
|
317
|
+
? "\nIt starts at boot and restarts after a crash."
|
|
318
|
+
: "\nIt starts when this user logs in and restarts after a crash.");
|
|
319
|
+
if (installed.manager === "launchd") {
|
|
320
|
+
console.log("For a Mac that must come back unattended after a restart, turn on automatic login for this user " +
|
|
321
|
+
"(System Settings → Users & Groups).");
|
|
322
|
+
}
|
|
323
|
+
for (const note of installed.notes)
|
|
324
|
+
console.log(note);
|
|
325
|
+
if (installed.missingEnv.length > 0) {
|
|
326
|
+
log.warn(`--env named variables that are not set in this shell: ${installed.missingEnv.join(", ")}`);
|
|
327
|
+
}
|
|
328
|
+
if (installed.uncapturedCredentials.length > 0) {
|
|
329
|
+
const names = installed.uncapturedCredentials.join(",");
|
|
330
|
+
console.log(`\nSet in this shell but not copied into the service: ${installed.uncapturedCredentials.join(", ")}. ` +
|
|
331
|
+
`If the coding agent relies on them, re-run \`${serviceInvocation("install", options.configDir)} --env ${names}\`.`);
|
|
332
|
+
}
|
|
333
|
+
console.log(`\nStop any \`supervise\` you started by hand for ${options.configDir}: two processes must never serve one agent.`);
|
|
334
|
+
console.log(`Check it with \`${serviceInvocation("status", options.configDir)}\`; remove it with \`${serviceInvocation("uninstall", options.configDir)}\`.`);
|
|
335
|
+
}
|
|
336
|
+
/** `navarch-runtime service install|restart|uninstall|status` — run `supervise` under launchd or systemd. */
|
|
337
|
+
async function serviceCommand(action, flags) {
|
|
338
|
+
const configDir = serviceConfigDir(flags);
|
|
339
|
+
const options = { configDir, serviceName: flags["service-name"] };
|
|
340
|
+
switch (action) {
|
|
341
|
+
case "install":
|
|
342
|
+
await installAndReportService(serviceInstallOptions(flags, configDir));
|
|
343
|
+
return;
|
|
344
|
+
case "restart": {
|
|
345
|
+
const restarted = await (0, service_cjs_1.restartService)(options);
|
|
346
|
+
console.log(restarted.started ? `Service restarted: ${restarted.id}` : `Service not started: ${restarted.id}`);
|
|
347
|
+
for (const note of restarted.notes)
|
|
348
|
+
console.log(note);
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
case "uninstall": {
|
|
352
|
+
const removed = await (0, service_cjs_1.uninstallService)(options);
|
|
353
|
+
console.log(removed.removed
|
|
354
|
+
? `Service removed: ${removed.id}. ${configDir} and its machine identity were left in place.`
|
|
355
|
+
: `No service is installed for ${configDir} (${removed.definitionPath} does not exist).`);
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
case "status": {
|
|
359
|
+
const status = await (0, service_cjs_1.serviceStatus)(options);
|
|
360
|
+
console.log(`service: ${status.id} (${status.manager})`);
|
|
361
|
+
console.log(`definition: ${status.installed ? status.definitionPath : `not installed — run \`${serviceInvocation("install", configDir)}\``}`);
|
|
362
|
+
console.log(`state: ${describeServiceState(status)}`);
|
|
363
|
+
if (status.halted) {
|
|
364
|
+
console.log(`halted: ${status.halted.at} — ${status.halted.reason}`);
|
|
365
|
+
}
|
|
366
|
+
console.log(`logs: ${serviceLogHint(status)}`);
|
|
367
|
+
// Scripts can test the exit status: 0 only while the service is running.
|
|
368
|
+
if (status.pid === null)
|
|
369
|
+
process.exitCode = 1;
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
default:
|
|
373
|
+
throw new Error("Usage: navarch-runtime service install|restart|uninstall|status [--config-dir <path>]");
|
|
374
|
+
}
|
|
250
375
|
}
|
|
251
376
|
async function startCommand(flags) {
|
|
252
377
|
const baseConfig = configFromFlags(flags);
|
|
@@ -309,8 +434,12 @@ async function startCommand(flags) {
|
|
|
309
434
|
log.error(status === 410
|
|
310
435
|
? `agent ${identity.name} has been removed from the fleet; it can no longer claim tasks.`
|
|
311
436
|
: `machine credentials for ${identity.name} were rejected by ${identity.api_base}; it can no longer claim tasks.`);
|
|
437
|
+
// Under an installed service the way back is to reinstall it, not to
|
|
438
|
+
// start a second, foreground supervisor beside it.
|
|
312
439
|
log.error(`Re-enroll this machine with a fresh "Connect an agent" token, then run ` +
|
|
313
|
-
|
|
440
|
+
(process.env[service_cjs_1.SERVICE_ENV]
|
|
441
|
+
? `\`${serviceInvocation("install", config.configDir)}\`.`
|
|
442
|
+
: `\`${superviseInvocation(config.configDir)}\` again.`));
|
|
314
443
|
// Removal/revocation is terminal: stop detached agent process groups so
|
|
315
444
|
// a provider-side hang cannot keep consuming local resources forever.
|
|
316
445
|
// runSession checkpoints or retains the worktree before releasing its
|
|
@@ -319,7 +448,7 @@ async function startCommand(flags) {
|
|
|
319
448
|
// Mirror warming can outlive its conversation's capacity slot. Wait for
|
|
320
449
|
// its killed process and private-cache cleanup before exiting too.
|
|
321
450
|
void Promise.all([capacity.waitForIdle(), conversationLoop.drain()])
|
|
322
|
-
.then(() => process.exit(CREDENTIALS_REJECTED_EXIT_CODE));
|
|
451
|
+
.then(() => process.exit(service_cjs_1.CREDENTIALS_REJECTED_EXIT_CODE));
|
|
323
452
|
}, browserProbe);
|
|
324
453
|
updateCoordinatorRef.current = new update_coordinator_cjs_1.RuntimeUpdateCoordinator({
|
|
325
454
|
config,
|
|
@@ -379,6 +508,17 @@ async function superviseCommand(flags) {
|
|
|
379
508
|
NAVARCH_MACHINE_NAME: identity.name,
|
|
380
509
|
NAVARCH_API_BASE: identity.api_base,
|
|
381
510
|
});
|
|
511
|
+
const serviceManager = process.env[service_cjs_1.SERVICE_ENV];
|
|
512
|
+
if (exitCode === service_cjs_1.CREDENTIALS_REJECTED_EXIT_CODE && serviceManager) {
|
|
513
|
+
const reason = `Navarch rejected the credentials for ${identity.name}; the agent was removed or its token revoked.`;
|
|
514
|
+
await (0, service_cjs_1.writeServiceHalt)(config.configDir, reason).catch(() => undefined);
|
|
515
|
+
log.error(`service halted and will not be restarted: ${reason}`);
|
|
516
|
+
// systemd exempts this status from Restart= itself. launchd can only tell
|
|
517
|
+
// success from failure, so report success to stop it restarting a
|
|
518
|
+
// supervisor that can never authenticate.
|
|
519
|
+
process.exitCode = serviceManager === "launchd" ? 0 : exitCode;
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
382
522
|
process.exitCode = exitCode;
|
|
383
523
|
}
|
|
384
524
|
async function doctorCommand(flags) {
|
|
@@ -440,9 +580,12 @@ Usage:
|
|
|
440
580
|
navarch-runtime register --token <enrollment-token> --name <machine-name> \\
|
|
441
581
|
[--config-dir <path>] [--agent ${AGENT_TYPE_USAGE}] [--model <model>] [--capabilities a,b] [--max-sessions N] [--owner-zone z] [--api-base url]
|
|
442
582
|
navarch-runtime connect --token <enrollment-token> --name <machine-name> \\
|
|
443
|
-
[--config-dir <path>] [--agent ${AGENT_TYPE_USAGE}] [--model <model>] [--project <project-id>] [--capabilities a,b] [--max-sessions N] [--api-base url]
|
|
583
|
+
[--config-dir <path>] [--agent ${AGENT_TYPE_USAGE}] [--model <model>] [--project <project-id>] [--capabilities a,b] [--max-sessions N] [--api-base url] \\
|
|
584
|
+
[--install-service]
|
|
444
585
|
navarch-runtime start [--config-dir <path>] [--agent ${AGENT_TYPE_USAGE}] [--model <model>]
|
|
445
|
-
navarch-runtime supervise [--config-dir <path>] [--agent ${AGENT_TYPE_USAGE}] [--model <model>]
|
|
586
|
+
navarch-runtime supervise [--config-dir <path>] [--agent ${AGENT_TYPE_USAGE}] [--model <model>] [--env-file <path>]
|
|
587
|
+
navarch-runtime service install [--config-dir <path>] [--service-name <name>] [--env NAME,NAME] [--stop-timeout <seconds>]
|
|
588
|
+
navarch-runtime service restart|uninstall|status [--config-dir <path>] [--service-name <name>]
|
|
446
589
|
navarch-runtime doctor [--config-dir <path>] [--agent ${AGENT_TYPE_USAGE}]
|
|
447
590
|
navarch-runtime browser-install
|
|
448
591
|
navarch-runtime code-graph --query <symbol-or-file> [--mode search|callers|callees|impact] [--commit HEAD] [--depth 1..5] [--repo <path>]
|
|
@@ -452,8 +595,13 @@ Other configuration is via NAVARCH_* environment variables; see runtime/README.m
|
|
|
452
595
|
`;
|
|
453
596
|
}
|
|
454
597
|
async function main(argv = process.argv.slice(2)) {
|
|
455
|
-
const { command, flags } = parseArgs(argv);
|
|
598
|
+
const { command, flags, positionals } = parseArgs(argv);
|
|
456
599
|
try {
|
|
600
|
+
// An installed service starts with a bare environment; its saved one must
|
|
601
|
+
// be in place before any configuration is read.
|
|
602
|
+
if ((command === "supervise" || command === "start") && flags["env-file"]) {
|
|
603
|
+
await (0, service_cjs_1.applyServiceEnvFile)(node_path_1.default.resolve(flags["env-file"]));
|
|
604
|
+
}
|
|
457
605
|
switch (command) {
|
|
458
606
|
case "register":
|
|
459
607
|
await registerCommand(flags);
|
|
@@ -467,6 +615,9 @@ async function main(argv = process.argv.slice(2)) {
|
|
|
467
615
|
case "supervise":
|
|
468
616
|
await superviseCommand(flags);
|
|
469
617
|
break;
|
|
618
|
+
case "service":
|
|
619
|
+
await serviceCommand(positionals[0], flags);
|
|
620
|
+
break;
|
|
470
621
|
case "code-graph": {
|
|
471
622
|
const { codeGraphCommand } = await import("./code-graph.cjs");
|
|
472
623
|
console.log(JSON.stringify(codeGraphCommand(flags), null, 2));
|
package/dist/local-browser.cjs
CHANGED
|
@@ -7,6 +7,7 @@ exports.registerLocalBrowserTools = registerLocalBrowserTools;
|
|
|
7
7
|
const node_net_1 = require("node:net");
|
|
8
8
|
const playwright_1 = require("playwright");
|
|
9
9
|
const zod_1 = require("zod");
|
|
10
|
+
const version_cjs_1 = require("./version.cjs");
|
|
10
11
|
/**
|
|
11
12
|
* Interactive browser for services the agent starts on this machine.
|
|
12
13
|
*
|
|
@@ -102,7 +103,7 @@ function createLocalBrowser(options) {
|
|
|
102
103
|
browser ??= await options.launch();
|
|
103
104
|
}
|
|
104
105
|
catch {
|
|
105
|
-
throw new Error(
|
|
106
|
+
throw new Error(`The local browser could not start. On the agent host run \`${version_cjs_1.BROWSER_INSTALL_COMMAND}\`.`);
|
|
106
107
|
}
|
|
107
108
|
const created = await browser.newContext({
|
|
108
109
|
...(wanted === "mobile" ? playwright_1.devices["iPhone 13"] : { viewport: { width: 1440, height: 900 } }),
|
package/dist/service.cjs
ADDED
|
@@ -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, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
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
|
+
}
|
package/dist/version.cjs
CHANGED
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.UPDATER_PROTOCOL_VERSION = exports.RUNTIME_VERSION = void 0;
|
|
3
|
+
exports.BROWSER_INSTALL_COMMAND = exports.UPDATER_PROTOCOL_VERSION = exports.RUNTIME_VERSION = void 0;
|
|
4
4
|
// package.json is always included in an npm package, even though the runtime's
|
|
5
5
|
// explicit `files` allowlist only names dist/bin/README.
|
|
6
6
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
7
7
|
const packageJson = require("../package.json");
|
|
8
8
|
exports.RUNTIME_VERSION = typeof packageJson.version === "string" ? packageJson.version : "0.0.0-unknown";
|
|
9
9
|
exports.UPDATER_PROTOCOL_VERSION = 1;
|
|
10
|
+
/**
|
|
11
|
+
* Command shown wherever the runtime's Chromium is missing. `navarch-runtime`
|
|
12
|
+
* is only on PATH after a global install, so name the package through npx.
|
|
13
|
+
* The version pin matters: Playwright is pinned per runtime release, and each
|
|
14
|
+
* Playwright version wants its own Chromium build.
|
|
15
|
+
*/
|
|
16
|
+
exports.BROWSER_INSTALL_COMMAND = `npx @sagentlab/navarch-runtime@${exports.RUNTIME_VERSION} browser-install`;
|
package/package.json
CHANGED