Skip to content

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

Hand-offs: a bot can't ask back a teammate that is waiting on it

milind-soni43e7a292e971
diff --git a/server/crossed-handoffs.e2e.test.ts b/server/crossed-handoffs.e2e.test.ts
new file mode 100644
index 0000000000..d038c9422e
--- /dev/null
+++ b/server/crossed-handoffs.e2e.test.ts
@@ -0,0 +1,72 @@
+// Two bots that ask each other at once, end to end on the scripted engine (docs/runtime-contract.md §2). Modelled on a real
+// day: the mail bot asked the chief of staff for yesterday's mailbox details; before that was answered, the person told the
+// chief of staff in its own chat that mail had worked yesterday, and the chief of staff asked the mail bot why it failed.
+// Both then waited on each other, both worked the same problem in two places, and each came back with its own plan.
+// After: the second request is refused at once, naming the request it would answer, so the chief of staff answers the
+// person itself and the mail bot's question still gets its answer. Once that answer is in, the same hand-off is ordinary.
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
+import { request } from "../scripts/mcp-server.ts";
+import { readHandoffs } from "./testing/handoff-rows.ts";
+
+const SETTLED = "Your downstream room requests have settled.";
+
+it("refuses a request back to a bot that is waiting on you, and the same hand-off once it has its answer", async () => {
+ const session = await launchVerificationServer(process.env, undefined, undefined, undefined, undefined, { scripted: true });
+ const cli = (...args: string[]) => runControlOmb(args, { env: { OPENMAUSBOT_URL: session.info.url } }) as Promise<any>;
+ const api = (path: string, body?: unknown, method = "POST") =>
+ request(path, body === undefined ? {} : { method, body: JSON.stringify(body) }, session.info.url) as Promise<any>;
+ try {
+ const post = (await cli("new-bot", "--name", "Post")).bot;
+ const cos = (await cli("new-bot", "--name", "Chief of staff")).bot;
+ const planPath = join(session.info.dataDir, "room-plan.json");
+ const gate = join(session.info.dataDir, "cos-answers");
+ const ready = join(session.info.dataDir, "cos-asked");
+ writeFileSync(planPath, JSON.stringify({
+ [post.id]: { script: [
+ { key: "P1", match: ["P1-JOB"], steps: [{ arguments: { bot_ids: [cos.id], message: "P1-ASK: do you still have yesterday's mailbox details?", consult: true } }],
+ reply: "P1: asked the chief of staff." },
+ { key: "P1-DONE", match: [SETTLED, "P1-JOB"], reply: "P1-DONE: nothing stored, so I need the mailbox password from you." },
+ { key: "C2-WORK", match: ["C2-ASK"], reply: "C2-WORK: the server answers on port 993." },
+ ] },
+ [cos.id]: { script: [
+ { key: "P1-ASK", match: ["P1-ASK"], readyFile: ready, gateFile: gate, reply: "P1-ASK: no mailbox details are stored here." },
+ { key: "C1", match: ["C1-JOB"], steps: [{ arguments: { bot_ids: [post.id], message: "C1-ASK: why can't you fetch mail?" }, expectError: true }],
+ reply: "C1: Post is already asking me about this; I'll answer it there." },
+ { key: "C2", match: ["C2-JOB"], steps: [{ arguments: { bot_ids: [post.id], message: "C2-ASK: which port does the mail server use?" } }], reply: "C2: asked Post." },
+ { key: "C2-DONE", match: [SETTLED, "C2-JOB"], reply: "C2-DONE: port 993." },
+ ] },
+ }));
+ const evidence = (): any[] => existsSync(`${planPath}.evidence.jsonl`)
+ ? readFileSync(`${planPath}.evidence.jsonl`, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [];
+ const keys = (botId: string) => evidence().filter((turn) => turn.botId === botId).map((turn) => turn.planKey);
+ const messages = async (threadId: string) => (await api(`/api/threads/${threadId}/messages`)).messages as any[];
+ const said = async (threadId: string, text: string) => (await messages(threadId)).some((row) => row.text === text);
+
+ await cli("send", "--bot", post.id, "--task", post.activeTaskId, "--text", "P1-JOB: fetch my mail through the Mac mini");
+ await expect.poll(() => existsSync(ready), { timeout: 20_000 }).toBe(true);
+ // The chief of staff is answering the mail bot in its work thread when the person writes to it in its own chat.
+ await cli("send", "--bot", cos.id, "--task", cos.activeTaskId, "--text", "C1-JOB: mail worked yesterday, find out why it fails");
+ await expect.poll(() => said(cos.activeTaskId, "C1: Post is already asking me about this; I'll answer it there."), { timeout: 20_000 }).toBe(true);
+ const refusal = evidence().find((turn) => turn.planKey === "C1").evidence.find((entry: any) => entry.step).response.result;
+ expect(refusal.isError).toBe(true);
+ expect(JSON.stringify(refusal)).toContain("@Post is already waiting on you: it handed you a request");
+ expect(JSON.stringify(refusal), "the waiting request's words stay in its own thread").not.toContain("P1-ASK");
+
+ writeFileSync(gate, "answer");
+ await expect.poll(() => said(post.activeTaskId, "P1-DONE: nothing stored, so I need the mailbox password from you."), { timeout: 20_000 }).toBe(true);
+ expect(keys(post.id), "the mail bot asked once and heard back once; nothing was handed back to it").toEqual(["P1", "P1-DONE"]);
+ expect(keys(cos.id).sort(), "the chief of staff answered the person and the mail bot, one turn each").toEqual(["C1", "P1-ASK"]);
+ expect(readHandoffs(session.info.dataDir).filter((node) => node.parentId)).toHaveLength(1);
+
+ // A legitimate hand-off the other way, once nothing waits on it any more, goes through as before.
+ await cli("send", "--bot", cos.id, "--task", cos.activeTaskId, "--text", "C2-JOB: ask Post for the mail server's port");
+ await expect.poll(() => said(cos.activeTaskId, "C2-DONE: port 993."), { timeout: 20_000 }).toBe(true);
+ expect(keys(post.id)).toEqual(["P1", "P1-DONE", "C2-WORK"]);
+ expect(readHandoffs(session.info.dataDir).filter((node) => node.parentId).map((node) => node.status)).toEqual(["completed", "completed"]);
+ } finally {
+ await session.close();
+ }
+}, 90_000);
diff --git a/server/runtime-coordinator.test.ts b/server/runtime-coordinator.test.ts
index b2d7cfb48b..9693431543 100644
--- a/server/runtime-coordinator.test.ts
+++ b/server/runtime-coordinator.test.ts
@@ -430,6 +430,64 @@ describe("RuntimeCoordinator: refusals in the legacy words", () => {
});
});
+// Modelled on a real day: the mail bot asked the chief of staff for yesterday's mailbox details, and before that was answered
+// the chief of staff, asked by the person in its own chat, asked the mail bot why mail failed. Both waited on each other and
+// worked the same problem in two places, each with its own plan.
+describe("RuntimeCoordinator: a request back to a bot that is waiting on you", () => {
+ const mail: RoomAddress = { botId: "mail", threadId: "mail-chat" };
+ const cos: RoomAddress = { botId: "cos", threadId: "cos-chat" };
+ const cosWork: RoomAddress = { botId: "cos", threadId: "cos-work-from-mail" };
+ const mailWork: RoomAddress = { botId: "mail", threadId: "mail-work-from-cos" };
+ const holdCos: Script = (node) => node.botId === "cos" && node.parentId !== undefined ? "hold" : undefined;
+
+ it("refuses it while the request it would answer is open, says which, and writes nothing", async () => {
+ const w = world(holdCos);
+ const asked = send(w, mail, "gen-mail", undefined, cosWork, "Do you have the mailbox details from yesterday?");
+ expect(() => send(w, cos, "gen-cos", undefined, mailWork, "Why can't you fetch mail?"))
+ .toThrow(`@mail is already waiting on you: it handed you a request (assignment ${asked.node.id}), and that has not reached you yet.`);
+ expect(w.coordinator.children("gen-cos")).toEqual([]);
+ w.coordinator.tick();
+ expect(w.coordinator.node(asked.node.id)?.status).toBe("running");
+ expect(() => send(w, cos, "gen-cos", undefined, mailWork, "Why can't you fetch mail?")).toThrow(/you are answering it in another conversation/);
+ await w.host.release(asked.node.id, { ok: true, text: "No details stored" });
+ expect(w.coordinator.node(asked.node.id)?.status).toBe("completed");
+ expect(send(w, cos, "gen-cos", undefined, mailWork, "Why can't you fetch mail?").node).toMatchObject({ botId: "mail", status: "queued" });
+ });
+
+ it("refuses a consultation the same way, and while the request waits on a question", async () => {
+ const w = world((node) => node.botId === "cos" && node.parentId !== undefined ? { ok: true, text: "NEEDS INPUT: Which mailbox?" } : undefined);
+ const asked = send(w, mail, "gen-mail", undefined, cosWork, "Do you have the mailbox details from yesterday?");
+ w.coordinator.tick(); await flush();
+ expect(w.coordinator.node(asked.node.id)?.status).toBe("waiting");
+ begun(w, cos, "gen-cos");
+ expect(() => w.coordinator.enqueue(cos, "gen-cos", undefined, mailWork, "Which mailbox do you mean?", { mode: "consult" }))
+ .toThrow(/@mail is already waiting on you/);
+ });
+
+ it("lets it through once the asker stopped waiting: the person stopped that conversation while the answer was being written", async () => {
+ const w = world(holdCos);
+ const asked = send(w, mail, "gen-mail", undefined, cosWork, "Do you have the mailbox details from yesterday?");
+ w.coordinator.tick();
+ expect(w.coordinator.stopAwaitingDirect("mail-chat").map(n => n.id)).toEqual([asked.node.id]);
+ expect(w.coordinator.node(asked.node.id)?.status).toBe("running");
+ expect(send(w, cos, "gen-cos", undefined, mailWork, "Why can't you fetch mail?").node).toMatchObject({ botId: "mail", status: "queued" });
+ await w.host.release(asked.node.id, { ok: true, text: "No details stored" });
+ });
+
+ it("leaves a one-way notice, other teammates, rooms and the bot's own requester alone", async () => {
+ const w = world(holdCos);
+ send(w, mail, "gen-mail", undefined, cosWork, "Do you have the mailbox details from yesterday?");
+ begun(w, cos, "gen-cos");
+ expect(w.coordinator.enqueue(cos, "gen-cos", undefined, mailWork, "FYI: the person says it worked yesterday", { mode: "notify", reply: "none" }).node)
+ .toMatchObject({ botId: "mail", reply: "none" });
+ expect(send(w, cos, "gen-cos", undefined, tester, "Check the mail server").node).toMatchObject({ botId: "tester" });
+ expect(send(w, inRoom("cos"), "gen-room", undefined, inRoom("mail"), "Why can't you fetch mail?").node).toMatchObject({ botId: "mail", groupId: "g1" });
+ // A bot that never asked is not waiting: the mail bot may still ask the chief of staff again from another conversation.
+ expect(send(w, { botId: "mail", threadId: "mail-other" }, "gen-mail-2", undefined, { botId: "cos", threadId: "cos-work-2" }, "And the SMTP host?").node)
+ .toMatchObject({ botId: "cos" });
+ });
+});
+
describe("RuntimeCoordinator: one answer to the same request from two teammates", () => {
const lead: RoomAddress = { botId: "lead", threadId: "lead-chat" };
const builderForLead: RoomAddress = { botId: "builder", threadId: "builder-work-2" };
diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.ts
index f632d0fd96..93ab7afd37 100644
--- a/server/runtime-coordinator.ts
+++ b/server/runtime-coordinator.ts
@@ -19,6 +19,13 @@ const ROOM_ANCESTOR = "A room request cannot return to an ancestor room; results
const DEPTH = "Room handoff depth limit reached";
const BUDGET = "Room handoff budget exhausted";
const NO_TURN = "The requesting turn has no root (no turn)";
+/** A request back to a bot that waits on the asker's answer would leave each waiting on the other, as two bots did on a real
+ * day, each then working the same problem with its own plan. The ancestor rule covers this within one request; this covers
+ * two requests. The waiting request's words are not repeated: it may come from another person's private chat. */
+const crossed = (asker: string, request: Assignment): string => `@${asker} is already waiting on you: it handed you a request (assignment ${
+ request.id}), and ${request.status === "queued" ? "that has not reached you yet" : request.status === "running" ? "you are answering it in another conversation now"
+ : "you have not finished it yet"}. Asking @${asker} for something now would leave each of you waiting on the other, so this was not sent. Answer the person here from what you know; @${
+ asker}'s request reaches you in its own thread, and your answer there goes back to it. Once @${asker} has that answer, you can ask it again.`;
const BRIEF_MAX = 12_000;
const RUNTIME_DEPTH = /^Assignment depth limit reached/;
@@ -225,6 +232,8 @@ export class RuntimeCoordinator implements Coordinator {
if (mode === "work" && !rework && siblings.some(c => c.mode === "work" && kindOf(c.assignee.destination.groupId, parent) === kind &&
c.assignee.destination.groupId === target.groupId && c.assignee.botId === target.botId && c.status === "completed")) throw new Error(ALREADY_COMPLETED);
if (kind === "work" && target.groupId && lineage.some(n => n.assignee.destination.groupId === target.groupId)) throw new Error(ROOM_ANCESTOR);
+ const waiting = mode === "notify" || target.groupId !== undefined ? undefined : this.waitingOn(source.botId, target.botId);
+ if (waiting) throw new Error(crossed(this.host.names(this.project(waiting.request), this.project(waiting.parent)).requester, waiting.request));
const wanted: Reply = mode === "notify" ? "none" : options.reply ?? "resume";
const reply: Reply = wanted === "none" ? "none" : root.reply === "poll" ? "poll" : wanted;
const requester: Requester = { kind: "bot_turn", botId: parent.assignee.botId, threadId: parent.assignee.destination.threadId,
@@ -585,6 +594,16 @@ export class RuntimeCoordinator implements Coordinator {
}
}
+ /** Direct work `asker` handed to `botId` and still waits on: an open request whose requesting turn is still open. */
+ private waitingOn(botId: string, asker: string): { request: Assignment; parent: Assignment } | undefined {
+ for (const request of this.live()) {
+ if (request.assignee.botId !== botId || request.requester.botId !== asker || request.reply === "none" || request.assignee.destination.groupId !== undefined) continue;
+ const parent = request.parentId ? this.store.get(request.parentId) : undefined;
+ if (parent && !isTerminal(parent)) return { request, parent };
+ }
+ return undefined;
+ }
+
private parkedIn(threadId: string): Assignment | undefined {
return this.live().find(n => n.status === "needs_input" && n.assignee.destination.threadId === threadId);
}