Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Give SSH desktops an independent idle timeout
Lin869a1023cb83
diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex b818b340d1..dfbac9ad15 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -1361,6 +1361,10 @@ using Tailscale Serve. Viewer requests require an admin session. Logging outor revoking that session closes open viewers. Client-only pairing does notgrant desktop control.+Managed VPS desktops stop after 480 idle minutes by default. Set+`vpsIdle.timeoutMinutes` in `config.json` to a whole number from 5 to 1440.+Private desktops have their own `localVm.idleTimeoutMinutes` setting.+An open Local VM viewer keeps that VM's idle timer active. Remote VPS viewersshare a tunnel; it closes 30 seconds after the last viewer leaves, allowingreconnects during that interval. **Hand control back**, closing the panel ordiff --git a/server/app-settings/registry-config.ts b/server/app-settings/registry-config.tsindex 029b2cb13a..0e3bf5afba 100644--- a/server/app-settings/registry-config.ts+++ b/server/app-settings/registry-config.ts@@ -10,6 +10,7 @@ import { DEFAULT_WINDOW_MINUTES } from "../cache-keepwarm.ts";import { botsTowardLimit } from "../../shared/bot-limit.ts";import { parseSocks5Proxy } from "../browser/egress/policy.ts";import { CONFIG_PATCH_FIELDS as F, MAX_THREAD_EVENT_LOG_BYTES, MIN_THREAD_EVENT_LOG_BYTES } from "../config.ts";+import { vpsIdleTimeoutMinutes } from "../vps-config.ts";import { display, withoutKeys, type RegistryDeps, type SettingEntry, type Where, type WritableSpec } from "./registry.ts";/** Security: what a bot or card reads of a section never carries a key, token, secret or password field. */@@ -151,6 +152,11 @@ export function configEntries(deps: Pick<RegistryDeps, "cfg" | "saveConfig" | "bvalue: nonEmpty(F.localVm.unwrap().pick({ mode: true, maxInstances: true, idleTimeoutMinutes: true }).strict()), allowed: '{"mode"?:"shared"|"per-bot"|"pool","maxInstances"?,"idleTimeoutMinutes"?}',current: () => cfg().localVm ?? {}, patch: (localVm) => ({ localVm }), says: (localVm) => `Private desktops: ${fields(localVm)}`,}),+ section({+ id: "desktops.vpsIdle", label: "Server desktop idle timeout", help: "Minutes before an idle SSH server desktop stops.", where: "page:desktops",+ synonyms: ["VPS", "SSH", "idle timer"], value: F.vpsIdle.unwrap().shape.timeoutMinutes.unwrap(), allowed: "5 to 1440 whole minutes",+ current: () => vpsIdleTimeoutMinutes(cfg()), patch: (timeoutMinutes) => ({ vpsIdle: { timeoutMinutes } }),+ }),feature("computer.sharing", "Computer sharing", "Whether every paired device may lend its computer to bots here. Each lent folder or app is still picked and confirmed on that device.", "page:desktops",["share computer", "shared computers", "lend", "lending"], "sharedComputers", false,"Let every paired device lend its computer to bots here, not only your own. A lent folder can be used to reach a shell", "Stop every device, your own included, lending its computer to bots here"),diff --git a/server/config.ts b/server/config.tsindex ecd80fbf3d..b718ba2667 100644--- a/server/config.ts+++ b/server/config.ts@@ -10,7 +10,7 @@ import type { ImageGenerationConfig } from "../shared/image-generation.ts";import { imageGenConfigSchema, imageGenPatchSchema, keepKeysOutOfImageModels, type ImageGenCredentialPatch } from "./image-generation-config.ts";import { botAvatarUrlSchema } from "../shared/bot-avatar.ts";import { writeFileAtomic } from "./atomic.ts";-import { isValidSshAlias, normalizeVpsConfig, storedVpsServersSchema, vpsConfigSchema, vpsServersSchema, type VpsConfig, type VpsServer } from "./vps-config.ts";+import { isValidSshAlias, normalizeVpsConfig, storedVpsServersSchema, vpsConfigSchema, vpsIdleConfigSchema, vpsServersSchema, type VpsConfig, type VpsServer } from "./vps-config.ts";import { configBackupRefusal, configSaveRefusal, readConfigFile, writeConfigBackup } from "./config-backup.ts";import { defaultBotThreads, MAX_CONCURRENT_BOT_THREADS } from "./bot-thread-limits.ts";import { anthropicKeyEnv } from "./anthropic-key-env.ts";@@ -390,6 +390,7 @@ const appConfigSchema = z.object({decisions: z.object({ retentionDays: z.number().int().min(1).max(3650).optional() }).strict().optional(),loopGuard: loopGuardConfigSchema.optional(),safetyFloor: z.object({ enabled: z.boolean().optional() }).strict().optional(), // off by default: safetyFloorEnabled in server/safety-floor-gate.ts+ vpsIdle: vpsIdleConfigSchema.optional(),localVm: localVmConfigSchema.optional(),features: featureConfigSchema.optional(),onboarding: onboardingConfigSchema.optional(),@@ -466,6 +467,7 @@ export interface AppConfig extends HelperConfig {threads?: { maxConcurrentPerBot: number; eventLogMaxBytes?: number; eventLogRetentionDays?: number }; burst?: { maxParallel?: number };context?: { rebuildBytes?: number; compactAt?: number; autoCompact?: boolean; roomCompactAt?: number; roomSessions?: boolean; replayToolHistory?: boolean };memory?: { captureQuietMs?: number; tidyHour?: number };+ vpsIdle?: z.infer<typeof vpsIdleConfigSchema>;localVm?: { mode?: "shared" | "per-bot" | "pool"; maxInstances?: number; idleTimeoutMinutes?: number; preserveInstalledApps?: boolean; memoryGb?: number; cpus?: number };features?: { skillAuthoring?: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; claudeUserSkills?: boolean; llmThreadTitles?: boolean; smartSetupChoices?: boolean; autoRecall?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; parallelRoomJobs?: boolean; acpPlanLines?: boolean; agentsToolBridge?: boolean; savedSteps?: boolean; usbPhoneTakeover?: boolean; cloudComputerAutoReplace?: boolean; phonePush?: boolean; skillBurger?: boolean; threadTabs?: boolean; roomFeed?: boolean; teamBoard?: boolean };onboarding?: { completedAt?: string; version?: number; reelSeen?: boolean; hintsSeen?: string[]; firstTurnAt?: string };@@ -889,7 +891,7 @@ export function saveConfig(const keepImageModels = keepKeysOutOfImageModels(disk, checkedPatch.imageGen);const storedProfiles = storedBrowserProfilesSchema.safeParse(disk.browserProfiles);if (storedProfiles.success) disk.browserProfiles = storedProfiles.data;- for (const key of ["xai", "anthropic", "mistral", "cerebras", "treg", "postiz", "groq", "greenference", "modelgo", "meta", "deepseek", "openai", "openrouter", "openaiCompat", "composio", "box", "opencodeGo", "tts", "decider", "imageGen", "live", "profile", "rooms", "mcp", "threads", "context", "memory", "localVm", "features", "budgets", "billing", "decisions", "loopGuard", "onboarding", "browserEngine", "newBots", "safetyFloor"] as const) {+ for (const key of ["xai", "anthropic", "mistral", "cerebras", "treg", "postiz", "groq", "greenference", "modelgo", "meta", "deepseek", "openai", "openrouter", "openaiCompat", "composio", "box", "opencodeGo", "tts", "decider", "imageGen", "live", "profile", "rooms", "mcp", "threads", "context", "memory", "localVm", "vpsIdle", "features", "budgets", "billing", "decisions", "loopGuard", "onboarding", "browserEngine", "newBots", "safetyFloor"] as const) {const section = checkedPatch[key];if (!section) continue;const current = jsonObjectSchema.safeParse(disk[key]);diff --git a/server/index.test.ts b/server/index.test.tsindex 804ac869a0..dcdd80eb26 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -11026,6 +11026,23 @@ describe("harness HTTP API", () => {await api("PATCH", "/api/config", { localVm: { mode: "shared", maxInstances: 2 } });});+ it("keeps VPS and private desktop idle timeouts independent", async () => {+ const get = async () => (await api("GET", "/api/config")).body;+ expect((await get()).vpsIdle).toEqual({ timeoutMinutes: 480 });+ try {+ for (const timeoutMinutes of [4, 1441, 5.5, "5", null]) {+ expect((await api("PATCH", "/api/config", { vpsIdle: { timeoutMinutes } })).status).toBe(400);+ }+ const saved = await api("PATCH", "/api/config", { vpsIdle: { timeoutMinutes: 5 } });+ expect(saved.body).toMatchObject({ vpsIdle: { timeoutMinutes: 5 }, localVm: { idleTimeoutMinutes: 480 } });+ await api("PATCH", "/api/config", { localVm: { idleTimeoutMinutes: 30 } });+ expect(await get()).toMatchObject({ vpsIdle: { timeoutMinutes: 5 }, localVm: { idleTimeoutMinutes: 30 } });+ expect(JSON.parse(readFileSync(join(home, ".openmausbot", "config.json"), "utf8")).vpsIdle).toEqual({ timeoutMinutes: 5 });+ } finally {+ await api("PATCH", "/api/config", { vpsIdle: { timeoutMinutes: 480 }, localVm: { idleTimeoutMinutes: 480 } });+ }+ });+it("validates, persists and applies the Local VM idle timeout in shared and per-bot modes", async () => {const bot = (await api("POST", "/api/bots")).body.bot;try {diff --git a/server/index.ts b/server/index.tsindex c08cd0fe3f..3b4020f1d8 100644--- a/server/index.ts+++ b/server/index.ts@@ -175,7 +175,7 @@ import {builtInBrowserEnabled,persistableInstanceConfigs,type AppConfig,- vpsResources, vpsSshAlias,+ vpsIdleTimeoutMinutes, vpsResources, vpsSshAlias,DATA_DIR, EVENTS_DIR,onConfigSaved,CLAUDE_API_INSTANCE,@@ -5602,6 +5602,7 @@ const orphanBoatLifecycleBusyIds = new Set<string>();const boatInventoryRequestsBusyIds = new Set<string>();type RemoteComputerProvider = "box" | "vps";const computerProviderConfigTransitions = new Set<RemoteComputerProvider>();+const vpsIdleMs = () => vpsIdleTimeoutMinutes(cfg) * 60_000;const localVmIdleMs = () => localVmIdleTimeoutMinutes(cfg) * 60_000;const LOCAL_VM_DESKTOP_WAIT_MS = 90_000;const localVmIdles = new Map<string, ComputerIdleTimer>();@@ -5619,7 +5620,7 @@ function touchVpsIdle(bot: BotRecord): void {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 () => {+ const timer: ComputerIdleTimer = new ComputerIdleTimer(vpsIdleMs(), () => inUse() || boatLifecycleBusyBots.has(id), async () => {if (!current()) return;const release = claimBotComputerLifecycle(id);try {@@ -11622,6 +11623,7 @@ function configStatus() {configured: composio.configured(cfg), mode: composio.connectionMode(cfg),},box: { ...boat.describeBoatAccount(cfg), ...(boat.boatAccount(cfg)?.included ? {} : keyHint(cfg.box?.token)) },+ vpsIdle: { timeoutMinutes: vpsIdleTimeoutMinutes(cfg) },vps: { configured: Boolean(vpsSshAlias(cfg)), sshAlias: vpsSshAlias(cfg) ?? "", servers: cfg.vpsServers ?? [], ...vpsResources(cfg) },opencodeGo: { ...keyStatus(cfg.opencodeGo?.apiKey), providerKeys: Object.keys(openCodeProviderKeys(cfg)) },tts: tts.describeVoice(cfg),@@ -12247,7 +12249,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: { *values() { yield* localVmIdles.values(); yield* vpsIdles.values(); } }, localVmActiveThreads, localVmLifecycleBusy,+ lendingEnabled: () => lendingEnabled() || ownerLends(), providerConfigs, localVmIdleMs, localVmIdles, vpsIdleMs, vpsIdles, localVmActiveThreads, localVmLifecycleBusy,localVmImageBusy: { get: () => localVmImageBusy },localVmModeChangeBusy: { set: (busy) => { localVmModeChangeBusy = busy; } },localVmModeChanging: sharedVm.modeChanging,diff --git a/server/routes/config-engine-effect.test.ts b/server/routes/config-engine-effect.test.tsindex d5d3c4eac1..f8b8c7afb2 100644--- a/server/routes/config-engine-effect.test.ts+++ b/server/routes/config-engine-effect.test.ts@@ -59,6 +59,7 @@ describe("saving config and the engines' status", () => {const auth = { kind: "owner", via: "loopback", scopes: ["admin", "client"] } as unknown as RequestAuth;function routes() {+ const localDeadlines: number[] = [], vpsDeadlines: number[] = [];let forgotten = 0, broadcasts = 0;const busy = () => ({ get: () => false, set: () => {} });const deps = {@@ -80,8 +81,10 @@ describe("saving config and the engines' status", () => {sharedMembership: () => false,lendingEnabled: () => true,providerConfigs: () => ({}),- localVmIdleMs: () => 0,- localVmIdles: new Map(),+ localVmIdleMs: () => (deps.cfg.localVm?.idleTimeoutMinutes ?? 480) * 60_000,+ localVmIdles: new Map([["private", { setIdleMs: (ms: number) => localDeadlines.push(ms) }]]),+ vpsIdleMs: () => (deps.cfg.vpsIdle?.timeoutMinutes ?? 480) * 60_000,+ vpsIdles: new Map([["server", { setIdleMs: (ms: number) => vpsDeadlines.push(ms) }]]),localVmActiveThreads: new Set(),localVmLifecycleBusy: new Set(),localVmImageBusy: busy(),@@ -113,9 +116,19 @@ describe("saving config and the engines' status", () => {} as unknown as Parameters<typeof route>[0]);return replies;};- return { save, forgotten: () => forgotten, broadcasts: () => broadcasts, cfg: deps.cfg };+ return { save, localDeadlines, vpsDeadlines, forgotten: () => forgotten, broadcasts: () => broadcasts, cfg: deps.cfg };}+ it("re-arms only timers belonging to the changed idle setting", async () => {+ const { save, localDeadlines, vpsDeadlines } = routes();+ expect(await save({ vpsIdle: { timeoutMinutes: 1440 } })).toEqual([200]);+ expect(vpsDeadlines).toEqual([1440 * 60_000]);+ expect(localDeadlines).toEqual([]);+ expect(await save({ localVm: { idleTimeoutMinutes: 5 } })).toEqual([200]);+ expect(localDeadlines).toEqual([5 * 60_000]);+ expect(vpsDeadlines).toEqual([1440 * 60_000]);+ });+it("keeps every engine's status through a save of what the app shows", async () => {const { save, forgotten, broadcasts, cfg } = routes();expect(await save({ onboarding: { hintsSeen: ["welcome"] } })).toEqual([200]);diff --git a/server/routes/config.ts b/server/routes/config.tsindex d5f2a6584a..f99c0a869f 100644--- a/server/routes/config.ts+++ b/server/routes/config.ts@@ -84,6 +84,8 @@ export interface ConfigRouteDeps {sharedMembership: () => boolean;lendingEnabled(): boolean;providerConfigs(): InstanceConfigMap;+ vpsIdleMs(): number;+ vpsIdles: ConfigRouteDeps["localVmIdles"];localVmIdleMs(): number;localVmIdles: { values(): Iterable<Pick<ComputerIdleTimer, "setIdleMs">> };localVmActiveThreads: { readonly size: number };@@ -127,7 +129,7 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {const {store, cfg, registry, sessions, browserCleanup, browserLive, browserRuntime, usedBrowserSessions, decider,closeBrowser, browserEngineSwitched, sharedComputers, sharedComputerControl, hostedModels, cloudHome: CLOUD_HOME, sharedMembership, lendingEnabled, providerConfigs,- localVmIdleMs, localVmIdles, localVmActiveThreads, localVmLifecycleBusy, localVmImageBusy, localVmModeChangeBusy, localVmModeChanging,+ vpsIdleMs, vpsIdles, localVmIdleMs, localVmIdles, localVmActiveThreads, localVmLifecycleBusy, localVmImageBusy, localVmModeChangeBusy, localVmModeChanging,providerConfigBusy, computerProviderConfigTransitions, managedBoatOwners, providerOperationConflict,perBotLocalVmCountForModeChange, checkedModelSelection, policyModelRefusal, browserSessionSpec, configStatus,configForAccess, resyncOpenCodeProviderKeys, revokeEngineCapabilities, reloadProviders, broadcast, drainQueuedSends, ownProfile, ownHints, postiz,@@ -637,6 +639,9 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {postiz?.configSaved(patch);// A saved key reaches an engine through the environment its status read uses, often with no reload.if (patchMayChangeEngineStatus(patch)) registry.forgetSnapshots();+ if (patch.vpsIdle?.timeoutMinutes !== undefined) {+ for (const idle of vpsIdles.values()) idle.setIdleMs(vpsIdleMs());+ }if (patch.localVm?.idleTimeoutMinutes !== undefined) {for (const idle of localVmIdles.values()) idle.setIdleMs(localVmIdleMs());}diff --git a/server/vps-config.ts b/server/vps-config.tsindex 80bd6ef260..c6fa36a0f4 100644--- a/server/vps-config.ts+++ b/server/vps-config.ts@@ -3,6 +3,12 @@ import { z } from "zod";import { DEFAULT_DESKTOP_RESOURCES, MAX_DESKTOP_CPUS, MAX_DESKTOP_MEMORY_GB, MIN_DESKTOP_CPUS, MIN_DESKTOP_MEMORY_GB, type DesktopResources } from "./container-limits.ts";+export const vpsIdleConfigSchema = z.object({ timeoutMinutes: z.number().int().min(5).max(1_440).optional() }).strict();++export function vpsIdleTimeoutMinutes(cfg: { vpsIdle?: z.infer<typeof vpsIdleConfigSchema> }): number {+ return cfg.vpsIdle?.timeoutMinutes ?? 480;+}+const SSH_ALIAS = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;/** What each bot's VPS desktop may use on the default server. */