Class: SwarmSDK::Tools::MultiEdit
- Includes:
- PathResolver
- Defined in:
- lib/swarm_sdk/tools/multi_edit.rb
Overview
MultiEdit tool for performing multiple exact string replacements in a file
Applies multiple edit operations sequentially to a single file. Each edit sees the result of all previous edits, allowing for coordinated multi-step transformations. Enforces read-before-edit rule.
Instance Attribute Summary
Attributes included from PathResolver
Class Method Summary collapse
Instance Method Summary collapse
- #execute(file_path:, edits_json:) ⇒ Object
-
#initialize(agent_name:, directory:) ⇒ MultiEdit
constructor
Initialize the MultiEdit tool for a specific agent.
-
#name ⇒ Object
Override name to return simple "MultiEdit" instead of full class path.
Methods inherited from Base
removable, removable?, #removable?
Constructor Details
#initialize(agent_name:, directory:) ⇒ MultiEdit
Initialize the MultiEdit tool for a specific agent
61 62 63 64 |
# File 'lib/swarm_sdk/tools/multi_edit.rb', line 61 def initialize(agent_name:, directory:) super() initialize_agent_context(agent_name: agent_name, directory: directory) end |
Class Method Details
.creation_requirements ⇒ Object
16 17 18 |
# File 'lib/swarm_sdk/tools/multi_edit.rb', line 16 def creation_requirements [:agent_name, :directory] end |
Instance Method Details
#execute(file_path:, edits_json:) ⇒ Object
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 |
# File 'lib/swarm_sdk/tools/multi_edit.rb', line 71 def execute(file_path:, edits_json:) # Validate inputs return validation_error("file_path is required") if file_path.nil? || file_path.to_s.strip.empty? # CRITICAL: Resolve path against agent directory resolved_path = resolve_path(file_path) # Parse JSON edits = begin JSON.parse(edits_json) rescue JSON::ParserError nil end return validation_error("Invalid JSON format. Please provide a valid JSON array of edit operations.") if edits.nil? return validation_error("edits must be an array") unless edits.is_a?(Array) return validation_error("edits array cannot be empty") if edits.empty? # File must exist (use resolved path) unless File.exist?(resolved_path) return validation_error("File does not exist: #{file_path}") end # Enforce read-before-edit (use resolved path) unless Stores::ReadTracker.file_read?(@agent_name, resolved_path) return validation_error( "Cannot edit file without reading it first. " \ "You must use the Read tool on '#{file_path}' before editing it. " \ "This ensures you have the current file contents to match against.", ) end # Read current content (use resolved path) content = File.read(resolved_path, encoding: "UTF-8") # Validate edit operations validated_edits = [] edits.each_with_index do |edit, index| unless edit.is_a?(Hash) return validation_error("Edit at index #{index} must be a hash/object with old_string and new_string") end # Convert string keys to symbols for consistency edit = edit.transform_keys(&:to_sym) unless edit[:old_string] return validation_error("Edit at index #{index} missing required field 'old_string'") end unless edit[:new_string] return validation_error("Edit at index #{index} missing required field 'new_string'") end # old_string and new_string must be different if edit[:old_string] == edit[:new_string] return validation_error("Edit at index #{index}: old_string and new_string must be different") end validated_edits << { old_string: edit[:old_string].to_s, new_string: edit[:new_string].to_s, replace_all: edit[:replace_all] == true, index: index, } end # Apply edits sequentially results = [] current_content = content validated_edits.each do |edit| # Check if old_string exists in current content unless current_content.include?(edit[:old_string]) return error_with_results( " Edit \#{edit[:index]}: old_string not found in file.\n Make sure it matches exactly, including all whitespace and indentation.\n Do not include line number prefixes from Read tool output.\n Note: This edit follows \#{edit[:index]} previous edit(s) which may have changed the file content.\n ERROR\n results,\n )\n end\n\n # Count occurrences\n occurrences = current_content.scan(edit[:old_string]).count\n\n # If not replace_all and multiple occurrences, error\n if !edit[:replace_all] && occurrences > 1\n return error_with_results(\n <<~ERROR.chomp,\n Edit \#{edit[:index]}: Found \#{occurrences} occurrences of old_string.\n Either provide more surrounding context to make the match unique, or set replace_all: true to replace all occurrences.\n ERROR\n results,\n )\n end\n\n # Perform replacement\n new_content = if edit[:replace_all]\n current_content.gsub(edit[:old_string], edit[:new_string])\n else\n current_content.sub(edit[:old_string], edit[:new_string])\n end\n\n # Record result\n replaced_count = edit[:replace_all] ? occurrences : 1\n results << {\n index: edit[:index],\n status: \"success\",\n occurrences: replaced_count,\n message: \"Replaced \#{replaced_count} occurrence(s)\",\n }\n\n # Update content for next edit\n current_content = new_content\n end\n\n # Write back to file (use resolved path)\n File.write(resolved_path, current_content, encoding: \"UTF-8\")\n\n # Build success message\n total_replacements = results.sum { |r| r[:occurrences] }\n message = \"Successfully applied \#{validated_edits.size} edit(s) to \#{file_path}\\n\"\n message += \"Total replacements: \#{total_replacements}\\n\\n\"\n message += \"Details:\\n\"\n results.each do |result|\n message += \" Edit \#{result[:index]}: \#{result[:message]}\\n\"\n end\n\n message\nrescue Encoding::InvalidByteSequenceError, Encoding::UndefinedConversionError\n error(\"File contains invalid UTF-8. Cannot edit binary or improperly encoded files.\")\nrescue Errno::EACCES\n error(\"Permission denied: Cannot read or write file '\#{file_path}'\")\nrescue StandardError => e\n error(\"Unexpected error editing file: \#{e.class.name} - \#{e.message}\")\nend\n".chomp, |
#name ⇒ Object
Override name to return simple "MultiEdit" instead of full class path
67 68 69 |
# File 'lib/swarm_sdk/tools/multi_edit.rb', line 67 def name "MultiEdit" end |