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): accept a legacy function_call from OpenAI-compatible relays
AdityaUmalec97c657d0c19
diff --git a/server/drivers/openai-chat-protocol.test.ts b/server/drivers/openai-chat-protocol.test.tsindex 19f0147faa..5d829d9057 100644--- a/server/drivers/openai-chat-protocol.test.ts+++ b/server/drivers/openai-chat-protocol.test.ts@@ -99,3 +99,53 @@ describe("streamed tool calls without an index (Gemini's OpenAI-compatible endpoexpect(() => calls.add([whole("call_32", "f")], true)).toThrow(/invalid tool-call index/);});});++describe("legacy function_call from OpenAI-compatible relays", () => {+ it("turns a streamed legacy call into one structured call", () => {+ const calls = new ChatToolCalls();+ calls.addLegacy({ name: "echo", arguments: "" });+ calls.addLegacy({ arguments: "{\"a\":" });+ calls.addLegacy({ name: null, arguments: "1}" });+ const [call, ...rest] = calls.finish("function_call", false);+ expect(rest).toEqual([]);+ expect(call).toMatchObject({ type: "function", function: { name: "echo", arguments: "{\"a\":1}" } });+ expect(call?.id).toMatch(/^call_[0-9a-f]{32}$/);+ });++ it("takes a whole legacy call from a non-streamed message", () => {+ const calls = new ChatToolCalls();+ calls.addLegacy({ name: "echo", arguments: "{}" });+ expect(calls.finish("stop", false)).toMatchObject([{ function: { name: "echo", arguments: "{}" } }]);+ });++ it("ignores an empty placeholder so a plain reply still finishes", () => {+ const calls = new ChatToolCalls();+ calls.addLegacy({});+ calls.addLegacy({ name: "", arguments: "" });+ expect(calls.finish("stop", false)).toEqual([]);+ });++ it("keeps the structured calls when a relay mirrors one into function_call", () => {+ const calls = new ChatToolCalls();+ calls.add([completeCall], false);+ calls.addLegacy({ name: "echo", arguments: "{}" });+ expect(calls.finish("tool_calls", false)).toEqual([completeCall]);+ });++ it("still rejects a function_call finish with no named call", () => {+ const calls = new ChatToolCalls();+ calls.addLegacy({ arguments: "{}" });+ expect(() => calls.finish("function_call", false)).toThrow(/without a complete call/);+ });++ it.each(["call", [], { name: 1 }, { arguments: {} }])("rejects a malformed legacy call %j", (value) => {+ expect(() => new ChatToolCalls().addLegacy(value)).toThrow();+ });++ it("applies the name rules and size limits to legacy calls", () => {+ const named = new ChatToolCalls();+ named.addLegacy({ name: "bad name", arguments: "{}" });+ expect(() => named.finish("function_call", false)).toThrow();+ expect(() => new ChatToolCalls().addLegacy({ name: "n".repeat(65) })).toThrow(/size limit/);+ });+});diff --git a/server/drivers/openai-chat-protocol.ts b/server/drivers/openai-chat-protocol.tsindex 6e8b0d77cd..d395b84695 100644--- a/server/drivers/openai-chat-protocol.ts+++ b/server/drivers/openai-chat-protocol.ts@@ -1,4 +1,6 @@// Structured chat-completions calls. Assistant content becomes a tool call only for a local model, in chat-text-tool-calls.ts.+import { randomUUID } from "node:crypto";+export interface ChatToolCall {id: string;type: "function";@@ -37,6 +39,22 @@ export class ChatReasoningDetails {export class ChatToolCalls {private calls = new Map<number, ChatToolCall>();private argumentChars = 0;+ /** The pre-tools `function_call` field some OpenAI-compatible relays still answer with: one call, no ID. */+ private legacy = { name: "", arguments: "" };++ addLegacy(value: unknown): void {+ if (value === undefined || value === null) return;+ const fn = object(value);+ if (!fn) throw new ChatProtocolError("provider returned an invalid function_call");+ for (const field of ["name", "arguments"] as const) {+ if (fn[field] === undefined || fn[field] === null) continue;+ if (typeof fn[field] !== "string") throw new ChatProtocolError("provider returned invalid function_call arguments or name");+ this.legacy[field] += fn[field];+ }+ if (this.legacy.name.length > 64 || this.legacy.arguments.length > MAX_ARGUMENT_CHARS) {+ throw new ChatProtocolError("provider tool calls exceeded the size limit");+ }+ }add(value: unknown, streaming: boolean): void {if (value === undefined || value === null) return;@@ -84,10 +102,15 @@ export class ChatToolCalls {finish(reason: string | null, malformedFrame: boolean): ChatToolCall[] {const calls = [...this.calls.entries()].sort(([a], [b]) => a - b).map(([, call]) => call);if (malformedFrame) throw new ChatProtocolError("provider stream contained a malformed completion frame");- if (reason === "function_call") throw new ChatProtocolError("legacy function_call is unsupported; use structured tool_calls");- if (reason === "tool_calls" && !calls.length) throw new ChatProtocolError("provider ended for tool calls without a complete call");+ // A legacy call counts only alone and named: relays that mirror tool_calls or send an empty placeholder add nothing.+ if (!calls.length && this.legacy.name) {+ calls.push({ id: `call_${randomUUID().replaceAll("-", "")}`, type: "function", function: { ...this.legacy } });+ }+ if ((reason === "tool_calls" || reason === "function_call") && !calls.length) {+ throw new ChatProtocolError("provider ended for tool calls without a complete call");+ }if (!calls.length) return calls;- if (reason !== null && reason !== "tool_calls" && reason !== "stop") {+ if (reason !== null && reason !== "tool_calls" && reason !== "function_call" && reason !== "stop") {throw new ChatProtocolError("provider tool calls were truncated or malformed");}const ids = new Set<string>();diff --git a/server/drivers/openai-chat.test.ts b/server/drivers/openai-chat.test.tsindex e7877b76c3..077f621d6d 100644--- a/server/drivers/openai-chat.test.ts+++ b/server/drivers/openai-chat.test.ts@@ -734,6 +734,16 @@ describe("createOpenAIChatRuntime stream termination", () => {expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: true });});+ it("finishes a plain reply from a relay that adds an empty legacy function_call", async () => {+ const events = await runTurn(+ 'data: {"choices":[{"index":0,"delta":{"content":"OK","function_call":{"name":"","arguments":""}}}]}\n\n'+ + 'data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n',+ );+ expect(events.find((event) => event.type === "runtime.error")).toBeUndefined();+ expect(events.find((event) => event.type === "item.completed")).toMatchObject({ text: "OK" });+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: true });+ });+it("still honors data: [DONE]", async () => {const events = await runTurn('data: {"choices":[{"delta":{"content":"hi"}}]}\n\ndata: [DONE]\n\n');expect(events.find((event) => event.type === "item.completed")).toMatchObject({ text: "hi" });diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex fec49d69df..0bd64afd56 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -348,9 +348,9 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)if (!message || !object(message) || !["content", "reasoning_content", "reasoning", "reasoning_details", "tool_calls", "function_call"].some((key) => key in message)) {throw new ChatProtocolError("provider returned no completion message");}- if (message?.function_call) throw new ChatProtocolError("legacy function_call is unsupported; use structured tool_calls");const calls = new ChatToolCalls();calls.add(message?.tool_calls, false);+ calls.addLegacy(message.function_call);const details = new ChatReasoningDetails();details.add(message.reasoning_details);const reasoning = message.reasoning_content ?? message.reasoning;@@ -401,8 +401,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)const choice = chunk.choices?.find((row) => row.index === undefined || row.index === 0);const delta = choice?.delta;if (object(delta)) sawChoice = true;- if (delta?.function_call) throw new ChatProtocolError("legacy function_call is unsupported; use structured tool_calls");calls.add(delta?.tool_calls, true);+ calls.addLegacy(delta?.function_call);details.add(delta?.reasoning_details);if (choice?.finish_reason) finishReason = choice.finish_reason;const reasoningPart = delta?.reasoning_content ?? delta?.reasoning;