@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.
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
@@ -580,13 +658,13 @@ unchanged across the deployment.
580
658
  | `NAVARCH_CODEX_BIN` | `codex` | Path/name of the Codex CLI binary. |
581
659
  | `NAVARCH_CODEX_EXTRA_ARGS` | — | Comma list of extra CLI args appended after the generated MCP `-c` overrides and `--json` (Codex). |
582
660
  | `NAVARCH_ANTIGRAVITY_BIN` | `agy` | Path/name of the Antigravity CLI binary, version 1.3.1+. |
583
- | `NAVARCH_ANTIGRAVITY_EXTRA_ARGS` | — | Comma list: only `--agent`, `--model`, `--effort`, `--sandbox`, `--dangerously-skip-permissions`; protocol, deadline and resume flags are owned by Navarch. |
661
+ | `NAVARCH_ANTIGRAVITY_EXTRA_ARGS` | — | Comma list: only `--agent`, `--model`, `--effort` (`low` to `max`), `--sandbox`, `--dangerously-skip-permissions`; protocol, deadline and resume flags are owned by Navarch. A `--model` here must match the model the project or task selects, or the session fails. |
584
662
  | `NAVARCH_OPENCODE_BIN` | `opencode` | Path/name of the OpenCode CLI binary. |
585
663
  | `NAVARCH_OPENCODE_EXTRA_ARGS` | — | Comma list of extra CLI args appended after `run`, the prompt, and the generated `--format json` argument. Explicit `--format`, `--model`, or `--variant` values replace the corresponding per-session default. |
586
664
  | `NAVARCH_ACP_BIN` | `dsh` | Path/name of an Agent Client Protocol v1 stdio server. DeepSeek Harness is the default implementation. |
587
665
  | `NAVARCH_ACP_EXTRA_ARGS` | `--profile,acp` | Comma list of arguments used to start the ACP server. Override this together with `NAVARCH_ACP_BIN` for another ACP-compatible coding agent. |
588
666
  | `NAVARCH_QODER_BIN` | `qoder` | Path/name of the Qoder CLI binary. |
589
- | `NAVARCH_QODER_EXTRA_ARGS` | — | Comma list of extra CLI args appended after the unattended defaults (`--setting-sources`, `--permission-mode auto`, `--output-format json`). An explicit `--output-format`, `--permission-mode`, `--settings`, `--model`, or `--reasoning-effort` here replaces the per-session default. Qoder selects its own account models; pin one via `--model` here or `connect --model` to override. |
667
+ | `NAVARCH_QODER_EXTRA_ARGS` | — | Comma list of extra CLI args appended after the unattended defaults (`--setting-sources`, `--permission-mode auto`, `--output-format json`). An explicit `--output-format`, `--permission-mode`, `--settings`, `--model`, or `--reasoning-effort` here replaces the per-session default. Qoder selects its own account models unless the project or a task names one; `--model` here or `connect --model` pins one for this machine. |
590
668
  | `NAVARCH_MUSE_BIN` | `muse` | Path/name of the native Muse Code CLI. Requires authenticated experimental `muse serve` SDK access; the npm SDK does not install the CLI. See [Muse Code setup](../docs/navarch/muse-code.md). |
591
669
  | `NAVARCH_MUSE_EXTRA_ARGS` | — | Comma list of arguments passed to `muse serve`. Permission/sandbox bypass flags are rejected. Configure narrow native approval rules rather than enabling blanket approval. |
592
670
  | `NAVARCH_MCP_CONFIG_PATH` | — | Path to the platform MCP config passed as `--mcp-config`. |
@@ -809,8 +887,8 @@ export NAVARCH_AGENT=opencode
809
887
  export NAVARCH_AGENT=acp
810
888
 
811
889
  # Qoder — requires an authenticated `qoder` CLI (or NAVARCH_QODER_BIN pointing
812
- # at it). Model selection is account-owned; NAVARCH_QODER_EXTRA_ARGS or
813
- # `connect --model` can pin one explicitly.
890
+ # at it). The model comes from the project setting (default: the account's own
891
+ # selection); NAVARCH_QODER_EXTRA_ARGS or `connect --model` pins one here.
814
892
  export NAVARCH_AGENT=qoder
815
893
 
816
894
  # Muse Code (experimental, runtime 0.1.117+) — see the dedicated setup
@@ -849,14 +927,17 @@ profile on every claim. The runtime passes those values as per-session CLI
849
927
  overrides (`codex exec --model ... -c model_reasoning_effort=...`,
850
928
  `claude -p --model ... --effort ...`, `agy --model ...`, or `opencode run
851
929
  --model ... --variant ...`) and records the effective model, profile, and
