Skip to main content

agentmux_srv_core/backend/agent_archive/
definition.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The definition an archive carries: an allowlist, not a denylist (spec section 4.1). A definition is instructions
5//! for a process that runs commands, so a field an archive could set that widens what the agent may do at the
6//! destination (permission mode, extra directories, shell, remote connections, MCP servers, environment, hooks,
7//! auto-approve rules, accounts, the working directory, the container's image and volumes) is not a field of
8//! [`PortableDefinition`] at all. Reading an archive keeps the fields below, drops every other key and lists what it
9//! dropped, so the arrival note can say so.
10
11use serde::{Deserialize, Serialize};
12
13use super::ArchiveError;
14use crate::backend::agent_session::is_valid_definition_id;
15use crate::backend::storage::AgentDefinition;
16use crate::registry::AgentSeat;
17
18/// The route and model the agent runs on, as ids. The destination checks them against its own catalog.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20#[serde(deny_unknown_fields)]
21pub struct RouteChoice {
22    pub route: String,
23    pub model: String,
24}
25
26#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
27#[serde(deny_unknown_fields)]
28pub struct PortableDefinition {
29    pub uid: String,
30    pub slug: String,
31    pub name: String,
32    pub icon: String,
33    pub description: String,
34    /// The harness (`provider`): fixed for an agent's life.
35    pub harness: String,
36    pub agent_type: String,
37    pub auto_start: i64,
38    pub restart_on_crash: i64,
39    pub idle_timeout_minutes: i64,
40    pub parent_id: String,
41    pub branch_label: String,
42    pub conversation_visibility: String,
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub route: Option<RouteChoice>,
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub seat: Option<AgentSeat>,
47    /// The kind of computer it was exported from (`windows`, `linux`, `macos`), for the arrival note: the paths in the
48    /// conversation refer to it.
49    pub source_os: String,
50}
51
52/// The keys of `agent.json` this build reads. Every other key is dropped.
53pub const ALLOWED_KEYS: &[&str] = &[
54    "uid",
55    "slug",
56    "name",
57    "icon",
58    "description",
59    "harness",
60    "agent_type",
61    "auto_start",
62    "restart_on_crash",
63    "idle_timeout_minutes",
64    "parent_id",
65    "branch_label",
66    "conversation_visibility",
67    "route",
68    "seat",
69    "source_os",
70];
71
72/// What reading `agent.json` gave.
73#[derive(Debug, Clone, PartialEq)]
74pub struct ParsedDefinition {
75    pub definition: PortableDefinition,
76    /// The keys the archive had that are not on the allowlist, sorted.
77    pub dropped: Vec<String>,
78    /// A seat role that was not carried (`super` is never carried: it is given on the destination, by its own route).
79    pub seat_role_dropped: Option<String>,
80}
81
82impl PortableDefinition {
83    /// The portable form of a definition read from the store, with the route its owner chose.
84    pub fn from_definition(def: &AgentDefinition, route: Option<RouteChoice>) -> Self {
85        Self {
86            uid: def.id.clone(),
87            slug: def.slug.clone(),
88            name: def.name.clone(),
89            icon: def.icon.clone(),
90            description: def.description.clone(),
91            harness: def.provider.clone(),
92            agent_type: def.agent_type.clone(),
93            auto_start: def.auto_start,
94            restart_on_crash: def.restart_on_crash,
95            idle_timeout_minutes: def.idle_timeout_minutes,
96            parent_id: def.parent_id.clone(),
97            branch_label: def.branch_label.clone(),
98            conversation_visibility: def.conversation_visibility.clone(),
99            route,
100            seat: def.seat.clone(),
101            source_os: std::env::consts::OS.to_string(),
102        }
103    }
104
105    pub fn to_json(&self) -> Result<Vec<u8>, ArchiveError> {
106        serde_json::to_vec_pretty(self).map_err(|e| ArchiveError::Io(e.to_string()))
107    }
108
109    /// Reads `agent.json` through the allowlist and checks each carried value.
110    pub fn parse(bytes: &[u8]) -> Result<ParsedDefinition, ArchiveError> {
111        let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| ArchiveError::Malformed(format!("agent.json: {e}")))?;
112        let serde_json::Value::Object(map) = value else {
113            return Err(ArchiveError::Malformed("agent.json is not an object".to_string()));
114        };
115        let mut dropped: Vec<String> = map.keys().filter(|k| !ALLOWED_KEYS.contains(&k.as_str())).cloned().collect();
116        dropped.sort();
117        let kept: serde_json::Map<String, serde_json::Value> = map.into_iter().filter(|(k, _)| ALLOWED_KEYS.contains(&k.as_str())).collect();
118        let mut definition: PortableDefinition =
119            serde_json::from_value(serde_json::Value::Object(kept)).map_err(|e| ArchiveError::Malformed(format!("agent.json: {e}")))?;
120        let mut seat_role_dropped = None;
121        if let Some(seat) = &mut definition.seat {
122            if seat.role.eq_ignore_ascii_case("super") {
123                seat_role_dropped = Some(seat.role.clone());
124                definition.seat = None;
125            }
126        }
127        definition.check()?;
128        Ok(ParsedDefinition { definition, dropped, seat_role_dropped })
129    }
130
131    fn check(&self) -> Result<(), ArchiveError> {
132        let bad = |what: &str| Err(ArchiveError::Malformed(format!("agent.json: {what}")));
133        if !is_valid_definition_id(&self.uid) || self.uid.len() > 64 {
134            return bad("uid is not an agent id");
135        }
136        if self.name.trim().is_empty() || self.name.chars().count() > 64 || self.name.chars().any(char::is_control) {
137            return bad("name is empty, longer than 64 characters or not on one line");
138        }
139        if self.slug.is_empty() || self.slug.chars().count() > 64 || self.slug.chars().any(|c| c.is_control() || c == '/' || c == '\\') {
140            return bad("slug is not a plain name");
141        }
142        if self.icon.chars().count() > 64 || self.icon.chars().any(char::is_control) {
143            return bad("icon is too long");
144        }
145        if self.description.chars().count() > 4000 {
146            return bad("description is longer than 4000 characters");
147        }
148        for (field, value) in [("harness", &self.harness), ("agent_type", &self.agent_type), ("conversation_visibility", &self.conversation_visibility)] {
149            if value.is_empty() || value.len() > 32 || !value.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_') {
150                return bad(&format!("{field} is not a plain lowercase word"));
151            }
152        }
153        if !(0..=1).contains(&self.auto_start) || !(0..=1).contains(&self.restart_on_crash) {
154            return bad("auto_start and restart_on_crash are 0 or 1");
155        }
156        if !(0..=1_000_000).contains(&self.idle_timeout_minutes) {
157            return bad("idle_timeout_minutes is out of range");
158        }
159        for (field, value) in [("parent_id", &self.parent_id), ("branch_label", &self.branch_label)] {
160            if value.chars().count() > 128 || value.chars().any(char::is_control) {
161                return bad(&format!("{field} is too long"));
162            }
163        }
164        if let Some(r) = &self.route {
165            if r.route.len() > 64 || r.model.len() > 128 || r.route.chars().chain(r.model.chars()).any(char::is_control) {
166                return bad("route is malformed");
167            }
168        }
169        if self.source_os.len() > 16 || !self.source_os.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) {
170            return bad("source_os is not a plain word");
171        }
172        Ok(())
173    }
174}