Files
coder/coderd/x/chatd/chattool/editfiles.go
T
Mathias Fredriksson f208fc0c83 refactor: rename edit_files wire type to old_text/new_text (#28467)
The schema has advertised old_text/new_text since #25658, but the
shared wire type still encoded search/replace.

Decode accepts the deprecated keys only when both new fields are
empty, through the pre-rename tags, so old coderd and cached MCP
schemas keep working. Marshal emits both key sets so old agents keep
working after a coderd upgrade. Both shims are removed in the first
release after Coder Agents GA (2026-09).

The Go field rename is a deliberate source break: FileEdit carries
no codersdk stability guarantee.

Fixes CODAGT-523
Refs CODAGT-483
2026-08-27 16:06:21 +03:00

151 lines
4.8 KiB
Go

package chattool
import (
"context"
"fmt"
"strings"
"charm.land/fantasy"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/workspacesdk"
)
type EditFilesOptions struct {
GetWorkspaceConn func(context.Context) (workspacesdk.AgentConn, error)
ResolvePlanPath func(context.Context) (chatPath string, home string, err error)
IsPlanTurn bool
}
// EditFilesArgs is the tool input schema, auto-generated by the
// fantasy framework from these struct tags.
type EditFilesArgs struct {
Files []workspacesdk.FileEdits `json:"files" description:"Files to edit. Every entry must include path and at least one edit."`
}
func EditFiles(options EditFilesOptions) fantasy.AgentTool {
return fantasy.NewAgentTool(
"edit_files",
"Perform edits on one or more files by replacing old_text with"+
" new_text. Each entry in files must include the absolute path"+
" of the file to edit and at least one edit. Matching is fuzzy"+
" (tolerates whitespace and indentation differences) and preserves"+
" the file's existing indentation and line endings. Errors if"+
" old_text matches zero locations, or more than one unless"+
" replace_all is set. All edits in a batch are validated before"+
" any file is written.",
func(ctx context.Context, args EditFilesArgs, _ fantasy.ToolCall) (fantasy.ToolResponse, error) {
if len(args.Files) == 0 {
return fantasy.NewTextErrorResponse("files is required"), nil
}
for i := range args.Files {
args.Files[i].Path = strings.TrimSpace(args.Files[i].Path)
if args.Files[i].Path == "" {
return fantasy.NewTextErrorResponse(fmt.Sprintf(
"files[%d].path is required; provide the absolute path of the file to edit; no files in this batch were applied", i,
)), nil
}
if len(args.Files[i].Edits) == 0 {
return fantasy.NewTextErrorResponse(fmt.Sprintf(
"files[%d].edits must contain at least one edit; no files in this batch were applied", i,
)), nil
}
}
var planPath string
if options.IsPlanTurn {
resolvedPlanPath, err := resolvePlanTurnPath(ctx, options.ResolvePlanPath)
if err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
for _, f := range args.Files {
if f.Path != resolvedPlanPath {
return fantasy.NewTextErrorResponse("during plan turns, edit_files is restricted to " + resolvedPlanPath), nil
}
}
planPath = resolvedPlanPath
}
if options.GetWorkspaceConn == nil {
return fantasy.NewTextErrorResponse("workspace connection resolver is not configured"), nil
}
conn, err := options.GetWorkspaceConn(ctx)
if err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
if planPath != "" {
if err := ensurePlanPathResolvesToItself(ctx, conn, planPath); err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
}
return executeEditFilesTool(ctx, conn, args, options.ResolvePlanPath)
},
)
}
func executeEditFilesTool(
ctx context.Context,
conn workspacesdk.AgentConn,
args EditFilesArgs,
resolvePlanPath func(context.Context) (chatPath string, home string, err error),
) (fantasy.ToolResponse, error) {
var (
chatPath string
home string
planPathErr error
planPathLoaded bool
)
for _, file := range args.Files {
hasPlanFileName := looksLikePlanFileName(file.Path)
if hasPlanFileName && !isAbsolutePath(file.Path) {
return fantasy.NewTextErrorResponse(
"plan files must use absolute paths; use the chat-specific absolute plan path; no files in this batch were applied",
), nil
}
if resolvePlanPath == nil || !hasPlanFileName {
continue
}
if !planPathLoaded {
chatPath, home, planPathErr = resolvePlanPath(ctx)
planPathLoaded = true
}
if resp, rejected := rejectSharedPlanPath(file.Path, home, chatPath, planPathErr); rejected {
return fantasy.NewTextErrorResponse(
resp.Content + "; no files in this batch were applied",
), nil
}
}
resp, err := conn.EditFiles(ctx, workspacesdk.FileEditRequest{
Files: args.Files,
IncludeDiff: true,
})
if err != nil {
return fantasy.NewTextErrorResponse(agentAPIErrorMessage(err)), nil
}
return toolResponse(map[string]any{
"ok": true,
"files": resp.Files,
}), nil
}
// agentAPIErrorMessage preserves the agent's actionable message while
// dropping the transport metadata (HTTP method, URL, status code) that
// codersdk.Error.Error() prefixes.
func agentAPIErrorMessage(err error) string {
sdkErr, ok := codersdk.AsError(err)
if !ok || sdkErr.Message == "" {
return err.Error()
}
var sb strings.Builder
_, _ = sb.WriteString(sdkErr.Message)
if sdkErr.Helper != "" {
_, _ = sb.WriteString(": " + sdkErr.Helper)
}
if sdkErr.Detail != "" {
_, _ = sb.WriteString(": " + sdkErr.Detail)
}
for _, v := range sdkErr.Validations {
_, _ = sb.WriteString("\n- " + v.Field + ": " + v.Detail)
}
return sb.String()
}