@parcha/agentrun 0.4.11 → 0.4.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -3
- package/bin/agentrun.mjs +9 -3
- package/install.sh +482 -0
- package/lib/cli.mjs +5 -2
- package/lib/commands.generated.mjs +18 -0
- package/lib/service.mjs +492 -0
- package/lib/start.mjs +21 -7
- package/lib/tailscale.mjs +172 -0
- package/package.json +3 -2
- package/skills/agentrun-cli/SKILL.md +2 -0
- package/skills/agentrun-cli/references/commands.md +70 -0
package/lib/service.mjs
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
// `agentrun service install|status|start|stop|restart|logs|upgrade|uninstall`: AgentRun as a service of this user, so it
|
|
2
|
+
// keeps running after the terminal closes and starts again at login. A launchd LaunchAgent on macOS, a systemd --user
|
|
3
|
+
// unit on Linux; never a system service, never sudo. The service runs the installer's command (~/.agentrun/bin/agentrun,
|
|
4
|
+
// install.sh), which brings its own Node, with --no-open and the interactive launcher's rules for the data directory and
|
|
5
|
+
// port, and writes to ~/.agentrun/logs/agentrun.log. With --tailscale it is also served on the person's tailnet
|
|
6
|
+
// (tailscale.mjs). `agentrun stop` stops the AgentRun the installer starts in the
|
|
7
|
+
// background where there is no service manager (a container): its pid is in ~/.agentrun/agentrun.pid.
|
|
8
|
+
import { spawnSync } from "node:child_process";
|
|
9
|
+
import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { homedir, userInfo } from "node:os";
|
|
11
|
+
import { join, resolve } from "node:path";
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { TAILNET_PORT, tailnetOf, targetOf } from "./tailscale.mjs";
|
|
14
|
+
|
|
15
|
+
export const LABEL = "ai.agentrun.server";
|
|
16
|
+
export const UNIT = "agentrun.service";
|
|
17
|
+
export const INSTALL_COMMAND = "curl -fsSL https://agentrun.ai/install | sh";
|
|
18
|
+
/** How long a start waits for the server to answer /health before it says it did not. */
|
|
19
|
+
export const HEALTH_WAIT_MS = 90_000;
|
|
20
|
+
/** How long `agentrun stop` waits for the background AgentRun to end after its SIGTERM before it sends a SIGKILL: past the
|
|
21
|
+
* server's own drain (--drain-timeout, 30 s by default), so a busy run gets its turn and the server cleans up. */
|
|
22
|
+
export const STOP_WAIT_MS = 45_000;
|
|
23
|
+
const INSTALLER = fileURLToPath(new URL("../install.sh", import.meta.url));
|
|
24
|
+
|
|
25
|
+
const xml = (text) => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
26
|
+
const unxml = (text) => text.replace(/"/g, '"').replace(/>/g, ">").replace(/</g, "<").replace(/&/g, "&");
|
|
27
|
+
|
|
28
|
+
/** The LaunchAgent: started at login (RunAtLoad), started again when it exits with a failure (KeepAlive), its output in
|
|
29
|
+
* `log`, with the PATH of the shell that installed it (launchd's own has no Homebrew, so no docker) and `env`. */
|
|
30
|
+
export function plistText({ program, args, path, log, env = {} }) {
|
|
31
|
+
const strings = [program, ...args].map((arg) => ` <string>${xml(arg)}</string>`).join("\n");
|
|
32
|
+
const vars = Object.entries({ PATH: path, ...env }).map(([key, value]) => ` <key>${xml(key)}</key>\n <string>${xml(value)}</string>`).join("\n");
|
|
33
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
34
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
35
|
+
<plist version="1.0">
|
|
36
|
+
<dict>
|
|
37
|
+
<key>Label</key>
|
|
38
|
+
<string>${LABEL}</string>
|
|
39
|
+
<key>ProgramArguments</key>
|
|
40
|
+
<array>
|
|
41
|
+
${strings}
|
|
42
|
+
</array>
|
|
43
|
+
<key>EnvironmentVariables</key>
|
|
44
|
+
<dict>
|
|
45
|
+
${vars}
|
|
46
|
+
</dict>
|
|
47
|
+
<key>RunAtLoad</key>
|
|
48
|
+
<true/>
|
|
49
|
+
<key>KeepAlive</key>
|
|
50
|
+
<dict>
|
|
51
|
+
<key>SuccessfulExit</key>
|
|
52
|
+
<false/>
|
|
53
|
+
</dict>
|
|
54
|
+
<key>StandardOutPath</key>
|
|
55
|
+
<string>${xml(log)}</string>
|
|
56
|
+
<key>StandardErrorPath</key>
|
|
57
|
+
<string>${xml(log)}</string>
|
|
58
|
+
</dict>
|
|
59
|
+
</plist>
|
|
60
|
+
`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The command and arguments a plist made by plistText runs. */
|
|
64
|
+
export const plistArgs = (text) => [...(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(text)?.[1] ?? "").matchAll(/<string>([^<]*)<\/string>/g)].map((match) => unxml(match[1]));
|
|
65
|
+
|
|
66
|
+
/** One word of a systemd command line or setting: quoted when it needs to be, its specifiers (%) and variables ($)
|
|
67
|
+
* escaped, as systemd.syntax(7) reads them. */
|
|
68
|
+
export const systemdWord = (word) => {
|
|
69
|
+
const escaped = word.replace(/%/g, "%%").replace(/\$/g, "$$$$");
|
|
70
|
+
return /^[\w@+=:,./-]+$/.test(escaped) ? escaped : `"${escaped.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/** The words of an ExecStart line systemdWord wrote. */
|
|
74
|
+
export function systemdWords(line) {
|
|
75
|
+
const words = [];
|
|
76
|
+
for (const [, quoted, plain] of line.matchAll(/"((?:[^"\\]|\\.)*)"|(\S+)/g)) {
|
|
77
|
+
words.push((quoted !== undefined ? quoted.replace(/\\(.)/g, "$1") : plain).replace(/\$\$/g, "$").replace(/%%/g, "%"));
|
|
78
|
+
}
|
|
79
|
+
return words;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The systemd --user unit: started at login (default.target) and at boot when lingering is on, started again when it
|
|
83
|
+
* fails, its output appended to `log`, with the PATH of the shell that installed it and `env`. */
|
|
84
|
+
export function unitText({ program, args, path, log, env = {} }) {
|
|
85
|
+
return `[Unit]
|
|
86
|
+
Description=AgentRun, an open-source platform for your agents
|
|
87
|
+
After=network-online.target
|
|
88
|
+
|
|
89
|
+
[Service]
|
|
90
|
+
ExecStart=${[program, ...args].map(systemdWord).join(" ")}
|
|
91
|
+
${Object.entries({ PATH: path, ...env }).map(([key, value]) => `Environment=${systemdWord(`${key}=${value}`)}`).join("\n")}
|
|
92
|
+
Restart=on-failure
|
|
93
|
+
RestartSec=2
|
|
94
|
+
StandardOutput=append:${log.replace(/%/g, "%%")}
|
|
95
|
+
StandardError=append:${log.replace(/%/g, "%%")}
|
|
96
|
+
|
|
97
|
+
[Install]
|
|
98
|
+
WantedBy=default.target
|
|
99
|
+
`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The command and arguments a unit made by unitText runs. */
|
|
103
|
+
export const unitArgs = (text) => systemdWords(/^ExecStart=(.*)$/m.exec(text)?.[1] ?? "");
|
|
104
|
+
|
|
105
|
+
const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
106
|
+
|
|
107
|
+
/** The service manager of this platform, driven through `exec` (spawnSync's shape). */
|
|
108
|
+
export function managerOf({ platform, home, uid, user, env, exec, fail }) {
|
|
109
|
+
const run = (command, args, { ok = false } = {}) => {
|
|
110
|
+
const result = exec(command, args);
|
|
111
|
+
if (!ok && result.status !== 0) {
|
|
112
|
+
const said = `${result.error?.message ?? ""}${result.stderr ?? ""}${result.stdout ?? ""}`.trim().split("\n").slice(-3).join(" ");
|
|
113
|
+
throw fail(1, `${command} ${args.join(" ")} failed${said ? `: ${said}` : ""}.`);
|
|
114
|
+
}
|
|
115
|
+
return result;
|
|
116
|
+
};
|
|
117
|
+
if (platform === "darwin") {
|
|
118
|
+
const domain = `gui/${uid}`;
|
|
119
|
+
const target = `${domain}/${LABEL}`;
|
|
120
|
+
const loaded = () => run("launchctl", ["print", target], { ok: true }).status === 0;
|
|
121
|
+
// A job just booted out can still be going: bootstrap again, a few times, until launchd takes it.
|
|
122
|
+
const bootstrap = (file) => {
|
|
123
|
+
for (let tries = 1; ; tries++) {
|
|
124
|
+
const result = run("launchctl", ["bootstrap", domain, file], { ok: true });
|
|
125
|
+
if (result.status === 0) return;
|
|
126
|
+
if (tries === 10) run("launchctl", ["bootstrap", domain, file]);
|
|
127
|
+
sleep(500);
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
const file = join(home, "Library", "LaunchAgents", `${LABEL}.plist`);
|
|
131
|
+
return {
|
|
132
|
+
file,
|
|
133
|
+
name: `launchd ${target}`,
|
|
134
|
+
text: plistText,
|
|
135
|
+
args: plistArgs,
|
|
136
|
+
available: () => (run("launchctl", ["print", domain], { ok: true }).status === 0 ? undefined : `this user has no launchd session (${domain}): a login over ssh has none; log in at the Mac`),
|
|
137
|
+
install() {
|
|
138
|
+
if (loaded()) run("launchctl", ["bootout", target], { ok: true });
|
|
139
|
+
run("launchctl", ["enable", target], { ok: true });
|
|
140
|
+
bootstrap(file);
|
|
141
|
+
},
|
|
142
|
+
start: () => (loaded() ? run("launchctl", ["kickstart", target]) : bootstrap(file)),
|
|
143
|
+
stop: () => loaded() && run("launchctl", ["bootout", target]),
|
|
144
|
+
restart: () => (loaded() ? run("launchctl", ["kickstart", "-k", target]) : bootstrap(file)),
|
|
145
|
+
remove: () => loaded() && run("launchctl", ["bootout", target]),
|
|
146
|
+
state() {
|
|
147
|
+
const result = run("launchctl", ["print", target], { ok: true });
|
|
148
|
+
if (result.status !== 0) return { active: false, words: "not loaded" };
|
|
149
|
+
const state = /^\s*state = (.+)$/m.exec(result.stdout)?.[1]?.trim() ?? "unknown";
|
|
150
|
+
const pid = /^\s*pid = (\d+)$/m.exec(result.stdout)?.[1];
|
|
151
|
+
return { active: state === "running", words: pid ? `${state}, pid ${pid}` : state };
|
|
152
|
+
},
|
|
153
|
+
notes: () => [],
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
if (platform === "linux") {
|
|
157
|
+
const systemctl = (...args) => run("systemctl", ["--user", ...args]);
|
|
158
|
+
return {
|
|
159
|
+
file: join(env.XDG_CONFIG_HOME || join(home, ".config"), "systemd", "user", UNIT),
|
|
160
|
+
name: `systemd --user ${UNIT}`,
|
|
161
|
+
text: unitText,
|
|
162
|
+
args: unitArgs,
|
|
163
|
+
available() {
|
|
164
|
+
const result = run("systemctl", ["--user", "show-environment"], { ok: true });
|
|
165
|
+
if (result.error?.code === "ENOENT") return "this machine has no systemd";
|
|
166
|
+
return result.status === 0 ? undefined : "this user has no systemd user session (a container, or a login without one)";
|
|
167
|
+
},
|
|
168
|
+
install() {
|
|
169
|
+
systemctl("daemon-reload");
|
|
170
|
+
systemctl("enable", UNIT);
|
|
171
|
+
systemctl("restart", UNIT);
|
|
172
|
+
},
|
|
173
|
+
start: () => systemctl("start", UNIT),
|
|
174
|
+
stop: () => systemctl("stop", UNIT),
|
|
175
|
+
restart: () => systemctl("restart", UNIT),
|
|
176
|
+
remove() {
|
|
177
|
+
run("systemctl", ["--user", "disable", "--now", UNIT], { ok: true });
|
|
178
|
+
run("systemctl", ["--user", "reset-failed", UNIT], { ok: true });
|
|
179
|
+
},
|
|
180
|
+
removed: () => systemctl("daemon-reload"),
|
|
181
|
+
state() {
|
|
182
|
+
const out = run("systemctl", ["--user", "show", UNIT, "--property=ActiveState,SubState,MainPID"], { ok: true }).stdout ?? "";
|
|
183
|
+
const field = (name) => new RegExp(`^${name}=(.*)$`, "m").exec(out)?.[1]?.trim();
|
|
184
|
+
const pid = field("MainPID");
|
|
185
|
+
return { active: field("ActiveState") === "active", words: `${field("ActiveState") ?? "unknown"} (${field("SubState") ?? "?"})${pid && pid !== "0" ? `, pid ${pid}` : ""}` };
|
|
186
|
+
},
|
|
187
|
+
// Without lingering, a user's services stop at their last logout and start at their first login.
|
|
188
|
+
notes() {
|
|
189
|
+
const linger = run("loginctl", ["show-user", user, "--property=Linger", "--value"], { ok: true });
|
|
190
|
+
return linger.status === 0 && linger.stdout.trim() === "no"
|
|
191
|
+
? [`It stops when you log out and starts when you log in. To keep it running, and start it at boot, run once: sudo loginctl enable-linger ${user}`]
|
|
192
|
+
: [];
|
|
193
|
+
},
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
return undefined;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** The data directory a service's arguments name, else the launcher's default. */
|
|
200
|
+
const dataOf = (args, home) => {
|
|
201
|
+
const at = args.indexOf("--data");
|
|
202
|
+
return resolve(at >= 0 ? args[at + 1] : join(home, ".agentrun"));
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
/** The server a data directory's record names, and whether it answers /health ok: `{ url, health, record }`. */
|
|
206
|
+
async function healthOf(data, { fetch: get = fetch, since = 0 } = {}) {
|
|
207
|
+
const file = join(data, ".server.json");
|
|
208
|
+
let record;
|
|
209
|
+
try {
|
|
210
|
+
// A record from before this start is the last server's. A second's slack: a file's time can trail the clock.
|
|
211
|
+
if (statSync(file).mtimeMs < since - 1_000) return {};
|
|
212
|
+
record = JSON.parse(readFileSync(file, "utf8"));
|
|
213
|
+
} catch {
|
|
214
|
+
return {};
|
|
215
|
+
}
|
|
216
|
+
if (typeof record?.base_url !== "string" || !URL.canParse(record.base_url)) return {};
|
|
217
|
+
const url = `${new URL(record.base_url).origin}/`;
|
|
218
|
+
try {
|
|
219
|
+
const response = await get(`${record.base_url.replace(/\/+$/, "")}/health`, { signal: AbortSignal.timeout(3_000) });
|
|
220
|
+
const body = await response.json().catch(() => ({}));
|
|
221
|
+
return { url, health: response.ok && body?.status === "ok" ? "ok" : `${response.status} ${body?.status ?? ""}`.trim(), checks: body?.checks };
|
|
222
|
+
} catch (error) {
|
|
223
|
+
return { url, health: `not answering (${error?.cause?.code ?? error?.name})` };
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** The last `count` lines of a file, read back from its end only as far as they go: the log is appended to forever. */
|
|
228
|
+
const tailOf = (file, count) => {
|
|
229
|
+
if (count === 0) return [];
|
|
230
|
+
let fd;
|
|
231
|
+
try {
|
|
232
|
+
fd = openSync(file, "r");
|
|
233
|
+
const chunks = [];
|
|
234
|
+
let start = fstatSync(fd).size;
|
|
235
|
+
let newlines = 0;
|
|
236
|
+
while (start > 0 && newlines <= count) {
|
|
237
|
+
const chunk = Buffer.alloc(Math.min(65_536, start));
|
|
238
|
+
start -= chunk.length;
|
|
239
|
+
readSync(fd, chunk, 0, chunk.length, start);
|
|
240
|
+
chunks.unshift(chunk);
|
|
241
|
+
for (let at = chunk.indexOf(10); at !== -1; at = chunk.indexOf(10, at + 1)) newlines++;
|
|
242
|
+
}
|
|
243
|
+
const lines = Buffer.concat(chunks).toString("utf8").split("\n");
|
|
244
|
+
if (lines.at(-1) === "") lines.pop();
|
|
245
|
+
if (start > 0) lines.shift();
|
|
246
|
+
return lines.slice(-count);
|
|
247
|
+
} catch {
|
|
248
|
+
return [];
|
|
249
|
+
} finally {
|
|
250
|
+
if (fd !== undefined) closeSync(fd);
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
/** Every service command, given what it runs on; the entries below bind it to this machine. */
|
|
255
|
+
export function serviceOf({ platform = process.platform, home = homedir(), uid = process.getuid?.(), user = userInfo().username, env = process.env, exec, io, fail, get = fetch, waitMs = HEALTH_WAIT_MS, kill = process.kill.bind(process), stopWaitMs = STOP_WAIT_MS }) {
|
|
256
|
+
exec ??= (command, args, options = {}) => spawnSync(command, args, { encoding: "utf8", ...options });
|
|
257
|
+
const root = join(home, ".agentrun");
|
|
258
|
+
const program = join(root, "bin", "agentrun");
|
|
259
|
+
const log = join(root, "logs", "agentrun.log");
|
|
260
|
+
const say = (line) => io.stdout.write(`${line}\n`);
|
|
261
|
+
const manager = managerOf({ platform, home, uid, user, env, exec, fail });
|
|
262
|
+
const need = () => {
|
|
263
|
+
if (manager === undefined) throw fail(1, `AgentRun runs as a service on macOS (launchd) and Linux (systemd); this is ${platform}.`);
|
|
264
|
+
return manager;
|
|
265
|
+
};
|
|
266
|
+
const installed = () => manager !== undefined && existsSync(manager.file);
|
|
267
|
+
const needInstalled = () => {
|
|
268
|
+
if (!installed()) throw fail(3, "AgentRun's service is not installed: agentrun service install installs it.");
|
|
269
|
+
return manager;
|
|
270
|
+
};
|
|
271
|
+
const argsNow = () => manager.args(readFileSync(manager.file, "utf8")).slice(1);
|
|
272
|
+
|
|
273
|
+
/** Waits for the server started at `since` to answer /health ok, then says where it is; exit 0, or 1 with the log's
|
|
274
|
+
* last lines. */
|
|
275
|
+
async function started(since, data) {
|
|
276
|
+
const deadline = Date.now() + waitMs;
|
|
277
|
+
let last = {};
|
|
278
|
+
while (Date.now() < deadline) {
|
|
279
|
+
last = await healthOf(data, { fetch: get, since });
|
|
280
|
+
if (last.health === "ok") {
|
|
281
|
+
say(`AgentRun is running at ${last.url} (${manager.name}).`);
|
|
282
|
+
say(`Logs: ${log}`);
|
|
283
|
+
for (const note of manager.notes()) say(note);
|
|
284
|
+
return 0;
|
|
285
|
+
}
|
|
286
|
+
await new Promise((done) => setTimeout(done, 500));
|
|
287
|
+
}
|
|
288
|
+
const lines = tailOf(log, 20);
|
|
289
|
+
io.stderr.write(`AgentRun's service did not answer /health ok within ${waitMs / 1000} s${last.health ? ` (${last.health})` : ""}. Its state: ${manager.state().words}.\n`);
|
|
290
|
+
if (lines.length) io.stderr.write(`The last lines of ${log}:\n${lines.map((line) => ` ${line}`).join("\n")}\n`);
|
|
291
|
+
return 1;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
return {
|
|
295
|
+
async install({ data, port, tailscale }) {
|
|
296
|
+
if (port !== undefined && !/^\d+$/.test(port)) throw fail(2, `--port takes a port number, not ${port}.`);
|
|
297
|
+
need();
|
|
298
|
+
if (!existsSync(program)) throw fail(1, `AgentRun's service runs the installed command, ${program}, and it is not there. Install it first: ${INSTALL_COMMAND}`);
|
|
299
|
+
const why = manager.available();
|
|
300
|
+
if (why !== undefined) throw fail(1, `AgentRun can't run as a service here: ${why}. Start it in a terminal with ${program}.`);
|
|
301
|
+
// --tailscale or --no-tailscale on an installed service changes its sharing only: its data folder and port stay
|
|
302
|
+
// unless named (the installer passes the flag alone).
|
|
303
|
+
if (tailscale !== undefined && installed()) {
|
|
304
|
+
const now = argsNow();
|
|
305
|
+
const option = (name) => (now.includes(name) ? now[now.indexOf(name) + 1] : undefined);
|
|
306
|
+
data ??= option("--data");
|
|
307
|
+
port ??= option("--port");
|
|
308
|
+
}
|
|
309
|
+
const again = (flag) => [`agentrun service install ${flag}`, ...(port !== undefined ? [`--port ${port}`] : []), ...(data !== undefined ? [`--data ${resolve(data)}`] : [])].join(" ");
|
|
310
|
+
const tailnet = tailnetOf({ platform, root, uid, exec, say, fail, again: again("--tailscale") });
|
|
311
|
+
// --no-tailscale takes it off the tailnet; with neither flag, a service on the tailnet stays there.
|
|
312
|
+
const share = tailscale ?? tailnet.recorded() !== undefined;
|
|
313
|
+
// On the tailnet the port is fixed, so the serve entry and the server still agree after a restart.
|
|
314
|
+
const served = share ? (port ?? TAILNET_PORT) : port;
|
|
315
|
+
if (share && Number(served) === 0) throw fail(2, `--tailscale serves a fixed port, and --port 0 has the system pick another at each start: name a port, or leave --port out for ${TAILNET_PORT}.`);
|
|
316
|
+
if (!share) tailnet.off(again("--no-tailscale"));
|
|
317
|
+
// The server knows the address people open: its host check takes the name, and its setup takes the printed code.
|
|
318
|
+
const at = share ? tailnet.address(targetOf(served)) : undefined;
|
|
319
|
+
const args = ["--no-open", ...(data !== undefined ? ["--data", resolve(data)] : []), ...(served !== undefined ? ["--port", served] : [])];
|
|
320
|
+
const vars = at ? { AGENTRUN_PUBLIC_URL: at.url, AGENTRUN_TRUSTED_PROXIES: "loopback" } : {};
|
|
321
|
+
mkdirSync(join(root, "logs"), { recursive: true, mode: 0o700 });
|
|
322
|
+
mkdirSync(join(manager.file, ".."), { recursive: true });
|
|
323
|
+
writeFileSync(manager.file, manager.text({ program, args, path: env.PATH ?? "/usr/bin:/bin", log, env: vars }));
|
|
324
|
+
const since = Date.now();
|
|
325
|
+
manager.install();
|
|
326
|
+
say(`Installed AgentRun's service (${manager.file}): it keeps running after this terminal closes, and starts again at login.`);
|
|
327
|
+
const code = await started(since, dataOf(args, home));
|
|
328
|
+
if (code === 0 && at) tailnet.serve(served, at.host);
|
|
329
|
+
return code;
|
|
330
|
+
},
|
|
331
|
+
async status() {
|
|
332
|
+
need();
|
|
333
|
+
if (!installed()) {
|
|
334
|
+
say("AgentRun's service is not installed: agentrun service install installs it.");
|
|
335
|
+
return 3;
|
|
336
|
+
}
|
|
337
|
+
const state = manager.state();
|
|
338
|
+
const { url, health } = state.active ? await healthOf(dataOf(argsNow(), home), { fetch: get }) : {};
|
|
339
|
+
say(`Service: ${manager.name}, ${state.words}`);
|
|
340
|
+
if (url) say(`Console: ${url}`);
|
|
341
|
+
say(`Health: ${health ?? "not running"}`);
|
|
342
|
+
say(`Logs: ${log}`);
|
|
343
|
+
for (const note of manager.notes()) say(note);
|
|
344
|
+
return state.active && health === "ok" ? 0 : 1;
|
|
345
|
+
},
|
|
346
|
+
async start() {
|
|
347
|
+
needInstalled();
|
|
348
|
+
// Starting a running service leaves it as it is, its record included.
|
|
349
|
+
const since = manager.state().active ? 0 : Date.now();
|
|
350
|
+
manager.start();
|
|
351
|
+
return started(since, dataOf(argsNow(), home));
|
|
352
|
+
},
|
|
353
|
+
async restart() {
|
|
354
|
+
needInstalled();
|
|
355
|
+
const since = Date.now();
|
|
356
|
+
manager.restart();
|
|
357
|
+
return started(since, dataOf(argsNow(), home));
|
|
358
|
+
},
|
|
359
|
+
async stop() {
|
|
360
|
+
needInstalled();
|
|
361
|
+
manager.stop();
|
|
362
|
+
say(`Stopped AgentRun's service (${manager.name}). agentrun service start starts it again; it also starts again at login.`);
|
|
363
|
+
return 0;
|
|
364
|
+
},
|
|
365
|
+
async logs({ follow, lines }) {
|
|
366
|
+
const count = lines === undefined ? 50 : Number(lines);
|
|
367
|
+
if (!Number.isInteger(count) || count < 0) throw fail(2, `--lines takes a whole number, not ${lines}.`);
|
|
368
|
+
if (!existsSync(log)) throw fail(1, `There is no service log yet (${log}).`);
|
|
369
|
+
if (!follow) {
|
|
370
|
+
for (const line of tailOf(log, count)) say(line);
|
|
371
|
+
return 0;
|
|
372
|
+
}
|
|
373
|
+
return exec("tail", ["-n", String(count), "-f", log], { stdio: "inherit" }).status ?? 1;
|
|
374
|
+
},
|
|
375
|
+
async upgrade({ version }) {
|
|
376
|
+
const args = ["--no-start", ...(version !== undefined ? ["--version", version] : [])];
|
|
377
|
+
const result = exec("sh", [INSTALLER, ...args], { stdio: "inherit" });
|
|
378
|
+
if (result.status !== 0) throw fail(1, `The installer stopped (${result.error?.message ?? `exit ${result.status}`}); the service was not restarted.`);
|
|
379
|
+
if (!installed()) return say(`The service is not installed: ${program} service install starts it.`), 0;
|
|
380
|
+
// The new version's own command restarts it, as the service's code may have changed with it.
|
|
381
|
+
return exec(program, ["service", "restart"], { stdio: "inherit" }).status ?? 1;
|
|
382
|
+
},
|
|
383
|
+
async uninstall() {
|
|
384
|
+
need();
|
|
385
|
+
tailnetOf({ platform, root, uid, exec, say, fail, again: "agentrun service uninstall" }).off();
|
|
386
|
+
if (!installed()) return say("AgentRun's service is not installed."), 0;
|
|
387
|
+
manager.remove();
|
|
388
|
+
unlinkSync(manager.file);
|
|
389
|
+
manager.removed?.();
|
|
390
|
+
say(`Removed AgentRun's service (${manager.file}). Its data stays in ${root}.`);
|
|
391
|
+
return 0;
|
|
392
|
+
},
|
|
393
|
+
/** `agentrun stop`: the AgentRun install.sh started in the background, stopped as Ctrl-C would (SIGTERM, which the
|
|
394
|
+
* launcher passes on to the server), then SIGKILL past stopWaitMs. Exit 0 once the launcher and its server have
|
|
395
|
+
* ended, 3 when none is running, 1 when one outlives its SIGKILL. install.sh stops it with the same steps in sh, so an
|
|
396
|
+
* install of a version with no `agentrun stop` stops it too. */
|
|
397
|
+
async background() {
|
|
398
|
+
const file = join(root, "agentrun.pid");
|
|
399
|
+
let pid;
|
|
400
|
+
try {
|
|
401
|
+
pid = Number(readFileSync(file, "utf8").trim());
|
|
402
|
+
} catch {}
|
|
403
|
+
// A process's state letter and command line: from /proc where there is one (a container may have no ps), else from
|
|
404
|
+
// ps. Undefined once it is gone. A process that ended is a zombie (Z) until its parent reaps it, and in a container
|
|
405
|
+
// with no init nothing does, so a zombie counts as ended.
|
|
406
|
+
const processOf = (n) => {
|
|
407
|
+
try {
|
|
408
|
+
const stat = readFileSync(`/proc/${n}/stat`, "utf8");
|
|
409
|
+
return { state: stat.slice(stat.lastIndexOf(")") + 2)[0], args: readFileSync(`/proc/${n}/cmdline`, "utf8").replaceAll("\0", " ") };
|
|
410
|
+
} catch {
|
|
411
|
+
if (existsSync("/proc/self/stat")) return undefined;
|
|
412
|
+
}
|
|
413
|
+
const ps = exec("ps", ["-o", "stat=", "-o", "args=", "-p", String(n)]);
|
|
414
|
+
const [, state, args] = (ps.status === 0 && /^\s*(\S)\S*\s+(.*)$/s.exec(ps.stdout ?? "")) || [];
|
|
415
|
+
return state === undefined ? undefined : { state, args };
|
|
416
|
+
};
|
|
417
|
+
// A pid file outlives a crash, and its pid can be another process's by now: only a running process that runs this
|
|
418
|
+
// install's files counts.
|
|
419
|
+
const ours = (n) => {
|
|
420
|
+
const now = Number.isInteger(n) && n > 1 ? processOf(n) : undefined;
|
|
421
|
+
return now !== undefined && now.state !== "Z" && now.args.includes(`${root}/`);
|
|
422
|
+
};
|
|
423
|
+
if (!ours(pid)) {
|
|
424
|
+
rmSync(file, { force: true });
|
|
425
|
+
say(`No AgentRun started in the background is running.${installed() ? " AgentRun runs as a service here: agentrun service stop stops it." : ""}`);
|
|
426
|
+
return 3;
|
|
427
|
+
}
|
|
428
|
+
// The launcher passes its SIGTERM on to the server it started (the pid in the server's record) and waits for it.
|
|
429
|
+
// The server is waited for too: without setsid the two share no process group of their own, and a SIGKILL to the
|
|
430
|
+
// launcher alone would leave the server running.
|
|
431
|
+
let server;
|
|
432
|
+
try {
|
|
433
|
+
server = JSON.parse(readFileSync(join(root, ".server.json"), "utf8")).pid;
|
|
434
|
+
} catch {}
|
|
435
|
+
const until = async (ms) => {
|
|
436
|
+
const deadline = Date.now() + ms;
|
|
437
|
+
while ([pid, server].some(ours) && Date.now() < deadline) await new Promise((done) => setTimeout(done, 200));
|
|
438
|
+
return [pid, server].filter(ours);
|
|
439
|
+
};
|
|
440
|
+
kill(pid, "SIGTERM");
|
|
441
|
+
const running = await until(stopWaitMs);
|
|
442
|
+
if (running.length > 0) {
|
|
443
|
+
// The installer starts it with setsid where there is one, so it leads a process group, the server's too.
|
|
444
|
+
try {
|
|
445
|
+
kill(-pid, "SIGKILL");
|
|
446
|
+
} catch {}
|
|
447
|
+
for (const each of running) {
|
|
448
|
+
try {
|
|
449
|
+
kill(each, "SIGKILL");
|
|
450
|
+
} catch {}
|
|
451
|
+
}
|
|
452
|
+
say(`AgentRun (pid ${running.join(", ")}) was still running ${stopWaitMs / 1000} s after its SIGTERM, so it was sent a SIGKILL.`);
|
|
453
|
+
const still = await until(5_000);
|
|
454
|
+
if (still.length > 0) return say(`AgentRun (pid ${still.join(", ")}) still runs after its SIGKILL; ${file} stays.`), 1;
|
|
455
|
+
}
|
|
456
|
+
rmSync(file, { force: true });
|
|
457
|
+
say(`Stopped AgentRun (pid ${pid}).`);
|
|
458
|
+
return 0;
|
|
459
|
+
},
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
const VERBS = [
|
|
464
|
+
["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"]], { port: { type: "string" }, tailscale: { type: "boolean" } }],
|
|
465
|
+
["status", "Say whether the service is installed and running, the console's address and its health (exit 0 healthy, 1 not, 3 not installed)", [], {}],
|
|
466
|
+
["start", "Start the service and wait until it answers", [], {}],
|
|
467
|
+
["stop", "Stop the service (it starts again at the next login)", [], {}],
|
|
468
|
+
["restart", "Restart the service and wait until it answers", [], {}],
|
|
469
|
+
["logs", "Print the service's log, ~/.agentrun/logs/agentrun.log", [["--lines N", "how many of its last lines (default 50)"], ["--follow", "and keep printing what comes (-f)"]], { lines: { type: "string" }, follow: { type: "boolean", short: "f" } }],
|
|
470
|
+
["upgrade", "Install another version with the installer, then restart the service on it", [["--version V", "the version or npm tag (default: latest)"]], { version: { type: "string" } }],
|
|
471
|
+
["uninstall", "Stop the service and remove it, and the tailscale serve entry --tailscale added; the data directory stays", [], {}],
|
|
472
|
+
];
|
|
473
|
+
|
|
474
|
+
/** The CLI's entries (cli.mjs LOCAL), one per verb. */
|
|
475
|
+
export const SERVICE = VERBS.map(([verb, summary, help, options]) => ({
|
|
476
|
+
command: ["service", verb],
|
|
477
|
+
pathParams: [],
|
|
478
|
+
summary,
|
|
479
|
+
help,
|
|
480
|
+
options,
|
|
481
|
+
run: ({ values, io, env, cli }) => serviceOf({ env, io, fail: cli.fail })[verb](values),
|
|
482
|
+
}));
|
|
483
|
+
|
|
484
|
+
/** `agentrun stop` (cli.mjs LOCAL). */
|
|
485
|
+
export const STOP = {
|
|
486
|
+
command: ["stop"],
|
|
487
|
+
pathParams: [],
|
|
488
|
+
summary: "Stop the AgentRun the installer started in the background, where there is no service manager (exit 0 stopped, 3 none running)",
|
|
489
|
+
help: [],
|
|
490
|
+
options: {},
|
|
491
|
+
run: ({ io, env, cli }) => serviceOf({ env, io, fail: cli.fail }).background(),
|
|
492
|
+
};
|
package/lib/start.mjs
CHANGED
|
@@ -35,8 +35,9 @@ export const API_ONLY_LINE = /^API only \(AGENTRUN_API_ONLY=1\)/;
|
|
|
35
35
|
/** How many of the server's last lines, on stdout and on stderr each, a start that fails shows. */
|
|
36
36
|
export const TAIL_LINES = 20;
|
|
37
37
|
|
|
38
|
-
/** How long a start waits for the server's "
|
|
39
|
-
* (milliseconds) sets another bound; the launcher's
|
|
38
|
+
/** How long a start waits for the server's "Starting " line (its port bound) or its "Open " line, whichever comes first,
|
|
39
|
+
* before it stops the server and says so. AGENTRUN_START_TIMEOUT_MS (milliseconds) sets another bound; the launcher's
|
|
40
|
+
* tests use it. After a "Starting " line it waits for "Open " with no bound: the server is up, still loading. */
|
|
40
41
|
export const START_TIMEOUT_MS = 60_000;
|
|
41
42
|
/** How long a server that did not start has to end after its SIGTERM before it is sent a SIGKILL. */
|
|
42
43
|
export const STOP_GRACE_MS = 10_000;
|
|
@@ -70,7 +71,7 @@ export function failureText({ command, step, error, code = null, signal = null,
|
|
|
70
71
|
exit = "it never ran";
|
|
71
72
|
} else if (stopped !== undefined) {
|
|
72
73
|
const was = stopped === "closed" ? "its output closed while it ran" : `still running after ${seconds(waitedMs)}`;
|
|
73
|
-
why = stopped === "closed" ? `${subject} closed its output without printing the address to open, so it was stopped` : `${subject} was still running after ${seconds(waitedMs)} without printing the address to open, so it was stopped`;
|
|
74
|
+
why = stopped === "closed" ? `${subject} closed its output without printing the address to open, so it was stopped` : `${subject} was still running after ${seconds(waitedMs)} without printing the address to open, so it was stopped. AGENTRUN_START_TIMEOUT_MS sets a longer wait, in milliseconds`;
|
|
74
75
|
exit = `${was}; stopped with ${sent.length > 1 ? `${sent[0]}, then ${sent.slice(1).join(", then ")} ${seconds(STOP_GRACE_MS)} later` : sent[0]}; then ${ended}`;
|
|
75
76
|
} else if (signal !== null) {
|
|
76
77
|
why = `${subject} was ended by ${signal}${before}`;
|
|
@@ -157,8 +158,10 @@ export const SAID = /^(Boxes: |Set up this server: )/;
|
|
|
157
158
|
* hosts as an "Open " line's. Resolves undefined when the output ends
|
|
158
159
|
* without one. Until then, the last TAIL_LINES lines before it are kept in `seen`: what a start that fails shows, and each
|
|
159
160
|
* goes to `onBefore`. Every whole line after it goes to `onLine`; the rest of the output is read and dropped, so the
|
|
160
|
-
* server never blocks on a full pipe.
|
|
161
|
-
|
|
161
|
+
* server never blocks on a full pipe. A "Starting " line before it, whose URL is one an "Open " line may name, goes to
|
|
162
|
+
* `onStarting` with that URL, once: the server has bound its port and is still loading. */
|
|
163
|
+
export function openUrl(stdout, publicUrl, seen = [], onLine = () => {}, onBefore = () => {}, onStarting = () => {}) {
|
|
164
|
+
let starting;
|
|
162
165
|
const keep = (line) => {
|
|
163
166
|
onBefore(line);
|
|
164
167
|
seen.push(line);
|
|
@@ -181,6 +184,8 @@ export function openUrl(stdout, publicUrl, seen = [], onLine = () => {}, onBefor
|
|
|
181
184
|
else {
|
|
182
185
|
const named = /^AGENTRUN_BASE_URL=(\S+)$/.exec(line)?.[1];
|
|
183
186
|
if (named !== undefined && openLineUrl(`Open ${named}`, publicUrl) !== undefined) base = named;
|
|
187
|
+
const bound = starting === undefined && line.startsWith("Starting ") ? openLineUrl(`Open ${line.slice("Starting ".length)}`, publicUrl) : undefined;
|
|
188
|
+
if (bound !== undefined) onStarting((starting = bound));
|
|
184
189
|
keep(line);
|
|
185
190
|
}
|
|
186
191
|
}
|
|
@@ -438,7 +443,16 @@ export async function main(argv, env = process.env) {
|
|
|
438
443
|
const seen = [];
|
|
439
444
|
const bound = startTimeoutMs(env);
|
|
440
445
|
const TIMED_OUT = Symbol("timed out");
|
|
441
|
-
|
|
446
|
+
// A server that says Starting has bound its port and answers there, warming, while it loads: the bound is for a server
|
|
447
|
+
// that never gets that far, so it ends here, and the person is told the address at once (stderr; stdout waits for the
|
|
448
|
+
// "Open " line, which says it is ready).
|
|
449
|
+
let listening;
|
|
450
|
+
const onStarting = (address) => {
|
|
451
|
+
listening = address;
|
|
452
|
+
clearTimeout(timer);
|
|
453
|
+
console.error(`AgentRun is starting at ${address}: it listens there now, and opens once its store is ready.`);
|
|
454
|
+
};
|
|
455
|
+
const url = await Promise.race([openUrl(child.stdout, env.AGENTRUN_PUBLIC_URL, seen, tell, tell, onStarting), new Promise((resolve) => { timer = setTimeout(() => resolve(TIMED_OUT), bound); })]);
|
|
442
456
|
clearTimeout(timer);
|
|
443
457
|
if (url === undefined || url === TIMED_OUT) {
|
|
444
458
|
// Its stdout ended (it exited, was never started, or closed it), or the bound passed with it still running. A server
|
|
@@ -457,7 +471,7 @@ export async function main(argv, env = process.env) {
|
|
|
457
471
|
if (spawnError === undefined) await within(closed, 2_000);
|
|
458
472
|
errLines.end();
|
|
459
473
|
const failure = failureText({
|
|
460
|
-
step: spawnError !== undefined ? `start the server (${launcher})` : `wait for the server to print the address to open (at most ${seconds(bound)})`,
|
|
474
|
+
step: spawnError !== undefined ? `start the server (${launcher})` : listening !== undefined ? `wait for the server, listening at ${listening}, to be ready` : `wait for the server to print the address to open (at most ${seconds(bound)})`,
|
|
461
475
|
error: spawnError,
|
|
462
476
|
code: ended?.code ?? null,
|
|
463
477
|
signal: ended?.signal ?? null,
|