Class: ClaudeAgentSDK::SubprocessCLITransport

Inherits:
Transport
  • Object
show all
Defined in:
lib/claude_agent_sdk/subprocess_cli_transport.rb

Overview

Subprocess transport using Claude Code CLI

Constant Summary collapse

DEFAULT_MAX_BUFFER_SIZE =

1MB buffer limit

1024 * 1024
MINIMUM_CLAUDE_CODE_VERSION =
'2.0.0'

Instance Method Summary collapse

Constructor Details

#initialize(options_or_prompt = nil, options = nil) ⇒ SubprocessCLITransport

Returns a new instance of SubprocessCLITransport.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 16

def initialize(options_or_prompt = nil, options = nil)
  # Support both new single-arg form and legacy two-arg form
  @options = options.nil? ? options_or_prompt : options
  @cli_path = @options.cli_path || find_cli
  @cwd = @options.cwd
  @process = nil
  @stdin = nil
  @stdout = nil
  @stderr = nil
  @ready = false
  @exit_error = nil
  @max_buffer_size = @options.max_buffer_size || DEFAULT_MAX_BUFFER_SIZE
  @stderr_task = nil
  @recent_stderr = []
  @recent_stderr_mutex = Mutex.new
end

Instance Method Details

#build_commandObject



68
69
70
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
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 68

def build_command
  cmd = [@cli_path, '--output-format', 'stream-json', '--verbose']

  # System prompt handling
  # When nil, pass empty string to ensure predictable behavior without default Claude Code system prompt
  if @options.system_prompt.nil?
    cmd.concat(['--system-prompt', ''])
  elsif @options.system_prompt.is_a?(String)
    cmd.concat(['--system-prompt', @options.system_prompt])
  elsif @options.system_prompt.is_a?(SystemPromptFile)
    cmd.concat(['--system-prompt-file', @options.system_prompt.path])
  elsif @options.system_prompt.is_a?(SystemPromptPreset)
    # Preset activates the default Claude Code system prompt by not passing --system-prompt ""
    # Only --append-system-prompt is passed if append text is provided
    cmd.concat(['--append-system-prompt', @options.system_prompt.append]) if @options.system_prompt.append
  elsif @options.system_prompt.is_a?(Hash)
    prompt_type = @options.system_prompt[:type] || @options.system_prompt['type']
    if prompt_type == 'file'
      prompt_path = @options.system_prompt[:path] || @options.system_prompt['path']
      cmd.concat(['--system-prompt-file', prompt_path]) if prompt_path
    elsif prompt_type == 'preset'
      append = @options.system_prompt[:append] || @options.system_prompt['append']
      # Preset activates the default Claude Code system prompt by not passing --system-prompt ""
      cmd.concat(['--append-system-prompt', append]) if append
    end
  end

  cmd.concat(['--allowedTools', @options.allowed_tools.join(',')]) unless @options.allowed_tools.empty?
  cmd.concat(['--max-turns', @options.max_turns.to_s]) if @options.max_turns
  cmd.concat(['--disallowedTools', @options.disallowed_tools.join(',')]) unless @options.disallowed_tools.empty?
  cmd.concat(['--model', @options.model]) if @options.model
  cmd.concat(['--fallback-model', @options.fallback_model]) if @options.fallback_model
  cmd.concat(['--permission-prompt-tool', @options.permission_prompt_tool_name]) if @options.permission_prompt_tool_name
  cmd.concat(['--permission-mode', @options.permission_mode]) if @options.permission_mode
  cmd << '--continue' if @options.continue_conversation
  cmd.concat(['--resume', @options.resume]) if @options.resume
  cmd.concat(['--session-id', @options.session_id]) if @options.session_id

  # Settings handling with sandbox merge
  build_settings_args(cmd)

  # Budget limit option
  cmd.concat(['--max-budget-usd', @options.max_budget_usd.to_s]) if @options.max_budget_usd

  # Task budget (API-side token budget)
  if @options.task_budget
    total = if @options.task_budget.is_a?(TaskBudget)
              @options.task_budget.total
            else
              @options.task_budget[:total] || @options.task_budget['total']
            end
    cmd.concat(['--task-budget', total.to_s]) if total
  end

  # Thinking configuration (takes precedence over deprecated max_thinking_tokens)
  build_thinking_args(cmd)

  # Effort level — see ClaudeAgentSDK::EFFORT_LEVELS. The set of supported
  # levels is model-dependent; the CLI falls back to the highest supported
  # level at or below the one requested (e.g. `xhigh` → `high` on Opus 4.6).
  cmd.concat(['--effort', @options.effort.to_s]) if @options.effort

  # Betas option for enabling experimental features
  if @options.betas && !@options.betas.empty?
    cmd.concat(['--betas', @options.betas.join(',')])
  end

  # Tools option for base tools selection
  build_tools_args(cmd)

  # Append allowed tools option
  if @options.append_allowed_tools && !@options.append_allowed_tools.empty?
    cmd.concat(['--append-allowed-tools', @options.append_allowed_tools.join(',')])
  end

  # JSON schema for structured output
  build_output_format_args(cmd)

  # Add directories
  @options.add_dirs.each do |dir|
    cmd.concat(['--add-dir', dir.to_s])
  end

  # MCP servers
  build_mcp_servers_args(cmd)

  cmd << '--include-partial-messages' if @options.include_partial_messages
  cmd << '--fork-session' if @options.fork_session
  cmd << '--bare' if @options.bare

  # Note: agents are now sent via the initialize control request (not CLI args)
  # to avoid OS ARG_MAX limits with large agent configurations.

  # Plugins
  build_plugins_args(cmd)

  # Setting sources
  sources_value = @options.setting_sources ? @options.setting_sources.join(',') : ''
  cmd.concat(['--setting-sources', sources_value])

  # Extra args
  @options.extra_args.each do |flag, value|
    if value.nil?
      cmd << "--#{flag}"
    else
      cmd.concat(["--#{flag}", value.to_s])
    end
  end

  # Always use streaming mode for bidirectional control protocol.
  # Prompts and agents are sent via stdin (initialize + user messages),
  # which avoids OS ARG_MAX limits for large prompts and agent configurations.
  cmd.concat(['--input-format', 'stream-json'])

  cmd
