#![deny(unsafe_code)]
use super::{
excerpt, part, record_clock, Body, Class, Lens, Part, RecordsAt, Step, Summary, Who, ARG,
EXCERPT,
};
use crate::json::Value;
pub const NAME: &str = "atif";
pub const ABOUT: &str = "ATIF agent trajectories: the conversation, mechanics folded away";
pub const STEPS: &str = "steps";
const ARG_KEYS: [&str; 5] = ["command", "filePath", "pattern", "query", "url"];
#[derive(Default)]
pub struct Atif;
impl Lens for Atif {
fn name(&self) -> &'static str {
NAME
}
fn about(&self) -> &'static str {
ABOUT
}
fn records_at(&self) -> RecordsAt {
RecordsAt::Member(STEPS)
}
fn read(&mut self, v: &Value) -> Option<Summary> {
match v.get("step_id") {
Some(_) => step(v),
None => session(v),
}
}
fn detail(&self, v: &Value) -> Vec<Part> {
if v.get("step_id").is_none() {
return Vec::new();
}
let mut out: Vec<Part> = Vec::new();
if !thought_is_body(v) {
if let Some(body) = thought_body(v) {
out.push(Part::Text { label: "thinking", body });
}
}
let mut results = results_of(v);
for call in calls_of(v) {
let result = take_result(&mut results, call.id.as_deref()).and_then(|at| result_body(v, at));
let args = args_of(v, &call);
out.push(Part::Call {
tool: call.name,
arg: call.arg.unwrap_or_default(),
args,
result,
});
}
for (_, at) in results {
out.push(Part::Call {
tool: "result".to_string(),
arg: String::new(),
args: Vec::new(),
result: result_body(v, at),
});
}
out
}
}
fn session(v: &Value) -> Option<Summary> {
let schema = text(v, "schema_version");
let id = text(v, "session_id");
if schema.is_none() && id.is_none() {
return None;
}
let agent = v.get("agent");
let mut parts: Vec<String> = Vec::new();
parts.extend(schema);
if let Some(a) = agent {
let name = text(a, "name").unwrap_or_else(|| "agent".to_string());
parts.push(match text(a, "version") {
Some(ver) => format!("{name} {ver}"),
None => name,
});
parts.extend(text(a, "model_name"));
}
parts.extend(id);
Some(Summary {
class: Class::Message,
who: Who::System,
actor: "session".to_string(),
time: None,
what: parts.join(" \u{b7} "),
calls: 0,
body: None,
})
}
fn step(v: &Value) -> Option<Summary> {
let source = v.get("source").and_then(|s| s.as_str()).unwrap_or("agent");
let time = record_clock(v);
let said = v.get("message").and_then(|m| m.as_str()).unwrap_or("");
let calls = calls_of(v);
let thinking = v
.get("reasoning_content")
.and_then(|r| r.as_str())
.is_some_and(|r| !r.trim().is_empty());
let sum = match said.trim().is_empty() {
false => spoken(source, said, thinking, calls.len()),
true => worked(source, v, thinking, calls),
};
Some(sum.at(time))
}
fn spoken(source: &str, said: &str, thinking: bool, calls: usize) -> Summary {
let (who, actor) = speaker(source);
let mut what = excerpt(said, EXCERPT);
if thinking {
what.push_str(" \u{b7} thinking");
}
if calls > 0 {
what.push_str(&format!(" \u{b7} {}", call_count(calls)));
}
let body = Body::new(said, vec![Step::Key("message")]);
Summary { class: Class::Message, who, actor, time: None, what, calls, body: Some(body) }
}
fn worked(source: &str, v: &Value, thinking: bool, calls: Vec<Call>) -> Summary {
let n = calls.len();
let mut results = results_of(v);
let mut parts: Vec<String> = Vec::new();
if thinking {
parts.push("thinking".to_string());
}
for call in &calls {
let answer = match take_result(&mut results, call.id.as_deref()) {
Some(at) => format!(" \u{2192} {}", size_of(result_content(v, at))),
None => String::new(),
};
parts.push(format!("{}{answer}", call.text()));
}
if !results.is_empty() {
parts.push(result_count(results.len()));
}
if parts.is_empty() {
parts.push("(no content)".to_string());
}
let (who, actor) = match n {
0 => speaker(source),
_ => (Who::Tool, "tool".to_string()),
};
Summary {
class: Class::Step,
who,
actor,
time: None,
what: collapse(parts).join(" \u{b7} "),
calls: n,
body: thought_body(v),
}
}
fn thought_body(v: &Value) -> Option<Body> {
let text = v.get("reasoning_content")?.as_str()?;
match text.trim().is_empty() {
true => None,
false => Some(Body::new(text, vec![Step::Key("reasoning_content")])),
}
}
fn thought_is_body(v: &Value) -> bool {
let said = v.get("message").and_then(|m| m.as_str()).unwrap_or("");
said.trim().is_empty()
}
fn speaker(source: &str) -> (Who, String) {
match source {
"user" => (Who::User, "user".to_string()),
_ => (Who::Assistant, "assistant".to_string()),
}
}
struct Call {
name: String,
arg: Option<String>,
id: Option<String>,
at: usize,
}
impl Call {
fn text(&self) -> String {
match &self.arg {
Some(arg) => format!("{}({arg})", self.name),
None => format!("{}()", self.name),
}
}
}
fn calls_of(v: &Value) -> Vec<Call> {
let Some(items) = v.get("tool_calls").and_then(|c| c.as_array()) else {
return Vec::new();
};
items
.iter()
.enumerate()
.map(|(at, c)| Call {
name: text(c, "function_name").unwrap_or_else(|| "tool".to_string()),
arg: arg_of(c),
id: text(c, "tool_call_id"),
at,
})
.collect()
}
fn arg_of(call: &Value) -> Option<String> {
let raw = call.get("arguments")?;
let decoded;
let args = match raw.as_str() {
Some(text) => {
decoded = crate::json::parse(text.as_bytes()).ok()?;
&decoded
}
None => raw,
};
for key in ARG_KEYS {
if let Some(text) = args.get(key).and_then(|v| v.as_str()) {
let cut = excerpt(text, ARG);
if !cut.is_empty() {
return Some(cut);
}
}
}
None
}
fn results_of(v: &Value) -> Vec<(Option<String>, usize)> {
let Some(items) = results_array(v) else {
return Vec::new();
};
items
.iter()
.enumerate()
.map(|(at, r)| (text(r, "source_call_id"), at))
.collect()
}
fn results_array(v: &Value) -> Option<&[Value]> {
v.get("observation")?.get("results")?.as_array()
}
fn result_content(v: &Value, at: usize) -> Option<&Value> {
match results_array(v)?.get(at)?.get("content")? {
Value::Null => None,
content => Some(content),
}
}
fn take_result(results: &mut Vec<(Option<String>, usize)>, id: Option<&str>) -> Option<usize> {
let id = id?;
let at = results.iter().position(|(k, _)| k.as_deref() == Some(id))?;
Some(results.remove(at).1)
}
fn args_of(v: &Value, call: &Call) -> Vec<(String, Body)> {
match call_arguments(v, call.at) {
Some(args) => part::args_of(&args),
None => Vec::new(),
}
}
fn call_arguments(v: &Value, at: usize) -> Option<Value> {
let raw = v.get("tool_calls")?.as_array()?.get(at)?.get("arguments")?;
match raw.as_str() {
Some(text) => Some(crate::json::parse(text.as_bytes()).unwrap_or_else(|_| raw.clone())),
None => Some(raw.clone()),
}
}
fn result_body(v: &Value, at: usize) -> Option<Body> {
let content = result_content(v, at)?;
let text = match content.as_str() {
Some(s) => s.to_string(),
None => return Some(Body::new(&content.to_json(), Vec::new())),
};
Some(Body::new(
&text,
vec![
Step::Key("observation"),
Step::Key("results"),
Step::At(at),
Step::Key("content"),
],
))
}
fn size_of(content: Option<&Value>) -> String {
let Some(content) = content else {
return "ok".to_string();
};
let text = part::as_text(content);
if text.is_empty() {
return "empty".to_string();
}
match text.lines().count() {
0 | 1 => crate::source::jsonrow::size(text.len() as u64),
n => format!("{n} lines"),
}
}
fn call_count(n: usize) -> String {
match n {
1 => "1 tool call".to_string(),
n => format!("{n} tool calls"),
}
}
fn result_count(n: usize) -> String {
match n {
1 => "1 result".to_string(),
n => format!("{n} results"),
}
}
fn collapse(parts: Vec<String>) -> Vec<String> {
let mut out: Vec<(String, usize)> = Vec::new();
for p in parts {
match out.last_mut() {
Some((last, n)) if *last == p => *n += 1,
_ => out.push((p, 1)),
}
}
out.into_iter()
.map(|(text, n)| match n {
1 => text,
n => format!("{text} \u{d7}{n}"),
})
.collect()
}
fn text(v: &Value, key: &str) -> Option<String> {
Some(v.get(key)?.as_str()?.to_string())
}
#[cfg(test)]
#[path = "atif_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "atif_parts_tests.rs"]
mod parts_tests;