Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Refuse a kept computer for a bot on its team's computer
AdityaUmalef7b85d0e6300
diff --git a/server/index.ts b/server/index.tsindex 5cc5b4ae7d..491971f344 100644--- a/server/index.ts+++ b/server/index.ts@@ -8660,7 +8660,7 @@ routines = new RoutineManager({skipStartupRuns: (startedFromSleep = Boolean(CLOUD_HOME) && wokeFromSleep(DATA_DIR)), prepareRun: (run, signal) => runComputers.prepare(run, signal), preparing: RUN_COMPUTER_LINES.waking, // a Cloud home waking from a sleep it was stopped forhasPendingDelegations: runtimeWorkPending, refusedHandoff: takeRefusedRun, handedOffWorkLive: (threadId) => coordinator.outstandingFor(threadId).length > 0,routineTurn: (threadId) => directRequestOwners.get(threadId)?.automation !== undefined, personTurn: (threadId) => directRequestOwners.get(threadId)?.origin?.kind === "user", home: { machine: CLOUD_HOME?.machineId, cloud: CLOUD_HOME !== null }, turnLive: (run) => runTurnLive(run, (threadId) => ({ busy: threadBusy(run.botId, threadId), settling: settlingTurns.has(threadId), queued: queuedThreadPosition(run.botId, threadId) !== null, pending: runtimeWorkPending(threadId), parked: store.taskByThread(run.botId, threadId)?.activity === "parked.computer" })),- botState: unattendedDispatchState, pausedText: (botId, run) => botHolds.text(botId, threadLanguage(store.bot(botId)?.threadId ?? "")) ?? (run ? starterRoutineWake?.refusal(run) ?? appTriggers.runRefusal(run) : null), /* the Starter limit only as the owner's options say: a routine wakes its bot (host/starter-routine-wake.ts) */ held: (botId) => botHolds.held(botId), capSkip: (botId, routineId) => usageCapGate.routineSkip(botId, routineId), capText: (botId, trigger) => usageCapGate.runText(botId, trigger, threadLanguage(store.bot(botId)?.threadId ?? "")),+ botState: unattendedDispatchState, teamComputer: (botId) => { const bot = store.bot(botId); return Boolean(bot && inheritedTeamComputer(bot)); }, pausedText: (botId, run) => botHolds.text(botId, threadLanguage(store.bot(botId)?.threadId ?? "")) ?? (run ? starterRoutineWake?.refusal(run) ?? appTriggers.runRefusal(run) : null), /* the Starter limit only as the owner's options say: a routine wakes its bot (host/starter-routine-wake.ts) */ held: (botId) => botHolds.held(botId), capSkip: (botId, routineId) => usageCapGate.routineSkip(botId, routineId), capText: (botId, trigger) => usageCapGate.runText(botId, trigger, threadLanguage(store.bot(botId)?.threadId ?? "")),goalState: (groupId, coordinatorBotId) => {if (!groupId) return unattendedDispatchState(coordinatorBotId);const group = store.group(groupId);@@ -8866,7 +8866,7 @@ const routineRequests = new RoutineRequestService({routines, engines: { name: engineName, resetAt: (engine) => limitClock.resetAt(engine), botEngine: (botId) => store.bot(botId)?.modelSelection.instanceId },autoApply: routineAppliesDirectly,cloudReady: cloudRoutineReadiness,- canPersist: proposalPersistence, chatComputer: (botId, threadId) => chatComputer(store.taskByThread(botId, threadId)),+ canPersist: proposalPersistence, chatComputer: (botId, threadId) => { const bot = store.bot(botId); return chatComputer(store.taskByThread(botId, threadId), Boolean(bot && inheritedTeamComputer(bot))); },// The card can sit open indefinitely, so the target is re-authorized at confirm, not just at proposal.validateTarget: (proposerBotId, target) => {const proposer = store.bot(proposerBotId);diff --git a/server/routine-computer.test.ts b/server/routine-computer.test.tsindex 5b6b100fa2..a58244e247 100644--- a/server/routine-computer.test.ts+++ b/server/routine-computer.test.ts@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";-import { chatComputer, runCloudComputerOwner, runComputerPin } from "./routine-computer.ts";+import { chatComputer, runCloudComputerOwner, runComputerPin, TEAM_COMPUTER_REFUSAL } from "./routine-computer.ts";import { loadRoutine, loadRun } from "./routine-load.ts";import { RoutineRequestService, type RoutineRequestMessage, type RoutineRequestOptionCard, type RoutineRequestStore } from "./routine-requests.ts";import { routineRunDefinition } from "./routine-run-definition.ts";@@ -19,7 +19,7 @@ const daily = { type: "daily" as const, time: "09:00", weekdays: [1] };const base: RoutineInput = { name: "Inbox sweep", prompt: "Sweep the inbox", botId: "bot-a", schedule: daily };type Pin = { surface?: "local" | "vm" | "cloud" | "browser"; surfaceSource?: "user" | "auto" };-function manager() {+function manager(teamBots: string[] = []) {const dir = mkdtempSync(join(tmpdir(), "omb-routine-computer-"));dirs.push(dir);const options: RoutineManagerOptions = {@@ -28,6 +28,7 @@ function manager() {botState: () => "ready",createTask: () => ({ threadId: "thread-1" }),startTurn: async () => {},+ teamComputer: (botId) => teamBots.includes(botId),};return { options, routines: new RoutineManager(options) };}@@ -49,15 +50,15 @@ class MemoryStore implements RoutineRequestStore {}}-function chatCards(pins: Record<string, Pin>) {- const { routines } = manager();+function chatCards(pins: Record<string, Pin>, teamBots: string[] = []) {+ const { routines } = manager(teamBots);const requests = new RoutineRequestService({store: new MemoryStore(),routines,now: () => START,timeZone: () => "UTC",autoApply: () => "full-access",- chatComputer: (botId, threadId) => chatComputer(pins[`${botId}/${threadId}`]),+ chatComputer: (botId, threadId) => chatComputer(pins[`${botId}/${threadId}`], teamBots.includes(botId)),});const create = (threadId: string, forBot?: { botId: string; name: string }) => requests.submit({botId: "bot-a",@@ -84,6 +85,13 @@ describe("a routine made in a chat keeps that chat's computer", () => {expect(byThread).toEqual({ pinned: "vm", auto: undefined, plain: undefined });});+ it("keeps nothing in the chat of a bot on its team's computer, so the card still saves", async () => {+ const { routines, create } = chatCards({ "bot-a/pinned": { surface: "vm", surfaceSource: "user" } }, ["bot-a"]);+ await create("pinned");+ expect(routines.listRoutines()).toHaveLength(1);+ expect(routines.listRoutines()[0]).not.toHaveProperty("computer");+ });+it("keeps nothing for a routine made for another bot, which works on its own setting", async () => {const { routines, create } = chatCards({ "bot-a/pinned": { surface: "local", surfaceSource: "user" } });await create("pinned", { botId: "bot-b", name: "Peer" });@@ -128,6 +136,26 @@ describe("a routine's own computer", () => {expect(routines.update(routine.id, { runOn: "cloud" })).not.toHaveProperty("computer");});+ it("is refused for a bot on its team's computer, which every turn of it uses, but a cloud one and other edits still save", () => {+ const { routines } = manager(["bot-a"]);+ expect(() => routines.create({ ...base, computer: "vm" })).toThrow(TEAM_COMPUTER_REFUSAL);+ expect(() => routines.create({ ...base, computer: "local" })).toThrow(TEAM_COMPUTER_REFUSAL);+ expect(routines.create({ ...base, computer: "cloud" }).computer).toBe("cloud");+ const routine = routines.create(base);+ expect(() => routines.update(routine.id, { computer: "browser" })).toThrow(TEAM_COMPUTER_REFUSAL);+ expect(routines.update(routine.id, { prompt: "Sweep it twice" })?.prompt).toBe("Sweep it twice");+ expect(routines.create({ ...base, botId: "bot-b", computer: "vm" }).computer).toBe("vm");+ });++ it("still lets a routine saved before its bot joined a team computer be edited", () => {+ const team: string[] = [];+ const { routines } = manager(team);+ const routine = routines.create({ ...base, computer: "vm" });+ team.push("bot-a");+ expect(routines.update(routine.id, { prompt: "Sweep it twice" })?.computer).toBe("vm");+ expect(routines.update(routine.id, { computer: null })).not.toHaveProperty("computer");+ });+it("loads a kept computer and drops one that is unknown or on a room goal", () => {const saved: Routine = { ...manager().routines.create(base), computer: "vm" };expect(loadRoutine(saved, START)?.computer).toBe("vm");diff --git a/server/routine-computer.ts b/server/routine-computer.tsindex dad15b1725..97f7da2eaa 100644--- a/server/routine-computer.ts+++ b/server/routine-computer.ts@@ -9,9 +9,17 @@ export function routineComputer(value: unknown, routine: { target?: Routine["tarreturn ROUTINE_COMPUTERS.find((computer) => computer === value);}-/** The computer the person chose for a chat; a place a turn picked on its own (Auto) is not kept. */-export function chatComputer(task: { surface?: RoutineComputer; surfaceSource?: "user" | "auto" } | undefined): RoutineComputer | undefined {- return chosenPin(task) ?? undefined;+/** A bot on its team's computer works there on every turn, so its routines may keep only the cloud computer. */+export const TEAM_COMPUTER_REFUSAL = "This bot works on its team's cloud computer, so its routines can't keep another computer. Clear the computer, or take the bot off the team computer first.";++/** Why a routine of this bot can't keep `computer`, or null when it can. */+export function keptComputerRefusal(computer: RoutineComputer | undefined, onTeamComputer: boolean): string | null {+ return computer && computer !== "cloud" && onTeamComputer ? TEAM_COMPUTER_REFUSAL : null;+}++/** The computer the person chose for a chat; a place a turn picked on its own (Auto) is not kept, nor any by a bot on its team's computer. */+export function chatComputer(task: { surface?: RoutineComputer; surfaceSource?: "user" | "auto" } | undefined, onTeamComputer = false): RoutineComputer | undefined {+ return onTeamComputer ? undefined : chosenPin(task) ?? undefined;}/** The pin a run's own new conversation starts with, so its turns work where the routine's chat did. */diff --git a/server/routines.ts b/server/routines.tsindex 19b64d0483..559477231e 100644--- a/server/routines.ts+++ b/server/routines.ts@@ -36,7 +36,7 @@ import { EVENT_RETRY_WINDOW_MS, MAX_EVENT_RECEIPTS, type EventRunReceipt } fromimport { attachmentPathsOf, cloneAttachments } from "./routine-attachments.ts";import { loadInstalledPackage, matchingRequestReceipt, rememberRequest } from "./routine-load.ts";import { applyHolds, holdCauses, type AppliedHolds } from "./routine-holds.ts";-import { cancelUnfinishedRuns, interruptRunTurns } from "./routine-stops.ts";+import { cancelUnfinishedRuns, interruptRunTurns } from "./routine-stops.ts"; import { keptComputerRefusal } from "./routine-computer.ts";import { sanitizeInput } from "./routine-input.ts";import { applyCheckResult, codedLine, keptRunOutput, routineLine, runLineFields, type RoutineLine, type RoutineLineCodes, type RoutineTroubleCode } from "./routine-lines.ts";import { checkHold, CHECK_BOOT_HOLD_MS, type CheckHold } from "./routine-check-pacing.ts";@@ -239,7 +239,7 @@ export interface RoutineManagerOptions {now?: () => number;/** Every payload must be `{ kind, … }`: the server numbers and replays frames by it. */emit?: (payload: Record<string, unknown>) => void;- botState: (botId: string) => "ready" | "busy" | "missing";+ botState: (botId: string) => "ready" | "busy" | "missing"; /** The bot works on its team's computer, which every one of its turns uses. */ teamComputer?: (botId: string) => boolean;/** Why this bot takes no runs now (or not `run`), in the person's words; null when it does. */ pausedText?: (botId: string, run?: RoutineRun) => string | null; /** The person paused this bot: its runs are let go quietly, not failed into To review. */ held?: (botId: string) => boolean; /** A reached usage cap (host/usage-cap-gate.ts): `capSkip` for a scheduled occurrence, which is counted on one `missed` row per cap and period and never switches the routine off; `capText` for a run already queued. */ capSkip?: (botId: string, routineId: string) => { behind: string; resetsAt: number; words(count: number): RoutineLine } | null; capText?: (botId: string, trigger: RoutineRunTrigger) => string | null;goalState?: (groupId: string | undefined, coordinatorBotId: string) => "ready" | "busy" | "missing";createTask: (botId: string, title: string, run?: RoutineRun) => { threadId: string } | null;@@ -566,6 +566,7 @@ export class RoutineManager {const clean = sanitizeInput(input, at);clean.schedule = this.timedSchedule(clean.schedule);if (this.targetState(clean) === "missing") throw new Error(this.missingTargetMessage(clean.target));+ this.refuseKeptComputer(clean);const nextRunAt = clean.enabled ? this.initialOccurrence(clean.schedule, at) : null;if (clean.schedule.type === "interval" && clean.enabled && nextRunAt === null) {throw new Error("This interval has no future runs. Choose a later end date or turn it off.");@@ -629,6 +630,7 @@ export class RoutineManager {}, now);clean.schedule = this.timedSchedule(clean.schedule, routine.id);if (this.targetState(clean) === "missing") throw new Error(this.missingTargetMessage(clean.target));+ if (patch.computer) this.refuseKeptComputer(clean);const scheduleChanged = JSON.stringify(clean.schedule) !== JSON.stringify(routine.schedule);const enabledChanged = clean.enabled !== routine.enabled;if (enabledChanged && clean.enabled && clean.schedule.type === "once" && clean.schedule.at <= now) throw new RoutineScheduleError("Its time has passed. Edit it to pick a new time.");@@ -1409,6 +1411,11 @@ export class RoutineManager {return this.options.botState(target.botId);}+ private refuseKeptComputer(routine: { botId: string; computer?: RoutineComputer }): void {+ const refusal = keptComputerRefusal(routine.computer, this.options.teamComputer?.(routine.botId) === true);+ if (refusal) throw new Error(refusal);+ }+private missingTargetMessage(target: RoutineTarget): string {return target === "room-goal"? "The assigned room or coordinator no longer exists"