Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Hand-offs: an approval nobody answered parks as a durable Inbox ask
Milind Soni3a6f460ef931
diff --git a/server/coordinator.ts b/server/coordinator.tsindex 9070b79f0f..7580826718 100644--- a/server/coordinator.ts+++ b/server/coordinator.ts@@ -90,6 +90,8 @@ export interface HostTurnResult {cards?: { question: string; ids: string[] };/** The question it ends on stayed in one person's private chat: only that person can answer it. */privateQuestion?: boolean;+ /** An approval this turn asked for went unanswered: handed-off work a person started parks on this question. Never a grant. */+ approvalAsk?: string;/** The host's stall watchdog stopped the turn, including a room turn a stall ended during setup, before it had an* outcome: it failed as `stalled`, not as a provider error. */stalled?: boolean;diff --git a/server/host/acting-person.test.ts b/server/host/acting-person.test.tsindex d8712eab58..b2b2b51d9e 100644--- a/server/host/acting-person.test.ts+++ b/server/host/acting-person.test.ts@@ -185,6 +185,9 @@ describe("what work in one person's private chat hands back", () => {it("to a chat others read: only where the result is, never the result or what was observed", () => {expect(privateHandBack(done, place(null))).toEqual({ ok: true, text: "Done. The result is in Helper's chat with Ada." });expect(privateHandBack({ ok: false, text: "Gmail said the board's thread is gone." }, place(null)).text).toBe("It stopped before it finished. The result is in Helper's chat with Ada.");+ const approval: Parameters<typeof privateHandBack>[0] = privateHandBack({ ok: true, text: "Did not run.", approvalAsk: "Approve “Bash: cat salary.csv”?" }, place(null));+ expect(approval.approvalAsk, "an unanswered approval names no private action").toBe("Helper has a question for Ada, in Helper's chat with Ada.");+ expect(approval.privateQuestion).toBe(true);expect(privateHandBack(done, place(BEN)).text, "another person's private chat reads none of hers").toBe("Done. The result is in Helper's chat with Ada.");});diff --git a/server/host/acting-person.ts b/server/host/acting-person.tsindex 54662a37fb..e185688066 100644--- a/server/host/acting-person.ts+++ b/server/host/acting-person.ts@@ -157,7 +157,7 @@ export function createActingPeople(deps: ActingPeopleDeps) {export type ActingPeople = ReturnType<typeof createActingPeople>;-type HandedBack = { ok: boolean; text: string; evidence?: unknown; cards?: { question: string; ids: string[] }; privateQuestion?: boolean };+type HandedBack = { ok: boolean; text: string; evidence?: unknown; cards?: { question: string; ids: string[] }; privateQuestion?: boolean; approvalAsk?: string };type Place = { child: string | null; parent: string | null };/** Work in one person's private chat, for a requester whose chat is not that one: its words stay with that person. */@@ -178,6 +178,7 @@ export function privateHandBack<T extends HandedBack>(outcome: T, place: Place &...rest,text: asks ? `NEEDS INPUT: ${question}` : `${outcome.ok ? "Done" : "It stopped before it finished"}. The result is in ${where}.`,...(outcome.cards ? { cards: { ...outcome.cards, question } } : {}),- ...(asks || outcome.cards ? { privateQuestion: true } : {}),+ ...(outcome.approvalAsk ? { approvalAsk: question } : {}),+ ...(asks || outcome.cards || outcome.approvalAsk ? { privateQuestion: true } : {}),} as T;}diff --git a/server/independent-threads-api.test.ts b/server/independent-threads-api.test.tsindex 407d8d1abc..3bb43714c9 100644--- a/server/independent-threads-api.test.ts+++ b/server/independent-threads-api.test.ts@@ -242,16 +242,16 @@ describe("independent bot tasks through the isolated control surface", () => {]);writeFileSync(modelFile(models[1], "gate"), "finish");- await expect.poll(() => handoff()?.status, { timeout: 20_000 }).toBe("completed");- const result: string = handoff()!.result;- expect(result.startsWith("[OpenMausBot: nobody answered the approval for “Bash: npm run release-check” in time, so it did not run. Do not report it as done;")).toBe(true);- expect(result).toContain("reply to:");- expect(result).not.toContain("git push");- expect(result).not.toContain("npm run lint");+ await expect.poll(() => handoff()?.status, { timeout: 20_000 }).toBe("waiting");+ const question = handoff()!.question ?? "";+ expect(question).toContain("“Bash: npm run release-check”");+ expect(question).not.toContain("git push");+ expect(question).not.toContain("npm run lint");+ await expect.poll(async () => (await api("GET", `/api/threads/${workThread}/messages?limit=100`)).body.messages+ .some((message: any) => message.card?.requestId?.startsWith("needs-input-") && message.card.options?.includes("Try again"))).toBe(true);await expect.poll(async () => (await api("GET", `/api/threads/${chief.activeTaskId}/messages?limit=100`)).body.messages- .find((message: any) => message.roomRequest?.id === requestId && message.roomRequest.phase === "result")?.tool?.output ?? "")- .toContain("nobody answered the approval for “Bash: npm run release-check”");- evidence.push({ requestId, result: result.slice(0, 400) });+ .some((message: any) => message.tool?.name?.includes("needs your input") && message.tool.name.includes("npm run release-check"))).toBe(true);+ evidence.push({ requestId, question: question.slice(0, 400) });}, 60_000);it.each(["finish", "fail"] as const)("tells a delegating bot that its teammate's approval went unanswered, so the step did not run (turn ends: %s)", async (ending) => {@@ -337,8 +337,8 @@ describe("independent bot tasks through the isolated control surface", () => {await expect.poll(() => unanswered.find((answer) => answer.id === "unanswered-room")).toMatchObject({ behavior: "deny", source: "timeout" });rmSync(expiry, { force: true });writeFileSync(modelFile(models[1], "gate"), "finish");- await expect.poll(() => handoff()?.status, { timeout: 20_000 }).toBe("completed");- expect(handoff()!.result.startsWith("[OpenMausBot: nobody answered the approval for “Bash: npm run release-check” in time, so it did not run.")).toBe(true);+ await expect.poll(() => handoff()?.status, { timeout: 20_000 }).toBe("waiting");+ expect(handoff()!.question).toContain("“Bash: npm run release-check”");}, 60_000);it("ends a one-way notice whose recipient thread was deleted before it started, without restarting the sender", async () => {diff --git a/server/index.ts b/server/index.tsindex 2aee79bbd3..349b28f002 100644--- a/server/index.ts+++ b/server/index.ts@@ -3831,7 +3831,7 @@ function runRoomNode(node: HandoffView, group: GroupRecord, bot: BotRecord, sign});groupQueues.set(node.threadId, tracked.catch(() => {}));tracked.then(- () => finish({ ok: result.outcome === "settled", text: result.stopReason || result.replyText || result.outcome || "The addressed agent could not run" }),+ () => finish({ ok: result.outcome === "settled", text: result.stopReason || result.replyText || result.outcome || "The addressed agent could not run", ...(result.approvalAsk ? { approvalAsk: result.approvalAsk } : {}) }),error => finish({ ok: false, text: error instanceof Error ? error.message : String(error) }),);});@@ -4780,7 +4780,7 @@ onSteeredQueueChange(() => broadcast({ kind: "bot.queued", queues: publicBotQueu// Keyed by threadId: provider item and request ids are unique only within a thread.const toolMessageByItem = new Map<string, string>();const askMessageByRequest = new Map<string, string>();-const unansweredApprovals = new UnansweredApprovals();+const unansweredApprovals = new UnansweredApprovals(); const approvalAsk = (botId: string | undefined, threadId: string, turnId: string | undefined): { approvalAsk?: string } => { const asked = botId ? unansweredApprovals.ask(threadId, turnId, store.bot(botId)?.name ?? "A teammate", threadLanguage(threadId)) : undefined; return asked ? { approvalAsk: asked } : {}; };// Only native, live permission metadata becomes a remembered grant, never an imported transcript or display summary.const pendingCommandRules = new Map<string, { botId: string; candidate: CommandAllowlistCandidate }>();@@ -5080,7 +5080,7 @@ bus.subscribe((event: RuntimeEvent) => {const text = event.ok ? reply || event.stopReason || "The bot finished without a text reply": stoppedTurnText(event.threadId, event.turnId, undefined, event.stopReason);const handoffPath = event.ok ? undefined : turnStops.read(event.threadId, event.turnId)?.handoffPath;- const outcome: DirectTurnOutcome = { ok: event.ok, text: unansweredApprovals.annotate(event.threadId, event.turnId, text.slice(0, 12_000), event.ok),+ const outcome: DirectTurnOutcome = { ok: event.ok, text: unansweredApprovals.annotate(event.threadId, event.turnId, text.slice(0, 12_000), event.ok), ...approvalAsk(store.botByThread(event.threadId)?.id, event.threadId, event.turnId),...(handoffPath ? { cap: { note: STEP_CAP_NOTE, handoffPath } } : {}) };const owner = directFollowupTurns.complete(event.threadId, event.turnId, outcome);if (owner) {@@ -9593,7 +9593,7 @@ type GroupTurnOrchestration = {turnNote?: string;turnRestartNote?: string;followMentions: boolean;- result: { replyText?: string; outcome?: GroupMemberTurnOutcome; stopReason?: string | null };+ result: { replyText?: string; outcome?: GroupMemberTurnOutcome; stopReason?: string | null; approvalAsk?: string };onClaimed?: () => void;onTurnStarted?: (turnId: string) => void;coordination?: { id: string; settle: (outcome: HostTurnResult) => void };@@ -10415,7 +10415,7 @@ async function runClaimedGroupMemberTurn(roomReply = unansweredApprovals.annotate(threadId, providerTurnId,(orchestration ? turnTexts.map((text) => `\n${text}`).join("") : replyText).trim(), outcome === "settled");if (orchestration) {- orchestration.result.replyText = roomReply;+ orchestration.result.replyText = roomReply; Object.assign(orchestration.result, approvalAsk(bot.id, threadId, providerTurnId));orchestration.result.outcome = outcome;}// A timed-out provider owns the room thread until its interrupt produces turn.completed: do not start the next member early.diff --git a/server/runtime-coordinator.test.ts b/server/runtime-coordinator.test.tsindex ecbacaa1af..3156963510 100644--- a/server/runtime-coordinator.test.ts+++ b/server/runtime-coordinator.test.ts@@ -456,6 +456,44 @@ describe("RuntimeCoordinator: refusals in the legacy words", () => {expect(() => send(tight, chief, "gen-1", undefined, tester, "Test it")).toThrow("Room handoff budget exhausted");});+ it("parks handed-off work a person started on an approval nobody answered, and carries the answer into its next turn", async () => {+ const asked = { ok: true, text: "Could not run the checks.", approvalAsk: "Approve it?\nDefault: Try again" };+ const w = world((node) => node.botId === "builder" && node.executions === 1 ? asked : undefined);+ const { node } = send(w, chief, "gen-1", undefined, builder, "Run the checks");+ w.coordinator.tick(); await flush();+ expect(w.coordinator.node(node.id)).toMatchObject({ status: "waiting", question: "Approve it?\nDefault: Try again" });+ expect(w.host.parks.map(p => p.question)).toEqual(["Approve it?\nDefault: Try again"]);+ expect(w.host.reports).toEqual([]);+ expect(w.coordinator.answerNode(node.id, "Try again")).toBe(true);+ w.coordinator.tick(); await flush();+ expect(w.host.runs.filter(r => r.node.botId === "builder").at(-1)!.text).toContain("The person answered: \"Try again\"");+ expect(w.coordinator.node(node.id)?.status).toBe("completed");+ });++ it("parks a turn that failed for want of the approval too, but not a stalled one", async () => {+ const failed = { ok: false, text: "One or more tool operations failed or were denied", approvalAsk: "Approve it?" };+ const w = world((node) => node.botId === "builder" ? failed : node.botId === "tester" ? { ...failed, stalled: true } : undefined);+ const { node: denied } = send(w, chief, "gen-1", undefined, builder, "Run the checks");+ const { node: stuck } = send(w, chief, "gen-1", undefined, tester, "Run the checks");+ w.coordinator.tick(); await flush();+ expect(w.coordinator.node(denied.id)?.status).toBe("waiting");+ expect(w.coordinator.node(stuck.id)).toMatchObject({ status: "failed", outcome: "stalled" });+ });++ it("leaves a bot's own question, and work no person started, on their usual path", async () => {+ const own = world(() => ({ ok: true, text: "NEEDS INPUT: Which region?", approvalAsk: "Approve it?" }));+ const { node } = send(own, chief, "gen-1", undefined, builder, "Run the checks");+ own.coordinator.tick(); await flush();+ expect(own.coordinator.node(node.id)?.question).toBe("Which region?");++ const routine = world((n) => n.botId === "builder" ? { ok: true, text: "It did not run.", approvalAsk: "Approve it?" } : undefined);+ routine.coordinator.beginTurn({ id: "gen-1", address: chief, brief: "Nightly", level: "ask",+ opener: { requester: { kind: "routine_run", runId: "run-1" }, origin: { kind: "routine", source: "routine" } } });+ const { node: nightly } = routine.coordinator.enqueue(chief, "gen-1", undefined, builder, "Run the checks");+ routine.coordinator.tick(); await flush();+ expect(routine.coordinator.node(nightly.id)).toMatchObject({ status: "completed", result: "It did not run." });+ });+it("lets one Chief turn brief a room of 25 visitors and starts every one of them", async () => {const w = world((node) => node.botId.startsWith("visitor-") ? "hold" : undefined);const visitors = Array.from({ length: 25 }, (_, i) => ({ botId: `visitor-${i + 1}`, threadId: `visitor-${i + 1}-work` }));diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.tsindex 013038cc82..a8d997b933 100644--- a/server/runtime-coordinator.ts+++ b/server/runtime-coordinator.ts@@ -619,8 +619,9 @@ export class RuntimeCoordinator implements Coordinator {if (signal.aborted) return { kind: "failed", outcome: "stopped", text: result.text };if (result.cap) return { kind: "continue", text: result.text, note: result.cap.note, ...(result.cap.handoffPath ? { handoffPath: result.cap.handoffPath } : {}), ...evidence(result) };if (result.cards) return { kind: "needs_input", question: result.cards.question, cards: result.cards.ids, ...evidence(result) };- if (!result.ok) return { kind: "failed", outcome: result.stalled ? "stalled" : "provider_error", text: result.text, ...evidence(result) };const question = root ? undefined : needsInputQuestion(result.text);+ if (!root && a.origin.kind === "person" && result.approvalAsk && !result.stalled && question === undefined) return { kind: "needs_input", question: result.approvalAsk, ...evidence(result) };+ if (!result.ok) return { kind: "failed", outcome: result.stalled ? "stalled" : "provider_error", text: result.text, ...evidence(result) };if (question === undefined) return { kind: "completed", text: result.text, ...(await this.statusOnly(a, parent, input.turn, result, signal) ? { statusOnly: true } : {}), ...evidence(result) };const named = withDefault(question);const decide = requesterDecides(a) && !result.privateQuestion && !personOnly(named.question) ? { decide: named.default ? { default: named.default } : {} } : {};diff --git a/server/waiting-on-person.test.ts b/server/waiting-on-person.test.tsindex 920d5721a9..57c66bb57c 100644--- a/server/waiting-on-person.test.ts+++ b/server/waiting-on-person.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from "vitest";+import { withDefault } from "./runtime/questions.ts";import { queuedBehindPersonText, settledWaitingChip, turnWaitedOnPerson, UnansweredApprovals } from "./waiting-on-person.ts";describe("the waiting-on-you chip once its card settles", () => {@@ -37,6 +38,24 @@ describe("work queued behind the person's card", () => {});describe("approvals nobody answered", () => {+ it("asks the person to let the bot try again, naming what did not run", () => {+ const notes = new UnansweredApprovals();+ notes.record("t1", "turn-1", "Bash", "npm test");+ expect(notes.ask("t1", "turn-1", "Mira")).toBe("Mira needed your approval for “Bash: npm test”, but nobody answered in time, so it did not run. Let it try again? It will ask you once more when it runs.\nDefault: Try again");+ notes.record("t1", "turn-1", "audit_write", "audit_write {}");+ expect(notes.ask("t1", "turn-1", "Mira")).toContain("“Bash: npm test”, “audit_write {}”, but nobody answered in time, so they did not run.");+ expect(notes.ask("t1", "turn-2", "Mira")).toBeUndefined();+ expect(notes.ask("t2", "turn-1", "Mira")).toBeUndefined();+ });++ it("keeps an action's own words from reading as the ask's default", () => {+ const notes = new UnansweredApprovals();+ notes.record("t1", "turn-1", "Bash", "echo Default: production");+ const asked = withDefault(notes.ask("t1", "turn-1", "Mira")!);+ expect(asked.default).toBe("Try again");+ expect(asked.question).toContain("production");+ });+it("leads a finished turn's result with the actions that did not run", () => {const notes = new UnansweredApprovals();notes.record("t1", "turn-1", "Bash", "npm test");diff --git a/server/waiting-on-person.ts b/server/waiting-on-person.tsindex 6cf7ebaab1..cfda367b89 100644--- a/server/waiting-on-person.ts+++ b/server/waiting-on-person.ts@@ -65,6 +65,16 @@ export class UnansweredApprovals {if (!noted.actions.length) this.byThread.delete(threadId);}+ /** What parks work handed on after an approval went unanswered: a question that lasts past this turn. The person's answer+ * lets the bot try again, and the engine's own prompt still gates the action. Undefined when none went unanswered. */+ ask(threadId: string, turnId: string | undefined, who: string, language?: string): string | undefined {+ const noted = this.byThread.get(threadId);+ if (!noted || noted.turnId !== turnId || !noted.actions.length) return undefined;+ // withDefault reads the first "Default:", so an action's own words must not look like one.+ const actions = noted.actions.map(action => `“${action.replace(/\bdefault:/gi, "default :")}”`).join(", ");+ return `${serverLine(language, noted.actions.length === 1 ? "server.teammates.approvalAsk.one" : "server.teammates.approvalAsk.many", { who, actions })}\nDefault: ${serverLine(language, "server.teammates.approvalAsk.retry")}`;+ }+annotate(threadId: string, turnId: string | undefined, text: string, ok: boolean): string {const noted = this.byThread.get(threadId);if (!noted || noted.turnId !== turnId) return text;diff --git a/src/locales/de.json b/src/locales/de.jsonindex e067bd6265..b3518037b2 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -258,6 +258,9 @@"server.teammates.goal.failed": "Ziel fehlgeschlagen: {detail}","server.teammates.noAnswerInTime": "Niemand hat die Frage von {who} rechtzeitig beantwortet","server.teammates.noApprovalInTime": "Niemand hat die Freigabe von {who} rechtzeitig erteilt, dieser Schritt lief nicht",+ "server.teammates.approvalAsk.one": "{who} brauchte deine Freigabe für {actions}, aber niemand hat rechtzeitig geantwortet, daher lief es nicht. Noch einmal versuchen lassen? Beim Ausführen wird noch einmal um Freigabe gefragt.",+ "server.teammates.approvalAsk.many": "{who} brauchte deine Freigabe für {actions}, aber niemand hat rechtzeitig geantwortet, daher liefen sie nicht. Noch einmal versuchen lassen? Beim Ausführen wird noch einmal um Freigabe gefragt.",+ "server.teammates.approvalAsk.retry": "Erneut versuchen","server.teammates.turnEndedBeforeAnswer": "Der Zug von {who} endete, bevor jemand seine Frage beantwortet hat","server.teammates.approvalClosed": "Die Freigabe von {who} wurde geschlossen, bevor jemand geantwortet hat, dieser Schritt lief nicht","server.teammates.questionDismissed": "Die Frage von {who} wurde verworfen",diff --git a/src/locales/en.json b/src/locales/en.jsonindex 1354da1a07..ae3528efd1 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -385,6 +385,9 @@"server.teammates.goal.failed": "Goal failed: {detail}","server.teammates.noAnswerInTime": "Nobody answered {who}'s question in time","server.teammates.noApprovalInTime": "Nobody answered {who}'s approval in time — that step did not run",+ "server.teammates.approvalAsk.one": "{who} needed your approval for {actions}, but nobody answered in time, so it did not run. Let it try again? It will ask you once more when it runs.",+ "server.teammates.approvalAsk.many": "{who} needed your approval for {actions}, but nobody answered in time, so they did not run. Let it try again? It will ask you once more when it runs.",+ "server.teammates.approvalAsk.retry": "Try again","server.teammates.turnEndedBeforeAnswer": "{who}'s turn ended before anyone answered its question","server.teammates.approvalClosed": "{who}'s approval closed before anyone answered — that step did not run","server.teammates.questionDismissed": "{who}'s question was dismissed",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 3cc07ce43b..383934692c 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -368,6 +368,9 @@"server.teammates.goal.failed": "O objetivo falhou: {detail}","server.teammates.noAnswerInTime": "Ninguém respondeu à pergunta de {who} a tempo","server.teammates.noApprovalInTime": "Ninguém respondeu ao pedido de aprovação de {who} a tempo — essa etapa não foi executada",+ "server.teammates.approvalAsk.one": "{who} precisava da sua aprovação para {actions}, mas ninguém respondeu a tempo, então não foi executado. Deixar tentar de novo? Ele vai pedir sua aprovação mais uma vez ao executar.",+ "server.teammates.approvalAsk.many": "{who} precisava da sua aprovação para {actions}, mas ninguém respondeu a tempo, então não foram executados. Deixar tentar de novo? Ele vai pedir sua aprovação mais uma vez ao executar.",+ "server.teammates.approvalAsk.retry": "Tentar de novo","server.teammates.turnEndedBeforeAnswer": "A sessão de {who} terminou antes de alguém responder à pergunta dele","server.teammates.approvalClosed": "O pedido de aprovação de {who} foi encerrado antes de alguém responder — essa etapa não foi executada","server.teammates.questionDismissed": "Pergunta de {who} descartada",