Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Stop idle per-bot VPS desktops through the guarded lifecycle
Linf63e14003cbf
diff --git a/server/index.ts b/server/index.tsindex de467aa139..145b7c95d6 100644--- a/server/index.ts+++ b/server/index.ts@@ -435,7 +435,7 @@ import { loopGuardSettings } from "./host/loop-guard.ts"; import { createUnattenimport { claudeUserSkillsEnabled } from "./turn-settings.ts";import { addHeldSecretScrubber, redactSecretsInText, scrubHeldSecrets } from "./redact.ts";import * as vps from "./vps-computer.ts";-import { vpsConfigForBot, vpsSshAliasForBot } from "./vps-hosts.ts"; import { vpsContainerExec } from "./vps-exec.ts";+import { vpsAliasesInPlay, vpsConfigForBot, vpsSshAliasForBot } from "./vps-hosts.ts"; import { vpsContainerExec } from "./vps-exec.ts";import { ROUTINE_RESTARTED, RoutineManager, type Routine, type RoutineRun, type RoutineRunOn, type RoutineRunTrigger } from "./routines.ts"; import { routineModelRefusal, routineThreadModel, type RoutineModelChecks } from "./routine-input.ts"; import { routineHistoryFor, routineRunsFor } from "./routine-run-window.ts"; import { routineRunLimits } from "./routine-run-limits.ts"; import { runTurnLive } from "./routine-turn-live.ts"; import { batchSaves, flushLaterSaves } from "./save-batch.ts"; import { restartCutStop } from "./memory-freeze-restart.ts";import { CalendarCallManager, type CalendarCall } from "./calendar-calls.ts";import { BROWSER_UPLOAD_TOOL, browserRuntimeEnv } from "./browser-runtime.ts";@@ -5592,7 +5592,7 @@ function vpsThreadStarted(botId: string, threadId: string): void {function vpsThreadEnded(botId: string, threadId: string): void {const threads = activeVpsThreads.get(botId);if (!threads) return;- threads.delete(threadId);+ if (threads.delete(threadId)) vpsIdles.get(botId)?.touch();if (!threads.size) activeVpsThreads.delete(botId);}const boatLifecycleBusyBots = new Set<string>();@@ -5605,6 +5605,34 @@ const computerProviderConfigTransitions = new Set<RemoteComputerProvider>();const localVmIdleMs = () => localVmIdleTimeoutMinutes(cfg) * 60_000;const LOCAL_VM_DESKTOP_WAIT_MS = 90_000;const localVmIdles = new Map<string, ComputerIdleTimer>();+const vpsIdles = new Map<string, ComputerIdleTimer>();++function touchVpsIdle(bot: BotRecord): void {+ const alias = vpsSshAliasForBot(cfg, bot);+ if (!alias) return;+ const id = bot.id;+ vpsIdles.get(id)?.cancel();+ const current = () => {+ const owner = store.bot(id);+ return owner && vpsSshAliasForBot(cfg, owner) === alias && vpsIdles.get(id) === timer;+ };+ const inUse = () => activeVpsThreads.has(id) || botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id))+ || sharedVm.snapshot(id).held || Boolean(vps.vpsDesktopConnection(id)) || computerPreviews.has(id)+ || computerProviderConfigTransitions.has("vps");+ const timer: ComputerIdleTimer = new ComputerIdleTimer(localVmIdleMs(), () => inUse() || boatLifecycleBusyBots.has(id), async () => {+ if (!current()) return;+ const release = claimBotComputerLifecycle(id);+ try {+ const status = await vps.vpsComputerAction("stop", { vps: { sshAlias: alias } }, id, undefined, () => Boolean(current()) && !inUse());+ if (status.container === "running") return "busy";+ } finally {+ release();+ }+ });+ vpsIdles.set(id, timer);+ timer.touch();+}+const meetingsHost = createMeetingsHost({ cfg, dataDir: DATA_DIR, store, startTurn: (botId, text, opts) => startTurn(botId, text, opts), threadBusy, power: () => cloudComputerPower, computerOwner: (bot) => botComputerControlKey(bot), routines: () => routines, log: (line) => console.warn(line) }, () => ({ personName: personNameIn, sendsFreely: (botId, threadId) => roomTurnLevels.forRequest(threadId, botId, () => sourceApprovalMode(botId, threadId)) === "full", outbound: () => outboundHold, markOutside: (threadId) => outsideLineage.mark(threadId), folder: (botId, threadId) => messageFileRootsForThread(botId, threadId).filter((root) => root !== ATTACHMENTS_DIR)[0] ?? null })); const cloudComputerPower = createCloudComputerPower({cfg, owners: managedBoatOwners, broadcast, log: line => console.warn(line), routines: () => routines?.listRoutines() ?? [], wakeTimedOut: (owner, boxId, ctx) => boatRecovery.wakeTimedOut(owner, boxId, ctx),routineComputer: routine => { const bot = store.bot(routine.botId); return bot && turnProvider(bot, routine.runOn) === "box" ? botComputerControlKey(bot) : null; },@@ -5793,6 +5821,7 @@ async function mountBotVps(const vpsResource = `computer:vps:${vpsSshAliasForBot(cfg, bot)}:${bot.id}`;const remote = await (opts.start ? vps.vpsComputerAction("provision", botVpsConfig, bot.id) : vps.inspectVpsForAuto(botVpsConfig, bot.id));if (!remote?.ready || !remote.sshAlias) return { problem: remote?.problem ?? null, reachable: remote?.daemonUp === true, outdated: vpsDesktopOutdated(remote) };+ touchVpsIdle(bot);const targetCfg = { ...cfg, vps: { sshAlias: remote.sshAlias } };const vpsMcp = vps.vpsComputerMcp(targetCfg, bot.id, remote.container_id ?? undefined);const vpsControl = controlIntegration(bot.id, owner.threadId, owner.generation);@@ -6212,6 +6241,13 @@ function releaseLocalVmThread(threadId: string): void {localVmThreadTargets.delete(threadId);}+void vps.listManagedVpsComputers(cfg, store.bots.map(bot => ({ botId: bot.id, name: bot.name, inUse: false })), undefined, vpsAliasesInPlay(cfg, store.bots)).then(inventory => {+ for (const instance of inventory.instances) {+ const bot = instance.ownerBotId && store.bot(instance.ownerBotId);+ if (bot && instance.state === "running" && instance.vpsAlias === vpsSshAliasForBot(cfg, bot) && !vpsIdles.has(bot.id)) touchVpsIdle(bot);+ }+}).catch(error => console.warn("Could not recover VPS idle timers", error));+void recoverLocalVms({ // at once: a queued or channel turn sent as the server listens finds a running VMmode: localVmMode(cfg), seats: localVmMaxInstances(cfg), bots: store.bots, seen: localVmSeen,status: (target) => containerComputerStatus(undefined, undefined, target).catch(() => null),@@ -12211,7 +12247,7 @@ const postiz = createPostiz({ cfg: () => cfg, mcpOAuth, persistMcpServers: persisharedComputers, sharedComputerControl, closeBrowser, browserEngineSwitched,hostedModels: Boolean(hostedModels),cloudHome: Boolean(CLOUD_HOME), cloudTeam: CLOUD_TEAM !== null, sharedMembership,- lendingEnabled: () => lendingEnabled() || ownerLends(), providerConfigs, localVmIdleMs, localVmIdles, localVmActiveThreads, localVmLifecycleBusy,+ lendingEnabled: () => lendingEnabled() || ownerLends(), providerConfigs, localVmIdleMs, localVmIdles: { *values() { yield* localVmIdles.values(); yield* vpsIdles.values(); } }, localVmActiveThreads, localVmLifecycleBusy,localVmImageBusy: { get: () => localVmImageBusy },localVmModeChangeBusy: { set: (busy) => { localVmModeChangeBusy = busy; } },localVmModeChanging: sharedVm.modeChanging,@@ -14975,11 +15011,18 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (m[2] === "join") {const remote = auth.kind !== "loopback";const result = await vps.vpsComputerJoin(vpsConfigForBot(cfg, bot), botId, undefined, remote);+ touchVpsIdle(bot);return json(res, 200, { ...result, joinUrl: remote? desktopViewerUrl(`vps/${botId}`, bot.threadId) : result.joinUrl });}const action = m[2] === "provision" ? "provision" : m[2] === "remove" ? "remove" : "stop";- return json(res, 200, await vps.vpsComputerAction(action, vpsConfigForBot(cfg, bot), botId));+ const status = await vps.vpsComputerAction(action, vpsConfigForBot(cfg, bot), botId);+ if (status.container === "running") touchVpsIdle(bot);+ else {+ vpsIdles.get(botId)?.cancel();+ vpsIdles.delete(botId);+ }+ return json(res, 200, status);} finally {releaseComputerLifecycle();if (joinSettled) {@@ -15198,6 +15241,7 @@ const gracefulShutdown = createGracefulShutdown({desktopViewer.closeAll();upgrades.close();for (const idle of localVmIdles.values()) idle.cancel();+ for (const idle of vpsIdles.values()) idle.cancel();cloudComputerPower.close(); boatRecovery.close();vps.closeAllVpsDesktopTunnels();watchdog.stop();diff --git a/server/vps-computer.test.ts b/server/vps-computer.test.tsindex 387a97fd1f..3edf5d4532 100644--- a/server/vps-computer.test.ts+++ b/server/vps-computer.test.ts@@ -35,6 +35,7 @@ import type { AppConfig } from "./config.ts";import {VPS_CONTAINER_LABEL,VPS_ENVIRONMENT_LABEL,+ vpsEnvironmentId,VPS_IMAGE,VPS_MANAGED_LABEL,VPS_VIEWER_LABEL,@@ -519,6 +520,29 @@ describe("VPS computer", () => {expect(stop.calls.some(({ args }) => ["rm", "system", "reboot", "shutdown"].includes(args[2]!))).toBe(false);});+ it("leaves the desktop running when work arrives during idle-stop inspection", async () => {+ const fake = fixture({ environmentId: vpsEnvironmentId() });+ const result = await vpsComputerAction("stop", CONFIG, BOT_ID, fake.runner, () => false);+ expect(result.container).toBe("running");+ expect(fake.calls.some(({ args }) => ["stop", "rm"].includes(args[2]!))).toBe(false);+ });++ it("restarts the same container after an unattended idle stop", async () => {+ const fake = fixture({ environmentId: vpsEnvironmentId() });+ const stopped = await vpsComputerAction("stop", CONFIG, BOT_ID, fake.runner, () => true);+ expect(stopped.container).toBe("stopped");+ const resumed = await vpsComputerAction("provision", CONFIG, BOT_ID, fake.runner);+ expect(resumed.ready).toBe(true);+ expect(resumed.container_id).toBe(CONTAINER_ID);+ expect(fake.calls.some(({ args }) => ["rm", "run"].includes(args[2]!))).toBe(false);+ });++ it.each([null, "another-installation"])("leaves an unverified idle desktop running (%s)", async environmentId => {+ const fake = fixture({ environmentId });+ await vpsComputerAction("stop", CONFIG, BOT_ID, fake.runner, () => true);+ expect(fake.calls.some(({ args }) => ["stop", "rm"].includes(args[2]!))).toBe(false);+ });+it("serializes concurrent provisioning for the same bot", async () => {const fake = fixture({ image: false, container: false });const results = await Promise.all([diff --git a/server/vps-computer.ts b/server/vps-computer.tsindex 427ce3aa0e..2119b97956 100644--- a/server/vps-computer.ts+++ b/server/vps-computer.ts@@ -383,6 +383,7 @@ async function computeVpsComputerStatus(cfg: AppConfig,botId: string,runner: VpsCommandRunner,+ requireEnvironmentLabel = false,): Promise<VpsComputerStatus> {const alias = vpsSshAlias(cfg);const status = emptyStatus(botId, alias);@@ -459,7 +460,7 @@ async function computeVpsComputerStatus(status.managed =labels?.[VPS_MANAGED_LABEL] === "1" &&labels?.[VPS_CONTAINER_LABEL] === status.container_name &&- (environmentLabel === undefined || environmentLabel === vpsEnvironmentId());+ ((!requireEnvironmentLabel && environmentLabel === undefined) || environmentLabel === vpsEnvironmentId());if (status.managed && status.container_id) raisePidsLimit(status.container_id, detail?.HostConfig?.PidsLimit, run);status.network = hasNoPublishedPorts(detail?.HostConfig, detail?.NetworkSettings?.Networks) ? "private" : "unsafe";status.mounts = hasNoHostMounts(detail ?? {}) ? "none" : "unsafe";@@ -957,6 +958,7 @@ export async function vpsComputerAction(cfg: AppConfig,botId: string,runner: VpsCommandRunner = defaultRunner,+ shouldStop?: () => boolean,): Promise<VpsComputerStatus> {cfg = snapshotVpsConfig(cfg);const alias = vpsSshAlias(cfg);@@ -967,8 +969,9 @@ export async function vpsComputerAction(const operation = async () => {invalidateVpsStatus(key);try {- const before = await computeVpsComputerStatus(cfg, botId, runner);+ const before = await computeVpsComputerStatus(cfg, botId, runner, Boolean(shouldStop));if (!before.daemonUp) throw Object.assign(new Error(before.problem ?? "Docker over SSH is not reachable"), { status: 409 });+ if (action === "stop" && shouldStop && (before.container !== "running" || !before.managed || !shouldStop())) return before;if (action === "provision" && before.ready) return before;if (action !== "provision" || before.container !== "running") stopDesktopTunnel(botId);const run = (args: string[], timeoutMs = 2 * 60_000) => runner(vpsDockerArgs(alias, args), { timeoutMs });