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 receive_messages
cli_path = find_cli_path
raise CLINotFoundError.new(cli_path: cli_path) unless cli_path
args = @options.to_cli_args
args.push(@prompt)
command = "#{cli_path} #{args.map { |arg| Shellwords.escape(arg) }.join(" ")}"
puts "[DEBUG] Command: #{command}" if ENV["DEBUG"]
env = { "ANTHROPIC_API_KEY" => ENV.fetch("ANTHROPIC_API_KEY", nil) }
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"]
unless $CHILD_STATUS.success?
raise ProcessError.new(
"Claude Code process failed",
exit_code: exit_status,
stderr: output
)
end
begin
data = JSON.parse(output, symbolize_names: true)
if data[:type] == "result" && data[:result]
yield({ type: "user", text: @prompt })
yield({
type: "assistant",
message: {
id: "msg-#{data[:session_id]}",
content: [{ type: "text", text: data[:result] }]
}
})
yield data
end
rescue JSON::ParserError
raise CLIJSONDecodeError.new(
"Failed to parse JSON from Claude Code",
line: output
)
end
end
|