Class: SwarmSDK::V3::Tools::Write

Inherits:
Base
  • Object
show all
Defined in:
lib/swarm_sdk/v3/tools/write.rb

Overview

Write tool for writing content to files

Creates new files or overwrites existing files. Enforces read-before-write for existing files via the Read tool’s tracking.

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#name

Constructor Details

#initialize(agent_name:, directory:, read_tracker:) ⇒ Write

Returns a new instance of Write.

Parameters:

  • agent_name (Symbol, String)

    Agent identifier

  • directory (String)

    Agent’s working directory

  • read_tracker (ReadTracker)

    Shared read tracker for enforcement



41
42
43
44
45
46
# File 'lib/swarm_sdk/v3/tools/write.rb', line 41

def initialize(agent_name:, directory:, read_tracker:)
  super()
  @agent_name = agent_name.to_sym
  @directory = File.expand_path(directory)
  @read_tracker = read_tracker
end

Class Method Details

.creation_requirementsArray<Symbol>

Returns Constructor requirements.

Returns:

  • (Array<Symbol>)

    Constructor requirements



13
14
15
# File 'lib/swarm_sdk/v3/tools/write.rb', line 13

def creation_requirements
  [:agent_name, :directory, :read_tracker]
end

Instance Method Details

#execute(file_path:, content:) ⇒ String

Execute file write

Parameters:

  • file_path (String)

    Path to the file

  • content (String)

    Content to write

Returns:

  • (String)

    Success or error message



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/swarm_sdk/v3/tools/write.rb', line 53

def execute(file_path:, content:)
  return validation_error("file_path is required") if file_path.nil? || file_path.to_s.strip.empty?
  return validation_error("content is required") if content.nil?

  resolved_path = resolve_path(file_path)
  file_exists = File.exist?(resolved_path)

  if file_exists && !@read_tracker.file_read?(@agent_name, resolved_path)
    return validation_error(
      "Cannot write to existing file without reading it first. " \
        "Use the Read tool on '#{file_path}' before overwriting.",
    )
  end

  parent_dir = File.dirname(resolved_path)
  FileUtils.mkdir_p(parent_dir) unless File.directory?(parent_dir)

  File.write(resolved_path, content, encoding: "UTF-8")

  byte_size = content.bytesize
  line_count = content.lines.count
  action = file_exists ? "overwrote" : "created"

  "Successfully #{action} file: #{file_path} (#{line_count} lines, #{byte_size} bytes)"
rescue Errno::EACCES
  error("Permission denied: Cannot write to file '#{file_path}'")
rescue Errno::EISDIR
  error("Path is a directory, not a file.")
rescue StandardError => e
  error("Unexpected error writing file: #{e.class.name} - #{e.message}")
end