@parcha/agentrun 0.3.4 → 0.3.6

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/start.mjs CHANGED
@@ -6,6 +6,7 @@ import { readFileSync } 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 { main as cli, NOUNS, words } from "./cli.mjs";
9
10
 
10
11
  export const SERVE_PACKAGE = "@parcha/agentrun-serve";
11
12
  /** This command's package at its version, handed to the server it starts (AGENTRUN_NPX_PACKAGE), so the server's hints
@@ -15,34 +16,53 @@ export const OWN_SPEC = `@parcha/agentrun@${JSON.parse(readFileSync(new URL("../
15
16
  export const HOST = "127.0.0.1"; // key-gate: loopback-rule the server this starts listens on this machine only
16
17
 
17
18
  /** The URL an "Open " line names: its first word after "Open ", when that is an http(s) URL on `HOST`, where the server
18
- * this command starts listens; any text after it (what the link does) is not part of it. Undefined for any other line. */
19
- export function openLineUrl(line) {
19
+ * this command starts listens, or at `publicUrl`'s origin, the address the server names instead when it was started with
20
+ * AGENTRUN_PUBLIC_URL; any text after it (what the link does) is not part of it. Undefined for any other line. */
21
+ export function openLineUrl(line, publicUrl) {
20
22
  const word = /^Open (\S+)/.exec(line)?.[1];
21
23
  if (word === undefined || !URL.canParse(word)) return undefined;
22
24
  const url = new URL(word);
23
- return (url.protocol === "http:" || url.protocol === "https:") && url.hostname === HOST ? word : undefined;
25
+ if (url.protocol !== "http:" && url.protocol !== "https:") return undefined;
26
+ if (url.hostname === HOST) return word;
27
+ return publicUrl !== undefined && URL.canParse(publicUrl) && url.origin === new URL(publicUrl).origin ? word : undefined;
24
28
  }
25
29
 
30
+ /** How many of the server's last output lines a start that fails shows. */
31
+ export const TAIL_LINES = 20;
32
+
33
+ /** The server's lines this command says too, as they come: its banner's boxes line (whether new agents get the Docker
34
+ * box, or why not) and the Docker box image's first build, as it starts and ends. */
35
+ export const SAID = /^(Boxes: |Preparing the Docker box image |The Docker box image )/;
36
+
26
37
  /** The address a person opens first, as the server says it: the URL of the first "Open " line of its output that names
27
38
  * one (openLineUrl). That line is the server's interface for it (the plain address today, a single-use sign-in link
28
39
  * once the server prints one), so this command never builds the address itself. Resolves undefined when the output ends
29
- * without one; the rest of the output is read and dropped, so the server never blocks on a full pipe. */
30
- export function openUrl(stdout) {
40
+ * without one. Until then, the last TAIL_LINES lines before it are kept in `seen`: what a start that fails shows. Every
41
+ * whole line after it goes to `onLine`; the rest of the output is read and dropped, so the server never blocks on a full
42
+ * pipe. */
43
+ export function openUrl(stdout, publicUrl, seen = [], onLine = () => {}) {
44
+ const keep = (line) => {
45
+ seen.push(line);
46
+ if (seen.length > TAIL_LINES) seen.shift();
47
+ };
31
48
  return new Promise((resolve) => {
32
49
  let pending = "";
33
50
  let found;
34
51
  stdout.setEncoding("utf8");
35
52
  stdout.on("data", (chunk) => {
36
- if (found !== undefined) return;
37
53
  pending += chunk;
38
- for (let end = pending.indexOf("\n"); end >= 0 && found === undefined; end = pending.indexOf("\n")) {
54
+ for (let end = pending.indexOf("\n"); end >= 0; end = pending.indexOf("\n")) {
39
55
  const line = pending.slice(0, end).replace(/\r$/, "");
40
56
  pending = pending.slice(end + 1);
41
- const url = openLineUrl(line);
42
- if (url !== undefined) resolve((found = url));
57
+ if (found !== undefined) onLine(line);
58
+ else if ((found = openLineUrl(line, publicUrl)) !== undefined) resolve(found);
59
+ else keep(line);
43
60
  }
44
61
  });
45
- stdout.on("end", () => resolve(found));
62
+ stdout.on("end", () => {
63
+ if (found === undefined && pending !== "") keep(pending);
64
+ resolve(found);
65
+ });
46
66
  });
47
67
  }
48
68
 
@@ -78,7 +98,9 @@ export function npmExecOf(env, from = process.ppid) {
78
98
  return undefined;
79
99
  }
80
100
 
81
- export const USAGE = "Usage: npx @parcha/agentrun [--port N] [--data DIR] [--no-open], or a server command: import, reset-password";
101
+ export const USAGE = `Usage: npx @parcha/agentrun [--port N] [--data DIR] [--no-open] start the server
102
+ npx @parcha/agentrun import|reset-password [--data DIR] a server command
103
+ npx @parcha/agentrun <command> [args] the server's API: agents, runs, triggers, ..., api (npx @parcha/agentrun help)`;
82
104
 
83
105
  /** The server's launcher, installed with this package (its dependency), or undefined. */
84
106
  export function installedServer(resolve = createRequire(import.meta.url).resolve) {
@@ -94,6 +116,7 @@ export function installedServer(resolve = createRequire(import.meta.url).resolve
94
116
  export const serverArgs = (argv) => (argv.includes("--no-open") ? argv.filter((arg) => arg !== "--no-open") : ["--open", ...argv]);
95
117
 
96
118
  export async function main(argv, env = process.env) {
119
+ if (NOUNS.has(words(argv)[0])) return cli(argv, env);
97
120
  if (argv.includes("--help") || argv.includes("-h")) return console.log(USAGE), 0;
98
121
  if (process.platform === "win32") return console.error("AgentRun's server runs on macOS and Linux; on Windows, use WSL or its container."), 1;
99
122
  const launcher = installedServer();
@@ -108,38 +131,67 @@ export async function main(argv, env = process.env) {
108
131
  // The data directory is ~/.agentrun unless --data names one, handed to the server and its subcommands (import,
109
132
  // reset-password) as --data (the server's own default is another directory). The server's hints name it too, so each
110
133
  // opens this same store.
111
- const at = argv.indexOf("--data");
112
- const data = ["--data", at >= 0 ? argv[at + 1] : join(homedir(), ".agentrun")];
113
- const rest = at >= 0 ? [...argv.slice(0, at), ...argv.slice(at + 2)] : argv;
134
+ // `--data <dir>` and `--data=<dir>` are the same option, and the last one wins, as the server reads them; the server is
135
+ // handed exactly one, so this command, its hint and the server agree on the directory.
136
+ let dir;
137
+ const rest = [];
138
+ for (let i = 0; i < argv.length; i++) {
139
+ if (argv[i] === "--data" && i + 1 < argv.length) dir = argv[++i];
140
+ else if (argv[i].startsWith("--data=")) dir = argv[i].slice("--data=".length);
141
+ else rest.push(argv[i]);
142
+ }
143
+ const dataDir = dir ?? join(homedir(), ".agentrun");
144
+ // A name that starts with a dash keeps the equals form: the server's parser reads "--data -x" as a missing value.
145
+ const data = dataDir.startsWith("-") ? [`--data=${dataDir}`] : ["--data", dataDir];
114
146
  if (rest[0] && !rest[0].startsWith("-")) {
115
147
  return new Promise((resolve) => spawn(launcher, [rest[0], ...data, ...rest.slice(1)], { stdio: "inherit", env: childEnv }).on("exit", (code) => resolve(code ?? 1)));
116
148
  }
117
149
  // The server's banner and request lines stay out of this terminal: one line here says where to go, the URL of the
118
- // server's own "Open " line. What it prints on stderr (why it did not start) comes through as it is.
150
+ // server's own "Open " line; the lines SAID names go to stderr after it, for the person, so stdout stays that one line.
151
+ // What it prints on stderr (why it did not start) comes through as it is.
119
152
  const child = spawn(launcher, serverArgs([...data, ...rest]), { stdio: ["ignore", "pipe", "inherit"], env: childEnv });
120
- const exited = new Promise((resolve) => child.on("exit", (code) => resolve(code ?? 1)));
121
- for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => child.kill(signal));
153
+ // A stop this command passes on (Ctrl-C, a process manager's SIGTERM, npm gone) is a clean end, 0, even when the signal
154
+ // itself ends the server; a server ended by a signal nobody here sent is not.
155
+ let stopping = false;
156
+ const stop = (signal) => {
157
+ stopping = true;
158
+ child.kill(signal);
159
+ };
160
+ const exited = new Promise((resolve) => child.on("exit", (code) => resolve(code ?? (stopping ? 0 : 1))));
161
+ for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => stop(signal));
122
162
  // A SIGHUP to this command alone (not the terminal's, which reaches the server too) asks the server to stop as a SIGTERM
123
163
  // does.
124
- process.on("SIGHUP", () => child.kill("SIGTERM"));
164
+ process.on("SIGHUP", () => stop("SIGTERM"));
125
165
  // When that npm goes, the server stops, as on a SIGTERM, and this ends.
126
166
  if (npm !== undefined) {
127
167
  const watch = setInterval(() => {
128
168
  if (!npmGone()) return;
129
169
  clearInterval(watch);
130
- child.kill("SIGTERM");
170
+ stop("SIGTERM");
131
171
  }, 1000);
132
172
  watch.unref();
133
173
  child.on("exit", () => clearInterval(watch));
134
174
  }
135
175
  let timer;
136
- const url = await Promise.race([openUrl(child.stdout), new Promise((resolve) => { timer = setTimeout(resolve, 60_000); })]);
176
+ let told = false;
177
+ const held = [];
178
+ const tell = (line) => SAID.test(line) && (told ? console.error(line) : held.push(line));
179
+ const seen = [];
180
+ const url = await Promise.race([openUrl(child.stdout, env.AGENTRUN_PUBLIC_URL, seen, tell), new Promise((resolve) => { timer = setTimeout(resolve, 60_000); })]);
137
181
  clearTimeout(timer);
138
182
  if (url === undefined) {
139
183
  child.kill("SIGTERM");
140
- console.error("AgentRun did not start; the server's lines above say why.");
184
+ // Its stdout is kept out of this terminal, so its last lines are shown here: with its stderr above, they say why.
185
+ 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, and the server printed nothing.");
141
186
  return (await exited) || 1;
142
187
  }
143
188
  console.log(`AgentRun is running at ${url}`);
189
+ // For the person at the terminal (stderr, so stdout stays the one line a script reads): how to stop it, and where its
190
+ // data is kept, which the next start opens again.
191
+ console.error(`Press Ctrl-C to stop it. Its data is in ${dataDir}.`);
192
+ // And where the API's bearer token is: the server prints it on a line this terminal doesn't show.
193
+ 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")}.`);
194
+ told = true;
195
+ for (const line of held.splice(0)) console.error(line);
144
196
  return exited;
145
197
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun",
3
- "version": "0.3.4",
3
+ "version": "0.3.6",
4
4
  "description": "Start AgentRun on this machine with one command: npx @parcha/agentrun",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -15,7 +15,7 @@
15
15
  "NOTICE"
16
16
  ],
17
17
  "dependencies": {
18
- "@parcha/agentrun-serve": "0.1.0-beta.29"
18
+ "@parcha/agentrun-serve": "0.1.0-beta.31"
19
19
  },
20
20
  "scripts": {
21
21
  "test": "node --test 'test/*.test.mjs'"