@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/README.md CHANGED
@@ -13,6 +13,12 @@ it in your browser (`--no-open`, a CI run or a machine with no display skips tha
13
13
  each version of this command runs the server it was released with. Node.js 22.19 or newer on 22, or 24.2 or newer, on
14
14
  macOS or Linux.
15
15
 
16
+ 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,
17
+ after the address, says so: `Boxes: docker (on by default; set AGENTRUN_BOXES to change).` Where it does not, that line says why
18
+ and that new agents run on the runner. The box image's first build takes a few minutes, said as it starts (`Preparing
19
+ the Docker box image (first start only, a few minutes); agents can be made now, and their first run waits for it.`)
20
+ and as it ends (`The Docker box image is ready.`). `AGENTRUN_BOXES=none` turns boxes off.
21
+
16
22
  pi runs every agent out of the box. The Claude Code and Codex harnesses need their own packages beside the server; when
17
23
  one is missing, AgentRun says so with the one command to paste: `npx` with this package, the server and that harness's
18
24
  package at their versions, with `--data` naming the same store.
@@ -24,5 +30,14 @@ the console's Settings → Model keys, which counts from the save on. Other comm
24
30
  `npx @parcha/agentrun reset-password` clears the console's password. `--data DIR` and `--port N` change where it keeps
25
31
  its data and the port it takes.
26
32
 
33
+ Every other command is the server's API, from a second terminal: `npx @parcha/agentrun agents list`,
34
+ `agents create --body @agent.json`, `runs start AGENT_ID --max-cost-usd 2 --body '{"input":{"content":"..."}}'`,
35
+ `runs get RUN_ID`, `runs message RUN_ID --content "..."`, and one command for each route the server serves
36
+ (`npx @parcha/agentrun help` lists them; `api METHOD PATH` calls any route). It finds the server started with the same
37
+ `--data` on its own: the server writes its address and where its token is to `DIR/.server.json` once it listens. For
38
+ another server, set `AGENTRUN_BASE_URL` and `AGENTRUN_API_KEY`. The response's JSON goes to stdout and an error's to
39
+ stderr; the exit code is 0 when it worked, 1 when the server refused, 2 for bad usage, 3 when the server cannot be
40
+ reached and 4 for a missing or refused token. The token is never a flag and never printed.
41
+
27
42
  The TypeScript SDK for the hosted AgentRun API is published as `@parcha/agentrun` 0.2.x, from its own repository; this
28
43
  package starts with 0.3.0, so a dependency on `^0.2` keeps the SDK.
package/lib/cli.mjs ADDED
@@ -0,0 +1,326 @@
1
+ // `npx @parcha/agentrun agents list`: the server's API from the terminal. Every command is an operation of the server's
2
+ // OpenAPI document, read from the generated table (commands.generated.mjs); nothing here is written per command.
3
+ import { closeSync, constants, fstatSync, openSync, readFileSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { join, resolve } from "node:path";
6
+ import { parseArgs } from "node:util";
7
+ import { COMMANDS } from "./commands.generated.mjs";
8
+
9
+ export const NOUNS = new Set(["api", "help", ...COMMANDS.map((entry) => entry.command[0])]);
10
+ const DEFAULT_BASE_URL = "http://127.0.0.1:7340/v2"; // key-gate: loopback-rule the default address of the server started on this machine
11
+ const START = "start it with `npx @parcha/agentrun`, or pass --base-url (or set AGENTRUN_BASE_URL) to the address the server printed";
12
+ const GLOBAL = { "base-url": { type: "string" }, data: { type: "string" }, help: { type: "boolean", short: "h" } };
13
+ const BODY = "--body JSON|@FILE|-";
14
+ const JSON_TYPE = /^application\/(?:[\w.+-]+\+)?json\b/;
15
+ // A header value fetch takes: no line break or other control character, nothing outside Latin-1.
16
+ const BAD_HEADER = /[\0-\x08\x0a-\x1f\x7f]|[^\0-\xff]/;
17
+
18
+ class Exit extends Error {
19
+ constructor(code, message) {
20
+ super(message);
21
+ this.code = code;
22
+ }
23
+ }
24
+ const usageError = (message) => new Exit(2, message);
25
+ const flag = (name) => name.replace(/_/g, "-").toLowerCase();
26
+
27
+ /** The words of `argv` that are not flags, past the values of the flags placed before a command (--data, --base-url,
28
+ * and the server's --port). */
29
+ export function words(argv) {
30
+ const found = [];
31
+ for (let i = 0; i < argv.length; i++) {
32
+ if (["--data", "--base-url", "--port"].includes(argv[i])) i++;
33
+ else if (!argv[i].startsWith("-")) found.push(argv[i]);
34
+ }
35
+ return found;
36
+ }
37
+
38
+ const HELP = () => {
39
+ const groups = new Map();
40
+ for (const { command, summary } of COMMANDS) groups.set(command[0], command.length === 1 ? [summary] : [...(groups.get(command[0]) ?? []), command[1]]);
41
+ const width = Math.max(...[...groups.keys()].map((noun) => noun.length));
42
+ return [
43
+ "Usage: npx @parcha/agentrun <command> [args] [--base-url URL] [--data DIR]",
44
+ "",
45
+ "Commands (agentrun <command> --help for a command's arguments):",
46
+ ...[...groups].map(([noun, verbs]) => ` ${noun.padEnd(width)} ${verbs.join(", ")}`),
47
+ ` ${"api".padEnd(width)} METHOD PATH [${BODY}] [--header 'NAME: VALUE'], any route, PATH under the base URL (/agents)`,
48
+ "",
49
+ "The server: --base-url, else AGENTRUN_BASE_URL, else base_url in $XDG_CONFIG_HOME/agentrun/config.json, else the",
50
+ "server started on this machine with the data directory (--data, default ~/.agentrun). The token: AGENTRUN_API_KEY,",
51
+ "else api_key in the config file, else that server's own; it is never a flag and never printed.",
52
+ "Output: the response's JSON on stdout, a file's bytes as they are; an error's on stderr. Exit codes: 0 ok, 1 the",
53
+ "server refused, 2 bad usage, 3 the server cannot be reached, 4 no token or the token was refused.",
54
+ ].join("\n");
55
+ };
56
+
57
+ const usageOf = (entry) => `agentrun ${entry.command.join(" ")}${entry.pathParams.map((name) => ` ${name.toUpperCase()}`).join("")}`;
58
+ const defaultType = (types) => (types.includes("application/json") ? "application/json" : types.includes("*/*") ? "application/octet-stream" : types[0]);
59
+
60
+ function commandHelp(entry) {
61
+ const flags = [...entry.query, ...entry.headers, ...entry.bodyFlags].map((f) => {
62
+ const value = f.type === "boolean" ? "" : ` ${f.enum ? f.enum.join("|") : f.type.toUpperCase()}`;
63
+ return [`--${flag(f.name)}${value}`, `${f.required ? "(required) " : ""}${f.description}`];
64
+ });
65
+ if (entry.hasBody) {
66
+ flags.push([BODY, entry.secretBody ? "the body, from stdin or a file only: it holds a secret" : "the body, inline, from a file or from stdin; flags win over a JSON body's fields"]);
67
+ flags.push(["--body-type TYPE", `the body's type: ${entry.bodyTypes.join(", ")} (default ${defaultType(entry.bodyTypes)}); any other than JSON is sent as given`]);
68
+ }
69
+ const width = Math.max(0, ...flags.map(([name]) => name.length));
70
+ return [`Usage: ${usageOf(entry)}${flags.length ? " [flags]" : ""}`, "", `${entry.summary} (${entry.method} ${entry.path})`, ...(flags.length ? ["", ...flags.map(([name, text]) => ` ${name.padEnd(width)} ${text}`.trimEnd())] : [])].join("\n");
71
+ }
72
+
73
+ const nounHelp = (noun, entries) => [`Usage: agentrun ${noun} <verb> [args]`, "", ...entries.map((entry) => ` ${usageOf(entry).padEnd(40)} ${entry.summary}`)].join("\n");
74
+
75
+ /** `file`'s JSON, or undefined when there is none. Never its text in a message: it may hold a key. */
76
+ function readJson(file, text) {
77
+ if (text === undefined) return undefined;
78
+ try {
79
+ return JSON.parse(text);
80
+ } catch {
81
+ throw usageError(`${file} is not valid JSON.`);
82
+ }
83
+ }
84
+
85
+ /** `file`'s text when it is a regular file of this user's that no one else may read or write, through no link; undefined
86
+ * when there is none. A file that fails that is refused: another user could have written it. */
87
+ function privateFile(file) {
88
+ let fd;
89
+ try {
90
+ fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
91
+ } catch (error) {
92
+ if (error.code === "ENOENT") return undefined;
93
+ throw new Exit(4, `${file} ${error.code === "ELOOP" ? "is a link" : `cannot be read (${error.code})`}; refusing it.`);
94
+ }
95
+ try {
96
+ const info = fstatSync(fd);
97
+ if (!info.isFile() || (process.getuid && info.uid !== process.getuid()) || (info.mode & 0o077) !== 0) {
98
+ throw new Exit(4, `${file} is not a private file of yours (a regular file you own, mode 0600); refusing it.`);
99
+ }
100
+ return readFileSync(fd, "utf8");
101
+ } finally {
102
+ closeSync(fd);
103
+ }
104
+ }
105
+
106
+ const alive = (pid) => {
107
+ try {
108
+ return process.kill(pid, 0);
109
+ } catch (error) {
110
+ return error.code === "EPERM";
111
+ }
112
+ };
113
+
114
+ const trim = (url) => url.replace(/\/+$/, "");
115
+
116
+ /** Where the request goes and the token it carries. A token goes only with the address it came with: the local
117
+ * server's own token is never sent to another server. The local token is DIR/.token, whatever the record says. */
118
+ function targetOf(values, env) {
119
+ const data = resolve(values.data ?? join(homedir(), ".agentrun"));
120
+ const configFile = join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "agentrun", "config.json");
121
+ const config = readJson(configFile, privateFile(configFile)) ?? {};
122
+ const recordFile = join(data, ".server.json");
123
+ const record = readJson(recordFile, privateFile(recordFile));
124
+ const stale = record && `The server recorded in ${recordFile} (pid ${record.pid}) is not running; start it with \`npx @parcha/agentrun\` or set AGENTRUN_BASE_URL.`;
125
+ const local = trim(record?.base_url ?? DEFAULT_BASE_URL);
126
+ const base = trim(values["base-url"] ?? env.AGENTRUN_BASE_URL ?? config.base_url ?? local);
127
+ let token = env.AGENTRUN_API_KEY || (config.base_url && base === trim(config.base_url) ? config.api_key : undefined);
128
+ const isLocal = base === local;
129
+ if (isLocal && record && !alive(record.pid)) throw new Exit(3, stale);
130
+ if (!token && isLocal) {
131
+ if (record && !record.token_file) throw new Exit(4, `The server recorded in ${recordFile} was started with its token in AGENTRUN_TOKEN; set AGENTRUN_API_KEY to it.`);
132
+ token = privateFile(join(data, ".token"))?.trim();
133
+ }
134
+ if (!token) {
135
+ throw new Exit(4, isLocal
136
+ ? `No token: AGENTRUN_API_KEY is not set and ${join(data, ".token")} does not exist; ${START}.`
137
+ : `No token for ${base}: set AGENTRUN_API_KEY.`);
138
+ }
139
+ if (BAD_HEADER.test(token)) throw new Exit(4, "The API key is not a valid header value (it holds a line break, a control character or a character outside Latin-1).");
140
+ return { base, token, unreachable: isLocal && record ? stale : undefined };
141
+ }
142
+
143
+ async function readBody(value, stdin) {
144
+ if (value === "-") {
145
+ const chunks = [];
146
+ for await (const chunk of stdin) chunks.push(chunk);
147
+ return Buffer.concat(chunks);
148
+ }
149
+ if (value.startsWith("@")) {
150
+ try {
151
+ return readFileSync(value.slice(1));
152
+ } catch (error) {
153
+ throw usageError(`--body ${value}: ${error.code === "ENOENT" ? "no such file" : `cannot be read (${error.code})`}`);
154
+ }
155
+ }
156
+ return Buffer.from(value);
157
+ }
158
+
159
+ /** The JSON in `bytes`, as `{ value }`, or undefined when they hold none. */
160
+ function jsonOf(bytes) {
161
+ try {
162
+ return { value: JSON.parse(bytes.toString("utf8")) };
163
+ } catch {
164
+ return undefined;
165
+ }
166
+ }
167
+
168
+ function coerce(f, value) {
169
+ if (f.type === "boolean") return value;
170
+ if (f.type === "number" || f.type === "integer") {
171
+ const n = Number(value);
172
+ if (value.trim() === "" || !Number.isFinite(n) || (f.type === "integer" && !Number.isInteger(n))) throw usageError(`--${flag(f.name)} takes ${f.type === "integer" ? "a whole number" : "a number"}, not ${value}`);
173
+ return n;
174
+ }
175
+ if (f.enum && !f.enum.includes(value)) throw usageError(`--${flag(f.name)} takes one of ${f.enum.join(", ")}, not ${value}`);
176
+ return value;
177
+ }
178
+
179
+ const refuseInline = (what, value) => {
180
+ if (value !== undefined && value !== "-" && !value.startsWith("@")) throw usageError(`${what} carries a secret: pass the body on stdin (--body -) or in a file (--body @FILE), never on the command line.`);
181
+ };
182
+
183
+ /** The operation whose body carries a secret that `method` on `path` reaches, once the path is normalized as fetch
184
+ * normalizes it (`..`, `.`, their encoded forms, repeated slashes). */
185
+ function secretAt(method, path) {
186
+ const pathname = new URL(`http://host/v2${path}`).pathname.replace(/\/{2,}/g, "/");
187
+ return COMMANDS.find((entry) => entry.secretBody && entry.method === method && new RegExp(`^/v2${entry.path.replace(/\{[^}]+\}/g, "[^/]+")}/?$`).test(pathname));
188
+ }
189
+
190
+ async function send(target, request, io) {
191
+ const headers = { ...request.headers, authorization: `Bearer ${target.token}`, accept: "application/json, */*" };
192
+ if (request.body !== undefined) headers["content-type"] = request.type;
193
+ let response;
194
+ try {
195
+ response = await fetch(`${target.base}${request.path}`, { method: request.method, headers, ...(request.body !== undefined ? { body: request.body } : {}) });
196
+ } catch (error) {
197
+ // Only the cause's code: a fetch error's message can quote a header, the token's among them.
198
+ throw new Exit(3, target.unreachable ?? `Cannot reach the server at ${target.base} (${error.cause?.code ?? error.name}); ${START}.`);
199
+ }
200
+ const bytes = Buffer.from(await response.arrayBuffer());
201
+ if (!response.ok) {
202
+ io.stderr.write(bytes.length ? bytes : `${response.status} ${response.statusText}`);
203
+ if (!bytes.length || bytes.at(-1) !== 10) io.stderr.write("\n");
204
+ return response.status === 401 || response.status === 403 ? 4 : 1;
205
+ }
206
+ if (response.status === 204 || bytes.length === 0) return 0;
207
+ const json = !request.raw && JSON_TYPE.test(response.headers.get("content-type") ?? "") ? jsonOf(bytes) : undefined;
208
+ if (json && io.stdout.isTTY) io.stdout.write(`${JSON.stringify(json.value, null, 2)}\n`);
209
+ else if (json) io.stdout.write(bytes.at(-1) === 10 ? bytes : Buffer.concat([bytes, Buffer.from("\n")]));
210
+ else io.stdout.write(bytes);
211
+ return 0;
212
+ }
213
+
214
+ const parse = (argv, options) => {
215
+ try {
216
+ return parseArgs({ args: argv, options, allowPositionals: true, allowNegative: true, strict: true });
217
+ } catch (error) {
218
+ throw usageError(error.message);
219
+ }
220
+ };
221
+
222
+ const checkHeader = (name, value) => {
223
+ if (BAD_HEADER.test(value)) throw usageError(`The value of ${name} is not a valid header value.`);
224
+ };
225
+
226
+ async function api(argv, env, io) {
227
+ const { values, positionals } = parse(argv, { ...GLOBAL, body: { type: "string" }, header: { type: "string", multiple: true } });
228
+ const [, method, path] = positionals;
229
+ if (values.help || method === undefined) return io.stdout.write(`Usage: agentrun api METHOD PATH [${BODY}] [--header 'NAME: VALUE']...\n\nAny route of the server; PATH is under the base URL (/agents, /runs/RUN_ID).\n`), values.help ? 0 : 2;
230
+ if (path === undefined || !path.startsWith("/") || positionals.length > 3) throw usageError("Usage: agentrun api METHOD PATH [--body JSON|@FILE|-]; PATH starts with /");
231
+ // fetch resolves `.` and `..` (and their encoded forms) against the base URL's own path, which may be longer than /v2.
232
+ const segments = path.split(/[?#]/)[0].split("/").slice(1).map((segment) => segment.replace(/%2e/gi, "."));
233
+ if (segments.some((segment, i) => segment === "." || segment === ".." || (segment === "" && i < segments.length - 1))) throw usageError("agentrun api: PATH may not hold a . or .. segment or an empty one (//).");
234
+ const verb = method.toUpperCase();
235
+ const secret = secretAt(verb, path);
236
+ if (secret) refuseInline(`${verb} ${secret.path}`, values.body);
237
+ const headers = {};
238
+ for (const line of values.header ?? []) {
239
+ const at = line.indexOf(":");
240
+ const name = line.slice(0, at).trim();
241
+ if (at <= 0 || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) throw usageError("--header takes 'NAME: VALUE'.");
242
+ if (["authorization", "cookie"].includes(name.toLowerCase())) throw usageError(`--header cannot set ${name}: the token is never a flag.`);
243
+ checkHeader(name, line.slice(at + 1).trim());
244
+ headers[name.toLowerCase()] = line.slice(at + 1).trim();
245
+ }
246
+ const body = values.body === undefined ? undefined : await readBody(values.body, io.stdin);
247
+ const type = headers["content-type"] ?? (body !== undefined && jsonOf(body) ? "application/json" : "application/octet-stream");
248
+ return send(targetOf(values, env), { method: verb, path, headers, body, type }, io);
249
+ }
250
+
251
+ async function command(entry, argv, env, io) {
252
+ const options = { ...GLOBAL };
253
+ for (const f of [...entry.query, ...entry.headers, ...entry.bodyFlags]) options[flag(f.name)] = { type: f.type === "boolean" ? "boolean" : "string" };
254
+ if (entry.hasBody) Object.assign(options, { body: { type: "string" }, "body-type": { type: "string" } });
255
+ const { values, positionals } = parse(argv, options);
256
+ if (values.help) return io.stdout.write(`${commandHelp(entry)}\n`), 0;
257
+ const args = positionals.slice(entry.command.length);
258
+ if (args.length !== entry.pathParams.length) throw usageError(`${commandHelp(entry)}\n\n${usageOf(entry)} takes ${entry.pathParams.length || "no"} argument${entry.pathParams.length === 1 ? "" : "s"}, given ${args.length}.`);
259
+ // A `.` or `..` segment would take the request to another route once fetch normalizes the path.
260
+ if (args.some((arg) => arg.split("/").some((segment) => segment === "." || segment === ".."))) throw usageError(`${usageOf(entry)}: an argument may not hold a . or .. path segment.`);
261
+ const path = entry.path.replace(/\{([^}]+)\}/g, (_, name) => {
262
+ const value = args[entry.pathParams.indexOf(name)];
263
+ if (!entry.multiSegment.includes(name)) return encodeURIComponent(value);
264
+ // A file path keeps its slashes, so no segment may be one fetch or the server would read otherwise.
265
+ const segments = value.split("/");
266
+ if (segments.some((segment) => segment === "" || /%2f/i.test(segment) || [".", ".."].includes(segment.replace(/%2e/gi, ".")))) {
267
+ throw usageError(`${usageOf(entry)}: ${name.toUpperCase()} may not hold an empty, . or .. segment (plain or encoded) or an encoded slash.`);
268
+ }
269
+ return segments.map(encodeURIComponent).join("/");
270
+ });
271
+ const query = new URLSearchParams();
272
+ for (const q of entry.query) {
273
+ const value = values[flag(q.name)];
274
+ if (value !== undefined) query.set(q.name, String(coerce(q, value)));
275
+ else if (q.required) throw usageError(`${usageOf(entry)} needs --${flag(q.name)}.`);
276
+ }
277
+ const headers = {};
278
+ for (const h of entry.headers) {
279
+ const value = values[flag(h.name)];
280
+ if (value !== undefined) checkHeader(`--${flag(h.name)}`, (headers[h.name] = String(coerce(h, value))));
281
+ else if (h.required) throw usageError(`${usageOf(entry)} needs --${flag(h.name)}.`);
282
+ }
283
+ if (entry.secretBody) refuseInline(entry.command.join(" "), values.body);
284
+ const type = values["body-type"] ?? (entry.hasBody ? defaultType(entry.bodyTypes) : undefined);
285
+ if (values["body-type"] !== undefined && !entry.bodyTypes.includes(type) && !entry.bodyTypes.includes("*/*")) throw usageError(`${usageOf(entry)} takes a body of type ${entry.bodyTypes.join(", ")}.`);
286
+ let body = values.body === undefined ? undefined : await readBody(values.body, io.stdin);
287
+ const fields = entry.bodyFlags.filter((f) => values[flag(f.name)] !== undefined).map((f) => [f.name, coerce(f, values[flag(f.name)])]);
288
+ if (fields.length && !JSON_TYPE.test(type)) throw usageError(`--${flag(fields[0][0])} is a field of the JSON body, and this body is ${type}.`);
289
+ if (JSON_TYPE.test(type ?? "") && body !== undefined && !jsonOf(body)) throw usageError("--body is not JSON.");
290
+ if (fields.length) {
291
+ const object = body === undefined ? {} : jsonOf(body).value;
292
+ if (object === null || typeof object !== "object" || Array.isArray(object)) throw usageError("--body is not a JSON object, so it cannot take the flags' fields.");
293
+ body = JSON.stringify({ ...object, ...Object.fromEntries(fields) });
294
+ }
295
+ if (entry.bodyRequired && body === undefined) throw usageError(`${usageOf(entry)} needs a body: ${BODY}.`);
296
+ const search = query.size ? `?${query}` : "";
297
+ return send(targetOf(values, env), { method: entry.method, path: `${path}${search}`, headers, body, type, raw: entry.raw }, io);
298
+ }
299
+
300
+ async function run(argv, env, io) {
301
+ const [noun, verb] = words(argv);
302
+ if (noun === undefined || noun === "help") return io.stdout.write(`${HELP()}\n`), 0;
303
+ if (noun === "api") return api(argv, env, io);
304
+ const entries = COMMANDS.filter((entry) => entry.command[0] === noun);
305
+ if (!entries.length) throw usageError(`agentrun has no command ${noun}.\n\n${HELP()}`);
306
+ const entry = entries.find((e) => e.command.length === 1 || e.command[1] === verb);
307
+ if (entry) return command(entry, argv, env, io);
308
+ if (verb === undefined) return io.stdout.write(`${nounHelp(noun, entries)}\n`), 0;
309
+ throw usageError(`agentrun ${noun} has no verb ${verb}.\n\n${nounHelp(noun, entries)}`);
310
+ }
311
+
312
+ export async function main(argv, env = process.env, io = process) {
313
+ // A reader that stops early (`| head`) closes stdout: the command ends quietly, as it would have. Stdout is written only
314
+ // once a request succeeded (or for help), so that is exit 0. Any other write error still throws.
315
+ io.stdout.on("error", (error) => {
316
+ if (error.code !== "EPIPE") throw error;
317
+ process.exit(0);
318
+ });
319
+ try {
320
+ return await run(argv, env, io);
321
+ } catch (error) {
322
+ if (!(error instanceof Exit)) throw error;
323
+ io.stderr.write(`${error.message}\n`);
324
+ return error.code;
325
+ }
326
+ }