@parcha/agentrun 0.4.14 → 0.4.15

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/lib/service.mjs CHANGED
@@ -3,13 +3,14 @@
3
3
  // unit on Linux; never a system service, never sudo. The service runs the installer's command (~/.agentrun/bin/agentrun,
4
4
  // install.sh), which brings its own Node, with --no-open and the interactive launcher's rules for the data directory and
5
5
  // port, and writes to ~/.agentrun/logs/agentrun.log. With --tailscale it is also served on the person's tailnet
6
- // (tailscale.mjs); with --env, on a local model (MODEL_ENV). `agentrun stop` stops the AgentRun the installer starts in the
6
+ // (tailscale.mjs); with --env, on a local model or with a start-time switch on (SERVICE_ENV). `agentrun stop` stops the AgentRun the installer starts in the
7
7
  // background where there is no service manager (a container): its pid is in ~/.agentrun/agentrun.pid.
8
- import { spawnSync } from "node:child_process";
8
+ import { spawn, spawnSync } from "node:child_process";
9
9
  import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
10
10
  import { homedir, userInfo } from "node:os";
11
11
  import { join, resolve } from "node:path";
12
12
  import { fileURLToPath } from "node:url";
13
+ import { publicUrlOf } from "./public-url.mjs";
13
14
  import { TAILNET_PORT, tailnetOf, targetOf } from "./tailscale.mjs";
14
15
 
15
16
  export const LABEL = "ai.agentrun.server";
