Watch
0
0
Fork
You've already forked hyperhive
0

swarm: the commands and skills an agent's message box offers

GET /api/agents/{name}/commands answers with the swarm's own commands, a table
in the controller, then the skills the agent's harness published to its key of
the agent-commands bucket. The published part is untrusted and cut down: plain
names only, no repeats, never a command's name, a capped list and one short line
per description. The agent credential may publish its own key. Nothing publishes
yet; the harness half and the swarm UI menu follow.
This commit is contained in:
iris 2026-11-15 19:42:17 +01:00
commit 8f11a38d17
4 changed files with 389 additions and 7 deletions

View file

@ -0,0 +1,207 @@
//! 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); 1] = [(
"compact",
"Compact this agent's context after the current turn",
)];
/// 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<Skills>) -> Vec<CommandEntry> {
let mut entries: Vec<CommandEntry> = COMMANDS
.iter()
.map(|&(name, description)| CommandEntry {
name: name.to_owned(),
description: description.to_owned(),
kind: CommandKind::Command,
})
.collect();
let mut skills: Vec<CommandEntry> = 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",
body = Vec<CommandEntry>),
(status = 400, description = "the agent name is not shaped like an identifier \
(problem+json)", body = String),
(status = 503, description = "no swarm queue is configured on this host, or the \
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<AppState>,
Path(agent): Path<String>,
) -> Result<Json<Vec<CommandEntry>>, 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::<Skills>(&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"]);
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", "alpha", "zeta"]);
assert_eq!(list[1].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("good", "one"),
skill("good", "two"),
skill("two words", "not a word"),
skill("", "empty"),
],
}));
assert_eq!(names(&list), ["compact", "good"]);
assert_eq!(list[0].kind, CommandKind::Command);
assert_eq!(list[1].description, "one");
}
#[test]
fn the_list_and_the_descriptions_are_cut() {
let many: Vec<Skill> = (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)
);
}
}

View file

@ -22,6 +22,7 @@ use std::sync::{Arc, Mutex};
use anyhow::{Context, Result};
mod agent_archetype;
mod agent_commands;
mod agent_config_repo;
mod agent_control;
mod agent_custom;

View file

@ -26,13 +26,13 @@ use crate::jobq::{
use crate::routes::hives::{HiveEntry, ServiceLink};
use crate::routes::{self, AppState, agents, config_prs, forge_admin, hives, jobq_graph};
use crate::{
agent_control, agent_custom, agent_icon, agent_input, agent_limits, agent_login,
agent_permissions, agent_renewal, agent_state_stream, agent_status, agents_md, alerts,
archetypes, auth, backend_env, bash_task, builder, claude_login, config_drift, config_pr,
egress_allow, egress_deny, forge, forge_account, github_account, gitlab_account, inference,
issue_report, linked_accounts, matrix_account, message_stream, notify_flows, notify_router_api,
pause_hold, pr_report, pulls, queue_identity, review_classifier, schedules, status,
subagent_term, term_stream, wanted, webhook,
agent_commands, agent_control, agent_custom, agent_icon, agent_input, agent_limits,
agent_login, agent_permissions, agent_renewal, agent_state_stream, agent_status, agents_md,
alerts, archetypes, auth, backend_env, bash_task, builder, claude_login, config_drift,
config_pr, egress_allow, egress_deny, forge, forge_account, github_account, gitlab_account,
inference, issue_report, linked_accounts, matrix_account, message_stream, notify_flows,
notify_router_api, pause_hold, pr_report, pulls, queue_identity, review_classifier, schedules,
status, subagent_term, term_stream, wanted, webhook,
};
/// Where the daemon binds, overridable via `SWARM_CONTROLLER_SOCKET`.
@ -666,6 +666,7 @@ pub(crate) fn build_app(state: AppState) -> axum::Router {
.routes(routes!(message_stream::stream_messages))
.routes(routes!(subagent_term::list_subagents))
.routes(routes!(bash_task::list_bash_tasks))
.routes(routes!(agent_commands::list_commands))
.routes(routes!(subagent_term::stream_subagent_term))
.routes(routes!(agent_state_stream::stream_agent_state))
.routes(routes!(agent_input::post_agent_input))

View file

@ -85,6 +85,12 @@ pub(crate) fn spawn(client: async_nats::Client, wanted: Arc<WantedWriter>, hives
"bash task status: opening the bucket failed; next pass"
);
}
if let Err(e) = swarm_queue_client::agent_commands::open_or_create(&client).await {
tracing::warn!(
error = %swarm_queue_client::chain(&e),
"agent commands: opening the bucket failed; next pass"
);
}
for agent in live_agents(&wanted, &hives).await {
if let Err(e) = swarm_queue_client::bash_task::open_output(&client, &agent).await {
tracing::warn!(