Skip to content

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

Starter: a routine wakes its paused bot instead of failing (#6866)

Milind Sonida592ee7251a
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.md
index 62ef34c08b..ce6a229e57 100644
--- a/docs/cloud-pro.md
+++ b/docs/cloud-pro.md
@@ -1188,14 +1188,31 @@ provider outage. So on a Cloud home (`server/engine-memory.ts`):
the five starts paused and never pushes out one the person was using: `POST /api/bots`
answers it with `"paused": true`, and the app opens **Keep these awake** with the new bot
chosen in place of the least recently active one that isn't working (`POST /api/starter/awake`).
- A Chief's `create_bot` answers with a `paused` line for the person. A restore or a move into a
- Cloud that never wrote a set down wakes the most recently active. A paused bot's turn answers
- `409` `{"code":"bot_paused"}`, a hand-off to it is refused, a routine or webhook run for it
- fails at once with that line (no conversation is made, and it never wakes a sleeping Cloud),
- and its daily memory upkeep waits. Every bot wakes as soon as the Admin tells the home its new
- plan, with no restart. An older server refuses a sixth bot with `409` `{"code":"bot_limit"}`;
- the app still shows its upgrade popup for that. Every plan holds at most 100 bots
- (`MAX_WORKSPACE_BOTS`), counted on `POST /api/bots`, a package import and a Chief's setup.
+ A Chief's `create_bot` answers with a `paused` line for the person. Places filled without a
+ choice (a restore or a move into a Cloud that never wrote a set down, or a chosen bot deleted) go
+ to the most recently active, except that once the routines are loaded a bot with an enabled
+ routine comes first. A paused bot's turn answers `409` `{"code":"bot_paused"}`, a hand-off to it
+ is refused, and its daily memory upkeep waits. Every bot wakes as soon as the Admin tells the
+ home its new plan, with no restart. An older server refuses a sixth bot with `409`
+ `{"code":"bot_limit"}`; the app still shows its upgrade popup for that. Every plan holds at most
+ 100 bots (`MAX_WORKSPACE_BOTS`), counted on `POST /api/bots`, a package import and a Chief's
+ setup.
+- **A routine gets priority for its bot.** The limit never fails a routine, webhook, app-event or
+ Run now run (`server/host/starter-routine-wake.ts`). When a routine (or a trigger that runs the
+ bot; a webhook that only posts doesn't count) is made or switched on, or runs, for a bot only the
+ limit paused, that bot takes the place of the awake bot that has no enabled routine, has nothing
+ in flight and waits on nobody (no turn, queued message, hand-off, question card, check-back or
+ wait), wasn't paused by the person, and has been idle longest, at least an hour
+ (`STARTER_SWAP_MIN_IDLE_MS`). The swap is written down like a choice, so **Keep these awake**
+ shows it and the person can swap back, and one quiet line in the woken bot's chat says what woke
+ it and which bot was paused for it. A routine bot the person left paused in their own last
+ choice stays paused, so does one no awake bot can make room for, and a run of a switched-off
+ routine swaps nothing: in each case the run still goes ahead in its own conversation (the rest of
+ the bot stays paused, and a person's new message in that conversation meets the paused line
+ too), and the bot's chat says so once. Run now of a switched-off routine, or a person's test of a
+ switched-off trigger, for a bot the limit paused is refused with the paused line. Such a routine's next run counts as due,
+ so a sleeping home is woken for it. The two turns at once below still apply: the run waits for a
+ place like any turn. A bot the person paused (`paused-bots.json`) is never woken by a routine.
- **How much a Starter Cloud runs at once.** Two turns Cloud-wide, and four hand-offs waiting
beyond them; past that a new hand-off is refused (`server/host/starter-caps.ts`).
- **Who goes first.** The gate only changes the order, never how much it lets in. A
diff --git a/server/host/starter-awake.test.ts b/server/host/starter-awake.test.ts
index 10492773dc..d37dd01dd9 100644
--- a/server/host/starter-awake.test.ts
+++ b/server/host/starter-awake.test.ts
@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
-import { createStarterAwake, STARTER_AWAKE_FILE, type AwakeBot } from "./starter-awake.ts";
+import { createStarterAwake, STARTER_AWAKE_FILE, STARTER_SWAP_MIN_IDLE_MS, type AwakeBot } from "./starter-awake.ts";
const dirs: string[] = [];
const dataDir = () => { const dir = mkdtempSync(join(tmpdir(), "starter-awake-")); dirs.push(dir); return dir; };
@@ -93,3 +93,98 @@ describe("which of a Starter Cloud's bots stay awake", () => {
expect(awake.paused()).toEqual([]);
});
});
+
+describe("a routine's bot on a Starter Cloud", () => {
+ /** Seven bots: b2–b6 awake (written down before any routine), b0 and b1 paused; `routines` have an enabled routine and
+ * `busy` are working. */
+ const seven = (dir = dataDir(), routines: string[] = ["b0"], busy: string[] = [], options: { held?: string[]; now?: number } = {}) => {
+ const awake = createStarterAwake({ dataDir: dir, starter: () => true, bots: () => bots(7), ...(options.now === undefined ? {} : { now: () => options.now! }) });
+ awake.paused();
+ awake.useRoutines({ routineBots: () => new Set(routines), busy: (id) => busy.includes(id), held: (id) => (options.held ?? []).includes(id) });
+ return awake;
+ };
+ const written = (dir: string) => JSON.parse(readFileSync(join(dir, STARTER_AWAKE_FILE), "utf8"));
+
+ it("wakes it in place of the awake bot with no routine that was idle longest, written down so the picker and a restart see it", () => {
+ const dir = dataDir(), awake = seven(dir);
+ expect(awake.paused()).toEqual(["b0", "b1"]);
+ expect(awake.wakeForRoutine("b0", true)).toEqual({ kind: "woke", out: "b2" });
+ expect(awake.paused()).toEqual(["b1", "b2"]);
+ expect(written(dir).awake).toEqual(expect.arrayContaining(["b0", "b3", "b4", "b5", "b6"]));
+ expect(createStarterAwake({ dataDir: dir, starter: () => true, bots: () => bots(7) }).paused()).toEqual(["b1", "b2"]);
+ // Awake now: its next run changes nothing.
+ expect(awake.wakeForRoutine("b0", true)).toEqual({ kind: "awake" });
+ });
+
+ it("never pauses a bot that is working, has a routine of its own, or was paused by the person, to make room", () => {
+ const awake = seven(dataDir(), ["b0", "b2"], ["b3"], { held: ["b4"] });
+ expect(awake.wakeForRoutine("b0", true)).toEqual({ kind: "woke", out: "b5" });
+ expect(awake.paused()).toEqual(["b1", "b5"]);
+ });
+
+ it("takes the place only of a bot idle for an hour or more; otherwise the routine runs and its bot stays paused", () => {
+ // b2–b6 were last active at minutes 2–6.
+ const minute = 60_000, hour = STARTER_SWAP_MIN_IDLE_MS;
+ expect(hour).toBe(60 * minute);
+ expect(seven(dataDir(), ["b0"], [], { now: 2 * minute + hour - 1 }).wakeForRoutine("b0", true)).toEqual({ kind: "ran", why: "full", first: true });
+ expect(seven(dataDir(), ["b0"], [], { now: 2 * minute + hour }).wakeForRoutine("b0", true)).toEqual({ kind: "woke", out: "b2" });
+ // b3 is idle long enough, b2 is not counted as it works: b3 goes.
+ expect(seven(dataDir(), ["b0"], ["b2"], { now: 3 * minute + hour }).wakeForRoutine("b0", true)).toEqual({ kind: "woke", out: "b3" });
+ expect(seven(dataDir(), ["b0"], ["b2"], { now: 3 * minute + hour - 1 }).wakeForRoutine("b0", true)).toMatchObject({ kind: "ran", why: "full" });
+ });
+
+ it("runs the routine without changing who is awake when every awake bot has a routine or is working, telling once, across a restart", () => {
+ const dir = dataDir(), all = ["b0", "b1", "b2", "b3", "b4", "b5", "b6"];
+ const awake = seven(dir, all);
+ expect(awake.wakeForRoutine("b0", false)).toEqual({ kind: "ran", why: "full", first: false });
+ expect(awake.wakeForRoutine("b0", true)).toEqual({ kind: "ran", why: "full", first: true });
+ expect(awake.wakeForRoutine("b0", true)).toEqual({ kind: "ran", why: "full", first: false });
+ expect(awake.wakeForRoutine("b1", true)).toEqual({ kind: "ran", why: "full", first: true });
+ expect(seven(dir, all).wakeForRoutine("b0", true)).toEqual({ kind: "ran", why: "full", first: false });
+ expect(awake.paused()).toEqual(["b0", "b1"]);
+ expect(seven(dataDir(), ["b0"], ["b2", "b3", "b4", "b5", "b6"]).wakeForRoutine("b0", true)).toMatchObject({ kind: "ran", why: "full" });
+ });
+
+ it("keeps the person's later choice: a routine bot they leave paused stays paused and its routine still runs", () => {
+ const dir = dataDir(), routines = ["b0"], awake = seven(dir, routines);
+ expect(awake.wakeForRoutine("b0", true)).toEqual({ kind: "woke", out: "b2" });
+ expect(awake.choose(["b2", "b3", "b4", "b5", "b6"])).toEqual({ ok: true });
+ expect(awake.wakeForRoutine("b0", true)).toEqual({ kind: "ran", why: "chosen", first: true });
+ expect(awake.wakeForRoutine("b0", true)).toEqual({ kind: "ran", why: "chosen", first: false });
+ expect(awake.paused()).toEqual(["b0", "b1"]);
+ // Across a restart too.
+ expect(seven(dir, routines).wakeForRoutine("b0", true)).toEqual({ kind: "ran", why: "chosen", first: false });
+ // b1 had no routine when they chose, so a routine made for it later wakes it.
+ routines.push("b1");
+ expect(awake.wakeForRoutine("b1", false)).toEqual({ kind: "woke", out: "b2" });
+ // Choosing b0 again lets it be woken later.
+ expect(awake.choose(["b0", "b1", "b4", "b5", "b6"])).toEqual({ ok: true });
+ expect(written(dir).left).toBeUndefined();
+ });
+
+ it("swaps nothing for a bot with no enabled routine, as when one switched off is run by hand", () => {
+ const awake = seven(dataDir(), []);
+ expect(awake.wakeForRoutine("b0", true)).toEqual({ kind: "ran", why: "off", first: true });
+ expect(awake.paused()).toEqual(["b0", "b1"]);
+ });
+
+ it("gives a freed place, or a first choice, to a paused bot with a routine before a more recently active one", () => {
+ const list = bots(7), awake = createStarterAwake({ dataDir: dataDir(), starter: () => true, bots: () => list });
+ expect(awake.paused()).toEqual(["b0", "b1"]);
+ awake.useRoutines({ routineBots: () => new Set(["b0"]), busy: () => false, held: () => false });
+ list.splice(list.findIndex((bot) => bot.id === "b4"), 1);
+ expect(awake.paused()).toEqual(["b1"]);
+ const fresh = createStarterAwake({ dataDir: dataDir(), starter: () => true, bots: () => bots(7) });
+ fresh.useRoutines({ routineBots: () => new Set(["b0"]), busy: () => false, held: () => false });
+ expect(fresh.paused()).toEqual(["b1", "b2"]);
+ });
+
+ it("changes nothing off Starter, within the limit, or for a bot the limit does not count", () => {
+ const off = createStarterAwake({ dataDir: dataDir(), starter: () => false, bots: () => bots(9) });
+ off.useRoutines({ routineBots: () => new Set(["b0"]), busy: () => false, held: () => false });
+ expect([off.wakeForRoutine("b0", true), off.paused()]).toEqual([{ kind: "awake" }, []]);
+ const few = createStarterAwake({ dataDir: dataDir(), starter: () => true, bots: () => bots(5) });
+ expect(few.wakeForRoutine("b0", true)).toEqual({ kind: "awake" });
+ expect(seven().wakeForRoutine("chief", true)).toEqual({ kind: "awake" });
+ });
+});
diff --git a/server/host/starter-awake.ts b/server/host/starter-awake.ts
index 535ee88d94..4ce1f7e22b 100644
--- a/server/host/starter-awake.ts
+++ b/server/host/starter-awake.ts
@@ -1,7 +1,17 @@
// Which of a Starter Cloud's bots stay awake. Starter makes as many bots as the person likes, but only this many take turns;
// the rest are paused until the person swaps them in or upgrades. The awake set is written down while every bot still fits,
// so a bot made past the limit starts paused and never pushes out one the person was using, and a paused bot that receives
-// a message never does either. A restore or a move into a Cloud that never wrote one down wakes the most recently active.
+// a message never does either. When places are filled (a restore or a move into a Cloud that never wrote a set down, or a
+// chosen bot deleted) they go to the most recently active, except that once the routines are known (useRoutines) a bot
+// with an enabled routine comes first.
+//
+// A routine gets priority for its bot (wakeForRoutine): the limit is the plan's, the routine is the person's, so a routine
+// never fails because its bot is paused for the limit. A bot with an enabled routine (or trigger that runs it) that is
+// paused takes the place of the awake bot that has none, has no work in flight and waits on nobody, was not paused by the
+// person, and was idle longest, at least STARTER_SWAP_MIN_IDLE_MS. That is written down like any choice, so the picker
+// shows it and the person can swap back. A routine bot the person left paused in their own last choice stays paused, and
+// so does one no awake bot can make room for; their routines run anyway without changing who is awake (starter-caps.ts
+// lets the run's own conversation through). A bot the PERSON paused (bot-holds.ts) is another thing: nothing here wakes it.
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { z } from "zod";
@@ -12,11 +22,34 @@ import { writeFileAtomic } from "../atomic.ts";
/** How many bots a Starter Cloud keeps awake, not counting its MausBot or chief of staff. The one number to change. */
export const STARTER_AWAKE_LIMIT = 5;
export const STARTER_AWAKE_FILE = "starter-awake.json";
-const fileSchema = z.object({ v: z.literal(1), awake: z.array(z.string().min(1).max(200)).max(STARTER_AWAKE_LIMIT) });
+/** A routine takes the place only of a bot idle at least this long: one used a moment ago may be about to hear from the
+ * person, whose next message would then meet the picker. */
+export const STARTER_SWAP_MIN_IDLE_MS = 60 * 60_000;
+const botIds = z.array(z.string().min(1).max(200));
+/** `left`: bots with a routine the person left paused in their own last choice. `told`: bots already told once that their
+ * routine ran while they stayed paused. */
+const fileSchema = z.object({
+ v: z.literal(1), awake: botIds.max(STARTER_AWAKE_LIMIT), left: botIds.max(2_000).optional().catch(undefined), told: botIds.max(2_000).optional().catch(undefined),
+});
type CountedBot = Parameters<typeof botsTowardLimit>[0][number];
export type AwakeBot = CountedBot & { id: string; chiefOfStaff?: boolean; createdAt?: number; tasks?: ReadonlyArray<{ updatedAt?: number }> };
+/** What a routine for a bot did to who is awake. `awake`: nothing to do (off Starter, the bot is awake or not counted). `woke`:
+ * it took the place of `out`. `ran`: it stays paused and its routine runs anyway, because the person left it paused (`chosen`),
+ * no awake bot can make room (`full`), or it has no enabled routine, as with Run now on one switched off (`off`). `first`:
+ * the first time that happened to this bot since the person last chose, so the person is told once. */
+export type RoutineWake = { kind: "awake" } | { kind: "woke"; out: string } | { kind: "ran"; why: "chosen" | "full" | "off"; first: boolean };
+
+export interface RoutineSource {
+ /** Bots with at least one enabled routine or trigger. */
+ routineBots(): ReadonlySet<string>;
+ /** The bot has work in flight or waits on the person (starter-routine-wake.ts `workInFlight`). */
+ busy(botId: string): boolean;
+ /** The person paused it (bot-holds.ts): it keeps its place for when they resume it. */
+ held(botId: string): boolean;
+}
+
export interface StarterAwake {
/** How many bots this plan keeps awake; undefined when it keeps them all. */
limit(): number | undefined;
@@ -25,28 +58,35 @@ export interface StarterAwake {
isPaused(botId: string): boolean;
/** Keeps exactly these awake; an error when they are not this Cloud's bots or not as many as the plan keeps. */
choose(ids: readonly string[]): { ok: true } | { ok: false; error: string };
+ /** A routine of this bot runs now (`run`), or was just made or switched on: see the top of this file. */
+ wakeForRoutine(botId: string, run: boolean): RoutineWake;
+ /** Which bots have a routine and which are working; until it is set no bot has one. */
+ useRoutines(source: RoutineSource): void;
}
/** A bot's latest activity: its newest thread's last message, or when it was made. */
const lastActive = (bot: AwakeBot) => Math.max(bot.createdAt ?? 0, ...(bot.tasks ?? []).map((task) => task.updatedAt ?? 0));
-export function createStarterAwake(deps: { dataDir: string; starter(): boolean; bots(): readonly AwakeBot[]; changed?: () => void }): StarterAwake {
+export function createStarterAwake(deps: { dataDir: string; starter(): boolean; bots(): readonly AwakeBot[]; changed?: () => void; now?: () => number }): StarterAwake {
+ const now = deps.now ?? Date.now;
const file = join(deps.dataDir, STARTER_AWAKE_FILE);
- let chosen: string[] | null = null;
+ let chosen: string[] | null = null, left: string[] = [], told: string[] = [], routines: RoutineSource | null = null;
try {
const parsed = fileSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));
- if (parsed.success) chosen = parsed.data.awake;
+ if (parsed.success) ({ awake: chosen, left = [], told = [] } = parsed.data);
} catch {
// none yet, or unreadable: chosen afresh when first needed
}
- const save = (awake: string[]) => {
+ const save = (awake: string[], more: { left?: string[]; told?: string[] } = {}) => {
chosen = awake;
+ ({ left = left, told = told } = more);
try {
- writeFileAtomic(file, `${JSON.stringify({ v: 1, awake })}\n`, { mode: 0o600 });
+ writeFileAtomic(file, `${JSON.stringify({ v: 1, awake, ...(left.length ? { left } : {}), ...(told.length ? { told } : {}) })}\n`, { mode: 0o600 });
} catch (error) {
console.warn(`starter awake: could not save ${file}: ${error instanceof Error ? error.message : String(error)}`);
}
};
+ const routineBots = () => routines?.routineBots() ?? new Set<string>();
/** The bots the limit counts, the chief of staff aside: it hands out the work, so it never sleeps. */
const candidates = () => deps.bots().filter((bot) => botsTowardLimit([bot]) === 1 && !bot.chiefOfStaff);
const limit = () => (deps.starter() ? STARTER_AWAKE_LIMIT : undefined);
@@ -55,12 +95,14 @@ export function createStarterAwake(deps: { dataDir: string; starter(): boolean;
if (most === undefined) return null;
const ids = new Set(bots.map((bot) => bot.id));
if (bots.length <= most) {
- if (chosen?.length !== ids.size || chosen.some((id) => !ids.has(id))) save([...ids]);
+ // Every bot fits, so no choice is in force: a bot made past the limit later starts paused, the others stay awake.
+ if (chosen?.length !== ids.size || chosen.some((id) => !ids.has(id)) || left.length || told.length) save([...ids], { left: [], told: [] });
return null;
}
const kept = (chosen ?? []).filter((id) => ids.has(id));
if (kept.length < most) {
- const rest = bots.filter((bot) => !kept.includes(bot.id)).sort((a, b) => lastActive(b) - lastActive(a));
+ const first = routineBots(), priority = (bot: AwakeBot) => (first.has(bot.id) && !left.includes(bot.id) ? 1 : 0);
+ const rest = bots.filter((bot) => !kept.includes(bot.id)).sort((a, b) => priority(b) - priority(a) || lastActive(b) - lastActive(a));
kept.push(...rest.slice(0, most - kept.length).map((bot) => bot.id));
}
if (kept.length !== chosen?.length || kept.some((id, index) => chosen![index] !== id)) save(kept);
@@ -79,9 +121,29 @@ export function createStarterAwake(deps: { dataDir: string; starter(): boolean;
if (most === undefined) return { ok: false, error: "this Cloud's plan keeps every bot awake" };
if (unique.some((id) => !bots.has(id))) return { ok: false, error: "choose this Cloud's own bots" };
if (unique.length !== Math.min(most, bots.size)) return { ok: false, error: `choose ${Math.min(most, bots.size)} bots to keep awake` };
- save(unique);
+ const first = routineBots();
+ save(unique, { left: [...bots].filter((id) => first.has(id) && !unique.includes(id)), told: [] });
deps.changed?.();
return { ok: true };
},
+ wakeForRoutine(botId, run) {
+ const keep = awake();
+ if (!keep || keep.has(botId) || !candidates().some((bot) => bot.id === botId)) return { kind: "awake" };
+ const first = routineBots(), byId = new Map(candidates().map((bot) => [bot.id, bot]));
+ const out = !first.has(botId) || left.includes(botId) ? undefined
+ : [...keep].filter((id) => !first.has(id) && !routines?.busy(id) && !routines?.held(id) && now() - lastActive(byId.get(id)!) >= STARTER_SWAP_MIN_IDLE_MS)
+ .sort((a, b) => lastActive(byId.get(a)!) - lastActive(byId.get(b)!))[0];
+ if (out !== undefined) {
+ save(chosen!.map((id) => (id === out ? botId : id)));
+ deps.changed?.();
+ return { kind: "woke", out };
+ }
+ const why = !first.has(botId) ? "off" : left.includes(botId) ? "chosen" : "full", once = run && !told.includes(botId);
+ if (once) save(chosen!, { told: [...told, botId] });
+ return { kind: "ran", why, first: once };
+ },
+ useRoutines(source) {
+ routines = source;
+ },
};
}
diff --git a/server/host/starter-caps.test.ts b/server/host/starter-caps.test.ts
index ad881c7abf..3eeb6baf26 100644
--- a/server/host/starter-caps.test.ts
+++ b/server/host/starter-caps.test.ts
@@ -2,13 +2,17 @@ import { describe, expect, it } from "vitest";
import type { StarterAwake } from "./starter-awake.ts";
import { createStarterCaps, STARTER_RUNNING_TURNS, STARTER_WAITING_HANDOFFS } from "./starter-caps.ts";
+import { PAUSED_RUN_ROUTINE_TURNS_ONLY } from "./starter-routine-wake.ts";
-const awake = (paused: string[]): StarterAwake => ({ limit: () => 5, paused: () => paused, isPaused: (id) => paused.includes(id), choose: () => ({ ok: true }) });
+const awake = (paused: string[]): StarterAwake => ({
+ limit: () => 5, paused: () => paused, isPaused: (id) => paused.includes(id), choose: () => ({ ok: true }), wakeForRoutine: () => ({ kind: "awake" }), useRoutines: () => {},
+});
-function caps(options: { starter?: boolean; paused?: string[] } = {}) {
+function caps(options: { starter?: boolean; paused?: string[]; routineThreads?: Record<string, string> } = {}) {
let refused = 0, clock = 1_000;
const made = createStarterCaps({
starter: () => options.starter ?? true, awake: awake(options.paused ?? []), waitsOnOthers: () => false, botName: (id) => id,
+ routineThread: (botId, threadId) => options.routineThreads?.[threadId] === botId,
pausedLine: (language, limit) => `${language ?? "en"}: paused, ${limit} awake`, now: () => clock, refused: () => { refused++; },
});
return { made, refusals: () => refused, advance: (ms: number) => { clock += ms; } };
@@ -39,6 +43,19 @@ describe("how much work a Starter Cloud runs at once", () => {
expect(made.pausedText("awake", "de")).toBeNull();
});
+ it("lets a limit-paused bot's turn through only in the conversation of its own routine run under way", () => {
+ const { made } = caps({ paused: ["sleepy"], routineThreads: { "run-thread": "sleepy", "other-run": "someone" } });
+ expect(made.pausedText("sleepy", "de", "run-thread", true)).toBeNull();
+ // A turn there that is not the routine's own (a person's new message) passes only without option A.
+ expect(made.pausedText("sleepy", "de", "run-thread")).toBe(PAUSED_RUN_ROUTINE_TURNS_ONLY ? "de: paused, 5 awake" : null);
+ expect(made.pausedText("sleepy", "de", "main-thread", true)).toBe("de: paused, 5 awake");
+ expect(made.pausedText("sleepy", "de", "main-thread")).toBe("de: paused, 5 awake");
+ expect(made.pausedText("sleepy", "de", "other-run")).toBe("de: paused, 5 awake");
+ expect(made.pausedText("sleepy", "de")).toBe("de: paused, 5 awake");
+ // Hand-offs to it are still refused: a routine is no way round the limit for other work.
+ expect(made.handoffs.refusal("sleepy", () => 0)).toMatch(/^@sleepy is paused/);
+ });
+
it("tells a bot that made a paused one, without refusing anything or opening the popup", () => {
const { made, refusals } = caps({ paused: ["scout"] });
expect(made.createdPaused("scout")).toMatch(/^@scout was created, and is paused: this Cloud's Starter plan keeps 5 bots awake/);
diff --git a/server/host/starter-caps.ts b/server/host/starter-caps.ts
index 98667a2bc1..84aee04b49 100644
--- a/server/host/starter-caps.ts
+++ b/server/host/starter-caps.ts
@@ -3,6 +3,7 @@
import type { EngineCap } from "../engine-memory.ts";
import type { HandoffLimit } from "../coordinator.ts";
import type { StarterAwake } from "./starter-awake.ts";
+import { PAUSED_RUN_ROUTINE_TURNS_ONLY } from "./starter-routine-wake.ts";
/** Turns a Starter Cloud runs at once, Cloud-wide. */
export const STARTER_RUNNING_TURNS = 2;
@@ -16,8 +17,9 @@ export interface StarterCaps {
handoffs: HandoffLimit;
/** What the app shows: the limits, and when work was last refused for one. Undefined off Starter. */
status(): { running: number; waiting: number; refusedAt?: number; refused?: PlanLimitReason } | undefined;
- /** The words a paused bot's turn is refused with, in the person's language; null when the bot is awake. */
- pausedText(botId: string, language: string | undefined): string | null;
+ /** The words a paused bot's turn is refused with, in the person's language; null when the bot is awake, or when the turn is in
+ * the conversation of a routine run of that bot under way (a routine always runs for a bot only the plan's limit paused). */
+ pausedText(botId: string, language: string | undefined, threadId?: string, routineTurn?: boolean): string | null;
/** What a bot that just made this one is told when it starts paused; null when it is awake. */
createdPaused(botId: string): string | null;
}
@@ -30,6 +32,8 @@ export function createStarterCaps(deps: {
/** Whether a burst's lane runs this thread: it has a limit of its own. */
laneOwned?(threadId: string): boolean;
botName(botId: string): string | undefined;
+ /** This thread is the conversation of a routine run of this bot that is under way. */
+ routineThread?(botId: string, threadId: string): boolean;
/** The paused bot's line in this language. */
pausedLine(language: string | undefined, limit: number): string;
now?: () => number;
@@ -64,8 +68,10 @@ export function createStarterCaps(deps: {
return `@${deps.botName(botId) ?? "The new bot"} was created, and is paused: this Cloud's Starter plan keeps ${deps.awake.limit()} bots awake, so it takes no work yet. `
+ "Tell the person in one line: they can choose which bots stay awake, or upgrade this Cloud to wake them all. Do not hand it work until then.";
},
- pausedText(botId, language) {
- return deps.starter() && deps.awake.isPaused(botId) ? deps.pausedLine(language, deps.awake.limit() ?? 0) : null;
+ pausedText(botId, language, threadId, routineTurn) {
+ const runsThere = threadId !== undefined && deps.routineThread?.(botId, threadId) && (routineTurn === true || !PAUSED_RUN_ROUTINE_TURNS_ONLY);
+ if (!deps.starter() || !deps.awake.isPaused(botId) || runsThere) return null;
+ return deps.pausedLine(language, deps.awake.limit() ?? 0);
},
};
}
diff --git a/server/host/starter-routine-wake.test.ts b/server/host/starter-routine-wake.test.ts
new file mode 100644
index 0000000000..0015d264b2
--- /dev/null
+++ b/server/host/starter-routine-wake.test.ts
@@ -0,0 +1,163 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { createCoordinator, type CoordinatorHost, type HandoffView, type HostTurnResult } from "../coordinator.ts";
+import { Store } from "../store.ts";
+import { createStarterAwake } from "./starter-awake.ts";
+import { createStarterRoutineWake, PAUSED_RUN_ROUTINE_TURNS_ONLY, PAUSED_RUN_SCHEDULES_ONLY, routineBots, workInFlight, type RoutineLike } from "./starter-routine-wake.ts";
+
+const dirs: string[] = [];
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+
+/** Seven bots made a minute apart, Bot 0 first: Bots 2–6 awake on Starter, Bots 0 and 1 paused. */
+function cloud(options: { starter?: boolean; held?: number } = {}) {
+ const dir = mkdtempSync(join(tmpdir(), "starter-routine-wake-")); dirs.push(dir);
+ const store = new Store(() => ({ instanceId: "claude", model: "claude-sonnet-5" }));
+ const made = Array.from({ length: 7 }, (_, n) => store.createBot({ name: `Bot ${n}` }));
+ // Only this test's bots: a Store reads whatever an earlier one in this data folder saved.
+ const bots = () => made.map((bot, n) => ({ ...store.bot(bot.id)!, createdAt: n * 60_000, tasks: [] }));
+ const awake = createStarterAwake({ dataDir: dir, starter: () => options.starter ?? true, bots });
+ awake.paused();
+ const items: RoutineLike[] = [], triggers: RoutineLike[] = [];
+ const wake = createStarterRoutineWake({ awake, store, routines: () => items, triggers: () => triggers, busy: () => false, held: (botId) => options.held !== undefined && made[options.held]?.id === botId });
+ const id = (n: number) => made[n]!.id;
+ const notices = (n: number) => store.messagesFor(made[n]!.threadId).filter((row) => row.kind === "activity").map((row) => row.tool?.name);
+ return { store, awake, wake, items, triggers, id, notices };
+}
+
+describe("a routine's bot on a Starter Cloud", () => {
+ it("wakes the bot when a routine for it is switched on, and says so once in its own chat: which routine, which bot made room", () => {
+ const { awake, wake, items, id, notices } = cloud();
+ expect(awake.paused()).toEqual([id(0), id(1)]);
+ const routine = { botId: id(0), name: "Morning report", enabled: true };
+ items.push(routine);
+ wake.emitted({ kind: "routine", routine });
+ expect(awake.paused()).toEqual([id(1), id(2)]);
+ expect(notices(0)).toEqual(["notice: Woke @Bot 0 for “Morning report”: this Cloud's Starter plan keeps 5 bots awake, so @Bot 2, idle for a while, is paused to make room. To swap them back, send @Bot 2 a message and choose which bots stay awake."]);
+ // Its runs and later saves change nothing more and say nothing more.
+ wake.emitted({ kind: "routine", routine });
+ wake.running(id(0), "Morning report");
+ expect([awake.paused(), notices(0).length]).toEqual([[id(1), id(2)], 1]);
+ });
+
+ it("wakes a bot for its webhook and app trigger too (not with option B), and leaves a switched-off one, a room goal, a webhook that only posts, or another frame alone", () => {
+ const { awake, wake, triggers, id } = cloud();
+ const posts = { botId: id(0), name: "Post it", enabled: true, delivery: "post" };
+ triggers.push(posts);
+ wake.emitted({ kind: "routine", routine: { botId: id(0), name: "Off", enabled: false } });
+ wake.emitted({ kind: "routine", routine: { botId: id(0), name: "Goal", enabled: true, target: "room-goal" } });
+ wake.emitted({ kind: "webhook", webhook: posts });
+ wake.emitted({ kind: "webhook.attempt", webhook: { botId: id(0), name: "Lead", enabled: true } });
+ expect(awake.paused()).toEqual([id(0), id(1)]);
+ const hook = { botId: id(0), name: "New lead", enabled: true }, app = { botId: id(1), name: "New email", enabled: true };
+ triggers.push(hook, app);
+ wake.emitted({ kind: "webhook", webhook: hook });
+ wake.emitted({ kind: "app-trigger", botId: id(1), trigger: app });
+ expect(awake.paused()).toEqual(PAUSED_RUN_SCHEDULES_ONLY ? [id(0), id(1)] : [id(2), id(3)]);
+ });
+
+ it("tells once that a routine ran while its bot stayed paused, when nothing awake can make room", () => {
+ const { awake, wake, items, id, notices } = cloud();
+ for (let n = 0; n < 7; n++) items.push({ botId: id(n), name: `Routine ${n}`, enabled: true });
+ wake.saved(items[0]);
+ expect(notices(0)).toEqual([]);
+ wake.running(id(0), "Routine 0");
+ wake.running(id(0), "Routine 0");
+ expect(notices(0)).toEqual(["notice: @Bot 0 is taking care of “Routine 0” and otherwise stays paused: this Cloud's Starter plan keeps 5 bots awake. Its routines and triggers still run; to chat with it, send it a message and choose which bots stay awake."]);
+ expect(awake.paused()).toEqual([id(0), id(1)]);
+ });
+
+ it("never wakes a bot the person paused, and does nothing off Starter", () => {
+ const held = cloud({ held: 0 });
+ held.items.push({ botId: held.id(0), name: "Report", enabled: true });
+ held.wake.saved(held.items[0]);
+ held.wake.running(held.id(0), "Report");
+ expect([held.awake.paused(), held.notices(0)]).toEqual([[held.id(0), held.id(1)], []]);
+
+ const off = cloud({ starter: false });
+ off.items.push({ botId: off.id(0), name: "Report", enabled: true });
+ off.wake.saved(off.items[0]);
+ off.wake.running(off.id(0), "Report");
+ expect([off.awake.paused(), off.notices(0)]).toEqual([[], []]);
+ });
+
+ it("refuses a run of a bot the limit paused only as the owner's options say, in the paused line", () => {
+ const { wake, items, triggers, id } = cloud();
+ items.push({ id: "off", botId: id(0), name: "Switched off", enabled: false }, { id: "on", botId: id(0), name: "Switched on", enabled: true });
+ triggers.push({ id: "hook", botId: id(1), name: "New lead", enabled: true }, { id: "hook-off", botId: id(1), name: "Old lead", enabled: false });
+ const paused = "Paused: Starter keeps 5 bots awake. Upgrade to wake it, or swap which bots are awake.";
+ // Option A: Run now of a switched-off routine, or a person's test of a switched-off trigger.
+ expect(wake.refusal({ botId: id(0), routineId: "off", manual: true })).toBe(PAUSED_RUN_ROUTINE_TURNS_ONLY ? paused : null);
+ // Option B: any webhook, app-event or wait run.
+ expect(wake.refusal({ botId: id(1), routineId: "hook", manual: false, triggerSource: "webhook" })).toBe(PAUSED_RUN_SCHEDULES_ONLY ? paused : null);
+ expect(wake.refusal({ botId: id(1), routineId: "hook-off", manual: false, byPerson: true, triggerSource: "webhook" }))
+ .toBe(PAUSED_RUN_ROUTINE_TURNS_ONLY || PAUSED_RUN_SCHEDULES_ONLY ? paused : null);
+ // Never: Run now of an enabled routine, a scheduled run, or any run of an awake bot.
+ expect(wake.refusal({ botId: id(0), routineId: "on", manual: true })).toBeNull();
+ expect(wake.refusal({ botId: id(0), routineId: "off", manual: false, triggerSource: "schedule" })).toBeNull();
+ expect(wake.refusal({ botId: id(6), routineId: "off", manual: true })).toBeNull();
+ });
+
+ it("counts only enabled routines and triggers that run the bot itself", () => {
+ expect([...routineBots([{ botId: "a", name: "x", enabled: true }, { botId: "b", name: "x", enabled: false }, { botId: "c", name: "x", enabled: true, target: "room-goal" },
+ { botId: "d", name: "x", enabled: true, target: "bot" }, { botId: "e", name: "x", enabled: true, delivery: "post" }, { botId: "f", name: "x", enabled: true, delivery: "run" }])]).toEqual(["a", "d", "f"]);
+ });
+});
+
+const flush = () => new Promise<void>((resolve) => setImmediate(resolve));
+
+describe("which awake bot a routine may not pause, with the real coordinator", () => {
+ type Ask = "outstandingFor" | "activeDirect" | "parkedFor";
+ /** A coordinator whose turns answer with `answer(node)`, and `busy` reading it through `asks` only (all by default), so each
+ * of its answers is shown to count on its own. */
+ function coordinated(answer: (node: HandoffView) => HostTurnResult) {
+ const host: CoordinatorHost = {
+ validate: vi.fn(() => undefined), busy: vi.fn(() => false), run: vi.fn(async (node: HandoffView) => answer(node)), report: vi.fn(), changed: vi.fn(),
+ names: vi.fn((node: HandoffView) => ({ requester: "Chief", assignee: node.botId })), park: vi.fn(), levelOf: vi.fn(() => ({ level: "ask" as const })), chiefOf: vi.fn(() => false),
+ };
+ const coordinator = createCoordinator({ dataDir: ":memory:", host, log: () => {} });
+ const extra = { checkBacks: new Map<string, number>(), waits: new Map<string, number>() };
+ const busy = (botId: string, asks: Ask[] = ["outstandingFor", "activeDirect", "parkedFor"]) => workInFlight({
+ conversations: (id) => [`${id}-chat`], turnActive: () => false, conversationBusy: () => false,
+ coordinator: {
+ outstandingFor: (threadId) => (asks.includes("outstandingFor") ? coordinator.outstandingFor(threadId) : []),
+ activeDirect: (threadId) => asks.includes("activeDirect") && coordinator.activeDirect(threadId),
+ parkedFor: (id) => (asks.includes("parkedFor") ? coordinator.parkedFor(id) : []),
+ },
+ checkBacks: (_botId, threadId) => extra.checkBacks.get(threadId) ?? 0, waits: (id) => extra.waits.get(id) ?? 0,
+ })(botId);
+ return { coordinator, busy, extra };
+ }
+ const address = (botId: string) => ({ botId, threadId: `${botId}-chat` });
+
+ it("keeps a bot whose own conversation is parked on a question card for the person", () => {
+ const { coordinator, busy } = coordinated(() => ({ ok: true, text: "" }));
+ coordinator.beginTurn({ id: "gen-b", address: address("b"), brief: "Pick a plan", level: "ask", origin: { kind: "user", request: "Pick a plan" } });
+ coordinator.endTurn("gen-b", { ok: true, text: "", cards: { question: "Which option?", ids: ["card-1"] } });
+ expect(coordinator.outstandingFor("b-chat")).toEqual([]);
+ expect([busy("b"), busy("b", ["activeDirect"]), busy("b", ["outstandingFor"]), busy("idle")]).toEqual([true, true, false, false]);
+ });
+
+ it("keeps a bot whose handed-off work waits on the person, and one that waits on work it handed out", async () => {
+ const { coordinator, busy } = coordinated((node) => (node.botId === "b" ? { ok: true, text: "NEEDS INPUT: CSV or Excel?" } : { ok: true, text: "" }));
+ coordinator.beginTurn({ id: "gen-chief", address: address("chief"), brief: "Export", level: "ask", origin: { kind: "user", request: "Export" } });
+ coordinator.enqueue(address("chief"), "gen-chief", undefined, address("b"), "Export the report");
+ coordinator.endTurn("gen-chief", { ok: true, text: "" });
+ coordinator.tick(); await flush();
+ expect(coordinator.parkedFor("b")).toHaveLength(1);
+ expect([busy("b"), busy("b", ["parkedFor"]), busy("chief"), busy("chief", ["outstandingFor"])]).toEqual([true, true, true, true]);
+ expect([busy("b", ["outstandingFor"]), busy("chief", ["parkedFor"])]).toEqual([false, false]);
+ });
+
+ it("keeps a bot with a check-back or a wait, and lets an idle one go", () => {
+ const { busy, extra } = coordinated(() => ({ ok: true, text: "" }));
+ expect(busy("b")).toBe(false);
+ extra.checkBacks.set("b-chat", 1);
+ expect(busy("b")).toBe(true);
+ extra.checkBacks.clear();
+ extra.waits.set("b", 1);
+ expect(busy("b")).toBe(true);
+ });
+});
diff --git a/server/host/starter-routine-wake.ts b/server/host/starter-routine-wake.ts
new file mode 100644
index 0000000000..5e242ed041
--- /dev/null
+++ b/server/host/starter-routine-wake.ts
@@ -0,0 +1,112 @@
+// A routine gets priority for its bot on a Starter Cloud (the rule is at the top of starter-awake.ts). This applies it where a
+// routine's work starts (a run of any kind: schedule, webhook, app event, Run now) and where one is made or switched on (the
+// routine editor, a bot's own tool, an imported bot's routines), so the first run already finds its bot awake. It tells the
+// person once, in one quiet line in the bot's own chat: no card, nothing to answer. A bot the person paused is left alone.
+import type { Coordinator } from "../coordinator.ts";
+import { conversationLanguage, serverLine, type ServerLineKey } from "../server-lines.ts";
+import type { Store } from "../store.ts";
+import type { StarterAwake } from "./starter-awake.ts";
+
+/** The owner's choice (on): while a routine's bot stays paused, only the routine's own turns pass in its conversation, not
+ * a person's new message there (starter-caps.ts), and a run started by hand of a switched-off routine or trigger is refused
+ * with the paused line. */
+export const PAUSED_RUN_ROUTINE_TURNS_ONLY = true;
+
+/** A routine, webhook or app trigger, as much of it as the rule reads. A webhook that only posts its event to a chat or a
+ * room (`delivery: "post"`) starts no turn, so it does not count. */
+export interface RoutineLike { id?: string; botId: string; name: string; enabled: boolean; target?: string; delivery?: string }
+
+/** A run as much as `refusal` reads: a webhook's or app event's (and a wait's follow-up) has trigger source "webhook". */
+export interface RunLike { botId: string; routineId: string; manual: boolean; byPerson?: true; triggerSource?: string }
+
+export interface StarterRoutineWake {
+ /** A run of `name` for this bot starts now. */
+ running(botId: string, name: string): void;
+ /** A routine or trigger was saved: an enabled one for a bot the limit paused wakes it now. */
+ saved(item: RoutineLike | null | undefined): void;
+ /** What the routine, webhook and app-trigger managers emit: a saved one is `saved`. */
+ emitted(payload: { kind?: unknown; routine?: unknown; webhook?: unknown; trigger?: unknown; [other: string]: unknown }): void;
+ /** The paused line a run of a bot the plan's limit paused is refused with under the owner's options; null: it runs. */
+ refusal(run: RunLike): string | null;
+}
+
+/** It starts a turn of the bot itself when it runs: enabled, aimed at the bot (a room goal runs through the room), and not a
+ * webhook that only posts. */
+const runsTheBot = (item: RoutineLike) => item.enabled && (item.target ?? "bot") === "bot" && item.delivery !== "post";
+
+/** Bots whose routines and triggers would run a turn of theirs. */
+export function routineBots(items: Iterable<RoutineLike>): Set<string> {
+ const bots = new Set<string>();
+ for (const item of items) if (runsTheBot(item)) bots.add(item.botId);
+ return bots;
+}
+
+/** The bot has work in flight or waits on the person, so pausing it now would refuse what comes next: a turn or a routine
+ * run, a busy or queued conversation, work it handed out and waits on, a conversation parked on a question card for the
+ * person, work handed to it that waits on the person, a check-back it set, or a wait it keeps. */
+export function workInFlight(deps: {
+ conversations(botId: string): readonly string[];
+ /** A turn of the bot runs now (in a conversation or a room), or its routine run is under way. */
+ turnActive(botId: string): boolean;
+ /** The conversation is busy, or a message waits in its queue. */
+ conversationBusy(botId: string, threadId: string): boolean;
+ coordinator: Pick<Coordinator, "outstandingFor" | "activeDirect" | "parkedFor">;
+ checkBacks(botId: string, threadId: string): number;
+ waits(botId: string): number;
+}): (botId: string) => boolean {
+ return (botId) => deps.turnActive(botId) || deps.coordinator.parkedFor(botId).length > 0 || deps.waits(botId) > 0
+ || deps.conversations(botId).some((threadId) => deps.conversationBusy(botId, threadId) || deps.coordinator.outstandingFor(threadId).length > 0
+ || deps.coordinator.activeDirect(threadId) || deps.checkBacks(botId, threadId) > 0);
+}
+
+export function createStarterRoutineWake(deps: {
+ awake: StarterAwake;
+ /** Every routine there is. */
+ routines(): Iterable<RoutineLike>;
+ /** Every webhook and app trigger there is. */
+ triggers(): Iterable<RoutineLike>;
+ busy(botId: string): boolean;
+ /** The person paused this bot (bot-holds.ts). */
+ held(botId: string): boolean;
+ store: Pick<Store, "bot" | "appendMessage">;
+}): StarterRoutineWake {
+ const counted = (): RoutineLike[] => [...deps.routines(), ...(PAUSED_RUN_SCHEDULES_ONLY ? [] : deps.triggers())];
+ deps.awake.useRoutines({ routineBots: () => routineBots(counted()), busy: deps.busy, held: deps.held });
+ /** One quiet line in the bot's own chat, in its language. */
+ const tell = (botId: string, key: ServerLineKey, params: Record<string, string | number>) => {
+ const bot = deps.store.bot(botId);
+ if (bot) deps.store.appendMessage(bot.threadId, { role: "bot", kind: "activity", tool: { name: `notice: ${serverLine(conversationLanguage(bot.threadId), key, params)}`, ok: true } });
+ };
+ const name = (botId: string) => deps.store.bot(botId)?.name ?? "";
+ const apply = (botId: string, routine: string, run: boolean) => {
+ if (deps.held(botId) || !deps.awake.isPaused(botId)) return;
+ const done = deps.awake.wakeForRoutine(botId, run), limit = deps.awake.limit() ?? 0;
+ // The bot swapped out is never one the person paused (starter-awake.ts), so a message to it opens the picker.
+ if (done.kind === "woke") tell(botId, "server.starter.routineWoke", { bot: name(botId), routine, out: name(done.out), limit });
+ else if (done.kind === "ran" && done.first) tell(botId, "server.starter.routineRanPaused", { bot: name(botId), routine, limit });
+ };
+ const saved = (item: RoutineLike | null | undefined) => {
+ if (item && runsTheBot(item)) apply(item.botId, item.name, false);
+ };
+ return {
+ running: (botId, routine) => apply(botId, routine, true),
+ saved,
+ emitted(payload) {
+ const item = payload.kind === "routine" ? payload.routine : PAUSED_RUN_SCHEDULES_ONLY ? null
+ : payload.kind === "webhook" ? payload.webhook : payload.kind === "app-trigger" ? payload.trigger : null;
+ if (item && typeof item === "object") saved(item as RoutineLike);
+ },
+ refusal(run) {
+ if (deps.held(run.botId) || !deps.awake.isPaused(run.botId)) return null;
+ const bot = deps.store.bot(run.botId), line = () => serverLine(conversationLanguage(bot?.threadId ?? ""), "server.botPaused", { limit: deps.awake.limit() ?? 0 });
+ if (PAUSED_RUN_SCHEDULES_ONLY && run.triggerSource === "webhook") return line();
+ const item = [...deps.routines(), ...deps.triggers()].find((each) => each.id === run.routineId);
+ if (PAUSED_RUN_ROUTINE_TURNS_ONLY && (run.manual || run.byPerson) && !(item && runsTheBot(item))) return line();
+ return null;
+ },
+ };
+}
+
+/** The owner's choice (off): only scheduled runs and Run now get priority; a webhook, app-event or wait follow-up run for a
+ * bot the limit paused is refused with the paused line as before, and webhooks and app triggers wake no bot. */
+export const PAUSED_RUN_SCHEDULES_ONLY = false;
diff --git a/server/index.ts b/server/index.ts
index dfbf9594fe..9cd6f8e983 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -117,7 +117,7 @@ import { vpsLeftBehindNotice, vpsNotChosenReason } from "./cloud-backend.ts";
import * as composio from "./composio.ts"; import { createConnectorListingRoutes } from "./routes/connectors-listing.ts";
import { appSandboxRule, connectorCallFromFrame, connectorRefusalText, connectorScopeRefusalText, connectorUnrecognizedText, evaluateConnectorTools } from "./connector-verdict.ts";
import { signInCardText } from "./connector-card-text.ts";
-import { BOT_HELD_CODE, BOT_PAUSED_CODE } from "../shared/bot-limit.ts"; import { createBotHolds } from "./host/bot-holds.ts"; import { createBotHoldRoutes } from "./routes/bot-holds.ts"; import { createCliLogin } from "./routes/cli-login.ts"; import { createStarterAwake } from "./host/starter-awake.ts"; import { createStarterCaps } from "./host/starter-caps.ts"; import { createStarterAwakeRoutes } from "./routes/starter-awake.ts"; import { chiefOfStaffPrompt, chiefOfStaffSystemPrompt } from "./chief-of-staff.ts"; import { coordinateMessageMax, coordinateTooLong } from "./too-long.ts"; import { chiefAbsentFrom, createChiefRooms } from "./host/chief-rooms.ts"; import { chiefLevel, readTeamRolesWith } from "./chief-level.ts"; import { defaultBotRefusal, ensureDefaultBot } from "./default-bot.ts";
+import { BOT_HELD_CODE, BOT_PAUSED_CODE } from "../shared/bot-limit.ts"; import { createBotHolds } from "./host/bot-holds.ts"; import { createBotHoldRoutes } from "./routes/bot-holds.ts"; import { createCliLogin } from "./routes/cli-login.ts"; import { createStarterAwake } from "./host/starter-awake.ts"; import { createStarterCaps } from "./host/starter-caps.ts"; import { createStarterRoutineWake, workInFlight, type StarterRoutineWake } from "./host/starter-routine-wake.ts"; import { createStarterAwakeRoutes } from "./routes/starter-awake.ts"; import { chiefOfStaffPrompt, chiefOfStaffSystemPrompt } from "./chief-of-staff.ts"; import { coordinateMessageMax, coordinateTooLong } from "./too-long.ts"; import { chiefAbsentFrom, createChiefRooms } from "./host/chief-rooms.ts"; import { chiefLevel, readTeamRolesWith } from "./chief-level.ts"; import { defaultBotRefusal, ensureDefaultBot } from "./default-bot.ts";
import { buildRecall, recallRooms, recallThreadIds, withRecalled } from "./recall.ts";
import { hostTimeZone, takesTurnClock, turnClockLine, withTurnClock } from "./turn-clock.ts";
import { createMemoryUpkeep, dreamConversations, upkeepEnabled } from "./memory-upkeep.ts";
@@ -1662,7 +1662,7 @@ const sessionCredentials = new Map<string, Map<string, { grants: string; token:
const enginePrestart = createEnginePrestart({ adapter: (id) => registry.get(id)?.adapter, credentials: sessionCredentials, allowed: prestartAllowed, blank: (threadId) => store.messagesFor(threadId).length === 0, busy: (botId, threadId) => threadBusy(botId, threadId), approval: (botId, threadId) => { const thread = botForThread(botId, threadId); return thread ? approvalModeFor(thread) : null; },
shape: (botId, threadId) => { const bot = store.projectBotForTask(botId, threadId), task = store.taskByThread(botId, threadId); return bot && task ? JSON.stringify([bot.modelSelection, approvalModeForTurn(bot, false, threadId), task.projectId ?? null, task.cwd?.includes(threadId) ? null : task.cwd ?? null]) : null; },
folder: (botId, threadId) => { const bot = store.projectBotForTask(botId, threadId), instance = bot && registry.get(bot.modelSelection.instanceId); if (!bot || !instance || !supportsWorkspaceFiles(instance.driverKind)) return null; ensureWorkspace(botId, appLanguage()); return ensureTaskWorkspaceWithSkills(botId, threadId, skillsHost.turnImports(bot, threadId, instance)) ?? null; },
- refused: (botId, threadId) => { const bot = store.projectBotForTask(botId, threadId); try { assertWithinBudget(cfg, DATA_DIR); } catch { return true; } return !bot || Boolean(bot.approvalGrant) || providerInstancesChanging.has(bot.modelSelection.instanceId) || limitTakeover.stillSignedOut(bot.modelSelection.instanceId) || botAtThreadCapacity(botId, threadId) || Boolean(botHolds.text(botId, threadLanguage(threadId)) ?? starterCaps.pausedText(botId, threadLanguage(threadId))); } }); onThreadMade(enginePrestart.threadMade);
+ refused: (botId, threadId) => { const bot = store.projectBotForTask(botId, threadId); try { assertWithinBudget(cfg, DATA_DIR); } catch { return true; } return !bot || Boolean(bot.approvalGrant) || providerInstancesChanging.has(bot.modelSelection.instanceId) || limitTakeover.stillSignedOut(bot.modelSelection.instanceId) || botAtThreadCapacity(botId, threadId) || Boolean(botHolds.text(botId, threadLanguage(threadId)) ?? starterCaps.pausedText(botId, threadLanguage(threadId), threadId)); } }); onThreadMade(enginePrestart.threadMade);
function sessionGrants({ generation: _turn, depth: _depth, roomHandoffId: _handoff, skillAuthoring: _skills, ...grants }: Omit<InternalCapability, "orphanExpiresAt">): string {
const thread = botForThread(grants.botId, grants.threadId);
@@ -2790,7 +2790,7 @@ const phones = createPhones({
mint: (botId, turn) => mintInternalCapability({ botId, ...turn, kind: "device", depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 }),
active: (turn) => internalCapabilityIsActive(turn as InternalCapability),
});
-const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterAwake = createStarterAwake({ dataDir: DATA_DIR, starter: () => cloudPlanTier.starter(), bots: () => store.bots, changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterCaps = createStarterCaps({ starter: () => cloudPlanTier.starter(), awake: starterAwake, waitsOnOthers: (threadId) => coordinator.outstandingFor(threadId).length > 0, laneOwned: (threadId) => burst.laneOwned(threadId), botName: (botId) => store.bot(botId)?.name, pausedLine: (language, limit) => serverLine(language, "server.botPaused", { limit }), refused: () => broadcast({ kind: "config", ...configStatus() }) }); engineMemory.useCap(starterCaps.engine); const botHolds = createBotHolds({ dataDir: DATA_DIR, bots: () => store.bots, line: (language, key, params) => serverLine(language, key, params), changed: () => broadcast({ kind: "config", ...configStatus() }) }); let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.
+const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterAwake = createStarterAwake({ dataDir: DATA_DIR, starter: () => cloudPlanTier.starter(), bots: () => store.bots, changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterCaps = createStarterCaps({ starter: () => cloudPlanTier.starter(), awake: starterAwake, waitsOnOthers: (threadId) => coordinator.outstandingFor(threadId).length > 0, laneOwned: (threadId) => burst.laneOwned(threadId), botName: (botId) => store.bot(botId)?.name, routineThread: (botId, threadId) => { const run = activeRoutineRunForThread(threadId); return run?.botId === botId && run.target === "bot"; }, pausedLine: (language, limit) => serverLine(language, "server.botPaused", { limit }), refused: () => broadcast({ kind: "config", ...configStatus() }) }); engineMemory.useCap(starterCaps.engine); let starterRoutineWake: StarterRoutineWake | undefined; /* made beside tieAutomationsToBots, once the routines and triggers are */ const botHolds = createBotHolds({ dataDir: DATA_DIR, bots: () => store.bots, line: (language, key, params) => serverLine(language, key, params), changed: () => broadcast({ kind: "config", ...configStatus() }) }); let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.
const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); teamSlack?.memberLeft(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, perf: perf.health, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE, routines: (cap) => routines?.health(cap) ?? [], schedule: () => routines?.scheduleReport() ?? null,
engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),
connectors: () => emailHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),
@@ -7168,7 +7168,7 @@ async function acceptDirectSend(
throw Object.assign(new Error("the target task no longer exists"), { status: 409 });
}
- if (guardedStart) return guardedStart(currentAtStart);
+ if (guardedStart) return guardedStart(currentAtStart); const planPaused = starterCaps.pausedText(botId, threadLanguage(threadId), threadId, false); if (planPaused) throw Object.assign(new Error(planPaused), { status: 409, code: BOT_PAUSED_CODE }); // a person's message never joins a paused bot's routine run (PAUSED_RUN_ROUTINE_TURNS_ONLY)
const typedStop = await stopOnTypedCommand({ botId, threadId, text, trigger, personPresent, fromApp: Boolean(app), busy: currentAtStart.busy === true, row: { replyToId: replyTo?.id, sendId, sender, ...spokenLineFields(via, callId) }, by: { ...(sender?.id ? { person: sender.id } : {}), admin: admin === true } });
if (typedStop) return typedStop;
@@ -7461,7 +7461,7 @@ async function beginTurn(
workspaceMaintenance.assertAvailable(); moveFreeze.assertTurns();
const profile = store.bot(botId); assertBotHere(profile);
if (!profile) throw Object.assign(new Error("no such bot"), { status: 404 });
- const threadId = opts?.threadId ?? profile.threadId, paused = botHolds.text(botId, threadLanguage(threadId)) ?? starterCaps.pausedText(botId, threadLanguage(threadId)); if (paused) throw Object.assign(new Error(paused), { status: 409, code: botHolds.held(botId) ? BOT_HELD_CODE : BOT_PAUSED_CODE });
+ const threadId = opts?.threadId ?? profile.threadId, paused = botHolds.text(botId, threadLanguage(threadId)) ?? starterCaps.pausedText(botId, threadLanguage(threadId), threadId, opts?.automationSource !== undefined || opts?.cardContinuation === true || opts?.continuesRun === true); if (paused) throw Object.assign(new Error(paused), { status: 409, code: botHolds.held(botId) ? BOT_HELD_CODE : BOT_PAUSED_CODE });
const continuingRoutine = opts?.cardContinuation ? activeRoutineRunForThread(threadId) : null;
if (continuingRoutine) {
const onDispatchError = opts?.onDispatchError;
@@ -8683,14 +8683,14 @@ const automationDestinations = createAutomationDestinations({ store, mainThread:
cloud: CLOUD_HOME ? { owner: CLOUD_OWNER_KEY!, opener: (id, routine) => (routine && teamRoutines.opener(routine)) || routineOpener(id), reportFromOthers: cloudReportFromOthers, opened: (threadId, person) => threadStarters.set(threadId, person), outside: (threadId) => outsideLineage.mark(threadId) } : null });
const routineModelChecks: RoutineModelChecks = { check: (raw) => checkedModelSelection(raw), bot: (botId) => store.bot(botId), engineSwitchNeedsAsk };
routines = new RoutineManager({
- emit: broadcast, limitResetAt: (engine) => limitClock.resetAt(engine), checks: proactive.checks,
+ emit: (payload) => { broadcast(payload); starterRoutineWake?.emitted(payload); }, limitResetAt: (engine) => limitClock.resetAt(engine), checks: proactive.checks,
limitBackup: (botId, scope) => { const bot = store.bot(botId); return quotaSwitchEnabled() ? Boolean(bot && limitTakeover.backups(botId, bot.modelSelection, scope, approvalModeFor(bot)).length) : Boolean(bot && startupBackups(bot, cfg.automaticRecovery).length); },
launchId: DESKTOP_MANAGED && /^[\w-]{1,100}$/.test(process.env.OMB_DESKTOP_LAUNCH_ID ?? "")
? process.env.OMB_DESKTOP_LAUNCH_ID : undefined,
skipStartupRuns: (startedFromSleep = Boolean(CLOUD_HOME) && wokeFromSleep(DATA_DIR)), prepareRun: (run, signal) => runComputers.prepare(run, signal), preparing: RUN_COMPUTER_LINES.waking, // a Cloud home waking from a sleep it was stopped for
hasPendingDelegations: runtimeWorkPending, refusedHandoff: takeRefusedRun, handedOffWorkLive: (threadId) => coordinator.outstandingFor(threadId).length > 0,
routineTurn: (threadId) => directRequestOwners.get(threadId)?.automation !== undefined, personTurn: (threadId) => directRequestOwners.get(threadId)?.origin?.kind === "user", home: { machine: CLOUD_HOME?.machineId, cloud: CLOUD_HOME !== null }, turnLive: (run) => runTurnLive(run, (threadId) => ({ busy: threadBusy(run.botId, threadId), settling: settlingTurns.has(threadId), queued: queuedThreadPosition(run.botId, threadId) !== null, pending: runtimeWorkPending(threadId), parked: store.taskByThread(run.botId, threadId)?.activity === "parked.computer" })),
- botState: unattendedDispatchState, pausedText: (botId) => botHolds.text(botId, threadLanguage(store.bot(botId)?.threadId ?? "")) ?? starterCaps.pausedText(botId, threadLanguage(store.bot(botId)?.threadId ?? "")), held: (botId) => botHolds.held(botId), capSkip: (botId, routineId) => usageCapGate.routineSkip(botId, routineId), capText: (botId, trigger) => usageCapGate.runText(botId, trigger, threadLanguage(store.bot(botId)?.threadId ?? "")),
+ botState: unattendedDispatchState, pausedText: (botId, run) => botHolds.text(botId, threadLanguage(store.bot(botId)?.threadId ?? "")) ?? (run ? starterRoutineWake?.refusal(run) ?? null : null), /* the Starter limit only as the owner's options say: a routine wakes its bot (host/starter-routine-wake.ts) */ held: (botId) => botHolds.held(botId), capSkip: (botId, routineId) => usageCapGate.routineSkip(botId, routineId), capText: (botId, trigger) => usageCapGate.runText(botId, trigger, threadLanguage(store.bot(botId)?.threadId ?? "")),
goalState: (groupId, coordinatorBotId) => {
if (!groupId) return unattendedDispatchState(coordinatorBotId);
const group = store.group(groupId);
@@ -8740,7 +8740,7 @@ routines = new RoutineManager({
}
},
startTurn: async (botId, threadId, prompt, runOn, triggerSource, onDispatchError, runId) => {
- if (!companyShutdown) await startTurn(botId, prompt, { threadId, runOn, automationSource: triggerSource, automationRunId: runId, onDispatchError });
+ if (!companyShutdown) { starterRoutineWake?.running(botId, routines?.runForThread(threadId)?.routineName ?? ""); await startTurn(botId, prompt, { threadId, runOn, automationSource: triggerSource, automationRunId: runId, onDispatchError }); }
},
startGoal: async (groupId, threadId, prompt, coordinatorBotId, runId, _onDispatchError) => {
if (!groupId) {
@@ -9365,7 +9365,7 @@ async function undoAppliedChange(res: ServerResponse, threadId: string, requestI
}
const webhooks = new WebhookManager({
- emit: broadcast,
+ emit: (event) => { broadcast(event); starterRoutineWake?.emitted(event); },
botState: unattendedDispatchState,
enqueue: (input) => { const capped = usageCapGate.refusal(input.botId, input.byPerson === true, threadLanguage(store.bot(input.botId)?.threadId ?? "")); if (capped) throw Object.assign(new Error(capped), { status: 429, code: USAGE_CAP_CODE }); return routines!.enqueueWebhook(input); },
findRun: (webhookId, deliveryId) => routines!.webhookRunReceipt(webhookId, deliveryId),
@@ -9382,10 +9382,10 @@ const webhooks = new WebhookManager({
return store.createTask(trigger.botId, "Updates", false)?.threadId;
}, ...createWebhookRoomPost({ store, cfg, roomTalks }) });
const webhookRequests = new WebhookRequestService({ store, webhooks, botName: (botId) => store.bot(botId)?.name ?? "the bot" }); const botApi = createBotApiHost({ store, manager: botApiManager, actsAsOwner: { available: botApiAsOwnerAvailable, refusal: (auth) => !botApiAsOwnerAvailable() ? "A key can act as the owner only on a server one person uses (no members and at most one admin, named by address), not on a team's Cloud or a shared or hosted workspace." : (sharedWorkspaceFullAccessEnabled() ? auth.scopes.includes("admin") : ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth)) || (auth.kind === "loopback" && auth.trust !== "service" && auth.scopes.includes("admin") && !CLOUD_HOME)) ? null : "Only this server's owner can let a key act as them." }, startTurn, threadBusy, canStart: canAdmitDirectTurn, canConfine: (botId) => registry.get(store.bot(botId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.guestTurns === "confined", discard: (botId, threadId) => { store.deleteTask(botId, threadId); }, included: () => !cloudPlanTier.starter(), opened: (threadId) => { if (CLOUD_OWNER_KEY) threadStarters.set(threadId, CLOUD_OWNER_KEY); }, hooksBaseUrl: () => webhookIngressStatus().baseUrl, manageRefusal: (auth, botId) => auth.scopes.includes("admin") || (CLOUD_TEAM && levelOf(auth, botId) === "edit") ? null : refusalFor(store.bot(botId)?.name ?? "this bot", "edit").error, claimRequest: () => { cloudPower?.arrived("/hooks", {}); moveFreeze.assertTurns(); return workspaceMaintenance.request(); }, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) });
-const appTriggers = createAppTriggerHost({ store, webhooks, webhookBase: () => webhookIngressStatus().baseUrl, routines: () => routines!, botState: unattendedDispatchState, timeZone: routineTimeZone, emit: broadcast, connectionMode: () => composio.connectionMode(cfg),
+const appTriggers = createAppTriggerHost({ store, webhooks, webhookBase: () => webhookIngressStatus().baseUrl, routines: () => routines!, botState: unattendedDispatchState, timeZone: routineTimeZone, emit: (frame) => { broadcast(frame); starterRoutineWake?.emitted(frame); }, connectionMode: () => composio.connectionMode(cfg),
access: composio.brokerAccess, connectedApps: () => composio.connectedServices(cfg), visibleBot: (auth, botId) => visibleTo(viewerFor(auth)).bot(botId),
audit: (row) => appendDecision(DATA_DIR, { ...row, decision: "auto-approved", source: "routine" }) });
-tieAutomationsToBots(store, { routines: routines!, webhooks, apps: appTriggers.manager, waits: botWaits });
+tieAutomationsToBots(store, { routines: routines!, webhooks, apps: appTriggers.manager, waits: botWaits }); starterRoutineWake = createStarterRoutineWake({ awake: starterAwake, store, held: (botId) => botHolds.held(botId), routines: () => routines!.listRoutines(), triggers: () => [...webhooks.list(), ...appTriggers.manager.list()], busy: workInFlight({ conversations: (botId) => store.tasks(botId).map((task) => task.threadId), turnActive: (botId) => botHasActiveTurn(botId) || routines?.activeBotRunForBot(botId) != null, conversationBusy: (botId, threadId) => threadBusy(botId, threadId) || queuedThreadPosition(botId, threadId) !== null, coordinator, checkBacks: (botId, threadId) => checkBacks.list(botId, threadId).length, waits: (botId) => botWaits.list(botId).length }) });
ROUTES.push(appTriggers.routes); ROUTES.unshift(createMoveFreezeRoutes({ freeze: moveFreeze, automationsOff: () => switchAutomationsOff({ routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }), restart: () => { restartRequested = true; gracefulShutdown(); }, busy: createMoveWaits({ bots: () => store.bots, rooms: () => store.groups, answering: (id) => watchdog.answering(id), turn: botHasActiveTurn, runs: () => routines?.listRuns() ?? [], roomWorking: (id) => { const group = store.group(id); return Boolean(group && groupIsWorking(group)); }, handoffs: () => coordinator.active(), exists: (node) => !(!node.parentId && node.groupId ? roomRootProblem(node) : roomHandoffProblem(node)), signingIn: () => providerAuthSessions.active }) }));
ROUTES.push(createPerfDiagnosticsRoutes({ text: perf.text, bots: perf.bots, launch: perf.noteLaunch })); ROUTES.push(createLimitResetRoutes({ clock: limitClock, routines: routines!, requests: routineRequests, engineName, threadEngine: (botId, threadId) => turnSelection(botId, threadId)?.instanceId,
threadTitle: (botId, threadId) => store.bot(botId) && !store.bot(botId)!.hidden ? store.taskByThread(botId, threadId)?.title ?? null : null,
diff --git a/server/memory-order.e2e.test.ts b/server/memory-order.e2e.test.ts
index c96790b970..f3a6368ede 100644
--- a/server/memory-order.e2e.test.ts
+++ b/server/memory-order.e2e.test.ts
@@ -79,6 +79,30 @@ it("on Starter, hand-offs to busy bots start at once: one thread per bot holds o
await expect.poll(() => nodes().map((node: any) => node.status), { timeout: 60_000 }).toEqual(["completed", "completed"]);
}), 180_000);
+it("on Starter, a routine for a bot the plan paused runs: it waits for one of the two places at once and never fails", () => fixture(async (f) => {
+ const bots: any[] = [];
+ for (let at = 0; at < 7; at += 1) bots.push(await f.bot(`Teammate ${at}`));
+ writeFileSync(join(f.dataDir, "test-starter"), "");
+ const config = await f.api("/api/config", undefined, "GET");
+ expect(config.cloudStarter).toBe(true);
+ const asleep = bots.find((bot) => config.pausedBots.includes(bot.id)), [one, two] = bots.filter((bot) => !config.pausedBots.includes(bot.id));
+ expect(asleep).toBeTruthy();
+ const gate = join(f.dataDir, "busy-may-finish");
+ writeFileSync(f.planPath, JSON.stringify({ [one.id]: { gateFile: gate, reply: "Done" }, [two.id]: { gateFile: gate, reply: "Done" }, [asleep.id]: { reply: "Inbox checked" } }));
+ f.free(8 * GB);
+ for (const busy of [one, two]) await f.cli("send", "--bot", busy.id, "--task", busy.activeTaskId, "--text", "Keep busy.");
+ await expect.poll(async () => (await f.api("/api/bots?messages=0", undefined, "GET")).bots.filter((bot: any) => [one.id, two.id].includes(bot.id) && bot.busy).length, { timeout: 30_000 }).toBe(2);
+ // Every awake bot was used moments ago, so nothing is swapped, and the run goes ahead anyway.
+ const routine = (await f.api("/api/routines", { name: "Inbox", prompt: "Check the inbox.", botId: asleep.id, enabled: true, schedule: { type: "interval", everyMinutes: 180, anchorAt: Date.now() + 3 * 3_600_000 } })).routine;
+ const run = (await f.api(`/api/routines/${routine.id}/run`, {})).run;
+ const current = async () => ((await f.api("/api/routines", undefined, "GET")).runs as any[]).find((each) => each.id === run.id);
+ await expect.poll(async () => { const now = await current(); return now?.threadId ? (await f.messages(now.threadId)).some((message: any) => message.tool?.name?.includes("Starter runs 2 tasks at once")) : false; }, { timeout: 30_000 }).toBe(true);
+ expect((await current()).status).toBe("running");
+ writeFileSync(gate, "finish");
+ await expect.poll(async () => (await current())?.status, { timeout: 60_000 }).toBe("completed");
+ expect((await f.api("/api/config", undefined, "GET")).pausedBots).toContain(asleep.id);
+}), 180_000);
+
it("a typed stop ends a turn waiting for memory at once and never starts it, and a stop for an idle bot starts nothing", () => fixture(async (f) => {
const [running, waiting, idle] = [await f.bot("Running"), await f.bot("Waiting"), await f.bot("Idle")];
const gate = join(f.dataDir, "running-may-finish");
diff --git a/server/routes/starter-awake.test.ts b/server/routes/starter-awake.test.ts
index a290d11a9e..4f925ba348 100644
--- a/server/routes/starter-awake.test.ts
+++ b/server/routes/starter-awake.test.ts
@@ -1,9 +1,12 @@
+import { mkdtempSync, rmSync } from "node:fs";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { json, readBody } from "../harness/http.ts";
-import type { StarterAwake } from "../host/starter-awake.ts";
+import { createStarterAwake, type StarterAwake } from "../host/starter-awake.ts";
import { requiredScope } from "../request-auth.ts";
import { createStarterAwakeRoutes, STARTER_AWAKE_PATH } from "./starter-awake.ts";
import { dispatchRoutes } from "./table.ts";
@@ -29,7 +32,7 @@ function fakeAwake() {
const chosen: string[][] = [];
const awake: StarterAwake = {
limit: () => 5, paused: () => ["b5"], isPaused: () => false,
- choose: (ids) => { if (ids.length !== 5) return { ok: false, error: "choose 5 bots to keep awake" }; chosen.push([...ids]); return { ok: true }; },
+ choose: (ids) => { if (ids.length !== 5) return { ok: false, error: "choose 5 bots to keep awake" }; chosen.push([...ids]); return { ok: true }; }, wakeForRoutine: () => ({ kind: "awake" }), useRoutines: () => {},
};
return { awake, chosen };
}
@@ -58,3 +61,25 @@ describe("choosing a Starter Cloud's awake bots", () => {
expect(chosen).toEqual([]);
});
});
+
+describe("the person's choice after a routine woke a bot", () => {
+ it("stands: the routine bot they leave paused stays paused while its routine still runs, and they can wake it again", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "starter-awake-route-"));
+ try {
+ const list = Array.from({ length: 7 }, (_, n) => ({ id: `b${n}`, createdAt: 0, tasks: [{ updatedAt: n * 60_000 }] }));
+ const awake = createStarterAwake({ dataDir: dir, starter: () => true, bots: () => list });
+ awake.paused();
+ awake.useRoutines({ routineBots: () => new Set(["b0"]), busy: () => false, held: () => false });
+ expect(awake.wakeForRoutine("b0", true)).toEqual({ kind: "woke", out: "b2" });
+ const url = await serve(awake);
+ const back = await post(url, { awake: ["b2", "b3", "b4", "b5", "b6"] });
+ expect([back.status, await back.json()]).toEqual([200, { paused: ["b0", "b1"] }]);
+ expect(awake.wakeForRoutine("b0", true)).toMatchObject({ kind: "ran", why: "chosen" });
+ expect(awake.paused()).toEqual(["b0", "b1"]);
+ const again = await post(url, { awake: ["b0", "b3", "b4", "b5", "b6"] });
+ expect([again.status, await again.json()]).toEqual([200, { paused: ["b1", "b2"] }]);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/server/routines.test.ts b/server/routines.test.ts
index 3131d1ac86..bede24d230 100644
--- a/server/routines.test.ts
+++ b/server/routines.test.ts
@@ -4144,9 +4144,11 @@ describe("turning a schedule back on, and a deleted bot's schedules", () => {
expect(h.started).toEqual([]);
});
+ // The host hands this only a bot the person paused (bot-holds.ts): one the Starter limit paused is woken for its routine
+ // (host/starter-routine-wake.ts) and never reaches here.
it("fails a paused bot's runs at once in the person's words, making no conversation and waking nothing for them", async () => {
const h = harness(start);
- let paused: string | null = "Paused: Starter keeps 5 bots awake.";
+ let paused: string | null = "Ada is paused, so it takes no new work.";
h.options.pausedText = (botId) => (botId === "maus-1" ? paused : null);
h.manager.create(once(start + 60_000));
expect(h.manager.nextDueAt()).toBeNull();
@@ -4155,7 +4157,7 @@ describe("turning a schedule back on, and a deleted bot's schedules", () => {
h.manager.enqueueWebhook({ webhookId: "hook", webhookName: "New lead", prompt: "Handle it", botId: "maus-1", runOn: "maus", deliveryId: "d1", receivedAt: start });
await h.manager.tick();
expect([h.taskTitles, h.started]).toEqual([[], []]);
- expect(h.manager.listRuns().map((run) => [run.status, run.error])).toEqual([["failed", "Paused: Starter keeps 5 bots awake."], ["failed", "Paused: Starter keeps 5 bots awake."]]);
+ expect(h.manager.listRuns().map((run) => [run.status, run.error])).toEqual([["failed", "Ada is paused, so it takes no new work."], ["failed", "Ada is paused, so it takes no new work."]]);
paused = null;
h.manager.create(once(start + 120_000));
diff --git a/server/routines.ts b/server/routines.ts
index f1161f5207..365ff056a1 100644
--- a/server/routines.ts
+++ b/server/routines.ts
@@ -240,7 +240,7 @@ export interface RoutineManagerOptions {
/** Every payload must be `{ kind, … }`: the server numbers and replays frames by it. */
emit?: (payload: Record<string, unknown>) => void;
botState: (botId: string) => "ready" | "busy" | "missing";
- /** Why this bot takes no runs now, in the person's words (a Starter Cloud keeps only so many bots awake); null when it does. */ pausedText?: (botId: string) => string | null; /** The person paused this bot: its runs are let go quietly, not failed into To review. */ held?: (botId: string) => boolean; /** A reached usage cap (host/usage-cap-gate.ts): `capSkip` for a scheduled occurrence, which is counted on one `missed` row per cap and period and never switches the routine off; `capText` for a run already queued. */ capSkip?: (botId: string, routineId: string) => { behind: string; resetsAt: number; words(count: number): RoutineLine } | null; capText?: (botId: string, trigger: RoutineRunTrigger) => string | null;
+ /** Why this bot takes no runs now (or not `run`), in the person's words; null when it does. */ pausedText?: (botId: string, run?: RoutineRun) => string | null; /** The person paused this bot: its runs are let go quietly, not failed into To review. */ held?: (botId: string) => boolean; /** A reached usage cap (host/usage-cap-gate.ts): `capSkip` for a scheduled occurrence, which is counted on one `missed` row per cap and period and never switches the routine off; `capText` for a run already queued. */ capSkip?: (botId: string, routineId: string) => { behind: string; resetsAt: number; words(count: number): RoutineLine } | null; capText?: (botId: string, trigger: RoutineRunTrigger) => string | null;
goalState?: (groupId: string | undefined, coordinatorBotId: string) => "ready" | "busy" | "missing";
createTask: (botId: string, title: string, run?: RoutineRun) => { threadId: string } | null;
joinConversation?: (run: RoutineRun) => string | null;
@@ -1139,7 +1139,7 @@ export class RoutineManager {
continue;
}
if (state === "missing") { this.failRun(run, this.missingTargetMessage(run.target)); continue; }
- const paused = run.target === "room-goal" ? null : this.options.pausedText?.(run.botId);
+ const paused = run.target === "room-goal" ? null : this.options.pausedText?.(run.botId, run);
if (!this.ledger.ready(run)) continue; if (this.ledger.startedElsewhere(run)) { const line = codedLine("error", "routines.server.duplicate"); Object.assign(run, line.codes); void this.cancelRun(run.id, line.text); continue; }
if (paused) { if (triggerSource !== "manual" && this.options.held?.(run.botId)) void this.cancelRun(run.id, paused); else this.failRun(run, paused); continue; } const startedBy = run.byPerson ? "manual" : triggerSource, capped = this.options.capText?.(run.botId, startedBy); if (capped) { if (startedBy === "manual") this.failRun(run, capped); else void this.cancelRun(run.id, capped); continue; } const gated = triggerSource === "manual" ? false : this.gate.hold(run); if (gated === true) { if (this.options.preparing && run.attention !== this.options.preparing) { run.attention = this.options.preparing; this.emitRun(run); } continue; } if (gated) { const again = wakeRetry(run, gated, definition, this.now()); if (again === true) { this.saveLater(); this.emitRun(run); } else this.failRun(run, again); continue; }
const startedAt = this.now();
diff --git a/server/starter-bots.e2e.test.ts b/server/starter-bots.e2e.test.ts
index f302a5b8f4..4c8b868d12 100644
--- a/server/starter-bots.e2e.test.ts
+++ b/server/starter-bots.e2e.test.ts
@@ -7,6 +7,7 @@ import { dirname, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import { cloudPairingSignature, cloudRequestSignature } from "./cloud-home.ts";
+import { PAUSED_RUN_ROUTINE_TURNS_ONLY } from "./host/starter-routine-wake.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import { freePortBlock } from "./testing/ports.ts";
@@ -205,6 +206,59 @@ describe("a Starter Cloud's bots, on a real server", () => {
expect(JSON.stringify(setup.body)).not.toContain("bot_limit");
}, 120_000);
+ it("runs a paused bot's routine without pausing a bot used within the hour, says so once, and never wakes a bot the person paused", async () => {
+ await starter();
+ await cloud.fill(5);
+ const sixth = made(await cloud.create("Sixth")).bot;
+ expect(await paused()).toEqual([sixth.id]);
+ const notices = async () => ((await cloud.api("GET", `/api/threads/${sixth.threadId}/messages?limit=200`)).body.messages as any[])
+ .filter((message) => message.kind === "activity" && String(message.tool?.name).startsWith("notice: ")).map((message) => message.tool.name as string);
+ const runs = async () => (await cloud.api("GET", "/api/routines")).body.runs as any[];
+
+ // Made for the paused sixth bot: every awake bot was made moments ago, so none gives up its place and nothing is said yet.
+ const created = await cloud.api("POST", "/api/routines", { name: "Every three hours", prompt: "Check the inbox.", botId: sixth.id, enabled: true,
+ schedule: { type: "interval", everyMinutes: 180, anchorAt: Date.now() + 3 * 3_600_000 } });
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ expect(await paused()).toEqual([sixth.id]);
+ expect(await notices()).toEqual([]);
+
+ // Its scheduled run still runs, in its own conversation, told once.
+ const soon = await cloud.api("POST", "/api/routines", { name: "In a moment", prompt: "Check the inbox.", botId: sixth.id, enabled: true, schedule: { type: "once", at: Date.now() + 2_000 } });
+ expect(soon.status, JSON.stringify(soon.body)).toBe(201);
+ await expect.poll(async () => (await runs()).find((run) => run.routineId === soon.body.routine.id)?.status, { timeout: 30_000 }).toBe("running");
+ expect(await paused()).toEqual([sixth.id]);
+ expect(await notices()).toEqual([expect.stringMatching(/^notice: @Sixth is taking care of “In a moment” and otherwise stays paused: this Cloud's Starter plan keeps 5 bots awake\./)]);
+ // A message to it in its own chat is still refused for the plan; one in the run's conversation joins the run, unless option A.
+ expect(await cloud.api("POST", `/api/bots/${sixth.id}/messages`, { text: "Hello", threadId: sixth.threadId })).toMatchObject({ status: 409, body: { code: "bot_paused" } });
+ const runThread = (await runs()).find((run) => run.routineId === soon.body.routine.id).threadId;
+ expect((await cloud.api("POST", `/api/bots/${sixth.id}/messages`, { text: "Also this", threadId: runThread })).status).toBe(PAUSED_RUN_ROUTINE_TURNS_ONLY ? 409 : 202);
+ cloud.finishTurn();
+ await expect.poll(async () => (await runs()).find((run) => run.routineId === soon.body.routine.id)?.status, { timeout: 30_000 }).toBe("completed");
+ // And Run now, with nothing more said.
+ const started = await cloud.api("POST", `/api/routines/${created.body.routine.id}/run`);
+ expect(started.status, JSON.stringify(started.body)).toBe(201);
+ await expect.poll(async () => (await runs()).find((run) => run.id === started.body.run.id)?.status, { timeout: 30_000 }).toBe("completed");
+ expect(await paused()).toEqual([sixth.id]);
+ expect(await notices()).toHaveLength(1);
+
+ // Run now of a switched-off routine: no swap, and it runs; with option A it is refused in the paused line, no conversation made.
+ const off = await cloud.api("POST", "/api/routines", { name: "Switched off", prompt: "Check the inbox.", botId: sixth.id, enabled: false,
+ schedule: { type: "interval", everyMinutes: 180, anchorAt: Date.now() + 3 * 3_600_000 } });
+ const offRun = await cloud.api("POST", `/api/routines/${off.body.routine.id}/run`);
+ await expect.poll(async () => (await runs()).find((run) => run.id === offRun.body.run.id)?.status, { timeout: 30_000 }).toBe(PAUSED_RUN_ROUTINE_TURNS_ONLY ? "failed" : "completed");
+ const offDone = (await runs()).find((run) => run.id === offRun.body.run.id);
+ if (PAUSED_RUN_ROUTINE_TURNS_ONLY) expect([offDone.error, offDone.threadId]).toEqual([expect.stringMatching(/^Paused: Starter keeps 5 bots awake/), undefined]);
+ expect(await paused()).toEqual([sixth.id]);
+
+ // A bot the person paused is not woken by its routine, and a run they start by hand fails in the pause's words.
+ expect((await cloud.api("POST", "/api/paused", { kind: "bot", id: sixth.id, paused: true })).status).toBe(200);
+ const held = await cloud.api("POST", `/api/routines/${created.body.routine.id}/run`);
+ await expect.poll(async () => (await runs()).find((run) => run.id === held.body.run.id)?.status, { timeout: 30_000 }).toBe("failed");
+ expect((await runs()).find((run) => run.id === held.body.run.id)?.error).toMatch(/^Sixth is paused, so it takes no new work/);
+ expect(await paused()).toEqual([sixth.id]);
+ expect(await notices()).toHaveLength(1);
+ }, 180_000);
+
it("takes a move and a restore past five, and keeps the bots that were awake awake", async () => {
await starter();
await cloud.fill(5);
diff --git a/src/components/routines/RoutineList.tsx b/src/components/routines/RoutineList.tsx
index c09d927aea..50b82951b4 100644
--- a/src/components/routines/RoutineList.tsx
+++ b/src/components/routines/RoutineList.tsx
@@ -57,8 +57,8 @@ export function RoutineList({ routines, runs, bots, pausedBots, heldBots, loadin
{!!routine.noStartStreak && <p className="mt-2 text-[12px] leading-relaxed text-warning" data-routine-no-start="">{t("routines.noStartStreak", { count: routine.noStartStreak })}</p>}
{routine.weekRuns && <p className="mt-2 text-[12px] text-ink-secondary">{t(routine.weekRuns.total === 1 ? "routines.weekRunsOne" : "routines.weekRuns", routine.weekRuns)}</p>}
{routine.warning && <p className="mt-2 text-[12px] leading-relaxed text-warning">{routine.warning}</p>}
- {routine.enabled && pausedBots?.includes(routine.botId) && <p className="mt-2 text-[12px] leading-relaxed text-warning" data-routine-bot-paused="">
- {t("routines.botPaused")}{" "}
+ {routine.enabled && pausedBots?.includes(routine.botId) && !heldBots?.includes(routine.botId) && <p className="mt-2 text-[12px] leading-relaxed text-warning" data-routine-bot-paused="">
+ {t("routines.botPausedRuns")}{" "}
<button type="button" className="cursor-pointer text-accent hover:underline" onClick={() => showBotLimit("paused")}>{t("routines.botPausedSwap")}</button>
</p>}
{routine.enabled && heldBots?.includes(routine.botId) && <p className="mt-2 text-[12px] leading-relaxed text-warning" data-routine-bot-held="">{t("routines.botHeld")}</p>}
diff --git a/src/components/routines/RoutineViews.test.ts b/src/components/routines/RoutineViews.test.ts
index 538ab393b9..b7d60ddc4e 100644
--- a/src/components/routines/RoutineViews.test.ts
+++ b/src/components/routines/RoutineViews.test.ts
@@ -19,10 +19,13 @@ function list(props: Partial<Parameters<typeof RoutineList>[0]> = {}) {
afterEach(() => vi.useRealTimers());
describe("routine list", () => {
- it("warns on an enabled routine whose bot is paused, with a way to swap it in", () => {
+ it("says an enabled routine whose bot the plan paused still runs, with a way to swap it in, and only the person's pause when both are", () => {
const paused = list({ pausedBots: ["scout"] });
- expect(paused).toContain("bot is paused on this plan, so it won&#x27;t run.");
+ expect(paused).toContain("bot is paused on this plan, but the routine still runs.");
expect(paused).toContain("Swap awake bots");
+ const both = list({ pausedBots: ["scout"], heldBots: ["scout"] });
+ expect(both).not.toContain("still runs");
+ expect(both).toContain("won’t run until the bot is resumed");
expect(list({ pausedBots: ["scout"], routines: [{ ...routine, enabled: false }] })).not.toContain("Swap awake bots");
expect(list({ pausedBots: ["other"] })).not.toContain("Swap awake bots");
expect(list()).not.toContain("Swap awake bots");
diff --git a/src/locales/de.json b/src/locales/de.json
index 5d4d7af5fb..208ce72436 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -224,6 +224,8 @@
"server.room.turnsStill": "Wartet noch: Dieser Server führt {limit} Aufgaben gleichzeitig aus. Davor in der Reihe: {ahead}.",
"chat.notice.outOfProcesses": "Es ist kein Platz, um ein weiteres Programm zu starten ({code}), deshalb konnte diese Aufgabe nicht laufen. An die KI wurde nichts gesendet. Sie startet von selbst neu, sobald Platz ist.",
"server.botPaused": "Pausiert: Starter hält {limit} Bots wach. Führe ein Upgrade durch, um ihn zu wecken, oder tausche, welche Bots wach sind.",
+ "server.starter.routineRanPaused": "@{bot} kümmert sich um „{routine}“ und bleibt sonst pausiert: Starter hält {limit} Bots wach. Seine Routinen und Auslöser laufen trotzdem; um mit ihm zu chatten, schreib ihm eine Nachricht und wähle, welche Bots wach bleiben.",
+ "server.starter.routineWoke": "@{bot} wurde für „{routine}“ geweckt: Starter hält {limit} Bots wach, deshalb ist @{out}, der eine Weile nichts zu tun hatte, jetzt pausiert. Um das rückgängig zu machen, schreib @{out} eine Nachricht und wähle, welche Bots wach bleiben.",
"server.botHeld": "{bot} ist pausiert und nimmt keine neue Arbeit an. Setze ihn über sein Menü in der Seitenleiste fort.",
"server.botHeldDepartment": "{bot} ist mit der Abteilung {department} pausiert und nimmt keine neue Arbeit an. Setze die Abteilung über ihr Menü in der Seitenleiste fort.",
"server.botHeldAll": "Alle Bots sind pausiert, daher nimmt {bot} keine neue Arbeit an. Setze alle Bots über das Menü eines beliebigen Bots in der Seitenleiste fort.",
diff --git a/src/locales/en.json b/src/locales/en.json
index 016fc4938b..0d60fe3e37 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -362,6 +362,8 @@
"server.room.turns": "Waiting for a turn: this server runs {limit} tasks at once. Ahead of this one: {ahead}. It starts by itself when one finishes.",
"server.room.turnsStill": "Still waiting: this server runs {limit} tasks at once. Ahead of this one: {ahead}.",
"server.botPaused": "Paused: Starter keeps {limit} bots awake. Upgrade to wake it, or swap which bots are awake.",
+ "server.starter.routineRanPaused": "@{bot} is taking care of “{routine}” and otherwise stays paused: this Cloud's Starter plan keeps {limit} bots awake. Its routines and triggers still run; to chat with it, send it a message and choose which bots stay awake.",
+ "server.starter.routineWoke": "Woke @{bot} for “{routine}”: this Cloud's Starter plan keeps {limit} bots awake, so @{out}, idle for a while, is paused to make room. To swap them back, send @{out} a message and choose which bots stay awake.",
"server.botHeld": "{bot} is paused, so it takes no new work. Resume it from its menu in the sidebar.",
"server.botHeldDepartment": "{bot} is paused with the {department} department, so it takes no new work. Resume the department from its menu in the sidebar.",
"server.botHeldAll": "Every bot is paused, so {bot} takes no new work. Resume every bot from any bot’s menu in the sidebar.",
@@ -5406,7 +5408,7 @@
"computer.tab.computer": "Screen",
"computer.tab.routines": "Routines",
"routines.list": "Routine list",
- "routines.botPaused": "This routine's bot is paused on this plan, so it won't run.",
+ "routines.botPausedRuns": "This routine's bot is paused on this plan, but the routine still runs.",
"routines.botPausedSwap": "Swap awake bots",
"routines.logs": "Run logs",
"routines.results.label": "Post results to",
diff --git a/src/locales/es.json b/src/locales/es.json
index 7df3986679..be0751683c 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -206,6 +206,8 @@
"server.planTurns.wait": "Esperando turno: Starter ejecuta {limit} tareas a la vez en esta Cloud. Delante de esta: {ahead}. Empieza sola cuando termine una, y un plan mayor ejecuta más a la vez.",
"server.planTurns.still": "Sigue esperando: Starter ejecuta {limit} tareas a la vez. Delante de esta: {ahead}.",
"server.botPaused": "En pausa: Starter mantiene {limit} bots despiertos. Mejora el plan para despertarlo o cambia qué bots están despiertos.",
+ "server.starter.routineRanPaused": "@{bot} se está ocupando de “{routine}” y, por lo demás, sigue en pausa: Starter mantiene {limit} bots despiertos. Sus rutinas y disparadores se siguen ejecutando; para chatear con él, envíale un mensaje y elige qué bots siguen despiertos.",
+ "server.starter.routineWoke": "Se despertó a @{bot} para “{routine}”: Starter mantiene {limit} bots despiertos, así que @{out}, inactivo desde hace un rato, quedó en pausa para hacer sitio. Para revertirlo, envía un mensaje a @{out} y elige qué bots siguen despiertos.",
"server.teammates.queued.thread": "{bot} aún no ha empezado esto: sigue en marcha un turno anterior de ese hilo.",
"server.teammates.queued.slots": "{bot} aún no ha empezado esto: ya ejecuta {busy} de {limit} hilos a la vez.",
"server.teammates.queued.room": "{bot} aún no ha empezado esto: está terminando un turno en una sala.",
@@ -3715,6 +3717,8 @@
"computer.botSettings": "Ajustes del bot",
"computer.tab.computer": "Pantalla",
"computer.tab.routines": "Rutinas",
+ "routines.botPausedRuns": "El bot de esta rutina está en pausa en este plan, pero la rutina se sigue ejecutando.",
+ "routines.botPausedSwap": "Cambiar bots despiertos",
"routines.list": "Lista de rutinas",
"routines.logs": "Registros de ejecución",
"routines.results.label": "Publicar los resultados en",
diff --git a/src/locales/fr.json b/src/locales/fr.json
index 5d55376666..e9caa3fb04 100644
--- a/src/locales/fr.json
+++ b/src/locales/fr.json
@@ -176,6 +176,8 @@
"server.planTurns.wait": "En attente d'une place : Starter exécute {limit} tâches à la fois sur ce Cloud. Avant celle-ci : {ahead}. Elle démarre d'elle-même dès qu'une se termine, et un plan supérieur en exécute davantage en même temps.",
"server.planTurns.still": "Toujours en attente : Starter exécute {limit} tâches à la fois. Avant celle-ci : {ahead}.",
"server.botPaused": "En pause : Starter garde {limit} bots éveillés. Passez à un plan supérieur pour le réveiller, ou changez les bots éveillés.",
+ "server.starter.routineRanPaused": "@{bot} s'occupe de « {routine} » et reste en pause pour le reste : Starter garde {limit} bots éveillés. Ses routines et déclencheurs continuent de s'exécuter ; pour discuter avec lui, envoyez-lui un message et choisissez les bots qui restent éveillés.",
+ "server.starter.routineWoke": "@{bot} a été réveillé pour « {routine} » : Starter garde {limit} bots éveillés, donc @{out}, inactif depuis un moment, est mis en pause pour faire de la place. Pour revenir en arrière, envoyez un message à @{out} et choisissez les bots qui restent éveillés.",
"server.teammates.queued.thread": "{bot} n'a pas encore commencé : un tour précédent de ce fil est toujours en cours.",
"server.teammates.queued.slots": "{bot} n'a pas encore commencé : {busy} fils sur {limit} sont déjà en cours en même temps.",
"server.teammates.queued.room": "{bot} n'a pas encore commencé : il termine un tour dans un salon.",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index a4ded5b00c..221bc9c971 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -343,6 +343,8 @@
"server.room.turns": "Aguardando a vez: este servidor roda {limit} tarefas ao mesmo tempo. À frente desta: {ahead}. Ela começa sozinha quando uma terminar.",
"server.room.turnsStill": "Ainda aguardando: este servidor roda {limit} tarefas ao mesmo tempo. À frente desta: {ahead}.",
"server.botPaused": "Pausado: o Starter mantém {limit} bots ativos. Faça upgrade para ativá-lo ou troque quais bots ficam ativos.",
+ "server.starter.routineRanPaused": "@{bot} está cuidando de “{routine}” e, fora isso, continua pausado: o plano Starter mantém {limit} bots ativos. As rotinas e gatilhos dele continuam rodando; para conversar com ele, mande uma mensagem e escolha quais bots ficam ativos.",
+ "server.starter.routineWoke": "@{bot} foi ativado para “{routine}”: o plano Starter mantém {limit} bots ativos, então @{out}, parado há um tempo, foi pausado para abrir espaço. Para trocar de volta, mande uma mensagem para @{out} e escolha quais bots ficam ativos.",
"server.botHeld": "{bot} está pausado e não recebe trabalho novo. Retome-o pelo menu dele na barra lateral.",
"server.botHeldDepartment": "{bot} está pausado junto com o departamento {department} e não recebe trabalho novo. Retome o departamento pelo menu dele na barra lateral.",
"server.botHeldAll": "Todos os bots estão pausados, então {bot} não recebe trabalho novo. Retome todos os bots pelo menu de qualquer bot na barra lateral.",
@@ -5075,7 +5077,7 @@
"computer.tab.computer": "Tela",
"computer.tab.routines": "Rotinas",
"routines.list": "Lista de rotinas",
- "routines.botPaused": "O bot desta rotina está pausado neste plano, então ela não será executada.",
+ "routines.botPausedRuns": "O bot desta rotina está pausado neste plano, mas a rotina continua rodando.",
"routines.botPausedSwap": "Trocar bots ativos",
"routines.logs": "Registros",
"routines.results.label": "Publicar resultados em",
diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.json
index 466d357f44..8f89332a92 100644
--- a/src/locales/source-hashes.json
+++ b/src/locales/source-hashes.json
@@ -35924,7 +35924,6 @@
"claudeBedrock.remove": "e6a3c4a1250a6ad3f10faa22333e5e50a6ba78e5b28a3b26f5743d9f8c7ede93",
"claudeBedrock.removeBody": "7ca132baf56134c772738b9a81274af75b428e59eaf1e341bc56770bfa0a0995",
"claudeBedrock.failed": "59d511f3c8496b794144a30f070e9a92edbf3f7c105417bc6f5949862665aabc",
- "routines.botPaused": "8f5a4c5ab705adfc02f0a40527baccd6d91233ba09c059974e3898910bfde301",
"routines.botPausedSwap": "f3ba4b0a76a16a26a75be5dabbe0b1440b416a83983f17a79eeb937d5b0e42d1",
"teamSide.label": "ce4b859f95a1a314dab4720bf6e64b63e39e0d2f89caeb02f08b9b441d3085d1",
"teamSide.me": "3a4b4df869c76a24361c80762c22cff078f382dbf16f54975415de1bb4ed1d82",