Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Chief notices: queue a busy teammate's retry instead of refusing it
skygunner579b341aadbb
diff --git a/server/host/chief-notices-retry.test.ts b/server/host/chief-notices-retry.test.tsindex df2fa63dc4..1963537904 100644--- a/server/host/chief-notices-retry.test.ts+++ b/server/host/chief-notices-retry.test.ts@@ -7,6 +7,7 @@ import { memoryStopText } from "../engine-memory.ts";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";function fixture(over: Partial<ChiefNoticeDeps> = {}) {@@ -69,6 +70,62 @@ describe("why a Chief's retry of a teammate's thread is refused", () => {});});+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({ threadBusy: (botId) => botId === "ada", 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(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({ threadQueued: () => true, 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 });+ 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 while the thread only shuts down, or when its bot has room and no room turn", async () => {+ const settling = fixture({ threadBusy: () => true, threadSettling: () => true, groupTurnActive: () => true });+ await expect(settling.notices.retryThread({ chief: settling.chief as never, bot: settling.ada as never, threadId: "ada-job", unattended: true })).rejects.toThrow(RETRY_BLOCKED.settling);+ const withRoom = fixture({ threadBusy: () => true });+ await expect(withRoom.notices.retryThread({ chief: withRoom.chief as never, bot: withRoom.ada as never, threadId: "ada-job", unattended: true })).rejects.toThrow(RETRY_BLOCKED.running);+ 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 --git a/server/host/chief-notices.ts b/server/host/chief-notices.tsindex 98a178bd12..93ed9f162c 100644--- a/server/host/chief-notices.ts+++ b/server/host/chief-notices.ts@@ -120,16 +120,26 @@ export function createChiefNotices(deps: ChiefNoticeDeps) {}/** 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. */- async function retryThread(input: { chief: BotRecord; bot: BotRecord; threadId: string; unattended: boolean; note?: string; automatic?: true }): Promise<void> {+ * start it here, after the same refusal checks. Throws the refusal, or why the start failed. A busy refusal queues the+ * retry instead when the bot is mid-turn elsewhere or at its turn limit: the steer queue starts it when the bot frees up. */+ async function retryThread(input: { chief: BotRecord; bot: BotRecord; threadId: string; unattended: boolean; note?: string; automatic?: true }): Promise<{ queued: true } | undefined> {const refused = retryRefusal(input.bot.id, input.threadId);- if (refused) throw new Error(refused);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 } : {}) };+ if (refused) {+ const atCapacity = deps.botAtThreadCapacity(input.bot.id);+ const groupTurn = deps.groupTurnActive(input.bot.id);+ if ((refused === RETRY_BLOCKED.running || refused === RETRY_BLOCKED.queued) && (atCapacity || groupTurn)) {+ queueSteeredMessage(input.bot.id, input.threadId, text, { reason: atCapacity ? "capacity" : "group-turn", unattended: input.unattended, peerAsk });+ return { queued: true };+ }+ throw new Error(refused);+ }+ await deps.startTurn(input.bot.id, text, { threadId: input.threadId, unattended: input.unattended, peerAsk });}/** A notice about this thread may go to `chief`: its asks are the Chief's person's, never another person's private chat. */diff --git a/server/index.ts b/server/index.tsindex 0695438091..c39e66d659 100644--- a/server/index.ts+++ b/server/index.ts@@ -13717,17 +13717,17 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {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;try {- await retryThread({ chief: from, bot: target, threadId, note, unattended: isUnattended(from.id, fromThreadId) });+ queued = await retryThread({ chief: from, bot: target, threadId, note, unattended: isUnattended(from.id, fromThreadId) });} catch (error) {return json(res, 409, { error: error instanceof Error ? error.message : String(error) });}- 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 (queued) {+ store.appendMessage(fromThreadId, { role: "bot", kind: "activity", tool: { name: `Queued a retry of ${target.name}'s thread #${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.` });}// 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.