Skip to content

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

A room member can hand work to a bot of the person's other place (#6098)

Milind Soni9774d0f9c43c
diff --git a/server/bot-link.e2e.test.ts b/server/bot-link.e2e.test.ts
index 8b0d180573..8d2319a860 100644
--- a/server/bot-link.e2e.test.ts
+++ b/server/bot-link.e2e.test.ts
@@ -112,6 +112,20 @@ it("a bot on the computer and a bot on the person's own server hand each other w
expect((await home.cli("wait", "--bot", atlas.id, "--task", atlas.activeTaskId, "--timeout", "30")).status).toBe("settled");
expect((await home.messages(atlas.activeTaskId)).filter((message) => message.kind === "text").at(-1)).toMatchObject({ role: "bot", text: "Writer drafted it." });
+ // From a room: the other place's bot is in no room here, so it gets the work directly and its result comes back to the room.
+ const editor = (await computer.cli("new-bot", "--name", "Editor")).bot;
+ const room = (await computer.cli("new-channel", "--name", "Newsroom", "--members", `${writer.id},${editor.id}`)).channel;
+ home.plan(atlas.id, { reply: "Atlas checked: 3 returns." });
+ computer.plan(writer.id,
+ { steps: [{ tool: "coordinate_bots", arguments: { bot_ids: ["Atlas"], request_key: "returns", message: "Count this week's returns." } }], reply: "Asked Atlas about returns." },
+ { reply: "Atlas counts 3 returns." });
+ await computer.cli("send-channel", "--channel", room.id, "--text", "@Writer ask Atlas how many returns we had.");
+ await expect.poll(async () => (await computer.messages(room.activeTaskId)).some((message) => message.roomRequest?.phase === "result" && /3 returns/.test(message.tool?.output ?? "")), { timeout: 40_000 }).toBe(true);
+ expect(await computer.cli("wait", "--channel", room.id, "--timeout", "30")).toMatchObject({ status: "settled" });
+ const said = await computer.messages(room.activeTaskId);
+ expect(said.some((message) => message.kind === "text" && message.text === "Atlas counts 3 returns.")).toBe(true);
+ expect(said.find((message) => message.roomRequest?.phase === "result").tool.name).toContain("Atlas (My server)");
+
// Off on the computer: the server is told, and neither keeps the link.
expect(await computer.api("PUT", "/api/bot-link", { on: false })).toEqual({ on: false });
await expect.poll(() => existsSync(join(home.dataDir, "bot-link.json")), { timeout: 10_000 }).toBe(false);
diff --git a/server/bot-link/link.test.ts b/server/bot-link/link.test.ts
index 86f63a21df..a94b379517 100644
--- a/server/bot-link/link.test.ts
+++ b/server/bot-link/link.test.ts
@@ -40,7 +40,7 @@ function place(label: string, bots: Bot[]) {
const dir = mkdtempSync(join(tmpdir(), `bot-link-${label}-`));
const threads = new Set<string>();
const runs: Array<{ botId: string; threadId: string; text: string; resumed: boolean; requester: string; origin: unknown }> = [];
- const sent: Array<{ recipient: string; threadId: string }> = [];
+ const sent: Array<{ recipient: string; threadId: string; roomId?: string }> = [];
const results: Array<{ thread: string; name: string; status: string; result: string }> = [];
const requests: string[] = [];
const issued = new Map<string, string>();
@@ -65,7 +65,7 @@ function place(label: string, bots: Bot[]) {
dataDir: dir, coordinator: () => coordinator, bots: () => bots, bot: (id) => bots.find((bot) => bot.id === id), level: () => "full",
openThread: (bot) => { const id = `${bot.id}-work-${++opened}`; threads.add(id); return id; },
hasThread: (_botId, threadId) => threads.has(threadId), personName: () => "Sam",
- sentRow: (input) => { sent.push({ recipient: input.recipient.name, threadId: input.threadId }); },
+ sentRow: (input) => { sent.push({ recipient: input.recipient.name, threadId: input.threadId, ...(input.roomId ? { roomId: input.roomId } : {}) }); },
resultRow: (parent, child, name) => { results.push({ thread: parent.threadId, name, status: child.status, result: child.result }); },
kick: () => { queueMicrotask(() => { try { coordinator.tick(); } catch { /* closed */ } }); },
revoke: (sessionId) => { for (const [token, id] of issued) if (id === sessionId) issued.delete(token); },
@@ -135,10 +135,11 @@ function place(label: string, bots: Bot[]) {
}
/** One of this place's bots takes a turn in which it hands work on; the turn then ends and waits for it. */
- async function handOff(from: string, input: CoordinateBotsCall, local: (input: CoordinateBotsCall) => Promise<{ status: number; body: Record<string, unknown> }> = async () => ({ status: 200, body: { receipts: [] } })) {
- const id = `${label}-turn-${++generation}`, address = { botId: from, threadId: `${from}-chat` };
+ async function handOff(from: string, input: CoordinateBotsCall, local: (input: CoordinateBotsCall) => Promise<{ status: number; body: Record<string, unknown> }> = async () => ({ status: 200, body: { receipts: [] } }),
+ room?: { id: string; problem?: string }) {
+ const id = `${label}-turn-${++generation}`, address = room ? { groupId: room.id, botId: from, threadId: `${room.id}-thread` } : { botId: from, threadId: `${from}-chat` };
coordinator.beginTurn({ id, address, brief: "Sort it out", level: "full", origin: { kind: "user", request: "Sort it out" } });
- const answer = await link.coordinate(input, { sender: bots.find((bot) => bot.id === from)!, address, generation: id, external: false, handed: () => {} }, local);
+ const answer = await link.coordinate(input, { sender: bots.find((bot) => bot.id === from)!, address, generation: id, external: false, handed: () => {}, ...(room?.problem ? { problem: room.problem } : {}) }, local);
coordinator.endTurn(id, { ok: true, text: "Handed on." });
return { id, answer, receipts: (answer.body.receipts ?? []) as Array<{ botId: string; outcome: string; detail: string; requestId?: string }> };
}
@@ -671,6 +672,26 @@ describe("the link between a computer and its Cloud", () => {
expect(readdirSync(root)).toEqual([]);
});
+ it("a room member hands work to a bot of the other place: it goes directly, and its result comes back to the room", async () => {
+ const { computer, cloud } = await two();
+ const { receipts } = await computer.handOff("local-writer", call(["Analyst"], "Count the orders"), undefined, { id: "newsroom" });
+ expect(receipts[0]).toMatchObject({ botId: onCloud("cloud-analyst"), outcome: "queued" });
+ await until(() => computer.results.length === 1, "the result is back in the room");
+ expect(computer.sent).toEqual([{ recipient: "Analyst (My Cloud)", threadId: "newsroom-thread", roomId: "newsroom" }]);
+ expect(computer.results[0]).toMatchObject({ thread: "newsroom-thread", name: "Analyst (My Cloud)", status: "completed" });
+ expect(cloud.runs.filter((run) => run.botId === "cloud-analyst").map((run) => run.threadId)).toEqual(["cloud-analyst-work-1"]);
+ await until(() => computer.runs.some((run) => run.resumed && run.threadId === "newsroom-thread"), "the member is resumed in the room");
+
+ const other = await computer.handOff("local-writer", call(["Analyst"], "Count again", { groupId: "another-room" }), undefined, { id: "newsroom" });
+ expect(other.answer.status).toBe(409);
+ expect(String(other.answer.body.error)).toContain("in no room here");
+ const left = await computer.handOff("local-writer", call(["Analyst"], "Count once more"), undefined, { id: "newsroom", problem: "Coordination needs a room you are a member of, or your own conversation." });
+ expect(left.answer.status).toBe(409);
+ expect(String(left.answer.body.error)).toContain("a room you are a member of");
+ await new Promise((resolve) => setTimeout(resolve, 150));
+ expect(cloud.runs.filter((run) => run.botId === "cloud-analyst")).toHaveLength(1);
+ });
+
it("the link's sign-in reaches the link's own routes and nothing else", () => {
const linked = { userId: "bot-link:computer-environment" };
expect(linkSessionRefusal(linked, "POST", SYNC_PATH)).toBeNull();
diff --git a/server/bot-link/link.ts b/server/bot-link/link.ts
index f573823c2f..553c8626de 100644
--- a/server/bot-link/link.ts
+++ b/server/bot-link/link.ts
@@ -118,7 +118,8 @@ export interface BotLinkDeps {
hasThread(botId: string, threadId: string): boolean;
personName(threadId: string): string | undefined;
/** "Sent to …" in the requester's conversation. */
- sentRow(input: { sender: LocalBot; threadId: string; recipient: { id: string; name: string }; workThreadId: string; nodeId: string; reason?: string; doneWhen?: string }): void;
+ sentRow(input: { sender: LocalBot; threadId: string; recipient: { id: string; name: string }; workThreadId: string; nodeId: string; reason?: string; doneWhen?: string;
+ /** The room the sender speaks in: the bot of the other place is not in it, so it got the work directly. */ roomId?: string }): void;
/** The files that travel with hand-offs (server/host/handoff-files.ts). Absent: files do not cross. */
files?: {
/** What this assignment carries one way, in the attachment store. */
@@ -145,6 +146,8 @@ export interface CoordinateContext {
parentId?: string;
/** The caller is not one of this place's own turns. */
external: boolean;
+ /** Why this conversation may not hand work on at all (it left its room, its task is gone), as for any hand-off. */
+ problem?: string;
handed(nodeId: string): void;
}
type CoordinateResult = { status: number; body: Record<string, unknown> };
@@ -617,7 +620,7 @@ export function createBotLink(deps: BotLinkDeps) {
if (!online) for (const listener of wantedListeners) listener();
if (!duplicate) {
context.handed(node.id);
- deps.sentRow({ sender: context.sender, threadId: context.address.threadId, recipient: { id: linked, name: `${remote.bot.name} (${place})` }, workThreadId: threadId, nodeId: node.id,
+ deps.sentRow({ sender: context.sender, threadId: context.address.threadId, recipient: { id: linked, name: `${remote.bot.name} (${place})` }, workThreadId: threadId, nodeId: node.id, ...(context.address.groupId ? { roomId: context.address.groupId } : {}),
...(call.reason ? { reason: call.reason } : {}), ...(call.doneWhen ? { doneWhen: call.doneWhen } : {}) });
}
} catch (error) {
@@ -638,7 +641,10 @@ export function createBotLink(deps: BotLinkDeps) {
}
/** Why this call cannot go to another place at all, or null. */
function unsupportedHere(call: CoordinateBotsCall, context: CoordinateContext, place: string): string | null {
- return call.groupId || context.address.groupId ? `Work in a room does not reach ${place} yet: hand it to the bot directly, from your own conversation`
+ // A bot of another place is in no room here. Named from a room, it gets the work directly, in a thread of its own
+ // there, and its result comes back to the room, as for any bot outside a room.
+ return context.problem ? context.problem
+ : call.groupId && call.groupId !== context.address.groupId ? `${place}'s bots are in no room here: hand it to the bot from your own conversation, or from the room you are speaking in`
: call.answers || call.post || call.ownThread ? `That does not reach ${place} yet: send the bot plain work or a question instead`
: call.consult && call.reply === "none" ? "consult asks a question whose answer comes back to you; leave reply out" : null;
}
diff --git a/server/host/bot-link-host.ts b/server/host/bot-link-host.ts
index 4c27e1a15a..fc5fa202c0 100644
--- a/server/host/bot-link-host.ts
+++ b/server/host/bot-link-host.ts
@@ -17,7 +17,7 @@ import { sentRow, teammateResultRow } from "./handoff-sent.ts";
export interface BotLinkHostDeps {
dataDir: string;
environmentId: string;
- store: Pick<Store, "bots" | "bot" | "createTask" | "taskByThread" | "appendMessage" | "patchTask" | "onChange">;
+ store: Pick<Store, "bots" | "bot" | "createTask" | "taskByThread" | "appendMessage" | "patchTask" | "onChange" | "group" | "groupTaskByThread" | "markGroupThreadUnread">;
coordinator(): Coordinator;
kick(): void;
level(bot: BotRecord): Level;
@@ -56,17 +56,20 @@ export function createBotLinkHost(deps: BotLinkHostDeps) {
return stored;
},
},
- sentRow: ({ sender, threadId, recipient, workThreadId, nodeId, reason, doneWhen }) => {
- store.appendMessage(threadId, sentRow({ sender: { id: sender.id, name: sender.name, color: sender.color ?? "blue" }, recipient: { ...recipient, color: "blue" }, threadId: workThreadId, via: "direct", language: deps.language(threadId),
+ sentRow: ({ sender, threadId, recipient, workThreadId, nodeId, reason, doneWhen, roomId }) => {
+ const room = roomId ? store.group(roomId) : undefined;
+ store.appendMessage(threadId, sentRow({ sender: { id: sender.id, name: sender.name, color: sender.color ?? "blue" }, recipient: { ...recipient, color: "blue" }, threadId: workThreadId, via: "direct", language: deps.language(threadId), ...(room ? { room: { id: room.id, name: room.name, here: true } } : {}),
...(reason ? { reason } : {}), ...(doneWhen ? { doneWhen: redactSecretsInText(doneWhen) } : {}), ...deps.files.sentWith(nodeId) }));
},
resultRow: (parent: HandoffView, child: HandoffView, name: string) => {
- if (!store.taskByThread(parent.botId, parent.threadId)) return;
+ const room = parent.groupId ? store.group(parent.groupId) : undefined;
+ if (parent.groupId ? !room || !store.groupTaskByThread(room.id, parent.threadId) : !store.taskByThread(parent.botId, parent.threadId)) return;
const done = child.status === "completed";
store.appendMessage(parent.threadId, { role: "bot", kind: "activity", roomRequest: { id: child.id, phase: "result" }, ...deps.files.returnedWith(child, parent),
tool: { name: teammateResultRow(deps.language(parent.threadId), child, name, undefined, undefined), ok: done,
...(done && child.result.trim() ? { output: redactSecretsInText(child.result.trim()).slice(0, 2_000) } : {}) } });
- if (!parent.parentId && parent.reply !== "poll") store.patchTask(parent.botId, parent.threadId, { unread: true });
+ if (room) store.markGroupThreadUnread(room.id, parent.threadId, true);
+ else if (!parent.parentId && parent.reply !== "poll") store.patchTask(parent.botId, parent.threadId, { unread: true });
},
});
const dialer = createDialer({ link, log: deps.log });
diff --git a/server/index.ts b/server/index.ts
index 45130ec9a3..1d7b932a44 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -13631,7 +13631,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
});
}
const EXTERNAL = internalCapability.generation === EXTERNAL_RUNTIME_GENERATION;
- const coordinateHere = async (call: CoordinateBotsCall): Promise<{ status: number; body: Record<string, unknown> }> => {
+ const linkSourceProblem = (botId: string, threadId: string) => { const source = store.groupByThread(threadId); return source && (source.dm || !source.memberIds.includes(botId)) ? "Coordination needs a room you are a member of, or your own conversation." : roomHandoffProblem({ groupId: source?.id, threadId, botId }); }; const coordinateHere = async (call: CoordinateBotsCall): Promise<{ status: number; body: Record<string, unknown> }> => {
const refuse = (status: number, error: string, more: Record<string, unknown> = {}) => ({ status, body: { error, ...more } });
const source = store.groupByThread(internalCapability.threadId);
if (source && (source.dm || !source.memberIds.includes(internalSender.id))) {
@@ -13774,7 +13774,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
const message = coordinateResultMessage(reply, answeredOnly);
return { status: sent ? 200 : 409, body: { receipts, ...(sent ? { message: lead ? `${lead} ${message}` : message } : { error: refused.join("; ") }),
...(EXTERNAL && sent ? { rootId: generation } : {}) } };
- }, coordinateBots = (call: CoordinateBotsCall) => botLink.link.coordinate(call, { sender: internalSender, address: { groupId: store.groupByThread(internalCapability.threadId)?.id, threadId: internalCapability.threadId, botId: internalSender.id }, generation: internalCapability.generation, parentId: internalCapability.roomHandoffId, external: EXTERNAL, handed: delegatedThisTurn }, coordinateHere);
+ }, coordinateBots = (call: CoordinateBotsCall) => botLink.link.coordinate(call, { sender: internalSender, address: { groupId: store.groupByThread(internalCapability.threadId)?.id, threadId: internalCapability.threadId, botId: internalSender.id }, generation: internalCapability.generation, parentId: internalCapability.roomHandoffId, external: EXTERNAL, handed: delegatedThisTurn, problem: linkSourceProblem(internalSender.id, internalCapability.threadId) }, coordinateHere);
if (method === "GET" && path === "/api/internal/assignment-status") {
const id = url.searchParams.get("id")?.trim() ?? "";
const fromThreadId = internalCapability.threadId;