Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
VPS wake: cap the wake script at 120 s and keep its time out of the Docker command timeout
AdityaUmalef53f9b213cbf
diff --git a/server/vps-command.ts b/server/vps-command.tsindex 7cbd14c665..04c3cdbc03 100644--- a/server/vps-command.ts+++ b/server/vps-command.ts@@ -43,9 +43,10 @@ function tailCollector() {export async function defaultRunner(args: string[], options: VpsCommandOptions = {}): Promise<{ stdout: string; stderr: string }> {const ssh = prepareVpsSsh(DATA_DIR, augmentedPath());- const deadline = Date.now() + (options.timeoutMs ?? 120_000);+ let deadline = Date.now() + (options.timeoutMs ?? 120_000);const destination = args[0] === "-H" && args[1]?.startsWith("ssh://") ? args[1].slice(6) : null;- if (destination) await ensureVpsSshMaster(ssh, destination, Math.min(30_000, deadline - Date.now()));+ // Time spent waking a paused host does not count against the command's own timeout.+ if (destination) deadline += await ensureVpsSshMaster(ssh, destination, Math.min(30_000, deadline - Date.now()));if (Date.now() >= deadline) throw new Error("Docker-over-SSH command timed out");return new Promise((resolve, reject) => {// Docker's SSH transport runs the first `ssh` on PATH: the app's shim, which shares one connection.diff --git a/server/vps-computer.test.ts b/server/vps-computer.test.tsindex 5e5c9a3445..143b50457b 100644--- a/server/vps-computer.test.ts+++ b/server/vps-computer.test.ts@@ -15,7 +15,7 @@ vi.mock("node:child_process", async () => ({vi.mock("./vps-ssh.ts", async () => ({...(await vi.importActual<typeof import("./vps-ssh.ts")>("./vps-ssh.ts")),- ensureVpsSshMaster: vi.fn().mockResolvedValue(undefined),+ ensureVpsSshMaster: vi.fn().mockResolvedValue(0),}));import {diff --git a/server/vps-ssh-wake.test.ts b/server/vps-ssh-wake.test.tsindex a6a1859666..fed43175ba 100644--- a/server/vps-ssh-wake.test.ts+++ b/server/vps-ssh-wake.test.ts@@ -48,7 +48,7 @@ describe.skipIf(process.platform === "win32")("VPS wake script", () => {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();+ await expect(ensureVpsSshMaster(host.ssh, "paused-vps")).resolves.toBeGreaterThanOrEqual(0);expect(readFileSync(host.awake, "utf8").trim()).toBe("paused-vps");expect(host.connectAttempts()).toBe(2);});@@ -57,7 +57,7 @@ describe.skipIf(process.platform === "win32")("VPS wake script", () => {const host = pausedHost();writeFileSync(host.awake, "already up");host.wakeWith(`echo woken > '${host.awake}'`);- await ensureVpsSshMaster(host.ssh, "awake-vps");+ await expect(ensureVpsSshMaster(host.ssh, "awake-vps")).resolves.toBe(0);expect(readFileSync(host.awake, "utf8")).toBe("already up");expect(host.connectAttempts()).toBe(1);});@@ -69,6 +69,22 @@ describe.skipIf(process.platform === "win32")("VPS wake script", () => {expect(host.connectAttempts()).toBe(1);});+ it("reports the time the wake script took, so the caller's command timeout does not count it", async () => {+ const host = pausedHost();+ host.wakeWith(`PATH=/usr/bin:/bin; sleep 0.4; echo up > '${host.awake}'`);+ await expect(ensureVpsSshMaster(host.ssh, "paused-vps")).resolves.toBeGreaterThanOrEqual(350);+ });++ it("stops a wake script that runs past its own limit", async () => {+ const host = pausedHost();+ host.wakeWith(`PATH=/usr/bin:/bin; sleep 5; echo up > '${host.awake}'`);+ const started = Date.now();+ await expect(ensureVpsSshMaster(host.ssh, "paused-vps", 30_000, 300)).rejects.toThrow(/the wake script failed: VPS SSH initialization timed out/);+ expect(Date.now() - started).toBeLessThan(4_000);+ expect(existsSync(host.awake)).toBe(false);+ 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);diff --git a/server/vps-ssh.test.ts b/server/vps-ssh.test.tsindex 26034a9501..a1ac31ee15 100644--- a/server/vps-ssh.test.ts+++ b/server/vps-ssh.test.ts@@ -22,7 +22,7 @@ describe("VPS SSH connection sharing supplied by the app", () => {it("does nothing on Windows, where OpenSSH has no connection sharing", async () => {const data = scratch();expect(prepareVpsSsh(data, "C:\\Windows\\System32", "win32")).toEqual({ configPath: null, path: "C:\\Windows\\System32" });- await expect(ensureVpsSshMaster({ configPath: null, path: "missing-ssh" }, "fixture-vps")).resolves.toBeUndefined();+ await expect(ensureVpsSshMaster({ configPath: null, path: "missing-ssh" }, "fixture-vps")).resolves.toBe(0);expect(existsSync(join(data, "ssh"))).toBe(false);});});diff --git a/server/vps-ssh.ts b/server/vps-ssh.tsindex eea5f724ae..ebfa26d5aa 100644--- a/server/vps-ssh.ts+++ b/server/vps-ssh.ts@@ -95,7 +95,9 @@ export function prepareVpsSsh(dataDir: string, pathValue: string, platform: Nodeconst 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>>();+// Kept back from the wake script so the connection retry after it still has time (ssh's ConnectTimeout is 10 s).+const WAKE_RETRY_RESERVE_MS = 15_000;+const pendingMasters = new Map<string, Promise<number>>();/** The wake script, when the person has put an executable one there. */function vpsWakeScript(ssh: VpsSshSetup): string | null {@@ -109,16 +111,25 @@ function vpsWakeScript(ssh: VpsSshSetup): string | null {}}-export async function ensureVpsSshMaster(ssh: VpsSshSetup, alias: string, timeoutMs = MASTER_INITIALIZATION_TIMEOUT_MS): Promise<void> {- if (!ssh.configPath) return;+/**+ * Starts (or reuses) the shared SSH connection to the alias. Resolves with the milliseconds spent running the wake+ * script (0 when it did not run), so callers can keep that time out of their own command deadline.+ */+export async function ensureVpsSshMaster(+ ssh: VpsSshSetup,+ alias: string,+ timeoutMs = MASTER_INITIALIZATION_TIMEOUT_MS,+ wakeTimeoutMs = WAKE_TIMEOUT_MS,+): Promise<number> {+ if (!ssh.configPath) return 0;const key = `${ssh.configPath}:${alias}`;const wake = vpsWakeScript(ssh);- const wakeBudget = wake ? WAKE_TIMEOUT_MS : 0;+ const wakeBudget = wake ? wakeTimeoutMs : 0;let pending = pendingMasters.get(key);if (!pending) {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();+ const command = (args: string[], file = "ssh", limitMs = Infinity) => new Promise<void>((resolve, reject) => {+ const remaining = Math.min(deadline - Date.now(), limitMs);if (remaining <= 0) { reject(new Error("VPS SSH initialization timed out")); return; }const child = execFile(file, args, {env: { ...process.env, PATH: ssh.path },@@ -134,20 +145,24 @@ export async function ensureVpsSshMaster(ssh: VpsSshSetup, alias: string, timeouchild.stdin?.end();});pending = (async () => {- try { await command(["-O", "check", "--", alias]); }+ try { await command(["-O", "check", "--", alias]); return 0; }catch (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.const connect = () => command(["-o", "BatchMode=yes", "-o", "PermitLocalCommand=no", "-T", "--", alias, "true"]);- try { await connect(); }+ try { await connect(); return 0; }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); }+ const wakeStarted = Date.now();+ // At most the wake limit, and never the time the retry below needs.+ try { await command([alias], wake, Math.min(wakeTimeoutMs, deadline - wakeStarted - WAKE_RETRY_RESERVE_MS)); }catch (failure) {throw new Error(`${(unreachable as Error).message}; the wake script failed: ${(failure as Error).message}`);}+ const wokeMs = Date.now() - wakeStarted;await connect();+ return wokeMs;}}})().finally(() => {@@ -157,7 +172,7 @@ export async function ensureVpsSshMaster(ssh: VpsSshSetup, alias: string, timeou}let timer: ReturnType<typeof setTimeout> | undefined;try {- await Promise.race([pending, new Promise<never>((_resolve, reject) => {+ return await Promise.race([pending, new Promise<never>((_resolve, reject) => {timer = setTimeout(() => reject(new Error("VPS SSH initialization timed out")), timeoutMs + wakeBudget);timer.unref();})]);