use serde::{Deserialize, Serialize};
use serde_json::Value;
use rusty_agent_runtime::journal::Journal;
use rusty_agent_runtime::record::{EventStatus, RunEventKind};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum RunStatus {
Done,
Interrupted,
Failed {
error: String,
},
}
impl RunStatus {
pub fn is_done(&self) -> bool {
matches!(self, RunStatus::Done)
}
}
impl std::fmt::Display for RunStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
RunStatus::Done => f.write_str("done"),
RunStatus::Interrupted => f.write_str("interrupted"),
RunStatus::Failed { error } => write!(f, "failed: {error}"),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolCallRecord {
pub seq: u64,
pub name: String,
pub arguments: Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub latency_ms: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cost_usd: Option<f64>,
pub status: EventStatus,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RunEvidence {
pub status: RunStatus,
pub tool_calls: Vec<ToolCallRecord>,
pub final_state: Value,
pub latency_ms: u64,
pub cost_usd: f64,
pub total_tokens: u64,
}
impl RunEvidence {
pub fn from_journal(
journal: &Journal,
status: RunStatus,
final_state: Value,
latency_ms: u64,
) -> Self {
let events = journal.events();
let mut tool_calls = Vec::new();
let mut cost_usd = 0.0_f64;
let mut total_tokens = 0_u64;
for event in &events {
if let Some(cost) = event.cost_usd {
cost_usd += cost;
}
if let Some(usage) = &event.tokens {
total_tokens = total_tokens.saturating_add(usage.total_tokens);
}
if event.kind != RunEventKind::ToolCall {
continue;
}
let payload = event
.input
.as_ref()
.and_then(|reference| journal.resolve(reference));
let (name, arguments) = match payload {
Some(value) => {
let name = value
.get("tool")
.and_then(Value::as_str)
.map(str::to_owned)
.or_else(|| event.node_id.clone())
.unwrap_or_else(|| "unknown".to_owned());
let arguments = value.get("arguments").cloned().unwrap_or(Value::Null);
(name, arguments)
}
None => (
event
.node_id
.clone()
.unwrap_or_else(|| "unknown".to_owned()),
Value::Null,
),
};
tool_calls.push(ToolCallRecord {
seq: event.seq,
name,
arguments,
latency_ms: event.latency_ms,
cost_usd: event.cost_usd,
status: event.status,
});
}
Self {
status,
tool_calls,
final_state,
latency_ms,
cost_usd,
total_tokens,
}
}
pub fn tool_names(&self) -> Vec<&str> {
self.tool_calls
.iter()
.map(|call| call.name.as_str())
.collect()
}
}