Skip to content

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

Merge main into train/nov27-f2a

milind-soni0b1745a951ec
diff --cc server/host/chief-notices-retry.test.ts
index 67d22d85d4,c2a59cc57f..39a9f17650
--- a/server/host/chief-notices-retry.test.ts
+++ b/server/host/chief-notices-retry.test.ts
@@@ -7,8 -7,7 +7,8 @@@ import { memoryStopText } from "../engi
import { AUTO_RETRY_LEAD, RETRY_BLOCKED } from "../incidents.ts";
import { FROZE_BROWSING } from "../memory-freeze-restart.ts";
import type { RoutineFailureFacts } from "../routine-recovery.ts";
+import { _queuedCount, cancelSteeredMessage, drainSteeredMessages, queuedSteerSnapshot } from "../steer-queue.ts";
- import { createChiefNotices, MEMORY_RETRY_MS, MEMORY_RETRY_TEXT, ROOM_RETRY_TEXT, SERVER_MEMORY_RETRY_TEXT, type ChiefNoticeDeps } from "./chief-notices.ts";
+ import { createChiefNotices, failedRequester, MEMORY_RETRY_MS, retriedMessage, MEMORY_RETRY_TEXT, ROOM_RETRY_TEXT, SERVER_MEMORY_RETRY_TEXT, type ChiefNoticeDeps } from "./chief-notices.ts";
function fixture(over: Partial<ChiefNoticeDeps> = {}) {
const bots = [
@@@ -70,74 -69,6 +70,74 @@@ describe("why a Chief's retry of a team
});
});
+describe("a Chief's retry of a teammate's busy thread", () => {
+ type Drained = { botId: string; threadId: string; prompt: string; unattended: boolean; peerAsk: unknown };
+ function drain(f: ReturnType<typeof fixture>, drained: Drained[]): void {
+ drainSteeredMessages(
+ { bot: (id: string) => f.store.bot(id) ?? null, appendMessage: (threadId: string, row: never) => f.store.appendMessage(threadId, row) } as never,
+ (botId, threadId, prompt, _message, _ids, unattended, head) => { drained.push({ botId, threadId, prompt, unattended, peerAsk: head.peerAsk }); },
+ );
+ }
+
+ it("queues the retry while its bot is mid-turn elsewhere, and the queue starts it when the bot frees up", async () => {
+ const f = fixture({ groupTurnActive: (botId) => botId === "ada" });
+ const queued = await f.notices.retryThread({ chief: f.chief as never, bot: f.ada as never, threadId: "ada-job", unattended: true, note: "The service was down." });
- expect(queued).toEqual({ queued: true });
++ expect(queued).toBe("queued");
+ expect(f.startTurn).not.toHaveBeenCalled();
+ expect(_queuedCount("ada-job")).toBe(1);
+ const drained: Drained[] = [];
+ drain(f, drained);
+ expect(drained).toEqual([{ botId: "ada", threadId: "ada-job",
+ prompt: expect.stringContaining("requested by Clive, your Chief of Staff, after this thread's last run stopped. Note from Clive: The service was down."),
+ unattended: true, peerAsk: { botId: "chief", name: "Clive", unattended: true } }]);
+ expect(drained[0]!.prompt).toContain("Continue the request above from where it stopped and finish it.");
+ expect(_queuedCount("ada-job")).toBe(0);
+ });
+
+ it("queues with the capacity reason at its bot's turn limit, answering queued rather than failed", async () => {
+ const f = fixture({ botAtThreadCapacity: () => true });
+ const queued = await f.notices.retryThread({ chief: f.chief as never, bot: f.ada as never, threadId: "ada-job", unattended: false });
- expect(queued).toEqual({ queued: true });
++ expect(queued).toBe("queued");
+ const snapshot = queuedSteerSnapshot(() => true);
+ expect(snapshot["ada-job"]?.[0]).toMatchObject({ reason: "capacity", text: expect.stringContaining("requested by Clive") });
+ cancelSteeredMessage("ada", snapshot["ada-job"]![0]!.queueId, "ada-job");
+ });
+
+ it("still refuses a thread that runs, shuts down or already waits, even while its bot is at its turn limit", async () => {
+ for (const [over, refusal] of [
+ [{ threadBusy: () => true }, RETRY_BLOCKED.running],
+ [{ threadBusy: () => true, threadSettling: () => true }, RETRY_BLOCKED.settling],
+ [{ threadQueued: () => true }, RETRY_BLOCKED.queued],
+ ] as const) {
+ const f = fixture({ ...over, botAtThreadCapacity: () => true, groupTurnActive: () => true });
+ await expect(f.notices.retryThread({ chief: f.chief as never, bot: f.ada as never, threadId: "ada-job", unattended: true })).rejects.toThrow(refusal);
+ expect(f.startTurn).not.toHaveBeenCalled();
+ }
+ expect(_queuedCount("ada-job")).toBe(0);
+ });
+
+ it("starts OpenMausBot's own retry at once, never from the queue", async () => {
+ const f = fixture({ botAtThreadCapacity: () => true });
+ await f.notices.retryThread({ chief: f.chief as never, bot: f.ada as never, threadId: "ada-job", unattended: true, automatic: true });
+ expect(f.startTurn).toHaveBeenCalledTimes(1);
+ expect(_queuedCount("ada-job")).toBe(0);
+ });
+
+ it("still refuses a thread that finished a run since it was reported, even at its bot's turn limit", async () => {
+ vi.useFakeTimers({ now: 1_000 });
+ try {
+ const f = fixture({ botAtThreadCapacity: () => true });
+ f.notices.reportIncident({ kind: "stalled", bot: f.ada as never, threadId: "ada-job", detail: "no activity for 20 minutes" });
+ vi.setSystemTime(2_000);
+ f.store.appendMessage("ada-job", { role: "bot", kind: "text", text: "Done.", turnSucceeded: true });
+ await expect(f.notices.retryThread({ chief: f.chief as never, bot: f.ada as never, threadId: "ada-job", unattended: true })).rejects.toThrow(/finished a run since it was reported/);
+ expect(_queuedCount("ada-job")).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
const CRASH = "claude exited 3 before result: fake-claude: simulated crash before result";
const DENIED = "One or more tool operations failed or were denied. See the tool results; the final response is not an execution receipt.";
const RETRIED = "OpenMausBot already retried this run once by itself; the failure above is how that retry ended.";
diff --cc server/host/chief-notices.ts
index 103f2bbc70,3e8ea16685..026bd8ed26
--- a/server/host/chief-notices.ts
+++ b/server/host/chief-notices.ts
@@@ -120,24 -141,30 +141,38 @@@ export function createChiefNotices(deps
}
/** The one way a teammate's stopped thread runs again: a Chief's retry_thread and OpenMausBot's automatic retry both
- * start it here, after the same refusal checks. Throws the refusal, or why the start failed. */
+ * start it here, after the same refusal checks. Throws the refusal, or why the start failed. A Chief's retry of an idle
+ * thread whose bot is busy elsewhere (at its turn limit, or in a room's turn) waits in that thread's queue instead, and
+ * the queue starts it when the bot frees up. A thread that still runs, shuts down or already waits is refused as before. */
- async function retryThread(input: { chief: BotRecord; bot: BotRecord; threadId: string; unattended: boolean; note?: string; automatic?: true }): Promise<{ queued: true } | undefined> {
+ async function retryThread(input: { chief: BotRecord; bot: BotRecord; threadId: string; unattended: boolean; note?: string; automatic?: true;
+ /** The retrying Chief's own coordinate_bots, from its current turn; left out from a room, where it would address the room, not this thread. */
- coordinateBots?: (call: CoordinateBotsCall) => Promise<{ status: number; body: Record<string, unknown> }> }): Promise<"request" | "turn"> {
++ coordinateBots?: (call: CoordinateBotsCall) => Promise<{ status: number; body: Record<string, unknown> }> }): Promise<"request" | "turn" | "queued"> {
const refused = retryRefusal(input.bot.id, input.threadId);
if (refused) throw new Error(refused);
+ // The Chief's own request failed here: it asks again from its current turn, so the result wakes it as the first would have.
+ const failed = input.automatic || !input.coordinateBots ? undefined : deps.failedRequester?.(input.threadId);
+ if (input.coordinateBots && failed?.botId === input.chief.id) {
+ const note = input.note ? ` Note: ${quoteInNote(input.note, 300)}` : "";
+ // A question stays a question: asked again, the teammate still acts on nothing.
+ const sent = await input.coordinateBots({ botIds: [input.bot.id], thread: input.threadId, reply: "resume", consult: failed.consult, rework: false,
+ message: `Your last run in this thread stopped before it finished my request, so I am asking again.${note} Continue the request above from where it stopped and finish it. If the same problem comes back, say exactly what is blocking and stop.` });
+ const receipt = (sent.body.receipts as PeerDeliveryReceipt[] | undefined)?.[0];
+ if (sent.status !== 200 || !receipt || receipt.outcome === "failed") throw new Error(String(receipt?.detail ?? sent.body.error ?? "Not delivered."));
+ return "request";
+ }
const chief = peerName(input.chief.name);
const lead = input.automatic
? `${AUTO_RETRY_LEAD}, once, before telling ${chief}, your Chief of Staff, that this thread's last run failed.`
: `${RETRY_LEAD}${chief}, your Chief of Staff, after this thread's last run stopped.${input.note ? ` Note from ${chief}: ${quoteInNote(input.note, 300)}` : ""}`;
- await deps.startTurn(input.bot.id, `${lead} Continue the request above from where it stopped and finish it. If the same problem comes back, say exactly what is blocking and stop.]`,
- { threadId: input.threadId, unattended: input.unattended, peerAsk: { botId: input.chief.id, name: input.chief.name, ...(input.unattended ? { unattended: true } : {}) } });
+ const text = `${lead} Continue the request above from where it stopped and finish it. If the same problem comes back, say exactly what is blocking and stop.]`;
+ const peerAsk = { botId: input.chief.id, name: input.chief.name, ...(input.unattended ? { unattended: true } : {}) };
+ const atCapacity = !input.automatic && deps.botAtThreadCapacity(input.bot.id);
+ if (atCapacity || (!input.automatic && deps.groupTurnActive(input.bot.id))) {
+ queueSteeredMessage(input.bot.id, input.threadId, text, { reason: atCapacity ? "capacity" : "group-turn", unattended: input.unattended, peerAsk });
- return { queued: true };
++ return "queued";
+ }
+ await deps.startTurn(input.bot.id, text, { threadId: input.threadId, unattended: input.unattended, peerAsk });
+ return "turn";
}
/** A notice about this thread may go to `chief`: its asks are the Chief's person's, never another person's private chat. */
diff --cc server/index.ts
index 0970ccca25,536e6822bb..1dfb5fbf7e
--- a/server/index.ts
+++ b/server/index.ts
@@@ -13717,18 -13722,19 +13722,18 @@@ const handleRequest = async (req: Incom
if (!task || (CLOUD_TEAM && !teamHost.readableFrom(fromThreadId)(threadId))) return json(res, 404, { error: "no such thread on that bot" });
if (!outsideLineage.mayReach(fromThreadId, threadId)) return json(res, 403, { error: OUTSIDE_STAYS_HERE });
requireActiveInternalCapability();
- let queued: { queued: true } | undefined;
- let retried: "request" | "turn";
++ let retried: "request" | "turn" | "queued";
try {
- queued = await retryThread({ chief: from, bot: target, threadId, note, unattended: isUnattended(from.id, fromThreadId) });
+ retried = await retryThread({ chief: from, bot: target, threadId, note, unattended: isUnattended(from.id, fromThreadId), ...(store.groupByThread(fromThreadId) ? {} : { coordinateBots }) });
} catch (error) {
return json(res, 409, { error: error instanceof Error ? error.message : String(error) });
}
- if (queued) {
- store.appendMessage(fromThreadId, {
- role: "bot",
- kind: "activity",
- tool: { name: `Retried ${target.name}'s thread #${task.title}`, ok: true },
- threadRef: { botId: target.id, threadId, title: task.title },
- });
++ if (retried === "queued") {
+ store.appendMessage(fromThreadId, { role: "bot", kind: "activity", tool: { name: serverLine(threadLanguage(fromThreadId), "server.chief.retryQueued", { name: target.name, title: task.title }), ok: true }, threadRef: { botId: target.id, threadId, title: task.title } });
+ return json(res, 200, { queued: true, message: `${target.name} is busy right now, so the retry of thread #${task.title} is queued and starts by itself when ${target.name} frees up. Its result stays in that thread; you are not woken for it — do not report this hand-off as failed and do not retry again.` });
+ }
+ store.appendMessage(fromThreadId, { role: "bot", kind: "activity", tool: { name: `Retried ${target.name}'s thread #${task.title}`, ok: true }, threadRef: { botId: target.id, threadId, title: task.title } });
- return json(res, 200, { started: true, message: `${target.name}'s thread #${task.title} is running again. Its result stays in that thread; you are not woken for it — check later with list_threads or session_search if you need to.` });
+ return json(res, 200, { started: true, message: retriedMessage(target.name, task.title, retried) });
}
// post_to_room appends role "bot", never "user" (which would start a round of real turns), starts no turn, and takes membership from the record.
if (method === "POST" && path === "/api/internal/post-to-room") {