Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
VPS: optional wake script resumes a host that pauses when idle
AdityaUmale6aa2fb9ab1a0
diff --git a/docs/byo-vps.md b/docs/byo-vps.mdindex 88e060969d..5e61a536b3 100644--- a/docs/byo-vps.md+++ b/docs/byo-vps.md@@ -110,6 +110,22 @@ it goes ahead, and the app says what may be left on that server and the commandis back. (Changing the default alias still waits until its server can be listed.) Any alias from your`~/.ssh/config`, host key already verified by hand, is all it takes. A new bot starts on the default server.+### A server that pauses when idle++Some cloud boxes pause after a while without traffic and refuse SSH until they are resumed. On macOS and Linux+you can give the app a wake step: put an executable script named `wake` in the app's SSH folder+(`~/.openmausbot/ssh/wake`, or `ssh/wake` in your data directory). When a server cannot be reached, the app+runs it once with the alias as its only argument (`wake my-vps`), then tries the connection once more. Make the+script resume the box with your provider's command or API and return once the server accepts SSH again; it gets+up to two minutes. If it exits with an error, the app shows that error next to the SSH one. Without the file+nothing changes. Only someone who can write to the data directory can add it; nothing in the app sets it.++```sh+#!/bin/sh+# ~/.openmausbot/ssh/wake: $1 is the SSH alias the app could not reach.+my-provider resume "$1" && my-provider wait-ready "$1"+```+**Host key first, by hand.** Connect once manually before pointing OpenMausBot at the alias:```shdiff --git a/server/vps-ssh-wake.test.ts b/server/vps-ssh-wake.test.tsnew file mode 100644index 0000000000..a6a1859666--- /dev/null+++ b/server/vps-ssh-wake.test.ts@@ -0,0 +1,78 @@+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { ensureVpsSshMaster, prepareVpsSsh, VPS_SSH_DIR, VPS_WAKE_SCRIPT } from "./vps-ssh.ts";++const roots: string[] = [];+afterEach(() => {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });+});++/** A host that refuses SSH until something creates its `awake` file, as a box paused when idle does until resumed. */+function pausedHost() {+ const root = mkdtempSync(join(tmpdir(), "omb-vps-wake-"));+ roots.push(root);+ const bin = join(root, "bin");+ const data = join(root, "data");+ mkdirSync(bin);+ mkdirSync(data);+ const awake = join(root, "awake");+ const calls = join(root, "calls");+ writeFileSync(join(bin, "ssh"), [+ "#!/bin/sh",+ `echo "$*" >> '${calls}'`,+ 'case " $* " in *" check "*) exit 255;; esac',+ `[ -f '${awake}' ] && exit 0`,+ "echo 'ssh: connect to host paused.example port 22: Connection refused' >&2",+ "exit 255",+ "",+ ].join("\n"), { mode: 0o700 });+ const ssh = prepareVpsSsh(data, bin, "linux");+ const wakePath = join(data, VPS_SSH_DIR, VPS_WAKE_SCRIPT);+ const sshCalls = () => existsSync(calls) ? readFileSync(calls, "utf8").trim().split("\n") : [];+ return {+ ssh, awake,+ wakeWith: (body: string, mode = 0o700) => writeFileSync(wakePath, `#!/bin/sh\n${body}\n`, { mode }),+ connectAttempts: () => sshCalls().filter((line) => line.endsWith(" true")).length,+ };+}++describe.skipIf(process.platform === "win32")("VPS wake script", () => {+ it("without a wake script, an unreachable host fails as before", async () => {+ const host = pausedHost();+ await expect(ensureVpsSshMaster(host.ssh, "paused-vps")).rejects.toThrow("Connection refused");+ expect(host.connectAttempts()).toBe(1);+ });++ it("runs the wake script with the alias when the host can't be reached, then connects", async () => {+ const host = pausedHost();+ host.wakeWith(`echo "$1" > '${host.awake}'`);+ await expect(ensureVpsSshMaster(host.ssh, "paused-vps")).resolves.toBeUndefined();+ expect(readFileSync(host.awake, "utf8").trim()).toBe("paused-vps");+ expect(host.connectAttempts()).toBe(2);+ });++ it("does not run the wake script for a host that answers", async () => {+ const host = pausedHost();+ writeFileSync(host.awake, "already up");+ host.wakeWith(`echo woken > '${host.awake}'`);+ await ensureVpsSshMaster(host.ssh, "awake-vps");+ expect(readFileSync(host.awake, "utf8")).toBe("already up");+ expect(host.connectAttempts()).toBe(1);+ });++ it("says when the wake script itself fails, and does not try again", async () => {+ const host = pausedHost();+ host.wakeWith("echo 'box not found' >&2; exit 3");+ await expect(ensureVpsSshMaster(host.ssh, "paused-vps")).rejects.toThrow(/Connection refused; the wake script failed: box not found/);+ expect(host.connectAttempts()).toBe(1);+ });++ it("ignores a wake file that is not executable", async () => {+ const host = pausedHost();+ host.wakeWith(`echo "$1" > '${host.awake}'`, 0o600);+ await expect(ensureVpsSshMaster(host.ssh, "paused-vps")).rejects.toThrow("Connection refused");+ expect(existsSync(host.awake)).toBe(false);+ });+});diff --git a/server/vps-ssh.ts b/server/vps-ssh.tsindex 6a27d61cce..eea5f724ae 100644--- a/server/vps-ssh.ts+++ b/server/vps-ssh.ts@@ -3,9 +3,11 @@ import { execFile } from "node:child_process";import { createHash } from "node:crypto";import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";import { homedir } from "node:os";-import { delimiter, join, resolve } from "node:path";+import { delimiter, dirname, join, resolve } from "node:path";export const VPS_SSH_DIR = "ssh";+/** The person's optional wake script in the data folder's ssh directory, e.g. to resume a host that pauses when idle. */+export const VPS_WAKE_SCRIPT = "wake";function shellQuote(value: string): string {return `'${value.replace(/'/g, "'\\''")}'`;@@ -91,18 +93,34 @@ export function prepareVpsSsh(dataDir: string, pathValue: string, platform: Node}const MASTER_INITIALIZATION_TIMEOUT_MS = 30_000;+// Long enough to resume a paused cloud box; the script should return once the host takes SSH again.+const WAKE_TIMEOUT_MS = 120_000;const pendingMasters = new Map<string, Promise<void>>();+/** The wake script, when the person has put an executable one there. */+function vpsWakeScript(ssh: VpsSshSetup): string | null {+ if (!ssh.configPath) return null;+ const path = join(dirname(ssh.configPath), VPS_WAKE_SCRIPT);+ try {+ const stat = statSync(path);+ return stat.isFile() && (stat.mode & 0o111) !== 0 ? path : null;+ } catch {+ return null;+ }+}+export async function ensureVpsSshMaster(ssh: VpsSshSetup, alias: string, timeoutMs = MASTER_INITIALIZATION_TIMEOUT_MS): Promise<void> {if (!ssh.configPath) return;const key = `${ssh.configPath}:${alias}`;+ const wake = vpsWakeScript(ssh);+ const wakeBudget = wake ? WAKE_TIMEOUT_MS : 0;let pending = pendingMasters.get(key);if (!pending) {- const deadline = Date.now() + MASTER_INITIALIZATION_TIMEOUT_MS;- const command = (args: string[]) => new Promise<void>((resolve, reject) => {+ const deadline = Date.now() + MASTER_INITIALIZATION_TIMEOUT_MS + wakeBudget;+ const command = (args: string[], file = "ssh") => new Promise<void>((resolve, reject) => {const remaining = deadline - Date.now();if (remaining <= 0) { reject(new Error("VPS SSH initialization timed out")); return; }- const child = execFile("ssh", args, {+ const child = execFile(file, args, {env: { ...process.env, PATH: ssh.path },timeout: remaining,killSignal: "SIGKILL",@@ -120,7 +138,17 @@ export async function ensureVpsSshMaster(ssh: VpsSshSetup, alias: string, timeoucatch (error) {if ((error as { killed?: boolean }).killed) throw error;// ControlMaster auto only shares after authentication. A harmless first command starts the persistent master without replaying Docker work.- await command(["-o", "BatchMode=yes", "-o", "PermitLocalCommand=no", "-T", "--", alias, "true"]);+ const connect = () => command(["-o", "BatchMode=yes", "-o", "PermitLocalCommand=no", "-T", "--", alias, "true"]);+ try { await connect(); }+ catch (unreachable) {+ if (!wake || (unreachable as { killed?: boolean }).killed) throw unreachable;+ // A host that pauses when idle refuses SSH until resumed: wake it once, then try once more.+ try { await command([alias], wake); }+ catch (failure) {+ throw new Error(`${(unreachable as Error).message}; the wake script failed: ${(failure as Error).message}`);+ }+ await connect();+ }}})().finally(() => {if (pendingMasters.get(key) === pending) pendingMasters.delete(key);@@ -130,7 +158,7 @@ export async function ensureVpsSshMaster(ssh: VpsSshSetup, alias: string, timeoulet timer: ReturnType<typeof setTimeout> | undefined;try {await Promise.race([pending, new Promise<never>((_resolve, reject) => {- timer = setTimeout(() => reject(new Error("VPS SSH initialization timed out")), timeoutMs);+ timer = setTimeout(() => reject(new Error("VPS SSH initialization timed out")), timeoutMs + wakeBudget);timer.unref();})]);} finally { clearTimeout(timer); }