Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(chat): preserve active task and steering in cap handoffs
agooll605fd9a52014
diff --git a/server/drivers/openai-chat-tools.test.ts b/server/drivers/openai-chat-tools.test.tsindex cb4d61fda7..b085a025a0 100644--- a/server/drivers/openai-chat-tools.test.ts+++ b/server/drivers/openai-chat-tools.test.ts@@ -1359,6 +1359,41 @@ describe("structured tool execution boundaries", () => {})]);});+ it.each([1, 25])("preserves the active task and delivered steering in a cap handoff (%i calls per reply)", async callsPerReply => {+ const first = deferred<ServerResponse>();+ const f = await fixture((_body, response, round) => {+ if (round === 1) first.resolve(response);+ else reply(response, round);+ });+ function reply(response: ServerResponse, round: number) {+ sse(response, [chunk({ tool_calls: Array.from({ length: callsPerReply }, (_, index) => ({+ ...toolCall("audit_write", `{"name":"step","value":"${round}-${index}"}`, `call_${round}_${index}`), index,+ })) }, "tool_calls")]);+ }+ const task = "Prepare the release draft";+ const updates = ["Do not publish it", "Use version 2"];+ await f.start({ approvalMode: "full", text: task, transcript: [+ { role: "user", text: "List repository files" },+ { role: "assistant", text: "Listed the files" },+ ] });+ const response = await first.promise;+ for (const update of updates) await expect(f.instance.adapter.steer!(f.threadId, update)).resolves.toBe("steered");+ reply(response, 1);+ expect(await f.completed()).toMatchObject({ ok: false, stopReason: "error" });+ const cap = f.recorder.events.find(event => event.type === "cap.exhausted");+ expect(cap?.type).toBe("cap.exhausted");+ if (cap?.type !== "cap.exhausted") throw new Error("missing cap handoff");+ const handoff = readFileSync(cap.handoffPath, "utf8");+ expect(handoff).toContain(task);+ expect(handoff).not.toContain("List repository files");+ expect(handoff).not.toContain("Listed the files");+ 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);+ });+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 < 64diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex ec7c60171d..acd9aee3e7 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -599,6 +599,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)const seenCalls = new Set<string>();let nudges = 0;let unread: string[] = [];+ const deliveredAsides: string[] = [];let callsAtNudge = -1;const repeats = options.localModel ? new ChatRepeatGuard() : undefined;let unreadable = false, askedAgain = false;@@ -621,7 +622,10 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)abort.signal.throwIfAborted();// Between rounds, never inside a tool batch.unread = turnEntry.asides.splice(0);- if (unread.length) messages.push({ role: "user", content: unread.join("\n\n") });+ if (unread.length) {+ 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;@@ -907,14 +911,10 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)const continuable = classifyContinuable(stopReason, failure);if (continuable) {const handoffPath = writeTurnHandoff({- threadId: turn.threadId,- turnId,- model,- usage,- hasUsage,- failure,- toolCalls: seenCalls.size,- messages,+ threadId: turn.threadId, turnId, model,+ usage, hasUsage, failure, toolCalls: seenCalls.size,+ task: turn.text, updates: deliveredAsides,+ messages: messages.slice(messages.indexOf(request) + 1),});if (handoffPath) emit({ ...base(turn.threadId, turnId), type: "cap.exhausted", handoffPath, reason: continuable });}diff --git a/server/turn-continuation.test.ts b/server/turn-continuation.test.tsindex 682d2897a8..e2d11a6599 100644--- a/server/turn-continuation.test.ts+++ b/server/turn-continuation.test.ts@@ -19,6 +19,44 @@ function withTempDataDir(): string {}describe("writeTurnHandoff", () => {+ it("uses the active task instead of an older request or a later image message", () => {+ withTempDataDir();+ const path = writeTurnHandoff({+ threadId: "current", turnId: "turn", toolCalls: 0,+ task: "Repair the parser test",+ messages: [+ { role: "user", content: "List repository files" },+ { role: "assistant", content: "Listed the files" },+ { role: "user", content: [{ type: "text", text: "Repair the parser test" }, { type: "image_url", image_url: { url: "data:image/png;base64,fixture" } }] },+ { role: "user", content: [{ type: "text", text: "Screenshot result from tool call read" }] },+ ],+ });+ const text = readFileSync(path!, "utf8");+ expect(text).toContain("Repair the parser test");+ expect(text).not.toContain("List repository files");+ expect(text).not.toContain("data:image");+ expect(text).not.toContain("Screenshot result");+ });++ it("retains delivered updates in order without treating internal user messages as instructions", () => {+ withTempDataDir();+ const path = writeTurnHandoff({+ threadId: "updated", turnId: "turn", toolCalls: 0, task: "Prepare a release",+ updates: ["Draft only; do not publish", "Use version 2"],+ messages: [+ { role: "user", content: "Prepare a release" },+ { role: "user", content: "Draft only; do not publish" },+ { role: "user", content: "Use version 2" },+ { role: "user", content: "Synthetic internal corrective prompt" },+ ],+ });+ const text = readFileSync(path!, "utf8");+ expect(text).toContain("Draft only; do not publish");+ expect(text).toContain("Use version 2");+ expect(text.indexOf("Draft only")).toBeLessThan(text.indexOf("Use version 2"));+ expect(text).not.toContain("Synthetic internal corrective prompt");+ });+it("writes a structured handoff with the original task, ordered tool calls, and last text", () => {const dir = withTempDataDir();const path = writeTurnHandoff({@@ -26,6 +64,7 @@ describe("writeTurnHandoff", () => {hasUsage: true, usage: { input: 10, output: 20 },failure: "Stopped after 64 steps without a final answer",toolCalls: 3,+ task: "Build the thing",messages: [{ role: "user", content: "Build the thing" },{ role: "assistant", content: null, tool_calls: [{ function: { name: "host_shell_exec", arguments: "{\"command\":\"ls\"}" } }] },@@ -50,7 +89,7 @@ describe("writeTurnHandoff", () => {it("returns an absolute handoff when OMB_DATA_DIR is relative", () => {const dir = withTempDataDir();process.env.OMB_DATA_DIR = relative(process.cwd(), dir);- const path = writeTurnHandoff({ threadId: "relative", turnId: "turn", toolCalls: 0, messages: [] });+ const path = writeTurnHandoff({ threadId: "relative", turnId: "turn", toolCalls: 0, task: "Continue", messages: [] });expect(path).not.toBeNull();expect(isAbsolute(path!)).toBe(true);expect(dirname(path!)).toBe(join(dir, "handoffs"));@@ -59,7 +98,7 @@ describe("writeTurnHandoff", () => {it("returns null when the handoff cannot be written", () => {process.env.OMB_DATA_DIR = join(tmpdir(), "omb-handoff-", "does-not-exist", "nested");- expect(writeTurnHandoff({ threadId: "t", turnId: "u", toolCalls: 0, messages: [] })).not.toBeNull();+ expect(writeTurnHandoff({ threadId: "t", turnId: "u", toolCalls: 0, task: "Continue", messages: [] })).not.toBeNull();rmSync(join(tmpdir(), "omb-handoff-"), { recursive: true, force: true });});});diff --git a/server/turn-continuation.ts b/server/turn-continuation.tsindex bc4fdfd13d..c642b4c4d0 100644--- a/server/turn-continuation.ts+++ b/server/turn-continuation.ts@@ -14,6 +14,8 @@ export interface HandoffInput {hasUsage?: boolean;failure?: string;toolCalls: number;+ task: string;+ updates?: string[];messages: Array<{role: string;content?: unknown;@@ -36,12 +38,11 @@ export function writeTurnHandoff(input: HandoffInput): string | null {if (input.hasUsage && input.usage) L.push(`- Tokens this turn: ${input.usage.input} in / ${input.usage.output} out`);L.push(`- Stop reason: ${input.failure ?? "unknown"}`);L.push(`- Written at: ${new Date().toISOString()}`, "");- L.push("## Original task (first user message)", "```");- const firstUser = input.messages.find((m) => m.role === "user");- const firstText = firstUser && typeof firstUser.content === "string"- ? firstUser.content- : JSON.stringify(firstUser?.content ?? null);- L.push(String(firstText).slice(0, 8000), "```", "");+ L.push("## Current task", "```", input.task.slice(0, 8000), "```", "");+ if (input.updates?.length) {+ L.push("## Updates delivered during this turn (in order)", "");+ for (const update of input.updates) L.push("```", update.slice(0, 8000), "```", "");+ }L.push("## Work performed (tool calls in order)", "");let n = 0;for (const m of input.messages) {