Repository navigation
feat: nudge the model when a tool call arrives unparseable - #437
Conversation
A tool call whose arguments fail JSON parsing is usually a response cut off at the output-token limit mid-payload. The generic repair fallback relayed only the bare parser error, so the model improvised (arbitrary chunking, shell concatenation). The invalid-tool error text now names the likely cause and the recovery: retry with smaller arguments, split large file writes across several smaller calls. Nudge only - schema validation and unknown-tool failures keep their current wording, and the model remains free to retry the same call.
|
This PR doesn't fully meet our contributing guidelines and PR template. What needs to be fixed:
Please edit this PR description to address the above within 2 hours, or it will be automatically closed. If you believe this was flagged incorrectly, please let a maintainer know. |
| // error, so the model retries with smaller arguments instead of improvising | ||
| // chunking schemes. A nudge only: the model remains free to retry the same call. | ||
| export function repairToolCallMessage(error: unknown): string { | ||
| const message = error instanceof Error ? error.message : String(error) |
There was a problem hiding this comment.
WARNING: Inline error coercion loses the message for non-Error error values
String(error) on an unknown degrades to "[object Object]" for any error value that is not an Error instance but still carries a message (a plain { message } record is a common shape for provider/SDK-thrown values). The previous code read failed.error.message directly, so that text reached the model; now it would reach the model as [object Object].
The repo already has a helper for this: errorMessage() from @/util/error (used at src/session/llm/ai-sdk.ts:257 and src/session/llm/native-runtime.ts:188). It handles Error, records with message, records with data.message, and falls back to unknown error. It also avoids the String(unknown) coercion that trips the repo's typescript/no-base-to-string oxlint rule — other call sites carry an explicit // oxlint-disable-next-line no-base-to-string for the same pattern (packages/core/src/util/retry.ts:22).
Same issue one line down: error.cause instanceof Error ignores a cause that is a plain { message } object, so a wrapped parse error whose cause is not an Error subclass is never detected. Use errorMessage(error.cause) there too, guarding for an undefined cause.
| const message = error instanceof Error ? error.message : String(error) | ||
| const cause = error instanceof Error && error.cause instanceof Error ? error.cause.message : "" | ||
| const combined = `${message} ${cause}` | ||
| if (!/json parse|unterminated|unexpected end of json|unexpected end of input|syntaxerror/i.test(combined)) { |
There was a problem hiding this comment.
WARNING: JSON-parse detection is substring based and misses most V8 parser messages
The five patterns cover Bun's JSON Parse error: ... prefix and two V8 messages only. The repo ships a Node build (packages/opencode/script/build-node.ts), and V8 emits a wider set of texts that all fall through to the bare parser error unchanged:
Unexpected token 'x', "abc" is not valid JSONExpected ',' or '}' after property value in JSON at position 42Expected property name or '}' in JSON at position 1Unexpected non-whitespace character after JSON at position 8Bad control character in string literal in JSON at position 2
The detection also ignores the error type. error.cause is right there and the new test even builds a SyntaxError cause, yet the check is textual only, so a SyntaxError whose message does not contain one of the five phrases (for example new SyntaxError('Unexpected token')) is not detected. Keying on error instanceof SyntaxError || cause instanceof SyntaxError — which needs the cause object, not just its message — covers the whole class and also removes the false-positive risk of matching an unrelated error that merely mentions syntaxerror.
Broadening the pattern at least catches the V8 texts above:
| if (!/json parse|unterminated|unexpected end of json|unexpected end of input|syntaxerror/i.test(combined)) { | |
| if (!/json parse|not valid json|unterminated|unexpected end of json|unexpected end of input|unexpected token|expected property|syntaxerror/i.test(combined)) { |
| return message | ||
| } | ||
| return [ | ||
| `The tool-call arguments were not valid JSON (${message}).`, |
There was a problem hiding this comment.
WARNING: The cause text is detected but never shown to the model
In the cause path — the case this PR's own second test exercises — the parse detail lives on error.cause, but the message interpolates only message, the outer error. When the SDK wraps the parse failure, the model receives:
The tool-call arguments were not valid JSON (Invalid input for tool write).
That is self-contradicting: it asserts a JSON failure while quoting a tool-input validation error, and the actual parse diagnostic (Unexpected end of JSON input) is discarded — the one piece of information that distinguishes truncation from malformed JSON. Prefer the cause when there is one:
| `The tool-call arguments were not valid JSON (${message}).`, | |
| `The tool-call arguments were not valid JSON (${cause || message}).`, |
| } | ||
| return [ | ||
| `The tool-call arguments were not valid JSON (${message}).`, | ||
| "This usually means the response was cut off at the output-token limit while the arguments were being generated.", |
There was a problem hiding this comment.
SUGGESTION: The truncation cause is asserted for every matched error, including genuinely malformed JSON
The function's own comment acknowledges the failure may be (or genuinely malformed JSON), but the text handed to the model names only the output-token limit. A model that emitted invalid JSON for another reason (a stray comma, a hallucinated structure) is told the cause was truncation and will start splitting a call that did not need splitting; conversely, a truncated payload whose parser text did not match the pattern gets no hint at all. Naming both possibilities keeps the nudge useful in either direction, for example: This usually means the response was cut off at the output-token limit while the arguments were being generated, or that the arguments were malformed JSON.
| const error = new Error("Invalid input for tool write") | ||
| ;(error as { cause?: unknown }).cause = new SyntaxError("Unexpected end of JSON input") | ||
| const out = repairToolCallMessage(error) | ||
| expect(out).toContain("not valid JSON") |
There was a problem hiding this comment.
SUGGESTION: This test cannot catch the dropped cause text, and the other branches are untested
The assertion only checks not valid JSON, so it still passes while the cause message is never surfaced (see the comment on repairToolCallMessage). Once the cause text is included, assert it directly, e.g. expect(out).toContain('Unexpected end of JSON input').
Worth adding as cases:
- a V8-style message the current pattern misses, e.g.
new Error('Unexpected token 'x', "abc" is not valid JSON'), to document whether the detection is meant to handle it; - a non-
Errorinput such as{ message: 'boom' }, to lock in theString(error)fallback; - an
Errorwith an empty message, which currently produces an empty string.
expect(out).toContain('smaller') on line 9 is also loose enough to pass on almost any rewording — assert the guidance phrases the behaviour actually depends on.
Code Review SummaryStatus: 5 Issues Found | Recommendation: Address before merge Overview
Issue Details (click to expand)WARNING
SUGGESTION
Files Reviewed (2 files)
Fix these issues in Kilo Cloud Reviewed by free · Input: 41.8K · Output: 32.8K · Cached: 1.2M |
Fixes #414.
The generic
experimental_repairToolCallfallback inpackages/opencode/src/session/llm.tsrelays only the bare parser error to the model via theinvalidtool (JSON Parse error: Unterminated string). When the failure looks like a JSON syntax/parse failure (message or cause), the error text now:Nudge only: schema-validation and unknown-tool failures keep their current wording, and the model remains free to retry the identical call. No effort-prompt changes.
Tests:
test/session/llm-repair.test.tscovers the truncation phrasing, the error-cause path, and the verbatim passthrough for non-parse failures.