xonecas.io
64875
Mc

mini-coder / commit c60f67d

fix: normalize zen openai-compatible tool-call inputs

xonecas2026-03-14 c60f67d7a5f2ed577b2b9475e8abfe425d61268c parent 173190b

3 files changed

TODO.md+4−83
@@ -1,79 +1,6 @@
11 # TODO
22
3-- Most models hang for long periods during turns. Sometines needing the user to interrupt to continue. This happened in recent sessions in the db. This is not a provider issues, both opencode and pi using the same provider and model don't have hangups.
4-
5-- Tool hooks output prints inline with spinner when they should output in a new line and indented like the tool calls output.
6-- add a spinner state showing the user when the undo snapshotting is happening
7-- Structuted output when a skill is auto loaded for the agent
8-- Kimi-k2.5, GLM-5 and other models that use the same sdk produce these errors:
9-
10-Error 1:
11-
12-```
13-"{\"error\":{\"object\":\"error\",\"type\":\"invalid_request_error\",\"code\":\"invalid_request_error\",\"message\":\"Invalid tool call in messages: tool_calls[].function.arguments for function 'read' must decode to a JSON object, got str\"}}",
14-```
15-
16-Error 2:
17-
18-```
19-2543 | text: responseBody,
20-2544 | schema: errorSchema
21-2545 | });
22-2546 | return {
23-2547 | responseHeaders,
24-2548 | value: new APICallError4({
25- ^
26-AI_APICallError: Expected dict in tool call arguments, got <class 'str'>
27- cause: undefined,
28- url: "https://opencode.ai/zen/v1/chat/completions",
29- requestBodyValues: {
30- model: "glm-5",
31- user: undefined,
32- max_tokens: undefined,
33- temperature: undefined,
34- top_p: undefined,
35- frequency_penalty: undefined,
36- presence_penalty: undefined,
37- response_format: undefined,
38- stop: undefined,
39- seed: undefined,
40- reasoning_effort: undefined,
41- verbosity: undefined,
42- messages: [
43- [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Objec …
44- ],
45- tools: [
46- [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...]
47- ],
48- tool_choice: "auto",
49- stream: true,
50- stream_options: undefined,
51-},
52- statusCode: 400,
53- responseHeaders: {
54- "cf-ray": "9dc2e9f38ed09063-BOS",
55- connection: "keep-alive",
56- "content-type": "application/json",
57- date: "Sat, 14 Mar 2026 11:24:46 GMT",
58- server: "cloudflare",
59- "transfer-encoding": "chunked",
60-},
61- responseBody: "{\n\t\"error\": {\n\t\t\"code\": 400,\n\t\t\"message\": \"Expected dict in tool call arguments, got \\u003cclass 'str'\\u003e\",\n\t\t\"type\": \"Bad Request\"\n\t}\n}\n",
62- isRetryable: false,
63- data: {
64- error: [Object ...],
65-},
66- vercel.ai.error: true,
67- vercel.ai.error.AI_APICallError: true,
68-
69- at /home/xonecas/src/mini-coder/node_modules/@ai-sdk/provider-utils/dist/index.mjs:2548:18
70- at /home/xonecas/src/mini-coder/node_modules/@ai-sdk/provider-utils/dist/index.mjs:2391:34
71- at processTicksAndRejections (native:7:39)
72-
73-✖ API error 400
74- https://opencode.ai/zen/v1/chat/completions
75-```
76-
3+- read/write tool call output only visible when tool call response is already visible too.
774 - Investigate db lock issues with spawning parallel subagents:
785
796 ```
@@ -86,15 +13,6 @@ AI_APICallError: Expected dict in tool call arguments, got <class 'str'>
8613 ◆ Subagent parallelism hit a SQLite lock in the shared app DB, so I’m finishing the audit with direct reads and a smaller follow-up pass grounded in file references.
8714 ```
8815
89-- double line print bug:
90-
91-```
92-· reasoning
93-│ Mapping command definitions
94-◆ Progress update: I’ve loaded the idea/TODO and core user docs; next I’m scanning implementation files to map actual behavior against t
95-◆ Progress update: I’ve loaded the idea/TODO and core user docs; next I’m scanning implementation files to map actual behavior against those sources and capture precise gaps/inconsistencies for the report.
96-```
97-
9816 - read tool path issues, says file not found on valid path:
9917
10018 ```
@@ -108,6 +26,9 @@ AI_APICallError: Expected dict in tool call arguments, got <class 'str'>
10826 · src/cli/stream-render.ts 296 lines
10927 ```
11028
29+- add a spinner state showing the user when the undo snapshotting is happening
30+- Structuted output when a skill is auto loaded for the agent and improve context pruning output to match out style
31+
11132 ---
11233
11334 ## UI Audit
src/llm-api/turn.test.ts+50−0
@@ -7,6 +7,7 @@ import {
77 getMessageDiagnostics,
88 getReasoningDeltaFromStreamChunk,
99 isOpenAIGPT,
10+ normalizeOpenAICompatibleToolCallInputs,
1011 sanitizeGeminiToolMessages,
1112 stripGPTCommentaryFromHistory,
1213 stripOpenAIItemIdsFromHistory,
@@ -36,6 +37,55 @@ describe("isOpenAIGPT", () => {
3637 });
3738 });
3839
40+describe("normalizeOpenAICompatibleToolCallInputs", () => {
41+ const makeAssistantToolCallMessages = (input: string): CoreMessage[] => [
42+ {
43+ role: "assistant",
44+ content: [
45+ {
46+ type: "tool-call",
47+ toolCallId: "call_1",
48+ toolName: "read",
49+ input,
50+ },
51+ ],
52+ } as unknown as CoreMessage,
53+ ];
54+
55+ test("parses stringified object tool-call input for zen openai-compatible chat models", () => {
56+ const messages = makeAssistantToolCallMessages('{"path":"TODO.md"}');
57+
58+ const normalized = normalizeOpenAICompatibleToolCallInputs(
59+ messages,
60+ "zen/glm-5",
61+ );
62+ const part = (normalized[0] as { content: Array<Record<string, unknown>> })
63+ .content[0];
64+ expect(part?.input).toEqual({ path: "TODO.md" });
65+ });
66+
67+ test("leaves non-object parsed inputs unchanged", () => {
68+ const messages = makeAssistantToolCallMessages('"raw-string"');
69+
70+ const normalized = normalizeOpenAICompatibleToolCallInputs(
71+ messages,
72+ "zen/glm-5",
73+ );
74+ expect(normalized).toBe(messages);
75+ });
76+
77+ test("does not run for non zen-openai-compatible models", () => {
78+ const messages = makeAssistantToolCallMessages('{"path":"TODO.md"}');
79+
80+ expect(
81+ normalizeOpenAICompatibleToolCallInputs(messages, "zen/gpt-5.3-codex"),
82+ ).toBe(messages);
83+ expect(
84+ normalizeOpenAICompatibleToolCallInputs(messages, "openai/gpt-4o"),
85+ ).toBe(messages);
86+ });
87+});
88+
3989 describe("getReasoningDeltaFromStreamChunk", () => {
4090 test("reads SDK reasoning-delta text field", () => {
4191 expect(
src/llm-api/turn.ts+70−3
@@ -431,6 +431,62 @@ function isGeminiModelFamily(modelString: string): boolean {
431431 );
432432 }
433433
434+function isZenOpenAICompatibleChatModel(modelString: string): boolean {
435+ const { provider, modelId } = parseModelString(modelString);
436+ if (provider !== "zen") return false;
437+ return (
438+ !modelId.startsWith("gpt-") &&
439+ !modelId.startsWith("gemini-") &&
440+ !modelId.startsWith("claude-")
441+ );
442+}
443+
444+export function normalizeOpenAICompatibleToolCallInputs(
445+ messages: CoreMessage[],
446+ modelString: string,
447+): CoreMessage[] {
448+ if (!isZenOpenAICompatibleChatModel(modelString)) return messages;
449+
450+ let mutated = false;
451+ const result = messages.map((message) => {
452+ if (message.role !== "assistant" || !Array.isArray(message.content)) {
453+ return message;
454+ }
455+
456+ let contentMutated = false;
457+ const nextContent = message.content.map((part) => {
458+ if (
459+ !isToolCallPart(part) ||
460+ !("input" in part) ||
461+ typeof part.input !== "string"
462+ ) {
463+ return part;
464+ }
465+
466+ try {
467+ const parsed = JSON.parse(part.input);
468+ if (!isRecord(parsed) || Array.isArray(parsed)) return part;
469+ contentMutated = true;
470+ return {
471+ ...part,
472+ input: parsed,
473+ };
474+ } catch {
475+ return part;
476+ }
477+ });
478+
479+ if (!contentMutated) return message;
480+ mutated = true;
481+ return {
482+ ...message,
483+ content: nextContent as CoreMessage["content"],
484+ } as CoreMessage;
485+ });
486+
487+ return mutated ? result : messages;
488+}
489+
434490 type GeminiToolHistoryRepairReason = "missing-signature-anchor";
435491
436492 function validateGeminiAssistantToolCallMessage(message: CoreMessage): {
@@ -888,15 +944,26 @@ export async function* runTurn(options: {
888944 logApiEvent("openai history transforms applied", { modelString });
889945 }
890946
947+ const compatNormalizedMessages = normalizeOpenAICompatibleToolCallInputs(
948+ openAIStrippedMessages,
949+ modelString,
950+ );
951+ if (
952+ compatNormalizedMessages !== openAIStrippedMessages &&
953+ isApiLogEnabled()
954+ ) {
955+ logApiEvent("openai-compatible tool input normalized", { modelString });
956+ }
957+
891958 // Only compute full diagnostics when the API log is active; otherwise
892959 // use a lightweight count+bytes helper that skips roleBreakdown/topContributors.
893960 const apiLogOn = isApiLogEnabled();
894961 const prePruneDiagnostics = apiLogOn
895- ? getMessageDiagnostics(openAIStrippedMessages)
896- : getMessageStats(openAIStrippedMessages);
962+ ? getMessageDiagnostics(compatNormalizedMessages)
963+ : getMessageStats(compatNormalizedMessages);
897964 if (apiLogOn) logApiEvent("turn context pre-prune", prePruneDiagnostics);
898965 const prunedMessages = applyContextPruning(
899- openAIStrippedMessages,
966+ compatNormalizedMessages,
900967 pruningMode,
901968 );
902969 const postPruneDiagnostics = apiLogOn