@parcha/agentrun 0.3.6 → 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 CHANGED
@@ -39,5 +39,13 @@ another server, set `AGENTRUN_BASE_URL` and `AGENTRUN_API_KEY`. The response's J
39
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
40
  reached and 4 for a missing or refused token. The token is never a flag and never printed.
41
41
 
42
- The TypeScript SDK for the hosted AgentRun API is published as `@parcha/agentrun` 0.2.x, from its own repository; this
43
- package starts with 0.3.0, so a dependency on `^0.2` keeps the SDK.
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 CHANGED
@@ -1,16 +1,26 @@
1
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.
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.
3
6
  import { closeSync, constants, fstatSync, openSync, readFileSync } from "node:fs";
4
7
  import { homedir } from "node:os";
5
8
  import { join, resolve } from "node:path";
6
9
  import { parseArgs } from "node:util";
7
- import { COMMANDS } from "./commands.generated.mjs";
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";
8
15
 
9
- export const NOUNS = new Set(["api", "help", ...COMMANDS.map((entry) => entry.command[0])]);
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])]);
10
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
11
20
  const START = "start it with `npx @parcha/agentrun`, or pass --base-url (or set AGENTRUN_BASE_URL) to the address the server printed";
12
21
  const GLOBAL = { "base-url": { type: "string" }, data: { type: "string" }, help: { type: "boolean", short: "h" } };
13
22
  const BODY = "--body JSON|@FILE|-";
23
+ const ACCEPT = "application/json, */*";
14
24
  const JSON_TYPE = /^application\/(?:[\w.+-]+\+)?json\b/;
15
25
  // A header value fetch takes: no line break or other control character, nothing outside Latin-1.
16
26
  const BAD_HEADER = /[\0-\x08\x0a-\x1f\x7f]|[^\0-\xff]/;
@@ -37,7 +47,7 @@ export function words(argv) {
37
47
 
38
48
  const HELP = () => {
39
49
  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]]);
50
+ for (const { command, summary } of [...COMMANDS, WAIT, ...LOCAL]) groups.set(command[0], command.length === 1 ? [summary] : [...(groups.get(command[0]) ?? []), command[1]].sort());
41
51
  const width = Math.max(...[...groups.keys()].map((noun) => noun.length));
42
52
  return [
43
53
  "Usage: npx @parcha/agentrun <command> [args] [--base-url URL] [--data DIR]",
@@ -48,15 +58,28 @@ const HELP = () => {
48
58
  "",
49
59
  "The server: --base-url, else AGENTRUN_BASE_URL, else base_url in $XDG_CONFIG_HOME/agentrun/config.json, else the",
50
60
  "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.",
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.",
52
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",
53
- "server refused, 2 bad usage, 3 the server cannot be reached, 4 no token or the token was refused.",
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.",
54
70
  ].join("\n");
55
71
  };
56
72
 
57
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
+ };
58
78
  const defaultType = (types) => (types.includes("application/json") ? "application/json" : types.includes("*/*") ? "application/octet-stream" : types[0]);
59
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
+
60
83
  function commandHelp(entry) {
61
84
  const flags = [...entry.query, ...entry.headers, ...entry.bodyFlags].map((f) => {
62
85
  const value = f.type === "boolean" ? "" : ` ${f.enum ? f.enum.join("|") : f.type.toUpperCase()}`;
@@ -66,8 +89,10 @@ function commandHelp(entry) {
66
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"]);
67
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`]);
68
91
  }
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");
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, "'\\''")}'`;
71
96
  }
72
97
 
73
98
  const nounHelp = (noun, entries) => [`Usage: agentrun ${noun} <verb> [args]`, "", ...entries.map((entry) => ` ${usageOf(entry).padEnd(40)} ${entry.summary}`)].join("\n");
@@ -87,7 +112,8 @@ function readJson(file, text) {
87
112
  function privateFile(file) {
88
113
  let fd;
89
114
  try {
90
- fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
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);
91
117
  } catch (error) {
92
118
  if (error.code === "ENOENT") return undefined;
93
119
  throw new Exit(4, `${file} ${error.code === "ELOOP" ? "is a link" : `cannot be read (${error.code})`}; refusing it.`);
@@ -113,17 +139,46 @@ const alive = (pid) => {
113
139
 
114
140
  const trim = (url) => url.replace(/\/+$/, "");
115
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
+
116
161
  /** Where the request goes and the token it carries. A token goes only with the address it came with: the local
117
162
  * server's own token is never sent to another server. The local token is DIR/.token, whatever the record says. */
118
163
  function targetOf(values, env) {
119
164
  const data = resolve(values.data ?? join(homedir(), ".agentrun"));
120
165
  const configFile = join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "agentrun", "config.json");
121
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
+ }
122
170
  const recordFile = join(data, ".server.json");
123
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
+ }
124
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.`;
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);
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;
127
182
  let token = env.AGENTRUN_API_KEY || (config.base_url && base === trim(config.base_url) ? config.api_key : undefined);
128
183
  const isLocal = base === local;
129
184
  if (isLocal && record && !alive(record.pid)) throw new Exit(3, stale);
@@ -180,37 +235,96 @@ const refuseInline = (what, value) => {
180
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.`);
181
236
  };
182
237
 
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));
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));
188
251
  }
