use std::collections::BTreeMap;
use std::time::SystemTime;
use ag_contracts::{
ActivityEvent, ActivityFacts, ActivityFailure, ActivityKind, ActivityStatus, DiffStat,
TurnEvent,
};
use ag_harness::event::{Item, RunSummary, ToolCallItem, ToolCallOutcome, ToolCallStatus};
use ag_harness::{ErrorKind, RunEventKind};
use serde_json::Value;
use super::command_exit::apply_command_exit;
use super::output::{OutputProjector, turn_notice};
use super::sandbox::notice as sandbox_notice;
use super::tool_description::ToolDescription;
use crate::agent::activity_content::first_line;
const FAILURE_TAIL_LINES: usize = 3;
pub(crate) struct RunProjector {
output: OutputProjector,
tool_rows: ToolRows,
}
impl RunProjector {
pub(crate) fn new() -> Self {
Self {
output: OutputProjector::default(),
tool_rows: ToolRows {
attempt_id: uuid::Uuid::new_v4().to_string(),
open: BTreeMap::new(),
},
}
}
pub(crate) fn project(&mut self, event: RunEventKind) -> Vec<TurnEvent> {
let mut events = Vec::new();
if let Some(notice) = turn_notice(&event).or_else(|| sandbox_notice(&event)) {
events.push(TurnEvent::Notice(notice));
}
let rows = self.tool_rows.project(&event);
events.extend(
self.output
.project(event)
.into_iter()
.map(TurnEvent::Output),
);
events.extend(rows.into_iter().map(TurnEvent::Activity));
events
}
}
struct ToolRows {
attempt_id: String,
open: BTreeMap<u64, ActivityEvent>,
}
impl ToolRows {
fn project(&mut self, event: &RunEventKind) -> Vec<ActivityEvent> {
match event {
RunEventKind::ToolCallRequested {
arguments,
call_id,
id,
name,
..
} => {
let row = self.requested(id.get(), call_id, name, arguments);
self.open.insert(id.get(), row.clone());
vec![row]
}
RunEventKind::ItemCompleted {
id,
item: Item::ToolCall(call),
..
} => {
let row = self.open.remove(&id.get()).unwrap_or_else(|| {
self.requested(id.get(), &call.call_id, &call.name, &call.arguments)
});
vec![Self::answered(row, call)]
}
RunEventKind::Completed(summary) => self.close_open(summary),
_ => Vec::new(),
}
}
fn requested(&self, id: u64, call_id: &str, name: &str, arguments: &str) -> ActivityEvent {
let description = ToolDescription::new(call_id, name, Some(arguments));
ActivityEvent {
attempt_id: self.attempt_id.clone(),
exit_code: None,
facts: Box::new(ActivityFacts {
lines: description.lines,
target: description.target,
..ActivityFacts::default()
}),
id: id.to_string(),
input: description.input,
kind: description.kind,
name: name.chars().take(128).collect(),
observed_at: SystemTime::now(),
output: None,
parent_id: None,
status: ActivityStatus::Running,
}
}
fn answered(mut row: ActivityEvent, call: &ToolCallItem) -> ActivityEvent {
let (status, failure) = match call.status {
ToolCallStatus::Completed | ToolCallStatus::Skipped | ToolCallStatus::Answered => {
(ActivityStatus::Completed, None)
}
ToolCallStatus::Unanswered => (ActivityStatus::Interrupted, None),
status => (ActivityStatus::Failed, Some(Self::failure_of(status))),
};
row.status = status;
row.facts.failure = failure;
Self::record_outcome(&mut row, call);
let error = Self::error_message(&call.output);
if row.status == ActivityStatus::Failed && row.facts.reason.is_none() {
row.facts.reason = first_line(error.as_deref().unwrap_or(&call.output));
}
if row.outcome() == ActivityStatus::Failed {
row.output = Self::failure_tail(row.kind, &call.output, error.as_deref());
}
row.observed_at = SystemTime::now();
row
}
fn failure_of(status: ToolCallStatus) -> ActivityFailure {
[
(ToolCallStatus::Denied, ActivityFailure::Denied),
(ToolCallStatus::Rejected, ActivityFailure::Rejected),
(ToolCallStatus::Unavailable, ActivityFailure::Unavailable),
]
.into_iter()
.find_map(|(known, failure)| (known == status).then_some(failure))
.unwrap_or(ActivityFailure::Error)
}
fn record_outcome(row: &mut ActivityEvent, call: &ToolCallItem) {
row.facts.duration = call.duration;
match &call.outcome {
Some(ToolCallOutcome::Command(exit)) => {
apply_command_exit(&mut row.status, &mut row.exit_code, &mut row.facts, exit);
}
Some(ToolCallOutcome::Write {
lines_added,
lines_removed,
..
}) => {
row.facts.diff_stat = Some(DiffStat {
added: *lines_added,
removed: *lines_removed,
});
}
_ => {}
}
}
fn failure_tail(kind: ActivityKind, output: &str, error: Option<&str>) -> Option<String> {
let after_reason = |text: &str| text.lines().skip(1).collect::<Vec<_>>().join("\n");
let text = match error {
Some(error) => after_reason(error),
None => (kind == ActivityKind::Command)
.then(|| Self::command_output(output))
.flatten()
.unwrap_or_else(|| after_reason(output)),
};
let mut lines = text
.lines()
.rev()
.filter_map(first_line)
.take(FAILURE_TAIL_LINES)
.collect::<Vec<_>>();
lines.reverse();
(!lines.is_empty()).then(|| lines.join("\n"))
}
fn error_message(output: &str) -> Option<String> {
serde_json::from_str::<Value>(output)
.ok()?
.get("error")?
.as_str()
.map(str::to_string)
}
fn command_output(output: &str) -> Option<String> {
let outcome = serde_json::from_str::<Value>(output).ok()?;
let stream = |name: &str| {
let text = |key: &str| {
outcome
.get(key)
.and_then(Value::as_str)
.filter(|text| !text.trim().is_empty())
};
text(&format!("{name}_tail")).or_else(|| text(name))
};
stream("stderr")
.or_else(|| stream("stdout"))
.map(str::to_string)
.or_else(|| outcome.is_object().then(String::new))
}
fn close_open(&mut self, summary: &RunSummary) -> Vec<ActivityEvent> {
let error = summary
.error
.as_ref()
.filter(|error| error.kind != ErrorKind::Cancelled);
let failure = error.map(|error| match error.kind {
ErrorKind::ApprovalTimeout => ActivityFailure::TimedOut,
_ => ActivityFailure::Error,
});
let reason = error.and_then(|error| first_line(&error.message));
std::mem::take(&mut self.open)
.into_values()
.map(|mut row| {
row.status = if failure.is_some() {
ActivityStatus::Failed
} else {
ActivityStatus::Interrupted
};
row.facts.failure = failure;
row.facts.reason.clone_from(&reason);
row.observed_at = SystemTime::now();
row
})
.collect()
}
}
#[cfg(test)]
#[path = "run_projector_test.rs"]
mod tests;