Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Routines: limit-reset routines refuse their own model, and keep files in their ratchet

Doğukaan Kılıçarslanbe0d16d715f5
diff --git a/apps/docs/content/docs/features/automation.mdx b/apps/docs/content/docs/features/automation.mdx
index 25bccce665..35cfac3aaa 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. A routine with its own model always opens a new thread, so a limit-reset run doesn't continue the conversation it came from. Send `"modelSelection": null` to go back to the bot's model. Room goals always use their bots' own models.
+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.
### Clear a folder's unread dots
diff --git a/server/index.ts b/server/index.ts
index f6c3bf3b05..ee1b534099 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -425,7 +425,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 { routineRunsFor } from "./routine-run-window.ts"; import { batchSaves } from "./save-batch.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 { CalendarCallManager, type CalendarCall } from "./calendar-calls.ts";
import { BROWSER_UPLOAD_TOOL, browserRuntimeEnv } from "./browser-runtime.ts";
import { BrowserUploadRefusal, uploadableFiles } from "./browser-upload.ts";
@@ -2647,15 +2647,6 @@ function retryComputerEngineMove(): Promise<void> {
return computerEngineMoveRunning;
}
-function routineModelRefusal(body: unknown): { status: number; error: string } | null {
- const raw = body && typeof body === "object" ? (body as { modelSelection?: unknown }).modelSelection : undefined;
- if (raw == null) return null;
- const checked = checkedModelSelection(raw);
- if (!checked.ok) return checked;
- (body as { modelSelection: ModelSelection }).modelSelection = checked.selection;
- return null;
-}
-
function checkedModelSelection(
raw: unknown,
current?: { selection: ModelSelection; busy: boolean },
@@ -8948,8 +8939,7 @@ routines = new RoutineManager({
return groupIsWorking(group) || coordinator.busy ? "busy" : "ready";
},
createTask: (botId, title, run) => {
- const model = run && routines?.listRoutines().find((routine) => routine.id === run.routineId)?.modelSelection;
- const task = store.createTask(botId, title, false, undefined, undefined, undefined, model || undefined);
+ const task = store.createTask(botId, title, false, undefined, undefined, undefined, (run && routines?.listRoutines().find((routine) => routine.id === run.routineId)?.modelSelection) || undefined);
// 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));
@@ -8958,9 +8948,8 @@ routines = new RoutineManager({
},
joinConversation: (run) => {
if (run.eventSource === "wait") return waitRunChat(run, directChatOf, Boolean(CLOUD_HOME));
- const routine = routines?.listRoutines().find((each) => each.id === run.routineId);
- // A routine with its own model opens its own thread: a joined conversation keeps the conversation's model.
- if (routine?.schedule.type !== "limit_reset" || routine.modelSelection || run.target !== "bot") return null;
+ const continues = routines?.listRoutines().some((routine) => routine.id === run.routineId && routine.schedule.type === "limit_reset");
+ if (!continues || run.target !== "bot") return null;
const source = routineSourceOwner(run);
if (!source || source.group || source.bot.id !== run.botId) return null;
return source.threadId;
@@ -14874,14 +14863,13 @@ 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 hidden = hiddenRoutineTarget(body, visible), notYours = routineResultsRefusal(body);
+ return routineModelRefusal(body, checkedModelSelection) ?? (hidden ? { status: 404, error: hidden } : notYours ? { status: 403, error: notYours } : null);
+ };
if (path === "/api/routines" && method === "POST") {
const body = await readBody(req);
- const model = routineModelRefusal(body);
- if (model) return json(res, model.status, { error: model.error });
- const hidden = hiddenRoutineTarget(body, visible);
- if (hidden) return json(res, 404, { error: hidden });
- const notYours = routineResultsRefusal(body);
- if (notYours) return json(res, 403, { error: notYours });
+ const refused = routineBodyRefusal(body); if (refused) return json(res, refused.status, { error: refused.error });
const writer = auth.kind === "session" ? actorKey(auth) : CLOUD_NOBODY_KEY;
const routine = withRoutineWriter(writer, () => routines!.create(body));
if (cloudRoutineAuthors && cloudOwnerSession(auth)) cloudRoutineAuthors.record(routine.id, routine);
@@ -14901,12 +14889,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
routineMatch = path.match(/^\/api\/routines\/([\w-]+)$/);
if (routineMatch && method === "PATCH") {
const body = await readBody(req);
- const model = routineModelRefusal(body);
- if (model) return json(res, model.status, { error: model.error });
- const hidden = hiddenRoutineTarget(body, visible);
- if (hidden) return json(res, 404, { error: hidden });
- const notYours = routineResultsRefusal(body);
- if (notYours) return json(res, 403, { error: notYours });
+ const refused = routineBodyRefusal(body); 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/limit-reset.e2e.test.ts b/server/limit-reset.e2e.test.ts
index a231966d4f..ad21724c8e 100644
--- a/server/limit-reset.e2e.test.ts
+++ b/server/limit-reset.e2e.test.ts
@@ -150,29 +150,6 @@ it("with no other AI to carry on, the stopped turn's Continue sets up a run that
});
}, 120_000);
-it("a limit-reset routine with its own model opens its own thread on that model, instead of continuing the conversation", async () => {
- await withLimitFixture({ codex: false }, async ({ api, control, limit, lift, evidence }) => {
- const resetsAt = Math.floor(Date.now() / 1000) + 10;
- limit(resetsAt);
- const { bot } = await control("new-bot", "--name", "Scout");
- const threadId = bot.activeTaskId;
- await control("send", "--bot", bot.id, "--task", threadId, "--text", "Write the quarterly report");
- expect((await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30")).status).toBe("failed");
- const { routine } = await api("POST", "/api/limit-resets/continue", { botId: bot.id, threadId }, 201);
- const own = { instanceId: bot.modelSelection.instanceId, model: `${bot.modelSelection.model}-routine` };
- await api("PATCH", `/api/routines/${routine.id}`, { modelSelection: own });
-
- lift();
- await expect.poll(async () => (await api("GET", "/api/routines")).runs.find((run: any) => run.routineId === routine.id)?.status, { timeout: 40_000 }).toBe("completed");
- const run = (await api("GET", "/api/routines")).runs.find((candidate: any) => candidate.routineId === routine.id);
- expect(run.threadId).not.toBe(threadId);
- const { tasks } = (await api("GET", "/api/bots")).bots.find((entry: any) => entry.id === bot.id);
- expect(tasks.find((task: any) => task.threadId === run.threadId).modelSelection).toEqual(own);
- expect(tasks.find((task: any) => task.threadId === threadId).modelSelection).toEqual(bot.modelSelection);
- evidence.push({ routine, run });
- });
-}, 120_000);
-
it("continues on the backup engine with one line, and goes back to its own engine after the reset", async () => {
await withLimitFixture({ recovery: { enabled: true, backup: codex } }, async ({ api, control, limit, lift, claudePrompts, evidence }) => {
const resetsAt = Math.floor(Date.now() / 1000) + 25;
diff --git a/server/routine-input.ts b/server/routine-input.ts
index b73106d7b9..b3d658069c 100644
--- a/server/routine-input.ts
+++ b/server/routine-input.ts
@@ -3,8 +3,19 @@ import { runsOnce } from "../shared/limit-reset.ts";
import { cleanAttachments, cleanTimeoutMinutes } from "./routine-attachments.ts";
import { loadChecks, loadModelSelection } from "./routine-load.ts";
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;
+}
+
export function sanitizeInput(input: RoutineInput, after: number): Omit<Routine, "id" | "createdAt" | "updatedAt" | "nextRunAt"> {
const name = String(input.name ?? "").trim().slice(0, 80);
const prompt = String(input.prompt ?? "").trim().slice(0, 20_000);
@@ -39,6 +50,7 @@ export function sanitizeInput(input: RoutineInput, after: number): Omit<Routine,
if (input.modelSelection != null && !modelSelection) throw new Error("Choose a model: an engine, a model id, and an effort level or a variant, not both");
if (modelSelection && target === "room-goal") throw new Error("Room goals run on their bots' own models");
const schedule = cleanSchedule(input.schedule, after);
+ if (modelSelection && schedule.type === "limit_reset") throw new Error("A limit-reset routine continues its conversation on that conversation's model");
const asked = Array.isArray(input.checks) && input.checks.length === 0 ? null : input.checks;
const checks = asked == null ? undefined : loadChecks(asked);
if (asked != null && (!checks || checks.length !== new Set(asked).size)) throw new Error("Choose checks from calendar, mail and runs");
diff --git a/server/routine-model.test.ts b/server/routine-model.test.ts
index d454348a3e..413fbe0dbe 100644
--- a/server/routine-model.test.ts
+++ b/server/routine-model.test.ts
@@ -39,6 +39,14 @@ describe("a routine's own model", () => {
expect(new RoutineManager(options).listRoutines()[0]).not.toHaveProperty("modelSelection");
});
+ it("refuses a model on a limit-reset routine, which stays on the model of the conversation it continues", () => {
+ const { routines } = manager();
+ const schedule = { type: "limit_reset" as const, engine: "claude", repeat: "once" as const };
+ expect(() => routines.create({ name: "Continue", prompt: "Carry on", botId: "maus-1", schedule, modelSelection: HAIKU })).toThrow("continues its conversation");
+ const routine = routines.create({ name: "Continue", prompt: "Carry on", botId: "maus-1", schedule });
+ expect(() => routines.update(routine.id, { modelSelection: HAIKU })).toThrow("continues its conversation");
+ });
+
it("refuses a model with no engine or model id, with both an effort and a variant, or on a room goal", () => {
const { routines } = manager();
const create = (modelSelection: unknown, target: "bot" | "room-goal" = "bot") =>
diff --git a/server/routines.ts b/server/routines.ts
index da7ae944f8..84e513b9a0 100644
--- a/server/routines.ts
+++ b/server/routines.ts
@@ -615,12 +615,7 @@ export class RoutineManager {
updatedAt: Math.max(now, routine.updatedAt + 1),
});
if (patch.enabled !== undefined) delete routine.heldFor;
- if (!clean.continuity) delete routine.continuity;
- if (!clean.modelSelection) delete routine.modelSelection;
- if (clean.overlap !== "queue") delete routine.overlap;
- if (!clean.runOnStartup) delete routine.runOnStartup;
- if (!clean.access) delete routine.access;
- if (!clean.deliver) delete routine.deliver;
+ for (const key of ["continuity", "modelSelection", "overlap", "runOnStartup", "access", "deliver"] as const) if (!clean[key]) delete routine[key];
if (!clean.checks) for (const key of ["checks", "checkedAt", "checkTrouble", "wakeAt"] as const) delete routine[key];
if (Object.hasOwn(patch, "timeoutMinutes") && patch.timeoutMinutes == null) {
delete routine.timeoutMinutes;