Skip to main content

agentmux_srv/server/app_api/
agent_define.rs

1use super::*;
2
3pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
4    register_agent_define(engine, state);
5}
6
7/// Rejects a non-empty `model_vendor_base_url` unless `provider_id`'s
8/// `ProviderConfig` declares support for redirection via
9/// `base_url_env_var`. Pure — no I/O — so it's directly unit-testable
10/// without the async `Store`/`Broker` harness `agent_define_core` needs.
11/// An empty `base_url` is always fine — that's "use the harness's default
12/// vendor endpoint," never rejected regardless of provider.
13///
14/// `pub(crate)` (not `pub(super)`) so `server::agent_handlers::template`'s
15/// `agentdefcreatefromtemplate` and `server::agent_handlers::core`'s
16/// `updateagent` handlers can reuse it too, instead of duplicating this
17/// check for the human-facing creation/edit paths.
18pub(crate) fn validate_vendor_base_url(provider_id: &str, base_url: &str) -> Result<(), String> {
19    if base_url.is_empty() {
20        return Ok(());
21    }
22    match providers::get_provider(provider_id) {
23        Some(p) if p.base_url_env_var.is_some() => Ok(()),
24        _ => Err(format!(
25            "agent.define: provider '{provider_id}' does not support a custom model vendor base URL"
26        )),
27    }
28}
29
30/// An agent's provider is read-only once set: its sessions, linked accounts
31/// and native memory all belong to that harness, so switching it would
32/// strand them. Run the same setup on another harness by forking the agent.
33/// The lock moved here from the agent's bundle
34/// (SPEC_AGENT_BUNDLE_FORMAT_V0_3_2026_10_05.md §3.1). An empty stored
35/// provider can still be set once.
36/// A definition's volumes list may not name a mount a container may not have (a container runtime's socket or a folder
37/// holding one): saved with one, it is refused with the reason a start would give.
38pub(crate) fn check_volumes(container_volumes: &str) -> Result<(), String> {
39    match crate::backend::container::runtime_socket::refused_in_json(container_volumes) {
40        Some(path) => Err(crate::backend::container::ContainerError::VolumeRefused { path }.user_message()),
41        None => Ok(()),
42    }
43}
44
45pub(crate) fn check_provider_unchanged(agent_id: &str, existing: &str, incoming: &str) -> Result<(), String> {
46    if existing.is_empty() || existing == incoming {
47        return Ok(());
48    }
49    Err(format!(
50        "FORBIDDEN: agent {agent_id} provider is readonly once set (has '{existing}', got '{incoming}'); fork the agent to run it on another provider"
51    ))
52}
53
54/// Infer a provider slug from a model name prefix.
55/// Only maps prefixes that correspond to a registered provider slug.
56/// Callers must still validate the result via `providers::get_provider`.
57pub(super) fn infer_provider_from_model(model: &str) -> String {
58    let m = model.to_lowercase();
59    if m.starts_with("claude") {
60        "claude".to_string()
61    } else if m.starts_with("gemini") {
62        "gemini".to_string()
63    } else if m.starts_with("codex") {
64        "codex".to_string()
65    } else {
66        // Unknown prefix — return as-is; get_provider will reject it with
67        // a "cannot infer provider" error so callers know to set provider explicitly.
68        model.to_string()
69    }
70}
71
72/// Returns `(agent_row_id, newly_inserted)`. In the consolidated model the
73/// definition row IS the agent, so the "stub instance" that makes a defined
74/// agent visible in My Agents is that same row carrying an `instance_name`;
75/// `instance_create` folds into it. `newly_inserted = false` when the row
76/// already carries a name (the stub already existed); callers use this to
77/// avoid broadcasting `agents:changed` on no-op calls. The returned id is
78/// the row's id, which is what `instance_create` reports back.
79pub(super) fn make_stub_idempotent(
80    mstore: &crate::backend::storage::store::Store,
81    def_id: &str,
82    name: &str,
83    now: i64,
84) -> Result<(String, bool), String> {
85    if let Some(existing) = mstore
86        .instance_get(def_id)
87        .map_err(|e| format!("agent.define: read agent row: {e}"))?
88    {
89        if !existing.instance_name.is_empty() {
90            return Ok((existing.id, false));
91        }
92    }
93    let stub_id = format!("si-{}", def_id.replace('-', ""));
94    let inst = AgentInstance {
95        id: stub_id.clone(),
96        definition_id: def_id.to_string(),
97        parent_instance_id: String::new(),
98        block_id: String::new(),
99        session_id: String::new(),
100        status: "stopped".to_string(),
101        github_context: String::new(),
102        started_at: now,
103        ended_at: 0,
104        created_at: now,
105        identity_id: String::new(),
106        memory_id: String::new(),
107        instance_name: name.to_string(),
108        working_directory: String::new(),
109        display_hidden: false,
110    };
111    match mstore.instance_create(&inst) {
112        Ok(canonical) => Ok((canonical.id, true)),
113        Err(e) => Err(format!("agent.define: create stub instance: {e}")),
114    }
115}
116
117/// Core logic for the `agent.define` command, shared by the WebSocket RPC
118/// handler and the HTTP service dispatch (`("agent", "define")` in service.rs).
119/// Persist `system_prompt` and `env` content blobs for a freshly created or
120/// updated agent definition.  Errors are logged but not propagated — the
121/// definition row is already committed and the caller has already published
122/// `agents:changed`, so a content-write failure must not abort the response.
123pub(super) fn persist_define_content(
124    mstore: &Store,
125    agent_id: &str,
126    cmd: &CommandAgentDefineData,
127    now: i64,
128) {
129    if let Some(prompt) = &cmd.system_prompt {
130        if !prompt.is_empty() {
131            if let Err(e) = mstore.agent_content_set(&AgentContent {
132                agent_id: agent_id.to_string(),
133                content_type: "agentmd".to_string(),
134                content: prompt.clone(),
135                updated_at: now,
136            }) {
137                tracing::warn!(agent_id, err = %e, "agent.define: failed to persist system_prompt (non-fatal)");
138            }
139        }
140    }
141    if let Some(env_map) = &cmd.env {
142        if !env_map.is_empty() {
143            let content = env_map.iter()
144                .map(|(k, v)| format!("{}={}", k, v))
145                .collect::<Vec<_>>()
146                .join("\n");
147            if let Err(e) = mstore.agent_content_set(&AgentContent {
148                agent_id: agent_id.to_string(),
149                content_type: "env".to_string(),
150                content,
151                updated_at: now,
152            }) {
153                tracing::warn!(agent_id, err = %e, "agent.define: failed to persist env (non-fatal)");
154            }
155        }
156    }
157}
158
159fn register_agent_define(engine: &Arc<WshRpcEngine>, state: &AppState) {
160    let mstore = state.mstore.clone();
161    let broker = state.broker.clone();
162
163    engine.register_typed(COMMAND_AGENT_DEFINE, move |cmd: CommandAgentDefineData, _ctx| {
164        let mstore = mstore.clone();
165        let broker = broker.clone();
166        async move { agent_define_core(mstore, broker, cmd).await }
167    });
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    #[test]
175    fn empty_base_url_is_always_valid() {
176        // Even for a provider with no base_url_env_var — "unset" never needs
177        // the capability to exist.
178        assert!(validate_vendor_base_url("codex", "").is_ok());
179        assert!(validate_vendor_base_url("claude", "").is_ok());
180        assert!(validate_vendor_base_url("nonexistent-provider", "").is_ok());
181    }
182
183    #[test]
184    fn non_empty_base_url_accepted_for_a_supporting_provider() {
185        assert!(validate_vendor_base_url("claude", "https://my-proxy.example.com").is_ok());
186    }
187
188    #[test]
189    fn non_empty_base_url_rejected_for_a_non_supporting_provider() {
190        let err = validate_vendor_base_url("codex", "https://my-proxy.example.com").unwrap_err();
191        assert!(err.contains("codex"));
192        assert!(err.contains("does not support"));
193    }
194
195    #[test]
196    fn non_empty_base_url_rejected_for_an_unknown_provider() {
197        assert!(validate_vendor_base_url("not-a-real-provider", "https://x").is_err());
198    }
199}
200
201// reagent P1 on PR #2505: agent.define's update path had no way to distinguish
202// "don't touch model_vendor_base_url" from "clear it" (a plain empty String
203// always meant "don't touch"). Combined with the authoritative validation
204// re-running on every update against whatever is currently stored, a provider
205// change away from a vendor-capable provider while an old override sat there
206// permanently blocked every future agent.define call for that agent — there
207// was no way to ever un-set the stale value. Fixed via Option<String>: `None`
208// = don't touch, `Some("")` = explicit clear.
209#[cfg(test)]
210mod agent_define_core_vendor_tests {
211    use super::*;
212    use crate::server::tests::test_state;
213
214    fn cmd(value: serde_json::Value) -> CommandAgentDefineData {
215        serde_json::from_value(value).unwrap()
216    }
217
218    #[tokio::test]
219    async fn a_definition_is_not_saved_with_a_container_runtime_socket_in_its_volumes() {
220        let state = test_state();
221        let refused = agent_define_core(state.mstore.clone(), state.broker.clone(), cmd(json!({
222            "name": "socket-agent",
223            "provider": "claude",
224            "container_volumes": r#"["/var/run/docker.sock:/var/run/docker.sock"]"#,
225        }))).await.unwrap_err();
226        assert!(refused.contains("/var/run/docker.sock") && refused.contains("remove it from the agent's volumes"), "{refused}");
227        assert!(state.mstore.agent_def_list().unwrap().iter().all(|d| d.name != "socket-agent"), "nothing was saved");
228        agent_define_core(state.mstore.clone(), state.broker.clone(), cmd(json!({
229            "name": "plain-volume-agent",
230            "provider": "claude",
231            "container_volumes": r#"["data:/data"]"#,
232        }))).await.unwrap();
233    }
234
235    #[tokio::test]
236    async fn omitting_the_field_on_update_does_not_clear_a_previously_set_override() {
237        let state = test_state();
238
239        let created = agent_define_core(state.mstore.clone(), state.broker.clone(), cmd(json!({
240            "name": "vendor-test-agent",
241            "provider": "claude",
242            "model_vendor_base_url": "https://my-proxy.example.com",
243        }))).await.unwrap();
244        let def = state.mstore.agent_def_get(&created.definition_id).unwrap().unwrap();
245        assert_eq!(def.model_vendor_base_url, "https://my-proxy.example.com");
246
247        // Update that touches an unrelated field and omits model_vendor_base_url.
248        agent_define_core(state.mstore.clone(), state.broker.clone(), cmd(json!({
249            "name": "vendor-test-agent",
250            "if_exists": "update",
251            "description": "just touching something else",
252        }))).await.unwrap();
253        let def = state.mstore.agent_def_get(&created.definition_id).unwrap().unwrap();
254        assert_eq!(
255            def.model_vendor_base_url, "https://my-proxy.example.com",
256            "an omitted field must not clear the stored override"
257        );
258    }
259
260    #[tokio::test]
261    async fn explicit_empty_string_clears_a_previously_set_override() {
262        let state = test_state();
263
264        let created = agent_define_core(state.mstore.clone(), state.broker.clone(), cmd(json!({
265            "name": "vendor-clear-test",
266            "provider": "claude",
267            "model_vendor_base_url": "https://my-proxy.example.com",
268        }))).await.unwrap();
269
270        agent_define_core(state.mstore.clone(), state.broker.clone(), cmd(json!({
271            "name": "vendor-clear-test",
272            "if_exists": "update",
273            "model_vendor_base_url": "",
274        }))).await.unwrap();
275        let def = state.mstore.agent_def_get(&created.definition_id).unwrap().unwrap();
276        assert_eq!(def.model_vendor_base_url, "", "explicit empty string must clear the override");
277    }
278
279    // The provider is read-only once set (SPEC_AGENT_BUNDLE_FORMAT_V0_3_2026_10_05.md
280    // §3.1), so the old "change provider and clear a stale override in the
281    // same call" path is now a refusal; the override itself still updates.
282    #[tokio::test]
283    async fn an_update_cannot_change_the_provider_but_can_change_the_rest() {
284        let state = test_state();
285
286        let created = agent_define_core(state.mstore.clone(), state.broker.clone(), cmd(json!({
287            "name": "provider-lock-test",
288            "provider": "claude",
289            "model_vendor_base_url": "https://my-proxy.example.com",
290        }))).await.unwrap();
291
292        for change in [json!({ "provider": "codex" }), json!({ "model": "gemini-2.5-pro" })] {
293            let mut req = json!({ "name": "provider-lock-test", "if_exists": "update" });
294            req.as_object_mut().unwrap().extend(change.as_object().unwrap().clone());
295            let err = agent_define_core(state.mstore.clone(), state.broker.clone(), cmd(req))
296                .await
297                .unwrap_err();
298            assert!(err.contains("readonly once set"), "{err}");
299        }
300
301        agent_define_core(state.mstore.clone(), state.broker.clone(), cmd(json!({
302            "name": "provider-lock-test",
303            "if_exists": "update",
304            "provider": "claude",
305            "model_vendor_base_url": "",
306            "description": "updated",
307        }))).await.unwrap();
308        let def = state.mstore.agent_def_get(&created.definition_id).unwrap().unwrap();
309        assert_eq!(def.provider, "claude");
310        assert_eq!(def.model_vendor_base_url, "");
311        assert_eq!(def.description, "updated");
312    }
313
314    #[test]
315    fn check_provider_unchanged_allows_setting_an_empty_provider_once() {
316        assert!(check_provider_unchanged("a", "", "codex").is_ok());
317        assert!(check_provider_unchanged("a", "codex", "codex").is_ok());
318        assert!(check_provider_unchanged("a", "codex", "claude").is_err());
319    }
320}
321
322// Mandatory ABF (ARCHITECTURE_MANDATORY_ABF_RETHINK_2026_08_14.md §3.2):
323// a fresh `agent.define` call provisions its own dedicated bundle.
324#[cfg(test)]
325mod agent_define_core_bundle_provisioning_tests {
326    use super::*;
327    use crate::server::tests::test_state;
328
329    fn cmd(value: serde_json::Value) -> CommandAgentDefineData {
330        serde_json::from_value(value).unwrap()
331    }
332
333    #[tokio::test]
334    async fn fresh_insert_creates_no_bundle_and_the_agent_keeps_the_provider() {
335        let state = test_state();
336        let bundles_before = state.mstore.bundle_list().unwrap().len();
337
338        let created = agent_define_core(state.mstore.clone(), state.broker.clone(), cmd(json!({
339            "name": "define-bundle-test",
340            "provider": "gemini",
341        }))).await.unwrap();
342
343        let def = state.mstore.agent_def_get(&created.definition_id).unwrap().unwrap();
344        assert!(def.memory_id.is_empty(), "a fresh agent.define insert has no bundle of its own");
345        assert_eq!(state.mstore.bundle_list().unwrap().len(), bundles_before, "no bundle is created");
346        assert_eq!(def.provider, "gemini");
347    }
348
349    #[tokio::test]
350    async fn skip_of_an_existing_definition_does_not_leak_a_stray_bundle() {
351        let state = test_state();
352
353        let first = agent_define_core(state.mstore.clone(), state.broker.clone(), cmd(json!({
354            "name": "skip-no-leak-test",
355            "provider": "claude",
356            "if_exists": "skip",
357        }))).await.unwrap();
358        assert_eq!(first.action, "created");
359        let bundles_after_first = state.mstore.bundle_list().unwrap().len();
360
361        // Same name again, if_exists=skip — must resolve to the SAME
362        // definition without creating (and leaking) a second bundle. The
363        // bundle-provision step only runs on agent_define_core's
364        // genuinely-fresh-insert path, not the atomic find-or-insert's
365        // own lookup, precisely so idempotent callers don't leak one
366        // unbound bundle per repeated call.
367        let second = agent_define_core(state.mstore.clone(), state.broker.clone(), cmd(json!({
368            "name": "skip-no-leak-test",
369            "provider": "claude",
370            "if_exists": "skip",
371        }))).await.unwrap();
372        assert_eq!(second.action, "skipped");
373        assert_eq!(second.definition_id, first.definition_id);
374        let bundles_after_second = state.mstore.bundle_list().unwrap().len();
375        assert_eq!(bundles_after_first, bundles_after_second, "skip path must not leak an extra bundle");
376    }
377}
378
379#[cfg(test)]
380#[path = "agent_define_tests.rs"]
381mod agent_define_tests;
382
383/// Atomically allocate an agent working directory.
384///
385/// Tries to atomically create `desired` via `std::fs::create_dir`. If
386/// that fails because the directory already exists, tries `<desired>-1`,
387/// `<desired>-2`, …, up to `-99`. The atomic `create_dir` (NOT
388/// `create_dir_all` for the leaf) is the reservation mechanism: two
389/// concurrent callers competing for the same path race on the OS
390/// `mkdir` syscall and one wins; the loser sees `AlreadyExists` and
391/// moves on.
392///
393/// Caller is responsible for distinguishing auto-generated paths from
394/// user-specified ones — this function rewrites the path on collision,
395/// which would clobber a user's intent if they pointed an agent at
396/// `~/projects/myrepo` and that already had a `CLAUDE.md`.
397pub fn allocate_agent_workdir(desired: &str) -> Result<String, String> {
398    let p = std::path::Path::new(desired);
399    if let Some(parent) = p.parent() {
400        if !parent.as_os_str().is_empty() {
401            std::fs::create_dir_all(parent)
402                .map_err(|e| format!("allocate_agent_workdir: parent {}: {e}", parent.display()))?;
403        }
404    }
405    match std::fs::create_dir(p) {
406        Ok(()) => return Ok(desired.to_string()),
407        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
408        Err(e) => return Err(format!("allocate_agent_workdir: create_dir({}): {e}", desired)),
409    }
410    for n in 1..=99u32 {
411        let candidate = format!("{desired}-{n}");
412        match std::fs::create_dir(std::path::Path::new(&candidate)) {
413            Ok(()) => return Ok(candidate),
414            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
415            Err(e) => return Err(format!("allocate_agent_workdir: create_dir({candidate}): {e}")),
416        }
417    }
418    Err(format!(
419        "allocate_agent_workdir: too many collisions (>99) under {desired}-N — clean up old runs"
420    ))
421}
422
423pub(crate) async fn agent_define_core(
424    mstore: Arc<Store>,
425    broker: Arc<crate::backend::mps::Broker>,
426    cmd: CommandAgentDefineData,
427) -> Result<AgentDefineResult, String> {
428    check_volumes(&cmd.container_volumes).map_err(|e| format!("agent.define: {e}"))?;
429    if cmd.name.trim().is_empty() { return Err("agent.define: name is required".to_string()); }
430
431    // Validate if_exists early so a typo is caught even for new definitions,
432    // not only when a matching definition already exists.
433    let if_exists = cmd.if_exists.as_deref().unwrap_or("skip");
434    if !matches!(if_exists, "skip" | "update" | "error") {
435        return Err(format!(
436            "agent.define: unknown if_exists value '{if_exists}'; valid: skip, update, error"
437        ));
438    }
439
440    let provider = resolve_define_provider(&cmd)?;
441    let create_stub = cmd.create_instance_stub.unwrap_or(true);
442    let now = agentmux_common::time::now_ms();
443
444    // Gates the fresh-insert path below (the "no existing match" case, where
445    // `def` — built from `provider` — is what actually gets written). The
446    // "update" branch re-validates against the EXISTING agent's actual
447    // provider (not this possibly-defaulted `provider`, which may not
448    // reflect an unspecified `cmd.provider` on an update call) right before
449    // its own write — this check doesn't gate that path.
450    let cmd_model_vendor_base_url = cmd.model_vendor_base_url.clone().unwrap_or_default();
451    agent_define::validate_vendor_base_url(&provider, &cmd_model_vendor_base_url)?;
452
453    // Build the new definition up-front so agent_def_find_or_insert can use
454    // it as both the lookup key and the insert payload. It holds a single
455    // mutex guard for the check + conditional insert, closing the TOCTOU
456    // window between list and insert.
457    // A definition that already has the name is not made again, so one with a reserved name is left as it is.
458    let named = cmd.name.trim();
459    let exists = mstore.agent_def_list().map(|all| all.iter().any(|d| d.is_seeded == 0 && (d.name.eq_ignore_ascii_case(named) || d.slug.eq_ignore_ascii_case(named)))).unwrap_or(false);
460    if !exists {
461        crate::backend::reserved_names::check_all(&[named]).map_err(|e| format!("agent.define: {e}"))?;
462    }
463    let mut def = new_definition(&cmd, &provider, cmd_model_vendor_base_url, now);
464    if !exists {
465        crate::backend::folder_overlap::check(&mstore, &def, None).map_err(|e| format!("agent.define: {e}"))?;
466    }
467
468    // Returns Some(existing) if a row matched by name/slug already exists;
469    // None if the row was freshly inserted (def.slug now holds the resolved slug).
470    let existing_opt = mstore.agent_def_find_or_insert(&mut def)
471        .map_err(|e| format!("agent.define: find_or_insert: {e}"))?;
472
473    let Some(existing) = existing_opt else {
474        return Ok(finish_created(&mstore, &broker, &def, &cmd, create_stub, now));
475    };
476    // A definition with this name/slug already exists — apply if_exists policy.
477    match if_exists {
478        "skip" => Ok(finish_skipped(&mstore, &broker, &existing, create_stub, now)),
479        "error" => Err(format!(
480            "agent.define: definition '{}' already exists (if_exists=error)",
481            cmd.name.trim()
482        )),
483        "update" => update_existing(&mstore, &broker, existing, &cmd, &provider, create_stub, now),
484        other => Err(format!("agent.define: unknown if_exists value '{other}'")),
485    }
486}
487
488/// The provider for a define call: an explicit `provider` wins; otherwise it is inferred from the
489/// `model` prefix; with neither it is "claude".
490fn resolve_define_provider(cmd: &CommandAgentDefineData) -> Result<String, String> {
491    if !cmd.provider.is_empty() {
492        if providers::get_provider(&cmd.provider).is_none() {
493            return Err(format!(
494                "agent.define: unknown provider '{}'; valid: claude, codex, gemini, pi, copilot",
495                cmd.provider
496            ));
497        }
498        Ok(cmd.provider.clone())
499    } else if !cmd.model.is_empty() {
500        let inferred = agent_define::infer_provider_from_model(&cmd.model);
501        if providers::get_provider(&inferred).is_none() {
502            return Err(format!(
503                "agent.define: cannot infer provider from model '{}'; set provider explicitly",
504                cmd.model
505            ));
506        }
507        Ok(inferred)
508    } else {
509        Ok("claude".to_string())
510    }
511}
512
513/// The definition row a define call inserts when no definition has the name yet.
514fn new_definition(cmd: &CommandAgentDefineData, provider: &str, model_vendor_base_url: String, now: i64) -> AgentDefinition {
515    AgentDefinition {
516        id: uuid::Uuid::new_v4().to_string(),
517        slug: String::new(), // resolved by agent_def_find_or_insert
518        name: cmd.name.clone(),
519        icon: cmd.icon.clone(),
520        provider: provider.to_string(),
521        description: cmd.description.clone(),
522        working_directory: cmd.working_directory.clone(),
523        shell: cmd.shell.clone(),
524        environment: cmd.environment.clone(),
525        // Persist the requested model as a CLI flag so the agent launches
526        // with the specified model rather than the provider default.
527        provider_flags: if cmd.model.is_empty() {
528            String::new()
529        } else {
530            format!("--model {}", cmd.model)
531        },
532        auto_start: 0,
533        restart_on_crash: 0,
534        idle_timeout_minutes: 0,
535        created_at: now,
536        agent_type: cmd.agent_type.clone(),
537        agent_bus_id: String::new(),
538        is_seeded: 0,
539        accounts: String::new(),
540        parent_id: String::new(),
541        branch_label: String::new(),
542        updated_at: now,
543        user_hidden: 0,
544        container_image: cmd.container_image.clone(),
545        container_volumes: cmd.container_volumes.clone(),
546        container_name: String::new(), // assigned by ContainerManager on first spawn
547        use_ambient_login: 0,
548        model_vendor_base_url,
549        memory_id: String::new(),
550        seat: None,
551        conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
552    }
553}
554
555/// The instance stub for a definition, as `(stub id, newly created)`. A failure is logged and
556/// treated as "no stub": the definition is already committed, so it is never fatal.
557fn ensure_stub(mstore: &Store, def_id: &str, name: &str, now: i64, path: &str) -> (Option<String>, bool) {
558    match agent_define::make_stub_idempotent(mstore, def_id, name, now) {
559        Ok((id, new)) => (Some(id), new),
560        Err(e) => {
561            tracing::warn!(id = %def_id, err = %e, path, "agent.define: stub failed (non-fatal)");
562            (None, false)
563        }
564    }
565}
566
567/// `if_exists=skip` on an existing definition. Honors create_instance_stub even on skip: a
568/// definition created with create_instance_stub=false (or imported another way) might not have a
569/// stub yet, and a later idempotent call with create_instance_stub=true should make it visible in
570/// My Agents. agents:changed fires only when the stub was actually newly inserted.
571fn finish_skipped(
572    mstore: &Store,
573    broker: &crate::backend::mps::Broker,
574    existing: &AgentDefinition,
575    create_stub: bool,
576    now: i64,
577) -> AgentDefineResult {
578    let (stub_id, stub_new) =
579        if create_stub { ensure_stub(mstore, &existing.id, &existing.name, now, "skip") } else { (None, false) };
580    if stub_new {
581        broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
582    }
583    tracing::info!(id = %existing.id, slug = %existing.slug, stub = stub_id.is_some(), "agent.define: skipped (exists)");
584    AgentDefineResult {
585        definition_id: existing.id.clone(),
586        slug: existing.slug.clone(),
587        action: "skipped".to_string(),
588        instance_stub_id: stub_id,
589    }
590}
591
592/// `if_exists=update` on an existing definition: overwrite only the fields the caller gave.
593fn update_existing(
594    mstore: &Store,
595    broker: &crate::backend::mps::Broker,
596    existing: AgentDefinition,
597    cmd: &CommandAgentDefineData,
598    provider: &str,
599    create_stub: bool,
600    now: i64,
601) -> Result<AgentDefineResult, String> {
602    let mut updated = existing.clone();
603    // provider was already validated/defaulted by the caller; only
604    // overwrite if the caller explicitly supplied a provider or model.
605    if !cmd.provider.is_empty() || !cmd.model.is_empty() {
606        agent_define::check_provider_unchanged(&existing.id, &existing.provider, provider)?;
607        updated.provider = provider.to_string();
608    }
609    // Persist the model as a CLI flag so the agent launches with the requested model rather than
610    // the provider default. If the provider is named but no model is supplied, clear stale flags
611    // so the provider's default is used.
612    if !cmd.model.is_empty() {
613        updated.provider_flags = format!("--model {}", cmd.model);
614    } else if !cmd.provider.is_empty() {
615        updated.provider_flags = String::new();
616    }
617    if !cmd.icon.is_empty()     { updated.icon = cmd.icon.clone(); }
618    if !cmd.description.is_empty() { updated.description = cmd.description.clone(); }
619    if !cmd.working_directory.is_empty() { updated.working_directory = cmd.working_directory.clone(); }
620    if !cmd.shell.is_empty()    { updated.shell = cmd.shell.clone(); }
621    // `None` = don't touch; `Some(_)` (including `Some("")`) sets it explicitly — the caller MUST
622    // be able to pass `Some("")` to clear a stale override, or a provider change away from a
623    // vendor-capable provider would permanently block every future agent.define call for this
624    // agent, since there'd be no way to ever un-set the old value.
625    if let Some(url) = &cmd.model_vendor_base_url { updated.model_vendor_base_url = url.clone(); }
626    // Authoritative check for this write: validates the FINAL effective (provider, override) pair,
627    // catching both a freshly-supplied override against the real provider and a provider change that
628    // leaves a stale override now invalid (the caller must clear it explicitly rather than carry an
629    // inconsistent combination).
630    agent_define::validate_vendor_base_url(&updated.provider, &updated.model_vendor_base_url)?;
631    if !cmd.environment.is_empty() { updated.environment = cmd.environment.clone(); }
632    // name update intentionally omitted — the slug is immutable; renaming would create a slug
633    // mismatch. Use updateagent for renames.
634    if crate::backend::folder_overlap::folders_changed(&existing, &updated) {
635        crate::backend::folder_overlap::check(mstore, &updated, None).map_err(|e| format!("agent.define: {e}"))?;
636    }
637    let did_update = mstore.agent_def_update(&mut updated)
638        .map_err(|e| format!("agent.define: update: {e}"))?;
639    if !did_update {
640        return Err("agent.define: update: row was deleted between find and update".to_string());
641    }
642    agent_define::persist_define_content(mstore, &updated.id, cmd, now);
643    let stub_id = if create_stub { ensure_stub(mstore, &updated.id, &updated.name, now, "update").0 } else { None };
644    broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
645    tracing::info!(id = %updated.id, slug = %updated.slug, stub = stub_id.is_some(), "agent.define: updated");
646    Ok(AgentDefineResult {
647        definition_id: updated.id.clone(),
648        slug: updated.slug.clone(),
649        action: "updated".to_string(),
650        instance_stub_id: stub_id,
651    })
652}
653
654/// A freshly inserted definition (`def.slug` is set by agent_def_find_or_insert). The stub is
655/// created first so listeners handling agents:changed can immediately find the new agent via
656/// ListRecentSessionsCommand. The definition is already committed, so a stub failure is non-fatal
657/// and the broadcast still goes out.
658fn finish_created(
659    mstore: &Store,
660    broker: &crate::backend::mps::Broker,
661    def: &AgentDefinition,
662    cmd: &CommandAgentDefineData,
663    create_stub: bool,
664    now: i64,
665) -> AgentDefineResult {
666    let stub_id = if create_stub { ensure_stub(mstore, &def.id, &def.name, now, "create").0 } else { None };
667    broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
668    agent_define::persist_define_content(mstore, &def.id, cmd, now);
669    tracing::info!(id = %def.id, slug = %def.slug, stub = stub_id.is_some(), "agent.define: created");
670    AgentDefineResult {
671        definition_id: def.id.clone(),
672        slug: def.slug.clone(),
673        action: "created".to_string(),
674        instance_stub_id: stub_id,
675    }
676}