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
|