Skip to content

feat: nudge the model when a tool call arrives unparseable - #437

Merged
agenteinstinct1-max merged 1 commit into
dev-vibecodedfrom
fix/tool-call-parse-nudge
Oct 21, 2026
Merged

agenteinstinct1-max merged 1 commit into
dev-vibecodedfrom
fix/tool-call-parse-nudge

Conversation

@agenteinstinct1-max

Copy link
Copy Markdown
Collaborator

Fixes #414.

The generic experimental_repairToolCall fallback in packages/opencode/src/session/llm.ts relays only the bare parser error to the model via the invalid tool (JSON Parse error: Unterminated string). When the failure looks like a JSON syntax/parse failure (message or cause), the error text now:

  • names the likely cause: the response was cut off at the output-token limit while the arguments were being generated
  • gives concrete recovery guidance: retry with smaller arguments; write large files across several smaller tool calls or append in chunks; keep each call within the output budget

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.ts covers the truncation phrasing, the error-cause path, and the verbatim passthrough for non-parse failures.

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.
@github-actions

Copy link
Copy Markdown

This PR doesn't fully meet our contributing guidelines and PR template.

What needs to be fixed:

  • PR description is missing required template sections. Please use the PR template.

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 JSON
  • Expected ',' or '}' after property value in JSON at position 42
  • Expected property name or '}' in JSON at position 1
  • Unexpected non-whitespace character after JSON at position 8
  • Bad 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:

Suggested change
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}).`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
`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.",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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-Error input such as { message: 'boom' }, to lock in the String(error) fallback;
  • an Error with 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.

@kilo-code-bot

kilo-code-bot Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Code Review Summary

Status: 5 Issues Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 3
SUGGESTION 2
Issue Details (click to expand)

WARNING

File Line Issue
packages/opencode/src/session/llm.ts 45 Inline String(error) coercion drops the message for non-Error error values (regression vs. the previous failed.error.message); the repo already has errorMessage() in @/util/error, and the same String(unknown) coercion trips the typescript/no-base-to-string oxlint rule. The cause instanceof Error check on the next line also ignores plain { message } causes.
packages/opencode/src/session/llm.ts 48 JSON-parse detection is substring based and misses most V8/Node parser messages (Unexpected token 'x', ... is not valid JSON, Expected ',' or '}' after property value in JSON at position N, …), and never checks the error type, so a SyntaxError cause with a different message is undetected. The repo ships a Node build, so these messages are live.
packages/opencode/src/session/llm.ts 52 The parse detail on error.cause is used for detection but never shown to the model; the message interpolates the outer error instead, producing a self-contradicting text such as The tool-call arguments were not valid JSON (Invalid input for tool write).

SUGGESTION

File Line Issue
packages/opencode/src/session/llm.ts 53 The output-token-limit cause is asserted for every matched error, including genuinely malformed JSON, so the model can be steered into unnecessary chunking; naming both possibilities keeps the nudge useful in either direction.
packages/opencode/test/session/llm-repair.test.ts 16 The cause-path assertion only checks not valid JSON, so it cannot catch the dropped cause text; the non-Error input path, an empty-message Error, and V8-style messages are untested, and toContain('smaller') on line 9 is too loose to be meaningful.
Files Reviewed (2 files)
  • packages/opencode/src/session/llm.ts - 4 issues
  • packages/opencode/test/session/llm-repair.test.ts - 1 issue

Fix these issues in Kilo Cloud


Reviewed by free · Input: 41.8K · Output: 32.8K · Cached: 1.2M

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant