Skip to main content

agentmux_srv/server/app_api/bundle/
export_for_agent.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `bundle.export_for_agent` / `bundle.export_for_agent_with_history`: build an
5//! ABF from a live agent definition, optionally with its session history under
6//! the size budgets defined here.
7
8use super::*;
9
10/// `bundle.export_for_agent` — ABF v0.2 §2.3. The only export path that
11/// carries native memory: pulls a bundle's normal components (identical to
12/// `bundle.export`) plus a snapshot of ONE agent's
13/// `db_agent_native_memory` rows, refreshed from the live filesystem
14/// first (see [`native_memory_handlers::refresh_memory_mirror_from_live_fs`]'s
15/// doc comment for why that refresh is required, not optional). `bundle.
16/// export` stays agent-less and memory-less — bundles are reusable across
17/// many agents by design, so memory (inherently per-agent) needs its own,
18/// explicitly-scoped entry point rather than an implicit "whichever agent
19/// happens to be attached" guess.
20#[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
30/// `bundle.export_for_agent` — ABF v0.2 §2.3. The only export path that
31/// carries native memory: pulls a bundle's normal components (identical to
32/// `bundle.export`) plus a snapshot of ONE agent's
33/// `db_agent_native_memory` rows, refreshed from the live filesystem
34/// first (see [`native_memory_handlers::refresh_memory_mirror_from_live_fs`]'s
35/// doc comment for why that refresh is required, not optional). `bundle.
36/// export` stays agent-less and memory-less — bundles are reusable across
37/// many agents by design, so memory (inherently per-agent) needs its own,
38/// explicitly-scoped entry point rather than an implicit "whichever agent
39/// happens to be attached" guess. Extracted from the RPC closure into a
40/// directly-callable, directly-testable function, matching
41/// `bundle_import_preview_impl`'s pattern.
42/// Shared by `bundle_export_for_agent_impl` and
43/// `bundle_export_for_agent_with_history_impl`: resolve the bundle + agent,
44/// build the base `BundleExport`, splice in native memory. Returns the
45/// export, the resolved agent (the history variant needs its id), combined
46/// warnings, and missing skill ids. Everything after this point (whether to
47/// zip, whether to also append history files) is caller-specific.
48pub(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    // Same resolver as the agent-less path, so the two cannot disagree about
71    // what the bundle contains.
72    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    // Always empty now — see the note at the agent-less export path.
76    let missing_skill_ids: Vec<String> = Vec::new();
77
78    // The hint names the agent this was exported from: the bundle itself
79    // carries no harness (SPEC_AGENT_BUNDLE_FORMAT_V0_3_2026_10_05.md §3.2).
80    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    // Refresh the mirror from the live FS, then read every mirrored
91    // file's content — this agent's memory, freshest as of right now,
92    // not as of whenever its Stash Bundle tab was last opened.
93    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                // reagent P2, PR #2527: surface truncation instead of
104                // silently exporting/importing a partial file.
105                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) => {} // deleted between list_meta and read — skip, not an error
120                    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    // Project instructions — carried as a record of what the source agent was
132    // reading, not as content to install. The working directory is resolved
133    // the same way launch resolves it, so the export describes the directory
134    // the agent actually runs in.
135    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/// Response for `bundle.export_for_agent_with_history`, which always zips.
194#[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
205/// Per-transcript size ceiling for `bundle.export_for_agent_with_history`.
206/// reagentx P1 on PR #2613: reading every session fully into a `String`
207/// with no bound could exhaust server memory for the multi-GB histories
208/// this feature exists to migrate. Unlike `MAX_ABF_FILE_SIZE_BYTES`
209/// (context files, truncated with a warning when oversized — fine, since
210/// a partial context file is still useful), a transcript is skipped
211/// ENTIRELY rather than truncated: JSONL requires whole lines, and a
212/// truncated mid-record file could fail to parse (or silently misparse)
213/// on the receiving end, which is worse than the session being visibly
214/// absent with a warning explaining why.
215pub(super) const MAX_HISTORY_SESSION_FILE_SIZE_BYTES: u64 = 200 * 1024 * 1024;
216
217/// Aggregate ceiling across every session included in one
218/// `bundle.export_for_agent_with_history` call. reagentx P1, third review
219/// round: a per-file cap alone doesn't bound an agent with many sessions
220/// each just under it — this is the analogous total cap the sibling
221/// import path already enforces (`MAX_TOTAL_UNCOMPRESSED_BYTES`,
222/// `bundle_import.rs`), sized larger since export's job is specifically
223/// to carry as much real history as reasonably fits, not to validate a
224/// small hand-authored bundle. Sessions are processed in
225/// `sessions_for_agent`'s existing `modified_at desc` order, so hitting
226/// this cap keeps the most recent conversations and cuts off the oldest
227/// — the same priority a human moving "my history" to a new machine would
228/// want. Unlike import's reject-the-whole-thing-on-overflow behavior,
229/// export keeps its existing best-effort philosophy: stop including
230/// further sessions and say so in a warning, never fail the call outright.
231pub(super) const MAX_TOTAL_HISTORY_BYTES: u64 = 500 * 1024 * 1024;
232
233/// Given per-session sizes already in priority order (most-recent-first,
234/// matching `sessions_for_agent`'s `modified_at desc` sort), decide how
235/// many fit within `total_cap`. Returns `(count_included, stopped_at_cap)`.
236/// Pure — no I/O — deliberately extracted so this decision is testable
237/// with tiny numbers instead of needing real `MAX_TOTAL_HISTORY_BYTES`-
238/// scale files on disk.
239pub(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
250/// `bundle.export_for_agent_with_history` —
251/// `docs/specs/SPEC_AGENT_IDENTITY_HISTORY_PERSISTENCE_PROTOCOL_2026_08_16.md`
252/// §3.3. Deliberately a SEPARATE, explicit, opt-in action from
253/// `bundle.export_for_agent` — see `COMMAND_BUNDLE_EXPORT_FOR_AGENT_WITH_HISTORY`'s
254/// doc comment for why conversation transcripts must never ride along in
255/// the default (shareable, reusable-across-agents) bundle export. Builds
256/// the identical base export, then appends the agent's conversation as the
257/// history store holds it (`bundle_conversation`): one `history/*.jsonl` file
258/// for the current session and one for each archived one, in the compact form.
259/// A provider's own session file is never read or included
260/// (`SPEC_HISTORY_COMPACT_FORM_ONLY_2026_11_23.md` §3, the bundle export row):
261/// it is a second raw copy of the conversation, removed by session id when a
262/// session ends. Always returns a zip — a multi-file, potentially large archive
263/// has no sensible inline-JSON shape, unlike the plain export's optional
264/// format. The archive is returned to the caller and AgentMux keeps no copy of
265/// it; the warnings say that it holds the conversation. A session that fails to
266/// render (damaged, or over `MAX_HISTORY_SESSION_FILE_SIZE_BYTES`) is warned
267/// about and skipped, never fails the whole export — same best-effort
268/// philosophy as the memory-splicing step above.
269///
270/// - the reads, the rendering, the zip and the base64 encode run inside their
271///   own `spawn_blocking` — synchronous, potentially slow I/O and CPU work
272///   that must not block the async RPC worker thread.
273/// - `MAX_TOTAL_HISTORY_BYTES` — a per-session cap alone doesn't bound an
274///   agent with MANY sessions each just under it; the sibling import path
275///   enforces an analogous total cap (`MAX_TOTAL_UNCOMPRESSED_BYTES`). The
276///   current session comes first, then the archives newest first, so the cap
277///   cuts the oldest. See `sessions_within_total_budget`.
278pub(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                // Pass 1: drop per-session-oversized ones. No reads yet — just the sizes the store
312                // reports, so the pure budget decision below can be tested with tiny numbers.
313                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                // Pass 2: how many of the (already newest-first) remaining sessions fit within the aggregate cap.
326                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                // Pass 3: render and include only what fit.
338                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        // §3.5: the files above are in the archive; say so in the manifest too.
363        // Must happen before zipping — the manifest (bundle.json) is zipped from export.files.
364        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}