Skip to content

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

When a customer leaves: routines pause, the trial credit takes no bots after a sign-out, a failed tool call is named

milind-soni2b663335f70c
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.md
index 1faa3b66ee..435160783b 100644
--- a/docs/cloud-pro.md
+++ b/docs/cloud-pro.md
@@ -1363,8 +1363,8 @@ credit, the Admin also sets:
A bot runs on the credit's default model unless the person picks another;
when the relay's default changes (Haiku to Sonnet), bots still on the old
default follow it.
-- **Every bot runs.** While nothing of the person's own is signed in, a bot on
- an engine My Cloud can't run (a desktop copy's own Claude or Codex, signed
+- **Every bot runs.** While nothing of the person's own has ever been signed in
+ here, a bot on an engine My Cloud can't run (a desktop copy's own Claude or Codex, signed
out here, or an engine only that desktop has) moves onto the credit when the
engines are read: at start, when the credit's list arrives, when the app
reads the engines, and before a message to that bot is sent. Where it came
@@ -1376,7 +1376,13 @@ credit, the Admin also sets:
each bot and conversation still on the credit moves to it, with one line in
each, and the credit is not offered to bots any more. A bot that came from
another engine goes back to that engine and model when it is the one signed
- in; otherwise it takes the new-bot default among the person's own.
+ in; otherwise it takes the new-bot default among the person's own. From then
+ on the credit takes no bot by itself: signing out of the last engine (or a
+ sign-in that lapsed) leaves every bot where it is, so a message to one says
+ to sign in again and routines wait
+ ([Routines wait while the owner has left](#routines-wait-while-the-owner-has-left)).
+ A bot can still be put on the credit by hand. That an engine of the person's
+ own was signed in is kept in `providers/trial-credit/own.json`.
- **Checked once connected.** Right after an engine is connected in the
welcome's **Connect your AI** step or the engine sign-in, the app sends it
one tiny real message (`POST /api/instances/:id/check`) and says
@@ -1535,7 +1541,7 @@ place's state (`shared/place-view.ts`); a cause the server words itself
`approval_undelivered`, `event_log`); the trial credit's refusal
(`trial_used_up`, …); the turn's stop reason when it says more than "failed"
(`auth_required`, `shutdown_timeout`, `provider_safety`, `update_required`,
-`spawn_error`, `quota`); the cause's class (`server/drivers/retry.ts`:
+`spawn_error`, `quota`, `tool_error`: a tool call that failed or wasn't allowed); the cause's class (`server/drivers/retry.ts`:
`auth`, `quota`, `rate_limited`, …); the generic stop reason (`rpc_error`);
else `unknown`. A turn that ends in `shutdown_timeout`, `auth_required`,
`update_required`, `spawn_error` or `rpc_error` without a failed row of its own
@@ -1638,6 +1644,38 @@ request after a stop is answered late rather than refused; Caddy dials the
server again every 50 ms, so a held request reaches it within 50 ms of its
listening. The Admin sets it only for a plan that sleeps.
+## Routines wait while the owner has left
+
+A Cloud home pauses its routines by itself when its owner has left
+(`server/host/routine-holds-host.ts`, `server/routine-holds.ts`), so nothing
+runs on an AI or a plan nobody uses any more, fails, and messages a person who
+left:
+
+- **No AI of theirs.** The person had an AI of their own signed in here, and
+ none of theirs can run now (signed out in Settings, a key removed, a sign-in
+ that lapsed). An engine whose sign-in can't be read yet counts as one that
+ might.
+- **Every connection removed.** The owner removed their last MCP server or
+ connected app and none is left. An app list that can't be read changes
+ nothing. Adding or connecting one, or one found connected again (read at
+ most every 15 minutes while none was), ends it.
+- **The plan was cancelled**, as the Admin says with the signed request below.
+
+A cause that begins turns every routine that is on off, stamped with it
+(`heldFor`, shown under the routine as "Paused because …"), cancels their
+queued runs, and writes one quiet line in the owner's Chief's chat; nothing
+else is sent. Once no cause holds a routine it turns back on from now, without
+the runs it skipped (a one-time run whose time passed stays over). Turning a
+routine on or off by hand clears its stamp, so the person's choice wins. What
+was last read is kept in `routine-holds.json` and the causes holding routines
+in `routines.json` (`holds`), so a restart neither pauses nor frees anything
+before the engines are read again.
+
+**`POST /api/cloud/plan`**, signed over its JSON body like the sleep request:
+`{"v":1,"cancelled":true}` when the customer cancels, `{"v":1,"cancelled":false}`
+when renewal is back on. `200 {"ok":true}`; `400 {"error":"invalid_plan"}`
+without a boolean `cancelled`. The Admin does not send it yet.
+
## What the desktop reads from the Admin
The desktop polls `GET /api/cloud/desktop/session` with its personal device
diff --git a/server/cloud-credit-moves.test.ts b/server/cloud-credit-moves.test.ts
index 437ce3df38..cc61aed945 100644
--- a/server/cloud-credit-moves.test.ts
+++ b/server/cloud-credit-moves.test.ts
@@ -116,6 +116,31 @@ describe("which engine a Cloud home's bots run on while it has the trial credit"
expect(moved()).toEqual({});
});
+ it("once the person had an AI of their own here, signing out of it leaves every bot where it is: the credit takes none, and they are away", () => {
+ const moves = make();
+ moves.settle([credit(), claude(false), codex(false)]);
+ moves.settle([credit(), claude(true), codex(false)]);
+ expect(bots.filter((entry) => entry.id !== "unset").map((entry) => entry.modelSelection.instanceId)).toEqual(["claude", "claude", "claude", "claude"]);
+ expect(moves.away([credit(), claude(true), codex(false)])).toBe(false);
+ // Signed out of Claude, read again after a restart too: nothing moves onto the credit.
+ const later = make();
+ later.settle([credit(), claude(false), codex(false)]);
+ expect(find("copied").modelSelection).toEqual({ instanceId: "claude", model: "claude-opus-4-8" });
+ expect(find("seeded").modelSelection.instanceId).toBe("claude");
+ expect(later.due(find("copied"), "copied-main", [credit(), claude(false), codex(false)])).toBe(false);
+ expect(later.away([credit(), claude(false), codex(false)])).toBe(true);
+ // A sign-in that can't be read yet might be back, and a credit-only engine is never the person's own.
+ expect(later.away([credit(), claude(undefined), codex(false)])).toBe(false);
+ });
+
+ it("someone who never had an AI of their own here is never away, and a send that only reads the engines remembers no sign-in", () => {
+ const moves = make();
+ expect(moves.due(find("seeded"), "seeded-main", [credit(), claude(true), codex(false)])).toBe(true);
+ expect(moves.away([credit(), claude(false), codex(false)])).toBe(false);
+ moves.settle([credit(), claude(false), codex(false)]);
+ expect(find("copied").modelSelection).toEqual({ instanceId: CREDIT, model: "claude-sonnet-5" });
+ });
+
it("an engine whose sign-in can't be read never takes the bots off the credit", () => {
make().settle([credit(), claude(undefined), codex(false)]);
expect(find("seeded").modelSelection.instanceId).toBe(CREDIT);
diff --git a/server/cloud-credit-moves.ts b/server/cloud-credit-moves.ts
index 4ed4e046e9..1fc9d8c7cd 100644
--- a/server/cloud-credit-moves.ts
+++ b/server/cloud-credit-moves.ts
@@ -1,8 +1,10 @@
-// Which engine each bot runs on, on a Cloud home with the trial's Claude credit. While nothing of the person's own is
-// signed in there, a bot on an engine that can't run (a copied bot's desktop engine, signed out here) runs on the credit,
-// and where it came from is remembered under providers/, which never travels in a backup or a move. Once an engine of
-// the person's own is signed in, every bot on the credit moves to it: back to the engine and model it came from when that
-// one can run, otherwise to the new-bot default among the person's own engines.
+// Which engine each bot runs on, on a Cloud home with the trial's Claude credit. While nothing of the person's own has
+// ever been signed in there, a bot on an engine that can't run (a copied bot's desktop engine, signed out here) runs on
+// the credit, and where it came from is remembered under providers/, which never travels in a backup or a move. Once an
+// engine of the person's own is signed in, every bot on the credit moves to it: back to the engine and model it came from
+// when that one can run, otherwise to the new-bot default among the person's own engines. From then on the credit takes
+// no bot by itself: when the person signs out of their last engine (or its sign-in lapses) the bots stay where they are,
+// a message to one says to sign in again, and routines wait (host/routine-holds-host.ts) instead of spending the credit.
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { writeFileAtomic } from "./atomic.ts";
@@ -38,6 +40,24 @@ export function createCreditMoves(options: CreditMovesOptions) {
const { credit, store, context } = options;
const file = () => join(credit.storage(), "moved.json");
const onCredit = (chosen?: ModelSelection) => Boolean(chosen && credit.owns(chosen.instanceId));
+ let hadOwn: boolean | undefined;
+
+ /** Whether an engine of the person's own was ever signed in here: kept beside moved.json once it was. */
+ function everOwn(): boolean {
+ if (hadOwn === undefined) {
+ try { readFileSync(join(credit.storage(), "own.json")); hadOwn = true; } catch { hadOwn = false; }
+ }
+ return hadOwn;
+ }
+ function sawOwn(): void {
+ if (everOwn()) return;
+ hadOwn = true;
+ try {
+ writeFileAtomic(join(credit.storage(), "own.json"), JSON.stringify({ at: Date.now() }), { mode: 0o600 });
+ } catch (error) {
+ options.log?.(`[trial credit] could not remember that the person's own AI was signed in (${error instanceof Error ? error.name : "error"})`);
+ }
+ }
function origins(): Map<string, ModelSelection> {
try {
@@ -60,11 +80,15 @@ export function createCreditMoves(options: CreditMovesOptions) {
const signedIn = (instances: readonly SelectableInstance[]) => instances.filter(instance =>
!context.company?.(instance.instanceId) && readyToRun(instance, context) && instance.snapshot.authenticated === true);
- function plan(instances: readonly SelectableInstance[]): Plan {
+ /** `settling`: what this reads is acted on, so a sign-in it finds is remembered. */
+ function plan(instances: readonly SelectableInstance[], settling = false): Plan {
const own = signedIn(instances);
- if (own.length) return { kind: "off", own };
+ if (own.length) {
+ if (settling) sawOwn();
+ return { kind: "off", own };
+ }
const engine = instances.find(instance => credit.owns(instance.instanceId));
- if (!engine || credit.status() !== "active" || !readyToRun(engine, context) || !engine.models.default) return null;
+ if (everOwn() || !engine || credit.status() !== "active" || !readyToRun(engine, context) || !engine.models.default) return null;
return { kind: "onto", target: { instanceId: engine.instanceId, model: engine.models.default } };
}
@@ -122,7 +146,7 @@ export function createCreditMoves(options: CreditMovesOptions) {
return {
/** Moves the bots onto the credit, or off it, as the engines read now say. */
settle(instances: readonly SelectableInstance[]): void {
- const next = plan(instances);
+ const next = plan(instances, true);
if (next?.kind === "onto") onto(next.target, instances);
else if (next?.kind === "off") off(next.own);
},
@@ -133,6 +157,11 @@ export function createCreditMoves(options: CreditMovesOptions) {
if (next?.kind === "onto") return stranded(bot.modelSelection, instances) || stranded(chosen, instances);
return next?.kind === "off" && onCredit(chosen);
},
+ /** The person had an AI of their own here and none of theirs can run now, for sure (one whose sign-in can't be read
+ * yet might): the credit takes none of their bots, so their routines wait. */
+ away(instances: readonly SelectableInstance[]): boolean {
+ return everOwn() && !instances.some(instance => !context.company?.(instance.instanceId) && readyToRun(instance, context));
+ },
/** The credit's default model changed (the Admin's list): bots and defaults on the old default follow it. */
followDefault(from: string, to: string): void {
const was = (chosen?: ModelSelection) => onCredit(chosen) && chosen!.model === from;
diff --git a/server/cloud-credit.e2e.test.ts b/server/cloud-credit.e2e.test.ts
index 8db3bbbd37..11742c31cb 100644
--- a/server/cloud-credit.e2e.test.ts
+++ b/server/cloud-credit.e2e.test.ts
@@ -120,10 +120,23 @@ beforeAll(async () => {
// environment; the credit's engine never runs it.
const cli = join(home, "fixture-claude.mjs");
writeFileSync(cli, `#!/usr/bin/env node
-import { existsSync } from "node:fs";
+import { existsSync, rmSync } from "node:fs";
import { join } from "node:path";
const home = ${JSON.stringify(home)};
+// Signing out in Settings runs \`claude auth logout\`.
+if (process.argv[2] === "auth" && process.argv[3] === "logout") {
+ rmSync(join(home, "signed-in"), { force: true });
+ process.stdout.write("Successfully logged out from your Anthropic account.\\n", () => process.exit(0));
+ await new Promise(() => {});
+}
+// Signed out, \`auth status\` exits 1, as Claude Code's does; a key leaked into its environment would still sign it in.
+if (process.argv[2] === "auth" && process.argv[3] === "status" && !existsSync(join(home, "signed-in")) && !process.env.ANTHROPIC_API_KEY) {
+ process.stdout.write(JSON.stringify({ loggedIn: false, authMethod: "none", apiProvider: "firstParty" }) + "\\n", () => process.exit(1));
+ await new Promise(() => {});
+}
process.env.FAKE_CLAUDE_AUTH = existsSync(join(home, "signed-in")) ? "in" : "inherited-api-key";
+// Signed out, a turn fails the way Claude Code's does.
+if (!existsSync(join(home, "signed-in"))) process.env.FAKE_CLAUDE_MODE = "not-logged-in";
// Signed out, a one-shot call answers as the CLI does: the sign-in line, and a failure.
const format = process.argv[process.argv.indexOf("--output-format") + 1];
if (!existsSync(join(home, "signed-in")) && process.argv.includes("-p") && (format === "text" || format === "json")) {
@@ -274,19 +287,46 @@ describe("the free trial's Claude credit on a Cloud home", { timeout: 90_000 },
expect((await named("From the desktop")).messages.filter((message) => message.tool?.name.startsWith("notice: Claude is connected"))).toHaveLength(1);
});
- it("signed out again, a bot's next message runs on the credit; used up, that chat says so once in plain words, and nothing more is sent", async () => {
- rmSync(join(home, "signed-in"), { force: true });
+ it("signed out on purpose, every bot stays on the person's own Claude: the credit takes none, a message says to sign in, and the routine waits quietly", async () => {
+ const copied = await named("From the desktop");
+ const created = await api("POST", "/api/routines", { body: { name: "Morning export", prompt: "Export the numbers.", botId: copied.id,
+ schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_600_000 } } });
+ expect(created.status, created.text).toBe(201);
rmSync(join(home, "own-turn.json"), { force: true });
- expect((await api("POST", "/api/instances/claude/check", { body: {} })).body)
- .toEqual({ ok: false, error: "Claude isn't signed in on this computer anymore. Sign in again, then check again." });
- await expect.poll(async () => (await credit())?.snapshot.state, { timeout: 15_000 }).toBe("available");
+ // Signing out in Settings is the whole request: nothing moves onto the credit in it, or after.
+ const signedOut = await api("POST", "/api/instances/claude/auth/sign-out", { body: {} });
+ expect(signedOut.status, signedOut.text).toBe(200);
+ expect((signedOut.body.instances as Instance[]).find((instance) => instance.instanceId === "claude")?.snapshot.authenticated).toBe(false);
+ expect((await credit())?.snapshot.state).toBe("available");
+ for (const bot of await bots()) expect(bot.modelSelection.instanceId).toBe("claude");
+ // The routine is off and says why; the person's Chief has one quiet line about it, and nothing else is sent.
+ const routines = (await api("GET", "/api/routines")).body.routines as Array<{ id: string; enabled: boolean; heldFor?: string }>;
+ expect(routines.find((routine) => routine.id === created.body.routine.id)).toMatchObject({ enabled: false, heldFor: "no_engine" });
+ const paused = (await bots()).flatMap((bot) => bot.messages).filter((message) => message.tool?.name.startsWith("notice: Your routines are paused"));
+ expect(paused).toHaveLength(1);
+ const sent = completions().length;
+ const failed = await turn("still there?", copied);
+ expect(answered(failed)).toBe(false);
+ expect(failed.modelSelection.instanceId).toBe("claude");
+ expect(completions()).toHaveLength(sent);
+ expect(moved()).toEqual({});
+ });
+
+ it("picked by hand, the credit still answers; used up, that chat says so once in plain words, and nothing more is sent", async () => {
const copied = await named("From the desktop");
- expect(answered(await turn("back on the credit?", copied))).toBe(true);
+ const others = (await bots()).filter((bot) => bot.id !== copied.id);
+ for (const bot of [copied, others[0]!]) {
+ const picked = await api("PATCH", `/api/bots/${bot.id}`, { body: { modelSelection: SONNET } });
+ expect(picked.status, picked.text).toBe(200);
+ }
+ expect(answered(await turn("on the credit now?", copied))).toBe(true);
expect((await named("From the desktop")).modelSelection).toEqual(SONNET);
- expect(() => readFileSync(join(home, "own-turn.json"), "utf8")).toThrow();
+ expect(completions().at(-1)!.model).toBe("claude-sonnet-5");
+ // Claude Code never ran this turn (bots still on the signed-out Claude may start their own work meanwhile).
+ expect((() => { try { return readFileSync(join(home, "own-turn.json"), "utf8"); } catch { return ""; } })()).not.toContain("on the credit now?");
usedUp = true;
const failed = await turn("one more", copied);
- const refusals = failed.messages.filter((message) => message.tool?.name.startsWith("error:"));
+ const refusals = failed.messages.slice(failed.messages.findLastIndex((message) => message.role === "user")).filter((message) => message.tool?.name.startsWith("error:"));
expect(refusals).toHaveLength(1);
expect(refusals[0]!.tool).toMatchObject({ name: `error: ${TRIAL_CREDIT_REFUSED.used_up}`, setup: true });
const transcript = (await api("GET", "/api/bots?messages=50")).text;
diff --git a/server/cloud-health.test.ts b/server/cloud-health.test.ts
index 9886e05bdc..9ec83addb2 100644
--- a/server/cloud-health.test.ts
+++ b/server/cloud-health.test.ts
@@ -12,6 +12,7 @@ import { CLOUD_HEALTH_MAX_BYTES, HEALTH_BUCKET_CAP, createCloudHealth, createClo
import { DATA_DIR, EVENTS_DIR } from "./config.ts";
import { memoryStallText, memoryStopText } from "./engine-memory.ts";
import type { RuntimeEvent } from "./contracts.ts";
+import { toolFailureMessage } from "./drivers/tool-failure.ts";
import { createCloudSignedRoutes } from "./routes/cloud-signed.ts";
import { SessionRegistry } from "./sessions.ts";
import { Store } from "./store.ts";
@@ -101,6 +102,14 @@ describe("the failure code a Cloud home reports", () => {
]);
});
+ it("files a turn a failed tool call stopped under tool_error, not unknown", () => {
+ const w = world();
+ w.emit(w.bot.threadId, { type: "turn.started" }, "openai-compat");
+ w.fail(toolFailureMessage(["composio_CLARITY_GET_INSIGHTS"], []));
+ w.emit(w.bot.threadId, { type: "turn.completed", ok: false, stopReason: "tool_error" }, "openai-compat");
+ expect(incidents(w)).toEqual([{ kind: "turn", code: "tool_error", engine: "openai-compat", count: 1 }]);
+ });
+
it("files a row whose turn never reports a stop under its own class once it has waited", () => {
const w = world();
w.emit(w.bot.threadId, { type: "turn.started" });
diff --git a/server/cloud-health.ts b/server/cloud-health.ts
index f6d38128a2..0a8884c5ad 100644
--- a/server/cloud-health.ts
+++ b/server/cloud-health.ts
@@ -35,7 +35,7 @@ const match = (pattern: RegExp, value: unknown): string | null => typeof value =
/** Stop reasons a driver settles a failed turn with. Free text never becomes a code. */
const STOP_CODES = new Set(["auth_required", "rpc_error", "shutdown_timeout", "provider_safety", "update_required", "spawn_error", "quota",
- "exit_before_result", "error_during_execution", "error", "failed"]);
+ "tool_error", "exit_before_result", "error_during_execution", "error", "failed"]);
/** Stops that say only that something failed: the cause's own class, when known, says more. */
const GENERIC_STOPS = new Set(["rpc_error", "error", "failed", "error_during_execution", "exit_before_result"]);
/** Engine stops that count as a failure even when no failed row was written for them. */
diff --git a/server/drivers/agents-bridge-chat.test.ts b/server/drivers/agents-bridge-chat.test.ts
index 11aa364e48..2c206163ec 100644
--- a/server/drivers/agents-bridge-chat.test.ts
+++ b/server/drivers/agents-bridge-chat.test.ts
@@ -100,5 +100,5 @@ it("a bridged turn on the chat-completions runtime carries on after use_tool nam
const errors = recorder.events.flatMap((event) => event.type === "runtime.error" ? [event.message] : []);
expect(errors.join("\n")).not.toMatch(/MCP request failed|MCP session closed|execution outcome may be uncertain/);
expect(completed).toMatchObject({ ok: false });
- expect(errors).toEqual([expect.stringContaining("One or more tool operations failed or were denied")]);
+ expect(errors).toEqual([expect.stringMatching(/^Stopped because the tool call “[^”]+” failed\./)]);
}, 30_000);
diff --git a/server/drivers/openai-chat.test.ts b/server/drivers/openai-chat.test.ts
index cab835adcc..784e36bc52 100644
--- a/server/drivers/openai-chat.test.ts
+++ b/server/drivers/openai-chat.test.ts
@@ -11,6 +11,8 @@ import { GrokDriver } from "./grok.ts";
import { MinimaxDriver } from "./minimax.ts";
import { OpenAICompatDriver } from "./openai-compat.ts";
import { MistralDriver } from "./mistral.ts";
+import { startFakeHttpMcp } from "../testing/fake-http-mcp-server.ts";
+import { whopLikeCatalog } from "../testing/whop-like-catalog.ts";
afterEach(() => vi.unstubAllGlobals());
@@ -316,13 +318,49 @@ describe("createOpenAIChatRuntime tool approvals", () => {
const completed = events.find((event) => event.type === "turn.completed") as any;
expect(completed.ok).toBe(false);
expect(completed.stopReason).toBe("tool_error");
- expect(events.some((event) => event.type === "runtime.error" && /One or more tool operations failed/.test((event as any).message ?? ""))).toBe(true);
+ // It says which call failed, so a routine's log and the person read the cause.
+ expect(events.filter((event) => event.type === "runtime.error").map((event) => (event as any).message))
+ .toEqual(["Stopped because the tool call “fx_write” failed. The bot's reply isn't proof the work was done; the failed step shows the error."]);
expect(events.some((event) => event.type === "cap.exhausted")).toBe(false);
} finally {
await instance.dispose();
}
}, 20_000);
+ it("names a searched server's tool that failed by its own name, not the call that reached it", async () => {
+ const remote = await startFakeHttpMcp({ tools: whopLikeCatalog(300), callResult: () => ({ isError: true, content: [{ type: "text", text: "boom" }] }) });
+ const call = { name: "payments_list", arguments: { company_id: "biz_1" } };
+ const callBody = `data: ${JSON.stringify({ choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: "c1", type: "function", function: { name: "whop_call_tool", arguments: JSON.stringify(call) } }] } }] })}\n\n`
+ + 'data: {"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}\n\n';
+ const finalBody = 'data: {"choices":[{"index":0,"delta":{"content":"Listed the payments."}}]}\n\n'
+ + 'data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\n';
+ let sent = 0;
+ vi.stubGlobal("fetch", vi.fn(async (input: unknown) => {
+ if (!String(input).endsWith("/chat/completions")) return new Response(JSON.stringify({ data: [] }));
+ return new Response(++sent === 1 ? callBody : finalBody, { headers: { "content-type": "text/event-stream" } });
+ }));
+ const instance = await OpenAICompatDriver.create({
+ instanceId: "searched", displayName: "Synthetic", enabled: true,
+ config: OpenAICompatDriver.decodeConfig({ url: "https://api.example.test/v1", apiKeyEnv: "K", model: "fixture" }),
+ environment: { K: "synthetic" },
+ });
+ const events: RuntimeEvent[] = [];
+ instance.adapter.onEvent((event) => events.push(event));
+ try {
+ await instance.adapter.sendTurn({
+ threadId: "searched", text: "List the payments.", approvalMode: "full",
+ integrations: { custom: { whop: { type: "http", url: remote.url, headers: {} } } },
+ });
+ await vi.waitFor(() => expect(events.some((event) => event.type === "turn.completed")).toBe(true), { timeout: 15_000 });
+ expect(remote.calls).toEqual([call]);
+ expect(events.filter((event) => event.type === "runtime.error").map((event) => (event as any).message))
+ .toEqual(["Stopped because the tool call “whop_payments_list” failed. The bot's reply isn't proof the work was done; the failed step shows the error."]);
+ } finally {
+ await instance.dispose();
+ await remote.close();
+ }
+ }, 30_000);
+
describe("corrective rounds", () => {
const toolCall = (id: string, name: string, args: unknown = {}) =>
`data: ${JSON.stringify({ choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id, type: "function", function: { name, arguments: JSON.stringify(args) } }] } }] })}\n\n`
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index bba4f32511..5ba170bb3d 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -20,7 +20,7 @@ import { createChatToolApproval, refusal } from "./chat-tool-approval.ts";
import { ChatProtocolError, ChatReasoningDetails, ChatToolCalls, object, type ChatToolCall } from "./openai-chat-protocol.ts";
import { appendNative } from "./native.ts";
import { classifyError, computeBackoff, interruptibleDelay, RETRY_MAX_ATTEMPTS } from "./retry.ts";
-import { plainFailureMessage } from "./engine-errors.ts";
+import { plainFailureMessage } from "./engine-errors.ts"; import { toolFailureMessage } from "./tool-failure.ts";
import { refusesRequestSize, RequestTooLargeError, sizeChange, smallerResend } from "./chat-size-limit.ts";
import { requestTooLargeMessage } from "../../shared/request-too-large.ts";
import { toolSchemaProfileFor } from "../tool-schema-profile.ts";
@@ -633,7 +633,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
let failure: string | undefined;
let toolFailed = false;
let correctiveRounds = 0;
- const denials: string[] = [];
+ const denials: string[] = [], failedCalls: string[] = [];
const seenCalls = new Set<string>();
let nudges = 0;
let unread: string[] = [];
@@ -766,7 +766,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
continue;
}
stopReason = "tool_error";
- throw new ChatProtocolError("One or more tool operations failed or were denied. See the tool results; the final response is not an execution receipt.");
+ throw new ChatProtocolError(toolFailureMessage(failedCalls, denials.filter((name) => name !== ASK_USER_TOOL)));
}
if (options.nudgeAnnouncedAction && tools.definitions.length && announcesAction(completion.text)) {
if (nudges >= MAX_ANNOUNCEMENT_NUDGES || turnEntry.ending) {
@@ -798,13 +798,13 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
if (seenCalls.size > MAX_TURN_TOOL_CALLS) throw new ChatProtocolError(stoppedAfter(`${MAX_TURN_TOOL_CALLS} tool calls`));
messages.push({ ...assistantReply(model, completion, completion.text || null), tool_calls: completion.toolCalls });
// After a corrective round, the failure stays pending only until the bot runs tools again.
- if (correctiveRounds && !denials.length) toolFailed = false;
+ if (correctiveRounds && !denials.length) { toolFailed = false; failedCalls.length = 0; }
const screenshotParts: ChatContentPart[] = [];
for (const call of completion.toolCalls) {
abort.signal.throwIfAborted();
let result: ChatToolResult;
let started = false;
- let fatal: Error | undefined;
+ let fatal: Error | undefined, title = call.function.name;
try {
let args: unknown;
try { args = JSON.parse(call.function.arguments); }
@@ -834,7 +834,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
}
} else {
tools.validate(call.function.name, args);
- const shown = tools.view(call.function.name, args as Record<string, unknown>);
+ const shown = tools.view(call.function.name, args as Record<string, unknown>); title = shown.title;
const shownPreview = shown.input === args ? inputPreview : preview(shown.input);
// This runtime has no provider reviewer, so Full access is honoured here.
const full = (turn.approvalModeNow?.() ?? turn.approvalMode) === "full";
@@ -875,7 +875,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const text = safeText(result.text);
const output = preview({ ok: result.ok, result: text });
emit({ ...base(turn.threadId, turnId), type: "item.completed", itemType: "tool", itemId: call.id, ok: result.ok, output });
- if (!result.ok) toolFailed = true;
+ if (!result.ok) { toolFailed = true; failedCalls.push(title); }
messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify({ ok: result.ok, result: text }) });
screenshotParts.push(...chatToolImages(call.id, result.images));
abort.signal.throwIfAborted();
diff --git a/server/drivers/tool-failure.test.ts b/server/drivers/tool-failure.test.ts
new file mode 100644
index 0000000000..7bb22ff023
--- /dev/null
+++ b/server/drivers/tool-failure.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "vitest";
+
+import { classifyContinuable } from "../turn-continuation.ts";
+import { toolFailureMessage } from "./tool-failure.ts";
+
+const AFTER_FAILURE = "The bot's reply isn't proof the work was done; the failed step shows the error.";
+
+describe("why a chat turn stopped on a tool call", () => {
+ it("names the call that failed", () => {
+ expect(toolFailureMessage(["composio_CLARITY_GET_INSIGHTS"], [])).toBe(`Stopped because the tool call “composio_CLARITY_GET_INSIGHTS” failed. ${AFTER_FAILURE}`);
+ });
+
+ it("tells a call that wasn't allowed apart from one that failed", () => {
+ expect(toolFailureMessage(["gmail_send"], ["gmail_send"]))
+ .toBe("Stopped because the tool call “gmail_send” wasn't allowed. The bot's reply isn't proof the work was done; that step didn't run.");
+ expect(toolFailureMessage(["gmail_send", "notion_search"], ["gmail_send"]))
+ .toBe(`Stopped because the tool call “notion_search” failed and “gmail_send” wasn't allowed. ${AFTER_FAILURE}`);
+ });
+
+ it("names each call once and at most three", () => {
+ expect(toolFailureMessage(["a", "b", "a"], [])).toBe(`Stopped because the tool calls “a” and “b” failed. ${AFTER_FAILURE}`);
+ expect(toolFailureMessage(["a", "b", "c", "d", "e"], [])).toBe(`Stopped because the tool calls “a”, “b”, “c” and 2 more failed. ${AFTER_FAILURE}`);
+ expect(toolFailureMessage(["x".repeat(200)], [])).toContain(`“${"x".repeat(79)}…”`);
+ });
+
+ it("is never read as a spent turn budget, which would continue the run by itself", () => {
+ expect(classifyContinuable("tool_error", toolFailureMessage(["stopped after 3 steps"], []))).toBeNull();
+ });
+});
diff --git a/server/drivers/tool-failure.ts b/server/drivers/tool-failure.ts
new file mode 100644
index 0000000000..bb89911fce
--- /dev/null
+++ b/server/drivers/tool-failure.ts
@@ -0,0 +1,28 @@
+// Why a chat-engine turn (openai-chat.ts) stopped on a tool call that failed or was not allowed: which calls, so the
+// person, a routine's run log and a Chief read the cause. The calls' own output stays in their steps: a tool's error text
+// ("403", "quota exceeded") must not read as the engine's own sign-in or usage limit to the failure classifiers.
+const SHOWN = 3;
+const NAME_CHARS = 80;
+
+const quoted = (name: string) => `“${name.length > NAME_CHARS ? `${name.slice(0, NAME_CHARS - 1)}…` : name}”`;
+
+function list(names: readonly string[]): string {
+ const shown = names.slice(0, SHOWN).map(quoted);
+ const more = names.length - shown.length;
+ if (more > 0) return `${shown.join(", ")} and ${more} more`;
+ return shown.length > 1 ? `${shown.slice(0, -1).join(", ")} and ${shown.at(-1)}` : shown[0] ?? "";
+}
+
+/** `failed`: the calls whose result was a failure, in order, refused ones included; `refused`: the ones not allowed. */
+export function toolFailureMessage(failed: readonly string[], refused: readonly string[]): string {
+ const notAllowed = [...new Set(refused)];
+ const broke = [...new Set(failed)].filter((name) => !notAllowed.includes(name));
+ const calls = (names: readonly string[]) => `${names.length === 1 ? "the tool call" : "the tool calls"} ${list(names)}`;
+ const wasnt = notAllowed.length === 1 ? "wasn't allowed" : "weren't allowed";
+ const why = broke.length && notAllowed.length ? `${calls(broke)} failed and ${list(notAllowed)} ${wasnt}`
+ : broke.length ? `${calls(broke)} failed`
+ : notAllowed.length ? `${calls(notAllowed)} ${wasnt}`
+ : "a tool call failed";
+ const after = broke.length || !notAllowed.length ? "the failed step shows the error" : "that step didn't run";
+ return `Stopped because ${why}. The bot's reply isn't proof the work was done; ${after}.`;
+}
diff --git a/server/host/cloud-signed-host.ts b/server/host/cloud-signed-host.ts
index 001e5e9d29..4c799ebae8 100644
--- a/server/host/cloud-signed-host.ts
+++ b/server/host/cloud-signed-host.ts
@@ -20,6 +20,8 @@ export interface CloudSignedHostDeps {
teamAdmin?: { summary(): Promise<TeamAdminSummary> };
/** A Team Cloud's member left (the Admin's signed request): delete what was theirs alone. */
memberLeft?: (email: string) => Promise<Record<string, unknown>>;
+ /** The plan was cancelled, or renews again (the Admin's signed request): routines wait while it is cancelled. */
+ plan?: (cancelled: boolean) => void;
}
export function createCloudSignedHost(deps: CloudSignedHostDeps): { cloudHealth: CloudHealth | null; cloudSigned: ReturnType<typeof createCloudSignedRoutes> | null } {
@@ -27,7 +29,7 @@ export function createCloudSignedHost(deps: CloudSignedHostDeps): { cloudHealth:
const cloudSigned = deps.cloudHome && cloudHealth
? createCloudSignedRoutes({ secret: deps.cloudHome.bootstrapSecret, sessions: deps.sessions, team: deps.cloudHome.team, health: cloudHealth, power: deps.power, box: deps.box,
...(deps.cloudHome.team && deps.teamAdmin ? { teamAdmin: deps.teamAdmin } : {}),
- ...(deps.cloudHome.team && deps.memberLeft ? { memberLeft: deps.memberLeft } : {}) })
+ ...(deps.cloudHome.team && deps.memberLeft ? { memberLeft: deps.memberLeft } : {}), ...(deps.plan ? { plan: deps.plan } : {}) })
: null;
return { cloudHealth, cloudSigned };
}
diff --git a/server/host/routine-holds-host.test.ts b/server/host/routine-holds-host.test.ts
new file mode 100644
index 0000000000..0182280158
--- /dev/null
+++ b/server/host/routine-holds-host.test.ts
@@ -0,0 +1,123 @@
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { RoutineManager } from "../routines.ts";
+import { createRoutineHoldsHost, ROUTINE_HOLD_LINES } from "./routine-holds-host.ts";
+
+const dirs: string[] = [];
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+
+const START = Date.parse("2026-10-30T06:00:00Z");
+const HOUR = 60 * 60_000;
+type Line = { threadId: string; name: string };
+
+/** A Cloud home's routines and bots: the owner's Chief, a teammate's later one, and a bot that is no Chief. */
+function world(dataDir?: string) {
+ const dir = dataDir ?? mkdtempSync(join(tmpdir(), "omb-routine-holds-host-"));
+ if (!dataDir) dirs.push(dir);
+ let now = START;
+ let mcp = 0;
+ let apps: boolean | null = true;
+ const lines: Line[] = [];
+ const routines = new RoutineManager({ file: join(dir, "routines.json"), now: () => now, botState: () => "ready", createTask: () => ({ threadId: "run" }), startTurn: async () => {} });
+ const bots = [
+ { id: "ops", name: "Ops", threadId: "ops-main", createdAt: 1 },
+ { id: "chief-2", name: "Second", threadId: "chief-2-main", createdAt: 3, chiefOfStaff: true },
+ { id: "chief", name: "MausBot", threadId: "chief-main", createdAt: 2, chiefOfStaff: true, defaultBot: {} },
+ ];
+ const host = createRoutineHoldsHost({
+ dataDir: dir, now: () => now,
+ store: { bots, appendMessage: (threadId: string, message: { tool?: { name: string } }) => { lines.push({ threadId, name: message.tool!.name }); return {}; } } as never,
+ mcpServers: () => mcp, appsConnected: async () => apps,
+ });
+ const routine = routines.create({ name: "Clarity export", prompt: "Export Clarity", botId: "ops", schedule: { type: "interval", everyMinutes: 60, anchorAt: START + HOUR } });
+ const state = () => routines.listRoutines().find((candidate) => candidate.id === routine.id)!;
+ return {
+ dir, host, routines, lines, state,
+ make: () => host.attach(routines),
+ setMcp: (count: number) => { mcp = count; }, setApps: (value: boolean | null) => { apps = value; },
+ advance: (ms: number) => { now += ms; },
+ };
+}
+
+describe("a Cloud home's routines wait while the owner has left", () => {
+ it("pauses when none of the owner's AI is signed in any more, with one quiet line in the owner's Chief's chat, and comes back on sign-in", () => {
+ const w = world();
+ w.make();
+ w.host.engines(true);
+ expect(w.state()).toMatchObject({ enabled: false, heldFor: "no_engine" });
+ expect(w.lines).toEqual([{ threadId: "chief-main", name: `notice: ${ROUTINE_HOLD_LINES.no_engine}` }]);
+ // Read again and again while signed out: nothing more is said.
+ w.host.engines(true);
+ w.host.engines(true);
+ expect(w.lines).toHaveLength(1);
+ w.host.engines(false);
+ expect(w.state()).toMatchObject({ enabled: true });
+ expect(w.state().heldFor).toBeUndefined();
+ expect(w.lines).toHaveLength(1);
+ });
+
+ it("pauses while the plan is cancelled and keeps that across a restart, before the engines are read again", () => {
+ const w = world();
+ w.make();
+ w.host.engines(false);
+ w.host.plan(true);
+ expect(w.state()).toMatchObject({ enabled: false, heldFor: "plan_cancelled" });
+ expect(w.lines.map((line) => line.name)).toEqual([`notice: ${ROUTINE_HOLD_LINES.plan_cancelled}`]);
+ expect(JSON.parse(readFileSync(join(w.dir, "routine-holds.json"), "utf8"))).toEqual({ planCancelled: true });
+
+ const again = world(w.dir);
+ again.make();
+ again.host.review();
+ expect(again.host.causes()).toEqual(["plan_cancelled"]);
+ expect(again.lines).toEqual([]);
+ again.host.plan(false);
+ expect(again.routines.listRoutines().every((routine) => routine.enabled)).toBe(true);
+ });
+
+ it("remembers what it read before the routines exist and applies it once they do", () => {
+ const w = world();
+ w.host.engines(true);
+ expect(w.state().enabled).toBe(true);
+ w.make();
+ w.host.review();
+ expect(w.state()).toMatchObject({ enabled: false, heldFor: "no_engine" });
+ expect(w.lines).toHaveLength(1);
+ });
+
+ it("pauses once the last connected app or server is removed, never on a guess, and resumes when one is added", async () => {
+ const w = world();
+ w.make();
+ w.setMcp(1);
+ await w.host.connections("removed");
+ expect(w.state().enabled).toBe(true);
+ w.setMcp(0);
+ w.setApps(null);
+ await w.host.connections("removed");
+ expect(w.state().enabled).toBe(true);
+ w.setApps(false);
+ await w.host.connections("removed");
+ expect(w.state()).toMatchObject({ enabled: false, heldFor: "no_connections" });
+ expect(w.lines.map((line) => line.name)).toEqual([`notice: ${ROUTINE_HOLD_LINES.no_connections}`]);
+ await w.host.connections("added");
+ expect(w.state().enabled).toBe(true);
+ });
+
+ it("notices an app connected some other way, reading again at most every 15 minutes while none was left", async () => {
+ const w = world();
+ w.make();
+ w.setApps(false);
+ await w.host.connections("removed");
+ expect(w.state().enabled).toBe(false);
+ w.setApps(true);
+ w.host.review();
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(w.state().enabled).toBe(false);
+ w.advance(15 * 60_000);
+ w.host.review();
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(w.state()).toMatchObject({ enabled: true });
+ });
+});
diff --git a/server/host/routine-holds-host.ts b/server/host/routine-holds-host.ts
new file mode 100644
index 0000000000..f4a4652625
--- /dev/null
+++ b/server/host/routine-holds-host.ts
@@ -0,0 +1,123 @@
+// Why every routine waits now (routine-holds.ts), on a Cloud home, read from three places: whether any AI of the owner's
+// own can still run here (cloud-credit-moves.ts `away`, read with the engines), whether the owner removed every connected
+// app and MCP server (marked when the last one goes, cleared when one comes back), and whether the plan was cancelled (the
+// Admin's signed request, routes/cloud-signed.ts). What was last read is kept in routine-holds.json, so a restart neither
+// frees nor pauses anything before the engines are read again. A cause that begins and pauses routines writes one quiet
+// line in the owner's Chief's chat; nothing else is sent, so nobody who left is messaged.
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import type { RoutineHoldCause } from "../../shared/routines.ts";
+import { writeFileAtomic } from "../atomic.ts";
+import type { RoutineManager } from "../routines.ts";
+import type { Store } from "../store.ts";
+
+/** While every connection is gone, whether one came back elsewhere (an app connected from another device) is read again at
+ * most this often. */
+const RECHECK_MS = 15 * 60_000;
+
+/** The owner's one line when a cause begins and pauses routines. */
+export const ROUTINE_HOLD_LINES: Record<RoutineHoldCause, string> = {
+ plan_cancelled: "Your routines are paused because the plan was cancelled. To keep one running until the plan ends, turn it back on in Routines.",
+ no_engine: "Your routines are paused: none of your AI accounts is signed in here any more. They turn back on by themselves when you sign in again.",
+ no_connections: "Your routines are paused: every connected app and server was removed. They turn back on when you connect one, or turn one back on in Routines.",
+};
+
+interface Saved { away?: true; planCancelled?: true; connectionsGone?: true }
+
+export interface RoutineHoldsHostDeps {
+ dataDir: string;
+ store: Pick<Store, "bots" | "appendMessage">;
+ /** MCP servers saved here. */
+ mcpServers: () => number;
+ /** Whether any app is connected here; null when that can't be read now. */
+ appsConnected: () => Promise<boolean | null>;
+ now?: () => number;
+ log?: (line: string) => void;
+}
+
+export function createRoutineHoldsHost(deps: RoutineHoldsHostDeps) {
+ const file = join(deps.dataDir, "routine-holds.json");
+ const now = deps.now ?? Date.now;
+ let saved: Saved = {};
+ try {
+ const raw = JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>;
+ saved = { ...(raw.away === true ? { away: true } : {}), ...(raw.planCancelled === true ? { planCancelled: true } : {}), ...(raw.connectionsGone === true ? { connectionsGone: true } : {}) };
+ } catch { /* none kept yet */ }
+ let rechecked = 0;
+ let rechecking = false;
+ /** The routines, once index.ts has made them (`attach`): what is read before then waits for them. */
+ let routines: Pick<RoutineManager, "holdFor"> | null = null;
+
+ function save(next: Saved): boolean {
+ if (JSON.stringify(next) === JSON.stringify(saved)) return false;
+ saved = next;
+ try { writeFileAtomic(file, JSON.stringify(saved), { mode: 0o600 }); }
+ catch (error) { deps.log?.(`[routines] could not keep why routines wait (${error instanceof Error ? error.name : "error"})`); }
+ return true;
+ }
+
+ function causes(): RoutineHoldCause[] {
+ return [...(saved.planCancelled ? ["plan_cancelled" as const] : []), ...(saved.away ? ["no_engine" as const] : []), ...(saved.connectionsGone ? ["no_connections" as const] : [])];
+ }
+
+ /** The owner's Chief: the place's own one, else the first made (a Team Cloud's founder's). */
+ function tell(line: string): void {
+ const chief = deps.store.bots.filter((bot) => !bot.hidden && bot.chiefOfStaff)
+ .sort((a, b) => Number(Boolean(b.defaultBot)) - Number(Boolean(a.defaultBot)) || a.createdAt - b.createdAt)[0];
+ if (chief) deps.store.appendMessage(chief.threadId, { role: "bot", kind: "activity", tool: { name: `notice: ${line}`, ok: true } });
+ }
+
+ /** Never throws: it runs inside reading the engines, which must not fail for it. */
+ function review(): void {
+ if (!routines) return;
+ try {
+ for (const cause of routines.holdFor(causes())) tell(ROUTINE_HOLD_LINES[cause]);
+ } catch (error) {
+ deps.log?.(`[routines] could not pause or resume routines (${error instanceof Error ? error.message : "error"})`);
+ }
+ if (saved.connectionsGone && !rechecking && now() - rechecked >= RECHECK_MS) void connections("recheck");
+ }
+
+ /** A connection removed (the hold begins when none is left), added (it ends), or read again while none was left. */
+ async function connections(change: "removed" | "added" | "recheck"): Promise<void> {
+ if (change === "added") {
+ if (save({ ...saved, connectionsGone: undefined })) review();
+ return;
+ }
+ if (change === "removed" && saved.connectionsGone) return;
+ rechecking = true;
+ try {
+ const left = deps.mcpServers() > 0 ? true : await deps.appsConnected().catch(() => null);
+ rechecked = now();
+ // Unreadable: nothing changes on a guess.
+ if (left === null) return;
+ if (save({ ...saved, connectionsGone: left ? undefined : true })) review();
+ } finally {
+ rechecking = false;
+ }
+ }
+
+ return {
+ /** The routines are made: what was last read applies to them now. */
+ attach(manager: Pick<RoutineManager, "holdFor">): void {
+ routines = manager;
+ review();
+ },
+ review,
+ /** The engines were read: whether no AI of the owner's own can run here, for sure. */
+ engines(away: boolean): void {
+ save({ ...saved, away: away ? true : undefined });
+ review();
+ },
+ /** The Admin's word on the plan: cancelled (routines pause), or renewing again (they turn back on). */
+ plan(cancelled: boolean): void {
+ save({ ...saved, planCancelled: cancelled ? true : undefined });
+ review();
+ },
+ connections,
+ /** The causes holding routines now. */
+ causes,
+ };
+}
+
+export type RoutineHoldsHost = ReturnType<typeof createRoutineHoldsHost>;
diff --git a/server/index.ts b/server/index.ts
index d47624b910..74b5b65081 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -284,7 +284,7 @@ import { createCloudMoveRoutes } from "./cloud-move-http.ts";
import { RESTART_EXIT_CODE } from "./restart.ts";
import { applyIncludedXMessage, holdIncludedServices, researchCredential, trialCreditCredential, xCredential, xResearchStatus } from "./included-services.ts";
import { CloudCreditProvider } from "./cloud-credit-provider.ts";
-import { createCreditMoves } from "./cloud-credit-moves.ts";
+import { createCreditMoves } from "./cloud-credit-moves.ts"; import { createRoutineHoldsHost } from "./host/routine-holds-host.ts";
import { TRIAL_CREDIT_OWN_AI, TRIAL_KEY_HELD } from "./trial-credit.ts"; import { createHeldKeys } from "./cloud-held-keys.ts";
import type { ProviderInstance } from "./contracts.ts";
import { readyToRun, selectDefaultModelSelection, withInstanceConfig, withNewBotEffort, type SelectableInstance } from "./default-model-selection.ts"; import { configIdentity, createTestedAi } from "./tested-ai.ts";
@@ -2575,7 +2575,7 @@ const selectionContext = {
async function refreshUnsetModelSelections(instances?: readonly SelectableInstance[], read = testedAi.read()): Promise<void> {
if (registry.provisional(instances)) return;
const selectable = selectableInstances(instances ?? await registry.describe());
- creditMoves?.settle(selectable);
+ creditMoves?.settle(selectable); routineHolds?.engines(Boolean(creditMoves?.away(selectable)));
bootSelection = testedAi.settle(await defaultSelection(undefined, selectable.filter(instance => readyToRun(instance, selectionContext))), selectable, read);
if (hostedModels || !bootSelection.instanceId || !bootSelection.model) return;
const selection = withNewBotEffort(bootSelection, cfg.newBots?.effort,
@@ -2877,6 +2877,8 @@ const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENV
const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, store, context: selectionContext, threadBusy, saveDefault: saveNewBotModel,
defaults: () => [cfg.defaultModelSelection, cfg.newBotDefaults?.profile.modelSelection], engineName: id => registry.get(id)?.displayName ?? id,
log: line => console.warn(line) });
+const routineHolds = CLOUD_HOME ? createRoutineHoldsHost({ dataDir: DATA_DIR, store, mcpServers: () => Object.keys(cfg.mcpServers ?? {}).length, log: (line) => console.warn(line),
+ appsConnected: async () => composio.configured(cfg) ? Object.values(await composio.connectedServices(cfg)).some((service) => service.connected) : false }) : null;
const skillsHost = createSkillsLibraryHost({ store, cfg, appendSkillRequestCard, engineConfig: (instanceId) => providerConfigs()[instanceId], instanceOf: (instanceId) => { const instance = registry.get(instanceId); return instance ? { instanceId, driverKind: instance.driverKind } : undefined; } });
const { listBotSkills, readBotSkillFile } = skillsHost; const cloudConnections = createCloudConnectionsHost({ cloudHome: CLOUD_HOME, config: () => cfg, environmentId: ENVIRONMENT_ID, mcpOAuth, highlevel, heldKeys, dataDir: DATA_DIR, engines: async () => selectableInstances(await registry.describe()).filter((instance) => readyToRun(instance, selectionContext)).map((instance) => instance.instanceId) });
const highlevelHost = createHighLevelHost({ service: highlevel, dataDir: DATA_DIR, bot: (id) => store.bot(id),
@@ -2890,7 +2892,7 @@ const phones = createPhones({
active: (turn) => internalCapabilityIsActive(turn as InternalCapability),
});
let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.
-const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE,
+const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), plan: (cancelled) => routineHolds?.plan(cancelled), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE,
engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),
connectors: () => highlevelHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),
browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount() }), firstHour: () => firstHourHooks.health(), ...(engineMemory.enabled ? { room: () => engineMemory.dayPressure() } : {}) } });
@@ -9009,7 +9011,7 @@ routines = new RoutineManager({
notify(buildNotification("routine-deferred", routineSourceOwner(run)?.bot ?? bot, routineSourceThread(run) ?? bot.threadId, detail));
},
});
-phones.adoptRoutines();
+phones.adoptRoutines(); routineHolds?.attach(routines);
// Settle Cloud ownership before anything is served and before any routine can run.
if (CLOUD_HOME && CLOUD_OWNER_KEY && cloudRoutineAuthors) {
cloudHome = settleCloudHome({ file: join(DATA_DIR, "cloud-owner.json"), machineId: CLOUD_HOME.machineId, ownerKey: CLOUD_OWNER_KEY, nobodyKey: CLOUD_NOBODY_KEY,
@@ -12548,7 +12550,7 @@ ROUTES.push(createMcpServerRoutes({
fallbackPublicUrl: FALLBACK_PUBLIC_URL,
mcpConfigBusy: { get: () => mcpConfigBusy, set: (busy) => { mcpConfigBusy = busy; } },
mcpServerResponse, mcpPolicyRefusal, persistMcpServers, savedCustomDomain, appCatalog: chatAppsMcp, forgetPeople: (name) => teamConnections.forgetServer(name), health: mcpServersHost.health,
-}));
+ connectionsChanged: (change) => void routineHolds?.connections(change) }));
ROUTES.push(createSetupImportRoutes({ local: DESKTOP_MANAGED && !CLOUD_HOME && !HOSTED_WORKSPACE, cfg, mcpPolicyRefusal, persistMcpServers,
mcpConfigBusy: { get: () => mcpConfigBusy, set: (busy) => { mcpConfigBusy = busy; } } }));
ROUTES.push(createComputerRoutes({
@@ -15322,12 +15324,12 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
m = path.match(/^\/api\/connectors\/([\w-]+)\/authorize$/);
if (m && method === "POST") {
const body = await readBody(req);
- return json(res, 200, await composio.authorizeService(cfg, m[1], body.alias));
+ const started = await composio.authorizeService(cfg, m[1], body.alias); void routineHolds?.connections("added"); return json(res, 200, started);
}
m = path.match(/^\/api\/connectors\/([\w-]+)\/accounts\/([A-Za-z0-9][A-Za-z0-9_-]{0,127})$/);
- if (m && method === "DELETE") return json(res, 200, await composio.removeAccount(cfg, m[1], m[2]));
+ if (m && method === "DELETE") { const removed = await composio.removeAccount(cfg, m[1], m[2]); void routineHolds?.connections("removed"); return json(res, 200, removed); }
m = path.match(/^\/api\/connectors\/([\w-]+)$/);
- if (m && method === "DELETE") return json(res, 200, await composio.removeService(cfg, m[1]));
+ if (m && method === "DELETE") { const removed = await composio.removeService(cfg, m[1]); void routineHolds?.connections("removed"); return json(res, 200, removed); }
// The browser auth URL goes only to this local UI and is never stored in the transcript.
m = path.match(/^\/api\/bots\/([\w-]+)\/connector-cards\/([\w-]+)\/(authorize|status|resume|dismiss)$/);
@@ -15341,7 +15343,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
const alias = composio.normalizeAccountAlias(typeof body.alias === "string" ? body.alias : undefined) ?? connector.alias;
store.patchMessage(threadId, message.id, { connector: { ...connector, alias, status: "authorizing", error: undefined, dismissed: false } });
try {
- return json(res, 200, await composio.authorizeService(cfg, connector.slug, alias));
+ const started = await composio.authorizeService(cfg, connector.slug, alias); void routineHolds?.connections("added"); return json(res, 200, started);
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
store.patchMessage(threadId, message.id, {
diff --git a/server/quota-switch.test.ts b/server/quota-switch.test.ts
index d0cea49a5e..040bd6e61f 100644
--- a/server/quota-switch.test.ts
+++ b/server/quota-switch.test.ts
@@ -9,6 +9,7 @@ import { PROBE_TIMEOUT_MS } from "./engine-install.ts";
import { closeMessageDb } from "./message-db.ts";
import { createQuotaSwitch, NOT_NOW, quotaSwitchEnabled, type QuotaRequest, type QuotaSwitch, type QuotaSwitchDeps, type QuotaSwitchEngine } from "./quota-switch.ts";
import { Store, type BotRecord, type Message } from "./store.ts";
+import { toolFailureMessage } from "./drivers/tool-failure.ts";
const QUOTA = "You've hit your weekly limit · resets Oct 12 at 2:30pm (Asia/Calcutta)";
const defaultSelection = (): ModelSelection => ({ instanceId: "claude", model: "claude-default" });
@@ -216,6 +217,16 @@ describe("quota switch", () => {
expect(moves, "so it goes back once the limit resets").toEqual([{ threadId: bot.threadId, from: defaultSelection(), to: CODEX }]);
});
+ it("never takes a failed tool call for the AI's usage limit, whatever the tool is called", async () => {
+ const turn = begin(bot.threadId, { messageId: said("export the quota report") });
+ coordinator.endTurn(turn.id, { ok: false, text: "tool failed" });
+ cause = toolFailureMessage(["mcp__billing__get-quota"], []);
+ expect(await quota.turnFailed(thread(), { ...turn.event, stopReason: "tool_error" }, false)).toBeNull();
+ expect(thread().modelSelection).toEqual(defaultSelection());
+ expect(told).toEqual([]);
+ expect(resend).not.toHaveBeenCalled();
+ });
+
it("goes by the engine's own limit flag and its reset when it gives them", async () => {
flags = { limit: "engine", limitResetsAt: 1_900_000_000_000 };
await limited({ messageId: said("hi") }, "This Claude account has reached its 5-hour limit, which resets Oct 28 at 2:00 PM.");
diff --git a/server/quota-switch.ts b/server/quota-switch.ts
index 2efb891deb..38c1ff1aad 100644
--- a/server/quota-switch.ts
+++ b/server/quota-switch.ts
@@ -201,8 +201,9 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {
const request = deps.request(threadId);
const flags = deps.turnStops.read?.(threadId, event.turnId)?.flags;
const cause = deps.turnStops.failureCause(event);
+ // A tool call's failure names the tool, never the engine's own limit, whatever its words.
const scope: TakeoverScope | undefined = signedOutStop(event.stopReason, cause) ? "signed-out"
- : flags?.limit ?? (classifyError({ text: cause ?? "" }).reason === "quota" ? "engine" : undefined);
+ : flags?.limit ?? (event.stopReason !== "tool_error" && classifyError({ text: cause ?? "" }).reason === "quota" ? "engine" : undefined);
if (!scope) return null;
const thread = store.projectBotForTask(bot.id, threadId) ?? bot;
const from = thread.modelSelection;
diff --git a/server/routes/cloud-signed-plan.test.ts b/server/routes/cloud-signed-plan.test.ts
new file mode 100644
index 0000000000..4f7592fdd8
--- /dev/null
+++ b/server/routes/cloud-signed-plan.test.ts
@@ -0,0 +1,70 @@
+import type { IncomingMessage, ServerResponse } from "node:http";
+import { join } from "node:path";
+import { PassThrough } from "node:stream";
+import { describe, expect, it } from "vitest";
+
+import { createCloudHealth } from "../cloud-health.ts";
+import { cloudRequestSignature } from "../cloud-home.ts";
+import { DATA_DIR } from "../config.ts";
+import { SessionRegistry } from "../sessions.ts";
+import { CLOUD_PLAN_PATH, createCloudSignedRoutes } from "./cloud-signed.ts";
+
+const secret = "S".repeat(43);
+
+function routes(withPlan = true) {
+ let counter = 0;
+ const now = () => 1_800_000_000_000;
+ const told: boolean[] = [];
+ const sessions = new SessionRegistry({ file: join(DATA_DIR, "sessions.json"), now });
+ const health = createCloudHealth({
+ store: { onChange: () => () => {}, botByThread: () => null, bots: [] }, bus: { subscribe: () => () => {} },
+ engines: () => [], dataDir: DATA_DIR, eventsDir: DATA_DIR, version: "0.1.0", image: undefined, connectors: () => null,
+ browser: () => ({ available: true, installing: false, interrupted: 0 }), now,
+ });
+ const handle = createCloudSignedRoutes({ secret, sessions, health, now, ...(withPlan ? { plan: (cancelled: boolean) => { told.push(cancelled); } } : {}) });
+ const sign = (body: string, key = secret, method = "POST") => {
+ const timestamp = String(Math.floor(now() / 1000)), nonce = `nonce-${String(++counter).padStart(12, "0")}`;
+ return { "content-type": "application/json", "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce,
+ "x-omb-cloud-signature": `v1=${cloudRequestSignature(key, timestamp, nonce, method, CLOUD_PLAN_PATH, body)}` };
+ };
+ const send = async (method: string, headers: Record<string, string>, body: string) => {
+ const req = Object.assign(new PassThrough(), { method, url: CLOUD_PLAN_PATH, headers, socket: { remoteAddress: "127.0.0.1" } }) as unknown as IncomingMessage;
+ let status = 0, text = "";
+ const res = { setHeader() {}, writeHead(code: number) { status = code; }, end(data: string) { text = data; } } as unknown as ServerResponse;
+ const url = new URL(CLOUD_PLAN_PATH, "http://localhost");
+ const answered = handle({ req, res, url, path: url.pathname, method });
+ (req as unknown as PassThrough).end(body);
+ return { answered: await answered, status, body: text ? JSON.parse(text) : null };
+ };
+ return { sign, send, told };
+}
+
+describe("POST /api/cloud/plan", () => {
+ it("takes the Admin's signed word that the plan was cancelled, or renews again", async () => {
+ const { sign, send, told } = routes();
+ const cancelled = JSON.stringify({ v: 1, cancelled: true });
+ expect(await send("POST", sign(cancelled), cancelled)).toEqual({ answered: true, status: 200, body: { ok: true } });
+ const renewing = JSON.stringify({ v: 1, cancelled: false });
+ expect((await send("POST", sign(renewing), renewing)).status).toBe(200);
+ expect(told).toEqual([true, false]);
+ });
+
+ it("refuses a wrong key, a replay, a body that says neither, and anything but POST; changes nothing", async () => {
+ const { sign, send, told } = routes();
+ const body = JSON.stringify({ v: 1, cancelled: true });
+ expect((await send("POST", sign(body, "W".repeat(43)), body)).status).toBe(401);
+ const once = sign(body);
+ expect((await send("POST", once, body)).status).toBe(200);
+ expect((await send("POST", once, body)).body).toEqual({ error: "replayed_request" });
+ const vague = JSON.stringify({ v: 1, cancelled: "yes" });
+ expect((await send("POST", sign(vague), vague)).body).toEqual({ error: "invalid_plan" });
+ expect((await send("GET", sign("", secret, "GET"), "")).status).toBe(405);
+ expect(told).toEqual([true]);
+ });
+
+ it("is not a route on a server with no routines to hold", async () => {
+ const { sign, send } = routes(false);
+ const body = JSON.stringify({ v: 1, cancelled: true });
+ expect((await send("POST", sign(body), body)).answered).toBe(false);
+ });
+});
diff --git a/server/routes/cloud-signed.ts b/server/routes/cloud-signed.ts
index b39f9490af..3245f735ce 100644
--- a/server/routes/cloud-signed.ts
+++ b/server/routes/cloud-signed.ts
@@ -23,6 +23,10 @@ export const CLOUD_BOX_PATH = "/api/cloud/box";
* theirs alone is deleted here (host/team-member-left.ts). */
export const CLOUD_TEAM_MEMBER_LEFT_PATH = "/api/cloud/team/member-left";
+/** The plan was cancelled, or renews again: `{"v":1,"cancelled":true|false}`, signed with the body like the sleep request.
+ * While it is cancelled the home's routines wait (host/routine-holds-host.ts). */
+export const CLOUD_PLAN_PATH = "/api/cloud/plan";
+
export function createCloudSignedRoutes(deps: {
secret: string;
sessions: Pick<SessionRegistry, "openPairing" | "revokeMember" | "attemptAllowed" | "noteFailure" | "clearFailures">;
@@ -37,6 +41,8 @@ export function createCloudSignedRoutes(deps: {
teamAdmin?: { summary(): Promise<TeamAdminSummary> } | null;
/** A Team Cloud's member left: delete what was theirs alone; absent on a My Cloud. */
memberLeft?: ((email: string) => Promise<Record<string, unknown>>) | null;
+ /** The plan was cancelled (true) or renews again (false); absent on a server that is not a Cloud home. */
+ plan?: ((cancelled: boolean) => void) | null;
now?: () => number;
}) {
const pairing = createCloudPairing({ secret: deps.secret, sessions: deps.sessions, team: deps.team ?? null, now: deps.now });
@@ -46,12 +52,14 @@ export function createCloudSignedRoutes(deps: {
const boxReads = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });
const teamAdminReads = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });
const memberLeftRequests = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });
+ const planRequests = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });
/** True when the request was one of these and has been answered. */
return async ({ req, res, url, path, method }: CloudSignedRequest): Promise<boolean> => {
const power = path === CLOUD_POWER_PATH || path === CLOUD_POWER_SLEEP_PATH ? deps.power?.() ?? null : null;
const teamAdmin = path === CLOUD_TEAM_ADMIN_PATH && deps.team ? deps.teamAdmin ?? null : null;
const memberLeft = path === CLOUD_TEAM_MEMBER_LEFT_PATH && deps.team ? deps.memberLeft ?? null : null;
- if (path !== CLOUD_PAIRING_PATH && path !== CLOUD_HEALTH_PATH && path !== CLOUD_BOX_PATH && !power && !teamAdmin && !memberLeft) return false;
+ const plan = path === CLOUD_PLAN_PATH ? deps.plan ?? null : null;
+ if (path !== CLOUD_PAIRING_PATH && path !== CLOUD_HEALTH_PATH && path !== CLOUD_BOX_PATH && !power && !teamAdmin && !memberLeft && !plan) return false;
res.setHeader("cache-control", "no-store");
const source = requestSource(req);
const header = (name: string) => { const value = req.headers[name]; return typeof value === "string" ? value : undefined; };
@@ -99,6 +107,20 @@ export function createCloudSignedRoutes(deps: {
json(res, 200, { ok: true, ...(await memberLeft(email)) });
return true;
}
+ if (plan) {
+ if (method !== "POST") { json(res, 405, { error: "method_not_allowed" }); return true; }
+ if (!/^application\/json\b/i.test(String(req.headers["content-type"] ?? ""))) { json(res, 415, { error: "send the request as JSON (content-type: application/json)" }); return true; }
+ const body = await readSignedBody(req);
+ const verdict = planRequests.verify({ ...signed, method, target: `${path}${url.search}`, body });
+ if (!verdict.ok) { console.warn(`cloud plan request refused from ${source}: ${verdict.error}`); json(res, verdict.status, { error: verdict.error }); return true; }
+ let parsed: unknown;
+ try { parsed = JSON.parse(body.toString("utf8")); } catch { json(res, 400, { error: "invalid_body" }); return true; }
+ const cancelled = (parsed as { cancelled?: unknown } | null)?.cancelled;
+ if (typeof cancelled !== "boolean") { json(res, 400, { error: "invalid_plan" }); return true; }
+ plan(cancelled);
+ json(res, 200, { ok: true });
+ return true;
+ }
if (path === CLOUD_BOX_PATH) {
if (method !== "GET") { json(res, 405, { error: "method_not_allowed" }); return true; }
const verdict = boxReads.verify({ ...signed, method, target: `${path}${url.search}`, body: "" });
diff --git a/server/routes/mcp-servers.test.ts b/server/routes/mcp-servers.test.ts
index 3eb5c5bffd..d53cd70ea6 100644
--- a/server/routes/mcp-servers.test.ts
+++ b/server/routes/mcp-servers.test.ts
@@ -20,6 +20,7 @@ afterEach(async () => {
async function serve() {
const cfg: Pick<AppConfig, "mcpServers"> = { mcpServers: {} };
+ const changes: string[] = [];
let busy = false;
const route = createMcpServerRoutes({
cfg,
@@ -33,6 +34,7 @@ async function serve() {
mcpPolicyRefusal: () => undefined,
persistMcpServers: (next) => { cfg.mcpServers = next; },
savedCustomDomain: () => null,
+ connectionsChanged: (change) => { changes.push(change); },
});
const active = createServer(async (req, res) => {
const url = new URL(req.url ?? "/", "http://localhost");
@@ -47,9 +49,20 @@ async function serve() {
const post = (path: string, body: unknown) => fetch(`${base}${path}`, {
method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
});
- return { cfg, post, get: () => fetch(`${base}/api/mcp/servers`) };
+ return { cfg, post, changes, get: () => fetch(`${base}/api/mcp/servers`), remove: (name: string) => fetch(`${base}/api/mcp/servers/${name}`, { method: "DELETE" }) };
}
+it("says when a server is added, imported or removed on purpose, so a Cloud home's routines can wait while none is left", async () => {
+ const { post, remove, changes } = await serve();
+ const added = await post("/api/mcp/servers", { name: "warehouse", url: "https://data.example.com/mcp", headers: { Authorization: "" } });
+ expect(added.status, await added.clone().text()).toBe(201);
+ const imported = await post("/api/mcp/servers/import", { json: JSON.stringify({ mcpServers: { nightwatch: { type: "http", url: "https://nightwatch.example.com/mcp" } } }) });
+ expect(imported.status, await imported.clone().text()).toBe(201);
+ expect((await remove("warehouse")).status).toBe(200);
+ expect((await remove("missing")).status).toBe(404);
+ expect(changes).toEqual(["added", "added", "removed"]);
+});
+
it.each([["private", "person"], ["public", "team"]])("lists the scope of %s in reads and mutation responses", async (name, scope) => {
const { post, get } = await serve();
const response = await post("/api/mcp/servers", { name, url: "https://mail.example.com/mcp", headers: { Authorization: "" } });
diff --git a/server/routes/mcp-servers.ts b/server/routes/mcp-servers.ts
index c9ff1a5178..782dc64cb3 100644
--- a/server/routes/mcp-servers.ts
+++ b/server/routes/mcp-servers.ts
@@ -32,6 +32,8 @@ export interface McpServerRouteDeps {
forgetPeople?(name: string): void;
/** Whether each command server starts for each bot: checked again when one is added, changed or turned on. */
health?: { changed(name: string): void };
+ /** A server was added or removed on purpose: a Cloud home's routines wait while every connection is gone. */
+ connectionsChanged?(change: "added" | "removed"): void;
}
/** A server of another computer's: its program, files or address are there, so it is never started or signed in to here. */
@@ -189,6 +191,7 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {
persistMcpServers({ ...current, [name]: parsed.server });
appCatalog?.serverChanged(name);
health?.changed(name);
+ deps.connectionsChanged?.("added");
return json(res, 201, withServerDetails(mcpServerResponse()));
} finally {
mcpConfigBusy.set(false);
@@ -225,6 +228,7 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {
const refused = names.filter(name => mcpPolicyRefusal(name, parsed.servers[name] as object));
if (refused.length) return json(res, 403, { error: `${mcpPolicyRefusal(refused[0]!, parsed.servers[refused[0]!] as object)} Not approved: ${refused.join(", ")}.`, code: "managed_policy" });
persistMcpServers({ ...current, ...parsed.servers });
+ deps.connectionsChanged?.("added");
return json(res, 201, { ...withServerDetails(mcpServerResponse()), added: names });
} finally {
mcpConfigBusy.set(false);
@@ -249,6 +253,7 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {
mcpOAuth.forget(name);
forgetPeople?.(name);
appCatalog?.forgetServer(name);
+ deps.connectionsChanged?.("removed");
return json(res, 200, withServerDetails(mcpServerResponse()));
}
diff --git a/server/routine-holds.test.ts b/server/routine-holds.test.ts
new file mode 100644
index 0000000000..e0ec0beb52
--- /dev/null
+++ b/server/routine-holds.test.ts
@@ -0,0 +1,158 @@
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { holdCauses, shiftHolds } from "./routine-holds.ts";
+import { RoutineManager, type RoutineManagerOptions } from "./routines.ts";
+
+const dirs: string[] = [];
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+
+const START = Date.parse("2026-10-30T06:00:00Z");
+/** Lets a scheduler pass started in the background finish first. */
+const settled = () => new Promise((resolve) => setImmediate(resolve));
+const HOUR = 60 * 60_000;
+
+function harness(file?: string) {
+ let now = START;
+ let task = 0;
+ const started: string[] = [];
+ const emitted: Array<Record<string, unknown>> = [];
+ if (!file) {
+ const dir = mkdtempSync(join(tmpdir(), "omb-routine-holds-"));
+ dirs.push(dir);
+ file = join(dir, "routines.json");
+ }
+ const options: RoutineManagerOptions = {
+ file, now: () => now, emit: (payload) => emitted.push(payload), botState: () => "ready", goalState: () => "ready",
+ createTask: () => ({ threadId: `thread-${++task}` }),
+ startTurn: async (_botId, threadId) => { started.push(threadId); },
+ };
+ const manager = new RoutineManager(options);
+ const hourly = (name: string, enabled = true) => manager.create({ name, prompt: `Do ${name}`, botId: "maus-1", enabled,
+ schedule: { type: "interval", everyMinutes: 60, anchorAt: START + HOUR } });
+ const routine = (id: string) => manager.listRoutines().find((candidate) => candidate.id === id)!;
+ return { manager, file, started, emitted, hourly, routine, setNow: (at: number) => { now = at; }, now: () => now };
+}
+
+describe("why routines wait while their owner has left", () => {
+ it("keeps the causes in one order, each once, and ignores anything else", () => {
+ expect(holdCauses(["no_connections", "plan_cancelled", "no_connections", "bogus"])).toEqual(["plan_cancelled", "no_connections"]);
+ expect(holdCauses("no_engine")).toEqual([]);
+ });
+
+ it("holds the routines that are on for the first cause that began, and frees each once no cause holds it", () => {
+ const on = { enabled: true } as { enabled: boolean; heldFor?: "no_engine" | "no_connections" | "plan_cancelled" };
+ const off = { enabled: false } as typeof on;
+ expect(shiftHolds([on, off], [], ["no_engine", "no_connections"])).toMatchObject({ paused: [on], resumed: [], began: ["no_engine", "no_connections"] });
+ expect(on.heldFor).toBe("no_engine");
+ expect(off.heldFor).toBeUndefined();
+ // Its cause ended while another still holds: it waits on that one.
+ expect(shiftHolds([on], ["no_engine", "no_connections"], ["no_connections"])).toMatchObject({ paused: [], resumed: [] });
+ expect(on.heldFor).toBe("no_connections");
+ expect(shiftHolds([on], ["no_connections"], [])).toMatchObject({ paused: [], resumed: [on] });
+ expect(on.heldFor).toBeUndefined();
+ });
+});
+
+describe("routines pause while their owner has left, and come back by themselves", () => {
+ it("turns off every routine that is on, cancels its queued run, and the list says why; nothing runs while it waits", async () => {
+ const h = harness();
+ const daily = h.hourly("Clarity export");
+ const offAlready = h.hourly("Weekly digest", false);
+ const queued = h.manager.runNow(daily.id)!;
+ expect(queued.status).toBe("queued");
+
+ expect(h.manager.holdFor(["no_engine"])).toEqual(["no_engine"]);
+ expect(h.routine(daily.id)).toMatchObject({ enabled: false, heldFor: "no_engine", nextRunAt: null });
+ expect(h.routine(offAlready.id).heldFor).toBeUndefined();
+ expect(h.manager.listRuns().find((run) => run.id === queued.id)).toMatchObject({ status: "cancelled", error: "The routine was paused before this run started" });
+ expect(h.emitted.some((frame) => frame.kind === "routine" && (frame.routine as { heldFor?: string })?.heldFor === "no_engine")).toBe(true);
+
+ h.setNow(START + 5 * HOUR);
+ await settled();
+ await h.manager.tick();
+ expect(h.started).toEqual([]);
+ expect(h.manager.listRuns().filter((run) => run.status === "failed" || run.status === "missed")).toEqual([]);
+ // The same causes again change nothing and pause nothing twice.
+ expect(h.manager.holdFor(["no_engine"])).toEqual([]);
+ });
+
+ it("turns them back on from now once nothing holds them, without the runs they skipped", async () => {
+ const h = harness();
+ const daily = h.hourly("Clarity export");
+ h.manager.holdFor(["plan_cancelled"]);
+ h.setNow(START + 5 * HOUR + 10 * 60_000);
+ expect(h.manager.holdFor([])).toEqual([]);
+ expect(h.routine(daily.id)).toMatchObject({ enabled: true, nextRunAt: START + 6 * HOUR });
+ expect(h.routine(daily.id).heldFor).toBeUndefined();
+ await settled();
+ await h.manager.tick();
+ expect(h.started).toEqual([]);
+ h.setNow(START + 6 * HOUR);
+ await h.manager.tick();
+ expect(h.started).toHaveLength(1);
+ });
+
+ it("waits until every cause has ended, and says nothing new for a cause that paused nothing", () => {
+ const h = harness();
+ const daily = h.hourly("Clarity export");
+ h.manager.holdFor(["no_engine"]);
+ expect(h.manager.holdFor(["no_engine", "no_connections"])).toEqual([]);
+ expect(h.manager.holdFor(["no_connections"])).toEqual([]);
+ expect(h.routine(daily.id)).toMatchObject({ enabled: false, heldFor: "no_connections" });
+ h.manager.holdFor([]);
+ expect(h.routine(daily.id)).toMatchObject({ enabled: true });
+ });
+
+ it("keeps the person's own choice: a routine turned on or off by hand is never paused or resumed for that cause", () => {
+ const h = harness();
+ const turnedOn = h.hourly("Clarity export");
+ const turnedOff = h.hourly("Inbox sweep");
+ const offBefore = h.hourly("Old report", false);
+ h.manager.holdFor(["plan_cancelled"]);
+ h.manager.update(turnedOn.id, { enabled: true });
+ h.manager.update(turnedOff.id, { enabled: false });
+ expect(h.routine(turnedOn.id)).toMatchObject({ enabled: true });
+ expect(h.routine(turnedOn.id).heldFor).toBeUndefined();
+ expect(h.routine(turnedOff.id).heldFor).toBeUndefined();
+ h.manager.holdFor([]);
+ expect(h.routine(turnedOn.id).enabled).toBe(true);
+ expect(h.routine(turnedOff.id).enabled).toBe(false);
+ expect(h.routine(offBefore.id).enabled).toBe(false);
+ });
+
+ it("never turns back on a room's routine whose room was deleted while it waited", () => {
+ const h = harness();
+ const goal = h.manager.create({ name: "Weekly plan", prompt: "Plan the week", botId: "maus-1", target: "room-goal", groupId: "room-1",
+ schedule: { type: "interval", everyMinutes: 60, anchorAt: START + HOUR } });
+ h.manager.holdFor(["no_engine"]);
+ h.manager.disableForGroup("room-1");
+ expect(h.routine(goal.id).heldFor).toBeUndefined();
+ h.manager.holdFor([]);
+ expect(h.routine(goal.id).enabled).toBe(false);
+ });
+
+ it("leaves a one-time run whose time passed while it waited over, never late", () => {
+ const h = harness();
+ const once = h.manager.create({ name: "Send the recap", prompt: "Send it", botId: "maus-1", schedule: { type: "once", at: START + HOUR } });
+ h.manager.holdFor(["no_engine"]);
+ h.setNow(START + 3 * HOUR);
+ h.manager.holdFor([]);
+ expect(h.routine(once.id)).toMatchObject({ enabled: false, nextRunAt: null });
+ expect(h.routine(once.id).heldFor).toBeUndefined();
+ });
+
+ it("keeps what holds them across a restart, so the same causes pause nothing twice and a release still turns them on", () => {
+ const h = harness();
+ const daily = h.hourly("Clarity export");
+ h.manager.holdFor(["no_engine"]);
+ expect(JSON.parse(readFileSync(h.file, "utf8")).holds).toEqual(["no_engine"]);
+ const again = harness(h.file);
+ expect(again.routine(daily.id)).toMatchObject({ enabled: false, heldFor: "no_engine" });
+ expect(again.manager.holdFor(["no_engine"])).toEqual([]);
+ again.manager.holdFor([]);
+ expect(again.routine(daily.id).enabled).toBe(true);
+ });
+});
diff --git a/server/routine-holds.ts b/server/routine-holds.ts
new file mode 100644
index 0000000000..03667b2119
--- /dev/null
+++ b/server/routine-holds.ts
@@ -0,0 +1,66 @@
+// Routines that wait while their owner has left (host/routine-holds-host.ts reads why): no AI of theirs is signed in here
+// any more, they removed every connected app and server, or the plan was cancelled. A cause that begins turns every routine
+// that is on off, stamped with that cause, so its list says why and nothing runs to fail or to message a person who left.
+// Once no cause holds a stamped routine it turns back on from now, without the runs it skipped. Turning a routine on or
+// off by hand clears its stamp: the person's choice wins, and a later change of cause leaves it alone.
+import { ROUTINE_HOLD_CAUSES, type RoutineHoldCause } from "../shared/routines.ts";
+
+export const isRoutineHoldCause = (value: unknown): value is RoutineHoldCause => ROUTINE_HOLD_CAUSES.includes(value as RoutineHoldCause);
+
+/** The causes in their fixed order, each once: the first one holding a routine is the one it shows. */
+export function holdCauses(value: unknown): RoutineHoldCause[] {
+ return Array.isArray(value) ? ROUTINE_HOLD_CAUSES.filter((cause) => value.includes(cause)) : [];
+}
+
+export interface HoldShift<T> {
+ /** Routines that were on and are now held: the caller turns each off. */
+ paused: T[];
+ /** Routines no cause holds any more: the caller turns each back on. */
+ resumed: T[];
+ /** Causes that began with this change. */
+ began: RoutineHoldCause[];
+}
+
+export interface AppliedHolds<R, Run> extends HoldShift<R> {
+ /** Queued runs of the paused routines, cancelled before they started. */
+ cancelled: Run[];
+}
+
+type HeldRoutine = { id: string; enabled: boolean; heldFor?: RoutineHoldCause; nextRunAt: number | null; schedule: { type: string } };
+type HeldRun = { routineId: string; status: string; attention?: string; finishedAt?: number; error?: string };
+
+/** Turns the routines a change of cause holds off (their queued runs cancelled) and the ones it frees back on from `now`.
+ * `next` is the routine's first occurrence from `now`; a one-time run whose time passed while it waited stays over. */
+export function applyHolds<R extends HeldRoutine, Run extends HeldRun>(routines: readonly R[], runs: readonly Run[],
+ before: readonly RoutineHoldCause[], after: readonly RoutineHoldCause[], now: number, next: (schedule: R["schedule"], now: number) => number | null): AppliedHolds<R, Run> {
+ const shift = shiftHolds(routines, before, after);
+ for (const routine of shift.paused) Object.assign(routine, { enabled: false, nextRunAt: null });
+ for (const routine of shift.resumed) {
+ const at = next(routine.schedule, now);
+ if (at !== null && (routine.schedule.type !== "once" || at > now)) Object.assign(routine, { enabled: true, nextRunAt: at });
+ }
+ const paused = new Set(shift.paused.map((routine) => routine.id));
+ const cancelled = runs.filter((run) => run.status === "queued" && paused.has(run.routineId));
+ for (const run of cancelled) Object.assign(run, { status: "cancelled", attention: undefined, finishedAt: now, error: "The routine was paused before this run started" });
+ return { ...shift, cancelled };
+}
+
+/** Stamps the routines a change from `before` to `after` holds or frees. A routine held for a cause that ended takes the
+ * first cause still holding; one that is on is held for the first cause that began. */
+export function shiftHolds<T extends { enabled: boolean; heldFor?: RoutineHoldCause }>(routines: readonly T[], before: readonly RoutineHoldCause[], after: readonly RoutineHoldCause[]): HoldShift<T> {
+ const began = after.filter((cause) => !before.includes(cause));
+ const shift: HoldShift<T> = { paused: [], resumed: [], began };
+ for (const routine of routines) {
+ if (routine.heldFor !== undefined && !after.includes(routine.heldFor)) {
+ if (after[0]) routine.heldFor = after[0];
+ else {
+ delete routine.heldFor;
+ shift.resumed.push(routine);
+ }
+ } else if (routine.heldFor === undefined && routine.enabled && began[0]) {
+ routine.heldFor = began[0];
+ shift.paused.push(routine);
+ }
+ }
+ return shift;
+}
diff --git a/server/routine-load.ts b/server/routine-load.ts
index 73f3beb8f0..58386f5b80 100644
--- a/server/routine-load.ts
+++ b/server/routine-load.ts
@@ -2,12 +2,14 @@
// edit or an older version left out of range is dropped, never trusted.
import { z } from "zod";
+import type { RoutineRequestOperation } from "../shared/routine-request.ts";
import { ROUTINE_CHECKS, type RoutineCheck } from "../shared/routines.ts";
import { ROUTINE_PARTS, type PartPair, type RoutinePart } from "./package-parts.ts";
import { loadAttachments, loadTimeoutMinutes } from "./routine-attachments.ts";
+import { isRoutineHoldCause } from "./routine-holds.ts";
import { MAX_DATE_MS } from "./routine-intervals.ts";
import { loadSchedule } from "./routine-schedules.ts";
-import type { Routine, RoutineGoalStatus, RoutinePackageStamp, RoutineRun, RoutineTarget } from "./routines.ts";
+import type { Routine, RoutineGoalStatus, RoutinePackageStamp, RoutineRequestReceipt, RoutineRun, RoutineTarget } from "./routines.ts";
const persistedSourceThreadId = z.string().trim().min(1).optional().catch(undefined);
@@ -96,9 +98,10 @@ export function loadRoutine(routine: Routine, now: number): Routine | null {
checkedAt: instant(routine.checkedAt),
checkTrouble: typeof routine.checkTrouble === "string" && routine.checkTrouble ? routine.checkTrouble.slice(0, 300) : undefined,
wakeAt: instant(routine.wakeAt),
+ heldFor: isRoutineHoldCause(routine.heldFor) ? routine.heldFor : undefined,
};
delete loaded.failureStreak;
- return withCheckFields(withoutUndefined(loaded, ["timeoutMinutes", "runOnStartup", "installedPackage", "checkedAt", "checkTrouble", "wakeAt"]));
+ return withCheckFields(withoutUndefined(loaded, ["timeoutMinutes", "runOnStartup", "installedPackage", "checkedAt", "checkTrouble", "wakeAt", "heldFor"]));
}
export function loadRun(run: RoutineRun): RoutineRun {
@@ -119,3 +122,20 @@ export function loadRun(run: RoutineRun): RoutineRun {
};
return withoutUndefined(loaded, ["timeoutMinutes", "access", "deliver", "checkKey"]);
}
+
+const REQUEST_ACTIONS = new Set<RoutineRequestOperation["action"]>(["create", "update", "pause", "resume", "run_now", "delete"]);
+
+/** The applied routine-request receipts routines.json holds, each whole: one with a field out of shape is dropped. */
+export function loadRequestReceipts(value: unknown): RoutineRequestReceipt[] {
+ if (!Array.isArray(value)) return [];
+ return value.filter((receipt): receipt is RoutineRequestReceipt =>
+ typeof receipt?.requestId === "string" &&
+ typeof receipt?.messageId === "string" &&
+ typeof receipt?.botId === "string" &&
+ typeof receipt?.threadId === "string" &&
+ REQUEST_ACTIONS.has(receipt?.action) &&
+ receipt?.fingerprintVersion === 1 &&
+ typeof receipt?.fingerprint === "string" && /^[a-f0-9]{64}$/.test(receipt.fingerprint) &&
+ typeof receipt?.resultId === "string" &&
+ Number.isFinite(receipt?.appliedAt));
+}
diff --git a/server/routines.ts b/server/routines.ts
index 3b9a966d0c..3475e17297 100644
--- a/server/routines.ts
+++ b/server/routines.ts
@@ -14,7 +14,7 @@ import { cloneSchedule, limitResetOccurrence, mergeScheduleUpdate, nextOccurrenc
import { runsOnce } from "../shared/limit-reset.ts";
import {
isRoutineProblemRun, type RoutineAccess, type RoutineCheck, type RoutineContextAttachment, type RoutineDelivery, type RoutineIntervalWindow, type RoutineRetryCause,
- type RoutineRunReport, type RoutineRunStatus, type RoutineRunTrigger,
+ type RoutineHoldCause, type RoutineRunReport, type RoutineRunStatus, type RoutineRunTrigger,
} from "../shared/routines.ts";
import type { PartPair, RoutinePart } from "./package-parts.ts";
import {
@@ -28,7 +28,8 @@ import { activeMs, askOf, settleAsk, waitingFor, type RoutineRunAsk } from "./ro
import { failsLikeLastOutcome, outcomesNewestFirst } from "./routine-outcomes.ts";
import { EVENT_RETRY_WINDOW_MS, loadEventReceipts, MAX_EVENT_RECEIPTS, type EventRunReceipt } from "./routine-event-receipts.ts";
import { cloneAttachments } from "./routine-attachments.ts";
-import { loadInstalledPackage, loadRoutine, loadRun } from "./routine-load.ts";
+import { loadInstalledPackage, loadRequestReceipts, loadRoutine, loadRun } from "./routine-load.ts";
+import { applyHolds, holdCauses, type AppliedHolds } from "./routine-holds.ts";
import { sanitizeInput } from "./routine-input.ts";
import { checkHold, CHECK_BOOT_HOLD_MS, type CheckHold } from "./routine-check-pacing.ts";
import { resolveRoutineResultsThread, routineRunDefinition, type ResultsThreadAllocation } from "./routine-run-definition.ts";
@@ -71,6 +72,7 @@ export interface Routine {
failureStreak?: number;
weekRuns?: { ok: number; total: number };
warning?: string;
+ heldFor?: RoutineHoldCause;
sourceThreadId?: string;
resultsThreadId?: string;
installedPackage?: RoutinePackageStamp;
@@ -189,6 +191,7 @@ interface RoutineFile {
webhookRunReceipts?: EventRunReceipt[];
startupLaunchId?: string;
ownerNotices?: RoutineOwnerNotice[];
+ holds?: RoutineHoldCause[];
}
@@ -273,19 +276,6 @@ const WAKE_HORIZON_MS = 60 * 60_000;
export const ROUTINE_RESTARTED = "OpenMausBot restarted while this routine was running";
const MAX_RUNS = 2_000;
-const ROUTINE_REQUEST_ACTIONS = new Set<RoutineRequestOperation["action"]>([
- "create",
- "update",
- "pause",
- "resume",
- "run_now",
- "delete",
-]);
-
-function isRoutineRequestAction(value: unknown): value is RoutineRequestOperation["action"] {
- return typeof value === "string" && ROUTINE_REQUEST_ACTIONS.has(value as RoutineRequestOperation["action"]);
-}
-
function cloneRoutine(routine: Routine): Routine {
return {
...routine,
@@ -318,6 +308,8 @@ export class RoutineManager {
private ticking = false;
private closing = false;
private ownerNotices: RoutineOwnerNotice[] = [];
+ /** Why routines are held now (routine-holds.ts): a change between two of these pauses or frees routines. */
+ private holds: RoutineHoldCause[] = [];
private readonly failureFacts = new Map<string, RoutineFailureFacts>();
/** Saves are refused while set, so an empty state never overwrites an unreadable file. */
private unreadable = false;
@@ -345,22 +337,11 @@ export class RoutineManager {
return loaded ? [loaded] : [];
}) : [];
this.runs = Array.isArray(disk.runs) ? disk.runs.map(loadRun) : [];
- this.routineRequestReceipts = Array.isArray(disk.routineRequestReceipts)
- ? disk.routineRequestReceipts.filter((receipt): receipt is RoutineRequestReceipt =>
- typeof receipt?.requestId === "string" &&
- typeof receipt?.messageId === "string" &&
- typeof receipt?.botId === "string" &&
- typeof receipt?.threadId === "string" &&
- isRoutineRequestAction(receipt?.action) &&
- receipt?.fingerprintVersion === 1 &&
- typeof receipt?.fingerprint === "string" && /^[a-f0-9]{64}$/.test(receipt.fingerprint) &&
- typeof receipt?.resultId === "string" &&
- Number.isFinite(receipt?.appliedAt)
- )
- : [];
+ this.routineRequestReceipts = loadRequestReceipts(disk.routineRequestReceipts);
this.webhookRunReceipts = loadEventReceipts(disk.webhookRunReceipts, this.runs, this.now());
this.frozenPending = disk.frozenResultsCleared !== true;
this.ownerNotices = loadOwnerNotices(disk.ownerNotices);
+ this.holds = holdCauses(disk.holds);
if (typeof disk.startupLaunchId === "string") this.startupLaunchId = disk.startupLaunchId;
} catch (error) {
this.routines = [];
@@ -629,6 +610,7 @@ export class RoutineManager {
// updatedAt doubles as the confirmation cards' optimistic revision: keep it monotonic within one ms.
updatedAt: Math.max(now, routine.updatedAt + 1),
});
+ if (patch.enabled !== undefined) delete routine.heldFor;
if (!clean.continuity) delete routine.continuity;
if (clean.overlap !== "queue") delete routine.overlap;
if (!clean.runOnStartup) delete routine.runOnStartup;
@@ -703,7 +685,8 @@ export class RoutineManager {
disableForGroup(groupId: string) {
let changed = false;
for (const routine of this.routines) {
- if (routine.target !== "room-goal" || routine.groupId !== groupId || !routine.enabled) continue;
+ if (routine.target !== "room-goal" || routine.groupId !== groupId || (!routine.enabled && !routine.heldFor)) continue;
+ delete routine.heldFor;
routine.enabled = false;
routine.nextRunAt = null;
routine.updatedAt = Math.max(this.now(), routine.updatedAt + 1);
@@ -923,6 +906,17 @@ export class RoutineManager {
}
/** Moves only the next run to `until`; the runs after it keep their schedule. A limit-reset routine has no time to move. */
+ /** Why routines wait now (routine-holds.ts). Returns the causes that began and paused a routine, for one line to the owner. */
+ holdFor(causes: readonly RoutineHoldCause[]): RoutineHoldCause[] {
+ const after = holdCauses(causes);
+ if (this.unreadable || after.join() === this.holds.join()) return [];
+ let held: AppliedHolds<Routine, RoutineRun> | undefined;
+ this.commitMutation(() => { held = applyHolds(this.routines, this.runs, this.holds, after, this.now(), (schedule, now) => this.initialOccurrence(schedule, now)); this.holds = after; });
+ for (const run of held!.cancelled) this.emitRun(run);
+ for (const routine of [...held!.paused, ...held!.resumed]) this.emitRoutine(routine);
+ return held!.paused.length ? held!.began : [];
+ }
+
deferNextRun(id: string, until: number): Routine | null {
const routine = this.routines.find((candidate) => candidate.id === id);
if (!routine) return null;
@@ -1570,6 +1564,7 @@ export class RoutineManager {
webhookRunReceipts: this.webhookRunReceipts,
...(this.startupLaunchId === undefined ? {} : { startupLaunchId: this.startupLaunchId }),
...(this.ownerNotices.length ? { ownerNotices: this.ownerNotices } : {}),
+ ...(this.holds.length ? { holds: this.holds } : {}),
} satisfies RoutineFile, null, 2), { mode: 0o600 });
}
}
diff --git a/shared/routines.ts b/shared/routines.ts
index f2e9dbca29..3266cbc178 100644
--- a/shared/routines.ts
+++ b/shared/routines.ts
@@ -74,6 +74,11 @@ export type RoutineAccess = "read-and-draft";
/** Where a routine's results go. `brief`: they become rows of the main agent's brief, not chat lines of their own. */
export type RoutineDelivery = "brief";
+/** Why OpenMausBot paused a routine by itself, after its owner left: no AI of theirs is signed in here any more, they
+ * removed every connected app and server, or the plan was cancelled. It turns back on once that changes. */
+export type RoutineHoldCause = "plan_cancelled" | "no_engine" | "no_connections";
+export const ROUTINE_HOLD_CAUSES: readonly RoutineHoldCause[] = ["plan_cancelled", "no_engine", "no_connections"];
+
/** What a finished run left in the chat it reports to: nothing, because it
* found nothing to tell; a report waiting for a turn there to end; or the bot
* message it wrote. */
@@ -145,6 +150,8 @@ export interface Routine {
weekRuns?: { ok: number; total: number };
/** A plain sentence when the routine names a path that cannot exist on the computer that runs it. */
warning?: string;
+ /** Set while OpenMausBot keeps it paused because its owner left; turning it on or off clears it. */
+ heldFor?: RoutineHoldCause;
attachments?: RoutineContextAttachment[];
sourceThreadId?: string;
resultsThreadId?: string;
diff --git a/src/components/routines/CalendarEventCard.tsx b/src/components/routines/CalendarEventCard.tsx
index f9c63f4ffb..eb5939b4ed 100644
--- a/src/components/routines/CalendarEventCard.tsx
+++ b/src/components/routines/CalendarEventCard.tsx
@@ -6,7 +6,7 @@ import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
import { MAUS_COLORS, type MausState } from "@/lib/mascot";
import { CALENDAR_SLOT_MINUTES } from "@/lib/routine-calendar";
-import { routineRunLabel } from "@/lib/routine-display";
+import { routineHeldNote, routineRunLabel } from "@/lib/routine-display";
import type { RoutineRunStatus } from "@/lib/routines";
import { intervalLabel, niceTime } from "@/lib/schedule-label";
import type { Bot, Group } from "@/state/store";
@@ -73,7 +73,7 @@ export function CalendarEventCard({
const height = Math.max(16, (previewDuration / 60) * HOUR_HEIGHT);
const fit = cardLayout(height);
const who = isCall ? t(ownerBots.length === 1 ? "routines.botCountOne" : "routines.botCountMany", { count: ownerBots.length }) : room ? room.name : primary?.name;
- const details = [name, niceTime(item.at), who, intervalCadence, paused ? t("routines.pausedSchedule") : statusLabel].filter(Boolean).join(" · ");
+ const details = [name, niceTime(item.at), who, intervalCadence, paused ? (routine && routineHeldNote(routine)) ?? t("routines.pausedSchedule") : statusLabel].filter(Boolean).join(" · ");
const cronHint = routine?.schedule.type === "cron" ? "Open this automation to change its repeating schedule and time zone." : "";
const beginResize = (event: ReactPointerEvent<HTMLDivElement>) => {
diff --git a/src/components/routines/RoutineList.tsx b/src/components/routines/RoutineList.tsx
index 82b83cf48e..ec447cef57 100644
--- a/src/components/routines/RoutineList.tsx
+++ b/src/components/routines/RoutineList.tsx
@@ -3,7 +3,7 @@ import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
import type { Routine, RoutineRun } from "@/lib/routines";
import { scheduleLabel } from "@/lib/schedule-label";
-import { latestRoutineRun, routineDateTime, routineFinished, routineNextLabel, routineRunLabel, routineRunTone, routineScheduleState } from "@/lib/routine-display";
+import { latestRoutineRun, routineDateTime, routineFinished, routineHeldNote, routineNextLabel, routineRunLabel, routineRunTone, routineScheduleState } from "@/lib/routine-display";
import type { Bot } from "@/state/store";
import { Switch } from "../SettingsPrimitives";
@@ -47,6 +47,7 @@ export function RoutineList({ routines, runs, bots, loading, error, onOpen, onLo
{!!routine.failureStreak && <p className="mt-2 text-[12px] text-danger">{t("routines.failureStreak", { count: routine.failureStreak })}</p>}
{routine.weekRuns && <p className="mt-2 text-[12px] text-ink-secondary">{t("routines.weekRuns", routine.weekRuns)}</p>}
{routine.warning && <p className="mt-2 text-[12px] leading-relaxed text-warning">{routine.warning}</p>}
+ {routine.heldFor && <p className="mt-2 text-[12px] leading-relaxed text-ink-secondary">{routineHeldNote(routine)}</p>}
{!!routine.skippedRuns && <p className="mt-2 text-[12px] text-ink-secondary">
{t("routines.skippedRuns", { count: routine.skippedRuns })}
{routine.lastSkippedAt != null && <> · {t("routines.lastSkipped", { date: routineDateTime(routine.lastSkippedAt) })}</>}
diff --git a/src/lib/routine-display.ts b/src/lib/routine-display.ts
index c63278a024..f2402169dc 100644
--- a/src/lib/routine-display.ts
+++ b/src/lib/routine-display.ts
@@ -37,6 +37,11 @@ export function routineScheduleState(routine: Routine): string {
return routine.enabled ? t("routines.activeSchedule") : t("routines.pausedSchedule");
}
+/** Why OpenMausBot keeps this routine paused, while it does (its owner left: shared/routines.ts RoutineHoldCause). */
+export function routineHeldNote(routine: Routine): string | null {
+ return routine.heldFor ? t(`routines.heldFor.${routine.heldFor}`) : null;
+}
+
export function routineNextLabel(routine: Routine): string {
if (!routine.enabled) return routineScheduleState(routine);
return routine.nextRunAt == null ? t("routines.noNextRun") : t("routines.nextRun", { time: routineDateTime(routine.nextRunAt) });
diff --git a/src/locales/en.json b/src/locales/en.json
index 08f96ff4c1..d079533090 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -4442,6 +4442,9 @@
"routines.unread": "Unseen failure",
"routines.activeSchedule": "Active",
"routines.pausedSchedule": "Paused",
+ "routines.heldFor.plan_cancelled": "Paused because the plan was cancelled. Turn it on to keep it running until the plan ends.",
+ "routines.heldFor.no_engine": "Paused because none of your AI accounts is signed in here. It turns back on when you sign in again.",
+ "routines.heldFor.no_connections": "Paused because every connected app and server was removed. It turns back on when you connect one, or turn it on here.",
"routines.toggle": "Run {name} on its schedule",
"routines.paused.close": "Close paused routines",
"routines.finishedSchedule": "Finished schedule",