agentmux_srv_core/backend/agent_archive/
build.rs1use std::io::{Seek, Write};
11
12use serde_json::Value;
13
14use super::definition::{PortableDefinition, RouteChoice};
15use super::manifest::{AgentInfo, Manifest, Source};
16use super::writer::{ArchiveWriter, Signer};
17use super::{transcript_md, ArchiveError, Limits};
18use crate::backend::bundle_conversation::{conversations, render};
19use crate::backend::storage::filestore::FileStore;
20use crate::backend::storage::store::Store;
21use crate::backend::storage::AgentDefinition;
22use crate::backend::transcript::withhold;
23
24pub const MAX_HISTORY_RAW_BYTES: i64 = 200 << 20;
27const MAX_TRANSCRIPT_BYTES: usize = 20 << 20;
29
30#[derive(Debug, Clone)]
32pub struct Options {
33 pub memory: bool,
34 pub history: bool,
35 pub scrub_shape: bool,
38 pub app_version: String,
39 pub instance_id: String,
40 pub host_hint: String,
41}
42
43pub struct Inputs<'a> {
45 pub mstore: &'a Store,
47 pub id_store: &'a Store,
49 pub transcripts: Option<&'a FileStore>,
51}
52
53#[derive(Debug, Clone)]
55pub struct Report {
56 pub manifest: Manifest,
57 pub warnings: Vec<String>,
59 pub memory_files: usize,
60 pub sessions: usize,
61}
62
63pub fn build<W: Write + Seek>(
65 out: W,
66 def: &AgentDefinition,
67 inputs: &Inputs<'_>,
68 opts: &Options,
69 limits: Limits,
70 signer: Option<Signer<'_>>,
71) -> Result<(Report, W), ArchiveError> {
72 let mut w = ArchiveWriter::new(out, limits);
73 let mut warnings = Vec::new();
74
75 let route = crate::backend::model_gateway::launch::choice_of(inputs.mstore, &def.id).map(|c| RouteChoice { route: c.route, model: c.model });
76 let mut stored = def.clone();
78 if stored.seat.is_none() {
79 stored.seat = inputs.mstore.agent_seat_get(&def.id);
80 }
81 let mut portable = PortableDefinition::from_definition(&stored, route);
82 portable.description = clean(&portable.description, opts);
85 portable.branch_label = clean(&portable.branch_label, opts);
86 w.add_bytes("agent.json", &portable.to_json()?)?;
87
88 let memory_files = if opts.memory { add_memory(&mut w, def, inputs, opts, &mut warnings)? } else { 0 };
89 let sessions = if opts.history { add_history(&mut w, def, inputs, opts, &mut warnings)? } else { 0 };
90
91 let info = AgentInfo { uid: def.id.clone(), name: def.name.clone(), slug: def.slug.clone() };
92 let source = Source { instance_id: opts.instance_id.clone(), host_hint: opts.host_hint.clone(), app_version: opts.app_version.clone(), os: std::env::consts::OS.to_string() };
93 let (manifest, out) = w.finish(info, source, agentmux_common::time::now_ms(), signer)?;
94 Ok((Report { manifest, warnings, memory_files, sessions }, out))
95}
96
97fn add_memory<W: Write + Seek>(w: &mut ArchiveWriter<W>, def: &AgentDefinition, inputs: &Inputs<'_>, opts: &Options, warnings: &mut Vec<String>) -> Result<usize, ArchiveError> {
98 if let Some(dir) = crate::backend::memory::native_files::memory_dir_for_agent_by_id(inputs.mstore, def) {
100 match crate::backend::memory::native_files::refresh_memory_mirror_from_live_fs(&def.id, &dir, inputs.id_store) {
101 Ok(truncated) => warnings.extend(truncated.into_iter().map(|f| format!("{f}: larger than the memory size limit and cut; the saved copy is incomplete"))),
102 Err(e) => warnings.push(format!("Personal Memory could not be refreshed from its folder; the last mirrored copy is saved: {e}")),
103 }
104 }
105 let rows = inputs.id_store.agent_native_memory_list_meta(&def.id).map_err(|e| ArchiveError::Io(e.to_string()))?;
106 let mut count = 0;
107 for row in rows {
108 let path = format!("memory/{}", row.filename);
109 if !super::manifest::valid_part_path(&path) {
110 warnings.push(format!("a memory file named {:?} was left out: its name is not a plain file name", row.filename));
111 continue;
112 }
113 match inputs.id_store.agent_native_memory_read(&def.id, &row.filename) {
114 Ok(Some(content)) => {
115 let text = clean(&content, opts);
116 w.add_bytes(&path, text.as_bytes())?;
117 count += 1;
118 }
119 Ok(None) => {}
120 Err(e) => warnings.push(format!("memory file {} could not be read and was left out: {e}", row.filename)),
121 }
122 }
123 Ok(count)
124}
125
126fn add_history<W: Write + Seek>(w: &mut ArchiveWriter<W>, def: &AgentDefinition, inputs: &Inputs<'_>, opts: &Options, warnings: &mut Vec<String>) -> Result<usize, ArchiveError> {
127 let Some(store) = inputs.transcripts else {
128 warnings.push("this install has no history store, so no conversation is saved".to_string());
129 return Ok(0);
130 };
131 let found = conversations(store, &def.id).map_err(|e| ArchiveError::Io(e.to_string()))?;
132 let mut taken = 0i64;
133 let mut kept = Vec::new();
134 for conv in found {
135 if taken + conv.size > MAX_HISTORY_RAW_BYTES {
136 warnings.push(format!("{} ({} MiB) was left out: a saved file holds the newest {} MiB of a conversation until its history is kept in the compact form only", conv.path, conv.size >> 20, MAX_HISTORY_RAW_BYTES >> 20));
137 continue;
138 }
139 taken += conv.size;
140 kept.push(conv);
141 }
142 let mut pieces: Vec<String> = Vec::new();
145 for conv in &kept {
146 let mut compact = render(store, &conv.zone).map_err(|e| ArchiveError::Io(e.to_string()))?;
147 if opts.scrub_shape {
148 compact = scrub_lines(compact);
149 }
150 w.add_bytes(&conv.path, compact.as_bytes())?;
151 let title = format!("Conversation of {} ({})", def.name, conv.path.trim_start_matches("history/").trim_end_matches(".jsonl"));
152 pieces.push(transcript_md::render(&title, &compact));
153 }
154 let (chosen, cut) = choose_pieces(&pieces, MAX_TRANSCRIPT_BYTES);
157 if cut {
158 warnings.push("the readable conversation file holds the newest sessions up to 20 MiB; the session files hold all of it".to_string());
159 }
160 let readable: String = chosen.iter().rev().map(|p| format!("{p}
161")).collect();
162 if !readable.is_empty() {
163 w.add_bytes("history/transcript.md", readable.as_bytes())?;
164 }
165 let zone = crate::backend::agent_session::agent_current_zone(&def.id);
166 if let Ok(mut files) = store.read_files_consistent(&zone, &[crate::backend::continuity_state::STATE_FILE]) {
167 if let Some(Some(state)) = files.pop() {
168 let text = clean(&String::from_utf8_lossy(&state), opts);
169 w.add_bytes("history/continuity.state.jsonl", text.as_bytes())?;
170 }
171 }
172 Ok(kept.len())
173}
174
175fn clean(text: &str, opts: &Options) -> String {
178 let text = withhold::text(text);
179 if opts.scrub_shape {
180 agentmux_common::secret_shape::scrub(&text)
181 } else {
182 text.into_owned()
183 }
184}
185
186pub fn scrub_lines(compact: String) -> String {
189 let mut out = String::with_capacity(compact.len());
190 for line in compact.lines() {
191 match serde_json::from_str::<Value>(line) {
192 Ok(mut v) => {
193 scrub_value(&mut v);
194 out.push_str(&v.to_string());
195 }
196 Err(_) => out.push_str(&agentmux_common::secret_shape::scrub(line)),
197 }
198 out.push_str("\n");
199 }
200 out
201}
202
203fn choose_pieces(pieces: &[String], max: usize) -> (Vec<&str>, bool) {
206 let mut chosen: Vec<&str> = Vec::new();
207 let mut size = 0usize;
208 for piece in pieces {
209 if size + piece.len() > max {
210 if chosen.is_empty() {
211 chosen.push(tail_of(piece, max));
212 }
213 return (chosen, true);
214 }
215 size += piece.len();
216 chosen.push(piece);
217 }
218 (chosen, false)
219}
220
221pub(super) fn tail_of(piece: &str, max: usize) -> &str {
223 if piece.len() <= max {
224 return piece;
225 }
226 let mut start = piece.len() - max;
227 while !piece.is_char_boundary(start) {
228 start += 1;
229 }
230 match piece[start..].find("
231## ") {
232 Some(at) => &piece[start + at + 1..],
233 None => &piece[start..],
234 }
235}
236
237fn scrub_value(v: &mut Value) {
238 match v {
239 Value::String(s) => {
240 let cleaned = agentmux_common::secret_shape::scrub(s);
241 if cleaned != *s {
242 *s = cleaned;
243 }
244 }
245 Value::Array(a) => a.iter_mut().for_each(scrub_value),
246 Value::Object(m) => m.values_mut().for_each(scrub_value),
247 _ => {}
248 }
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254
255 #[test]
256 fn the_readable_file_keeps_the_newest_sessions_when_the_budget_runs_out() {
257 let pieces = ["# newest
258
259## Person
260
261aaaa
262".to_string(), "# middle
263bbbbbbbbbbbb
264".to_string(), "# oldest
265cccccccccccc
266".to_string()];
267 let (fits, cut) = choose_pieces(&pieces, 1000);
268 assert_eq!((fits.len(), cut), (3, false));
269 let (kept, cut) = choose_pieces(&pieces, pieces[0].len() + pieces[1].len());
270 assert!(cut);
271 assert_eq!(kept, [pieces[0].as_str(), pieces[1].as_str()], "the oldest is the one left out, and no piece passes the budget");
272 let (kept, cut) = choose_pieces(&pieces, 10);
273 assert!(cut && kept.len() == 1 && kept[0].len() <= 10, "{kept:?}");
274 let big = format!("# s
275
276## Person
277
278{}
279
280## Agent
281
282the end
283", "x".repeat(100));
284 assert!(tail_of(&big, 40).starts_with("## Agent"), "cut at a section: {:?}", tail_of(&big, 40));
285 }
286
287 #[test]
288 fn a_key_in_a_json_string_is_withheld_and_the_line_stays_json() {
289 let key = format!("ghp_{}", "a1B2c3D4e5F6g7H8i9J0");
290 let line = serde_json::json!({ "type": "user", "message": { "content": format!("use {key} for the push") } }).to_string();
291 let out = scrub_lines(format!("{line}\nnot json {key} here\n"));
292 assert!(!out.contains(&key), "{out}");
293 let first: Value = serde_json::from_str(out.lines().next().unwrap()).expect("still one JSON value");
294 assert!(first["message"]["content"].as_str().unwrap().contains("for the push"));
295 assert_eq!(out.lines().count(), 2);
296 }
297}