@parcha/agentrun 0.4.35 → 0.4.36
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 +1 -1
- package/install.sh +6 -5
- package/lib/cli.mjs +2 -1
- package/lib/commands.generated.mjs +12 -0
- package/lib/device.mjs +5 -2
- package/lib/local.mjs +2 -1
- package/lib/race.mjs +337 -0
- package/lib/service.mjs +7 -5
- package/package.json +2 -2
- package/skills/agentrun-cli/references/commands.md +29 -0
package/README.md
CHANGED
|
@@ -32,7 +32,7 @@ LaunchAgent on macOS or a systemd user unit on Linux, which starts again at logi
|
|
|
32
32
|
to the same file. With no terminal to ask on, or its output captured (CI, a script, an agent's shell), it installs the
|
|
33
33
|
service without asking; `--service` and `--no-service` choose without the question. Where there is no service manager (a
|
|
34
34
|
container, say), it starts AgentRun in the background. In the background it runs until the machine or container stops, and `agentrun stop` stops it (a SIGTERM, then a SIGKILL to the launcher and its server
|
|
35
|
-
after
|
|
35
|
+
after 60 seconds). Either way the installer returns once AgentRun answers, and prints its address. `sh -s -- --no-start`
|
|
36
36
|
installs only, `--version V` installs another version, `--node-version V` installs that Node.js (at least the floor),
|
|
37
37
|
and `--service` fails where there is no service manager. Running it again upgrades, or installs an older version, and
|
|
38
38
|
first stops the AgentRun it started in the background itself, whatever version that is. An older version does not start on
|
package/install.sh
CHANGED
|
@@ -458,8 +458,9 @@ ours() {
|
|
|
458
458
|
|
|
459
459
|
# Stops the AgentRun an earlier install started in the background, so only one server uses ~/.agentrun. The installer does
|
|
460
460
|
# it itself, as `agentrun stop` does, since the version installed may have no `agentrun stop`: a SIGTERM to the launcher,
|
|
461
|
-
# which passes it on to its server (the pid in .server.json) and waits for it. Both get
|
|
462
|
-
#
|
|
461
|
+
# which passes it on to its server (the pid in .server.json) and waits for it. Both get 60 s, past the close of the
|
|
462
|
+
# runner beside the server (55 s with its 30 s drain: the drain, then the loops' stop), then a SIGKILL; one that outlives
|
|
463
|
+
# that fails the install, so a second server never starts beside it.
|
|
463
464
|
stop_background() {
|
|
464
465
|
bg=$(cat "$root/agentrun.pid" 2> /dev/null) || return 0
|
|
465
466
|
if ours "$bg"; then
|
|
@@ -467,7 +468,7 @@ stop_background() {
|
|
|
467
468
|
say "Stopping the AgentRun started in the background before (pid $bg) ..."
|
|
468
469
|
kill -s TERM "$bg" 2> /dev/null || true
|
|
469
470
|
waited=0
|
|
470
|
-
while { ours "$bg" || ours "$server"; } && [ "$waited" -lt
|
|
471
|
+
while { ours "$bg" || ours "$server"; } && [ "$waited" -lt 60 ]; do
|
|
471
472
|
sleep 1
|
|
472
473
|
waited=$((waited + 1))
|
|
473
474
|
done
|
|
@@ -880,8 +881,8 @@ services:
|
|
|
880
881
|
AGENTRUN_TOKEN: ${AGENTRUN_TOKEN:?run the installer again}
|
|
881
882
|
AGENTRUN_PUBLIC_URL: ${AGENTRUN_PUBLIC_URL:?run the installer again}
|
|
882
883
|
restart: unless-stopped
|
|
883
|
-
#
|
|
884
|
-
stop_grace_period:
|
|
884
|
+
# Above the close of the runner beside the server (40 s with the image's 6 s drain), as the quickstart's.
|
|
885
|
+
stop_grace_period: 45s
|
|
885
886
|
volumes:
|
|
886
887
|
agentrun-data:
|
|
887
888
|
EOF
|
package/lib/cli.mjs
CHANGED
|
@@ -8,7 +8,8 @@
|
|
|
8
8
|
// service.mjs's, doctor (how this AgentRun is set up, read-only) is doctor.mjs's, export (an agent written as a template
|
|
9
9
|
// package folder) is export.mjs's, share (a run's bundle published to a share host with --to, or shown with --dry-run)
|
|
10
10
|
// and share delete are share.mjs's, and deploy (an agent's package sent to another AgentRun, with its lock, rollback and
|
|
11
|
-
// delete) is deploy.mjs's
|
|
11
|
+
// delete) is deploy.mjs's, and race start and race show (one task on 2 to 4 harness and model lanes, as the console's
|
|
12
|
+
// New race form starts one) are race.mjs's. Any other word runs agentrun-WORD from PATH, as git runs git-WORD (externalOf, below).
|
|
12
13
|
import { spawn } from "node:child_process";
|
|
13
14
|
import { accessSync, closeSync, constants, fstatSync, openSync, readFileSync, statSync } from "node:fs";
|
|
14
15
|
import { homedir, constants as osConstants } from "node:os";
|
|
@@ -2628,6 +2628,18 @@ export const COMMANDS = [
|
|
|
2628
2628
|
"type": "string",
|
|
2629
2629
|
"required": true,
|
|
2630
2630
|
"description": "owner/name, or its https://github.com URL."
|
|
2631
|
+
},
|
|
2632
|
+
{
|
|
2633
|
+
"name": "run_id",
|
|
2634
|
+
"type": "string",
|
|
2635
|
+
"required": false,
|
|
2636
|
+
"description": "The run the host started for a reserved scan, sent with that reservation's `scan`."
|
|
2637
|
+
},
|
|
2638
|
+
{
|
|
2639
|
+
"name": "scan",
|
|
2640
|
+
"type": "string",
|
|
2641
|
+
"required": false,
|
|
2642
|
+
"description": "The reservation a host-started run is bound to (the reserve's `scan`); sent alone, the reservation released."
|
|
2631
2643
|
}
|
|
2632
2644
|
],
|
|
2633
2645
|
"hasBody": true,
|
package/lib/device.mjs
CHANGED
|
@@ -21,6 +21,9 @@ export class SignInError extends Error {
|
|
|
21
21
|
const NOTHING = "nothing was written";
|
|
22
22
|
const refuse = (code, message) => new SignInError(code, message);
|
|
23
23
|
const bad = (what) => refuse(1, `The server's device sign-in ${what}; ${NOTHING}.`);
|
|
24
|
+
/** access_denied, from the authorization endpoint or the poll. A team workspace's key is its team admins' to approve, so
|
|
25
|
+
* a member is pointed at them; the server's own description of the refusal is never printed. */
|
|
26
|
+
const denied = () => refuse(4, `The sign-in was denied; ${NOTHING}. A team workspace takes a key only from a team admin: ask one to deploy for you, or sign in again and choose another workspace.`);
|
|
24
27
|
|
|
25
28
|
/** The most read of a capabilities answer, and of each answer of the device flow. */
|
|
26
29
|
const CAPABILITIES_BYTES = 4 * 1024 * 1024;
|
|
@@ -193,7 +196,7 @@ export async function deviceSignIn(base, offer, io, { wait = sleep, now = Date.n
|
|
|
193
196
|
if (granted.status === 200 && !g) throw bad("authorization endpoint answered something other than a JSON object, or one too large");
|
|
194
197
|
if (granted.status !== 200 || g.error !== undefined) {
|
|
195
198
|
const code = errorOf(g);
|
|
196
|
-
if (code === "access_denied") throw
|
|
199
|
+
if (code === "access_denied") throw denied();
|
|
197
200
|
throw refuse(1, `The server refused the device sign-in request: ${granted.status}${code ? ` ${code}` : ""}; ${NOTHING}.`);
|
|
198
201
|
}
|
|
199
202
|
const interval = g.interval === undefined ? INTERVAL_S : g.interval;
|
|
@@ -248,7 +251,7 @@ export async function deviceSignIn(base, offer, io, { wait = sleep, now = Date.n
|
|
|
248
251
|
delay = Math.max(every, Math.min(BACKOFF_MS, delay * 2), answer.retryAfter);
|
|
249
252
|
continue;
|
|
250
253
|
}
|
|
251
|
-
if (code === "access_denied") throw
|
|
254
|
+
if (code === "access_denied") throw denied();
|
|
252
255
|
if (code === "expired_token") throw expired();
|
|
253
256
|
throw refuse(1, `The server refused the sign-in: ${answer.status}${code ? ` ${code}` : ""}; ${NOTHING}.`);
|
|
254
257
|
}
|
package/lib/local.mjs
CHANGED
|
@@ -6,9 +6,10 @@ import { DOCTOR } from "./doctor.mjs";
|
|
|
6
6
|
import { EXPORT } from "./export.mjs";
|
|
7
7
|
import { HARNESS_CHECK, HARNESS_INSTALL, HARNESS_KEYS, HARNESS_SIGN_IN } from "./harness.mjs";
|
|
8
8
|
import { SECRETS } from "./login.mjs";
|
|
9
|
+
import { RACE_SHOW, RACE_START } from "./race.mjs";
|
|
9
10
|
import { SHARE, SHARE_DELETE } from "./share.mjs";
|
|
10
11
|
import { OPEN, SERVICE, STOP } from "./service.mjs";
|
|
11
12
|
import { SKILL_INSTALL } from "./skill.mjs";
|
|
12
13
|
import { TEMPLATE_EVAL, TEMPLATE_INSTALL, TEMPLATE_VALIDATE } from "./template.mjs";
|
|
13
14
|
|
|
14
|
-
export const LOCAL = [...SECRETS, SKILL_INSTALL, TEMPLATE_VALIDATE, TEMPLATE_EVAL, TEMPLATE_INSTALL, EXPORT, SHARE, SHARE_DELETE, HARNESS_INSTALL, HARNESS_SIGN_IN, HARNESS_KEYS, HARNESS_CHECK, ...SERVICE, STOP, OPEN, DOCTOR, DEPLOY, DEPLOY_ROLLBACK, DEPLOY_DELETE];
|
|
15
|
+
export const LOCAL = [...SECRETS, SKILL_INSTALL, TEMPLATE_VALIDATE, TEMPLATE_EVAL, TEMPLATE_INSTALL, EXPORT, SHARE, SHARE_DELETE, HARNESS_INSTALL, HARNESS_SIGN_IN, HARNESS_KEYS, HARNESS_CHECK, ...SERVICE, STOP, OPEN, DOCTOR, DEPLOY, DEPLOY_ROLLBACK, DEPLOY_DELETE, RACE_START, RACE_SHOW];
|
package/lib/race.mjs
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
// `agentrun race start` and `agentrun race show`: one task run side by side on 2 to 4 harness and model lanes, as the
|
|
2
|
+
// console's New race form starts one (apps/console lib/race.ts laneStart, RaceStart.tsx) and its race view reads it. Each
|
|
3
|
+
// lane is a new agent of its own (POST /agents) with the console's lane instructions and a new agent's default tools on
|
|
4
|
+
// this server, and one run of its first revision (POST /agents/{agent_id}/runs) carrying the race's task, cap and labels:
|
|
5
|
+
// race:<label>, lane, harness and model. `race show LABEL` reads the runs that label groups (GET /runs?label=race:LABEL).
|
|
6
|
+
// With --wait, either follows every lane's run to its end on the run's own timeline, as `runs wait` does (follow.mjs
|
|
7
|
+
// waitRun: the long-polled timeline the console's live run reads too, never a polled list), and prints the lanes side by side.
|
|
8
|
+
import { readFileSync } from "node:fs";
|
|
9
|
+
import { randomUUID } from "node:crypto";
|
|
10
|
+
import { waitRun } from "./follow.mjs";
|
|
11
|
+
|
|
12
|
+
/** Exits: 0 every lane started (start) or the race read (show); 1 a lane not started, the others' runs going on; 2 refused
|
|
13
|
+
* (a lane, task, cap or label not given as the command takes it). With --wait: 0 every lane completed; 1 a lane failed,
|
|
14
|
+
* was cancelled, did not start, could not be followed or is still running past --timeout; else 8 (gh's "pending", as
|
|
15
|
+
* `runs wait`) when a lane waits on a person. */
|
|
16
|
+
const REFUSED = 2;
|
|
17
|
+
const RACE_KEY = "race";
|
|
18
|
+
const LANE_KEY = "lane";
|
|
19
|
+
const MIN_LANES = 2;
|
|
20
|
+
const MAX_LANES = 4;
|
|
21
|
+
/** Every lane's instructions, as the console's: the task itself is the run's input, the same on every lane. */
|
|
22
|
+
const LANE_INSTRUCTIONS = "Do the task you are given.";
|
|
23
|
+
/** The tools a run on the runner never names (the browser runs only there) and those it names only where its run
|
|
24
|
+
* shell runs them: the console's (agentForm.ts RUNNER_ONLY, SANDBOX_ONLY; place.ts RUNNER_SHELL). */
|
|
25
|
+
const RUNNER_ONLY = new Set(["browser"]);
|
|
26
|
+
const RUNNER_SHELL = new Set(["bash"]);
|
|
27
|
+
/** A label's words: what a run label's value takes, and a race's page names. */
|
|
28
|
+
const LABEL = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
29
|
+
/** The race view reads at most this many runs of a label: more is a label used for something else too. */
|
|
30
|
+
const RACE_READ = 50;
|
|
31
|
+
/** --wait's bound when no --timeout is given: the runs go on past it. */
|
|
32
|
+
const WAIT_DEFAULT_S = 1800;
|
|
33
|
+
/** The most of a lane's answer its table row shows: its first line, cut. */
|
|
34
|
+
const ANSWER_MAX = 60;
|
|
35
|
+
const ENDED = new Set(["completed", "failed", "cancelled"]);
|
|
36
|
+
const PERSON = new Set(["input_required", "paused"]);
|
|
37
|
+
const WAIT_HELP = [
|
|
38
|
+
["--wait", "then follow every lane's run to its end and print the lanes side by side: exit 0 when every lane completed, 1 when one failed, was cancelled, did not start or still runs past --timeout, 8 when one waits on a person"],
|
|
39
|
+
["--timeout SECONDS", `with --wait: stop waiting after this long (default ${WAIT_DEFAULT_S}), exit 1; the runs go on`],
|
|
40
|
+
["--json", "with --wait: the lanes as JSON, in place of the table"],
|
|
41
|
+
];
|
|
42
|
+
const WAIT_OPTIONS = { wait: { type: "boolean" }, timeout: { type: "string" }, json: { type: "boolean" } };
|
|
43
|
+
|
|
44
|
+
/** A new race's label as the console makes one: when it starts (UTC, to the minute) and 48 random bits. */
|
|
45
|
+
export function newRaceLabel(now = new Date(), random = randomUUID) {
|
|
46
|
+
const at = now.toISOString().slice(0, 16).replace(/[-:]/g, "").replace("T", "-");
|
|
47
|
+
return `${at}-${random().replace(/-/g, "").slice(0, 12)}`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** `HARNESS/MODEL`: the harness is the word before the first slash, the model all after it (a model id may hold one). */
|
|
51
|
+
export function laneOf(text) {
|
|
52
|
+
const at = text.indexOf("/");
|
|
53
|
+
const harness = text.slice(0, at).trim(), model = text.slice(at + 1).trim();
|
|
54
|
+
return at > 0 && harness && model ? { harness, model } : undefined;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A new agent's tools on this server for `harness`, as the console's race form gives a lane (lib/race.ts laneKit): every
|
|
58
|
+
* tool its harness runs here that is available (agentForm.ts toolOffers: unless it says it is not), never a workflow's
|
|
59
|
+
* call-only one, nor a host tool over the run's own (`meta`: tools_search, tools_call, codemode; no grant). Where the server's default place is a
|
|
60
|
+
* box, a runner-only tool is left out; on the runner, a box-only tool is kept only where the runner's own shell runs it
|
|
61
|
+
* (GET /computers, the computer none's `shell`: "local"). */
|
|
62
|
+
export function laneTools(harness, capabilities, computers) {
|
|
63
|
+
const offers = Array.isArray(capabilities?.tools) ? capabilities.tools : [];
|
|
64
|
+
const sandbox = capabilities?.places?.default_place?.mode === "sandbox";
|
|
65
|
+
const none = (Array.isArray(computers?.kinds) ? computers.kinds : []).find((kind) => kind?.kind === "none");
|
|
66
|
+
const shell = none?.shell === "local" ? RUNNER_SHELL : new Set();
|
|
67
|
+
return offers
|
|
68
|
+
.filter((t) => t && typeof t.name === "string" && t.available !== false && !t.call_only && t.meta !== true && Array.isArray(t.harnesses) && t.harnesses.includes(harness))
|
|
69
|
+
.filter((t) => (sandbox ? !RUNNER_ONLY.has(t.name) && !t.runner_only : !t.sandbox_only || shell.has(t.name)))
|
|
70
|
+
.map((t) => t.name);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const jsonBody = (value) => ({ body: Buffer.from(JSON.stringify(value)), type: "application/json" });
|
|
74
|
+
const parsed = (bytes) => {
|
|
75
|
+
try {
|
|
76
|
+
return JSON.parse(bytes.toString("utf8"));
|
|
77
|
+
} catch {
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/** One request whose refusal is a value, not an exit: the server's code and message, so one lane's refusal leaves the
|
|
83
|
+
* others started. Each request has a client of its own, so lanes asked at once never read one another's refusal. A
|
|
84
|
+
* server not reached throws (cli.request's unreachable). */
|
|
85
|
+
async function call(cli, target, io, method, path, value, headers = {}) {
|
|
86
|
+
let said;
|
|
87
|
+
const client = {
|
|
88
|
+
...cli.clientOf(target, io),
|
|
89
|
+
refused: (response, bytes) => {
|
|
90
|
+
const answer = parsed(bytes);
|
|
91
|
+
said = { status: response.status, code: answer?.error?.code ?? answer?.code ?? `http_${response.status}`, message: answer?.error?.message ?? answer?.message ?? `HTTP ${response.status}` };
|
|
92
|
+
return 1;
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
const { bytes, code } = await cli.request(client, { method, path, headers, ...(value === undefined ? {} : jsonBody(value)) });
|
|
96
|
+
return code !== undefined ? { refused: said } : { answer: parsed(bytes) };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** What went wrong with a request that threw, in its own words (an Exit's message names the server not reached). */
|
|
100
|
+
const wordsOf = (error) => (error instanceof Error ? error.message : String(error));
|
|
101
|
+
|
|
102
|
+
/** --wait's seconds, or undefined without --wait; --timeout or --json without it is refused. */
|
|
103
|
+
function waitOf(values, cli) {
|
|
104
|
+
if (!values.wait) {
|
|
105
|
+
if (values.timeout !== undefined || values.json) throw cli.fail(REFUSED, `${values.json ? "--json" : "--timeout"} goes with --wait.`);
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
if (values.timeout === undefined) return WAIT_DEFAULT_S;
|
|
109
|
+
const seconds = Number(values.timeout);
|
|
110
|
+
if (!(Number.isFinite(seconds) && seconds > 0)) throw cli.fail(REFUSED, `--timeout ${values.timeout}: seconds above 0.`);
|
|
111
|
+
return seconds;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Text a model or a server wrote, safe on a terminal: escape sequences and other control characters gone, its first
|
|
115
|
+
* line with words in it, cut at ANSWER_MAX. */
|
|
116
|
+
function lineOf(text) {
|
|
117
|
+
const plain = String(text ?? "").replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, "").replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?/g, "");
|
|
118
|
+
const line = plain.split(/\r\n|\r|\n/).map((part) => part.replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim()).find(Boolean) ?? "";
|
|
119
|
+
return line.length > ANSWER_MAX ? `${line.slice(0, ANSWER_MAX - 1).trimEnd()}…` : line;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** A run's answer for its row: its final answer (or text output), else its error's code and words. */
|
|
123
|
+
function answerOf(run) {
|
|
124
|
+
const said = run?.result?.final_answer ?? (typeof run?.result?.output === "string" ? run.result.output : undefined);
|
|
125
|
+
if (typeof said === "string" && lineOf(said)) return lineOf(said);
|
|
126
|
+
const error = run?.error;
|
|
127
|
+
return error ? lineOf(error.code && error.message ? `${error.code}: ${error.message}` : (error.message ?? error.code)) : "";
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** One lane's run followed until it ends or waits on a person, or `deadline` passes (waitRun, on a client of its own
|
|
131
|
+
* whose stderr is kept, so the lanes' words are said once, in lane order): the run as last read, the server's words. */
|
|
132
|
+
async function follow(cli, target, io, runId, deadline) {
|
|
133
|
+
let run;
|
|
134
|
+
let said = "";
|
|
135
|
+
const kept = { stdout: io.stdout, stderr: { isTTY: false, write: (text) => ((said += String(text)), true) } };
|
|
136
|
+
const client = { ...cli.clientOf(target, kept), print: (value) => (run = value) };
|
|
137
|
+
try {
|
|
138
|
+
const code = await waitRun(client, runId, Math.max(1, deadline - Date.now()));
|
|
139
|
+
return { code, run, said };
|
|
140
|
+
} catch (error) {
|
|
141
|
+
return { lost: wordsOf(error), run, said };
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Every lane followed at once, then the lanes side by side on stdout (a table, or JSON with --json) and a line on stderr
|
|
146
|
+
* for each lane that did not complete; its exit code. `lanes`: each `{ lane, harness, model, run_id?, error?, unsure? }`. */
|
|
147
|
+
async function waitLanes(cli, target, io, label, lanes, seconds, json, more = false) {
|
|
148
|
+
const deadline = Date.now() + seconds * 1000;
|
|
149
|
+
const followed = await Promise.all(lanes.map((lane) => (lane.run_id && !lane.error ? follow(cli, target, io, lane.run_id, deadline) : undefined)));
|
|
150
|
+
const now = Date.now();
|
|
151
|
+
const rows = lanes.map((lane, i) => {
|
|
152
|
+
const got = followed[i];
|
|
153
|
+
const run = got?.run;
|
|
154
|
+
const status = lane.error ? "not started" : run?.status ?? "unknown";
|
|
155
|
+
return { ...lane, status, cost_usd: run?.cost?.usd ?? null, cap_usd: run?.cost?.cap_usd ?? null, seconds: run ? secondsOf(run, now) : null, answer: lane.error ? lineOf(lane.error) : answerOf(run), got };
|
|
156
|
+
});
|
|
157
|
+
const printed = rows.map(({ got, ...row }) => row);
|
|
158
|
+
if (json) io.stdout.write(`${JSON.stringify({ label, filter: `${RACE_KEY}:${label}`, console: `#/races/${encodeURIComponent(label)}`, lanes: printed, ...(more ? { more: true } : {}) }, null, 2)}\n`);
|
|
159
|
+
else io.stdout.write(tableOf(printed));
|
|
160
|
+
// A label with more runs than one read: lanes past it are neither shown nor followed, so the race is never done.
|
|
161
|
+
let failed = more;
|
|
162
|
+
if (more) io.stderr.write(`More than ${RACE_READ} runs carry the label ${RACE_KEY}:${label}: only the first ${RACE_READ} were followed, so the race is not reported done.\n`);
|
|
163
|
+
let person = false;
|
|
164
|
+
const again = `agentrun race show ${label} --wait`;
|
|
165
|
+
for (const row of rows) {
|
|
166
|
+
const name = `Lane ${row.lane} (${row.harness}/${row.model})`;
|
|
167
|
+
const { got } = row;
|
|
168
|
+
if (row.error) {
|
|
169
|
+
failed = true;
|
|
170
|
+
io.stderr.write(`${name} did not start: ${row.error}${row.archive ? ` (its agent was not archived: ${row.archive})` : ""}\n`);
|
|
171
|
+
} else if (!row.run_id) {
|
|
172
|
+
failed = true;
|
|
173
|
+
io.stderr.write(`${name} may have started: its start had no answer (${row.unsure}). See agentrun race show ${label}.\n`);
|
|
174
|
+
} else if (got.lost !== undefined) {
|
|
175
|
+
failed = true;
|
|
176
|
+
io.stderr.write(`${name} could not be followed: ${got.lost}; see ${again}.\n`);
|
|
177
|
+
} else if (got.run === undefined) {
|
|
178
|
+
failed = true;
|
|
179
|
+
io.stderr.write(`${name} could not be read: ${lineOf(got.said) || `exit ${got.code}`}; see ${again}.\n`);
|
|
180
|
+
} else if (row.status === "completed" && got.code === 0) {
|
|
181
|
+
continue;
|
|
182
|
+
} else if (row.status === "completed") {
|
|
183
|
+
// Completed, its timeline not final yet (end-of-run work going on) when the wait ran out: not done.
|
|
184
|
+
failed = true;
|
|
185
|
+
io.stderr.write(`${name} is still finishing after ${seconds} s; it goes on: see ${again}.\n`);
|
|
186
|
+
} else if (ENDED.has(row.status)) {
|
|
187
|
+
failed = true;
|
|
188
|
+
io.stderr.write(`${name} ${row.status === "cancelled" ? "was cancelled" : "failed"}.\n`);
|
|
189
|
+
} else if (PERSON.has(row.status)) {
|
|
190
|
+
person = true;
|
|
191
|
+
io.stderr.write(got.run.pending?.kind === "approval"
|
|
192
|
+
? `${name} waits on an approval: answer it on the race's page in the console, #/races/${encodeURIComponent(label)}; then ${again}.\n`
|
|
193
|
+
: `${name}: ${got.said.trim()}\n`);
|
|
194
|
+
} else {
|
|
195
|
+
failed = true;
|
|
196
|
+
io.stderr.write(`${name} is still ${row.status} after ${seconds} s; it goes on: see ${again}.\n`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return failed ? 1 : person ? 8 : 0;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** The lanes as a table: one row each, its columns padded to line up, the answer last. */
|
|
203
|
+
function tableOf(rows) {
|
|
204
|
+
const money = (usd, cap) => (typeof usd === "number" ? `$${usd.toFixed(4)}${typeof cap === "number" ? ` of $${cap.toFixed(2)}` : ""}` : "-");
|
|
205
|
+
const cells = [["LANE", "HARNESS/MODEL", "STATUS", "COST", "SECONDS", "ANSWER"], ...rows.map((row) => [String(row.lane), `${row.harness}/${row.model}`, row.status, money(row.cost_usd, row.cap_usd), row.seconds === null ? "-" : String(row.seconds), row.answer])];
|
|
206
|
+
const widths = cells[0].map((_, col) => Math.max(...cells.map((line) => line[col].length)));
|
|
207
|
+
return cells.map((line) => line.map((cell, col) => (col === line.length - 1 ? cell : cell.padEnd(widths[col]))).join(" ").trimEnd()).join("\n") + "\n";
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function taskOf(value, cli) {
|
|
211
|
+
if (value === undefined) throw cli.fail(REFUSED, "--task TEXT|@FILE is the task every lane runs.");
|
|
212
|
+
let task = value;
|
|
213
|
+
if (value.startsWith("@")) {
|
|
214
|
+
try {
|
|
215
|
+
task = readFileSync(value.slice(1), "utf8");
|
|
216
|
+
} catch (error) {
|
|
217
|
+
throw cli.fail(REFUSED, `--task ${value}: ${error.code === "ENOENT" ? "no such file" : error.message}.`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
if (!task.trim()) throw cli.fail(REFUSED, "--task is empty: give the task every lane runs.");
|
|
221
|
+
return task.trim();
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export const RACE_START = {
|
|
225
|
+
command: ["race", "start"],
|
|
226
|
+
pathParams: [],
|
|
227
|
+
summary: "Run one task on 2 to 4 harness and model lanes side by side, as the console's New race form does",
|
|
228
|
+
route: "POST /agents, then POST /agents/{agent_id}/runs, a lane each",
|
|
229
|
+
help: [
|
|
230
|
+
["--lane HARNESS/MODEL", "a lane, 2 to 4 times: the harness, then its model (pi/anthropic/claude-sonnet-4.5)"],
|
|
231
|
+
["--task TEXT|@FILE", "the task every lane runs, the same on each"],
|
|
232
|
+
["--max-cost-usd USD", "each lane's cap (default 1)"],
|
|
233
|
+
["--label LABEL", "the race's label (default: the start time and random letters, as the console's)"],
|
|
234
|
+
["--file FILE_ID", "a file uploaded with POST /files, given to every lane's run (repeatable)"],
|
|
235
|
+
...WAIT_HELP,
|
|
236
|
+
],
|
|
237
|
+
options: { lane: { type: "string", multiple: true }, task: { type: "string" }, "max-cost-usd": { type: "string" }, label: { type: "string" }, file: { type: "string", multiple: true }, ...WAIT_OPTIONS },
|
|
238
|
+
async run({ values, env, io, cli }) {
|
|
239
|
+
const given = values.lane ?? [];
|
|
240
|
+
const lanes = given.map(laneOf);
|
|
241
|
+
const bad = given.find((_, i) => !lanes[i]);
|
|
242
|
+
if (bad !== undefined) throw cli.fail(REFUSED, `--lane ${bad}: a lane is HARNESS/MODEL, the harness then its model (pi/anthropic/claude-sonnet-4.5).`);
|
|
243
|
+
if (lanes.length < MIN_LANES || lanes.length > MAX_LANES) throw cli.fail(REFUSED, `A race takes ${MIN_LANES} to ${MAX_LANES} lanes (--lane HARNESS/MODEL each), given ${lanes.length}.`);
|
|
244
|
+
const task = taskOf(values.task, cli);
|
|
245
|
+
const cap = values["max-cost-usd"] === undefined ? 1 : Number(values["max-cost-usd"]);
|
|
246
|
+
if (!(Number.isFinite(cap) && cap > 0)) throw cli.fail(REFUSED, `--max-cost-usd ${values["max-cost-usd"]}: each lane's cap is dollars above 0.`);
|
|
247
|
+
const label = values.label ?? newRaceLabel();
|
|
248
|
+
if (!LABEL.test(label)) throw cli.fail(REFUSED, `--label ${label}: a race's label is 1 to 64 letters, digits, dots, dashes or underscores, starting with a letter or digit.`);
|
|
249
|
+
const files = values.file ?? [];
|
|
250
|
+
const reads = {};
|
|
251
|
+
const seconds = waitOf(values, cli);
|
|
252
|
+
const target = cli.targetOf(values, env);
|
|
253
|
+
// What a new agent gets here: the server's tools for each harness, where its default place is, and the runner's shell.
|
|
254
|
+
// Both are read before any lane starts, as the console's form waits for them: without the computers, a lane on the
|
|
255
|
+
// runner would start without the shell its runner runs.
|
|
256
|
+
for (const path of ["/capabilities", "/computers"]) {
|
|
257
|
+
const read = await call(cli, target, io, "GET", path);
|
|
258
|
+
if (read.refused) throw cli.fail(1, `GET ${path}: ${read.refused.message}. No lane was started.`);
|
|
259
|
+
reads[path] = read.answer;
|
|
260
|
+
}
|
|
261
|
+
// Every lane at once, each on its own: one refused, or cut off, leaves the others started and every lane reported.
|
|
262
|
+
const started = await Promise.all(lanes.map(async (lane, i) => {
|
|
263
|
+
const n = i + 1;
|
|
264
|
+
const said = { lane: n, harness: lane.harness, model: lane.model };
|
|
265
|
+
const definition = { id: `race-${label}-${n}-1`, version: 1, name: `Race ${label}, lane ${n}`, instructions: LANE_INSTRUCTIONS, harness: lane.harness, model: lane.model, tools: laneTools(lane.harness, reads["/capabilities"], reads["/computers"]), skills: [] };
|
|
266
|
+
const agentPath = `/agents/${encodeURIComponent(definition.id)}`;
|
|
267
|
+
let made, run;
|
|
268
|
+
try {
|
|
269
|
+
made = await call(cli, target, io, "POST", "/agents", { definition });
|
|
270
|
+
} catch (error) {
|
|
271
|
+
// No answer: the agent may have been made, but no run of it was asked for.
|
|
272
|
+
return { ...said, error: `its agent was not confirmed made: ${wordsOf(error)}` };
|
|
273
|
+
}
|
|
274
|
+
if (made.refused) return { ...said, error: `${made.refused.code}: ${made.refused.message}` };
|
|
275
|
+
const body = { input: { content: task }, revision: made.answer?.revision, max_cost_usd: cap, labels: { [RACE_KEY]: label, [LANE_KEY]: String(n), harness: lane.harness, model: lane.model }, ...(files.length ? { file_ids: files } : {}) };
|
|
276
|
+
try {
|
|
277
|
+
run = await call(cli, target, io, "POST", `${agentPath}/runs`, body, { "idempotency-key": `race-${label}-${n}` });
|
|
278
|
+
} catch (error) {
|
|
279
|
+
// Asked, with no answer: the run may have started. A refusal is only what the server said.
|
|
280
|
+
return { ...said, agent_id: definition.id, unsure: wordsOf(error) };
|
|
281
|
+
}
|
|
282
|
+
if (run.refused) {
|
|
283
|
+
const refusal = { ...said, agent_id: definition.id, error: `${run.refused.code}: ${run.refused.message}` };
|
|
284
|
+
// A lane's agent is the race's own: one whose run never started is archived, as the console lets one go. An
|
|
285
|
+
// archive that fails is said beside the refusal, never in its place.
|
|
286
|
+
try {
|
|
287
|
+
const archived = await call(cli, target, io, "POST", `${agentPath}/archive`);
|
|
288
|
+
return archived.refused ? { ...refusal, archive: `${archived.refused.code}: ${archived.refused.message}` } : refusal;
|
|
289
|
+
} catch (error) {
|
|
290
|
+
return { ...refusal, archive: wordsOf(error) };
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
return { ...said, agent_id: definition.id, run_id: run.answer?.run_id, status: run.answer?.status };
|
|
294
|
+
}));
|
|
295
|
+
if (seconds !== undefined) return waitLanes(cli, target, io, label, started, seconds, values.json);
|
|
296
|
+
io.stdout.write(`${JSON.stringify({ label, filter: `${RACE_KEY}:${label}`, console: `#/races/${encodeURIComponent(label)}`, lanes: started }, null, 2)}\n`);
|
|
297
|
+
for (const lane of started) {
|
|
298
|
+
const name = `Lane ${lane.lane} (${lane.harness}/${lane.model})`;
|
|
299
|
+
if (lane.error) io.stderr.write(`${name} did not start: ${lane.error}${lane.archive ? ` (its agent was not archived: ${lane.archive})` : ""}\n`);
|
|
300
|
+
if (lane.unsure) io.stderr.write(`${name} may have started: its start had no answer (${lane.unsure}). See agentrun race show ${label}.\n`);
|
|
301
|
+
}
|
|
302
|
+
return started.some((lane) => lane.error || lane.unsure) ? 1 : 0;
|
|
303
|
+
},
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
/** A lane's seconds: from its run's start to its end, or to now while it goes. */
|
|
307
|
+
const secondsOf = (run, now) => {
|
|
308
|
+
const from = Date.parse(run.created_at), to = run.ended_at ? Date.parse(run.ended_at) : now;
|
|
309
|
+
return Number.isFinite(from) && Number.isFinite(to) ? Math.max(0, Math.round((to - from) / 1000)) : null;
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
export const RACE_SHOW = {
|
|
313
|
+
command: ["race", "show"],
|
|
314
|
+
pathParams: ["label"],
|
|
315
|
+
summary: "A race's lanes: each lane's harness, model, run, status, cost and seconds, in lane order",
|
|
316
|
+
route: "GET /runs?label=race:LABEL",
|
|
317
|
+
help: [["LABEL", "the race's label, as race start printed it"], ...WAIT_HELP],
|
|
318
|
+
options: WAIT_OPTIONS,
|
|
319
|
+
async run({ args, values, env, io, cli }) {
|
|
320
|
+
const label = args[0];
|
|
321
|
+
if (!LABEL.test(label)) throw cli.fail(REFUSED, `${label}: a race's label is 1 to 64 letters, digits, dots, dashes or underscores, starting with a letter or digit.`);
|
|
322
|
+
const seconds = waitOf(values, cli);
|
|
323
|
+
const target = cli.targetOf(values, env);
|
|
324
|
+
const query = new URLSearchParams({ limit: String(RACE_READ), label: `${RACE_KEY}:${label}` });
|
|
325
|
+
const read = await call(cli, target, io, "GET", `/runs?${query}`);
|
|
326
|
+
if (read.refused) throw cli.fail(1, `GET /runs: ${read.refused.message}`);
|
|
327
|
+
const runs = Array.isArray(read.answer?.runs) ? read.answer.runs : [];
|
|
328
|
+
if (!runs.length) throw cli.fail(REFUSED, `No run carries the label ${RACE_KEY}:${label}.`);
|
|
329
|
+
const now = Date.now();
|
|
330
|
+
const lane = (run) => Number(run.labels?.[LANE_KEY]);
|
|
331
|
+
const lanes = [...runs].sort((a, b) => (lane(a) || Infinity) - (lane(b) || Infinity) || String(a.created_at).localeCompare(String(b.created_at)))
|
|
332
|
+
.map((run) => ({ lane: run.labels?.[LANE_KEY] ?? null, harness: run.labels?.harness ?? null, model: run.labels?.model ?? null, run_id: run.run_id, status: run.status, cost_usd: run.cost?.usd ?? null, cap_usd: run.cost?.cap_usd ?? null, seconds: secondsOf(run, now) }));
|
|
333
|
+
if (seconds !== undefined) return waitLanes(cli, target, io, label, lanes.map(({ lane, harness, model, run_id }) => ({ lane, harness, model, run_id })), seconds, values.json, Boolean(read.answer?.next_cursor));
|
|
334
|
+
io.stdout.write(`${JSON.stringify({ label, lanes, ...(read.answer?.next_cursor ? { more: true } : {}) }, null, 2)}\n`);
|
|
335
|
+
return 0;
|
|
336
|
+
},
|
|
337
|
+
};
|
package/lib/service.mjs
CHANGED
|
@@ -19,8 +19,9 @@ export const INSTALL_COMMAND = "curl -fsSL https://agentrun.ai/install | sh";
|
|
|
19
19
|
/** How long a start waits for the server to answer /health before it says it did not. */
|
|
20
20
|
export const HEALTH_WAIT_MS = 90_000;
|
|
21
21
|
/** How long `agentrun stop` waits for the background AgentRun to end after its SIGTERM before it sends a SIGKILL: past the
|
|
22
|
-
* server
|
|
23
|
-
|
|
22
|
+
* close of the runner beside the server (55 s with its 30 s --drain-timeout: the drain, then the loops' stop), so a busy
|
|
23
|
+
* run gets its turn and its end and release are written. */
|
|
24
|
+
export const STOP_WAIT_MS = 60_000;
|
|
24
25
|
const INSTALLER = fileURLToPath(new URL("../install.sh", import.meta.url));
|
|
25
26
|
|
|
26
27
|
const xml = (text) => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
@@ -28,8 +29,9 @@ const unxml = (text) => text.replace(/"/g, '"').replace(/>/g, ">").repla
|
|
|
28
29
|
|
|
29
30
|
/** The LaunchAgent: started at login (RunAtLoad), started again when it exits with a failure (KeepAlive), its output in
|
|
30
31
|
* `log`, with the PATH of the shell that installed it (launchd's own has no Homebrew, so no docker) and `env`. A stop
|
|
31
|
-
* gets
|
|
32
|
-
*
|
|
32
|
+
* gets 60 s before launchd's SIGKILL (ExitTimeOut; its default is 20 s), as `agentrun stop` waits (STOP_WAIT_MS): the
|
|
33
|
+
* runner beside the server closes in up to 55 s (its 30 s drain, then the loops' stop), which outlasts a signed-in
|
|
34
|
+
* server's 27 s stop and a ChatGPT renewal its runner sends. */
|
|
33
35
|
export function plistText({ program, args, path, log, env = {} }) {
|
|
34
36
|
const strings = [program, ...args].map((arg) => ` <string>${xml(arg)}</string>`).join("\n");
|
|
35
37
|
const vars = Object.entries({ PATH: path, ...env }).map(([key, value]) => ` <key>${xml(key)}</key>\n <string>${xml(value)}</string>`).join("\n");
|
|
@@ -55,7 +57,7 @@ ${vars}
|
|
|
55
57
|
<false/>
|
|
56
58
|
</dict>
|
|
57
59
|
<key>ExitTimeOut</key>
|
|
58
|
-
<integer>
|
|
60
|
+
<integer>60</integer>
|
|
59
61
|
<key>StandardOutPath</key>
|
|
60
62
|
<string>${xml(log)}</string>
|
|
61
63
|
<key>StandardErrorPath</key>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parcha/agentrun",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.36",
|
|
4
4
|
"description": "AgentRun, the open-source platform that supercharges your agents (self-improvement, durable execution and a control plane on top of your favorite agent harness), on this machine with one command: npx @parcha/agentrun",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
"NOTICE"
|
|
18
18
|
],
|
|
19
19
|
"dependencies": {
|
|
20
|
-
"@parcha/agentrun-serve": "0.1.0-beta.
|
|
20
|
+
"@parcha/agentrun-serve": "0.1.0-beta.68"
|
|
21
21
|
},
|
|
22
22
|
"scripts": {
|
|
23
23
|
"test": "node --test 'test/*.test.mjs'"
|
|
@@ -854,6 +854,8 @@ Scan a repository for places its app needs an agent.
|
|
|
854
854
|
Route: `POST /suggestions/scans`.
|
|
855
855
|
|
|
856
856
|
- `--repo STRING` (string, required): owner/name, or its https://github.com URL.
|
|
857
|
+
- `--run-id STRING` (string): The run the host started for a reserved scan, sent with that reservation's `scan`.
|
|
858
|
+
- `--scan STRING` (string): The reservation a host-started run is bound to (the reserve's `scan`); sent alone, the reservation released.
|
|
857
859
|
- `--body JSON|@FILE|-` (application/json, required): The whole body: inline, from a file or from stdin. The flags above win over a JSON body's fields.
|
|
858
860
|
- `--body-type TYPE` (string): The body's type, one of application/json; any other than JSON is sent as given.
|
|
859
861
|
|
|
@@ -951,6 +953,33 @@ Route: none, it runs on this machine.
|
|
|
951
953
|
- `--data DIR` (string, this CLI's own): the data directory of the AgentRun to open (default ~/.agentrun)
|
|
952
954
|
- `--setup-only` (boolean, this CLI's own): open nothing once the owner's password is set (the installer's last step)
|
|
953
955
|
|
|
956
|
+
## race
|
|
957
|
+
|
|
958
|
+
### `agentrun race show LABEL`
|
|
959
|
+
|
|
960
|
+
A race's lanes: each lane's harness, model, run, status, cost and seconds, in lane order.
|
|
961
|
+
|
|
962
|
+
Route: `GET /runs?label=race:LABEL`.
|
|
963
|
+
|
|
964
|
+
- `--wait` (boolean, this CLI's own): then follow every lane's run to its end and print the lanes side by side: exit 0 when every lane completed, 1 when one failed, was cancelled, did not start or still runs past --timeout, 8 when one waits on a person
|
|
965
|
+
- `--timeout SECONDS` (number, this CLI's own): with --wait: stop waiting after this long (default 1800), exit 1; the runs go on
|
|
966
|
+
- `--json` (boolean, this CLI's own): with --wait: the lanes as JSON, in place of the table
|
|
967
|
+
|
|
968
|
+
### `agentrun race start`
|
|
969
|
+
|
|
970
|
+
Run one task on 2 to 4 harness and model lanes side by side, as the console's New race form does.
|
|
971
|
+
|
|
972
|
+
Route: `POST /agents, then POST /agents/{agent_id}/runs, a lane each`.
|
|
973
|
+
|
|
974
|
+
- `--lane HARNESS/MODEL` (string, this CLI's own): a lane, 2 to 4 times: the harness, then its model (pi/anthropic/claude-sonnet-4.5)
|
|
975
|
+
- `--task TEXT|@FILE` (string, this CLI's own): the task every lane runs, the same on each
|
|
976
|
+
- `--max-cost-usd USD` (string, this CLI's own): each lane's cap (default 1)
|
|
977
|
+
- `--label LABEL` (string, this CLI's own): the race's label (default: the start time and random letters, as the console's)
|
|
978
|
+
- `--file FILE_ID` (string, this CLI's own): a file uploaded with POST /files, given to every lane's run (repeatable)
|
|
979
|
+
- `--wait` (boolean, this CLI's own): then follow every lane's run to its end and print the lanes side by side: exit 0 when every lane completed, 1 when one failed, was cancelled, did not start or still runs past --timeout, 8 when one waits on a person
|
|
980
|
+
- `--timeout SECONDS` (number, this CLI's own): with --wait: stop waiting after this long (default 1800), exit 1; the runs go on
|
|
981
|
+
- `--json` (boolean, this CLI's own): with --wait: the lanes as JSON, in place of the table
|
|
982
|
+
|
|
954
983
|
## revisions
|
|
955
984
|
|
|
956
985
|
### `agentrun revisions list AGENT_ID`
|