Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Routines: a routine's model keeps its bot's permission level
milind-soni60f775269fa1
diff --git a/apps/docs/content/docs/features/automation.mdx b/apps/docs/content/docs/features/automation.mdxindex 35cfac3aaa..82de6cc7b3 100644--- a/apps/docs/content/docs/features/automation.mdx+++ b/apps/docs/content/docs/features/automation.mdx@@ -38,7 +38,7 @@ If your computer is often off when a routine is due, open the routine's **Advanc### A routine's own model-A routine runs on its bot's model unless it has its own. Give it one through the API with `modelSelection` (the same shape as a bot's: `instanceId`, `model`, and an optional `effort` or `variant`), for example a light hourly check on a smaller model while the bot chats on a stronger one: `PATCH /api/routines/<id>` with `{"modelSelection": {"instanceId": "claude", "model": "claude-haiku-4-5"}}`. Each run's thread then uses that model; if its AI isn't available, the thread falls back to the bot's model. Room goals always use their bots' own models, and a limit-reset routine stays on the model of the conversation it continues. Send `"modelSelection": null` to go back to the bot's model.+A routine runs on its bot's model unless it has its own. Give it one through the API with `modelSelection` (the same shape as a bot's: `instanceId`, `model`, and an optional `effort` or `variant`), for example a light hourly check on a smaller model while the bot chats on a stronger one: `PATCH /api/routines/<id>` with `{"modelSelection": {"instanceId": "claude", "model": "claude-haiku-4-5"}}`. Each run's thread then uses that model; if its AI isn't available, the thread falls back to the bot's model. The model has to keep the bot's permission level, as a bot's own model change does: with Custom approval it must run on the bot's own engine, and with Auto-accept edits on an engine that has that level. Other models are refused, and if the bot's permissions change later so the routine's model no longer fits, runs use the bot's model. Room goals always use their bots' own models, and a limit-reset routine stays on the model of the conversation it continues. Send `"modelSelection": null` to go back to the bot's model.### Clear a folder's unread dotsdiff --git a/server/index.ts b/server/index.tsindex 1ef95f710e..6422f151ba 100644--- a/server/index.ts+++ b/server/index.ts@@ -426,7 +426,7 @@ import { claudeUserSkillsEnabled, settingsTurnFields } 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 { ROUTINE_RESTARTED, RoutineManager, type RoutineRun, type RoutineRunOn, type RoutineRunTrigger } from "./routines.ts"; import { routineModelRefusal } from "./routine-input.ts"; import { routineRunsFor } from "./routine-run-window.ts"; import { batchSaves } from "./save-batch.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 { routineRunsFor } from "./routine-run-window.ts"; import { batchSaves } from "./save-batch.ts";import { CalendarCallManager, type CalendarCall } from "./calendar-calls.ts";import { BROWSER_UPLOAD_TOOL, browserRuntimeEnv } from "./browser-runtime.ts";import { BrowserUploadRefusal, uploadableFiles } from "./browser-upload.ts";@@ -8810,6 +8810,7 @@ const limitFailovers = new LimitFailovers({ file: join(DATA_DIR, "limit-failover} });const automationDestinations = createAutomationDestinations({ store, mainThread: botMainThread, runs: () => routines?.listRuns() ?? [],cloud: CLOUD_HOME ? { owner: CLOUD_OWNER_KEY!, opener: routineOpener, reportFromOthers: cloudReportFromOthers, opened: (threadId, person) => threadStarters.set(threadId, person), outside: (threadId) => outsideLineage.mark(threadId) } : null });+const routineModelChecks: RoutineModelChecks = { check: (raw) => checkedModelSelection(raw), bot: (botId) => store.bot(botId), engineSwitchNeedsAsk };routines = new RoutineManager({emit: broadcast, limitResetAt: (engine) => limitClock.resetAt(engine), checks: proactive.checks,limitBackup: (botId, scope) => { const bot = store.bot(botId); return quotaSwitchEnabled() ? Boolean(bot && limitTakeover.backups(botId, bot.modelSelection, scope, approvalModeFor(bot)).length) : Boolean(bot && startupBackups(bot, cfg.automaticRecovery).length); },@@ -8836,7 +8837,7 @@ routines = new RoutineManager({return groupIsWorking(group) || coordinator.busy ? "busy" : "ready";},createTask: (botId, title, run) => {- const task = store.createTask(botId, title, false, undefined, undefined, undefined, (run && routines?.listRoutines().find((routine) => routine.id === run.routineId)?.modelSelection) || undefined);+ const task = store.createTask(botId, title, false, undefined, undefined, undefined, routineThreadModel(run && routines?.listRoutines().find((routine) => routine.id === run.routineId), routineModelChecks));// On a Cloud home the routine's writer opens a run's conversation; a webhook run is the owner's, but its payload never reaches the lent Mac.if (task && CLOUD_HOME && run) {threadStarters.set(task.threadId, run.triggerSource === "webhook" ? CLOUD_OWNER_KEY! : routineOpener(run.routineId));@@ -14776,9 +14777,9 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const routineResultsRefusal = (body: unknown): string | null =>body && typeof body === "object" && typeof (body as { resultsThreadId?: unknown }).resultsThreadId === "string"? cloudThreadRefusal(auth, (body as { resultsThreadId: string }).resultsThreadId) : null;- const routineBodyRefusal = (body: unknown): { status: number; error: string } | null => {+ const routineBodyRefusal = (body: unknown, existing?: Routine): { status: number; error: string } | null => {const hidden = hiddenRoutineTarget(body, visible), notYours = routineResultsRefusal(body);- return routineModelRefusal(body, checkedModelSelection) ?? (hidden ? { status: 404, error: hidden } : notYours ? { status: 403, error: notYours } : null);+ return hidden ? { status: 404, error: hidden } : notYours ? { status: 403, error: notYours } : routineModelRefusal(body, routineModelChecks, existing);};if (path === "/api/routines" && method === "POST") {const body = await readBody(req);@@ -14802,7 +14803,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {routineMatch = path.match(/^\/api\/routines\/([\w-]+)$/);if (routineMatch && method === "PATCH") {const body = await readBody(req);- const refused = routineBodyRefusal(body); if (refused) return json(res, refused.status, { error: refused.error });+ const refused = routineBodyRefusal(body, routines!.listRoutines().find((candidate) => candidate.id === routineMatch![1])); if (refused) return json(res, refused.status, { error: refused.error });const authors = cloudRoutineAuthors ?? phones.routineAuthors;const before = authors ? routines!.listRoutines().find((candidate) => candidate.id === routineMatch![1]) : undefined;const wasOwners = Boolean(before && authors?.authored(before.id, before));diff --git a/server/routine-input.ts b/server/routine-input.tsindex b3d658069c..40d210e76f 100644--- a/server/routine-input.ts+++ b/server/routine-input.ts@@ -1,4 +1,5 @@// A routine as a person, a bot or an import asked for it, checked and cleaned before RoutineManager keeps it.+import { approvalModeFor, type ApprovalMode } from "../shared/approval-mode.ts";import { runsOnce } from "../shared/limit-reset.ts";import { cleanAttachments, cleanTimeoutMinutes } from "./routine-attachments.ts";import { loadChecks, loadModelSelection } from "./routine-load.ts";@@ -6,14 +7,43 @@ import { cleanSchedule } from "./routine-schedules.ts";import type { ModelSelection } from "../shared/wire.ts";import type { Routine, RoutineInput } from "./routines.ts";-/** Checks a requested routine model the way a bot's is checked, and leaves the checked form in the body. */-export function routineModelRefusal(body: unknown, check: (raw: unknown) => { ok: true; selection: ModelSelection } | { ok: false; status: number; error: string }): { status: number; error: string } | null {- const raw = body && typeof body === "object" ? (body as { modelSelection?: unknown }).modelSelection : undefined;- if (raw == null) return null;- const checked = check(raw);- if (!checked.ok) return checked;- (body as { modelSelection: ModelSelection }).modelSelection = checked.selection;- return null;+type Refusal = { status: number; error: string };++/** What a routine's model is held to: the checks a bot's own model change gets. */+export interface RoutineModelChecks {+ check(raw: unknown): { ok: true; selection: ModelSelection } | ({ ok: false } & Refusal);+ bot(botId: string): (Parameters<typeof approvalModeFor>[0] & { modelSelection: ModelSelection }) | null | undefined;+ engineSwitchNeedsAsk(mode: ApprovalMode, from: ModelSelection, to: ModelSelection): boolean;+}++export const ROUTINE_MODEL_PERMISSIONS = "That model runs on another engine, which can't keep this bot's permission level. Choose a model on the bot's own engine, or change the bot's permissions first.";++/** A run's thread keeps its bot's permission level, so its model may change engines only where a bot's own model change could+ * without dropping to Ask: a Custom grant never leaves its engine, and Auto-accept edits stops at an engine without it. */+function keepsPermissions(checks: Pick<RoutineModelChecks, "bot" | "engineSwitchNeedsAsk">, botId: string, selection: ModelSelection): boolean {+ const bot = checks.bot(botId);+ return !bot || !checks.engineSwitchNeedsAsk(approvalModeFor(bot), bot.modelSelection, selection);+}++/** Checks a requested routine model the way a bot's is checked, and leaves the checked form in the body. A move to another bot+ * checks the model the routine already has against that bot. */+export function routineModelRefusal(body: unknown, checks: RoutineModelChecks, existing?: Pick<Routine, "botId" | "modelSelection">): Refusal | null {+ const fields = body && typeof body === "object" ? body as { modelSelection?: unknown; botId?: unknown } : {};+ if (fields.modelSelection == null && fields.botId === undefined) return null;+ let selection = fields.modelSelection === null ? undefined : existing?.modelSelection;+ if (fields.modelSelection != null) {+ const checked = checks.check(fields.modelSelection);+ if (!checked.ok) return { status: checked.status, error: checked.error };+ selection = (body as { modelSelection: ModelSelection }).modelSelection = checked.selection;+ }+ const botId = typeof fields.botId === "string" ? fields.botId : existing?.botId;+ return selection && botId && !keepsPermissions(checks, botId, selection) ? { status: 400, error: ROUTINE_MODEL_PERMISSIONS } : null;+}++/** The model a run opens its thread on: the routine's own, unless its bot's permissions changed since so that it no longer may. */+export function routineThreadModel(routine: Pick<Routine, "botId" | "modelSelection"> | undefined,+ checks: Pick<RoutineModelChecks, "bot" | "engineSwitchNeedsAsk">): ModelSelection | undefined {+ return routine?.modelSelection && keepsPermissions(checks, routine.botId, routine.modelSelection) ? routine.modelSelection : undefined;}export function sanitizeInput(input: RoutineInput, after: number): Omit<Routine, "id" | "createdAt" | "updatedAt" | "nextRunAt"> {diff --git a/server/routine-model.test.ts b/server/routine-model.test.tsindex 413fbe0dbe..7e088604c2 100644--- a/server/routine-model.test.ts+++ b/server/routine-model.test.ts@@ -3,6 +3,9 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";+import { modelSwitchNeedsAsk, type ApprovalMode } from "../shared/approval-mode.ts";+import type { ModelSelection } from "../shared/wire.ts";+import { ROUTINE_MODEL_PERMISSIONS, routineModelRefusal, routineThreadModel, type RoutineModelChecks } from "./routine-input.ts";import { RoutineManager, type RoutineManagerOptions } from "./routines.ts";const dirs: string[] = [];@@ -58,3 +61,43 @@ describe("a routine's own model", () => {expect(routines.listRoutines()).toEqual([]);});});++describe("a routine's model and its bot's permissions", () => {+ const DRIVERS: Record<string, string> = { claude: "claudeAgent", codex: "codex", gemini: "geminiAgent", pi: "pi" };+ const CODEX = { instanceId: "codex", model: "gpt-5-codex" };+ const bots: Record<string, { modelSelection: ModelSelection; approvalMode: ApprovalMode }> = {+ custom: { modelSelection: CODEX, approvalMode: "custom" },+ edits: { modelSelection: HAIKU, approvalMode: "edits" },+ full: { modelSelection: CODEX, approvalMode: "full" },+ };+ const checks: RoutineModelChecks = {+ check: (raw) => ({ ok: true, selection: raw as ModelSelection }),+ bot: (botId) => bots[botId],+ engineSwitchNeedsAsk: (mode, from, to) => modelSwitchNeedsAsk(mode, DRIVERS[from.instanceId], DRIVERS[to.instanceId]),+ };+ const refusal = { status: 400, error: ROUTINE_MODEL_PERMISSIONS };++ it("refuses a model on another engine that the bot's permission level can't move to, as a bot's own model change is", () => {+ expect(routineModelRefusal({ botId: "custom", modelSelection: HAIKU }, checks)).toEqual(refusal);+ expect(routineModelRefusal({ botId: "edits", modelSelection: { instanceId: "pi", model: "pi-1" } }, checks)).toEqual(refusal);+ });++ it("keeps a model on the bot's own engine, or on any engine the permission level carries to", () => {+ expect(routineModelRefusal({ botId: "custom", modelSelection: { ...CODEX, model: "gpt-5-mini" } }, checks)).toBeNull();+ expect(routineModelRefusal({ botId: "edits", modelSelection: { instanceId: "gemini", model: "gemini-flash" } }, checks)).toBeNull();+ expect(routineModelRefusal({ botId: "full", modelSelection: HAIKU }, checks)).toBeNull();+ });++ it("checks the routine's model again when an edit moves it to another bot, and not when the edit drops it", () => {+ const existing = { botId: "full", modelSelection: HAIKU };+ expect(routineModelRefusal({ botId: "custom" }, checks, existing)).toEqual(refusal);+ expect(routineModelRefusal({ botId: "custom", modelSelection: null }, checks, existing)).toBeNull();+ expect(routineModelRefusal({ prompt: "Sweep twice" }, checks, existing)).toBeNull();+ });++ it("opens a run on the bot's model once the bot's permissions no longer let the routine's model through", () => {+ expect(routineThreadModel({ botId: "full", modelSelection: HAIKU }, checks)).toEqual(HAIKU);+ expect(routineThreadModel({ botId: "custom", modelSelection: HAIKU }, checks)).toBeUndefined();+ expect(routineThreadModel({ botId: "custom" }, checks)).toBeUndefined();+ });+});