Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Server container: clear the lease its own earlier run left, so a server killed outright starts again
milind-soni0d3ead341804
diff --git a/electron/data-dir-lease.d.mts b/electron/data-dir-lease.d.mtsindex d6454d7e49..8153d9974f 100644--- a/electron/data-dir-lease.d.mts+++ b/electron/data-dir-lease.d.mts@@ -30,3 +30,7 @@ export declare function acquireDataDirLeaseForProcess(export declare function clearRecordsFromOtherMachines(dataDir: string,): { path: string; host: string; pid: number }[];++export declare function clearRecordsFromEarlierRunOfThisContainer(+ dataDir: string,+): { path: string; host: string; pid: number }[];diff --git a/electron/data-dir-lease.mjs b/electron/data-dir-lease.mjsindex c09dc0e335..1ff2dbcd4e 100644--- a/electron/data-dir-lease.mjs+++ b/electron/data-dir-lease.mjs@@ -573,6 +573,25 @@ export function acquireDataDirLease(dataDir, options = {}) {* for a folder several computers share.*/export function clearRecordsFromOtherMachines(dataDir) {+ return clearRecords(dataDir, (record) => !sameMachine(record));+}++/**+ * For a container's entry as it starts (server/server-launcher.ts): a record this same container left in an earlier run+ * (its hostname, this boot, another pid namespace) belongs to a process that died with that run, since a container's+ * pid namespace and every process in it end together, and a restarted container gets a new one. Without this, a+ * server killed outright (out of memory, `kill -9`) was refused at every restart as "another machine". Removes those+ * records and returns their holders. Another container's records (another hostname, as Docker names each container)+ * stay, and acquireDataDirLease() refuses them as before.+ */+export function clearRecordsFromEarlierRunOfThisContainer(dataDir) {+ const boot = bootSession();+ const ns = pidNamespace();+ if (boot === null || ns === null) return [];+ return clearRecords(dataDir, (record) => record.host === hostname() && record.boot === boot && typeof record.ns === "string" && record.ns !== ns);+}++function clearRecords(dataDir, stale) {validateDataDir(dataDir);let entries;try {@@ -589,7 +608,7 @@ export function clearRecordsFromOtherMachines(dataDir) {const cleared = [];for (const path of paths) {const record = readOwner(path);- if (!record || sameMachine(record)) continue;+ if (!record || !stale(record)) continue;unlinkExact(path, "OpenMausBot could not remove the data-directory record another machine left.");cleared.push({ path, host: record.host, pid: record.pid });}diff --git a/electron/data-dir-lease.node-test.mjs b/electron/data-dir-lease.node-test.mjsindex b35616e3b1..81a68dbb70 100644--- a/electron/data-dir-lease.node-test.mjs+++ b/electron/data-dir-lease.node-test.mjs@@ -9,6 +9,7 @@ import test from "node:test";import {acquireDataDirLease,acquireDataDirLeaseForProcess,+ clearRecordsFromEarlierRunOfThisContainer,clearRecordsFromOtherMachines,} from "./data-dir-lease.mjs";@@ -451,6 +452,31 @@ test("a lease another container on this host left is never judged by this contaiassert.equal(lease.release(), true);});+// A container Docker restarts after its server was killed outright (out of memory, kill -9) keeps its hostname, and gets a+// new pid namespace: its launcher clears what the earlier run left, and only that.+test("a container's launcher clears the lease its own earlier run left, never another container's", (t) => {+ const { dataDir } = temporaryDirectory();+ const current = recordWrittenByThisProcess(dataDir);+ if (current.ns === null || current.boot === null) return t.skip("no pid namespace or boot identity on this platform");+ const leasePath = path.join(dataDir, LEASE_NAME);+ const plant = (overrides) => writeFileSync(leasePath, `${JSON.stringify({ ...current, ...overrides })}\n`, { mode: 0o600 });+ plant({ host: `${current.host}-another-container`, ns: anotherPidNamespace(current), pid: process.pid, token: randomUUID() });+ assert.deepEqual(clearRecordsFromEarlierRunOfThisContainer(dataDir), []);+ assert.throws(() => acquireDataDirLease(dataDir), /already owned by a process on another machine/i);++ plant({ ns: anotherPidNamespace(current), pid: process.pid, token: randomUUID() });+ assert.throws(() => acquireDataDirLease(dataDir), /already owned by a process on another machine/i);+ assert.deepEqual(clearRecordsFromEarlierRunOfThisContainer(dataDir), [{ path: leasePath, host: current.host, pid: process.pid }]);+ const lease = acquireDataDirLease(dataDir);+ try {+ // This run's own lease is live, and stays.+ assert.deepEqual(clearRecordsFromEarlierRunOfThisContainer(dataDir), []);+ assert.throws(() => acquireDataDirLease(dataDir), /already using this data directory/i);+ } finally {+ lease.release();+ }+});+test("a pid this container reused for another process is not the lease's owner", (t) => {const { dataDir } = temporaryDirectory();const current = recordWrittenByThisProcess(dataDir);diff --git a/server/data-dir-lease.ts b/server/data-dir-lease.tsindex b5d6df70a3..f7ac4adbbb 100644--- a/server/data-dir-lease.ts+++ b/server/data-dir-lease.ts@@ -2,6 +2,7 @@export {acquireDataDirLease,acquireDataDirLeaseForProcess,+ clearRecordsFromEarlierRunOfThisContainer,clearRecordsFromOtherMachines,DataDirLeaseError,} from "../electron/data-dir-lease.mjs";diff --git a/server/server-launcher.ts b/server/server-launcher.tsindex 8bd4f95e19..69b0ba94e1 100644--- a/server/server-launcher.ts+++ b/server/server-launcher.ts@@ -1,10 +1,11 @@-// Container entry: restarts the server in place on RESTART_EXIT_CODE, since a container restart cuts off a Caddy sharing its network.+// Container entry: restarts the server in place on RESTART_EXIT_CODE, so a restart the server asks for keeps the container.import { spawn, type ChildProcess } from "node:child_process";import { existsSync, realpathSync } from "node:fs";import { homedir } from "node:os";import { dirname, join, resolve } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";import { boxMemory, heapSizeArgs, type BoxMemory } from "./box-memory.ts";+import { clearRecordsFromEarlierRunOfThisContainer } from "./data-dir-lease.ts";import { restartPolicy } from "./restart.ts";/** The server's heap sized to the container's memory limit, run through the bootstrap that keeps Node's compile cache on@@ -51,6 +52,13 @@ function isEntry(): boolean {}if (isEntry()) {+ const dataDir = process.env.OMB_DATA_DIR || join(homedir(), ".openmausbot");+ try {+ // A container starts with nothing of its own running: a lease its earlier run left is a dead server's.+ for (const { path, pid } of clearRecordsFromEarlierRunOfThisContainer(dataDir)) console.log(`Removed ${path}, left by this container's server (process ${pid}) when it stopped without closing.`);+ } catch (error) {+ console.warn(`The data folder's lease could not be checked: ${error instanceof Error ? error.message : String(error)}`);+ }const server = serverCommand(dirname(fileURLToPath(import.meta.url)), process.env);void superviseServer(() => spawn(process.execPath, server.args, { stdio: "inherit", env: server.env })).then((code) => { process.exitCode = code; });}