end

#check_claude_versionObject



473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 473

def check_claude_version
  begin
    stdout, stderr, = Open3.capture3(@cli_path.to_s, '-v')
    output = (stdout.to_s + stderr.to_s).strip
    if match = output.match(/([0-9]+\.[0-9]+\.[0-9]+)/)
      version = match[1]
      version_parts = version.split('.').map(&:to_i)
      min_parts = MINIMUM_CLAUDE_CODE_VERSION.split('.').map(&:to_i)

      if version_parts < min_parts
        warning = "Warning: Claude Code version #{version} is unsupported in the Agent SDK. " \
                  "Minimum required version is #{MINIMUM_CLAUDE_CODE_VERSION}. " \
                  "Some features may not work correctly."
        warn warning
      end
    end
  rescue StandardError
    # Ignore version check errors
  end
end

#closeObject



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 296

def close
  @ready = false
  return unless @process

  cleanup_errors = []

  # Kill stderr thread
  if @stderr_task&.alive?
    begin
      @stderr_task.kill
      @stderr_task.join(1)
    rescue StandardError => e
      cleanup_errors << "stderr thread: #{e.message}"
    end
  end

  # Close streams
  begin
    @stdin&.close
  rescue IOError
    # Already closed, ignore
  rescue StandardError => e
    cleanup_errors << "stdin: #{e.message}"
  end

  begin
    @stdout&.close
  rescue IOError
    # Already closed, ignore
  rescue StandardError => e
    cleanup_errors << "stdout: #{e.message}"
  end

  begin
    @stderr&.close
  rescue IOError
    # Already closed, ignore
  rescue StandardError => e
    cleanup_errors << "stderr: #{e.message}"
  end

  # Wait for graceful shutdown after stdin EOF, then terminate if needed.
  # The subprocess needs time to flush its session file after receiving
  # EOF on stdin. Without this grace period, SIGTERM can interrupt the
  # write and cause the last assistant message to be lost.
  begin
    if @process.alive?
      # Give the process up to 5 seconds to exit on its own
      Timeout.timeout(5) { @process.value }
    end
  rescue Timeout::Error
    # Graceful shutdown timed out — send SIGTERM
    begin
      Process.kill('TERM', @process.pid)
      Timeout.timeout(2) { @process.value }
    rescue Timeout::Error
      # SIGTERM didn't work — force kill
      begin
        Process.kill('KILL', @process.pid)
        @process.value
      rescue StandardError => e
        cleanup_errors << "force kill: #{e.message}"
      end
    rescue Errno::ESRCH
      # Process already dead
    end
  rescue Errno::ESRCH
    # Process already dead, ignore
  rescue StandardError => e
    cleanup_errors << "process termination: #{e.message}"
  end

  # Log any cleanup errors (non-fatal)
  if cleanup_errors.any?
    warn "Claude SDK: Cleanup warnings: #{cleanup_errors.join(', ')}"
  end

  @process = nil
  @stdout = nil
  @stdin = nil
  @stderr = nil
  @stderr_task = nil
  @exit_error = nil
