Class: EditTool

Inherits:
LlmGateway::Tool show all
Defined in:
lib/llm_gateway/agents/tools/edit_tool.rb

Defined Under Namespace

Classes: EditError

Instance Method Summary collapse

Methods inherited from LlmGateway::Tool

cache, definition, description, #initialize, input_schema, name, tool_name

Constructor Details

This class inherits a constructor from LlmGateway::Tool

Instance Method Details

#execute(input) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/llm_gateway/agents/tools/edit_tool.rb', line 33

def execute(input)
  path = input[:path]
  edits = prepare_edits(input[:edits])

  return "Edit tool input is invalid. edits must contain at least one replacement." if !edits.is_a?(Array) || edits.empty?

  absolute_path = ToolUtils.resolve_to_cwd(path)

  ToolUtils.with_file_mutation_lock(absolute_path) do
    begin
      File.open(absolute_path, File::RDWR) { }
    rescue SystemCallError => e
      return "Could not edit file: #{path}. Error code: #{e.class.name.split("::").last}."
    end

    raw_content = File.binread(absolute_path)

    bom = raw_content.start_with?("\xEF\xBB\xBF".b) ? "\xEF\xBB\xBF".b : "".b
    content_without_bom = bom.empty? ? raw_content : raw_content.byteslice(3..)
    content_utf8 = content_without_bom.force_encoding("UTF-8")

    original_ending = detect_line_ending(content_utf8)
    normalized_content = normalize_to_lf(content_utf8)
    base_content, new_content = apply_edits_to_normalized_content(normalized_content, edits, path)

    restored = restore_line_endings(new_content, original_ending)
    final_bytes = bom + restored.encode("UTF-8").b

    File.binwrite(absolute_path, final_bytes)
    "Successfully replaced #{edits.length} block(s) in #{path}."
  end
rescue EditError => e
  e.message
rescue StandardError => e
  "Error editing file: #{e.message}"
end