14 "github.com/charmbracelet/crush/internal/diff"
15 "github.com/charmbracelet/crush/internal/filepathext"
16 "github.com/charmbracelet/crush/internal/filetracker"
17 "github.com/charmbracelet/crush/internal/fsext"
18 "github.com/charmbracelet/crush/internal/history"
20 "github.com/charmbracelet/crush/internal/lsp"
21 "github.com/charmbracelet/crush/internal/permission"
25var writeDescription []byte
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"`
32type WritePermissionsParams struct {
33 FilePath string `json:"file_path"`
34 OldContent string `json:"old_content,omitempty"`
35 NewContent string `json:"new_content,omitempty"`
38type WriteResponseMetadata struct {
39 Diff string `json:"diff"`
40 Additions int `json:"additions"`
41 Removals int `json:"removals"`
44const WriteToolName = "write"
47 lspManager *lsp.Manager,
48 permissions permission.Service,
49 files history.Service,
50 filetracker filetracker.Service,
53 return fantasy.NewAgentTool(
55 FirstLineDescription(writeDescription),
56 func(ctx context.Context, params WriteParams, call fantasy.ToolCall) (fantasy.ToolResponse, error) {
57 if params.FilePath == "" {
58 return fantasy.NewTextErrorResponse("file_path is required"), nil
61 if params.Content == "" {
62 return fantasy.NewTextErrorResponse("content is required"), nil
65 sessionID := GetSessionFromContext(ctx)
67 return fantasy.ToolResponse{}, fmt.Errorf("session_id is required")
70 filePath := filepathext.SmartJoin(workingDir, params.FilePath)
72 fileInfo, err := os.Stat(filePath)
75 return fantasy.NewTextErrorResponse(fmt.Sprintf("Path is a directory, not a file: %s", filePath)), nil
78 modTime := fileInfo.ModTime().Truncate(time.Second)
79 lastRead := filetracker.LastReadTime(ctx, sessionID, filePath)
80 if modTime.After(lastRead) {
81 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.",
82 filePath, modTime.Format(time.RFC3339), lastRead.Format(time.RFC3339))), nil
85 oldContent, readErr := os.ReadFile(filePath)
86 if readErr == nil && string(oldContent) == params.Content {
87 return fantasy.NewTextErrorResponse(fmt.Sprintf("File %s already contains the exact content. No changes made.", filePath)), nil
89 } else if !os.IsNotExist(err) {
90 return fantasy.ToolResponse{}, fmt.Errorf("error checking file: %w", err)
93 dir := filepath.Dir(filePath)
94 if err = os.MkdirAll(dir, 0o755); err != nil {
95 return fantasy.ToolResponse{}, fmt.Errorf("error creating directory: %w", err)
99 if fileInfo != nil && !fileInfo.IsDir() {
100 oldBytes, readErr := os.ReadFile(filePath)
102 oldContent = string(oldBytes)
106 diff, additions, removals := diff.GenerateDiff(
109 strings.TrimPrefix(filePath, workingDir),
112 p, err := permissions.Request(ctx,
113 permission.CreatePermissionRequest{
114 SessionID: sessionID,
115 Path: fsext.PathOrPrefix(filePath, workingDir),
117 ToolName: WriteToolName,
119 Description: fmt.Sprintf("Create file %s", filePath),
120 Params: WritePermissionsParams{
122 OldContent: oldContent,
123 NewContent: params.Content,
128 return fantasy.ToolResponse{}, err
131 return NewPermissionDeniedResponse(), nil
134 err = os.WriteFile(filePath, []byte(params.Content), 0o644)
136 return fantasy.ToolResponse{}, fmt.Errorf("error writing file: %w", err)
139 // Check if file exists in history
140 file, err := files.GetByPathAndSession(ctx, filePath, sessionID)
142 _, err = files.Create(ctx, sessionID, filePath, oldContent)
144 // Log error but don't fail the operation
145 return fantasy.ToolResponse{}, fmt.Errorf("error creating file history: %w", err)
148 if file.Content != oldContent {
149 // User manually changed the content; store an intermediate version
150 _, err = files.CreateVersion(ctx, sessionID, filePath, oldContent)
152 slog.Error("Error creating file history version", "error", err)
155 // Store the new version
156 _, err = files.CreateVersion(ctx, sessionID, filePath, params.Content)
158 slog.Error("Error creating file history version", "error", err)
161 filetracker.RecordRead(ctx, sessionID, filePath)
163 notifyLSPs(ctx, lspManager, params.FilePath)
165 result := fmt.Sprintf("File successfully written: %s", filePath)
166 result = fmt.Sprintf("<result>\n%s\n</result>", result)
167 result += getDiagnostics(filePath, lspManager)
168 return fantasy.WithResponseMetadata(fantasy.NewTextResponse(result),
169 WriteResponseMetadata{
171 Additions: additions,
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list