@parcha/agentrun 0.4.21 → 0.4.23

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 CHANGED
@@ -2,35 +2,30 @@
2
2
  // package is a folder (DIR, default the current one: its agent.md, skills/, rules/ and evals/ and the answer's schema,
3
3
  // nothing else of it) or an agent of this install (AGENT, read from its export, GET /agents/{id}/package). It is
4
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
5
+ // a terminal, or with --yes), and a lock written: DIR/.agentrun/deploy.json for a folder, a file of the CLI's config
6
+ // (deploy.<hash>.json, by this install's address and the agent's id) for an install's agent. The lock names the target,
7
+ // the agent and its revision, and the package's sha256: the next deploy of the same package is up to date and sends
8
+ // nothing that writes; a changed one writes the agent's next revision; one whose target was edited since the lock is
9
+ // refused unless --force. `deploy rollback` makes the agent's previous revision current; `deploy delete` deletes the
9
10
  // 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
11
  // 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
+ // printed when the target gives one), 1 the target refused otherwise or could not be reached, 4 no token for it, 5 an
13
+ // operation the target does not offer.
12
14
  import { createHash } from "node:crypto";
13
15
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, rmdirSync, statSync, writeFileSync } from "node:fs";
14
- import { createRequire } from "node:module";
15
16
  import { homedir, hostname } from "node:os";
16
17
  import { dirname, join, resolve } from "node:path";
17
18
  import { createInterface } from "node:readline/promises";
18
- import { refusalExit } from "./login.mjs";
19
19
  import { toUrl } from "./target.mjs";
20
20
 
21
21
  /** What of a folder its package is, as the target reads it (its readPackage reads nothing else): agent.md, these trees,
22
22
  * and the answer's schema file the manifest names at the folder's root. */
23
23
  const MANIFEST = "agent.md";
24
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
25
  /** What an upload takes (the server's import limits): refused here before anything is read past them. */
28
26
  const MAX_FILES = 256;
29
27
  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;
28
+ const LOCK_FIELDS = ["target", "agent_id", "revision_id", "package_sha256", "deployed_at"];
34
29
  /** A hold's folder left empty this long (tryHold): its maker ended before naming itself. */
35
30
  const HOLD_EMPTY_MS = 60_000;
36
31
 
@@ -48,39 +43,29 @@ export function packageSha256(files) {
48
43
  return hash.digest("hex");
49
44
  }
