Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Limit-reset automations: a read just after the reset no longer skips the run (#5958)
Milind Soni07552cb14873
diff --git a/server/limit-poll.test.ts b/server/limit-poll.test.tsindex 3f8cb6b00c..48d2d09e31 100644--- a/server/limit-poll.test.ts+++ b/server/limit-poll.test.ts@@ -4,7 +4,7 @@ import { join } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";import { LimitResetClock } from "./limit-resets.ts";-import { LIMIT_ACTIVE_MS, LIMIT_IDLE_POLL_MS, LIMIT_POLL_MS, limitReadDue, RESET_READ_AFTER_MS } from "./limit-poll.ts";+import { LIMIT_ACTIVE_MS, LIMIT_IDLE_POLL_MS, LIMIT_POLL_MS, limitReadDue, RESET_READ_AFTER_MS, retryAfterFailureMs } from "./limit-poll.ts";import { parseClaudeUsage, type PlanUsageReport } from "./plan-usage.ts";import { RoutineManager, type RoutineRun } from "./routines.ts";import type { RuntimeEvent } from "../shared/runtime-events.ts";@@ -51,6 +51,18 @@ describe("limitReadDue", () => {it("reads at once when it never read", () => {expect(limitReadDue({ ...state, checkedAt: 0 })).toBe(true);});++ it("reads at once when the clock was set back past the last read", () => {+ expect(limitReadDue({ ...state, checkedAt: NOW + 2 * HOUR })).toBe(true);+ expect(limitReadDue({ ...state, checkedAt: NOW + 2 * HOUR, lastTurnAt: NOW + 2 * HOUR })).toBe(true);+ });++ it("tries a failed read again in minutes, backing off to the hourly read", () => {+ expect([1, 2, 3, 4, 5].map(retryAfterFailureMs)).toEqual([5 * MINUTE, 10 * MINUTE, 20 * MINUTE, 40 * MINUTE, HOUR]);+ expect(limitReadDue({ ...state, checkedAt: NOW - 5 * MINUTE, failures: 1 })).toBe(true);+ expect(limitReadDue({ ...state, checkedAt: NOW - 5 * MINUTE, failures: 2 })).toBe(false);+ expect(limitReadDue({ ...state, checkedAt: NOW - 4 * MINUTE, failures: 1 }), "never a tight loop").toBe(false);+ });});describe("the limit clock on a quiet home", () => {@@ -140,3 +152,138 @@ describe("the limit clock on a quiet home", () => {routines.stop();});});++/** A clock and a RoutineManager wired as index.ts wires them. */+function wired(loadUsage: () => Promise<PlanUsageReport>, file?: string) {+ const dir = mkdtempSync(join(tmpdir(), "omb-limit-poll-"));+ dirs.push(dir);+ const started: string[] = [];+ let routines: RoutineManager | null = null;+ const clock = new LimitResetClock({ accounts: () => accounts, loadUsage, onChange: () => routines?.retimeLimitResets(), ...(file ? { file } : {}),+ waiting: () => Boolean(routines?.listRoutines().some((routine) => routine.enabled && routine.schedule.type === "limit_reset")) });+ routines = new RoutineManager({+ file: join(dir, "routines.json"), now: () => Date.now(), emit: () => {}, botState: () => "ready" as const,+ createTask: () => ({ threadId: `thread-${started.length + 1}` }), joinConversation: (run: RoutineRun) => run.sourceThreadId ?? null,+ startTurn: async (_botId: string, threadId: string) => { started.push(threadId); },+ limitResetAt: (engine: string) => clock.resetAt(engine),+ });+ return { clock, routines, started };+}+/** Claude's usage just after its five-hour window reset, before a turn starts the next one: only the weekly window has a reset. */+const unstarted = (weekly: [number, number]): PlanUsageReport => ({+ fetchedAt: iso(Date.now()),+ providers: [{ id: "claude", name: "Claude", driver: "claude", ok: true, error: null, ...parseClaudeUsage({+ five_hour: { utilization: 0, resets_at: null }, seven_day: { utilization: weekly[0], resets_at: iso(weekly[1]) },+ }) }],+});+const unreachable = (): PlanUsageReport => ({ fetchedAt: iso(Date.now()),+ providers: [{ id: "claude", name: "Claude", driver: "claude", ok: false, error: "Couldn't reach Claude", fiveHour: { available: false, remainingPercent: null, usedPercent: null, resetsAt: null }, weekly: { available: false, remainingPercent: null, usedPercent: null, resetsAt: null }, extra: [], models: [] } as never] });++describe("the limit clock and the automations that wait for a reset", () => {+ it("a read seconds after the reset (someone opens the limits) shows only Claude's weekly window: the automation still starts on time", async () => {+ vi.useFakeTimers({ now: NOW });+ const reset = NOW + 20 * MINUTE + 30_000;+ let report = usage([100, reset], [40, NOW + 4 * 24 * HOUR]);+ const { clock, routines, started } = wired(async () => ({ ...report, fetchedAt: iso(Date.now()) }));+ routines.create({ name: "Carry on", prompt: "Carry on.", botId: "scout", schedule: { type: "limit_reset", engine: "claude", repeat: "once" } });+ clock.start();+ await vi.advanceTimersByTimeAsync(MINUTE);+ expect(routines.listRoutines()[0]!.nextRunAt).toBe(reset + 60_000);+ report = unstarted([40, NOW + 4 * 24 * HOUR]);+ await vi.advanceTimersByTimeAsync(reset + 10_000 - Date.now());+ await clock.ensureFresh(0);+ expect(clock.resetAt("claude"), "the weekly window now").toBe(NOW + 4 * 24 * HOUR);+ expect(routines.listRoutines()[0]!.nextRunAt, "not moved days away").toBe(reset + 60_000);+ await vi.advanceTimersByTimeAsync(MINUTE);+ await routines.tick();+ expect(started).toHaveLength(1);+ clock.stop();+ routines.stop();+ });++ it("a hold that ends a minute and a half after its window's reset: the read after the window ends the hold, and the automation still starts once", async () => {+ vi.useFakeTimers({ now: NOW });+ const reset = NOW + 20 * MINUTE + 30_000, held = reset + 90_000;+ let report = usage([100, reset], [40, NOW + 4 * 24 * HOUR]);+ const loadUsage = vi.fn(async () => ({ ...report, fetchedAt: iso(Date.now()) }));+ const { clock, routines, started } = wired(loadUsage);+ clock.noteRefusal("claude", held);+ routines.create({ name: "Carry on", prompt: "Carry on.", botId: "scout", schedule: { type: "limit_reset", engine: "claude", repeat: "every_reset" } });+ clock.start();+ await vi.advanceTimersByTimeAsync(MINUTE);+ expect(routines.listRoutines()[0]!.nextRunAt, "timed by the hold, the later of the two").toBe(held + 60_000);+ report = usage([3, reset + 5 * HOUR], [2, NOW + 4 * 24 * HOUR]);+ loadUsage.mockClear();+ for (let at = Date.now(); at < held + 5 * MINUTE; at = Date.now()) {+ await vi.advanceTimersByTimeAsync(30_000);+ await routines.tick();+ if (Date.now() > held) expect(clock.blockedUntil("claude"), "the hold ended at its time").toBeNull();+ }+ expect(started, "once, after the hold").toHaveLength(1);+ // The read two minutes after the window's reset shows room, which ends the hold, 30 s before the automation is due.+ expect(loadUsage.mock.calls.length, "a read after the window's reset").toBeGreaterThanOrEqual(1);+ expect(routines.listRoutines()[0]!.nextRunAt, "then the next window").toBe(reset + 5 * HOUR + 60_000);+ clock.stop();+ routines.stop();+ });+});++describe("the limit clock after a restart, a clock change or a failed read", () => {+ it("reads at once after a restart that left an engine held", async () => {+ vi.useFakeTimers({ now: NOW });+ const dir = mkdtempSync(join(tmpdir(), "omb-limit-holds-"));+ dirs.push(dir);+ const file = join(dir, "limit-holds.json");+ new LimitResetClock({ accounts: () => accounts, file, now: () => NOW }).noteRefusal("claude", NOW + 23 * HOUR);+ const loadUsage = vi.fn(async () => usage([100, NOW + 23 * HOUR], [40, NOW + 5 * 24 * HOUR]));+ const restarted = new LimitResetClock({ accounts: () => accounts, file, loadUsage, waiting: () => false });+ expect(restarted.blockedUntil("claude"), "the hold came back").toBe(NOW + 23 * HOUR);+ restarted.start();+ await vi.advanceTimersByTimeAsync(MINUTE);+ expect(loadUsage).toHaveBeenCalledTimes(1);+ restarted.stop();+ });++ it("reads at once when the clock is set back, not an hour after the time it had", async () => {+ vi.useFakeTimers({ now: NOW });+ const loadUsage = vi.fn(async () => usage([100, NOW + 23 * HOUR], [40, NOW + 5 * 24 * HOUR]));+ const instance = new LimitResetClock({ accounts: () => accounts, loadUsage, waiting: () => true });+ instance.start();+ await vi.advanceTimersByTimeAsync(MINUTE);+ expect(loadUsage).toHaveBeenCalledTimes(1);+ vi.setSystemTime(Date.now() - 3 * HOUR);+ await vi.advanceTimersByTimeAsync(MINUTE);+ expect(loadUsage).toHaveBeenCalledTimes(2);+ await vi.advanceTimersByTimeAsync(30 * MINUTE);+ expect(loadUsage, "then quiet again").toHaveBeenCalledTimes(2);+ instance.stop();+ });++ it("tries a failed read again in minutes, backing off, with no tight loop, and goes back to hourly once one works", async () => {+ vi.useFakeTimers({ now: NOW });+ let failing = 3;+ const loadUsage = vi.fn(async () => {+ if (failing-- > 0) {+ if (failing === 1) throw new Error("offline");+ return unreachable();+ }+ return usage([100, NOW + 23 * HOUR], [40, NOW + 5 * 24 * HOUR]);+ });+ const instance = new LimitResetClock({ accounts: () => accounts, loadUsage, waiting: () => true });+ instance.start();+ await vi.advanceTimersByTimeAsync(MINUTE);+ expect(loadUsage, "the first read, which fails").toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(4 * MINUTE);+ expect(loadUsage, "no retry within minutes").toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(MINUTE);+ expect(loadUsage, "five minutes later").toHaveBeenCalledTimes(2);+ await vi.advanceTimersByTimeAsync(10 * MINUTE);+ expect(loadUsage, "ten minutes after that").toHaveBeenCalledTimes(3);+ await vi.advanceTimersByTimeAsync(20 * MINUTE);+ expect(loadUsage, "twenty after that, and it works").toHaveBeenCalledTimes(4);+ expect(instance.limit("claude")?.usedPercent).toBe(100);+ await vi.advanceTimersByTimeAsync(55 * MINUTE);+ expect(loadUsage, "hourly again").toHaveBeenCalledTimes(4);+ instance.stop();+ });+});diff --git a/server/limit-poll.ts b/server/limit-poll.tsindex 50eecbd46e..5c11155eee 100644--- a/server/limit-poll.ts+++ b/server/limit-poll.ts@@ -11,8 +11,9 @@ export const LIMIT_POLL_MS = 5 * 60_000;export const LIMIT_ACTIVE_MS = 15 * 60_000;/** With nothing running, the most usage goes unread while something holds or waits. */export const LIMIT_IDLE_POLL_MS = 60 * 60_000;-/** A known reset is read this long after its time: a minute after the automation waiting for it starts, so the new- * window's reset re-times an automation that repeats, never one still due for this reset. */+/** A known reset is read this long after its time, a minute after the automation waiting for it starts. A read that+ * lands sooner (another window's, a person's, the first after a wake) leaves an automation still owed a run for this+ * reset where it is too (limit-reset-owed.ts); the new window re-times it once that run was made. */export const RESET_READ_AFTER_MS = AFTER_RESET_MS + 60_000;export interface LimitReadState {@@ -23,12 +24,21 @@ export interface LimitReadState {lastTurnAt: number;/** The reset times known now: the holds' and the usage windows'. */resets: readonly number[];+ /** Reads in a row that failed (no account answered, or the read threw); 0 after one that worked. */+ failures?: number;+}++/** After a failed read on a quiet home, the next comes this long later, doubled after each further failure, at most hourly. */+export function retryAfterFailureMs(failures: number): number {+ return Math.min(LIMIT_POLL_MS * 2 ** Math.max(0, failures - 1), LIMIT_IDLE_POLL_MS);}/** Whether the clock's minute tick reads usage now. Called only while an engine is held or an automation waits. */-export function limitReadDue({ now, checkedAt, lastTurnAt, resets }: LimitReadState): boolean {+export function limitReadDue({ now, checkedAt, lastTurnAt, resets, failures = 0 }: LimitReadState): boolean {const age = now - checkedAt;+ // The clock was set back past the last read: nothing measured from it holds, so read now and start again from there.+ if (age < 0) return true;if (now - lastTurnAt < LIMIT_ACTIVE_MS) return age >= LIMIT_POLL_MS - 1_000;if (resets.some((reset) => checkedAt < reset + RESET_READ_AFTER_MS && reset + RESET_READ_AFTER_MS <= now)) return true;- return age >= LIMIT_IDLE_POLL_MS;+ return age >= (failures > 0 ? retryAfterFailureMs(failures) : LIMIT_IDLE_POLL_MS);}diff --git a/server/limit-reset-owed.ts b/server/limit-reset-owed.tsnew file mode 100644index 0000000000..ff87d865fa--- /dev/null+++ b/server/limit-reset-owed.ts@@ -0,0 +1,21 @@+// A limit-reset automation's run for a reset that already passed is owed: a usage read in the minute after that reset (the+// limit clock's own, another engine's, a person opening the limits, or the first one after a laptop wakes) already shows+// the next window's reset, or, for a Claude window that has not started again, only the weekly one. Re-timing the+// automation then would skip the run it waited for. routines.ts leaves such an automation alone until that run exists,+// and re-times it after.+import { AFTER_RESET_MS } from "../shared/limit-reset.ts";++interface Timed {+ id: string;+ enabled: boolean;+ nextRunAt: number | null;+ schedule: { type: string };+}++/** The reset this automation was timed for (`nextRunAt` less AFTER_RESET_MS) has passed, and its run has not been made. */+export function limitResetRunOwed(routine: Timed, runs: ReadonlyArray<{ routineId: string; scheduledFor: number }>, now: number): boolean {+ if (!routine.enabled || routine.schedule.type !== "limit_reset" || routine.nextRunAt === null) return false;+ if (routine.nextRunAt - now > AFTER_RESET_MS) return false;+ const due = routine.nextRunAt;+ return !runs.some((run) => run.routineId === routine.id && run.scheduledFor === due);+}diff --git a/server/limit-resets.ts b/server/limit-resets.tsindex df647991ad..c9bf08703e 100644--- a/server/limit-resets.ts+++ b/server/limit-resets.ts@@ -116,6 +116,8 @@ export class LimitResetClock {private checkedAt = 0;/** The last runtime event of any turn: while turns run, usage is kept five minutes fresh (limit-poll.ts). */private lastTurnAt = -Infinity;+ /** Reads in a row that failed: a quiet home retries them sooner than its hourly read (limit-poll.ts). */+ private failures = 0;private loading: Promise<void> | null = null;private timer: ReturnType<typeof setInterval> | null = null;private soon: ReturnType<typeof setTimeout> | null = null;@@ -257,10 +259,14 @@ export class LimitResetClock {const accounts = this.options.accounts();this.loading = (async () => {try {- if (accounts.length) this.noteUsage(await this.load(accounts, force));- else this.checkedAt = this.now();+ if (!accounts.length) { this.checkedAt = this.now(); this.failures = 0; return; }+ const report = await this.load(accounts, force);+ // No account answered (offline, a laptop just woke): a quiet home tries again in minutes, not in an hour.+ this.failures = report.providers.length && report.providers.every((row) => !row.ok) ? this.failures + 1 : 0;+ this.noteUsage(report);} catch {this.checkedAt = this.now();+ this.failures += 1;}})().finally(() => {this.loading = null;@@ -274,7 +280,7 @@ export class LimitResetClock {// while turns run, else just after each known reset and hourly (limit-poll.ts), so a quiet home reads nothing more.this.timer = setInterval(() => {if (!this.holding() && !this.options.waiting?.()) return;- if (limitReadDue({ now: this.now(), checkedAt: this.checkedAt, lastTurnAt: this.lastTurnAt, resets: this.knownResets() })) void this.refresh(false);+ if (limitReadDue({ now: this.now(), checkedAt: this.checkedAt, lastTurnAt: this.lastTurnAt, resets: this.knownResets(), failures: this.failures })) void this.refresh(false);}, 60_000);this.timer.unref?.();}diff --git a/server/routines-limit-reset.test.ts b/server/routines-limit-reset.test.tsindex 4af3568f60..a352ee063d 100644--- a/server/routines-limit-reset.test.ts+++ b/server/routines-limit-reset.test.ts@@ -163,6 +163,65 @@ describe("Move to after reset", () => {expect(h.manager.listRoutines()[0]!.nextRunAt).toBe(START + 25 * HOUR);});+ it("a usage read just after the reset leaves the run it owes in place: it starts once, then the next window is timed", async () => {+ const h = harness();+ const reset = START + 60 * 60_000 + 30_000;+ h.reset("claude", reset);+ const routine = h.create("every_reset");+ expect(routine.nextRunAt).toBe(reset + 60_000);+ // A read at reset + 30 s already shows the next five-hour window.+ h.at(reset + 30_000);+ h.reset("claude", reset + 5 * HOUR);+ expect(h.manager.retimeLimitResets(), "the run for this reset is still owed").toBe(0);+ expect(h.manager.listRoutines()[0]!.nextRunAt).toBe(reset + 60_000);+ h.at(reset + 61_000);+ expect(h.manager.retimeLimitResets()).toBe(0);+ await h.manager.tick();+ expect(h.started).toHaveLength(1);+ expect(h.manager.listRoutines()[0]!.nextRunAt, "then the next window").toBe(reset + 5 * HOUR + 60_000);+ h.at(reset + 2 * 60_000);+ h.manager.retimeLimitResets();+ await h.manager.tick();+ expect(h.started, "exactly once").toHaveLength(1);+ });++ it("a Claude window that has not started again reports only the weekly reset: the owed run still starts at the reset", async () => {+ const h = harness();+ const reset = START + HOUR;+ h.reset("claude", reset);+ h.create("once");+ h.at(reset + 10_000);+ h.reset("claude", START + 4 * 24 * HOUR);+ h.manager.retimeLimitResets();+ expect(h.manager.listRoutines()[0]!.nextRunAt, "not moved days away").toBe(reset + 60_000);+ h.at(reset + 60_000);+ await h.manager.tick();+ expect(h.started).toHaveLength(1);+ });++ it("after a sleep past the reset, a read that comes before the wake's scheduler pass moves nothing; the run starts on the pass", async () => {+ const h = harness();+ const reset = START + HOUR;+ h.reset("claude", reset);+ h.create("every_reset");+ h.at(reset + 3 * HOUR);+ h.reset("claude", reset + 5 * HOUR);+ expect(h.manager.retimeLimitResets()).toBe(0);+ await h.manager.tick();+ expect(h.started).toHaveLength(1);+ expect(h.manager.listRoutines()[0]!.nextRunAt).toBe(reset + 5 * HOUR + 60_000);+ });++ it("still moves an automation whose reset has not come yet", () => {+ const h = harness();+ h.reset("claude", START + 2 * HOUR);+ h.create("once");+ h.at(START + 2 * HOUR - 61_000);+ h.reset("claude", START + 3 * HOUR);+ expect(h.manager.retimeLimitResets()).toBe(1);+ expect(h.manager.listRoutines()[0]!.nextRunAt).toBe(START + 3 * HOUR + 60_000);+ });+it("moves a one-time schedule's time, and leaves a run already after the reset alone", () => {const h = harness();const once = h.manager.create({ name: "Once", prompt: "Do it.", botId: "scout", schedule: { type: "once", at: START + HOUR } });diff --git a/server/routines.ts b/server/routines.tsindex 4593fb20cd..2700a5e162 100644--- a/server/routines.ts+++ b/server/routines.ts@@ -13,7 +13,7 @@ import type { RoutineRequestOperation } from "../shared/routine-request.ts";import type { ModelSelection } from "../shared/wire.ts";import { intervalAllowsOccurrence, intervalHasRestrictions, isSameLocalDay, latestIntervalOccurrence } from "./routine-intervals.ts";import { cloneSchedule, limitResetOccurrence, mergeScheduleUpdate, nextOccurrence, RoutineScheduleError, type RoutineSchedule, type RoutineScheduleInput } from "./routine-schedules.ts";-import { runsOnce } from "../shared/limit-reset.ts";+import { runsOnce } from "../shared/limit-reset.ts"; import { limitResetRunOwed } from "./limit-reset-owed.ts";import {ROUTINE_HANDOFF_WAIT, isRoutineProblemRun, type RoutineAccess, type RoutineCheck, type RoutineContextAttachment, type RoutineDelivery, type RoutineIntervalWindow, type RoutineRetryCause,type RoutineHoldCause, type RoutineRunReport, type RoutineRunStatus, type RoutineRunTrigger,@@ -880,10 +880,10 @@ export class RoutineManager {return moved.length;}- /** The engines' reset times changed: each limit-reset routine that is on takes its engine's new time. */+ /** The engines' reset times changed: each limit-reset routine that is on takes its engine's new time, once the run it owes a passed reset was made (limit-reset-owed.ts). */retimeLimitResets(): number {const moved = this.routines.filter((routine) => {- if (!routine.enabled || routine.schedule.type !== "limit_reset") return false;+ if (!routine.enabled || routine.schedule.type !== "limit_reset" || limitResetRunOwed(routine, this.runs, this.now())) return false;const schedule = this.timedSchedule(routine.schedule, routine.id);if (schedule.type !== "limit_reset" || (schedule.at === routine.schedule.at && schedule.at === routine.nextRunAt)) return false;routine.schedule = schedule;