//! The commands and skills an agent's message box offers in the swarm UI: //! `GET /api/agents/{name}/commands`. //! //! The list is the swarm's own commands, a table here, followed by the skills //! the agent's harness published (`swarm_wire::agent_commands`). Adding a //! swarm command is one line of [`COMMANDS`]. The published part comes from //! the agent and is untrusted, so [`build`] cuts it down and never lets a skill //! take the name of a command. use axum::Json; use axum::extract::{Path, State}; use axum::http::StatusCode; use serde::Serialize; use swarm_wire::agent_commands::{self, Skills}; use utoipa::ToSchema; use crate::routes::AppState; /// The commands the swarm UI offers every agent: the name without the slash, /// and what it does. const COMMANDS: [(&str, &str); 3] = [ ( "compact", "Compact this agent's context after the current turn", ), ( "clear", "Start the next turn on a fresh session, dropping this one's context", ), ("clear-todos", "Mark all of this agent's todos done"), ]; /// Whether an entry is one of the swarm's commands or a skill of the agent. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub(crate) enum CommandKind { /// A command of the swarm. Command, /// A skill the agent has. Skill, } /// One entry of the list. #[derive(Debug, Clone, PartialEq, Eq, Serialize, ToSchema)] pub(crate) struct CommandEntry { /// The name without the slash. pub name: String, /// One line saying what it does. pub description: String, pub kind: CommandKind, } /// The list for an agent whose harness published `published` (or nothing): /// the swarm's commands, then the skills sorted by name. A skill is dropped when /// its name is not a plain word, repeats an earlier name, or is a command's; /// the list is cut to [`agent_commands::MAX_SKILLS`] skills and each /// description to one short line. fn build(published: Option) -> Vec { let mut entries: Vec = COMMANDS .iter() .map(|&(name, description)| CommandEntry { name: name.to_owned(), description: description.to_owned(), kind: CommandKind::Command, }) .collect(); let mut skills: Vec = Vec::new(); for skill in published.unwrap_or_default().skills { let taken = |entries: &[CommandEntry]| entries.iter().any(|e| e.name == skill.name); if !agent_commands::is_plain_name(&skill.name) || taken(&entries) || taken(&skills) { continue; } skills.push(CommandEntry { name: skill.name, description: agent_commands::clip_description(&skill.description), kind: CommandKind::Skill, }); if skills.len() >= agent_commands::MAX_SKILLS { break; } } skills.sort_by(|a, b| a.name.cmp(&b.name)); entries.extend(skills); entries } #[utoipa::path( get, path = "/api/agents/{name}/commands", params(("name" = String, Path, description = "agent whose commands to list")), responses( (status = 200, description = "the swarm's own commands, then the skills the agent's \ harness published, for the message box's command menu; just the swarm's commands \ when the agent has published none and on a host with no swarm queue", body = Vec), (status = 400, description = "the agent name is not shaped like an identifier \ (problem+json)", body = String), (status = 503, description = "the swarm queue could not be reached \ (problem+json)", body = String), (status = 500, description = "reading the agent's skills failed (problem+json)", body = String), ), tag = "agents" )] pub(crate) async fn list_commands( State(state): State, Path(agent): Path, ) -> Result>, problem_details::ProblemDetails> { let agent = hive_types::Ident::parse(&agent) .map(hive_types::Ident::into_string) .map_err(|reason| crate::routes::error_problem(StatusCode::BAD_REQUEST, reason))?; let Some(status) = state.status.as_ref() else { // No queue here, so no agent has published skills: the swarm's own // commands still make a useful menu. return Ok(Json(build(None))); }; let client = status.queue_client(); swarm_queue_client::ensure_connected(&client).map_err(|e| { crate::routes::error_problem( StatusCode::SERVICE_UNAVAILABLE, &swarm_queue_client::chain(&e), ) })?; let js = async_nats::jetstream::new(client); // The controller creates the bucket on a pass of `subagent_term::spawn`; // until then nothing has published. let published = match js.get_key_value(agent_commands::BUCKET).await { Ok(store) => match store.get(&agent).await { Ok(Some(bytes)) => serde_json::from_slice::(&bytes) .map_err(|e| { tracing::warn!(%agent, error = %e, "agent commands: the published skills are not readable"); }) .ok(), Ok(None) => None, Err(e) => return Err(read_failed(&agent, &e)), }, Err(e) => { tracing::debug!(%agent, error = %swarm_queue_client::chain(&e), "agent commands: the bucket is not readable"); None } }; Ok(Json(build(published))) } fn read_failed(agent: &str, e: &dyn std::error::Error) -> problem_details::ProblemDetails { let detail = swarm_queue_client::chain(e); tracing::warn!(%agent, error = %detail, "listing commands: reading the agent's skills failed"); crate::routes::error_problem(StatusCode::INTERNAL_SERVER_ERROR, &detail) } #[cfg(test)] mod tests { use super::*; use swarm_wire::agent_commands::Skill; fn skill(name: &str, description: &str) -> Skill { Skill { name: name.to_owned(), description: description.to_owned(), } } fn names(entries: &[CommandEntry]) -> Vec<&str> { entries.iter().map(|e| e.name.as_str()).collect() } /// An agent that published nothing still gets the swarm's own commands. #[test] fn the_swarms_commands_come_first_and_always() { let list = build(None); assert_eq!(names(&list), ["compact", "clear", "clear-todos"]); assert!(list.iter().all(|e| e.kind == CommandKind::Command)); } #[test] fn skills_follow_sorted_by_name() { let list = build(Some(Skills { skills: vec![skill("zeta", "z"), skill("alpha", "a")], })); assert_eq!( names(&list), ["compact", "clear", "clear-todos", "alpha", "zeta"] ); assert_eq!(list[3].kind, CommandKind::Skill); } /// What the agent publishes is untrusted: a skill cannot take a command's /// name, repeat a name, or have a name that is not one plain word. #[test] fn a_published_skill_cannot_shadow_or_repeat_or_break_the_box() { let list = build(Some(Skills { skills: vec![ skill("compact", "pretends to be the command"), skill("clear", "so does this"), skill("good", "one"), skill("good", "two"), skill("two words", "not a word"), skill("", "empty"), ], })); assert_eq!(names(&list), ["compact", "clear", "clear-todos", "good"]); assert_eq!(list[0].kind, CommandKind::Command); assert_eq!(list[3].description, "one"); } #[test] fn the_list_and_the_descriptions_are_cut() { let many: Vec = (0..agent_commands::MAX_SKILLS + 20) .map(|i| skill(&format!("s{i:04}"), &"d ".repeat(300))) .collect(); let list = build(Some(Skills { skills: many })); assert_eq!(list.len(), COMMANDS.len() + agent_commands::MAX_SKILLS); assert!( list.iter() .all(|e| e.description.chars().count() <= agent_commands::MAX_DESCRIPTION_CHARS) ); } }