agentmux_srv/server/app_api/bundle/
export_for_agent.rs1use super::*;
9
10#[derive(serde::Deserialize, Default, ts_rs::TS)]
21#[ts(export, export_to = "../../../frontend/types/rpc/", rename = "BundleExportForAgentReq")]
22pub(super) struct ExportForAgentReq {
23 pub(crate) bundle_id: String,
24 pub(crate) agent_id: String,
25 #[serde(default)]
26 #[ts(as = "Option<String>", optional)]
27 pub(crate) format: String,
28}
29
30pub(super) async fn build_export_for_agent(
49 id_store: &crate::backend::storage::store::Store,
50 mstore: &crate::backend::storage::store::Store,
51 identity_store: &crate::backend::storage::store::Store,
52 bundle_id: &str,
53 agent_id: &str,
54 err_prefix: &str,
55) -> Result<(
56 crate::backend::bundle_export::BundleExport,
57 crate::backend::storage::store::AgentDefinition,
58 Vec<String>,
59 Vec<String>,
60), String> {
61 let bundle = id_store
62 .bundle_get(bundle_id)
63 .map_err(|e| format!("{err_prefix}: {e}"))?
64 .ok_or_else(|| format!("{err_prefix}: no bundle with id {bundle_id}"))?;
65 let agent = mstore
66 .agent_def_get(agent_id)
67 .map_err(|e| format!("{err_prefix}: {e}"))?
68 .ok_or_else(|| format!("{err_prefix}: no agent with id {agent_id}"))?;
69
70 let components = resolve_bundle_components(mstore, identity_store, &bundle.id)
73 .map_err(|e| format!("{err_prefix}: {e}"))?;
74 let mut handler_warnings: Vec<String> = Vec::new();
75 let missing_skill_ids: Vec<String> = Vec::new();
77
78 let mut bundle = bundle;
81 let provider = id_store.resolve_effective_provider_id(&agent);
82 if !provider.is_empty() {
83 bundle.model =
84 crate::backend::storage::store::Store::resolve_effective_vendor(&provider, &agent.model_vendor_base_url);
85 bundle.provider = provider;
86 }
87
88 let mut export = crate::backend::bundle_export::export_bundle(&bundle, &components.skills);
89
90 let mut memory_files: Vec<(String, String)> = Vec::new();
94 if let Some(memory_dir) =
95 crate::server::native_memory_handlers::memory_dir_for_agent_by_id(mstore, &agent)
96 {
97 match crate::server::native_memory_handlers::refresh_memory_mirror_from_live_fs(
98 &agent.id,
99 &memory_dir,
100 id_store,
101 ) {
102 Ok(truncated) => {
103 for filename in truncated {
106 handler_warnings.push(format!(
107 "{filename}: exceeds the native-memory size limit and was truncated; the exported copy is incomplete"
108 ));
109 }
110 }
111 Err(e) => handler_warnings.push(format!("native memory refresh failed (exporting mirror as-is): {e}")),
112 }
113 }
114 match id_store.agent_native_memory_list_meta(&agent.id) {
115 Ok(rows) => {
116 for row in rows {
117 match id_store.agent_native_memory_read(&agent.id, &row.filename) {
118 Ok(Some(content)) => memory_files.push((row.filename, content)),
119 Ok(None) => {} Err(e) => handler_warnings.push(format!(
121 "native memory: failed to read {}: {e}",
122 row.filename
123 )),
124 }
125 }
126 }
127 Err(e) => handler_warnings.push(format!("native memory: failed to list: {e}")),
128 }
129 splice_memory_component(&mut export, &memory_files).map_err(|e| format!("{err_prefix}: {e}"))?;
130
131 let work_dir = crate::backend::project_instructions::effective_working_dir(
136 &agent.working_directory,
137 &agent.name,
138 );
139 let instructions = crate::backend::project_instructions::resolve_project_instructions(
140 &agent.provider,
141 &work_dir,
142 );
143 splice_project_instructions_component(&mut export, &instructions)
144 .map_err(|e| format!("{err_prefix}: {e}"))?;
145
146 let mut all_warnings = export.warnings.clone();
147 all_warnings.append(&mut handler_warnings);
148
149 Ok((export, agent, all_warnings, missing_skill_ids))
150}
151
152pub(super) async fn bundle_export_for_agent_impl(
153 id_store: &crate::backend::storage::store::Store,
154 mstore: &crate::backend::storage::store::Store,
155 identity_store: &crate::backend::storage::store::Store,
156 req: ExportForAgentReq,
157) -> Result<BundleExportResponse, String> {
158 let (export, _agent, all_warnings, missing_skill_ids) =
159 build_export_for_agent(id_store, mstore, identity_store, &req.bundle_id, &req.agent_id, "bundle.export_for_agent").await?;
160
161 if req.format == "zip" {
162 let zip_bytes = crate::backend::bundle_export::zip_bundle_export(&export)
163 .map_err(|e| format!("bundle.export_for_agent: {e}"))?;
164 use base64::Engine as _;
165 let encoded = base64::engine::general_purpose::STANDARD.encode(&zip_bytes);
166 return Ok(BundleExportResponse {
167 root_slug: export.root_slug,
168 files: None,
169 skipped_skills: export.skipped_skills,
170 warnings: all_warnings,
171 missing_skill_ids,
172 zip_base64: Some(encoded),
173 });
174 }
175
176 Ok(BundleExportResponse {
177 root_slug: export.root_slug,
178 files: Some(export.files),
179 skipped_skills: export.skipped_skills,
180 warnings: all_warnings,
181 missing_skill_ids,
182 zip_base64: None,
183 })
184}
185
186#[derive(serde::Deserialize, ts_rs::TS)]
187#[ts(export, export_to = "../../../frontend/types/rpc/", rename = "BundleExportForAgentWithHistoryReq")]
188pub(super) struct ExportForAgentWithHistoryReq {
189 pub(crate) bundle_id: String,
190 pub(crate) agent_id: String,
191}
192
193#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
195#[ts(export, export_to = "../../../frontend/types/rpc/")]
196pub(crate) struct BundleExportWithHistoryResponse {
197 pub(crate) root_slug: String,
198 pub(crate) skipped_skills: Vec<String>,
199 pub(crate) warnings: Vec<String>,
200 pub(crate) missing_skill_ids: Vec<String>,
201 pub(crate) history_session_count: u32,
202 pub(crate) zip_base64: String,
203}
204
205pub(super) const MAX_HISTORY_SESSION_FILE_SIZE_BYTES: u64 = 200 * 1024 * 1024;
216
217pub(super) const MAX_TOTAL_HISTORY_BYTES: u64 = 500 * 1024 * 1024;
232
233pub(super) fn sessions_within_total_budget(sizes: &[u64], total_cap: u64) -> (usize, bool) {
240 let mut total = 0u64;
241 for (i, &size) in sizes.iter().enumerate() {
242 if total + size > total_cap {
243 return (i, true);
244 }
245 total += size;
246 }
247 (sizes.len(), false)
248}
249
250pub(super) async fn bundle_export_for_agent_with_history_impl(
279 id_store: Arc<crate::backend::storage::store::Store>,
280 identity_store: Arc<crate::backend::storage::store::Store>,
281 mstore: &crate::backend::storage::store::Store,
282 transcripts: Option<Arc<crate::backend::storage::filestore::FileStore>>,
283 req: ExportForAgentWithHistoryReq,
284) -> Result<BundleExportWithHistoryResponse, String> {
285 let (export, agent, all_warnings, missing_skill_ids) = build_export_for_agent(
286 &id_store,
287 mstore,
288 &identity_store,
289 &req.bundle_id,
290 &req.agent_id,
291 "bundle.export_for_agent_with_history",
292 )
293 .await?;
294 let definition_id = agent.id.clone();
295
296 tokio::task::spawn_blocking(move || {
297 let mut export = export;
298 let mut all_warnings = all_warnings;
299 let mut included = 0u32;
300 let mut history_paths: Vec<String> = Vec::new();
301
302 match transcripts {
303 None => all_warnings.push("history: the history store is not available, so no conversation was included".to_string()),
304 Some(store) => {
305 let found = crate::backend::bundle_conversation::conversations(&store, &definition_id).unwrap_or_else(|e| {
306 all_warnings.push(format!("history: failed to list the conversations: {e}"));
307 Vec::new()
308 });
309 let known = found.len();
310
311 let mut sized = Vec::new();
314 for conversation in found {
315 if conversation.size.max(0) as u64 > MAX_HISTORY_SESSION_FILE_SIZE_BYTES {
316 all_warnings.push(format!(
317 "history: skipped {} — {} bytes exceeds the {} byte per-session limit",
318 conversation.path, conversation.size, MAX_HISTORY_SESSION_FILE_SIZE_BYTES
319 ));
320 } else {
321 sized.push(conversation);
322 }
323 }
324
325 let sizes: Vec<u64> = sized.iter().map(|c| c.size.max(0) as u64).collect();
327 let sized_count = sized.len();
328 let (fit_count, stopped_at_total_cap) = sessions_within_total_budget(&sizes, MAX_TOTAL_HISTORY_BYTES);
329 if stopped_at_total_cap {
330 let total: u64 = sizes[..fit_count].iter().sum();
331 all_warnings.push(format!(
332 "history: stopped after {total} bytes (limit {MAX_TOTAL_HISTORY_BYTES}) — {} additional session(s) omitted, oldest first",
333 sized_count - fit_count
334 ));
335 }
336
337 for conversation in sized.into_iter().take(fit_count) {
339 if crate::backend::transcript::damage::is_damaged(&conversation.zone) {
340 all_warnings.push(format!("history: skipped {} — the store found it damaged", conversation.path));
341 continue;
342 }
343 match crate::backend::bundle_conversation::render(&store, &conversation.zone) {
344 Ok(content) => {
345 export.files.push(crate::backend::bundle_export::BundleExportFile { path: conversation.path.clone(), content });
346 history_paths.push(conversation.path);
347 included += 1;
348 }
349 Err(e) => all_warnings.push(format!("history: failed to read {}: {e}", conversation.path)),
350 }
351 }
352 all_warnings.push(format!("history: included {included} of {known} known session(s)"));
353 }
354 }
355 if included > 0 {
356 all_warnings.push(
357 "history: this archive contains the agent's conversation, in the history store's compact form; keep it as private as the store itself"
358 .to_string(),
359 );
360 }
361
362 splice_history_component(&mut export, history_paths)
365 .map_err(|e| format!("bundle.export_for_agent_with_history: {e}"))?;
366
367 let zip_bytes = crate::backend::bundle_export::zip_bundle_export(&export)
368 .map_err(|e| format!("bundle.export_for_agent_with_history: {e}"))?;
369 use base64::Engine as _;
370 let encoded = base64::engine::general_purpose::STANDARD.encode(&zip_bytes);
371 Ok(BundleExportWithHistoryResponse {
372 root_slug: export.root_slug,
373 skipped_skills: export.skipped_skills,
374 warnings: all_warnings,
375 missing_skill_ids,
376 history_session_count: included,
377 zip_base64: encoded,
378 })
379 })
380 .await
381 .map_err(|e| format!("bundle.export_for_agent_with_history: blocking task panicked: {e}"))?
382}
383
384pub(super) fn register_bundle_export_for_agent(engine: &Arc<WshRpcEngine>, state: &AppState) {
385 let id_store = state.id_store.clone();
386 let mstore = state.mstore.clone();
387 let identity_store = state.identity_store.clone();
388 engine.register_typed(
389 COMMAND_BUNDLE_EXPORT_FOR_AGENT,
390 move |req: ExportForAgentReq, _ctx| {
391 let id_store = id_store.clone();
392 let mstore = mstore.clone();
393 let identity_store = identity_store.clone();
394 async move {
395 crate::backend::bundle_use::note("export_for_agent");
396 bundle_export_for_agent_impl(&id_store, &mstore, &identity_store, req).await
397 }
398 },
399 );
400}
401
402pub(super) fn register_bundle_export_for_agent_with_history(engine: &Arc<WshRpcEngine>, state: &AppState) {
403 let id_store = state.id_store.clone();
404 let identity_store = state.identity_store.clone();
405 let mstore = state.mstore.clone();
406 let transcripts = state.global_transcript_store.clone();
407 engine.register_typed(
408 COMMAND_BUNDLE_EXPORT_FOR_AGENT_WITH_HISTORY,
409 move |req: ExportForAgentWithHistoryReq, _ctx| {
410 let id_store = id_store.clone();
411 let identity_store = identity_store.clone();
412 let mstore = mstore.clone();
413 let transcripts = transcripts.clone();
414 async move {
415 crate::backend::bundle_use::note("export_for_agent_with_history");
416 bundle_export_for_agent_with_history_impl(id_store, identity_store, &mstore, transcripts, req).await
417 }
418 },
419 );
420}