Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Limit clock: no five-minute usage reads on a quiet home (#5932)
Milind Soni2e0c3b9aff8c
diff --git a/server/limit-poll.test.ts b/server/limit-poll.test.tsnew file mode 100644index 0000000000..3f8cb6b00c--- /dev/null+++ b/server/limit-poll.test.ts@@ -0,0 +1,142 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+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 { parseClaudeUsage, type PlanUsageReport } from "./plan-usage.ts";+import { RoutineManager, type RoutineRun } from "./routines.ts";+import type { RuntimeEvent } from "../shared/runtime-events.ts";++const NOW = Date.parse("2026-10-19T10:00:00Z");+const MINUTE = 60_000, HOUR = 60 * MINUTE;+const iso = (at: number) => new Date(at).toISOString();+const accounts = [{ id: "claude", name: "Claude", driver: "claude" as const, environment: {} }];+/** Claude's usage as its endpoint answers: [percent used, when the window resets]. */+const usage = (fiveHour: [number, number], weekly: [number, number]): PlanUsageReport => ({+ fetchedAt: iso(Date.now()),+ providers: [{ id: "claude", name: "Claude", driver: "claude", ok: true, error: null, ...parseClaudeUsage({+ five_hour: { utilization: fiveHour[0], resets_at: iso(fiveHour[1]) },+ seven_day: { utilization: weekly[0], resets_at: iso(weekly[1]) },+ }) }],+});+const turnEvent = (threadId: string): RuntimeEvent => ({ eventId: "e", provider: "claudeAgent", createdAt: iso(Date.now()), threadId, type: "turn.started" }) as RuntimeEvent;++const dirs: string[] = [];+afterEach(() => {+ vi.useRealTimers();+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++describe("limitReadDue", () => {+ const state = { now: NOW, checkedAt: NOW - 2 * MINUTE, lastTurnAt: -Infinity, resets: [] as number[] };++ it("keeps usage five minutes fresh while turns run", () => {+ const running = { ...state, lastTurnAt: NOW - MINUTE };+ expect(limitReadDue(running)).toBe(false);+ expect(limitReadDue({ ...running, checkedAt: NOW - LIMIT_POLL_MS })).toBe(true);+ expect(limitReadDue({ ...running, lastTurnAt: NOW - LIMIT_ACTIVE_MS, checkedAt: NOW - LIMIT_POLL_MS }), "turns ended a while ago").toBe(false);+ });++ it("on a quiet home, reads once after each known reset and otherwise hourly", () => {+ expect(limitReadDue({ ...state, checkedAt: NOW - 59 * MINUTE })).toBe(false);+ expect(limitReadDue({ ...state, checkedAt: NOW - LIMIT_IDLE_POLL_MS })).toBe(true);+ const reset = NOW - RESET_READ_AFTER_MS;+ expect(limitReadDue({ ...state, resets: [reset] }), "a reset passed since the last read").toBe(true);+ expect(limitReadDue({ ...state, resets: [reset], checkedAt: NOW }), "read already after it").toBe(false);+ expect(limitReadDue({ ...state, resets: [NOW + MINUTE] }), "not yet").toBe(false);+ });++ it("reads at once when it never read", () => {+ expect(limitReadDue({ ...state, checkedAt: 0 })).toBe(true);+ });+});++describe("the limit clock on a quiet home", () => {+ it("reads usage once, then nothing for the next hour, though an engine is held and an automation waits", 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.noteRefusal("claude", NOW + 23 * HOUR);+ instance.start();+ await vi.advanceTimersByTimeAsync(2 * MINUTE);+ expect(loadUsage, "the read just after the refusal").toHaveBeenCalledTimes(1);+ loadUsage.mockClear();+ await vi.advanceTimersByTimeAsync(57 * MINUTE);+ expect(loadUsage, "every five minutes before: twelve reads an hour").not.toHaveBeenCalled();+ expect(instance.blockedUntil("claude"), "still held").toBe(NOW + 23 * HOUR);+ await vi.advanceTimersByTimeAsync(2 * MINUTE);+ expect(loadUsage, "the hourly read, which still ends a hold that reset early").toHaveBeenCalledTimes(1);+ instance.stop();+ });++ it("goes back to five-minute reads while turns run", 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);+ for (let minute = 0; minute < 30; minute++) {+ instance.noteRuntimeEvent("codex", turnEvent(`t${minute}`));+ await vi.advanceTimersByTimeAsync(MINUTE);+ }+ expect(loadUsage.mock.calls.length).toBeGreaterThanOrEqual(6);+ instance.stop();+ });++ it("answers fresh when someone looks at the limits", async () => {+ vi.useFakeTimers({ now: NOW });+ let report = usage([100, NOW + 23 * HOUR], [40, NOW + 5 * 24 * HOUR]);+ const loadUsage = vi.fn(async () => ({ ...report, fetchedAt: iso(Date.now()) }));+ const instance = new LimitResetClock({ accounts: () => accounts, loadUsage, waiting: () => true });+ instance.start();+ await vi.advanceTimersByTimeAsync(30 * MINUTE);+ expect(loadUsage).toHaveBeenCalledTimes(1);+ report = usage([20, NOW + 4 * HOUR], [10, NOW + 5 * 24 * HOUR]);+ await instance.ensureFresh();+ expect(loadUsage).toHaveBeenCalledTimes(2);+ expect(instance.report().checkedAt).toBe(Date.now());+ expect(instance.limit("claude")?.usedPercent).toBe(20);+ instance.stop();+ });++ it("still starts a waiting limit-reset automation on time, and reads the next reset just after", async () => {+ vi.useFakeTimers({ now: NOW });+ const dir = mkdtempSync(join(tmpdir(), "omb-limit-poll-"));+ dirs.push(dir);+ const reset = NOW + 20 * MINUTE;+ let report = usage([100, reset], [40, NOW + 5 * 24 * HOUR]);+ const loadUsage = vi.fn(async () => ({ ...report, fetchedAt: iso(Date.now()) }));+ const started: string[] = [];+ let routines: RoutineManager | null = null;+ const clock = new LimitResetClock({ accounts: () => accounts, loadUsage, onChange: () => routines?.retimeLimitResets(),+ 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-1" }), joinConversation: (run: RoutineRun) => run.sourceThreadId ?? null,+ startTurn: async (_botId: string, threadId: string) => { started.push(threadId); },+ limitResetAt: (engine: string) => clock.resetAt(engine),+ });+ 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(clock.resetAt("claude")).toBe(reset);+ expect(routines.listRoutines()[0]!.nextRunAt, "timed by the first read").toBe(reset + 60_000);+ loadUsage.mockClear();+ // The window rolls over at its reset: the next one ends five hours later.+ report = usage([5, reset + 5 * HOUR], [2, NOW + 5 * 24 * HOUR]);+ await vi.advanceTimersByTimeAsync(reset - Date.now() + 30_000);+ expect(loadUsage, "nothing read before the reset").not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(MINUTE);+ await routines.tick();+ expect(started, "the automation starts a minute after the reset").toEqual(["thread-1"]);+ expect(loadUsage, "not re-timed before it ran").not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(MINUTE);+ expect(loadUsage, "read just after the reset").toHaveBeenCalledTimes(1);+ expect(routines.listRoutines()[0]!.nextRunAt, "and timed to the next reset").toBe(reset + 5 * HOUR + 60_000);+ clock.stop();+ routines.stop();+ });+});diff --git a/server/limit-poll.ts b/server/limit-poll.tsnew file mode 100644index 0000000000..50eecbd46e--- /dev/null+++ b/server/limit-poll.ts@@ -0,0 +1,34 @@+// When the limit clock (limit-resets.ts) reads plan usage again on its own, while an engine is held or a limit-reset+// automation waits. While turns run, every five minutes, as before. On a quiet home or a closed laptop nobody needs a+// fresher answer than that: it reads once just after each reset it knows of (so a hold ends, and a waiting automation+// is re-timed, on fresh usage) and otherwise once an hour, which still catches a limit that reset early. Someone who+// looks at the limits gets a read at once (LimitResetClock.ensureFresh), whatever this says.+import { AFTER_RESET_MS } from "../shared/limit-reset.ts";++/** How fresh usage is kept while turns run, and how fresh a shown limit must be. */+export const LIMIT_POLL_MS = 5 * 60_000;+/** A turn event this recent counts as the home being in use. */+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. */+export const RESET_READ_AFTER_MS = AFTER_RESET_MS + 60_000;++export interface LimitReadState {+ now: number;+ /** When usage was last read (0: never). */+ checkedAt: number;+ /** The last runtime event of any turn, on any engine. */+ lastTurnAt: number;+ /** The reset times known now: the holds' and the usage windows'. */+ resets: readonly number[];+}++/** 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 {+ const age = now - checkedAt;+ 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;+}diff --git a/server/limit-resets.test.ts b/server/limit-resets.test.tsindex 37556d0e1c..41bcbf34e5 100644--- a/server/limit-resets.test.ts+++ b/server/limit-resets.test.ts@@ -464,7 +464,7 @@ describe("LimitResetClock and the turns that follow a refusal", () => {expect(instance.blockedUntil("claude")).toBeNull();});- it("re-reads usage every few minutes while an engine is held, with nothing else waiting, and so ends a hold that reset early", async () => {+ it("re-reads usage every few minutes while an engine is held and turns run, with nothing else waiting, and so ends a hold that reset early", async () => {vi.useFakeTimers({ now: NOW });let usage = report(claude([100, NOW + 23 * HOUR], [8, NOW + 5 * 24 * HOUR]));const loadUsage = vi.fn(async () => ({ ...usage, fetchedAt: iso(Date.now()) }));@@ -472,7 +472,9 @@ describe("LimitResetClock and the turns that follow a refusal", () => {instance.start();await vi.advanceTimersByTimeAsync(10 * 60_000);expect(loadUsage, "nothing held, nothing waiting: no reads").not.toHaveBeenCalled();- instance.noteRefusal("claude", Date.now() + 23 * HOUR);+ // A turn on Claude meets its limit: the home is in use.+ instance.noteRuntimeEvent("claude", { eventId: "e", provider: "claudeAgent", createdAt: iso(Date.now()), threadId: "t1", type: "runtime.error",+ message: "limit", limitResetsAt: Date.now() + 23 * HOUR } as RuntimeEvent);await vi.advanceTimersByTimeAsync(6_000);expect(instance.blockedUntil("claude"), "the read soon after the refusal still shows the full window").not.toBeNull();usage = report(claude([2, NOW + 5 * HOUR], [8, NOW + 5 * 24 * HOUR]));diff --git a/server/limit-resets.ts b/server/limit-resets.tsindex a58bce4664..df647991ad 100644--- a/server/limit-resets.ts+++ b/server/limit-resets.ts@@ -5,11 +5,11 @@ import { readFileSync } from "node:fs";import { NEAR_LIMIT_PERCENT, type EngineLimit, type EngineLimitsReport, type LimitWindowName } from "../shared/limit-reset.ts";import { writeFileAtomic } from "./atomic.ts";+import { LIMIT_POLL_MS, limitReadDue } from "./limit-poll.ts";import { claudeHasExtraUsageRoom, loadPlanUsage, type PlanAccount, type PlanProviderRow, type PlanUsageReport, type PlanWindow } from "./plan-usage.ts";import type { RuntimeEvent } from "../shared/runtime-events.ts";-/** How often a waiting limit-reset automation checks usage again, and how fresh a shown limit must be. */-export const LIMIT_POLL_MS = 5 * 60_000;+export { LIMIT_POLL_MS };/** A refusal's reset is kept a little past its time, so a run due right then still finds it. */const REFUSAL_GRACE_MS = 10 * 60_000;const SOON_AFTER_REFUSAL_MS = 5_000;@@ -114,6 +114,8 @@ export class LimitResetClock {private readonly heldAt = new Map<string, number>();private readonly turnEngines = new Map<string, string>();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;private loading: Promise<void> | null = null;private timer: ReturnType<typeof setInterval> | null = null;private soon: ReturnType<typeof setTimeout> | null = null;@@ -169,6 +171,7 @@ export class LimitResetClock {/** Every runtime event, with the engine its turn runs on when known: a refusal holds the engine, and a turn that* works on it afterwards ends the hold, since the account plainly has room again (another model, plan or account). */noteRuntimeEvent(engine: string | undefined, event: RuntimeEvent): void {+ this.lastTurnAt = this.now();if (event.type === "turn.started" && engine) this.turnEngines.set(event.threadId, engine);else if (event.type === "runtime.error") {const refused = engine ?? this.turnEngines.get(event.threadId);@@ -267,11 +270,22 @@ export class LimitResetClock {start(): void {if (this.timer) return;- // While an engine is held its usage is read every few minutes too, so a limit that reset early ends the hold.- this.timer = setInterval(() => { if (this.holding() || this.options.waiting?.()) void this.ensureFresh(LIMIT_POLL_MS - 1_000); }, 60_000);+ // While an engine is held its usage is read again too, so a limit that reset early ends the hold: every few minutes+ // 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);+ }, 60_000);this.timer.unref?.();}+ /** Every reset time known now: the holds' and each usage window's. */+ private knownResets(): number[] {+ const resets = [...this.refusals.values()];+ for (const limit of this.usage.values()) for (const window of limit.windows ?? []) if (window.resetsAt !== null) resets.push(window.resetsAt);+ return resets;+ }+stop(): void {if (this.timer) clearInterval(this.timer);if (this.soon) clearTimeout(this.soon);