@parcha/agentrun 0.3.5 → 0.4.0
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 +25 -2
- package/lib/cli.mjs +490 -0
- package/lib/commands.generated.mjs +2606 -0
- package/lib/follow.mjs +260 -0
- package/lib/login.mjs +208 -0
- package/lib/skill.mjs +88 -0
- package/lib/start.mjs +149 -22
- package/lib/template.mjs +75 -0
- package/package.json +4 -3
- package/skills/agentrun-cli/SKILL.md +138 -0
- package/skills/agentrun-cli/references/commands.md +793 -0
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,22 @@ 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
|
|
|
27
|
-
|
|
28
|
-
|
|
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
|
+
|
|
42
|
+
`runs wait RUN_ID` waits until the run ends or waits on a person and prints it; `runs start AGENT_ID ... --wait` starts
|
|
43
|
+
a run and does the same. Its exit code says how it stopped: 0 completed, 1 failed or cancelled, 8 it waits on a person
|
|
44
|
+
(a question, its spend cap, a stopped turn, a paused workflow run), with a line on stderr saying what to do next, such as
|
|
45
|
+
`runs message RUN_ID --content "..."` to answer. `--timeout SECONDS` stops waiting after that long and exits 1; the run
|
|
46
|
+
goes on. `runs timeline RUN_ID --follow` prints the timeline as it changes, one page per line (NDJSON): upsert its
|
|
47
|
+
`rows` by `id`, delete its `drop` ids, and drop everything first on a page with `reset: true`. It resumes a dropped
|
|
48
|
+
connection where it left off and ends when the run ends, 0 completed, 1 failed or cancelled.
|
|
49
|
+
|
|
50
|
+
The TypeScript client for this server is `@parcha/agentrun-client` (packages/client), and the Python client is
|
|
51
|
+
`parcha-agentrun` (python/).
|
package/lib/cli.mjs
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
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. Waiting for
|
|
3
|
+
// a run and following it live (runs start --wait, runs wait, runs timeline --follow) are follow.mjs's; the commands that
|
|
4
|
+
// read a secret from stdin (login, logout) are login.mjs's, skill install is skill.mjs's, and template
|
|
5
|
+
// validate and template eval, which check and run a package folder on this machine, are template.mjs's.
|
|
6
|
+
import { closeSync, constants, fstatSync, openSync, readFileSync } from "node:fs";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { join, resolve } from "node:path";
|
|
9
|
+
import { parseArgs } from "node:util";
|
|
10
|
+
import { COMMANDS, SECRET_ROUTES } from "./commands.generated.mjs";
|
|
11
|
+
import { FLAGS, REQUEST_MS, WAIT, followTimeline, timerMs, waitRun } from "./follow.mjs";
|
|
12
|
+
import { SECRETS, guarded } from "./login.mjs";
|
|
13
|
+
import { SKILL_INSTALL } from "./skill.mjs";
|
|
14
|
+
import { TEMPLATE_EVAL, TEMPLATE_VALIDATE } from "./template.mjs";
|
|
15
|
+
|
|
16
|
+
/** The hand-written commands that run as they are given (`run`), beside the table's. */
|
|
17
|
+
const LOCAL = [...SECRETS, SKILL_INSTALL, TEMPLATE_VALIDATE, TEMPLATE_EVAL];
|
|
18
|
+
export const NOUNS = new Set(["api", "help", ...[...COMMANDS, ...LOCAL].map((entry) => entry.command[0])]);
|
|
19
|
+
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
|
|
20
|
+
const START = "start it with `npx @parcha/agentrun`, or pass --base-url (or set AGENTRUN_BASE_URL) to the address the server printed";
|
|
21
|
+
const GLOBAL = { "base-url": { type: "string" }, data: { type: "string" }, help: { type: "boolean", short: "h" } };
|
|
22
|
+
const BODY = "--body JSON|@FILE|-";
|
|
23
|
+
const ACCEPT = "application/json, */*";
|
|
24
|
+
const JSON_TYPE = /^application\/(?:[\w.+-]+\+)?json\b/;
|
|
25
|
+
// A header value fetch takes: no line break or other control character, nothing outside Latin-1.
|
|
26
|
+
const BAD_HEADER = /[\0-\x08\x0a-\x1f\x7f]|[^\0-\xff]/;
|
|
27
|
+
|
|
28
|
+
class Exit extends Error {
|
|
29
|
+
constructor(code, message) {
|
|
30
|
+
super(message);
|
|
31
|
+
this.code = code;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const usageError = (message) => new Exit(2, message);
|
|
35
|
+
const flag = (name) => name.replace(/_/g, "-").toLowerCase();
|
|
36
|
+
|
|
37
|
+
/** The words of `argv` that are not flags, past the values of the flags placed before a command (--data, --base-url,
|
|
38
|
+
* and the server's --port). */
|
|
39
|
+
export function words(argv) {
|
|
40
|
+
const found = [];
|
|
41
|
+
for (let i = 0; i < argv.length; i++) {
|
|
42
|
+
if (["--data", "--base-url", "--port"].includes(argv[i])) i++;
|
|
43
|
+
else if (!argv[i].startsWith("-")) found.push(argv[i]);
|
|
44
|
+
}
|
|
45
|
+
return found;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const HELP = () => {
|
|
49
|
+
const groups = new Map();
|
|
50
|
+
for (const { command, summary } of [...COMMANDS, WAIT, ...LOCAL]) groups.set(command[0], command.length === 1 ? [summary] : [...(groups.get(command[0]) ?? []), command[1]].sort());
|
|
51
|
+
const width = Math.max(...[...groups.keys()].map((noun) => noun.length));
|
|
52
|
+
return [
|
|
53
|
+
"Usage: npx @parcha/agentrun <command> [args] [--base-url URL] [--data DIR]",
|
|
54
|
+
"",
|
|
55
|
+
"Commands (agentrun <command> --help for a command's arguments):",
|
|
56
|
+
...[...groups].map(([noun, verbs]) => ` ${noun.padEnd(width)} ${verbs.join(", ")}`),
|
|
57
|
+
` ${"api".padEnd(width)} METHOD PATH [${BODY}] [--header 'NAME: VALUE'], any route, PATH under the base URL (/agents)`,
|
|
58
|
+
"",
|
|
59
|
+
"The server: --base-url, else AGENTRUN_BASE_URL, else base_url in $XDG_CONFIG_HOME/agentrun/config.json, else the",
|
|
60
|
+
"server started on this machine with the data directory (--data, default ~/.agentrun). The token: AGENTRUN_API_KEY,",
|
|
61
|
+
"else api_key in the config file, else that server's own; it is never a flag and never printed. agentrun login",
|
|
62
|
+
"--base-url URL checks a token read from stdin and writes the config file (0600); agentrun logout removes it.",
|
|
63
|
+
"Keys and other secrets are set in the console, signed in: the token can't write one, so no command does.",
|
|
64
|
+
"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",
|
|
65
|
+
"server refused, 2 bad usage (a bad base URL among it), 3 the server cannot be reached, 4 no token, the token was",
|
|
66
|
+
"refused, or the config file, the server's record or its token file was refused. runs wait and runs start --wait",
|
|
67
|
+
"print the run once it ends or waits on a person: 0 completed, 1 failed, cancelled or --timeout passed (it goes on),",
|
|
68
|
+
"8 it waits on a person (a question, its spend cap, a stopped turn, a paused workflow). runs timeline --follow prints",
|
|
69
|
+
"the timeline's pages as they come, one JSON object per line, until the run ends: 0 completed, 1 failed or cancelled.",
|
|
70
|
+
].join("\n");
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const usageOf = (entry) => `agentrun ${entry.command.join(" ")}${entry.pathParams.map((name) => ` ${name.toUpperCase()}`).join("")}`;
|
|
74
|
+
const helpOf = (entry, flags) => {
|
|
75
|
+
const width = Math.max(0, ...flags.map(([name]) => name.length));
|
|
76
|
+
return [`Usage: ${usageOf(entry)}${flags.length ? " [flags]" : ""}`, "", `${entry.summary}${entry.method ? ` (${entry.method} ${entry.path})` : ""}`, ...(flags.length ? ["", ...flags.map(([name, text]) => ` ${name.padEnd(width)} ${text}`.trimEnd())] : [])].join("\n");
|
|
77
|
+
};
|
|
78
|
+
const defaultType = (types) => (types.includes("application/json") ? "application/json" : types.includes("*/*") ? "application/octet-stream" : types[0]);
|
|
79
|
+
|
|
80
|
+
/** What a body made of flags alone carries besides them, as help says it. */
|
|
81
|
+
const fillLine = (fill) => `Built from flags alone, the body also has: ${Object.entries(fill).map(([name, value]) => `${name} ${JSON.stringify(value)}`).join(", ")}.`;
|
|
82
|
+
|
|
83
|
+
function commandHelp(entry) {
|
|
84
|
+
const flags = [...entry.query, ...entry.headers, ...entry.bodyFlags].map((f) => {
|
|
85
|
+
const value = f.type === "boolean" ? "" : ` ${f.enum ? f.enum.join("|") : f.type.toUpperCase()}`;
|
|
86
|
+
return [`--${flag(f.name)}${value}`, `${f.required ? "(required) " : ""}${f.description}`];
|
|
87
|
+
});
|
|
88
|
+
if (entry.hasBody) {
|
|
89
|
+
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"]);
|
|
90
|
+
flags.push(["--body-type TYPE", `the body's type: ${entry.bodyTypes.join(", ")} (default ${defaultType(entry.bodyTypes)}); any other than JSON is sent as given`]);
|
|
91
|
+
}
|
|
92
|
+
const filled = entry.bodyFill ? `\n\n${fillLine(entry.bodyFill)}` : "";
|
|
93
|
+
const help = `${helpOf(entry, [...flags, ...(FLAGS[entry.operationId]?.help ?? [])])}${filled}`;
|
|
94
|
+
// The document's working body, ready to paste: single-quoted for a POSIX shell.
|
|
95
|
+
return entry.example === undefined ? help : `${help}\n\nExample:\n ${usageOf(entry)} --body '${JSON.stringify(entry.example).replace(/'/g, "'\\''")}'`;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const nounHelp = (noun, entries) => [`Usage: agentrun ${noun} <verb> [args]`, "", ...entries.map((entry) => ` ${usageOf(entry).padEnd(40)} ${entry.summary}`)].join("\n");
|
|
99
|
+
|
|
100
|
+
/** `file`'s JSON, or undefined when there is none. Never its text in a message: it may hold a key. */
|
|
101
|
+
function readJson(file, text) {
|
|
102
|
+
if (text === undefined) return undefined;
|
|
103
|
+
try {
|
|
104
|
+
return JSON.parse(text);
|
|
105
|
+
} catch {
|
|
106
|
+
throw usageError(`${file} is not valid JSON.`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** `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
|
|
111
|
+
* when there is none. A file that fails that is refused: another user could have written it. */
|
|
112
|
+
function privateFile(file) {
|
|
113
|
+
let fd;
|
|
114
|
+
try {
|
|
115
|
+
// O_NONBLOCK: a FIFO planted there opens at once, and fstat refuses it, rather than the open waiting for a writer.
|
|
116
|
+
fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
117
|
+
} catch (error) {
|
|
118
|
+
if (error.code === "ENOENT") return undefined;
|
|
119
|
+
throw new Exit(4, `${file} ${error.code === "ELOOP" ? "is a link" : `cannot be read (${error.code})`}; refusing it.`);
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
const info = fstatSync(fd);
|
|
123
|
+
if (!info.isFile() || (process.getuid && info.uid !== process.getuid()) || (info.mode & 0o077) !== 0) {
|
|
124
|
+
throw new Exit(4, `${file} is not a private file of yours (a regular file you own, mode 0600); refusing it.`);
|
|
125
|
+
}
|
|
126
|
+
return readFileSync(fd, "utf8");
|
|
127
|
+
} finally {
|
|
128
|
+
closeSync(fd);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const alive = (pid) => {
|
|
133
|
+
try {
|
|
134
|
+
return process.kill(pid, 0);
|
|
135
|
+
} catch (error) {
|
|
136
|
+
return error.code === "EPERM";
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
const trim = (url) => url.replace(/\/+$/, "");
|
|
141
|
+
|
|
142
|
+
/** A base URL as every command takes it: http or https, with no query, fragment, user or password, which would carry
|
|
143
|
+
* the token elsewhere or swallow the path appended to it. `where` names it in the refusal; the URL itself is never
|
|
144
|
+
* echoed, as it may hold a password. */
|
|
145
|
+
function baseOf(given, where) {
|
|
146
|
+
const url = URL.canParse(given) ? new URL(given) : undefined;
|
|
147
|
+
if (!url || !/^https?:$/.test(url.protocol) || /[?#]/.test(given) || url.username || url.password) {
|
|
148
|
+
throw usageError(`${where} must be an http or https URL with no query, fragment, user or password: the API's base, ending /v2.`);
|
|
149
|
+
}
|
|
150
|
+
return trim(given);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const isBase = (url) => {
|
|
154
|
+
try {
|
|
155
|
+
return baseOf(url, ""), true;
|
|
156
|
+
} catch {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
/** Where the request goes and the token it carries. A token goes only with the address it came with: the local
|
|
162
|
+
* server's own token is never sent to another server. The local token is DIR/.token, whatever the record says. */
|
|
163
|
+
function targetOf(values, env) {
|
|
164
|
+
const data = resolve(values.data ?? join(homedir(), ".agentrun"));
|
|
165
|
+
const configFile = join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "agentrun", "config.json");
|
|
166
|
+
const config = readJson(configFile, privateFile(configFile)) ?? {};
|
|
167
|
+
if (["base_url", "api_key"].some((field) => config[field] !== undefined && typeof config[field] !== "string")) {
|
|
168
|
+
throw new Exit(4, `${configFile} is not a CLI config (base_url and api_key, when there, are strings); refusing it.`);
|
|
169
|
+
}
|
|
170
|
+
const recordFile = join(data, ".server.json");
|
|
171
|
+
const record = readJson(recordFile, privateFile(recordFile));
|
|
172
|
+
// A record whose base_url baseOf refuses is refused as a malformed one is, exit 4: the file is wrong, not the usage.
|
|
173
|
+
if (record !== undefined && (typeof record?.base_url !== "string" || !isBase(record.base_url) || !Number.isInteger(record.pid) || record.pid <= 0)) {
|
|
174
|
+
throw new Exit(4, `${recordFile} is not a server record (base_url an http or https URL with no query, fragment, user or password, pid a positive whole number); refusing it.`);
|
|
175
|
+
}
|
|
176
|
+
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.`;
|
|
177
|
+
const local = baseOf(record?.base_url ?? DEFAULT_BASE_URL, `base_url in ${recordFile}`);
|
|
178
|
+
const base = values["base-url"] !== undefined ? baseOf(values["base-url"], "--base-url")
|
|
179
|
+
: env.AGENTRUN_BASE_URL !== undefined ? baseOf(env.AGENTRUN_BASE_URL, "AGENTRUN_BASE_URL")
|
|
180
|
+
: config.base_url !== undefined ? baseOf(config.base_url, `base_url in ${configFile}`)
|
|
181
|
+
: local;
|
|
182
|
+
let token = env.AGENTRUN_API_KEY || (config.base_url && base === trim(config.base_url) ? config.api_key : undefined);
|
|
183
|
+
const isLocal = base === local;
|
|
184
|
+
if (isLocal && record && !alive(record.pid)) throw new Exit(3, stale);
|
|
185
|
+
if (!token && isLocal) {
|
|
186
|
+
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.`);
|
|
187
|
+
token = privateFile(join(data, ".token"))?.trim();
|
|
188
|
+
}
|
|
189
|
+
if (!token) {
|
|
190
|
+
throw new Exit(4, isLocal
|
|
191
|
+
? `No token: AGENTRUN_API_KEY is not set and ${join(data, ".token")} does not exist; ${START}.`
|
|
192
|
+
: `No token for ${base}: set AGENTRUN_API_KEY.`);
|
|
193
|
+
}
|
|
194
|
+
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).");
|
|
195
|
+
return { base, token, unreachable: isLocal && record ? stale : undefined };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async function readBody(value, stdin) {
|
|
199
|
+
if (value === "-") {
|
|
200
|
+
const chunks = [];
|
|
201
|
+
for await (const chunk of stdin) chunks.push(chunk);
|
|
202
|
+
return Buffer.concat(chunks);
|
|
203
|
+
}
|
|
204
|
+
if (value.startsWith("@")) {
|
|
205
|
+
try {
|
|
206
|
+
return readFileSync(value.slice(1));
|
|
207
|
+
} catch (error) {
|
|
208
|
+
throw usageError(`--body ${value}: ${error.code === "ENOENT" ? "no such file" : `cannot be read (${error.code})`}`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return Buffer.from(value);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** The JSON in `bytes`, as `{ value }`, or undefined when they hold none. */
|
|
215
|
+
function jsonOf(bytes) {
|
|
216
|
+
try {
|
|
217
|
+
return { value: JSON.parse(bytes.toString("utf8")) };
|
|
218
|
+
} catch {
|
|
219
|
+
return undefined;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function coerce(f, value) {
|
|
224
|
+
if (f.type === "boolean") return value;
|
|
225
|
+
if (f.type === "number" || f.type === "integer") {
|
|
226
|
+
const n = Number(value);
|
|
227
|
+
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}`);
|
|
228
|
+
return n;
|
|
229
|
+
}
|
|
230
|
+
if (f.enum && !f.enum.includes(value)) throw usageError(`--${flag(f.name)} takes one of ${f.enum.join(", ")}, not ${value}`);
|
|
231
|
+
return value;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const refuseInline = (what, value) => {
|
|
235
|
+
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.`);
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
/** A body refused inline for a request whose path ends like a secret route once resolved (`landed`, secretAt's): it may
|
|
239
|
+
* be any command's (a home file at settings/tool-keys/x), but the guard fails closed, and says so. */
|
|
240
|
+
const refuseLanded = (landed, value) => {
|
|
241
|
+
if (value !== undefined && value !== "-" && !value.startsWith("@")) throw usageError(`This request's path, with the base URL's, ends like the secret route ${landed.method} ${landed.path}, so its body is held as a secret: pass it on stdin (--body -) or from a file (--body @FILE), not on the command line.`);
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
/** The operation whose body carries a secret that `method` on `url` reaches, once its path is normalized as fetch
|
|
245
|
+
* normalizes it (`..`, `.`, their encoded forms, repeated slashes): the operation's route at the end of the path,
|
|
246
|
+
* whatever part of it the base URL holds. */
|
|
247
|
+
function secretAt(method, url) {
|
|
248
|
+
const pathname = new URL(url).pathname.replace(/\/{2,}/g, "/");
|
|
249
|
+
const route = (entry) => new RegExp(`(?:^|/)${entry.path.slice(1).split(/\{[^}]+\}/).map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[^/]+")}/?$`);
|
|
250
|
+
return SECRET_ROUTES.find((entry) => entry.method === method && route(entry).test(pathname));
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Requests to the target, each with its token (follow.mjs makes its own through one): `fetch(path, init)`, exit 3 for
|
|
254
|
+
* a server not reached, a refused answer's body on stderr with its exit code, and JSON on stdout. */
|
|
255
|
+
function clientOf(target, io) {
|
|
256
|
+
return {
|
|
257
|
+
io,
|
|
258
|
+
// The caller's headers, by name in any case; the default Accept only when they set none; the token last, always.
|
|
259
|
+
fetch: (path, { method = "GET", headers = {}, body, signal } = {}) => {
|
|
260
|
+
const sent = new Headers(headers);
|
|
261
|
+
if (!sent.has("accept")) sent.set("accept", ACCEPT);
|
|
262
|
+
sent.set("authorization", `Bearer ${target.token}`);
|
|
263
|
+
return fetch(`${target.base}${path}`, { method, signal, headers: sent, ...(body !== undefined ? { body } : {}) });
|
|
264
|
+
},
|
|
265
|
+
// Only the cause's code: a fetch error's message can quote a header, the token's among them.
|
|
266
|
+
unreachable: (error) => new Exit(3, target.unreachable ?? `Cannot reach the server at ${target.base} (${error?.cause?.code ?? error?.name}); ${START}.`),
|
|
267
|
+
refused(response, bytes) {
|
|
268
|
+
io.stderr.write(bytes.length ? bytes : `${response.status} ${response.statusText}`);
|
|
269
|
+
if (!bytes.length || bytes.at(-1) !== 10) io.stderr.write("\n");
|
|
270
|
+
return response.status === 401 || response.status === 403 ? 4 : 1;
|
|
271
|
+
},
|
|
272
|
+
print: (value) => io.stdout.write(`${io.stdout.isTTY ? JSON.stringify(value, null, 2) : JSON.stringify(value)}\n`),
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** One request: `{ response, bytes }`, `{ code }` once it was refused (its error on stderr), or `{ late: true }` once
|
|
277
|
+
* `signal`, when given, ended it first. */
|
|
278
|
+
async function request(client, { method, path, headers, body, type, signal }) {
|
|
279
|
+
try {
|
|
280
|
+
const sent = new Headers(headers);
|
|
281
|
+
if (body !== undefined) sent.set("content-type", type);
|
|
282
|
+
const response = await client.fetch(path, { method, signal, headers: sent, body });
|
|
283
|
+
const bytes = Buffer.from(await response.arrayBuffer());
|
|
284
|
+
return response.ok ? { response, bytes } : { code: client.refused(response, bytes) };
|
|
285
|
+
} catch (error) {
|
|
286
|
+
if (signal?.aborted) return { late: true };
|
|
287
|
+
throw client.unreachable(error);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** One request, its answer on stdout; the exit code. */
|
|
292
|
+
async function send(client, req) {
|
|
293
|
+
const { response, bytes, code } = await request(client, req);
|
|
294
|
+
if (code !== undefined) return code;
|
|
295
|
+
const { io } = client;
|
|
296
|
+
if (response.status === 204 || bytes.length === 0) return 0;
|
|
297
|
+
const json = !req.raw && JSON_TYPE.test(response.headers.get("content-type") ?? "") ? jsonOf(bytes) : undefined;
|
|
298
|
+
// A request that carried a secret (login.mjs): its copies cut from a JSON answer's values, or else from the text.
|
|
299
|
+
if (client.scrub) return json ? client.print(client.scrub.value(json.value)) : io.stdout.write(client.scrub.text(bytes.toString("utf8"))), 0;
|
|
300
|
+
if (json && io.stdout.isTTY) io.stdout.write(`${JSON.stringify(json.value, null, 2)}\n`);
|
|
301
|
+
else if (json) io.stdout.write(bytes.at(-1) === 10 ? bytes : Buffer.concat([bytes, Buffer.from("\n")]));
|
|
302
|
+
else io.stdout.write(bytes);
|
|
303
|
+
return 0;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** `--timeout SECONDS` in milliseconds. */
|
|
307
|
+
function timeoutOf(value) {
|
|
308
|
+
if (value === undefined) return undefined;
|
|
309
|
+
const seconds = coerce({ name: "timeout", type: "number" }, value);
|
|
310
|
+
if (seconds <= 0) throw usageError(`--timeout takes a number of seconds above 0, not ${value}`);
|
|
311
|
+
return seconds * 1000;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** A run id goes whole into one path segment (encoded); one that fetch would read as no segment or a step up is none. */
|
|
315
|
+
const runIdOk = (id) => typeof id === "string" && !["", ".", ".."].includes(id);
|
|
316
|
+
|
|
317
|
+
/** `runs wait RUN_ID [--timeout SECONDS]`. */
|
|
318
|
+
async function wait(argv, env, io) {
|
|
319
|
+
const { values, positionals } = parse(argv, { ...GLOBAL, timeout: { type: "string" } });
|
|
320
|
+
if (values.help) return io.stdout.write(`${helpOf(WAIT, WAIT.help)}\n`), 0;
|
|
321
|
+
const args = positionals.slice(WAIT.command.length);
|
|
322
|
+
if (args.length !== 1) throw usageError(`${helpOf(WAIT, WAIT.help)}\n\n${usageOf(WAIT)} takes 1 argument, given ${args.length}.`);
|
|
323
|
+
if (!runIdOk(args[0])) throw usageError(`${usageOf(WAIT)}: RUN_ID may not be empty, . or ..`);
|
|
324
|
+
const timeout = timeoutOf(values.timeout);
|
|
325
|
+
return waitRun(clientOf(targetOf(values, env), io), args[0], timeout);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const parse = (argv, options) => {
|
|
329
|
+
try {
|
|
330
|
+
return parseArgs({ args: argv, options, allowPositionals: true, allowNegative: true, strict: true });
|
|
331
|
+
} catch (error) {
|
|
332
|
+
throw usageError(error.message);
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
const checkHeader = (name, value) => {
|
|
337
|
+
if (BAD_HEADER.test(value)) throw usageError(`The value of ${name} is not a valid header value.`);
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
async function api(argv, env, io) {
|
|
341
|
+
const { values, positionals } = parse(argv, { ...GLOBAL, body: { type: "string" }, header: { type: "string", multiple: true } });
|
|
342
|
+
const [, method, path] = positionals;
|
|
343
|
+
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;
|
|
344
|
+
if (path === undefined || !path.startsWith("/") || positionals.length > 3) throw usageError("Usage: agentrun api METHOD PATH [--body JSON|@FILE|-]; PATH starts with /");
|
|
345
|
+
// fetch resolves `.` and `..` (and their encoded forms) against the base URL's own path, which may be longer than /v2.
|
|
346
|
+
const segments = path.split(/[?#]/)[0].split("/").slice(1).map((segment) => segment.replace(/%2e/gi, "."));
|
|
347
|
+
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 (//).");
|
|
348
|
+
const verb = method.toUpperCase();
|
|
349
|
+
const secret = secretAt(verb, `http://host/v2${path}`);
|
|
350
|
+
if (secret) refuseInline(`${verb} ${secret.path}`, values.body);
|
|
351
|
+
// No prototype, so a header named __proto__ is a key of its own, not the object's prototype set.
|
|
352
|
+
const headers = Object.create(null);
|
|
353
|
+
for (const line of values.header ?? []) {
|
|
354
|
+
const at = line.indexOf(":");
|
|
355
|
+
const name = line.slice(0, at).trim();
|
|
356
|
+
if (at <= 0 || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) throw usageError("--header takes 'NAME: VALUE'.");
|
|
357
|
+
if (["authorization", "cookie"].includes(name.toLowerCase())) throw usageError(`--header cannot set ${name}: the token is never a flag.`);
|
|
358
|
+
// Node's fetch keeps its headers in a plain object and drops this one unsent: refused, so it is never lost unsaid.
|
|
359
|
+
if (name.trim().toLowerCase() === "__proto__") throw usageError("--header cannot send a header named __proto__: Node's fetch drops it.");
|
|
360
|
+
checkHeader(name, line.slice(at + 1).trim());
|
|
361
|
+
headers[name.toLowerCase()] = line.slice(at + 1).trim();
|
|
362
|
+
}
|
|
363
|
+
const body = values.body === undefined ? undefined : await readBody(values.body, io.stdin);
|
|
364
|
+
const type = headers["content-type"] ?? (body !== undefined && jsonOf(body) ? "application/json" : "application/octet-stream");
|
|
365
|
+
const target = targetOf(values, env);
|
|
366
|
+
// The base URL's own path counts too: --base-url .../v2/settings with PUT /tool-keys/exa reaches the secret route.
|
|
367
|
+
const landed = secretAt(verb, `${target.base}${path}`);
|
|
368
|
+
if (landed) refuseLanded(landed, values.body);
|
|
369
|
+
// A body bound for a secret route: an error's answer is never printed, and the body's values are cut from the rest.
|
|
370
|
+
const route = secret || landed;
|
|
371
|
+
const client = route ? guarded(clientOf, target, io, body, route.publicFields) : clientOf(target, io);
|
|
372
|
+
return send(client, { method: verb, path, headers, body, type });
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
async function command(entry, argv, env, io) {
|
|
376
|
+
const options = { ...GLOBAL };
|
|
377
|
+
for (const f of [...entry.query, ...entry.headers, ...entry.bodyFlags]) options[flag(f.name)] = { type: f.type === "boolean" ? "boolean" : "string" };
|
|
378
|
+
if (entry.hasBody) Object.assign(options, { body: { type: "string" }, "body-type": { type: "string" } });
|
|
379
|
+
Object.assign(options, FLAGS[entry.operationId]?.options);
|
|
380
|
+
const { values, positionals } = parse(argv, options);
|
|
381
|
+
if (values.help) return io.stdout.write(`${commandHelp(entry)}\n`), 0;
|
|
382
|
+
const args = positionals.slice(entry.command.length);
|
|
383
|
+
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}.`);
|
|
384
|
+
// A `.` or `..` segment would take the request to another route once fetch normalizes the path.
|
|
385
|
+
if (args.some((arg) => arg.split("/").some((segment) => segment === "." || segment === ".."))) throw usageError(`${usageOf(entry)}: an argument may not hold a . or .. path segment.`);
|
|
386
|
+
const path = entry.path.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
387
|
+
const value = args[entry.pathParams.indexOf(name)];
|
|
388
|
+
if (!entry.multiSegment.includes(name)) return encodeURIComponent(value);
|
|
389
|
+
// A file path keeps its slashes, so no segment may be one fetch or the server would read otherwise.
|
|
390
|
+
const segments = value.split("/");
|
|
391
|
+
if (segments.some((segment) => segment === "" || /%2f/i.test(segment) || [".", ".."].includes(segment.replace(/%2e/gi, ".")))) {
|
|
392
|
+
throw usageError(`${usageOf(entry)}: ${name.toUpperCase()} may not hold an empty, . or .. segment (plain or encoded) or an encoded slash.`);
|
|
393
|
+
}
|
|
394
|
+
return segments.map(encodeURIComponent).join("/");
|
|
395
|
+
});
|
|
396
|
+
const query = new URLSearchParams();
|
|
397
|
+
for (const q of entry.query) {
|
|
398
|
+
const value = values[flag(q.name)];
|
|
399
|
+
if (value !== undefined) query.set(q.name, String(coerce(q, value)));
|
|
400
|
+
else if (q.required) throw usageError(`${usageOf(entry)} needs --${flag(q.name)}.`);
|
|
401
|
+
}
|
|
402
|
+
const headers = {};
|
|
403
|
+
for (const h of entry.headers) {
|
|
404
|
+
const value = values[flag(h.name)];
|
|
405
|
+
if (value !== undefined) checkHeader(`--${flag(h.name)}`, (headers[h.name] = String(coerce(h, value))));
|
|
406
|
+
else if (h.required) throw usageError(`${usageOf(entry)} needs --${flag(h.name)}.`);
|
|
407
|
+
}
|
|
408
|
+
if (entry.secretBody) refuseInline(entry.command.join(" "), values.body);
|
|
409
|
+
const type = values["body-type"] ?? (entry.hasBody ? defaultType(entry.bodyTypes) : undefined);
|
|
410
|
+
if (values["body-type"] !== undefined && !entry.bodyTypes.includes(type) && !entry.bodyTypes.includes("*/*")) throw usageError(`${usageOf(entry)} takes a body of type ${entry.bodyTypes.join(", ")}.`);
|
|
411
|
+
let body = values.body === undefined ? undefined : await readBody(values.body, io.stdin);
|
|
412
|
+
const fields = entry.bodyFlags.filter((f) => values[flag(f.name)] !== undefined).map((f) => [f.name, coerce(f, values[flag(f.name)])]);
|
|
413
|
+
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}.`);
|
|
414
|
+
if (JSON_TYPE.test(type ?? "") && body !== undefined && !jsonOf(body)) throw usageError("--body is not JSON.");
|
|
415
|
+
if (fields.length) {
|
|
416
|
+
// Built from flags alone, the body also carries what the table fills (bodyFill: a JSON-RPC request's jsonrpc and id).
|
|
417
|
+
const object = body === undefined ? { ...entry.bodyFill } : jsonOf(body).value;
|
|
418
|
+
if (object === null || typeof object !== "object" || Array.isArray(object)) throw usageError("--body is not a JSON object, so it cannot take the flags' fields.");
|
|
419
|
+
body = JSON.stringify({ ...object, ...Object.fromEntries(fields) });
|
|
420
|
+
}
|
|
421
|
+
if (entry.bodyRequired && body === undefined) throw usageError(`${usageOf(entry)} needs a body: ${BODY}.`);
|
|
422
|
+
if (values.timeout !== undefined && !values.wait) throw usageError("--timeout goes with --wait.");
|
|
423
|
+
const timeout = timeoutOf(values.timeout);
|
|
424
|
+
const search = query.size ? `?${query}` : "";
|
|
425
|
+
const target = targetOf(values, env);
|
|
426
|
+
const landed = !entry.secretBody && secretAt(entry.method, `${target.base}${path}`);
|
|
427
|
+
if (landed) refuseLanded(landed, values.body);
|
|
428
|
+
const client = entry.secretBody || landed ? guarded(clientOf, target, io, body, (entry.secretBody ? entry : landed).publicFields) : clientOf(target, io);
|
|
429
|
+
const req = { method: entry.method, path: `${path}${search}`, headers, body, type, raw: entry.raw };
|
|
430
|
+
if (values.follow) return followTimeline(client, req.path, headers);
|
|
431
|
+
if (!values.wait) return send(client, req);
|
|
432
|
+
// The start is bounded as the wait is: by --timeout, which the wait then has what is left of, else as one of the
|
|
433
|
+
// wait's requests is.
|
|
434
|
+
const began = Date.now();
|
|
435
|
+
const bound = timeout ?? REQUEST_MS;
|
|
436
|
+
const started = await request(client, { ...req, signal: AbortSignal.timeout(timerMs(bound)) });
|
|
437
|
+
if (started.late) {
|
|
438
|
+
const said = `The server did not answer the start within ${bound / 1000} s; it may have started the run: look for it with \`agentrun runs list --agent ${args[0]}\`.`;
|
|
439
|
+
if (timeout === undefined) throw new Exit(3, said);
|
|
440
|
+
return io.stderr.write(`${said}\n`), 1;
|
|
441
|
+
}
|
|
442
|
+
if (started.code !== undefined) return started.code;
|
|
443
|
+
const run = jsonOf(started.bytes)?.value;
|
|
444
|
+
if (!runIdOk(run?.run_id)) return io.stderr.write("The server's answer to the start names no usable run_id.\n"), 1;
|
|
445
|
+
return waitRun(client, run.run_id, timeout === undefined ? undefined : Math.max(1, timeout - (Date.now() - began)));
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** A hand-written command of LOCAL: its flags and arguments checked, then its `run`, with this module's custody of the
|
|
449
|
+
* token (targetOf, BAD_HEADER), its requests (clientOf, request, send) and its secret-route guard (secretAt). */
|
|
450
|
+
async function local(entry, argv, env, io) {
|
|
451
|
+
const { values, positionals } = parse(argv, { ...GLOBAL, ...entry.options });
|
|
452
|
+
if (values.help) return io.stdout.write(`${helpOf(entry, entry.help)}\n`), 0;
|
|
453
|
+
const args = positionals.slice(entry.command.length);
|
|
454
|
+
const count = entry.pathParams.length;
|
|
455
|
+
if (args.length !== count) throw usageError(`${helpOf(entry, entry.help)}\n\n${usageOf(entry)} takes ${count || "no"} argument${count === 1 ? "" : "s"}, given ${args.length}.`);
|
|
456
|
+
const cli = { fail: (code, message) => new Exit(code, message), baseOf, targetOf, clientOf, request, send, secretAt, BAD_HEADER };
|
|
457
|
+
return entry.run({ values, args, env, io, cli });
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
async function run(argv, env, io) {
|
|
461
|
+
const [noun, verb] = words(argv);
|
|
462
|
+
if (noun === undefined || noun === "help") return io.stdout.write(`${HELP()}\n`), 0;
|
|
463
|
+
if (noun === "api") return api(argv, env, io);
|
|
464
|
+
if (noun === WAIT.command[0] && verb === WAIT.command[1]) return wait(argv, env, io);
|
|
465
|
+
const own = LOCAL.find((e) => e.command[0] === noun && (e.command.length === 1 || e.command[1] === verb));
|
|
466
|
+
if (own) return local(own, argv, env, io);
|
|
467
|
+
const entries = COMMANDS.filter((entry) => entry.command[0] === noun);
|
|
468
|
+
const listed = [...entries, ...LOCAL.filter((e) => e.command[0] === noun), ...(noun === WAIT.command[0] ? [WAIT] : [])];
|
|
469
|
+
if (!listed.length) throw usageError(`agentrun has no command ${noun}.\n\n${HELP()}`);
|
|
470
|
+
const entry = entries.find((e) => e.command.length === 1 || e.command[1] === verb);
|
|
471
|
+
if (entry) return command(entry, argv, env, io);
|
|
472
|
+
if (verb === undefined) return io.stdout.write(`${nounHelp(noun, listed)}\n`), 0;
|
|
473
|
+
throw usageError(`agentrun ${noun} has no verb ${verb}.\n\n${nounHelp(noun, listed)}`);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
export async function main(argv, env = process.env, io = process) {
|
|
477
|
+
// A reader that stops early (`| head`) closes stdout: the command ends quietly, as it would have. Stdout is written only
|
|
478
|
+
// once a request succeeded (or for help), so that is exit 0. Any other write error still throws.
|
|
479
|
+
io.stdout.on("error", (error) => {
|
|
480
|
+
if (error.code !== "EPIPE") throw error;
|
|
481
|
+
process.exit(0);
|
|
482
|
+
});
|
|
483
|
+
try {
|
|
484
|
+
return await run(argv, env, io);
|
|
485
|
+
} catch (error) {
|
|
486
|
+
if (!(error instanceof Exit)) throw error;
|
|
487
|
+
io.stderr.write(`${error.message}\n`);
|
|
488
|
+
return error.code;
|
|
489
|
+
}
|
|
490
|
+
}
|