@@ -110,9 +111,29 @@ export const unitArgs = (text) => systemdWords(/^ExecStart=(.*)$/m.exec(text)?.[
110
111
  export const unitEnv = (text) =>
111
112
  Object.fromEntries([...text.matchAll(/^Environment=(.*)$/gm)].map((match) => systemdWords(match[1])[0] ?? "").map((pair) => [pair.slice(0, pair.indexOf("=")), pair.slice(pair.indexOf("=") + 1)]));
112
113
 
113
- /** The variables `service install --env` sets: a local model's (AGENT_MODEL_BASE_URL in front of a gateway such as
114
- * Ollama's). Never a key: a unit file is plain text, and keys are sealed in the console. */
115
- export const MODEL_ENV = ["AGENT_MODEL_BASE_URL", "AGENT_MODEL_GATEWAY_IDS", "AGENT_MODEL", "AGENT_MODEL_PRICE"];
114
+ /** The variables `service install --env` sets, and an installed service keeps through a re-install: each name, with the
115
+ * values it takes alone, or null for any value. `KEY=` removes one. Never a model key: a unit file is plain text, and keys
116
+ * are sealed in the console.
117
+ * - A local model's (AGENT_MODEL_BASE_URL in front of a gateway such as Ollama's), and its key at `none`: a server that
118
+ * holds no key for its gateway refuses each run that brings none (run-model-key.ts, model_key_required).
119
+ * - The start-time switches (the server's start-switches.ts), on at `1` alone, for a machine its owner alone uses. A
120
+ * server reads them at its start, so the service restarts.
121
+ * - The usage counts' switches (docs/telemetry.md). A service never sees the shell that installed it, so install writes
122
+ * these into it as that shell set them, and AGENTRUN_TELEMETRY=0 under CI. */
123
+ export const SERVICE_ENV = {
124
+ AGENT_MODEL_BASE_URL: null,
125
+ AGENT_MODEL_GATEWAY_IDS: null,
126
+ AGENT_MODEL: null,
127
+ AGENT_MODEL_PRICE: null,
128
+ AGENT_MODEL_API_KEY: ["none"],
129
+ AGENTRUN_MCP_ALLOW_LOOPBACK: ["1"],
130
+ AGENTRUN_WEBHOOK_PRIVATE_TARGETS: ["1"],
131
+ AGENTRUN_TELEMETRY: null,
132
+ DO_NOT_TRACK: null,
133
+ };
134
+ const SERVICE_NAMES = Object.keys(SERVICE_ENV);
135
+ /** The usage counts' two switches in SERVICE_ENV, which install also copies from its own shell. */
136
+ const TELEMETRY_NAMES = ["AGENTRUN_TELEMETRY", "DO_NOT_TRACK"];
116
137
 
117
138
  const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
118
139
 
@@ -232,12 +253,29 @@ async function healthOf(data, { fetch: get = fetch, since = 0 } = {}) {
232
253
  try {
233
254
  const response = await get(`${record.base_url.replace(/\/+$/, "")}/health`, { signal: AbortSignal.timeout(3_000) });
234
255
  const body = await response.json().catch(() => ({}));
235
- return { url, health: response.ok && body?.status === "ok" ? "ok" : `${response.status} ${body?.status ?? ""}`.trim(), checks: body?.checks };
256
+ return { url, answered: true, health: response.ok && body?.status === "ok" ? "ok" : `${response.status} ${body?.status ?? ""}`.trim(), checks: body?.checks };
236
257
  } catch (error) {
237
- return { url, health: `not answering (${error?.cause?.code ?? error?.name})` };
258
+ return { url, answered: false, health: `not answering (${error?.cause?.code ?? error?.name})` };
238
259
  }
239
260
  }
240
261
 
262
+ /** Whether a browser can be opened here: not in CI, and on Linux or FreeBSD only with a display (serve's host.ts canOpen). */
263
+ export const canOpen = (env, platform) => !env.CI && (platform === "darwin" || (["linux", "freebsd"].includes(platform) && Boolean(env.DISPLAY || env.WAYLAND_DISPLAY)));
264
+ /** Starts `command` on `args` for the browser and leaves it running: an opener can stay in the foreground until the
265
+ * browser it starts closes, so nothing waits for its exit (serve's --open spawns it the same way). True once it started,
266
+ * false when it could not (no such command). */
267
+ export const launchOpener = (command, args, env) => new Promise((done) => {
268
+ const child = spawn(command, args, { env, stdio: "ignore", detached: true });
269
+ child.once("error", () => done(false));
270
+ child.once("spawn", () => {
271
+ child.unref();
272
+ done(true);
273
+ });
274
+ });
275
+ /** The newest setup link a server printed to `log` (`Set up this server: <link> ...`), or undefined. */
276
+ export const SETUP_LINE = /^Set up this server: (https?:\/\/\S+\/setup#code=[A-Za-z0-9_-]+)/;
277
+ const SETUP_TAIL = 2_000;
278
+
241
279
  /** The last `count` lines of a file, read back from its end only as far as they go: the log is appended to forever. */
242
280
  const tailOf = (file, count) => {
243
281
  if (count === 0) return [];
@@ -266,7 +304,7 @@ const tailOf = (file, count) => {
266
304
  };
267
305
 
268
306
  /** Every service command, given what it runs on; the entries below bind it to this machine. */
269
- export function serviceOf({ platform = process.platform, home = homedir(), uid = process.getuid?.(), user = userInfo().username, env = process.env, exec, io, fail, get = fetch, waitMs = HEALTH_WAIT_MS, kill = process.kill.bind(process), stopWaitMs = STOP_WAIT_MS }) {
307
+ export function serviceOf({ platform = process.platform, home = homedir(), uid = process.getuid?.(), user = userInfo().username, env = process.env, exec, io, fail, get = fetch, waitMs = HEALTH_WAIT_MS, kill = process.kill.bind(process), stopWaitMs = STOP_WAIT_MS, launch = launchOpener }) {
270
308
  exec ??= (command, args, options = {}) => spawnSync(command, args, { encoding: "utf8", ...options });
271
309
  const root = join(home, ".agentrun");
272
310
  const program = join(root, "bin", "agentrun");
@@ -284,9 +322,9 @@ export function serviceOf({ platform = process.platform, home = homedir(), uid =
284
322
  };
285
323
  const argsNow = () => manager.args(readFileSync(manager.file, "utf8")).slice(1);
286
324
 
287
- /** Waits for the server started at `since` to answer /health ok, then says where it is; exit 0, or 1 with the log's
288
- * last lines. */
289
- async function started(since, data) {
325
+ /** Waits for the server started at `since` to answer /health ok, then says where it is, runs `ready` and opens its
326
+ * setup page while it has no owner; exit 0, or 1 with the log's last lines. */
327
+ async function started(since, data, ready = () => {}) {
290
328
  const deadline = Date.now() + waitMs;
291
329
  let last = {};
292
330
  while (Date.now() < deadline) {
@@ -295,6 +333,10 @@ export function serviceOf({ platform = process.platform, home = homedir(), uid =
295
333
  say(`AgentRun is running at ${last.url} (${manager.name}).`);
296
334
  say(`Logs: ${log}`);
297
335
  for (const note of manager.notes()) say(note);
336
+ // The tailnet's serve entry first: the setup link names that address.
337
+ ready();
338
+ // A server with no owner yet: its setup page, open in the browser with the code filled in.
339
+ await openPage(data, { setupOnly: true, url: last.url });
298
340
  return 0;
299
341
  }
300
342
  await new Promise((done) => setTimeout(done, 500));
@@ -305,34 +347,122 @@ export function serviceOf({ platform = process.platform, home = homedir(), uid =
305
347
  return 1;
306
348
  }
307
349
 
350
+ /** The newest setup link in the service's log. */
351
+ const newestSetup = () => {
352
+ for (const line of tailOf(log, SETUP_TAIL).reverse()) {
353
+ const found = SETUP_LINE.exec(line);
354
+ if (found) return found[1];
355
+ }
356
+ return undefined;
357
+ };
358
+
359
+ /** `agentrun open`, and the end of a start: the page to open first, in this machine's browser. With no owner yet, the
360
+ * setup page: its code filled in when setup takes one (a code still good is kept; an expired or spent one is replaced
361
+ * first, as the page's Get a new code does), or `/setup` where setup takes none. With an owner, the console, unless
362
+ * `setupOnly`. The link is printed for the person at this terminal as well, for when no browser opens (an opener can
363
+ * start and still find none): theirs to open, and a setup code works once and for 30 minutes, unlike the API token,
364
+ * which never leaves its file. The code comes from the log the service (or the installer's background start) writes,
365
+ * so only for the data folder that log is for: another server prints its own elsewhere. Exit 0, or 1 when no server
366
+ * answers. */
367
+ async function openPage(data, { setupOnly = false, url = undefined } = {}) {
368
+ let unwell;
369
+ if (url === undefined) {
370
+ // A record a crash or a forced stop left behind names an address no server answers. A server that answers with a
371
+ // failed check (low disk is a 503) still serves its console and its setup page: it opens, and the check is said.
372
+ const now = await healthOf(data, { fetch: get });
373
+ if (now.answered) url = now.url;
374
+ if (now.answered && now.health !== "ok") {
375
+ const failing = Object.entries(now.checks ?? {}).filter(([, value]) => value !== "ok").map(([name, value]) => `${name}: ${value}`);
376
+ unwell = failing.length ? `${now.health} (${failing.join(", ")})` : now.health;
377
+ }
378
+ }
379
+ if (!url) {
380
+ if (setupOnly) return 0;
381
+ io.stderr.write(`No AgentRun answers for ${data}: start it with agentrun service start, or agentrun.\n`);
382
+ return 1;
383
+ }
384
+ const record = JSON.parse(readFileSync(join(data, ".server.json"), "utf8"));
385
+ const api = record.base_url.replace(/\/+$/, "");
386
+ const ask = async (path, init) => {
387
+ try {
388
+ const response = await get(`${api}${path}`, { ...init, signal: AbortSignal.timeout(5_000) });
389
+ return response.ok ? await response.json().catch(() => ({})) : undefined;
390
+ } catch {
391
+ return undefined;
392
+ }
393
+ };
394
+ if (unwell) say(`Its health check answers ${unwell}; agentrun service status says more.`);
395
+ const logged = resolve(data) === (installed() ? dataOf(argsNow(), home) : resolve(root));
396
+ const session = await ask("/auth/session");
397
+ let link;
398
+ let coded = false;
399
+ if (session?.accounts !== false && session?.password_set === false) {
400
+ if (session.setup_code) {
401
+ const before = logged ? newestSetup() : undefined;
402
+ const renewed = await ask("/setup/code", { method: "POST" });
403
+ // A new code goes to the log as the answer is sent: wait for its line.
404
+ for (let waited = 0; logged && renewed?.printed && newestSetup() === before && waited < 3_000; waited += 100) await new Promise((done) => setTimeout(done, 100));
405
+ link = logged ? newestSetup() : undefined;
406
+ coded = link !== undefined;
407
+ if (!link) {
408
+ link = url;
409
+ say(`Its setup code is in the log of the terminal or service AgentRun runs in: the newest line "Set up this server:".`);
410
+ }
411
+ } else link = `${url}setup`;
412
+ } else if (setupOnly) return 0;
413
+ else link = url;
414
+ const opener = platform === "darwin" ? "open" : "xdg-open";
415
+ const opened = canOpen(env, platform) && (await launch(opener, [link], env));
416
+ const setup = !(link === url && session?.password_set !== false);
417
+ if (opened) {
418
+ say(setup ? "Opened the setup page in your browser: set the owner password there." : "Opened the console in your browser.");
419
+ say(`If no browser opened, open ${link}`);
420
+ } else say(setup ? `Set the owner password at the setup page: ${link}` : `The console: ${link}`);
421
+ if (coded) say("Its setup code works once and for 30 minutes; agentrun open gives a new one after that.");
422
+ return 0;
423
+ }
424
+
308
425
  return {
309
- async install({ data, port, tailscale, env: sets = [] }) {
426
+ open: ({ data, "setup-only": setupOnly }) => openPage(resolve(data ?? root), { setupOnly }),
427
+ async install({ data, port, tailscale, env: sets = [], "public-url": given }) {
310
428
  if (port !== undefined && !/^\d+$/.test(port)) throw fail(2, `--port takes a port number, not ${port}.`);
311
429
  const changes = sets.map((pair) => {
312
430
  const at = pair.indexOf("=");
313
431
  if (at < 1) throw fail(2, `--env takes KEY=VALUE, not ${pair}.`);
314
432
  const key = pair.slice(0, at);
315
- if (!MODEL_ENV.includes(key)) throw fail(2, `--env takes ${MODEL_ENV.slice(0, -1).join(", ")} or ${MODEL_ENV.at(-1)}, not ${key}: a key goes in the console (Settings → Model keys), never in a service file.`);
433
+ if (!Object.hasOwn(SERVICE_ENV, key)) throw fail(2, `--env takes ${SERVICE_NAMES.slice(0, -1).join(", ")} or ${SERVICE_NAMES.at(-1)}, not ${key}: a key goes in the console (Settings → Model keys), never in a service file.`);
316
434
  if (/[\0-\x1f]/.test(pair)) throw fail(2, `${key}'s value has a line break or another control character.`);
435
+ const takes = SERVICE_ENV[key];
436
+ // The value is never echoed: it may be a key.
437
+ if (takes && pair.slice(at + 1) !== "" && !takes.includes(pair.slice(at + 1))) throw fail(2, `${key} takes ${takes.join(" or ")} alone, or nothing to remove it: a model key goes in the console (Settings → Model keys), never in a service file.`);
317
438
  return [key, pair.slice(at + 1)];
318
439
  });
440
+ // --public-url goes on the service's command line, so every start of it (a restart, a login) has it, and with it
441
+ // the launcher's AGENTRUN_TRUSTED_PROXIES=loopback.
442
+ let publicUrl = given === undefined ? undefined : publicUrlOf(given);
443
+ if (publicUrl?.error !== undefined) throw fail(2, publicUrl.error);
319
444
  need();
320
445
  if (!existsSync(program)) throw fail(1, `AgentRun's service runs the installed command, ${program}, and it is not there. Install it first: ${INSTALL_COMMAND}`);
321
446
  const why = manager.available();
322
447
  if (why !== undefined) throw fail(1, `AgentRun can't run as a service here: ${why}. Start it in a terminal with ${program}.`);
323
- // An installed service keeps its local model's variables; --env KEY=VALUE sets one, KEY= removes it.
324
- const model = installed() ? Object.fromEntries(Object.entries(manager.env(readFileSync(manager.file, "utf8"))).filter(([key]) => MODEL_ENV.includes(key))) : {};
448
+ // An installed service keeps its local model's variables, its start-time switches and its usage counts' switches; the switches set in this
449
+ // shell reach it (and under CI, AGENTRUN_TELEMETRY=0), then --env KEY=VALUE sets one and KEY= removes it.
450
+ const model = installed() ? Object.fromEntries(Object.entries(manager.env(readFileSync(manager.file, "utf8"))).filter(([key]) => Object.hasOwn(SERVICE_ENV, key))) : {};
451
+ for (const key of TELEMETRY_NAMES) if ((env[key] ?? "") !== "" && !/[\0-\x1f]/.test(env[key])) model[key] = env[key];
452
+ if (env.CI && model.AGENTRUN_TELEMETRY === undefined) model.AGENTRUN_TELEMETRY = "0";
325
453
  for (const [key, value] of changes) {
326
454
  if (value === "") delete model[key];
327
455
  else model[key] = value;
328
456
  }
329
- // --tailscale, --no-tailscale or --env on an installed service changes that only: its data folder and port stay
330
- // unless named (the installer passes the flag alone).
331
- if ((tailscale !== undefined || changes.length > 0) && installed()) {
457
+ // --tailscale, --no-tailscale, --env or --public-url on an installed service changes that only: its data folder, port
458
+ // and public address stay unless named (the installer passes the flag alone). --tailscale names its own address instead.
459
+ if ((tailscale !== undefined || changes.length > 0 || given !== undefined) && installed()) {
332
460
  const now = argsNow();
333
461
  const option = (name) => (now.includes(name) ? now[now.indexOf(name) + 1] : undefined);
334
462
  data ??= option("--data");
335
463
  port ??= option("--port");
464
+ const kept = option("--public-url");
465
+ if (publicUrl === undefined && tailscale !== true && kept !== undefined && publicUrlOf(kept).url !== undefined) publicUrl = publicUrlOf(kept);
336
466
  }
337
467
  const again = (flag) => [`agentrun service install ${flag}`, ...(port !== undefined ? [`--port ${port}`] : []), ...(data !== undefined ? [`--data ${resolve(data)}`] : [])].join(" ");
338
468
  const tailnet = tailnetOf({ platform, root, uid, exec, say, fail, again: again("--tailscale") });
@@ -341,10 +471,13 @@ export function serviceOf({ platform = process.platform, home = homedir(), uid =
341
471
  // On the tailnet the port is fixed, so the serve entry and the server still agree after a restart.
342
472
  const served = share ? (port ?? TAILNET_PORT) : port;
343
473
  if (share && Number(served) === 0) throw fail(2, `--tailscale serves a fixed port, and --port 0 has the system pick another at each start: name a port, or leave --port out for ${TAILNET_PORT}.`);
474
+ if (share && publicUrl !== undefined) {
475
+ throw fail(2, `--public-url and --tailscale each set the address people open, and --tailscale names its own (this machine's tailnet name). Leave out --public-url, or take AgentRun off the tailnet with --no-tailscale.`);
476
+ }
344
477
  if (!share) tailnet.off(again("--no-tailscale"));
345
478
  // The server knows the address people open: its host check takes the name, and its setup takes the printed code.
346
479
  const at = share ? tailnet.address(targetOf(served)) : undefined;
347
- const args = ["--no-open", ...(data !== undefined ? ["--data", resolve(data)] : []), ...(served !== undefined ? ["--port", served] : [])];
480
+ const args = ["--no-open", ...(data !== undefined ? ["--data", resolve(data)] : []), ...(served !== undefined ? ["--port", served] : []), ...(publicUrl !== undefined ? ["--public-url", publicUrl.url] : [])];
348
481
  const vars = { ...model, ...(at ? { AGENTRUN_PUBLIC_URL: at.url, AGENTRUN_TRUSTED_PROXIES: "loopback" } : {}) };
349
482
  mkdirSync(join(root, "logs"), { recursive: true, mode: 0o700 });
350
483
  mkdirSync(join(manager.file, ".."), { recursive: true });
@@ -352,9 +485,9 @@ export function serviceOf({ platform = process.platform, home = homedir(), uid =
352
485
  const since = Date.now();
353
486
  manager.install();
354
487
  say(`Installed AgentRun's service (${manager.file}): it keeps running after this terminal closes, and starts again at login.`);
355
- const code = await started(since, dataOf(args, home));
356
- if (code === 0 && at) tailnet.serve(served, at.host);
357
- return code;
488
+ return started(since, dataOf(args, home), () => {
489
+ if (at) tailnet.serve(served, at.host);
490
+ });
358
491
  },
359
492
  async status() {
360
493
  need();
@@ -420,7 +553,7 @@ export function serviceOf({ platform = process.platform, home = homedir(), uid =
420
553
  },
421
554
  /** `agentrun stop`: the AgentRun install.sh started in the background, stopped as Ctrl-C would (SIGTERM, which the
422
555
  * launcher passes on to the server), then SIGKILL past stopWaitMs. Exit 0 once the launcher and its server have
423
- * ended, 3 when none is running, 1 when one outlives its SIGKILL. install.sh stops it with the same steps in sh, so an
556
+ * ended, 3 when none is running, 1 when one outlives its SIGKILL or runs in the foreground (named, and left running). install.sh stops it with the same steps in sh, so an
424
557
  * install of a version with no `agentrun stop` stops it too. */
425
558
  async background() {
426
559
  const file = join(root, "agentrun.pid");
@@ -450,6 +583,20 @@ export function serviceOf({ platform = process.platform, home = homedir(), uid =
450
583
  };
451
584
  if (!ours(pid)) {
452
585
  rmSync(file, { force: true });
586
+ // A server in the foreground (`npx @parcha/agentrun` in a terminal) has no pid file, only the record every server
587
+ // writes, and it runs from npm's folder, not this install's. One whose process runs and whose recorded address
588
+ // answers /health ok is named, with how to stop it, and left running: Ctrl-C there is its stop. A service writes the
589
+ // same record and no pid file, so while one runs its server is the service's, and the hint below says so; with the
590
+ // service stopped (service stop, then npx), a server that answers is in a terminal.
591
+ let record;
592
+ try {
593
+ record = JSON.parse(readFileSync(join(root, ".server.json"), "utf8"));
594
+ } catch {}
595
+ const live = Number.isInteger(record?.pid) && record.pid > 1 && ![undefined, "Z"].includes(processOf(record.pid)?.state);
596
+ if (live && !(installed() && manager.state().active) && (await healthOf(root, { fetch: get })).health === "ok") {
597
+ say(`AgentRun is running in the foreground (pid ${record.pid}); press Ctrl-C in its terminal.`);
598
+ return 1;
599
+ }
453
600
  say(`No AgentRun started in the background is running.${installed() ? " AgentRun runs as a service here: agentrun service stop stops it." : ""}`);
454
601
  return 3;
455
602
  }
@@ -489,7 +636,7 @@ export function serviceOf({ platform = process.platform, home = homedir(), uid =
489
636
  }
490
637
 
491
638
  const VERBS = [
492
- ["install", "Install AgentRun as a service of this user and start it: it keeps running after the terminal closes and starts again at login", [["--port N", "the port to listen on (default: the first free from 7340; 7340 with --tailscale)"], ["--data DIR", "the data directory (default ~/.agentrun)"], ["--tailscale", "also serve it over HTTPS on your own tailnet only (tailscale serve, never Funnel); --no-tailscale takes it off"], ["--env KEY=VALUE", `a local model's variable for the server (${MODEL_ENV.join(", ")}), kept until KEY= removes it; repeatable`]], { port: { type: "string" }, tailscale: { type: "boolean" }, env: { type: "string", multiple: true } }],
639
+ ["install", "Install AgentRun as a service of this user and start it: it keeps running after the terminal closes and starts again at login", [["--port N", "the port to listen on (default: the first free from 7340; 7340 with --tailscale)"], ["--data DIR", "the data directory (default ~/.agentrun)"], ["--tailscale", "also serve it over HTTPS on your own tailnet only (tailscale serve, never Funnel); --no-tailscale takes it off"], ["--env KEY=VALUE", `a local model's variable for the server, a start-time switch or the usage counts' switch: ${Object.entries(SERVICE_ENV).map(([name, takes]) => (takes ? `${name} (${takes.join(" or ")})` : name)).join(", ")}; kept until KEY= removes it; repeatable`], ["--public-url URL", "the https address people open it at, through a proxy you run in front of it (your own tailscale serve, a reverse proxy); kept for every restart"]], { port: { type: "string" }, tailscale: { type: "boolean" }, env: { type: "string", multiple: true }, "public-url": { type: "string" } }],
493
640
  ["status", "Say whether the service is installed and running, the console's address and its health (exit 0 healthy, 1 not, 3 not installed)", [], {}],
494
641
  ["start", "Start the service and wait until it answers", [], {}],
495
642
  ["stop", "Stop the service (it starts again at the next login)", [], {}],
@@ -509,6 +656,16 @@ export const SERVICE = VERBS.map(([verb, summary, help, options]) => ({
509
656
  run: ({ values, io, env, cli }) => serviceOf({ env, io, fail: cli.fail })[verb](values),
510
657
  }));
511
658
 
659
+ /** `agentrun open` (cli.mjs LOCAL). */
660
+ export const OPEN = {
661
+ command: ["open"],
662
+ pathParams: [],
663
+ summary: "Open AgentRun in this machine's browser: the setup page, its code filled in, until the owner's password is set; the console after (where no browser opens, it prints the link)",
664
+ help: [["--data DIR", "the data directory of the AgentRun to open (default ~/.agentrun)"], ["--setup-only", "open nothing once the owner's password is set (the installer's last step)"]],
665
+ options: { "setup-only": { type: "boolean" } },
666
+ run: ({ values, io, env, cli }) => serviceOf({ env, io, fail: cli.fail }).open(values),
667
+ };
668
+
512
669
  /** `agentrun stop` (cli.mjs LOCAL). */
513
670
  export const STOP = {
514
671
  command: ["stop"],
package/lib/start.mjs CHANGED
@@ -8,6 +8,8 @@ import { homedir } from "node:os";
8
8
  import { dirname, join } from "node:path";
9
9
  import { StringDecoder } from "node:string_decoder";
10
10
  import { main as cli, NOUNS, words } from "./cli.mjs";
11
+ import { chosenPublicUrl } from "./public-url.mjs";
12
+ import { tailnetHint, tailnetNameOf } from "./tailscale.mjs";
11
13
 
12
14
  export const SERVE_PACKAGE = "@parcha/agentrun-serve";
13
15
  /** This command's package at its version, handed to the server it starts (AGENTRUN_NPX_PACKAGE), so the server's hints
@@ -148,8 +150,8 @@ function tailOf(tail) {
148
150
 
149
151
  /** The server's lines this command says too, as they come: its banner's boxes line (whether new agents get the Docker
150
152
  * box, or why not), and, on a server with a public address and no password yet, the setup link with its code, which
151
- * setup at that address asks for. */
152
- export const SAID = /^(Boxes: |Set up this server: )/;
153
+ * setup at that address asks for, with the same link at this machine's addresses for a server on every address. */
154
+ export const SAID = /^(Boxes: |Set up this server: |From another machine: )/;
153
155
 
154
156
  /** The address a person opens first, as the server says it: the URL of the first "Open " line of its output that names
155
157
  * one (openLineUrl). That line is the server's interface for it (the plain address today, a single-use sign-in link
@@ -229,7 +231,8 @@ export function npmExecOf(env, from = process.ppid) {
229
231
  return undefined;
230
232
  }
231
233
 
232
- export const USAGE = `Usage: npx @parcha/agentrun [--port N] [--data DIR] [--no-open] start the server
234
+ export const USAGE = `Usage: npx @parcha/agentrun [--port N] [--data DIR] [--no-open] [--public-url URL] start the server
235
+ (--public-url: the https address people open it at, through a proxy such as tailscale serve)
233
236
  npx @parcha/agentrun import|reset-password|runner|native [--data DIR] a server command (native: discover/connect an existing project)
234
237
  npx @parcha/agentrun <command> [args] the server's API: agents, runs, triggers, ..., api (npx @parcha/agentrun help)`;
235
238
 
@@ -246,9 +249,23 @@ export function installedServer(resolve = createRequire(import.meta.url).resolve
246
249
  * --open, which itself skips a CI run and a machine with no display). */
247
250
  export const serverArgs = (argv) => (argv.includes("--no-open") ? argv.filter((arg) => arg !== "--no-open") : ["--open", ...argv]);
248
251
 
252
+ /** Whether the server listens on this machine only: no --listen (127.0.0.1), or a loopback one. Its last --listen counts,
253
+ * as the server reads them. */
254
+ export function onLoopback(args) {
255
+ let listen;
256
+ for (let i = 0; i < args.length; i++) {
257
+ if (args[i] === "--listen") listen = args[++i];
258
+ else if (args[i].startsWith("--listen=")) listen = args[i].slice("--listen=".length);
259
+ }
260
+ return listen === undefined || /^(localhost|127(?:\.\d{1,3}){3}|::1|\[::1\])$/i.test(listen);
261
+ }
262
+
263
+ /** Whether this runs in CI, where nobody reads a hint. */
264
+ const inCi = (env) => Boolean(env.CI) && env.CI !== "false" && env.CI !== "0";
265
+
249
266
  /** The server's own commands (its CLI's first word), which this command runs on its store: every other first word is
250
267
  * the CLI's, which names a command it has or says it has none. */
251
- export const SERVER_COMMANDS = ["eval-template", "import", "install-harness", "native", "remote-bridge", "reset-password", "runner", "validate-template"];
268
+ export const SERVER_COMMANDS = ["check-harness", "eval-template", "import", "install-harness", "native", "remote-bridge", "reset-password", "runner", "validate-template"];
252
269
 
253
270
  /** How many of the server's refusals and ignored deliveries a start says, each route and reason once, before one line
254
271
  * that says the rest are not: under this command the server's log goes nowhere else (its stdout is read here and dropped). */
@@ -301,7 +318,10 @@ export async function main(argv, env = process.env) {
301
318
  // and a flag starts the server, whose flags with values (--listen ADDR) follow.
302
319
  const first = argv.find((arg, i) => arg !== "--data" && !arg.startsWith("--data=") && argv[i - 1] !== "--data");
303
320
  if (NOUNS.has(words(argv)[0]) || (first !== undefined && !first.startsWith("-") && !SERVER_COMMANDS.includes(first))) return cli(argv, env);
304
- if (argv.includes("--help") || argv.includes("-h")) return console.log(USAGE), 0;
321
+ // --help is this command's usage when it starts the server; a server command's --help is that command's, which the
322
+ // server prints (import --help names --from and --dry-run). remote-bridge, the connector's own process, has no usage of
323
+ // its own to print and never reads --help, so it keeps this one.
324
+ if (!(SERVER_COMMANDS.includes(first) && first !== "remote-bridge") && (argv.includes("--help") || argv.includes("-h"))) return console.log(USAGE), 0;
305
325
  if (process.platform === "win32") return console.error("AgentRun's server runs on macOS and Linux; on Windows, use WSL or its container."), 1;
306
326
  const launcher = installedServer();
307
327
  if (launcher === undefined) return console.error(`AgentRun's server (${SERVE_PACKAGE}) is not installed beside this command; run it as npx ${OWN_SPEC}.`), 1;
@@ -317,13 +337,26 @@ export async function main(argv, env = process.env) {
317
337
  // opens this same store.
318
338
  // `--data <dir>` and `--data=<dir>` are the same option, and the last one wins, as the server reads them; the server is
319
339
  // handed exactly one, so this command, its hint and the server agree on the directory.
340
+ // --public-url is this command's own: the server takes the address as AGENTRUN_PUBLIC_URL, never as a flag.
320
341
  let dir;
342
+ let publicFlag;
321
343
  const rest = [];
322
344
  for (let i = 0; i < argv.length; i++) {
323
345
  if (argv[i] === "--data" && i + 1 < argv.length) dir = argv[++i];
324
346
  else if (argv[i].startsWith("--data=")) dir = argv[i].slice("--data=".length);
347
+ else if (argv[i] === "--public-url") publicFlag = argv[++i] ?? "";
348
+ else if (argv[i].startsWith("--public-url=")) publicFlag = argv[i].slice("--public-url=".length);
325
349
  else rest.push(argv[i]);
326
350
  }
351
+ const chosen = chosenPublicUrl(publicFlag, env.AGENTRUN_PUBLIC_URL);
352
+ if (chosen.error !== undefined) return console.error(chosen.error), 2;
353
+ const publicUrl = chosen.url;
354
+ if (publicUrl !== undefined) childEnv.AGENTRUN_PUBLIC_URL = publicUrl;
355
+ // --public-url on loopback means a proxy on this machine sends every request (tailscale serve, a reverse proxy), as
356
+ // --tailscale's does: the server counts sign-ins by the address its X-Forwarded-For names, not one for everyone. An
357
+ // operator's own AGENTRUN_TRUSTED_PROXIES stays, an empty one (trust no proxy) too; a server on another address trusts no
358
+ // one it was not told to.
359
+ if (publicFlag !== undefined && onLoopback(rest) && env.AGENTRUN_TRUSTED_PROXIES === undefined) childEnv.AGENTRUN_TRUSTED_PROXIES = "loopback";
327
360
  const dataDir = dir ?? join(homedir(), ".agentrun");
328
361
  // A name that starts with a dash keeps the equals form: the server's parser reads "--data -x" as a missing value.
329
362
  const data = dataDir.startsWith("-") ? [`--data=${dataDir}`] : ["--data", dataDir];
@@ -387,6 +420,10 @@ export async function main(argv, env = process.env) {
387
420
  if (log.fd !== undefined) try { closeSync(log.fd); } catch {}
388
421
  log.fd = undefined;
389
422
  };
423
+ // On loopback with no public address, a person may want it on their other devices: where Tailscale runs here, the
424
+ // start says how (tailnetHint), once it is up. Reading Tailscale's status is all it does there, bounded, in parallel
425
+ // with the start; any error says nothing.
426
+ const tailnetName = publicUrl === undefined && !env.RENDER_EXTERNAL_URL && onLoopback(rest) && !inCi(env) ? tailnetNameOf({ env }) : Promise.resolve(undefined);
390
427
  const child = spawn(launcher, serverArgs([...data, ...rest]), { stdio: ["ignore", "pipe", "pipe"], env: childEnv });
391
428
  let started = false;
392
429
  const errTail = [];
@@ -452,7 +489,7 @@ export async function main(argv, env = process.env) {
452
489
  clearTimeout(timer);
453
490
  console.error(`AgentRun is starting at ${address}: it listens there now, and opens once its store is ready.`);
454
491
  };
455
- const url = await Promise.race([openUrl(child.stdout, env.AGENTRUN_PUBLIC_URL, seen, tell, tell, onStarting), new Promise((resolve) => { timer = setTimeout(() => resolve(TIMED_OUT), bound); })]);
492
+ const url = await Promise.race([openUrl(child.stdout, publicUrl, seen, tell, tell, onStarting), new Promise((resolve) => { timer = setTimeout(() => resolve(TIMED_OUT), bound); })]);
456
493
  clearTimeout(timer);
457
494
  if (url === undefined || url === TIMED_OUT) {
458
495
  // Its stdout ended (it exited, was never started, or closed it), or the bound passed with it still running. A server
@@ -499,5 +536,8 @@ export async function main(argv, env = process.env) {
499
536
  console.error(env.AGENTRUN_TOKEN ? "The API token is the AGENTRUN_TOKEN this command was started with." : `The API token is in ${join(dataDir, ".token")}.`);
500
537
  told = true;
501
538
  for (const line of held.splice(0)) console.error(line);
539
+ const name = await tailnetName;
540
+ const port = new URL(url).port;
541
+ if (name !== undefined && port !== "" && new URL(url).hostname === HOST) console.error(tailnetHint(name, port));
502
542
  return exited;
503
543
  }
package/lib/tailscale.mjs CHANGED
@@ -10,7 +10,7 @@
10
10
  // node tailscale.mjs serve PORT AGAIN URL [LOG] serves the loopback PORT at URL, the address printed, and says where;
11
11
  // LOG is where the setup code's line is (default ~/.agentrun's log)
12
12
  // node tailscale.mjs off removes the entry it added
13
- import { spawnSync } from "node:child_process";
13
+ import { execFile, spawnSync } from "node:child_process";
14
14
  import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
15
15
  import { homedir } from "node:os";
16
16
  import { join } from "node:path";
@@ -150,6 +150,52 @@ export function tailnetOf({ platform = process.platform, root = join(homedir(),
150
150
  };
151
151
  }
152
152
 
153
+ /** How long a start waits for `tailscale status --json` before it says nothing about Tailscale. */
154
+ export const HINT_TIMEOUT_MS = 2_000;
155
+
156
+ /** This machine's name on its tailnet (`Self.DNSName`, without its last dot), read with `tailscale status --json`, the
157
+ * one Tailscale command a start runs: it changes nothing. Undefined when Tailscale is not on PATH, is not running or
158
+ * signed in (BackendState other than Running), names no machine, or does not answer within `timeoutMs`. Never throws. */
159
+ export function tailnetNameOf({ env = process.env, timeoutMs = HINT_TIMEOUT_MS } = {}) {
160
+ return new Promise((done) => {
161
+ let child;
162
+ const timer = setTimeout(() => {
163
+ child?.kill("SIGKILL");
164
+ done(undefined);
165
+ }, timeoutMs);
166
+ timer.unref();
167
+ const end = (name) => {
168
+ clearTimeout(timer);
169
+ done(name);
170
+ };
171
+ try {
172
+ child = execFile("tailscale", ["status", "--json"], { env, encoding: "utf8", maxBuffer: 4 * 1024 * 1024, timeout: timeoutMs, killSignal: "SIGKILL" }, (error, stdout) => {
173
+ if (error) return end(undefined);
174
+ try {
175
+ const status = JSON.parse(stdout);
176
+ const name = String(status?.Self?.DNSName ?? "").replace(/\.$/, "").toLowerCase();
177
+ end(status?.BackendState === "Running" && /^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(name) ? name : undefined);
178
+ } catch {
179
+ end(undefined);
180
+ }
181
+ });
182
+ child.on("error", () => end(undefined));
183
+ child.unref();
184
+ } catch {
185
+ end(undefined);
186
+ }
187
+ });
188
+ }
189
+
190
+ /** What a start on loopback with no public address says when Tailscale runs here: the tailnet address it could have, and
191
+ * the two steps to it. `tailscale serve` keeps it on the tailnet; Funnel, which would put it on the internet, is never
192
+ * named. The restart names the port, so the serve entry and the server agree after it. */
193
+ export const tailnetHint = (name, port) => [
194
+ `Tailscale is running here: AgentRun could be at https://${name}/ for your devices on your tailnet, and no one else. To serve it there:`,
195
+ ` 1. tailscale serve --bg ${port}`,
196
+ ` 2. Stop AgentRun and start it again with --port ${port} --public-url https://${name}/ added to its command`,
197
+ ].join("\n");
198
+
153
199
  /** The installer's step for an AgentRun in the background or under --vps. Exit 1 on a refusal, said on stderr. */
154
200
  function script([verb, port, again, url, log]) {
155
201
  const fail = (code, message) => Object.assign(new Error(message), { code });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun",
3
- "version": "0.4.14",
3
+ "version": "0.4.15",
4
4
  "description": "AgentRun, the open-source platform that supercharges your agents (self-improvement, durable execution and a control plane on top of your favorite agent harness), on this machine with one command: npx @parcha/agentrun",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -17,7 +17,7 @@
17
17
  "NOTICE"
18
18
  ],
19
19
  "dependencies": {
20
- "@parcha/agentrun-serve": "0.1.0-beta.46"
20
+ "@parcha/agentrun-serve": "0.1.0-beta.47"
21
21
  },
22
22
  "scripts": {
23
23
  "test": "node --test 'test/*.test.mjs'"
@@ -133,21 +133,25 @@ Two clients call the same API from code, with the same server and token. `@parch
133
133
 
134
134
  - `agentrun agents`: archive, connect-native, create, delete-agent, delete-agent-archil, disconnect-native, discover-native, forget-sign-in, get, get-agent-archil, get-learning-loop, get-native, list, list-learning-audits, list-learning-promotions, runs, unarchive, update, verify-native
135
135
  - `agentrun connectors`: complete-remote-command, enroll-remote-connector, import-remote-history, import-remote-target, list-remote-connectors, poll-remote-connector, register-remote-connector, remote-command-events, revoke-remote-connector
136
+ - `agentrun doctor`: Check how this AgentRun is set up (Node, the server, its service, address, password, models, switches, Docker) and print what to change; read-only (exit 0 ok or warnings, 1 a check failed, 3 no server answering)
136
137
  - `agentrun files`: create, delete, get, list, upload
137
138
  - `agentrun harness`: install
139
+ - `agentrun harness-check`: Run a recipe's installed agent for real and check it (tools off, env allowlist, pins, limits, no side requests, resume, a denied call, an MCP tool): a JSON report and three facts. Real models cost money
138
140
  - `agentrun home`: delete, list, read, write
139
141
  - `agentrun learning`: corrections, cost, get, log, read, replay, retire, workflow-revisions, write-corrections
140
- - `agentrun local`: create-pairing, delete-composio-subscription, delete-computer, delete-workspace-archil, disconnect-git-hub, get-git-hub-connection, get-workspace-archil, list-composio-events, list-composio-triggers, list-computer-choices, list-computers, receive-hook-composio, rotate-composio-secret, test-computer, test-workspace-archil
142
+ - `agentrun local`: create-pairing, delete-composio-subscription, delete-computer, delete-workspace-archil, disconnect-git-hub, get-git-hub-connection, get-model-gateway, get-workspace-archil, list-composio-events, list-composio-triggers, list-computer-choices, list-computers, receive-hook-composio, rotate-composio-secret, test-computer, test-workspace-archil
141
143
  - `agentrun login`: Check a server's token, read from stdin, and keep it with the server's address in the config file
142
144
  - `agentrun logout`: Remove the config file login wrote, its address and token
143
145
  - `agentrun mcp-servers`: delete, get, list, oauth-client, private-hosts, refresh
144
146
  - `agentrun Observations`: get-observations
147
+ - `agentrun open`: Open AgentRun in this machine's browser: the setup page, its code filled in, until the owner's password is set; the console after (where no browser opens, it prints the link)
145
148
  - `agentrun revisions`: list, set-current
146
149
  - `agentrun runs`: archive, cancel, computer-call, computer-release, create-inline-run, files, get, grade-run, graph, hand-back-run-computer, learning, learning-diff, list, message, pause, raise-cap, read-file, resume, start, start-held, stop, take-over-run-computer, timeline, trace, unarchive, wait
147
150
  - `agentrun sdk-runs`: complete, events, get, start
148
151
  - `agentrun server`: capabilities, health, mcp, openapi
149
152
  - `agentrun service`: install, logs, restart, start, status, stop, uninstall, upgrade
150
153
  - `agentrun skill`: install
154
+ - `agentrun slack`: deliveries, get, redeliver, test
151
155
  - `agentrun stats`: Counts and cost over every agent and run
152
156
  - `agentrun stop`: Stop the AgentRun the installer started in the background, where there is no service manager (exit 0 stopped, 3 none running)
153
157
  - `agentrun template`: apply, delete, eval, import, install, list, validate