@parcha/agentrun 0.4.19 → 0.4.21
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 +12 -1
- package/lib/cli.mjs +108 -11
- package/lib/commands.generated.mjs +416 -6
- package/lib/deploy.mjs +664 -0
- package/lib/device.mjs +230 -0
- package/lib/export.mjs +80 -0
- package/lib/harness.mjs +19 -0
- package/lib/login.mjs +63 -42
- package/lib/start.mjs +1 -1
- package/lib/target.mjs +13 -0
- package/package.json +2 -2
- package/skills/agentrun-cli/SKILL.md +9 -7
- package/skills/agentrun-cli/references/commands.md +177 -8
package/lib/device.mjs
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
// Device sign-in (RFC 8628) for `agentrun login --to`, used when the target's GET /v2/capabilities offers it:
|
|
2
|
+
// `sign_in.device`, the metadata's URL and the scope to ask for. The person opens the address printed, enters the code
|
|
3
|
+
// and approves there; the token endpoint then answers a token, which login keeps where it keeps a pasted one. Every URL
|
|
4
|
+
// fetched is on the target's own origin, over https unless the target is on this machine; no redirect is followed; each
|
|
5
|
+
// answer's size and shape are checked before any of it is used. The device code and the token are never printed, never
|
|
6
|
+
// in an error and never in argv.
|
|
7
|
+
|
|
8
|
+
/** A sign-in that stopped: its exit code (cli.mjs's), and words of this CLI's own, never a server's answer. */
|
|
9
|
+
export class SignInError extends Error {
|
|
10
|
+
constructor(code, message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.code = code;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const NOTHING = "nothing was written";
|
|
17
|
+
const refuse = (code, message) => new SignInError(code, message);
|
|
18
|
+
const bad = (what) => refuse(1, `The server's device sign-in ${what}; ${NOTHING}.`);
|
|
19
|
+
|
|
20
|
+
/** The most read of a capabilities answer, and of each answer of the device flow. */
|
|
21
|
+
const CAPABILITIES_BYTES = 4 * 1024 * 1024;
|
|
22
|
+
const ANSWER_BYTES = 64 * 1024;
|
|
23
|
+
/** How long one request may take. */
|
|
24
|
+
const REQUEST_MS = 10_000;
|
|
25
|
+
/** The longest wait between two polls after a server error or a failed request. */
|
|
26
|
+
const BACKOFF_MS = 60_000;
|
|
27
|
+
/** The interval when the authorization's answer names none (RFC 8628 3.2), and what slow_down adds to it (3.5). */
|
|
28
|
+
const INTERVAL_S = 5;
|
|
29
|
+
const SLOW_DOWN_MS = 5_000;
|
|
30
|
+
const GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
|
|
31
|
+
|
|
32
|
+
const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]); // key-gate: loopback-rule the hosts a device sign-in may reach over http
|
|
33
|
+
const VISIBLE = /^[\x21-\x7e]{1,2048}$/;
|
|
34
|
+
const USER_CODE = /^[\x20-\x7e]{1,256}$/;
|
|
35
|
+
const SECRET = /^[\x21-\x7e]{1,8192}$/;
|
|
36
|
+
const SCOPE_TOKEN = "[\\x21\\x23-\\x5b\\x5d-\\x7e]+";
|
|
37
|
+
const SCOPE = new RegExp(`^${SCOPE_TOKEN}(?: ${SCOPE_TOKEN})*$`);
|
|
38
|
+
const OBJECT = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
39
|
+
const SECONDS = (value, min, max) => Number.isInteger(value) && value >= min && value <= max;
|
|
40
|
+
|
|
41
|
+
/** `value` as a URL when this flow takes it: absolute and printable, with no user, password, fragment, backslash or port
|
|
42
|
+
* 0, no query unless `query`; https, or http on a loopback host while the target is on one too; and on the target's own
|
|
43
|
+
* origin unless `elsewhere` (an address the person opens, which the flow never fetches). Else undefined. */
|
|
44
|
+
function urlOf(value, target, { query = false, elsewhere = false } = {}) {
|
|
45
|
+
if (typeof value !== "string" || !VISIBLE.test(value) || /[\\#]/.test(value) || (!query && value.includes("?")) || !URL.canParse(value)) return undefined;
|
|
46
|
+
const url = new URL(value);
|
|
47
|
+
if (url.username || url.password || url.port === "0") return undefined;
|
|
48
|
+
const sealed = url.protocol === "https:" || (url.protocol === "http:" && LOOPBACK.has(url.hostname) && LOOPBACK.has(target.hostname));
|
|
49
|
+
return sealed && (elsewhere || url.origin === target.origin) ? url : undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** An OAuth error code from an answer's body, when it is one: a short lowercase word, never a server's free text. */
|
|
53
|
+
const errorOf = (body) => (typeof body?.error === "string" && /^[a-z_]{1,64}$/.test(body.error) ? body.error : undefined);
|
|
54
|
+
|
|
55
|
+
/** `response`'s body, or undefined past `max` bytes, read no further. */
|
|
56
|
+
async function capped(response, max) {
|
|
57
|
+
if (Number(response.headers.get("content-length")) > max) return void (await response.body?.cancel());
|
|
58
|
+
const chunks = [];
|
|
59
|
+
let size = 0;
|
|
60
|
+
for await (const chunk of response.body ?? []) {
|
|
61
|
+
size += chunk.byteLength;
|
|
62
|
+
if (size > max) return undefined;
|
|
63
|
+
chunks.push(chunk);
|
|
64
|
+
}
|
|
65
|
+
return Buffer.concat(chunks);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** One request, never redirected: `{ status, redirect }` for a 3xx, else `{ status, body, retryAfter }`, body the answer's
|
|
69
|
+
* JSON object (undefined when it holds none or is past `max`). A request that fails throws as fetch does. */
|
|
70
|
+
async function ask(url, { form, max = ANSWER_BYTES, ms = REQUEST_MS } = {}) {
|
|
71
|
+
const response = await fetch(url, {
|
|
72
|
+
method: form ? "POST" : "GET",
|
|
73
|
+
redirect: "manual",
|
|
74
|
+
signal: AbortSignal.timeout(ms),
|
|
75
|
+
headers: { accept: "application/json", ...(form ? { "content-type": "application/x-www-form-urlencoded" } : {}) },
|
|
76
|
+
...(form ? { body: new URLSearchParams(form).toString() } : {}),
|
|
77
|
+
});
|
|
78
|
+
if (response.status >= 300 && response.status < 400) return await response.body?.cancel(), { status: response.status, redirect: true };
|
|
79
|
+
const bytes = await capped(response, max);
|
|
80
|
+
let body;
|
|
81
|
+
try {
|
|
82
|
+
body = bytes === undefined ? undefined : JSON.parse(bytes.toString("utf8"));
|
|
83
|
+
} catch {
|
|
84
|
+
body = undefined;
|
|
85
|
+
}
|
|
86
|
+
return { status: response.status, body: OBJECT(body) ? body : undefined, retryAfter: retryAfterMs(response.headers.get("retry-after")) };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** A Retry-After header's wait in ms from `now` (RFC 9110 10.2.3: delay seconds, or an HTTP date), 0 for anything else
|
|
90
|
+
* or a time already past. It is never cut short: the code's expiry bounds every wait. */
|
|
91
|
+
export function retryAfterMs(value, now = Date.now()) {
|
|
92
|
+
if (typeof value !== "string" || value.length > 64) return 0;
|
|
93
|
+
if (/^\d+$/.test(value)) return Number(value) * 1000;
|
|
94
|
+
const at = /[a-z]/i.test(value) ? Date.parse(value) : NaN;
|
|
95
|
+
return Number.isFinite(at) && at > now ? at - now : 0;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Why a request failed, in a word: the cause's code, or the error's name (TimeoutError). */
|
|
99
|
+
const why = (error) => (typeof error?.cause?.code === "string" ? error.cause.code : typeof error?.name === "string" ? error.name : "an error");
|
|
100
|
+
|
|
101
|
+
/** The target's GET /capabilities, asked with no token: its JSON object, or undefined when it answers no 2xx (a target
|
|
102
|
+
* that offers nothing, so login reads a token from stdin). A redirect, an answer that is not a JSON object, or a target
|
|
103
|
+
* not reached is refused. */
|
|
104
|
+
export async function capabilitiesOf(base) {
|
|
105
|
+
let answer;
|
|
106
|
+
try {
|
|
107
|
+
answer = await ask(`${base}/capabilities`, { max: CAPABILITIES_BYTES });
|
|
108
|
+
} catch (error) {
|
|
109
|
+
throw refuse(3, `Cannot reach the server at ${base} (${why(error)}); ${NOTHING}.`);
|
|
110
|
+
}
|
|
111
|
+
if (answer.redirect) throw refuse(1, `The server at ${base} answered GET /capabilities with a redirect (${answer.status}), which login never follows: give the address it redirects to; ${NOTHING}.`);
|
|
112
|
+
if (answer.status < 200 || answer.status > 299) return undefined;
|
|
113
|
+
if (!answer.body) throw refuse(1, `The server at ${base} answered GET /capabilities with something other than a JSON object; ${NOTHING}.`);
|
|
114
|
+
return answer.body;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The device sign-in a capabilities answer offers, `{ metadata, scope }`, or undefined when it offers none (no
|
|
118
|
+
* sign_in.device). An offer this flow cannot take is refused: a target over http off this machine (exit 2), or an offer
|
|
119
|
+
* that is malformed or whose metadata is off the target's origin (exit 1). */
|
|
120
|
+
export function deviceOffer(capabilities, base) {
|
|
121
|
+
const offer = capabilities?.sign_in;
|
|
122
|
+
if (offer === undefined || offer === null) return undefined;
|
|
123
|
+
if (!OBJECT(offer)) throw bad("offer (sign_in) is not an object");
|
|
124
|
+
if (offer.device === undefined) return undefined;
|
|
125
|
+
const target = new URL(base);
|
|
126
|
+
if (target.protocol !== "https:" && !LOOPBACK.has(target.hostname)) throw refuse(2, `The server at ${base} offers a device sign-in over http, which would carry the token in the clear: use its https address; ${NOTHING}.`);
|
|
127
|
+
const metadata = OBJECT(offer.device) ? urlOf(offer.device.metadata, target) : undefined;
|
|
128
|
+
const scope = offer.device?.scope;
|
|
129
|
+
if (!metadata || typeof scope !== "string" || scope.length > 1024 || !SCOPE.test(scope)) {
|
|
130
|
+
throw bad("offer (sign_in.device) is not one this CLI takes: metadata must be an https URL on the server's own origin (http only on this machine) and scope an OAuth scope");
|
|
131
|
+
}
|
|
132
|
+
return { metadata, scope };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
136
|
+
|
|
137
|
+
/** The device flow for `offer` on the target `base`, its lines to the person on `io.stderr`: the token, once the person
|
|
138
|
+
* approved. Every refusal is a SignInError that says nothing was written. */
|
|
139
|
+
export async function deviceSignIn(base, offer, io) {
|
|
140
|
+
const target = new URL(base);
|
|
141
|
+
const unreached = (url, error) => refuse(3, `Cannot reach ${url.origin} for the device sign-in (${why(error)}); ${NOTHING}.`);
|
|
142
|
+
|
|
143
|
+
let meta;
|
|
144
|
+
try {
|
|
145
|
+
meta = await ask(offer.metadata);
|
|
146
|
+
} catch (error) {
|
|
147
|
+
throw unreached(offer.metadata, error);
|
|
148
|
+
}
|
|
149
|
+
if (meta.redirect) throw bad(`metadata answered with a redirect (${meta.status}), which this CLI never follows`);
|
|
150
|
+
if (meta.status !== 200 || !meta.body) throw bad(`metadata answered ${meta.status}${meta.body ? "" : ", not a JSON object (or one too large)"}`);
|
|
151
|
+
const m = meta.body;
|
|
152
|
+
if (["issuer", "client_id", "device_authorization_endpoint", "token_endpoint", "resource"].some((field) => typeof m[field] !== "string" || !VISIBLE.test(m[field])) || typeof m.scope !== "string" || !/^[\x20-\x7e]{1,1024}$/.test(m.scope)) {
|
|
153
|
+
throw bad("metadata lacks a field it needs, or holds one this CLI does not take");
|
|
154
|
+
}
|
|
155
|
+
const issuer = urlOf(m.issuer, target);
|
|
156
|
+
const authorization = urlOf(m.device_authorization_endpoint, target);
|
|
157
|
+
const tokenAt = urlOf(m.token_endpoint, target);
|
|
158
|
+
if (!issuer || !authorization || !tokenAt) throw bad("metadata names an issuer or endpoint that is off the server's own origin or not over https");
|
|
159
|
+
if (m.verification_uri != null && !urlOf(m.verification_uri, target, { query: true, elsewhere: true })) throw bad("metadata's verification_uri is not an https URL");
|
|
160
|
+
|
|
161
|
+
const started = Date.now();
|
|
162
|
+
let granted;
|
|
163
|
+
try {
|
|
164
|
+
granted = await ask(authorization, { form: { client_id: m.client_id, scope: offer.scope, audience: m.resource } });
|
|
165
|
+
} catch (error) {
|
|
166
|
+
throw unreached(authorization, error);
|
|
167
|
+
}
|
|
168
|
+
if (granted.redirect) throw bad(`authorization endpoint answered with a redirect (${granted.status}), which this CLI never follows`);
|
|
169
|
+
const g = granted.body;
|
|
170
|
+
if (granted.status === 200 && !g) throw bad("authorization endpoint answered something other than a JSON object, or one too large");
|
|
171
|
+
if (granted.status !== 200 || g.error !== undefined) {
|
|
172
|
+
const code = errorOf(g);
|
|
173
|
+
if (code === "access_denied") throw refuse(4, `The sign-in was denied; ${NOTHING}.`);
|
|
174
|
+
throw refuse(1, `The server refused the device sign-in request: ${granted.status}${code ? ` ${code}` : ""}; ${NOTHING}.`);
|
|
175
|
+
}
|
|
176
|
+
const interval = g.interval === undefined ? INTERVAL_S : g.interval;
|
|
177
|
+
if (typeof g.device_code !== "string" || !SECRET.test(g.device_code) || typeof g.user_code !== "string" || !USER_CODE.test(g.user_code)
|
|
178
|
+
|| !urlOf(g.verification_uri, target, { query: true, elsewhere: true }) || (g.verification_uri_complete != null && !urlOf(g.verification_uri_complete, target, { query: true, elsewhere: true }))
|
|
179
|
+
|| !SECONDS(g.expires_in, 1, 3600) || !SECONDS(interval, 1, 300)) {
|
|
180
|
+
throw bad("authorization endpoint answered a code this CLI does not take");
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// The metadata's verification_uri first, when it names one, as the open-source connector's client does.
|
|
184
|
+
const open = m.verification_uri ?? g.verification_uri;
|
|
185
|
+
io.stderr.write(`Open ${open} and enter the code ${g.user_code}${g.verification_uri_complete ? ` (or open ${g.verification_uri_complete})` : ""}.\n`);
|
|
186
|
+
io.stderr.write(`Waiting for the sign-in to be approved there; the code expires in ${Math.ceil(g.expires_in / 60)} min.\n`);
|
|
187
|
+
|
|
188
|
+
const deadline = started + g.expires_in * 1000;
|
|
189
|
+
const expired = () => refuse(4, `The code expired before the sign-in was approved; ${NOTHING}. Run agentrun login --to again.`);
|
|
190
|
+
let every = interval * 1000;
|
|
191
|
+
let delay = every;
|
|
192
|
+
for (;;) {
|
|
193
|
+
if (Date.now() >= deadline) throw expired();
|
|
194
|
+
await sleep(Math.min(delay, deadline - Date.now()));
|
|
195
|
+
if (Date.now() >= deadline) throw expired();
|
|
196
|
+
let answer;
|
|
197
|
+
try {
|
|
198
|
+
answer = await ask(tokenAt, { form: { grant_type: GRANT_TYPE, device_code: g.device_code, client_id: m.client_id, audience: m.resource }, ms: Math.max(1, Math.min(REQUEST_MS, deadline - Date.now())) });
|
|
199
|
+
} catch {
|
|
200
|
+
// Not reached this time (a dropped connection, a timeout): wait longer, until the code expires.
|
|
201
|
+
delay = Math.max(every, Math.min(BACKOFF_MS, delay * 2));
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
if (answer.redirect) throw bad(`token endpoint answered with a redirect (${answer.status}), which this CLI never follows`);
|
|
205
|
+
const code = errorOf(answer.body);
|
|
206
|
+
if (answer.status === 200) {
|
|
207
|
+
const t = answer.body;
|
|
208
|
+
if (!t || t.error !== undefined || typeof t.access_token !== "string" || !SECRET.test(t.access_token) || typeof t.token_type !== "string" || t.token_type.toLowerCase() !== "bearer" || (t.expires_in !== undefined && !SECONDS(t.expires_in, 1, Number.MAX_SAFE_INTEGER))) {
|
|
209
|
+
throw bad("token endpoint answered a token this CLI does not take (a bearer access_token of printable characters)");
|
|
210
|
+
}
|
|
211
|
+
return t.access_token;
|
|
212
|
+
}
|
|
213
|
+
if (answer.status === 400 && code === "authorization_pending") {
|
|
214
|
+
delay = every;
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
if (answer.status === 400 && code === "slow_down") {
|
|
218
|
+
every += SLOW_DOWN_MS;
|
|
219
|
+
delay = every;
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
if (answer.status === 429 || answer.status >= 500) {
|
|
223
|
+
delay = Math.max(every, Math.min(BACKOFF_MS, delay * 2), answer.retryAfter);
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
if (code === "access_denied") throw refuse(4, `The sign-in was denied; ${NOTHING}.`);
|
|
227
|
+
if (code === "expired_token") throw expired();
|
|
228
|
+
throw refuse(1, `The server refused the sign-in: ${answer.status}${code ? ` ${code}` : ""}; ${NOTHING}.`);
|
|
229
|
+
}
|
|
230
|
+
}
|
package/lib/export.mjs
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// `agentrun export AGENT --out DIR`: the agent's current revision written as a template package folder (GET
|
|
2
|
+
// /agents/{agent_id}/package), which `agentrun template validate` reads and any AgentRun applies. The server's report is
|
|
3
|
+
// printed whole: what kept the package from working elsewhere (`blocked`) and what the target sets up again (`remade`).
|
|
4
|
+
// With anything blocked, or an agent the server does not export, nothing is written and the exit is 2.
|
|
5
|
+
import { mkdirSync, readdirSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
|
|
7
|
+
|
|
8
|
+
/** Exits: 0 written; 2 refused (blocked, an agent the server does not export, an unknown one, a folder that holds files). */
|
|
9
|
+
const REFUSED = 2;
|
|
10
|
+
|
|
11
|
+
export const EXPORT = {
|
|
12
|
+
command: ["export"],
|
|
13
|
+
pathParams: ["agent"],
|
|
14
|
+
summary: "Write an agent's current revision as a template package folder, and say what the target sets up again",
|
|
15
|
+
help: [
|
|
16
|
+
["AGENT", "the agent's id"],
|
|
17
|
+
["--out DIR", "the folder to write: a new one, or an empty one"],
|
|
18
|
+
],
|
|
19
|
+
options: { out: { type: "string" } },
|
|
20
|
+
async run({ values, args, env, io, cli }) {
|
|
21
|
+
if (!values.out) throw cli.fail(REFUSED, "--out DIR is the folder the package is written to.");
|
|
22
|
+
const out = resolve(values.out);
|
|
23
|
+
if (holdsFiles(out)) throw cli.fail(REFUSED, `${out} is not empty: export into a new folder, or an empty one.`);
|
|
24
|
+
const client = cli.clientOf(cli.targetOf(values, env), io);
|
|
25
|
+
const refused = client.refused;
|
|
26
|
+
// The server's error goes to stderr as any command's does; an agent it does not export, or does not have, is a refusal.
|
|
27
|
+
client.refused = (response, bytes) => {
|
|
28
|
+
const code = refused(response, bytes);
|
|
29
|
+
return [404, 409, 422].includes(response.status) ? REFUSED : code;
|
|
30
|
+
};
|
|
31
|
+
const { response, bytes, code } = await cli.request(client, { method: "GET", path: `/agents/${encodeURIComponent(args[0])}/package` });
|
|
32
|
+
if (code !== undefined) {
|
|
33
|
+
io.stderr.write("Nothing was written.\n");
|
|
34
|
+
return code;
|
|
35
|
+
}
|
|
36
|
+
let answer;
|
|
37
|
+
try {
|
|
38
|
+
answer = JSON.parse(bytes.toString("utf8"));
|
|
39
|
+
} catch {
|
|
40
|
+
throw cli.fail(1, `The server's answer (${response.status}) is not JSON.`);
|
|
41
|
+
}
|
|
42
|
+
const { name, sha256, files = [], report = {} } = answer;
|
|
43
|
+
const blocked = report.blocked ?? [];
|
|
44
|
+
const remade = report.remade ?? [];
|
|
45
|
+
for (const [label, list] of [["Blocked", blocked], ["Set up again on the target", remade]]) {
|
|
46
|
+
if (list.length) io.stderr.write(`${label}:\n${list.map((note) => ` ${note.kind} ${note.name}: ${note.reason}`).join("\n")}\n`);
|
|
47
|
+
}
|
|
48
|
+
if (blocked.length) {
|
|
49
|
+
client.print({ name, sha256, blocked, remade, folder: null });
|
|
50
|
+
io.stderr.write("Nothing was written: the package would not work elsewhere until what is blocked is fixed on this agent.\n");
|
|
51
|
+
return REFUSED;
|
|
52
|
+
}
|
|
53
|
+
// Every path checked before the first write: one that leaves the folder writes nothing.
|
|
54
|
+
const written = files.map((file) => {
|
|
55
|
+
const at = resolve(out, file.path);
|
|
56
|
+
const inside = relative(out, at);
|
|
57
|
+
if (isAbsolute(file.path) || !inside || inside.startsWith(`..${sep}`) || inside === "..") throw cli.fail(1, `The server's answer names a file outside the folder (${JSON.stringify(file.path)}): nothing was written.`);
|
|
58
|
+
return { at, bytes: Buffer.from(file.content, file.encoding === "base64" ? "base64" : "utf8") };
|
|
59
|
+
});
|
|
60
|
+
for (const file of written) {
|
|
61
|
+
mkdirSync(dirname(file.at), { recursive: true });
|
|
62
|
+
writeFileSync(file.at, file.bytes, { flag: "wx" });
|
|
63
|
+
}
|
|
64
|
+
if (!written.length) mkdirSync(out, { recursive: true });
|
|
65
|
+
client.print({ name, sha256, blocked, remade, folder: out });
|
|
66
|
+
if (io.stdout.isTTY) io.stderr.write(`Check it: agentrun template validate ${relative(process.cwd(), out) || "."}\n`);
|
|
67
|
+
return 0;
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/** Whether `dir` exists and holds anything (a file in the way is refused the same). */
|
|
72
|
+
function holdsFiles(dir) {
|
|
73
|
+
try {
|
|
74
|
+
return readdirSync(dir).length > 0;
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (error.code === "ENOENT") return false;
|
|
77
|
+
if (error.code === "ENOTDIR") return true;
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
}
|
package/lib/harness.mjs
CHANGED
|
@@ -55,6 +55,25 @@ export const HARNESS_INSTALL = {
|
|
|
55
55
|
},
|
|
56
56
|
};
|
|
57
57
|
|
|
58
|
+
export const HARNESS_SIGN_IN = {
|
|
59
|
+
command: ["harness", "sign-in"],
|
|
60
|
+
pathParams: [],
|
|
61
|
+
summary: "Sign a recipe's agent in to your own account with the agent's own sign-in, in this terminal (Antigravity's agy acp --login); a server you start with --harness-sign-in on your own machine then runs your own runs on it",
|
|
62
|
+
help: [
|
|
63
|
+
["--recipe FILE", "the recipe file, whose signIn names the agent's own sign-in flags; its agent installed first with agentrun harness install --recipe FILE"],
|
|
64
|
+
["--data DIR", "the data directory the recipe's agent was installed into (default ~/.agentrun)"],
|
|
65
|
+
],
|
|
66
|
+
options: { recipe: { type: "string" } },
|
|
67
|
+
async run({ values, env, cli }) {
|
|
68
|
+
if (values.recipe === undefined) throw cli.fail(2, "agentrun harness sign-in needs --recipe FILE.");
|
|
69
|
+
const launcher = await launcherOf(cli, "signs a harness in");
|
|
70
|
+
// The agent prints where to sign in on this terminal itself, and keeps its sign-in in its own folder: no key is
|
|
71
|
+
// needed, so none reaches it.
|
|
72
|
+
const keyless = Object.fromEntries(Object.entries(env).filter(([key]) => !KEY_NAMED.test(key)));
|
|
73
|
+
return spawnSync(launcher, ["sign-in-harness", "--recipe", resolve(values.recipe), "--data", dataOf(values, env)], { stdio: "inherit", env: keyless }).status ?? 1;
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
|
|
58
77
|
export const HARNESS_CHECK = {
|
|
59
78
|
command: ["harness-check"],
|
|
60
79
|
pathParams: [],
|
package/lib/login.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
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
|
|
2
|
+
// and kept in the config file, or one a device sign-in ends with: device.mjs) and `logout`. No command writes a key or any other secret to the server: those are set in
|
|
3
3
|
// the console, signed in, and the server refuses the token on them (secret-writes.ts). A secret is never in argv, so
|
|
4
4
|
// never in shell history or `ps`, and never in any output or error. Each command is `{ command, pathParams, summary,
|
|
5
5
|
// route?, help, options, run }`; cli.mjs runs it with `{ values, args, env, io, cli }`, where `cli` is its own
|
|
@@ -8,6 +8,8 @@ import { randomBytes } from "node:crypto";
|
|
|
8
8
|
import { chmodSync, closeSync, constants, existsSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync, writeSync } from "node:fs";
|
|
9
9
|
import { homedir } from "node:os";
|
|
10
10
|
import { dirname, join } from "node:path";
|
|
11
|
+
import { SignInError, capabilitiesOf, deviceOffer, deviceSignIn } from "./device.mjs";
|
|
12
|
+
import { CLOUD_URL, toUrl } from "./target.mjs";
|
|
11
13
|
|
|
12
14
|
/** The config file `login` writes and every command reads (cli.mjs's targetOf, which refuses it unless it is a private
|
|
13
15
|
* file of this user's): $XDG_CONFIG_HOME/agentrun/config.json, else
|
|
@@ -122,21 +124,73 @@ function syncFolder(dir) {
|
|
|
122
124
|
|
|
123
125
|
const print = (io, value) => io.stdout.write(`${io.stdout.isTTY ? JSON.stringify(value, null, 2) : JSON.stringify(value)}\n`);
|
|
124
126
|
|
|
127
|
+
/** `{ base_url, api_key }` in the config file, then its path printed: what every login ends with, whichever way the token
|
|
128
|
+
* came. */
|
|
129
|
+
function keep(base, token, env, io, cli) {
|
|
130
|
+
const file = configFileOf(env);
|
|
131
|
+
// Written whole beside it under a name no one could have planted (random, opened only if it is new, through no
|
|
132
|
+
// link), then moved over it: a reader never sees half a file, and it is never wider than 0600. Any failure is said
|
|
133
|
+
// plainly, its code alone, and leaves nothing behind.
|
|
134
|
+
const temp = join(dirname(file), `.config.json.${randomBytes(8).toString("hex")}.tmp`);
|
|
135
|
+
let made = false;
|
|
136
|
+
try {
|
|
137
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
138
|
+
chmodSync(dirname(file), 0o700);
|
|
139
|
+
const fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
140
|
+
made = true;
|
|
141
|
+
try {
|
|
142
|
+
// Every byte, however few one write takes (a full disk, a quota), and on the disk before it takes the old one's
|
|
143
|
+
// place: the rename never puts half a config where a whole one was.
|
|
144
|
+
const bytes = Buffer.from(`${JSON.stringify({ base_url: base, api_key: token }, null, 2)}\n`);
|
|
145
|
+
for (let at = 0; at < bytes.length; ) {
|
|
146
|
+
const wrote = writeSync(fd, bytes, at, bytes.length - at);
|
|
147
|
+
if (!(wrote > 0)) throw Object.assign(new Error("a write wrote nothing"), { code: "EIO" });
|
|
148
|
+
at += wrote;
|
|
149
|
+
}
|
|
150
|
+
fsyncSync(fd);
|
|
151
|
+
} finally {
|
|
152
|
+
closeSync(fd);
|
|
153
|
+
}
|
|
154
|
+
renameSync(temp, file);
|
|
155
|
+
made = false;
|
|
156
|
+
syncFolder(dirname(file));
|
|
157
|
+
} catch (error) {
|
|
158
|
+
throw cli.fail(4, `Cannot write the config file ${file} (${/^E[A-Z]+$/.test(error?.code ?? "") ? error.code : "an error"}); nothing was written.`);
|
|
159
|
+
} finally {
|
|
160
|
+
if (made) rmSync(temp, { force: true });
|
|
161
|
+
}
|
|
162
|
+
print(io, { base_url: base, config_file: file });
|
|
163
|
+
return 0;
|
|
164
|
+
}
|
|
165
|
+
|
|
125
166
|
export const LOGIN = {
|
|
126
167
|
command: ["login"],
|
|
127
168
|
pathParams: [],
|
|
128
|
-
summary: "
|
|
129
|
-
route: "GET /agents?limit=1, to check
|
|
169
|
+
summary: "Sign in to a server, with a device code when it offers one, else a token read from stdin, and keep the token with the server's address in the config file",
|
|
170
|
+
route: "GET /capabilities, then its device sign-in; else GET /agents?limit=1, to check a token from stdin",
|
|
130
171
|
help: [
|
|
131
|
-
["--
|
|
172
|
+
["--to URL|cloud", `the server, /v2 added when its address lacks it; cloud is AgentRun cloud (AGENTRUN_CLOUD_URL, else ${CLOUD_URL}). When its capabilities offer a device sign-in, prints an address and a code to approve there, else reads the token from stdin`],
|
|
173
|
+
["--base-url URL", "the server's API, ending /v2 (default AGENTRUN_BASE_URL); the token from stdin"],
|
|
132
174
|
["(stdin)", "the token: agentrun login --base-url URL < FILE"],
|
|
133
175
|
],
|
|
134
|
-
options: {},
|
|
176
|
+
options: { to: { type: "string" } },
|
|
135
177
|
async run({ values, env, io, cli }) {
|
|
178
|
+
if (values.to !== undefined && values["base-url"] !== undefined) throw cli.fail(2, "agentrun login takes the server once: --to or --base-url, not both.");
|
|
136
179
|
const flagged = values["base-url"] !== undefined;
|
|
137
|
-
const given = flagged ? values["base-url"] : env.AGENTRUN_BASE_URL;
|
|
138
|
-
if (given === undefined) throw cli.fail(2, "agentrun login needs the server: --base-url URL (its API, ending /v2) or AGENTRUN_BASE_URL.");
|
|
139
|
-
const base = cli.baseOf(given, flagged ? "--base-url" : "AGENTRUN_BASE_URL");
|
|
180
|
+
const given = values.to !== undefined ? toUrl(values.to, env) : flagged ? values["base-url"] : env.AGENTRUN_BASE_URL;
|
|
181
|
+
if (given === undefined) throw cli.fail(2, "agentrun login needs the server: --to URL, --base-url URL (its API, ending /v2) or AGENTRUN_BASE_URL.");
|
|
182
|
+
const base = cli.baseOf(given, values.to !== undefined ? "--to" : flagged ? "--base-url" : "AGENTRUN_BASE_URL");
|
|
183
|
+
if (values.to !== undefined) {
|
|
184
|
+
// The device sign-in, when the server offers one; a SignInError's words are this CLI's own and say nothing was
|
|
185
|
+
// written. The token it ends with is the server's own answer from its own origin, so it is kept as it is.
|
|
186
|
+
try {
|
|
187
|
+
const offer = deviceOffer(await capabilitiesOf(base), base);
|
|
188
|
+
if (offer) return keep(base, await deviceSignIn(base, offer, io), env, io, cli);
|
|
189
|
+
} catch (error) {
|
|
190
|
+
if (error instanceof SignInError) throw cli.fail(error.code, error.message);
|
|
191
|
+
throw error;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
140
194
|
const token = (await readSecret(io, cli.fail, "The token", "agentrun login --base-url URL < FILE")).trim();
|
|
141
195
|
if (!token) throw cli.fail(2, "stdin holds no token: one line, the token alone.");
|
|
142
196
|
// Refused before it is sent, as every command refuses one: fetch would quote a bad header value in its error.
|
|
@@ -158,40 +212,7 @@ export const LOGIN = {
|
|
|
158
212
|
client.io.stderr.write(`The server at ${base} answered the check with ${checked.response.status}, not an agents list; nothing was written.\n`);
|
|
159
213
|
return 1;
|
|
160
214
|
}
|
|
161
|
-
|
|
162
|
-
// Written whole beside it under a name no one could have planted (random, opened only if it is new, through no
|
|
163
|
-
// link), then moved over it: a reader never sees half a file, and it is never wider than 0600. Any failure is said
|
|
164
|
-
// plainly, its code alone, and leaves nothing behind.
|
|
165
|
-
const temp = join(dirname(file), `.config.json.${randomBytes(8).toString("hex")}.tmp`);
|
|
166
|
-
let made = false;
|
|
167
|
-
try {
|
|
168
|
-
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
169
|
-
chmodSync(dirname(file), 0o700);
|
|
170
|
-
const fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
171
|
-
made = true;
|
|
172
|
-
try {
|
|
173
|
-
// Every byte, however few one write takes (a full disk, a quota), and on the disk before it takes the old one's
|
|
174
|
-
// place: the rename never puts half a config where a whole one was.
|
|
175
|
-
const bytes = Buffer.from(`${JSON.stringify({ base_url: base, api_key: token }, null, 2)}\n`);
|
|
176
|
-
for (let at = 0; at < bytes.length; ) {
|
|
177
|
-
const wrote = writeSync(fd, bytes, at, bytes.length - at);
|
|
178
|
-
if (!(wrote > 0)) throw Object.assign(new Error("a write wrote nothing"), { code: "EIO" });
|
|
179
|
-
at += wrote;
|
|
180
|
-
}
|
|
181
|
-
fsyncSync(fd);
|
|
182
|
-
} finally {
|
|
183
|
-
closeSync(fd);
|
|
184
|
-
}
|
|
185
|
-
renameSync(temp, file);
|
|
186
|
-
made = false;
|
|
187
|
-
syncFolder(dirname(file));
|
|
188
|
-
} catch (error) {
|
|
189
|
-
throw cli.fail(4, `Cannot write the config file ${file} (${/^E[A-Z]+$/.test(error?.code ?? "") ? error.code : "an error"}); nothing was written.`);
|
|
190
|
-
} finally {
|
|
191
|
-
if (made) rmSync(temp, { force: true });
|
|
192
|
-
}
|
|
193
|
-
print(io, { base_url: base, config_file: file });
|
|
194
|
-
return 0;
|
|
215
|
+
return keep(base, token, env, io, cli);
|
|
195
216
|
},
|
|
196
217
|
};
|
|
197
218
|
|
package/lib/start.mjs
CHANGED
|
@@ -265,7 +265,7 @@ const inCi = (env) => Boolean(env.CI) && env.CI !== "false" && env.CI !== "0";
|
|
|
265
265
|
|
|
266
266
|
/** The server's own commands (its CLI's first word), which this command runs on its store: every other first word is
|
|
267
267
|
* the CLI's, which names a command it has or says it has none. */
|
|
268
|
-
export const SERVER_COMMANDS = ["check-harness", "eval-template", "import", "install-harness", "learning", "native", "remote-bridge", "reset-password", "runner", "store-schema", "validate-template"];
|
|
268
|
+
export const SERVER_COMMANDS = ["check-harness", "eval-template", "import", "install-harness", "learning", "native", "remote-bridge", "reset-password", "runner", "sign-in-harness", "store-schema", "validate-template"];
|
|
269
269
|
|
|
270
270
|
/** How many of the server's refusals and ignored deliveries a start says, each route and reason once, before one line
|
|
271
271
|
* that says the rest are not: under this command the server's log goes nowhere else (its stdout is read here and dropped). */
|
package/lib/target.mjs
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// The AgentRun a command sends to (`--to`): an address, or `cloud`, the shortcut for AgentRun cloud. `agentrun login --to`
|
|
2
|
+
// and `agentrun deploy --to` name a target the same way.
|
|
3
|
+
|
|
4
|
+
/** AgentRun cloud's address, which `--to cloud` names unless AGENTRUN_CLOUD_URL names another. */
|
|
5
|
+
export const CLOUD_URL = "https://api.agentrun.ai";
|
|
6
|
+
|
|
7
|
+
/** The API base a `--to` names, ending /v2: `cloud` is AGENTRUN_CLOUD_URL, else CLOUD_URL; an address whose path does
|
|
8
|
+
* not end /v2 gets it appended. The caller checks the result as every base URL is checked (cli.mjs baseOf), so a query,
|
|
9
|
+
* fragment, user or password is refused there. */
|
|
10
|
+
export function toUrl(given, env) {
|
|
11
|
+
const url = (given === "cloud" ? env.AGENTRUN_CLOUD_URL || CLOUD_URL : given).replace(/\/+$/, "");
|
|
12
|
+
return /\/v2$/.test(url) ? url : `${url}/v2`;
|
|
13
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parcha/agentrun",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.21",
|
|
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.53"
|
|
21
21
|
},
|
|
22
22
|
"scripts": {
|
|
23
23
|
"test": "node --test 'test/*.test.mjs'"
|
|
@@ -131,18 +131,20 @@ Two clients call the same API from code, with the same server and token. `@parch
|
|
|
131
131
|
|
|
132
132
|
## Commands
|
|
133
133
|
|
|
134
|
-
- `agentrun agents`: archive, connect-native, create, delete-agent, delete-agent-archil, disconnect-native, discover-native, forget-sign-in, get, get-agent-archil, get-learning-loop, get-native, list, list-learning-audits, list-learning-promotions, runs, unarchive, update, verify-native
|
|
134
|
+
- `agentrun agents`: archive, bind-source-tool, connect-native, create, delete-agent, delete-agent-archil, disconnect-native, discover-native, forget-sign-in, get, get-agent-archil, get-learning-loop, get-native, get-source-sync, list, list-learning-audits, list-learning-promotions, move-source-agent, package, resolve-source-sync, review-source-project, runs, set-source-sync, unarchive, update, verify-native
|
|
135
135
|
- `agentrun capabilities`: get-capacity
|
|
136
136
|
- `agentrun cli-learning`: complete, enroll, events, get, list, revoke, start
|
|
137
|
-
- `agentrun connectors`: complete-remote-command, enroll-remote-connector, import-remote-history, import-remote-target, list-remote-connectors, poll-remote-connector, register-remote-connector, remote-command-events, revoke-remote-connector
|
|
137
|
+
- `agentrun connectors`: complete-remote-command, enroll-remote-connector, grant-source-sync, import-remote-history, import-remote-target, list-remote-connectors, poll-remote-connector, publish-source-sync, register-remote-connector, remote-command-events, revoke-remote-connector, source-sync-failure
|
|
138
|
+
- `agentrun deploy SOURCE`: Deploy an agent's package to another AgentRun: upload, plan, apply, lock (deploy rollback, deploy delete)
|
|
138
139
|
- `agentrun doctor`: Check how this AgentRun is set up (Node, the server, its service, address, password, models, switches, Docker) and print what to change; read-only (exit 0 ok or warnings, 1 a check failed, 3 no server answering)
|
|
140
|
+
- `agentrun export AGENT`: Write an agent's current revision as a template package folder, and say what the target sets up again
|
|
139
141
|
- `agentrun files`: create, delete, get, list, upload
|
|
140
|
-
- `agentrun harness`: install
|
|
142
|
+
- `agentrun harness`: install, sign-in
|
|
141
143
|
- `agentrun harness-check`: Run a recipe's installed agent for real and check it (tools off, env allowlist, pins, limits, no side requests, resume, a denied call, an MCP tool): a JSON report and three facts. Real models cost money
|
|
142
144
|
- `agentrun home`: delete, list, read, write
|
|
143
|
-
- `agentrun learning`: corrections, cost, get, log, read, replay, retire, workflow-revisions, write-corrections
|
|
144
|
-
- `agentrun local`: create-pairing, delete-composio-subscription, delete-computer, delete-workspace-archil, disconnect-git-hub, get-git-hub-connection, get-model-gateway, get-workspace-archil, list-composio-events, list-composio-triggers, list-computer-choices, list-computers, receive-hook-composio, rotate-composio-secret, test-computer, test-workspace-archil
|
|
145
|
-
- `agentrun login`:
|
|
145
|
+
- `agentrun learning`: corrections, cost, get, log, read, replay, reset, retire, workflow-revisions, write-corrections
|
|
146
|
+
- `agentrun local`: create-pairing, delete-composio-subscription, delete-computer, delete-workspace-archil, disconnect-git-hub, get-git-hub-connection, get-model-gateway, get-workspace-archil, list-composio-events, list-composio-triggers, list-computer-choices, list-computers, list-mcp-server-names, receive-hook-composio, rotate-composio-secret, test-computer, test-workspace-archil
|
|
147
|
+
- `agentrun login`: Sign in to a server, with a device code when it offers one, else a token read from stdin, and keep the token with the server's address in the config file
|
|
146
148
|
- `agentrun logout`: Remove the config file login wrote, its address and token
|
|
147
149
|
- `agentrun mcp-servers`: delete, get, list, oauth-client, private-hosts, refresh
|
|
148
150
|
- `agentrun Observations`: get-observations
|
|
@@ -156,7 +158,7 @@ Two clients call the same API from code, with the same server and token. `@parch
|
|
|
156
158
|
- `agentrun slack`: deliveries, get, redeliver, test
|
|
157
159
|
- `agentrun stats`: Counts and cost over every agent and run
|
|
158
160
|
- `agentrun stop`: Stop the AgentRun the installer started in the background, where there is no service manager (exit 0 stopped, 3 none running)
|
|
159
|
-
- `agentrun template`: apply, delete, eval, import, install, list, validate
|
|
161
|
+
- `agentrun template`: apply, delete, eval, get, import, install, list, validate
|
|
160
162
|
- `agentrun tool-keys`: list
|
|
161
163
|
- `agentrun tool-settings`: get, save
|
|
162
164
|
- `agentrun triggers`: create, delete, fire, firings, get, list, update
|