Skip to main content

agentmux_srv/server/agent_handlers/
core.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4
5use std::sync::Arc;
6use chrono::Utc;
7
8use crate::backend::rpc::engine::WshRpcEngine;
9use crate::backend::rpc_types::{
10    COMMAND_LIST_AGENTS, COMMAND_CREATE_AGENT, COMMAND_UPDATE_AGENT,
11    COMMAND_DELETE_AGENT, COMMAND_GET_AGENT_CONTENT, COMMAND_SET_AGENT_CONTENT,
12    COMMAND_GET_ALL_AGENT_CONTENT,
13    COMMAND_IMPORT_AGENT_FROM_CLAW, COMMAND_IMPORT_AGENTS, COMMAND_EXPORT_AGENTS,
14    COMMAND_RESEED_AGENTS,
15    COMMAND_CONTAINER_RUNTIME_AVAILABLE, COMMAND_CONTAINER_IMAGE_CHECK, COMMAND_UPDATE_CONTAINER,
16    CommandUpdateContainerData, UpdateContainerResult,
17    COMMAND_CLEAR_CONTAINER_CACHES, COMMAND_GET_CONTAINER_CACHES, COMMAND_GET_CONTAINER_LIMITS, COMMAND_SET_CONTAINER_LIMITS,
18    CommandContainerCachesData, CommandGetContainerLimitsData, CommandSetContainerLimitsData,
19    CommandContainerImageCheckData, ContainerImageCheckResult,
20    CommandListAgentDefinitionsData,
21    CommandContainerRuntimeAvailableData, CommandReseedAgentsData, CommandExportAgentsData,
22    ContainerRuntimeAvailableResult, ReseedAgentsResult,
23    CommandCreateAgentDefinitionData, CommandUpdateAgentDefinitionData, CommandDeleteAgentDefinitionData,
24    CommandGetAgentContentData, CommandSetAgentContentData, CommandGetAllAgentContentData,
25    CommandImportAgentFromClawData,
26    CommandImportAgentDefinitionsData, ImportAgentDefinitionsResult,
27    ExportAgentDefinitionsResult, AgentDefinitionExport, AgentSkillExport,
28};
29use crate::backend::storage::{AgentDefinition, AgentContent, AgentSkill};
30
31use super::super::AppState;
32
33pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
34    register_definition_handlers(engine, state);
35    register_container_handlers(engine, state);
36    register_content_handlers(engine, state);
37    register_import_export_handlers(engine, state);
38}
39
40fn register_definition_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
41    // listagents → return all agent definitions, optionally filtered by
42    // `is_seeded`. Filter input is backward-compatible: callers that
43    // pass `null` / `{}` (every existing caller) get the full list.
44    // The two-tier picker (Phase 1) passes `{ is_seeded: 0 }` for the
45    // "My Agents" section and `{ is_seeded: 1 }` for the "Templates"
46    // section — see SPEC_AGENT_PICKER_TWO_TIER_2026_05_24.md.
47    //
48    // Phase 2 (Q2 Decision Y — hide templates): templates with
49    // `user_hidden = 1` are filtered out by default. Callers that want
50    // them back (the settings panel's "Hidden templates" surface) pass
51    // `include_hidden: true`. Hide filter applies ONLY to templates —
52    // user-owned definitions are unaffected (their `user_hidden` is
53    // always 0 by backend invariant; `agent_def_set_hidden` rejects
54    // non-template ids).
55    let mstore_lfa = state.mstore.clone();
56    // NOT migrated to `register_typed`, deliberately. `register_typed`
57    // deserializes the payload strictly and answers Err on failure, but this
58    // command tolerates a null/malformed body on purpose: older clients never
59    // sent one, and the server defaults a missing `data` field to
60    // `Value::Null`, which cannot deserialize into a struct. Typing it would
61    // turn "older client asks for the unfiltered list" into an RPC error.
62    //
63    // Same rule as `bundle.validate` and `widget.health`: a handler that
64    // deliberately accepts loose input keeps its `Value` request. Its RESPONSE
65    // is still `Vec<AgentDefinition>`, which IS generated -- that is where the
66    // drift risk lived.
67    engine.register_typed(COMMAND_LIST_AGENTS, move |data: serde_json::Value, _ctx| {
68        list_agents(data, mstore_lfa.clone())
69    });
70
71    // createagent → insert new agent, broadcast agents:changed
72    let mstore_cfa = state.mstore.clone();
73    let broker_cfa = state.broker.clone();
74    engine.register_typed(COMMAND_CREATE_AGENT, move |cmd: CommandCreateAgentDefinitionData, ctx| {
75        create_agent(cmd, mstore_cfa.clone(), broker_cfa.clone(), is_the_window(&ctx))
76    });
77
78    // updateagent → update existing agent, broadcast agents:changed
79    let mstore_ufa = state.mstore.clone();
80    let broker_ufa = state.broker.clone();
81    engine.register_typed(COMMAND_UPDATE_AGENT, move |cmd: CommandUpdateAgentDefinitionData, ctx| {
82        update_agent(cmd, mstore_ufa.clone(), broker_ufa.clone(), is_the_window(&ctx))
83    });
84
85    // deleteagent → delete agent by id, broadcast agents:changed
86    let state_dfa = state.clone();
87    engine.register_typed(
88        COMMAND_DELETE_AGENT,
89        move |cmd: CommandDeleteAgentDefinitionData, _ctx| {
90            let state = state_dfa.clone();
91            async move { delete_agent_definition(&state, &cmd.id, "deleteagent").await }
92        },
93    );
94}
95
96fn register_container_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
97    // containerruntimeavailable → does the Docker DAEMON answer a ping
98    // right now? Returns `{ available: bool }`. The create-from-template
99    // modal (via the frontend's shared toolchain-capabilities store) uses
100    // this to gate/default the container runtime. Distinct from
101    // `resolvecli docker`, which only confirms the CLI binary is on PATH —
102    // that false-positives when Docker is installed but the daemon is
103    // stopped, steering users into a container agent that can't start
104    // (codex P1 on #1576). `ContainerRuntimeHandle::is_available()` retries
105    // the connection on demand, so a daemon that came up or went down
106    // since launch is reflected without an app restart.
107    let container_manager_cra = state.container_manager.clone();
108    engine.register_typed(
109        COMMAND_CONTAINER_RUNTIME_AVAILABLE,
110        move |_cmd: Option<CommandContainerRuntimeAvailableData>, _ctx| {
111            let cm = container_manager_cra.clone();
112            async move {
113                let available = cm.is_available().await;
114                let (runtime, detail) = if available {
115                    (cm.runtime_label().await, None)
116                } else {
117                    (None, cm.missing_message())
118                };
119                Ok(ContainerRuntimeAvailableResult { available, runtime, detail })
120            }
121        },
122    );
123
124    // updatecontainer → remove the container so the next message starts it from the current
125    // agent image; refused while a turn runs (`app_api::container_update`).
126    let state_uc = state.clone();
127    engine.register_typed(COMMAND_UPDATE_CONTAINER, move |cmd: CommandUpdateContainerData, _ctx| {
128        let state = state_uc.clone();
129        async move {
130            let image_version = crate::server::app_api::container_update::update_for_block(&state, &cmd.block_id).await?;
131            Ok(UpdateContainerResult { image_version })
132        }
133    });
134
135    // getcontainerlimits / setcontainerlimits → a container agent's CPU and memory limits
136    // (`app_api::container_limits`); the operator's client sets them, an agent uses MuxAPI.
137    let state_gl = state.clone();
138    engine.register_typed(COMMAND_GET_CONTAINER_LIMITS, move |cmd: CommandGetContainerLimitsData, _ctx| {
139        let state = state_gl.clone();
140        async move {
141            let (uid, _def) = crate::server::app_api::container_limits::container_agent(&state, &cmd.agent_id).map_err(|(_, m)| m)?;
142            crate::server::app_api::container_limits::view(&state, &uid, None).await.map_err(|(_, m)| m)
143        }
144    });
145    let state_sl = state.clone();
146    engine.register_typed(COMMAND_SET_CONTAINER_LIMITS, move |cmd: CommandSetContainerLimitsData, ctx| {
147        let state = state_sl.clone();
148        async move {
149            ctx.operator_only("only the operator's client changes container limits here; an agent uses Agents set_container_limits")?;
150            let (uid, def) = crate::server::app_api::container_limits::container_agent(&state, &cmd.agent_id).map_err(|(_, m)| m)?;
151            let (memory, cpus) = (cmd.memory_mb.map(serde_json::Value::String), cmd.cpus.map(serde_json::Value::String));
152            crate::server::app_api::container_limits::set(&state, &uid, &def, memory.as_ref(), cpus.as_ref(), "you")
153                .await
154                .map_err(|(_, m)| m)
155        }
156    });
157    // getcontainercaches / clearcontainercaches → a container agent's cache volumes (`app_api::container_caches`);
158    // the operator's client clears them, an agent uses MuxAPI.
159    let state_gc = state.clone();
160    engine.register_typed(COMMAND_GET_CONTAINER_CACHES, move |cmd: CommandContainerCachesData, _ctx| {
161        let state = state_gc.clone();
162        async move {
163            let (uid, _def) = crate::server::app_api::container_limits::container_agent(&state, &cmd.agent_id).map_err(|(_, m)| m)?;
164            crate::server::app_api::container_caches::view(&state, &uid).await.map_err(|(_, m)| m)
165        }
166    });
167    let state_cc = state.clone();
168    engine.register_typed(COMMAND_CLEAR_CONTAINER_CACHES, move |cmd: CommandContainerCachesData, ctx| {
169        let state = state_cc.clone();
170        async move {
171            ctx.operator_only("only the operator's client clears a container's caches here; an agent uses Agents container_caches")?;
172            let (uid, _def) = crate::server::app_api::container_limits::container_agent(&state, &cmd.agent_id).map_err(|(_, m)| m)?;
173            crate::server::app_api::container_caches::clear(&state, &uid).await.map_err(|(_, m)| m)
174        }
175    });
176    // containerimagecheck → can this image be had on this machine? Answers from
177    // the daemon's own cache first, then an anonymous registry check, so the
178    // create modal does not preselect a container that cannot start.
179    let container_manager_cic = state.container_manager.clone();
180    engine.register_typed(
181        COMMAND_CONTAINER_IMAGE_CHECK,
182        move |cmd: Option<CommandContainerImageCheckData>, _ctx| {
183            let cm = container_manager_cic.clone();
184            async move {
185                let image = cmd.unwrap_or_default().image;
186                let manager = cm.get().await;
187                let status = crate::backend::container::image::check_image_access(manager.as_ref(), &image).await;
188                Ok(ContainerImageCheckResult { status })
189            }
190        },
191    );
192}
193
194fn register_content_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
195    // getagentcontent → return a single content blob for an agent
196    let mstore_gfc = state.mstore.clone();
197    engine.register_typed(
198        COMMAND_GET_AGENT_CONTENT,
199        move |cmd: CommandGetAgentContentData, _ctx| {
200            let mstore = mstore_gfc.clone();
201            async move {
202                let content = mstore.agent_content_get(&cmd.agent_id, &cmd.content_type)
203                    .map_err(|e| format!("getagentcontent: {e}"))?;
204                // `Option<AgentContent>`, not a hand-serialized Value: the schema
205                // registry records the Resp type, so serializing here would have it
206                // record `Value` and leave this one endpoint outside the drift net.
207                // Serializes identically -- `None` is JSON null, matching the stub's
208                // `Promise<AgentContent | null>`.
209                Ok(content)
210            }
211        },
212    );
213
214    // setagentcontent → upsert a content blob, broadcast agentcontent:changed
215    let mstore_sfc = state.mstore.clone();
216    let broker_sfc = state.broker.clone();
217    engine.register_typed(
218        COMMAND_SET_AGENT_CONTENT,
219        move |cmd: CommandSetAgentContentData, _ctx| {
220            let mstore = mstore_sfc.clone();
221            let broker = broker_sfc.clone();
222            async move {
223                crate::server::app_api::agent_spawn::client_may_write_content(&cmd.content_type)
224                    .map_err(|e| format!("setagentcontent: {e}"))?;
225                let now = agentmux_common::time::now_ms();
226                let content = AgentContent {
227                    agent_id: cmd.agent_id,
228                    content_type: cmd.content_type,
229                    content: cmd.content,
230                    updated_at: now,
231                };
232                mstore.agent_content_set(&content).map_err(|e| format!("setagentcontent: {e}"))?;
233                broker.publish_event::<crate::backend::mps_events::AgentContentChanged>(&(), vec![], 0);
234                Ok(content)
235            }
236        },
237    );
238
239    // getallagentcontent → return all content blobs for an agent
240    let mstore_gafc = state.mstore.clone();
241    engine.register_typed(
242        COMMAND_GET_ALL_AGENT_CONTENT,
243        move |cmd: CommandGetAllAgentContentData, _ctx| {
244            let mstore = mstore_gafc.clone();
245            async move {
246                let contents = mstore.agent_content_get_all(&cmd.agent_id)
247                    .map_err(|e| format!("getallagentcontent: {e}"))?;
248                Ok(contents)
249            }
250        },
251    );
252
253    // ── Agent Import handler ───────────────────────────────────────────────
254
255    // importagentfromclaw → read claw workspace, create agent + content
256    let mstore_ifc = state.mstore.clone();
257    let broker_ifc = state.broker.clone();
258    engine.register_typed(COMMAND_IMPORT_AGENT_FROM_CLAW, move |cmd: CommandImportAgentFromClawData, _ctx| {
259        import_agent_from_claw(cmd, mstore_ifc.clone(), broker_ifc.clone())
260    });
261
262    // reseedagents → delete all seeded agents and re-run seed from manifest
263    let mstore_rsfa = state.mstore.clone();
264    let broker_rsfa = state.broker.clone();
265    engine.register_typed(
266        COMMAND_RESEED_AGENTS,
267        move |_cmd: Option<CommandReseedAgentsData>, _ctx| {
268            let mstore = mstore_rsfa.clone();
269            let broker = broker_rsfa.clone();
270            async move {
271                // Delete all previously seeded agents (cascade deletes content, skills, history)
272                let deleted = mstore.agent_def_delete_seeded()
273                    .map_err(|e| format!("reseedagents: delete seeded: {e}"))?;
274
275                // Re-run seed
276                let report = crate::backend::agent_seed::seed_agents(&mstore)
277                    .map_err(|e| format!("reseedagents: seed: {e}"))?;
278
279                broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
280                Ok(ReseedAgentsResult {
281                    deleted,
282                    created: report.created,
283                    skipped: report.skipped,
284                })
285            }
286        },
287    );
288}
289
290fn register_import_export_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
291    // importagents — bulk import from JSON export format
292    let mstore_ifa = state.mstore.clone();
293    let broker_ifa = state.broker.clone();
294    engine.register_typed(COMMAND_IMPORT_AGENTS, move |cmd: CommandImportAgentDefinitionsData, _ctx| {
295        import_agents(cmd, mstore_ifa.clone(), broker_ifa.clone())
296    });
297
298    // exportagents — export all agent definitions with content and skills
299    let mstore_efa = state.mstore.clone();
300    let id_store_efa = state.id_store.clone();
301    engine.register_typed(COMMAND_EXPORT_AGENTS, move |_cmd: Option<CommandExportAgentsData>, _ctx| {
302        export_agents(mstore_efa.clone(), id_store_efa.clone())
303    });
304}
305
306async fn list_agents(
307    data: serde_json::Value,
308    mstore: Arc<crate::backend::storage::store::Store>,
309) -> Result<Vec<AgentDefinition>, String> {
310    // unwrap_or_default — both `null` and `{}` deserialize
311    // to the default (no filter). Anything malformed falls
312    // back to no-filter rather than erroring; older clients
313    // never sent a body for this RPC and we can't know
314    // which JSON shape they're on.
315    let cmd: CommandListAgentDefinitionsData =
316        serde_json::from_value(data).unwrap_or_default();
317    let agents = mstore.agent_def_list().map_err(|e| format!("listagents: {e}"))?;
318    let is_seeded_filter = cmd.is_seeded;
319    let include_hidden = cmd.include_hidden;
320    let filtered: Vec<_> = agents
321        .into_iter()
322        .filter(|a| match is_seeded_filter {
323            Some(flag) => a.is_seeded == flag,
324            None => true,
325        })
326        // Default behaviour: drop hidden templates. The
327        // settings panel opts back in with include_hidden.
328        // User-owned rows (is_seeded == 0) are never
329        // hideable; the conditional below is a no-op for
330        // them.
331        .filter(|a| {
332            include_hidden || a.is_seeded != 1 || a.user_hidden == 0
333        })
334        .collect();
335    let mut filtered = filtered;
336    // A spawned worker with no seat of its own shows its leader
337    // as its lead (SPEC_AGENT_SEATS_IN_THE_UI_2026_10_23.md §2).
338    crate::backend::agent_seat::apply_effective_seats(&mstore, &mut filtered);
339    Ok(filtered)
340}
341
342/// Whether the call is the AgentMux window's own. It has no editor for an agent's folders to ask in: a host agent that
343/// shares a folder with a container agent is asked about when it is opened (`folder_overlap`), so only a caller that is
344/// not the window is refused when it saves one.
345fn is_the_window(ctx: &crate::backend::rpc_types::RpcContext) -> bool {
346    ctx.operator_only("").is_ok()
347}
348
349async fn create_agent(
350    cmd: CommandCreateAgentDefinitionData,
351    mstore: Arc<crate::backend::storage::store::Store>,
352    broker: Arc<crate::backend::mps::Broker>,
353    from_window: bool,
354) -> Result<AgentDefinition, String> {
355    let now = agentmux_common::time::now_ms();
356    crate::backend::reserved_names::check_all(&[&cmd.name]).map_err(|e| format!("createagent: {e}"))?;
357    // slug is empty here — agent_def_insert auto-derives it
358    // from name AND collision-resolves AND mutates the
359    // struct so we serialize the resolved value back to
360    // the frontend (not "").
361    let mut agent = AgentDefinition {
362        id: uuid::Uuid::new_v4().to_string(),
363        slug: String::new(),
364        name: cmd.name,
365        icon: cmd.icon,
366        provider: cmd.provider,
367        description: cmd.description,
368        working_directory: cmd.working_directory,
369        shell: cmd.shell,
370        provider_flags: cmd.provider_flags,
371        auto_start: cmd.auto_start,
372        restart_on_crash: cmd.restart_on_crash,
373        idle_timeout_minutes: cmd.idle_timeout_minutes,
374        created_at: now,
375        agent_type: cmd.agent_type,
376        environment: cmd.environment,
377        agent_bus_id: cmd.agent_bus_id,
378        is_seeded: 0,
379        accounts: String::new(),
380        parent_id: String::new(),
381        branch_label: String::new(),
382        updated_at: now,
383        user_hidden: 0,
384        container_image: String::new(),
385        container_volumes: "[]".to_string(),
386        container_name: String::new(),
387        // Inert (see the field's doc); always 0.
388        use_ambient_login: 0,
389        // Not settable via this RPC yet — only `agent.define`
390        // (the App-API/MCP path) can set a model vendor override.
391        model_vendor_base_url: String::new(),
392        memory_id: String::new(),
393        seat: None,
394        conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
395    };
396    if !from_window {
397        crate::backend::folder_overlap::check(&mstore, &agent, None).map_err(|e| format!("createagent: {e}"))?;
398    }
399    mstore.agent_def_insert(&mut agent).map_err(|e| format!("createagent: {e}"))?;
400    // Assign the agent its display color at creation
401    // (SPEC_AGENT_COLOR_2026_08_08.md). Best-effort: a failure
402    // here shouldn't fail the create — agent.open assigns a
403    // color on first open as the fallback.
404    let _ = mstore.agent_content_set(&crate::backend::storage::store::AgentContent {
405        agent_id: agent.id.clone(),
406        content_type: "ui:color".to_string(),
407        content: crate::backend::agent_color::color_for_new_agent(&mstore, &agent.id),
408        updated_at: now,
409    });
410    broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
411    Ok(agent)
412}
413
414async fn update_agent(
415    cmd: CommandUpdateAgentDefinitionData,
416    mstore: Arc<crate::backend::storage::store::Store>,
417    broker: Arc<crate::backend::mps::Broker>,
418    from_window: bool,
419) -> Result<AgentDefinition, String> {
420    // Fetch existing to preserve created_at
421    let existing = mstore.agent_def_list().map_err(|e| format!("updateagent: {e}"))?;
422    let old = existing.iter().find(|a| a.id == cmd.id)
423        .ok_or_else(|| format!("updateagent: agent {} not found", cmd.id))?;
424    // An agent that already has a reserved name keeps it; a new one is not given.
425    if cmd.name != old.name {
426        crate::backend::reserved_names::check_all(&[&cmd.name]).map_err(|e| format!("updateagent: {e}"))?;
427    }
428    crate::server::app_api::check_provider_unchanged(&old.id, &old.provider, &cmd.provider)
429        .and_then(|()| crate::server::app_api::check_volumes(&cmd.container_volumes)).map_err(|e| format!("updateagent: {e}"))?;
430    // Model vendor base URL: `None` (omitted) preserves the
431    // stored value; `Some(url)` overrides it (including
432    // `Some("")` to explicitly clear). Validated against the
433    // (possibly also-updated) `cmd.provider` — same check
434    // `agent.define` applies.
435    let chosen_model_vendor_base_url = match &cmd.model_vendor_base_url {
436        Some(url) => {
437            crate::server::app_api::validate_vendor_base_url(&cmd.provider, url)
438                .map_err(|e| format!("updateagent: {e}"))?;
439            url.clone()
440        }
441        None => old.model_vendor_base_url.clone(),
442    };
443    let mut agent = updated_definition(cmd, old, chosen_model_vendor_base_url);
444    if !from_window && crate::backend::folder_overlap::folders_changed(old, &agent) {
445        crate::backend::folder_overlap::check(&mstore, &agent, None).map_err(|e| format!("updateagent: {e}"))?;
446    }
447    let found = mstore.agent_def_update(&mut agent).map_err(|e| format!("updateagent: {e}"))?;
448    if !found {
449        return Err(format!("updateagent: agent {} not found", agent.id));
450    }
451    crate::backend::mcp_folder_rule::mark_when_moved_to_the_host(old, &agent);
452    // The seat `listagents` would show.
453    agent.seat = crate::backend::agent_seat::effective_seat(&mstore, &agent);
454    broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
455    Ok(agent)
456}
457
458/// The definition an `updateagent` writes: the caller's fields over the stored row, keeping what the call does not carry.
459fn updated_definition(
460    cmd: CommandUpdateAgentDefinitionData,
461    old: &AgentDefinition,
462    chosen_model_vendor_base_url: String,
463) -> AgentDefinition {
464        // slug is preserved from the existing row — it's
465        // immutable after creation. The update path never
466        // accepts a new slug from the client.
467        AgentDefinition {
468            id: cmd.id,
469            slug: old.slug.clone(),
470            name: cmd.name,
471            icon: cmd.icon,
472            provider: cmd.provider,
473            description: cmd.description,
474            working_directory: cmd.working_directory,
475            shell: cmd.shell,
476            provider_flags: cmd.provider_flags,
477            auto_start: cmd.auto_start,
478            restart_on_crash: cmd.restart_on_crash,
479            idle_timeout_minutes: cmd.idle_timeout_minutes,
480            created_at: old.created_at,
481            agent_type: cmd.agent_type,
482            environment: cmd.environment,
483            agent_bus_id: cmd.agent_bus_id,
484            is_seeded: old.is_seeded,
485            // Preserve existing accounts when the caller omits the field
486            // (cmd.accounts defaults to "" via #[serde(default)]). Callers
487            // that only update name/icon/etc. (AgentDefForm, AgentPicker rename)
488            // don't carry accounts, so falling back to old.accounts prevents
489            // silently wiping saved assignments.
490            accounts: if cmd.accounts.is_empty() { old.accounts.clone() } else { cmd.accounts },
491            // parent_id + branch_label describe provenance and
492            // are immutable post-insert (forks are separate rows,
493            // not in-place edits).
494            parent_id: old.parent_id.clone(),
495            branch_label: old.branch_label.clone(),
496            // Placeholder — agent_def_update self-stamps the real
497            // timestamp and writes it back into `agent` below, so
498            // the response body carries the fresh value.
499            updated_at: old.updated_at,
500            // Preserve user_hidden — updateagent edits the
501            // definition payload, not the per-user view-state
502            // flag. Hide/unhide go through their dedicated RPCs
503            // (`agentdefhide` / `agentdefunhide`). Phase 2 of
504            // SPEC_AGENT_PICKER_TWO_TIER_2026_05_24.md.
505            user_hidden: old.user_hidden,
506            // Preserve existing container config when the caller omits the field
507            // (cmd.container_image defaults to "" via #[serde(default)]). Callers
508            // that only update name/icon/etc. (AgentDefForm) don't carry container
509            // fields, so falling back to old values prevents silently wiping a
510            // container agent's image and volumes — same guard as `accounts` above.
511            container_image: if cmd.container_image.is_empty() { old.container_image.clone() } else { cmd.container_image },
512            container_volumes: if cmd.container_volumes == "[]" { old.container_volumes.clone() } else { cmd.container_volumes },
513            // container_name is server-managed; preserve the existing value.
514            container_name: old.container_name.clone(),
515            // Inert; carried over unchanged (see the field's doc).
516            use_ambient_login: old.use_ambient_login,
517            model_vendor_base_url: chosen_model_vendor_base_url,
518            // Immutable post-insert, same as slug/parent_id/branch_label
519            // above — agent_def_update's SET clause doesn't even
520            // touch this column, but the in-memory struct still
521            // needs the real value: it's what gets serialized back
522            // to the frontend as the "updated" agent.
523            memory_id: old.memory_id.clone(),
524            // Not this RPC's: a seat is set only by `agent.setSeat`, and
525            // the mirror write keeps the stored one whatever this says.
526            seat: old.seat.clone(),
527            // Not yet exposed by this RPC's own command schema
528            // (CommandUpdateAgentData has no conversation_visibility
529            // field) — preserve the existing value, same as
530            // memory_id just above, rather than silently resetting
531            // a configured agent back to the default on an
532            // unrelated name/icon/accounts edit.
533            conversation_visibility: old.conversation_visibility.clone(),
534        }
535}
536
537async fn import_agent_from_claw(
538    cmd: CommandImportAgentFromClawData,
539    mstore: Arc<crate::backend::storage::store::Store>,
540    broker: Arc<crate::backend::mps::Broker>,
541) -> Result<AgentDefinition, String> {
542    let workspace_path = std::path::Path::new(&cmd.workspace_path);
543    if !workspace_path.exists() {
544        return Err(format!("importagentfromclaw: path does not exist: {}", cmd.workspace_path));
545    }
546    crate::backend::reserved_names::check_all(&[&cmd.agent_name]).map_err(|e| format!("importagentfromclaw: {e}"))?;
547
548    let now = agentmux_common::time::now_ms();
549
550    // Detect provider from .claude/settings.json if present
551    let mut provider = "claude".to_string();
552    let settings_path = workspace_path.join(".claude").join("settings.json");
553    if settings_path.exists() {
554        if let Ok(settings_str) = std::fs::read_to_string(&settings_path) {
555            if let Ok(settings) = serde_json::from_str::<serde_json::Value>(&settings_str) {
556                if let Some(p) = settings.get("provider").and_then(|v| v.as_str()) {
557                    provider = p.to_string();
558                }
559            }
560        }
561    }
562
563    // Create the agent — slug is empty, agent_def_insert will
564    // auto-derive from agent_name and mutate the struct
565    // so the resolved slug is returned to the frontend.
566    let mut agent = AgentDefinition {
567        id: uuid::Uuid::new_v4().to_string(),
568        slug: String::new(),
569        name: cmd.agent_name.clone(),
570        icon: "\u{2726}".to_string(),
571        provider,
572        description: format!("Imported from {}", cmd.workspace_path),
573        working_directory: cmd.workspace_path.clone(),
574        shell: String::new(),
575        provider_flags: String::new(),
576        auto_start: 0,
577        restart_on_crash: 0,
578        idle_timeout_minutes: 0,
579        created_at: now,
580        agent_type: "standalone".to_string(),
581        environment: String::new(),
582        agent_bus_id: String::new(),
583        is_seeded: 0,
584        accounts: String::new(),
585        parent_id: String::new(),
586        branch_label: String::new(),
587        updated_at: now,
588        user_hidden: 0,
589        container_image: String::new(),
590        container_volumes: "[]".to_string(),
591        container_name: String::new(),
592        use_ambient_login: 0,
593        model_vendor_base_url: String::new(),
594        memory_id: String::new(),
595        seat: None,
596        conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
597    };
598    mstore.agent_def_insert(&mut agent).map_err(|e| format!("importagentfromclaw: {e}"))?;
599
600    // Read CLAUDE.md → agentmd content
601    let claude_md_path = workspace_path.join("CLAUDE.md");
602    if claude_md_path.exists() {
603        if let Ok(content) = std::fs::read_to_string(&claude_md_path) {
604            let fc = AgentContent {
605                agent_id: agent.id.clone(),
606                content_type: "agentmd".to_string(),
607                content,
608                updated_at: now,
609            };
610            let _ = mstore.agent_content_set(&fc);
611        }
612    }
613
614    // Read .mcp.json → mcp content. Not from a folder a container agent can write: the host agent
615    // imported gets the servers set in AgentMux, and its pane names the rest (`mcp_folder_rule`).
616    if let Some(content) = crate::backend::mcp_folder_rule::config_to_import(workspace_path) {
617        let fc = AgentContent {
618            agent_id: agent.id.clone(),
619            content_type: "mcp".to_string(),
620            content,
621            updated_at: now,
622        };
623        let _ = mstore.agent_content_set(&fc);
624    }
625
626    broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
627    Ok(agent)
628}
629
630async fn import_agents(
631    cmd: CommandImportAgentDefinitionsData,
632    mstore: Arc<crate::backend::storage::store::Store>,
633    broker: Arc<crate::backend::mps::Broker>,
634) -> Result<ImportAgentDefinitionsResult, String> {
635    let now = agentmux_common::time::now_ms();
636
637    let mut imported: Vec<String> = Vec::new();
638    let mut skipped: Vec<String> = Vec::new();
639    let mut failed: Vec<String> = Vec::new();
640
641    for agent_import in cmd.agents {
642            // Check for existing agent by slug (id field from export)
643            let existing = mstore.agent_def_list()
644                .unwrap_or_default()
645                .into_iter()
646                .any(|a| a.slug == agent_import.id);
647
648            if existing {
649                skipped.push(agent_import.name.clone());
650                continue;
651            }
652
653        if let Err(e) = crate::backend::reserved_names::check_all(&[&agent_import.name, &agent_import.id]) {
654            failed.push(format!("{}: {e}", agent_import.name));
655            continue;
656        }
657        let mut agent = agent_from_import(&agent_import, now);
658
659        if let Err(e) = mstore.agent_def_insert(&mut agent) {
660            failed.push(format!("{}: {e}", agent_import.name));
661            continue;
662        }
663
664        if import_content_and_skills(&mstore, &agent, &agent_import, now) {
665            imported.push(agent_import.name.clone());
666        } else {
667            failed.push(agent_import.name.clone());
668        }
669    }
670
671    broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
672
673    let result = ImportAgentDefinitionsResult { imported, skipped, failed };
674    Ok(result)
675}
676
677/// The new user-owned definition for one row of an `importagents` payload (its id becomes the slug).
678fn agent_from_import(agent_import: &crate::backend::rpc_types::AgentDefinitionImport, now: i64) -> AgentDefinition {
679            AgentDefinition {
680                id: uuid::Uuid::new_v4().to_string(),
681                slug: agent_import.id.clone(),
682                name: agent_import.name.clone(),
683                icon: agent_import.icon.clone(),
684                provider: agent_import.provider.clone(),
685                description: agent_import.description.clone(),
686                working_directory: agent_import.working_directory.clone(),
687                shell: agent_import.shell.clone(),
688                provider_flags: String::new(),
689                auto_start: 0,
690                restart_on_crash: if agent_import.restart_on_crash { 1 } else { 0 },
691                idle_timeout_minutes: 0,
692                created_at: now,
693                agent_type: agent_import.agent_type.clone(),
694                environment: agent_import.environment.clone(),
695                agent_bus_id: agent_import.agent_bus_id.clone(),
696                is_seeded: 0,
697                accounts: String::new(),
698                parent_id: String::new(),
699                branch_label: String::new(),
700                updated_at: now,
701                user_hidden: 0,
702                container_image: String::new(),
703                container_volumes: "[]".to_string(),
704                container_name: String::new(),
705                use_ambient_login: 0,
706                model_vendor_base_url: String::new(),
707                memory_id: String::new(),
708                seat: None,
709                conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
710            }
711}
712
713/// Insert an imported agent's content blobs and skills; false when any of them failed (all are tried).
714fn import_content_and_skills(
715    mstore: &Arc<crate::backend::storage::store::Store>,
716    agent: &AgentDefinition,
717    agent_import: &crate::backend::rpc_types::AgentDefinitionImport,
718    now: i64,
719) -> bool {
720            // Insert content types
721            let mut content_ok = true;
722            for (content_type, content) in &agent_import.content {
723                let fc = AgentContent {
724                    agent_id: agent.id.clone(),
725                    content_type: content_type.clone(),
726                    content: content.clone(),
727                    updated_at: now,
728                };
729                if let Err(e) = mstore.agent_content_set(&fc) {
730                    tracing::warn!("import: failed to set content for agent {}: {e}", agent.id);
731                    content_ok = false;
732                }
733            }
734
735            // Insert skills
736            let mut skills_ok = true;
737            for skill_import in &agent_import.skills {
738                let skill = AgentSkill {
739                    id: uuid::Uuid::new_v4().to_string(),
740                    agent_id: agent.id.clone(),
741                    name: skill_import.name.clone(),
742                    trigger: skill_import.trigger.clone(),
743                    skill_type: skill_import.skill_type.clone(),
744                    description: skill_import.description.clone(),
745                    content: skill_import.content.clone(),
746                    created_at: now,
747                };
748                if let Err(e) = mstore.agent_skill_insert(&skill) {
749                    tracing::warn!("import: failed to insert skill '{}' for agent {}: {e}", skill.name, agent.id);
750                    skills_ok = false;
751                }
752            }
753    content_ok && skills_ok
754}
755
756async fn export_agents(
757    mstore: Arc<crate::backend::storage::store::Store>,
758    id_store: Arc<crate::backend::storage::store::Store>,
759) -> Result<ExportAgentDefinitionsResult, String> {
760    let agents = mstore.agent_def_list()
761        .map_err(|e| format!("exportagents: list: {e}"))?;
762
763    let mut agent_exports: Vec<AgentDefinitionExport> = Vec::new();
764
765    for agent in agents {
766        let content_map = mstore.agent_content_get_all(&agent.id)
767            .unwrap_or_default()
768            .into_iter()
769            .map(|fc| (fc.content_type, fc.content))
770            .collect::<std::collections::HashMap<String, String>>();
771
772        let skills = mstore.agent_skill_list(&agent.id)
773            .unwrap_or_default()
774            .into_iter()
775            .map(|s| AgentSkillExport {
776                name: s.name,
777                trigger: s.trigger,
778                skill_type: s.skill_type,
779                description: s.description,
780                content: s.content,
781            })
782            .collect::<Vec<_>>();
783
784        // The provider the agent runs, from the shared resolver
785        // (#2594; SPEC_AGENT_BUNDLE_FORMAT_V0_3_2026_10_05.md §3.1): `importagents` gives it to the new
786        // agent, so the import runs the same CLI.
787        let effective_provider = id_store.resolve_effective_provider_id(&agent);
788        agent_exports.push(AgentDefinitionExport {
789            id: agent.slug.clone(),
790            name: agent.name,
791            icon: agent.icon,
792            description: agent.description,
793            provider: effective_provider,
794            shell: agent.shell,
795            working_directory: agent.working_directory,
796            agent_bus_id: agent.agent_bus_id,
797            agent_type: agent.agent_type,
798            environment: agent.environment,
799            restart_on_crash: agent.restart_on_crash != 0,
800            content: content_map,
801            skills,
802        });
803    }
804
805    let exported_at = Utc::now().to_rfc3339();
806
807    let result = ExportAgentDefinitionsResult {
808        version: 4,
809        exported_at,
810        source: "agentmux-export".to_string(),
811        agents: agent_exports,
812    };
813    Ok(result)
814}
815
816/// Deletes the agent definition `id` with everything that belongs to it: its parked block (which stops it), its
817/// identity rows, and a container agent's container and volumes. The `deleteagent` RPC and `Agents delete` both
818/// come here; `via` names the caller in the log.
819pub(crate) async fn delete_agent_definition(state: &AppState, id: &str, via: &'static str) -> Result<(), String> {
820    // Deleting an agent is the one thing that deletes its parked block (and stops it).
821    crate::sagas::park_agents::delete_parked_blocks_of(state, id).await;
822    state.mstore.agent_def_delete(id).map_err(|e| format!("{via}: {e}"))?;
823    // What the person chose for a pair this agent was in is not kept for the pair it was.
824    crate::backend::folder_overlap::forget_agent(id);
825    crate::server::app_api::folder_overlap::forget_asks_of(state, id);
826    // A key account's gateway token ends with the agent, before the container's own cleanup (which also ends it) runs.
827    crate::backend::model_gateway::token::revoke(id, crate::backend::model_gateway::catalog::KEY_ROUTE_ID);
828    super::purge_identity_store_rows(&state.identity_store, &state.id_store, id, via);
829    // A container agent's container and volumes (a developer agent's build output is gigabytes) go with it.
830    // The container is named by the definition's id, a UUID that no later agent is given, so a new agent
831    // created meanwhile cannot meet this cleanup; it runs detached so the delete does not wait out a stop.
832    if let Some(cm) = state.container_manager.get().await {
833        let name = crate::backend::container::container_name_for_slug(id);
834        tokio::spawn(async move { cm.remove_agent_storage(&name).await });
835    }
836    state.broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
837    Ok(())
838}
839
840#[cfg(test)]
841mod tests {
842    use super::*;
843    use crate::backend::rpc_types::RpcMessage;
844    use crate::backend::storage::bundles::Bundle;
845    use crate::server::tests::test_state;
846
847    fn seed_bundle(state: &AppState, id: &str, provider: &str) {
848        let bundle = Bundle {
849            id: id.to_string(),
850            name: "Bundle".to_string(),
851            description: String::new(),
852            is_blank: false,
853            is_global: false,
854            provider: provider.to_string(),
855            model: String::new(),
856            instructions: String::new(),
857            instructions_by_provider: "{}".to_string(),
858            context_files: "[]".to_string(),
859            mcp_servers: "[]".to_string(),
860            skills: "[]".to_string(),
861            sort_order: 0,
862            created_at: 0,
863            updated_at: 0,
864            is_system: false,
865        };
866        state.id_store.bundle_upsert(&bundle).unwrap();
867    }
868
869    // The agent says "codex"; its bound bundle, from before bundles stopped
870    // carrying a harness, says "claude". The agent owns its harness
871    // (SPEC_AGENT_BUNDLE_FORMAT_V0_3_2026_10_05.md §3.1), so the export
872    // carries "codex", which `importagents` gives the imported agent.
873    fn seed_drifted_agent(state: &AppState, def_id: &str, bundle_id: &str) {
874        let mut def = AgentDefinition {
875            memory_id: bundle_id.to_string(),
876            ..crate::backend::storage::agents::test_agent_def(def_id, "Drifted Agent", "codex", "host", 0, "")
877        };
878        state.mstore.agent_def_insert(&mut def).unwrap();
879    }
880
881    #[tokio::test]
882    async fn exportagents_carries_the_agents_own_provider_not_its_bundles() {
883        let state = test_state();
884        seed_bundle(&state, "bundle-claude", "claude");
885        seed_drifted_agent(&state, "agent-drift", "bundle-claude");
886
887        let (engine, mut output_rx) = WshRpcEngine::new();
888        register(&engine, &state);
889
890        engine.handle_message(RpcMessage {
891            command: COMMAND_EXPORT_AGENTS.to_string(),
892            reqid: "req-1".to_string(),
893            data: Some(serde_json::json!({})),
894            ..Default::default()
895        });
896        let resp = tokio::time::timeout(std::time::Duration::from_secs(2), output_rx.recv())
897            .await
898            .unwrap()
899            .unwrap();
900        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
901        let result: ExportAgentDefinitionsResult =
902            serde_json::from_value(resp.data.expect("expected result data")).unwrap();
903
904        let exported = result
905            .agents
906            .iter()
907            .find(|a| a.id == "agent-drift")
908            .expect("exported agent should be present");
909        assert_eq!(
910            exported.provider, "codex",
911            "the agent owns its harness; the bundle's provider is a hint (SPEC_AGENT_BUNDLE_FORMAT_V0_3_2026_10_05.md §3.1)"
912        );
913    }
914
915    #[tokio::test]
916    async fn deleting_an_agent_ends_its_api_key_token() {
917        use crate::backend::model_gateway::{catalog::KEY_ROUTE_ID, token};
918        let state = test_state();
919        seed_drifted_agent(&state, "agent-del-key", "bundle-none");
920        let on_key = token::renew_for_account("agent-del-key", "agent-del-key", KEY_ROUTE_ID, "acct", None);
921        let other = token::renew_for_account("agent-keep-key", "agent-keep-key", KEY_ROUTE_ID, "acct", None);
922        delete_agent_definition(&state, "agent-del-key", "test").await.unwrap();
923        assert_eq!(token::grant_for(&on_key), None);
924        assert!(token::grant_for(&other).is_some(), "another agent's token stays");
925        token::revoke("agent-keep-key", KEY_ROUTE_ID);
926    }
927}
928
929#[cfg(test)]
930#[path = "core_tests.rs"]
931mod core_tests;