Skip to main content

agentmux_srv_core/backend/agent_archive/
transcript_md.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The conversation as one readable file (`history/transcript.md`): what an agent that cannot resume the old thread
5//! reads to know what was said (spec section 7.3). It reads the compact form line by line and keeps the words of
6//! the person and of the agent. A tool call is one short line naming the tool; a tool's output is a note of how long
7//! it was, because the output is in the conversation files and a fresh thread needs the decisions, not the logs.
8
9use serde_json::Value;
10
11/// The most of one text the file keeps, so one huge paste cannot be most of it.
12const MAX_TEXT_CHARS: usize = 20_000;
13/// The most of a tool call's input shown on its line.
14const MAX_INPUT_CHARS: usize = 160;
15
16/// Renders `compact` (newline-delimited JSON, one message per line) under `title`. A line that is not JSON, or has a
17/// shape this does not know, is skipped.
18pub fn render(title: &str, compact: &str) -> String {
19    let mut out = format!("# {title}\n");
20    for line in compact.lines().filter(|l| !l.trim().is_empty()) {
21        let Ok(v) = serde_json::from_str::<Value>(line) else { continue };
22        match v.get("type").and_then(Value::as_str) {
23            Some("user") => user(&v, &mut out),
24            Some("assistant") => assistant(&v, &mut out),
25            _ => {}
26        }
27    }
28    out
29}
30
31fn user(v: &Value, out: &mut String) {
32    let content = &v["message"]["content"];
33    let mut text = String::new();
34    let mut results = 0usize;
35    match content {
36        Value::String(s) => text.push_str(s),
37        Value::Array(blocks) => {
38            for b in blocks {
39                match b.get("type").and_then(Value::as_str) {
40                    Some("text") => {
41                        if let Some(t) = b.get("text").and_then(Value::as_str) {
42                            if !text.is_empty() {
43                                text.push('\n');
44                            }
45                            text.push_str(t);
46                        }
47                    }
48                    Some("tool_result") => results += 1,
49                    _ => {}
50                }
51            }
52        }
53        _ => {}
54    }
55    if !text.trim().is_empty() {
56        section(out, "Person", &text);
57    } else if results > 0 {
58        out.push_str(&format!("\n_{results} tool result{} not shown_\n", if results == 1 { "" } else { "s" }));
59    }
60}
61
62fn assistant(v: &Value, out: &mut String) {
63    let interrupted = v.get("interrupted").and_then(Value::as_bool).unwrap_or(false);
64    let Some(blocks) = v["message"]["content"].as_array() else { return };
65    let mut text = String::new();
66    let mut tools: Vec<String> = Vec::new();
67    for b in blocks {
68        match b.get("type").and_then(Value::as_str) {
69            Some("text") => {
70                if let Some(t) = b.get("text").and_then(Value::as_str) {
71                    if !text.is_empty() {
72                        text.push('\n');
73                    }
74                    text.push_str(t);
75                }
76            }
77            Some("tool_use") => tools.push(tool_line(b)),
78            _ => {}
79        }
80    }
81    if !text.trim().is_empty() {
82        section(out, if interrupted { "Agent (cut off)" } else { "Agent" }, &text);
83    }
84    for t in tools {
85        out.push_str(&format!("\n_{t}_\n"));
86    }
87}
88
89fn tool_line(b: &Value) -> String {
90    let name = b.get("name").and_then(Value::as_str).unwrap_or("tool");
91    let input = &b["input"];
92    let first = ["command", "file_path", "path", "pattern", "url", "query", "description"].iter().find_map(|k| input.get(*k).and_then(Value::as_str));
93    match first {
94        Some(s) => format!("tool: {name} {}", clip(&s.replace('\n', " "), MAX_INPUT_CHARS)),
95        None => format!("tool: {name}"),
96    }
97}
98
99fn section(out: &mut String, who: &str, text: &str) {
100    out.push_str(&format!("\n## {who}\n\n{}\n", clip(text.trim(), MAX_TEXT_CHARS)));
101}
102
103fn clip(s: &str, max: usize) -> String {
104    if s.chars().count() <= max {
105        return s.to_string();
106    }
107    let cut: String = s.chars().take(max).collect();
108    format!("{cut} [cut: {} more characters]", s.chars().count() - max)
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114    use serde_json::json;
115
116    #[test]
117    fn the_words_of_both_sides_are_kept_and_tool_output_is_not() {
118        let compact = [
119            json!({ "type": "user", "message": { "role": "user", "content": "fix the build" } }),
120            json!({ "type": "assistant", "message": { "content": [
121                { "type": "text", "text": "Looking." },
122                { "type": "tool_use", "name": "Bash", "input": { "command": "cargo check" } } ] } }),
123            json!({ "type": "user", "message": { "content": [ { "type": "tool_result", "content": "a very long log" } ] } }),
124            json!({ "type": "assistant", "interrupted": true, "message": { "content": [ { "type": "text", "text": "Half an ans" } ] } }),
125            json!({ "type": "system", "subtype": "init" }),
126        ]
127        .iter()
128        .map(|v| v.to_string())
129        .collect::<Vec<_>>()
130        .join("\n");
131        let md = render("Agent5", &compact);
132        assert!(md.contains("## Person\n\nfix the build"), "{md}");
133        assert!(md.contains("## Agent\n\nLooking."), "{md}");
134        assert!(md.contains("_tool: Bash cargo check_"), "{md}");
135        assert!(md.contains("_1 tool result not shown_") && !md.contains("a very long log"), "{md}");
136        assert!(md.contains("## Agent (cut off)\n\nHalf an ans"), "{md}");
137        assert!(!md.contains("init"), "{md}");
138    }
139
140    #[test]
141    fn a_line_that_is_not_json_is_skipped_and_a_huge_text_is_cut() {
142        let big = "x".repeat(MAX_TEXT_CHARS + 50);
143        let compact = format!("not json\n{}\n", json!({ "type": "user", "message": { "content": big } }));
144        let md = render("T", &compact);
145        assert!(md.contains("[cut: 50 more characters]"), "{}", &md[md.len() - 80..]);
146    }
147}