1use super::*;
13use crate::server::api_error::ApiError;
14
15use crate::backend::rpc_types::BundleImportFileEntry as FileEntry;
20
21use crate::backend::rpc_types::{
26 BundleImportSkillSelection as SkillSelection,
27 CommandBundleImportCommitData as CommitReq,
28 CommandBundleImportPreviewData as PreviewReq,
29};
30
31mod components;
32mod export;
33mod export_for_agent;
34mod import;
35mod import_for_agent;
36
37#[cfg(test)]
38mod tests;
39
40use components::*;
41use export::*;
42use export_for_agent::*;
43use import::*;
44use import_for_agent::*;
45
46pub(crate) use components::purge_bundle_component_refs;
48pub(super) use components::resolve_bundle_components;
49pub(crate) use components::MEMORY_NOT_EXPORTED_WARNING;
50
51static BUNDLE_IMPORT_FOR_AGENT_LOCKS: std::sync::LazyLock<
58 std::sync::Mutex<std::collections::HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
59> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
60
61fn bundle_import_for_agent_lock(agent_id: &str) -> Arc<tokio::sync::Mutex<()>> {
62 let mut locks = BUNDLE_IMPORT_FOR_AGENT_LOCKS.lock().unwrap_or_else(|e| e.into_inner());
63 locks
64 .entry(agent_id.to_string())
65 .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
66 .clone()
67}
68
69pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
70 register_bundle_list(engine, state);
71 register_bundle_get(engine, state);
72 register_bundle_upsert(engine, state);
73 register_bundle_delete(engine, state);
74 register_bundle_self_get(engine, state);
75 register_bundle_export(engine, state);
76 register_bundle_import(engine, state);
77 register_bundle_import_preview(engine, state);
78 register_bundle_import_commit(engine, state);
79 register_bundle_export_for_agent(engine, state);
80 register_bundle_export_for_agent_with_history(engine, state);
81 register_bundle_import_for_agent(engine, state);
82 register_bundle_validate(engine, state);
83 register_agent_project_instructions(engine, state);
84}
85
86pub(super) fn normalize_bundle_upsert_input(mut data: serde_json::Value) -> serde_json::Value {
97 if let serde_json::Value::Object(ref mut map) = data {
98 match map.get("id") {
99 Some(serde_json::Value::String(_)) => {}
100 _ => {
101 map.insert("id".to_string(), serde_json::Value::String(String::new()));
102 }
103 }
104 for key in ["context_files", "mcp_servers", "skills"] {
105 if let Some(v) = map.get(key) {
106 if v.is_array() {
107 let encoded =
108 serde_json::to_string(v).unwrap_or_else(|_| "[]".to_string());
109 map.insert(key.to_string(), serde_json::Value::String(encoded));
110 }
111 }
112 }
113 }
114 data
115}
116
117#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
124#[ts(export, export_to = "../../../frontend/types/rpc/")]
125pub(crate) struct BundleListItem {
126 pub(crate) id: String,
127 pub(crate) name: String,
128 pub(crate) description: String,
129 pub(crate) provider: String,
130 pub(crate) model: String,
131 pub(crate) is_blank: bool,
132 #[ts(type = "number")]
133 pub(crate) updated_at: i64,
134}
135
136#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
139#[ts(export, export_to = "../../../frontend/types/rpc/")]
140pub(crate) struct BundleListResponse {
141 pub(crate) bundles: Vec<BundleListItem>,
142 pub(crate) presets: Vec<BundleListItem>,
143}
144
145fn register_bundle_list(engine: &Arc<WshRpcEngine>, state: &AppState) {
146 let state = state.clone();
147 engine.register_typed(COMMAND_BUNDLE_LIST, move |_req: Option<NoArgsReq>, _ctx| {
148 let state = state.clone();
149 async move { bundle_list_impl(&state).await.map_err(|e| e.to_string()) }
150 });
151}
152
153#[derive(serde::Deserialize, Default, ts_rs::TS)]
154#[ts(export, export_to = "../../../frontend/types/rpc/")]
155pub(super) struct BundleGetReq {
156 #[serde(default)]
157 #[ts(as = "Option<String>", optional)]
158 id: String,
159 #[serde(default)]
160 #[ts(as = "Option<String>", optional)]
161 name: String,
162}
163
164fn register_bundle_get(engine: &Arc<WshRpcEngine>, state: &AppState) {
165 let state = state.clone();
166 engine.register_typed(COMMAND_BUNDLE_GET, move |req: BundleGetReq, _ctx| {
167 let state = state.clone();
168 async move { bundle_get_impl(&state, &req.id, &req.name).await.map_err(|e| e.to_string()) }
169 });
170}
171
172fn register_bundle_validate(engine: &Arc<WshRpcEngine>, _state: &AppState) {
187 engine.register_typed(COMMAND_BUNDLE_VALIDATE, |data: serde_json::Value, _ctx| async move {
190 bundle_validate_impl(data)
191 });
192}
193
194fn register_bundle_upsert(engine: &Arc<WshRpcEngine>, state: &AppState) {
195 let make = |state: &AppState| {
196 let id_store = state.id_store.clone();
197 let broker = state.broker.clone();
198 move |data: serde_json::Value, _ctx: RpcContext| {
201 let id_store = id_store.clone();
202 let broker = broker.clone();
203 async move {
204 let mut memory: Bundle =
205 serde_json::from_value(normalize_bundle_upsert_input(data))
206 .map_err(|e| format!("bundle.upsert: {e}"))?;
207
208 if memory.id == "blank" || memory.id.starts_with("seed-") || memory.is_blank {
211 return Err("FORBIDDEN: cannot mutate a protected bundle".to_string());
212 }
213 if !memory.id.is_empty() {
216 if let Some(existing) = id_store.bundle_get(&memory.id)
217 .map_err(|e| format!("bundle.upsert: {e}"))?
218 {
219 if existing.is_global {
220 return Err("FORBIDDEN: cannot mutate a global bundle".to_string());
221 }
222 }
226 }
227 if memory.id.is_empty() {
228 memory.id = uuid::Uuid::new_v4().to_string();
229 }
230 memory.is_global = false;
232 memory.sort_order = 0;
233
234 let now = agentmux_common::time::now_ms();
235 if memory.created_at == 0 { memory.created_at = now; }
236 memory.updated_at = now;
237
238 id_store.bundle_upsert(&memory)
239 .map_err(|e| format!("bundle.upsert: {e}"))?;
240 broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
241 Ok(memory)
242 }
243 }
244 };
245 engine.register_typed(COMMAND_BUNDLE_UPSERT, make(state));
246}
247
248fn register_bundle_delete(engine: &Arc<WshRpcEngine>, state: &AppState) {
249 let make = |state: &AppState| {
250 let id_store = state.id_store.clone();
251 let mstore = state.mstore.clone();
252 let broker = state.broker.clone();
253 move |req: CommandDeleteBundleData, _ctx: RpcContext| {
255 let id_store = id_store.clone();
256 let mstore = mstore.clone();
257 let broker = broker.clone();
258 async move {
259 if req.id == "blank" {
260 return Err("FORBIDDEN: cannot delete a seeded bundle".to_string());
261 }
262
263 match id_store.bundle_delete(&req.id) {
264 Ok(deleted) => {
265 if deleted {
266 purge_bundle_component_refs(&mstore, &req.id);
267 broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
268 }
269 Ok(DeleteBundleResult { deleted })
270 }
271 Err(crate::backend::storage::error::StoreError::Other(msg))
272 if msg.contains("seed") || msg.contains("seeded") =>
273 {
274 Err(format!("FORBIDDEN: cannot delete a seeded bundle"))
275 }
276 Err(e) => Err(format!("bundle.delete: {e}")),
277 }
278 }
279 }
280 };
281 engine.register_typed(COMMAND_BUNDLE_DELETE, make(state));
282}
283
284#[derive(serde::Deserialize, ts_rs::TS)]
285#[ts(export, export_to = "../../../frontend/types/rpc/")]
286pub(super) struct BundleSelfGetReq { agent_id: String }
287
288fn register_bundle_self_get(engine: &Arc<WshRpcEngine>, state: &AppState) {
289 let state = state.clone();
290 engine.register_typed(COMMAND_BUNDLE_SELF_GET, move |req: BundleSelfGetReq, ctx| {
291 let state = state.clone();
292 async move {
293 check_s1(&state.mstore, &ctx, &req.agent_id)?;
294 bundle_self_get_impl(&state, &req.agent_id).await.map_err(|e| e.to_string())
295 }
296 });
297}
298
299fn resolve_agent_for_s1(
313 state: &AppState,
314 agent_id: &str,
315) -> Result<crate::backend::storage::AgentDefinition, String> {
316 let def_id = resolve_agent_definition_id(state, agent_id)?;
317 state
318 .mstore
319 .agent_def_get(&def_id)
320 .map_err(|e| e.to_string())?
321 .ok_or_else(|| format!("no agent with slug or id {agent_id}"))
322}
323
324#[derive(serde::Deserialize, ts_rs::TS)]
325#[ts(export, export_to = "../../../frontend/types/rpc/")]
326pub(super) struct AgentProjectInstructionsReq {
327 agent_id: String,
328}
329
330#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
334#[ts(export, export_to = "../../../frontend/types/rpc/")]
335pub(super) struct AgentProjectInstructionFile {
336 path: String,
337 exists: bool,
338 #[ts(type = "number")]
339 size_bytes: u64,
340 content_hash: String,
341 owner: String,
343 content: String,
344 truncated: bool,
345 error: Option<String>,
346 change: crate::backend::storage::project_instructions::InstructionChange,
347 #[ts(type = "number | null")]
349 last_observed_at: Option<i64>,
350}
351
352#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
354#[ts(export, export_to = "../../../frontend/types/rpc/")]
355pub(super) struct AgentProjectInstructionsResponse {
356 provider: String,
357 working_directory: String,
358 files: Vec<AgentProjectInstructionFile>,
359}
360
361fn register_agent_project_instructions(engine: &Arc<WshRpcEngine>, state: &AppState) {
375 let make = |state: AppState| {
376 move |req: AgentProjectInstructionsReq, ctx: RpcContext| {
377 let state = state.clone();
378 async move {
379 check_s1(&state.mstore, &ctx, &req.agent_id)?;
380
381 let agent = resolve_agent_for_s1(&state, &req.agent_id)
382 .map_err(|e| format!("agent.project_instructions: {e}"))?;
383
384 let work_dir = crate::backend::project_instructions::effective_working_dir(
389 &agent.working_directory,
390 &agent.name,
391 );
392 let files = crate::backend::project_instructions::resolve_project_instructions(
393 &agent.provider,
394 &work_dir,
395 );
396
397 let previous = state
405 .mstore
406 .project_instructions_list(&agent.id)
407 .unwrap_or_default();
408 let mut enriched: Vec<AgentProjectInstructionFile> = files
409 .iter()
410 .map(|f| {
411 let prev = previous.iter().find(|p| p.path == f.path);
412 let change = crate::backend::storage::project_instructions::classify_change(
413 prev,
414 f.exists,
415 &f.content_hash,
416 );
417 AgentProjectInstructionFile {
418 path: f.path.clone(),
419 exists: f.exists,
420 size_bytes: f.size_bytes,
421 content_hash: f.content_hash.clone(),
422 owner: match f.owner {
423 crate::backend::project_instructions::InstructionOwner::Agentmux => "agentmux",
424 crate::backend::project_instructions::InstructionOwner::Foreign => "foreign",
425 }
426 .to_string(),
427 content: f.content.clone(),
428 truncated: f.truncated,
429 error: f.error.clone(),
430 change,
431 last_observed_at: prev.map(|p| p.observed_at),
432 }
433 })
434 .collect();
435
436 for prev in previous.iter().filter(|p| !files.iter().any(|f| f.path == p.path)) {
444 let change = crate::backend::storage::project_instructions::classify_change(
445 Some(prev),
446 false,
447 "",
448 );
449 enriched.push(AgentProjectInstructionFile {
450 path: prev.path.clone(),
451 exists: false,
452 size_bytes: 0,
453 content_hash: String::new(),
454 owner: prev.owner.clone(),
455 content: String::new(),
456 truncated: false,
457 error: None,
458 change,
459 last_observed_at: Some(prev.observed_at),
460 });
461 }
462
463 Ok(AgentProjectInstructionsResponse {
464 provider: agent.provider,
465 working_directory: work_dir,
466 files: enriched,
467 })
468 }
469 }
470 };
471 engine.register_typed(COMMAND_AGENT_PROJECT_INSTRUCTIONS, make(state.clone()));
472}
473
474struct RequirementResolution {
487 id: String,
488 provider: String,
489 env: String,
490 match_count: usize,
491}
492
493impl RequirementResolution {
494 fn resolved(&self) -> bool {
495 self.match_count == 1
496 }
497}
498
499fn resolve_account_requirements(
500 id_store: &crate::backend::storage::store::Store,
501 requirements: &[crate::backend::bundle_import::AccountRequirement],
502) -> Result<Vec<RequirementResolution>, String> {
503 let mut results: Vec<RequirementResolution> = Vec::new();
504 let mut match_count_by_provider: std::collections::HashMap<&str, usize> =
505 std::collections::HashMap::new();
506 for requirement in requirements {
507 let match_count = match match_count_by_provider.get(requirement.provider.as_str()) {
508 Some(&n) => n,
509 None => {
510 let n = id_store
514 .identity_list(Some(&requirement.provider))
515 .map_err(|e| format!("account lookup failed: {e}"))?
516 .len();
517 match_count_by_provider.insert(requirement.provider.as_str(), n);
518 n
519 }
520 };
521 results.push(RequirementResolution {
522 id: requirement.id.clone(),
523 provider: requirement.provider.clone(),
524 env: requirement.env.clone(),
525 match_count,
526 });
527 }
528 Ok(results)
529}
530
531fn bounded_display(s: &str) -> String {
539 crate::backend::bundle_import::truncate_display(s, crate::backend::bundle_import::MAX_DISPLAY_FIELD_CHARS)
540}
541
542pub(crate) async fn bundle_list_impl(state: &AppState) -> Result<BundleListResponse, ApiError> {
543 let memories = state.id_store.bundle_list().map_err(|e| format!("bundle.list: {e}"))?;
544 let bundles: Vec<BundleListItem> = memories.into_iter().map(|m| BundleListItem {
545 id: m.id, name: m.name, description: m.description,
546 provider: m.provider, model: m.model, is_blank: m.is_blank, updated_at: m.updated_at,
547 }).collect();
548 Ok(BundleListResponse { presets: bundles.clone(), bundles })
554}
555
556pub(crate) async fn bundle_get_impl(
557 state: &AppState,
558 id: &str,
559 name: &str,
560) -> Result<Bundle, ApiError> {
561 let memory = if !id.is_empty() {
562 state.id_store.bundle_get(id).map_err(|e| format!("bundle.get: {e}"))?
563 .ok_or_else(|| ApiError::not_found(format!("bundle.get: not found id={id}")))?
564 } else if !name.is_empty() {
565 let all = state.id_store.bundle_list().map_err(|e| format!("bundle.get: {e}"))?;
566 all.into_iter().filter(|m| m.name == name).max_by_key(|m| m.updated_at)
567 .ok_or_else(|| ApiError::not_found(format!("bundle.get: not found name={name}")))?
568 } else {
569 return Err(ApiError::bad_request("bundle.get: provide id or name"));
570 };
571 Ok(memory)
572}
573
574pub(crate) fn bundle_validate_impl(
585 data: serde_json::Value,
586) -> Result<crate::backend::bundle_validate::ValidationReport, String> {
587 let memory: Bundle = serde_json::from_value(bundle::normalize_bundle_upsert_input(data))
588 .map_err(|e| format!("bundle.validate: {e}"))?;
589 Ok(crate::backend::bundle_validate::validate_bundle(&memory))
590}
591
592pub(crate) async fn bundle_self_get_impl<'o>(
593 state: &AppState,
594 owner: impl Into<SelfOwner<'o>>,
595) -> Result<Bundle, ApiError> {
596 let agent_id = match owner.into() {
597 SelfOwner::Slug(slug) => slug,
598 SelfOwner::Uid(uid) => {
602 let row = SelfOwner::caller_row(uid, &state.mstore).map_err(|e| e.under("bundle.self.get"))?;
603 let launch = state.mstore.instance_get(uid)
607 .map_err(|e| format!("bundle.self.get: {e}"))?;
608 let memory_id = launch
609 .map(|i| i.memory_id)
610 .filter(|m| !m.is_empty())
611 .or_else(|| {
612 crate::backend::agent_registry_lookup::find_active_record_by_slug_and_definition(
613 &row.slug, &row.id,
614 )
615 .and_then(|rec| rec.data.memory_id)
616 });
617 return bundle_self_get_by_memory_id(state, memory_id);
618 }
619 };
620 let instance = state.mstore.instance_get_by_slug(agent_id)
621 .map_err(|e| format!("bundle.self.get: {e}"))?;
622 let memory_id = instance.as_ref()
632 .and_then(|i| if i.memory_id.is_empty() { None } else { Some(i.memory_id.clone()) })
633 .or_else(|| {
634 crate::server::native_memory_handlers::find_active_registry_record_by_slug(agent_id)
635 .and_then(|rec| rec.data.memory_id)
636 });
637 bundle_self_get_by_memory_id(state, memory_id)
638}
639
640fn bundle_self_get_by_memory_id(
642 state: &AppState,
643 memory_id: Option<String>,
644) -> Result<Bundle, ApiError> {
645 let memory = if let Some(mid) = memory_id {
646 state.id_store.bundle_get(&mid).map_err(|e| format!("bundle.self.get: {e}"))?
647 .ok_or_else(|| ApiError::not_found(format!("bundle.self.get: memory_id {mid} not found")))?
648 } else {
649 let all = state.id_store.bundle_list().map_err(|e| format!("bundle.self.get: {e}"))?;
652 let blank_id = all.into_iter().find(|m| m.is_blank).map(|m| m.id)
653 .ok_or_else(|| ApiError::internal("bundle.self.get: blank singleton not found"))?;
654 state.id_store.bundle_get(&blank_id).map_err(|e| format!("bundle.self.get: {e}"))?
655 .ok_or_else(|| ApiError::internal("bundle.self.get: blank singleton row missing"))?
656 };
657 Ok(memory)
658}
659
660#[derive(Debug, Clone, Copy)]
665pub(crate) enum SelfOwner<'a> {
666 Uid(&'a str),
673 Slug(&'a str),
677}
678
679impl<'a> From<&'a str> for SelfOwner<'a> {
680 fn from(slug: &'a str) -> Self {
681 Self::Slug(slug)
682 }
683}
684
685impl<'a> From<&'a String> for SelfOwner<'a> {
686 fn from(slug: &'a String) -> Self {
687 Self::Slug(slug)
688 }
689}
690
691impl<'a> SelfOwner<'a> {
692 pub(crate) fn of(
699 caller: Option<&'a crate::server::caller::Caller>,
700 slug: &'a str,
701 by_name_counter: &'static str,
702 ) -> Self {
703 match caller.and_then(crate::server::caller::Caller::uid) {
704 Some(uid) => Self::Uid(uid),
705 None => {
706 crate::backend::agent_resolve::record_uid_fallback(by_name_counter);
707 Self::Slug(slug)
708 }
709 }
710 }
711
712 pub(super) fn label(self) -> &'a str {
714 match self {
715 Self::Uid(v) | Self::Slug(v) => v,
716 }
717 }
718
719 pub(crate) fn caller_row(
723 uid: &str,
724 mstore: &crate::backend::storage::store::Store,
725 ) -> Result<crate::backend::storage::AgentDefinition, ApiError> {
726 mstore
727 .agent_def_get(uid)
728 .map_err(|e| format!("store: {e}"))?
729 .ok_or_else(|| ApiError::not_found(format!("calling agent {uid} not found")))
730 }
731
732 pub(super) fn dir(self, mstore: &crate::backend::storage::store::Store) -> Result<std::path::PathBuf, ApiError> {
734 match self {
735 Self::Uid(uid) => {
736 let agent = Self::caller_row(uid, mstore).map_err(|e| e.under("memory"))?;
737 crate::server::native_memory_handlers::memory_dir_for_agent_by_id(mstore, &agent)
738 .ok_or_else(|| ApiError::not_found(format!("memory: memory directory for agent {uid} not found")))
739 }
740 Self::Slug(slug) => Ok(crate::server::native_memory_handlers::memory_dir_for_agent(mstore, slug)?),
741 }
742 }
743
744 pub(super) fn dir_for_write(self, mstore: &crate::backend::storage::store::Store) -> Result<std::path::PathBuf, ApiError> {
747 let id = self.owner_id(mstore).map_err(|e| e.under("memory"))?;
748 match mstore.agent_def_get(&id).map_err(|e| format!("memory: store: {e}"))? {
749 Some(agent) => Ok(crate::server::native_memory_handlers::memory_dir_for_write_by_id(mstore, &agent)
750 .map_err(|e| format!("memory: {e}"))?),
751 None => crate::server::native_memory_handlers::memory_dir_from_spawn(&id).ok_or_else(|| {
754 ApiError::conflict(format!(
755 "memory: agent {} has no local row and no spawn on record, so its memory directory \
756 can't be verified for a write",
757 self.label()
758 ))
759 }),
760 }
761 }
762
763 pub(super) fn owner_id(self, mstore: &crate::backend::storage::store::Store) -> Result<String, ApiError> {
766 match self {
767 Self::Uid(uid) => Self::caller_row(uid, mstore).map(|row| row.id),
768 Self::Slug(slug) => Ok(crate::server::native_memory_handlers::resolve_agent_uuid(mstore, slug)?),
769 }
770 }
771}