tread 0.4.3

A terminal reader for markdown, CSV, JSON and source code. Zero dependencies.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! The `agent` lens: Claude Code session logs.
//!
//! # The dialect, as found in a real session file
//!
//! `~/.claude/projects/<slug>/<session-uuid>.jsonl`, one JSON object per line,
//! in wall-clock order. Every record carries a `type`; the ones that matter:
//!
//! | `type` | what it is |
//! | --- | --- |
//! | `user` | `message.role = "user"`, `message.content` a string (a typed prompt) or an array of blocks |
//! | `assistant` | `message.role = "assistant"`, `message.content` an array of blocks, `message.model` the model |
//! | `system` | a `subtype` (`turn_duration`, …) and whatever fields it needs |
//! | `attachment`, `mode`, `permission-mode`, `last-prompt`, `ai-title`, `bridge-session`, `queue-operation`, `file-history-snapshot`, `file-history-delta`, `summary` | bookkeeping the transcript writes alongside the conversation |
//!
//! A content block is `{"type": …}`:
//!
//! * `text` — `text`: what was said. The only thing that makes a record a
//!   [`Class::Message`].
//! * `thinking` — `thinking` plus a `signature`; often empty (redacted).
//! * `tool_use` — `id`, `name`, `input`. The call.
//! * `tool_result` — `tool_use_id`, `content` (a string, or a block array),
//!   `is_error`. The result, which arrives as a `user` record: **the model's
//!   turn and the tool's answer are both "messages" in the API sense**, which
//!   is exactly why the generic tree is useless here and why a `user` record
//!   whose only content is a `tool_result` is mechanics, not conversation.
//!
//! Shared record fields: `timestamp` (ISO-8601, UTC, `…Z`), `uuid`,
//! `parentUuid`, `sessionId`, `cwd`, `gitBranch`, `version`, and
//! **`isSidechain`** — `true` for a subagent's own conversation, which is how a
//! `Task` run is marked. `isMeta` marks a record injected by the harness rather
//! than by the user.
//!
//! Nothing here assumes any of that is present. Every field is optional, every
//! type is checked, and a record this does not recognise returns `None` and
//! renders as the generic tree with nothing hidden.
#![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";

/// Tool calls remembered so a result can name the tool that produced it.
///
/// A ring rather than a map: results follow their call within a record or two,
/// and a log with a million calls must not grow a million entries.
const RECENT_CALLS: usize = 64;

/// What one message's content blocks hold, in the order a row says them.
#[derive(Default)]
struct Blocks {
    /// Text blocks — the only thing that makes a record a message.
    spoken: Vec<String>,
    /// What goes **under** the row: the first text block that says something,
    /// or, on a record that only thought, the thought. [`body_block`] is the
    /// one definition of which, so [`Lens::detail`] can skip exactly that block
    /// rather than showing the reader a paragraph twice.
    body: Option<Body>,
    calls: Vec<String>,
    results: Vec<String>,
    thoughts: usize,
}

