Skip to main content

agentmux_srv/server/app_api/
agent_env.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Agents env_get` and `Agents env_set`: an agent, host or container, reads and edits the
5//! extra environment variables a definition launches with (its `env` content,
6//! `backend::agent_env`), its own or another's. The change applies at that
7//! agent's next launch.
8//!
9//! The caller is the agent its token names; a request without one (the UI has
10//! `setagentcontent` for this) is refused, so the change is never attributed
11//! to the operator. Each change, and each refused attempt, is recorded in the
12//! audit log under the calling agent's slug and in the `identity` log with
13//! its UID.
14
15use axum::extract::State;
16use axum::http::StatusCode;
17use axum::response::{IntoResponse, Response};
18use axum::{Extension, Json};
19use serde::Deserialize;
20use serde_json::{json, Value};
21use std::collections::BTreeMap;
22
23use crate::backend::agent_env;
24use crate::backend::endpoint_notice;
25use crate::backend::storage::store::{AgentContent, AgentDefinition};
26use crate::server::caller::Caller;
27use crate::server::state::AppState;
28
29/// The audit entry's action for a change.
30pub(crate) const AUDIT_ACTION: &str = "agent.env.set";
31
32#[derive(Debug, Deserialize)]
33pub(crate) struct AgentEnvRequest {
34    /// `get` or `set`.
35    action: String,
36    /// The definition's id or slug; the caller's own when absent.
37    #[serde(default)]
38    agent: Option<String>,
39    /// `set`: the whole new text, comments and blank lines as written.
40    #[serde(default)]
41    lines: Option<String>,
42    /// `set`: variables to add or change, the rest left alone.
43    #[serde(default)]
44    set: Option<BTreeMap<String, String>>,
45    /// `set`: variables to remove.
46    #[serde(default)]
47    unset: Option<Vec<String>>,
48}
49
50struct Refusal {
51    status: StatusCode,
52    message: String,
53}
54
55fn refuse(status: StatusCode, message: impl Into<String>) -> Refusal {
56    Refusal { status, message: message.into() }
57}
58
59/// The agent making the request.
60struct Actor {
61    uid: String,
62    slug: String,
63    name: String,
64}
65
66fn actor_of(state: &AppState, caller: Option<&Caller>) -> Result<Actor, Refusal> {
67    let Some(uid) = caller.and_then(Caller::uid) else {
68        return Err(refuse(
69            StatusCode::UNAUTHORIZED,
70            "no agent token: Agents env_get and env_set act as the calling agent; the operator edits an environment in My Agents",
71        ));
72    };
73    let def = state
74        .mstore
75        .agent_def_get(uid)
76        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("agent env: {e}")))?
77        .ok_or_else(|| refuse(StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine"))?;
78    Ok(Actor { uid: uid.to_string(), slug: def.slug, name: def.name })
79}
80
81/// The definition `agent` names, the caller's own when it names none.
82fn target_of(state: &AppState, actor: &Actor, agent: Option<&str>) -> Result<AgentDefinition, Refusal> {
83    let id = match agent.map(str::trim).filter(|a| !a.is_empty()) {
84        None => actor.uid.clone(),
85        Some(named) => crate::backend::agent_resolve::resolve_agent_id(&state.mstore, named)
86            .map_err(|_| refuse(StatusCode::NOT_FOUND, format!("no agent '{named}' on this machine")))?,
87    };
88    let def = state
89        .mstore
90        .agent_def_get(&id)
91        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("agent env: {e}")))?
92        .ok_or_else(|| refuse(StatusCode::NOT_FOUND, format!("no agent '{id}' on this machine")))?;
93    if def.is_seeded != 0 {
94        return Err(refuse(StatusCode::BAD_REQUEST, format!("{} is a template; only an agent has an environment", def.name)));
95    }
96    Ok(def)
97}
98
99fn current_text(state: &AppState, id: &str) -> Result<String, Refusal> {
100    state
101        .mstore
102        .agent_content_get(id, agent_env::CONTENT_TYPE)
103        .map(|c| c.map(|c| c.content).unwrap_or_default())
104        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("agent env: {e}")))
105}
106
107/// The text `req` would leave, refused when it breaks a rule.
108fn proposed(current: &str, req: &AgentEnvRequest) -> Result<String, Refusal> {
109    let bad = |m: String| refuse(StatusCode::BAD_REQUEST, m);
110    let text = match (&req.lines, &req.set, &req.unset) {
111        (Some(_), Some(_), _) | (Some(_), _, Some(_)) => {
112            return Err(bad("give lines (the whole new text) or set and unset, not both".to_string()))
113        }
114        (Some(lines), None, None) => {
115            agent_env::resolve_lines(current, lines).map_err(&bad)?
116        }
117        (None, set, unset) => {
118            if set.is_none() && unset.is_none() {
119                return Err(bad("env_set needs lines, or set and/or unset".to_string()));
120            }
121            agent_env::edit(current, set.as_ref().unwrap_or(&BTreeMap::new()), unset.as_deref().unwrap_or(&[])).map_err(&bad)?
122        }
123    };
124    agent_env::check_size(&text).map_err(&bad)?;
125    Ok(text)
126}
127
128fn audit(state: &AppState, actor: &Actor, target: &AgentDefinition, ok: bool, error: Option<&str>, note: &str) -> String {
129    let request_id = uuid::Uuid::new_v4().to_string();
130    let block_id = state.reactive_handler.block_for_uid(&actor.uid).unwrap_or_default();
131    let reason = format!("{} (uid {}) on {} ({}): {note}", actor.slug, actor.uid, target.name, target.id);
132    state.reactive_handler.log_fleet_action_audit(
133        Some(&actor.slug),
134        &target.slug,
135        &block_id,
136        AUDIT_ACTION,
137        ok,
138        error,
139        &request_id,
140        Some(&reason),
141    );
142    request_id
143}
144
145/// Why this change to `target`'s model endpoint is refused, if it is. Not for what it does (the notice and its
146/// undo window answer that) but for where it would not work: an agent on a model route keeps the route's
147/// server and keys, a container agent gets the person's account mounted in its image, which a custom
148/// server must not receive, and a key must be a Vault entry the person opened to that agent. A key is
149/// also one the acting agent could use itself: srv does not put a key in a server's hands for an agent
150/// that could not have read it. (An agent on another machine names none: it has no agent here.) The
151/// answer is the same for an entry that is missing, of another kind or closed to an agent, so it never
152/// says which entries exist.
153fn endpoint_refusal(state: &AppState, actor: &Actor, target: &AgentDefinition, current: &str, new: &str) -> Option<Refusal> {
154    let bad = |m: String| Some(refuse(StatusCode::BAD_REQUEST, m));
155    if crate::backend::model_gateway::launch::choice_of(&state.mstore, &target.id).is_some() {
156        return bad(format!(
157            "{} is on a model route, which sets its server, key and models: switch its route instead (the model panel, or Agents update)",
158            target.name
159        ));
160    }
161    if target.runtime().is_container() {
162        return bad(format!(
163            "{} is a container agent: its image is given the person's account, which a server of its own must not receive. Use a model route, or ask the operator to set the endpoint in My Agents",
164            target.name
165        ));
166    }
167    key_refusal(state, actor, target, current, new)
168}
169
170/// Why the keys the new environment holds may not go to its server. When the call moves the address, every
171/// key in the environment goes with it, so every one is checked, the ones already there as well as the
172/// ones the call writes: a `vault:` reference must be usable by the acting agent and by the target, and a
173/// key written in the clear (the operator's, from My Agents) is never handed to an address an agent chose.
174/// When only a key changes, that key is checked. A key is only written for a server of its own: with no
175/// address, or Anthropic's, the launch passes it through next to the person's login and the CLI would send
176/// that string to Anthropic as its key; so a call that takes the address away takes those keys with it.
177fn key_refusal(state: &AppState, actor: &Actor, target: &AgentDefinition, current: &str, new: &str) -> Option<Refusal> {
178    let bad = |m: String| Some(refuse(StatusCode::BAD_REQUEST, m));
179    let (before, after) = (agent_env::effective(current), agent_env::effective(new));
180    let url = |m: &BTreeMap<String, String>| m.iter().find(|(k, _)| k.eq_ignore_ascii_case("ANTHROPIC_BASE_URL")).map(|(_, v)| v.trim().to_string());
181    let moved = url(&before) != url(&after);
182    let custom = url(&after).is_some_and(|u| !agent_env::is_anthropic_url(&u));
183    for (name, value) in &after {
184        if !(name.eq_ignore_ascii_case("ANTHROPIC_AUTH_TOKEN") || name.eq_ignore_ascii_case("ANTHROPIC_API_KEY")) {
185            continue;
186        }
187        let written = before.get(name) != Some(value);
188        let value = value.trim();
189        if !custom {
190            if written {
191                return bad(format!("{name}: a key goes with the address of a server of its own; set ANTHROPIC_BASE_URL in the same call"));
192            }
193            // A placeholder or a Vault reference was for the server being left; a key the person wrote is theirs.
194            if moved && (agent_env::vault_ref(value).is_some() || agent_env::is_placeholder(value)) {
195                return bad(format!("{name}: is for the server this agent was pointed at; unset it in the same call that takes the address away"));
196            }
197            continue;
198        }
199        // With a server of its own the key goes there if it is new or the address is.
200        if !(written || moved) {
201            continue;
202        }
203        let Some(entry) = agent_env::vault_ref(value) else {
204            if !value.is_empty() && !agent_env::is_placeholder(value) {
205                return bad(format!(
206                    "{name}: holds a key written in the environment, which would go to the new address; replace it with vault:<entry id> or have the person set the address in My Agents"
207                ));
208            }
209            continue;
210        };
211        let usable = |agent_id: &str| crate::backend::vault::endpoint_key::problem(&state.identity_store, entry, agent_id).is_none();
212        if actor.uid.starts_with("remote:") || !usable(&actor.uid) || !usable(&target.id) {
213            return bad(format!(
214                "{name}: {}; the person opens a Vault to an agent in the Vault's agents setting",
215                crate::backend::vault::endpoint_key::NOT_AVAILABLE
216            ));
217        }
218    }
219    None
220}
221
222/// Held from reading an environment to writing it, so two agents changing the
223/// same definition at once don't lose one change. (A save from My Agents goes
224/// through `setagentcontent` and isn't serialized with this.)
225static ENV_WRITE: std::sync::Mutex<()> = std::sync::Mutex::new(());
226
227fn run(state: &AppState, caller: Option<&Caller>, req: AgentEnvRequest) -> Result<Value, Refusal> {
228    let actor = actor_of(state, caller)?;
229    run_as(state, actor, req)
230}
231
232/// `env_get` or `env_set` for an agent on another machine (`remote_ops::agent_ops`): the same rules and
233/// write a local call has, recorded under `who` (`slug@machine`). The agent must be named: a remote
234/// caller has no definition here to default to.
235pub(crate) fn run_remote(state: &AppState, who: &str, req: AgentEnvRequest) -> Result<Value, (StatusCode, String)> {
236    if req.agent.as_deref().map(str::trim).filter(|a| !a.is_empty()).is_none() {
237        return Err((StatusCode::BAD_REQUEST, "INVALID_ARG: agent is required: the id or slug of an agent on this machine".to_string()));
238    }
239    let actor = Actor { uid: format!("remote:{who}"), slug: who.to_string(), name: who.to_string() };
240    run_as(state, actor, req).map_err(|r| (r.status, r.message))
241}
242
243fn run_as(state: &AppState, actor: Actor, req: AgentEnvRequest) -> Result<Value, Refusal> {
244    let target = target_of(state, &actor, req.agent.as_deref())?;
245    let _writing = (req.action == "set").then(|| ENV_WRITE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()));
246    let current = current_text(state, &target.id)?;
247    let agent = json!({ "id": target.id, "slug": target.slug, "name": target.name });
248    match req.action.as_str() {
249        "get" => Ok(json!({
250            "agent": agent,
251            "lines": agent_env::redacted(&current),
252            "note": "values of names an agent may not set are shown as [hidden]; a change applies at the agent's next launch",
253        })),
254        "set" => {
255            let new = match proposed(&current, &req) {
256                Ok(new) => new,
257                Err(refusal) => {
258                    audit(state, &actor, &target, false, Some(&refusal.message), "refused");
259                    return Err(refusal);
260                }
261            };
262            let change = agent_env::diff(&current, &new);
263            if new == current {
264                return Ok(json!({ "agent": agent, "changed": change, "note": "nothing changed" }));
265            }
266            // A name that changes nothing is refused, not accepted: ANTHROPIC_MODEL is read only for an agent pointed
267            // at a server of its own, and the launch passes the pane's own `--model` to every other.
268            if change.sets_model_name() && !agent_env::points_at_own_server_with(&new, &target.model_vendor_base_url) {
269                let message = format!(
270                    "ANTHROPIC_MODEL has no effect on {}: it runs on Anthropic's own service with the model its pane's picker chose, which the launch passes as --model. Use Agents update with model (and effort) to change it; ANTHROPIC_MODEL is read only for an agent pointed at a server of its own (ANTHROPIC_BASE_URL in the same call, or the definition's model vendor URL)",
271                    target.name
272                );
273                audit(state, &actor, &target, false, Some(&message), "refused (ANTHROPIC_MODEL has no effect)");
274                return Err(refuse(StatusCode::BAD_REQUEST, message));
275            }
276            let endpoint = change.touches_endpoint();
277            // Setting an endpoint name is checked in full; taking one away only for the keys it leaves behind.
278            let refusal = if change.sets_endpoint() {
279                endpoint_refusal(state, &actor, &target, &current, &new)
280            } else if endpoint {
281                key_refusal(state, &actor, &target, &current, &new)
282            } else {
283                None
284            };
285            if let Some(refusal) = refusal {
286                audit(state, &actor, &target, false, Some(&refusal.message), "refused (model endpoint)");
287                return Err(refusal);
288            }
289            let content = AgentContent {
290                agent_id: target.id.clone(),
291                content_type: agent_env::CONTENT_TYPE.to_string(),
292                content: new.clone(),
293                updated_at: agentmux_common::time::now_ms(),
294            };
295            if let Err(e) = state.mstore.agent_content_set(&content) {
296                let message = format!("agent env: {e}");
297                audit(state, &actor, &target, false, Some(&message), "not saved");
298                return Err(refuse(StatusCode::INTERNAL_SERVER_ERROR, message));
299            }
300            let summary = if endpoint { format!("{} [model endpoint]", change.summary()) } else { change.summary() };
301            let audit_id = audit(state, &actor, &target, true, None, &summary);
302            tracing::info!(
303                target: "identity",
304                actor_uid = %actor.uid,
305                actor = %actor.name,
306                agent_id = %target.id,
307                agent = %target.name,
308                "agent.env.set: {summary}"
309            );
310            state.broker.publish_event::<crate::backend::mps_events::AgentContentChanged>(&(), vec![], 0);
311            // A card and an Undo are for a change of address: not for a model name, nor for a key or a timeout on the address it had.
312            let pointed = endpoint_notice::pointed(&current, &new);
313            let noticed = pointed.moved;
314            let notice = noticed.then(|| {
315                let event = endpoint_notice::open(
316                    (&target.id, &target.slug, &target.name),
317                    &actor.name,
318                    pointed,
319                    &current,
320                    &new,
321                    agentmux_common::time::now_ms(),
322                );
323                state.broker.publish_event::<crate::backend::mps_events::AgentEndpointNotice>(&event, vec![], 0);
324                json!({ "id": event.id, "undo_for_ms": event.window_ms })
325            });
326            Ok(json!({
327                "agent": agent,
328                "changed": change,
329                "lines": agent_env::redacted(&new),
330                "audit_id": audit_id,
331                "note": if noticed {
332                    "applies at the agent's next launch, on a conversation of its own: its pane and My Agents say who pointed it where, with an Undo for 30 seconds"
333                } else {
334                    "applies at the agent's next launch"
335                },
336                "notice": notice,
337            }))
338        }
339        other => Err(refuse(StatusCode::BAD_REQUEST, format!("unknown env action '{other}': get or set"))),
340    }
341}
342
343/// Undo a model-server change within its window, for the person's Undo on the notice: puts the environment
344/// back as it was. `by` is who pressed it, for the record.
345pub(crate) fn undo_endpoint(state: &AppState, notice_id: &str, by: &str) -> Result<(), String> {
346    let agent_id = endpoint_notice::agent_id_of(notice_id).ok_or_else(|| endpoint_notice::Refusal::Unknown.words().to_string())?;
347    let def = state
348        .mstore
349        .agent_def_get(&agent_id)
350        .map_err(|e| format!("agent env: {e}"))?
351        .ok_or_else(|| format!("no agent '{agent_id}' on this machine"))?;
352    let actor = Actor { uid: format!("ui:{by}"), slug: by.to_string(), name: by.to_string() };
353    let _writing = ENV_WRITE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
354    let current = current_text(state, &def.id).map_err(|r| r.message)?;
355    let (previous, event) = endpoint_notice::check_for_undo(notice_id, &current, agentmux_common::time::now_ms()).map_err(|r| r.words().to_string())?;
356    let content = AgentContent {
357        agent_id: def.id.clone(),
358        content_type: agent_env::CONTENT_TYPE.to_string(),
359        content: previous,
360        updated_at: agentmux_common::time::now_ms(),
361    };
362    if let Err(e) = state.mstore.agent_content_set(&content) {
363        let message = format!("agent env: {e}");
364        audit(state, &actor, &def, false, Some(&message), "undo of a model endpoint change: not saved");
365        return Err(message);
366    }
367    endpoint_notice::finish_undo(notice_id);
368    audit(state, &actor, &def, true, None, &format!("undid the model endpoint change {} made", event.by));
369    state.broker.publish_event::<crate::backend::mps_events::AgentContentChanged>(&(), vec![], 0);
370    state.broker.publish_event::<crate::backend::mps_events::AgentEndpointNotice>(&event, vec![], 0);
371    Ok(())
372}
373
374/// `POST /api/v1/agent/env`
375pub(crate) async fn handle_agent_env(
376    State(state): State<AppState>,
377    caller: Option<Extension<Caller>>,
378    Json(req): Json<AgentEnvRequest>,
379) -> Response {
380    let caller = caller.map(|Extension(c)| c);
381    match tokio::task::spawn_blocking(move || run(&state, caller.as_ref(), req)).await {
382        Ok(Ok(body)) => Json(body).into_response(),
383        Ok(Err(r)) => (r.status, Json(json!({ "error": r.message }))).into_response(),
384        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": format!("agent env: {e}") }))).into_response(),
385    }
386}
387
388#[cfg(test)]
389#[path = "tests/agent_env_tests.rs"]
390mod tests;