use std::{io, path::Path, time::Duration};
use serde_json::Value;
use tokio::{
io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader},
task::JoinHandle,
};
use super::{
command::{self, Launch},
mcp::{self, Server},
wire::{self, ControlResponse, Initialized, Line},
};
use crate::{
error::{Code, Failure},
platform::{self, Environment},
};
const LINE_LIMIT: usize = 32 * 1024 * 1024;
const STDERR_LIMIT: usize = 16 * 1024;
const STDERR_READ: usize = 4096;
const STOP_GRACE: Duration = Duration::from_secs(2);
pub struct Channel<R, W> {
reader: BufReader<R>,
partial: Vec<u8>,
writer: Option<W>,
}
impl<R: AsyncRead + Unpin, W: AsyncWrite + Unpin> Channel<R, W> {
pub fn new(reader: R, writer: W) -> Self {
Self {
reader: BufReader::new(reader),
partial: Vec::new(),
writer: Some(writer),
}
}
pub async fn send(&mut self, line: &Value) -> Result<(), Failure> {
let writer = self
.writer
.as_mut()
.expect("input is closed only at the end");
let mut bytes = line.to_string().into_bytes();
bytes.push(b'\n');
let written = async {
writer.write_all(&bytes).await?;
writer.flush().await
};
written
.await
.map_err(|error| failure(format!("Claude Code stopped reading its input: {error}.")))
}
pub async fn next(&mut self) -> Result<Option<Line>, Failure> {
loop {
let remaining = LINE_LIMIT + 1 - self.partial.len();
(&mut self.reader)
.take(remaining as u64)
.read_until(b'\n', &mut self.partial)
.await
.map_err(|error| failure(format!("Cannot read Claude Code's output: {error}.")))?;
if self.partial.is_empty() {
return Ok(None);
}
if self.partial.len() > LINE_LIMIT {
return Err(failure("Claude Code wrote a line over 32 MiB.".into()));
}
if self.partial.iter().all(u8::is_ascii_whitespace) {
self.partial.clear();
continue;
}
let parsed = serde_json::from_slice(&self.partial);
self.partial.clear();
return parsed.map(Some).map_err(|error| {
failure(format!(
"Claude Code wrote a line artifactize cannot read: {error}."
))
});
}
}
pub fn close(&mut self) {
self.writer = None;
}
pub async fn initialize(&mut self, server: Option<&Server>) -> Result<Initialized, Failure> {
self.send(&wire::initialize(server.map(|_| command::SERVER)))
.await?;
loop {
match self.next().await? {
None => return Err(failure("Claude Code exited while starting.".into())),
Some(Line::ControlRequest {
request_id,
request,
}) => {
let reply = match (server, request) {
(Some(server), wire::ControlRequest::McpMessage { message, .. }) => {
match server.answer(message) {
mcp::Answer::Reply(reply) => wire::mcp_reply(&request_id, reply),
mcp::Answer::Call { id, .. } => wire::mcp_reply(
&request_id,
mcp::call_error(&id, "The review has not started."),
),
}
}
_ => wire::refusal(&request_id, "Not served by artifactize."),
};
self.send(&reply).await?;
}
Some(Line::ControlResponse {
response: ControlResponse::Success { response, .. },
}) => {
let initialized = response.unwrap_or_default();
check_version(initialized.claude_code_version.as_deref())?;
return Ok(initialized);
}
Some(Line::ControlResponse {
response: ControlResponse::Error { error, .. },
}) => {
return Err(failure(format!(
"Claude Code refused to start the session: {}",
super::shown(&error)
)));
}
Some(_) => {}
}
}
}
}
pub const MINIMUM_VERSION: semver::Version = semver::Version::new(2, 1, 248);
fn check_version(version: Option<&str>) -> Result<(), Failure> {
let parsed = version.and_then(|text| semver::Version::parse(text).ok());
match parsed {
Some(version) if version >= MINIMUM_VERSION => Ok(()),
_ => Err(Failure::new(
Code::AgentError,
format!(
"Claude Code {} is older than {MINIMUM_VERSION}, which the claude-agent backend needs; run `claude update`.",
version.unwrap_or("of an unknown version")
),
)),
}
}
fn failure(message: String) -> Failure {
Failure::new(Code::ProviderError, message)
}
pub struct Running {
child: platform::Child,
stderr: JoinHandle<Vec<u8>>,
_cwd_dir: Option<artifactize_foundation::platform::private::PrivateTempDir>,
}
pub type ProcessChannel = Channel<tokio::process::ChildStdout, tokio::process::ChildStdin>;
pub async fn start(
launch: &Launch<'_>,
cwd: &Path,
environment: Environment,
) -> Result<(ProcessChannel, Running), Failure> {
let command = platform::command(
command::PROGRAM,
launch.args(),
cwd,
&command::environment(environment),
true,
);
let result = match command {
Ok(command) => Running::spawn(command).await,
Err(error) => Err(error),
};
let (stdout, stdin, running) = result.map_err(|error| match error.kind() {
io::ErrorKind::NotFound => Failure::new(
Code::Authentication,
"Claude Code (`claude`) is not on PATH; install it and sign in with `claude auth login`.",
),
_ => Failure::new(Code::AgentError, format!("Cannot start Claude Code: process could not be spawned: {error}.")),
})?;
Ok((Channel::new(stdout, stdin), running))
}
impl Running {
async fn spawn(
command: platform::Command,
) -> io::Result<(
tokio::process::ChildStdout,
tokio::process::ChildStdin,
Self,
)> {
let mut child = platform::spawn_now(command).await?;
let stdout = child.stdout().take().expect("stdout is piped");
let stdin = child.stdin().take().expect("stdin is piped");
let mut stderr = child.stderr().take().expect("stderr is piped");
let stderr = tokio::spawn(async move {
let mut kept = Vec::new();
let mut buffer = [0; STDERR_READ];
while let Ok(count) = stderr.read(&mut buffer).await {
if count == 0 {
break;
}
kept.extend_from_slice(&buffer[..count]);
if kept.len() > STDERR_LIMIT {
kept.drain(..kept.len() - STDERR_LIMIT);
}
}
kept
});
Ok((
stdout,
stdin,
Self {
child,
stderr,
_cwd_dir: None,
},
))
}
pub(crate) fn with_tempdir(
mut self,
dir: artifactize_foundation::platform::private::PrivateTempDir,
) -> Self {
self._cwd_dir = Some(dir);
self
}
pub async fn stop(self, mut channel: ProcessChannel) -> Result<String, Failure> {
channel.close();
drop(channel);
let stderr = self.reap().await.map_err(|error| {
Failure::new(
Code::AgentError,
format!("Cannot clean up Claude Code: {error}."),
)
})?;
Ok(super::shown(&crate::platform::output_text(&stderr)))
}
async fn reap(mut self) -> io::Result<Vec<u8>> {
let cleanup = match tokio::time::timeout(STOP_GRACE, self.child.wait()).await {
Ok(Ok(_)) => self.child.cleanup().await.map(|_| ()),
Ok(Err(_)) | Err(_) => platform::terminate(&mut self.child).await,
};
if cleanup.is_err() {
self.stderr.abort();
}
let stderr = match self.stderr.await {
Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()),
result => result,
};
cleanup?;
stderr.map_err(io::Error::other)
}
}
#[cfg(test)]
mod tests;