end

#connectObject



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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 185

def connect
  return if @process

  check_claude_version

  cmd = build_command

  # Build environment
  # Convert symbol keys to strings for spawn compatibility
  custom_env = @options.env.transform_keys { |k| k.to_s }
  # Explicitly unset CLAUDECODE to prevent "nested session" detection when the SDK
  # launches Claude Code from within an existing Claude Code terminal.
  # NOTE: Must set to nil (not just omit the key) — Ruby's spawn only overlays
  # the env hash on top of the parent environment; a nil value actively unsets.
  process_env = ENV.to_h.merge('CLAUDECODE' => nil, 'CLAUDE_AGENT_SDK_VERSION' => VERSION).merge(custom_env)
  process_env['CLAUDE_CODE_ENTRYPOINT'] ||= 'sdk-rb'
  process_env['CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING'] = 'true' if @options.enable_file_checkpointing
  process_env['PWD'] = @cwd.to_s if @cwd

  # Determine stderr handling
  should_pipe_stderr = @options.stderr || @options.debug_stderr || @options.extra_args.key?('debug-to-stderr')

  begin
    # Start process using Open3
    opts = { chdir: @cwd&.to_s }.compact

    @stdin, @stdout, @stderr, @process = Open3.popen3(process_env, *cmd, opts)

    # Always drain stderr to prevent pipe buffer deadlock.
    # Without this, --verbose output fills the OS pipe buffer (~64KB),
    # the subprocess blocks on write, and all pipes stall → EPIPE.
    if @stderr
      if should_pipe_stderr # rubocop:disable Style/ConditionalAssignment
        @stderr_task = Thread.new do
          handle_stderr
        rescue StandardError
          # Ignore errors during stderr reading
        end
      else
        # Silently drain stderr so the subprocess never blocks,
        # but still accumulate recent lines for error reporting.
        @stderr_task = Thread.new do
          drain_stderr_with_accumulation
        rescue StandardError
          # Ignore — process may have already exited
        end
      end
    end

    # Always keep stdin open — streaming mode uses it for the control protocol
    @ready = true
  rescue Errno::ENOENT => e
    # Check if error is from cwd or CLI
    if @cwd && !File.directory?(@cwd.to_s)
      error = CLIConnectionError.new("Working directory does not exist: #{@cwd}")
      @exit_error = error
      raise error
    end
    error = CLINotFoundError.new("Claude Code not found at: #{@cli_path}")
    @exit_error = error
    raise error
  rescue StandardError => e
    error = CLIConnectionError.new("Failed to start Claude Code: #{e}")
    @exit_error = error
    raise error
  end
end

#drain_stderr_with_accumulationObject



282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 282

def drain_stderr_with_accumulation
  return unless @stderr

  @stderr.each_line do |line|
    line_str = line.chomp
    next if line_str.empty?

    @recent_stderr_mutex.synchronize do
      @recent_stderr << line_str
      @recent_stderr.shift if @recent_stderr.size > 20
    end
  end
end

#end_inputObject



397
398
399
400
401
402
403
404
405
406
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 397

def end_input
  return unless @stdin

  begin
    @stdin.close
  rescue StandardError
    # Ignore
  end
  @stdin = nil
end

#find_cliObject

Raises:



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
62
63
64
65
66
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 33

