@parcha/agentrun 0.4.7 → 0.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +6 -0
  2. package/lib/start.mjs +219 -15
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -15,6 +15,12 @@ it in your browser (`--no-open`, a CI run or a machine with no display skips tha
15
15
  each version of this command runs the server it was released with. Node.js 24.22.3 or newer, on macOS or Linux; an older
16
16
  Node gets one line naming that floor.
17
17
 
18
+ A start that fails says why on stderr: the step that failed, how the server ended (its exit code or signal, or still
19
+ running after 60 seconds without printing its address, and stopped), its last lines on stderr and stdout, and
20
+ `~/.agentrun/start.log` (in the folder `--data` names), which holds everything the server wrote in that start. Each start
21
+ overwrites that log; it is private to you, as the server's first lines name its API token. A log the disk could not hold
22
+ all of is named with the error that cut it short.
23
+
18
24
  Where Docker answers on this machine, a new agent runs in a Docker box of its own with a shell, and a line on stderr,
19
25
  after the address, says so: `Boxes: docker (on by default; set AGENTRUN_BOXES to change).` Where it does not, that line says why
20
26
  and that new agents run on the runner. A Docker box's image is built on its first run, which shows that on its
package/lib/start.mjs CHANGED
@@ -2,10 +2,11 @@
2
2
  // npx installs the two together and this command always runs the server it was released with. The server's own CLI picks
3
3
  // the port and whether to open the browser; this command passes its arguments through.
4
4
  import { execFileSync, spawn } from "node:child_process";
5
- import { readFileSync } from "node:fs";
5
+ import { closeSync, constants, fchmodSync, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
6
6
  import { createRequire } from "node:module";
7
7
  import { homedir } from "node:os";
8
8
  import { dirname, join } from "node:path";
9
+ import { StringDecoder } from "node:string_decoder";
9
10
  import { main as cli, NOUNS, words } from "./cli.mjs";
10
11
 
11
12
  export const SERVE_PACKAGE = "@parcha/agentrun-serve";
@@ -31,9 +32,119 @@ export function openLineUrl(line, publicUrl) {
31
32
  * the address this command names is the server's API, from the AGENTRUN_BASE_URL line before it. */
32
33
  export const API_ONLY_LINE = /^API only \(AGENTRUN_API_ONLY=1\)/;
33
34
 
34
- /** How many of the server's last output lines a start that fails shows. */
35
+ /** How many of the server's last lines, on stdout and on stderr each, a start that fails shows. */
35
36
  export const TAIL_LINES = 20;
36
37
 
38
+ /** How long a start waits for the server's "Open " line before it stops the server and says so. AGENTRUN_START_TIMEOUT_MS
39
+ * (milliseconds) sets another bound; the launcher's tests use it. */
40
+ export const START_TIMEOUT_MS = 60_000;
41
+ /** How long a server that did not start has to end after its SIGTERM before it is sent a SIGKILL. */
42
+ export const STOP_GRACE_MS = 10_000;
43
+ /** The start log, in the data folder: everything the server wrote on stdout and stderr in the last start, until it
44
+ * printed the address to open, then the failure if it did not. Each start overwrites it. */
45
+ export const START_LOG = "start.log";
46
+
47
+ const seconds = (ms) => `${Number((ms / 1000).toFixed(1))} s`;
48
+ /** `promise`'s value, or undefined once `ms` pass; the timer goes with it, so it never holds this process up. */
49
+ const within = (promise, ms) => {
50
+ let timer;
51
+ return Promise.race([promise, new Promise((resolve) => { timer = setTimeout(resolve, ms); })]).finally(() => clearTimeout(timer));
52
+ };
53
+
54
+ /** What a start, or a server command, that failed says on stderr: one line saying what happened, then the step that
55
+ * failed, how the server's process ended (its exit code or signal; still running past the bound and stopped; or never
56
+ * started), its last lines on stderr and on stdout, and the start log that holds all of its output, or why there is none
57
+ * (`logError`), or why it holds only the start of it (`logIncomplete`, the write that failed: a full disk, a quota).
58
+ * `command` names a server command (import, ...), whose output went to the terminal as it ran: no lines, no log. `sent`
59
+ * is the signals this command sent the server, in order; `stopped` is why it sent them unasked: "timeout" (still running
60
+ * `waitedMs` after it started) or "closed" (its output closed while it ran). */
61
+ export function failureText({ command, step, error, code = null, signal = null, stopped, waitedMs, sent = [], stderrTail, stdoutTail, logPath, logError, logIncomplete }) {
62
+ const lead = command === undefined ? "AgentRun did not start" : `The server's ${command} command failed`;
63
+ const subject = command === undefined ? "the server" : "it";
64
+ const before = command === undefined ? " before it printed the address to open" : "";
65
+ const ended = signal !== null ? `signal ${signal}` : code !== null ? `code ${code}` : "not ended yet";
66
+ let why;
67
+ let exit;
68
+ if (error !== undefined) {
69
+ why = `${subject} could not be started (${error.message})`;
70
+ exit = "it never ran";
71
+ } else if (stopped !== undefined) {
72
+ const was = stopped === "closed" ? "its output closed while it ran" : `still running after ${seconds(waitedMs)}`;
73
+ why = stopped === "closed" ? `${subject} closed its output without printing the address to open, so it was stopped` : `${subject} was still running after ${seconds(waitedMs)} without printing the address to open, so it was stopped`;
74
+ exit = `${was}; stopped with ${sent.length > 1 ? `${sent[0]}, then ${sent.slice(1).join(", then ")} ${seconds(STOP_GRACE_MS)} later` : sent[0]}; then ${ended}`;
75
+ } else if (signal !== null) {
76
+ why = `${subject} was ended by ${signal}${before}`;
77
+ exit = `signal ${signal}${sent.includes(signal) ? " (sent by this command)" : signal === "SIGKILL" ? " (not sent by this command: the system may have run out of memory)" : ""}`;
78
+ } else {
79
+ why = `${subject} exited with code ${code}${before}`;
80
+ exit = `code ${code}`;
81
+ }
82
+ const lines = (name, tail) => {
83
+ if (tail === undefined) return [];
84
+ if (tail.length === 0) return [` ${name}: nothing`];
85
+ return [` ${name}, last ${tail.length === 1 ? "line" : `${tail.length} lines`}:`, ...tail.map((line) => ` ${line}`)];
86
+ };
87
+ const log = logPath !== undefined ? [` log: ${logPath}${logIncomplete !== undefined ? ` (incomplete: ${logIncomplete.message})` : ""}`] : logError !== undefined ? [` log: none (${logError.message})`] : [];
88
+ return [`${lead}: ${why}.`, ` step: ${step}`, ` exit: ${exit}`, ...lines("stderr", stderrTail), ...lines("stdout", stdoutTail), ...log].join("\n");
89
+ }
90
+
91
+ /** The bound on a start's wait for the "Open " line: AGENTRUN_START_TIMEOUT_MS when it is a whole number of
92
+ * milliseconds above 0, else START_TIMEOUT_MS. */
93
+ export const startTimeoutMs = (env) => (/^[1-9]\d*$/.test(env.AGENTRUN_START_TIMEOUT_MS ?? "") ? Number(env.AGENTRUN_START_TIMEOUT_MS) : START_TIMEOUT_MS);
94
+
95
+ /** The start log, opened afresh in `dataDir` (made first, private, as the server makes it): private, as the server's banner
96
+ * names its API token, and never through a link. `{ fd }`, or `{ error }` when it can't be kept: a start goes on
97
+ * without it, and a start that fails says why there is none. */
98
+ function openStartLog(dataDir) {
99
+ try {
100
+ mkdirSync(dataDir, { recursive: true, mode: 0o700 });
101
+ const fd = openSync(join(dataDir, START_LOG), constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW, 0o600);
102
+ fchmodSync(fd, 0o600);
103
+ return { fd };
104
+ } catch (error) {
105
+ return { error };
106
+ }
107
+ }
108
+
109
+ /** Passes `source` (the server's stderr) on to `dest` (this command's) as it comes, at the pace `dest` is read: a slow
110
+ * reader slows the server, as an inherited stderr did, and nothing piles up here. Each chunk goes to `onChunk` too (the
111
+ * tail and the start log). A `dest` that fails (EPIPE: its reader went, a `| head`, a log reader restarting) never ends
112
+ * this command: the passing on stops, and `source` is still read, to `onChunk` and then dropped, so the server never
113
+ * blocks on a full pipe and is still stopped by this command's signals. */
114
+ export function forward(source, dest, onChunk) {
115
+ source.on("data", onChunk);
116
+ source.pipe(dest, { end: false });
117
+ dest.on("error", () => {
118
+ source.unpipe(dest);
119
+ source.resume();
120
+ });
121
+ }
122
+
123
+ /** Keeps the last TAIL_LINES whole lines of a stream's chunks (bytes, a character split between two chunks kept whole) in
124
+ * `tail`; `end()` keeps an unfinished last line too. */
125
+ function tailOf(tail) {
126
+ const decoder = new StringDecoder("utf8");
127
+ let pending = "";
128
+ const keep = (line) => {
129
+ tail.push(line.replace(/\r$/, ""));
130
+ if (tail.length > TAIL_LINES) tail.shift();
131
+ };
132
+ return {
133
+ add(chunk) {
134
+ pending += decoder.write(chunk);
135
+ for (let end = pending.indexOf("\n"); end >= 0; end = pending.indexOf("\n")) {
136
+ keep(pending.slice(0, end));
137
+ pending = pending.slice(end + 1);
138
+ }
139
+ },
140
+ end() {
141
+ pending += decoder.end();
142
+ if (pending !== "") keep(pending);
143
+ pending = "";
144
+ },
145
+ };
146
+ }
147
+
37
148
  /** The server's lines this command says too, as they come: its banner's boxes line (whether new agents get the Docker
38
149
  * box, or why not), and, on a server with a public address and no password yet, the setup link with its code, which
39
150
  * setup at that address asks for. */
@@ -214,32 +325,92 @@ export async function main(argv, env = process.env) {
214
325
  if (rest[0] && !rest[0].startsWith("-")) {
215
326
  // A server command (an eval among them, which spends while it runs): a stop sent to this command alone (a job
216
327
  // runner's SIGTERM, a SIGHUP) is passed on, and this waits for the command to clean up and end. A hangup is passed
217
- // on as a SIGTERM, which every server command stops on.
328
+ // on as a SIGTERM, which every server command stops on. Its output comes to this terminal as it is; a command that
329
+ // could not be started, or that a signal this command did not pass on ended, is said here (failureText).
218
330
  const child = spawn(launcher, [rest[0], ...data, ...rest.slice(1)], { stdio: "inherit", env: childEnv });
219
331
  const codes = { SIGINT: 130, SIGTERM: 143, SIGHUP: 129 };
220
- const pass = Object.fromEntries(Object.keys(codes).map((signal) => [signal, () => child.kill(signal === "SIGHUP" ? "SIGTERM" : signal)]));
332
+ const sent = [];
333
+ const pass = Object.fromEntries(Object.keys(codes).map((signal) => [signal, () => {
334
+ const passed = signal === "SIGHUP" ? "SIGTERM" : signal;
335
+ sent.push(passed);
336
+ child.kill(passed);
337
+ }]));
221
338
  for (const [signal, on] of Object.entries(pass)) process.on(signal, on);
339
+ const step = `run the server's ${rest[0]} command (${launcher})`;
222
340
  return new Promise((resolve) => {
341
+ let over = false;
223
342
  const done = (code) => {
343
+ if (over) return;
344
+ over = true;
224
345
  for (const [signal, on] of Object.entries(pass)) process.off(signal, on);
225
346
  resolve(code);
226
347
  };
227
- child.on("error", () => done(1));
228
- child.on("exit", (code, signal) => done(code ?? codes[signal] ?? 1));
348
+ child.on("error", (error) => {
349
+ if (child.pid === undefined && !over) console.error(failureText({ command: rest[0], step, error }));
350
+ done(1);
351
+ });
352
+ child.on("exit", (code, signal) => {
353
+ if (signal !== null && !sent.includes(signal)) console.error(failureText({ command: rest[0], step, code, signal, sent }));
354
+ done(code ?? codes[signal] ?? 1);
355
+ });
229
356
  });
230
357
  }
231
358
  // The server's banner and request lines stay out of this terminal: one line here says where to go, the URL of the
232
359
  // server's own "Open " line; the lines SAID names go to stderr after it, for the person, so stdout stays that one line.
233
- // What it prints on stderr (why it did not start) comes through as it is.
234
- const child = spawn(launcher, serverArgs([...data, ...rest]), { stdio: ["ignore", "pipe", "inherit"], env: childEnv });
360
+ // What it prints on stderr comes through as it is, as it prints it, at the pace this command's stderr is read (forward).
361
+ // Until the server prints the address, all it writes on either goes to the start log too, and the last lines of each are
362
+ // kept: a start that fails says them, with the step, how the server ended and the log (failureText).
363
+ const log = openStartLog(dataDir);
364
+ const logPath = log.fd === undefined ? undefined : join(dataDir, START_LOG);
365
+ // The first write to the log that failed (a full disk, a quota): the start goes on, the log keeps what it holds, and a
366
+ // start that fails says it is incomplete, and why.
367
+ let logIncomplete;
368
+ const toLog = (chunk) => {
369
+ if (log.fd === undefined || logIncomplete !== undefined) return;
370
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
371
+ try {
372
+ for (let at = 0; at < bytes.length; ) {
373
+ const wrote = writeSync(log.fd, bytes, at, bytes.length - at);
374
+ if (wrote <= 0) throw new Error(`wrote ${at} of ${bytes.length} bytes`);
375
+ at += wrote;
376
+ }
377
+ } catch (error) {
378
+ logIncomplete = error;
379
+ }
380
+ };
381
+ const closeLog = () => {
382
+ if (log.fd !== undefined) try { closeSync(log.fd); } catch {}
383
+ log.fd = undefined;
384
+ };
385
+ const child = spawn(launcher, serverArgs([...data, ...rest]), { stdio: ["ignore", "pipe", "pipe"], env: childEnv });
386
+ let started = false;
387
+ const errTail = [];
388
+ const errLines = tailOf(errTail);
389
+ forward(child.stderr, process.stderr, (chunk) => {
390
+ if (started) return;
391
+ toLog(chunk);
392
+ errLines.add(chunk);
393
+ });
394
+ child.stdout.on("data", (chunk) => { if (!started) toLog(chunk); });
395
+ // A child that could not be started (the launcher missing, or not executable) says so here, and never exits.
396
+ let spawnError;
397
+ const failedToSpawn = new Promise((resolve) => child.on("error", (error) => {
398
+ if (child.pid === undefined) spawnError ??= error;
399
+ resolve();
400
+ }));
235
401
  // A stop this command passes on (Ctrl-C, a process manager's SIGTERM, npm gone) is a clean end, 0, even when the signal
236
402
  // itself ends the server; a server ended by a signal nobody here sent is not.
237
403
  let stopping = false;
404
+ const sent = [];
238
405
  const stop = (signal) => {
239
406
  stopping = true;
407
+ sent.push(signal);
240
408
  child.kill(signal);
241
409
  };
242
- const exited = new Promise((resolve) => child.on("exit", (code) => resolve(code ?? (stopping ? 0 : 1))));
410
+ let ended;
411
+ const exit = new Promise((resolve) => child.on("exit", (code, signal) => resolve((ended = { code, signal }))));
412
+ const exited = exit.then(({ code }) => code ?? (stopping ? 0 : 1));
413
+ const closed = new Promise((resolve) => child.on("close", resolve));
243
414
  for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => stop(signal));
244
415
  // A SIGHUP to this command alone (not the terminal's, which reaches the server too) asks the server to stop as a SIGTERM
245
416
  // does.
@@ -265,14 +436,47 @@ export async function main(argv, env = process.env) {
265
436
  // A SAID line can come before the "Open " line too (the setup link is printed as the server attaches its owner, before
266
437
  // its banner): it is held and said first, in order.
267
438
  const seen = [];
268
- const url = await Promise.race([openUrl(child.stdout, env.AGENTRUN_PUBLIC_URL, seen, tell, tell), new Promise((resolve) => { timer = setTimeout(resolve, 60_000); })]);
439
+ const bound = startTimeoutMs(env);
440
+ const TIMED_OUT = Symbol("timed out");
441
+ const url = await Promise.race([openUrl(child.stdout, env.AGENTRUN_PUBLIC_URL, seen, tell, tell), new Promise((resolve) => { timer = setTimeout(() => resolve(TIMED_OUT), bound); })]);
269
442
  clearTimeout(timer);
270
- if (url === undefined) {
271
- child.kill("SIGTERM");
272
- // Its stdout is kept out of this terminal, so its last lines are shown here: with its stderr above, they say why.
273
- console.error(seen.length > 0 ? `AgentRun did not start. The server's last lines:\n${seen.map((line) => ` ${line}`).join("\n")}` : "AgentRun did not start; the server's own message, if it gave one, is above.");
274
- return (await exited) || 1;
443
+ if (url === undefined || url === TIMED_OUT) {
444
+ // Its stdout ended (it exited, was never started, or closed it), or the bound passed with it still running. A server
445
+ // still running is stopped: a SIGTERM, then a SIGKILL if it has not ended within STOP_GRACE_MS.
446
+ if (url === undefined) await within(Promise.race([exit, failedToSpawn]), 2_000);
447
+ let stopped;
448
+ if (spawnError === undefined && ended === undefined) {
449
+ stopped = url === TIMED_OUT ? "timeout" : "closed";
450
+ stop("SIGTERM");
451
+ if ((await within(exit, STOP_GRACE_MS)) === undefined) {
452
+ stop("SIGKILL");
453
+ await within(exit, 5_000);
454
+ }
455
+ }
456
+ // Its stderr, to the end: what it wrote last comes before the failure, and is in its tail.
457
+ if (spawnError === undefined) await within(closed, 2_000);
458
+ errLines.end();
459
+ const failure = failureText({
460
+ step: spawnError !== undefined ? `start the server (${launcher})` : `wait for the server to print the address to open (at most ${seconds(bound)})`,
461
+ error: spawnError,
462
+ code: ended?.code ?? null,
463
+ signal: ended?.signal ?? null,
464
+ stopped,
465
+ waitedMs: bound,
466
+ sent,
467
+ stderrTail: errTail,
468
+ stdoutTail: seen,
469
+ logPath,
470
+ logError: log.error,
471
+ logIncomplete,
472
+ });
473
+ toLog(`${failure}\n`);
474
+ closeLog();
475
+ console.error(failure);
476
+ return ended?.code || 1;
275
477
  }
478
+ started = true;
479
+ closeLog();
276
480
  console.log(`AgentRun is running at ${url}`);
277
481
  // For the person at the terminal (stderr, so stdout stays the one line a script reads): how to stop it, and where its
278
482
  // data is kept, which the next start opens again.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun",
3
- "version": "0.4.7",
3
+ "version": "0.4.8",
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",
@@ -16,7 +16,7 @@
16
16
  "NOTICE"
17
17
  ],
18
18
  "dependencies": {
19
- "@parcha/agentrun-serve": "0.1.0-beta.39"
19
+ "@parcha/agentrun-serve": "0.1.0-beta.40"
20
20
  },
21
21
  "scripts": {
22
22
  "test": "node --test 'test/*.test.mjs'"