1package tools
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "os"
8 "path/filepath"
9 "strings"
10 "time"
11
12 "github.com/charmbracelet/crush/internal/config"
13 "github.com/charmbracelet/crush/internal/diff"
14 "github.com/charmbracelet/crush/internal/history"
15 "github.com/charmbracelet/crush/internal/logging"
16 "github.com/charmbracelet/crush/internal/lsp"
17 "github.com/charmbracelet/crush/internal/permission"
18)
19
20type WriteParams struct {
21 FilePath string `json:"file_path"`
22 Content string `json:"content"`
23}
24
25type WritePermissionsParams struct {
26 FilePath string `json:"file_path"`
27 OldContent string `json:"old_content,omitempty"`
28 NewContent string `json:"new_content,omitempty"`
29}
30
31type writeTool struct {
32 lspClients map[string]*lsp.Client
33 permissions permission.Service
34 files history.Service
35}
36
37type WriteResponseMetadata struct {
38 Diff string `json:"diff"`
39 Additions int `json:"additions"`
40 Removals int `json:"removals"`
41}
42
43const (
44 WriteToolName = "write"
45 writeDescription = `File writing tool that creates or updates files in the filesystem, allowing you to save or modify text content.
46
47WHEN TO USE THIS TOOL:
48- Use when you need to create a new file
49- Helpful for updating existing files with modified content
50- Perfect for saving generated code, configurations, or text data
51
52HOW TO USE:
53- Provide the path to the file you want to write
54- Include the content to be written to the file
55- The tool will create any necessary parent directories
56
57FEATURES:
58- Can create new files or overwrite existing ones
59- Creates parent directories automatically if they don't exist
60- Checks if the file has been modified since last read for safety
61- Avoids unnecessary writes when content hasn't changed
62
63LIMITATIONS:
64- You should read a file before writing to it to avoid conflicts
65- Cannot append to files (rewrites the entire file)
66
67
68TIPS:
69- Use the View tool first to examine existing files before modifying them
70- Use the LS tool to verify the correct location when creating new files
71- Combine with Glob and Grep tools to find and modify multiple files
72- Always include descriptive comments when making changes to existing code`
73)
74
75func NewWriteTool(lspClients map[string]*lsp.Client, permissions permission.Service, files history.Service) BaseTool {
76 return &writeTool{
77 lspClients: lspClients,
78 permissions: permissions,
79 files: files,
80 }
81}
82
83func (w *writeTool) Info() ToolInfo {
84 return ToolInfo{
85 Name: WriteToolName,
86 Description: writeDescription,
87 Parameters: map[string]any{
88 "file_path": map[string]any{
89 "type": "string",
90 "description": "The path to the file to write",
91 },
92 "content": map[string]any{
93 "type": "string",
94 "description": "The content to write to the file",
95 },
96 },
97 Required: []string{"file_path", "content"},
98 }
99}
100
101func (w *writeTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
102 var params WriteParams
103 if err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {
104 return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
105 }
106
107 if params.FilePath == "" {
108 return NewTextErrorResponse("file_path is required"), nil
109 }
110
111 if params.Content == "" {
112 return NewTextErrorResponse("content is required"), nil
113 }
114
115 filePath := params.FilePath
116 if !filepath.IsAbs(filePath) {
117 filePath = filepath.Join(config.WorkingDirectory(), filePath)
118 }
119
120 fileInfo, err := os.Stat(filePath)
121 if err == nil {
122 if fileInfo.IsDir() {
123 return NewTextErrorResponse(fmt.Sprintf("Path is a directory, not a file: %s", filePath)), nil
124 }
125
126 modTime := fileInfo.ModTime()
127 lastRead := getLastReadTime(filePath)
128 if modTime.After(lastRead) {
129 return 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.",
130 filePath, modTime.Format(time.RFC3339), lastRead.Format(time.RFC3339))), nil
131 }
132
133 oldContent, readErr := os.ReadFile(filePath)
134 if readErr == nil && string(oldContent) == params.Content {
135 return NewTextErrorResponse(fmt.Sprintf("File %s already contains the exact content. No changes made.", filePath)), nil
136 }
137 } else if !os.IsNotExist(err) {
138 return ToolResponse{}, fmt.Errorf("error checking file: %w", err)
139 }
140
141 dir := filepath.Dir(filePath)
142 if err = os.MkdirAll(dir, 0o755); err != nil {
143 return ToolResponse{}, fmt.Errorf("error creating directory: %w", err)
144 }
145
146 oldContent := ""
147 if fileInfo != nil && !fileInfo.IsDir() {
148 oldBytes, readErr := os.ReadFile(filePath)
149 if readErr == nil {
150 oldContent = string(oldBytes)
151 }
152 }
153
154 sessionID, messageID := GetContextValues(ctx)
155 if sessionID == "" || messageID == "" {
156 return ToolResponse{}, fmt.Errorf("session_id and message_id are required")
157 }
158
159 diff, additions, removals := diff.GenerateDiff(
160 oldContent,
161 params.Content,
162 filePath,
163 )
164
165 rootDir := config.WorkingDirectory()
166 permissionPath := filepath.Dir(filePath)
167 if strings.HasPrefix(filePath, rootDir) {
168 permissionPath = rootDir
169 }
170 p := w.permissions.Request(
171 permission.CreatePermissionRequest{
172 SessionID: sessionID,
173 Path: permissionPath,
174 ToolName: WriteToolName,
175 Action: "write",
176 Description: fmt.Sprintf("Create file %s", filePath),
177 Params: WritePermissionsParams{
178 FilePath: filePath,
179 OldContent: oldContent,
180 NewContent: params.Content,
181 },
182 },
183 )
184 if !p {
185 return ToolResponse{}, permission.ErrorPermissionDenied
186 }
187
188 err = os.WriteFile(filePath, []byte(params.Content), 0o644)
189 if err != nil {
190 return ToolResponse{}, fmt.Errorf("error writing file: %w", err)
191 }
192
193 // Check if file exists in history
194 file, err := w.files.GetByPathAndSession(ctx, filePath, sessionID)
195 if err != nil {
196 _, err = w.files.Create(ctx, sessionID, filePath, oldContent)
197 if err != nil {
198 // Log error but don't fail the operation
199 return ToolResponse{}, fmt.Errorf("error creating file history: %w", err)
200 }
201 }
202 if file.Content != oldContent {
203 // User Manually changed the content store an intermediate version
204 _, err = w.files.CreateVersion(ctx, sessionID, filePath, oldContent)
205 if err != nil {
206 logging.Debug("Error creating file history version", "error", err)
207 }
208 }
209 // Store the new version
210 _, err = w.files.CreateVersion(ctx, sessionID, filePath, params.Content)
211 if err != nil {
212 logging.Debug("Error creating file history version", "error", err)
213 }
214
215 recordFileWrite(filePath)
216 recordFileRead(filePath)
217 waitForLspDiagnostics(ctx, filePath, w.lspClients)
218
219 result := fmt.Sprintf("File successfully written: %s", filePath)
220 result = fmt.Sprintf("<result>\n%s\n</result>", result)
221 result += getDiagnostics(filePath, w.lspClients)
222 return WithResponseMetadata(NewTextResponse(result),
223 WriteResponseMetadata{
224 Diff: diff,
225 Additions: additions,
226 Removals: removals,
227 },
228 ), nil
229}