Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(chief): a Chief's retry of its own failed request wakes the Chief again
AdityaUmale1254fb66c942
diff --git a/server/host/chief-notices-retry.test.ts b/server/host/chief-notices-retry.test.tsindex df2fa63dc4..f2b54a26e5 100644--- a/server/host/chief-notices-retry.test.ts+++ b/server/host/chief-notices-retry.test.ts@@ -7,7 +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 { 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 = [@@ -354,3 +354,50 @@ describe("a run the server had no room to start", () => {expect(crash.continued).toEqual([]);});});++describe("a Chief's retry of a thread that failed the Chief's own request", () => {+ const sent = { status: 200, body: { receipts: [{ botId: "ada", botName: "Ada", outcome: "queued", threadId: "ada-job" }] } };+ const node = (over: Record<string, unknown>) => ({ id: "child", parentId: "chief-turn", threadId: "ada-job", botId: "ada", status: "failed", reply: "resume", ...over });+ const coordinator = (last: Record<string, unknown> | undefined) => ({+ inThread: () => (last ? [node({ id: "older", status: "completed" }), last] : []) as never,+ node: (id: string) => (id === "chief-turn" ? { id, botId: "chief", threadId: "chief-main" } : undefined) as never,+ });+ const requester = (last: Record<string, unknown> | undefined) => failedRequester(coordinator(last), "ada-job");++ it("knows which bot asked, with reply resume, for the failed work, and nobody for anything else", () => {+ expect(requester(node({}))).toBe("chief");+ expect(requester(node({ status: "completed" }))).toBeUndefined();+ expect(requester(node({ reply: "none" }))).toBeUndefined();+ expect(requester(node({ parentId: undefined }))).toBeUndefined();+ expect(requester(undefined)).toBeUndefined();+ });++ it("asks again from the Chief's own turn, so the result wakes the Chief, and says so", async () => {+ const coordinateBots = vi.fn(async () => sent);+ const f = fixture({ failedRequester: () => "chief" });+ const how = await f.notices.retryThread({ chief: f.chief as never, bot: f.ada as never, threadId: "ada-job", unattended: true, note: "The service was down.", coordinateBots });+ expect(f.startTurn).not.toHaveBeenCalled();+ expect(coordinateBots).toHaveBeenCalledWith(expect.objectContaining({ botIds: ["ada"], thread: "ada-job", reply: "resume", consult: false }));+ expect(how).toBe("request");+ expect(retriedMessage("Ada", "Invoices", "request")).toContain("resumes you");+ });++ it("tells the Chief why when that request could not be sent", async () => {+ const coordinateBots = vi.fn(async () => ({ status: 403, body: { error: "not reachable" } }));+ const f = fixture({ failedRequester: () => "chief" });+ await expect(f.notices.retryThread({ chief: f.chief as never, bot: f.ada as never, threadId: "ada-job", unattended: true, coordinateBots })).rejects.toThrow("not reachable");+ expect(f.startTurn).not.toHaveBeenCalled();+ });++ it("retries every other thread as before: another bot's request, the person's own work, or OpenMausBot's automatic retry", async () => {+ for (const [requested, automatic] of [["someone-else", false], [undefined, false], ["chief", true]] as const) {+ const coordinateBots = vi.fn(async () => sent);+ const f = fixture({ failedRequester: () => requested });+ const how = await f.notices.retryThread({ chief: f.chief as never, bot: f.ada as never, threadId: "ada-job", unattended: true, coordinateBots, ...(automatic ? { automatic: true as const } : {}) });+ expect(coordinateBots).not.toHaveBeenCalled();+ expect(f.turnsOf("ada")).toHaveLength(1);+ expect(how).toBe("turn");+ }+ expect(retriedMessage("Ada", "Invoices", "turn")).toBe("Ada's thread #Invoices 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.");+ });+});diff --git a/server/host/chief-notices.ts b/server/host/chief-notices.tsindex 98a178bd12..984a85d13b 100644--- a/server/host/chief-notices.ts+++ b/server/host/chief-notices.ts@@ -14,12 +14,16 @@ import { serverLine } from "../server-lines.ts";import { retriesTeammateThread, type RoutineFailureFacts } from "../routine-recovery.ts";import { queueSteeredMessage } from "../steer-queue.ts";import type { BotRecord, Message, Store } from "../store.ts";+import type { Coordinator, CoordinateBotsCall } from "../coordinator.ts";+import type { PeerDeliveryReceipt } from "../peer-delivery.ts";type PeerAsk = NonNullable<Message["peerAsk"]>;export interface ChiefNoticeDeps {store: Pick<Store, "bots" | "bot" | "tasks" | "taskByThread" | "groupByThread" | "createTask" | "appendMessage" | "messagesFor" | "activePath"> & Partial<Pick<Store, "patchMessage">>;assignerOf(threadId: string): unknown;+ /** The bot whose reply-resume request this thread's newest assignment was, when that assignment failed (`failedRequester`). */+ failedRequester?(threadId: string): string | undefined;notify(notification: Notification | null): void;threadBusy(botId: string, threadId: string): boolean;botAtThreadCapacity(botId: string): boolean;@@ -75,6 +79,19 @@ export const SERVER_MEMORY_RETRY_TEXT = "[OpenMausBot started this again by itseexport const ROOM_RETRY_TEXT = "[OpenMausBot started this again by itself, once: the last run could not start because this server had no room for another program. "+ "Continue the request above from where it stopped and finish it. If the same problem comes back, say exactly what is blocking and stop.]";+/** The bot that asked, with reply resume, for the work this thread's newest assignment was, when that assignment failed. */+export function failedRequester(coordinator: Pick<Coordinator, "inThread" | "node">, threadId: string): string | undefined {+ const last = coordinator.inThread(threadId).at(-1);+ return last?.status === "failed" && last.reply === "resume" && last.parentId ? coordinator.node(last.parentId)?.botId : undefined;+}++/** What retry_thread tells the Chief: a retry of its own failed request comes back to it; any other result stays there. */+export function retriedMessage(botName: string, title: string, how: "request" | "turn"): string {+ return how === "request"+ ? `${botName}'s thread #${title} is running again as a new request from you: its result comes back to this conversation and resumes you.`+ : `${botName}'s thread #${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.`;+}+export function createChiefNotices(deps: ChiefNoticeDeps) {const { store } = deps;const incidentLedger = new IncidentLedger();@@ -121,15 +138,27 @@ 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> {+ 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. */+ coordinateBots?: (call: CoordinateBotsCall) => Promise<{ status: number; body: Record<string, unknown> }> }): Promise<"request" | "turn"> {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.+ if (!input.automatic && input.coordinateBots && deps.failedRequester?.(input.threadId) === input.chief.id) {+ const note = input.note ? ` Note: ${quoteInNote(input.note, 300)}` : "";+ const sent = await input.coordinateBots({ botIds: [input.bot.id], thread: input.threadId, reply: "resume", consult: false, 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 } : {}) } });+ 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 --git a/server/index.ts b/server/index.tsindex 6062126e74..35f3ba0777 100644--- a/server/index.ts+++ b/server/index.ts@@ -238,7 +238,7 @@ import { openCodeProviderKeysAllowed, setOpenCodeProviderKeyPolicy } from "./driimport { forgetNotificationReader, liveAppRows, openCardRows, readMessageText, recallMessages, recentMessages, closeMessageSearch, closeMessageDb, chatFollowups, cancelledChatFollowup, settleChatFollowups, threadsReferencing, logNotification, lastRowAt, threadsWithCardsSince } from "./message-db.ts";import { briefCrossingLabel, claimRecallCrossings, recallCrossingLabel } from "./recall-disclosure.ts";import { parseSince, parseUntil, recentWork, recentWorkPrompt, turnOutcomeLine } from "./recent-work.ts";-import { createChiefNotices } from "./host/chief-notices.ts"; import { sessionHolds } from "./routine-recovery.ts"; import { dismissLeftoverPeerCards } from "./host/leftover-peer-cards.ts";+import { createChiefNotices, failedRequester, retriedMessage } from "./host/chief-notices.ts"; import { sessionHolds } from "./routine-recovery.ts"; import { dismissLeftoverPeerCards } from "./host/leftover-peer-cards.ts";import { createHandoffTicks } from "./handoff-ticks.ts"; import { IDLE_HTTP_SERVER } from "./due-timer.ts";const SESSION_READ_MAX_CHARS = 8_000;@@ -6870,7 +6870,7 @@ function runtimeWorkPending(threadId: string): boolean {const { reportIncident, incidentRefused, retryThread } = createChiefNotices({store, notify, threadBusy, botAtThreadCapacity, startTurn, quietThread: (_botId, threadId) => proactive.fence.confines(threadId) || botApiThread(threadId), privateThread: (threadId) => teamHost.ownTurn(threadId), confined: cloudGuestDriven, threadLanguage,- assignerOf: (threadId) => coordinator.assignerOf(threadId),+ assignerOf: (threadId) => coordinator.assignerOf(threadId), failedRequester: (threadId) => failedRequester(coordinator, threadId),threadSettling: (threadId) => settlingTurns.has(threadId), threadQueued: (botId, threadId) => queuedThreadPosition(botId, threadId) !== null,groupTurnActive: (botId) => Boolean(activeGroupTurnForBot(botId)),...(teamOwners.noticeRouting ? { routing: teamOwners.noticeRouting } : {}),@@ -13726,8 +13726,9 @@ 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 retried: "request" | "turn";try {- 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), coordinateBots });} catch (error) {return json(res, 409, { error: error instanceof Error ? error.message : String(error) });}@@ -13737,7 +13738,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {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") {