Class: ClaudeCodeSDK::Transport::SubprocessCLI

Inherits:
Base
  • Object
show all
Defined in:
lib/claude_code_sdk/transport/subprocess_cli.rb

Constant Summary collapse

BUFFER_SIZE =

1MB

1024 * 1024
STDERR_TIMEOUT =

seconds

5

Instance Method Summary collapse

Constructor Details

#initialize(prompt:, options: nil) ⇒ SubprocessCLI

Returns a new instance of SubprocessCLI.



13
14
15
16
17
18
19
20
21
# File 'lib/claude_code_sdk/transport/subprocess_cli.rb', line 13

def initialize(prompt:, options: nil)
  @prompt = prompt
  @options = options || Options.new
  @process = nil
  @stdin = nil
  @stdout = nil
  @stderr = nil
  @wait_thread = nil
end

Instance Method Details

#connectObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/claude_code_sdk/transport/subprocess_cli.rb', line 23

def connect
  return if @connected

  cli_path = find_cli_path
  raise CLINotFoundError.new(cli_path: cli_path) unless cli_path

  args = @options.to_cli_args
  args.push("--print", @prompt) # Add prompt after --print

  command = [cli_path] + args
  puts "[DEBUG] Command: #{command.join(" ")}" if ENV["DEBUG"]

  env = { "ANTHROPIC_API_KEY" => ENV.fetch("ANTHROPIC_API_KEY", nil) }
  env["CLAUDE_CODE_ENTRYPOINT"] = "sdk-ruby"

  popen_options = { chdir: @options.cwd }.compact
  @stdin, @stdout, @stderr, @wait_thread = Open3.popen3(env, *command, **popen_options)
  @stdin.close # Close stdin since we pass all data via args
  @connected = true
rescue Errno::ENOENT
  raise CLINotFoundError.new("Claude Code CLI not found", cli_path: cli_path)
end

#connected?Boolean

Returns:

  • (Boolean)


66
67
68
69
70
# File 'lib/claude_code_sdk/transport/subprocess_cli.rb', line 66

def connected?
  @connected && @wait_thread&.alive?
rescue Errno::ESRCH
  false
end

#disconnectObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/claude_code_sdk/transport/subprocess_cli.rb', line 46

def disconnect
  return unless @connected

  @stdin&.close unless @stdin&.closed?
  @stdout&.close unless @stdout&.closed?
  @stderr&.close unless @stderr&.closed?

  if @wait_thread&.alive?
    begin
      Process.kill("TERM", @wait_thread.pid)
      @wait_thread.join(5)
    rescue Errno::ESRCH
      # Process already finished
    end
  end

  @process = nil
  @connected = false
end

#receive_messagesObject



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
# File 'lib/claude_code_sdk/transport/subprocess_cli.rb', line 72

def receive_messages
  connect unless @connected

  json_buffer = ""

  # Read streaming JSON from stdout
  puts "[DEBUG] Reading streaming JSON..." if ENV["DEBUG"]

  begin
    @stdout.each_line do |line|
      line_str = line.strip
      next if line_str.empty?

      puts "[DEBUG] Read line: #{line_str}" if ENV["DEBUG"]

      json_buffer += line_str

      begin
        data = JSON.parse(json_buffer, symbolize_names: true)
        json_buffer = ""
        puts "[DEBUG] Parsed message: #{data[:type]}" if ENV["DEBUG"]
        yield data
      rescue JSON::ParserError
        # Continue accumulating until we have valid JSON
        next
      end
    end
  rescue IOError => e
    puts "[DEBUG] IOError reading stdout: #{e.message}" if ENV["DEBUG"]
  end

  # Handle process completion
  puts "[DEBUG] Waiting for process to complete..." if ENV["DEBUG"]
  @wait_thread.join
  exit_status = @wait_thread.value.exitstatus

  puts "[DEBUG] Process exited with status: #{exit_status}" if ENV["DEBUG"]

  unless exit_status.zero?
    stderr_output = @stderr.read
    puts "[DEBUG] stderr: #{stderr_output}" if ENV["DEBUG"]
    raise ProcessError.new(
      "Claude Code process failed",
      exit_code: exit_status,
      stderr: stderr_output
    )
  end
ensure
  disconnect
end