50
45
 
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) {
46
+ /** The server's manifest reader (its `manifest` export; the server is this package's one dependency), so agent.md is
47
+ * read here as the target reads it. Loaded for a folder's deploy alone. */
48
+ async function serverManifest(fail) {
55
49
  // Loaded here: start.mjs loads cli.mjs, which loads this module.
56
50
  const { SERVE_PACKAGE } = await import("./start.mjs");
57
51
  try {
58
- return createRequire(createRequire(import.meta.url).resolve(`${SERVE_PACKAGE}/package.json`))("yaml");
52
+ return (await import(`${SERVE_PACKAGE}/manifest`)).manifestOf;
59
53
  } catch {
60
54
  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
55
  }
62
56
  }
63
57
 
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;
58
+ /** The answer's schema file agent.md names (`output: {schema}`) when it is a file at the package's root other than
59
+ * agent.md. One under skills/, rules/ or evals/ goes with its tree, and the target takes no other folder. None when
60
+ * the manifest names none or does not parse: the target refuses it then, in its own words. */
61
+ function rootSchemaOf(manifest, manifestOf) {
62
+ const schema = manifestOf(manifest.toString("utf8"))?.output?.schema;
63
+ return typeof schema === "string" && /^[^/\\]+$/.test(schema) && schema !== "." && schema !== ".." && schema !== MANIFEST ? schema : undefined;
79
64
  }
80
65
 
81
66
  /** A folder's package by path, each file its bytes: agent.md, the skills/, rules/ and evals/ trees, and the answer's
82
67
  * 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
68
+ * folder), nor a hidden file or folder inside the trees. No agent.md, a symbolic link, or anything that is neither a file nor a folder refuses the deploy with
84
69
  * nothing sent. */
85
70
  async function readFolder(dir, fail) {
86
71
  const files = new Map();
@@ -96,11 +81,11 @@ async function readFolder(dir, fail) {
96
81
  const take = (rel, entry) => {
97
82
  if (entry.isSymbolicLink()) throw fail(2, `${rel} is a symbolic link: a package holds files and folders alone, so nothing was sent.`);
98
83
  if (entry.isDirectory()) {
99
- for (const one of readdirSync(join(dir, rel), { withFileTypes: true })) take(`${rel}/${one.name}`, one);
84
+ // A hidden file or folder (.env, .DS_Store) is never part of a package: the target leaves it out too.
85
+ for (const one of readdirSync(join(dir, rel), { withFileTypes: true })) if (!one.name.startsWith(".")) take(`${rel}/${one.name}`, one);
100
86
  return;
101
87
  }
102
88
  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
89
  if (files.size >= MAX_FILES) throw fail(2, `The package holds over ${MAX_FILES} files: nothing was sent.`);
105
90
  const data = readFileSync(join(dir, rel));
106
91
  bytes += data.length;
@@ -114,7 +99,7 @@ async function readFolder(dir, fail) {
114
99
  const entry = entryOf(tree);
115
100
  if (entry && !entry.isFile()) take(tree, entry);
116
101
  }
117
- const schema = rootSchemaOf(files.get(MANIFEST), await serverYaml(fail));
102
+ const schema = rootSchemaOf(files.get(MANIFEST), await serverManifest(fail));
118
103
  const entry = schema === undefined ? undefined : entryOf(schema);
119
104
  if (entry && !entry.isDirectory()) take(schema, entry);
120
105
  return files;
@@ -129,9 +114,16 @@ const filesBody = (files) => [...files].sort(([a], [b]) => (a < b ? -1 : a > b ?
129
114
  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
115
  });
131
116
 
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;
117
+ /** A lock read back from its file's text (none when there is no file): its fields as written, or a refusal naming the
118
+ * file. */
119
+ function lockOf(text, file, fail) {
120
+ if (text === undefined) return undefined;
121
+ let value;
122
+ try {
123
+ value = JSON.parse(text);
124
+ } catch {
125
+ value = null;
126
+ }
135
127
  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
128
  if (!ok) throw fail(2, `${file} is not a deploy lock (target, agent_id, revision_id, package_sha256): fix or remove it.`);
137
129
  return Object.fromEntries(LOCK_FIELDS.map((field) => [field, value[field] ?? null]));
@@ -149,8 +141,9 @@ const writeAtomic = (file, text, mode) => {
149
141
  * 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
142
  * its name alone, the folder only by whoever removed that file (rmdir keeps a folder that holds anything), and a
151
143
  * 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) {
144
+ * HOLD_EMPTY_MS old. The parent is made again if another command's cleanup removed it meanwhile. `alive` says whether
145
+ * a pid runs (cli.mjs). */
146
+ function tryHold(held, alive) {
154
147
  const host = hostname();
155
148
  const me = `${host}-${process.pid}`;
156
149
  for (let tries = 0; tries < 5; tries++) {
@@ -207,24 +200,16 @@ function tryHold(held) {
207
200
 
208
201
  /** One command at a time per source (its hold: tryHold), so two deploys of one source never both read no lock and each
209
202
  * 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);
203
+ function holdSource(held, cli) {
204
+ const { release, owner } = tryHold(held, cli.alive);
212
205
  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.`);
206
+ throw cli.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
207
  }
215
208
 
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
209
  /** A folder's lock: DIR/.agentrun/deploy.json. Either a symbolic link is refused (nothing sent): the lock would be
226
210
  * another folder's, which deploy, rollback and delete would then act on. */
227
- function folderLock(dir, fail) {
211
+ function folderLock(dir, cli) {
212
+ const fail = cli.fail;
228
213
  for (const rel of [".agentrun", ".agentrun/deploy.json"]) {
229
214
  let linked = false;
230
215
  try {
@@ -238,7 +223,7 @@ function folderLock(dir, fail) {
238
223
  return {
239
224
  file,
240
225
  hold() {
241
- const release = holdSource(`${file}.held`, fail);
226
+ const release = holdSource(`${file}.held`, cli);
242
227
  return () => {
243
228
  release();
244
229
  try {
@@ -248,123 +233,111 @@ function folderLock(dir, fail) {
248
233
  }
249
234
  };
250
235
  },
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
- },
236
+ read: () => lockOf(existsSync(file) ? readFileSync(file, "utf8") : undefined, file, fail),
261
237
  write: (lock) => writeAtomic(file, `${JSON.stringify(lock, null, 2)}\n`),
262
238
  remove: () => rmSync(file, { force: true }),
263
239
  };
264
240
  }
265
241
 
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
- };
242
+ /** The CLI's own deploy files, in its config folder (made 0700): each install agent's lock (installLock), and under
243
+ * deploy-targets/ an empty file for each address a deploy was sent to from here, named by the address's sha256 (a
244
+ * folder lock's target is trusted by it: targetFor). Each is a file of its own written whole, so two CLIs deploying at
245
+ * once never write back what the other changed. Each is read as a private file of this user's (cli.mjs privateFile). */
246
+ function cliFiles(env, cli) {
247
+ const dir = join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "agentrun");
248
+ const marker = (target) => join(dir, "deploy-targets", createHash("sha256").update(target).digest("hex"));
299
249
  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] })),
250
+ dir,
251
+ knows: (target) => cli.privateFile(marker(target)) !== undefined,
252
+ learn(target) {
253
+ mkdirSync(dirname(marker(target)), { recursive: true, mode: 0o700 });
254
+ try {
255
+ writeFileSync(marker(target), "", { flag: "wx", mode: 0o600 });
256
+ } catch (error) {
257
+ if (error.code !== "EEXIST") throw error;
258
+ }
259
+ },
305
260
  };
306
261
  }
307
262
 
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}`;
263
+ /** An install agent's lock: the CLI's own file for `<install's address> <agent id>`, deploy.<hash>.json (0600), held by
264
+ * deploy.<hash>.held beside it. */
265
+ function installLock(env, cli, source, agentId) {
266
+ const { dir } = cliFiles(env, cli);
267
+ const name = `deploy.${createHash("sha256").update(`${source} ${agentId}`).digest("hex").slice(0, 16)}`;
268
+ const file = join(dir, `${name}.json`);
312
269
  return {
313
- file: record.file,
270
+ file,
314
271
  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);
272
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
273
+ return holdSource(join(dir, `${name}.held`), cli);
317
274
  },
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),
275
+ read: () => lockOf(cli.privateFile(file), file, cli.fail),
276
+ write: (lock) => writeAtomic(file, `${JSON.stringify(lock, null, 2)}\n`, 0o600),
277
+ remove: () => rmSync(file, { force: true }),
321
278
  };
322
279
  }
323
280
 
324
281
  /** 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
282
  * 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. */
283
+ * where this CLI has deployed before (cliFiles `knows`) or it is AgentRun cloud, else `--to` must name it. */
327
284
  function targetFor({ values, env, cli }, from, lock, fail) {
328
285
  if (values.to !== undefined) return toOf(cli, values.to, env);
329
286
  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;
287
+ if (lock.target === toOf(cli, "cloud", env) || cliFiles(env, cli).knows(lock.target)) return lock.target;
331
288
  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
289
  }
333
290
 
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));
291
+ /** The exit code of a target's refusal of a deploy's own: 3 for a package not runnable there, 2 for one it refused as
292
+ * given (its input, a stale revision, a trigger name another owns). Any other is the CLI's own (clientOf's refused: 4
293
+ * for the token, 5 for an operation the target lacks). */
294
+ const exitOf = (status, code) => (status === 409 && code === "agent_not_runnable" ? 3 : status === 422 || status === 412 || (status === 409 && code === "name_taken") ? 2 : undefined);
337
295
 
