Skip to content

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

Routines and incidents back off and are bounded when unattended work keeps failing (#6173)

Milind Soni4988422e6c68
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 08407b6bb8..0e64d93b78 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -1583,6 +1583,38 @@ apart from the AI's errors, because starting the same work again cannot fix it.
A routine stays on however often it fails.
+A failed run starts once more by itself only when a second start can plausibly
+pass: a rate limit, a provider that is overloaded or answered with a temporary
+error, an engine that crashed or was stopped for memory (that start waits for
+room). A tool server that is down, an AI that is signed out, a full disk or an
+engine that could not be started fail the run at once. The second start sends
+one short line saying to finish the run when the engine resumes a session that
+holds the routine's instructions, or replays a conversation small enough to
+still include them. Otherwise, and always on a backup AI, after a usage-limit
+wait or for a routine that calls a /command, it sends the instructions again.
+
+Past these limits, something is held back and says so in one line: on the
+routine's run row, or in the Chief's "Problems to look at" chat.
+
+| Setting | Default | What it bounds |
+| --- | --- | --- |
+| `OMB_ROUTINE_FAILURES_BEFORE_SPACING` | `3` | The runs of one routine that may fail in a row before its next scheduled runs are spaced out. A run that completes, a change to the routine, turning it on again, or a run that failed only because the bot's AI is signed out, out of credit or at its usage limit ends the streak and the spacing. The skipped runs share one row: "Skipped 12 scheduled runs because its last runs failed, so its next tries are spaced out". From `1`. |
+| `OMB_ROUTINE_FAILURE_SPACING_MS` | `3600000` (1 hour) | How long after the failure that starts the spacing the next run waits. From `60000`. |
+| `OMB_ROUTINE_FAILURE_SPACING_MAX_MS` | `14400000` (4 hours) | How long after each later failure the next run waits. Never below `OMB_ROUTINE_FAILURE_SPACING_MS`. |
+| `OMB_CHIEF_INCIDENT_TURNS_PER_HOUR` | `6` | The turns a Chief of Staff is started for problems in an hour, across all the chats it hears about. Past that, the Chief is not started: you are notified of each such problem, and one line in its "Problems to look at" chat counts them, names the first five chats they came from and links the newest. From `1`. |
+| `OMB_STARTUP_ROUTINE_GAP_MS` | `1800000` (30 minutes) | On a server not started by the desktop app, how soon after the start that last ran them routines set to "Also run when OpenMausBot starts" may run again. A start within that time leaves one row per routine: "Not run at 4 starts because OpenMausBot started again soon after the start that last ran it". `0` runs them at every start. |
+| `OMB_ROUTINE_RESTART_STAGGER_MS` | `30000` (30 seconds) | The time between the runs a restart cut off as each starts again, so they do not all start at once. From `0`. |
+| `OMB_BURST_PART_MAX_RESTARTS` | `2` | The times a burst's part, or its merge, starts again after a restart cut it off. Past that the part fails with "Not started again: OpenMausBot restarted while this part ran 3 times.", and the parts are posted as they came instead of merged. From `0`. |
+
+A routine every minute (`* * * * *`) is still accepted and is spaced out the
+same way. Identical failures are told to you and to the Chief once: two
+failures that differ only in ids, paths, long numbers or times count as the
+same, while different exit codes, HTTP statuses or models do not.
+A Chief told of a failure that is this server's own is told not to retry it.
+
+Any value that is not a whole number in range leaves the default. Set them in
+the server's environment and restart it.
+
### Hand-offs and unattended turns
A turn with a person waiting in the chat keeps the limits described under
diff --git a/packages/phone-protocol/src/routines.ts b/packages/phone-protocol/src/routines.ts
index bd00b2f7a0..9386da0849 100644
--- a/packages/phone-protocol/src/routines.ts
+++ b/packages/phone-protocol/src/routines.ts
@@ -230,6 +230,9 @@ export interface RoutineRun {
partial?: boolean;
/** Set when the run used its one automatic second start, and why. */
retried?: RoutineRetryCause;
+ /** A failed run that only the owner's AI account could have let through (signed out, out of credit, a usage limit, an
+ * engine to set up): it spent nothing, so it does not count towards spacing its routine out. */
+ ownerCause?: "signed_out" | "credits" | "usage_limit" | "setup";
/** Concise, redacted question or approval reason while status is waiting,
* or why a queued run starts later. */
attention?: string;
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index 08bd70b58c..f862e646da 100644
--- a/server/bot-box/env.test.ts
+++ b/server/bot-box/env.test.ts
@@ -56,6 +56,8 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set([
"OMB_TTS_KEY", "OMB_TUNNEL_ORIGIN_PORT", "OMB_TUNNEL_SOCKET", "OMB_TURN_STALL_MS", "OMB_UNDER_IMAGE_INIT", "OMB_UPDATE_CHANNEL", "OMB_UPDATE_INSTALL",
"OMB_USER_DATA", "OMB_WARM_SUMMARY", "OMB_WARM_SUMMARY_TIME_SCALE", "OMB_WEBHOOK_PORT", "OMB_WEBHOOK_PUBLIC_URL", "OMB_WEBHOOK_SOCKET",
"OMB_WORKERS_AI_TOKEN", "OMB_XAI_TTS_API",
+ "OMB_BURST_PART_MAX_RESTARTS", "OMB_CHIEF_INCIDENT_TURNS_PER_HOUR", "OMB_ROUTINE_FAILURES_BEFORE_SPACING", "OMB_ROUTINE_FAILURE_SPACING_MAX_MS",
+ "OMB_ROUTINE_FAILURE_SPACING_MS", "OMB_ROUTINE_RESTART_STAGGER_MS", "OMB_STARTUP_ROUTINE_GAP_MS",
]);
const ROOT = new URL("../../", import.meta.url);
diff --git a/server/burst/manager.test.ts b/server/burst/manager.test.ts
index 1646ba8132..0b8bcfef66 100644
--- a/server/burst/manager.test.ts
+++ b/server/burst/manager.test.ts
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { BurstCardData } from "../../shared/burst.ts";
import { burstLimits, BURST_PLAN_LIMITS, type BurstLimits } from "./limits.ts";
-import { childOpening, createBurstManager, mergePrompt, type BurstManagerDeps, type BurstTurnOutcome } from "./manager.ts";
+import { BURST_PART_MAX_RESTARTS, childOpening, createBurstManager, cutOffTooOften, mergePrompt, type BurstManagerDeps, type BurstTurnOutcome } from "./manager.ts";
import { openBurstStore, type BurstChild, type BurstRecord, type BurstStore } from "./store.ts";
type Started = { burst: BurstRecord; child: BurstChild & { threadId: string }; text: string; done: (outcome: BurstTurnOutcome) => void };
@@ -346,6 +346,28 @@ describe("after a restart", () => {
expect(started.map((run) => run.child.threadId)).toEqual(["thread-1", "thread-2"]);
restarted.close();
});
+
+ it("in a crash loop, starts a part or its merge at most OMB_BURST_PART_MAX_RESTARTS more times, then fails the part with one line and posts what is left", () => {
+ const one = fresh({ limits: { parallel: 2, maxTasks: 50, smallPlan: false } });
+ const { manager, started, store } = one;
+ const { burstId } = one.propose(items(2));
+ manager.run(burstId);
+ const merges: string[] = [];
+ for (let restart = 0; restart < 10; restart++) {
+ const restarted = createBurstManager({ store, limits: () => ({ parallel: 2, maxTasks: 50, smallPlan: false }), hasRoom: () => true,
+ openThread: () => "thread-new", startChild: async (burst, child, text, done) => { started.push({ burst, child, text, done }); }, stopChild: () => {},
+ startMerge: async (_burst, text) => { merges.push(text()); return true; }, draw: () => undefined, postParts: () => "", deliver: () => {}, log: () => {}, now: () => 1_700_000_000_000 });
+ restarted.recover();
+ restarted.close();
+ }
+ console.log(`part starts over 10 restarts of a crash loop: ${started.length}, merge starts: ${merges.length}`);
+ expect(started).toHaveLength(2 + 2 * BURST_PART_MAX_RESTARTS);
+ expect(store.childrenIn(burstId, "failed").map((child) => child.error)).toEqual([cutOffTooOften(BURST_PART_MAX_RESTARTS), cutOffTooOften(BURST_PART_MAX_RESTARTS)]);
+ expect(cutOffTooOften(2)).toBe("Not started again: OpenMausBot restarted while this part ran 3 times.");
+ // The merge turn is cut off by the restarts that follow it as well: the parts are posted as they came instead.
+ expect(merges).toHaveLength(1 + BURST_PART_MAX_RESTARTS);
+ expect(store.get(burstId)!.phase).toBe("done");
+ });
});
describe("a child's start", () => {
diff --git a/server/burst/manager.ts b/server/burst/manager.ts
index 411a97e9de..1e69153ca8 100644
--- a/server/burst/manager.ts
+++ b/server/burst/manager.ts
@@ -5,6 +5,7 @@ import { randomUUID } from "node:crypto";
import type { BurstCardData, BurstChildRow, BurstView } from "../../shared/burst.ts";
import type { ModelSelection } from "../../shared/wire.ts";
import { BurstLane } from "./lane.ts";
+import { envWhole } from "../env-limits.ts";
import type { BurstLimits } from "./limits.ts";
import { burstRow, type BurstChild, type BurstRecord, type BurstStore } from "./store.ts";
@@ -17,6 +18,10 @@ const RESULT_MAX = 20_000;
const FAILURES_SHOWN = 10;
/** What one merge turn reads of all the parts together: a burst of any size fits one engine's context. */
const MERGE_BUDGET = 150_000;
+export const BURST_PART_MAX_RESTARTS = 2;
+/** OMB_BURST_PART_MAX_RESTARTS, a whole number from 0; anything else leaves the default. */
+export const burstPartMaxRestarts = (env: NodeJS.ProcessEnv = process.env): number => envWhole(env.OMB_BURST_PART_MAX_RESTARTS, BURST_PART_MAX_RESTARTS, 0);
+export const cutOffTooOften = (restarts: number): string => `Not started again: OpenMausBot restarted while this part ran ${restarts + 1} times.`;
export const ITEM_MAX = 2_000;
export const INSTRUCTIONS_MAX = 12_000;
@@ -332,11 +337,22 @@ export function createBurstManager(deps: BurstManagerDeps) {
laneOwned(threadId: string): boolean {
return ownThreads.has(threadId);
},
- /** After a restart: a running turn is gone, so its part goes back in line, and a merge waiting on its turn tries again. */
+ /** After a restart: a running turn is gone, so its part goes back in line and a merge tries again, until restarts cut
+ * either off more than OMB_BURST_PART_MAX_RESTARTS times: the part then fails with one line, and the parts are
+ * posted as they came instead of merged. */
recover(): void {
store.prune(now() - PRUNE_AFTER_MS);
+ const most = burstPartMaxRestarts();
for (const burst of store.active()) {
- if (burst.phase === "running") { store.requeueRunning(burst.id); enlist(burst.id); }
+ if (burst.phase === "running") {
+ store.requeueRunning(burst.id, most, cutOffTooOften(most));
+ enlist(burst.id);
+ const left = store.get(burst.id);
+ if (left && left.counts.queued === 0 && left.counts.running === 0) settled(left);
+ } else if (burst.phase === "merging") {
+ const cut = (burst.mergeRestarts ?? 0) + 1, current = store.update(burst.id, { mergeRestarts: cut }) ?? burst;
+ if (cut > most) finish(current, store.childrenIn(burst.id, "done"), store.childrenIn(burst.id, "failed"), { ok: false, text: "" });
+ }
ensureTimer();
}
tick();
diff --git a/server/burst/store.ts b/server/burst/store.ts
index 64eb21a662..a63671f9e4 100644
--- a/server/burst/store.ts
+++ b/server/burst/store.ts
@@ -13,6 +13,8 @@ export interface BurstRecord {
threadId: string;
cardMessageId?: string;
phase: BurstPhase;
+ /** Times a restart cut its merge turn off. */
+ mergeRestarts?: number;
task: string;
instructions: string;
model: ModelSelection;
@@ -33,6 +35,8 @@ export interface BurstChild {
status: BurstChildStatus;
threadId?: string;
attempts: number;
+ /** Times a restart cut this part off while it ran. */
+ restarts?: number;
result?: string;
error?: string;
}
@@ -164,7 +168,7 @@ export function openBurstStore(dataDir: string) {
active(): BurstRecord[] {
return rows.activeBursts.all().map(parseBurst);
},
- update(id: string, patch: Partial<Pick<BurstRecord, "phase" | "cardMessageId">>): BurstRecord | undefined {
+ update(id: string, patch: Partial<Pick<BurstRecord, "phase" | "cardMessageId" | "mergeRestarts">>): BurstRecord | undefined {
return transaction(() => {
const burst = getBurst(id);
if (!burst) return undefined;
@@ -216,8 +220,12 @@ export function openBurstStore(dataDir: string) {
requeue(burstId: string, seq: number): BurstChild | undefined {
return move(burstId, seq, "queued");
},
- requeueRunning(burstId: string): BurstChild[] {
- return moveAll(burstId, "running", "queued");
+ /** Running children go back in line, each counted as cut off once more; one cut off more than `maxRestarts` times fails
+ * with `stopped` instead. */
+ requeueRunning(burstId: string, maxRestarts = Infinity, stopped = ""): BurstChild[] {
+ const requeued = moveAll(burstId, "running", "queued", (child) => { child.restarts = (child.restarts ?? 0) + 1; });
+ for (const child of requeued) if (child.restarts! > maxRestarts) move(burstId, child.seq, "failed", (failed) => { failed.error = stopped; });
+ return requeued.filter((child) => child.restarts! <= maxRestarts);
},
/** Failed children go back in line, with their reason cleared. */
requeueFailed(burstId: string): BurstChild[] {
diff --git a/server/env-limits.ts b/server/env-limits.ts
new file mode 100644
index 0000000000..9af667f628
--- /dev/null
+++ b/server/env-limits.ts
@@ -0,0 +1,5 @@
+/** A limit read from the server's environment: a whole number from `min`; anything else leaves the default. */
+export function envWhole(raw: string | undefined, fallback: number, min = 1): number {
+ const value = Number(raw?.trim() || NaN);
+ return Number.isSafeInteger(value) && value >= min ? value : fallback;
+}
diff --git a/server/host-fault.test.ts b/server/host-fault.test.ts
index 2aaa60404f..fd815f6833 100644
--- a/server/host-fault.test.ts
+++ b/server/host-fault.test.ts
@@ -1,13 +1,23 @@
import { describe, expect, it } from "vitest";
-import { hostFaultOf } from "./host-fault.ts";
+import { hostFaultOf, retryCannotFix } from "./host-fault.ts";
describe("hostFaultOf", () => {
it.each([
["spawn /usr/local/bin/claude EAGAIN", "process_start"],
["Error: spawn EMFILE", "process_start"],
- ["posix_spawn failed: ENOMEM", "process_start"],
+ ["posix_spawn failed: ENOMEM", "out_of_room"],
+ ["spawn /usr/local/bin/claude ENOMEM", "out_of_room"],
+ ["fork: Cannot allocate memory", "out_of_room"],
+ ["There is no room to start another program (ENOMEM), so this task could not run. Nothing was sent to the AI.", "out_of_room"],
+ ["claude exited null before result", "out_of_room"],
["fork: Resource temporarily unavailable", "process_start"],
["EMFILE: too many open files, open '/data/x'", "process_start"],
+ ["There is no room to start another program (EAGAIN), so this task could not run. Nothing was sent to the AI.", "process_start"],
+ ["Ran out of room, so I stopped this task to keep everything else running.", "out_of_room"],
+ ["Ran out of room, so I closed the browser to keep everything else running. (3 tasks)", "out_of_room"],
+ ["claude exited null (signal SIGKILL) before result", "out_of_room"],
+ ["codex exited 137 before turn/completed", "out_of_room"],
+ ["The engine started but never sent its first frame in 60 seconds", "out_of_room"],
["ENOSPC: no space left on device, write", "disk_full"],
["write failed: Disk quota exceeded", "disk_full"],
["MCP server could not start; check its command and installation", "tool_server"],
@@ -15,12 +25,20 @@ describe("hostFaultOf", () => {
['MCP server "crm" is not connected', "tool_server"],
['The "crm" MCP server couldn\'t be set up, so Claude couldn\'t start this reply.', "tool_server"],
["MCP startup timed out", "tool_server"],
- ["401 Unauthorized", "signed_out"],
+ ['API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"OAuth token has expired."}}', "signed_out"],
+ ["xAI HTTP 401: invalid bearer token", "signed_out"],
+ ["unexpected status 401 Unauthorized: Missing bearer or basic authentication in header", "signed_out"],
+ ["API error (status 401 Unauthorized): Invalid API key", "signed_out"],
["Not logged in · Please run /login", "signed_out"],
] as const)("%s is %s", (failure, fault) => {
expect(hostFaultOf(failure)).toBe(fault);
});
+ it("leaves a start held for room to the admission: only that fault may pass on a later start", () => {
+ expect(retryCannotFix("out_of_room")).toBe(false);
+ expect((["process_start", "disk_full", "tool_server", "signed_out"] as const).every(retryCannotFix)).toBe(true);
+ });
+
it("reads the engine's own stop reason for a sign-in", () => {
expect(hostFaultOf("The turn ended", "auth_required")).toBe("signed_out");
});
@@ -33,6 +51,13 @@ describe("hostFaultOf", () => {
"The AI stopped before it answered",
"read EAGAIN",
"Tool search_crm failed: record not found",
+ "claude exited 1 before result: Error: boom",
+ "MCP request timed out",
+ 'claude exited 1 before result: [warn] MCP server "calendar" failed to start; continuing\nTypeError: x is undefined',
+ "Rebalance my 401(k): The AI stopped before it answered",
+ "Forbidden-words scan: Claude is overloaded right now (HTTP 529).",
+ "Tool fetch_orders failed: the /orders endpoint returned 403 Forbidden",
+ "401 Unauthorized",
])("%s is not this server's fault", (failure) => {
expect(hostFaultOf(failure)).toBeNull();
});
diff --git a/server/host-fault.ts b/server/host-fault.ts
index 4f0383d8bb..bd6333cd58 100644
--- a/server/host-fault.ts
+++ b/server/host-fault.ts
@@ -1,34 +1,57 @@
// A failure whose cause is this server, one of its tool servers or a sign-in, not the AI's work: starting the same work
// again meets it again and spends the person's AI budget for nothing. Read from the failure's own words, so every caller
// (a routine's second start, a Chief's incident, a hand-off's resume, the turn admission) judges one failure one way.
-import { classifyError } from "./drivers/retry.ts";
-/** process_start: the server could not start another process (out of processes, file handles or memory);
- * disk_full: no room left to write; tool_server: an MCP server did not start, died or needs its own sign-in;
- * signed_out: the bot's AI needs signing in again. */
-export type HostFault = "process_start" | "disk_full" | "tool_server" | "signed_out";
+/** process_start: the server could not start another process (out of processes or file handles);
+ * out_of_room: no memory to start an engine, or an engine that had started was stopped for memory, killed by the kernel,
+ * or never sent its first output; disk_full: no room left to write; tool_server: an MCP server did not start, died or
+ * needs its own sign-in; signed_out: the engine says the bot's AI needs signing in again. */
+export type HostFault = "process_start" | "out_of_room" | "disk_full" | "tool_server" | "signed_out";
-const EXHAUSTED = String.raw`(?:EAGAIN|EMFILE|ENFILE|ENOMEM)`;
+const EXHAUSTED = String.raw`(?:EAGAIN|EMFILE|ENFILE)`;
const PROCESS_START = new RegExp(
String.raw`\b(?:posix_)?spawn(?:Sync)?\b[^\n]*\b${EXHAUSTED}\b|\b${EXHAUSTED}\b[^\n]*\b(?:posix_)?spawn\b` +
- String.raw`|\bfork\b[^\n]*\b(?:resource temporarily unavailable|cannot allocate memory)\b|\btoo many open files\b|\bcannot allocate memory\b`, "i");
+ String.raw`|\bfork\b[^\n]*\bresource temporarily unavailable\b|\btoo many open files\b` +
+ String.raw`|^There is no room to start another program \(${EXHAUSTED}\)`, "i");
+const OUT_OF_ROOM = new RegExp(
+ String.raw`\bENOMEM\b|\bcannot allocate memory\b|^There is no room to start another program \(ENOMEM\)` +
+ String.raw`|^Ran out of room, so I (?:closed the browser|stopped this task)\b|\bran out of memory\b|\bout of memory\b|\bOOM[- ]kill` +
+ String.raw`|\bexited null\b|\bexited 137\b|\(signal SIGKILL\)|\bkilled by (?:the kernel|signal SIGKILL)\b` +
+ String.raw`|\b(?:never sent|sent nothing|did not send) (?:its|a|any) first (?:frame|event|output|message)\b`, "i");
const DISK_FULL = /\bno space left on device\b|\bENOSPC\b|\bdisk quota exceeded\b|\bEDQUOT\b/i;
const TOOL_SERVER = new RegExp(
String.raw`\bMCP server\b[^\n]*\b(?:could not start|couldn't be set up|failed to start|exited|input closed|stdin (?:is )?closed|is not connected|session expired|needs (?:a sign-in|authentication)|refused the sign-in)\b` +
- String.raw`|\bMCP (?:request|startup) timed out\b|\bMCP session closed\b|\bCould not reach this MCP server\b`, "i");
+ String.raw`|\bMCP startup timed out\b|\bMCP session closed\b|\bCould not reach this MCP server\b`, "i");
+/** The engine's own words for a sign-in it needs: Claude Code's "Not logged in · Please run /login", a provider's
+ * "API Error: 401", "HTTP 401", "(status 401 …)", Codex's "unexpected status 401", "authentication_error", "invalid x-api-key". A 401 or "forbidden"
+ * anywhere else (a tool's answer, a routine's name) is not a sign-in. */
+const SIGNED_OUT = new RegExp(
+ String.raw`\bnot logged in\b|\bplease run /login\b|\blogged out\b|\bauthentication_error\b|\binvalid (?:api key|x-api-key|bearer token)\b` +
+ String.raw`|\bmissing bearer\b|\bauthentication required\b|\bOAuth token (?:has )?expired\b|(?:^API Error:? |\bHTTP |\(status |\bunexpected status |\bstatus code:? )401\b`, "i");
+/** An engine that exited before its result: its stderr tail follows the colon, and names a cause only for what an
+ * exit itself shows (memory, disk, processes), never a tool server it merely mentions. */
+const ENGINE_EXIT = /^([\w.-]+ exited (?:-?\d+|null)(?: \(signal \w+\))? before [\w/]+)[:;]/;
-/** Which such fault a failure's words name; null for anything else, the AI's own errors and its provider's among them. */
+/** Which such fault a failure's own words name; null for anything else, the AI's own errors and its provider's among
+ * them. Classify the system's failure text and stop reason only: never a name, a request or a model's reply. */
export function hostFaultOf(failure: string, stopReason?: string | null): HostFault | null {
if (PROCESS_START.test(failure)) return "process_start";
if (DISK_FULL.test(failure)) return "disk_full";
- if (TOOL_SERVER.test(failure)) return "tool_server";
- if (stopReason === "auth_required" || classifyError({ text: failure }).reason === "auth") return "signed_out";
+ if (OUT_OF_ROOM.test(failure)) return "out_of_room";
+ const head = ENGINE_EXIT.exec(failure)?.[1] ?? failure;
+ if (TOOL_SERVER.test(head)) return "tool_server";
+ if (stopReason === "auth_required" || SIGNED_OUT.test(head)) return "signed_out";
return null;
}
+/** Whether starting the same work again soon meets the fault again. An engine stopped for room is the exception: the
+ * memory and process admission holds its next start until there is room, so that start may pass. */
+export const retryCannotFix = (fault: HostFault): boolean => fault !== "out_of_room";
+
/** The fault in the words a model is given, to follow "because". */
export const HOST_FAULT_WHY: Readonly<Record<HostFault, string>> = {
process_start: "this server could not start another process",
+ out_of_room: "this server ran out of room for the AI's engine",
disk_full: "this server's disk is full",
tool_server: "one of its tool servers is not running or not signed in",
signed_out: "its AI is signed out",
diff --git a/server/host/chief-incident-spend.test.ts b/server/host/chief-incident-spend.test.ts
new file mode 100644
index 0000000000..80a0d71042
--- /dev/null
+++ b/server/host/chief-incident-spend.test.ts
@@ -0,0 +1,194 @@
+// What failing routines cost in requests to the AI, counted as the turns they start: the routine's own starts and the
+// Chief turns their failures start, wired as the host wires them (a failure the owner was already told of reaches no one).
+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 { INCIDENT_WINDOW_MS, incidentText } from "../incidents.ts";
+import { failureShape } from "../routine-outcomes.ts";
+import { RoutineManager, type RoutineRun } from "../routines.ts";
+import { createChiefNotices } from "./chief-notices.ts";
+
+const MINUTE = 60_000, HOUR = 60 * MINUTE;
+const START = Date.parse("2026-11-16T08:00:00Z");
+const dirs: string[] = [];
+
+afterEach(() => {
+ vi.useRealTimers();
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+/** A dead tool server as the engine reports it: the same failure, with a new process id and time each run. */
+const deadTool = (at: number) => `MCP server "crm" could not start (pid ${4000 + (at / MINUTE) % 997}) at ${new Date(at).toISOString()}; check its command and installation`;
+const spawnRefused = (at: number) => `spawn /usr/local/bin/claude EAGAIN (pid ${30000 + Math.floor(at / MINUTE) % 997})`;
+
+function world(botCount: number, failure: (at: number) => string, refuseStart = false) {
+ const dir = mkdtempSync(join(tmpdir(), "omb-chief-incident-spend-"));
+ dirs.push(dir);
+ let now = START, made = 0;
+ vi.useFakeTimers({ now, toFake: ["Date"] });
+ const bots = [
+ { id: "chief", name: "Clive", chiefOfStaff: true, section: "", threadId: "chief-main", tasks: [] as Array<{ threadId: string; title: string }> },
+ ...Array.from({ length: botCount }, (_, i) => ({ id: `bot-${i}`, name: `Bot ${i}`, section: "", threadId: `bot-${i}-main`, tasks: [] as Array<{ threadId: string; title: string }> })),
+ ];
+ const lines = new Map<string, Array<Record<string, unknown>>>();
+ const store = {
+ bots, bot: (id: string) => bots.find((one) => one.id === id),
+ tasks: (id: string) => bots.find((one) => one.id === id)?.tasks ?? [],
+ taskByThread: (id: string, threadId: string) => bots.find((one) => one.id === id)?.tasks.find((task) => task.threadId === threadId),
+ groupByThread: () => undefined,
+ createTask: (id: string, title: string) => {
+ const task = { threadId: `thread-${++made}`, title };
+ bots.find((one) => one.id === id)!.tasks.push(task);
+ return task;
+ },
+ appendMessage: (threadId: string, row: Record<string, unknown>) => {
+ const line = { id: `line-${++made}`, ...row, at: now };
+ lines.set(threadId, [...(lines.get(threadId) ?? []), line]);
+ return line;
+ },
+ patchMessage: (threadId: string, id: string, patch: Record<string, unknown>) => {
+ const list = lines.get(threadId) ?? [], at = list.findIndex((line) => line.id === id);
+ if (at < 0) return null;
+ list[at] = { ...list[at], ...patch };
+ return list[at];
+ },
+ messagesFor: (threadId: string) => lines.get(threadId) ?? [],
+ activePath: (threadId: string) => lines.get(threadId) ?? [],
+ };
+ const chiefTurns: string[] = [], notified: string[] = [];
+ const notices = createChiefNotices({
+ store: store as never, notify: (notification) => { if (notification) notified.push(notification.threadId ?? ""); }, threadBusy: () => false, botAtThreadCapacity: () => false, groupTurnActive: () => false,
+ startTurn: async (botId, text, opts) => { if (botId === "chief") chiefTurns.push(text); store.appendMessage(opts.threadId, { role: "user", kind: "text", text }); },
+ assignerOf: () => undefined, schedule: (run) => run(), now: () => now,
+ });
+ const routineTurns: string[] = [];
+ const manager = new RoutineManager({
+ file: join(dir, "routines.json"), now: () => now, botState: () => "ready",
+ createTask: (botId, title) => store.createTask(botId, title),
+ startTurn: async (_botId, threadId, prompt) => {
+ routineTurns.push(threadId);
+ store.appendMessage(threadId, { role: "user", kind: "text", text: prompt });
+ if (refuseStart) throw new Error(failure(now));
+ },
+ promptSaid: (threadId, prompt) => store.messagesFor(threadId).some((line) => line.role === "user" && line.text === prompt),
+ // As the host wires it: a failure the owner was already told of (alert null) reaches neither them nor a Chief.
+ onRunFailed: (run, alert) => {
+ const bot = store.bot(run.botId);
+ if (!bot || alert === null) return;
+ const said = alert?.detail ?? run.error;
+ notices.reportIncident({ kind: "routine-failed", bot: bot as never, threadId: run.threadId ?? bot.threadId, detail: said ? `${run.routineName}: ${said}` : run.routineName });
+ },
+ });
+ for (const bot of bots.slice(1)) manager.create({ name: `Sync for ${bot.name}`, prompt: "Read new leads from the CRM and file them", botId: bot.id, schedule: { type: "interval", everyMinutes: 5, anchorAt: START } });
+ const running = () => manager.listRuns().filter((run: RoutineRun) => run.status === "running");
+ return {
+ routineTurns, chiefTurns, lines, notified, report: notices.reportIncident, bot: (id: string) => store.bot(id), task: (botId: string, title: string) => store.createTask(botId, title),
+ /** A scheduler pass every minute up to `to`; each turn the pass before left running fails. */
+ async passTo(to: number) {
+ while (now < to) {
+ now += MINUTE;
+ vi.setSystemTime(now);
+ for (const run of running()) manager.failThread(run.threadId!, failure(now));
+ await manager.tick();
+ }
+ },
+ };
+}
+
+describe("a failure's words, without what changes from run to run", () => {
+ it("read the same for two runs that fail for one reason, and differently for another reason", () => {
+ expect(failureShape(deadTool(START))).toBe(failureShape(deadTool(START + 5 * MINUTE)));
+ expect(failureShape(spawnRefused(START))).toBe(failureShape(spawnRefused(START + 5 * MINUTE)));
+ expect(failureShape("Request req_011CUa7xYz9 to /v1/messages failed: 529 overloaded")).toBe(failureShape("Request req_022ABb1qWe3 to /v1/messages failed: 529 overloaded"));
+ expect(failureShape("Error in /home/omb/data/bots/7f3e9c2a-1b4d-4e8f-9a6b-2c1d3e4f5a6b/run.log line 12")).toBe(failureShape("Error in /home/omb/data/bots/0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/run.log line 12"));
+ expect(failureShape(deadTool(START))).not.toBe(failureShape("Claude is overloaded right now. Wait a minute, then run it again."));
+ });
+
+ it("keep exit codes, HTTP statuses and models apart", () => {
+ expect(failureShape("claude exited 1 before result")).not.toBe(failureShape("claude exited 137 before result"));
+ expect(failureShape("API Error: 503 Service Unavailable")).not.toBe(failureShape("API Error: 401 Unauthorized"));
+ expect(failureShape("model not found: claude-sonnet-4-5-20250929")).not.toBe(failureShape("model not found: claude-opus-4-1-20250805"));
+ expect(failureShape("model not found: gpt-5.1")).not.toBe(failureShape("model not found: gpt-5.2"));
+ });
+});
+
+describe("a Chief told of a failure a retry cannot fix", () => {
+ it("is told not to retry it, and why", () => {
+ const text = incidentText({ kind: "routine-failed", bot: { id: "bot-0", name: "Bot 0" }, threadId: "t", detail: `Sync: ${deadTool(START)}` }, { count: 1, mayRetry: true, muted: false });
+ expect(text).toContain("A retry cannot fix this: one of its tool servers is not running or not signed in");
+ expect(text).toContain("Do not call retry_thread");
+ expect(text).not.toContain("call retry_thread with");
+ });
+
+ it("is never told so by a routine's name", () => {
+ const text = incidentText({ kind: "routine-failed", bot: { id: "bot-0", name: "Bot 0" }, threadId: "t", detail: "Rebalance my 401(k): The AI stopped before it answered",
+ failure: { text: "The AI stopped before it answered" } }, { count: 1, mayRetry: true, muted: false });
+ expect(text).not.toContain("A retry cannot fix this");
+ expect(text).toContain('call retry_thread with bot_id "bot-0"');
+ });
+
+ it("is still told how to retry one a retry may fix", () => {
+ const text = incidentText({ kind: "failed", bot: { id: "bot-0", name: "Bot 0" }, threadId: "t", detail: "Claude is overloaded right now (HTTP 529)." }, { count: 1, mayRetry: true, muted: false });
+ expect(text).toContain('call retry_thread with bot_id "bot-0"');
+ });
+});
+
+describe("a routine every 5 minutes whose tool server is dead, for a day", () => {
+ it("starts 9 routine turns and 2 Chief turns: the first failure, and the one that spaces it out", async () => {
+ const w = world(1, deadTool);
+ await w.passTo(START + 24 * HOUR);
+ console.log(`requests in 24 hours: ${w.routineTurns.length} routine turns + ${w.chiefTurns.length} Chief turns`);
+ expect(w.routineTurns).toHaveLength(9);
+ expect(w.chiefTurns).toHaveLength(2);
+ expect(w.chiefTurns.every((text) => text.includes("A retry cannot fix this"))).toBe(true);
+ });
+});
+
+describe("a routine every 5 minutes on a server whose engines cannot start, for a day", () => {
+ it("tries 9 starts and starts 2 Chief turns", async () => {
+ const w = world(1, spawnRefused, true);
+ await w.passTo(START + 24 * HOUR);
+ console.log(`requests in 24 hours: ${w.routineTurns.length} routine starts tried + ${w.chiefTurns.length} Chief turns`);
+ expect(w.routineTurns).toHaveLength(9);
+ expect(w.chiefTurns).toHaveLength(2);
+ });
+});
+
+describe("twenty bots under one Chief whose routines all fail at once", () => {
+ it("start no more Chief turns in an hour than OMB_CHIEF_INCIDENT_TURNS_PER_HOUR, and count the rest on one line", async () => {
+ vi.stubEnv("OMB_CHIEF_INCIDENT_TURNS_PER_HOUR", "6");
+ try {
+ const w = world(20, (at) => `The AI stopped before it answered (${at})`);
+ await w.passTo(START + INCIDENT_WINDOW_MS - MINUTE);
+ console.log(`Chief turns in the first hour with 20 failing routines: ${w.chiefTurns.length}`);
+ expect(w.chiefTurns).toHaveLength(6);
+ const folded = [...w.lines.values()].flat().filter((row) => (row.tool as { name?: string } | undefined)?.name?.startsWith("Clive is asked about only so many"));
+ expect(folded).toHaveLength(1);
+ expect((folded[0]!.tool as { name: string }).name).toMatch(/^Clive is asked about only so many problems an hour, so \d+ more this hour were not sent to it\. From: Bot \d+ · Sync for Bot \d+/);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+});
+
+describe("eight teammates' runs that stall within the hour, past a Chief's share of 6", () => {
+ it("tell the person of the 2 the Chief is not started for, and list and link them on its one line", () => {
+ vi.stubEnv("OMB_CHIEF_INCIDENT_TURNS_PER_HOUR", "6");
+ try {
+ const w = world(8, () => "");
+ for (let i = 0; i < 8; i++) {
+ const { threadId } = w.task(`bot-${i}`, `Job ${i}`);
+ w.report({ kind: "stalled", bot: w.bot(`bot-${i}`) as never, threadId, detail: "no activity for 20 minutes" });
+ }
+ expect(w.chiefTurns).toHaveLength(6);
+ expect(w.notified).toHaveLength(2);
+ const [line] = [...w.lines.values()].flat().filter((row) => (row.tool as { name?: string } | undefined)?.name?.startsWith("Clive is asked about only so many"));
+ expect((line!.tool as { name: string }).name).toBe("Clive is asked about only so many problems an hour, so 2 more this hour were not sent to it. From: Bot 6 · Job 6; Bot 7 · Job 7");
+ expect(line!.threadRef).toMatchObject({ botId: "bot-7", title: "Job 7" });
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+});
diff --git a/server/host/chief-notices.ts b/server/host/chief-notices.ts
index fec6808ae8..6f09101a8a 100644
--- a/server/host/chief-notices.ts
+++ b/server/host/chief-notices.ts
@@ -2,13 +2,14 @@ import { failedTurnTool } from "../../shared/failed-turn.ts";
import { admit } from "../admission.ts";
import { memoryStopped } from "../engine-memory.ts";
import {
- AUTO_RETRY_LEAD, chiefForBot, INCIDENTS_THREAD_TITLE, OLD_INCIDENTS_THREAD_TITLE, IncidentLedger, incidentChip, incidentContext, incidentText, RETRY_BLOCKED, RETRY_LEAD,
+ AUTO_RETRY_LEAD, ChiefIncidentBudget, chiefForBot, INCIDENTS_THREAD_TITLE, OLD_INCIDENTS_THREAD_TITLE, IncidentLedger, incidentChip, incidentContext, incidentText, RETRY_BLOCKED, RETRY_LEAD,
type Incident, type IncidentKind, type IncidentRetry,
} from "../incidents.ts";
import { buildNotification, type Notification } from "../notify.ts";
import { quoteInNote } from "../peer-provenance.ts";
import { peerName } from "../peer-roster.ts";
import { redactSecretsInText } from "../redact.ts";
+import { serverLine } from "../server-lines.ts";
import { retriesTeammateThread, type RoutineFailureFacts } from "../routine-recovery.ts";
import { queueSteeredMessage } from "../steer-queue.ts";
import type { BotRecord, Message, Store } from "../store.ts";
@@ -16,7 +17,7 @@ import type { BotRecord, Message, Store } from "../store.ts";
type PeerAsk = NonNullable<Message["peerAsk"]>;
export interface ChiefNoticeDeps {
- store: Pick<Store, "bots" | "bot" | "tasks" | "taskByThread" | "groupByThread" | "createTask" | "appendMessage" | "messagesFor" | "activePath">;
+ store: Pick<Store, "bots" | "bot" | "tasks" | "taskByThread" | "groupByThread" | "createTask" | "appendMessage" | "messagesFor" | "activePath"> & Partial<Pick<Store, "patchMessage">>;
assignerOf(threadId: string): unknown;
notify(notification: Notification | null): void;
threadBusy(botId: string, threadId: string): boolean;
@@ -43,6 +44,9 @@ export interface ChiefNoticeDeps {
confined?(threadId: string): boolean;
/** The language a line about this conversation is written in for its person (server/server-lines.ts). */
threadLanguage?(threadId: string): string | undefined;
+ /** The incident turns a Chief may start in an hour, across threads (OMB_CHIEF_INCIDENT_TURNS_PER_HOUR by default). */
+ chiefTurnsPerHour?(): number;
+ now?(): number;
/** A Team Cloud: a notice reaches a Chief only when the conversation's asks are its person's (a member's private chat
* is theirs alone), into a notices chat of that person's own. */
routing?: {
@@ -55,12 +59,17 @@ export interface ChiefNoticeDeps {
/** How long a run stopped for memory waits before it starts again; the memory gate then holds it until there is room. */
export const MEMORY_RETRY_MS = 30_000;
+/** The chats a Chief's line for the problems it was not started for names; its count covers the rest. */
+export const FOLDED_LISTED = 5;
export const MEMORY_RETRY_TEXT = "[OpenMausBot started this again by itself, once: the last run was stopped to free memory on this Cloud. "
+ "Continue the request above from where it stopped and finish it. If the same problem comes back, say exactly what is blocking and stop.]";
export function createChiefNotices(deps: ChiefNoticeDeps) {
const { store } = deps;
const incidentLedger = new IncidentLedger();
+ const chiefBudget = new ChiefIncidentBudget({ now: deps.now, limit: deps.chiefTurnsPerHour });
+ /** Each Chief's line that counts the problems it was not started for, while its hour's share is spent. */
+ const folded = new Map<string, { threadId: string; messageId: string; count: number; until: number; chats: Array<{ botId: string; threadId: string; title: string; name: string }> }>();
const schedule = deps.schedule ?? ((run: () => void) => { setTimeout(run, 0).unref?.(); });
const later = deps.later ?? ((run: () => void, ms: number) => { setTimeout(run, ms).unref?.(); });
/** Each thread's last request a run stopped for memory was started again for: once a request. */
@@ -137,6 +146,21 @@ export function createChiefNotices(deps: ChiefNoticeDeps) {
}
}
+ /** Past its hour's share a Chief is not started again: the problems are counted on one line in its notices chat, which
+ * lists the chats they came from (the first FOLDED_LISTED) and links the newest. */
+ function fold(chief: BotRecord, threadId: string, until: number, from: { botId: string; threadId: string; title: string; name: string }): void {
+ const open = folded.get(chief.id), now = deps.now?.() ?? Date.now();
+ const same = open && open.threadId === threadId && open.until > now ? open : null;
+ const count = (same?.count ?? 0) + 1;
+ const chats = same?.chats.some((chat) => chat.threadId === from.threadId) ? same.chats : [...(same?.chats ?? []), from];
+ const list = chats.slice(0, FOLDED_LISTED).map((chat) => chat.name).join("; ");
+ const name = serverLine(deps.threadLanguage?.(threadId), "server.incidents.folded", { count, chief: chief.name, list });
+ const threadRef = { botId: from.botId, threadId: from.threadId, title: from.title };
+ const line = same && store.patchMessage?.(threadId, same.messageId, { tool: { name, ok: false }, threadRef })
+ || store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name, ok: false }, threadRef });
+ folded.set(chief.id, { threadId, messageId: line.id, count, chats, until: Math.max(until, same?.until ?? 0) });
+ }
+
function deliver(input: {
chief: BotRecord | null; title: string; bot: BotRecord; threadId: string; chip: string; text: string; alreadyNotified: boolean;
}): "chief" | "person" {
@@ -161,6 +185,13 @@ export function createChiefNotices(deps: ChiefNoticeDeps) {
routing && person ? (created) => routing.open(created.threadId, person) : undefined);
if (!notices || notices.threadId === threadId) return tellThePerson();
if (routing && person && routing.startedBy(notices.threadId) === undefined) routing.open(notices.threadId, person);
+ const spent = chiefBudget.take(chief.id);
+ if (spent) {
+ const title = task?.title ?? (group ? group.name : `${bot.name}'s conversation`);
+ fold(chief, notices.threadId, spent.until, { botId: bot.id, threadId, title, name: `${bot.name} · ${title}` });
+ tellThePerson();
+ return "chief";
+ }
store.appendMessage(notices.threadId, {
role: "bot",
kind: "activity",
@@ -188,7 +219,8 @@ export function createChiefNotices(deps: ChiefNoticeDeps) {
* Never retried: a stall the turn watchdog stopped (kind "stalled"), a stop, a refusal or a cap (retriesTeammateThread,
* from the failure's words and `facts`), a run that answered a retry, and a thread whose asks are not the Chief's person's. */
/** `notified`: the person already heard of it another way (a usage limit's own notice), so only the Chief is told. */
- function reportIncident(input: { kind: IncidentKind; bot: BotRecord; threadId: string; detail: string; facts?: RoutineFailureFacts; notified?: boolean }): void {
+ /** `failure`: the failure's own words when `detail` adds a name to them; only those are read for the kind of failure. */
+ function reportIncident(input: { kind: IncidentKind; bot: BotRecord; threadId: string; detail: string; failure?: string; facts?: RoutineFailureFacts; notified?: boolean }): void {
const { bot, threadId } = input;
if (deps.quietThread?.(bot.id, threadId)) return;
const task = store.taskByThread(bot.id, threadId);
@@ -201,6 +233,7 @@ export function createChiefNotices(deps: ChiefNoticeDeps) {
title: task?.title ?? null,
room: group?.name ?? null,
detail: redactSecretsInText(input.detail),
+ failure: { text: input.failure ?? input.detail, stopReason: input.facts?.stopReason },
...incidentContext(deps.store.messagesFor(threadId)),
};
const count = incidentLedger.note(threadId);
diff --git a/server/incidents.e2e.test.ts b/server/incidents.e2e.test.ts
index 2ade004afc..3b9720af0b 100644
--- a/server/incidents.e2e.test.ts
+++ b/server/incidents.e2e.test.ts
@@ -523,7 +523,7 @@ it("tells the person of a failure whose report waited and was then refused", asy
}
}, 150_000);
-it("reports a routine that keeps failing the same way once, and again when the failure changes", async () => {
+it("reports a routine that keeps failing the same way once, again when it is spaced out, and again when the failure changes", async () => {
const { dataDir, api, control, messages, useCli, incidentsThread, close } = await launch();
try {
const chief = (await control(["new-bot", "--name", "Clive", "--section", "Ops"])).bot;
@@ -534,9 +534,11 @@ it("reports a routine that keeps failing the same way once, and again when the f
const routine = (await api("POST", "/api/routines", {
name: "Inbox brief", prompt: "Summarise my inbox.", botId: ada.id, schedule: { type: "cron", expression: "0 7 * * *", timeZone: "Europe/London" },
}, undefined, 201)).routine;
+ // Each run fails twice: its one automatic second start comes 15 s after the first (ROUTINE_RETRY_MS), so a run takes
+ // over 15 s before it fails, and a busy machine needs room beyond that.
const runFails = async () => {
const { id } = (await api("POST", `/api/routines/${routine.id}/run`, undefined, undefined, 201)).run;
- await expect.poll(async () => ((await api("GET", "/api/routines")).runs as any[]).find((run) => run.id === id)?.status, { timeout: 30_000 }).toBe("failed");
+ await expect.poll(async () => ((await api("GET", "/api/routines")).runs as any[]).find((run) => run.id === id)?.status, { timeout: 45_000 }).toBe("failed");
};
const reports = async (incidents: string) => (await messages(incidents))
.filter((m) => m.kind === "activity" && (m.tool?.name ?? "").startsWith("Ada hit a problem: its scheduled routine")).map((m) => m.tool.name as string);
@@ -546,13 +548,16 @@ it("reports a routine that keeps failing the same way once, and again when the f
await expect.poll(() => reports(incidents), { timeout: 20_000 }).toHaveLength(1);
await runFails();
await runFails();
+ // The third failure in a row spaces the routine out, and says so once.
+ await expect.poll(() => reports(incidents), { timeout: 20_000 }).toHaveLength(2);
writeFileSync(changedFlag, "changed");
await runFails();
- await expect.poll(() => reports(incidents), { timeout: 20_000 }).toHaveLength(2);
- const [crashed, changed] = await reports(incidents);
+ await expect.poll(() => reports(incidents), { timeout: 20_000 }).toHaveLength(3);
+ const [crashed, spaced, changed] = await reports(incidents);
expect(crashed).toContain("simulated crash before result");
+ expect(spaced).toContain("3 runs in a row failed. It stays on, and tries again less often until a run completes.");
expect(changed).not.toContain("simulated crash before result");
} finally {
await close();
}
-}, 150_000);
+}, 240_000);
diff --git a/server/incidents.ts b/server/incidents.ts
index 6bf38ecac2..dac0b606f8 100644
--- a/server/incidents.ts
+++ b/server/incidents.ts
@@ -1,4 +1,6 @@
import type { WireMessage as Message } from "../shared/wire.ts";
+import { envWhole } from "./env-limits.ts";
+import { HOST_FAULT_WHY, hostFaultOf, retryCannotFix } from "./host-fault.ts";
import { withoutDeliveredNote } from "./peer-provenance.ts";
import { AUTHORITY, fromNoteWith, HARNESS_WHO } from "./provenance-label.ts";
import { botOwner } from "../shared/bot-owner.ts";
@@ -25,6 +27,9 @@ export interface Incident {
title?: string | null;
room?: string | null;
detail: string;
+ /** The failure's own words and stop reason, when `detail` adds anything to them (a routine's name): only these are
+ * read for what kind of failure it was. */
+ failure?: { text: string; stopReason?: string | null };
lastRequest?: string | null;
lastReply?: string | null;
}
@@ -63,6 +68,32 @@ export const INCIDENT_RETRY_LIMIT = 2;
export const INCIDENT_HARD_LIMIT = 5;
export const INCIDENT_WINDOW_MS = 60 * 60_000;
+export const CHIEF_INCIDENT_TURNS_PER_HOUR = 6;
+
+/** OMB_CHIEF_INCIDENT_TURNS_PER_HOUR, a whole number from 1; anything else leaves the default. */
+export const chiefIncidentTurnsPerHour = (env: NodeJS.ProcessEnv = process.env): number =>
+ envWhole(env.OMB_CHIEF_INCIDENT_TURNS_PER_HOUR, CHIEF_INCIDENT_TURNS_PER_HOUR);
+
+/** The incident turns each Chief started within the last hour, across all the threads it hears about. */
+export class ChiefIncidentBudget {
+ private readonly at = new Map<string, number[]>();
+ private readonly options: { now?: () => number; limit?: () => number };
+
+ constructor(options: { now?: () => number; limit?: () => number } = {}) {
+ this.options = options;
+ }
+
+ /** Counts one more incident turn for `chiefId`; null when it has had its hour's share, with when the oldest one leaves the hour. */
+ take(chiefId: string): { until: number } | null {
+ const now = this.options.now?.() ?? Date.now();
+ const recent = (this.at.get(chiefId) ?? []).filter((time) => now - time < INCIDENT_WINDOW_MS);
+ this.at.set(chiefId, recent);
+ if (recent.length >= (this.options.limit ?? chiefIncidentTurnsPerHour)()) return { until: recent[0]! + INCIDENT_WINDOW_MS };
+ recent.push(now);
+ return null;
+ }
+}
+
export interface IncidentCount {
count: number;
mayRetry: boolean;
@@ -172,7 +203,10 @@ export function incidentText(incident: Incident, count: IncidentCount, retry?: I
if (count.count > 1) lines.push(`This is the ${ordinal(count.count)} incident on that thread within the hour.`);
if (retry && "retried" in retry) lines.push("OpenMausBot already retried this run once by itself; the failure above is how that retry ended.");
else if (retry) lines.push(`OpenMausBot did not retry it: ${retry.notRetried}.`);
- lines.push(count.mayRetry
+ const fault = hostFaultOf(incident.failure?.text ?? incident.detail, incident.failure?.stopReason);
+ lines.push(fault && retryCannotFix(fault)
+ ? `A retry cannot fix this: ${HOST_FAULT_WHY[fault]}, and starting the run again would meet the same fault. Do not call retry_thread or hand the work on again. Say in one or two plain sentences what is blocking and what the person should do, then stop.`
+ : count.mayRetry
? [
"Decide, in this order:",
"1. If the cause is something only the person can fix — a sign-in, a missing credential, an unanswered question, a setting — say so here in one or two plain sentences and stop.",
diff --git a/server/index.ts b/server/index.ts
index b3f3998d2d..eb765af0e8 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -239,7 +239,7 @@ import { openCodeProviderKeysAllowed, setOpenCodeProviderKeyPolicy } from "./dri
import { forgetNotificationReader, liveAppRows, openCardRows, readMessageText, recallMessages, recentMessages, closeMessageSearch, closeMessageDb, chatFollowups, cancelledChatFollowup, settleChatFollowups, threadsReferencing, logNotification, lastRowAt, threadsWithCardsSince } from "./message-db.ts";
import { briefCrossingLabel, claimRecallCrossings, recallCrossingLabel } from "./recall-disclosure.ts";
import { parseSince, parseUntil, recentWork, recentWorkPrompt, turnOutcomeLine } from "./recent-work.ts";
-import { createChiefNotices } from "./host/chief-notices.ts"; import { dismissLeftoverPeerCards } from "./host/leftover-peer-cards.ts";
+import { createChiefNotices } from "./host/chief-notices.ts"; import { sessionHolds } from "./routine-recovery.ts"; import { dismissLeftoverPeerCards } from "./host/leftover-peer-cards.ts";
import { createHandoffTicks } from "./handoff-ticks.ts"; import { IDLE_HTTP_SERVER } from "./due-timer.ts";
const SESSION_READ_MAX_CHARS = 8_000;
@@ -8868,7 +8868,7 @@ routines = new RoutineManager({
}
},
interruptGoal: interruptRoutineGroupGoal,
- onRunChanged: (run) => { syncRoutineRunToSource(run); }, moveFrozen: () => moveFreeze.frozen(), restartsToReload: () => { if (!CLOUD_HOME) return false; restartRequested = true; gracefulShutdown(); return true; }, onReadable: routinesReadable,
+ onRunChanged: (run) => { syncRoutineRunToSource(run); }, promptSaid: (threadId, prompt) => { const bot = store.botByThread(threadId), task = bot && store.taskByThread(bot.id, threadId), engine = bot && turnSelection(bot.id, threadId)?.instanceId; return sessionHolds({ resumes: Boolean(task && engine && task.lastInstanceId === engine && task.resumeCursors[engine] !== undefined), messages: store.activePath(threadId), prompt, budgetBytes: cfg.context?.rebuildBytes ?? DEFAULT_REBUILD_BYTES }); }, moveFrozen: () => moveFreeze.frozen(), restartsToReload: () => { if (!CLOUD_HOME) return false; restartRequested = true; gracefulShutdown(); return true; }, onReadable: routinesReadable,
onRunCut: (run) => run.groupId ? coordinator.cancelRoom(run.groupId, run.threadId!, ROUTINE_RESTARTED) : coordinator.cancelDirect(run.threadId!, ROUTINE_RESTARTED),
onRunFailed: (run, alert) => {
const bot = store.bot(run.botId);
@@ -8877,7 +8877,7 @@ routines = new RoutineManager({
automationReports.runFailed(run, said ?? "");
const notificationBot = routineSourceOwner(run)?.bot ?? bot;
notify(buildNotification("routine-failed", notificationBot, routineSourceThread(run) ?? run.threadId ?? bot.threadId, detail));
- reportIncident({ kind: "routine-failed", bot, threadId: run.threadId ?? bot.threadId, detail });
+ reportIncident({ kind: "routine-failed", bot, threadId: run.threadId ?? bot.threadId, detail, failure: run.error ?? "" });
},
onRunDeferred: (run, alert) => {
const bot = store.bot(run.botId);
diff --git a/server/routine-execution.ts b/server/routine-execution.ts
index b4a4fa782a..554e26f337 100644
--- a/server/routine-execution.ts
+++ b/server/routine-execution.ts
@@ -1,7 +1,5 @@
-import type { RoutineRetryCause } from "../shared/routines.ts";
import { stopCause } from "./drivers/engine-errors.ts";
import { redactSecretsInText } from "./redact.ts";
-import { retryNote } from "./routine-recovery.ts";
import type { Routine, RoutineContextAttachment, RoutineRun, RoutineRunOn, RoutineRunTrigger } from "./routines.ts";
export interface RoutineContinuityCarry {
@@ -69,9 +67,8 @@ export function composeExecutionPrompt(
prompt: string,
attachments: readonly RoutineContextAttachment[] | undefined,
carry?: RoutineContinuityCarry | null,
- retried?: RoutineRetryCause,
): string {
- const parts = [`${routineHeader(routine.name, routine.trigger)}${routine.trigger === "webhook" ? "" : `Trigger id: ${routine.id}\n`}${prompt}`, retried ? retryNote(retried) : ""];
+ const parts = [`${routineHeader(routine.name, routine.trigger)}${routine.trigger === "webhook" ? "" : `Trigger id: ${routine.id}\n`}${prompt}`];
const foreign = foreignPaths([prompt, ...(attachments ?? []).map((attachment) => attachment.path)], runHostPlatform(routine.runOn));
if (foreign.length) {
parts.push(`[OpenMausBot: this run is on a ${hostName(runHostPlatform(routine.runOn))} computer, where ${foreign.join(", ")} cannot exist. If the work needs ${foreign.length > 1 ? "them" : "it"}, say plainly what is missing instead of reporting success.]`);
diff --git a/server/routine-failure-spacing.test.ts b/server/routine-failure-spacing.test.ts
new file mode 100644
index 0000000000..592744870f
--- /dev/null
+++ b/server/routine-failure-spacing.test.ts
@@ -0,0 +1,200 @@
+// A routine whose runs keep failing stays on, and stops spending its bot's AI on a start every few minutes: the audit's
+// scenario is a routine every 5 minutes whose tool server is dead, counted in turns started (each is at least one
+// request to the AI) over a day.
+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 { FAILURE_FIRST_SPACING_MS, FAILURE_SPACING_MS, failedRuns, failureSpacing, failureSpacingAlert, failureSpacingLimits, runSpacing } from "./routine-failure-spacing.ts";
+import { sessionHolds, startPrompt } from "./routine-recovery.ts";
+import { RoutineManager, type RoutineManagerOptions, type RoutineRun } from "./routines.ts";
+
+const MINUTE = 60_000, HOUR = 60 * MINUTE;
+const START = Date.parse("2026-11-16T08:00:00Z");
+const DEAD_TOOL = "MCP server could not start; check its command and installation";
+const OVERLOADED = "Claude is overloaded right now (HTTP 529). Wait a minute, then run it again.";
+const NO_START = "Maus's cloud desktop didn't start. Change where this routine runs.";
+const SPAWN_REFUSED = "spawn /usr/local/bin/claude EAGAIN";
+const dirs: string[] = [];
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+const failed = (id: string, at: number, more: Record<string, unknown> = {}) => ({ id, routineId: "r", status: "failed", error: DEAD_TOOL, createdAt: at, startedAt: at, finishedAt: at + 50, ...more });
+const completed = (id: string, at: number) => ({ id, routineId: "r", status: "completed", createdAt: at, startedAt: at, finishedAt: at + 50 });
+const routine = { id: "r", updatedAt: 0 };
+
+describe("failed runs in a row", () => {
+ it("space the routine's scheduled runs an hour after the third and four hours after each later one", () => {
+ expect(failureSpacing(routine, [failed("a", 100), failed("b", 200)])).toBeNull();
+ expect(failureSpacing(routine, [failed("a", 100), failed("b", 200), failed("c", 300)])).toMatchObject({ streak: 3, until: 350 + FAILURE_FIRST_SPACING_MS, last: { id: "c" } });
+ expect(failureSpacing(routine, [failed("a", 100), failed("b", 200), failed("c", 300), failed("d", 400)])).toMatchObject({ streak: 4, until: 450 + FAILURE_SPACING_MS });
+ });
+
+ it("end with the first run that completes or a change to the routine", () => {
+ const three = [failed("a", 100), failed("b", 200), failed("c", 300)];
+ expect(failureSpacing(routine, [...three, completed("d", 400)])).toBeNull();
+ expect(failureSpacing({ id: "r", updatedAt: 250 }, three)).toBeNull();
+ expect(failureSpacing({ id: "other", updatedAt: 0 }, three)).toBeNull();
+ });
+
+ it("do not count a run that never started work", () => {
+ const rows = [failed("a", 100), failed("b", 200), failed("paused", 300, { startedAt: undefined })];
+ expect(failedRuns(routine, rows).map((run) => run.id)).toEqual(["b", "a"]);
+ expect(failureSpacing(routine, [...rows, failed("c", 600)])).toMatchObject({ streak: 3, last: { id: "c" } });
+ });
+
+ it("end at a run only the owner's AI account stopped, and so does a spacing already begun", () => {
+ const three = [failed("a", 100), failed("b", 200), failed("c", 300)];
+ expect(failureSpacing(routine, three)).not.toBeNull();
+ expect(failureSpacing(routine, [...three, failed("signed-out", 400, { ownerCause: "signed_out" })])).toBeNull();
+ const after = [...three, failed("limit", 400, { ownerCause: "usage_limit" }), failed("d", 500), failed("e", 600)];
+ expect(failedRuns(routine, after).map((run) => run.id)).toEqual(["e", "d"]);
+ expect(failureSpacing(routine, after)).toBeNull();
+ });
+
+ it("tell the owner once, at the failure that begins the spacing", () => {
+ const rows = [failed("a", 100), failed("b", 200), failed("c", 300)];
+ expect(failureSpacingAlert(routine, rows.slice(0, 2), rows[1]!)).toBeUndefined();
+ expect(failureSpacingAlert(routine, rows, rows[2]!)).toEqual({ detail: `${DEAD_TOOL} 3 runs in a row failed. It stays on, and tries again less often until a run completes.` });
+ expect(failureSpacingAlert(routine, [...rows, failed("d", 400)], rows[2]!)).toBeUndefined();
+ expect(failureSpacingAlert(undefined, rows, rows[2]!)).toBeUndefined();
+ expect(failureSpacingAlert({ ...routine, enabled: false }, rows, rows[2]!)).toBeUndefined();
+ });
+
+ it("give way to the spacing for a cloud computer that did not start when that one holds as long", () => {
+ const rows = [failed("a", 100, { error: NO_START }), failed("b", 200, { error: NO_START }), failed("c", 300, { error: NO_START })];
+ expect(runSpacing(routine, rows)).toMatchObject({ behind: "no-start:c", why: "routines.server.part.computerNoStart" });
+ expect(runSpacing(routine, [failed("a", 100), failed("b", 200), failed("c", 300)])).toMatchObject({ behind: "failed:c", why: "routines.server.part.runsFailed" });
+ expect(runSpacing(routine, [failed("a", 100)])).toBeNull();
+ });
+
+ it("read their limits from the environment, and keep the defaults for anything that is not a whole number in range", () => {
+ expect(failureSpacingLimits({})).toEqual({ runs: 3, firstMs: HOUR, laterMs: 4 * HOUR });
+ expect(failureSpacingLimits({ OMB_ROUTINE_FAILURES_BEFORE_SPACING: "5", OMB_ROUTINE_FAILURE_SPACING_MS: "600000", OMB_ROUTINE_FAILURE_SPACING_MAX_MS: "1800000" })).toEqual({ runs: 5, firstMs: 10 * MINUTE, laterMs: 30 * MINUTE });
+ expect(failureSpacingLimits({ OMB_ROUTINE_FAILURES_BEFORE_SPACING: "0", OMB_ROUTINE_FAILURE_SPACING_MS: "5m", OMB_ROUTINE_FAILURE_SPACING_MAX_MS: "1000" })).toEqual({ runs: 3, firstMs: HOUR, laterMs: 4 * HOUR });
+ expect(failureSpacingLimits({ OMB_ROUTINE_FAILURE_SPACING_MS: "7200000", OMB_ROUTINE_FAILURE_SPACING_MAX_MS: "3600000" })).toMatchObject({ firstMs: 2 * HOUR, laterMs: 2 * HOUR });
+ });
+});
+
+function harness(start?: RoutineManagerOptions["startTurn"], schedule: Parameters<RoutineManager["create"]>[0]["schedule"] = { type: "interval", everyMinutes: 5, anchorAt: START }) {
+ const dir = mkdtempSync(join(tmpdir(), "omb-routine-failure-spacing-"));
+ dirs.push(dir);
+ let now = START, task = 0;
+ const started: Array<{ threadId: string; prompt: string }> = [], alerts: unknown[] = [];
+ const said = new Map<string, string[]>();
+ const options: RoutineManagerOptions = {
+ file: join(dir, "routines.json"), now: () => now, botState: () => "ready",
+ createTask: () => ({ threadId: `thread-${++task}` }),
+ startTurn: async (botId, threadId, prompt, ...rest) => { started.push({ threadId, prompt }); said.set(threadId, [...(said.get(threadId) ?? []), prompt]); await start?.(botId, threadId, prompt, ...rest); },
+ promptSaid: (threadId, prompt) => said.get(threadId)?.includes(prompt) === true,
+ onRunFailed: (_run, alert) => alerts.push(alert),
+ };
+ const manager = new RoutineManager(options);
+ manager.create({ name: "Sync the CRM", prompt: "Read new leads from the CRM and file them", botId: "maus-1", schedule });
+ const working = () => manager.listRuns().filter((run) => run.status === "running");
+ return {
+ manager, started, alerts,
+ /** A scheduler pass every minute up to `to`; `settle` ends each turn the pass before left working. */
+ passTo: async (to: number, settle: (run: RoutineRun) => void) => {
+ while (now < to) {
+ now += MINUTE;
+ for (const run of working()) settle(run);
+ await manager.tick();
+ }
+ },
+ fail: (failure: string) => (run: RoutineRun) => manager.failThread(run.threadId!, failure),
+ complete: (run: RoutineRun) => void manager.handleRuntimeEvent({ eventId: `done-${run.id}-${now}`, provider: "fake", threadId: run.threadId!, createdAt: new Date(now).toISOString(), type: "turn.completed", ok: true } as Parameters<RoutineManager["handleRuntimeEvent"]>[0]),
+ rows: () => manager.listRuns().sort((a, b) => a.createdAt - b.createdAt),
+ routine: () => manager.listRoutines()[0]!,
+ };
+}
+
+describe("a routine every 5 minutes whose tool server is dead", () => {
+ it("starts 9 turns in its first day instead of one or two every 5 minutes, stays on, and leaves one row for what it skipped", async () => {
+ const h = harness();
+ await h.passTo(START + 24 * HOUR, h.fail(DEAD_TOOL));
+ console.log(`turns started in 24 hours with a dead tool server: ${h.started.length}`);
+ expect(h.started).toHaveLength(9);
+ expect(h.routine()).toMatchObject({ enabled: true });
+ const skipped = h.rows().filter((run) => run.skipped);
+ expect(skipped.every((run) => run.status === "missed" && /^Skipped \d+ scheduled runs because its last runs failed, so its next tries are spaced out$/.test(run.error!))).toBe(true);
+ expect(skipped.reduce((sum, run) => sum + run.skipped!.count, 0) + h.started.length).toBe(24 * 12);
+ expect(h.rows().filter((run) => run.status === "failed").every((run) => run.retried === undefined)).toBe(true);
+ expect(h.alerts.filter((alert) => alert !== null && alert !== undefined)).toEqual([{ detail: expect.stringContaining("3 runs in a row failed. It stays on") }]);
+ });
+
+ it("goes back to every 5 minutes with the first run that completes", async () => {
+ const h = harness();
+ await h.passTo(START + 2 * HOUR, h.fail(DEAD_TOOL));
+ const before = h.started.length;
+ await h.passTo(START + 6 * HOUR, h.complete);
+ await h.passTo(START + 7 * HOUR, h.complete);
+ expect(h.started.length - before).toBeGreaterThanOrEqual(12);
+ expect(h.rows().at(-2)).toMatchObject({ status: "completed" });
+ });
+
+ it("with the spacing set out of reach by OMB_ROUTINE_FAILURES_BEFORE_SPACING, starts one turn at every occurrence", async () => {
+ vi.stubEnv("OMB_ROUTINE_FAILURES_BEFORE_SPACING", "100000");
+ const h = harness();
+ await h.passTo(START + 24 * HOUR, h.fail(DEAD_TOOL));
+ console.log(`turns started in 24 hours with a dead tool server and no spacing: ${h.started.length}`);
+ expect(h.started).toHaveLength(24 * 12);
+ });
+});
+
+describe("a routine every minute by cron whose tool server is dead", () => {
+ it("is accepted, stays on, and is spaced out the same way", async () => {
+ const h = harness(undefined, { type: "cron", expression: "* * * * *", timeZone: "UTC" });
+ await h.passTo(START + 6 * HOUR, h.fail(DEAD_TOOL));
+ console.log(`turns started in 6 hours by a routine every minute with a dead tool server: ${h.started.length}`);
+ expect(h.started).toHaveLength(5);
+ expect(h.routine()).toMatchObject({ enabled: true, schedule: { type: "cron", expression: "* * * * *" } });
+ });
+});
+
+describe("a routine every 5 minutes on a server whose engines cannot start", () => {
+ it("tries 9 starts in its first day instead of two at every occurrence, and never a second start on the same full server", async () => {
+ const h = harness(async () => { throw new Error(SPAWN_REFUSED); });
+ await h.passTo(START + 24 * HOUR, () => {});
+ console.log(`engine starts tried in 24 hours on a server that cannot start one: ${h.started.length}`);
+ expect(h.started).toHaveLength(9);
+ expect(h.routine()).toMatchObject({ enabled: true });
+ expect(h.rows().filter((run) => run.status === "failed").every((run) => run.retried === undefined && run.error === SPAWN_REFUSED)).toBe(true);
+ });
+});
+
+describe("a run's one second start", () => {
+ it("is kept for a failure that passes, and sends only a short note when the conversation already holds the routine's instructions", async () => {
+ const h = harness();
+ await h.passTo(START + 5 * MINUTE, h.fail(OVERLOADED));
+ await h.passTo(START + 7 * MINUTE, h.fail(OVERLOADED));
+ expect(h.started.map((turn) => turn.threadId)).toEqual(["thread-1", "thread-1"]);
+ const [first, second] = h.started;
+ expect(first!.prompt).toContain("Read new leads from the CRM and file them");
+ expect(second!.prompt).not.toContain("Read new leads from the CRM and file them");
+ expect(second!.prompt).toContain("this run's first start failed on a temporary AI error before it finished");
+ expect(second!.prompt).toContain("so nothing is done twice");
+ console.log(`second start: ${second!.prompt.length} characters sent instead of ${first!.prompt.length + second!.prompt.length}`);
+ });
+
+ it("sends the routine's instructions again when the engine will not hold them: a backup AI, a usage-limit wait, a /command", () => {
+ const said = () => true;
+ expect(startPrompt({ retried: "provider" }, "Sync the CRM", "FIRST", said)).not.toContain("FIRST");
+ expect(startPrompt({ retried: "usage_limit" }, "Sync the CRM", "FIRST", said)).toMatch(/^FIRST\n\n/);
+ expect(startPrompt({ retried: "failed", attentionCode: "routines.server.backupSignedOut" }, "Sync the CRM", "FIRST", said)).toMatch(/^FIRST\n\n/);
+ expect(startPrompt({ retried: "provider" }, "/weekly-report for the CRM", "FIRST", said)).toMatch(/^FIRST\n\n/);
+ expect(startPrompt({ retried: "provider" }, "Sync the CRM", "FIRST", () => false)).toMatch(/^FIRST\n\n/);
+ });
+
+ it("counts the conversation as holding them only while a resumed session has them, or a replay's budget still reaches them", () => {
+ const messages = [{ role: "user", text: "older" }, { role: "user", text: "FIRST" }, { role: "bot", text: "x".repeat(10_000) }];
+ expect(sessionHolds({ resumes: true, messages, prompt: "FIRST", budgetBytes: 24_000 })).toBe(true);
+ expect(sessionHolds({ resumes: false, messages, prompt: "FIRST", budgetBytes: 24_000 })).toBe(true);
+ expect(sessionHolds({ resumes: false, messages: [...messages, { role: "bot", text: "y".repeat(20_000) }], prompt: "FIRST", budgetBytes: 24_000 })).toBe(false);
+ expect(sessionHolds({ resumes: true, messages, prompt: "missing", budgetBytes: 24_000 })).toBe(false);
+ });
+});
diff --git a/server/routine-failure-spacing.ts b/server/routine-failure-spacing.ts
new file mode 100644
index 0000000000..62557375fb
--- /dev/null
+++ b/server/routine-failure-spacing.ts
@@ -0,0 +1,70 @@
+// A routine whose runs keep failing is never turned off for it. Each failed run spent the bot's AI, so after a few in a
+// row its scheduled runs are spaced out as for a cloud computer that does not start, and every occurrence held back is
+// counted on one `missed` row. The first run that completes, turning the routine on again, or any change to it ends the
+// spacing, and so does a run only the owner's AI account stopped (signed out, out of credit, a usage limit). A run that
+// never started work counts for nothing here.
+import { envWhole } from "./env-limits.ts";
+import { afterSpacing, noStartSpacing } from "./routine-no-start.ts";
+import { outcomesNewestFirst } from "./routine-outcomes.ts";
+import type { RoutineAlert } from "./routine-recovery.ts";
+import type { SkipWhy } from "./routine-skips.ts";
+
+type Outcome = { id: string; routineId: string; status: string; error?: string | null; createdAt: number; startedAt?: number | null; finishedAt?: number | null; ownerCause?: string };
+type Spaced = { id: string; updatedAt: number };
+
+export interface FailureSpacingLimits {
+ /** Failed runs in a row before the routine's next scheduled runs are spaced out. */
+ runs: number;
+ /** How long after the last failure the next scheduled run waits: at that failure, and from the one after it on. */
+ firstMs: number;
+ laterMs: number;
+}
+
+export const FAILED_RUNS_BEFORE_SPACING = 3;
+export const FAILURE_FIRST_SPACING_MS = 60 * 60_000;
+export const FAILURE_SPACING_MS = 4 * 60 * 60_000;
+
+/** OMB_ROUTINE_FAILURES_BEFORE_SPACING (from 1), OMB_ROUTINE_FAILURE_SPACING_MS and OMB_ROUTINE_FAILURE_SPACING_MAX_MS
+ * (whole milliseconds from 60000, the second never below the first); anything else leaves the default. */
+export function failureSpacingLimits(env: NodeJS.ProcessEnv = process.env): FailureSpacingLimits {
+ const firstMs = envWhole(env.OMB_ROUTINE_FAILURE_SPACING_MS, FAILURE_FIRST_SPACING_MS, 60_000);
+ return { runs: envWhole(env.OMB_ROUTINE_FAILURES_BEFORE_SPACING, FAILED_RUNS_BEFORE_SPACING), firstMs,
+ laterMs: Math.max(firstMs, envWhole(env.OMB_ROUTINE_FAILURE_SPACING_MAX_MS, FAILURE_SPACING_MS, 60_000)) };
+}
+
+/** The routine's newest failed runs that started work, since it last completed a run, was turned on or was changed, or
+ * a run failed only on the owner's AI account (signed out, out of credit, a usage limit): that ends a streak and any
+ * spacing it began, since the cause changed. */
+export function failedRuns<T extends Outcome>(routine: Spaced, runs: readonly T[]): T[] {
+ const outcomes = outcomesNewestFirst(runs, routine.id);
+ const end = outcomes.findIndex((run) => run.status !== "failed" || run.createdAt < routine.updatedAt || run.ownerCause !== undefined);
+ return (end < 0 ? outcomes : outcomes.slice(0, end)).filter((run) => run.startedAt != null);
+}
+
+/** Until when the routine's scheduled runs are held back for failing, and the failure the spacing counts from; null when they are not. */
+export function failureSpacing<T extends Outcome>(routine: Spaced, runs: readonly T[], limits = failureSpacingLimits()): { until: number; last: T; streak: number } | null {
+ const failed = failedRuns(routine, runs), last = failed[0];
+ if (!last || failed.length < limits.runs) return null;
+ return { until: (last.finishedAt ?? last.createdAt) + (failed.length === limits.runs ? limits.firstMs : limits.laterMs), last, streak: failed.length };
+}
+
+export interface RunSpacing<T> { until: number; last: T; streak: number; behind: string; why: SkipWhy }
+
+/** The spacing that holds the routine's scheduled runs back longest: for a cloud computer that did not start, or for failed runs. */
+export function runSpacing<T extends Outcome>(routine: Spaced, runs: readonly T[], limits = failureSpacingLimits()): RunSpacing<T> | null {
+ const noStart = noStartSpacing(routine, runs), failed = failureSpacing(routine, runs, limits);
+ if (noStart && (!failed || noStart.until >= failed.until)) return { ...noStart, behind: `no-start:${noStart.last.id}`, why: "routines.server.part.computerNoStart" };
+ return failed && { ...failed, behind: `failed:${failed.last.id}`, why: "routines.server.part.runsFailed" };
+}
+
+/** What the owner is told, once, by the failure that begins the spacing; nothing for a routine that is off, whose schedule starts no run to space. */
+export function failureSpacingAlert<T extends Outcome>(routine: Spaced & { enabled?: boolean } | undefined, runs: readonly T[], run: T, limits = failureSpacingLimits()): RoutineAlert | undefined {
+ const failed = routine && routine.enabled !== false ? failedRuns(routine, runs) : [];
+ if (failed.length !== limits.runs || failed[0]?.id !== run.id) return undefined;
+ return { detail: `${run.error} ${limits.runs} runs in a row failed. It stays on, and tries again less often until a run completes.` };
+}
+
+/** The routine as wake and sleep planning should see it: its next run is the first occurrence a spacing does not skip. */
+export function afterRunSpacing<R extends Spaced & { enabled: boolean; nextRunAt: number | null; schedule: unknown }, T extends Outcome>(routine: R, runs: readonly T[], now: number, next: (schedule: R["schedule"], after: number) => number | null): R {
+ return afterSpacing(routine, runs, now, next, runSpacing);
+}
diff --git a/server/routine-lines.ts b/server/routine-lines.ts
index 062a1fac8d..0816ebd8ea 100644
--- a/server/routine-lines.ts
+++ b/server/routine-lines.ts
@@ -26,10 +26,14 @@ export const ROUTINE_LINE = {
"routines.server.stopUnconfirmed": "Its turn never confirmed that it stopped, so the next run started without that.",
"routines.server.skippedOne": "Skipped because {why}",
"routines.server.skippedMany": "Skipped {count} scheduled runs because {why}",
+ "routines.server.startSkippedOne": "Not run at this start because {why}",
+ "routines.server.startSkippedMany": "Not run at {count} starts because {why}",
"routines.server.part.stillWaiting": "the previous run of this routine is still waiting",
"routines.server.part.stillRunning": "the previous run of this routine is still running",
"routines.server.part.notStarted": "the previous run of this routine has not started yet",
"routines.server.part.computerNoStart": "its cloud desktop has not started, so its next tries are spaced out",
+ "routines.server.part.runsFailed": "its last runs failed, so its next tries are spaced out",
+ "routines.server.part.restartedSoon": "OpenMausBot started again soon after the start that last ran it",
"routines.server.missedOne": "Missed because {why}",
"routines.server.missedMany": "Missed {count} scheduled runs because {why}",
"routines.server.missedTooLate": "Missed because {why} until more than {hours} hours after its time",
diff --git a/server/routine-no-start.ts b/server/routine-no-start.ts
index 12b0fab722..86da337ba1 100644
--- a/server/routine-no-start.ts
+++ b/server/routine-no-start.ts
@@ -45,8 +45,9 @@ export function noStartAlert<T extends Outcome>(routine: Spaced | undefined, run
/** The routine as the computer's wake and sleep planning should see it: while its runs are spaced out, its next run is the
* first occurrence at or after the spacing's end (`next` gives a schedule's first occurrence after a time), not one that
* will only be skipped. */
-export function afterSpacing<R extends Spaced & { enabled: boolean; nextRunAt: number | null; schedule: unknown }, T extends Outcome>(routine: R, runs: readonly T[], now: number, next: (schedule: R["schedule"], after: number) => number | null): R {
- const spaced = routine.enabled && routine.nextRunAt !== null ? noStartSpacing(routine, runs) : null;
+export function afterSpacing<R extends Spaced & { enabled: boolean; nextRunAt: number | null; schedule: unknown }, T extends Outcome>(routine: R, runs: readonly T[], now: number, next: (schedule: R["schedule"], after: number) => number | null,
+ spacing: (routine: R, runs: readonly T[]) => { until: number } | null = noStartSpacing): R {
+ const spaced = routine.enabled && routine.nextRunAt !== null ? spacing(routine, runs) : null;
if (!spaced || spaced.until <= now || routine.nextRunAt! >= spaced.until) return routine;
return { ...routine, nextRunAt: next(routine.schedule, spaced.until - 1) };
}
diff --git a/server/routine-outcomes.ts b/server/routine-outcomes.ts
index 1c59dab8e4..1efcac43de 100644
--- a/server/routine-outcomes.ts
+++ b/server/routine-outcomes.ts
@@ -6,8 +6,24 @@ export function outcomesNewestFirst<T extends Outcome>(runs: readonly T[], routi
.sort((a, b) => (b.finishedAt ?? b.createdAt) - (a.finishedAt ?? a.createdAt) || b.createdAt - a.createdAt);
}
+const TIME = /\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?/g;
+const UUID = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi;
+const PATH = /(?:\b[A-Za-z]:)?(?:[\\/][\w.@~+-]+){2,}[\\/]?/g;
+/** A provider's request or object id ("req_011CUa7xYz9", "msg_01…", "toolu_01…") and a long hex digest. */
+const PREFIXED_ID = /\b[a-z]{2,8}_[A-Za-z0-9]{8,}\b|\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{12,}\b/g;
+/** A number of four digits or more on its own (a process id, a port, a count): never one inside a model id, and never a
+ * shorter one, so exit codes and HTTP statuses stay apart. */
+const LONG_NUMBER = /(?<![\w.-])\d{4,}(?![\w-]|\.\d)/g;
+
+/** A failure's words without what changes from one run to the next (times, ids, paths, long numbers), so two runs that
+ * fail for one reason read as the same failure, and an exit code, an HTTP status or a model still tell two apart. */
+export function failureShape(text: string): string {
+ return text.replace(TIME, "<time>").replace(PATH, "<path>").replace(UUID, "<id>").replace(PREFIXED_ID, "<id>")
+ .replace(LONG_NUMBER, "#").replace(/\s+/g, " ").trim().toLowerCase();
+}
+
/** The run failed the same way the routine's previous outcome did. */
export function failsLikeLastOutcome<T extends Outcome>(runs: readonly T[], run: T): boolean {
const last = outcomesNewestFirst(runs, run.routineId, run.id)[0];
- return last?.status === "failed" && last.error === run.error;
+ return last?.status === "failed" && failureShape(last.error ?? "") === failureShape(run.error ?? "");
}
diff --git a/server/routine-recovery.e2e.test.ts b/server/routine-recovery.e2e.test.ts
index ac4a76be98..dfa8ff47b4 100644
--- a/server/routine-recovery.e2e.test.ts
+++ b/server/routine-recovery.e2e.test.ts
@@ -15,6 +15,7 @@ import { openSse, type SseRecorder } from "./testing/sse.ts";
const STALLED = "No activity for 20 minutes — the routine was stopped";
const SIGN_IN = "This bot's AI is signed out. Sign in again in Settings → AI.";
const ROUTINE_HEADER = '[Routine "Inbox brief" — do this now:]';
+const DEAD_TOOL_SERVER = "MCP server could not start; check its command and installation";
let fixture: VerificationServer | undefined;
let restarted: ChildProcess | undefined;
@@ -109,8 +110,12 @@ it("starts a routine that crashed again once, and it completes in the same conve
await expect.poll(async () => (await s.run(id))?.status, { timeout: hostTimeout(60_000) }).toBe("completed");
expect(await s.run(id)).toMatchObject({ retried: "failed", threadId });
- expect(JSON.stringify(JSON.parse(readFileSync(s.dump, "utf8")).prompt)).toContain("this run's first start failed before it finished");
- expect((await s.prompts(threadId)).filter((text) => text.includes(ROUTINE_HEADER))).toHaveLength(2);
+ const second = JSON.stringify(JSON.parse(readFileSync(s.dump, "utf8")).prompt);
+ expect(second).toContain("this run's first start failed before it finished");
+ expect(second).toContain("The routine's instructions are in the message above and are not repeated here.");
+ // The crashed start left no session to resume, so the conversation is replayed: the instructions arrive once, not twice.
+ expect(second.split("Summarise my inbox.")).toHaveLength(2);
+ expect((await s.prompts(threadId)).filter((text) => text.includes(ROUTINE_HEADER))).toHaveLength(1);
expect(s.notified().filter((notification) => notification.kind === "routine-failed")).toEqual([]);
}, hostTimeout(120_000));
@@ -123,10 +128,33 @@ it("fails a routine that crashes again on its retry, says so, and never retries
expect(failed).toMatchObject({ retried: "failed", error: expect.stringMatching(/^Failed after one automatic retry: /) });
await expect.poll(() => s.notified().filter((notification) => notification.kind === "routine-failed"), { timeout: hostTimeout(15_000) })
.toEqual([expect.objectContaining({ title: "Inbox bot's routine failed", body: `Inbox brief: ${failed.error}` })]);
- expect((await s.prompts(failed.threadId)).filter((text) => text.includes(ROUTINE_HEADER))).toHaveLength(2);
+ expect((await s.prompts(failed.threadId)).filter((text) => text.includes(ROUTINE_HEADER))).toHaveLength(1);
expect(await s.runs()).toHaveLength(1);
}, hostTimeout(150_000));
+it("starts a routine whose tool server is dead once, not twice: one request to the AI, and the run row says why it failed", async () => {
+ const s = await server();
+ const requests = join(s.dataDir, "claude-requests.ndjson");
+ const sent = () => { try { return readFileSync(requests, "utf8").split("\n").filter(Boolean).length; } catch { return 0; } };
+ s.engine("api-error", { FAKE_CLAUDE_API_ERROR: DEAD_TOOL_SERVER, FAKE_CLAUDE_PROMPTS: requests });
+ const { id } = await s.runNow((await s.routine()).id);
+ await expect.poll(async () => (await s.run(id))?.status, { timeout: hostTimeout(30_000) }).toBe("failed");
+ const failed = await s.run(id);
+ expect(failed.error).toContain(DEAD_TOOL_SERVER);
+ expect(failed.retried).toBeUndefined();
+ // Longer than the 15 seconds a second start would have waited.
+ await new Promise((resolve) => setTimeout(resolve, 20_000));
+ expect(await s.run(id)).toMatchObject({ status: "failed" });
+ expect(sent()).toBe(1);
+ expect((await s.prompts(failed.threadId)).filter((text) => text.includes(ROUTINE_HEADER))).toHaveLength(1);
+
+ s.engine("api-error", { FAKE_CLAUDE_PROMPTS: requests });
+ const passing = await s.runNow((await s.routine("Calendar check")).id);
+ await expect.poll(async () => (await s.run(passing.id))?.status, { timeout: hostTimeout(90_000) }).toBe("failed");
+ expect(await s.run(passing.id)).toMatchObject({ retried: "provider" });
+ expect(sent()).toBe(3);
+}, hostTimeout(180_000));
+
it("picks a run that a restart cut off up again once on the next start, and never runs it twice", async () => {
const s = await server();
// Exiting slowly, as taskkill does on Windows, the engine ends its turn while the server is still shutting down.
@@ -149,7 +177,7 @@ it("picks a run that a restart cut off up again once on the next start, and neve
expect(JSON.stringify(JSON.parse(readFileSync(s.dump, "utf8")).prompt)).toContain("this run's first start was cut off when OpenMausBot restarted");
await new Promise((resolve) => setTimeout(resolve, 3_000));
const sent = await s.prompts(threadId);
- expect(sent.filter((text) => text.includes(ROUTINE_HEADER))).toHaveLength(2);
+ expect(sent.filter((text) => text.includes(ROUTINE_HEADER))).toHaveLength(1);
expect(sent.join("\n")).not.toContain("restarted while your previous turn here was running");
expect(await s.runs()).toHaveLength(1);
// The cut turn's own job is closed, so nothing can take it up again beside the second start.
diff --git a/server/routine-recovery.ts b/server/routine-recovery.ts
index 0465455918..334aa1691b 100644
--- a/server/routine-recovery.ts
+++ b/server/routine-recovery.ts
@@ -1,13 +1,15 @@
// What an unattended routine run's failure turns into: a failure starts the run once more after a short wait, unless a
// second start could only repeat or undo it (a stall the turn watchdog stopped, a stop someone pressed or typed, a
-// refusal, a spent cap); a busy target is waited for, a usage limit with a known reset is waited out, and what only the
-// owner can fix fails at once and is told to them once per bot and cause, until one of that bot's runs completes.
+// refusal, a spent cap, a fault of this server or its tool servers that a retry cannot fix); a busy target is waited
+// for, a usage limit with a known reset is waited out, and what only the owner can fix fails at once and is told to them
+// once per bot and cause, until one of that bot's runs completes.
// A teammate's failed thread takes the same verdict (host/chief-notices.ts).
import type { RuntimeEvent } from "../shared/runtime-events.ts";
import type { ServerText } from "../shared/server-text.ts";
import { isCountedSkip, type RoutineRetryCause } from "../shared/routines.ts";
import { engineFailureKind } from "./drivers/engine-errors.ts";
import { classifyError } from "./drivers/retry.ts";
+import { hostFaultOf, retryCannotFix } from "./host-fault.ts";
import { nextOccurrence } from "./routine-schedules.ts";
import type { Routine, RoutineRun } from "./routines.ts";
import { codedLine, fittedLine, type RoutineLine, type RoutineLineKey } from "./routine-lines.ts";
@@ -37,6 +39,10 @@ export interface RoutineFailureFacts {
partial?: boolean;
}
+/** On a failed run that only the owner's AI account could have let through: it spent nothing, so it does not count
+ * towards spacing its routine out. */
+export interface RoutineOwnerMark { ownerCause?: RoutineOwnerCause }
+
export type RoutineFailureClass =
| { kind: "retry"; cause: Exclude<RoutineRetryCause, "usage_limit"> }
| { kind: "busy" }
@@ -50,7 +56,7 @@ export interface RoutineOwnerNotice { botId: string; cause: RoutineOwnerCause; a
export type RoutineRecovery = { queued: true; alert?: RoutineAlert } | { queued: false; error: string; alert?: RoutineAlert | null };
-const RETRY_MS = 15_000;
+export const ROUTINE_RETRY_MS = 15_000;
const RATE_LIMIT_RETRY_MS = 60_000;
export const ROUTINE_BUSY_RECHECK_MS = 30_000;
export const ROUTINE_BUSY_WAIT_MS = 60 * 60_000;
@@ -84,12 +90,15 @@ const FIRST_START: Record<RoutineRetryCause, string> = {
};
/** Any failure gets one automatic retry, except a stall the turn watchdog stopped (its Chief hears instead), a
- * stop someone pressed or typed, a refusal, and a spent cap. Routine runs and teammate threads both judge by this. */
+ * stop someone pressed or typed, a refusal, a spent cap, and a fault a second start would meet again (no process could
+ * start, a full disk, a tool server that is down). Routine runs and teammate threads both judge by this. */
export function classifyRoutineFailure(failure: string, facts: RoutineFailureFacts = {}): RoutineFailureClass {
if (facts.cause === "busy") return { kind: "busy" };
if (facts.cause === "stalled" || facts.cause === "cap") return { kind: "final" };
if (facts.stopReason && NOT_RETRIED_STOPS.has(facts.stopReason)) return { kind: "final" };
if (classifyContinuable(facts.stopReason, failure) === "cap") return { kind: "final" };
+ const fault = hostFaultOf(failure, facts.stopReason);
+ if (fault && fault !== "signed_out" && retryCannotFix(fault)) return { kind: "final" };
if (facts.stalled) return { kind: "retry", cause: "stalled" };
const engine = engineFailureKind(failure);
const { reason, transient } = classifyError({ text: failure });
@@ -144,7 +153,7 @@ function attend(run: RoutineRun, line: RoutineLine): void {
/** Queues the run's one second start; false when it already had it or is not a bot's run. */
export function requeueOnce(run: RoutineRun, cause: RoutineRetryCause, failure: string, now: number,
- at = now + (cause === "rate_limited" ? RATE_LIMIT_RETRY_MS : RETRY_MS)): boolean {
+ at = now + (cause === "rate_limited" ? RATE_LIMIT_RETRY_MS : ROUTINE_RETRY_MS)): boolean {
if (run.target !== "bot" || run.retried !== undefined) return false;
run.status = "queued";
run.retried = cause;
@@ -162,6 +171,36 @@ export function retryNote(cause: RoutineRetryCause): string {
"check what it did (files, messages sent, anything started) so nothing is done twice; then finish the routine.]";
}
+/** The second start's whole message when the first start's is already in the conversation: the routine's instructions,
+ * attachments and previous-run excerpt are read from there and not sent, and paid for, a second time. */
+export function continueNote(cause: RoutineRetryCause): string {
+ return `[OpenMausBot: this run's first start ${FIRST_START[cause]} before it finished. The routine's instructions are in the message above ` +
+ "and are not repeated here. Check what the first start already did (files, messages sent, anything started) so nothing is done twice; then finish the routine.]";
+}
+
+/** Whether the conversation a second start continues still holds the first start's message (`prompt`) for its engine:
+ * a session it resumes does, and a replayed one only while that message and all after it fit the replay's budget. */
+export function sessionHolds(input: { resumes: boolean; messages: ReadonlyArray<{ role: string; text?: string }>; prompt: string; budgetBytes: number; maxMessages?: number }): boolean {
+ const at = input.messages.findLastIndex((message) => message.role === "user" && message.text === input.prompt);
+ if (at < 0) return false;
+ if (input.resumes) return true;
+ const replayed = input.messages.slice(at);
+ return replayed.length <= (input.maxMessages ?? 40) && replayed.reduce((bytes, message) => bytes + Buffer.byteLength(message.text ?? ""), 0) <= input.budgetBytes;
+}
+
+/** A second start whose engine session will not hold the first start's message: one moved to a backup AI or waiting out a
+ * usage limit, or a routine that calls a /command, which is only expanded where it is sent. */
+const startsAfresh = (run: Pick<RoutineRun, "retried" | "attentionCode">, prompt: string): boolean =>
+ run.retried === "usage_limit" || run.attentionCode === "routines.server.backupSignedOut" || run.attentionCode === "routines.server.backupAi"
+ || /(?:^|\s)\/[A-Za-z][\w:-]*/.test(prompt);
+
+/** What a run's start sends: `first`, what its first start sent, alone; for the one second start, the short note when the
+ * engine resumes a session that already holds `first` (`said`), else `first` again with the note. */
+export function startPrompt(run: Pick<RoutineRun, "retried" | "attentionCode">, prompt: string, first: string, said: (first: string) => boolean): string {
+ if (!run.retried) return first;
+ return !startsAfresh(run, prompt) && said(first) ? continueNote(run.retried) : `${first}\n\n${retryNote(run.retried)}`;
+}
+
function firstNotice(notices: RoutineOwnerNotice[], botId: string, cause: RoutineOwnerCause, at: number): boolean {
if (notices.some((notice) => notice.botId === botId && notice.cause === cause)) return false;
notices.push({ botId, cause, at });
@@ -188,12 +227,12 @@ export function recoverRun(run: RoutineRun, failure: string, facts: RoutineFailu
}
if (verdict.kind === "retry") return requeueOnce(run, verdict.cause, failure, now) ? { queued: true } : failed(again);
if (verdict.kind === "final") return failed(again);
- if (verdict.cause === "usage_limit" && facts.backupReady && requeueOnce(run, "usage_limit", failure, now, now + RETRY_MS)) {
+ if (verdict.cause === "usage_limit" && facts.backupReady && requeueOnce(run, "usage_limit", failure, now, now + ROUTINE_RETRY_MS)) {
attend(run, codedLine("attention", "routines.server.backupAi"));
return { queued: true };
}
// A signed-out AI's run starts again on the backup the person chose; its start there says once that it needs signing in.
- if (verdict.cause === "signed_out" && facts.backupReady && requeueOnce(run, "failed", failure, now, now + RETRY_MS)) {
+ if (verdict.cause === "signed_out" && facts.backupReady && requeueOnce(run, "failed", failure, now, now + ROUTINE_RETRY_MS)) {
attend(run, codedLine("attention", "routines.server.backupSignedOut"));
return { queued: true };
}
@@ -204,6 +243,7 @@ export function recoverRun(run: RoutineRun, failure: string, facts: RoutineFailu
if (reset && !nextCovers && reset > now && reset - now <= LIMIT_WAIT_MS && requeueOnce(run, "usage_limit", failure, now, reset + AFTER_RESET_MS)) {
return { queued: true, ...(first ? { alert: { detail: `This bot's AI reached its usage limit. This run starts again at ${when(reset + AFTER_RESET_MS)}.` } } : {}) };
}
+ run.ownerCause = verdict.cause;
const action = verdict.cause === "setup" ? failure : verdict.cause === "credits" && facts.trialCredit ? TRIAL_ACTION : OWNER_ACTION[verdict.cause];
return failed(verdict.cause === "signed_out" ? codedLine("error", "routines.server.signedOut", { failure }) : fittedLine("error", failure, verdict.cause === "setup" ? undefined : facts.text),
first ? { detail: action } : null);
diff --git a/server/routine-restarts.test.ts b/server/routine-restarts.test.ts
new file mode 100644
index 0000000000..541f75f2bf
--- /dev/null
+++ b/server/routine-restarts.test.ts
@@ -0,0 +1,125 @@
+// A headless server that crashes and starts again in a loop: what its routines start, counted in turns (each is at least
+// one request to the AI).
+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 { ROUTINE_RETRY_MS } from "./routine-recovery.ts";
+import { restartRetryAt, ROUTINE_RESTART_STAGGER_MS, STARTUP_ROUTINE_GAP_MS, startupDecision, startupRoutineGapMs } from "./routine-restarts.ts";
+import { RoutineManager, type RoutineManagerOptions } from "./routines.ts";
+
+const MINUTE = 60_000, HOUR = 60 * MINUTE;
+const START = Date.parse("2026-11-16T08:00:00Z");
+const dirs: string[] = [];
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+function server(launchId?: () => string) {
+ const dir = mkdtempSync(join(tmpdir(), "omb-routine-restarts-"));
+ dirs.push(dir);
+ let now = START, task = 0;
+ const started: Array<{ threadId: string; trigger: string }> = [];
+ const options = (): RoutineManagerOptions => ({
+ file: join(dir, "routines.json"), now: () => now, botState: () => "ready", launchId: launchId?.(),
+ createTask: () => ({ threadId: `thread-${++task}` }),
+ startTurn: async (_botId, threadId, _prompt, _runOn, trigger) => { started.push({ threadId, trigger }); },
+ });
+ const first = new RoutineManager(options());
+ return {
+ started, first,
+ setNow: (at: number) => { now = at; },
+ /** One process start: its scheduler's first pass, then each turn it started ends before the process dies. */
+ async boot(): Promise<RoutineManager> {
+ const booted = new RoutineManager(options());
+ booted.start();
+ await booted.tick();
+ for (const run of booted.listRuns().filter((candidate) => candidate.status === "running")) {
+ booted.handleRuntimeEvent({ eventId: `done-${run.id}`, provider: "fake", threadId: run.threadId!, createdAt: new Date(now).toISOString(), type: "turn.completed", ok: true });
+ }
+ booted.close();
+ return booted;
+ },
+ };
+}
+
+const daily = { name: "Morning brief", prompt: "Brief me", botId: "maus-1", runOnStartup: true, schedule: { type: "daily" as const, time: "23:00", weekdays: [0, 1, 2, 3, 4, 5, 6] } };
+
+describe("a headless server's startup routines", () => {
+ it("run at most once in OMB_STARTUP_ROUTINE_GAP_MS while the server crashes and starts again every minute", async () => {
+ const s = server();
+ const routine = s.first.create(daily);
+ let last: RoutineManager | undefined;
+ for (let minute = 0; minute < 60; minute++) {
+ s.setNow(START + minute * MINUTE);
+ last = await s.boot();
+ }
+ const startups = s.started.filter((turn) => turn.trigger === "startup");
+ console.log(`startup turns in an hour of restarts every minute: ${startups.length}`);
+ expect(startups).toHaveLength(2);
+ const skipped = last!.listRuns().filter((run) => run.status === "missed");
+ expect(skipped.map((run) => [run.routineId, run.triggerSource, run.skipped?.count, run.error])).toEqual([
+ [routine.id, "startup", 29, "Not run at 29 starts because OpenMausBot started again soon after the start that last ran it"],
+ [routine.id, "startup", 29, "Not run at 29 starts because OpenMausBot started again soon after the start that last ran it"],
+ ]);
+ });
+
+ it("run at every start with OMB_STARTUP_ROUTINE_GAP_MS=0", async () => {
+ vi.stubEnv("OMB_STARTUP_ROUTINE_GAP_MS", "0");
+ const s = server();
+ s.first.create(daily);
+ for (let minute = 0; minute < 10; minute++) {
+ s.setNow(START + minute * MINUTE);
+ await s.boot();
+ }
+ expect(s.started.filter((turn) => turn.trigger === "startup")).toHaveLength(10);
+ });
+
+ it("still run once per desktop launch, whatever the gap", async () => {
+ let launch = 0;
+ const s = server(() => `launch-${++launch}`);
+ s.first.create(daily);
+ for (let minute = 0; minute < 3; minute++) {
+ s.setNow(START + minute * MINUTE);
+ await s.boot();
+ }
+ expect(s.started.filter((turn) => turn.trigger === "startup")).toHaveLength(3);
+ });
+
+ it("decide from what the last start recorded", () => {
+ expect(startupDecision("launch-a", "at:1", START)).toEqual({ run: true, marker: "launch-a" });
+ expect(startupDecision(undefined, undefined, START)).toEqual({ run: true, marker: `at:${START}` });
+ expect(startupDecision(undefined, "launch-a", START)).toEqual({ run: true, marker: `at:${START}` });
+ const held = startupDecision(undefined, `at:${START}`, START + STARTUP_ROUTINE_GAP_MS - 1);
+ expect(held.run === false && held.behind("r1")).toBe(`startup:${START}:r1`);
+ expect(startupDecision(undefined, `at:${START}`, START + STARTUP_ROUTINE_GAP_MS)).toEqual({ run: true, marker: `at:${START + STARTUP_ROUTINE_GAP_MS}` });
+ // A clock set back runs them rather than holding them for good.
+ expect(startupDecision(undefined, `at:${START}`, START - HOUR)).toMatchObject({ run: true });
+ expect(startupRoutineGapMs({ OMB_STARTUP_ROUTINE_GAP_MS: "60000" })).toBe(MINUTE);
+ expect(startupRoutineGapMs({ OMB_STARTUP_ROUTINE_GAP_MS: "30m" })).toBe(STARTUP_ROUTINE_GAP_MS);
+ });
+});
+
+describe("runs a restart cut off", () => {
+ it("start again one after another, OMB_ROUTINE_RESTART_STAGGER_MS apart, not all at once", async () => {
+ const s = server();
+ for (let i = 0; i < 4; i++) s.first.runNow(s.first.create({ ...daily, name: `Brief ${i}`, runOnStartup: false }).id);
+ await s.first.tick();
+ expect(s.first.listRuns().filter((run) => run.status === "running")).toHaveLength(4);
+ s.first.close();
+ s.setNow(START + MINUTE);
+ const restarted = new RoutineManager({ file: join(dirs[0]!, "routines.json"), now: () => START + MINUTE, botState: () => "ready", createTask: () => ({ threadId: "x" }), startTurn: async () => {} });
+ const at = restarted.listRuns().map((run) => [run.status, run.retried, run.retryAt]).sort((a, b) => Number(a[2]) - Number(b[2]));
+ expect(at).toEqual([0, 1, 2, 3].map((i) => ["queued", "restarted", START + MINUTE + ROUTINE_RETRY_MS + i * ROUTINE_RESTART_STAGGER_MS]));
+ restarted.close();
+ });
+
+ it("wait for another machine's lease when that is later", () => {
+ expect(restartRetryAt(START, 0, undefined)).toBe(START + ROUTINE_RETRY_MS);
+ expect(restartRetryAt(START, 2, START + HOUR)).toBe(START + HOUR);
+ expect(restartRetryAt(START, 2, undefined, 0)).toBe(START + ROUTINE_RETRY_MS);
+ });
+});
diff --git a/server/routine-restarts.ts b/server/routine-restarts.ts
new file mode 100644
index 0000000000..6fde0ee386
--- /dev/null
+++ b/server/routine-restarts.ts
@@ -0,0 +1,32 @@
+// What a server start does to routines when the server may be crashing and starting again in a loop. A start with no
+// desktop launch (a headless server) runs its startup routines at most once in OMB_STARTUP_ROUTINE_GAP_MS, counted from
+// the start that last ran them, and each start it skips adds to one row per routine. Runs a restart cut off start again
+// one after another, OMB_ROUTINE_RESTART_STAGGER_MS apart, not all at the same moment.
+import { envWhole } from "./env-limits.ts";
+import { ROUTINE_RETRY_MS } from "./routine-recovery.ts";
+
+export const STARTUP_ROUTINE_GAP_MS = 30 * 60_000;
+export const ROUTINE_RESTART_STAGGER_MS = 30_000;
+
+/** OMB_STARTUP_ROUTINE_GAP_MS, whole milliseconds from 0 (0 runs them at every start); anything else leaves the default. */
+export const startupRoutineGapMs = (env: NodeJS.ProcessEnv = process.env): number => envWhole(env.OMB_STARTUP_ROUTINE_GAP_MS, STARTUP_ROUTINE_GAP_MS, 0);
+/** OMB_ROUTINE_RESTART_STAGGER_MS, whole milliseconds from 0; anything else leaves the default. */
+export const restartStaggerMs = (env: NodeJS.ProcessEnv = process.env): number => envWhole(env.OMB_ROUTINE_RESTART_STAGGER_MS, ROUTINE_RESTART_STAGGER_MS, 0);
+
+const HEADLESS_START = /^at:(\d{1,16})$/;
+
+export type StartupDecision = { run: true; marker: string | undefined } | { run: false; behind: (routineId: string) => string };
+
+/** Whether this start runs its startup routines, and what it records: the desktop's launch, or for a headless server the
+ * time it ran them (`last` is what the previous start recorded). A skip is counted on one row per routine and window. */
+export function startupDecision(launchId: string | undefined, last: string | undefined, now: number, gapMs = startupRoutineGapMs()): StartupDecision {
+ if (launchId !== undefined) return { run: true, marker: launchId };
+ const ranAt = HEADLESS_START.exec(last ?? "")?.[1];
+ if (ranAt !== undefined && now >= Number(ranAt) && now - Number(ranAt) < gapMs) return { run: false, behind: (routineId) => `startup:${ranAt}:${routineId}` };
+ return { run: true, marker: `at:${now}` };
+}
+
+/** When the `index`-th run a restart cut off may start again: in turn, and not before `held` (another machine's lease). */
+export function restartRetryAt(now: number, index: number, held: number | undefined, staggerMs = restartStaggerMs()): number {
+ return Math.max(held ?? 0, now + ROUTINE_RETRY_MS + index * staggerMs);
+}
diff --git a/server/routine-skips.ts b/server/routine-skips.ts
index 5239c2c07f..8fb248c0fa 100644
--- a/server/routine-skips.ts
+++ b/server/routine-skips.ts
@@ -1,5 +1,5 @@
// A scheduled occurrence that does not run always leaves a `missed` row saying why. Occurrences skipped for one cause
-// (the same earlier run still going, the same spacing after a cloud computer that did not start) share one row, which
+// (the same earlier run still going, the same spacing after a cloud computer that did not start or after failed runs) share one row, which
// counts them and keeps the first and last time: a schedule every minute behind a run of hours adds one row, not hundreds.
import { ROUTINE_DEFERRAL_NOTICE_MS } from "./routine-execution.ts";
import { codedLine, type RoutineLineKey } from "./routine-lines.ts";
@@ -12,13 +12,14 @@ export interface RoutineSkips {
/** The scheduled times of the first and the last of them. */
firstAt: number;
lastAt: number;
- /** The cause: the id of the run they waited behind, or `no-start:` and the id of the last run whose computer did not start. */
+ /** The cause: the id of the run they waited behind, `no-start:` and the id of the last run whose computer did not start, `failed:` and the id of the last run that failed, or `startup:`, the time of the start that last ran a startup routine and the routine's id. */
behind: string;
/** The owner was told about this cause. */
told?: true;
}
-export type SkipWhy = Extract<RoutineLineKey, "routines.server.part.stillWaiting" | "routines.server.part.stillRunning" | "routines.server.part.notStarted" | "routines.server.part.computerNoStart">;
+export type SkipWhy = Extract<RoutineLineKey, "routines.server.part.stillWaiting" | "routines.server.part.stillRunning" | "routines.server.part.notStarted" | "routines.server.part.computerNoStart" | "routines.server.part.runsFailed"
+ | "routines.server.part.restartedSoon">;
/** A run of the same routine that an occurrence is skipped behind, and, for one that waits, since when. */
export function blockingRun(runs: readonly RoutineRun[], routineId: string): { run: RoutineRun; why: SkipWhy; waitingSince?: number } | undefined {
@@ -43,7 +44,9 @@ export function recordSkip(runs: readonly RoutineRun[], make: () => RoutineRun,
: { count, firstAt: earlier?.scheduledFor ?? scheduledFor, lastAt: scheduledFor, behind: cause.behind };
const tell = !skipped.told && cause.waitingSince !== undefined && scheduledFor >= cause.waitingSince + ROUTINE_DEFERRAL_NOTICE_MS;
if (tell) skipped.told = true;
- const line = skipped.count === 1 ? codedLine("error", "routines.server.skippedOne", { why: cause.why }) : codedLine("error", "routines.server.skippedMany", { count: skipped.count, why: cause.why });
+ const atStart = cause.why === "routines.server.part.restartedSoon";
+ const line = skipped.count === 1 ? codedLine("error", atStart ? "routines.server.startSkippedOne" : "routines.server.skippedOne", { why: cause.why })
+ : codedLine("error", atStart ? "routines.server.startSkippedMany" : "routines.server.skippedMany", { count: skipped.count, why: cause.why });
Object.assign(row, line.codes, { status: "missed", error: line.text, finishedAt: now, skipped } satisfies Partial<RoutineRun>);
if (tell) delete row.seenAt;
else if (!found) row.seenAt = now;
diff --git a/server/routines.ts b/server/routines.ts
index e434266f66..e522e0bb8c 100644
--- a/server/routines.ts
+++ b/server/routines.ts
@@ -24,13 +24,13 @@ import {
routineFailure, routineHostWarning, supersededBy,
} from "./routine-execution.ts";
import {
- dispatchRefusal, engineFacts, nextScheduledRun, recoverRun, requeueOnce, weekRuns, type RoutineAlert, type RoutineFailureFacts, type RoutineOwnerNotice,
+ dispatchRefusal, engineFacts, nextScheduledRun, recoverRun, requeueOnce, startPrompt, weekRuns, type RoutineAlert, type RoutineFailureFacts, type RoutineOwnerMark, type RoutineOwnerNotice,
} from "./routine-recovery.ts";
import { askOf, settleAsk, waitingFor, type RoutineRunAsk } from "./routine-waits.ts";
import { failsLikeLastOutcome, outcomesNewestFirst } from "./routine-outcomes.ts"; import { createRunGate, type RunPreparation } from "./routine-run-gate.ts";
import { busyWait, markStop, RunClock, runOverLimit, SlowStops, withBoundedStops, type StopState } from "./routine-bounds.ts"; import { keepUnreadableAside, readRoutineFile, UNREADABLE_RETRY_MS } from "./routine-file.ts";
-import { afterSpacing, noStartAlert, noStartSpacing, turnBackOn } from "./routine-no-start.ts"; import { blockingRun, recordSkip, type RoutineSkips } from "./routine-skips.ts";
-import { routineHealthOf, type RoutineHealth } from "./routine-health.ts"; import { Occurrences, ROUTINE_TURN_GONE } from "./routine-occurrences.ts"; import type { Occurrence } from "./routine-ledger.ts";
+import { noStartAlert, noStartSpacing, turnBackOn } from "./routine-no-start.ts"; import { afterRunSpacing, failureSpacingAlert, runSpacing } from "./routine-failure-spacing.ts"; import { blockingRun, recordSkip, type RoutineSkips } from "./routine-skips.ts";
+import { restartRetryAt, startupDecision } from "./routine-restarts.ts"; import { routineHealthOf, type RoutineHealth } from "./routine-health.ts"; import { Occurrences, ROUTINE_TURN_GONE } from "./routine-occurrences.ts"; import type { Occurrence } from "./routine-ledger.ts";
import { CATCH_UP_MS, planOccurrence, settleRestored, staggered } from "./routine-catch-up.ts"; import { evictRuns } from "./routine-run-history.ts"; import { RunWatch } from "./routine-run-watch.ts"; import { scheduleSection, type ScheduleSection } from "./routine-schedule-report.ts";
import { EVENT_RETRY_WINDOW_MS, MAX_EVENT_RECEIPTS, type EventRunReceipt } from "./routine-event-receipts.ts";
import { attachmentPathsOf, cloneAttachments } from "./routine-attachments.ts";
@@ -97,7 +97,7 @@ export interface RoutinePackageStamp {
parts: Record<RoutinePart, PartPair>;
}
-export interface RoutineRun extends RoutineLineCodes {
+export interface RoutineRun extends RoutineLineCodes, RoutineOwnerMark {
id: string;
routineId: string;
routineName: string;
@@ -271,6 +271,7 @@ export interface RoutineManagerOptions {
outcome?: { status: "stopped" | "limit-reached"; detail: string },
) => Promise<void>;
onRunChanged?: (run: RoutineRun) => void;
+ /** The thread's engine session will resume holding this message, so a second start need not send it again. */ promptSaid?: (threadId: string, prompt: string) => boolean;
onRunFailed?: (run: RoutineRun, alert?: RoutineAlert | null) => void;
onRunDeferred?: (run: RoutineRun, alert?: RoutineAlert) => void;
/** A run a restart cut off, before it starts again or fails: its old turn's work must not resume as well. */
@@ -369,13 +370,14 @@ export class RoutineManager {
startupLaunchId: this.startupLaunchId, noStartOffsChecked: this.noStartOffsChecked } = read);
this.disk.loaded(read.text);
const cut = settleRestored(this.routines, this.runs, this.ledger.restoredThrough, this.now(), (routine, past) => this.advancePastOccurrence(routine, past, past)).map(cloneRun); this.ledger.restoredThrough = null;
+ let restarts = 0;
for (const run of this.runs.filter((candidate) => candidate.status === "running" || candidate.status === "waiting")) {
settleAsk(run, undefined, this.now());
if (run.threadId && run.target === "bot" && this.options.hasPendingDelegations?.(run.threadId) === true) {
this.wait(run, ROUTINE_HANDOFF_WAIT);
continue;
}
- if (!requeueOnce(run, "restarted", ROUTINE_RESTARTED, this.now(), this.ledger.retryAfterBoot(run))) {
+ if (!requeueOnce(run, "restarted", ROUTINE_RESTARTED, this.now(), restartRetryAt(this.now(), restarts++, this.ledger.retryAfterBoot(run)))) {
Object.assign(run, { status: "failed", error: ROUTINE_RESTARTED, attention: undefined, finishedAt: this.now() } satisfies Partial<RoutineRun>);
if (run.target === "room-goal") run.goalStatus = "failed";
}
@@ -451,7 +453,7 @@ export class RoutineManager {
/** Routines an earlier version had switched off that this start turned back on, handed over once, for a line to their bots. */
takeTurnedBackOn(): Routine[] { return this.turnedBackOn.splice(0).map(cloneRoutine); }
/** Each routine with the next run it will really make: one whose runs are spaced out is not due for the occurrences it skips. */
- private planned(routines: readonly Routine[]): Routine[] { return routines.map((routine) => routine.checks || runsOnce(routine.schedule) ? routine : afterSpacing(routine, this.runs, this.now(), nextOccurrence)); }
+ private planned(routines: readonly Routine[]): Routine[] { return routines.map((routine) => routine.checks || runsOnce(routine.schedule) ? routine : afterRunSpacing(routine, this.runs, this.now(), nextOccurrence)); }
wakeHold(horizonMs = WAKE_HORIZON_MS) { return wakeHoldOf(this.planned(this.routines), this.runs, this.now(), horizonMs); }
/** A Cloud home's sleep check (server/routine-due.ts). */
hasActiveRuns(): boolean { return activeRunsOf(this.runs, this.now()); }
@@ -976,9 +978,8 @@ export class RoutineManager {
private queueStartupRuns(): boolean {
if (this.options.skipStartupRuns) return true;
- const launchId = this.options.launchId;
+ const launchId = this.options.launchId, now = this.now();
if (launchId !== undefined && launchId === this.startupLaunchId) return true;
- const now = this.now();
const flagged = this.routines.filter((routine) =>
routine.enabled && routine.runOnStartup && routine.schedule.type !== "once" &&
(routine.schedule.type !== "interval" || routine.schedule.endsAt === undefined || now <= routine.schedule.endsAt));
@@ -986,16 +987,14 @@ export class RoutineManager {
!(routine.nextRunAt != null && routine.nextRunAt <= now && now - routine.nextRunAt <= CATCH_UP_MS) &&
!this.runs.some((run) => run.routineId === routine.id && ["queued", "running", "waiting"].includes(run.status)));
if (marked.length === 0 && launchId === undefined) return true;
- const previousLaunchId = this.startupLaunchId;
- const runs: RoutineRun[] = [];
- const allocations: ResultsThreadAllocation[] = [];
+ const previousLaunchId = this.startupLaunchId, decision = startupDecision(launchId, previousLaunchId, now), runs: RoutineRun[] = [], allocations: ResultsThreadAllocation[] = [];
try {
this.commitMutation(() => {
- if (launchId !== undefined) this.startupLaunchId = launchId;
+ if (decision.run && decision.marker !== undefined) this.startupLaunchId = decision.marker;
for (const routine of marked) {
- const run = this.newRun(routine, now, false, allocations);
- run.triggerSource = "startup";
- runs.push(run);
+ const startup = () => Object.assign(this.newRun(routine, now, false, allocations), { triggerSource: "startup" as const });
+ if (!decision.run) { runs.push(recordSkip(this.runs, startup, { behind: decision.behind(routine.id), why: "routines.server.part.restartedSoon" }, now, now).row); continue; }
+ runs.push(startup());
if (routine.nextRunAt != null && routine.nextRunAt <= now) this.advancePastOccurrence(routine, now, routine.nextRunAt);
}
}, () => {
@@ -1053,11 +1052,11 @@ export class RoutineManager {
}
const plan = planOccurrence(routine, now, this.options.home?.cloud === true, this.passedAt >= routine.nextRunAt!), scheduledFor = plan.scheduledFor;
if (this.ledger.decided(routine.id, scheduledFor)) { this.advancePastOccurrence(routine, now, plan.through); continue; }
- const once = runsOnce(routine.schedule), blocker = once ? undefined : blockingRun(this.runs, routine.id), spaced = once ? null : noStartSpacing(routine, this.runs);
+ const once = runsOnce(routine.schedule), blocker = once ? undefined : blockingRun(this.runs, routine.id), spaced = once ? null : runSpacing(routine, this.runs);
const scheduledQueued = this.runs.some(run => run.routineId === routine.id && run.status === "queued" &&
(run.triggerSource ?? (run.manual ? "manual" : "schedule")) === "schedule");
const skipFor = blocker && !(routine.overlap === "queue" && !scheduledQueued) ? { behind: blocker.run.id, why: blocker.why, waitingSince: blocker.waitingSince }
- : spaced && spaced.until > now ? { behind: `no-start:${spaced.last.id}`, why: "routines.server.part.computerNoStart" as const } : undefined;
+ : spaced && spaced.until > now ? { behind: spaced.behind, why: spaced.why } : undefined;
if (!skipFor) {
if (plan.older) countedSkips.push(Object.assign(this.newRun(routine, plan.older.scheduledFor, false, allocations), plan.older.fields));
scheduledRuns.push(Object.assign(this.newRun(routine, scheduledFor, false, allocations), plan.fields, plan.late ? staggered(now, lateStarts++) : {}));
@@ -1184,7 +1183,7 @@ export class RoutineManager {
await this.options.startTurn(
run.botId,
task.threadId,
- composeExecutionPrompt({ id: run.routineId, name: run.routineName, trigger: triggerSource, runOn: run.runOn ?? "maus" }, prompt, run.attachments, continuityCarry(run, this.routines, this.runs), run.retried),
+ startPrompt(run, prompt, composeExecutionPrompt({ id: run.routineId, name: run.routineName, trigger: triggerSource, runOn: run.runOn ?? "maus" }, prompt, run.attachments, continuityCarry(run, this.routines, this.runs)), (first) => this.options.promptSaid?.(task.threadId, first) === true),
run.runOn ?? "maus",
triggerSource,
(message) => this.failThread(task.threadId, message, { cause: "refused" }),
@@ -1379,7 +1378,7 @@ 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>);
- const spaced = status === "failed" ? noStartAlert(this.routines.find((routine) => routine.id === run.routineId), this.runs, run) : undefined;
+ const routine = this.routines.find((candidate) => candidate.id === run.routineId), spaced = status === "failed" ? noStartAlert(routine, this.runs, run) ?? failureSpacingAlert(routine, this.runs, run) : undefined;
this.saveLater(); this.emitRun(run);
const repeat = failsLikeLastOutcome(this.runs, run) || (run.checkKey !== undefined && outcomesNewestFirst(this.runs, run.routineId, run.id)[0]?.status === "failed");
this.options.onRunFailed?.(cloneRun(run), spaced ?? (alert === undefined && repeat ? null : alert));
diff --git a/src/locales/de.json b/src/locales/de.json
index d85350d161..3e0738234f 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -97,6 +97,7 @@
"server.incidents.where.room": "im Raum „{room}“",
"server.incidents.where.thread": "im Thread #{title}",
"server.incidents.where.main": "in der Hauptunterhaltung",
+ "server.incidents.folded": "{chief} wird nur zu einer begrenzten Zahl von Problemen pro Stunde gefragt, daher wurden {count} weitere in dieser Stunde nicht dorthin geschickt. Aus: {list}",
"server.connect.signIn": "Bitte melde dich bei {site} an.",
"server.connect.signInWhy": "Bitte melde dich bei {site} an: {reason}",
"server.connect.app": "Bitte verbinde {app}.",
diff --git a/src/locales/en.json b/src/locales/en.json
index abd1ebde1e..2ee1006113 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -233,6 +233,7 @@
"server.problem.routineFailedWhy": "{bot} hit a problem: its scheduled routine {where} failed: \"{detail}\"",
"server.incidents.where.thread": "in its thread #{title}",
"server.incidents.where.main": "in its main conversation",
+ "server.incidents.folded": "{chief} is asked about only so many problems an hour, so {count} more this hour were not sent to it. From: {list}",
"server.connect.signIn": "I need you to sign in to {site}.",
"server.connect.signInWhy": "I need you to sign in to {site}: {reason}",
"server.connect.app": "I need you to connect {app}.",
@@ -10130,10 +10131,14 @@
"routines.server.stopUnconfirmed": "Its turn never confirmed that it stopped, so the next run started without that.",
"routines.server.skippedOne": "Skipped because {why}",
"routines.server.skippedMany": "Skipped {count} scheduled runs because {why}",
+ "routines.server.startSkippedOne": "Not run at this start because {why}",
+ "routines.server.startSkippedMany": "Not run at {count} starts because {why}",
"routines.server.part.stillWaiting": "the previous run of this routine is still waiting",
"routines.server.part.stillRunning": "the previous run of this routine is still running",
"routines.server.part.notStarted": "the previous run of this routine has not started yet",
"routines.server.part.computerNoStart": "its cloud desktop has not started, so its next tries are spaced out",
+ "routines.server.part.runsFailed": "its last runs failed, so its next tries are spaced out",
+ "routines.server.part.restartedSoon": "OpenMausBot started again soon after the start that last ran it",
"routines.server.missedOne": "Missed because {why}",
"routines.server.missedMany": "Missed {count} scheduled runs because {why}",
"routines.server.missedTooLate": "Missed because {why} until more than {hours} hours after its time",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 707637024b..7fe67d652e 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -216,6 +216,7 @@
"server.problem.routineFailedWhy": "{bot} encontrou um problema: a rotina agendada {where} falhou: \"{detail}\"",
"server.incidents.where.thread": "na conversa #{title} dele",
"server.incidents.where.main": "na conversa principal dele",
+ "server.incidents.folded": "{chief} só recebe um número limitado de problemas por hora, então outros {count} desta hora não foram enviados para ele. Origem: {list}",
"server.connect.signIn": "Preciso que você faça login em {site}.",
"server.connect.signInWhy": "Preciso que você faça login em {site}: {reason}",
"server.connect.app": "Preciso que você conecte {app}.",
@@ -10052,10 +10053,14 @@
"routines.server.stopUnconfirmed": "O turno nunca confirmou que parou, então a próxima execução começou sem essa confirmação.",
"routines.server.skippedOne": "Pulada porque {why}",
"routines.server.skippedMany": "{count} execuções agendadas foram puladas porque {why}",
+ "routines.server.startSkippedOne": "Não rodou nesta inicialização porque {why}",
+ "routines.server.startSkippedMany": "Não rodou em {count} inicializações porque {why}",
"routines.server.part.stillWaiting": "a execução anterior desta rotina ainda está esperando",
"routines.server.part.stillRunning": "a execução anterior desta rotina ainda está em andamento",
"routines.server.part.notStarted": "a execução anterior desta rotina ainda não começou",
"routines.server.part.computerNoStart": "o desktop na nuvem dela não iniciou, então as próximas tentativas ficam mais espaçadas",
+ "routines.server.part.runsFailed": "as últimas execuções dela falharam, então as próximas tentativas ficam mais espaçadas",
+ "routines.server.part.restartedSoon": "o OpenMausBot iniciou novamente logo depois da inicialização em que ela rodou pela última vez",
"routines.server.missedOne": "Não rodou porque {why}",
"routines.server.missedMany": "{count} execuções agendadas não rodaram porque {why}",
"routines.server.missedTooLate": "Não rodou porque {why} até mais de {hours} horas depois do horário",
diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.json
index b690d53ed2..e6108ee840 100644
--- a/src/locales/source-hashes.json
+++ b/src/locales/source-hashes.json
@@ -2,6 +2,7 @@
"version": 1,
"locales": {
"de": {
+ "server.incidents.folded": "0f3510347ddace2c9fb06627f1759a1358aba45e82546e98aca8e968a5789105",
"pro.fromPrice": "a48a04a457d60b08b54fc83e7a6c4584ffedb1e23621859084900c8521a3af7b",
"pro.seePlans": "30d9abfd7c7af513814bdfadcafe7ec4a90bc6bcee519086dc513f63f2cd7384",
"pro.reauthShort": "089c74d900d6e3d84b0d4981fb4eb0b4038d9a243ca8209862f7500766382473",
@@ -26302,6 +26303,7 @@
"server.problem.routineFailedWhy": "e75cb57f69f5b83f3382ee555a781d9c138b4103754516269b5f3d6c46a8a054",
"server.incidents.where.thread": "7183a89f7d0a8b4e46d5bae46eb1a46f0e115121ed3df5ffa543dc20399e951b",
"server.incidents.where.main": "3487a3ee49954d4abe9ba0eef161dfd6b625f80160a4de210a1bbed8be7f171c",
+ "server.incidents.folded": "0f3510347ddace2c9fb06627f1759a1358aba45e82546e98aca8e968a5789105",
"server.connect.signIn": "5f56f9a9e5350cb543bec3a741946319aba177a5ff20d904685b233886355963",
"server.connect.signInWhy": "a2db45f4f98be35ec33f63ef819f4a33fecb48e8921b8ed05fe96a05d2af2796",
"server.connect.app": "98e9946a8e4ea7eb20fd81744ad7a17d0ae306ecd3b8564f11380a5cd6b80cbb",
@@ -37032,10 +37034,14 @@
"routines.server.stopUnconfirmed": "325194f89d84fa5bed6ad357614fd516eb53ca92bb0dbb3cb34683f397f45cfd",
"routines.server.skippedOne": "810d0808a5d18387746ab48b22609928a22a23b24e61683a6134003256f2da67",
"routines.server.skippedMany": "90adef9a8d06fb810a7de6a9f0c72047638bd816866717f0d37192b1caa76f64",
+ "routines.server.startSkippedOne": "19921d7e7115d8593116aa0d3c89dd5dde8deb332f957a508baa453058ae2b65",
+ "routines.server.startSkippedMany": "a3ae1c3fa7c3265b5a652d27a4c5ca62033e545832e222b18aeda478fe263346",
"routines.server.part.stillWaiting": "bbe0bd65555f33dad78b594155eba6012ec8675d62911c0e1df75554de05d0c8",
"routines.server.part.stillRunning": "cd6a3743e230f16c3d418e8dc5979a549b9c172ee0a959cb7d114723d0291db0",
"routines.server.part.notStarted": "f9dca9af97df19cd027e3c0b452cc7ec520c886f489275601d05193d32df0207",
"routines.server.part.computerNoStart": "1e1166d01f459bda1f8f5d5f47a750770f92da7874a0d56a5ac94edf7a3de7cd",
+ "routines.server.part.runsFailed": "64be354b5bdbc2367a7066d43fba4b48182d36f0f8e6bd2bfb0a5b280d9ff1d3",
+ "routines.server.part.restartedSoon": "c844f459112ecab7ff40c3776674f4a380408bb4f524f7b5a81be2fa61c9f3d8",
"server.routines.turnedBackOn": "e091ee76b804f84c0ac8a9b0f40adefd1661708a4b933be334c4a398f6917b6d",
"server.routines.turnedBackOnMany": "b9b1f8055114f9a1b59fc53167a4d2d3be904e945cbe33f829142a8195a1ec4f",
"routines.server.missedOne": "53921b4529c366da5012a02c6a6eb73db3a4f6608811b7538681e5c81c5a1a96",