Module: Crimson::Tools::WriteFile

Defined in:
lib/crimson/tools/write_file.rb

Overview

Write content to a file, creating parent directories and showing a diff.

Constant Summary collapse

TOOL_NAME =
"write_file"
PARAMS =

Tool parameter definitions.

{
  path: { type: "string", description: "The path to the file to write" },
  content: { type: "string", description: "The content to write" }
}.freeze
MUTATION_QUEUE =
FileMutationQueue.new

Class Method Summary collapse

Class Method Details

.anthropic_definitionHash

Returns Anthropic-compatible tool definition.

Returns:

  • (Hash)

    Anthropic-compatible tool definition



25
26
27
# File 'lib/crimson/tools/write_file.rb', line 25

def self.anthropic_definition
  Schema.build_anthropic(name: TOOL_NAME, description: "Write content to a file. Creates the file and parent directories if needed.", parameters: PARAMS, required: %w[path content])
end

.call(path:, content:) ⇒ String

Execute the tool.

Parameters:

  • path (String)

    file path

  • content (String)

    content to write

Returns:

  • (String)

    result message with diff or error



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/crimson/tools/write_file.rb', line 33

def self.call(path:, content:)
  return "Error: No path provided" if path.nil? || path.strip.empty?

  expanded = File.expand_path(path)

  MUTATION_QUEUE.with_file(expanded) do
    dir = File.dirname(expanded)
    old_content = File.exist?(expanded) ? File.read(expanded) : nil

    FileUtils.mkdir_p(dir) unless Dir.exist?(dir)
    File.write(expanded, content)

    diff = DiffUtil.format_diff(old_content || "", content, path)
    "Successfully wrote to #{path}\n#{diff}"
  end
rescue => e
  "Error writing file: #{e.message}"
end

.definitionHash

Returns OpenAI-compatible tool definition.

Returns:

  • (Hash)

    OpenAI-compatible tool definition



20
21
22
# File 'lib/crimson/tools/write_file.rb', line 20

def self.definition
  Schema.build(name: TOOL_NAME, description: "Write content to a file. Creates the file and parent directories if needed.", parameters: PARAMS, required: %w[path content])
end