338
296
  /** 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. */
297
+ * clientOf): `call(method, path, body?, allow?)` answers `{status, value}`, or prints the refusal as every command does
298
+ * (clientOf's refused) and stops with its exit code. A server not reached is exit 1 here: 3 is a package not
299
+ * runnable. `ask(method, path, body?)` is for a request the command carries on past: `{value}`, or `{why}` it got
300
+ * none (the status and the error's message, or the server not reached), nothing printed. */
341
301
  function remote(cli, values, env, io, base) {
342
302
  const target = cli.targetOf(base === undefined ? values : { ...values, "base-url": base }, env);
343
303
  const client = cli.clientOf(target, io);
344
- const call = async (method, path, body, allow = []) => {
304
+ const send = async (method, path, body) => {
345
305
  let response;
306
+ let bytes;
346
307
  try {
347
308
  response = await client.fetch(path, { method, ...(body === undefined ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }) });
309
+ // The body's read too: an answer whose connection closes after its headers is a server not reached, as one that
310
+ // never answered is.
311
+ bytes = Buffer.from(await response.arrayBuffer());
348
312
  } catch (error) {
349
313
  // 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}).`);
314
+ return { unreached: error?.cause?.code ?? error?.name };
351
315
  }
352
- const bytes = Buffer.from(await response.arrayBuffer());
353
316
  let value;
354
317
  try {
355
318
  value = bytes.length ? JSON.parse(bytes.toString("utf8")) : undefined;
356
319
  } catch {
357
320
  value = undefined;
358
321
  }
322
+ return { response, bytes, value };
323
+ };
324
+ const ask = async (method, path, body) => {
325
+ const { response, value, unreached } = await send(method, path, body);
326
+ if (unreached !== undefined) return { why: `not reached: ${unreached}` };
327
+ if (response.ok) return { value };
328
+ return { why: `${response.status}${typeof value?.error?.message === "string" ? `: ${value.error.message}` : ""}` };
329
+ };
330
+ const call = async (method, path, body, allow = []) => {
331
+ const { response, bytes, value, unreached } = await send(method, path, body);
332
+ if (unreached !== undefined) throw cli.fail(1, `Cannot reach ${target.base} (${unreached}).`);
359
333
  if (response.ok || allow.includes(response.status)) {
360
334
  if (response.ok && response.status !== 204 && value === undefined) throw cli.fail(1, `${method} ${path} on ${target.base} answered ${response.status} with no JSON.`);
361
335
  return { status: response.status, value };
362
336
  }
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));
337
+ const exit = client.refused(response, bytes);
338
+ throw new Stopped(exitOf(response.status, value?.error?.code) ?? exit);
366
339
  };
367
- return { base: target.base, call };
340
+ return { base: target.base, call, ask };
368
341
  }