852
- effort on completion. Antigravity uses the `default` sentinel to preserve the CLI account model;
853
- explicit low/medium/high effort is supported without inventing higher levels. OpenCode accepts any `provider/model`
930
+ effort on completion. Antigravity, Qoder, Muse Code and ACP use the `default` sentinel to keep the
931
+ agent's own model until the project or a task names one; an Antigravity slug carries its effort
932
+ level, so no separate effort is sent, and an ACP model the agent does not advertise fails the
933
+ session before the first prompt. OpenCode accepts any `provider/model`
854
934
  reference (the platform default is `opencode/x-preview-f-free`, Ox Alpha Free
855
935
  (Unlimited) on OpenCode Zen), or `default` to preserve the authenticated
856
- account's selection. ACP sessions use the agent's advertised default model and
857
- set the standard `reasoning_effort` configuration option when it is available.
858
- Muse uses the account-owned `default` model; Navarch adds no Muse project-model
859
- column or public model catalog. Its SDK integration is experimental and has no
936
+ account's selection. ACP sessions select a named model through the agent's
937
+ advertised model option and set the standard `reasoning_effort` configuration
938
+ option when it is available.
939
+ Muse uses the account-owned `default` model unless the project names a
940
+ `modelId`; there is no public model catalog. Its SDK integration is experimental and has no
860
941
  Navi conversation capability. Read [Muse Code setup and limitations](../docs/navarch/muse-code.md)
861
942
  before using private repositories, especially Muse Contributor data settings.
862
943
  Machine-wide extra arguments still configure other CLI behavior; dispatched
@@ -1247,7 +1328,8 @@ repositories without changing the query format.
1247
1328
  machine identity. `start` and `supervise` reuse that model, including after worker
1248
1329
  restarts. Their optional `--model` flag overrides the saved choice. The pin wins
1249
1330
  over the project's session model for the selected adapter only; switching agent
1250
- types does not reuse another adapter's pin. Reconnect without `--model` to return
1331
+ types does not reuse another adapter's pin. A model pinned on the task itself
1332
+ wins over the machine pin (runtime 0.1.187+). Reconnect without `--model` to return
1251
1333
  to project-controlled model selection. Older identities without a model keep
1252
1334
  using the control-plane execution policy.
1253
1335
 
@@ -158,7 +158,10 @@ async function runAcpAdapter(options) {
158
158
  });
159
159
  sessionId = created.sessionId;
160
160
  let configOptions = created.configOptions ?? [];
161
- configOptions = await setConfigOption(context, acp.methods.agent.session.setConfigOption, sessionId, configOptions, "model", options.model === "default" ? undefined : options.model);
161
+ configOptions = await setConfigOption(context, acp.methods.agent.session.setConfigOption, sessionId, configOptions, "model", options.model === "default" ? undefined : options.model,
162
+ // A named model is an explicit selection: running the agent's own
163
+ // default instead would be a silent substitution.
164
+ true);
162
165
  await setConfigOption(context, acp.methods.agent.session.setConfigOption, sessionId, configOptions, "reasoning_effort", options.reasoningEffort);
163
166
  // The probe saw protocol v1; an agent that now answers another version
164
167
  // takes no interrupt, which then waits for the turn boundary.
@@ -266,19 +269,34 @@ function collectUpdate(notification, messages, thoughts, setCostUsd) {
266
269
  setCostUsd(update.cost.amount);
267
270
  }
268
271
  }
