Skip to main content

agentmux_srv_core/backend/
bundle_conversation.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What an export carries of an agent's conversation: the history store's compact form, one file per session
5//! (SPEC_HISTORY_COMPACT_FORM_ONLY section 3, the bundle export row). The export reads the store only. It never reads a
6//! provider's own session file: that file is a second, raw copy of the conversation that AgentMux removes by session id
7//! when a session ends, so an export that copied it would put a copy back that the history guarantee takes away.
8//!
9//! A session is a zone of the global transcript store: the agent's current one, and each archive an ended session left
10//! (`agent:<id>:archive:<ms>`). Each is rendered as newline-delimited JSON, one line per message: the fragments of a
11//! streamed reply are dropped where the complete line proves them redundant, and a reply that was cut off is one
12//! `interrupted` line. A value srv holds secret is replaced by the withhold mark.
13
14use crate::backend::agent_session::{agent_current_zone, is_valid_definition_id, OUTPUT_FILE};
15use crate::backend::storage::error::StoreError;
16use crate::backend::storage::filestore::FileStore;
17use crate::backend::transcript::compact::{compact_lines, WindowEnd};
18use crate::backend::transcript::live::LIVE_FILE;
19use crate::backend::transcript::withhold;
20
21/// One session an export can carry.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct Conversation {
24    /// Where it goes in the archive.
25    pub path: String,
26    /// Its zone in the store.
27    pub zone: String,
28    /// The size of its `output` file in the store, which is the most its compact form can be.
29    pub size: i64,
30}
31
32/// The sessions of an agent that have content, newest first: the current one, then the archives by their time.
33pub fn conversations(store: &FileStore, definition_id: &str) -> Result<Vec<Conversation>, StoreError> {
34    if !is_valid_definition_id(definition_id) {
35        return Ok(Vec::new());
36    }
37    let mut found = Vec::new();
38    let current = agent_current_zone(definition_id);
39    if let Some(file) = store.stat(&current, OUTPUT_FILE)?.filter(|f| f.size > 0) {
40        found.push(Conversation { path: "history/current.jsonl".to_string(), zone: current, size: file.size });
41    }
42    let prefix = format!("agent:{definition_id}:archive:");
43    let mut archives: Vec<(u64, String)> = store
44        .zone_ids_with_prefix(&prefix)?
45        .into_iter()
46        .filter_map(|zone| zone.strip_prefix(&prefix).and_then(|at| at.parse::<u64>().ok()).map(|at| (at, zone)))
47        .collect();
48    archives.sort_by_key(|(at, _)| std::cmp::Reverse(*at));
49    for (at, zone) in archives {
50        if let Some(file) = store.stat(&zone, OUTPUT_FILE)?.filter(|f| f.size > 0) {
51            found.push(Conversation { path: format!("history/archive-{at}.jsonl"), zone, size: file.size });
52        }
53    }
54    Ok(found)
55}
56
57/// The compact form of one session, as newline-delimited JSON. `output` and `output.live` are read together, so a reply in
58/// progress is not lost.
59pub fn render(store: &FileStore, zone: &str) -> Result<String, StoreError> {
60    let mut files = store.read_files_consistent(zone, &[OUTPUT_FILE, LIVE_FILE])?.into_iter();
61    let output = files.next().flatten().unwrap_or_default();
62    let live = files.next().flatten().unwrap_or_default();
63    Ok(compact_ndjson(&output, &live))
64}
65
66/// The compact form of `output` followed by the fragments in `live`, with every value srv holds secret withheld.
67pub fn compact_ndjson(output: &[u8], live: &[u8]) -> String {
68    let text = String::from_utf8_lossy(output);
69    let live_text = String::from_utf8_lossy(live);
70    let lines: Vec<&str> = text.split('\n').chain(live_text.split('\n')).map(|l| l.trim_end_matches('\r')).filter(|l| !l.is_empty()).collect();
71    let (compact, _) = compact_lines(&lines, WindowEnd::Final);
72    let mut out = String::with_capacity(compact.iter().map(|l| l.len() + 1).sum());
73    for line in &compact {
74        out.push_str(line);
75        out.push('\n');
76    }
77    withhold::text(&out).into_owned()
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83    use crate::backend::storage::filestore::{FileMeta, FileOpts};
84    use serde_json::json;
85    use std::collections::HashMap;
86
87    fn put(fs: &FileStore, zone: &str, name: &str, body: &str) {
88        let meta: FileMeta = HashMap::new();
89        fs.make_file(zone, name, meta, FileOpts::default()).unwrap();
90        fs.write_file(zone, name, body.as_bytes()).unwrap();
91    }
92
93    fn user(text: &str) -> String {
94        json!({ "type": "user", "session_id": "s", "message": { "role": "user", "content": text } }).to_string()
95    }
96
97    fn fragment(text: &str) -> String {
98        let event = json!({ "type": "content_block_delta", "index": 0, "delta": { "type": "text_delta", "text": text } });
99        json!({ "type": "stream_event", "session_id": "s", "parent_tool_use_id": null, "event": event }).to_string()
100    }
101
102    fn start(id: &str) -> String {
103        let event = json!({ "type": "message_start", "message": { "id": id, "role": "assistant", "content": [] } });
104        json!({ "type": "stream_event", "session_id": "s", "parent_tool_use_id": null, "event": event }).to_string()
105    }
106
107    fn block_start() -> String {
108        let event = json!({ "type": "content_block_start", "index": 0, "content_block": { "type": "text", "text": "" } });
109        json!({ "type": "stream_event", "session_id": "s", "parent_tool_use_id": null, "event": event }).to_string()
110    }
111
112    fn assistant(id: &str, text: &str) -> String {
113        json!({ "type": "assistant", "session_id": "s", "message": { "id": id, "role": "assistant", "content": [{ "type": "text", "text": text }] } }).to_string()
114    }
115
116    #[test]
117    fn a_session_with_no_fragments_is_exported_as_it_is() {
118        let body = format!("{}\n{}\n", user("hello"), assistant("m1", "hi"));
119        assert_eq!(compact_ndjson(body.as_bytes(), b""), body);
120    }
121
122    #[test]
123    fn the_fragments_of_a_finished_reply_are_not_exported() {
124        let body = [user("hello"), start("m1"), block_start(), fragment("h"), fragment("i"), assistant("m1", "hi")].join("\n") + "\n";
125        let out = compact_ndjson(body.as_bytes(), b"");
126        assert!(!out.contains("stream_event"), "{out}");
127        assert_eq!(out.lines().count(), 2, "{out}");
128        assert!(out.contains("\"hi\""), "{out}");
129    }
130
131    #[test]
132    fn a_reply_in_the_live_file_becomes_one_interrupted_line() {
133        let output = format!("{}\n", user("hello"));
134        let live = [start("m2"), block_start(), fragment("par")].join("\n") + "\n";
135        let out = compact_ndjson(output.as_bytes(), live.as_bytes());
136        assert!(!out.contains("stream_event"), "{out}");
137        assert_eq!(out.lines().count(), 2, "{out}");
138        assert!(out.contains("par"), "what streamed so far is kept: {out}");
139    }
140
141    #[test]
142    fn a_value_srv_holds_secret_is_not_exported() {
143        let value = "canary-conversation-4471-ZxCv";
144        crate::backend::transcript::withhold::register(value);
145        let body = format!("{}\n", user(&format!("the key is {value}")));
146        let out = compact_ndjson(body.as_bytes(), b"");
147        assert!(!out.contains(value), "{out}");
148        assert!(out.contains(crate::backend::transcript::withhold::MARK), "{out}");
149    }
150
151    #[test]
152    fn the_current_session_and_each_archive_are_listed_newest_first_and_empty_ones_are_not() {
153        let fs = FileStore::open_in_memory().unwrap();
154        put(&fs, "agent:agent-1:current", OUTPUT_FILE, &format!("{}\n", user("now")));
155        put(&fs, "agent:agent-1:archive:100", OUTPUT_FILE, &format!("{}\n", user("old")));
156        put(&fs, "agent:agent-1:archive:300", OUTPUT_FILE, &format!("{}\n", user("newer")));
157        put(&fs, "agent:agent-1:archive:200", OUTPUT_FILE, "");
158        put(&fs, "agent:agent-2:current", OUTPUT_FILE, &format!("{}\n", user("someone else")));
159        let found = conversations(&fs, "agent-1").unwrap();
160        let paths: Vec<&str> = found.iter().map(|c| c.path.as_str()).collect();
161        assert_eq!(paths, ["history/current.jsonl", "history/archive-300.jsonl", "history/archive-100.jsonl"]);
162        assert!(found.iter().all(|c| c.zone.starts_with("agent:agent-1:") && c.size > 0));
163    }
164
165    #[test]
166    fn a_session_is_rendered_from_the_store_and_a_name_that_is_not_an_id_finds_nothing() {
167        let fs = FileStore::open_in_memory().unwrap();
168        let body = format!("{}\n", user("hello"));
169        put(&fs, "agent:agent-1:current", OUTPUT_FILE, &body);
170        assert_eq!(render(&fs, "agent:agent-1:current").unwrap(), body);
171        assert!(conversations(&fs, "agent:other").unwrap().is_empty());
172        assert!(conversations(&fs, "").unwrap().is_empty());
173        assert_eq!(render(&fs, "agent:nobody:current").unwrap(), "");
174    }
175
176    #[test]
177    fn the_live_file_is_read_with_the_output() {
178        let fs = FileStore::open_in_memory().unwrap();
179        put(&fs, "agent:agent-1:current", OUTPUT_FILE, &format!("{}\n", user("hello")));
180        put(&fs, "agent:agent-1:current", LIVE_FILE, &([start("m3"), block_start(), fragment("so far")].join("\n") + "\n"));
181        let out = render(&fs, "agent:agent-1:current").unwrap();
182        assert!(out.contains("so far") && !out.contains("stream_event"), "{out}");
183    }
184}