369
342
 
370
343
  const enc = encodeURIComponent;
@@ -407,17 +380,17 @@ async function sourceOf({ values, args, env, io, cli, releases }, fail) {
407
380
  const dir = resolve(given);
408
381
  if (existsSync(dir) && statSync(dir).isDirectory()) {
409
382
  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);
383
+ // A lock this CLI writes teaches it the target (cliFiles), so the next deploy of the folder needs no --to.
384
+ const lock = folderLock(dir, cli);
412
385
  releases.push(lock.hold());
413
- const write = (written) => (lock.write(written), privateRecord(env, cli, fail, io).learn(written.target));
386
+ const write = (written) => (lock.write(written), cliFiles(env, cli).learn(written.target));
414
387
  return { kind: "folder", dir, lock: { ...lock, write }, files: () => readFolder(dir, fail) };
415
388
  }
416
389
  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
390
  // The install the agent is on: --base-url, else as every command finds it; never with AGENTRUN_API_KEY, which is the
418
391
  // target's token here.
419
392
  const source = remote(cli, values, { ...env, AGENTRUN_API_KEY: "" }, io, undefined);
420
- const lock = installLock(env, cli, source.base, given, fail, io);
393
+ const lock = installLock(env, cli, source.base, given);
421
394
  releases.push(lock.hold());
