Skip to main content

agentmux_srv/server/agent_handlers/
template_create.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Making a user-owned agent from a seeded template: the core of the `agentdefcreatefromtemplate` RPC
5//! (Phase 1 of the two-tier picker, SPEC_AGENT_PICKER_TWO_TIER_2026_05_24.md), shared with the `Agents create`
6//! API (`app_api/agent_spawn/create.rs`).
7//!
8//! The template stays pristine; the new row carries `is_seeded = 0`. Validation:
9//!  - `template_id` must resolve to a row with `is_seeded = 1`. Cloning a user-owned row would be confusing
10//!    semantics; use `forkagentdefinition` for that.
11//!  - `name` is non-empty, at most 200 characters, and not already taken by any `is_seeded = 0` row.
12
13use crate::backend::mps::Broker;
14use crate::backend::rpc_types::{AgentDefCreateFromTemplateResult, CommandAgentDefCreateFromTemplateData};
15use crate::backend::storage::store::{IdentityAccount, Store};
16use crate::backend::storage::AgentDefinition;
17
18use super::template::{former_name_of_another, name_taken};
19
20/// Link a new agent to the account it is created with, for its own provider: `chosen` (the account the caller
21/// picked) when it is one of this channel's accounts for that provider, else the provider's only account.
22/// Two or more accounts with none chosen leave it unbound: that is a choice, made in Accounts.
23///
24/// The launch writes this link too (`linkLaunchAccount`), but only after it has started the controller, so
25/// the new agent's first spawn found no link, refused with "no credentials", and nothing started it again
26/// once the link landed, while Accounts already counted the agent as using the account. The same race
27/// `inherit_source_account_links` closes for a fork. Best-effort: a failure is logged and leaves the agent
28/// unbound, as before.
29fn link_new_agent_account(id_store: &Store, identity_store: &Store, broker: &Broker, def: &AgentDefinition, chosen: &str) {
30    use crate::backend::providers::resolve_provider_alias;
31    let provider = resolve_provider_alias(&def.provider);
32    if provider.is_empty() {
33        return;
34    }
35    let same_provider = |a: &IdentityAccount| resolve_provider_alias(&a.provider) == provider;
36    let chosen = chosen.trim();
37    let account = if chosen.is_empty() {
38        let mut mine = match id_store.identity_list(None) {
39            Ok(all) => all.into_iter().filter(same_provider),
40            Err(e) => {
41                tracing::warn!(target: "identity", agent = %def.id, error = %e, "agentdefcreatefromtemplate: could not read the accounts; the new agent starts unbound");
42                return;
43            }
44        };
45        match (mine.next(), mine.next()) {
46            (Some(only), None) => only,
47            _ => return,
48        }
49    } else {
50        match id_store.identity_get(chosen) {
51            Ok(Some(a)) if same_provider(&a) => a,
52            _ => return,
53        }
54    };
55    match identity_store.agent_identity_link(&def.id, &account.id, &def.provider) {
56        Ok(()) => {
57            tracing::info!(target: "identity", agent = %def.id, provider = %provider, "agentdefcreatefromtemplate: new agent linked to its account");
58            broker.publish_event_for::<crate::backend::mps_events::AgentIdentitiesChanged>(&def.id, &(), vec![], 0);
59        }
60        Err(e) => tracing::warn!(target: "identity", agent = %def.id, account_id = %account.id, error = %e, "agentdefcreatefromtemplate: could not link the new agent to its account"),
61    }
62}
63
64/// Clone the template `cmd.template_id` into a new agent named `cmd.name`.
65pub(crate) fn create_from_template(
66    mstore: &Store,
67    id_store: &Store,
68    identity_store: &Store,
69    broker: &Broker,
70    cmd: CommandAgentDefCreateFromTemplateData,
71) -> Result<AgentDefCreateFromTemplateResult, String> {
72    let name = checked_name(&cmd.name)?;
73    let all = mstore
74        .agent_def_list()
75        .map_err(|e| format!("agentdefcreatefromtemplate: list: {e}"))?;
76    let template = seeded_template(&all, &cmd.template_id)?;
77    if name_taken(&all, &name) {
78        return Err(format!(
79            "agentdefcreatefromtemplate: an agent named {:?} already exists",
80            name
81        ));
82    }
83    if former_name_of_another(&mstore, &name, "") {
84        return Err(format!("agentdefcreatefromtemplate: {name:?} still addresses another agent"));
85    }
86
87    let mut new_def = cloned_definition(id_store, template, &name, &cmd)?;
88    mstore
89        .agent_def_insert(&mut new_def)
90        .map_err(|e| format!("agentdefcreatefromtemplate: insert: {e}"))?;
91    if let Some(bundle_ids) = cmd.bundle_ids.as_deref().filter(|ids| !ids.is_empty()) {
92        mstore
93            .agent_bundles_set(&new_def.id, bundle_ids)
94            .map_err(|e| format!("agentdefcreatefromtemplate: bundles: {e}"))?;
95    }
96
97    link_new_agent_account(id_store, identity_store, broker, &new_def, cmd.identity_id.as_deref().unwrap_or(""));
98    broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
99
100    let resp = AgentDefCreateFromTemplateResult {
101        definition_id: new_def.id.clone(),
102        identity_id: cmd.identity_id.unwrap_or_default(),
103        memory_id: cmd.memory_id.unwrap_or_default(),
104        slug: new_def.slug.clone(),
105    };
106    tracing::info!(
107        template_id = %cmd.template_id,
108        new_definition_id = %new_def.id,
109        new_name = %new_def.name,
110        "agentdefcreatefromtemplate: cloned template into user agent"
111    );
112    Ok(resp)
113}
114
115/// The name as stored: trimmed, non-empty, at most 200 characters.
116fn checked_name(raw: &str) -> Result<String, String> {
117    let name = raw.trim().to_string();
118    if name.is_empty() {
119        return Err("agentdefcreatefromtemplate: name must be non-empty".into());
120    }
121    if name.chars().count() > 200 {
122        return Err(
123            "agentdefcreatefromtemplate: name must be ≤200 characters".into(),
124        );
125    }
126    Ok(name)
127}
128
129/// The row `template_id` names, which must be a seeded template.
130fn seeded_template<'a>(all: &'a [AgentDefinition], template_id: &str) -> Result<&'a AgentDefinition, String> {
131    let template = all
132        .iter()
133        .find(|a| a.id == template_id)
134        .ok_or_else(|| {
135            format!(
136                "agentdefcreatefromtemplate: template {} not found",
137                template_id
138            )
139        })?;
140    if template.is_seeded != 1 {
141        return Err(format!(
142            "agentdefcreatefromtemplate: {} is not a seeded template (is_seeded={})",
143            template_id, template.is_seeded
144        ));
145    }
146    Ok(template)
147}
148
149/// The new row: what the template keeps, with the caller's choices applied and the opt-in settings reset.
150fn cloned_definition(
151    id_store: &Store,
152    template: &AgentDefinition,
153    name: &str,
154    cmd: &CommandAgentDefCreateFromTemplateData,
155) -> Result<AgentDefinition, String> {
156    let now = agentmux_common::time::now_ms();
157    // Runtime is the user's instantiation-time choice, not a
158    // template property. When supplied, the clone records it
159    // (and the matching `environment`); empty falls back to
160    // the template's value for back-compat with older callers.
161    let chosen_agent_type = match cmd.agent_type.as_deref().unwrap_or("").trim() {
162        "host" | "container" => cmd.agent_type.as_deref().unwrap_or("").trim().to_string(),
163        _ => template.agent_type.clone(),
164    };
165    let chosen_environment = if crate::backend::runtime_adapter::RuntimeKind::of_agent_type(&chosen_agent_type).is_container() {
166        "docker".to_string()
167    } else {
168        "local".to_string()
169    };
170    // Template's EFFECTIVE provider, from the shared resolver
171    // (#2594; SPEC_AGENT_BUNDLE_FORMAT_V0_3_2026_10_05.md §3.1). Used for both the vendor-base-url
172    // validation below and the clone's own `provider` field so
173    // the two can't disagree with each other.
174    let effective_provider = id_store.resolve_effective_provider_id(template);
175    // Model vendor base URL: `None` (omitted) inherits the
176    // template's own value (the only behavior before this
177    // field existed on this RPC); `Some(url)` overrides it,
178    // including `Some("")` to explicitly clear a
179    // template-inherited override. Same validation `agent.define`
180    // already applies — rejected unless the template's provider
181    // declares `base_url_env_var`.
182    let chosen_model_vendor_base_url = match &cmd.model_vendor_base_url {
183        Some(url) => {
184            crate::server::app_api::validate_vendor_base_url(&effective_provider, url)
185                .map_err(|e| format!("agentdefcreatefromtemplate: {e}"))?;
186            url.clone()
187        }
188        None => template.model_vendor_base_url.clone(),
189    };
190    let chosen_container_image = super::template_image::chosen_container_image(cmd.container_image.as_deref(), &chosen_agent_type, &template.container_image)
191        .map_err(|e| format!("agentdefcreatefromtemplate: {e}"))?;
192    crate::backend::reserved_names::check_all(&[name]).map_err(|e| format!("agentdefcreatefromtemplate: {e}"))?;
193    Ok(AgentDefinition {
194        id: uuid::Uuid::new_v4().to_string(),
195        // agent_def_insert derives a unique slug from the name when this is empty + collision-resolves.
196        slug: String::new(),
197        name: name.to_string(),
198        icon: template.icon.clone(),
199        provider: effective_provider.clone(),
200        description: template.description.clone(),
201        // Force re-allocation of the per-agent working
202        // directory at first launch via the new slug —
203        // matches forkagentdefinition's behaviour.
204        working_directory: String::new(),
205        shell: template.shell.clone(),
206        provider_flags: template.provider_flags.clone(),
207        // Users opt in to auto-start explicitly; cloning
208        // shouldn't carry it over (mirrors fork).
209        auto_start: 0,
210        restart_on_crash: template.restart_on_crash,
211        idle_timeout_minutes: template.idle_timeout_minutes,
212        created_at: now,
213        agent_type: chosen_agent_type,
214        environment: chosen_environment,
215        agent_bus_id: String::new(),
216        is_seeded: 0,
217        accounts: String::new(),
218        parent_id: template.id.clone(),
219        branch_label: String::new(),
220        updated_at: now,
221        // New user-owned agent starts visible. Phase 2
222        // (Q2 Decision Y) — hide applies only to seeded
223        // templates, never to user-owned agents.
224        user_hidden: 0,
225        // The template's image unless the picker chose one (above), so container-type
226        // templates still propagate theirs to user-cloned agents.
227        container_image: chosen_container_image,
228        container_volumes: template.container_volumes.clone(),
229        container_name: String::new(),
230        use_ambient_login: 0,
231        model_vendor_base_url: chosen_model_vendor_base_url,
232        memory_id: String::new(),
233        // Fail-closed default, not inherited from the template —
234        // same convention as auto_start/use_ambient_login above
235        // (opt-in settings reset on a fresh clone, not carried
236        // over).
237        seat: None,
238        conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
239    })
240}