Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Turn a routine off after three runs in a row on a cloud computer that didn't start
AdityaUmalea78e8b3cdc1e
diff --git a/server/routine-outcomes.ts b/server/routine-outcomes.tsindex 1c59dab8e4..9ff3ebf7e5 100644--- a/server/routine-outcomes.ts+++ b/server/routine-outcomes.ts@@ -1,3 +1,5 @@+import { PLACE_EN } from "../shared/place-view.ts";+type Outcome = { id: string; routineId: string; status: string; error?: string | null; createdAt: number; finishedAt?: number | null };/** A routine's finished runs (failed or completed), newest first. */@@ -11,3 +13,19 @@ export function failsLikeLastOutcome<T extends Outcome>(runs: readonly T[], run:const last = outcomesNewestFirst(runs, run.routineId, run.id)[0];return last?.status === "failed" && last.error === run.error;}++/** Runs in a row, since the routine was last turned on or changed, that failed because its cloud computer didn't start. */+export const NO_START_RUNS_BEFORE_OFF = 3;+const [beforeBot, afterBot] = PLACE_EN["place.view.ccNoStart.line"].split("{bot}").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));+const NO_START = new RegExp(`^${beforeBot}.+${afterBot}`);++/** Each run on a cloud computer that doesn't start spends the bot's AI for minutes before it fails, so the third such+ * run in a row turns the routine off and says so. Turning it on again, or any change, starts the count afresh. A busy+ * or unavailable Cloud service is not counted: that passes by itself, and nothing would turn the routine back on. */+export function offAfterNoStarts<R extends { enabled: boolean; nextRunAt: number | null; updatedAt: number }, T extends Outcome>(routine: R | undefined, runs: readonly T[], run: T, now: number): { routine: R; alert: { detail: string } } | undefined {+ if (!routine?.enabled || run.status !== "failed" || !run.error || !NO_START.test(run.error)) return undefined;+ const earlier = outcomesNewestFirst(runs, run.routineId, run.id).slice(0, NO_START_RUNS_BEFORE_OFF - 1);+ if (earlier.length < NO_START_RUNS_BEFORE_OFF - 1 || earlier.some((other) => other.status !== "failed" || other.error !== run.error || other.createdAt < routine.updatedAt)) return undefined;+ Object.assign(routine, { enabled: false, nextRunAt: null, updatedAt: Math.max(now, routine.updatedAt + 1) });+ return { routine, alert: { detail: `${run.error} It was turned off after ${NO_START_RUNS_BEFORE_OFF} runs in a row failed this way: turn it on again once its computer starts.` } };+}diff --git a/server/routines.test.ts b/server/routines.test.tsindex a2f008f50c..601bb19135 100644--- a/server/routines.test.ts+++ b/server/routines.test.ts@@ -328,6 +328,31 @@ describe("bounded scheduled overlap and run health", () => {expect(alerts).toEqual([undefined, null, undefined, undefined]);});+ it("turns a routine off after three runs in a row on a cloud computer that didn't start, and counts afresh once turned on", async () => {+ const h = harness(start);+ const alerts: unknown[] = [];+ h.options.onRunFailed = (_run, alert) => alerts.push(alert);+ const routine = h.manager.create({ ...input(), schedule: { type: "interval", everyMinutes: 60, anchorAt: start + 3_600_000 } });+ const noStart = "Maus's cloud desktop didn't start. Change where this routine runs.";+ let thread = 0;+ const attempt = async (error: string) => {+ h.manager.runNow(routine.id); await h.manager.tick();+ h.manager.failThread(`thread-${++thread}`, error, { cause: "refused" });+ };+ await attempt(noStart);+ await attempt("Cloud computers are busy right now. Try again in a few minutes.");+ await attempt(noStart);+ await attempt(noStart);+ expect(h.manager.listRoutines()[0]).toMatchObject({ enabled: true });+ await attempt(noStart);+ expect(h.manager.listRoutines()[0]).toMatchObject({ enabled: false, nextRunAt: null });+ expect(alerts.at(-1)).toEqual({ detail: expect.stringContaining("turned off after 3 runs in a row") });+ h.manager.update(routine.id, { enabled: true });+ await attempt(noStart);+ expect(h.manager.listRoutines()[0]).toMatchObject({ enabled: true });+ expect(alerts.at(-1)).toBeNull();+ });+it("counts restart recovery only once and sanitizes obsolete or invalid health metadata", async () => {const h = harness(start);const routine = h.manager.create({ ...input(), enabled: false });diff --git a/server/routines.ts b/server/routines.tsindex ec27249270..d33a19f7c6 100644--- a/server/routines.ts+++ b/server/routines.ts@@ -27,7 +27,7 @@ import {dispatchRefusal, engineFacts, loadOwnerNotices, nextScheduledRun, recoverRun, requeueOnce, weekRuns, type RoutineAlert, type RoutineFailureFacts, type RoutineOwnerNotice,} from "./routine-recovery.ts";import { activeMs, askOf, settleAsk, waitingFor, type RoutineRunAsk } from "./routine-waits.ts";-import { failsLikeLastOutcome, outcomesNewestFirst } from "./routine-outcomes.ts";+import { failsLikeLastOutcome, offAfterNoStarts, outcomesNewestFirst } from "./routine-outcomes.ts";import { EVENT_RETRY_WINDOW_MS, loadEventReceipts, MAX_EVENT_RECEIPTS, type EventRunReceipt } from "./routine-event-receipts.ts";import { attachmentPathsOf, attachmentsMalformed, cloneAttachments } from "./routine-attachments.ts";import { loadInstalledPackage, loadRequestReceipts, loadRoutine, loadRun } from "./routine-load.ts";@@ -1366,10 +1366,10 @@ export class RoutineManager {private failRun(run: RoutineRun, message: string, status: "failed" | "missed" = "failed", alert?: RoutineAlert | null) {Object.assign(run, { status, attention: undefined, error: redactSecretsInText(message).slice(0, 500), finishedAt: this.now() } satisfies Partial<RoutineRun>);- this.saveLater();- this.emitRun(run);+ const off = offAfterNoStarts(this.routines.find((routine) => routine.id === run.routineId), this.runs, run, this.now());+ this.saveLater(); this.emitRun(run); if (off) this.emitRoutine(off.routine);const repeat = failsLikeLastOutcome(this.runs, run) || (run.checkKey !== undefined && outcomesNewestFirst(this.runs, run.routineId, run.id)[0]?.status === "failed");- this.options.onRunFailed?.(cloneRun(run), alert === undefined && repeat ? null : alert);+ this.options.onRunFailed?.(cloneRun(run), off?.alert ?? (alert === undefined && repeat ? null : alert));}private advancePastOccurrence(routine: Routine, now: number, occurrence: number) {