422
395
  return {
423
396
  kind: "agent",
@@ -443,15 +416,20 @@ async function sourceOf({ values, args, env, io, cli, releases }, fail) {
443
416
  };
444
417
  }
445
418
 
446
- /** The schedules of the install agent that still fire there: turned off with --pause-source, else warned of. */
419
+ /** The schedules of the install agent that still fire there: turned off with --pause-source, else warned of. The deploy
420
+ * is done by now, so an install that refuses its trigger routes (a front door without them) or is not reached is said
421
+ * and the command goes on: a schedule it could not read or turn off is never said to be paused. */
447
422
  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);
423
+ const pause = values["pause-source"];
424
+ const where = from.source.base;
425
+ const listed = await from.source.ask("GET", "/triggers");
426
+ if (listed.why) return say(io, `Warning: the agent's schedules on ${where} could not be read ${pause ? "or paused " : ""}(${listed.why}): any it has still run there, so each fires in both places.`);
427
+ const live = (listed.value?.triggers ?? []).filter((one) => (one.agent_id ?? one.target?.agent_id) === from.agentId && one.source?.kind === "schedule" && one.enabled);
450
428
  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.`);
429
+ if (!pause) return say(io, `Warning: the agent's schedules (${live.map((one) => one.name).join(", ")}) still run on ${where}, so each fires in both places. --pause-source turns them off there.`);
452
430
  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}.`);
431
+ const paused = await from.source.ask("PATCH", `/triggers/${enc(one.id ?? one.trigger_id)}`, { enabled: false });
432
+ say(io, paused.why ? `Warning: ${one.name} could not be paused on ${where} (${paused.why}): it still runs there, so it fires in both places.` : `Paused ${one.name} on ${where}.`);
455
433
  }
456
434
  }
457
435
 
@@ -474,18 +452,28 @@ async function deploy(ctx) {
474
452
  const base = targetFor(ctx, from, prior, fail);
475
453
  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
454
  const lock = prior && prior.target === base ? prior : undefined;
455
+ // --agent: the target's agent this deploy is for where no lock here names one there, by its id, or `new` for another.
456
+ // With a lock it may name only the lock's agent: a deploy never moves to another agent on its own.
457
+ const picked = values.agent;
458
+ if (picked !== undefined && !picked.trim()) throw fail(2, "--agent takes the id of an agent on the target, or new.");
459
+ if (picked !== undefined && lock && picked !== lock.agent_id) throw fail(2, `${from.lock.file} names the agent ${lock.agent_id} on ${base}: --agent ${picked} names another. Nothing was sent: leave --agent out to deploy onto ${lock.agent_id}, or remove the lock to deploy to another agent there.`);
477
460
  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
461
  const to = remote(cli, values, env, io, base);
479
462
 
480
463
  // The lock's agent as the target has it now: gone (deployed anew), edited since (refused unless --force), or the same
481
464
  // 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).
465
+ // can't vouch for; the apply then keeps the revision when they are the same). With no lock, the agent --agent names,
466
+ // onto its current revision.
483
467
  let onto;
484
- if (lock) {
468
+ if (!lock && picked !== undefined && picked !== "new") {
469
+ const { status, value: agent } = await to.call("GET", `/agents/${enc(picked)}`, undefined, [404, 410]);
470
+ if (status !== 200) throw fail(2, `--agent ${picked}: ${to.base} has no such agent${status === 410 ? " (it was deleted)" : ""}. Nothing was sent.`);
471
+ onto = { agent_id: picked, revision: agent.revision };
472
+ } else if (lock) {
485
473
  const { status, value: agent } = await to.call("GET", `/agents/${enc(lock.agent_id)}`, undefined, [404, 410]);
486
474
  if (status !== 200) say(io, `The agent ${lock.agent_id} is gone from ${to.base}: deploying it anew.`);
487
475
  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).`);