def find_cli
  # Try which command first (using Open3 for thread safety)
  cli = nil
  begin
    stdout, _status = Open3.capture2('which', 'claude')
    cli = stdout.strip
  rescue StandardError
    # which command failed, try common locations
  end
  return cli if cli && !cli.empty? && File.executable?(cli)

  # Try common locations
  locations = [
    File.join(Dir.home, '.claude/local/claude'),  # Claude Code default install location
    File.join(Dir.home, '.npm-global/bin/claude'),
    '/usr/local/bin/claude',
    File.join(Dir.home, '.local/bin/claude'),
    File.join(Dir.home, 'node_modules/.bin/claude'),
    File.join(Dir.home, '.yarn/bin/claude')
  ]

  locations.each do |path|
    return path if File.exist?(path) && File.file?(path)
  end

  raise CLINotFoundError.new(
    "Claude Code not found. Install with:\n" \
    "  npm install -g @anthropic-ai/claude-code\n" \
    "\nIf already installed locally, try:\n" \
    '  export PATH="$HOME/node_modules/.bin:$PATH"' \
    "\n\nOr provide the path via ClaudeAgentOptions:\n" \
    "  ClaudeAgentOptions.new(cli_path: '/path/to/claude')"
  )
end

#handle_stderrObject



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 253

def handle_stderr
  return unless @stderr

  @stderr.each_line do |line|
    line_str = line.chomp
    next if line_str.empty?

    # Accumulate recent lines for inclusion in ProcessError
    @recent_stderr_mutex.synchronize do
      @recent_stderr << line_str
      @recent_stderr.shift if @recent_stderr.size > 20
    end

    # Call stderr callback if provided
    @options.stderr&.call(line_str)

    # Write to debug_stderr file/IO if provided
    if @options.debug_stderr
      if @options.debug_stderr.respond_to?(:puts)
        @options.debug_stderr.puts(line_str)
      elsif @options.debug_stderr.is_a?(String)
        File.open(@options.debug_stderr, 'a') { |f| f.puts(line_str) }
      end
    end
  end
rescue StandardError
  # Ignore errors during stderr reading
end

#read_messages(&block) ⇒ Object

Raises:



408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 408

def read_messages(&block)
  return enum_for(:read_messages) unless block_given?

  raise CLIConnectionError, 'Not connected' unless @process && @stdout

  json_buffer = ''

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

      json_lines = line_str.split("\n")

      json_lines.each do |json_line|
        json_line = json_line.strip
        next if json_line.empty?

        json_buffer += json_line

        if json_buffer.bytesize > @max_buffer_size
          buffer_length = json_buffer.bytesize
          json_buffer = ''
          raise CLIJSONDecodeError.new(
            "JSON message exceeded maximum buffer size",
            StandardError.new("Buffer size #{buffer_length} exceeds limit #{@max_buffer_size}")
          )
        end

        begin
          data = JSON.parse(json_buffer, symbolize_names: true)
          json_buffer = ''
          yield data
        rescue JSON::ParserError
          # Continue accumulating
          next
        end
      end
    end
  rescue IOError
    # Stream closed
  rescue StopIteration
    # Client disconnected
  end

  # Check process completion
  status = @process.value
  returncode = status.exitstatus

  if returncode && returncode != 0
    # Wait briefly for stderr thread to finish draining
    @stderr_task&.join(1)

    stderr_text = @recent_stderr_mutex.synchronize { @recent_stderr.last(10).join("\n") }
    stderr_text = 'No stderr output captured' if stderr_text.empty?

    @exit_error = ProcessError.new(
      "Command failed with exit code #{returncode}",
      exit_code: returncode,
      stderr: stderr_text
    )
    raise @exit_error
  end
end

#ready?Boolean

Returns:

  • (Boolean)


494
495
496
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 494

def ready?
  @ready
end

#write(data) ⇒ Object

Raises:



381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 381

def write(data)
  raise CLIConnectionError, 'ProcessTransport is not ready for writing' unless @ready && @stdin
  raise CLIConnectionError, "Cannot write to terminated process" if @process && !@process.alive?

  raise CLIConnectionError, "Cannot write to process that exited with error: #{@exit_error}" if @exit_error

  begin
    @stdin.write(data)
    @stdin.flush
  rescue StandardError => e
    @ready = false
    @exit_error = CLIConnectionError.new("Failed to write to process stdin: #{e}")
    raise @exit_error
  end
end