1use 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
29pub(crate) const AUDIT_ACTION: &str = "agent.env.set";
31
32#[derive(Debug, Deserialize)]
33pub(crate) struct AgentEnvRequest {
34 action: String,
36 #[serde(default)]
38 agent: Option<String>,
39 #[serde(default)]
41 lines: Option<String>,
42 #[serde(default)]
44 set: Option<BTreeMap<String, String>>,
45 #[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
59struct 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
81fn 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
107fn 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
145fn 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
170fn 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 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 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
222static 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
232pub(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(¤t),
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(¤t, &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(¤t, &new);
263 if new == current {
264 return Ok(json!({ "agent": agent, "changed": change, "note": "nothing changed" }));
265 }
266 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 let refusal = if change.sets_endpoint() {
279 endpoint_refusal(state, &actor, &target, ¤t, &new)
280 } else if endpoint {
281 key_refusal(state, &actor, &target, ¤t, &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 let pointed = endpoint_notice::pointed(¤t, &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 ¤t,
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
343pub(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, ¤t, 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
374pub(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;