Skip to content

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

coordinate_bots: run a standing-thread send beside a busy turn instead of queueing it

AdityaUmalec2b874c48ace
diff --git a/docs/runtime-contract.md b/docs/runtime-contract.md
index 16cad6e136..e9be9f5307 100644
--- a/docs/runtime-contract.md
+++ b/docs/runtime-contract.md
@@ -119,7 +119,7 @@ Engine drivers declare capabilities (`server/runtime/capabilities.ts`): `resume`
Every turn that may hand work on, whatever started it, gets the same tools:
-- `coordinate_bots(bot_ids, message, reason?, rework?, thread?: "standing" | "new" | "<thread id>", reply?: "resume" | "none", consult?: true, done_when?, answers?)`. `thread: "new"` opens a new thread on the teammate, and a thread id sends to a thread the sender opened on that teammate earlier (a receipt's `threadId`, or `list_threads`), refused with where ids come from for any other, except that a Chief that manages the teammate may name a thread it did not open where the teammate's turn waits on a question card to the person (in words, not one only the person can answer): the message answers it for the person, the turn runs on with `@<Chief> answered for the person: …`, the card names the Chief, and the person's own answer still replaces it. The Chief's turns list such questions (bot, thread id, question). A Chief turn with no person behind it (a webhook, a routine, a guest) neither lists nor answers them, and a question in work an outside event started stays the person's; `reply: "none"` is a one-way notice that is never awaited; `consult: true` asks a question that the teammate answers from what it knows, acting on nothing, and the asker is resumed with the answer. `answers: "<assignment id>"` makes the message the answer to that teammate work's open question (parked, or a question card its turn waits on) instead of new work, whoever sends it; refused, with the reason, when that work no longer asks. A message to a teammate from the very turn that was resumed with its question answers it too. **What the bot that handed work on sends to the thread that work runs in goes into that work**, outside a room, whatever its level and whichever of its turns sends it: where the work waits on a question (parked on `NEEDS INPUT:`, or a question card its turn waits on; never a sign-in or another card only the person can act on) the message answers it, and the work runs on with `@<bot> answered: "…"` and reports once, to the turn that handed it out; where the work is running, the message is handed to that running turn (`steer`), which reads it at its next step as a person's line sent mid-turn is, and is shown in that thread as the sender's; the work's one result still comes back once. Only when the engine cannot take a message mid-turn does it run next, as new work. Work handed out in the sending turn itself stays apart: a second assignment is its own. A consultation, and a message to a room, never go into other work. A parked question waits on its own clock, which never runs out unless a host sets one (§6): it is answered, or its work is stopped.
+- `coordinate_bots(bot_ids, message, reason?, rework?, thread?: "standing" | "new" | "<thread id>", reply?: "resume" | "none", consult?: true, done_when?, answers?)`. `thread: "standing"` (the default) runs in the conversation's work thread with the teammate; while a turn runs there, it starts in another idle work thread the conversation opened on the teammate, or a new one, unless the teammate is at its thread limit or a room turn holds it (then it queues there as before), and a send follows work the same turn already handed that teammate, or work the conversation still waits on, in that work's thread. `thread: "new"` opens a new thread on the teammate, and a thread id sends to a thread the sender opened on that teammate earlier (a receipt's `threadId`, or `list_threads`), refused with where ids come from for any other, except that a Chief that manages the teammate may name a thread it did not open where the teammate's turn waits on a question card to the person (in words, not one only the person can answer): the message answers it for the person, the turn runs on with `@<Chief> answered for the person: …`, the card names the Chief, and the person's own answer still replaces it. The Chief's turns list such questions (bot, thread id, question). A Chief turn with no person behind it (a webhook, a routine, a guest) neither lists nor answers them, and a question in work an outside event started stays the person's; `reply: "none"` is a one-way notice that is never awaited; `consult: true` asks a question that the teammate answers from what it knows, acting on nothing, and the asker is resumed with the answer. `answers: "<assignment id>"` makes the message the answer to that teammate work's open question (parked, or a question card its turn waits on) instead of new work, whoever sends it; refused, with the reason, when that work no longer asks. A message to a teammate from the very turn that was resumed with its question answers it too. **What the bot that handed work on sends to the thread that work runs in goes into that work**, outside a room, whatever its level and whichever of its turns sends it: where the work waits on a question (parked on `NEEDS INPUT:`, or a question card its turn waits on; never a sign-in or another card only the person can act on) the message answers it, and the work runs on with `@<bot> answered: "…"` and reports once, to the turn that handed it out; where the work is running, the message is handed to that running turn (`steer`), which reads it at its next step as a person's line sent mid-turn is, and is shown in that thread as the sender's; the work's one result still comes back once. Only when the engine cannot take a message mid-turn does it run next, as new work. Work handed out in the sending turn itself stays apart: a second assignment is its own. A consultation, and a message to a room, never go into other work. A parked question waits on its own clock, which never runs out unless a host sets one (§6): it is answered, or its work is stopped.
- A teammate on another server (saved in Settings, see [Bot API: bot to bot across servers](bot-api.md#bot-to-bot-across-servers)) is listed by `list_bots` as `remote-<id>` and takes `coordinate_bots` work through its Bot API; its reply resumes the sender as information from that bot.
- `assignment_status(id?)`: read-only; one assignment's status, outcome and result, or everything this conversation still waits on. External runtimes long-poll it; it never blocks a bot.
- `usage_limits` reads each AI account's percent used, reset time and when that was checked, read-only: no credential, address or account id, an `unknown` status for no data and `unsupported` for an AI that reports no limits. A turn sees only accounts its audience may read, and a guest-driven turn is refused.
diff --git a/server/coordinator.ts b/server/coordinator.ts
index b9d6bc593d..1dd5d035f4 100644
--- a/server/coordinator.ts
+++ b/server/coordinator.ts
@@ -13,8 +13,8 @@ export type CoordinateBotsCall = {
message: string;
reason?: string;
rework: boolean;
- /** "standing" (the conversation's one work thread with each teammate), "new", or the id of a thread the caller opened on
- * that teammate. */
+ /** "standing" (the conversation's work thread with each teammate; while a turn runs there, another idle one or a new one,
+ * unless work it still waits on is there), "new", or the id of a thread the caller opened on that teammate. */
thread: string;
reply: "resume" | "none";
consult: boolean;
diff --git a/server/direct-coordination.e2e.test.ts b/server/direct-coordination.e2e.test.ts
index 0742b9d68a..2ed926b04f 100644
--- a/server/direct-coordination.e2e.test.ts
+++ b/server/direct-coordination.e2e.test.ts
@@ -633,6 +633,36 @@ it("runs two assignments to one teammate from one turn in its thread, one after
expect(transcript).toContain("Benchmark the exporter");
}), 60_000);
+it("starts a later send in a parallel work thread while the teammate's standing thread is busy, instead of queueing it", () => fixture(async f => {
+ const gate = join(f.session.info.dataDir, "first-assignment.gate");
+ f.plan[f.lead.id] = { gateFile: gate, reply: "Done" };
+ f.plan[f.chief.id] = { turns: [
+ { steps: [{ arguments: { bot_ids: [f.lead.id], message: "Implement the CSV export", reply: "none" } }], reply: "Assigned the build" },
+ { steps: [{ arguments: { bot_ids: [f.lead.id], message: "Export the invoices", reply: "none" } }], reply: "Assigned the invoices" },
+ ] };
+ f.save();
+ const leadNodes = () => f.nodes().filter((node: any) => node.botId === f.lead.id);
+ try {
+ await f.cli("send", "--bot", f.chief.id, "--task", f.chief.activeTaskId, "--text", "Ask Engineering to build the CSV export.");
+ expect((await f.wait()).status).toBe("settled");
+ await expect.poll(() => leadNodes()[0]?.status, { timeout: 15_000 }).toBe("running");
+ await f.cli("send", "--bot", f.chief.id, "--task", f.chief.activeTaskId, "--text", "Now ask them to export the invoices.");
+ expect((await f.wait()).status).toBe("settled");
+ await expect.poll(() => leadNodes()[1]?.status, { timeout: 15_000 }).toBe("running");
+ const [first, second] = leadNodes();
+ expect(first.status, "the first assignment still runs").toBe("running");
+ expect(second.threadId).not.toBe(first.threadId);
+ writeFileSync(gate, "go");
+ await expect.poll(() => leadNodes().map((node: any) => node.status), { timeout: 15_000 }).toEqual(["completed", "completed"]);
+ const work = (await f.api("/api/bots")).bots.find((bot: any) => bot.id === f.lead.id).tasks.filter((task: any) => task.openedBy?.kind === "work");
+ expect(work.map((task: any) => task.threadId).sort()).toEqual([first.threadId, second.threadId].sort());
+ for (const task of work) expect(task).toMatchObject({ title: "@Clive · work", openedBy: { botId: f.chief.id, threadId: f.chief.activeTaskId } });
+ expect(sendReceipts(f, f.chief.id).map((receipt: any) => receipt.threadId)).toEqual([first.threadId, second.threadId]);
+ } finally {
+ writeFileSync(gate, "go");
+ }
+}), 60_000);
+
it("gives another conversation of the same Chief its own thread with the teammate", () => fixture(async f => {
f.plan[f.lead.id] = { turns: [{ reply: "Export implemented" }, { reply: "Invoices exported" }] };
f.plan[f.chief.id] = { turns: [
diff --git a/server/host/work-thread.test.ts b/server/host/work-thread.test.ts
index 9614c2c7cb..158712607a 100644
--- a/server/host/work-thread.test.ts
+++ b/server/host/work-thread.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import type { TaskRecord } from "../store.ts";
import { OUTSIDE_STAYS_HERE } from "./outside-lineage.ts";
-import { workThreadFor } from "./work-thread.ts";
+import { besideBusy, workThreadFor } from "./work-thread.ts";
const by = (botId: string, name: string, threadId: string): TaskRecord["openedBy"] => ({ botId, name, threadId, kind: "work", at: 0 });
const task = (threadId: string, openedBy?: TaskRecord["openedBy"], more: Partial<TaskRecord> = {}): TaskRecord =>
@@ -66,3 +66,33 @@ describe("workThreadFor", () => {
thread: "x", notice: true, answering: undefined, also: () => true, reach: () => false, any: true })).toThrow(OUTSIDE_STAYS_HERE);
});
});
+
+describe("besideBusy", () => {
+ // Liaison's chat "liaison-chat" opened two work threads on Bugfixer earlier: "standing" and "spare".
+ const opened = [task("standing", by("liaison", "Liaison", "liaison-chat")), task("spare", by("liaison", "Liaison", "liaison-chat"))];
+ const workStore = { workThread: (_bot: string, _from: string, _thread: string, _room = false, also: (task: TaskRecord) => boolean = () => true) => opened.find(also) };
+ const into = (busy: string[], more: { full?: boolean; kept?: string[]; holding?: string[]; fits?: (task: TaskRecord) => boolean } = {}) => besideBusy(workStore, opened[0]!, {
+ botId: "bugfixer", fromBotId: "liaison", fromThreadId: "liaison-chat", fits: more.fits ?? (() => true), busy: (threadId) => busy.includes(threadId), idle: (threadId) => !busy.includes(threadId) && !(more.holding ?? []).includes(threadId),
+ full: more.full ?? false, keeps: (threadId) => (more.kept ?? []).includes(threadId) })?.threadId;
+
+ it("keeps the standing thread while nothing runs there", () => {
+ expect(into([])).toBe("standing");
+ expect(into(["spare"])).toBe("standing");
+ });
+
+ it("runs beside a busy standing thread: in an idle work thread it opened, else a new one", () => {
+ expect(into(["standing"])).toBe("spare");
+ expect(into(["standing", "spare"])).toBeUndefined();
+ expect(into(["standing"], { fits: (task) => task.threadId !== "spare" })).toBeUndefined();
+ expect(into(["standing"], { holding: ["spare"] }), "a thread with queued or waiting work is not idle").toBeUndefined();
+ });
+
+ it("queues in the standing thread when the teammate could not start it anyway", () => {
+ expect(into(["standing"], { full: true })).toBe("standing");
+ });
+
+ it("keeps a send behind work this turn handed on or this conversation still waits on, wherever that runs", () => {
+ expect(into(["standing"], { kept: ["standing"] })).toBe("standing");
+ expect(into(["standing", "spare"], { kept: ["spare"] })).toBe("spare");
+ });
+});
diff --git a/server/host/work-thread.ts b/server/host/work-thread.ts
index 3a9ce81eb6..7fa75dff59 100644
--- a/server/host/work-thread.ts
+++ b/server/host/work-thread.ts
@@ -29,3 +29,15 @@ export function workThreadFor(store: Pick<Store, "workThread" | "taskByThread">,
if (handedWork) throw new Error(`"${thread}" handed you work: answer it there with reply "none", a one-way notice; it cannot be given new work`);
throw new Error(`"${thread}" is not a thread you opened on ${input.botName}: use a threadId one of your coordinate_bots receipts gave, or one list_threads shows on them`);
}
+
+/** The thread a send to a teammate's standing work thread runs in. A thread holding work this turn already handed the
+ * teammate, or work this conversation still waits on (`keeps`), takes it, so it runs after that work. Otherwise, while a
+ * turn runs in the standing thread, the send takes another work thread this conversation opened on the teammate that holds
+ * no work (`idle`), or undefined to open a new one, instead of waiting behind it. A teammate that could not start it anyway
+ * (`full`) keeps the standing thread, where it queues as before. */
+export function besideBusy(store: Pick<Store, "workThread">, standing: TaskRecord, input: { botId: string; fromBotId: string; fromThreadId: string;
+ fits: (task: TaskRecord) => boolean; busy: (threadId: string) => boolean; idle: (threadId: string) => boolean; full: boolean;
+ keeps: (threadId: string) => boolean }): TaskRecord | undefined {
+ const pick = (more: (task: TaskRecord) => boolean) => store.workThread(input.botId, input.fromBotId, input.fromThreadId, false, (task) => input.fits(task) && more(task));
+ return pick((task) => input.keeps(task.threadId)) ?? (input.full || !input.busy(standing.threadId) ? standing : pick((task) => input.idle(task.threadId)));
+}
diff --git a/server/index.ts b/server/index.ts
index 4dd680d681..bb2406447f 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -26,7 +26,7 @@ import { botMemoryFiles, createLendingMemory } from "./lending-memory.ts";
import { SharedComputerControl } from "./shared-computer-control.ts";
import { STATUS_REPLY_TIMEOUT_MS } from "./runtime/status-reply.ts"; import { createCoordinator, type ComposedTurn, type CoordinateBotsCall, type Coordinator, type HandoffOpener, type HandoffOptions, type HandoffView, type HostTurnResult } from "./coordinator.ts";
import { queuedBehindPersonText, turnWaitedOnPerson, UnansweredApprovals } from "./waiting-on-person.ts";
-import { createPersonWaits } from "./host/person-waits.ts"; import { askToolName, createAskCards } from "./host/ask-cards.ts"; import { createQuestionRouting } from "./host/question-routing.ts"; import { workThreadFor } from "./host/work-thread.ts"; import { leaveThreadPost, postToThread, threadWaitsOn, unreadThreadPosts } from "./host/thread-posts.ts"; import { anyCardLive, closedByStop, resumableCards as cardsWaitedOn } from "./host/resumable-cards.ts"; import { createMcpChat } from "./host/mcp-chat.ts"; import { isCardOwnerLive, isMcpSignInCard } from "./host/mcp-sign-in-cards.ts"; import { createConnectCardSettle } from "./host/connect-card-settle.ts";
+import { createPersonWaits } from "./host/person-waits.ts"; import { askToolName, createAskCards } from "./host/ask-cards.ts"; import { createQuestionRouting } from "./host/question-routing.ts"; import { besideBusy, workThreadFor } from "./host/work-thread.ts"; import { leaveThreadPost, postToThread, threadWaitsOn, unreadThreadPosts } from "./host/thread-posts.ts"; import { anyCardLive, closedByStop, resumableCards as cardsWaitedOn } from "./host/resumable-cards.ts"; import { createMcpChat } from "./host/mcp-chat.ts"; import { isCardOwnerLive, isMcpSignInCard } from "./host/mcp-sign-in-cards.ts"; import { createConnectCardSettle } from "./host/connect-card-settle.ts";
import { assertRequestTarget, guardedRequestPath, requestConflict, requestNeedsInput } from "./guarded-requests.ts";
import { botAvatarUrlFromStoredPath } from "../shared/bot-avatar.ts";
import { BOT_PROFILE_LIMITS } from "../shared/bot-profile.ts";
@@ -13561,12 +13561,12 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
// A Chief answers, for the person, the question a teammate it manages waits on in a thread the Chief did not open.
let lends = mode === "work" && (CLOUD_HOME ? handsOnLending(internalCapability) : !store.groupByThread(internalCapability.threadId) && sharedComputerPrincipal(internalCapability) === OWN_SERVER_LENDER); const forPerson = EXTERNAL || room || fresh || post || call.answers || mode !== "work" || call.thread === "standing" || !teammatePrompts.actsForPerson(internalSender, internalCapability.threadId) || !canManage(internalSender, recipient) || !threadReadableFrom(internalCapability.threadId)(call.thread) || !asksActingPerson(internalCapability.threadId, store.groupByThread(internalCapability.threadId) ? internalCapability.generation : undefined)(call.thread, recipient.id) ? undefined : await questionRouting.answerForPerson({ lends, sender: internalSender, senderThreadId: address.threadId, target: recipient, threadId: call.thread, message: call.message });
if (forPerson) { if (forPerson.outcome === "failed") refused.push(forPerson.detail); else answeredForPerson.add(forPerson); receipts.push(forPerson); continue; }
- const continued = room || fresh ? undefined : workThreadFor(store, { botId: target.botId, botName: recipient.name, fromBotId: internalSender.id, fromThreadId: address.threadId, thread: call.thread, notice: mode === "notify", any: Boolean(post),
- answering: coordinator.answersTo(internalCapability.roomHandoffId ?? generation), also: (task) => !CLOUD_TEAM || threadStarters.get(task.threadId) === opener, reach: (task) => outsideLineage.mayReach(address.threadId, task.threadId) });
- const relayed = EXTERNAL || post || (!call.answers && (room || fresh || mode === "consult")) ? undefined : await questionRouting.relay({ lends, sender: internalSender, senderThreadId: address.threadId,
- senderNode: coordinator.node(internalCapability.roomHandoffId ?? generation), target: recipient, message: call.message, ...(call.answers ? { answers: call.answers } : {}), ...(continued ? { threadId: continued.threadId, ...(steersOwn ? { selected: true } : {}) } : {}),
+ const startedHere = (task: TaskRecord) => !CLOUD_TEAM || threadStarters.get(task.threadId) === opener, reachable = (task: TaskRecord) => outsideLineage.mayReach(address.threadId, task.threadId), standing = room || fresh ? undefined : workThreadFor(store, { botId: target.botId, botName: recipient.name, fromBotId: internalSender.id, fromThreadId: address.threadId, thread: call.thread, notice: mode === "notify", any: Boolean(post),
+ answering: coordinator.answersTo(internalCapability.roomHandoffId ?? generation), also: startedHere, reach: reachable });
+ const continued = standing && !post && !call.answers && !call.rework && call.thread === "standing" ? besideBusy(store, standing, { botId: target.botId, fromBotId: internalSender.id, fromThreadId: address.threadId, fits: (task) => startedHere(task) && reachable(task), busy: (threadId) => threadBusy(target.botId, threadId), idle: (threadId) => !threadBusy(target.botId, threadId) && !coordinator.active().some((node) => node.botId === target.botId && node.threadId === threadId), full: botAtThreadCapacity(target.botId, undefined, true) || Boolean(activeGroupTurnForBot(target.botId)), keeps: (threadId) => [...internalCapability.delegatedThisTurn ?? []].some((id) => coordinator.node(id)?.threadId === threadId) || coordinator.outstandingDirect(address.threadId).some((node) => node.botId === target.botId && node.threadId === threadId) }) : standing; const relayed = EXTERNAL || post || (!call.answers && (room || fresh || mode === "consult")) ? undefined : await questionRouting.relay({ lends, sender: internalSender, senderThreadId: address.threadId,
+ senderNode: coordinator.node(internalCapability.roomHandoffId ?? generation), target: recipient, message: call.message, ...(call.answers ? { answers: call.answers } : {}), ...(standing ? { threadId: (continued ?? standing).threadId, ...(steersOwn ? { selected: true } : {}) } : {}),
...(internalCapability.delegatedThisTurn ? { sentThisTurn: internalCapability.delegatedThisTurn } : {}) });
- if (relayed) { if (relayed.outcome === "failed") refused.push(relayed.detail); receipts.push(relayed); continue; } if (post && !post.wake && continued) { receipts.push(leaveThreadPost(store, { from: internalSender, fromThreadId: address.threadId, deliveryId: post.deliveryId, text: call.message, to: recipient, task: continued, label: serverLine(threadLanguage(continued.threadId), "server.threads.posted", { bot: internalSender.name }) })); continue; } // no turn starts: its next run reads it
+ if (relayed) { if (relayed.outcome === "failed") refused.push(relayed.detail); receipts.push(relayed); continue; } if (post && !post.wake && standing) { receipts.push(leaveThreadPost(store, { from: internalSender, fromThreadId: address.threadId, deliveryId: post.deliveryId, text: call.message, to: recipient, task: standing, label: serverLine(threadLanguage(standing.threadId), "server.threads.posted", { bot: internalSender.name }) })); continue; } // no turn starts: its next run reads it
const lane = room && lanes ? roomJobs.openLane(room, target.threadId, target.botId, internalSender, call.message) : undefined;
const via = lane ? "lane" : room ? "room" : "direct";
if (lane?.created) createdThread = lane.threadId;