476
+ if (agent.revision !== lock.revision_id && !values.force) throw fail(2, `The agent ${lock.agent_id} was edited on ${to.base} since this lock was written; --force to replace it with this package (its current revision is not the one ${from.lock.file} names).`);
489
477
  if (agent.revision === lock.revision_id && lock.package_sha256 === sha && parameters === undefined) {
490
478
  say(io, `This package is up to date on ${to.base}: the agent ${lock.agent_id}, revision ${lock.revision_id}. Nothing was sent.`);
491
479
  if (from.kind === "agent") await sourceSchedules(io, from, values);
@@ -506,6 +494,13 @@ async function deploy(ctx) {
506
494
  const { value: planned } = await to.call("POST", `/templates/${enc(template.id)}/apply`, { ...body, dry_run: true });
507
495
  const plan = planned.plan;
508
496
  for (const line of planLines(to.base, template, sha, plan, grants)) say(io, line);
497
+ // An agent this package already made there with these parameters (the plan's twins), which no lock here names (it is
498
+ // gone, or this CLI never wrote it): another would run beside it, its schedules firing twice. --agent says which.
499
+ const twins = !onto && picked !== "new" && Array.isArray(plan.twins) ? plan.twins : [];
500
+ if (twins.length) {
501
+ const many = twins.length > 1;
502
+ throw fail(2, `${many ? `The agents ${twins.join(", ")} on ${to.base} were` : `The agent ${twins[0]} on ${to.base} was`} made from this package with these parameters, and no lock here names ${many ? "one" : "it"}. Nothing was applied: --agent ${many ? "ID (one of them)" : twins[0]} deploys onto it, --agent new makes another.`);
503
+ }
509
504
  if (plan.missing_secrets.length || plan.unmatched_mcp.some((need) => need.required)) {
510
505
  const setup = typeof planned.setup_url === "string" ? planned.setup_url : typeof plan.setup_url === "string" ? plan.setup_url : undefined;
511
506
  say(io, `Not runnable yet on ${to.base}: add what is marked ! there, then deploy again. Nothing was created.${setup ? ` Finish setup: ${setup}` : ""}`);
@@ -519,9 +514,11 @@ async function deploy(ctx) {
519
514
  const { value: applied } = await to.call("POST", `/templates/${enc(template.id)}/apply`, body);
520
515
  // 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
516
  // answer. The lock then names no package, so the next deploy of the same files applies again and makes it once it can.
517
+ // One the target never makes (its plan's skip code not_an_option: a webhook on an API-only install) is no reason to:
518
+ // the plan above said it is skipped, and the same files stay up to date.
522
519
  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() };
520
+ const unmade = plan.triggers.filter((one) => one.action !== "remove" && one.code !== "not_an_option" && !there.has(one.name)).map((one) => one.name);
521
+ const written = { target: to.base, agent_id: applied.agent_id, revision_id: applied.revision_id, package_sha256: unmade.length ? null : sha, deployed_at: new Date().toISOString() };
525
522
  from.lock.write(written);
526
523
  for (const warning of applied.warnings ?? []) say(io, `Warning (${warning.field}): ${warning.message}`);
527
524
  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).`);
@@ -543,8 +540,7 @@ async function locked(ctx) {
543
540
  async function rollback(ctx) {
544
541
  const { io, cli } = ctx;
545
542
  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.
543
+ // Every page: the current revision and the one before it may be on any of them.
548
544
  const revisions = [];
549
545
  for (let cursor; ; ) {
550
546
  const { value: listed } = await to.call("GET", `/agents/${enc(lock.agent_id)}/revisions${cursor ? `?cursor=${enc(cursor)}` : ""}`);
@@ -552,7 +548,7 @@ async function rollback(ctx) {
552
548
  if (typeof listed.next_cursor !== "string" || !listed.next_cursor || listed.next_cursor === cursor) break;
553
549
  cursor = listed.next_cursor;
554
550
  }
555
- const current = revisions.find((one) => one.revision === agent.revision);
551
+ const current = revisions.find((one) => one.current);
556
552
  const previous = revisions.filter((one) => current && one.version < current.version).sort((a, b) => b.version - a.version)[0];
557
553
  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
554
  await to.call("POST", `/agents/${enc(lock.agent_id)}/current`, { revision: previous.revision });
@@ -562,7 +558,7 @@ async function rollback(ctx) {
562
558
  const written = { ...lock, target: to.base, revision_id: previous.revision, package_sha256: null, deployed_at: new Date().toISOString() };
563
559
  from.lock.write(written);
564
560
  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`);
561
+ 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: current.revision })}\n`);
566
562
  return 0;
567
563
  }
568
564
 
@@ -629,6 +625,7 @@ export const DEPLOY = {
629
625
  pathParams: ["source"],
630
626
  argsOptional: true,
631
627
  summary: "Deploy an agent's package to another AgentRun: upload, plan, apply, lock (deploy rollback, deploy delete)",
628
+ route: ["POST /templates/import", "POST /templates/{template}/apply"],
632
629
  help: [
633
630
  SOURCE,
634
631
  TO,
@@ -636,10 +633,11 @@ export const DEPLOY = {
636
633
  ["--force", "replace an agent edited on the target since the last deploy"],
637
634
  ["--params FILE", "the package's parameters, a JSON object"],
638
635
  ["--pause-source", "an install agent: turn its schedules off on this install once deployed (else they fire in both places)"],
636
+ ["--agent ID|new", "with no lock for the target: deploy onto its agent ID, or make another agent (new), where it has one this package made with these parameters; with a lock, only the lock's agent"],
639
637
  ["", 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."],
638
+ ["", "Exit codes: 0 deployed or up to date, 2 refused (bad input, edited on the target, an agent there this package made that no lock names, not confirmed), 3 not runnable yet there (nothing made), 1 the target refused or was not reached."],
641
639
  ],
642
- options: { to: { type: "string" }, yes: { type: "boolean" }, force: { type: "boolean" }, params: { type: "string" }, "pause-source": { type: "boolean" } },
640
+ options: { to: { type: "string" }, yes: { type: "boolean" }, force: { type: "boolean" }, params: { type: "string" }, "pause-source": { type: "boolean" }, agent: { type: "string" } },
643
641
  run: ending(deploy),
644
642
  };
645
643
 
@@ -648,6 +646,7 @@ export const DEPLOY_ROLLBACK = {
648
646
  pathParams: ["source"],
649
647
  argsOptional: true,
650
648
  summary: "Make the deployed agent's previous revision current on its target, and the lock follow",
649
+ route: ["GET /agents/{agent_id}/revisions", "POST /agents/{agent_id}/current"],
651
650
  help: [SOURCE, ["--to URL", "the target, in place of the lock's"], ["", TOKEN]],
652
651
  options: { to: { type: "string" } },
653
652
  run: ending(rollback),
@@ -658,6 +657,7 @@ export const DEPLOY_DELETE = {
658
657
  pathParams: ["source"],
659
658
  argsOptional: true,
660
659
  summary: "Delete the deployed agent from its target (archived first), and the lock here",
660
+ route: ["POST /agents/{agent_id}/archive", "DELETE /agents/{agent_id}"],
661
661
  help: [SOURCE, ["--to URL", "the target, in place of the lock's"], ["--yes", "delete without asking (needed off a terminal)"], ["", TOKEN]],
662
662
  options: { to: { type: "string" }, yes: { type: "boolean" } },
663
663
  run: ending(remove),