Files
coder/coderd/x/chatd/toolinput.go
T
Michael Suchacz a41e5ae6eb refactor: rename prepareGeneration to buildTurnEnvironment (#30866)
Renames the turn preparation step after what it returns: the environment
for one turn. Only names change, plus one small change to how callers
release the environment.

- `generation_preparer.go` becomes `turn_environment.go`, and its test
file becomes `turn_environment_internal_test.go`. GitHub shows both as
renames. A comment in `compactionTriggers.test.ts` that names the test
file follows the rename.
- `prepareGeneration` becomes `buildTurnEnvironment`, and its result
type `generationPrepared` becomes `turnEnvironment`. Four
`TestPrepareGeneration*` tests become `TestBuildTurnEnvironment*`.
- The `Cleanup` field becomes the unexported `cleanup`, and callers use
`Close()`. `Close()` does nothing on a zero value.

The type stays in `generation.go` for now. #30870 moves it next to
`buildTurnEnvironment`.

Validation: build and vet pass, the renamed tests and the `toolinput`
tests pass, and the pre-commit hook passed.

## Stack

This stack splits #28757, as requested in review. It moves the code that
prepares a chat turn into one file, `turn_environment.go`, and moves the
tool policy tests from full turns to a table test. chatd behaves as on
`main`, except for the debug log in #30865.

1. #30864 Remove the no-op `allowedBehaviorToolNames` filter
2. #30865 Log workspace agent lookup errors in turn preparation
3. #30866 Rename `prepareGeneration` to `buildTurnEnvironment`
4. #30867 Cover the turn tool policy at `buildTurnEnvironment`
5. #30868 Remove seven end-to-end tool policy tests
6. #30869 Name the `*Server` receiver `p` in `turn_environment.go`
7. #30870 Move the turn preparation helpers into `turn_environment.go`

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-16 21:20:00 +00:00

101 lines
3.9 KiB
Go

package chatd
import (
"encoding/json"
"charm.land/fantasy"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/coderd/x/chatd/chathooks"
"github.com/coder/coder/v2/coderd/x/chatd/toolschema"
)
// partitionAmbiguousToolCalls separates the calls a consumer must not be asked
// to decide from the rest, returning synthetic error results for them. Callers
// reject before pre_tool_use so a hook consumer is never asked to authorize
// bytes whose meaning depends on which reader resolves them, and so input that
// cannot be carried in a hook payload fails as a retryable tool error instead
// of a dispatch failure. allowedIndexes maps allowed calls back to the input
// order without relying on duplicate-prone IDs.
func partitionAmbiguousToolCalls(
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, ambiguousToolResult(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 ambiguous 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 {
// Execution resolves a deprecated alias to its canonical tool, so
// skipping that here would let the old name bypass validation.
if canonical, aliased := subagentToolNameAliases[toolName]; aliased {
toolName = canonical
}
if !prepared.BuiltinToolNames[toolName] {
return nil
}
for _, tool := range prepared.Tools {
info := tool.Info()
if info.Name != toolName {
continue
}
return toolschema.ValidateUnambiguous(info.Parameters, input)
}
return nil
}
// malformedToolResult reports input the tool decoder would reject anyway. It
// is produced here because a hook payload carries the input as JSON, so
// invalid bytes would otherwise surface as a dispatch failure and end the
// turn instead of letting the model correct the call.
func malformedToolResult(toolCall fantasy.ToolCallContent) fantasy.ToolResultContent {
return fantasy.ToolResultContent{
ToolCallID: toolCall.ToolCallID,
ToolName: toolCall.ToolName,
Result: fantasy.ToolResultOutputContentError{
Error: xerrors.New("This tool call was not executed because its input is not valid JSON. Retry with a well-formed JSON object matching the tool schema."),
},
}
}
func ambiguousToolResult(toolCall fantasy.ToolCallContent, err error) fantasy.ToolResultContent {
message := "This tool call was not executed because its input is ambiguous: " + err.Error() +
". Retry with the exact property names from the tool schema, each key used once."
return fantasy.ToolResultContent{
ToolCallID: toolCall.ToolCallID,
ToolName: toolCall.ToolName,
Result: fantasy.ToolResultOutputContentError{
Error: xerrors.New(message),
},
}
}