Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
doctor --host checks a Linux machine can run the server and its sandbox
milind-soni192357be91e7
diff --git a/docs/headless-cli.md b/docs/headless-cli.mdindex e2f69b968f..67ee5c654f 100644--- a/docs/headless-cli.md+++ b/docs/headless-cli.md@@ -59,6 +59,7 @@ redaction the transcript uses). Durations are written `90`, `90s`, `5m` or `2h`.| 4 | Timed out (the work keeps running) || 5 | Cannot reach the server, not allowed, or the server is too old || 6 | `team apply --check` found changes |+| 7 | `doctor --host`: this machine is missing something the server needs || 130 | Ctrl-C (the work keeps running) |## Commands@@ -70,6 +71,7 @@ one of its conversations.| Command | What it does ||---|---|| `doctor [--wait 2m]` | Checks the server answers, is new enough, who you are to it (and when your session expires), that an engine is ready, and whether bots have a browser. |+| `doctor --host` | Checks this Linux machine can run the server and the bots' sandbox (below). || `bots`, `channels`, `models` | Your bots and what each is doing, your rooms, the engines and the models each offers. || `messages TARGET [--limit 30]` | The latest messages of a conversation. || `send TARGET TEXT` | Sends one message and returns at once. `--send-id ID` makes a retry safe: the same id never sends twice. |@@ -87,6 +89,44 @@ one of its conversations.The message for `send` and `run` can be the next word, `--text TEXT`,`--message-file FILE`, or `-` to read it from stdin.+## doctor --host++Before you install a server, check the machine it will run on:++```text+$ sudo openmausbot doctor --host --data-dir /srv/mausbot+ok Ubuntu 24.04.1 LTS, kernel 6.8.0-45-generic+ok x86_64+ok Docker 27.3.1+FAIL Bot sandbox: AppArmor blocks unprivileged user namespaces+ fix: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 (and put it in /etc/sysctl.d/ to keep it after a reboot)+ok seccomp is available+ok cgroup v2+ok 412 GB free for /srv/mausbot+warn /srv/mausbot is not on an encrypted disk+ fix: use LUKS full-disk encryption, unless your provider encrypts the disk at rest+ok 8 CPUs, 31 GB memory (a team of 20 needs 8 CPUs and 16 GB)+ok Port 8799 is free for the server+ok Ports 80 and 443 are free+ok Clock is within 1 s of network time (signed requests allow 300 s)+1 problem, 1 warning.+```++It checks the system (Ubuntu 24.04 or 22.04, or Debian 12, are the ones we+test), the processor (x86_64; arm64 runs a server but not a self-hosted Team+server), Docker or Podman, that unprivileged user namespaces are allowed (the+AppArmor and Debian switches), seccomp, cgroup v2, free disk for the data+folder (`--data-dir`, else `OMB_DATA_DIR` or `~/.openmausbot`: at least 10 GB,+and 100 GB for a Team server), disk encryption, CPUs and memory (a Team needs+4 CPUs and 8 GB), the server's port (`--port`, else 8799), ports 80 and 443+(required with `--domain HOST`, else only a warning), and the clock against+network time (signed requests allow 300 seconds). It changes nothing.++A problem fails the check (exit 7) and says its fix on the next line; a+warning does not. `--json` prints `{ ok, problems, warnings, checks: [{ id,+status, message, fix }] }`. On macOS and Windows it says it checks Linux+servers, and exits 7.+## run and wait```shdiff --git a/server/cli-usage.ts b/server/cli-usage.tsindex 11b19eaf86..d96a2e5f09 100644--- a/server/cli-usage.ts+++ b/server/cli-usage.ts@@ -2,6 +2,7 @@ export { HEADLESS_VERBS as HEADLESS_VERB_NAMES } from "./headless/args.ts";export const HEADLESS_USAGE = `Drive a running workspace (scripts, CI, other agents):openmausbot doctor check the server answers and an engine is ready+ openmausbot doctor --host check this Linux machine can run a server (exit 7 if not)openmausbot bots | channels | models your bots, your rooms, the engines and their modelsopenmausbot run BOT "do this" give a bot one job and wait until it and every teammate it asked are doneopenmausbot send BOT "text" send one message and return at oncediff --git a/server/headless/args.ts b/server/headless/args.tsindex 0c9a396347..731a22afa7 100644--- a/server/headless/args.ts+++ b/server/headless/args.ts@@ -9,6 +9,8 @@ export const EXIT = {timeout: 4,unreachable: 5,changes: 6,+ /** `doctor --host`: this machine is missing something the server needs. */+ hostMissing: 7,interrupted: 130,} as const;@@ -54,7 +56,7 @@ const WAITING = {} satisfies ParseArgsOptionsConfig;const VERBS: Record<string, { options: ParseArgsOptionsConfig; positionals: number }> = {- doctor: { options: { wait: { type: "string" } }, positionals: 0 },+ doctor: { options: { wait: { type: "string" }, host: { type: "boolean" }, "data-dir": { type: "string" }, domain: { type: "string" } }, positionals: 0 },bots: { options: {}, positionals: 0 },channels: { options: {}, positionals: 0 },models: { options: {}, positionals: 0 },diff --git a/server/headless/commands.ts b/server/headless/commands.tsindex c4d803417d..b4ece740a9 100644--- a/server/headless/commands.ts+++ b/server/headless/commands.ts@@ -65,6 +65,11 @@ async function doctorOnce(ctx: VerbContext): Promise<VerbOutcome> {}export async function doctor(ctx: VerbContext): Promise<VerbOutcome> {+ if (ctx.flags.host === true) {+ if (flag(ctx.flags, "wait") !== undefined || flag(ctx.flags, "url") !== undefined) throw usageError("doctor --host checks this machine: drop --wait and --url");+ return (await import("./host-doctor.ts")).hostDoctor(ctx);+ }+ if (flag(ctx.flags, "data-dir") !== undefined || flag(ctx.flags, "domain") !== undefined) throw usageError("--data-dir and --domain go with doctor --host");const raw = flag(ctx.flags, "wait");const deadline = Date.now() + (raw ? parseDuration(raw, "--wait") : 0);for (;;) {diff --git a/server/headless/host-doctor.test.ts b/server/headless/host-doctor.test.tsnew file mode 100644index 0000000000..17b0c5ea26--- /dev/null+++ b/server/headless/host-doctor.test.ts@@ -0,0 +1,165 @@+import { describe, expect, it } from "vitest";++import type { VerbContext } from "./context.ts";+import { checkHost, hostDoctor, hostReport, listeningPorts, type CommandResult, type HostCheck, type HostProbe } from "./host-doctor.ts";+import type { HeadlessIo } from "./output.ts";+import { runHeadless } from "./main.ts";++const GB = 1_000_000_000;+// /proc/net/tcp rows: sl, local address (hex ip:port), remote, state (0A is LISTEN)+const tcp = (...ports: number[]) => [" sl local_address rem_address st", ...ports.map((port, index) =>+ ` ${index}: 00000000:${port.toString(16).toUpperCase().padStart(4, "0")} 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 1`)].join("\n");++/** A healthy Ubuntu 24.04 server; each test breaks one thing. */+function probe(overrides: { files?: Record<string, string | null>; lists?: Record<string, string[]>; commands?: Record<string, Partial<CommandResult>> } & Partial<HostProbe> = {}): HostProbe {+ const files: Record<string, string | null> = {+ "/etc/os-release": 'PRETTY_NAME="Ubuntu 24.04.1 LTS"\nID=ubuntu\nVERSION_ID="24.04"\n',+ "/proc/sys/kernel/apparmor_restrict_unprivileged_userns": "0\n",+ "/proc/self/status": "Name:\tnode\nSeccomp:\t0\nSeccomp_filters:\t0\n",+ "/sys/fs/cgroup/cgroup.controllers": "cpuset cpu io memory pids\n",+ "/proc/self/mountinfo": "22 1 253:1 / / rw,relatime - ext4 /dev/mapper/root rw\n30 22 8:2 / /boot rw - ext4 /dev/sda2 rw\n",+ "/sys/dev/block/253:1/dm/uuid": "LVM-abc\n",+ "/sys/class/block/dm-0/dev": "253:0\n",+ "/sys/dev/block/253:0/dm/uuid": "CRYPT-LUKS2-abc-sda3_crypt\n",+ "/proc/net/tcp": tcp(22),+ "/proc/net/tcp6": tcp(),+ ...overrides.files,+ };+ const lists: Record<string, string[]> = { "/proc/self/ns": ["mnt", "net", "user"], "/sys/dev/block/253:1/slaves": ["dm-0"], ...overrides.lists };+ const commands: Record<string, Partial<CommandResult>> = {+ docker: { ok: true, stdout: "27.3.1\n" }, podman: { missing: true }, timedatectl: { ok: true, stdout: "yes\n" }, ...overrides.commands,+ };+ const { files: _files, lists: _lists, commands: _commands, ...rest } = overrides;+ return {+ platform: "linux", arch: "x64", kernel: "6.8.0-45-generic", cpus: 8, memoryBytes: 32 * 2 ** 30,+ read: (path) => files[path] ?? null,+ list: (path) => lists[path] ?? [],+ run: async (command) => ({ ok: false, stdout: "", stderr: "", missing: false, ...commands[command] }),+ freeBytes: () => 412 * GB,+ clockOffset: async () => 200,+ serverAnswers: async () => false,+ ...rest,+ };+}++const OPTIONS = { dataDir: "/srv/mausbot", port: 8799 };+const byId = (checks: HostCheck[], id: string) => checks.find((check) => check.id === id);++describe("doctor --host", () => {+ it("passes a healthy server, one line per check", async () => {+ const report = hostReport(await checkHost(probe(), OPTIONS));+ expect(report.exitCode).toBe(0);+ expect(report.human).toEqual([+ "ok Ubuntu 24.04.1 LTS, kernel 6.8.0-45-generic",+ "ok x86_64",+ "ok Docker 27.3.1",+ "ok Unprivileged user namespaces are allowed",+ "ok seccomp is available",+ "ok cgroup v2",+ "ok 412 GB free for /srv/mausbot",+ "ok /srv/mausbot is on an encrypted disk",+ "ok 8 CPUs, 32 GB memory (a team of 20 needs 8 CPUs and 16 GB)",+ "ok Port 8799 is free for the server",+ "ok Ports 80 and 443 are free",+ "ok Clock is within 1 s of network time (signed requests allow 300 s)",+ "Ready.",+ ]);+ });++ it.each([+ ["AppArmor's switch", { files: { "/proc/sys/kernel/apparmor_restrict_unprivileged_userns": "1\n" } }, "userns", "kernel.apparmor_restrict_unprivileged_userns=0"],+ ["Debian's switch", { files: { "/proc/sys/kernel/unprivileged_userns_clone": "0\n" } }, "userns", "kernel.unprivileged_userns_clone=1"],+ ["a zero namespace limit", { files: { "/proc/sys/user/max_user_namespaces": "0\n" } }, "userns", "user.max_user_namespaces="],+ ["a kernel without user namespaces", { lists: { "/proc/self/ns": ["mnt", "net"] } }, "userns", "CONFIG_USER_NS"],+ ["no seccomp", { files: { "/proc/self/status": "Name:\tnode\n" } }, "seccomp", "CONFIG_SECCOMP_FILTER"],+ ["cgroup v1", { files: { "/sys/fs/cgroup/cgroup.controllers": null } }, "cgroup", "systemd.unified_cgroup_hierarchy=1"],+ ["no Docker or Podman", { commands: { docker: { missing: true }, podman: { missing: true } } }, "containers", "apt-get install -y docker.io"],+ ["a Docker daemon this user cannot reach", { commands: { docker: { stderr: "permission denied while trying to connect to the Docker daemon socket" } } }, "containers", "usermod -aG docker"],+ ["a stopped Docker daemon", { commands: { docker: { stderr: "Cannot connect to the Docker daemon. Is the docker daemon running?" } } }, "containers", "systemctl enable --now docker"],+ ["under 10 GB free", { freeBytes: () => 6 * GB }, "disk", "--data-dir"],+ ["under 2 GB memory", { memoryBytes: 1 * 2 ** 30 }, "size", "larger server"],+ ["a clock 10 minutes off", { clockOffset: async () => 600_000 }, "clock", "timedatectl set-ntp true"],+ ["a processor we build nothing for", { arch: "s390x" }, "arch", "x86_64"],+ ["the server's port taken by another program", { files: { "/proc/net/tcp": tcp(22, 8799) } }, "port", "--port N"],+ ] as const)("fails on %s (exit 7) and says the fix in one line", async (_name, overrides, id, fix) => {+ const checks = await checkHost(probe(overrides as Parameters<typeof probe>[0]), OPTIONS);+ expect(byId(checks, id)).toMatchObject({ status: "FAIL", fix: expect.stringContaining(fix) });+ expect(checks.filter((check) => check.status === "FAIL")).toHaveLength(1);+ const report = hostReport(checks);+ expect(report.exitCode).toBe(7);+ const at = report.human.findIndex((line) => line.startsWith("FAIL "));+ expect(report.human[at + 1]).toBe(` fix: ${byId(checks, id)!.fix}`);+ expect(report.human.at(-1)).toBe("1 problem.");+ });++ it("warns, and still passes, on what a standalone server can live with", async () => {+ const checks = await checkHost(probe({+ arch: "arm64", cpus: 2, memoryBytes: 4 * 2 ** 30, freeBytes: () => 40 * GB, clockOffset: async () => 45_000,+ files: { "/etc/os-release": 'PRETTY_NAME="Fedora Linux 40"\nID=fedora\nVERSION_ID=40\n', "/sys/dev/block/253:0/dm/uuid": null, "/proc/net/tcp": tcp(22, 443) },+ }), OPTIONS);+ expect(checks.filter((check) => check.status === "warn").map((check) => check.id).sort())+ .toEqual(["arch", "clock", "disk", "encryption", "size", "system", "web-ports"]);+ const report = hostReport(checks);+ expect(report.exitCode).toBe(0);+ expect(report.human.at(-1)).toBe("Ready, with 7 warnings.");+ expect(byId(checks, "clock")!.message).toBe("Clock is 45 s ahead of network time");+ });++ it("needs ports 80 and 443 for --domain, unless this server already answers", async () => {+ const taken = { files: { "/proc/net/tcp": tcp(22, 80, 8799), "/proc/net/tcp6": tcp(443) } };+ expect(byId(await checkHost(probe(taken), { ...OPTIONS, domain: "maus.example.com" }), "web-ports"))+ .toMatchObject({ status: "FAIL", message: "Ports 80 and 443 are taken, and --domain maus.example.com needs 80 and 443" });+ const ours = await checkHost(probe({ ...taken, serverAnswers: async () => true }), { ...OPTIONS, domain: "maus.example.com" });+ expect(byId(ours, "port")).toMatchObject({ status: "ok", message: "OpenMausBot already answers on port 8799" });+ expect(byId(ours, "web-ports")!.status).toBe("warn");+ });++ it("reads listening sockets from /proc/net, IPv4 and IPv6", () => {+ expect([...listeningPorts(probe({ files: { "/proc/net/tcp": tcp(22, 8799), "/proc/net/tcp6": tcp(443) } }))].sort((a, b) => a - b)).toEqual([22, 443, 8799]);+ });++ it("says when the clock cannot be compared, and passes when NTP keeps it", async () => {+ expect(byId(await checkHost(probe({ clockOffset: async () => null }), OPTIONS), "clock")!.status).toBe("ok");+ expect(byId(await checkHost(probe({ clockOffset: async () => null, commands: { timedatectl: { ok: true, stdout: "no\n" } } }), OPTIONS), "clock"))+ .toMatchObject({ status: "warn", fix: "sudo timedatectl set-ntp true" });+ });++ it("finds Podman when Docker is missing", async () => {+ const checks = await checkHost(probe({ commands: { docker: { missing: true }, podman: { ok: true, stdout: "4.9.3\n" } } }), OPTIONS);+ expect(byId(checks, "containers")).toEqual({ id: "containers", status: "ok", message: "Podman 4.9.3" });+ });++ it.each([["darwin", "macOS"], ["win32", "Windows"]] as const)("says it is for Linux servers on %s", async (platform, name) => {+ const report = hostReport(await checkHost(probe({ platform }), OPTIONS));+ expect(report.exitCode).toBe(7);+ expect(report.human[0]).toBe(`FAIL doctor --host checks a Linux server, and this is ${name}`);+ });++ it("takes the data folder, port and domain from its flags, else the environment", async () => {+ const seen: string[] = [];+ const watching = probe({ freeBytes: (path) => { seen.push(path); return 412 * GB; } });+ const ctx = (flags: Record<string, string | boolean>, env: NodeJS.ProcessEnv = {}) => ({ flags, env }) as unknown as VerbContext;+ await hostDoctor(ctx({ host: true }, { OMB_DATA_DIR: "/srv/from-env" }), watching);+ const flagged = await hostDoctor(ctx({ host: true, "data-dir": "/srv/mausbot", port: "9000", domain: "Maus.Example.com" }), probe({+ freeBytes: (path) => { seen.push(path); return 412 * GB; }, files: { "/proc/net/tcp": tcp(443, 9000) } }));+ expect(seen).toEqual(["/srv/from-env", "/srv/mausbot"]);+ expect((flagged.result as { checks: HostCheck[] }).checks.filter((check) => check.status === "FAIL").map((check) => check.message))+ .toEqual(["Port 9000 is taken by another program", "Port 443 is taken, and --domain maus.example.com needs 80 and 443"]);+ await expect(hostDoctor(ctx({ host: true, port: "99999" }), probe())).rejects.toMatchObject({ exitCode: 2 });+ });++ it("is doctor --host on the command line, and its flags belong to it", async () => {+ const io: HeadlessIo = { out: () => undefined, err: () => undefined, readStdin: async () => "" };+ expect(await runHeadless(["doctor", "--domain", "maus.example.com"], { io, env: {} })).toBe(2);+ expect(await runHeadless(["doctor", "--host", "--wait", "1m"], { io, env: {} })).toBe(2);+ });++ // Elsewhere it would probe this machine for real.+ it.skipIf(process.platform === "linux")("prints one JSON document saying it is for Linux, and exits 7", async () => {+ const out: string[] = [];+ const io: HeadlessIo = { out: (text) => out.push(text), err: () => undefined, readStdin: async () => "" };+ expect(await runHeadless(["doctor", "--host", "--json"], { io, env: {} })).toBe(7);+ expect(out).toHaveLength(1);+ expect(JSON.parse(out[0]!)).toMatchObject({ ok: false, problems: 1, checks: [{ id: "platform", status: "FAIL", fix: expect.any(String) }] });+ });+});diff --git a/server/headless/host-doctor.ts b/server/headless/host-doctor.tsnew file mode 100644index 0000000000..1026e36302--- /dev/null+++ b/server/headless/host-doctor.ts@@ -0,0 +1,284 @@+// `doctor --host`: can this Linux machine run the server and the bots' sandbox? It only looks: files under /proc and /sys,+// version queries to docker, podman and timedatectl, the sockets already listening, and one HEAD request for the time.+import { execFile } from "node:child_process";+import { existsSync, readdirSync, readFileSync, statfsSync } from "node:fs";+import { arch, cpus, homedir, release, totalmem } from "node:os";+import { dirname, join, resolve } from "node:path";++import { PRODUCTION_CLOUD_ORIGIN } from "../devs-report-send.ts";+import { EXIT, flag, usageError } from "./args.ts";+import type { VerbContext, VerbOutcome } from "./context.ts";++export type HostStatus = "ok" | "warn" | "FAIL";++export interface HostCheck {+ id: string;+ status: HostStatus;+ message: string;+ fix?: string;+}++export interface CommandResult {+ ok: boolean;+ stdout: string;+ stderr: string;+ /** The command is not installed. */+ missing: boolean;+}++export interface HostProbe {+ platform: NodeJS.Platform;+ arch: string;+ kernel: string;+ cpus: number;+ memoryBytes: number;+ /** A file's text, or null when it is missing or unreadable. */+ read(path: string): string | null;+ list(path: string): string[];+ run(command: string, args: string[]): Promise<CommandResult>;+ /** Free bytes for an unprivileged user on the disk that holds `path` (or its nearest existing parent). */+ freeBytes(path: string): number | null;+ /** This clock minus network time, in ms, or null when no time server answered. */+ clockOffset(): Promise<number | null>;+ serverAnswers(port: number): Promise<boolean>;+}++export interface HostOptions {+ dataDir: string;+ port: number;+ domain?: string;+}++const GB = 1_000_000_000;+const SIGNED_REQUEST_SKEW_S = 300;+const NTP_FIX = "sudo timedatectl set-ntp true";++const ok = (id: string, message: string): HostCheck => ({ id, status: "ok", message });+const warn = (id: string, message: string, fix?: string): HostCheck => ({ id, status: "warn", message, ...(fix ? { fix } : {}) });+const fail = (id: string, message: string, fix: string): HostCheck => ({ id, status: "FAIL", message, fix });++function osRelease(probe: HostProbe): Record<string, string> {+ const text = probe.read("/etc/os-release") ?? probe.read("/usr/lib/os-release") ?? "";+ return Object.fromEntries(text.split("\n").map((line) => /^([A-Z_]+)=(.*)$/.exec(line.trim())).filter((match) => match !== null)+ .map((match) => [match[1]!, match[2]!.replace(/^"(.*)"$/, "$1")]));+}++function systemCheck(probe: HostProbe): HostCheck {+ const os = osRelease(probe);+ const name = os.PRETTY_NAME || "An unknown Linux";+ const tested = (os.ID === "ubuntu" && ["22.04", "24.04"].includes(os.VERSION_ID ?? "")) || (os.ID === "debian" && os.VERSION_ID === "12");+ const line = `${name}, kernel ${probe.kernel}`;+ return tested ? ok("system", line) : warn("system", `${line}: not a system we test (Ubuntu 24.04 or 22.04, or Debian 12)`);+}++function archCheck(probe: HostProbe): HostCheck {+ if (probe.arch === "x64") return ok("arch", "x86_64");+ if (probe.arch === "arm64") return warn("arch", "arm64: the server runs here, but a self-hosted Team server is supported on x86_64 only");+ return fail("arch", `${probe.arch}: OpenMausBot's images are built for x86_64 and arm64 only`, "use an x86_64 server");+}++async function containerCheck(probe: HostProbe): Promise<HostCheck> {+ const docker = await probe.run("docker", ["version", "--format", "{{.Server.Version}}"]);+ if (docker.ok && docker.stdout.trim()) return ok("containers", `Docker ${docker.stdout.trim()}`);+ if (!docker.missing) {+ return /permission denied/i.test(docker.stderr)+ ? fail("containers", "Docker is installed, but this user cannot reach its daemon", "run as root, or add the user to the docker group: sudo usermod -aG docker $USER")+ : fail("containers", "Docker is installed, but its daemon is not running", "sudo systemctl enable --now docker");+ }+ const podman = await probe.run("podman", ["version", "--format", "{{.Version}}"]);+ if (podman.ok && podman.stdout.trim()) return ok("containers", `Podman ${podman.stdout.trim()}`);+ if (!podman.missing) return fail("containers", "Podman is installed, but does not answer", "podman info names the problem; for a rootless Podman, check /etc/subuid");+ return fail("containers", "Neither Docker nor Podman is installed", "sudo apt-get install -y docker.io (or podman)");+}++function userNamespaceCheck(probe: HostProbe): HostCheck {+ const sysctl = (name: string) => probe.read(`/proc/sys/${name.replaceAll(".", "/")}`)?.trim();+ const keep = (setting: string) => `sudo sysctl -w ${setting} (and put it in /etc/sysctl.d/ to keep it after a reboot)`;+ if (!probe.list("/proc/self/ns").includes("user")) {+ return fail("userns", "Bot sandbox: this kernel has no user namespaces", "use a stock Ubuntu or Debian kernel (CONFIG_USER_NS)");+ }+ if (sysctl("kernel.apparmor_restrict_unprivileged_userns") === "1") {+ return fail("userns", "Bot sandbox: AppArmor blocks unprivileged user namespaces", keep("kernel.apparmor_restrict_unprivileged_userns=0"));+ }+ if (sysctl("kernel.unprivileged_userns_clone") === "0") {+ return fail("userns", "Bot sandbox: unprivileged user namespaces are turned off", keep("kernel.unprivileged_userns_clone=1"));+ }+ if (sysctl("user.max_user_namespaces") === "0") {+ return fail("userns", "Bot sandbox: user namespaces are limited to none", keep("user.max_user_namespaces=15000"));+ }+ return ok("userns", "Unprivileged user namespaces are allowed");+}++function seccompCheck(probe: HostProbe): HostCheck {+ return /^Seccomp:\s*\d/m.test(probe.read("/proc/self/status") ?? "")+ ? ok("seccomp", "seccomp is available")+ : fail("seccomp", "Bot sandbox: this kernel has no seccomp", "use a stock Ubuntu or Debian kernel (CONFIG_SECCOMP_FILTER)");+}++function cgroupCheck(probe: HostProbe): HostCheck {+ return probe.read("/sys/fs/cgroup/cgroup.controllers") !== null+ ? ok("cgroup", "cgroup v2")+ : fail("cgroup", "Only cgroup v1 is mounted; the bot box needs cgroup v2", "boot with systemd.unified_cgroup_hierarchy=1 (the default since Ubuntu 21.10 and Debian 11)");+}++function diskCheck(probe: HostProbe, dataDir: string): HostCheck {+ const free = probe.freeBytes(dataDir);+ if (free === null) return warn("disk", `Could not read the free space for ${dataDir}`);+ const shown = `${Math.floor(free / GB)} GB free for ${dataDir}`;+ if (free < 10 * GB) return fail("disk", `${shown}; the server needs at least 10 GB`, "free space on that disk, or pass --data-dir on a larger one");+ if (free < 100 * GB) return warn("disk", `${shown}; a Team server needs 100 GB`, "grow the disk before a team moves in");+ return ok("disk", shown);+}++/** The block device under `dataDir`, then every device it sits on: a dm-crypt mapping among them is an encrypted disk. */+function encryptedCheck(probe: HostProbe, dataDir: string): HostCheck {+ const mounts = (probe.read("/proc/self/mountinfo") ?? "").split("\n").map((line) => line.split(" ")).filter((fields) => fields.length > 4);+ const path = resolve(dataDir);+ const mount = mounts.filter(([, , , , point]) => path === point || path.startsWith(point === "/" ? "/" : `${point}/`))+ .sort((a, b) => b[4]!.length - a[4]!.length)[0];+ if (!mount || mount[2]!.startsWith("0:")) return warn("encryption", `Could not tell whether ${dataDir} is on an encrypted disk`);+ const seen = new Set<string>();+ const encrypted = (device: string): boolean => {+ if (seen.has(device)) return false;+ seen.add(device);+ if ((probe.read(`/sys/dev/block/${device}/dm/uuid`) ?? "").startsWith("CRYPT-")) return true;+ return probe.list(`/sys/dev/block/${device}/slaves`).some((slave) => {+ const dev = probe.read(`/sys/class/block/${slave}/dev`)?.trim();+ return dev ? encrypted(dev) : false;+ });+ };+ return encrypted(mount[2]!)+ ? ok("encryption", `${dataDir} is on an encrypted disk`)+ : warn("encryption", `${dataDir} is not on an encrypted disk`, "use LUKS full-disk encryption, unless your provider encrypts the disk at rest");+}++function sizeCheck(probe: HostProbe): HostCheck {+ const memory = Math.round(probe.memoryBytes / 2 ** 30);+ const line = `${probe.cpus} CPUs, ${memory} GB memory`;+ if (probe.memoryBytes < 2 * 2 ** 30) return fail("size", `${line}; the server needs at least 2 GB`, "use a larger server");+ if (probe.cpus < 4 || probe.memoryBytes < 7.5 * 2 ** 30) return warn("size", `${line}; a Team server needs at least 4 CPUs and 8 GB`, "use a larger server for a team");+ return ok("size", `${line} (a team of 20 needs 8 CPUs and 16 GB)`);+}++/** Listening TCP ports, from /proc/net/tcp and tcp6: state 0A is LISTEN. */+export function listeningPorts(probe: HostProbe): Set<number> {+ const ports = new Set<number>();+ for (const table of ["/proc/net/tcp", "/proc/net/tcp6"]) {+ for (const line of (probe.read(table) ?? "").split("\n").slice(1)) {+ const [, local, , state] = line.trim().split(/\s+/);+ if (state === "0A" && local) ports.add(Number.parseInt(local.split(":").at(-1)!, 16));+ }+ }+ return ports;+}++async function portChecks(probe: HostProbe, options: HostOptions): Promise<HostCheck[]> {+ const taken = listeningPorts(probe);+ const ours = taken.has(options.port) && await probe.serverAnswers(options.port);+ const server = !taken.has(options.port) ? ok("port", `Port ${options.port} is free for the server`)+ : ours ? ok("port", `OpenMausBot already answers on port ${options.port}`)+ : fail("port", `Port ${options.port} is taken by another program`, `stop it (sudo ss -ltnp 'sport = :${options.port}' names it), or run the server with --port N`);+ const web = [80, 443].filter((port) => taken.has(port));+ if (!web.length) return [server, ok("web-ports", "Ports 80 and 443 are free")];+ const which = web.length === 2 ? "Ports 80 and 443 are" : `Port ${web[0]} is`;+ const named = `sudo ss -ltnp 'sport = :${web[0]}' names it`;+ if (ours) return [server, warn("web-ports", `${which} in use: by this server's Caddy if it serves --domain, else by another program`, named)];+ return [server, options.domain+ ? fail("web-ports", `${which} taken, and --domain ${options.domain} needs 80 and 443`, `stop that program (${named}), or use --tunnel instead`)+ : warn("web-ports", `${which} taken: serving on your own domain needs 80 and 443 (a tunnel or Tailscale does not)`, named)];+}++async function clockCheck(probe: HostProbe): Promise<HostCheck> {+ const [offset, ntp] = await Promise.all([probe.clockOffset(), probe.run("timedatectl", ["show", "-p", "NTPSynchronized", "--value"])]);+ const synced = ntp.ok ? ntp.stdout.trim() === "yes" : null;+ if (offset === null) {+ return synced ? ok("clock", "Clock is kept synchronised (network time could not be reached to compare)")+ : warn("clock", synced === false ? "Clock is not kept synchronised, and network time could not be reached" : "Could not check the clock", NTP_FIX);+ }+ const seconds = Math.abs(offset) / 1_000;+ const off = seconds < 1.5 ? "within 1 s of network time" : `${Math.round(seconds)} s ${offset > 0 ? "ahead of" : "behind"} network time`;+ if (seconds > SIGNED_REQUEST_SKEW_S) return fail("clock", `Clock is ${off}; signed requests allow ${SIGNED_REQUEST_SKEW_S} s`, NTP_FIX);+ if (seconds > 30 || synced === false) return warn("clock", `Clock is ${off}${synced === false ? ", and not kept synchronised" : ""}`, NTP_FIX);+ return ok("clock", `Clock is ${off} (signed requests allow ${SIGNED_REQUEST_SKEW_S} s)`);+}++export async function checkHost(probe: HostProbe, options: HostOptions): Promise<HostCheck[]> {+ if (probe.platform !== "linux") {+ const name = probe.platform === "darwin" ? "macOS" : probe.platform === "win32" ? "Windows" : probe.platform;+ return [fail("platform", `doctor --host checks a Linux server, and this is ${name}`, "run it on the Linux server that will host OpenMausBot")];+ }+ const [containers, ports, clock] = await Promise.all([containerCheck(probe), portChecks(probe, options), clockCheck(probe)]);+ return [systemCheck(probe), archCheck(probe), containers, userNamespaceCheck(probe), seccompCheck(probe), cgroupCheck(probe),+ diskCheck(probe, options.dataDir), encryptedCheck(probe, options.dataDir), sizeCheck(probe), ...ports, clock];+}++export function hostReport(checks: readonly HostCheck[]): { result: Record<string, unknown>; exitCode: number; human: string[] } {+ const problems = checks.filter((check) => check.status === "FAIL").length;+ const warnings = checks.filter((check) => check.status === "warn").length;+ const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? "" : "s"}`;+ return {+ result: { ok: problems === 0, problems, warnings, checks },+ exitCode: problems ? EXIT.hostMissing : EXIT.done,+ human: [+ ...checks.flatMap((check) => [`${check.status.padEnd(6)}${check.message}`, ...(check.fix && check.status !== "ok" ? [` fix: ${check.fix}`] : [])]),+ problems ? `${plural(problems, "problem")}${warnings ? `, ${plural(warnings, "warning")}` : ""}.` : `Ready${warnings ? `, with ${plural(warnings, "warning")}` : ""}.`,+ ],+ };+}++function run(command: string, args: string[]): Promise<CommandResult> {+ return new Promise((done) => {+ execFile(command, args, { timeout: 10_000, env: { ...process.env, LC_ALL: "C" } }, (error, stdout, stderr) => {+ done({ ok: !error, stdout: String(stdout), stderr: String(stderr), missing: (error as NodeJS.ErrnoException | null)?.code === "ENOENT" });+ });+ });+}++export function systemProbe(): HostProbe {+ const read = (path: string) => { try { return readFileSync(path, "utf8"); } catch { return null; } };+ return {+ platform: process.platform, arch: arch(), kernel: release(), cpus: cpus().length, memoryBytes: totalmem(),+ read,+ list: (path) => { try { return readdirSync(path); } catch { return []; } },+ run,+ freeBytes(path) {+ let at = resolve(path);+ while (!existsSync(at) && dirname(at) !== at) at = dirname(at);+ try {+ const stats = statfsSync(at);+ return Number(stats.bavail) * Number(stats.bsize);+ } catch {+ return null;+ }+ },+ async clockOffset() {+ try {+ const before = Date.now();+ const response = await fetch(PRODUCTION_CLOUD_ORIGIN, { method: "HEAD", redirect: "manual", signal: AbortSignal.timeout(5_000) });+ const after = Date.now();+ const date = Date.parse(response.headers.get("date") ?? "");+ // An HTTP date is whole seconds: the server's clock was somewhere in the second after it.+ return Number.isFinite(date) ? (before + after) / 2 - (date + 500) : null;+ } catch {+ return null;+ }+ },+ async serverAnswers(port) {+ try {+ const response = await fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(2_000) });+ return ((await response.json()) as { app?: unknown }).app === "openmausbot";+ } catch {+ return false;+ }+ },+ };+}++export async function hostDoctor(ctx: VerbContext, probe: HostProbe = systemProbe()): Promise<VerbOutcome> {+ const rawPort = flag(ctx.flags, "port") ?? ctx.env.OMB_PORT ?? "8799";+ const port = Number(rawPort);+ if (!Number.isInteger(port) || port < 1 || port > 65_535) throw usageError("--port must be 1-65535");+ const dataDir = resolve(flag(ctx.flags, "data-dir") ?? ctx.env.OMB_DATA_DIR ?? join(homedir(), ".openmausbot"));+ const domain = flag(ctx.flags, "domain")?.trim().toLowerCase();+ return hostReport(await checkHost(probe, { dataDir, port, ...(domain ? { domain } : {}) }));+}diff --git a/server/headless/main.ts b/server/headless/main.tsindex d3f9698581..f5e29161bf 100644--- a/server/headless/main.ts+++ b/server/headless/main.ts@@ -17,7 +17,11 @@ const T = "TARGET is a bot or room by name or id, or --bot ID, --channel ID, --texport const VERB_HELP: Record<string, string> = {doctor: `openmausbot doctor [--wait DURATION]Check the server answers, is new enough, says who you are to it, and has an engine ready.- --wait 2m keeps checking until it is ready. Exit 0 ready, 1 no engine, 5 unreachable or too old.`,+ --wait 2m keeps checking until it is ready. Exit 0 ready, 1 no engine, 5 unreachable or too old.+openmausbot doctor --host [--data-dir DIR] [--port 8799] [--domain HOST]+ Check this Linux machine can run the server and the bots' sandbox: the system, Docker or Podman, user+ namespaces, seccomp, cgroup v2, free disk, size, ports and the clock. Each problem says its fix.+ Exit 0 ready (warnings allowed), 7 something is missing. On macOS and Windows it says it is for Linux.`,bots: "openmausbot bots\n Your bots and what each is doing.",channels: "openmausbot channels\n Your rooms (group chats) and who is in them.",models: "openmausbot models\n The engines and the models each offers (use them as INSTANCE/MODEL).",