@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/device.mjs CHANGED
@@ -1,9 +1,14 @@
1
- // Device sign-in (RFC 8628) for `agentrun login --to`, used when the target's GET /v2/capabilities offers it:
1
+ // Device sign-in (RFC 8628) for `agentrun login`, used when the target's GET /v2/capabilities offers it:
2
2
  // `sign_in.device`, the metadata's URL and the scope to ask for. The person opens the address printed, enters the code
3
3
  // and approves there; the token endpoint then answers a token, which login keeps where it keeps a pasted one. Every URL
4
4
  // fetched is on the target's own origin, over https unless the target is on this machine; no redirect is followed; each
5
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
6
  // in an error and never in argv.
7
+ import { OWN_VERSION } from "./own.mjs";
8
+ import { CLOUD_CONSOLE, CLOUD_URL } from "./target.mjs";
9
+
10
+ /** What each request of the flow names itself: this package and its version. */
11
+ const USER_AGENT = `agentrun-cli/${OWN_VERSION}`;
7
12
 
8
13
  /** A sign-in that stopped: its exit code (cli.mjs's), and words of this CLI's own, never a server's answer. */
9
14
  export class SignInError extends Error {
@@ -31,7 +36,9 @@ const GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
31
36
 
32
37
  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
38
  const VISIBLE = /^[\x21-\x7e]{1,2048}$/;
34
- const USER_CODE = /^[\x20-\x7e]{1,256}$/;
39
+ /** A user code is printed on the line after the cross-origin one: a short token with no space, so a server can't put a
40
+ * sentence of its own beside the warning. */
41
+ const USER_CODE = /^[\x21-\x7e]{1,32}$/;
35
42
  const SECRET = /^[\x21-\x7e]{1,8192}$/;
36
43
  const SCOPE_TOKEN = "[\\x21\\x23-\\x5b\\x5d-\\x7e]+";
37
44
  const SCOPE = new RegExp(`^${SCOPE_TOKEN}(?: ${SCOPE_TOKEN})*$`);
@@ -66,13 +73,14 @@ async function capped(response, max) {
66
73
  }
67
74
 
68
75
  /** 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 } = {}) {
76
+ * JSON object (undefined when it holds none or is past `max`), retryAfter its Retry-After from `now`. A request that
77
+ * fails throws as fetch does. */
78
+ async function ask(url, { form, max = ANSWER_BYTES, ms = REQUEST_MS, now = Date.now } = {}) {
71
79
  const response = await fetch(url, {
72
80
  method: form ? "POST" : "GET",
73
81
  redirect: "manual",
74
82
  signal: AbortSignal.timeout(ms),
75
- headers: { accept: "application/json", ...(form ? { "content-type": "application/x-www-form-urlencoded" } : {}) },
83
+ headers: { accept: "application/json", "user-agent": USER_AGENT, ...(form ? { "content-type": "application/x-www-form-urlencoded" } : {}) },
76
84
  ...(form ? { body: new URLSearchParams(form).toString() } : {}),
77
85
  });
78
86
  if (response.status >= 300 && response.status < 400) return await response.body?.cancel(), { status: response.status, redirect: true };
@@ -83,7 +91,7 @@ async function ask(url, { form, max = ANSWER_BYTES, ms = REQUEST_MS } = {}) {
83
91
  } catch {
84
92
  body = undefined;
85
93
  }
86
- return { status: response.status, body: OBJECT(body) ? body : undefined, retryAfter: retryAfterMs(response.headers.get("retry-after")) };
94
+ return { status: response.status, body: OBJECT(body) ? body : undefined, retryAfter: retryAfterMs(response.headers.get("retry-after"), now()) };
87
95
  }
88
96
 
89
97
  /** 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
@@ -132,36 +140,51 @@ export function deviceOffer(capabilities, base) {
132
140
  return { metadata, scope };
133
141
  }
134
142
 
143
+ const CLOUD_PAIR = { api: new URL(CLOUD_URL).origin, page: new URL(CLOUD_CONSOLE).origin };
144
+
145
+ /** The origins of the printed `addresses` other than the target's, each once. Another origin is taken, not refused (a
146
+ * self-hosted console may live elsewhere), so the person is told it before the code. Cloud's API with its console page
147
+ * is the one pair never named, and it is exempt from this line alone. */
148
+ export function elsewhereOf(target, addresses) {
149
+ const own = new URL(target).origin;
150
+ const known = (origin) => own === CLOUD_PAIR.api && origin === CLOUD_PAIR.page;
151
+ return [...new Set(addresses.filter((at) => at != null).map((at) => new URL(at).origin))].filter((origin) => origin !== own && !known(origin));
152
+ }
153
+
135
154
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
136
155
 
137
156
  /** 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) {
157
+ * approved. Every wait is `wait(ms)`'s and every reading of the time `now()`'s (a test's fake clock). Every refusal is a
158
+ * SignInError that says nothing was written. */
159
+ export async function deviceSignIn(base, offer, io, { wait = sleep, now = Date.now } = {}) {
140
160
  const target = new URL(base);
161
+ // The server first, before anything else of the flow: a server named by a stale or wrong AGENTRUN_BASE_URL is seen
162
+ // before any code is approved.
163
+ io.stderr.write(`Signing in to ${target.origin}.\n`);
141
164
  const unreached = (url, error) => refuse(3, `Cannot reach ${url.origin} for the device sign-in (${why(error)}); ${NOTHING}.`);
142
165
 
143
166
  let meta;
144
167
  try {
145
- meta = await ask(offer.metadata);
168
+ meta = await ask(offer.metadata, { now });
146
169
  } catch (error) {
147
170
  throw unreached(offer.metadata, error);
148
171
  }
149
172
  if (meta.redirect) throw bad(`metadata answered with a redirect (${meta.status}), which this CLI never follows`);
150
173
  if (meta.status !== 200 || !meta.body) throw bad(`metadata answered ${meta.status}${meta.body ? "" : ", not a JSON object (or one too large)"}`);
174
+ // Only the fields the flow uses: the scope it asks for is the capabilities' (offer.scope), and no issuer is read.
151
175
  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)) {
176
+ if (["client_id", "device_authorization_endpoint", "token_endpoint", "resource"].some((field) => typeof m[field] !== "string" || !VISIBLE.test(m[field]))) {
153
177
  throw bad("metadata lacks a field it needs, or holds one this CLI does not take");
154
178
  }
155
- const issuer = urlOf(m.issuer, target);
156
179
  const authorization = urlOf(m.device_authorization_endpoint, target);
157
180
  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");
181
+ if (!authorization || !tokenAt) throw bad("metadata names an endpoint that is off the server's own origin or not over https");
159
182
  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
183
 
161
- const started = Date.now();
184
+ const started = now();
162
185
  let granted;
163
186
  try {
164
- granted = await ask(authorization, { form: { client_id: m.client_id, scope: offer.scope, audience: m.resource } });
187
+ granted = await ask(authorization, { form: { client_id: m.client_id, scope: offer.scope, audience: m.resource }, now });
165
188
  } catch (error) {
166
189
  throw unreached(authorization, error);
167
190
  }
@@ -182,20 +205,22 @@ export async function deviceSignIn(base, offer, io) {
182
205
 
183
206
  // The metadata's verification_uri first, when it names one, as the open-source connector's client does.
184
207
  const open = m.verification_uri ?? g.verification_uri;
208
+ const elsewhere = elsewhereOf(target, [open, g.verification_uri_complete]);
209
+ if (elsewhere.length) io.stderr.write(`The code is approved at ${elsewhere.join(" and ")}, not at ${target.origin}. Approve it only if ${target.origin} is the server you meant to sign in to.\n`);
185
210
  io.stderr.write(`Open ${open} and enter the code ${g.user_code}${g.verification_uri_complete ? ` (or open ${g.verification_uri_complete})` : ""}.\n`);
186
211
  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
212
 
188
213
  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.`);
214
+ const expired = () => refuse(4, `The code expired before the sign-in was approved; ${NOTHING}. Run agentrun login again.`);
190
215
  let every = interval * 1000;
191
216
  let delay = every;
192
217
  for (;;) {
193
- if (Date.now() >= deadline) throw expired();
194
- await sleep(Math.min(delay, deadline - Date.now()));
195
- if (Date.now() >= deadline) throw expired();
218
+ if (now() >= deadline) throw expired();
219
+ await wait(Math.min(delay, deadline - now()));
220
+ if (now() >= deadline) throw expired();
196
221
  let answer;
197
222
  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())) });
223
+ 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 - now())), now });
199
224
  } catch {
200
225
  // Not reached this time (a dropped connection, a timeout): wait longer, until the code expires.
201
226
  delay = Math.max(every, Math.min(BACKOFF_MS, delay * 2));
package/lib/doctor.mjs CHANGED
@@ -11,9 +11,9 @@ import { spawnSync } from "node:child_process";
11
11
  import { existsSync, readFileSync } from "node:fs";
12
12
  import { homedir, userInfo } from "node:os";
13
13
  import { join, resolve } from "node:path";
14
+ import { OWN_NODE, OWN_VERSION } from "./own.mjs";
14
15
  import { INSTALL_COMMAND, managerOf } from "./service.mjs";
15
16
 
16
- const OWN = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
17
17
  const REPO = "https://github.com/Parcha-ai/agentrun/blob/main/packages";
18
18
  export const DOCS = {
19
19
  launcher: `${REPO}/agentrun/README.md`,
@@ -87,7 +87,7 @@ export async function doctorOf({
87
87
  exec = (command, args) => spawnSync(command, args, { encoding: "utf8", timeout: 10_000, env }),
88
88
  get = fetch,
89
89
  nodeVersion = process.versions.node,
90
- engines = OWN.engines.node,
90
+ engines = OWN_NODE,
91
91
  readRecord = plainText,
92
92
  alive = isAlive,
93
93
  readToken = () => undefined,
@@ -342,7 +342,7 @@ export async function doctorOf({
342
342
  }
343
343
 
344
344
  const exit = refused !== undefined ? 1 : !answering ? 3 : checks.some((c) => c.status === "fail") ? 1 : 0;
345
- return { data, launcher: OWN.version, server: answering ? { url: health.url, version: version ?? null } : null, exit, checks };
345
+ return { data, launcher: OWN_VERSION, server: answering ? { url: health.url, version: version ?? null } : null, exit, checks };
346
346
  }
347
347
 
348
348
  /** The checks as a person reads them: one line each, then its fix and docs when it is not ok. */
package/lib/export.mjs CHANGED
@@ -12,6 +12,7 @@ export const EXPORT = {
12
12
  command: ["export"],
13
13
  pathParams: ["agent"],
14
14
  summary: "Write an agent's current revision as a template package folder, and say what the target sets up again",
15
+ route: "GET /agents/{agent_id}/package",
15
16
  help: [
16
17
  ["AGENT", "the agent's id"],
17
18
  ["--out DIR", "the folder to write: a new one, or an empty one"],
package/lib/harness.mjs CHANGED
@@ -11,6 +11,7 @@
11
11
  // (agentrun-serve check-harness, named as install-harness is, so this command's own word stays the CLI's): a JSON
12
12
  // report, and the three facts printed. It spends, on the model's key.
13
13
  import { spawnSync } from "node:child_process";
14
+ import { readFileSync } from "node:fs";
14
15
  import { homedir } from "node:os";
15
16
  import { join, resolve } from "node:path";
16
17
 
@@ -74,6 +75,35 @@ export const HARNESS_SIGN_IN = {
74
75
  },
75
76
  };
76
77
 
78
+ /** The console's page for a plan-billed recipe's keys (serve's harness-keys.ts HARNESS_KEYS_PAGE). */
79
+ const HARNESS_KEYS_PAGE = "/#/settings/harness-keys";
80
+
81
+ export const HARNESS_KEYS = {
82
+ command: ["harness", "keys"],
83
+ pathParams: [],
84
+ summary: "Print the link to Settings → Harness keys, where the owner saves the keys a plan-billed recipe runs on, for that harness alone (exit 1 when no AgentRun has started on DATA)",
85
+ help: [["--data DIR", "the data directory of the AgentRun the keys are for (default ~/.agentrun)"]],
86
+ options: {},
87
+ // Never a key on this terminal: a key is a secret write, the owner's signed-in session's alone, so it is pasted in the
88
+ // console, which keeps it sealed for that harness alone.
89
+ run({ values, env, io }) {
90
+ const data = dataOf(values, env);
91
+ let origin;
92
+ try {
93
+ const record = JSON.parse(readFileSync(join(data, ".server.json"), "utf8"));
94
+ origin = typeof record?.base_url === "string" && URL.canParse(record.base_url) ? new URL(record.base_url).origin : undefined;
95
+ } catch {
96
+ origin = undefined;
97
+ }
98
+ if (origin === undefined) {
99
+ io.stderr.write(`No AgentRun has started on ${data}: start it (agentrun), then save the keys in Settings → Harness keys (${HARNESS_KEYS_PAGE}).\n`);
100
+ return 1;
101
+ }
102
+ io.stdout.write(`${origin}${HARNESS_KEYS_PAGE}\n`);
103
+ return 0;
104
+ },
105
+ };
106
+
77
107
  export const HARNESS_CHECK = {
78
108
  command: ["harness-check"],
79
109
  pathParams: [],
package/lib/local.mjs ADDED
@@ -0,0 +1,13 @@
1
+ // The CLI's hand-written commands, which run as they are given beside the generated table's: cli.mjs runs them, and the
2
+ // table's generator (scripts/generate-clients.mjs) reads them so no generated command takes one of their names and the
3
+ // skill lists them. A command that calls the API names its routes (`route`), which the skill prints.
4
+ import { DEPLOY, DEPLOY_DELETE, DEPLOY_ROLLBACK } from "./deploy.mjs";
5
+ import { DOCTOR } from "./doctor.mjs";
6
+ import { EXPORT } from "./export.mjs";
7
+ import { HARNESS_CHECK, HARNESS_INSTALL, HARNESS_KEYS, HARNESS_SIGN_IN } from "./harness.mjs";
8
+ import { SECRETS } from "./login.mjs";
9
+ import { OPEN, SERVICE, STOP } from "./service.mjs";
10
+ import { SKILL_INSTALL } from "./skill.mjs";
11
+ import { TEMPLATE_EVAL, TEMPLATE_INSTALL, TEMPLATE_VALIDATE } from "./template.mjs";
12
+
13
+ export const LOCAL = [...SECRETS, SKILL_INSTALL, TEMPLATE_VALIDATE, TEMPLATE_EVAL, TEMPLATE_INSTALL, EXPORT, HARNESS_INSTALL, HARNESS_SIGN_IN, HARNESS_KEYS, HARNESS_CHECK, ...SERVICE, STOP, OPEN, DOCTOR, DEPLOY, DEPLOY_ROLLBACK, DEPLOY_DELETE];
package/lib/login.mjs CHANGED
@@ -169,20 +169,20 @@ export const LOGIN = {
169
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
170
  route: "GET /capabilities, then its device sign-in; else GET /agents?limit=1, to check a token from stdin",
171
171
  help: [
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"],
172
+ ["--to URL|cloud", `the server, /v2 added when its address's path holds none; 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, /v2 added as for --to (default AGENTRUN_BASE_URL); the token from stdin, or on a terminal a device sign-in when the server offers one"],
174
174
  ["(stdin)", "the token: agentrun login --base-url URL < FILE"],
175
175
  ],
176
176
  options: { to: { type: "string" } },
177
177
  async run({ values, env, io, cli }) {
178
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.");
179
+ const named = values.to !== undefined;
179
180
  const flagged = values["base-url"] !== undefined;
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.
181
+ const given = named ? toUrl(values.to, env) : flagged ? values["base-url"] : env.AGENTRUN_BASE_URL;
182
+ if (given === undefined) throw cli.fail(2, "agentrun login needs the server: --to URL, --base-url URL or AGENTRUN_BASE_URL.");
183
+ const base = cli.baseOf(given, named ? "--to" : flagged ? "--base-url" : "AGENTRUN_BASE_URL");
184
+ // The device sign-in for --to, or when stdin is a terminal, which can hold no token.
185
+ if (named || io.stdin.isTTY) {
186
186
  try {
187
187
  const offer = deviceOffer(await capabilitiesOf(base), base);
188
188
  if (offer) return keep(base, await deviceSignIn(base, offer, io), env, io, cli);
package/lib/own.mjs ADDED
@@ -0,0 +1,10 @@
1
+ // This package's own version and the Node.js it needs, read once from its package.json. A module of its own that imports
2
+ // nothing of this package, so any module may import it (start.mjs imports cli.mjs, which imports the rest).
3
+ import { readFileSync } from "node:fs";
4
+
5
+ const own = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
6
+
7
+ /** This package's version. */
8
+ export const OWN_VERSION = own.version;
9
+ /** The Node.js versions it runs on: package.json's engines.node. */
10
+ export const OWN_NODE = own.engines.node;
package/lib/service.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  // unit on Linux; never a system service, never sudo. The service runs the installer's command (~/.agentrun/bin/agentrun,
4
4
  // install.sh), which brings its own Node, with --no-open and the interactive launcher's rules for the data directory and
5
5
  // port, and writes to ~/.agentrun/logs/agentrun.log. With --tailscale it is also served on the person's tailnet
6
- // (tailscale.mjs); with --env, on a local model or with a start-time switch on (SERVICE_ENV). `agentrun stop` stops the AgentRun the installer starts in the
6
+ // (tailscale.mjs); with --env, on a local model, an Ollama off its default address or with a start-time switch on (SERVICE_ENV). `agentrun stop` stops the AgentRun the installer starts in the
7
7
  // background where there is no service manager (a container): its pid is in ~/.agentrun/agentrun.pid.
8
8
  import { spawn, spawnSync } from "node:child_process";
9
9
  import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
@@ -116,6 +116,8 @@ export const unitEnv = (text) =>
116
116
  * are sealed in the console.
117
117
  * - A local model's (AGENT_MODEL_BASE_URL in front of a gateway such as Ollama's), and its key at `none`: a server that
118
118
  * holds no key for its gateway refuses each run that brings none (run-model-key.ts, model_key_required).
119
+ * - Where Ollama listens (OLLAMA_HOST, read as the ollama CLI reads it), for an Ollama off its default address: the
120
+ * server lists its models itself (serve's ollama-provider.ts).
119
121
  * - The start-time switches (the server's start-switches.ts), on at `1` alone, for a machine its owner alone uses. A
120
122
  * server reads them at its start, so the service restarts.
121
123
  * - The usage counts' switches (docs/telemetry.md). A service never sees the shell that installed it, so install writes
@@ -126,6 +128,7 @@ export const SERVICE_ENV = {
126
128
  AGENT_MODEL: null,
127
129
  AGENT_MODEL_PRICE: null,
128
130
  AGENT_MODEL_API_KEY: ["none"],
131
+ OLLAMA_HOST: null,
129
132
  AGENTRUN_MCP_ALLOW_LOOPBACK: ["1"],
130
133
  AGENTRUN_WEBHOOK_PRIVATE_TARGETS: ["1"],
131
134
  AGENTRUN_TELEMETRY: null,
@@ -636,7 +639,7 @@ export function serviceOf({ platform = process.platform, home = homedir(), uid =
636
639
  }
637
640
 
638
641
  const VERBS = [
639
- ["install", "Install AgentRun as a service of this user and start it: it keeps running after the terminal closes and starts again at login", [["--port N", "the port to listen on (default: the first free from 7340; 7340 with --tailscale)"], ["--data DIR", "the data directory (default ~/.agentrun)"], ["--tailscale", "also serve it over HTTPS on your own tailnet only (tailscale serve, never Funnel); --no-tailscale takes it off"], ["--env KEY=VALUE", `a local model's variable for the server, a start-time switch or the usage counts' switch: ${Object.entries(SERVICE_ENV).map(([name, takes]) => (takes ? `${name} (${takes.join(" or ")})` : name)).join(", ")}; kept until KEY= removes it; repeatable`], ["--public-url URL", "the https address people open it at, through a proxy you run in front of it (your own tailscale serve, a reverse proxy); kept for every restart"]], { port: { type: "string" }, tailscale: { type: "boolean" }, env: { type: "string", multiple: true }, "public-url": { type: "string" } }],
642
+ ["install", "Install AgentRun as a service of this user and start it: it keeps running after the terminal closes and starts again at login", [["--port N", "the port to listen on (default: the first free from 7340; 7340 with --tailscale)"], ["--data DIR", "the data directory (default ~/.agentrun)"], ["--tailscale", "also serve it over HTTPS on your own tailnet only (tailscale serve, never Funnel); --no-tailscale takes it off"], ["--env KEY=VALUE", `a local model's variable for the server or where Ollama listens, a start-time switch or the usage counts' switch: ${Object.entries(SERVICE_ENV).map(([name, takes]) => (takes ? `${name} (${takes.join(" or ")})` : name)).join(", ")}; kept until KEY= removes it; repeatable`], ["--public-url URL", "the https address people open it at, through a proxy you run in front of it (your own tailscale serve, a reverse proxy); kept for every restart"]], { port: { type: "string" }, tailscale: { type: "boolean" }, env: { type: "string", multiple: true }, "public-url": { type: "string" } }],
640
643
  ["status", "Say whether the service is installed and running, the console's address and its health (exit 0 healthy, 1 not, 3 not installed)", [], {}],
641
644
  ["start", "Start the service and wait until it answers", [], {}],
642
645
  ["stop", "Stop the service (it starts again at the next login)", [], {}],
package/lib/start.mjs CHANGED
@@ -8,13 +8,14 @@ import { homedir } from "node:os";
8
8
  import { dirname, join } from "node:path";
9
9
  import { StringDecoder } from "node:string_decoder";
10
10
  import { main as cli, NOUNS, words } from "./cli.mjs";
11
+ import { OWN_VERSION } from "./own.mjs";
11
12
  import { chosenPublicUrl } from "./public-url.mjs";
12
13
  import { tailnetHint, tailnetNameOf } from "./tailscale.mjs";
13
14
 
14
15
  export const SERVE_PACKAGE = "@parcha/agentrun-serve";
15
16
  /** This command's package at its version, handed to the server it starts (AGENTRUN_NPX_PACKAGE), so the server's hints
16
17
  * name this command. */
17
- export const OWN_SPEC = `@parcha/agentrun@${JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version}`;
18
+ export const OWN_SPEC = `@parcha/agentrun@${OWN_VERSION}`;
18
19
  /** Where the server listens and the console is opened: this machine only. */
19
20
  export const HOST = "127.0.0.1"; // key-gate: loopback-rule the server this starts listens on this machine only
20
21
 
@@ -313,6 +314,42 @@ export function tellerOf() {
313
314
  };
314
315
  }
315
316
 
317
+ /** Runs one of the server's commands (`argv[0]`; an eval among them, which spends while it runs) to its end and answers
318
+ * its exit code. A stop sent to this command alone (a job runner's SIGTERM, a SIGHUP) is passed on, and this waits for
319
+ * the command to clean up and end: 130, 143 or 129 when a stop ended it. A hangup is passed on as a SIGTERM, which every
320
+ * server command stops on. Its output comes to this terminal as it is; a command that could not be started, or that a
321
+ * signal this command did not pass on ended, is said here (failureText). `agentrun template eval` runs its eval here
322
+ * too. */
323
+ export function runServerCommand(launcher, argv, env) {
324
+ const child = spawn(launcher, argv, { stdio: "inherit", env });
325
+ const codes = { SIGINT: 130, SIGTERM: 143, SIGHUP: 129 };
326
+ const sent = [];
327
+ const pass = Object.fromEntries(Object.keys(codes).map((signal) => [signal, () => {
328
+ const passed = signal === "SIGHUP" ? "SIGTERM" : signal;
329
+ sent.push(passed);
330
+ child.kill(passed);
331
+ }]));
332
+ for (const [signal, on] of Object.entries(pass)) process.on(signal, on);
333
+ const step = `run the server's ${argv[0]} command (${launcher})`;
334
+ return new Promise((resolve) => {
335
+ let over = false;
336
+ const done = (code) => {
337
+ if (over) return;
338
+ over = true;
339
+ for (const [signal, on] of Object.entries(pass)) process.off(signal, on);
340
+ resolve(code);
341
+ };
342
+ child.on("error", (error) => {
343
+ if (child.pid === undefined && !over) console.error(failureText({ command: argv[0], step, error }));
344
+ done(1);
345
+ });
346
+ child.on("exit", (code, signal) => {
347
+ if (signal !== null && !sent.includes(signal)) console.error(failureText({ command: argv[0], step, code, signal, sent }));
348
+ done(code ?? codes[signal] ?? 1);
349
+ });
350
+ });
351
+ }
352
+
316
353
  export async function main(argv, env = process.env) {
317
354
  // The first argument, past --data and its value: a word there names a command (the server's own, or else the CLI's),
318
355
  // and a flag starts the server, whose flags with values (--listen ADDR) follow.
@@ -363,39 +400,7 @@ export async function main(argv, env = process.env) {
363
400
  const dataDir = dir ?? join(homedir(), ".agentrun");
364
401
  // A name that starts with a dash keeps the equals form: the server's parser reads "--data -x" as a missing value.
365
402
  const data = dataDir.startsWith("-") ? [`--data=${dataDir}`] : ["--data", dataDir];
366
- if (rest[0] && !rest[0].startsWith("-")) {
367
- // A server command (an eval among them, which spends while it runs): a stop sent to this command alone (a job
368
- // runner's SIGTERM, a SIGHUP) is passed on, and this waits for the command to clean up and end. A hangup is passed
369
- // on as a SIGTERM, which every server command stops on. Its output comes to this terminal as it is; a command that
370
- // could not be started, or that a signal this command did not pass on ended, is said here (failureText).
371
- const child = spawn(launcher, [rest[0], ...data, ...rest.slice(1)], { stdio: "inherit", env: childEnv });
372
- const codes = { SIGINT: 130, SIGTERM: 143, SIGHUP: 129 };
373
- const sent = [];
374
- const pass = Object.fromEntries(Object.keys(codes).map((signal) => [signal, () => {
375
- const passed = signal === "SIGHUP" ? "SIGTERM" : signal;
376
- sent.push(passed);
377
- child.kill(passed);
378
- }]));
379
- for (const [signal, on] of Object.entries(pass)) process.on(signal, on);
380
- const step = `run the server's ${rest[0]} command (${launcher})`;
381
- return new Promise((resolve) => {
382
- let over = false;
383
- const done = (code) => {
384
- if (over) return;
385
- over = true;
386
- for (const [signal, on] of Object.entries(pass)) process.off(signal, on);
387
- resolve(code);
388
- };
389
- child.on("error", (error) => {
390
- if (child.pid === undefined && !over) console.error(failureText({ command: rest[0], step, error }));
391
- done(1);
392
- });
393
- child.on("exit", (code, signal) => {
394
- if (signal !== null && !sent.includes(signal)) console.error(failureText({ command: rest[0], step, code, signal, sent }));
395
- done(code ?? codes[signal] ?? 1);
396
- });
397
- });
398
- }
403
+ if (rest[0] && !rest[0].startsWith("-")) return runServerCommand(launcher, [rest[0], ...data, ...rest.slice(1)], childEnv);
399
404
  // The server's banner and request lines stay out of this terminal: one line here says where to go, the URL of the
400
405
  // server's own "Open " line; the lines SAID names go to stderr after it, for the person, so stdout stays that one line.
401
406
  // What it prints on stderr comes through as it is, as it prints it, at the pace this command's stderr is read (forward).
package/lib/target.mjs CHANGED
@@ -3,11 +3,22 @@
3
3
 
4
4
  /** AgentRun cloud's address, which `--to cloud` names unless AGENTRUN_CLOUD_URL names another. */
5
5
  export const CLOUD_URL = "https://api.agentrun.ai";
6
+ /** AgentRun cloud's console, where cloud's device sign-in page is. */
7
+ export const CLOUD_CONSOLE = "https://console.agentrun.ai";
6
8
 
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
+ /** The API base of a server's address, the one rule every command takes it by: the address without its trailing
10
+ * slashes, with /v2 added when its path holds no v2 segment, so `https://host/prefix` is `https://host/prefix/v2` and
11
+ * `https://host/v2/` is `https://host/v2`. Only the path's end changes: the string is never re-serialized, so the
12
+ * origin is the given one, byte for byte. The caller checks the address first (cli.mjs baseOf). */
13
+ export function apiBase(given) {
14
+ const url = given.replace(/\/+$/, "");
15
+ const path = URL.canParse(url) ? new URL(url).pathname : "";
16
+ return path.split("/").includes("v2") ? url : `${url}/v2`;
17
+ }
18
+
19
+ /** The API base a `--to` names: `cloud` is AGENTRUN_CLOUD_URL, else CLOUD_URL; any other address is taken as every
20
+ * command takes one (apiBase). The caller checks the result as every base URL is checked (cli.mjs baseOf), so a query,
9
21
  * fragment, user or password is refused there. */
10
22
  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`;
23
+ return apiBase(given === "cloud" ? env.AGENTRUN_CLOUD_URL || CLOUD_URL : given);
13
24
  }
package/lib/template.mjs CHANGED
@@ -2,8 +2,24 @@
2
2
  // the one a server runs on the packages it ships at its start. The server installed with this command checks it
3
3
  // (agentrun-serve validate-template), as it runs import and reset-password: this command reaches the server through its
4
4
  // launcher and its API alone. Nothing in the package runs.
5
- import { spawn, spawnSync } from "node:child_process";
6
- import { resolve } from "node:path";
5
+ import { spawnSync } from "node:child_process";
6
+ import { readdirSync, statSync } from "node:fs";
7
+ import { join, resolve } from "node:path";
8
+
9
+ /** The refusal of the cases `names` lists that the package in `dir` does not have (a case is a folder in its evals/), in
10
+ * the words the server uses (template-eval.ts readCases), or undefined: every one is there, or `dir` is no folder, which
11
+ * the server refuses in its own words. The server still checks each case it runs whole. */
12
+ function missingCases(dir, names) {
13
+ if (!names.length || !statSync(dir, { throwIfNoEntry: false })?.isDirectory()) return undefined;
14
+ let cases = [];
15
+ try {
16
+ cases = readdirSync(join(dir, "evals"), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
17
+ } catch {
18
+ // No evals/ folder: the package has no case.
19
+ }
20
+ const missing = names.filter((name) => !cases.includes(name));
21
+ return missing.length ? `${dir}: its eval cases do not check:\n${missing.map((name) => `- evals/${name}: no such case (the package's are ${cases.join(", ") || "none"})`).join("\n")}` : undefined;
22
+ }
7
23
 
8
24
  export const TEMPLATE_VALIDATE = {
9
25
  command: ["template", "validate"],
@@ -83,7 +99,10 @@ export const TEMPLATE_EVAL = {
83
99
  ],
84
100
  options: { case: { type: "string", multiple: true }, runs: { type: "string" }, server: { type: "string" }, "grader-model": { type: "string" }, report: { type: "string" }, faux: { type: "string" } },
85
101
  async run({ values, args, env, cli }) {
86
- const { installedServer } = await import("./start.mjs");
102
+ // A case the package does not have is refused here, at once, in the server's words, before its launcher starts.
103
+ const missing = missingCases(resolve(args[0]), values.case ?? []);
104
+ if (missing) throw cli.fail(2, missing);
105
+ const { installedServer, runServerCommand } = await import("./start.mjs");
87
106
  const launcher = installedServer();
88
107
  if (launcher === undefined) throw cli.fail(2, "AgentRun's server is not installed beside this command, and it is the server that runs an eval.");
89
108
  const argv = ["eval-template", resolve(args[0])];
@@ -99,19 +118,8 @@ export const TEMPLATE_EVAL = {
99
118
  childEnv = { ...env, AGENTRUN_API_KEY: token };
100
119
  }
101
120
  // A stop sent to this command alone (a job runner's SIGTERM, a SIGHUP) is passed on to the eval, which cancels its
102
- // run and cleans up before it exits, as it does on the Ctrl-C a terminal sends both: this command waits for that.
103
- const child = spawn(launcher, argv, { stdio: "inherit", env: childEnv });
104
- const signals = { SIGINT: 130, SIGTERM: 143, SIGHUP: 129 };
105
- // The eval stops on SIGINT and SIGTERM; a hangup is passed on as a SIGTERM, which it cleans up after.
106
- const pass = Object.fromEntries(Object.keys(signals).map((signal) => [signal, () => child.kill(signal === "SIGHUP" ? "SIGTERM" : signal)]));
107
- for (const [signal, on] of Object.entries(pass)) process.on(signal, on);
108
- try {
109
- return await new Promise((done) => {
110
- child.on("error", () => done(1));
111
- child.on("exit", (code, signal) => done(code ?? signals[signal] ?? 1));
112
- });
113
- } finally {
114
- for (const [signal, on] of Object.entries(pass)) process.off(signal, on);
115
- }
121
+ // run and cleans up before it exits, as it does on the Ctrl-C a terminal sends both: this command waits for that, as
122
+ // for every server command.
123
+ return runServerCommand(launcher, argv, childEnv);
116
124
  },
117
125
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun",
3
- "version": "0.4.21",
3
+ "version": "0.4.23",
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.53"
20
+ "@parcha/agentrun-serve": "0.1.0-beta.55"
21
21
  },
22
22
  "scripts": {
23
23
  "test": "node --test 'test/*.test.mjs'"
@@ -139,11 +139,12 @@ Two clients call the same API from code, with the same server and token. `@parch
139
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
140
  - `agentrun export AGENT`: Write an agent's current revision as a template package folder, and say what the target sets up again
141
141
  - `agentrun files`: create, delete, get, list, upload
142
- - `agentrun harness`: install, sign-in
142
+ - `agentrun harness`: install, keys, sign-in
143
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
144
+ - `agentrun harness-keys`: list
144
145
  - `agentrun home`: delete, list, read, write
145
146
  - `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 local`: create-pairing, create-suggested-agent, delete-composio-subscription, delete-computer, delete-workspace-archil, discard-suggestion, disconnect-git-hub, get-git-hub-connection, get-model-gateway, get-suggestion, get-workspace-archil, list-composio-events, list-composio-triggers, list-computer-choices, list-computers, list-git-hub-repositories, list-mcp-server-names, list-running-computers, list-suggestions, receive-hook-composio, restore-suggestion, rotate-composio-secret, scan-for-suggestions, test-computer, test-workspace-archil
147
148
  - `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
148
149
  - `agentrun logout`: Remove the config file login wrote, its address and token
149
150
  - `agentrun mcp-servers`: delete, get, list, oauth-client, private-hosts, refresh