Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(openai-chat): replay a tool call with unparseable arguments as {}
AdityaUmale64aadbd27cb2
diff --git a/server/drivers/openai-chat-protocol.ts b/server/drivers/openai-chat-protocol.tsindex eabde05000..070a2d916e 100644--- a/server/drivers/openai-chat-protocol.ts+++ b/server/drivers/openai-chat-protocol.ts@@ -24,6 +24,25 @@ export function object(value: unknown): Record<string, unknown> | undefined {? value as Record<string, unknown> : undefined;}+/** A call's arguments as its tool gets them. An empty argument string is a tool with no arguments. */+export function toolArguments(text: string): Record<string, unknown> {+ let args: unknown;+ try { args = JSON.parse(text.trim() || "{}"); }+ catch { throw new ChatProtocolError("tool arguments are not complete JSON"); }+ const found = object(args);+ if (!found) throw new ChatProtocolError("tool arguments must be a JSON object");+ return found;+}++/** The calls as the next request replays them. Arguments `toolArguments` refuses never ran (the call's result says+ * so) and go back as `{}`: a strict server refuses the whole request over them ("function.arguments must be valid JSON"). */+export function replayableToolCalls(calls: ChatToolCall[]): ChatToolCall[] {+ return calls.map((call) => {+ try { toolArguments(call.function.arguments); return call; }+ catch { return { ...call, function: { ...call.function, arguments: "{}" } }; }+ });+}+/** Opaque provider reasoning blocks must keep their original order/signatures.* OpenRouter streams the sequence as arrays of blocks, not tool-call deltas. */export class ChatReasoningDetails {diff --git a/server/drivers/openai-chat.test.ts b/server/drivers/openai-chat.test.tsindex d9083749e3..be98b5fc01 100644--- a/server/drivers/openai-chat.test.ts+++ b/server/drivers/openai-chat.test.ts@@ -435,6 +435,45 @@ describe("createOpenAIChatRuntime tool approvals", () => {}, 20_000);});+ it("replays a call whose arguments are not JSON as an empty object, so a strict provider takes the next request", async () => {+ const call = (id: string, argumentsText: string) =>+ `data: ${JSON.stringify({ choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id, type: "function", function: { name: "fx_write", arguments: argumentsText } }] } }] })}\n\n`+ + 'data: {"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}\n\n';+ const replies = [call("c1", '{"path":"a.md","content":"cut off'), call("c2", "{}"),+ 'data: {"choices":[{"index":0,"delta":{"content":"Written."}}]}\n\ndata: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\n'];+ const bodies: any[] = [];+ vi.stubGlobal("fetch", vi.fn(async (input: unknown, init?: RequestInit) => {+ if (!String(input).endsWith("/chat/completions")) return new Response(JSON.stringify({ data: [] }));+ const body = JSON.parse(String(init?.body));+ bodies.push(body);+ const replayed = body.messages.flatMap((message: any) => message.tool_calls ?? []);+ if (replayed.some((toolCall: any) => { try { JSON.parse(toolCall.function.arguments); return false; } catch { return true; } })) {+ return new Response(JSON.stringify({ error: { message: "Assistant tool call function.arguments must be valid JSON", type: "invalid_request_error" } }), { status: 400 });+ }+ return new Response(replies[bodies.length - 1], { headers: { "content-type": "text/event-stream" } });+ }));+ const instance = await OpenAICompatDriver.create({+ instanceId: "badargs", displayName: "Synthetic", enabled: true,+ config: OpenAICompatDriver.decodeConfig({ url: "https://api.example.test/v1", apiKeyEnv: "K", model: "fixture" }),+ environment: { K: "synthetic" },+ });+ const events: RuntimeEvent[] = [];+ instance.adapter.onEvent((event) => events.push(event));+ try {+ await instance.adapter.sendTurn({+ threadId: "badargs", text: "Write the file.", approvalMode: "full", integrations: { custom: { fx: toolServer() } },+ });+ await vi.waitFor(() => expect(events.some((event) => event.type === "turn.completed")).toBe(true), { timeout: 10_000 });+ expect(bodies).toHaveLength(3);+ expect(bodies[1].messages.find((message: any) => message.tool_calls)?.tool_calls[0].function.arguments).toBe("{}");+ expect(bodies[1].messages.find((message: any) => message.role === "tool" && message.tool_call_id === "c1")?.content)+ .toContain("tool arguments are not complete JSON");+ expect((events.find((event) => event.type === "turn.completed") as any).ok).toBe(true);+ } finally {+ await instance.dispose();+ }+ }, 20_000);+it("completes the turn when a question goes unanswered, without tainting the final answer", async () => {const askBody = 'data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"ask1","type":"function","function":{"name":"ask_user","arguments":'+ JSON.stringify(JSON.stringify({ questions: [{ question: "Ship the fixture?", options: [{ label: "Yes" }, { label: "No" }] }] }))diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex 2f8f82b7ac..40a32e1b76 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -20,7 +20,7 @@ import { chatToolLimitFor, chatToolLimitKey } from "../tool-count-limit.ts";import { assertImageTransport, chatImageBudget, chatToolImages, chatUserContent, type ChatContentPart } from "./chat-images.ts";import { promptHalves, volatileContextNote, withContextNote } from "./prompt-split.ts";import { createChatToolApproval, refusal } from "./chat-tool-approval.ts";-import { ChatProtocolError, ChatReasoningDetails, ChatToolCalls, object, type ChatToolCall } from "./openai-chat-protocol.ts";+import { ChatProtocolError, ChatReasoningDetails, ChatToolCalls, object, replayableToolCalls, toolArguments, type ChatToolCall } from "./openai-chat-protocol.ts";import { completionError, httpErrorDetail, refusedToolCall, refusedToolCallFailure, rejectsReasoningReplay, rejectsToolsParameter, RejectedToolCallError, StreamTruncatedError, UnsupportedChatToolsError, UnsupportedReasoningReplayError, type ProviderBody } from "./openai-chat-refusals.ts";import { ChatRepeatGuard } from "./chat-repeat-guard.ts";import { TextCallHoldback, textToolCalls } from "./chat-text-tool-calls.ts";@@ -790,7 +790,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)seenCalls.add(call.id);}if (seenCalls.size > MAX_TURN_TOOL_CALLS) throw new ChatProtocolError(stoppedAfter(`${MAX_TURN_TOOL_CALLS} tool calls`));- messages.push(assistantReply(model, completion, completion.text || null, completion.toolCalls));+ messages.push(assistantReply(model, completion, completion.text || null, replayableToolCalls(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// failed step still shows as failed; a failure in the last calls before the answer, or a person's no, still ends it.@@ -802,10 +802,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)let started = false;let fatal: Error | undefined, title = call.function.name, skipRepeatCount = false;try {- let args: unknown;- try { args = JSON.parse(call.function.arguments.trim() || "{}"); } // An empty argument string is a tool with no arguments.- catch { throw new ChatProtocolError("tool arguments are not complete JSON"); }- if (!object(args)) throw new ChatProtocolError("tool arguments must be a JSON object");+ const args = toolArguments(call.function.arguments);const inputPreview = preview(args);if (call.function.name === ASK_USER_TOOL) {if (!questionAllowed || !allowsTool(scope, { kind: "native", name: ASK_USER_TOOL })) throw new Error("Tool selection excludes this tool");@@ -832,7 +829,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)const refused = repeats?.refuses(call.function.name, call.function.arguments);if (refused) { skipRepeatCount = true; throw new Error(refused); }tools.validate(call.function.name, args);- const shown = tools.view(call.function.name, args as Record<string, unknown>); title = shown.title;+ const shown = tools.view(call.function.name, args); title = shown.title;const shownPreview = shown.input === args ? inputPreview : preview(shown.input);// This runtime has no provider reviewer, so Full access is honoured here.const full = (turn.approvalModeNow?.() ?? turn.approvalMode) === "full";@@ -845,7 +842,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)});started = true;if (allowed) {- result = await tools.execute(call.function.name, args as Record<string, unknown>, abort.signal);+ result = await tools.execute(call.function.name, args, abort.signal);if (result.images?.length && !seesImages(turn)) {const { images: _dropped, ...rest } = result;result = { ...rest, text: `${rest.text}\n${TEXT_ONLY_SCREENSHOT_NOTE}` };