Class: ClaudeAgentSDK::SubprocessCLITransport
- 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
- #build_command ⇒ Object
- #check_claude_version ⇒ Object
- #close ⇒ Object
- #connect ⇒ Object
- #end_input ⇒ Object
- #find_cli ⇒ Object
- #handle_stderr ⇒ Object
-
#initialize(prompt, options) ⇒ SubprocessCLITransport
constructor
A new instance of SubprocessCLITransport.
- #read_messages(&block) ⇒ Object
- #ready? ⇒ Boolean
- #write(data) ⇒ Object
Constructor Details
#initialize(prompt, options) ⇒ SubprocessCLITransport
Returns a new instance of SubprocessCLITransport.
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 16 def initialize(prompt, ) @prompt = prompt @is_streaming = !prompt.is_a?(String) @options = @cli_path = .cli_path || find_cli @cwd = .cwd @process = nil @stdin = nil @stdout = nil @stderr = nil @ready = false @exit_error = nil @max_buffer_size = .max_buffer_size || DEFAULT_MAX_BUFFER_SIZE @stderr_task = nil end |
Instance Method Details
#build_command ⇒ Object
67 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 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 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 252 253 |
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 67 def build_command cmd = [@cli_path, '--output-format', 'stream-json', '--verbose'] # System prompt handling if @options.system_prompt if @options.system_prompt.is_a?(String) cmd.concat(['--system-prompt', @options.system_prompt]) elsif @options.system_prompt.is_a?(SystemPromptPreset) cmd.concat(['--system-prompt-preset', @options.system_prompt.preset]) if @options.system_prompt.preset 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 == 'preset' preset = @options.system_prompt[:preset] || @options.system_prompt['preset'] append = @options.system_prompt[:append] || @options.system_prompt['append'] cmd.concat(['--system-prompt-preset', preset]) if preset cmd.concat(['--append-system-prompt', append]) if append end 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.]) if @options. cmd.concat(['--permission-mode', @options.]) if @options. cmd << '--continue' if @options.continue_conversation cmd.concat(['--resume', @options.resume]) if @options.resume # Settings handling with sandbox merge # Sandbox settings are merged into the main settings JSON if @options.settings || @options.sandbox settings_hash = {} settings_is_path = false # Parse existing settings if provided if @options.settings if @options.settings.is_a?(String) begin settings_hash = JSON.parse(@options.settings) rescue JSON::ParserError # If not valid JSON, treat as file path and pass as-is settings_is_path = true cmd.concat(['--settings', @options.settings]) if @options.sandbox warn "Warning: Cannot merge sandbox settings when settings is a file path. " \ "Sandbox settings will be ignored. Use a Hash or JSON string for settings " \ "to enable sandbox merging." end end elsif @options.settings.is_a?(Hash) settings_hash = @options.settings.dup end end # Merge sandbox settings if provided (only when settings is not a file path) if !settings_is_path && @options.sandbox sandbox_hash = if @options.sandbox.is_a?(SandboxSettings) @options.sandbox.to_h else @options.sandbox end settings_hash[:sandbox] = sandbox_hash unless sandbox_hash.empty? end # Output merged settings (only when settings is not a file path) if !settings_is_path && !settings_hash.empty? cmd.concat(['--settings', JSON.generate(settings_hash)]) end end # Budget limit option cmd.concat(['--max-budget-usd', @options.max_budget_usd.to_s]) if @options.max_budget_usd # Note: max_thinking_tokens is stored in options but not yet supported by Claude CLI # 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 if @options.tools if @options.tools.is_a?(Array) cmd.concat(['--tools', @options.tools.join(',')]) elsif @options.tools.is_a?(ToolsPreset) cmd.concat(['--tools', JSON.generate(@options.tools.to_h)]) elsif @options.tools.is_a?(Hash) cmd.concat(['--tools', JSON.generate(@options.tools)]) end end # 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 # File checkpointing for rewind support cmd << '--enable-file-checkpointing' if @options.enable_file_checkpointing # JSON schema for structured output # Accepts either: # 1. Direct schema: { type: 'object', properties: {...} } # 2. Wrapped format: { type: 'json_schema', schema: {...} } if @options.output_format schema = if @options.output_format.is_a?(Hash) && @options.output_format[:type] == 'json_schema' @options.output_format[:schema] elsif @options.output_format.is_a?(Hash) && @options.output_format['type'] == 'json_schema' @options.output_format['schema'] else @options.output_format end schema_json = schema.is_a?(String) ? schema : JSON.generate(schema) cmd.concat(['--json-schema', schema_json]) end # Add directories @options.add_dirs.each do |dir| cmd.concat(['--add-dir', dir.to_s]) end # MCP servers if @options.mcp_servers && !@options.mcp_servers.empty? if @options.mcp_servers.is_a?(Hash) servers_for_cli = {} @options.mcp_servers.each do |name, config| if config.is_a?(Hash) && config[:type] == 'sdk' # For SDK servers, exclude instance field sdk_config = config.reject { |k, _| k == :instance } servers_for_cli[name] = sdk_config else servers_for_cli[name] = config end end cmd.concat(['--mcp-config', JSON.generate({ mcpServers: servers_for_cli })]) unless servers_for_cli.empty? else cmd.concat(['--mcp-config', @options.mcp_servers.to_s]) end end cmd << '--include-partial-messages' if @options. cmd << '--fork-session' if @options.fork_session # Agents if @options.agents agents_dict = @options.agents.transform_values do |agent_def| { description: agent_def.description, prompt: agent_def.prompt, tools: agent_def.tools, model: agent_def.model }.compact end cmd.concat(['--agents', JSON.generate(agents_dict)]) end # Plugins if @options.plugins && !@options.plugins.empty? plugins_config = @options.plugins.map do |plugin| plugin.is_a?(SdkPluginConfig) ? plugin.to_h : plugin end cmd.concat(['--plugins', JSON.generate(plugins_config)]) end # 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 # Prompt handling if @is_streaming cmd.concat(['--input-format', 'stream-json']) else cmd.concat(['--print', '--', @prompt.to_s]) end cmd end |
#check_claude_version ⇒ Object
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 |
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 495 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 |
#close ⇒ Object
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 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 |
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 334 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.}" end end # Close streams begin @stdin&.close rescue IOError # Already closed, ignore rescue StandardError => e cleanup_errors << "stdin: #{e.}" end begin @stdout&.close rescue IOError # Already closed, ignore rescue StandardError => e cleanup_errors << "stdout: #{e.}" end begin @stderr&.close rescue IOError # Already closed, ignore rescue StandardError => e cleanup_errors << "stderr: #{e.}" end # Terminate process begin if @process.alive? Process.kill('TERM', @process.pid) # Wait briefly for graceful shutdown Timeout.timeout(2) { @process.value } end rescue Timeout::Error # Force kill if graceful shutdown failed begin Process.kill('KILL', @process.pid) @process.value rescue StandardError => e cleanup_errors << "force kill: #{e.}" end rescue Errno::ESRCH # Process already dead, ignore rescue StandardError => e cleanup_errors << "process termination: #{e.}" 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 |
#connect ⇒ Object
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 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 |
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 255 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 } # Strip CLAUDECODE to prevent "nested session" detection when the SDK # launches Claude Code from within an existing Claude Code terminal process_env = ENV.to_h.except('CLAUDECODE').merge('CLAUDE_AGENT_SDK_VERSION' => VERSION).merge(custom_env) process_env['CLAUDE_CODE_ENTRYPOINT'] ||= 'sdk-rb' 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) # Handle stderr if piped if should_pipe_stderr && @stderr @stderr_task = Thread.new do handle_stderr rescue StandardError # Ignore errors during stderr reading end end # Close stdin for non-streaming mode @stdin.close unless @is_streaming @stdin = nil unless @is_streaming @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 |
#end_input ⇒ Object
425 426 427 428 429 430 431 432 433 434 |
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 425 def end_input return unless @stdin begin @stdin.close rescue StandardError # Ignore end @stdin = nil end |
#find_cli ⇒ Object
32 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 |
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 32 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_stderr ⇒ Object
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 |
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 311 def handle_stderr return unless @stderr @stderr.each_line do |line| line_str = line.chomp next if line_str.empty? # 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
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 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 |
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 436 def (&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 @exit_error = ProcessError.new( "Command failed with exit code #{returncode}", exit_code: returncode, stderr: 'Check stderr output for details' ) raise @exit_error end end |
#ready? ⇒ Boolean
516 517 518 |
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 516 def ready? @ready end |
#write(data) ⇒ Object
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 |
# File 'lib/claude_agent_sdk/subprocess_cli_transport.rb', line 409 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 |