1package tools
2
3import (
4 "context"
5 _ "embed"
6 "fmt"
7 "log/slog"
8 "os"
9 "path/filepath"
10 "strings"
11 "time"
12
13 "charm.land/fantasy"
14 "github.com/charmbracelet/crush/internal/csync"
15 "github.com/charmbracelet/crush/internal/diff"
16 "github.com/charmbracelet/crush/internal/filepathext"
17 "github.com/charmbracelet/crush/internal/fsext"
18 "github.com/charmbracelet/crush/internal/history"
19
20 "github.com/charmbracelet/crush/internal/lsp"
21 "github.com/charmbracelet/crush/internal/permission"
22)
23
24//go:embed write.md
25var writeDescription []byte
26
27type WriteParams struct {
28 FilePath string `json:"file_path" description:"The path to the file to write"`
29 Content string `json:"content" description:"The content to write to the file"`
30}
31
32type WritePermissionsParams struct {
33 FilePath string `json:"file_path"`
34 OldContent string `json:"old_content,omitempty"`
35 NewContent string `json:"new_content,omitempty"`
36}
37
38type writeTool struct {
39 lspClients *csync.Map[string, *lsp.Client]
40 permissions permission.Service
41 files history.Service
42 workingDir string
43}
44
45type WriteResponseMetadata struct {
46 Diff string `json:"diff"`
47 Additions int `json:"additions"`
48 Removals int `json:"removals"`
49}
50
51const WriteToolName = "write"
52
53func NewWriteTool(lspClients *csync.Map[string, *lsp.Client], permissions permission.Service, files history.Service, workingDir string) fantasy.AgentTool {
54 return fantasy.NewAgentTool(
55 WriteToolName,
56 string(writeDescription),
57 func(ctx context.Context, params WriteParams, call fantasy.ToolCall) (fantasy.ToolResponse, error) {
58 if params.FilePath == "" {
59 return fantasy.NewTextErrorResponse("file_path is required"), nil
60 }
61
62 if params.Content == "" {
63 return fantasy.NewTextErrorResponse("content is required"), nil
64 }
65
66 filePath := filepathext.SmartJoin(workingDir, params.FilePath)
67
68 fileInfo, err := os.Stat(filePath)
69 if err == nil {
70 if fileInfo.IsDir() {
71 return fantasy.NewTextErrorResponse(fmt.Sprintf("Path is a directory, not a file: %s", filePath)), nil
72 }
73
74 modTime := fileInfo.ModTime()
75 lastRead := getLastReadTime(filePath)
76 if modTime.After(lastRead) {
77 return fantasy.NewTextErrorResponse(fmt.Sprintf("File %s has been modified since it was last read.\nLast modification: %s\nLast read: %s\n\nPlease read the file again before modifying it.",
78 filePath, modTime.Format(time.RFC3339), lastRead.Format(time.RFC3339))), nil
79 }
80
81 oldContent, readErr := os.ReadFile(filePath)
82 if readErr == nil && string(oldContent) == params.Content {
83 return fantasy.NewTextErrorResponse(fmt.Sprintf("File %s already contains the exact content. No changes made.", filePath)), nil
84 }
85 } else if !os.IsNotExist(err) {
86 return fantasy.ToolResponse{}, fmt.Errorf("error checking file: %w", err)
87 }
88
89 dir := filepath.Dir(filePath)
90 if err = os.MkdirAll(dir, 0o755); err != nil {
91 return fantasy.ToolResponse{}, fmt.Errorf("error creating directory: %w", err)
92 }
93
94 oldContent := ""
95 if fileInfo != nil && !fileInfo.IsDir() {
96 oldBytes, readErr := os.ReadFile(filePath)
97 if readErr == nil {
98 oldContent = string(oldBytes)
99 }
100 }
101
102 sessionID := GetSessionFromContext(ctx)
103 if sessionID == "" {
104 return fantasy.ToolResponse{}, fmt.Errorf("session_id is required")
105 }
106
107 diff, additions, removals := diff.GenerateDiff(
108 oldContent,
109 params.Content,
110 strings.TrimPrefix(filePath, workingDir),
111 )
112
113 granted, err := CheckHookPermission(ctx, permissions, permission.CreatePermissionRequest{
114 SessionID: sessionID,
115 Path: fsext.PathOrPrefix(filePath, workingDir),
116 ToolCallID: call.ID,
117 ToolName: WriteToolName,
118 Action: "write",
119 Description: fmt.Sprintf("Create file %s", filePath),
120 Params: WritePermissionsParams{
121 FilePath: filePath,
122 OldContent: oldContent,
123 NewContent: params.Content,
124 },
125 })
126 if err != nil {
127 return fantasy.ToolResponse{}, err
128 }
129 if !granted {
130 return fantasy.ToolResponse{}, permission.ErrorPermissionDenied
131 }
132
133 err = os.WriteFile(filePath, []byte(params.Content), 0o644)
134 if err != nil {
135 return fantasy.ToolResponse{}, fmt.Errorf("error writing file: %w", err)
136 }
137
138 // Check if file exists in history
139 file, err := files.GetByPathAndSession(ctx, filePath, sessionID)
140 if err != nil {
141 _, err = files.Create(ctx, sessionID, filePath, oldContent)
142 if err != nil {
143 // Log error but don't fail the operation
144 return fantasy.ToolResponse{}, fmt.Errorf("error creating file history: %w", err)
145 }
146 }
147 if file.Content != oldContent {
148 // User Manually changed the content store an intermediate version
149 _, err = files.CreateVersion(ctx, sessionID, filePath, oldContent)
150 if err != nil {
151 slog.Debug("Error creating file history version", "error", err)
152 }
153 }
154 // Store the new version
155 _, err = files.CreateVersion(ctx, sessionID, filePath, params.Content)
156 if err != nil {
157 slog.Debug("Error creating file history version", "error", err)
158 }
159
160 recordFileWrite(filePath)
161 recordFileRead(filePath)
162
163 notifyLSPs(ctx, lspClients, params.FilePath)
164
165 result := fmt.Sprintf("File successfully written: %s", filePath)
166 result = fmt.Sprintf("<result>\n%s\n</result>", result)
167 result += getDiagnostics(filePath, lspClients)
168 return fantasy.WithResponseMetadata(fantasy.NewTextResponse(result),
169 WriteResponseMetadata{
170 Diff: diff,
171 Additions: additions,
172 Removals: removals,
173 },
174 ), nil
175 })
176}