Class: Nanobot::Agent::Tools::EditFile
- Inherits:
-
RubyLLM::Tool
- Object
- RubyLLM::Tool
- Nanobot::Agent::Tools::EditFile
- Includes:
- WorkspaceSandbox
- Defined in:
- lib/nanobot/agent/tools/filesystem.rb
Overview
Tool for editing files by replacing text
Constant Summary
Constants included from WorkspaceSandbox
WorkspaceSandbox::PROTECTED_FILENAMES
Instance Method Summary collapse
-
#execute(path:, old_text:, new_text:) ⇒ String
Replace a unique occurrence of old_text with new_text in a file.
-
#initialize(allowed_dir: nil) ⇒ EditFile
constructor
A new instance of EditFile.
Constructor Details
#initialize(allowed_dir: nil) ⇒ EditFile
Returns a new instance of EditFile.
153 154 155 156 |
# File 'lib/nanobot/agent/tools/filesystem.rb', line 153 def initialize(allowed_dir: nil) super() @allowed_dir = allowed_dir ? Pathname.new(allowed_dir). : nil end |
Instance Method Details
#execute(path:, old_text:, new_text:) ⇒ String
Replace a unique occurrence of old_text with new_text in a file.
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 |
# File 'lib/nanobot/agent/tools/filesystem.rb', line 163 def execute(path:, old_text:, new_text:) file_path = Pathname.new(path). # Security check if @allowed_dir && !within_allowed_dir?(file_path) return "Error: Access denied. Path is outside allowed directory: #{@allowed_dir}" end if protected_path?(file_path) return "Error: Access denied. Bootstrap file #{file_path.basename} is read-only." end return "Error: File not found: #{path}" unless file_path.exist? return "Error: Path is not a file: #{path}" unless file_path.file? begin content = file_path.read return "Error: Text not found in file: #{old_text[0..50]}..." unless content.include?(old_text) # Check if old_text appears multiple times occurrences = content.scan(old_text).length return "Error: Text appears #{occurrences} times in file. Please be more specific." if occurrences > 1 new_content = content.sub(old_text, new_text) file_path.write(new_content) "Successfully edited #{path}" rescue StandardError => e "Error editing file: #{e.}" end end |