Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Remove the 64-step cap from chat-engine turns
AdityaUmaled6788b49cb6d
diff --git a/docs/runtime-contract.md b/docs/runtime-contract.mdindex a049678588..fc19844593 100644--- a/docs/runtime-contract.md+++ b/docs/runtime-contract.md@@ -113,7 +113,7 @@ The suite asserts these after every scenario (`server/runtime/invariants.ts`):The host (today `server/index.ts`) implements `TurnRunner`: `validate`, `canStart`, `run`, `park`, `report`, `changed`, `names`, and optionally `outward(a)`: the short labels of the outward actions (sends, posts, publishes, commits, pushes, payments) the node's cut turn completed since it began, read from the thread's activity rows (a room thread's rows attributed to the member); the restart policy (§5) reads it once at open and never reruns a turn that acted outward. The runtime owns the record and the decisions; the host owns engines, threads, chips, cards, names and notifications. A turn the host runs itself (a person's, a routine's, a room member's) begins its root with `begin()` and ends it through `end()` with the turn's evidence, cards and seat; a turn the runtime dispatched ends through its `run` result. There is no other settle, and a hand-off from a turn whose root was never begun is refused ("no turn"). The level the host records at enqueue (`levelOf`) is the level the target's turn will run with: a room hand-off's is resolved from its source, since a Chief's level flows into a room with the hand-off and never onto the shared thread (invariant I6). When that level came down a Chief's chain, `levelOf` also returns the Chief conversation's level, which the coordinator passes as `levels.chief`; the host resolves the chain from the requester's node up its parents (`server/host/delegated-level.ts`). A host method that throws is logged and read as "not now"; the next tick retries. The host calls `tick()` on its own schedule and `progress(id)` when it sees activity on a turn; `progress` writes no event (per-tool-call rows would be noise), every status change does.-Engine drivers declare capabilities (`server/runtime/capabilities.ts`): `resume` (keeps a native session), `nativeReviewer`, `full`, `edits`, `stepCap`, `subagents`. The level rule and the continuation rule read these flags, never driver names.+Engine drivers declare capabilities (`server/runtime/capabilities.ts`): `resume` (keeps a native session), `nativeReviewer`, `full`, `edits`, `subagents`. The level rule and the continuation rule read these flags, never driver names.## 9. One tool surfacediff --git a/server/comms.test.ts b/server/comms.test.tsindex 69d329ebc8..18f3a79856 100644--- a/server/comms.test.ts+++ b/server/comms.test.ts@@ -976,14 +976,14 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {failed = askerBot.messages.find((m: any) => m.kind === "activity" && m.tool?.ok === false && m.from?.botId === helper.id);return Boolean(failed) && lastText(askerBot.messages)?.text === WOKE_WITH_FAILURE && !askerBot.busy;}, 90_000, "the stall never reached the delegator");- expect(failed.tool.name).toMatch(/^CapHelper — failed: Stopped after 64 steps without a final answer\./);+ expect(failed.tool.name).toMatch(/^CapHelper — failed: Stopped after 200 tool calls without a final answer\./);expect(failed.tool.name).not.toContain("\n");const tasks = (await bot(helper.id)).tasks;expect(tasks.map((task: any) => task.title).filter((title: string) => title?.startsWith("Continue:"))).toEqual([]);const handed = assignments(helper.id, asker.id);expect(handed).toHaveLength(1);expect(handed[0]).toMatchObject({ status: "failed", outcome: "stalled", executions: 2 });- expect(handed[0]!.outcomeDetail).toMatch(/^Stopped after 2 continuations without progress: Stopped after 64 steps/);+ expect(handed[0]!.outcomeDetail).toMatch(/^Stopped after 2 continuations without progress: Stopped after 200 tool calls/);} finally {compatAnswer = "hang";}diff --git a/server/direct-coordination.e2e.test.ts b/server/direct-coordination.e2e.test.tsindex 5263e3df8e..03dc76a5ea 100644--- a/server/direct-coordination.e2e.test.ts+++ b/server/direct-coordination.e2e.test.ts@@ -1004,8 +1004,8 @@ it("continues a teammate's step cap in place and stops it once it makes no progrexpect(leads).toHaveLength(1);const child = leads[0];expect(child).toMatchObject({ status: "failed", outcome: "stalled", executions: 2,- result: expect.stringMatching(/^Stopped after 64 steps without a final answer\./) });- expect(child.outcomeDetail).toMatch(/^Stopped after 2 continuations without progress: Stopped after 64 steps without a final answer\./);+ result: expect.stringMatching(/^Stopped after 200 tool calls without a final answer\./) });+ expect(child.outcomeDetail).toMatch(/^Stopped after 2 continuations without progress: Stopped after 200 tool calls without a final answer\./);expect(child.result).not.toContain("assign what is left");expect(f.eventsOf(child.id).filter((kind: string) => kind === "continued")).toHaveLength(1);expect(f.eventsOf(child.id)).toContain("stalled");@@ -1013,11 +1013,11 @@ it("continues a teammate's step cap in place and stops it once it makes no progrexpect(resumed.prompt.message.content).toContain("Stopped after 2 continuations without progress");expect(resumed.prompt.message.content).not.toContain("assign what is left");const chip = (await f.messages(f.chief.activeTaskId)).find((message: any) => message.roomRequest?.phase === "result");- expect(chip.tool.name).toContain("Engineering lead — failed: Stopped after 64 steps without a final answer");+ expect(chip.tool.name).toContain("Engineering lead — failed: Stopped after 200 tool calls without a final answer");expect((await f.messages(f.chief.activeTaskId)).filter((message: any) => message.roomRequest?.phase === "result")).toHaveLength(1);const lead = (await f.api("/api/bots")).bots.find((bot: any) => bot.id === f.lead.id);expect(lead.tasks.map((task: any) => task.title).filter((title: string) => title.startsWith("Continue:"))).toEqual([]);- expect(calls).toBe(128);+ expect(calls).toBe(402);} finally { await close(); }}), 90_000);diff --git a/server/drivers/openai-chat-tools.test.ts b/server/drivers/openai-chat-tools.test.tsindex b085a025a0..0f2fc674c6 100644--- a/server/drivers/openai-chat-tools.test.ts+++ b/server/drivers/openai-chat-tools.test.ts@@ -1341,7 +1341,7 @@ describe("structured tool execution boundaries", () => {expect(f.recorder.events.some((event) => event.type === "runtime.error")).toBe(false);});- it("stops a model that keeps requesting tools after 64 steps, with one next action that does not repeat the steps that ran", async () => {+ it("stops a model that keeps requesting one tool per step at 200 tool calls, with one next action that does not repeat the steps that ran", async () => {const f = await fixture((_body, response, round) => sse(response, [chunk({ tool_calls: [toolCall("audit_write", '{"name":"receipt","value":"done"}', `call_${round}`)] }, "tool_calls"),]), "grok");@@ -1351,10 +1351,10 @@ describe("structured tool execution boundaries", () => {await f.start();expect(await f.completed()).toMatchObject({ ok: false, stopReason: "error" });stop();- expect(f.requests).toHaveLength(64);- expect(f.effects()).toHaveLength(64);+ expect(f.requests).toHaveLength(201);+ expect(f.effects()).toHaveLength(200);expect(f.recorder.events.filter((event) => event.type === "runtime.error")).toEqual([expect.objectContaining({- message: "Stopped after 64 steps without a final answer. The steps so far already ran, so ask only for what's left.",+ message: "Stopped after 200 tool calls without a final answer. The steps so far already ran, so ask only for what's left.",terminal: true,})]);});@@ -1390,33 +1390,19 @@ describe("structured tool execution boundaries", () => {for (const update of updates) expect(handoff).toContain(update);expect(handoff.indexOf(updates[0]!)).toBeLessThan(handoff.indexOf(updates[1]!));expect(JSON.stringify(f.requests[1]!.messages)).toContain(updates.join("\\n\\n"));- expect(f.requests).toHaveLength(callsPerReply === 1 ? 64 : 9);- expect(f.effects()).toHaveLength(callsPerReply === 1 ? 64 : 200);+ expect(f.requests).toHaveLength(callsPerReply === 1 ? 201 : 9);+ expect(f.effects()).toHaveLength(200);});- it("answers in the last allowed step and leaves a message steered during it for the next turn", async () => {- const last = deferred<ServerResponse>();- const f = await fixture((_body, response, round) => round < 64+ it("finishes a turn that needs more than 64 steps", async () => {+ const f = await fixture((_body, response, round) => round < 100? sse(response, [chunk({ tool_calls: [toolCall("audit_write", `{"name":"step","value":"${round}"}`, `call_${round}`)] }, "tool_calls")])- : last.resolve(response));+ : answer(response));await f.start({ approvalMode: "full" });- const response = await last.promise;- await expect(f.instance.adapter.steer!(f.threadId, "One more thing.")).resolves.toBe("refused");- answer(response);expect(await f.completed()).toMatchObject({ ok: true });- expect(f.requests).toHaveLength(64);- });-- it.each([- ["a failed tool call", "audit_fail", "The operation is complete.", "tool_error"],- ["an announced action", "audit_write", "I'll write the next receipt.", "incomplete_action"],- ])("ends on %s in the last allowed step without asking for another step", async (_, lastTool, text, stopReason) => {- const f = await fixture((_body, response, round) => round < 64- ? sse(response, [chunk({ tool_calls: [toolCall(round === 63 ? lastTool : "audit_write", `{"name":"step","value":"${round}"}`, `call_${round}`)] }, "tool_calls")])- : answer(response, text));- await f.start({ approvalMode: "full", toolErrorCorrectiveRounds: 1 });- expect(await f.completed()).toMatchObject({ ok: false, stopReason });- expect(f.requests).toHaveLength(64);+ expect(f.requests).toHaveLength(100);+ expect(f.effects()).toHaveLength(99);+ expect(f.recorder.events.some((event) => event.type === "runtime.error")).toBe(false);});it("stops at 200 tool calls in one turn without running the batch that crosses it", async () => {diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex 86c6e718ea..8a622d5683 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -141,11 +141,8 @@ const completionUsage = (json: CompletionJson) => json.usage ?? json.x_groq?.usaconst asError = (value: unknown): Error =>value instanceof Error ? value : new Error(String(value));-const MAX_CHAT_ROUNDS = 64;const MAX_TURN_TOOL_CALLS = 200;const MAX_ANNOUNCEMENT_NUDGES = 3;-const stoppedAfter = (count: string) =>- `Stopped after ${count} without a final answer. The steps so far already ran, so ask only for what's left.`;interface DeliveredUserMessage {text: string;@@ -618,7 +615,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)if (questionAllowed && !tools.definitions.some((definition) => definition.function.name === ASK_USER_TOOL)) {tools.definitions.push(ASK_USER_TOOL_DEFINITION);}- for (let round = 0; round < MAX_CHAT_ROUNDS; round++) {+ for (let round = 0; ; round++) {abort.signal.throwIfAborted();// Between rounds, never inside a tool batch.unread = turnEntry.asides.splice(0);@@ -626,7 +623,6 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)messages.push({ role: "user", content: unread.join("\n\n") });deliveredAsides.push(...unread);}- turnEntry.ending = round === MAX_CHAT_ROUNDS - 1;native("out", options.nativeLog.outgoing(turn, messages, model, tools.definitions));let attempt = 0;let resized = false;@@ -754,7 +750,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)}if (toolFailed) {// A person's "no" is never answered with another attempt; a failure may first get the configured corrective rounds.- if (!denials.length && !turnEntry.ending && correctiveRounds < Math.max(turn.toolErrorCorrectiveRounds ?? 0, options.localModel ? LOCAL_CORRECTIVE_ROUNDS : 0)) {+ if (!denials.length && correctiveRounds < Math.max(turn.toolErrorCorrectiveRounds ?? 0, options.localModel ? LOCAL_CORRECTIVE_ROUNDS : 0)) {correctiveRounds += 1;messages.push({ role: "user", content: CORRECTIVE_ROUND });continue;@@ -763,9 +759,9 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)throw new ChatProtocolError(toolFailureMessage(failedCalls, denials.filter((name) => name !== ASK_USER_TOOL)));}if (options.nudgeAnnouncedAction && tools.definitions.length && announcesAction(completion.text)) {- if (nudges >= MAX_ANNOUNCEMENT_NUDGES || turnEntry.ending) {+ if (nudges >= MAX_ANNOUNCEMENT_NUDGES) {stopReason = "incomplete_action";- throw new ChatProtocolError(`Stopped after ${turnEntry.ending ? `${MAX_CHAT_ROUNDS} steps` : `${MAX_ANNOUNCEMENT_NUDGES} announcement nudges`} without a verified final answer. Earlier operations may have taken effect; inspect their state and continue only the remaining work.`);+ throw new ChatProtocolError(`Stopped after ${MAX_ANNOUNCEMENT_NUDGES} announcement nudges without a verified final answer. Earlier operations may have taken effect; inspect their state and continue only the remaining work.`);}if (callsAtNudge === seenCalls.size) {stopReason = "incomplete_action";@@ -789,7 +785,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)if (seenCalls.has(call.id)) throw new ChatProtocolError("provider reused a tool-call ID; refusing to repeat an operation");seenCalls.add(call.id);}- if (seenCalls.size > MAX_TURN_TOOL_CALLS) throw new ChatProtocolError(stoppedAfter(`${MAX_TURN_TOOL_CALLS} tool calls`));+ if (seenCalls.size > MAX_TURN_TOOL_CALLS) throw new ChatProtocolError(`Stopped after ${MAX_TURN_TOOL_CALLS} tool calls without a final answer. The steps so far already ran, so ask only for what's left.`);messages.push(assistantReply(model, completion, completion.text || null, completion.toolCalls));// A failure stays pending only until the bot runs tools again: one that went on to use more tools has read the error// and reacted (a wrong guess, a bad query, then the right call), so its turn is not failed for it, on any model. The@@ -883,7 +879,6 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)}if (screenshotParts.length) messages.push({ role: "user", content: screenshotParts });}- if (!ok) throw new ChatProtocolError(stoppedAfter(`${MAX_CHAT_ROUNDS} steps`));} catch (value) {stopReason = abort.signal.aborted ? "interrupted" : stopReason ?? "error";failure = safeText(asError(value).message).slice(0, 2_000);diff --git a/server/long-running-chief.e2e.test.ts b/server/long-running-chief.e2e.test.tsindex b9ca5c2822..65dfeda1e3 100644--- a/server/long-running-chief.e2e.test.ts+++ b/server/long-running-chief.e2e.test.ts@@ -217,12 +217,12 @@ it("carries a consult-and-implement job over several teammate turns, through a sexpect(f.root(job).status).toBe("completed");const review = f.prompt(f.turn("A1"));expect(review).toContain("IMPLEMENT-FINISHED");- expect(review).not.toContain("Stopped after 64 steps");+ expect(review).not.toContain("Stopped after 200 tool calls");expect(review).not.toContain("assign what is left");expect(review).not.toContain('"result":"error"');expect((await f.tasks(f.eli.id)).map((task: any) => task.title).filter((title: string) => title.startsWith("Continue:"))).toEqual([]);expect(f.model.requests.filter((sent: ModelRequest) => sent.lastUser.includes("[Auto-continuation]"))).toEqual([]);- expect(f.model.requests.filter((sent: ModelRequest) => sent.lastUser.includes("IMPLEMENT-CAP") && !sent.lastUser.includes(STEP_CAP_CONTINUES))).toHaveLength(64);+ expect(f.model.requests.filter((sent: ModelRequest) => sent.lastUser.includes("IMPLEMENT-CAP") && !sent.lastUser.includes(STEP_CAP_CONTINUES))).toHaveLength(201);const continued = f.model.requests.filter((sent: ModelRequest) => sent.lastUser.includes(STEP_CAP_CONTINUES));expect(continued).toHaveLength(1);expect(continued[0]!.lastUser).toMatch(/Every step so far is listed in \S*handoffs\S*; read it before going on\./);diff --git a/server/runtime-roots.e2e.test.ts b/server/runtime-roots.e2e.test.tsindex 7417a0f770..595f85b15d 100644--- a/server/runtime-roots.e2e.test.ts+++ b/server/runtime-roots.e2e.test.ts@@ -375,7 +375,7 @@ it("T6 continues a person's step-capped turn in place on the same root", async (const root = f.roots()[0];expect(root).toMatchObject({ status: "completed", outcome: "done", executions: 2, result: "T6-DONE: finished the rest." });expect(f.eventsOf(root.id)).toEqual(expect.arrayContaining(["started", "continued", "started", "settled"]));- expect(model.requests.filter((sent) => sent.lastUser.includes("T6-JOB") && !sent.lastUser.includes(STEP_CAP_CONTINUES))).toHaveLength(64);+ expect(model.requests.filter((sent) => sent.lastUser.includes("T6-JOB") && !sent.lastUser.includes(STEP_CAP_CONTINUES))).toHaveLength(201);const continued = model.requests.filter((sent) => sent.lastUser.includes(STEP_CAP_CONTINUES));expect(continued).toHaveLength(1);expect(continued[0]!.lastUser).toMatch(/Every step so far is listed in \S*handoffs\S*; read it before going on\./);diff --git a/server/runtime/capabilities.test.ts b/server/runtime/capabilities.test.tsindex d185e510ab..f050877973 100644--- a/server/runtime/capabilities.test.ts+++ b/server/runtime/capabilities.test.ts@@ -7,7 +7,7 @@ import { describe, expect, it } from "vitest";import { BUILT_IN_DRIVERS } from "../drivers/builtIn.ts";import { ENGINE_KINDS, engineCapabilities, replaysTranscriptNatively, type EngineCapabilities } from "./capabilities.ts";-const chat: EngineCapabilities = { resume: false, nativeReviewer: false, full: true, edits: false, stepCap: 64, subagents: false };+const chat: EngineCapabilities = { resume: false, nativeReviewer: false, full: true, edits: false, subagents: false };const bare: EngineCapabilities = { resume: true, nativeReviewer: false, full: true, edits: false, subagents: false };const EXPECTED: Record<string, EngineCapabilities> = {@@ -70,21 +70,6 @@ describe("engineCapabilities", () => {it("gives no engine subagents today", () => {for (const kind of ENGINE_KINDS) expect(engineCapabilities(kind).subagents).toBe(false);});-- it("leaves stepCap off engines that bound their own turns", () => {- for (const kind of ENGINE_KINDS) {- const caps = engineCapabilities(kind);- if (caps.resume) expect("stepCap" in caps, `${kind} keeps a native session and needs no step cap`).toBe(false);- else expect(caps.stepCap, `${kind} replays the transcript and needs the chat family's cap`).toBe(64);- }- });-- it("keeps the chat family's step cap equal to MAX_CHAT_ROUNDS in openai-chat.ts", () => {- const source = readFileSync(new URL("../drivers/openai-chat.ts", import.meta.url), "utf8");- const found = /^const MAX_CHAT_ROUNDS = (\d+);/m.exec(source);- expect(found, "MAX_CHAT_ROUNDS moved or was renamed; update server/runtime/capabilities.ts").not.toBeNull();- expect(engineCapabilities("openai-compat").stepCap).toBe(Number(found![1]));- });});describe("replaysTranscriptNatively", () => {diff --git a/server/runtime/capabilities.ts b/server/runtime/capabilities.tsindex a54b81feb7..f6d0b644f2 100644--- a/server/runtime/capabilities.ts+++ b/server/runtime/capabilities.ts@@ -6,16 +6,13 @@ export interface EngineCapabilities {nativeReviewer: boolean;full: boolean;edits: boolean;- stepCap?: number;subagents: boolean;}-const CHAT_STEP_CAP = 64;-// transcript: the engine sends the thread as SendTurnInput.transcript messages, so the turn text must not replay it inline too.-type EngineRow = Pick<EngineCapabilities, "resume" | "stepCap"> & { transcript?: true };+type EngineRow = Pick<EngineCapabilities, "resume"> & { transcript?: true };-const CHAT_ROW: EngineRow = { resume: false, stepCap: CHAT_STEP_CAP, transcript: true };+const CHAT_ROW: EngineRow = { resume: false, transcript: true };const ENGINES: Readonly<Record<string, EngineRow>> = {claudeAgent: { resume: true },@@ -64,7 +61,6 @@ export function engineCapabilities(driverKind: string | undefined): EngineCapabinativeReviewer: hasNativeAutoReview(driverKind),full: supportsApprovalMode(driverKind, "full"),edits: supportsApprovalMode(driverKind, "edits"),- ...(row?.stepCap === undefined ? {} : { stepCap: row.stepCap }),subagents: false,};}