use std::{collections::BTreeSet, fmt};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
pub const SERVICE_NAME: &str = "agent-registry";
pub const AUDIENCE: &str = "agent-registry";
pub const DEFAULT_PORT: u16 = 5100;
pub const HEALTH_PATH: &str = "/health";
pub const AGENTS_PATH: &str = "/internal/v1/agents";
pub const AGENT_PATH: &str = "/internal/v1/agents/{agent_id}";
pub const PUBLIC_AGENTS_PATH: &str = "/v1/agents";
pub const PUBLIC_AGENT_PATH: &str = "/v1/agents/{agent_id}";
const MAX_IDENTIFIER_BYTES: usize = 255;
const MAX_RELATIONS_PER_KIND: usize = 256;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct AgentId(String);
impl AgentId {
pub fn new(value: impl Into<String>) -> Result<Self, String> {
let value = value.into();
if !value.starts_with("agt_") {
return Err("agent_id must start with 'agt_'".into());
}
validate_identifier("agent_id", &value)?;
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl<'de> Deserialize<'de> for AgentId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Self::new(value).map_err(D::Error::custom)
}
}
impl fmt::Display for AgentId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(formatter)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ResourceRelations {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub agent_ids: Vec<AgentId>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub runtime_ids: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub user_ids: Vec<String>,
}
impl ResourceRelations {
pub fn normalize(mut self) -> Result<Self, String> {
normalize_values("agent_ids", &mut self.agent_ids)?;
normalize_strings("runtime_ids", &mut self.runtime_ids)?;
normalize_strings("user_ids", &mut self.user_ids)?;
Ok(self)
}
pub fn contains_user(&self, user_id: &str) -> bool {
self.user_ids.iter().any(|candidate| candidate == user_id)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AgentStatus {
#[default]
Active,
Archived,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Agent {
pub id: AgentId,
pub owner_user_id: String,
pub name: String,
pub description: String,
pub status: AgentStatus,
pub revision: u64,
#[serde(default)]
pub relations: ResourceRelations,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CreateAgentRequest {
pub name: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub relations: ResourceRelations,
pub idempotency_key: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct UpdateAgentRequest {
pub expected_revision: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<AgentStatus>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub relations: Option<ResourceRelations>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ListAgentsRequest {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<AgentStatus>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub related_agent_id: Option<AgentId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub related_runtime_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub related_user_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cursor: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AgentPage {
pub items: Vec<Agent>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_cursor: Option<String>,
}
pub fn validate_name(value: &str) -> Result<String, String> {
let value = value.trim();
if value.is_empty() || value.chars().count() > 128 {
return Err("agent name must contain 1..=128 characters".into());
}
if value.chars().any(char::is_control) {
return Err("agent name must not contain control characters".into());
}
Ok(value.to_string())
}
pub fn validate_description(value: &str) -> Result<String, String> {
let value = value.trim();
if value.chars().count() > 4096 {
return Err("agent description must contain at most 4096 characters".into());
}
if value.chars().any(|character| character == '\0') {
return Err("agent description must not contain NUL".into());
}
Ok(value.to_string())
}
pub fn validate_identifier(field: &str, value: &str) -> Result<(), String> {
if value.is_empty() || value.len() > MAX_IDENTIFIER_BYTES {
return Err(format!(
"{field} must contain 1..={MAX_IDENTIFIER_BYTES} bytes"
));
}
if !value.bytes().all(|byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':' | b'@')
}) {
return Err(format!("{field} contains unsupported characters"));
}
Ok(())
}
fn normalize_strings(field: &str, values: &mut Vec<String>) -> Result<(), String> {
if values.len() > MAX_RELATIONS_PER_KIND {
return Err(format!("{field} contains too many relations"));
}
for value in values.iter_mut() {
*value = value.trim().to_string();
validate_identifier(field, value)?;
}
values.sort();
values.dedup();
Ok(())
}
fn normalize_values(field: &str, values: &mut Vec<AgentId>) -> Result<(), String> {
if values.len() > MAX_RELATIONS_PER_KIND {
return Err(format!("{field} contains too many relations"));
}
let unique = values.iter().cloned().collect::<BTreeSet<_>>();
*values = unique.into_iter().collect();
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn relations_are_sets_not_singular_scope_fields() {
let relations = ResourceRelations {
agent_ids: vec![
AgentId::new("agt_b").unwrap(),
AgentId::new("agt_a").unwrap(),
],
runtime_ids: vec!["runtime-1".into(), "runtime-1".into()],
user_ids: vec!["user-2".into(), "user-1".into()],
}
.normalize()
.unwrap();
assert_eq!(relations.agent_ids[0].as_str(), "agt_a");
assert_eq!(relations.runtime_ids, ["runtime-1"]);
assert_eq!(relations.user_ids, ["user-1", "user-2"]);
}
#[test]
fn agent_id_validation_cannot_be_bypassed_by_json() {
let error = serde_json::from_str::<AgentId>(r#""agent-legacy""#).unwrap_err();
assert!(error.to_string().contains("must start with 'agt_'"));
}
}