Class: Kreator::Tools::Edit

Inherits:
Object
  • Object
show all
Defined in:
lib/kreator/tools/edit.rb

Instance Method Summary collapse

Instance Method Details

#call(args:, context:, signal:) ⇒ Object



31
32
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
# File 'lib/kreator/tools/edit.rb', line 31

def call(args:, context:, signal:)
  path = context.ensure_path_allowed!(context.resolve_path(args.fetch("path")), action: :edit)
  old_string = args.fetch("old_string")
  new_string = args.fetch("new_string")
  replace_all = args.fetch("replace_all", false)
  context.approve!(
    action: :edit,
    target: path,
    details: { "replace_all" => replace_all }
  )
  context.ensure_not_cancelled!(signal)

  FileMutationLocks.with(path) do
    original = File.read(path)
    occurrences = original.scan(old_string).length
    raise ArgumentError, "old_string was not found in #{path}" if occurrences.zero?
    raise ArgumentError, "old_string occurs #{occurrences} times; pass replace_all=true to replace all" if occurrences > 1 && !replace_all

    updated = replace_all ? original.gsub(old_string, new_string) : original.sub(old_string, new_string)
    context.ensure_not_cancelled!(signal)
    File.write(path, updated)
    diff = unified_diff(original, updated, path)

    ToolResult.new(
      tool_call_id: "",
      name: name,
      content: diff,
      metadata: { "path" => path, "replacements" => replace_all ? occurrences : 1 }
    )
  end
end

#descriptionObject



13
14
15
# File 'lib/kreator/tools/edit.rb', line 13

def description
  "Apply an exact text replacement to a file and return a unified diff."
end

#nameObject



9
10
11
# File 'lib/kreator/tools/edit.rb', line 9

def name
  "edit"
end

#schemaObject



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/kreator/tools/edit.rb', line 17

def schema
  {
    "type" => "object",
    "additionalProperties" => false,
    "required" => %w[path old_string new_string],
    "properties" => {
      "path" => { "type" => "string", "minLength" => 1 },
      "old_string" => { "type" => "string", "minLength" => 1 },
      "new_string" => { "type" => "string" },
      "replace_all" => { "type" => "boolean" }
    }
  }
end