#![deny(unsafe_code)]
use super::{excerpt, record_clock, record_type, Body, Class, Lens, Part, Step, Summary, Who, ARG, EXCERPT};
use crate::json::Value;
pub const NAME: &str = "agent";
pub const ABOUT: &str = "Claude Code session logs: the conversation, mechanics folded away";
const RECENT_CALLS: usize = 64;
#[derive(Default)]
struct Blocks {
spoken: Vec<String>,
body: Option<Body>,
calls: Vec<String>,
results: Vec<String>,
thoughts: usize,
}
#[derive(Default)]
pub struct Agent {
calls: Vec<(String, String)>,
}
impl Lens for Agent {
fn name(&self) -> &'static str {
NAME
}
fn about(&self) -> &'static str {
ABOUT
}
fn read(&mut self, v: &Value) -> Option<Summary> {
let kind = record_type(v)?;
let time = record_clock(v);
let sum = match kind {
"user" | "assistant" => self.message(v, kind)?,
"system" => Summary::step(Who::System, "system", system_text(v)),
other => Summary::step(Who::System, "system", bookkeeping(v, other)?),
};
Some(sum.at(time))
}
fn detail(&self, v: &Value) -> Vec<Part> {
let Some(blocks) = v.get("message").and_then(|m| m.get("content")).and_then(|c| c.as_array())
else {
return Vec::new();
};
let mut out: Vec<Part> = Vec::new();
let said = body_block(blocks);
for (i, b) in blocks.iter().enumerate() {
if said == Some(i) {
continue;
}
match b.get("type").and_then(|t| t.as_str()).unwrap_or("") {
"text" => out.extend(text_part(b, "text", "message", text_at(i))),
"thinking" => out.extend(text_part(b, "thinking", "thinking", thinking_at(i))),
"tool_use" => out.push(call_part(b)),
"tool_result" => out.push(self.result_part(b, i)),
_ => {}
}
}
out
}
}
impl Agent {
fn message(&mut self, v: &Value, kind: &str) -> Option<Summary> {
let msg = v.get("message")?;
let role = msg.get("role").and_then(|r| r.as_str()).unwrap_or(kind);
let actor = actor_name(v, role);
let who = match role {
"user" => Who::User,
_ => Who::Assistant,
};
if let Some(text) = msg.get("content").and_then(|c| c.as_str()) {
let at = vec![Step::Key("message"), Step::Key("content")];
let body = Body::new(text, at);
return Some(said(who, actor, excerpt(text, EXCERPT), Some(body)));
}
let blocks = msg.get("content")?.as_array()?;
Some(self.blocks_row(blocks, who, actor))
}
fn blocks_row(&mut self, blocks: &[Value], who: Who, actor: String) -> Summary {
let mut seen = self.scan(blocks);
let body = seen.body.take();
if !seen.spoken.is_empty() {
let mut what = seen.spoken.join(" \u{b7} ");
if !seen.calls.is_empty() {
what.push_str(" \u{b7} ");
what.push_str(&seen.calls.join(" \u{b7} "));
}
return Summary { calls: seen.calls.len(), ..said(who, actor, what, body) };
}
let what = match (seen.calls.is_empty(), seen.results.is_empty()) {
(false, _) => seen.calls.join(" \u{b7} "),
(true, false) => seen.results.join(" \u{b7} "),
(true, true) if seen.thoughts > 0 => thinking_text(seen.thoughts),
(true, true) => "(no content)".to_string(),
};
let (who, actor) = match seen.results.is_empty() {
true => (who, actor),
false => (Who::Tool, "tool".to_string()),
};
Summary {
class: Class::Step,
who,
actor,
time: None,
what,
calls: seen.calls.len(),
tokens: 0,
body,
}
}
fn scan(&mut self, blocks: &[Value]) -> Blocks {
let mut seen = Blocks::default();
for b in blocks {
match b.get("type").and_then(|t| t.as_str()).unwrap_or("") {
"text" => match b.get("text").and_then(|t| t.as_str()) {
Some(t) if !t.trim().is_empty() => seen.spoken.push(excerpt(t, EXCERPT)),
_ => {}
},
"thinking" => seen.thoughts += 1,
"tool_use" => {
self.remember(b);
seen.calls.push(call_text(b));
}
"tool_result" => seen.results.push(self.result_text(b)),
_ => {}
}
}
seen.body = body_block(blocks).and_then(|i| block_body(blocks.get(i)?, i));
seen
}
fn remember(&mut self, block: &Value) {
let (Some(id), Some(name)) = (
block.get("id").and_then(|i| i.as_str()),
block.get("name").and_then(|n| n.as_str()),
) else {
return;
};
if self.calls.len() >= RECENT_CALLS {
self.calls.remove(0);
}
self.calls.push((id.to_string(), name.to_string()));
}
fn tool_of(&self, id: &str) -> Option<&str> {
self.calls
.iter()
.rev()
.find(|(k, _)| k == id)
.map(|(_, n)| n.as_str())
}
fn result_part(&self, block: &Value, i: usize) -> Part {
let tool = block
.get("tool_use_id")
.and_then(|i| i.as_str())
.and_then(|id| self.tool_of(id))
.unwrap_or("result");
let failed = block.get("is_error").and_then(|e| e.as_bool()).unwrap_or(false);
Part::Call {
tool: tool.to_string(),
arg: match failed {
true => "error".to_string(),
false => String::new(),
},
args: Vec::new(),
result: result_body(block.get("content"), i),
}
}
fn result_text(&self, block: &Value) -> String {
let name = block
.get("tool_use_id")
.and_then(|i| i.as_str())
.and_then(|id| self.tool_of(id))
.unwrap_or("result");
let failed = block.get("is_error").and_then(|e| e.as_bool()).unwrap_or(false);
if failed {
return format!("{name} \u{2192} error");
}
match result_size(block.get("content")) {
Some(size) => format!("{name} \u{2192} {size}"),
None => format!("{name} \u{2192} ok"),
}
}
}
fn said(who: Who, actor: String, what: String, body: Option<Body>) -> Summary {
Summary {
class: Class::Message,
who,
actor,
time: None,
what,
calls: 0,
tokens: 0,
body,
}
}
fn actor_name(v: &Value, role: &str) -> String {
let side = v.get("isSidechain").and_then(|s| s.as_bool()).unwrap_or(false);
match side {
true => format!("\u{21b3} {role}"),
false => role.to_string(),
}
}
fn thinking_text(n: usize) -> String {
match n {
1 => "thinking".to_string(),
n => format!("thinking \u{d7}{n}"),
}
}
fn call_text(block: &Value) -> String {
let name = block.get("name").and_then(|n| n.as_str()).unwrap_or("tool");
match block.get("input").and_then(tool_arg) {
Some(arg) => format!("{name}({arg})"),
None => name.to_string(),
}
}
const ARG_KEYS: [&str; 10] = [
"command",
"file_path",
"path",
"pattern",
"query",
"url",
"subagent_type",
"prompt",
"description",
"skill",
];
pub(super) fn tool_arg(input: &Value) -> Option<String> {
for key in ARG_KEYS {
if let Some(text) = input.get(key).and_then(|v| v.as_str()) {
let cut = excerpt(text, ARG);
if !cut.is_empty() {
return Some(cut);
}
}
}
None
}
fn result_size(content: Option<&Value>) -> Option<String> {
let text = match content? {
Value::Str(s) => s.clone(),
Value::Array(items) => items
.iter()
.filter_map(|b| b.get("text").and_then(|t| t.as_str()))
.collect::<Vec<_>>()
.join("\n"),
_ => return None,
};
if text.is_empty() {
return Some("empty".to_string());
}
let lines = text.lines().count();
match lines {
0 | 1 => Some(crate::source::jsonrow::size(text.len() as u64)),
n => Some(format!("{n} lines")),
}
}
fn system_text(v: &Value) -> String {
let subtype = v
.get("subtype")
.and_then(|s| s.as_str())
.unwrap_or("system");
if let Some(ms) = v.get("durationMs").and_then(|d| d.as_number()) {
let secs = ms.as_f64() / 1000.0;
return format!("{subtype} {secs:.1}s");
}
match v.get("content").and_then(|c| c.as_str()) {
Some(text) => format!("{subtype}: {}", excerpt(text, EXCERPT)),
None => subtype.to_string(),
}
}
fn bookkeeping(v: &Value, kind: &str) -> Option<String> {
let text = match kind {
"mode" => field(v, "mode"),
"permission-mode" => field(v, "permissionMode"),
"ai-title" => field(v, "aiTitle"),
"last-prompt" => field(v, "lastPrompt"),
"bridge-session" => field(v, "bridgeSessionId"),
"summary" => field(v, "summary"),
"queue-operation" => {
let op = v.get("operation").and_then(|o| o.as_str()).unwrap_or("");
let what = v.get("content").and_then(|c| c.as_str()).unwrap_or("");
Some(format!("{op} {}", excerpt(what, ARG)))
}
"attachment" => v
.get("attachment")
.and_then(|a| a.get("type"))
.and_then(|t| t.as_str())
.map(|t| t.to_string()),
"file-history-snapshot" => Some(String::new()),
"file-history-delta" => field(v, "trackingPath"),
_ => return None,
};
let detail = text.unwrap_or_default();
Some(match detail.is_empty() {
true => kind.to_string(),
false => format!("{kind} {detail}"),
})
}
fn field(v: &Value, key: &str) -> Option<String> {
Some(excerpt(v.get(key)?.as_str()?, ARG))
}
#[path = "agent_parts.rs"]
mod parts;
use parts::{block_body, body_block, call_part, result_body, text_at, text_part, thinking_at};
#[cfg(test)]
#[path = "agent_tests.rs"]
mod tests;