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, #tool_result

Constructor Details

This class inherits a constructor from LlmGateway::Tool

Instance Method Details

#execute(input, tool_use_id:) ⇒ Object



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
69
# File 'lib/llm_gateway/agents/tools/edit_tool.rb', line 34

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

  return tool_result("Edit tool input is invalid. edits must contain at least one replacement.", tool_use_id: tool_use_id) 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 tool_result("Could not edit file: #{path}. Error code: #{e.class.name.split("::").last}.", tool_use_id: tool_use_id)
    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)
    tool_result("Successfully replaced #{edits.length} block(s) in #{path}.", tool_use_id: tool_use_id)
  end
rescue EditError => e
  tool_result(e.message, tool_use_id: tool_use_id)
rescue StandardError => e
  tool_result("Error editing file: #{e.message}", tool_use_id: tool_use_id)
end