#[derive(Default)]
pub struct Agent {
    /// `(tool_use_id, tool name)`, newest last, [`RECENT_CALLS`] deep.
    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))
    }

    /// A record's content blocks, read as what they are.
    ///
    /// # What this dialect can say, and what it cannot
    ///
    /// A `tool_use` block carries its whole `input`, so a call's arguments are
    /// here in full. **Its result is not**: the API answers a call in a *later*
    /// `user` record, and a [`Body`]'s path starts at the record it belongs to
    /// — so the call part carries `result: None` and the result record
    /// contributes a part of its own. That is the honest shape for a transcript
    /// where the two halves are two records, and it is why `Part::Call::result`
    /// is an `Option` rather than a `Body`.
    ///
    /// The tool a result belongs to is looked up in the same ring `read` used,
    /// and that ring is [`RECENT_CALLS`] deep while classification runs far
    /// ahead of the viewport — so by the time a reader opens an old record the
    /// call is long evicted and the part is labelled `result`. Widening the ring
    /// would be a per-document allocation, which this seam does not do; the
    /// tool's name is on the row above either way, where `read` put it.
    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();
        // The block the row's own body is already showing, skipped here so the
        // reader is not shown the same paragraph twice.
        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 {
    /// A `user` or `assistant` record.
    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,
        };
        // A prompt typed by a person: `content` is a bare string.
        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))
    }

    /// The block array of one message, read into one row.
    fn blocks_row(&mut self, blocks: &[Value], who: Who, actor: String) -> Summary {
        let mut seen = self.scan(blocks);
        let body = seen.body.take();
        // Anything a person would read keeps the record on screen; everything
        // else is a step, however many blocks it took.
        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(),
        };
        // A record carrying tool results is the tool's turn, whatever the API
        // calls the role it arrived under.
        let (who, actor) = match seen.results.is_empty() {
            true => (who, actor),
            false => (Who::Tool, "tool".to_string()),
        };
        // A step's row stays one line — what it *did* — and whatever it was
        // thinking goes under it. Reasoning is text, so it is shown.
        Summary {
            class: Class::Step,
            who,
            actor,
            time: None,
            what,
            calls: seen.calls.len(),
            // What a turn *spent* is `--lens usage`'s question, not this one's.
            tokens: 0,
            body,
        }
    }

    /// Read the blocks of one message into the four things a row can say.
    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)),
                _ => {}
            }
        }
        // One rule for what goes under the row, read off the blocks themselves,
        // so [`Lens::detail`] can skip exactly the block this took.
        seen.body = body_block(blocks).and_then(|i| block_body(blocks.get(i)?, i));
        seen
    }

    /// Remember a `tool_use` so its result can name it.
    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()));
    }

    /// The tool a result belongs to, when the call is still remembered.
    fn tool_of(&self, id: &str) -> Option<&str> {
        self.calls
            .iter()
            .rev()
            .find(|(k, _)| k == id)
            .map(|(_, n)| n.as_str())
    }

    /// A `tool_result` block as the half of a call this record *does* hold: the
    /// answer, named after the call it answers when the ring still remembers it
    /// and `result` when it does not.
    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),
        }
    }

    /// `Bash → 42 lines`, or `Bash → error`.
    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"),
        }
    }
}

/// A record someone would read.
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,
    }
}

/// The speaker's name, with a subagent's conversation marked: `isSidechain` is
/// how a `Task` run's own transcript is written into the same file as the run
/// that spawned it.
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(),
    }
}

/// `thinking`, with a count when a record holds several blocks of it.
fn thinking_text(n: usize) -> String {
    match n {
        1 => "thinking".to_string(),
        n => format!("thinking \u{d7}{n}"),
    }
}

/// `Bash(cargo test)` — the call and the one argument worth seeing.
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(),
    }
}

/// The argument that says what a call *did*, by the name tools give it.
///
/// Ordered, not guessed: `command` before `file_path` before `pattern`, so a
/// tool carrying several still shows the one a reader scans for. A tool this
/// does not know shows its name alone rather than an arbitrary field.
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
}

/// How much a tool returned: `42 lines`, or the size when it is one long line.
fn result_size(content: Option<&Value>) -> Option<String> {
    let text = match content? {
        Value::Str(s) => s.clone(),
        // The block-array form: `[{"type":"text","text":…}]`.
        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")),
    }
}

/// A `system` record: its subtype, plus whatever that subtype is about.
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(),
    }
}

/// The transcript's own bookkeeping, one line each. `None` for a `type` this
/// dialect has never seen, which is what sends the record to the generic tree
/// rather than summarising it wrongly.
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))
}

/// The blocks of one record read as [`Part`]s — a child module so the two
/// halves of this dialect stay under the size limit and share one set of
/// imports.
#[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;