@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/lib/deploy.mjs ADDED
@@ -0,0 +1,664 @@
1
+ // `agentrun deploy [AGENT|DIR] --to URL`: an agent's package sent to another AgentRun and made into its agent there. The
2
+ // package is a folder (DIR, default the current one: its agent.md, skills/, rules/ and evals/ and the answer's schema,
3
+ // nothing else of it) or an agent of this install (AGENT, read from its export, GET /agents/{id}/package). It is
4
+ // uploaded (POST /templates/import {files}), its plan read (apply with dry_run) and printed, applied once confirmed (on
5
+ // a terminal, or with --yes), and a lock written: DIR/.agentrun/deploy.json for a folder, the CLI config's deploy.json
6
+ // (by this install's address and the agent's id) for an install's agent. The lock names the target, the agent and its
7
+ // revision, and the package's sha256: the next deploy of the same package is up to date and sends nothing that writes;
8
+ // a changed one writes the agent's next revision; one whose target was edited since the lock is refused unless --force. `deploy rollback` makes the agent's previous revision current; `deploy delete` deletes the
9
+ // agent there and the lock here. Exit codes: 0 done or up to date, 2 refused (bad input, a link in the folder, edited on
10
+ // the target, not confirmed), 3 not runnable yet (keys or MCP servers the target lacks: nothing is made, the setup page
11
+ // printed when the target gives one), 1 the target refused otherwise or could not be reached, 4 no token for it.
12
+ import { createHash } from "node:crypto";
13
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, rmdirSync, statSync, writeFileSync } from "node:fs";
14
+ import { createRequire } from "node:module";
15
+ import { homedir, hostname } from "node:os";
16
+ import { dirname, join, resolve } from "node:path";
17
+ import { createInterface } from "node:readline/promises";
18
+ import { refusalExit } from "./login.mjs";
19
+ import { toUrl } from "./target.mjs";
20
+
21
+ /** What of a folder its package is, as the target reads it (its readPackage reads nothing else): agent.md, these trees,
22
+ * and the answer's schema file the manifest names at the folder's root. */
23
+ const MANIFEST = "agent.md";
24
+ const TREES = ["skills", "rules", "evals"];
25
+ /** agent.md's YAML front matter, found as the target finds it. */
26
+ const FRONT = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;
27
+ /** What an upload takes (the server's import limits): refused here before anything is read past them. */
28
+ const MAX_FILES = 256;
29
+ const MAX_BYTES = 8 * 1024 * 1024;
30
+ const LOCK_FIELDS = ["target", "workspace", "agent_id", "revision_id", "package_sha256", "deployed_at"];
31
+ /** The CLI's deploy record's lock (privateRecord): how often a change looks for it and how long it waits. */
32
+ const LOCK_POLL_MS = 25;
33
+ const LOCK_WAIT_MS = 10_000;
34
+ /** A hold's folder left empty this long (tryHold): its maker ended before naming itself. */
35
+ const HOLD_EMPTY_MS = 60_000;
36
+
37
+ /** A request's refusal already said on stderr: the command ends with `code`. */
38
+ class Stopped {
39
+ constructor(code) {
40
+ this.code = code;
41
+ }
42
+ }
43
+
44
+ /** A package's sha256: hex over its files sorted by path, each `path NUL bytes NUL` (the server's for an upload). */
45
+ export function packageSha256(files) {
46
+ const hash = createHash("sha256");
47
+ for (const path of [...files.keys()].sort()) hash.update(path).update("\0").update(files.get(path)).update("\0");
48
+ return hash.digest("hex");
49
+ }
50
+
51
+ /** The server's YAML reader: the `yaml` the server installed with this command depends on (this package's one
52
+ * dependency is the server), so agent.md's front matter is read as the server reads it. Loaded for a folder's deploy
53
+ * alone. */
54
+ async function serverYaml(fail) {
55
+ // Loaded here: start.mjs loads cli.mjs, which loads this module.
56
+ const { SERVE_PACKAGE } = await import("./start.mjs");
57
+ try {
58
+ return createRequire(createRequire(import.meta.url).resolve(`${SERVE_PACKAGE}/package.json`))("yaml");
59
+ } catch {
60
+ throw fail(2, `AgentRun's server (${SERVE_PACKAGE}) is not installed beside this command, and it is the server's reader that reads agent.md: nothing was sent.`);
61
+ }
62
+ }
63
+
64
+ /** The answer's schema file agent.md names (`output: {schema}`) when it is a file at the package's root. One under
65
+ * skills/, rules/ or evals/ goes with its tree, and the target takes no other folder. None when the manifest names
66
+ * none or does not parse: the target refuses it then, in its own words. */
67
+ function rootSchemaOf(manifest, { parseDocument }) {
68
+ const match = FRONT.exec(manifest.toString("utf8"));
69
+ if (!match) return undefined;
70
+ const doc = parseDocument(match[1], { schema: "core", merge: false, uniqueKeys: true, strict: true });
71
+ if (doc.errors.length) return undefined;
72
+ let schema;
73
+ try {
74
+ schema = doc.toJS({ maxAliasCount: 0 })?.output?.schema;
75
+ } catch {
76
+ return undefined;
77
+ }
78
+ return typeof schema === "string" && /^[^/\\]+$/.test(schema) && schema !== "." && schema !== ".." ? schema : undefined;
79
+ }
80
+
81
+ /** A folder's package by path, each file its bytes: agent.md, the skills/, rules/ and evals/ trees, and the answer's
82
+ * schema file the manifest names at the root. Nothing else of the folder is sent (a .env, a key, a README, another
83
+ * folder). No agent.md, a symbolic link, or anything that is neither a file nor a folder refuses the deploy with
84
+ * nothing sent. */
85
+ async function readFolder(dir, fail) {
86
+ const files = new Map();
87
+ let bytes = 0;
88
+ const entryOf = (rel) => {
89
+ try {
90
+ return lstatSync(join(dir, rel));
91
+ } catch (error) {
92
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return undefined;
93
+ throw error;
94
+ }
95
+ };
96
+ const take = (rel, entry) => {
97
+ if (entry.isSymbolicLink()) throw fail(2, `${rel} is a symbolic link: a package holds files and folders alone, so nothing was sent.`);
98
+ if (entry.isDirectory()) {
99
+ for (const one of readdirSync(join(dir, rel), { withFileTypes: true })) take(`${rel}/${one.name}`, one);
100
+ return;
101
+ }
102
+ if (!entry.isFile()) throw fail(2, `${rel} is neither a file nor a folder: a package holds files and folders alone, so nothing was sent.`);
103
+ if (files.has(rel)) return;
104
+ if (files.size >= MAX_FILES) throw fail(2, `The package holds over ${MAX_FILES} files: nothing was sent.`);
105
+ const data = readFileSync(join(dir, rel));
106
+ bytes += data.length;
107
+ if (bytes > MAX_BYTES) throw fail(2, `The package's files are over the ${MAX_BYTES} bytes an import keeps: nothing was sent.`);
108
+ files.set(rel, data);
109
+ };
110
+ const manifest = entryOf(MANIFEST);
111
+ if (!manifest || manifest.isDirectory()) throw fail(2, `${dir} has no agent.md: a package is a folder with agent.md (its manifest in the front matter, the agent's instructions in the body), so nothing was sent.`);
112
+ take(MANIFEST, manifest);
113
+ for (const tree of TREES) {
114
+ const entry = entryOf(tree);
115
+ if (entry && !entry.isFile()) take(tree, entry);
116
+ }
117
+ const schema = rootSchemaOf(files.get(MANIFEST), await serverYaml(fail));
118
+ const entry = schema === undefined ? undefined : entryOf(schema);
119
+ if (entry && !entry.isDirectory()) take(schema, entry);
120
+ return files;
121
+ }
122
+
123
+ /** The files as an upload sends them: text as it is, unless JSON's escapes make it longer than base64 would (a file of
124
+ * newlines or control characters), and any other bytes base64. So the body stays within the base64 size the server's
125
+ * upload limit allows for. */
126
+ const filesBody = (files) => [...files].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([path, data]) => {
127
+ const text = data.toString("utf8");
128
+ const base64 = data.toString("base64");
129
+ return Buffer.from(text, "utf8").equals(data) && Buffer.byteLength(JSON.stringify(text)) <= base64.length + 2 ? { path, encoding: "utf8", content: text } : { path, encoding: "base64", content: base64 };
130
+ });
131
+
132
+ /** A lock read back: its fields as written, or a refusal naming the file. */
133
+ function lockOf(value, file, fail) {
134
+ if (value === undefined) return undefined;
135
+ const ok = value && typeof value === "object" && ["target", "agent_id", "revision_id"].every((field) => typeof value[field] === "string") && (value.package_sha256 === null || typeof value.package_sha256 === "string");
136
+ if (!ok) throw fail(2, `${file} is not a deploy lock (target, agent_id, revision_id, package_sha256): fix or remove it.`);
137
+ return Object.fromEntries(LOCK_FIELDS.map((field) => [field, value[field] ?? null]));
138
+ }
139
+
140
+ const writeAtomic = (file, text, mode) => {
141
+ mkdirSync(dirname(file), { recursive: true, ...(mode ? { mode: 0o700 } : {}) });
142
+ const temp = `${file}.${process.pid}.tmp`;
143
+ writeFileSync(temp, text, mode ? { mode } : {});
144
+ renameSync(temp, file);
145
+ };
146
+
147
+ /** A hold on `held`: a folder made only where none is, holding one empty file named for its process (`host-pid`).
148
+ * Answers `{release}`, or `{owner}` (the process holding it; none while its maker has yet to name itself). A hold left
149
+ * by an ended process of this machine is taken, and no live one is ever touched: the ended one's file is removed by
150
+ * its name alone, the folder only by whoever removed that file (rmdir keeps a folder that holds anything), and a
151
+ * release removes only its own. A folder left empty (its maker ended before naming itself) is taken once
152
+ * HOLD_EMPTY_MS old. The parent is made again if another command's cleanup removed it meanwhile. */
153
+ function tryHold(held) {
154
+ const host = hostname();
155
+ const me = `${host}-${process.pid}`;
156
+ for (let tries = 0; tries < 5; tries++) {
157
+ try {
158
+ mkdirSync(dirname(held), { recursive: true });
159
+ mkdirSync(held);
160
+ writeFileSync(join(held, me), "", { flag: "wx" });
161
+ return {
162
+ release() {
163
+ rmSync(join(held, me), { force: true });
164
+ try {
165
+ rmdirSync(held);
166
+ } catch {
167
+ // not ours to remove
168
+ }
169
+ },
170
+ };
171
+ } catch (error) {
172
+ if (error.code !== "EEXIST" && error.code !== "ENOENT") throw error;
173
+ }
174
+ let names;
175
+ let age;
176
+ try {
177
+ names = readdirSync(held);
178
+ age = Date.now() - statSync(held).mtimeMs;
179
+ } catch {
180
+ continue; // let go of meanwhile
181
+ }
182
+ if (!names.length) {
183
+ if (age < HOLD_EMPTY_MS) return { owner: undefined };
184
+ try {
185
+ rmdirSync(held);
186
+ } catch {
187
+ // named meanwhile
188
+ }
189
+ continue;
190
+ }
191
+ const at = names[0].lastIndexOf("-");
192
+ const owner = { host: names[0].slice(0, at), pid: Number(names[0].slice(at + 1)) };
193
+ if (owner.host !== host || !(owner.pid > 0) || alive(owner.pid)) return { owner };
194
+ try {
195
+ rmSync(join(held, names[0]));
196
+ } catch {
197
+ continue; // another took it first
198
+ }
199
+ try {
200
+ rmdirSync(held);
201
+ } catch {
202
+ // named meanwhile
203
+ }
204
+ }
205
+ return { owner: undefined };
206
+ }
207
+
208
+ /** One command at a time per source (its hold: tryHold), so two deploys of one source never both read no lock and each
209
+ * make an agent. Another process's refuses the command (exit 2) with nothing sent. Answers its letting go. */
210
+ function holdSource(held, fail) {
211
+ const { release, owner } = tryHold(held);
212
+ if (release) return release;
213
+ throw fail(2, `Another agentrun deploy of this source is running${owner ? ` (process ${owner.pid}${owner.host === hostname() ? "" : ` on ${owner.host}`})` : ""}: try again once it ends, or remove ${held} if none is. Nothing was sent.`);
214
+ }
215
+
216
+ const alive = (pid) => {
217
+ try {
218
+ process.kill(pid, 0);
219
+ return true;
220
+ } catch (error) {
221
+ return error.code === "EPERM";
222
+ }
223
+ };
224
+
225
+ /** A folder's lock: DIR/.agentrun/deploy.json. Either a symbolic link is refused (nothing sent): the lock would be
226
+ * another folder's, which deploy, rollback and delete would then act on. */
227
+ function folderLock(dir, fail) {
228
+ for (const rel of [".agentrun", ".agentrun/deploy.json"]) {
229
+ let linked = false;
230
+ try {
231
+ linked = lstatSync(join(dir, rel)).isSymbolicLink();
232
+ } catch {
233
+ // not there
234
+ }
235
+ if (linked) throw fail(2, `${rel} is a symbolic link: a folder's deploy lock is its own file, so nothing was sent.`);
236
+ }
237
+ const file = join(dir, ".agentrun", "deploy.json");
238
+ return {
239
+ file,
240
+ hold() {
241
+ const release = holdSource(`${file}.held`, fail);
242
+ return () => {
243
+ release();
244
+ try {
245
+ rmdirSync(dirname(file));
246
+ } catch {
247
+ // it holds the lock, or something else of its owner's: kept
248
+ }
249
+ };
250
+ },
251
+ read() {
252
+ if (!existsSync(file)) return undefined;
253
+ let value;
254
+ try {
255
+ value = JSON.parse(readFileSync(file, "utf8"));
256
+ } catch {
257
+ value = null;
258
+ }
259
+ return lockOf(value, file, fail);
260
+ },
261
+ write: (lock) => writeAtomic(file, `${JSON.stringify(lock, null, 2)}\n`),
262
+ remove: () => rmSync(file, { force: true }),
263
+ };
264
+ }
265
+
266
+ /** The CLI's own deploy record, its config's deploy.json (0600): an install agent's lock per `<install's address> <agent
267
+ * id>`, and under `targets` each address a deploy was sent to from here (a folder lock's target is trusted by it). A
268
+ * change that waits for another's says so on `io`. */
269
+ function privateRecord(env, cli, fail, io) {
270
+ const file = join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "agentrun", "deploy.json");
271
+ const all = () => {
272
+ const text = cli.privateFile(file);
273
+ if (text === undefined) return {};
274
+ try {
275
+ const value = JSON.parse(text);
276
+ if (value && typeof value === "object" && !Array.isArray(value) && (value.targets === undefined || (Array.isArray(value.targets) && value.targets.every((one) => typeof one === "string")))) return value;
277
+ } catch {
278
+ // refused below
279
+ }
280
+ throw fail(2, `${file} is not the CLI's deploy record (an object of locks by install and agent, and its targets): fix or remove it.`);
281
+ };
282
+ // Each change is read and written holding `<file>.lock` (tryHold), so two CLIs deploying at the same time never write
283
+ // back a record the other has changed since. A change waits for another's.
284
+ const update = (change) => {
285
+ const held = `${file}.lock`;
286
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
287
+ let got;
288
+ for (let waited = 0; !(got = tryHold(held)).release; waited += LOCK_POLL_MS) {
289
+ if (waited >= LOCK_WAIT_MS) throw fail(1, `Another deploy holds ${file} (${held}${got.owner ? `, process ${got.owner.pid} on ${got.owner.host}` : ""}): try again once it ends, or remove ${held} if none is running.`);
290
+ if (waited === 0 && io) say(io, `Waiting for another agentrun deploy${got.owner ? ` (process ${got.owner.pid}${got.owner.host === hostname() ? "" : ` on ${got.owner.host}`})` : ""} to save ${file}.`);
291
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, LOCK_POLL_MS);
292
+ }
293
+ try {
294
+ writeAtomic(file, `${JSON.stringify(change(all()), null, 2)}\n`, 0o600);
295
+ } finally {
296
+ got.release();
297
+ }
298
+ };
299
+ return {
300
+ file,
301
+ all,
302
+ update,
303
+ knows: (target) => (all().targets ?? []).includes(target),
304
+ learn: (target) => update((record) => ((record.targets ?? []).includes(target) ? record : { ...record, targets: [...(record.targets ?? []), target] })),
305
+ };
306
+ }
307
+
308
+ /** An install agent's lock, in the CLI's own record (privateRecord). */
309
+ function installLock(env, cli, source, agentId, fail, io) {
310
+ const record = privateRecord(env, cli, fail, io);
311
+ const key = `${source} ${agentId}`;
312
+ return {
313
+ file: record.file,
314
+ hold() {
315
+ mkdirSync(dirname(record.file), { recursive: true, mode: 0o700 });
316
+ return holdSource(join(dirname(record.file), `deploy.${createHash("sha256").update(key).digest("hex").slice(0, 16)}.held`), fail);
317
+ },
318
+ read: () => lockOf(record.all()[key], record.file, fail),
319
+ write: (lock) => record.update((all) => ({ ...all, [key]: lock })),
320
+ remove: () => record.update(({ [key]: _, ...rest }) => rest),
321
+ };
322
+ }
323
+
324
+ /** Where a deploy may send this CLI's key: an address `--to` names, else the lock's target. An install agent's lock is
325
+ * the CLI's own; a folder's comes with the folder, so one from elsewhere can name any address: its target is used only
326
+ * where this CLI has deployed before (privateRecord `targets`) or it is AgentRun cloud, else `--to` must name it. */
327
+ function targetFor({ values, env, cli }, from, lock, fail) {
328
+ if (values.to !== undefined) return toOf(cli, values.to, env);
329
+ if (lock === undefined || from.kind !== "folder") return lock?.target;
330
+ if (lock.target === toOf(cli, "cloud", env) || privateRecord(env, cli, fail).knows(lock.target)) return lock.target;
331
+ throw fail(2, `${from.lock.file} names ${lock.target} as its target, an address this CLI has not deployed to: pass --to ${lock.target} to deploy there. Nothing was sent (a lock comes with its folder, and the deploy sends your API key to its target).`);
332
+ }
333
+
334
+ /** The exit code of a target's refusal: 3 for a package not runnable there, 2 for one it refused as given (its input,
335
+ * a stale revision, a trigger name another owns), else the CLI's own (4 for the token, 5 for an operation it lacks). */
336
+ const exitOf = (status, code) => (status === 409 && code === "agent_not_runnable" ? 3 : status === 422 || status === 412 || (status === 409 && code === "name_taken") ? 2 : refusalExit(status));
337
+
338
+ /** Requests to one AgentRun (`base`, else the one every command finds), with its token (the CLI's custody: targetOf,
339
+ * clientOf): `call(method, path, body?, allow?)` answers `{status, value}`, or prints the refusal and stops with its
340
+ * exit code. A server not reached is exit 1 here: 3 is a package not runnable. */
341
+ function remote(cli, values, env, io, base) {
342
+ const target = cli.targetOf(base === undefined ? values : { ...values, "base-url": base }, env);
343
+ const client = cli.clientOf(target, io);
344
+ const call = async (method, path, body, allow = []) => {
345
+ let response;
346
+ try {
347
+ response = await client.fetch(path, { method, ...(body === undefined ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }) });
348
+ } catch (error) {
349
+ // Only the cause's code: a fetch error's message can quote a header, the token's among them.
350
+ throw cli.fail(1, `Cannot reach ${target.base} (${error?.cause?.code ?? error?.name}).`);
351
+ }
352
+ const bytes = Buffer.from(await response.arrayBuffer());
353
+ let value;
354
+ try {
355
+ value = bytes.length ? JSON.parse(bytes.toString("utf8")) : undefined;
356
+ } catch {
357
+ value = undefined;
358
+ }
359
+ if (response.ok || allow.includes(response.status)) {
360
+ if (response.ok && response.status !== 204 && value === undefined) throw cli.fail(1, `${method} ${path} on ${target.base} answered ${response.status} with no JSON.`);
361
+ return { status: response.status, value };
362
+ }
363
+ io.stderr.write(bytes.length ? bytes : `${response.status} ${response.statusText}`);
364
+ if (!bytes.length || bytes.at(-1) !== 10) io.stderr.write("\n");
365
+ throw new Stopped(exitOf(response.status, value?.error?.code));
366
+ };
367
+ return { base: target.base, call };
368
+ }
369
+
370
+ const enc = encodeURIComponent;
371
+ const say = (io, line) => io.stderr.write(`${line}\n`);
372
+ /** `--to` as an API base (target.mjs toUrl), checked as every base URL is (exit 2 naming --to). */
373
+ const toOf = (cli, given, env) => cli.baseOf(toUrl(given, env), "--to");
374
+
375
+ /** Yes on a terminal, or --yes: false means the command stops (exit 2) with `asked` said. */
376
+ async function confirmed(io, values, question, offTerminal) {
377
+ if (values.yes) return true;
378
+ if (!io.stdin.isTTY) return say(io, offTerminal), false;
379
+ const rl = createInterface({ input: io.stdin, output: io.stderr });
380
+ try {
381
+ return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim());
382
+ } finally {
383
+ rl.close();
384
+ }
385
+ }
386
+
387
+ /** The plan's lines, as the deploy prints them before it applies anything. */
388
+ function planLines(base, template, sha, plan, grants) {
389
+ const rows = [];
390
+ rows.push([plan.action === "revise" ? "~" : "+", "agent", template.name, plan.action === "revise" ? `revise ${plan.agent_id}` : "new"]);
391
+ for (const name of plan.missing_secrets) rows.push(["!", "key", name, "missing: add it on the target"]);
392
+ for (const need of plan.unmatched_mcp) rows.push([need.required ? "!" : "?", "tools", `${need.toolkit} (${need.source})`, need.required ? "missing: save a server of it on the target" : "missing: the agent runs without them"]);
393
+ for (const tool of grants) rows.push(["+", "grant", tool, "allowed"]);
394
+ for (const trigger of plan.triggers) {
395
+ const mark = { create: "+", update: "~", remove: "-", skip: "!" }[trigger.action] ?? "?";
396
+ rows.push([mark, "trigger", trigger.name, `${trigger.kind}${trigger.action === "skip" ? ` skipped: ${trigger.reason ?? ""}` : trigger.reason ? ` (${trigger.reason})` : ""}`]);
397
+ }
398
+ if (plan.computer) rows.push([" ", "computer", plan.computer.kind, plan.computer.provider ?? ""]);
399
+ const width = Math.max(...rows.map(([, , name]) => name.length));
400
+ return [`Plan for ${base} (${template.id}, sha256 ${sha.slice(0, 12)}):`, ...rows.map(([mark, kind, name, what]) => ` ${mark} ${kind.padEnd(8)} ${name.padEnd(width)} ${what}`.trimEnd())];
401
+ }
402
+
403
+ /** What the command deploys: a folder's files, or an install agent's export; its lock; and, for an install agent, the
404
+ * install it came from. */
405
+ async function sourceOf({ values, args, env, io, cli, releases }, fail) {
406
+ const given = args[0] ?? ".";
407
+ const dir = resolve(given);
408
+ if (existsSync(dir) && statSync(dir).isDirectory()) {
409
+ if (values["pause-source"]) throw fail(2, "--pause-source is for an agent deployed from an install (agentrun deploy AGENT_ID): a folder has no schedules running anywhere.");
410
+ // A lock this CLI writes teaches it the target (privateRecord), so the next deploy of the folder needs no --to.
411
+ const lock = folderLock(dir, fail);
412
+ releases.push(lock.hold());
413
+ const write = (written) => (lock.write(written), privateRecord(env, cli, fail, io).learn(written.target));
414
+ return { kind: "folder", dir, lock: { ...lock, write }, files: () => readFolder(dir, fail) };
415
+ }
416
+ if (/[\\/]/.test(given) || given.startsWith(".")) throw fail(2, `${given} is not a folder: deploy takes a package folder or an agent id of this install.`);
417
+ // The install the agent is on: --base-url, else as every command finds it; never with AGENTRUN_API_KEY, which is the
418
+ // target's token here.
419
+ const source = remote(cli, values, { ...env, AGENTRUN_API_KEY: "" }, io, undefined);
420
+ const lock = installLock(env, cli, source.base, given, fail, io);
421
+ releases.push(lock.hold());
422
+ return {
423
+ kind: "agent",
424
+ agentId: given,
425
+ source,
426
+ lock,
427
+ async files() {
428
+ // No such agent here, or one this install does not export (409 not_exportable: a workflow, an agent with no
429
+ // revision, one another system owns): refused as given, as `agentrun export` refuses it.
430
+ const { status, value } = await source.call("GET", `/agents/${enc(given)}/package`, undefined, [404, 409, 422]);
431
+ if (status !== 200) throw fail(2, `${source.base} does not export ${given}: ${value?.error?.message ?? status}. Nothing was sent.`);
432
+ const blocked = Array.isArray(value?.report?.blocked) ? value.report.blocked : [];
433
+ if (blocked.length) {
434
+ for (const one of blocked) say(io, ` ! ${one.kind} ${one.name}: ${one.reason}`);
435
+ throw fail(2, `The agent ${given} can't be deployed as it is: its export blocks on what is listed above. Nothing was sent.`);
436
+ }
437
+ for (const one of Array.isArray(value?.report?.remade) ? value.report.remade : []) say(io, ` ~ ${one.kind} ${one.name}: ${one.reason}`);
438
+ if (!Array.isArray(value?.files)) throw fail(1, `The agent ${given}'s export holds no files.`);
439
+ const files = new Map(value.files.map((file) => [file.path, Buffer.from(file.content, file.encoding === "base64" ? "base64" : "utf8")]));
440
+ if (typeof value.sha256 === "string" && value.sha256 !== packageSha256(files)) throw fail(1, `The agent ${given}'s export names a sha256 its files do not have.`);
441
+ return files;
442
+ },
443
+ };
444
+ }
445
+
446
+ /** The schedules of the install agent that still fire there: turned off with --pause-source, else warned of. */
447
+ async function sourceSchedules(io, from, values) {
448
+ const { value } = await from.source.call("GET", "/triggers");
449
+ const live = (value?.triggers ?? []).filter((one) => (one.agent_id ?? one.target?.agent_id) === from.agentId && one.source?.kind === "schedule" && one.enabled);
450
+ if (!live.length) return;
451
+ if (!values["pause-source"]) return say(io, `Warning: the agent's schedules (${live.map((one) => one.name).join(", ")}) still run on ${from.source.base}, so each fires in both places. --pause-source turns them off there.`);
452
+ for (const one of live) {
453
+ await from.source.call("PATCH", `/triggers/${enc(one.id ?? one.trigger_id)}`, { enabled: false });
454
+ say(io, `Paused ${one.name} on ${from.source.base}.`);
455
+ }
456
+ }
457
+
458
+ async function deploy(ctx) {
459
+ const { values, env, io, cli } = ctx;
460
+ const fail = cli.fail;
461
+ const from = await sourceOf(ctx, fail);
462
+ const files = await from.files();
463
+ const sha = packageSha256(files);
464
+ let parameters;
465
+ if (values.params !== undefined) {
466
+ try {
467
+ parameters = JSON.parse(readFileSync(values.params, "utf8"));
468
+ } catch (error) {
469
+ throw fail(2, `--params ${values.params}: ${error.code === "ENOENT" ? "no such file" : error instanceof SyntaxError ? "not JSON" : `cannot be read (${error.code})`}.`);
470
+ }
471
+ if (!parameters || typeof parameters !== "object" || Array.isArray(parameters)) throw fail(2, `--params ${values.params} is not a JSON object of the package's parameters.`);
472
+ }
473
+ const prior = from.lock.read();
474
+ const base = targetFor(ctx, from, prior, fail);
475
+ if (base === undefined) throw fail(2, `Where to? Pass --to URL (cloud, or an AgentRun's address); a deploy after the first reads it from ${from.lock.file}.`);
476
+ const lock = prior && prior.target === base ? prior : undefined;
477
+ if (prior && !lock) say(io, `The lock names ${prior.target}; this deploy is to ${base}, so it makes the agent there and the lock names it after.`);
478
+ const to = remote(cli, values, env, io, base);
479
+
480
+ // The lock's agent as the target has it now: gone (deployed anew), edited since (refused unless --force), or the same
481
+ // revision with the same package (up to date: nothing sent that writes, unless --params asks for parameters the lock
482
+ // can't vouch for; the apply then keeps the revision when they are the same).
483
+ let onto;
484
+ if (lock) {
485
+ const { status, value: agent } = await to.call("GET", `/agents/${enc(lock.agent_id)}`, undefined, [404, 410]);
486
+ if (status !== 200) say(io, `The agent ${lock.agent_id} is gone from ${to.base}: deploying it anew.`);
487
+ else {
488
+ if (agent.revision !== lock.revision_id && !values.force) throw fail(2, `The agent ${lock.agent_id} on ${to.base} was edited in the cloud; --force to replace it with this package (its current revision is not the one ${from.lock.file} names).`);
489
+ if (agent.revision === lock.revision_id && lock.package_sha256 === sha && parameters === undefined) {
490
+ say(io, `This package is up to date on ${to.base}: the agent ${lock.agent_id}, revision ${lock.revision_id}. Nothing was sent.`);
491
+ if (from.kind === "agent") await sourceSchedules(io, from, values);
492
+ ctx.io.stdout.write(`${JSON.stringify({ status: "up_to_date", target: to.base, agent_id: lock.agent_id, revision_id: lock.revision_id, package_sha256: sha })}\n`);
493
+ return 0;
494
+ }
495
+ // Onto the revision read here: one written after this read (an edit, another deploy) makes the apply 412.
496
+ onto = { agent_id: lock.agent_id, revision: agent.revision };
497
+ }
498
+ }
499
+
500
+ const { value: imported } = await to.call("POST", "/templates/import", { files: filesBody(files) });
501
+ const template = imported.template;
502
+ const grants = (template.mcp ?? []).flatMap((need) => (need.tools ?? []).map((tool) => tool.tool)).filter((tool) => typeof tool === "string");
503
+ // The plan and the apply both name the package uploaded here (its sha): another upload of the same name in between
504
+ // makes them 412, never applies a package this deploy did not plan.
505
+ const body = { grants, sha: template.sha, ...(parameters ? { parameters } : {}), ...(onto ?? {}) };
506
+ const { value: planned } = await to.call("POST", `/templates/${enc(template.id)}/apply`, { ...body, dry_run: true });
507
+ const plan = planned.plan;
508
+ for (const line of planLines(to.base, template, sha, plan, grants)) say(io, line);
509
+ if (plan.missing_secrets.length || plan.unmatched_mcp.some((need) => need.required)) {
510
+ const setup = typeof planned.setup_url === "string" ? planned.setup_url : typeof plan.setup_url === "string" ? plan.setup_url : undefined;
511
+ say(io, `Not runnable yet on ${to.base}: add what is marked ! there, then deploy again. Nothing was created.${setup ? ` Finish setup: ${setup}` : ""}`);
512
+ io.stdout.write(`${JSON.stringify({ status: "not_runnable", target: to.base, template: template.id, plan, ...(setup ? { setup_url: setup } : {}) })}\n`);
513
+ return 3;
514
+ }
515
+ if (!(await confirmed(io, values, `Apply this plan to ${to.base}?`, "Not applied: off a terminal, deploy applies only with --yes (read the plan above first)."))) {
516
+ if (io.stdin.isTTY) say(io, "Not applied.");
517
+ return 2;
518
+ }
519
+ const { value: applied } = await to.call("POST", `/templates/${enc(template.id)}/apply`, body);
520
+ // A trigger the apply could not make yet (a connection or a feed the target lacks; a warning says which) is not in its
521
+ // answer. The lock then names no package, so the next deploy of the same files applies again and makes it once it can.
522
+ const there = new Set((applied.triggers ?? []).map((one) => one.name));
523
+ const unmade = plan.triggers.filter((one) => one.action !== "remove" && !there.has(one.name)).map((one) => one.name);
524
+ const written = { target: to.base, workspace: null, agent_id: applied.agent_id, revision_id: applied.revision_id, package_sha256: unmade.length ? null : sha, deployed_at: new Date().toISOString() };
525
+ from.lock.write(written);
526
+ for (const warning of applied.warnings ?? []) say(io, `Warning (${warning.field}): ${warning.message}`);
527
+ if (unmade.length) say(io, `Not made on ${to.base} yet: ${unmade.join(", ")}. Until they are, the lock names no package, so the next deploy applies again (keeping the revision when nothing else changed).`);
528
+ say(io, `Deployed ${template.name} to ${to.base}: the agent ${applied.agent_id}, revision ${applied.revision_version} (${applied.agent_change}). Lock: ${from.lock.file}.`);
529
+ if (from.kind === "agent") await sourceSchedules(io, from, values);
530
+ io.stdout.write(`${JSON.stringify({ status: "deployed", ...written, revision_version: applied.revision_version, agent_change: applied.agent_change, template: template.id, warnings: applied.warnings ?? [] })}\n`);
531
+ return 0;
532
+ }
533
+
534
+ /** The lock a rollback or delete acts on, and the target it names (--to wins). */
535
+ async function locked(ctx) {
536
+ const { values, env, cli } = ctx;
537
+ const from = await sourceOf(ctx, cli.fail);
538
+ const lock = from.lock.read();
539
+ if (!lock) throw cli.fail(2, `Nothing deployed here: ${from.lock.file} does not exist.`);
540
+ return { from, lock, to: remote(cli, values, env, ctx.io, targetFor(ctx, from, lock, cli.fail)) };
541
+ }
542
+
543
+ async function rollback(ctx) {
544
+ const { io, cli } = ctx;
545
+ const { from, lock, to } = await locked(ctx);
546
+ const { value: agent } = await to.call("GET", `/agents/${enc(lock.agent_id)}`);
547
+ // Every page: the previous revision may be on any of them.
548
+ const revisions = [];
549
+ for (let cursor; ; ) {
550
+ const { value: listed } = await to.call("GET", `/agents/${enc(lock.agent_id)}/revisions${cursor ? `?cursor=${enc(cursor)}` : ""}`);
551
+ revisions.push(...(listed.revisions ?? []));
552
+ if (typeof listed.next_cursor !== "string" || !listed.next_cursor || listed.next_cursor === cursor) break;
553
+ cursor = listed.next_cursor;
554
+ }
555
+ const current = revisions.find((one) => one.revision === agent.revision);
556
+ const previous = revisions.filter((one) => current && one.version < current.version).sort((a, b) => b.version - a.version)[0];
557
+ if (!previous) throw cli.fail(2, `The agent ${lock.agent_id} on ${to.base} has no revision before its current one: nothing to roll back to.`);
558
+ await to.call("POST", `/agents/${enc(lock.agent_id)}/current`, { revision: previous.revision });
559
+ // The lock follows the revision now current. Which package that revision was made from is not read anywhere (the
560
+ // agent's `template` is the newest package applied, not the restored one), so the lock names none: the next deploy is
561
+ // never up to date, and its apply keeps this revision when the package and parameters are the ones it holds.
562
+ const written = { ...lock, target: to.base, revision_id: previous.revision, package_sha256: null, deployed_at: new Date().toISOString() };
563
+ from.lock.write(written);
564
+ say(io, `Rolled back: the agent ${lock.agent_id} on ${to.base} runs revision ${previous.version} again (it was on ${current.version}).`);
565
+ io.stdout.write(`${JSON.stringify({ status: "rolled_back", target: to.base, agent_id: lock.agent_id, revision_id: previous.revision, version: previous.version, from_revision_id: agent.revision })}\n`);
566
+ return 0;
567
+ }
568
+
569
+ async function remove(ctx) {
570
+ const { io, values } = ctx;
571
+ const { from, lock, to } = await locked(ctx);
572
+ if (!(await confirmed(io, values, `Delete the agent ${lock.agent_id} from ${to.base}, its runs and its learning with it?`, `Not deleted: off a terminal, deploy delete deletes only with --yes.`))) {
573
+ if (io.stdin.isTTY) say(io, "Not deleted.");
574
+ return 2;
575
+ }
576
+ // A 404 (or 410) means gone only when the agent is not there: a server that does not serve the route (an older
577
+ // install, a front door without it) answers 404 too, while the agent is still there and running. Then nothing is
578
+ // deleted and the lock stays.
579
+ const absent = (status) => status === 404 || status === 410;
580
+ const mustBeGone = async (step, after) => {
581
+ const { status } = await to.call("GET", `/agents/${enc(lock.agent_id)}`, undefined, [404, 410]);
582
+ if (!absent(status)) throw ctx.cli.fail(2, `${to.base} did not ${step} ${lock.agent_id}; nothing was deleted${after}. The lock ${from.lock.file} is kept.`);
583
+ };
584
+ // An agent is deleted once archived (which turns its triggers off, so no run starts) and once no run of it is live:
585
+ // each one the DELETE names is cancelled, as the confirmation said, and the DELETE sent again.
586
+ const archived = await to.call("POST", `/agents/${enc(lock.agent_id)}/archive`, undefined, [404, 409, 410]);
587
+ if (absent(archived.status)) await mustBeGone("archive", "");
588
+ for (let round = 1; !absent(archived.status); round++) {
589
+ const last = round === 5;
590
+ const { status, value } = await to.call("DELETE", `/agents/${enc(lock.agent_id)}`, undefined, last ? [404, 410] : [404, 409, 410]);
591
+ if (absent(status)) await mustBeGone("delete", " (it stays archived there)");
592
+ if (status !== 409) break;
593
+ if (value?.error?.code !== "run_not_final") {
594
+ io.stderr.write(`${JSON.stringify(value)}\n`);
595
+ return 1;
596
+ }
597
+ for (const run of Array.isArray(value.error.details?.runs) ? value.error.details.runs : []) {
598
+ await to.call("POST", `/runs/${enc(run)}/cancel`, undefined, [404, 409, 410]);
599
+ say(io, `Cancelled the run ${run}.`);
600
+ }
601
+ await new Promise((done) => setTimeout(done, 200 * round));
602
+ }
603
+ from.lock.remove();
604
+ say(io, `Deleted the agent ${lock.agent_id} from ${to.base}, and the lock ${from.lock.file}.`);
605
+ io.stdout.write(`${JSON.stringify({ status: "deleted", target: to.base, agent_id: lock.agent_id })}\n`);
606
+ return 0;
607
+ }
608
+
609
+ /** Each entry's `run`, its stop (a refusal already said) its exit code. */
610
+ const ending = (work) => async (ctx) => {
611
+ // What the command holds (its source's hold: sourceOf), let go of however it ends.
612
+ const releases = [];
613
+ try {
614
+ return await work({ ...ctx, releases });
615
+ } catch (error) {
616
+ if (error instanceof Stopped) return error.code;
617
+ throw error;
618
+ } finally {
619
+ for (const release of releases) release();
620
+ }
621
+ };
622
+
623
+ const SOURCE = ["SOURCE", "a package folder (default: the current one), or an agent id of this install (its export)"];
624
+ const TO = ["--to URL", "where: cloud (the hosted AgentRun; AGENTRUN_CLOUD_URL overrides its address), or an AgentRun's address; left out after the first deploy, the lock's target (a folder's, only where this CLI deployed it, or cloud)"];
625
+ const TOKEN = "The target's token: AGENTRUN_API_KEY, else api_key in the CLI config for that address. An install agent's own install is --base-url, else as every command finds it.";
626
+
627
+ export const DEPLOY = {
628
+ command: ["deploy"],
629
+ pathParams: ["source"],
630
+ argsOptional: true,
631
+ summary: "Deploy an agent's package to another AgentRun: upload, plan, apply, lock (deploy rollback, deploy delete)",
632
+ help: [
633
+ SOURCE,
634
+ TO,
635
+ ["--yes", "apply without asking (needed off a terminal)"],
636
+ ["--force", "replace an agent edited on the target since the last deploy"],
637
+ ["--params FILE", "the package's parameters, a JSON object"],
638
+ ["--pause-source", "an install agent: turn its schedules off on this install once deployed (else they fire in both places)"],
639
+ ["", TOKEN],
640
+ ["", "Exit codes: 0 deployed or up to date, 2 refused (bad input, edited on the target, not confirmed), 3 not runnable yet there (nothing made), 1 the target refused or was not reached."],
641
+ ],
642
+ options: { to: { type: "string" }, yes: { type: "boolean" }, force: { type: "boolean" }, params: { type: "string" }, "pause-source": { type: "boolean" } },
643
+ run: ending(deploy),
644
+ };
645
+
646
+ export const DEPLOY_ROLLBACK = {
647
+ command: ["deploy", "rollback"],
648
+ pathParams: ["source"],
649
+ argsOptional: true,
650
+ summary: "Make the deployed agent's previous revision current on its target, and the lock follow",
651
+ help: [SOURCE, ["--to URL", "the target, in place of the lock's"], ["", TOKEN]],
652
+ options: { to: { type: "string" } },
653
+ run: ending(rollback),
654
+ };
655
+
656
+ export const DEPLOY_DELETE = {
657
+ command: ["deploy", "delete"],
658
+ pathParams: ["source"],
659
+ argsOptional: true,
660
+ summary: "Delete the deployed agent from its target (archived first), and the lock here",
661
+ help: [SOURCE, ["--to URL", "the target, in place of the lock's"], ["--yes", "delete without asking (needed off a terminal)"], ["", TOKEN]],
662
+ options: { to: { type: "string" }, yes: { type: "boolean" } },
663
+ run: ending(remove),
664
+ };