@parcha/agentrun 0.4.13 → 0.4.15

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/doctor.mjs ADDED
@@ -0,0 +1,381 @@
1
+ // `agentrun doctor`: how this AgentRun is set up, checked in one go, each problem with what to change. It reads and never
2
+ // writes: no file is changed, nothing is started or stopped, and every request is a GET. The server is the one the data
3
+ // directory's record names (DIR/.server.json), read as every CLI command reads it (cli.mjs targetOf): a private file of
4
+ // this user's, its base_url an http or https URL with no query, fragment, user or password, its pid a positive whole
5
+ // number; a record that fails that is refused, and one whose process has exited is stale: nothing is asked of the address
6
+ // either names, where another process may listen now. Its routes that take no credential (/v2/health,
7
+ // /v2/auth/session) come first, and capabilities are read with the server's own token (DIR/.token) only where that file
8
+ // is there. No token, key, setup code or other secret is ever printed: the token goes in a header to this machine's own
9
+ // server and nowhere else, and the setup link is left to `agentrun open`.
10
+ import { spawnSync } from "node:child_process";
11
+ import { existsSync, readFileSync } from "node:fs";
12
+ import { homedir, userInfo } from "node:os";
13
+ import { join, resolve } from "node:path";
14
+ import { INSTALL_COMMAND, managerOf } from "./service.mjs";
15
+
16
+ const OWN = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
17
+ const REPO = "https://github.com/Parcha-ai/agentrun/blob/main/packages";
18
+ export const DOCS = {
19
+ launcher: `${REPO}/agentrun/README.md`,
20
+ health: `${REPO}/serve/README.md#capacity-and-health`,
21
+ address: `${REPO}/serve/README.md#quick-start-no-key-no-network`,
22
+ password: `${REPO}/serve/README.md#your-password`,
23
+ models: `${REPO}/serve/README.md#models`,
24
+ harnesses: `${REPO}/serve/README.md#harnesses`,
25
+ safety: `${REPO}/serve/README.md#safety`,
26
+ docker: `${REPO}/serve/README.md#a-run-in-a-docker-box`,
27
+ };
28
+ const REQUEST_MS = 3_000;
29
+ const LOOPBACK = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i;
30
+
31
+ /** A check's line: `ok`, `warn` (works, with a gap), `fail` (something will not work), `info` (a fact, nothing to fix) or
32
+ * `skip` (could not be checked, and why). */
33
+ const line = (id, title, status, summary, { fix = [], docs, details } = {}) => ({ id, title, status, summary, fix, ...(docs ? { docs } : {}), ...(details ? { details } : {}) });
34
+
35
+ /** `version` against a floor ">=MAJOR.MINOR.PATCH": true when it is that or newer. */
36
+ export function meetsFloor(version, engines) {
37
+ const floor = /^>=(\d+)\.(\d+)\.(\d+)$/.exec(engines ?? "");
38
+ if (!floor) return true;
39
+ const need = floor.slice(1).map(Number);
40
+ const have = String(version).replace(/^v/, "").split(".").map(Number);
41
+ for (let i = 0; i < 3; i++) if ((have[i] ?? 0) !== need[i]) return (have[i] ?? 0) > need[i];
42
+ return true;
43
+ }
44
+
45
+ /** A record's base_url as the CLI takes one (cli.mjs baseOf): http or https, with no query, fragment, user or password,
46
+ * any of which would carry a request elsewhere, and a pid that is a positive whole number. The base without its trailing
47
+ * slashes, or undefined. */
48
+ const baseOfRecord = (record) => {
49
+ const given = record?.base_url;
50
+ if (typeof given !== "string" || !URL.canParse(given) || !Number.isInteger(record.pid) || record.pid <= 0) return undefined;
51
+ const url = new URL(given);
52
+ return /^https?:$/.test(url.protocol) && !/[?#]/.test(given) && !url.username && !url.password ? given.replace(/\/+$/, "") : undefined;
53
+ };
54
+
55
+ /** Whether process `pid` runs (cli.mjs alive): one of another user's still counts. */
56
+ const isAlive = (pid) => {
57
+ try {
58
+ return process.kill(pid, 0);
59
+ } catch (error) {
60
+ return error.code === "EPERM";
61
+ }
62
+ };
63
+
64
+ /** A file's text, or undefined when there is none: what doctorOf reads the record with when its caller gives no
65
+ * `readRecord`. The CLI gives its private-file check (cli.mjs privateFile); without one, no token is read either
66
+ * (`readToken`'s default), so an address this read takes from another user's file is sent nothing secret. */
67
+ const plainText = (file) => {
68
+ try {
69
+ return readFileSync(file, "utf8");
70
+ } catch (error) {
71
+ if (error.code === "ENOENT") return undefined;
72
+ throw error;
73
+ }
74
+ };
75
+
76
+ /** Every check, from what this machine and its server say. Each dependency can be replaced (tests): `exec` has
77
+ * spawnSync's shape, `get` fetch's, `alive` says whether a pid runs, `readRecord` returns a file's text or undefined when there is none (and throws to
78
+ * refuse it: no request is sent then), `readToken` returns the server's token or undefined (and may throw, which skips
79
+ * the capabilities read). */
80
+ export async function doctorOf({
81
+ data,
82
+ env = process.env,
83
+ platform = process.platform,
84
+ home = homedir(),
85
+ uid = process.getuid?.(),
86
+ user = userInfo().username,
87
+ exec = (command, args) => spawnSync(command, args, { encoding: "utf8", timeout: 10_000, env }),
88
+ get = fetch,
89
+ nodeVersion = process.versions.node,
90
+ engines = OWN.engines.node,
91
+ readRecord = plainText,
92
+ alive = isAlive,
93
+ readToken = () => undefined,
94
+ }) {
95
+ data = resolve(data ?? join(home, ".agentrun"));
96
+ const root = join(home, ".agentrun");
97
+ const floor = engines.replace(/^>=/, "");
98
+ const checks = [];
99
+ const add = (...args) => checks.push(line(...args));
100
+ const getJson = async (url, headers = {}) => {
101
+ try {
102
+ const response = await get(url, { headers: { accept: "application/json", ...headers }, signal: AbortSignal.timeout(REQUEST_MS) });
103
+ const body = await response.json().catch(() => undefined);
104
+ return { status: response.status, body };
105
+ } catch (error) {
106
+ return { status: 0, error: error?.cause?.code ?? error?.name ?? "error" };
107
+ }
108
+ };
109
+
110
+ // 1. Node: this command's, and the `node` on PATH, which `npx @parcha/agentrun` runs on.
111
+ const fromPath = exec("node", ["--version"]);
112
+ const pathVersion = fromPath.status === 0 ? String(fromPath.stdout ?? "").trim().replace(/^v/, "") : undefined;
113
+ const nodeFix = [`Install AgentRun with a Node.js of its own: ${INSTALL_COMMAND}`, `Or install Node.js ${floor} or newer (https://nodejs.org).`];
114
+ if (!meetsFloor(nodeVersion, engines)) add("node", "Node", "fail", `This command runs on Node.js v${nodeVersion}; AgentRun needs ${floor} or newer.`, { fix: nodeFix, docs: DOCS.launcher });
115
+ else if (pathVersion !== undefined && pathVersion !== nodeVersion && !meetsFloor(pathVersion, engines)) {
116
+ add("node", "Node", "warn", `This command runs on Node.js v${nodeVersion}, but the node on PATH is v${pathVersion}, older than ${floor}: npx @parcha/agentrun refuses to start on it.`, { fix: nodeFix, docs: DOCS.launcher });
117
+ } else add("node", "Node", "ok", `Node.js v${nodeVersion} (AgentRun needs ${floor} or newer).`);
118
+
119
+ // 2. Server: the record's address, checked before anything is sent to it, then /v2/health there.
120
+ const recordFile = join(data, ".server.json");
121
+ let record;
122
+ let refused;
123
+ try {
124
+ const text = readRecord(recordFile);
125
+ if (text !== undefined) record = JSON.parse(text);
126
+ } catch (error) {
127
+ refused = error instanceof SyntaxError ? `${recordFile} is not valid JSON` : error.message.replace(/\.$/, "");
128
+ }
129
+ const base = refused === undefined && record !== undefined ? baseOfRecord(record) : undefined;
130
+ if (refused === undefined && record !== undefined && base === undefined) refused = `${recordFile} is not a server record (base_url an http or https URL with no query, fragment, user or password, pid a positive whole number); refusing it`;
131
+ if (refused !== undefined) record = undefined;
132
+ // A record a crash left behind names a port another process may have taken since: it is asked nothing, as the CLI
133
+ // sends nothing to it (cli.mjs targetOf).
134
+ const stale = base !== undefined && !alive(record.pid);
135
+ const health = {};
136
+ if (stale) Object.assign(health, { url: `${new URL(base).origin}/`, health: `not running (its process, pid ${record.pid}, has exited)` });
137
+ else if (base) {
138
+ health.url = `${new URL(base).origin}/`;
139
+ const answer = await getJson(`${base}/health`);
140
+ health.health = answer.status === 0 ? `not answering (${answer.error})` : answer.status === 200 && answer.body?.status === "ok" ? "ok" : `${answer.status} ${answer.body?.status ?? ""}`.trim();
141
+ health.checks = answer.body?.checks;
142
+ }
143
+ const answering = !stale && health.health !== undefined && !health.health.startsWith("not answering");
144
+ const program = join(root, "bin", "agentrun");
145
+ const manager = managerOf({ platform, home, uid, user, env, exec, fail: (_code, message) => new Error(message) });
146
+ // The service counts only when it serves this data directory: one installed for another is said, and left out.
147
+ const unitText = manager !== undefined && existsSync(manager.file) ? readFileSync(manager.file, "utf8") : undefined;
148
+ const unitArgs = unitText === undefined ? [] : manager.args(unitText);
149
+ const serviceData = unitText === undefined ? undefined : resolve(unitArgs.includes("--data") ? unitArgs[unitArgs.indexOf("--data") + 1] : root);
150
+ const installed = serviceData === data;
151
+ const serviceState = installed ? manager.state() : undefined;
152
+ const dataFlag = data === root ? "" : ` --data ${data}`;
153
+ const startFix = installed ? ["agentrun service start", "agentrun service logs (if it does not come up: the log says why)"]
154
+ : existsSync(program) ? [`${program}${dataFlag} (in a terminal), or agentrun service install${dataFlag} (keeps it running)`]
155
+ : dataFlag ? [`npx @parcha/agentrun${dataFlag} (in a terminal)`] : [`${INSTALL_COMMAND} (installs and starts it)`, "Or, in a terminal: npx @parcha/agentrun"];
156
+
157
+ // Capabilities, with the server's own token, read only from this data directory's private token file.
158
+ let caps;
159
+ let capsWhy;
160
+ if (answering && base) {
161
+ let token;
162
+ try {
163
+ token = readToken({ data, record, env });
164
+ } catch (error) {
165
+ capsWhy = error.message;
166
+ }
167
+ if (token) {
168
+ const answer = await getJson(`${base}/capabilities`, { authorization: `Bearer ${token}` });
169
+ if (answer.status === 200 && answer.body && typeof answer.body === "object") caps = answer.body;
170
+ else capsWhy = `GET /v2/capabilities answered ${answer.status || answer.error}`;
171
+ } else capsWhy ??= `no token to read the server's capabilities with: ${join(data, ".token")} is not there${record?.token_file ? "" : " (the server was started with AGENTRUN_TOKEN; set AGENTRUN_API_KEY to it)"}`;
172
+ }
173
+ const version = caps?.server?.version;
174
+
175
+ if (refused !== undefined) {
176
+ add("server", "Server", "fail", `${refused}: nothing is sent to the address it names.`, {
177
+ fix: [`ls -l ${recordFile}: it must be a regular file you own, mode 0600, that no one else can write. If it is not yours, remove it; then start AgentRun again (it writes a new one)`],
178
+ docs: DOCS.launcher,
179
+ });
180
+ } else if (health.health === "ok") add("server", "Server", "ok", `${health.url} answers /v2/health ok${version ? `, version ${version}` : ""}.`, { details: { url: health.url, version: version ?? null } });
181
+ else if (answering) {
182
+ const why = Object.entries(health.checks ?? {}).filter(([, value]) => value !== "ok").map(([name, value]) => `${name} ${value}`).join(", ");
183
+ const fix = [];
184
+ if (health.checks?.disk === "below_floor") fix.push(`Free disk space where ${data} is (the server needs 64 MiB free, or AGENTRUN_MIN_FREE_MB).`);
185
+ if (health.checks?.store === "does_not_open") fix.push("The store does not answer: agentrun service logs (or the terminal it runs in) says why; then agentrun service restart.");
186
+ if (!fix.length) fix.push("agentrun service logs, then agentrun service restart");
187
+ add("server", "Server", "fail", `${health.url} answers /v2/health ${health.health}${why ? ` (${why})` : ""}.`, { fix, docs: DOCS.health, details: { url: health.url, version: version ?? null } });
188
+ } else {
189
+ const where = base ? `The server recorded in ${join(data, ".server.json")} (${health.url}) is ${health.health}.` : `No AgentRun server is running for ${data} (no ${join(data, ".server.json")}).`;
190
+ add("server", "Server", "fail", where, { fix: startFix, docs: DOCS.launcher });
191
+ }
192
+ const skip = (id, title) => add(id, title, "skip", refused !== undefined ? "Not checked: the server record is refused (Server, above)." : "No server answering to ask.");
193
+ const noCaps = (id, title) => add(id, title, "skip", `Not checked: ${capsWhy}.`);
194
+
195
+ // 3. Service: installed? running? lingering?
196
+ if (manager === undefined) add("service", "Service", "info", `AgentRun runs as a service on macOS (launchd) and Linux (systemd); this is ${platform}.`);
197
+ else if (serviceData !== undefined && !installed) add("service", "Service", "info", `AgentRun's service (${manager.name}) serves another data directory, ${serviceData}, not this one.`);
198
+ else if (installed) {
199
+ const state = serviceState;
200
+ const notes = manager.notes();
201
+ if (!state.active) {
202
+ add("service", "Service", answering ? "warn" : "fail", `${manager.name} is installed but ${state.words}${answering ? "; the server that answers was started another way" : ""}.`, { fix: ["agentrun service start", "agentrun service logs (why it stopped)"], docs: DOCS.launcher });
203
+ } else if (notes.length) add("service", "Service", "warn", `${manager.name}, ${state.words}. ${notes.join(" ").split(". To keep")[0]}.`, { fix: notes.map((note) => note.replace(/^.*run once: /, "")), docs: DOCS.launcher });
204
+ else add("service", "Service", "ok", `${manager.name}, ${state.words}: it starts again at login${platform === "linux" ? " and at boot" : ""}.`);
205
+ } else {
206
+ const why = manager.available();
207
+ const background = existsSync(join(root, "agentrun.pid"));
208
+ // The service of the data directory checked: its --data, as startFix gives it. The installer alone sets up ~/.agentrun.
209
+ const serviceFix = existsSync(program) ? [`agentrun service install${dataFlag}`]
210
+ : dataFlag ? [`${INSTALL_COMMAND} -s -- --no-start (installs the command alone)`, `Then: ${program} service install${dataFlag} (a new terminal has agentrun on PATH; this one does not yet)`]
211
+ : [`${INSTALL_COMMAND} (installs it as a service)`];
212
+ if (why !== undefined) add("service", "Service", "info", `Not a service: ${why}.${background ? " The installer started AgentRun in the background; agentrun stop stops it." : ""}`);
213
+ else add("service", "Service", "warn", "AgentRun is not installed as a service: it stops when its terminal closes or this machine restarts.", { fix: serviceFix, docs: DOCS.launcher });
214
+ }
215
+
216
+ // 4. Address: who can open it.
217
+ if (!answering || !base) skip("address", "Address");
218
+ else {
219
+ const at = new URL(base);
220
+ const port = at.port || (at.protocol === "https:" ? "443" : "80");
221
+ // Something that forwards to it: a public address (capabilities, else the settings of the service while it is what
222
+ // runs) or the tailnet entry, when it forwards to this server's port. --allow-host is not one: it only names the Host
223
+ // names the server accepts, and forwards nothing. A stopped service's settings say nothing of a server started
224
+ // another way.
225
+ // The setting as the service's own file holds it: the launcher's --public-url on its command line (agentrun service
226
+ // install --public-url), or AGENTRUN_PUBLIC_URL as a systemd Environment= line or a launchd plist's key and string.
227
+ const named = serviceState?.active === true && (Boolean(manager.env(unitText).AGENTRUN_PUBLIC_URL) || (unitArgs.includes("--public-url") && Boolean(unitArgs[unitArgs.indexOf("--public-url") + 1])));
228
+ let tailnet;
229
+ try {
230
+ // The tailnet entry the launcher added ({url, proxy}) is the service's; it counts when its proxy is this port.
231
+ if (installed) tailnet = JSON.parse(readFileSync(join(root, "tailscale.json"), "utf8"));
232
+ } catch {}
233
+ const proxied = typeof tailnet?.proxy === "string" && URL.canParse(tailnet.proxy) ? new URL(tailnet.proxy) : undefined;
234
+ if (!(typeof tailnet?.url === "string" && proxied && LOOPBACK.test(proxied.hostname) && proxied.port === port)) tailnet = undefined;
235
+ const reachable = caps?.features?.triggers?.public_url === true || named || tailnet !== undefined;
236
+ const remote = Boolean(env.SSH_CONNECTION || env.SSH_TTY) || (platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY);
237
+ if (!LOOPBACK.test(at.hostname)) add("address", "Address", "ok", `It listens at ${at.host}, which other machines that reach this one can open; the token and the password are its only lock, so put TLS in front of it.`);
238
+ else if (reachable) add("address", "Address", "ok", `It listens on loopback (${at.host}) and is served at a name of its own${typeof tailnet?.url === "string" ? ` (${tailnet.url}, on your tailnet)` : " (its public URL)"}.`);
239
+ else if (!remote) add("address", "Address", "ok", `It listens on loopback (${at.host}): a browser on this machine opens it.`);
240
+ else {
241
+ // The launcher's --public-url: kept on the service's command line (its port kept too), or given where AgentRun starts
242
+ // in a terminal, with this port: a start without --port takes the first free one from 7340, which a proxy to this
243
+ // port does not reach.
244
+ const publicUrl = (url) => (installed ? `agentrun service install --public-url ${url}` : `start AgentRun with --port ${port} --public-url ${url}${dataFlag}`);
245
+ const fix = [`From your own computer, a tunnel: ssh -L ${port}:localhost:${port} <this machine>, then open http://localhost:${port}/`];
246
+ const status = exec("tailscale", ["status", "--json"]);
247
+ let ts;
248
+ try {
249
+ ts = status.status === 0 ? JSON.parse(status.stdout) : undefined;
250
+ } catch {}
251
+ const host = String(ts?.Self?.DNSName ?? "").replace(/\.$/, "");
252
+ if (ts?.BackendState === "Running" && host) {
253
+ fix.push(`On your tailnet only (never Funnel): tailscale serve --bg ${port}, then ${publicUrl(`https://${host}`)} so it answers at that name`);
254
+ // The launcher's own --tailscale serves the default data directory's AgentRun.
255
+ if (data === root) fix.push(installed || existsSync(program) ? "Or let AgentRun do both, as a service: agentrun service install --tailscale" : `Or let the installer do both: ${INSTALL_COMMAND} -s -- --tailscale`);
256
+ }
257
+ fix.push(`Behind a proxy or another name: ${publicUrl("https://<name>")} (or --allow-host <name>); it refuses any other Host name`);
258
+ add("address", "Address", "warn", `It listens on loopback only (${at.host}), and this session looks remote${env.SSH_CONNECTION || env.SSH_TTY ? " (SSH)" : " (no display)"}: a browser on another computer cannot open it.`, { fix, docs: DOCS.address });
259
+ }
260
+ }
261
+
262
+ // 5. Owner: is the console's password set?
263
+ if (!answering || !base) skip("owner", "Owner");
264
+ else {
265
+ const session = await getJson(`${base}/auth/session`);
266
+ if (session.status === 200 && session.body?.password_set === true) add("owner", "Owner", "ok", "The console's password is set.");
267
+ else if (session.status === 200 && session.body?.password_set === false) {
268
+ // agentrun open opens the setup page (its code filled in when setup takes one) or, where no browser opens, prints
269
+ // its link. The doctor itself asks for no code: a new one is a POST.
270
+ const coded = session.body?.setup_code !== false;
271
+ const fix = [`agentrun open${dataFlag} (opens the setup page${coded ? " with its code filled in" : ""}; where no browser opens, it prints the link)`];
272
+ if (!coded) fix.push(`Or open ${health.url}setup in a browser that reaches this server: its setup takes no code`);
273
+ add("owner", "Owner", "warn", "No password yet: whoever opens the console first sets it. Set it now.", { fix, docs: DOCS.password });
274
+ } else if ((session.status === 200 && session.body?.accounts === false) || session.status === 404) add("owner", "Owner", "info", "This server has no accounts (AGENTRUN_ACCOUNTS=0): its token opens the console.");
275
+ else add("owner", "Owner", "skip", `GET /v2/auth/session answered ${session.status || session.error}.`);
276
+ }
277
+
278
+ // 6. Models and harnesses.
279
+ if (!answering || !base) skip("models", "Models"), skip("harnesses", "Harnesses");
280
+ else if (!caps) noCaps("models", "Models"), noCaps("harnesses", "Harnesses");
281
+ else {
282
+ const models = caps.models ?? {};
283
+ if (models.ready === true) {
284
+ const through = { gateway: "through the gateway (AGENT_MODEL_BASE_URL)", chatgpt: "on the ChatGPT plan", faux: "on the faux model", providers: "on a provider's key" }[models.source] ?? `from ${models.source}`;
285
+ add("models", "Models", "ok", `A model is ready ${through}${models.default ? `: ${models.default}` : ""}.`, { details: { source: models.source ?? null, default: models.default ?? null } });
286
+ } else {
287
+ const fix = models.needs === "model"
288
+ ? ["AGENT_MODEL names a model no key here runs: set it to provider/model-id of a provider you have a key for, or add that provider's key in the console (Settings → Model keys)"]
289
+ : [
290
+ "In the console: Settings → Model keys (an Anthropic, OpenAI or OpenRouter key, or Continue with ChatGPT)",
291
+ "Or a gateway (LiteLLM, OpenRouter, ...): restart AgentRun with AGENT_MODEL_BASE_URL=<its base URL>, AGENT_MODEL=<its model id>, AGENT_MODEL_GATEWAY_IDS=bare when it names models without a provider/ prefix, and AGENT_MODEL_API_KEY when it takes a key",
292
+ ];
293
+ // models.ready is the model AgentRun runs itself; a connected native agent (Claude Code or Codex on its own sign-in)
294
+ // runs without it.
295
+ add("models", "Models", "fail", `No model is ready (it needs ${models.needs === "model" ? "another model" : "a model key"}): no agent on a model AgentRun runs can start. A connected native agent (Claude Code or Codex on its own sign-in) needs none.`, { fix, docs: DOCS.models, details: { source: models.source ?? null, needs: models.needs ?? null } });
296
+ }
297
+ const harnesses = Array.isArray(caps.harnesses) ? caps.harnesses : [];
298
+ // Ready: it runs here and has a model to run a definition that names none. One that runs here with no default model
299
+ // (default_model null: pi with no key) is not, and its reason says why. A server from before default_model was
300
+ // listed leaves it out: available alone says it then.
301
+ const runs = (h) => h.available === true && h.default_model !== null;
302
+ const ready = harnesses.filter(runs).map((h) => h.id);
303
+ const not = harnesses.filter((h) => !runs(h));
304
+ // A reason that starts with its harness's name is said as it is.
305
+ const notWords = not.map((h) => { const why = String(h.reason ?? "not available").replace(/\.$/, ""); return why.startsWith(h.id) ? why : `${h.id}: ${why}`; });
306
+ const details = { ready, not_ready: Object.fromEntries(not.map((h) => [h.id, h.reason ?? null])) };
307
+ if (!ready.length) add("harnesses", "Harnesses", "fail", `No harness runs here: ${notWords.join("; ")}.`, { fix: ["Add a model key (Models, above); each harness says what it needs"], docs: DOCS.harnesses, details });
308
+ else add("harnesses", "Harnesses", not.length ? "info" : "ok", `Ready: ${ready.join(", ")}.${not.length ? ` Not ready: ${notWords.join("; ")}.` : ""}`, { ...(not.length ? { docs: DOCS.harnesses } : {}), details });
309
+ }
310
+
311
+ // 7. Start-time switches (a server from before they were listed has none).
312
+ if (!answering || !base) skip("switches", "Switches");
313
+ else if (!caps) noCaps("switches", "Switches");
314
+ else if (!caps.switches || typeof caps.switches !== "object") add("switches", "Switches", "info", "This server does not list its start-time switches (a version from before they were listed).");
315
+ else {
316
+ const entries = Object.entries(caps.switches);
317
+ const words = entries.map(([name, s]) => `${name} ${s?.on ? `on${s.value !== null && s.value !== "1" ? ` (${s.value})` : ""}` : "off"}`);
318
+ add("switches", "Switches", "info", `${words.join(", ")}. Each is set where AgentRun starts and takes a restart.`, {
319
+ docs: DOCS.safety,
320
+ details: Object.fromEntries(entries.map(([name, s]) => [name, { on: Boolean(s?.on), value: s?.value ?? null, allows: s?.allows ?? null }])),
321
+ });
322
+ }
323
+
324
+ // 8. Docker: the box a run's computer runs in.
325
+ const dockerFix = (why) => {
326
+ if (/permission denied/i.test(why) && platform === "linux") return [`Let this user use Docker: sudo usermod -aG docker ${user}, then log in again`, "Then restart AgentRun (agentrun service restart)"];
327
+ return [platform === "darwin" ? "Install and start Docker Desktop (or OrbStack, Colima): docker info must answer" : "Install Docker Engine and start it (https://docs.docker.com/engine/install/): docker info must answer", "Then restart AgentRun (agentrun service restart): it looks for Docker at its start"];
328
+ };
329
+ const boxes = Array.isArray(caps?.places?.boxes) ? caps.places.boxes : [];
330
+ const box = boxes.find((b) => b.id === "docker");
331
+ // Another box that is ready (Daytona, Modal, ...) runs an agent's computer without Docker: then Docker's absence is a fact.
332
+ const others = boxes.filter((b) => b.id !== "docker" && b.available === true).map((b) => b.id);
333
+ if (box?.available) add("docker", "Docker", "ok", "Docker boxes are ready: an agent with a computer runs its tools in one.");
334
+ else if (box && others.length) add("docker", "Docker", "info", `No Docker box: ${box.reason ?? "unavailable"}. An agent that needs a computer runs in ${others.join(" or ")} instead.`, { details: { ready: others } });
335
+ else if (box) add("docker", "Docker", "warn", `No Docker box: ${box.reason ?? "unavailable"}. An agent that needs a computer (bash, files) fails to start, and new agents run on the runner.`, { fix: dockerFix(box.reason ?? ""), docs: DOCS.docker });
336
+ else {
337
+ const info = exec("docker", ["info", "--format", "{{.ServerVersion}}"]);
338
+ const said = `${info.stderr ?? ""}`.trim().split("\n")[0];
339
+ if (info.status === 0) add("docker", "Docker", "ok", `docker info answers (Docker ${String(info.stdout ?? "").trim()}).`);
340
+ else if (info.error?.code === "ENOENT") add("docker", "Docker", "warn", "Docker is not installed: an agent that needs a computer (bash, files) fails to start.", { fix: dockerFix(""), docs: DOCS.docker });
341
+ else add("docker", "Docker", "warn", `docker info does not answer${said ? ` (${said})` : ""}: an agent that needs a computer (bash, files) fails to start.`, { fix: dockerFix(said), docs: DOCS.docker });
342
+ }
343
+
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 };
346
+ }
347
+
348
+ /** The checks as a person reads them: one line each, then its fix and docs when it is not ok. */
349
+ export function textOf(report, home = homedir()) {
350
+ const tilde = (path) => (path === home || path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path);
351
+ const width = Math.max(...report.checks.map((c) => c.title.length));
352
+ const out = [`AgentRun doctor (agentrun ${report.launcher}, data directory ${tilde(report.data)})`, ""];
353
+ for (const check of report.checks) {
354
+ out.push(`${check.status.padEnd(4)} ${check.title.padEnd(width)} ${check.summary}`);
355
+ const pad = " ".repeat(6 + width + 2);
356
+ for (const fix of check.fix) out.push(`${pad}Fix: ${fix}`);
357
+ if (check.docs && check.status !== "ok") out.push(`${pad}Docs: ${check.docs}`);
358
+ }
359
+ const counts = ["fail", "warn"].map((status) => [status, report.checks.filter((c) => c.status === status).length]).filter(([, n]) => n);
360
+ out.push("", report.exit === 3 ? "No server is answering: start it first (Server, above)." : counts.length ? `${counts.map(([status, n]) => `${n} ${status === "fail" ? "failed" : n === 1 ? "warning" : "warnings"}`).join(", ")}.` : "All good.");
361
+ return `${out.join("\n")}\n`;
362
+ }
363
+
364
+ /** `agentrun doctor` (cli.mjs LOCAL). */
365
+ export const DOCTOR = {
366
+ command: ["doctor"],
367
+ pathParams: [],
368
+ summary: "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)",
369
+ help: [["--data DIR", "the data directory whose server it checks (default ~/.agentrun)"], ["--json", "print the checks as JSON: {exit, server, checks: [{id, status, summary, fix, docs}]}"]],
370
+ options: { json: { type: "boolean" } },
371
+ async run({ values, io, env, cli }) {
372
+ if (values["base-url"] !== undefined) throw cli.fail(2, "agentrun doctor checks the AgentRun on this machine, the server of --data (default ~/.agentrun); it takes no --base-url.");
373
+ const readToken = ({ data, record, env: vars }) => {
374
+ if (record && !record.token_file) return vars.AGENTRUN_API_KEY || undefined;
375
+ return cli.privateFile(join(data, ".token"))?.trim() || undefined;
376
+ };
377
+ const report = await doctorOf({ data: values.data, env, readRecord: cli.privateFile, readToken });
378
+ io.stdout.write(values.json ? `${JSON.stringify(report, null, 2)}\n` : textOf(report));
379
+ return report.exit;
380
+ },
381
+ };
package/lib/harness.mjs CHANGED
@@ -1,37 +1,80 @@
1
- // `agentrun harness install goose`: the harness its owner installs, never a run (Goose, the one there is). The server
2
- // installed with this command does it (agentrun-serve install-harness), as it runs validate-template: the pinned archive
3
- // downloaded, its sha256 checked, unpacked into DATA/harnesses/goose, the binary's sha256 checked, then put in place
1
+ // `agentrun harness install goose|cursor` and `agentrun harness install --recipe FILE`: the harness its owner installs,
2
+ // never a run (Goose; Cursor, on the owner's own Cursor API key; or an ACP agent a recipe file names:
3
+ // docs/harness-recipe.md). The server installed with this command does it (agentrun-serve install-harness), as it runs
4
+ // validate-template: the pinned archive downloaded, its sha256 checked, unpacked into DATA/harnesses/<id>, the binary's
5
+ // sha256 checked (for Cursor, every file's too; for a recipe that pins none, the first one recorded), then put in place
4
6
  // read-only. DATA is this command's (~/.agentrun unless --data names one), the store `npx @parcha/agentrun` starts the
5
- // server on. Run again with the pinned binary in place, it downloads nothing. No provider key goes near it.
7
+ // server on. Run again with the pinned release in place, it downloads nothing. No provider key goes near it,
8
+ // CURSOR_API_KEY included.
9
+ //
10
+ // `agentrun harness-check --recipe FILE`: the recipe's installed agent run for real on --model and judged
11
+ // (agentrun-serve check-harness, named as install-harness is, so this command's own word stays the CLI's): a JSON
12
+ // report, and the three facts printed. It spends, on the model's key.
6
13
  import { spawnSync } from "node:child_process";
7
14
  import { homedir } from "node:os";
8
15
  import { join, resolve } from "node:path";
9
16
 
10
- /** The harnesses this command installs. */
11
- const INSTALLABLE = ["goose"];
17
+ /** The harnesses this command installs by name. */
18
+ const INSTALLABLE = ["goose", "cursor"];
12
19
 
13
20
  /** A variable named like a credential (a KEY, TOKEN, SECRET, PASSWORD or CREDENTIAL(S) segment). */
14
21
  const KEY_NAMED = /(?:^|_)(?:KEY|TOKEN|TOKENS|SECRET|PASSWORD|CREDENTIALS?)(?:_|$)/i;
15
22
 
23
+ /** The data directory: --data, else this command's own. */
24
+ const dataOf = (values, env) => resolve(values.data ?? join(env.HOME || homedir(), ".agentrun"));
25
+
26
+ /** The installed server's launcher, or a usage failure saying it is not there. */
27
+ async function launcherOf(cli, what) {
28
+ // Loaded here: start.mjs loads cli.mjs, which loads this module.
29
+ const { installedServer } = await import("./start.mjs");
30
+ const launcher = installedServer();
31
+ if (launcher === undefined) throw cli.fail(2, `AgentRun's server is not installed beside this command, and it is the server that ${what}.`);
32
+ return launcher;
33
+ }
34
+
16
35
  export const HARNESS_INSTALL = {
17
36
  command: ["harness", "install"],
18
37
  pathParams: ["harness"],
19
- summary: "Install a harness AgentRun runs only once its owner installs it (goose), then restart AgentRun",
38
+ argsOptional: true,
39
+ summary: "Install a harness AgentRun runs only once its owner installs it (goose, cursor, or a recipe file's), then restart AgentRun",
20
40
  help: [
21
41
  ["HARNESS", `the harness: ${INSTALLABLE.join(", ")}. Its pinned release is downloaded and checked by sha256 into DATA/harnesses/HARNESS; run again, it downloads nothing`],
42
+ ["--recipe FILE", "in place of HARNESS: a recipe file (docs/harness-recipe.md), checked against its five rules before anything is downloaded"],
22
43
  ["--data DIR", "the data directory of the AgentRun it is for (default ~/.agentrun, where npx @parcha/agentrun keeps it)"],
23
44
  ],
24
- options: {},
45
+ options: { recipe: { type: "string" } },
25
46
  async run({ values, args, env, cli }) {
26
47
  const [name] = args;
27
- if (!INSTALLABLE.includes(name)) throw cli.fail(2, `agentrun harness install installs ${INSTALLABLE.join(", ")}, not ${name}: claude-agent and codex install on first use, and pi and opencode come with AgentRun.`);
28
- // Loaded here: start.mjs loads cli.mjs, which loads this module.
29
- const { installedServer } = await import("./start.mjs");
30
- const launcher = installedServer();
31
- if (launcher === undefined) throw cli.fail(2, "AgentRun's server is not installed beside this command, and it is the server that installs a harness.");
32
- const data = resolve(values.data ?? join(env.HOME || homedir(), ".agentrun"));
48
+ if (values.recipe !== undefined && name !== undefined) throw cli.fail(2, "agentrun harness install takes a harness's name or --recipe FILE, not both.");
49
+ if (values.recipe === undefined && !INSTALLABLE.includes(name)) throw cli.fail(2, `agentrun harness install installs ${INSTALLABLE.join(", ")} or a recipe file (--recipe FILE), not ${name ?? "nothing"}: claude-agent and codex install on first use, and pi and opencode come with AgentRun.`);
50
+ const launcher = await launcherOf(cli, "installs a harness");
33
51
  // No key reaches the install: every variable named like one is left out of its environment.
34
52
  const keyless = Object.fromEntries(Object.entries(env).filter(([key]) => !KEY_NAMED.test(key)));
35
- return spawnSync(launcher, ["install-harness", name, "--data", data], { stdio: "inherit", env: keyless }).status ?? 1;
53
+ const which = values.recipe === undefined ? [name] : ["--recipe", resolve(values.recipe)];
54
+ return spawnSync(launcher, ["install-harness", ...which, "--data", dataOf(values, env)], { stdio: "inherit", env: keyless }).status ?? 1;
55
+ },
56
+ };
57
+
58
+ export const HARNESS_CHECK = {
59
+ command: ["harness-check"],
60
+ pathParams: [],
61
+ summary: "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",
62
+ help: [
63
+ ["--recipe FILE", "the recipe file (docs/harness-recipe.md); its agent installed first with agentrun harness install --recipe FILE"],
64
+ ["--model PROVIDER/MODEL", "the run's model, for a recipe billed through the proxy (openrouter/anthropic/claude-haiku-4.5, anthropic/claude-haiku-4-5)"],
65
+ ["--report FILE", "where the JSON report goes (default ./harness-check-ID.json)"],
66
+ ["--cap USD", "the most the check may spend (default 0.25)"],
67
+ ["--data DIR", "the data directory the recipe's agent was installed into (default ~/.agentrun)"],
68
+ ],
69
+ options: { recipe: { type: "string" }, model: { type: "string" }, report: { type: "string" }, cap: { type: "string" } },
70
+ async run({ values, env, cli }) {
71
+ if (values.recipe === undefined) throw cli.fail(2, "agentrun harness-check needs --recipe FILE.");
72
+ const launcher = await launcherOf(cli, "checks a harness");
73
+ const flags = ["--recipe", resolve(values.recipe), "--data", dataOf(values, env)];
74
+ if (values.model !== undefined) flags.push("--model", values.model);
75
+ if (values.report !== undefined) flags.push("--report", resolve(values.report));
76
+ if (values.cap !== undefined) flags.push("--cap", values.cap);
77
+ // The model's key goes to the server's launcher, which holds it in memory (its SECRETS) and hands it to no agent.
78
+ return spawnSync(launcher, ["check-harness", ...flags], { stdio: "inherit", env }).status ?? 1;
36
79
  },
37
80
  };
@@ -0,0 +1,42 @@
1
+ // `--public-url URL` (`npx @parcha/agentrun`, `agentrun service install`): the address people open the server at, through
2
+ // a proxy in front of it (`tailscale serve`, a reverse proxy). The launcher hands it to the server as AGENTRUN_PUBLIC_URL,
3
+ // the one way the server takes it: its links name it, its Host check on loopback takes its name, and its first visit asks
4
+ // for the setup code.
5
+
6
+ /** The names an http:// address may have: this machine's, where nothing crosses a network in clear text. */
7
+ const LOOPBACK = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/;
8
+
9
+ /** The server's own form of an address, as it reads AGENTRUN_PUBLIC_URL: parsed, with no trailing slash. */
10
+ const same = (value) => (URL.canParse(value) ? new URL(value).href.replace(/\/+$/, "") : value);
11
+
12
+ /** `{ url }`, `value` as the server's root address (`https://name/`), or `{ error }` saying what is wrong with it: an
13
+ * https address, or http on this machine only; no user name or password; no path beyond `/`, no query or fragment. */
14
+ export function publicUrlOf(value, name = "--public-url") {
15
+ const example = `such as https://box.tailnet.example/`;
16
+ // A value that is no address is repeated only when it has no "@": one with user info in it may hold a password, and an
17
+ // address that fails to parse has not been checked for one yet.
18
+ if (typeof value !== "string" || value === "" || !URL.canParse(value)) return { error: `${name} takes the https address people open AgentRun at, ${example}${value && !value.includes("@") ? `, not ${value}` : ""}.` };
19
+ const url = new URL(value);
20
+ // Never repeated: a password in the address is the one part that must not reach a log.
21
+ if (url.username !== "" || url.password !== "") return { error: `${name} takes an address with no user name or password in it, ${example}.` };
22
+ if (url.protocol !== "https:" && url.protocol !== "http:") return { error: `${name} takes an https address, ${example}, not ${url.protocol} ${value}.` };
23
+ if (url.protocol === "http:" && !LOOPBACK.test(url.hostname)) {
24
+ return { error: `${name} takes an https address: over http:// the password and the session cross the network in clear text, so http is taken only for this machine (localhost, 127.0.0.1). Put HTTPS in front (tailscale serve, a reverse proxy) and give its https:// address, not ${value}.` };
25
+ }
26
+ if (url.pathname !== "/" || url.search !== "" || url.hash !== "") {
27
+ return { error: `${name} takes the address of the server's root, ${url.origin}/, with no path, query or fragment: AgentRun is served at the root of its own name, not at ${value}.` };
28
+ }
29
+ return { url: url.href };
30
+ }
31
+
32
+ /** The public address a start runs with: `--public-url` (`flag`) or AGENTRUN_PUBLIC_URL (`env`), `{ url }` (undefined
33
+ * with neither), or `{ error }` when the flag is not one or the two name different addresses. */
34
+ export function chosenPublicUrl(flag, env) {
35
+ if (flag === undefined) return { url: env || undefined };
36
+ const checked = publicUrlOf(flag);
37
+ if (checked.error !== undefined) return checked;
38
+ if (env && same(env) !== same(checked.url)) {
39
+ return { error: `AGENTRUN_PUBLIC_URL names another address than --public-url ${checked.url}, and the server takes one. Give one of them.` };
40
+ }
41
+ return checked;
42
+ }