Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
A stop the person made is remembered against the same request coming back
milind-soni70c9109317cd
diff --git a/server/remembered-stop.e2e.test.ts b/server/remembered-stop.e2e.test.tsnew file mode 100644index 0000000000..76b8928b56--- /dev/null+++ b/server/remembered-stop.e2e.test.ts@@ -0,0 +1,57 @@+// A stop the person made is remembered, end to end on the scripted engine. The person stops a teammate working on their+// request; the bot that asked hears it stopped and tries to hand the same work back: refused, until the person asks+// again. Then it goes through as usual.+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("keeps a teammate the person stopped from getting the same request back, until the person asks again", 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 research = (await cli("new-bot", "--name", "Research")).bot;+ const planPath = join(session.info.dataDir, "room-plan.json");+ const started = join(session.info.dataDir, "research-started");+ const again = (expectError: boolean) => ({ arguments: { bot_ids: [research.id], message: "R1-AGAIN: please still look up the mail host" }, expectError });+ writeFileSync(planPath, JSON.stringify({+ [post.id]: { script: [+ { key: "R1", match: ["R1-JOB"], steps: [{ arguments: { bot_ids: [research.id], message: "R1-ASK: look up the mail host" } }], reply: "R1: asked Research." },+ { key: "R1-BACK", match: [SETTLED, "R1-JOB"], steps: [again(true)], reply: "R1-BACK: Research was stopped; say if you want it looked up." },+ { key: "R2", match: ["R1-JOB"], steps: [again(false)], reply: "R2: asked Research again." },+ { key: "R2-DONE", match: [SETTLED, "R1-JOB"], reply: "R2-DONE: the host is imap.example.test." },+ ] },+ [research.id]: { script: [+ { key: "R1-ASK", match: ["R1-ASK"], readyFile: started, delayMs: 8_000, reply: "R1-ASK late: imap.example.test" },+ { key: "R2-WORK", match: ["R1-AGAIN"], reply: "R2-WORK: imap.example.test" },+ ] },+ }));+ const evidence = (): any[] => existsSync(`${planPath}.evidence.jsonl`)+ ? readFileSync(`${planPath}.evidence.jsonl`, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [];+ const said = async (threadId: string, text: string) => ((await api(`/api/threads/${threadId}/messages`)).messages as any[]).some((row) => row.text === text);+ const step = (key: string) => evidence().find((turn) => turn.planKey === key)?.evidence.find((entry: any) => entry.step)?.response.result;++ await cli("send", "--bot", post.id, "--task", post.activeTaskId, "--text", "R1-JOB: find out where my mail lives");+ await expect.poll(() => existsSync(started), { timeout: 20_000 }).toBe(true);+ const work = readHandoffs(session.info.dataDir).find((node) => node.parentId)!;+ // The person stops Research's work in its own thread.+ await cli("interrupt", "--bot", research.id, "--task", work.threadId);+ await expect.poll(() => said(post.activeTaskId, "R1-BACK: Research was stopped; say if you want it looked up."), { timeout: 20_000 }).toBe(true);+ expect(step("R1-BACK").isError).toBe(true);+ expect(JSON.stringify(step("R1-BACK"))).toContain("The person stopped this teammate's work on this request.");++ // The person asks again, in the same words: the same hand-off goes through.+ await cli("send", "--bot", post.id, "--task", post.activeTaskId, "--text", "R1-JOB: find out where my mail lives");+ await expect.poll(() => said(post.activeTaskId, "R2-DONE: the host is imap.example.test."), { timeout: 20_000 }).toBe(true);+ expect(evidence().filter((turn) => turn.botId === research.id).map((turn) => turn.planKey)).toContain("R2-WORK");+ } finally {+ await session.close();+ }+}, 90_000);diff --git a/server/runtime-coordinator.test.ts b/server/runtime-coordinator.test.tsindex a49bd5b917..3e8f32cfb5 100644--- a/server/runtime-coordinator.test.ts+++ b/server/runtime-coordinator.test.ts@@ -718,6 +718,61 @@ describe("RuntimeCoordinator: stops", () => {});});+describe("RuntimeCoordinator: a stop the person made is remembered", () => {+ const tick = () => sleep(2);++ it("keeps the work it stopped from coming back from that request, until the person asks again", async () => {+ const w = world(hold);+ const { node } = send(w, chief, "gen-1", undefined, builder, "Build it");+ begun(w, { botId: "tester", threadId: "tester-chat" }, "gen-2");+ begun(w, { botId: "tester", threadId: "tester-other" }, "gen-4", "Order more paper", { origin: { kind: "user", request: "Order more paper" } });+ w.coordinator.tick();+ await tick();+ w.coordinator.stopAwaitingDirect("builder-work");+ expect(w.coordinator.node(node.id)?.status).toBe("cancelled");+ await tick();+ // The request that handed it out, in other words, and another conversation on the same line of the person's: refused.+ expect(() => send(w, chief, "gen-1", undefined, builder, "Please build the CSV export after all")).toThrow("The person stopped this teammate's work on this request.");+ expect(() => send(w, { botId: "tester", threadId: "tester-chat" }, "gen-2", undefined, builder, "Build it for me")).toThrow(/stopped this teammate's work/);+ expect(w.coordinator.children("gen-2")).toEqual([]);+ // Another request of the person's, other teammates, and the person asking again after the stop, go through.+ expect(send(w, { botId: "tester", threadId: "tester-other" }, "gen-4", undefined, builder, "Order the paper").node).toMatchObject({ botId: "builder" });+ expect(send(w, chief, "gen-1", undefined, tester, "Test it").node).toMatchObject({ botId: "tester", status: "queued" });+ expect(send(w, { botId: "chief", threadId: "chief-2" }, "gen-3", undefined, builder, "Build it").node).toMatchObject({ botId: "builder", status: "queued" });+ });++ it("remembers every bot the stop ended, and nothing for a stop with another cause or work no person asked for", async () => {+ const w = world(hold);+ const { node } = send(w, chief, "gen-1", undefined, builder, "Build it");+ w.coordinator.tick();+ begun(w, inRoom("other"), "gen-room");+ await tick();+ w.coordinator.stopAwaitingDirect("chief-chat");+ expect(w.coordinator.node(node.id)?.status).toBe("cancelled");+ await tick();+ expect(() => send(w, inRoom("other"), "gen-room", undefined, builder, "Build it")).toThrow(/stopped this teammate's work/);+ expect(() => send(w, inRoom("other"), "gen-room", undefined, chief, "Ship it")).toThrow(/stopped this teammate's work/);++ const h = world(hold);+ const first = send(h, chief, "gen-1", undefined, builder, "Build it");+ h.coordinator.tick();+ await tick();+ h.coordinator.stopAwaitingDirect("builder-work", "Turn interrupted — provider settings changed");+ expect(h.coordinator.node(first.node.id)?.status).toBe("cancelled");+ expect(send(h, chief, "gen-1", undefined, builder, "Build it again").node).toMatchObject({ botId: "builder" });++ const r = world(hold);+ r.coordinator.beginTurn({ id: "gen-run", address: chief, brief: "Nightly export", level: "ask",+ opener: { requester: { kind: "routine_run", runId: "run-1", botId: "chief", threadId: "chief-chat" }, origin: { kind: "routine", source: "routine", ref: "nightly" } } });+ const nightly = r.coordinator.enqueue(chief, "gen-run", undefined, builder, "Export", {});+ r.coordinator.tick();+ await tick();+ r.coordinator.stopAwaitingDirect("builder-work");+ expect(r.coordinator.node(nightly.node.id)?.status).toBe("cancelled");+ expect(r.coordinator.enqueue(chief, "gen-run", undefined, builder, "Export again", {}).node).toMatchObject({ botId: "builder" });+ });+});+describe("RuntimeCoordinator: read models", () => {it("awaitingTeammateThreads answers, for every thread at once, what outstandingDirect and the parked roots answer per thread", async () => {const w = world(hold);diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.tsindex 4bf49cdb41..2636cc8ac1 100644--- a/server/runtime-coordinator.ts+++ b/server/runtime-coordinator.ts@@ -20,6 +20,13 @@ const ROOM_ANCESTOR = "A room request cannot return to an ancestor room; resultsconst DEPTH = "Room handoff depth limit reached";const BUDGET = "Room handoff budget exhausted";const NO_TURN = "The requesting turn has no root (no turn)";+/** A stop with no other cause is the person's own. */+const STOPPED_BY_USER = "Stopped by user";+/** How long a person's stop holds against the same request coming back. */+const STOP_MEMORY_MS = 24 * 60 * 60_000;+const STOPPED_AGAIN = "The person stopped this teammate's work on this request. It isn't handed out again until the person asks again: tell them what you still wanted done, and don't send it another way.";+/** The person's request a tree traces to, as one key: their own words, harness-quoted. Empty when no person's line started it. */+const requestKey = (root: Assignment): string => root.origin.kind === "person" ? (root.origin.quote ?? "").replace(/\s+/g, " ").trim().toLowerCase() : "";const BRIEF_MAX = 12_000;const RUNTIME_DEPTH = /^Assignment depth limit reached/;@@ -127,6 +134,8 @@ export class RuntimeCoordinator implements Coordinator {private readonly legacyThreads: LegacyThreadResolver | undefined;private readonly now: () => number;private readonly log: (line: string) => void;+ /** The person's stops, remembered: which bots' work on which request they stopped, and when. */+ private readonly stops: Array<{ at: number; request: string; bots: Set<string> }> = [];private opened = false;private prunedAt: number | undefined;@@ -220,6 +229,7 @@ export class RuntimeCoordinator implements Coordinator {const lineage = path(this.store, parent);const root = lineage[0]!;if (!answersSender(parent, mode, target) && lineage.some(n => ancestorOf(address(n), target))) throw new Error(ANCESTOR);+ if (this.stoppedFor(root, target.botId)) throw new Error(STOPPED_AGAIN);const siblings = this.store.children(parent.id);const existing = siblings.findLast(c => c.assignee.botId === target.botId && c.assignee.destination.groupId === target.groupId && c.brief === brief && c.mode === mode);if (existing && !(rework && isTerminal(existing))) return { node: view(existing, parent), duplicate: true };@@ -388,9 +398,28 @@ export class RuntimeCoordinator implements Coordinator {for (const n of this.live()) if (this.direct(n, threadId)) this.runtime.cancel(n.id, reason, "stopped");}- stopAwaitingDirect(threadId: string, reason = "Stopped by user"): void {+ stopAwaitingDirect(threadId: string, reason = STOPPED_BY_USER): void {this.ready();+ const stopping = reason === STOPPED_BY_USER ? this.live().filter(n => n.assignee.destination.threadId === threadId) : [];+ const trees = stopping.map(n => ({ root: this.store.get(n.rootId), work: this.subtree(n).filter(a => !isTerminal(a)) }));this.runtime.stopRequester({ threadId }, reason);+ for (const { root, work } of trees) if (root) this.rememberStop(root, work);+ }++ /** The person's stop, remembered (scoped to that request): the bots whose work on it the stop ended don't take the same+ * request from another bot again, unless the person asked again after the stop. In memory only, for a day. */+ private rememberStop(root: Assignment, work: readonly Assignment[]): void {+ const request = requestKey(root);+ const bots = new Set(work.filter(a => this.store.get(a.id)?.status === "cancelled").map(a => a.assignee.botId));+ const at = this.now();+ while (this.stops.length && at - this.stops[0]!.at > STOP_MEMORY_MS) this.stops.shift();+ if (request && bots.size) this.stops.push({ at, request, bots });+ }++ /** Work for `root`'s request was stopped for `botId`, and this request is not one the person made after that stop. */+ private stoppedFor(root: Assignment, botId: string): boolean {+ const request = requestKey(root);+ return request !== "" && this.stops.some(stop => stop.request === request && stop.bots.has(botId) && root.createdAt <= stop.at && this.now() - stop.at <= STOP_MEMORY_MS);}activeDirect(threadId: string): boolean {