When a malformed tool call reaches tool-call admission in `chatd`,
`chatd` does not execute it, persistence discards invalid arguments on
save, and `chatprompt.normalizeToolCallInput` replays calls without a
valid JSON object as `{}`. Previously `malformedToolResult` only told
the model that the input was "not valid JSON", so models saw `{}` next
to that error and started sending `{}` on subsequent calls. (Calls cut
off by the output token limit already receive their own error result in
the chat loop and are unchanged.)
Update `malformedToolResult` to inspect the raw bytes in memory before
persistence discards them. The error result now distinguishes empty or
whitespace-only input, truncated input (reporting how many bytes arrived
before the value ended), and syntax errors (reporting the received byte
length, the `encoding/json` error, and the byte offset). When the input
consists of multiple complete JSON values back to back, it also reports
how many concatenated values arrived. It notes that if the call's input
appears as `{}` in conversation history, that is a placeholder rather
than what was sent.
Tested with `gofmt -l coderd/x/chatd/` and `go test ./coderd/x/chatd/
-run
'TestMalformedToolResultDescribesInput|TestMalformedToolInputReplayDescribesReceivedInput'
-count=1`. Unit cases cover concatenated objects, whitespace-separated
objects, concatenated non-objects, trailing garbage, truncated object,
truncated literal, truncated string escape, empty input, whitespace-only
input, and non-JSON text; an end-to-end replay test asserts that the
second model request carries `{}` alongside the diagnostic error result
(byte length, concatenated value count, parse error, byte offset, and
placeholder note).
Refs CODAGT-1658.
<details>
<summary>Implementation plan and decision log</summary>
This change is separate from the `coder/fantasy` index-less tool-call
merge fix and is still needed alongside it, because truncated or
malformed input from any provider takes the same admission rejection
path.
- Keep the `{}` replay placeholder in
`chatprompt.normalizeToolCallInput`, which every provider accepts.
- Rewrite `malformedToolResult` so it describes the bytes received
before persistence discards invalid arguments:
- empty or whitespace-only input;
- truncated input and how many bytes arrived;
- the byte length, `encoding/json` parse error, and byte offset for
other syntax errors;
- the count of concatenated JSON values when the input contains multiple
complete values back to back;
- a conditional note that `{}` in conversation history is a placeholder,
not what the model sent.
- This needs no schema change, only affects newly written results, and
no existing test asserts the old text.
- Rejected alternatives:
- **Replay the raw text:** Google's OpenAI-compatible endpoint returned
HTTP 400 for a merged call in history, and
`chatprompt.normalizeToolCallInput` falls back to `{}` for all
providers.
- **Wrap the raw text in an object:** it invents an argument shape the
model would copy, and it resends up to about 10 KB per failure on every
request.
- **Drop the call and its result from history:** the model loses its
only feedback.
- Tests:
- A unit table in `toolinput_internal_test.go`.
- An end-to-end chattest run where one call's input is
`{"path":"a"}{"path":"b"}`, asserting the second request carries `{}`
and the new explanation.
- The UI's "Failed to spawn Sub-agent" row with no prompt follows from
the missing arguments (`Tool.tsx`, `subagentDescriptor.ts`) and needs no
change.
</details>
> 🤖 Created with the help of Coder Agents.
240 lines
8.4 KiB
Go
240 lines
8.4 KiB
Go
package chatd
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"strings"
|
|
|
|
"charm.land/fantasy"
|
|
"github.com/google/jsonschema-go/jsonschema"
|
|
"golang.org/x/xerrors"
|
|
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chathooks"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/toolschema"
|
|
)
|
|
|
|
// partitionInvalidToolCalls rejects malformed JSON and invalid builtin inputs
|
|
// before pre_tool_use or execution. Synthetic tool errors let the model correct
|
|
// its arguments without failing the turn. allowedIndexes maps allowed calls
|
|
// back to the input order without relying on duplicate-prone IDs.
|
|
func partitionInvalidToolCalls(
|
|
prepared turnEnvironment,
|
|
toolCalls []fantasy.ToolCallContent,
|
|
) (allowed []fantasy.ToolCallContent, allowedIndexes []int, rejected []fantasy.ToolResultContent) {
|
|
for i, toolCall := range toolCalls {
|
|
if !json.Valid([]byte(toolCall.Input)) {
|
|
rejected = append(rejected, malformedToolResult(toolCall))
|
|
continue
|
|
}
|
|
if err := validateBuiltinToolInput(prepared, toolCall.ToolName, []byte(toolCall.Input)); err != nil {
|
|
rejected = append(rejected, invalidToolInputResult(toolCall, err))
|
|
continue
|
|
}
|
|
allowed = append(allowed, toolCall)
|
|
allowedIndexes = append(allowedIndexes, i)
|
|
}
|
|
return allowed, allowedIndexes, rejected
|
|
}
|
|
|
|
// validateOverriddenToolInputs rechecks the inputs a pre_tool_use consumer
|
|
// replaced. The model cannot fix an invalid override, so the turn fails
|
|
// closed instead of executing it.
|
|
func validateOverriddenToolInputs(prepared turnEnvironment, preflight chathooks.PreToolUseExecutionResult) error {
|
|
for _, toolCall := range preflight.Allowed {
|
|
if _, overridden := preflight.Overrides[toolCall.ToolCallID]; !overridden {
|
|
continue
|
|
}
|
|
if err := validateBuiltinToolInput(prepared, toolCall.ToolName, []byte(toolCall.Input)); err != nil {
|
|
return xerrors.Errorf("hook input override for tool %s: %w", toolCall.ToolName, err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// validateBuiltinToolInput only guards builtin tools, whose input coderd
|
|
// decodes itself. Dynamic calls are executed by the client and MCP calls by
|
|
// their own server, and a dynamic tool cannot shadow a builtin name.
|
|
func validateBuiltinToolInput(prepared turnEnvironment, toolName string, input []byte) error {
|
|
if !prepared.BuiltinToolNames[toolName] {
|
|
return nil
|
|
}
|
|
for _, tool := range prepared.Tools {
|
|
info := tool.Info()
|
|
if info.Name != toolName {
|
|
continue
|
|
}
|
|
if err := toolschema.ValidateUnambiguous(info.Parameters, input); err != nil {
|
|
return err
|
|
}
|
|
schemaJSON, err := json.Marshal(info.Parameters)
|
|
if err != nil {
|
|
return xerrors.Errorf("marshal tool schema: %w", err)
|
|
}
|
|
schema := jsonschema.Schema{Type: "object", Required: info.Required}
|
|
if err := json.Unmarshal(schemaJSON, &schema.Properties); err != nil {
|
|
return xerrors.Errorf("decode tool schema: %w", err)
|
|
}
|
|
normalizeToolMapSchemas(&schema)
|
|
compiled, err := schema.Resolve(nil)
|
|
if err != nil {
|
|
return xerrors.Errorf("compile tool schema: %w", err)
|
|
}
|
|
var value any
|
|
if err := json.Unmarshal(input, &value); err != nil {
|
|
return xerrors.Errorf("decode tool input: %w", err)
|
|
}
|
|
// jsonschema-go wraps each recursive error with an absolute schema path.
|
|
// Keep the innermost wrapper so the location and cause are reported once,
|
|
// without repeating every ancestor path.
|
|
err = compiled.Validate(value)
|
|
for {
|
|
cause := errors.Unwrap(err)
|
|
if cause == nil || errors.Unwrap(cause) == nil {
|
|
return err
|
|
}
|
|
err = cause
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// normalizeToolMapSchemas translates Fantasy's map[string]T wildcard property
|
|
// into JSON Schema's additionalProperties, leaving the tool metadata intact.
|
|
func normalizeToolMapSchemas(schema *jsonschema.Schema) {
|
|
if schema == nil {
|
|
return
|
|
}
|
|
for _, property := range schema.Properties {
|
|
normalizeToolMapSchemas(property)
|
|
}
|
|
normalizeToolMapSchemas(schema.Items)
|
|
normalizeToolMapSchemas(schema.AdditionalProperties)
|
|
for _, branches := range [][]*jsonschema.Schema{schema.AnyOf, schema.OneOf, schema.AllOf} {
|
|
for _, branch := range branches {
|
|
normalizeToolMapSchemas(branch)
|
|
}
|
|
}
|
|
if value, wildcard := schema.Properties["*"]; wildcard && len(schema.Properties) == 1 && schema.AdditionalProperties == nil {
|
|
schema.AdditionalProperties = value
|
|
schema.Properties = nil
|
|
}
|
|
}
|
|
|
|
// malformedToolResult reports invalid JSON input so hook dispatch does not
|
|
// fail the turn and the model gets a description of the received bytes before
|
|
// persistence discards invalid arguments and replays them as {}.
|
|
func malformedToolResult(toolCall fantasy.ToolCallContent) fantasy.ToolResultContent {
|
|
return fantasy.ToolResultContent{
|
|
ToolCallID: toolCall.ToolCallID,
|
|
ToolName: toolCall.ToolName,
|
|
Result: fantasy.ToolResultOutputContentError{
|
|
Error: xerrors.New(inspectMalformedToolInput(toolCall.Input).String()),
|
|
},
|
|
}
|
|
}
|
|
|
|
// malformedToolInput summarizes rejected tool-call bytes before persistence
|
|
// discards invalid arguments.
|
|
type malformedToolInput struct {
|
|
Bytes int
|
|
// NoInput is true when the input is empty or contains only JSON whitespace.
|
|
NoInput bool
|
|
// Truncated is true when the input ends before its first JSON value is
|
|
// complete. encoding/json's scanner error is omitted in this case because
|
|
// it can report a synthetic space byte as the invalid character.
|
|
Truncated bool
|
|
// SyntaxError and Offset come from encoding/json; Offset is the number of
|
|
// bytes read before the parse error.
|
|
SyntaxError string
|
|
Offset int64
|
|
// ConcatenatedValues is the count of complete JSON values when the input
|
|
// contains two or more values separated only by whitespace, and zero
|
|
// otherwise.
|
|
ConcatenatedValues int
|
|
}
|
|
|
|
// jsonWhitespace lists JSON insignificant whitespace characters (RFC 8259).
|
|
const jsonWhitespace = " \t\r\n"
|
|
|
|
func inspectMalformedToolInput(input string) malformedToolInput {
|
|
inspected := malformedToolInput{Bytes: len(input)}
|
|
if strings.Trim(input, jsonWhitespace) == "" {
|
|
inspected.NoInput = true
|
|
return inspected
|
|
}
|
|
|
|
values, err := decodeJSONValues(input)
|
|
if errors.Is(err, io.ErrUnexpectedEOF) && len(values) == 0 {
|
|
inspected.Truncated = true
|
|
return inspected
|
|
}
|
|
if err == nil && len(values) > 1 {
|
|
inspected.ConcatenatedValues = len(values)
|
|
}
|
|
|
|
var value json.RawMessage
|
|
err = json.Unmarshal([]byte(input), &value)
|
|
if syntaxErr, ok := errors.AsType[*json.SyntaxError](err); ok {
|
|
inspected.SyntaxError = syntaxErr.Error()
|
|
inspected.Offset = syntaxErr.Offset
|
|
} else if err != nil {
|
|
inspected.SyntaxError = err.Error()
|
|
}
|
|
return inspected
|
|
}
|
|
|
|
// decodeJSONValues decodes consecutive complete JSON values from input,
|
|
// returning a nil error only when input ends cleanly after the last value.
|
|
func decodeJSONValues(input string) ([]json.RawMessage, error) {
|
|
decoder := json.NewDecoder(strings.NewReader(input))
|
|
var values []json.RawMessage
|
|
for {
|
|
var value json.RawMessage
|
|
err := decoder.Decode(&value)
|
|
if errors.Is(err, io.EOF) {
|
|
return values, nil
|
|
}
|
|
if err != nil {
|
|
return values, err
|
|
}
|
|
values = append(values, value)
|
|
}
|
|
}
|
|
|
|
func (m malformedToolInput) String() string {
|
|
var b strings.Builder
|
|
switch {
|
|
case m.NoInput:
|
|
_, _ = b.WriteString("This tool call was not executed because it had no input.")
|
|
case m.Truncated:
|
|
_, _ = fmt.Fprintf(&b, "This tool call was not executed because its input ended after %d bytes, before the JSON value was complete.",
|
|
m.Bytes)
|
|
default:
|
|
_, _ = fmt.Fprintf(&b, "This tool call was not executed because the %d bytes received are not valid JSON: %s (byte offset %d).",
|
|
m.Bytes, m.SyntaxError, m.Offset)
|
|
}
|
|
if m.ConcatenatedValues > 0 {
|
|
_, _ = fmt.Fprintf(&b, " The input contained %d concatenated JSON values.", m.ConcatenatedValues)
|
|
}
|
|
// Persistence trims Unicode whitespace before validating, so an input such
|
|
// as a leading NBSP before a valid object replays as that object rather
|
|
// than {}.
|
|
_, _ = b.WriteString(" If this call's input shows as {} in conversation history, that is a placeholder, not what was sent.")
|
|
_, _ = b.WriteString(" Retry with one JSON object matching the tool schema.")
|
|
return b.String()
|
|
}
|
|
|
|
func invalidToolInputResult(toolCall fantasy.ToolCallContent, err error) fantasy.ToolResultContent {
|
|
message := "This tool call was not executed because its input is invalid: " + err.Error() +
|
|
". Retry with a JSON object matching the tool schema, including all required properties and their declared types."
|
|
return fantasy.ToolResultContent{
|
|
ToolCallID: toolCall.ToolCallID,
|
|
ToolName: toolCall.ToolName,
|
|
Result: fantasy.ToolResultOutputContentError{
|
|
Error: xerrors.New(message),
|
|
},
|
|
}
|
|
}
|