Class: ClaudeCodeSDK::Transport::SimpleCLI
- Defined in:
- lib/claude_code_sdk/transport/simple_cli.rb
Instance Method Summary collapse
- #connect ⇒ Object
- #connected? ⇒ Boolean
- #disconnect ⇒ Object
-
#initialize(prompt:, options: nil) ⇒ SimpleCLI
constructor
A new instance of SimpleCLI.
- #receive_messages ⇒ Object
Constructor Details
#initialize(prompt:, options: nil) ⇒ SimpleCLI
Returns a new instance of SimpleCLI.
10 11 12 13 14 |
# File 'lib/claude_code_sdk/transport/simple_cli.rb', line 10 def initialize(prompt:, options: nil) @prompt = prompt = || Options.new @connected = false end |
Instance Method Details
#connect ⇒ Object
16 17 18 |
# File 'lib/claude_code_sdk/transport/simple_cli.rb', line 16 def connect @connected = true end |
#connected? ⇒ Boolean
24 25 26 |
# File 'lib/claude_code_sdk/transport/simple_cli.rb', line 24 def connected? @connected end |
#disconnect ⇒ Object
20 21 22 |
# File 'lib/claude_code_sdk/transport/simple_cli.rb', line 20 def disconnect @connected = false end |
#receive_messages ⇒ Object
28 29 30 31 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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/claude_code_sdk/transport/simple_cli.rb', line 28 def cli_path = find_cli_path raise CLINotFoundError.new(cli_path: cli_path) unless cli_path args = .to_cli_args args.push(@prompt) command = "#{cli_path} #{args.map { |arg| Shellwords.escape(arg) }.join(" ")}" puts "[DEBUG] Command: #{command}" if ENV["DEBUG"] # Set environment variable env = { "ANTHROPIC_API_KEY" => ENV.fetch("ANTHROPIC_API_KEY", nil) } # Run command and capture output output = IO.popen(env, command, "r", &:read) exit_status = $CHILD_STATUS.exitstatus puts "[DEBUG] Exit status: #{exit_status}" if ENV["DEBUG"] puts "[DEBUG] Output: #{output}" if ENV["DEBUG"] # Check for errors unless $CHILD_STATUS.success? raise ProcessError.new( "Claude Code process failed", exit_code: exit_status, stderr: output ) end # Parse the JSON response begin data = JSON.parse(output, symbolize_names: true) # The response is a single result object, but we need to yield messages if data[:type] == "result" && data[:result] # Yield a user message with the prompt yield({ type: "user", text: @prompt }) # Yield an assistant message with the response yield({ type: "assistant", message: { id: "msg-#{data[:session_id]}", content: [{ type: "text", text: data[:result] }] } }) # Yield the result message yield data end rescue JSON::ParserError raise CLIJSONDecodeError.new( "Failed to parse JSON from Claude Code", line: output ) end end |