Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Let a bot steer its own report-back thread and send it follow-ups
AdityaUmaled5fededd4397
diff --git a/server/drivers/agents-call.ts b/server/drivers/agents-call.tsindex de223bffa5..c33e134539 100644--- a/server/drivers/agents-call.ts+++ b/server/drivers/agents-call.ts@@ -474,7 +474,7 @@ export async function callTool(called: string, input: Json, context: ToolCallConconst r = await api("/api/internal/threads", { method: "POST", body: JSON.stringify(body) });if (r.error && r.state !== "failed") return { text: `Couldn't open that thread: ${String(r.error)}`, isError: true };if (r.reportBack === true) {- return { text: `Opened thread #${String(r.title ?? title)} on yourself [thread id: ${String(r.threadId ?? "")}]. It starts when this turn ends, and its result comes back to this conversation and resumes you automatically (assignment id: ${String(r.requestId ?? "unknown")}). Mention it to the person as #${String(r.title ?? title)} and finish your turn; do not check or wait for it in this turn.` };+ return { text: `Opened thread #${String(r.title ?? title)} on yourself [thread id: ${String(r.threadId ?? "")}]. It starts when this turn ends, and its result comes back to this conversation and resumes you automatically (assignment id: ${String(r.requestId ?? "unknown")}). Mention it to the person as #${String(r.title ?? title)} and finish your turn; do not check or wait for it in this turn. To steer it or send it a follow-up, while it runs or after, use coordinate_bots with bot_ids ["${BOT_ID}"] and thread "${String(r.threadId ?? "")}".` };}const receipt = r.self !== true && Array.isArray(r.receipts) && jsonRecord(r.receipts[0]) ? r.receipts[0] : undefined;const threadTitle = String(r.title ?? receipt?.title ?? title);diff --git a/server/host/own-threads.ts b/server/host/own-threads.tsindex 3ce77d4adf..08b201cea2 100644--- a/server/host/own-threads.ts+++ b/server/host/own-threads.ts@@ -37,7 +37,12 @@ export function createOwnThreads(deps: {const reason = chosen && cannotRun(chosen, bot);return reason ? `${reason} Nothing ran on another model in its place; open it again on a model list_models offers.` : null;},- /** `answers` names a question one of `botId`'s own threads waits on: the one message a bot may address to itself. */+ /** `thread` is a report-back thread `botId` opened from `fromThreadId`: its opener may steer it or send it follow-ups. */+ steersOwn(thread: string, botId: string, fromThreadId: string): boolean {+ const openedBy = thread === "new" || thread === "standing" ? undefined : store.taskByThread(botId, thread)?.openedBy;+ return openedBy?.botId === botId && openedBy.threadId === fromThreadId && openedBy.kind === undefined && !openedBy.roomLane;+ },+ /** `answers` names a question one of `botId`'s own threads waits on: with steersOwn, the only messages a bot may address to itself. */answersOwn(answers: string | undefined, botId: string): boolean {const asked = answers === undefined ? undefined : deps.node(answers);const requester = asked?.parentId === undefined ? undefined : deps.node(asked.parentId);diff --git a/server/index.ts b/server/index.tsindex 2aee79bbd3..2601db7f91 100644--- a/server/index.ts+++ b/server/index.ts@@ -13746,7 +13746,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (fresh && !EXTERNAL && internalCapability.openedThreads >= MAX_THREADS_OPENED_PER_TURN) {return refuse(429, `You have already opened ${MAX_THREADS_OPENED_PER_TURN} threads this turn, which is the limit. Do not retry — finish your turn and tell the person which threads you still wanted to open, so they can open them or ask you again.`);}- const toSelf = Boolean(call.ownThread) || ownThreads.answersOwn(call.answers, internalSender.id);+ const steersOwn = !destination && botIds.length === 1 && botIds[0] === internalSender.id && ownThreads.steersOwn(call.thread, internalSender.id, address.threadId), toSelf = Boolean(call.ownThread) || steersOwn || ownThreads.answersOwn(call.answers, internalSender.id);for (const target of targets) {// Echo only the id the caller sent, never a bot's name.const addressed = store.bot(target.botId);@@ -13820,7 +13820,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const routed = lane ? { botId: target.botId, threadId: lane.threadId } : target;outsideLineage.carry(address.threadId, routed.threadId);const { node, duplicate } = coordinator.enqueue(address, generation, internalCapability.roomHandoffId, routed, call.message, {- mode, reply, thread: lane || fresh ? "new" : "standing", approvalGranted, rework: call.rework, ...(lane ? {} : { requestBatchKey }), ...(call.ownThread ? { ownThread: true } : {}),+ mode, reply, thread: lane || fresh || steersOwn ? "new" : "standing", approvalGranted, rework: call.rework, ...(lane ? {} : { requestBatchKey }), ...(call.ownThread || steersOwn ? { ownThread: true } : {}),...(call.doneWhen ? { doneWhen: call.doneWhen } : {}),});usageTrace.link(node.id, node.parentId, { threadId: internalCapability.threadId, turnId: liveTurnByThread.get(internalCapability.threadId) ?? "" }); if (!duplicate) actingPeople.handOn(internalCapability, node);diff --git a/server/thread-aware-bots.e2e.test.ts b/server/thread-aware-bots.e2e.test.tsindex d5675021a4..a097183eac 100644--- a/server/thread-aware-bots.e2e.test.ts+++ b/server/thread-aware-bots.e2e.test.ts@@ -506,6 +506,55 @@ describe("start_thread on another model, reporting back", () => {}}, 60_000);+ it("lets the opener steer its own report-back thread while it runs and send it a follow-up after, never another thread of its own", async () => {+ const pm = await createBot("Pam", "gated");+ try {+ const token = await heldTurn(pm, "Get a review of the diff.");+ const opened = await api("POST", "/api/internal/threads", { title: "Review: steer", message: "Review the diff. [[gate:own-steer]]", reportBack: true }, token);+ expect(opened.status, JSON.stringify(opened.body)).toBe(201);+ const { threadId, requestId } = opened.body;+ await expect.poll(() => handoffs().find((node) => node.id === requestId)?.status, { timeout: 15_000 }).toBe("running");+ await expect.poll(() => dumpOf("own-steer"), { timeout: 15_000 }).toBeTruthy();+ const seen = () => JSON.stringify([...promptsOf("own-steer"), ...promptsOf(threadId)]);+ // The opener's turn ends, and the person's next message asks it to steer the thread still running.+ rmSync(join(gates, `${pm.threadId}.json`), { force: true });+ release(pm.threadId);+ await expect.poll(() => handoffs().find((node) => node.threadId === pm.threadId)?.status, { timeout: 15_000 }).toBe("waiting");+ rmSync(join(gates, `${pm.threadId}.gate`), { force: true });+ const nextSent = await api("POST", `/api/bots/${pm.id}/messages`, { text: "Have it check the tests too.", threadId: pm.threadId });+ expect(nextSent.status).toBe(202);+ const later = await liveToken(pm.threadId);++ const steered = await api("POST", "/api/internal/coordinate-bots", { botIds: [pm.id], message: "Also check the tests.", thread: threadId }, later);+ expect(steered.status, JSON.stringify(steered.body)).toBe(200);+ expect(steered.body.receipts).toMatchObject([{ outcome: "injected", threadId, requestId }]);+ expect((await messages(threadId)).find((message) => message.text === "Also check the tests.")).toMatchObject({ role: "user", steered: true, peerAsk: { botId: pm.id } });+ release(threadId);+ release("own-steer");+ await expect.poll(() => handoffs().filter((node) => node.threadId === threadId).every((node) => node.status === "completed"), { timeout: 15_000 }).toBe(true);++ const followUp = await api("POST", "/api/internal/coordinate-bots", { botIds: [pm.id], message: "One more: check the docs.", thread: threadId }, later);+ expect(followUp.status, JSON.stringify(followUp.body)).toBe(200);+ const [receipt] = followUp.body.receipts;+ expect(receipt).toMatchObject({ threadId });+ await expect.poll(seen, { timeout: 15_000 }).toContain("One more: check the docs.");+ await expect.poll(() => handoffs().find((node) => node.id === receipt.requestId)?.status, { timeout: 15_000 }).toBe("completed");+ expect((await botState(pm.id)).tasks.filter((task: any) => task.title === "Review: steer")).toHaveLength(1);++ const standing = await api("POST", "/api/internal/coordinate-bots", { botIds: [pm.id], message: "Do it again." }, later);+ expect([standing.status, standing.body.error]).toEqual([403, "Choose a teammate, not yourself"]);+ const quiet = await api("POST", "/api/internal/threads", { title: "Quiet job", message: "Tidy up. [[gate:own-quiet]]" }, later);+ expect(quiet.status, JSON.stringify(quiet.body)).toBe(201);+ const notReporting = await api("POST", "/api/internal/coordinate-bots", { botIds: [pm.id], message: "Faster.", thread: quiet.body.threadId }, later);+ expect([notReporting.status, notReporting.body.error]).toEqual([403, "Choose a teammate, not yourself"]);+ release("own-quiet");+ release(pm.threadId);+ await expect.poll(async () => (await botState(pm.id))?.busy, { timeout: 15_000 }).toBe(false);+ } finally {+ await cleanup([pm.id]);+ }+ }, 60_000);+it("fails a report-back thread whose model can no longer run when its turn comes, instead of running it on the bot's own model", async () => {const pm = await createBot("Pam", "gated");try {