269
- async function setConfigOption(context, method, sessionId, options, configId, desired) {
272
+ async function setConfigOption(context, method, sessionId, options, configId, desired,
273
+ /** Fail the session when the agent cannot apply `desired`, instead of keeping its own value. */
274
+ required = false) {
270
275
  if (!desired)
271
276
  return options;
272
277
  const expectedCategory = configId === "model" ? "model" : "thought_level";
273
278
  const option = options.find((candidate) => ((candidate.id === configId || candidate.category === expectedCategory)
274
279
  && candidate.type === "select"));
275
- if (!option || option.type !== "select")
280
+ if (!option || option.type !== "select") {
281
+ if (required) {
282
+ throw new Error(`The ACP agent offers no selectable ${configId}, so the selected ${configId} "${desired}" cannot be applied. `
283
+ + `Set the project's ACP agent model to default, or connect an agent that advertises it.`);
284
+ }
276
285
  return options;
286
+ }
277
287
  const choices = option.options.flatMap((candidate) => "group" in candidate ? candidate.options : [candidate]);
278
288
  const selected = choices.find((candidate) => candidate.value === desired || candidate.name === desired);
279
- if (!selected || selected.value === option.currentValue)
289
+ if (!selected) {
290
+ if (required) {
291
+ const offered = choices.slice(0, 20).map((candidate) => candidate.value).join(", ");
292
+ throw new Error(`The ACP agent does not offer ${configId} "${desired}". It offers: ${offered || "none"}${choices.length > 20 ? ", …" : ""}. `
293
+ + `Select one of these, or set the project's ACP agent model to default.`);
294
+ }
295
+ return options;
296
+ }
297
+ if (selected.value === option.currentValue)
280
298
  return options;
281
- const response = await context.request(method, { sessionId, configId, value: selected.value });
299
+ const response = await context.request(method, { sessionId, configId: option.id, value: selected.value });
282
300
  return response.configOptions ?? options;
283
301
  }
284
302
  async function readMcpServers(configPath, env) {
@@ -16,7 +16,10 @@ const antigravity_mcp_cjs_1 = require("./antigravity-mcp.cjs");
16
16
  const types_cjs_1 = require("./types.cjs");
17
17
  /** Documented agy 1.3.1 contract, not Gemini CLI's similarly named format.
18
18
  * https://antigravity.google/docs/cli/headless/
19
- * https://antigravity.google/docs/changelog (1.1.27, 1.1.28, 1.2.6, 1.2.10)
19
+ * https://antigravity.google/docs/changelog (1.1.27, 1.1.28, 1.2.6, 1.2.10, 1.2.11)
20
+ * `--model` takes a slug from `agy models`; headless mode exits non-zero on an
21
+ * unknown one instead of falling back. `--effort` is low to max "depending on
22
+ * the model", so the CLI, not this adapter, decides which levels a model takes.
20
23
  * One stdin user event + EOF per process; later lease-local turns may resume
21
24
  * only the exact validated AG conversation. No interactive approval protocol.
22
25
  */
@@ -118,13 +121,13 @@ function antigravityArgs(options) {
118
121
  }
119
122
  const model = options.model && options.model !== "default" ? options.model : values.get("--model");
120
123
  if (values.has("--model") && options.model && options.model !== "default" && values.get("--model") !== options.model)
121
- return "Antigravity model arguments conflict with the selected execution model.";
124
+ return `Antigravity model arguments conflict: NAVARCH_ANTIGRAVITY_EXTRA_ARGS names ${values.get("--model")} but the selected execution model is ${options.model}. Remove --model from the extra arguments or select the same model.`;
122
125
  if (model)
123
126
  values.set("--model", model);
124
127
  const effort = options.reasoningEffort ?? values.get("--effort");
125
128
  if (effort) {
126
- if (!["low", "medium", "high"].includes(effort))
127
- return "Antigravity supports low, medium or high reasoning effort only.";
129
+ if (!["low", "medium", "high", "xhigh", "max"].includes(effort))
130
+ return "Antigravity reasoning effort must be low, medium, high, xhigh or max.";
128
131
  if (values.has("--effort") && values.get("--effort") !== effort)
129
132
  return "Antigravity reasoning effort arguments conflict.";
130
133
  values.set("--effort", effort);
@@ -20,10 +20,10 @@ function hasFlag(args, flag) {
20
20
  * parseClaudeJsonResult and its result text lands in the ordinary
21
21
  * exit-conditions path.
22
22
  *
23
- * Model selection is account-owned (`qoder --list-models`), so the claim-time
23
+ * The catalog is account-owned (`qoder --list-models`), so the claim-time
24
24
  * `"default"` sentinel (execution-policy.ts / session.cts) is passed through
25
- * as no `--model` flag; an explicit pin from `--model` at enroll or
26
- * NAVARCH_QODER_EXTRA_ARGS still reaches the CLI.
25
+ * as no `--model` flag; a model named by the project, a task pin, `--model` at
26
+ * enroll or NAVARCH_QODER_EXTRA_ARGS reaches the CLI.
27
27
  */
28
28
  async function runQoderAdapter(options) {
29
29
  if (options.signal?.aborted) {
@@ -52,8 +52,21 @@ async function runQoderAdapter(options) {
52
52
  args.push("--output-format", "json");
53
53
  }
54
54
  args.push(...options.extraArgs);
55
- if (options.model && options.model !== "default" && !hasFlag(options.extraArgs, "--model")) {
56
- args.push("--model", options.model);
55
+ if (options.model && options.model !== "default") {
56
+ const model = options.model;
57
+ const modelArgs = options.extraArgs.flatMap((arg, index) => arg === "--model" ? [options.extraArgs[index + 1]]
58
+ : arg.startsWith("--model=") ? [arg.slice("--model=".length)] : []);
59
+ if (modelArgs.some((value) => value !== model)) {
60
+ return {
61
+ exitCode: 1,
62
+ timedOut: false,
63
+ killedByLeaseLoss: false,
64
+ stdout: "",
65
+ stderr: `Qoder model arguments conflict with the selected model ${model}. Remove --model from NAVARCH_QODER_EXTRA_ARGS or select the same model.`,
66
+ };
67
+ }
68
+ if (modelArgs.length === 0)
69
+ args.push("--model", model);
57
70
  }
58
71
  if (options.reasoningEffort && !hasFlag(options.extraArgs, "--reasoning-effort")) {
59
72
  args.push("--reasoning-effort", options.reasoningEffort);
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
- * Exit code for "this machine's identity is gone". Deliberately outside the
33
- * supervisor's restart codes (75 update, 76 remote restart): respawning cannot
34
- * fix a revoked or removed credential, so the supervisor must exit too.
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
- console.log(`\nStored in ${config.configDir}/machine.json (mode 0600). Run \`${superviseInvocation(config.configDir)}\` to begin serving tasks.`);
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
- `\`${superviseInvocation(config.configDir)}\` again.`);
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));