189
252
 
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;
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 }) {
194
279
  try {
195
- response = await fetch(`${target.base}${request.path}`, { method: request.method, headers, ...(request.body !== undefined ? { body: request.body } : {}) });
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) };
196
285
  } 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;
286
+ if (signal?.aborted) return { late: true };
287
+ throw client.unreachable(error);
205
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;
206
296
  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;
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;
208
300
  if (json && io.stdout.isTTY) io.stdout.write(`${JSON.stringify(json.value, null, 2)}\n`);
209
301
  else if (json) io.stdout.write(bytes.at(-1) === 10 ? bytes : Buffer.concat([bytes, Buffer.from("\n")]));
210
302
  else io.stdout.write(bytes);
211
303
  return 0;
212
304
  }
213
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
+
214
328
  const parse = (argv, options) => {
215
329
  try {
216
330
  return parseArgs({ args: argv, options, allowPositionals: true, allowNegative: true, strict: true });
@@ -232,26 +346,37 @@ async function api(argv, env, io) {
232
346
  const segments = path.split(/[?#]/)[0].split("/").slice(1).map((segment) => segment.replace(/%2e/gi, "."));
233
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 (//).");
234
348
  const verb = method.toUpperCase();
235
- const secret = secretAt(verb, path);
349
+ const secret = secretAt(verb, `http://host/v2${path}`);
236
350
  if (secret) refuseInline(`${verb} ${secret.path}`, values.body);
237
- const headers = {};
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);
238
353
  for (const line of values.header ?? []) {
239
354
  const at = line.indexOf(":");
240
355
  const name = line.slice(0, at).trim();
241
356
  if (at <= 0 || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) throw usageError("--header takes 'NAME: VALUE'.");
242
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.");
243
360
  checkHeader(name, line.slice(at + 1).trim());
244
361
  headers[name.toLowerCase()] = line.slice(at + 1).trim();
245
362
  }
246
363
  const body = values.body === undefined ? undefined : await readBody(values.body, io.stdin);
247
364
  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);
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 });
249
373
  }
250
374
 
251
375
  async function command(entry, argv, env, io) {
252
376
  const options = { ...GLOBAL };
253
377
  for (const f of [...entry.query, ...entry.headers, ...entry.bodyFlags]) options[flag(f.name)] = { type: f.type === "boolean" ? "boolean" : "string" };
254
378
  if (entry.hasBody) Object.assign(options, { body: { type: "string" }, "body-type": { type: "string" } });
379
+ Object.assign(options, FLAGS[entry.operationId]?.options);
255
380
  const { values, positionals } = parse(argv, options);
256
381
  if (values.help) return io.stdout.write(`${commandHelp(entry)}\n`), 0;
257
382
  const args = positionals.slice(entry.command.length);
@@ -288,25 +413,64 @@ async function command(entry, argv, env, io) {
288
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}.`);
289
414
  if (JSON_TYPE.test(type ?? "") && body !== undefined && !jsonOf(body)) throw usageError("--body is not JSON.");
290
415
  if (fields.length) {
291
- const object = body === undefined ? {} : jsonOf(body).value;
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;
292
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.");
293
419
  body = JSON.stringify({ ...object, ...Object.fromEntries(fields) });
294
420
  }
295
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);
296
424
  const search = query.size ? `?${query}` : "";
297
- return send(targetOf(values, env), { method: entry.method, path: `${path}${search}`, headers, body, type, raw: entry.raw }, io);
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 });
298
458
  }
299
459
 
300
460
  async function run(argv, env, io) {
301
461
  const [noun, verb] = words(argv);
302
462
  if (noun === undefined || noun === "help") return io.stdout.write(`${HELP()}\n`), 0;
303
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);
304
467
  const entries = COMMANDS.filter((entry) => entry.command[0] === noun);
305
- if (!entries.length) throw usageError(`agentrun has no command ${noun}.\n\n${HELP()}`);
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()}`);
306
470
  const entry = entries.find((e) => e.command.length === 1 || e.command[1] === verb);
307
471
  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)}`);
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)}`);
310
474
  }
311
475
 
312
476
  export async function main(argv, env = process.env, io = process) {