Skip to main content

agentmux_srv/server/app_api/
agent_definition.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Agents update`, `bundles`, `hide` and `unhide` (`POST /api/v1/agent/{update,bundles,hide,unhide}`):
5//! an agent edits an agent's definition, sets its Bundles list and hides or shows a picker template
6//! without the operator's window, by the code the window's `updateagent`, `setagentbundles` and
7//! `agentdefhide`/`agentdefunhide` run.
8//!
9//! - update: only the fields given change, and only ones that say how the agent is listed or when it runs:
10//!   description, icon, auto_start, restart_on_crash, idle_timeout_minutes, the model route's model and the agent's
11//!   daily spend cap (spend_cap_usd, and reset_spend_today for a spend that was wrong; see below). What decides what an agent runs, or
12//!   where its traffic goes or which project files it reads (shell, provider_flags, working_directory,
13//!   model_vendor_base_url) is not taken, as `env_set` refuses the same: the operator sets those in My Agents. The
14//!   name has its own action (`rename`), the provider is fixed when an agent is made, and environment variables,
15//!   accounts, container settings and the seat have their own actions.
16//! - spend cap: the agent's leader may set or reset another agent's cap; an agent may only lower its own. Each change
17//!   is recorded with the cap before and after (`docs/specs/SPEC_ROUTE_AGENT_BRAKES_2026_11_10.md` section 3.2).
18//! - bundles: with `bundle_ids`, replaces the agent's picked bundles, in order; without, reads them.
19//! - hide, unhide: a seeded picker template; an agent you made is removed with `delete`.
20//!
21//! Each acts as the agent its token names; a request without one is refused, so a change is never attributed to
22//! the operator, and each one, and each refusal, is recorded in the audit log under the calling agent.
23
24use axum::extract::State;
25use axum::http::StatusCode;
26use axum::response::{IntoResponse, Response};
27use axum::{Extension, Json};
28use serde::Deserialize;
29use serde_json::{json, Value};
30
31use super::agent_lifecycle::{actor_of, audit, refuse, target_of, Actor, Refusal};
32use crate::backend::storage::AgentDefinition;
33use crate::server::caller::Caller;
34use crate::server::state::AppState;
35
36/// The longest description or text field: what the definition form accepts in practice.
37const MAX_TEXT_CHARS: usize = 4000;
38/// A week: the longest idle timeout.
39const MAX_IDLE_MINUTES: i64 = 7 * 24 * 60;
40
41/// A field outside the list above is refused by name (`deny_unknown_fields`), never ignored.
42#[derive(Debug, Clone, Deserialize)]
43#[serde(deny_unknown_fields)]
44pub(crate) struct UpdateRequest {
45    /// The agent's id, slug or name.
46    agent: String,
47    description: Option<String>,
48    icon: Option<String>,
49    auto_start: Option<bool>,
50    restart_on_crash: Option<bool>,
51    idle_timeout_minutes: Option<i64>,
52    /// `""` takes the agent off its model route (its token stops working at once); the route it is on, or only
53    /// `model`, changes its model on that route.
54    route: Option<String>,
55    /// On a model route: the model on that route. Otherwise (a Claude or Codex agent on its own login): its model, as
56    /// the pane's picker sets it (`agent_runtime_pick`).
57    model: Option<String>,
58    /// The agent's effort, as the pane's picker sets it; Claude agents not on a route.
59    effort: Option<String>,
60    /// Dollars a day through the model gateway: a number, or 0 / "none" for no cap.
61    spend_cap_usd: Option<Value>,
62    /// Zero the agent's spend counted for today.
63    reset_spend_today: Option<bool>,
64    /// With `route` or `model` on a model route: start a new session on the new model instead of resuming the
65    /// conversation, with `handoff` as its first message.
66    fresh: Option<bool>,
67    /// With `fresh`: what the next session must know. Empty: it reads its task list.
68    handoff: Option<String>,
69}
70
71#[derive(Debug, Clone, Deserialize)]
72pub(crate) struct BundlesRequest {
73    agent: String,
74    /// The whole list, in order; absent reads the current one.
75    bundle_ids: Option<Vec<String>>,
76}
77
78#[derive(Debug, Clone, Deserialize)]
79pub(crate) struct HideRequest {
80    /// The template's id or slug.
81    template: String,
82}
83
84fn bad(message: impl Into<String>) -> Refusal {
85    refuse(StatusCode::BAD_REQUEST, format!("INVALID_ARG: {}", message.into()))
86}
87
88fn text_field(name: &str, value: &str) -> Result<String, Refusal> {
89    let value = value.trim();
90    if value.chars().count() > MAX_TEXT_CHARS {
91        return Err(bad(format!("{name} is at most {MAX_TEXT_CHARS} characters")));
92    }
93    Ok(value.to_string())
94}
95
96/// `value` trimmed, `None` when the caller left it out; an empty or blank one is refused, naming `field`.
97fn named_or_absent<'a>(field: &str, value: &'a Option<String>) -> Result<Option<&'a str>, Refusal> {
98    match value.as_deref().map(str::trim) {
99        Some("") => Err(bad(format!("{field} is empty; name one, or leave {field} out"))),
100        other => Ok(other),
101    }
102}
103
104fn publish_changed(state: &AppState) {
105    state.broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
106}
107
108/// `route` and `model` of `Agents update`: leave a model route (`route: ""`), or change the model on the route the agent
109/// is already on. Putting an agent onto a route spends the person's key, so that is asked of them when the agent is
110/// made or in the composer's model panel, not done by a call that names no one to ask.
111fn route_change(state: &AppState, agent: &AgentDefinition, req: &UpdateRequest) -> Result<Vec<&'static str>, Refusal> {
112    use crate::backend::model_gateway::{launch, switch::{self, Target}};
113    let current = launch::choice_of(&state.mstore, &agent.id);
114    let route = req.route.as_deref().map(str::trim);
115    let model = req.model.as_deref().map(str::trim).filter(|m| !m.is_empty());
116    if route == Some("") {
117        if model.is_some() {
118            return Err(bad("route \"\" leaves the model route; it takes no model"));
119        }
120        if current.is_none() {
121            return Err(bad("the agent is not on a model route"));
122        }
123        let harness = state.id_store.resolve_effective_provider_id(agent);
124        switch::agent_switch_allowed(&agent.id).map_err(bad)?;
125        // Before the agent moves: a fresh session that can't be started must not leave it moved.
126        let fresh = fresh_message(state, agent, req, &harness, "", "")?;
127        switch::move_to(&state.mstore, &agent.id, &harness, Target::OwnLogin, |_| true).map_err(bad)?;
128        switch::count_agent_switch(&agent.id);
129        restart_on_new_model(state, agent, fresh);
130        return Ok(vec!["route"]);
131    }
132    let Some(current) = current else {
133        return Err(bad("the agent is not on a model route, and putting one on a route spends the key in the Vault, which the person approves when the agent is made (Agents spawn or create with route) or in the model panel"));
134    };
135    let target = route.unwrap_or(&current.route);
136    if target != current.route {
137        return Err(bad(format!("the agent is on the {} route; moving it to {target} spends another key, which the person approves in the model panel", current.route)));
138    }
139    let harness = state.id_store.resolve_effective_provider_id(agent);
140    let wanted = model.unwrap_or(&current.model);
141    if wanted == current.model {
142        return Ok(Vec::new());
143    }
144    switch::agent_switch_allowed(&agent.id).map_err(bad)?;
145    let key_present = |r: &crate::backend::model_gateway::catalog::Route| crate::backend::vault::route_key::present(&state.identity_store, r.key_label);
146    let fresh = fresh_message(state, agent, req, &harness, target, wanted)?;
147    switch::move_to(&state.mstore, &agent.id, &harness, Target::Route { route: target, model: wanted }, key_present).map_err(bad)?;
148    switch::count_agent_switch(&agent.id);
149    restart_on_new_model(state, agent, fresh);
150    Ok(vec!["model"])
151}
152
153/// The first message of the fresh session `fresh: true` asks for, once it is known to be possible: None when the request
154/// does not ask for one. Checked before the agent moves, so a refusal leaves it where it was.
155fn fresh_message(state: &AppState, agent: &AgentDefinition, req: &UpdateRequest, harness: &str, route: &str, model: &str) -> Result<Option<String>, Refusal> {
156    if req.fresh != Some(true) {
157        return Ok(None);
158    }
159    let handoff = req.handoff.as_deref().map(str::trim).unwrap_or_default();
160    super::agent_model::check_fresh(state, &agent.id, handoff).map_err(bad)?;
161    Ok(Some(super::agent_context::switch_message(&super::agent_model::place_label(harness, route, model), handoff)))
162}
163
164/// The choice is read at every launch, so the agent's panes are restarted, with their conversation, at the end of
165/// the turn they are in. A pane that cannot be restarted starts on it the next time it opens. With `fresh_message` they
166/// start a new session instead, its first message that one.
167fn restart_on_new_model(state: &AppState, agent: &AgentDefinition, fresh_message: Option<String>) {
168    let (_, failed) = match fresh_message {
169        Some(message) => super::agent_model::start_fresh_panes(state, &agent.id, &message),
170        None => super::agent_model::restart_panes(state, &agent.id),
171    };
172    for why in failed {
173        tracing::warn!(agent = %agent.slug, why, "Agents update: a pane was not restarted on the new model");
174    }
175}
176
177/// What `spend_cap_usd` and `reset_spend_today` of `Agents update` ask for, once allowed.
178struct SpendPlan {
179    /// The new cap (`Some(None)`: no cap); absent when the request leaves it.
180    cap: Option<Option<f64>>,
181    reset: bool,
182}
183
184/// Checks `spend_cap_usd` and `reset_spend_today` before anything else in the request changes. The leader of an agent
185/// sets and resets its cap; an agent may only lower its own, and not reset it, since a cap it could lift or clear would
186/// stop nothing.
187fn spend_plan(state: &AppState, actor_uid: &str, target_uid: &str, req: &UpdateRequest) -> Result<SpendPlan, Refusal> {
188    use crate::backend::model_gateway::cap;
189    let own = actor_uid == target_uid;
190    let led = crate::backend::agent_seat::effective_seat_by_id(&state.mstore, target_uid).and_then(|s| s.lead).is_some_and(|lead| lead == actor_uid);
191    let mut plan = SpendPlan { cap: None, reset: false };
192    if let Some(value) = req.spend_cap_usd.as_ref().filter(|v| !v.is_null()) {
193        let to = cap::parse_request(value).map_err(bad)?;
194        let from = cap::agent_cap(&state.mstore, &state.config_watcher.get_settings().extra, target_uid);
195        if own {
196            if !to.is_some_and(|to| from.is_none_or(|from| to <= from)) {
197                return Err(refuse(StatusCode::FORBIDDEN, "an agent may lower its own spend cap, not raise or lift it; its leader or the person can"));
198            }
199        } else if !led {
200            return Err(refuse(StatusCode::FORBIDDEN, "only an agent's leader sets its spend cap (Agents set_seat names the lead); you can lower your own"));
201        }
202        plan.cap = Some(to);
203    }
204    if req.reset_spend_today == Some(true) {
205        if !led {
206            return Err(refuse(StatusCode::FORBIDDEN, "only an agent's leader resets the spend counted for today"));
207        }
208        plan.reset = true;
209    }
210    if (plan.cap.is_some() || plan.reset) && crate::server::spend_watch::on_a_route(state, target_uid).is_err() {
211        return Err(bad("the agent is not on a model route or an API key, so it has no spend cap (an agent on its own login has plan limits instead)"));
212    }
213    Ok(plan)
214}
215
216/// Does what [`spend_plan`] allowed. Returns what was done, for the audit row.
217fn spend_apply(state: &AppState, target_uid: &str, plan: &SpendPlan) -> Result<Vec<String>, Refusal> {
218    let internal = |e: String| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents update: {e}"));
219    let mut done = Vec::new();
220    if let Some(to) = plan.cap {
221        let change = crate::server::spend_watch::change_cap(state, target_uid, to).map_err(internal)?;
222        let show = |c: Option<f64>| c.map_or("none".to_string(), |c| format!("${c:.2}"));
223        done.push(format!("spend cap {} to {}", show(change.from), show(change.to)));
224    }
225    if plan.reset {
226        let removed = crate::server::spend_watch::reset_today(state, target_uid).map_err(internal)?;
227        done.push(format!("reset today's spend (${removed:.2} counted)"));
228    }
229    Ok(done)
230}
231
232/// What `update` did: the agent, the definition fields changed, what the spend change did, and what a model or effort
233/// pick did.
234struct Updated {
235    agent_id: String,
236    changed: Vec<&'static str>,
237    spend_done: Vec<String>,
238    applied: Option<serde_json::Value>,
239    /// What the caller should know about the change it made, beyond that it was made.
240    warning: Option<&'static str>,
241}
242
243/// Said when a model change resumes the conversation: the one case where the new model reads what another wrote.
244const RESUMED_WARNING: &str = "The conversation was resumed on the new model. A model that did not write a long conversation can read it badly (one fell into a loop of thinking on its first turn). Pass fresh: true, with a handoff, to start a new session on the new model instead.";
245
246/// Apply the fields `req` gives to the agent's stored definition. Returns the names of the fields changed, and what
247/// the audit row says beyond them.
248fn update(state: &AppState, actor_uid: &str, req: &UpdateRequest) -> Result<Updated, Refusal> {
249    let target = target_of(state, &req.agent)?;
250    // Before anything is applied: a refused spend change must not leave a model change behind it.
251    let plan = spend_plan(state, actor_uid, &target.agent_id, req)?;
252    let internal = |e: crate::backend::storage::error::StoreError| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents update: {e}"));
253    let mut agent = state
254        .mstore
255        .agent_def_list()
256        .map_err(internal)?
257        .into_iter()
258        .find(|a| a.id == target.agent_id)
259        .ok_or_else(|| refuse(StatusCode::NOT_FOUND, format!("no agent '{}' on this machine", req.agent)))?;
260    let mut changed: Vec<&'static str> = Vec::new();
261    let mut set = |field: &'static str, slot: &mut String, value: &Option<String>| -> Result<(), Refusal> {
262        if let Some(v) = value {
263            *slot = text_field(field, v)?;
264            changed.push(field);
265        }
266        Ok(())
267    };
268    set("description", &mut agent.description, &req.description)?;
269    set("icon", &mut agent.icon, &req.icon)?;
270    if let Some(on) = req.auto_start {
271        agent.auto_start = i64::from(on);
272        changed.push("auto_start");
273    }
274    if let Some(on) = req.restart_on_crash {
275        agent.restart_on_crash = i64::from(on);
276        changed.push("restart_on_crash");
277    }
278    if let Some(minutes) = req.idle_timeout_minutes {
279        if !(0..=MAX_IDLE_MINUTES).contains(&minutes) {
280            return Err(bad(format!("idle_timeout_minutes is 0 (never) to {MAX_IDLE_MINUTES}")));
281        }
282        agent.idle_timeout_minutes = minutes;
283        changed.push("idle_timeout_minutes");
284    }
285    let mut applied = None;
286    let mut warning = None;
287    let on_route = crate::backend::model_gateway::launch::choice_of(&state.mstore, &agent.id).is_some();
288    if req.effort.is_some() && on_route {
289        return Err(bad("the agent is on a model route, which sets its model and thinking: its effort is set in the pane's model panel"));
290    }
291    // An empty model or effort names nothing: refused by name here, before a pick rewrites any pane.
292    let model = named_or_absent("model", &req.model)?;
293    let effort = named_or_absent("effort", &req.effort)?;
294    if !on_route && req.route.is_none() && (model.is_some() || effort.is_some()) {
295        let picked = super::agent_runtime_pick::pick(state, &agent, model, effort)?;
296        changed.extend(["model", "effort"].into_iter().filter(|f| if *f == "model" { picked.model.is_some() } else { picked.effort.is_some() }));
297        applied = Some(picked.to_json());
298    } else if req.route.is_some() || req.model.is_some() {
299        let done = route_change(state, &agent, req)?;
300        if !done.is_empty() && req.fresh != Some(true) {
301            warning = Some(RESUMED_WARNING);
302        }
303        changed.extend(done);
304    }
305    let spend_done = spend_apply(state, &target.agent_id, &plan)?;
306    if changed.is_empty() && spend_done.is_empty() {
307        return Err(bad("nothing to change; give at least one of description, icon, auto_start, restart_on_crash, idle_timeout_minutes, route, model, effort, spend_cap_usd, reset_spend_today (name: rename; environment: env_set)"));
308    }
309    // A request that only changes the spend cap leaves the definition as it is.
310    if !changed.is_empty() {
311        if !state.mstore.agent_def_update(&mut agent).map_err(internal)? {
312            return Err(refuse(StatusCode::NOT_FOUND, format!("no agent '{}' on this machine", req.agent)));
313        }
314        publish_changed(state);
315    }
316    Ok(Updated { agent_id: target.agent_id, changed, spend_done, applied, warning })
317}
318
319fn bundles(state: &AppState, req: &BundlesRequest) -> Result<Value, Refusal> {
320    let target = target_of(state, &req.agent)?;
321    let internal = |e: crate::backend::storage::error::StoreError| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents bundles: {e}"));
322    let Some(ids) = &req.bundle_ids else {
323        return Ok(json!({ "agent_id": target.agent_id, "bundle_ids": state.mstore.agent_bundle_ids(&target.agent_id).map_err(internal)? }));
324    };
325    for id in ids.iter().map(|id| id.trim()).filter(|id| !id.is_empty()) {
326        match state.id_store.bundle_get(id).map_err(internal)? {
327            Some(b) if !b.is_blank && !b.is_system => {}
328            Some(_) => return Err(bad(format!("bundle {id} is the blank or a system entry, which an agent doesn't pick"))),
329            None => return Err(refuse(StatusCode::NOT_FOUND, format!("no bundle {id}; Identity presets lists the bundles"))),
330        }
331    }
332    let stored = state.mstore.agent_bundles_set(&target.agent_id, ids).map_err(internal)?;
333    Ok(json!({
334        "agent_id": target.agent_id,
335        "bundle_ids": stored,
336        "note": "its next launch reads them: their instructions go into its startup file after Global Memory and their skills are added",
337    }))
338}
339
340fn hide(state: &AppState, req: &HideRequest, hidden: bool) -> Result<Value, Refusal> {
341    let verb = if hidden { "hide" } else { "unhide" };
342    let named = req.template.trim();
343    let internal = |e: crate::backend::storage::error::StoreError| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents {verb}: {e}"));
344    let template = state
345        .mstore
346        .agent_def_list()
347        .map_err(internal)?
348        .into_iter()
349        .find(|a| a.is_seeded == 1 && (a.id == named || a.slug == named))
350        .ok_or_else(|| refuse(StatusCode::NOT_FOUND, format!("no picker template '{named}'; only a seeded template can be hidden (an agent you made is removed with delete)")))?;
351    state.mstore.agent_def_set_hidden(&template.id, hidden).map_err(internal)?;
352    publish_changed(state);
353    Ok(json!({ "template_id": template.id, "hidden": hidden }))
354}
355
356/// Run `op` as the calling agent, and record the outcome under it.
357async fn run<F>(state: &AppState, caller: Option<&Caller>, action: &'static str, named: String, op: F) -> Response
358where
359    F: FnOnce(&AppState, &str) -> Result<(Value, String), Refusal> + Send + 'static,
360{
361    let respond = |r: Refusal| (r.status, Json(json!({ "error": r.message }))).into_response();
362    let actor: Actor = match actor_of(state, caller, action) {
363        Ok(actor) => actor,
364        Err(r) => return respond(r),
365    };
366    let blocking = state.clone();
367    let actor_uid = actor.uid().to_string();
368    let outcome = tokio::task::spawn_blocking(move || op(&blocking, &actor_uid))
369        .await
370        .unwrap_or_else(|e| Err(refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents {action}: {e}"))));
371    let audit_action = format!("agent.{action}");
372    match outcome {
373        Ok((mut body, note)) => {
374            let id = audit(state, &actor, &audit_action, &named, "", true, None, &note);
375            body["audit_id"] = json!(id);
376            Json(body).into_response()
377        }
378        Err(r) => {
379            audit(state, &actor, &audit_action, &named, "", false, Some(&r.message), "refused");
380            respond(r)
381        }
382    }
383}
384
385/// `Agents update`: the change, and what the answer and the audit row say about it.
386fn update_response(s: &AppState, actor: &str, req: &UpdateRequest) -> Result<(Value, String), Refusal> {
387    let Updated { agent_id, changed, spend_done, applied, warning } = update(s, actor, req)?;
388    let mut parts: Vec<String> = Vec::new();
389    if !changed.is_empty() {
390        parts.push(format!("changed {} of {agent_id}", changed.join(", ")));
391    }
392    parts.extend(spend_done.iter().map(|d| format!("{d} of {agent_id}")));
393    let note = parts.join("; ");
394    let mut changed: Vec<String> = changed.iter().map(|c| c.to_string()).collect();
395    changed.extend(spend_done.iter().map(|_| "spend".to_string()));
396    let shown = match &applied {
397        Some(a) => a["when"].as_str().unwrap_or_default().to_string(),
398        None => "a running agent keeps what it launched with until it is launched again; a spend cap applies at its next request".to_string(),
399    };
400    let mut body = json!({ "agent_id": agent_id, "changed": changed, "note": shown });
401    if let Some(applied) = applied {
402        body["applied"] = applied;
403    }
404    if let Some(warning) = warning {
405        body["warning"] = json!(warning);
406    }
407    Ok((body, note))
408}
409
410pub(crate) async fn handle_agent_update(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<UpdateRequest>) -> Response {
411    let caller = caller.map(|Extension(c)| c);
412    let named = req.agent.trim().to_string();
413    run(&state, caller.as_ref(), "update", named, move |s, actor| update_response(s, actor, &req)).await
414}
415
416/// `update` for an agent on another machine (`remote_ops::agent_ops`): the same checks and change a local call has,
417/// recorded under `who` (`slug@machine`). A caller from another machine is nobody's leader, so it cannot raise a spend cap.
418pub(crate) async fn run_remote(state: &AppState, who: &str, req: UpdateRequest) -> Result<Value, (StatusCode, String)> {
419    let actor = Actor::remote(who);
420    let named = req.agent.trim().to_string();
421    let (blocking, uid) = (state.clone(), actor.uid().to_string());
422    let outcome = tokio::task::spawn_blocking(move || update_response(&blocking, &uid, &req))
423        .await
424        .unwrap_or_else(|e| Err(refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents update: {e}"))));
425    match outcome {
426        Ok((mut body, note)) => {
427            body["audit_id"] = json!(audit(state, &actor, "agent.update", &named, "", true, None, &note));
428            Ok(body)
429        }
430        Err(r) => {
431            audit(state, &actor, "agent.update", &named, "", false, Some(&r.message), "refused");
432            Err((r.status, r.message))
433        }
434    }
435}
436
437pub(crate) async fn handle_agent_bundles(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<BundlesRequest>) -> Response {
438    let caller = caller.map(|Extension(c)| c);
439    let named = req.agent.trim().to_string();
440    run(&state, caller.as_ref(), "bundles", named, move |s, _| {
441        let body = bundles(s, &req)?;
442        let note = if req.bundle_ids.is_some() { format!("set the bundles of {}", body["agent_id"]) } else { "read".to_string() };
443        Ok((body, note))
444    })
445    .await
446}
447
448pub(crate) async fn handle_agent_hide(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<HideRequest>) -> Response {
449    hide_or_show(state, caller, req, true).await
450}
451
452pub(crate) async fn handle_agent_unhide(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<HideRequest>) -> Response {
453    hide_or_show(state, caller, req, false).await
454}
455
456async fn hide_or_show(state: AppState, caller: Option<Extension<Caller>>, req: HideRequest, hidden: bool) -> Response {
457    let caller = caller.map(|Extension(c)| c);
458    let named = req.template.trim().to_string();
459    let action = if hidden { "hide" } else { "unhide" };
460    run(&state, caller.as_ref(), action, named, move |s, _| {
461        let body = hide(s, &req, hidden)?;
462        let note = format!("{action} template {}", body["template_id"]);
463        Ok((body, note))
464    })
465    .await
466}
467
468#[cfg(test)]
469#[path = "tests/agent_definition_tests.rs"]
470mod tests;