#[cfg(feature = "json")]
use std::time::Duration;
#[cfg(feature = "json")]
use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
#[cfg(feature = "json")]
use tokio::process::{ChildStderr, Command};
#[cfg(feature = "json")]
use tracing::{debug, warn};
#[cfg(feature = "json")]
use crate::Claude;
#[cfg(feature = "json")]
use crate::error::{Error, Result};
#[cfg(feature = "json")]
use crate::exec::CommandOutput;
#[cfg(feature = "json")]
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct StreamEvent {
#[serde(flatten)]
pub data: serde_json::Value,
}
#[cfg(feature = "json")]
impl StreamEvent {
pub fn event_type(&self) -> Option<&str> {
self.data.get("type").and_then(|v| v.as_str())
}
pub fn role(&self) -> Option<&str> {
self.data.get("role").and_then(|v| v.as_str())
}
pub fn is_result(&self) -> bool {
self.event_type() == Some("result")
}
pub fn result_text(&self) -> Option<&str> {
self.data.get("result").and_then(|v| v.as_str())
}
pub fn session_id(&self) -> Option<&str> {
self.data.get("session_id").and_then(|v| v.as_str())
}
pub fn cost_usd(&self) -> Option<f64> {
self.data
.get("total_cost_usd")
.or_else(|| self.data.get("cost_usd"))
.and_then(|v| v.as_f64())
}
}
#[cfg(feature = "json")]
pub async fn stream_query<F>(
claude: &Claude,
cmd: &crate::command::query::QueryCommand,
handler: F,
) -> Result<CommandOutput>
where
F: FnMut(StreamEvent),
{
stream_query_impl(claude, cmd, handler, claude.timeout).await
}
#[cfg(feature = "json")]
async fn stream_query_impl<F>(
claude: &Claude,
cmd: &crate::command::query::QueryCommand,
mut handler: F,
timeout: Option<Duration>,
) -> Result<CommandOutput>
where
F: FnMut(StreamEvent),
{
use crate::command::ClaudeCommand;
let args = cmd.args();
let mut command_args = Vec::new();
command_args.extend(claude.global_args.clone());
command_args.extend(args);
debug!(
binary = %claude.binary.display(),
args = ?command_args,
timeout = ?timeout,
"streaming claude command"
);
let mut cmd = Command::new(&claude.binary);
cmd.args(&command_args)
.env_remove("CLAUDECODE")
.envs(&claude.env)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.stdin(std::process::Stdio::null());
if let Some(ref dir) = claude.working_dir {
cmd.current_dir(dir);
}
let mut child = cmd.spawn().map_err(|e| Error::Io {
message: format!("failed to spawn claude: {e}"),
source: e,
working_dir: claude.working_dir.clone(),
})?;
let stdout = child.stdout.take().expect("stdout was piped");
let mut stderr = child.stderr.take().expect("stderr was piped");
let mut reader = BufReader::new(stdout).lines();
let drain = drain_stderr(&mut stderr);
let read_future = read_lines(&mut reader, &mut handler, claude.working_dir.clone());
let combined = async {
let (line_result, stderr_str) = tokio::join!(read_future, drain);
(line_result, stderr_str)
};
let (line_result, stderr_str) = match timeout {
Some(d) => match tokio::time::timeout(d, combined).await {
Ok(pair) => pair,
Err(_) => {
let _ = child.kill().await;
let drain_budget = Duration::from_millis(200);
let stderr_str = tokio::time::timeout(drain_budget, drain_stderr(&mut stderr))
.await
.unwrap_or_default();
if !stderr_str.is_empty() {
warn!(stderr = %stderr_str, "stderr from timed-out streaming process");
}
return Err(Error::Timeout {
timeout_seconds: d.as_secs(),
});
}
},
None => combined.await,
};
if let Err(e) = line_result {
let _ = child.kill().await;
return Err(e);
}
let status = child.wait().await.map_err(|e| Error::Io {
message: "failed to wait for claude process".to_string(),
source: e,
working_dir: claude.working_dir.clone(),
})?;
let exit_code = status.code().unwrap_or(-1);
if !status.success() {
return Err(Error::CommandFailed {
command: format!("{} {}", claude.binary.display(), command_args.join(" ")),
exit_code,
stdout: String::new(),
stderr: stderr_str,
working_dir: claude.working_dir.clone(),
});
}
Ok(CommandOutput {
stdout: String::new(), stderr: stderr_str,
exit_code,
success: true,
})
}
#[cfg(feature = "json")]
async fn drain_stderr(stderr: &mut ChildStderr) -> String {
let mut buf = Vec::new();
let _ = stderr.read_to_end(&mut buf).await;
String::from_utf8_lossy(&buf).into_owned()
}
#[cfg(feature = "json")]
async fn read_lines<F>(
reader: &mut tokio::io::Lines<BufReader<tokio::process::ChildStdout>>,
handler: &mut F,
working_dir: Option<std::path::PathBuf>,
) -> Result<()>
where
F: FnMut(StreamEvent),
{
while let Some(line) = reader.next_line().await.map_err(|e| Error::Io {
message: "failed to read stdout line".to_string(),
source: e,
working_dir: working_dir.clone(),
})? {
if line.trim().is_empty() {
continue;
}
match serde_json::from_str::<StreamEvent>(&line) {
Ok(event) => handler(event),
Err(e) => {
debug!(line = %line, error = %e, "failed to parse stream event, skipping");
}
}
}
Ok(())
}