Skip to content

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

fix(handoff): remove the per-request rework cap on coordinate_bots

Bugfixer 28aba443e6969
diff --git a/server/checked-handoff.e2e.test.ts b/server/checked-handoff.e2e.test.ts
index f60f37a8be..fbfde5e7d3 100644
--- a/server/checked-handoff.e2e.test.ts
+++ b/server/checked-handoff.e2e.test.ts
@@ -104,19 +104,20 @@ it("says which other provider's AI a checker would start on only when asked: nul
}
}, 120_000);
-it("stops a worker and a checker that never agree: rework past four to the same checker under one request is refused", () => fixture(async (f) => {
- const send = (rework: boolean, expectError = false) => ({ arguments: { bot_ids: [f.checker.id], message: "Check result.md against chapter.md and request.md.", rework }, ...(expectError ? { expectError } : {}) });
+it("keeps sending rework to the same checker under one request: no round limit, the worker decides when to stop", () => fixture(async (f) => {
+ const send = (rework: boolean) => ({ arguments: { bot_ids: [f.checker.id], message: "Check result.md against chapter.md and request.md.", rework } });
f.plan = {
[f.worker.id]: { turns: [
{ steps: [send(false)], reply: "Being checked." },
- ...Array.from({ length: 4 }, () => ({ steps: [send(true)], reply: "Fixed and sent back." })),
- { steps: [send(true, true)], reply: "Still open after the last round." },
+ ...Array.from({ length: 6 }, () => ({ steps: [send(true)], reply: "Fixed and sent back." })),
+ { reply: "Still open after six rounds." },
] },
[f.checker.id]: { reply: "issues: 1\n1. Line 1: dusk should be dawn." },
};
await f.send(f.plan, "Improve the dialogue and have it checked.");
- await expect.poll(() => f.turns(f.worker.id).length, { timeout: 60_000 }).toBe(6);
- const last = f.turns(f.worker.id)[5].evidence.find((entry: any) => entry.step?.arguments?.rework);
- expect(JSON.stringify(last.response)).toContain("past the limit of 4, so nothing was sent. Stop here");
- expect(f.turns(f.checker.id)).toHaveLength(5);
+ await expect.poll(() => f.turns(f.worker.id).length, { timeout: 60_000 }).toBe(8);
+ const reworks = f.turns(f.worker.id).flatMap((turn: any) => turn.evidence.filter((entry: any) => entry.step?.arguments?.rework));
+ expect(reworks).toHaveLength(6);
+ for (const entry of reworks) expect(entry.response.result?.isError, JSON.stringify(entry.response)).toBeFalsy();
+ expect(f.turns(f.checker.id)).toHaveLength(7);
}), 120_000);
diff --git a/server/host/rework-cap.test.ts b/server/host/rework-cap.test.ts
deleted file mode 100644
index b8de4404c0..0000000000
--- a/server/host/rework-cap.test.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { createReworkCap, REWORK_MAX } from "./rework-cap.ts";
-
-describe("rework cap", () => {
- it("refuses rework past the limit to one teammate under one request, and counts each request and teammate apart", () => {
- const cap = createReworkCap(() => 0);
- const name = (id: string) => (id === "vera" ? "Vera" : id);
- for (let round = 0; round < REWORK_MAX; round++) expect(cap.take("request-1", ["vera"], name)).toBeNull();
- expect(cap.take("request-1", ["vera"], name)).toContain("past the limit of 4, so nothing was sent. Stop here: give the person the latest result");
- expect(cap.take("request-1", ["vera", "other"], name)).toContain("sent to Vera");
- expect(cap.take("request-1", ["other"], name)).toBeNull();
- expect(cap.take("request-2", ["vera"], name)).toBeNull();
- });
-
- it("forgets a request after six hours", () => {
- let clock = 0;
- const cap = createReworkCap(() => clock);
- for (let round = 0; round < REWORK_MAX; round++) cap.take("request-1", ["vera"], String);
- clock = 6 * 60 * 60_000 + 1;
- expect(cap.take("request-1", ["vera"], String)).toBeNull();
- });
-});
diff --git a/server/host/rework-cap.ts b/server/host/rework-cap.ts
deleted file mode 100644
index f0c6640206..0000000000
--- a/server/host/rework-cap.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-// A hand-off loop's hard stop. Rework sent back to one teammate is counted per request, so a worker and a checker that
-// never agree end after REWORK_MAX rounds whatever their instructions say; the runtime's own loop guards reset on every
-// result that comes back, so they never see this loop.
-
-export const REWORK_MAX = 4;
-const KEPT_MS = 6 * 60 * 60_000;
-
-export const reworkRefusal = (bot: string): string =>
- `coordinate_bots was not run: this would be rework number ${REWORK_MAX + 1} sent to ${bot} for the same request, past the limit of ${REWORK_MAX}, so nothing was sent. Stop here: give the person the latest result and say what is still open, with ${bot}'s last report.`;
-
-export function createReworkCap(now: () => number = Date.now) {
- const counts = new Map<string, { count: number; at: number }>();
- return {
- /** Counts one rework to each of `botIds` under `request`; the refusal for the first that is past the limit, which counts none. */
- take(request: string, botIds: readonly string[], name: (botId: string) => string): string | null {
- const at = now();
- for (const [key, entry] of counts) if (at - entry.at > KEPT_MS) counts.delete(key);
- const keys = botIds.map((botId) => `${request}\u0000${botId}`);
- const over = botIds.find((_botId, index) => (counts.get(keys[index]!)?.count ?? 0) >= REWORK_MAX);
- if (over !== undefined) return reworkRefusal(name(over));
- for (const key of keys) counts.set(key, { count: (counts.get(key)?.count ?? 0) + 1, at });
- return null;
- },
- };
-}
diff --git a/server/index.ts b/server/index.ts
index 50384d56ba..89fae82476 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -291,7 +291,7 @@ import { threadModelFallback, type ThreadEngine } from "./thread-model.ts";
import { computerEngineMoveText, removedComputerInstanceIds, writeComputerEngineMoveLines } from "./computer-engine-removal.ts";
import { peerDeliveryReceipt, refusalsOnlyInstructions, type PeerDeliveryReceipt } from "./peer-delivery.ts";
import { createRoomAccess, PRIVATE_CHAT_ROOM_WRITE } from "./host/room-access.ts";
-import { outsideRoomNote, sentRow, teammateResultRow, WAIT_CARD_CLOSED_REASON } from "./host/handoff-sent.ts"; import { createHandoffFiles, handoffFilesSchema, inboxRead, turnsRunInOwnFolder } from "./host/handoff-files.ts"; import { conversationAttachments } from "./conversation-attachments.ts"; import { createReworkCap } from "./host/rework-cap.ts";
+import { outsideRoomNote, sentRow, teammateResultRow, WAIT_CARD_CLOSED_REASON } from "./host/handoff-sent.ts"; import { createHandoffFiles, handoffFilesSchema, inboxRead, turnsRunInOwnFolder } from "./host/handoff-files.ts"; import { conversationAttachments } from "./conversation-attachments.ts";
import { createWebhookRoomPost } from "./host/webhook-room-deps.ts";
import { createRoomJobs, parallelRoomJobsEnabled, type RoomRoundLine } from "./host/room-jobs.ts";
import { markGroupThreadUnreadAfterTurn } from "./group-task-state.ts";
@@ -3836,7 +3836,7 @@ const questionRouting = createQuestionRouting({ store, handedInUnproven, active:
answerLive: async (threadId, requestId, text) => await answerRequest(threadId, botForThread(store.botByThread(threadId)?.id ?? "", threadId)?.modelSelection.instanceId ?? "", requestId, "answer", text) === "answered", settleSignIns: (node) => signInSettle.answeredElsewhere(node),
keptPrivate: (node, requester) => keptPrivate({ child: teamHost.privateTo(node.threadId), parent: teamHost.privateTo(requester.threadId) }),
steer: async (threadId, text) => canSteerThread(threadId) && (await steerThread(threadId, text)) !== "refused", mayReach: outsideLineage.mayReach });
-const reworkCap = createReworkCap(); const handoffFiles = createHandoffFiles({ dataDir: DATA_DIR, attachmentsDir: ATTACHMENTS_DIR, botName: (id) => store.bot(id)?.name, node: (id) => coordinator.node(id), children: (id) => coordinator.children(id), discard: deleteAttachment, threadsReferencing, changes: (listener) => store.onChange(listener), log: (line) => console.error(line),
+const handoffFiles = createHandoffFiles({ dataDir: DATA_DIR, attachmentsDir: ATTACHMENTS_DIR, botName: (id) => store.bot(id)?.name, node: (id) => coordinator.node(id), children: (id) => coordinator.children(id), discard: deleteAttachment, threadsReferencing, changes: (listener) => store.onChange(listener), log: (line) => console.error(line),
worksInOwnFolder: (botId, threadId) => turnsRunInOwnFolder(botId, threadId, store.taskByThread(botId, threadId)?.cwd, store.bot(botId)?.cwd, Boolean(store.groupByThread(threadId))), vmHome: (botId) => localVmMode(cfg) === "per-bot" ? perBotLocalVmTarget(botId).workspaceDir : null, withheld: (child, parent) => Boolean(roomHandoffProblem(child, parent)) || keptPrivate({ child: teamHost.privateTo(child.threadId), parent: teamHost.privateTo(parent.threadId) }) });
const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), roomWindow: (threadId, reader) => roomTranscript.window(threadId, userNameFor(threadId), undefined, reader), roomOpener: (botId, threadId) => handoffOpener({ botId, threadId }, threadId), roomChanged: (groupId) => { const room = store.group(groupId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); }, roomFollow: followRoomMentions<GroupTurnOperation>({ members: (groupId) => (store.group(groupId)?.memberIds ?? []).map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot)), mentioned: (text, members) => roomResponders(text, members, { kind: "mentions" }), begin: beginGroupTurnOperation, finish: finishGroupTurnOperation, queue: groupQueues, wait: waitForChatRoomMember, run: (groupId, threadId, botId, hop, spoken, operation) => runGroupMemberTurn(groupId, threadId, botId, hop, spoken, undefined, undefined, () => operation.cancelled, undefined, undefined, undefined, undefined, operation) }), dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), refusal: botMoveRefusal, language: (threadId) => threadLanguage(threadId), personName: personNameIn, sessions, power: () => cloudPower, files: handoffFiles, storeFile: (path, name, root) => saveBotAttachment({ path, name, roots: [root], byContent: true }), log: (line) => console.error(line), local: (auth) => auth.kind === "loopback" && auth.trust !== "service" && !CLOUD_HOME && !HOSTED_WORKSPACE, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }); ROUTES.push(botLink.routes); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({
dataDir: DATA_DIR,
@@ -13691,7 +13691,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
done_when: z.string().trim().max(1000).optional(), answers: z.string().trim().min(1).max(128).optional(), files: handoffFilesSchema,
}).safeParse(await readInternalBody());
if (!parsed.success) return json(res, 400, { error: coordinateTooLong(parsed.error.issues) ?? `Provide 1-4 distinct botIds and a message of 1-${coordinateMessageMax} characters; thread is standing, new or the id of a thread you opened on that teammate, title one line of at most 80 characters, reply is resume or none, consult is a boolean, done_when at most 1000 characters, files at most 5 paths.` });
- const { groupId, botIds, message, reason, rework, thread, title, reply, consult, inMyFolder, done_when: doneWhen, answers, files: paths } = parsed.data; const reworkRefused = rework ? reworkCap.take(directRequestOwners.get(internalCapability.threadId)?.messageId ?? internalCapability.threadId, botIds, (id) => store.bot(id)?.name ?? "that teammate") : null; if (reworkRefused) return json(res, 400, { error: reworkRefused });
+ const { groupId, botIds, message, reason, rework, thread, title, reply, consult, inMyFolder, done_when: doneWhen, answers, files: paths } = parsed.data;
const callRun = activeRoutineRunForThread(internalCapability.threadId) ?? undefined, result = await handoffFiles.coordinate({ paths, answers, senderId: internalSender.id, recipients: botIds.length, saveOne: async (path) => saveTurnFile(internalCapability, internalSender.id, await attachmentVmForTurn(internalCapability), path, undefined, true),
send: (files) => coordinateBots({ groupId, botIds, message, reason: reason || undefined, rework, thread, title: title || undefined, reply, consult, inMyFolder, doneWhen: doneWhen || undefined, ...(answers ? { answers } : {}), ...(files ? { files } : {}) }) }); refusedHandoffs.settled(internalCapability.threadId, internalSender, botIds, result.status, callRun);
return json(res, result.status, result.body);