Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(vps): count a host as unreachable only on SSH's own lookup/connect failure or a timeout
AdityaUmale1394b9f515f1
diff --git a/docs/byo-vps.md b/docs/byo-vps.mdindex 413800d4a6..d5b44ade01 100644--- a/docs/byo-vps.md+++ b/docs/byo-vps.md@@ -108,7 +108,9 @@ Self-hosted VPS computers (or by hand: `docker -H ssh://old-server rm -f openmauthat cannot be reached never traps a bot: moving the bot to another server, switching its computer, or deletingit goes ahead, and the app says what may be left on that server and the command that removes it once the serveris back. Changing or clearing the default alias works the same way: the app lists the command that finds this-installation's computers left on that server. Any alias from your+installation's computers left on that server. Only a name lookup or connection failure that SSH reports, or a+timeout, counts as not reached: a server that answers but refuses (a changed host key, a Docker error) keeps the+alias until it 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 idlediff --git a/server/cloud-backend.ts b/server/cloud-backend.tsindex 4b5e4b52d4..386cef4bd8 100644--- a/server/cloud-backend.ts+++ b/server/cloud-backend.ts@@ -16,10 +16,12 @@ export function vpsLeftBehindNotice(done: "Moved" | "Deleted", alias: string, co}/** What an unreachable old default alias may still run for this installation, and how to find and remove it. */-export function vpsAliasLeftBehindNotice(done: "Saved" | "Removed", alias: string, environmentFilter: string, managedFilter: string): string {+export function vpsAliasLeftBehindNotice(done: "Saved" | "Removed", alias: string, environmentFilter: string | null, managedFilter: string): string {return `${done}. ${alias} could not be reached, so this installation's computers there, if any are still there, were left as they are. ` +- `When ${alias} is back, list them with: docker -H ssh://${alias} ps -a --filter ${environmentFilter} ` +- `and remove any you no longer need with: docker -H ssh://${alias} rm -f <name>. ` ++ (environmentFilter+ ? `When ${alias} is back, list them with: docker -H ssh://${alias} ps -a --filter ${environmentFilter} ` ++ `and remove any you no longer need with: docker -H ssh://${alias} rm -f <name>. `+ : `This installation's ID could not be read, so no filter lists only its computers on ${alias}. `) +`Computers made by older versions have no installation label: docker -H ssh://${alias} ps -a --filter ${managedFilter} lists every managed one, ` +`so remove one of those only when you have its exact name from this installation, such as the one in a bot's move or delete notice. ` +`A name that only starts with openmausbot-vps- does not prove it is this installation's: if you have nothing more, leave it.`;diff --git a/server/index.test.ts b/server/index.test.tsindex d0b86e19bb..29264bfaa3 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -471,7 +471,7 @@ beforeAll(async () => {'import { appendFileSync, existsSync } from "node:fs";','const args = process.argv.slice(2);',`appendFileSync(${JSON.stringify(fakeSshLog)}, JSON.stringify(args) + "\\n");`,- `if (existsSync(${JSON.stringify(fakeSshUnavailable)})) { console.error("fixture SSH is unavailable"); process.exit(255); }`,+ `if (existsSync(${JSON.stringify(fakeSshUnavailable)})) { console.error("ssh: connect to host fixture-vps port 22: Connection refused"); process.exit(255); }`,'if (args[0] === "-F") args.splice(0, 2);','if (args.length === 4 && args.slice(0, 3).join(" ") === "-O check --") process.exit(255);','if (args.length === 8 && args.slice(0, 6).join(" ") === "-o BatchMode=yes -o PermitLocalCommand=no -T --" && args[7] === "true") process.exit(0);',@@ -11157,7 +11157,7 @@ describe("harness HTTP API", () => {expect(cleared.body.notice).toContain(`docker -H ssh://fixture-vps ps -a --filter label=com.openmausbot.environment=${environmentId} `);expect(cleared.body.notice).toContain("docker -H ssh://fixture-vps rm -f <name>");expect(cleared.body.notice).toContain("docker -H ssh://fixture-vps ps -a --filter label=com.openmausbot.vps=1 lists every managed one");- expect(cleared.body.notice).toContain("does not prove it is this installation's: if you have nothing more, leave it");+ expect(cleared.body.notice).toContain("A name that only starts with openmausbot-vps- does not prove it is this installation's: if you have nothing more, leave it");expect((await api("GET", "/api/config")).body.vps.sshAlias).toBe("");expect(existsSync(fakeVpsFixture)).toBe(true);} finally {diff --git a/server/routes/config.ts b/server/routes/config.tsindex 6a20c6d53f..72322e2508 100644--- a/server/routes/config.ts+++ b/server/routes/config.ts@@ -116,6 +116,11 @@ export interface ConfigRouteDeps {postiz?: Pick<Postiz, "configCheck" | "configSaved">;}+/** The label that lists only this installation's VPS computers, or null when its ID can't be read. */+function vpsEnvironmentFilter(): string | null {+ try { return `label=${vps.VPS_ENVIRONMENT_LABEL}=${vps.vpsEnvironmentId()}`; } catch { return null; }+}+export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {const {store, cfg, registry, sessions, browserCleanup, browserLive, browserRuntime, usedBrowserSessions, decider,@@ -549,6 +554,10 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {return spec ? [{ session, spec }] : [];});let configWriteCommitted = false;+ // Ready before the save: once it commits, nothing that fails later may lose what the old server may still hold.+ const vpsNotice = vpsLeftOn+ ? vpsAliasLeftBehindNotice(nextVpsAlias ? "Saved" : "Removed", vpsLeftOn, vpsEnvironmentFilter(), `label=${vps.VPS_MANAGED_LABEL}=1`)+ : null;const enginesBefore = engineLaunches(providerConfigs());const localVmModeChanged = changingLocalVmMode ? localVmModeChanging() : null;const externalSecretStorage = url.searchParams.get("secretStorage") === "external";@@ -589,11 +598,13 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {if (persisted.postiz?.key !== undefined) persisted.postiz.key = "";saveConfig(persisted);configWriteCommitted = true;+ savedVpsNotice = vpsNotice;syncCredentialEnv(patch);Object.assign(cfg, loadConfig());} else {saveConfig(patch);configWriteCommitted = true;+ savedVpsNotice = vpsNotice;// loadConfig prefers env over the file for credentials, so the env must follow the save.syncCredentialEnv(patch);Object.assign(cfg, loadConfig());@@ -654,7 +665,6 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {const changedEngines = new Set(changedInstanceIds(enginesBefore, engineLaunches(providerConfigs())));// Revoked before any await: a changed engine's old children are invalid at once.revokeEngineCapabilities(changedEngines);- if (vpsLeftOn) savedVpsNotice = vpsAliasLeftBehindNotice(nextVpsAlias ? "Saved" : "Removed", vpsLeftOn, `label=${vps.VPS_ENVIRONMENT_LABEL}=${vps.vpsEnvironmentId()}`, `label=${vps.VPS_MANAGED_LABEL}=1`);// Commit failures wait until every mandatory effect has run: no journal failure may leave a bearer or stale engines active.const finalized = await finalizeBrowserCleanupMutation({requests: browserCleanupRequests,diff --git a/server/vps-command.ts b/server/vps-command.tsindex d0c8278b23..9899fa6038 100644--- a/server/vps-command.ts+++ b/server/vps-command.ts@@ -24,8 +24,15 @@ const STREAM_CAP_CHARS = 16 * 1024 * 1024;/** SSH never got through (or the command ran out of time): unlike a Docker refusal, nothing on the host answered. */export class VpsHostUnreachableError extends Error {}-// OpenSSH exits 255 for its own failures; Docker's SSH transport quotes that status when the connection drops.-const SSH_EXIT_255 = /exit(?:ed with exit)? status 255\b/i;+// OpenSSH's own words when it never reached the host. Exit status 255 alone is not proof: ssh also passes on a remote command's 255.+const SSH_TRANSPORT_FAILURE = /\bssh: (?:Could not resolve hostname|connect to host \S+ port \d+:)/i;++/** Only a lookup or connection failure ssh reports itself, or a timeout, means nothing on the host answered. */+function sshNeverReachedHost(error: unknown): boolean {+ if ((error as { killed?: boolean }).killed === true) return true;+ const message = error instanceof Error ? error.message : String(error);+ return SSH_TRANSPORT_FAILURE.test(message) || message === "VPS SSH initialization timed out";+}function tailCollector() {const chunks: string[] = [];@@ -54,7 +61,10 @@ export async function defaultRunner(args: string[], options: VpsCommandOptions =// Time spent waking a paused host does not count against the command's own timeout.if (destination) {try { deadline += await ensureVpsSshMaster(ssh, destination, Math.min(30_000, deadline - Date.now())); }- catch (error) { throw new VpsHostUnreachableError(error instanceof Error ? error.message : String(error)); }+ catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ throw sshNeverReachedHost(error) ? new VpsHostUnreachableError(message) : new Error(message);+ }}if (Date.now() >= deadline) throw new VpsHostUnreachableError("Docker-over-SSH command timed out");return new Promise((resolve, reject) => {@@ -109,9 +119,9 @@ export async function defaultRunner(args: string[], options: VpsCommandOptions =if (failure) return;settle(() => {if (code === 0) return resolve({ stdout: stdout.text(), stderr: stderr.text() });- const detail = stderr.text().trim().slice(-1000);- const message = detail || `Docker-over-SSH exited ${code ?? signal ?? "without a status"}`;- reject(SSH_EXIT_255.test(message) ? new VpsHostUnreachableError(message) : new Error(message));+ const captured = stderr.text().trim();+ const message = captured.slice(-1000) || `Docker-over-SSH exited ${code ?? signal ?? "without a status"}`;+ reject(SSH_TRANSPORT_FAILURE.test(captured) ? new VpsHostUnreachableError(message) : new Error(message));});});try {diff --git a/server/vps-computer.runner.test.ts b/server/vps-computer.runner.test.tsindex a8d166fd26..adea89c83d 100644--- a/server/vps-computer.runner.test.ts+++ b/server/vps-computer.runner.test.ts@@ -15,7 +15,7 @@ vi.mock("./procs.ts", async () => ({killCliTree: stopMock,}));-import { defaultRunner, dockerCliInstallCommand } from "./vps-computer.ts";+import { defaultRunner, dockerCliInstallCommand, VpsHostUnreachableError } from "./vps-computer.ts";import { resolveCliSpawn } from "./env-path.ts";type FakeChild = EventEmitter & {@@ -45,6 +45,24 @@ describe("default VPS command runner", () => {vi.useRealTimers();});+ it("calls a host unreachable only when ssh itself says it never got there", async () => {+ const transport = fakeChild();+ const lost = defaultRunner(["info"]);+ // Docker puts ssh's words first; a long tail after them must not hide them.+ transport.stderr.write("error during connect: command [ssh -- vps docker system dial-stdio] has exited with exit status 255, " ++ "stderr=ssh: connect to host vps port 22: Connection refused\n" + "debug1: retrying\n".repeat(200));+ transport.emit("close", 1, null);+ await expect(lost).rejects.toBeInstanceOf(VpsHostUnreachableError);++ const remote = fakeChild();+ const refused = defaultRunner(["info"]);+ remote.stderr.write("error during connect: command [ssh -- vps docker system dial-stdio] has exited with exit status 255, stderr=dial-stdio is not allowed here");+ remote.emit("close", 1, null);+ const error = await refused.catch((failure: unknown) => failure);+ expect(error).toBeInstanceOf(Error);+ expect(error).not.toBeInstanceOf(VpsHostUnreachableError);+ });+it("collects output and resolves after the child closes", async () => {const child = fakeChild();const result = defaultRunner(["info"], { input: "request" });diff --git a/server/vps-computer.test.ts b/server/vps-computer.test.tsindex 81ef79fecf..387a97fd1f 100644--- a/server/vps-computer.test.ts+++ b/server/vps-computer.test.ts@@ -1421,6 +1421,13 @@ describe("a VPS inventory that fails", () => {if (process.platform !== "win32") {vi.mocked(ensureVpsSshMaster).mockRejectedValueOnce(new Error("ssh: Could not resolve hostname production-vps"));expect((await listManagedVpsComputers(CONFIG, [])).unreachable).toBe(true);+ // The host answered with a changed key, or the local ssh never started: the host may still be up.+ vi.mocked(ensureVpsSshMaster).mockRejectedValueOnce(new Error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @\nHost key verification failed."));+ expect((await listManagedVpsComputers(CONFIG, [])).unreachable).toBeUndefined();+ vi.mocked(ensureVpsSshMaster).mockRejectedValueOnce(new Error("spawn ssh ENOENT"));+ expect((await listManagedVpsComputers(CONFIG, [])).unreachable).toBeUndefined();+ vi.mocked(ensureVpsSshMaster).mockRejectedValueOnce(Object.assign(new Error("VPS SSH initialization timed out"), { killed: true }));+ expect((await listManagedVpsComputers(CONFIG, [])).unreachable).toBe(true);}} finally { spawnMock.mockReset(); }});