@parcha/agentrun 0.3.6 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/follow.mjs ADDED
@@ -0,0 +1,260 @@
1
+ // `runs start --wait`, `runs wait` and `runs timeline --follow`: wait for a run and follow it live. Hand-written on top of
2
+ // the generated table (cli.mjs), from the timeline route's two forms: the long-polled JSON page and the event stream.
3
+ // `client` is cli.mjs's: `fetch(path, init)` with the token, `refused(response, bytes)` (the error on stderr, its exit
4
+ // code), `unreachable(error)` (exit 3, naming only the error's cause code, never its message) and `print(value)`.
5
+
6
+ const TERMINAL = new Set(["completed", "failed", "cancelled"]);
7
+ // What moves only once a person acts: input_required (a question, the spend cap, a stopped turn), and a workflow run's
8
+ // `paused` (this server's own status), which no wait ends until someone resumes it.
9
+ const PERSON = new Set(["input_required", "paused"]);
10
+ /** Exit codes, gh's: 8 is its "pending". */
11
+ const EXIT = { completed: 0, failed: 1, cancelled: 1, person: 8 };
12
+ const MAX_WAIT_MS = 25_000; // the route's wait_ms maximum
13
+ const RETRIES = 5; // tries in a row that get nothing before giving up, exit 3
14
+ const BACKOFF_MS = 500;
15
+ const MAX_BACKOFF_MS = 30_000;
16
+ const RETRIABLE = new Set([502, 503, 504]);
17
+ const IDLE_MS = 45_000; // three of the stream's 15 s keepalives missed: the connection is gone
18
+ /** The longest one request of a wait may take: a long poll's wait and the silence that means its connection is gone. */
19
+ export const REQUEST_MS = MAX_WAIT_MS + IDLE_MS;
20
+
21
+ /** The flags these add to a generated command (by its operationId), and their help lines. */
22
+ export const FLAGS = {
23
+ createRun: {
24
+ options: { wait: { type: "boolean" }, timeout: { type: "string" } },
25
+ help: [
26
+ ["--wait", "then wait until the run ends or waits on a person, and print it as runs wait does"],
27
+ ["--timeout SECONDS", "with --wait: stop waiting after this long, exit 1 (the run goes on)"],
28
+ ],
29
+ },
30
+ getTimeline: {
31
+ options: { follow: { type: "boolean" } },
32
+ help: [["--follow", "the timeline as it changes, one page per line (NDJSON), until the run ends; resumes a dropped connection"]],
33
+ },
34
+ };
35
+
36
+ /** The one command with no route of its own. */
37
+ export const WAIT = {
38
+ command: ["runs", "wait"],
39
+ pathParams: ["run_id"],
40
+ summary: "Wait until the run ends or waits on a person, and print it",
41
+ route: "GET /runs/{run_id}/timeline, long-polled, then GET /runs/{run_id}",
42
+ help: [["--timeout SECONDS", "stop waiting after this long, exit 1 (the run goes on)"]],
43
+ };
44
+
45
+ /** An error for `client.unreachable` that names what happened by its code alone. */
46
+ const failure = (code) => Object.assign(new Error(code), { cause: { code } });
47
+ /** The longest a Node timer waits: one asked for longer fires after 1 ms (TimeoutOverflowWarning). */
48
+ const MAX_TIMER_MS = 2 ** 31 - 1;
49
+ /** A count of milliseconds as timers and AbortSignal.timeout take it: a whole number (a fraction throws), at least 1,
50
+ * at most MAX_TIMER_MS. A wait longer than that is cut into timers this long by the loop that waits, so it keeps its
51
+ * length: every timer and abort here goes through this. */
52
+ export const timerMs = (ms) => Math.min(MAX_TIMER_MS, Math.max(1, Math.ceil(ms)));
53
+ /** A JSON object: not null, not a list. */
54
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
55
+ /** `text`'s JSON as `{ value }`, or undefined when it holds none. */
56
+ const jsonOf = (text) => {
57
+ try {
58
+ return { value: JSON.parse(text) };
59
+ } catch {
60
+ return undefined;
61
+ }
62
+ };
63
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, timerMs(ms)));
64
+ /** The wait before try `tries + 1`: the client's own delay, doubling up to its cap, and never under the server's `retry`
65
+ * (`floor`), which may be above that cap. */
66
+ export const backoff = (tries, floor = 0) => Math.max(floor, Math.min(MAX_BACKOFF_MS, BACKOFF_MS * 2 ** (tries - 1)));
67
+ // The final read of a wait past its --timeout, which prints the run as it is: bounded too.
68
+ const LAST_READ_MS = 1_000;
69
+
70
+ /** GET `path` as JSON: `{ value }`, `{ code }` once the server refused (its error on stderr), or `{ late: true }` once
71
+ * `deadline` passed: every try and every wait between tries ends by it. Once the server answered (`reached`), a dropped
72
+ * connection or a gateway's 502/503/504 is tried again a few times with backoff, then exit 3 (a 5xx, 1); a server never
73
+ * reached is exit 3 at once. */
74
+ async function getJson(client, path, reached, deadline) {
75
+ for (let tries = 1; ; tries++) {
76
+ const left = deadline - Date.now();
77
+ if (left <= 0) return { late: true };
78
+ let response;
79
+ let bytes;
80
+ try {
81
+ // A long poll answers within its wait_ms: one silent well past it is a connection gone.
82
+ response = await client.fetch(path, { signal: AbortSignal.timeout(timerMs(Math.min(REQUEST_MS, left))) });
83
+ bytes = Buffer.from(await response.arrayBuffer());
84
+ reached.yes = true;
85
+ } catch (error) {
86
+ if (Date.now() >= deadline) return { late: true };
87
+ if (!reached.yes || tries >= RETRIES) throw client.unreachable(error);
88
+ await pause(Math.min(backoff(tries), deadline - Date.now()));
89
+ continue;
90
+ }
91
+ if (RETRIABLE.has(response.status) && tries < RETRIES) {
92
+ await pause(Math.min(backoff(tries), deadline - Date.now()));
93
+ continue;
94
+ }
95
+ if (!response.ok) return { code: client.refused(response, bytes) };
96
+ try {
97
+ return { value: JSON.parse(bytes.toString("utf8")) };
98
+ } catch {
99
+ client.io.stderr.write(`The server's answer to GET ${path.split("?")[0]} is not JSON.\n`);
100
+ return { code: 1 };
101
+ }
102
+ }
103
+ }
104
+
105
+ /** The run printed, a line on stderr for one that waits on a person, and its exit code. */
106
+ function settle(client, run, id) {
107
+ client.print(run);
108
+ if (!PERSON.has(run.status)) return EXIT[run.status];
109
+ const go = `then \`agentrun runs wait ${id}\``;
110
+ const why = run.status === "paused" ? `is paused: resume it with \`agentrun runs resume ${id}\``
111
+ : run.pending?.kind === "question" ? `asked a question: answer it with \`agentrun runs message ${id} --content TEXT\``
112
+ : run.pending?.kind === "budget" ? `stopped at its spend cap: raise it with \`agentrun runs raise-cap ${id} --max-cost-usd ${Number.isFinite(run.pending.suggested_cap_usd) ? run.pending.suggested_cap_usd : "N"}\``
113
+ : run.pending?.kind ? `waits on a person (${run.pending.kind})`
114
+ : `was stopped by a person: send it a message with \`agentrun runs message ${id} --content TEXT\``;
115
+ client.io.stderr.write(`Run ${id} ${why}, ${go}.\n`);
116
+ return EXIT.person;
117
+ }
118
+
119
+ /** Waits until the run ends (completed, failed or cancelled, with every row in) or waits on a person, and prints it: exit
120
+ * 0 completed, 1 failed or cancelled, 8 waits on a person. It long-polls the timeline from change to change and reads
121
+ * the run when the page says it is there. `timeoutMs` bounds every request and every wait between them; past it, it
122
+ * prints the run as it is (read once more, briefly; else as last read, if it was) and exits 1, the run going on. */
123
+ export async function waitRun(client, runId, timeoutMs) {
124
+ const id = encodeURIComponent(runId);
125
+ const deadline = timeoutMs === undefined ? Infinity : Date.now() + Math.ceil(timeoutMs);
126
+ const reached = { yes: false };
127
+ let after = 0;
128
+ let last;
129
+ const late = async () => {
130
+ const run = await getJson(client, `/runs/${id}`, reached, Date.now() + LAST_READ_MS);
131
+ if (run.code !== undefined) return run.code;
132
+ const seen = run.value ?? last;
133
+ if (seen !== undefined) client.print(seen);
134
+ client.io.stderr.write(`Run ${runId} is still ${seen?.status ?? "going"} after ${Math.ceil(timeoutMs) / 1000} s; it goes on: wait again with \`agentrun runs wait ${runId}\`.\n`);
135
+ return 1;
136
+ };
137
+ for (let first = true; ; first = false) {
138
+ const left = deadline - Date.now();
139
+ if (left <= 0) return late();
140
+ const waitMs = first ? 0 : Math.min(MAX_WAIT_MS, Math.ceil(left));
141
+ const got = await getJson(client, `/runs/${id}/timeline?after=${after}&wait_ms=${waitMs}`, reached, deadline);
142
+ if (got.late) return late();
143
+ if (got.code !== undefined) return got.code;
144
+ const page = got.value;
145
+ after = page.next_after;
146
+ const ended = (status) => (TERMINAL.has(status) && page.final) || PERSON.has(status);
147
+ if (ended(page.status)) {
148
+ const run = await getJson(client, `/runs/${id}`, reached, deadline);
149
+ if (run.late) return late();
150
+ if (run.code !== undefined) return run.code;
151
+ last = run.value;
152
+ // A message can reopen the run between the two reads: then it is waited for again.
153
+ if (ended(run.value.status)) return settle(client, run.value, runId);
154
+ }
155
+ if (page.unchanged && !page.has_more) await pause(Math.min(page.poll_after_ms ?? 1000, deadline - Date.now()));
156
+ }
157
+ }
158
+
159
+ /** The events of a `text/event-stream` body, as the HTML standard parses them: `{ event, data, id, retry }` once its
160
+ * blank line came, so an event cut off mid-way is never seen. `id` is the last id field seen, carried from event to event. */
161
+ async function* events(body, heard) {
162
+ const decoder = new TextDecoder();
163
+ let buffer = "";
164
+ let event = { event: "", data: [] };
165
+ let id;
166
+ for await (const chunk of body) {
167
+ heard();
168
+ let text = buffer + decoder.decode(chunk, { stream: true });
169
+ // A CR at the end may be the first half of a CRLF still to come.
170
+ const held = text.endsWith("\r") ? "\r" : "";
171
+ if (held) text = text.slice(0, -1);
172
+ const lines = text.split(/\r\n|\r|\n/);
173
+ buffer = lines.pop() + held;
174
+ for (const line of lines) {
175
+ if (line === "") {
176
+ if (event.data.length || event.retry !== undefined) yield { event: event.data.length ? event.event || "message" : "", data: event.data.join("\n"), id, retry: event.retry };
177
+ event = { event: "", data: [] };
178
+ } else if (!line.startsWith(":")) {
179
+ const colon = line.indexOf(":");
180
+ const field = colon < 0 ? line : line.slice(0, colon);
181
+ const value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, "");
182
+ if (field === "event") event.event = value;
183
+ else if (field === "data") event.data.push(value);
184
+ // The route's ids are change numbers; anything else is never sent back as a header.
185
+ else if (field === "id" && /^\d+$/.test(value)) id = value;
186
+ else if (field === "retry" && /^\d+$/.test(value)) event.retry = Number(value);
187
+ }
188
+ }
189
+ }
190
+ }
191
+
192
+ /** `runs timeline RUN_ID --follow`: the route's event stream, each `rows` event's page as one line of JSON on stdout, as
193
+ * the server sent it (its rows, its drops, `reset` when the rows held are to go first). A dropped connection, or the
194
+ * server's `end` with `reason: reconnect`, or a stream silent past three keepalives, reconnects with `Last-Event-ID`, so
195
+ * no change comes twice; tries that get no event back off (the server's `retry` the least wait) and give up after a few
196
+ * in a row, exit 3. It ends with the server's `end` with `reason: terminal`, which comes right after the first page with
197
+ * `final: true`: exit 0 when the run completed, 1 when it failed or was cancelled. A run that waits on a person keeps
198
+ * the stream open, as the server does. `path` is the route with its query (`after` is where it starts), and `headers`
199
+ * the command's (its `--last-event-id` wins over `after`, as the route says). */
200
+ export async function followTimeline(client, path, headers = {}) {
201
+ const { "Last-Event-ID": from, ...rest } = headers;
202
+ let reached = false;
203
+ let last = from;
204
+ let retryMs = 0;
205
+ let status;
206
+ for (let tries = 0; ; ) {
207
+ let progress = false;
208
+ let reconnect = false;
209
+ let cause;
210
+ const silent = new AbortController();
211
+ let timer;
212
+ const heard = () => (clearTimeout(timer), (timer = setTimeout(() => silent.abort(failure("stream_silent")), IDLE_MS)));
213
+ heard();
214
+ try {
215
+ const response = await client.fetch(path, { headers: { ...rest, accept: "text/event-stream", ...(last !== undefined ? { "last-event-id": last } : {}) }, signal: silent.signal });
216
+ reached = true;
217
+ if (RETRIABLE.has(response.status)) throw failure(`http_${response.status}`);
218
+ if (!response.ok) return client.refused(response, Buffer.from(await response.arrayBuffer()));
219
+ if (!/^text\/event-stream\b/.test(response.headers.get("content-type") ?? "")) {
220
+ client.io.stderr.write(`The server answered ${response.headers.get("content-type") ?? "with no content type"}, not an event stream.\n`);
221
+ return 1;
222
+ }
223
+ for await (const { event, data, id, retry } of events(response.body, heard)) {
224
+ if (retry !== undefined) retryMs = retry;
225
+ // An event that is not JSON is the server's bad answer, not a connection gone: said, exit 1, not tried again.
226
+ const json = event === "rows" || event === "end" ? jsonOf(data) : undefined;
227
+ if ((event === "rows" || event === "end") && !isObject(json?.value)) {
228
+ client.io.stderr.write(`The server's timeline stream sent ${event === "end" ? "an" : "a"} ${event} event that is not a JSON object.\n`);
229
+ return 1;
230
+ }
231
+ if (event === "rows") {
232
+ const page = json.value;
233
+ client.io.stdout.write(`${JSON.stringify(page)}\n`);
234
+ status = page.status;
235
+ progress = true;
236
+ }
237
+ if (id !== undefined) last = id;
238
+ if (event === "end") {
239
+ if (json.value?.reason === "terminal") return EXIT[status] ?? 1;
240
+ reconnect = true;
241
+ break;
242
+ }
243
+ }
244
+ } catch (error) {
245
+ if (!reached) throw client.unreachable(error);
246
+ cause = error;
247
+ } finally {
248
+ clearTimeout(timer);
249
+ }
250
+ if (reconnect) {
251
+ tries = 0;
252
+ if (retryMs) await pause(retryMs);
253
+ continue;
254
+ }
255
+ // The stream ended with no `end`, or broke: the connection dropped.
256
+ tries = progress ? 1 : tries + 1;
257
+ if (tries > RETRIES) throw client.unreachable(cause ?? failure("stream_closed"));
258
+ await pause(backoff(tries, retryMs));
259
+ }
260
+ }
package/lib/login.mjs ADDED
@@ -0,0 +1,208 @@
1
+ // The commands that take a secret, from stdin and never from the command line: `login` (the token for a server, checked
2
+ // and kept in the config file) and `logout`. No command writes a key or any other secret to the server: those are set in
3
+ // the console, signed in, and the server refuses the token on them (secret-writes.ts). A secret is never in argv, so
4
+ // never in shell history or `ps`, and never in any output or error. Each command is `{ command, pathParams, summary,
5
+ // route?, help, options, run }`; cli.mjs runs it with `{ values, args, env, io, cli }`, where `cli` is its own
6
+ // `{ fail, targetOf, clientOf, request, send, secretAt, BAD_HEADER }`: the token's custody and the requests are its.
7
+ import { randomBytes } from "node:crypto";
8
+ import { chmodSync, closeSync, constants, existsSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync, writeSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import { dirname, join } from "node:path";
11
+
12
+ /** The config file `login` writes and every command reads (cli.mjs's targetOf, which refuses it unless it is a private
13
+ * file of this user's): $XDG_CONFIG_HOME/agentrun/config.json, else
14
+ * ~/.config/agentrun/config.json. */
15
+ export const configFileOf = (env) => join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "agentrun", "config.json");
16
+
17
+ /** Everything on stdin, refused when stdin is a terminal: what is typed there is shown on it. */
18
+ async function readSecret(io, fail, what, how) {
19
+ if (io.stdin.isTTY) throw fail(2, `${what} is read from stdin, never typed on a terminal or given as an argument: ${how}.`);
20
+ const chunks = [];
21
+ for await (const chunk of io.stdin) chunks.push(chunk);
22
+ return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
23
+ }
24
+
25
+ /** The forms a server that echoes what it was sent quotes a secret in: as it is, JSON-escaped and URL-encoded. */
26
+ const formsOf = (secret) => [...new Set([secret, JSON.stringify(secret).slice(1, -1), encodeURIComponent(secret)])].sort((a, b) => b.length - a.length);
27
+
28
+ /** A second line against a server that echoes what it was sent (the first: a refusal's body is never printed): what
29
+ * cuts each secret's copies in those three forms, at any length. `text(string)` cuts them from a text, and
30
+ * `value(json)` from a JSON value's strings and keys only, so the value printed again is still JSON, its structure and
31
+ * every other value as they were. Two keys the cut makes one are kept apart. It is no guard against a server that
32
+ * means to hand a secret back, which can encode it any other way: a secret goes only to a server it is meant for. */
33
+ function scrubberOf(secrets) {
34
+ const forms = [...new Set(secrets.filter(Boolean).flatMap(formsOf))].sort((a, b) => b.length - a.length);
35
+ const text = (string) => forms.reduce((at, form) => at.split(form).join("[hidden]"), string);
36
+ const value = (node) => {
37
+ if (typeof node === "string") return text(node);
38
+ if (Array.isArray(node)) return node.map(value);
39
+ if (node === null || typeof node !== "object") return node;
40
+ // No prototype, so every key is the object's own, __proto__ and constructor as much as any; JSON.stringify prints
41
+ // it as it would a plain object.
42
+ const out = Object.create(null);
43
+ for (const [key, child] of Object.entries(node)) {
44
+ let name = text(key);
45
+ for (let n = 2; Object.hasOwn(out, name); n++) name = `${text(key)} (${n})`;
46
+ out[name] = value(child);
47
+ }
48
+ return out;
49
+ };
50
+ return { text, value };
51
+ }
52
+
53
+ /** `io` with the secrets cut from what goes to stderr, which carries only this CLI's own lines. */
54
+ const quietStderr = (io, scrub) => ({ ...io, stderr: { isTTY: io.stderr.isTTY, write: (chunk) => io.stderr.write(scrub.text(String(chunk))) } });
55
+
56
+ /** The string values of a secret route's JSON body, but for its public fields (`publicFields`, full paths such as
57
+ * `auth.type`, or `scopes.[]` for each item of a list, from the table), or the whole body when it is not JSON: the secrets to cut from what is printed. A value
58
+ * under a map (a header's, a tool key field's) is never public, whatever its key. */
59
+ function secretsOf(body, publicFields = []) {
60
+ const text = body === undefined ? "" : String(body);
61
+ let value;
62
+ try {
63
+ value = JSON.parse(text);
64
+ } catch {
65
+ return [text];
66
+ }
67
+ const open = new Set(publicFields.map((field) => JSON.stringify(field.split("."))));
68
+ const found = [];
69
+ const walk = (node, path) => {
70
+ if (typeof node === "string") return void (open.has(JSON.stringify(path)) || found.push(node));
71
+ if (node && typeof node === "object") for (const [key, child] of Object.entries(node)) walk(child, Array.isArray(node) ? [...path, "[]"] : [...path, key]);
72
+ };
73
+ walk(value, []);
74
+ return found;
75
+ }
76
+
77
+ /** A client for a request that carries a secret: a refusal prints the status, the error's code when it is one, and a
78
+ * message of this CLI's own, never the server's answer, which could quote the secret. What it does print has every
79
+ * copy of `secrets` cut: `scrub`, which cli.mjs's send applies to a JSON answer's value before it prints it, and to a
80
+ * text answer's text. */
81
+ function secretClient(clientOf, target, io, secrets) {
82
+ const scrub = scrubberOf(secrets);
83
+ const client = clientOf(target, quietStderr(io, scrub));
84
+ return {
85
+ ...client,
86
+ scrub,
87
+ refused(response, bytes) {
88
+ let code;
89
+ try {
90
+ code = JSON.parse(bytes.toString("utf8"))?.error?.code;
91
+ } catch {
92
+ code = undefined;
93
+ }
94
+ const named = typeof code === "string" && /^[a-z_]+$/.test(code) ? ` ${code}` : "";
95
+ client.io.stderr.write(`The server refused it: ${response.status}${named}. Its answer is not shown, since it could quote the secret sent.\n`);
96
+ return response.status === 401 || response.status === 403 ? 4 : 1;
97
+ },
98
+ };
99
+ }
100
+
101
+ /** cli.mjs's client for a generated command or an `api` call whose body goes to a secret route, with that route's
102
+ * public fields. */
103
+ export const guarded = (clientOf, target, io, body, publicFields) => secretClient(clientOf, target, io, secretsOf(body, publicFields));
104
+
105
+ /** The folder's entries on the disk, so a rename in it outlasts a crash; where a folder cannot be synced, as is. */
106
+ function syncFolder(dir) {
107
+ let fd;
108
+ try {
109
+ fd = openSync(dir, constants.O_RDONLY);
110
+ fsyncSync(fd);
111
+ } catch {
112
+ // Some filesystems take no fsync of a folder: the file itself is on the disk.
113
+ } finally {
114
+ if (fd !== undefined) closeSync(fd);
115
+ }
116
+ }
117
+
118
+ const print = (io, value) => io.stdout.write(`${io.stdout.isTTY ? JSON.stringify(value, null, 2) : JSON.stringify(value)}\n`);
119
+
120
+ export const LOGIN = {
121
+ command: ["login"],
122
+ pathParams: [],
123
+ summary: "Check a server's token, read from stdin, and keep it with the server's address in the config file",
124
+ route: "GET /agents?limit=1, to check the token",
125
+ help: [
126
+ ["--base-url URL", "the server's API, ending /v2 (default AGENTRUN_BASE_URL)"],
127
+ ["(stdin)", "the token: agentrun login --base-url URL < FILE"],
128
+ ],
129
+ options: {},
130
+ async run({ values, env, io, cli }) {
131
+ const flagged = values["base-url"] !== undefined;
132
+ const given = flagged ? values["base-url"] : env.AGENTRUN_BASE_URL;
133
+ if (given === undefined) throw cli.fail(2, "agentrun login needs the server: --base-url URL (its API, ending /v2) or AGENTRUN_BASE_URL.");
134
+ const base = cli.baseOf(given, flagged ? "--base-url" : "AGENTRUN_BASE_URL");
135
+ const token = (await readSecret(io, cli.fail, "The token", "agentrun login --base-url URL < FILE")).trim();
136
+ if (!token) throw cli.fail(2, "stdin holds no token: one line, the token alone.");
137
+ // Refused before it is sent, as every command refuses one: fetch would quote a bad header value in its error.
138
+ if (cli.BAD_HEADER.test(token) || /\s/.test(token)) throw cli.fail(4, "The token is not a valid header value (it holds a space, a line break, a control character or a character outside Latin-1); nothing was written.");
139
+ const client = secretClient(cli.clientOf, { base, token }, io, [token]);
140
+ const checked = await cli.request(client, { method: "GET", path: "/agents?limit=1", headers: {} });
141
+ if (checked.code !== undefined) {
142
+ client.io.stderr.write(`${checked.code === 4 ? `The server at ${base} refused the token` : `The server at ${base} did not take the check`}; nothing was written.\n`);
143
+ return checked.code;
144
+ }
145
+ // A 200 from another route or another server would save a token nothing checked: the answer must be the agents list.
146
+ let list;
147
+ try {
148
+ list = JSON.parse(checked.bytes.toString("utf8"));
149
+ } catch {
150
+ list = undefined;
151
+ }
152
+ if (!Array.isArray(list?.agents) || !("next_cursor" in list)) {
153
+ client.io.stderr.write(`The server at ${base} answered the check with ${checked.response.status}, not an agents list; nothing was written.\n`);
154
+ return 1;
155
+ }
156
+ const file = configFileOf(env);
157
+ // Written whole beside it under a name no one could have planted (random, opened only if it is new, through no
158
+ // link), then moved over it: a reader never sees half a file, and it is never wider than 0600. Any failure is said
159
+ // plainly, its code alone, and leaves nothing behind.
160
+ const temp = join(dirname(file), `.config.json.${randomBytes(8).toString("hex")}.tmp`);
161
+ let made = false;
162
+ try {
163
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
164
+ chmodSync(dirname(file), 0o700);
165
+ const fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
166
+ made = true;
167
+ try {
168
+ // Every byte, however few one write takes (a full disk, a quota), and on the disk before it takes the old one's
169
+ // place: the rename never puts half a config where a whole one was.
170
+ const bytes = Buffer.from(`${JSON.stringify({ base_url: base, api_key: token }, null, 2)}\n`);
171
+ for (let at = 0; at < bytes.length; ) {
172
+ const wrote = writeSync(fd, bytes, at, bytes.length - at);
173
+ if (!(wrote > 0)) throw Object.assign(new Error("a write wrote nothing"), { code: "EIO" });
174
+ at += wrote;
175
+ }
176
+ fsyncSync(fd);
177
+ } finally {
178
+ closeSync(fd);
179
+ }
180
+ renameSync(temp, file);
181
+ made = false;
182
+ syncFolder(dirname(file));
183
+ } catch (error) {
184
+ throw cli.fail(4, `Cannot write the config file ${file} (${/^E[A-Z]+$/.test(error?.code ?? "") ? error.code : "an error"}); nothing was written.`);
185
+ } finally {
186
+ if (made) rmSync(temp, { force: true });
187
+ }
188
+ print(io, { base_url: base, config_file: file });
189
+ return 0;
190
+ },
191
+ };
192
+
193
+ export const LOGOUT = {
194
+ command: ["logout"],
195
+ pathParams: [],
196
+ summary: "Remove the config file login wrote, its address and token",
197
+ help: [],
198
+ options: {},
199
+ async run({ env, io }) {
200
+ const file = configFileOf(env);
201
+ const removed = existsSync(file);
202
+ rmSync(file, { force: true });
203
+ print(io, { config_file: file, removed });
204
+ return 0;
205
+ },
206
+ };
207
+
208
+ export const SECRETS = [LOGIN, LOGOUT];
package/lib/skill.mjs ADDED
@@ -0,0 +1,88 @@
1
+ // `agentrun skill install`: this package's skill (skills/agentrun-cli, generated by scripts/generate-clients.mjs) copied
2
+ // into the skill folders of the coding agents on this machine, or into one named. Claude Code reads a person's skills from
3
+ // ~/.claude/skills (CLAUDE_CONFIG_DIR moves ~/.claude), Codex from ~/.agents/skills, the shared folder Cursor reads too.
4
+ import { cpSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import { basename, dirname, join, resolve, sep } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const NAME = "agentrun-cli";
10
+ const SOURCE = fileURLToPath(new URL(`../skills/${NAME}`, import.meta.url));
11
+
12
+ /** `path` with every link resolved, for a path that does not exist yet too (from the nearest folder that does). */
13
+ const real = (path) => {
14
+ try {
15
+ return realpathSync(path);
16
+ } catch (error) {
17
+ if (error.code !== "ENOENT" || dirname(path) === path) throw error;
18
+ return join(real(dirname(path)), basename(path));
19
+ }
20
+ };
21
+ const within = (path, folder) => path === folder || path.startsWith(`${folder}${sep}`);
22
+
23
+ /** `target` replaced by a copy of the skill: copied beside it first and moved in by rename, so a copy that fails
24
+ * leaves `target` as it was, and the old one goes only once the new one is in its place. */
25
+ function replace(target) {
26
+ const dir = dirname(target);
27
+ mkdirSync(dir, { recursive: true });
28
+ const stamp = `${process.pid}-${Date.now()}`;
29
+ const fresh = join(dir, `.${NAME}.${stamp}.new`);
30
+ const old = join(dir, `.${NAME}.${stamp}.old`);
31
+ try {
32
+ cpSync(SOURCE, fresh, { recursive: true });
33
+ const had = existsSync(target);
34
+ if (had) renameSync(target, old);
35
+ try {
36
+ renameSync(fresh, target);
37
+ } catch (error) {
38
+ if (had) renameSync(old, target);
39
+ throw error;
40
+ }
41
+ } finally {
42
+ rmSync(fresh, { recursive: true, force: true });
43
+ rmSync(old, { recursive: true, force: true });
44
+ }
45
+ }
46
+
47
+ /** A folder this command may replace: none there yet, or this skill, by its front matter's name. */
48
+ const ours = (dir) => {
49
+ if (!existsSync(dir)) return true;
50
+ try {
51
+ return /^---\n(?:.*\n)*?name: agentrun-cli\n/.test(readFileSync(join(dir, "SKILL.md"), "utf8"));
52
+ } catch {
53
+ return false;
54
+ }
55
+ };
56
+
57
+ export const SKILL_INSTALL = {
58
+ command: ["skill", "install"],
59
+ pathParams: [],
60
+ summary: "Install this CLI's skill (agentrun-cli) for Claude Code and Codex, or into a skills directory",
61
+ help: [
62
+ ["--claude", "into Claude Code's skills: ~/.claude/skills/agentrun-cli"],
63
+ ["--codex", "into ~/.agents/skills/agentrun-cli, the shared skills folder Codex reads (Cursor too)"],
64
+ ["--dir DIR", "into DIR/agentrun-cli (a project's .claude/skills or .agents/skills, say)"],
65
+ ["", "with none of them: each of ~/.claude (Claude Code) and ~/.agents that exists on this machine"],
66
+ ],
67
+ options: { claude: { type: "boolean" }, codex: { type: "boolean" }, dir: { type: "string" } },
68
+ async run({ values, env, io, cli }) {
69
+ const claude = join(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "skills");
70
+ const agents = join(homedir(), ".agents", "skills");
71
+ const asked = [values.claude && claude, values.codex && agents, values.dir !== undefined && resolve(values.dir)].filter(Boolean);
72
+ const dirs = asked.length ? asked : [claude, agents].filter((dir) => existsSync(join(dir, "..")));
73
+ if (!dirs.length) throw cli.fail(2, `Neither ${join(claude, "..")} nor ${join(agents, "..")} exists: name where with --claude, --codex or --dir DIR.`);
74
+ // Every target checked before any is touched: none may be this package's own skill folder (through a link too),
75
+ // lie inside it, or hold it, and each is empty or this skill.
76
+ const source = realpathSync(SOURCE);
77
+ const targets = dirs.map((dir) => join(dir, NAME));
78
+ for (const target of targets) {
79
+ const at = real(target);
80
+ if (within(at, source) || within(source, at)) throw cli.fail(2, `${target} is this package's own skill folder, lies inside it or holds it: install the skill elsewhere.`);
81
+ if (!ours(target)) throw cli.fail(1, `${target} exists and is not this skill: move it, or install with --dir DIR.`);
82
+ }
83
+ for (const target of targets) replace(target);
84
+ const installed = targets;
85
+ io.stdout.write(`${JSON.stringify({ installed })}\n`);
86
+ return 0;
87
+ },
88
+ };