pub mod auth;
mod channel;
pub mod command;
mod conversation;
mod record;
use crate::stdio_mcp as mcp;
mod wire;
pub use wire::{Account, Model};
use std::{path::Path, time::Duration};
use tokio::time::Instant;
use tokio_util::sync::CancellationToken;
pub use channel::MINIMUM_VERSION;
use artifactize_foundation::platform::{private::PrivateTempDir, probe};
use artifactize_provider::{llm::models::ListedModel, names::ModelId};
use rig_core::{completion::ToolDefinition, message::Message};
use crate::{
Event, Io, Review,
api::{self, Api},
budgets::Limits,
error::{Code, Failure},
platform::Environment,
verdict::{Issues, Judgment},
};
use channel::Running;
use command::Launch;
use conversation::Conversation;
use mcp::Server;
const SHOWN_CHARS: usize = 2000;
const PROBE_TIMEOUT: Duration = Duration::from_secs(25);
fn shown(text: &str) -> String {
let cleaned = crate::platform::output_text(text.trim().as_bytes());
match cleaned.char_indices().nth(SHOWN_CHARS) {
Some((end, _)) => format!("{}…", &cleaned[..end]),
None => cleaned.into_owned(),
}
}
pub struct Probe {
pub version: Option<String>,
pub account: Option<wire::Account>,
pub models: Vec<wire::Model>,
}
pub async fn probe(host: Host<'_>, cancellation: &CancellationToken) -> Result<Probe, Failure> {
let deadline = Instant::now() + PROBE_TIMEOUT;
let cwd_dir = host
.directory("artifactize-claude-probe-")
.map_err(|error| {
Failure::new(
Code::AgentError,
format!("Cannot create isolated directory for Claude Code probe: {error}."),
)
})?;
let (mut channel, running) =
channel::start(&Launch::default(), cwd_dir.path(), host.environment).await?;
let running = running.with_tempdir(cwd_dir);
let initialized = tokio::select! {
biased;
_ = cancellation.cancelled() => Err(Failure::cancelled()),
_ = tokio::time::sleep_until(deadline) => Err(Failure::timeout()),
initialized = channel.initialize(None) => initialized,
};
let initialized = after_stop(initialized, running.stop(channel).await, with_stderr)?;
Ok(Probe {
version: initialized.claude_code_version,
account: initialized.account,
models: initialized.models,
})
}
pub async fn models(host: Host<'_>) -> Result<Vec<ListedModel>, String> {
let probe = probe(host, &CancellationToken::new())
.await
.map_err(|failure| failure.message)?;
Ok(listed(probe.models))
}
fn listed(models: Vec<wire::Model>) -> Vec<ListedModel> {
let entries: Vec<(String, wire::Model)> = models
.into_iter()
.map(|model| {
(
model
.resolved_model
.clone()
.unwrap_or_else(|| model.value.clone()),
model,
)
})
.collect();
let mut listed: Vec<ListedModel> = Vec::new();
for (id, model) in &entries {
if model.value == "default"
&& entries
.iter()
.any(|(other, entry)| other == id && entry.value != "default")
{
continue;
}
let Ok(slug) = id.parse::<ModelId>() else {
continue;
};
if listed.iter().any(|entry| entry.slug == slug) {
continue;
}
let entry = ListedModel::new(
slug,
model.display_name.clone().unwrap_or_else(|| id.clone()),
);
if model.supports_effort == Some(false) {
listed.push(entry);
continue;
}
let levels = model.supported_effort_levels.clone().unwrap_or_else(|| {
["low", "medium", "high", "xhigh", "max"]
.map(str::to_owned)
.into()
});
listed.push(entry.with_efforts(levels, model.default_effort.clone()));
}
listed
}
pub(crate) fn with_stderr(failure: Failure, stderr: &str) -> Failure {
if stderr.is_empty() {
failure
} else {
Failure {
message: format!("{} Claude Code: {stderr}", failure.message),
..failure
}
}
}
pub struct Host<'a> {
pub environment: Environment,
pub temporary_parent: &'a Path,
pub workspace: Option<&'a Path>,
pub markers: probe::Markers<'a>,
}
impl Host<'_> {
fn directory(&self, prefix: &str) -> Result<PrivateTempDir, probe::Error> {
probe::directory(
prefix,
self.temporary_parent,
self.workspace.as_slice(),
&self.markers,
)
}
}
pub async fn review(
review: Review<'_>,
host: Host<'_>,
io: &mut impl Io,
) -> Result<Judgment, Failure> {
let issues = Issues::new(review.red_at);
let system = crate::verdict::review_system(review.system);
let mut parameters = api::parameters(Api::ClaudeAgent, review.reasoning, review.cache_key)?;
api::output_format(Api::ClaudeAgent, &mut parameters, issues.schema.clone());
io.event(Event::Started {
parameters,
tools: &review.tools,
});
io.event(Event::Message {
turn: 1,
message: &Message::system(system.clone()),
repair: false,
});
io.event(Event::Message {
turn: 1,
message: &Message::user(review.prompt.clone()),
repair: false,
});
let turn = Turn {
model: review.model,
reasoning: review.reasoning,
system: &system,
prompt: &review.prompt,
tools: &review.tools,
limits: review.limits,
cancellation: review.cancellation,
};
let (mut conversation, running) = turn.open(host, Some(&issues.schema), io).await?;
let result = judge(&mut conversation, turn.prompt, &issues).await;
close(conversation, running, result).await
}
pub struct Turn<'a> {
pub model: &'a ModelId,
pub reasoning: Option<&'a str>,
pub system: &'a str,
pub prompt: &'a str,
pub tools: &'a [ToolDefinition],
pub limits: Limits,
pub cancellation: &'a CancellationToken,
}
pub async fn converse(turn: Turn<'_>, host: Host<'_>, io: &mut impl Io) -> Result<String, Failure> {
let (mut conversation, running) = turn.open(host, None, io).await?;
let answer = conversation.ask(turn.prompt).await;
close(conversation, running, answer).await
}
impl Turn<'_> {
async fn open<'a, I: Io>(
&'a self,
host: Host<'_>,
schema: Option<&serde_json::Value>,
io: &'a mut I,
) -> Result<(Started<'a, I>, Running), Failure> {
let cwd_dir = host.directory("artifactize-claude-").map_err(|error| {
Failure::new(
Code::AgentError,
format!("Cannot create isolated directory for claude-agent eval: {error}."),
)
})?;
let launch = Launch {
model: Some(self.model.as_str()),
effort: self.reasoning,
system: Some(self.system),
tools: self.tools.iter().map(|tool| tool.name.as_str()).collect(),
schema,
};
let (channel, running) = channel::start(&launch, cwd_dir.path(), host.environment).await?;
let running = running.with_tempdir(cwd_dir);
let session = Session {
server: Server::new(self.tools),
tools: self.tools,
model: self.model,
limits: self.limits,
cancellation: self.cancellation,
io,
};
let mut conversation = Conversation::new(session, channel);
match conversation.initialize().await {
Ok(()) => Ok((conversation, running)),
Err(failure) => Err(close::<(), I>(conversation, running, Err(failure))
.await
.unwrap_err()),
}
}
}
struct Session<'a, I> {
server: Server,
tools: &'a [ToolDefinition],
model: &'a ModelId,
limits: Limits,
cancellation: &'a CancellationToken,
io: &'a mut I,
}
type Started<'a, I> = Conversation<'a, I, tokio::process::ChildStdout, tokio::process::ChildStdin>;
async fn judge<R, W>(
conversation: &mut Conversation<'_, impl Io, R, W>,
prompt: &str,
issues: &Issues,
) -> Result<Judgment, Failure>
where
R: tokio::io::AsyncRead + Unpin,
W: tokio::io::AsyncWrite + Unpin,
{
let answer = conversation.ask(prompt).await?;
let error = match issues.parse_model(&answer) {
Ok(result) => return Ok(result),
Err(error) => error,
};
let repair = Issues::repair_prompt(error);
conversation.session.io.event(Event::Message {
turn: conversation.turn + 1,
message: &Message::user(repair.clone()),
repair: true,
});
conversation.tools_open = false;
let answer = conversation.ask(&repair).await?;
issues.parse_model(&answer).map_err(Issues::repair_failed)
}
async fn close<T, I: Io>(
mut conversation: Started<'_, I>,
running: Running,
result: Result<T, Failure>,
) -> Result<T, Failure> {
if let Err(failure) = &result {
conversation.fail(failure);
}
after_stop(
result,
running.stop(conversation.channel).await,
|failure, stderr| match failure.code {
Code::ProviderError | Code::AgentError => with_stderr(failure, stderr),
_ => failure,
},
)
}
fn after_stop<T>(
result: Result<T, Failure>,
stopped: Result<String, Failure>,
output: impl FnOnce(Failure, &str) -> Failure,
) -> Result<T, Failure> {
match (result, stopped) {
(result, Ok(stderr)) => result.map_err(|failure| output(failure, &stderr)),
(Ok(_), Err(cleanup)) => Err(cleanup),
(Err(mut failure), Err(cleanup)) => {
failure.message.push(' ');
failure.message.push_str(&cleanup.message);
Err(failure)
}
}
}
#[cfg(test)]
mod tests;