Watch
0
0
Fork
You've already forked hyperhive
0

swarm: an agent's open todos, mirrored to the queue and served by the controller

This commit is contained in:
iris 2026-11-16 00:28:54 +01:00 • committed by mara
commit b239500f88
4 changed files with 478 additions and 6 deletions

View file

@ -0,0 +1,171 @@
//! The open todos an agent holds, for the swarm UI's agent card:
//! `GET /api/agents/{name}/todos`.
//!
//! The list is what the agent's harness last published into the `agent-todos`
//! bucket (`swarm_wire::agent_todos`); the controller only reads it. It comes
//! from the agent and is untrusted, so [`build`] cuts it down before serving
//! it. An agent that never published, or a host with no swarm queue, has no
//! todos to show: an empty list, not an error.
use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use serde::Serialize;
use swarm_wire::agent_todos::{self, Todos};
use utoipa::ToSchema;
use crate::routes::AppState;
/// One open todo.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, ToSchema)]
pub(crate) struct TodoEntry {
/// The harness's own id for it.
pub id: i64,
/// What produced it: `matrix`, `forge`, `bash`, …
pub subsystem: String,
/// What it says, as one line.
pub summary: String,
/// Where it came from, when the producer says.
#[serde(skip_serializing_if = "Option::is_none")]
pub source: Option<String>,
/// When it was last updated, in seconds since the Unix epoch.
pub updated_unix: i64,
}
/// The list for an agent whose harness published `published` (or nothing),
/// newest first, cut to [`agent_todos::MAX_TODOS`] with each text one short
/// line.
fn build(published: Option<Todos>) -> Vec<TodoEntry> {
let mut entries: Vec<TodoEntry> = published
.unwrap_or_default()
.todos
.into_iter()
.map(|t| TodoEntry {
id: t.id,
subsystem: agent_todos::clip(&t.subsystem, agent_todos::MAX_LABEL_CHARS),
summary: agent_todos::clip(&t.summary, agent_todos::MAX_SUMMARY_CHARS),
source: t
.source
.map(|s| agent_todos::clip(&s, agent_todos::MAX_LABEL_CHARS))
.filter(|s| !s.is_empty()),
updated_unix: t.updated_unix,
})
.collect();
entries.sort_by_key(|e| std::cmp::Reverse(e.updated_unix));
entries.truncate(agent_todos::MAX_TODOS);
entries
}
#[utoipa::path(
get,
path = "/api/agents/{name}/todos",
params(("name" = String, Path, description = "agent whose open todos to list")),
responses(
(status = 200, description = "the open todos the agent's harness last published, \
newest first; empty when it has published none and on a host with no swarm queue",
body = Vec<TodoEntry>),
(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 todos failed (problem+json)",
body = String),
),
tag = "agents"
)]
pub(crate) async fn list_todos(
State(state): State<AppState>,
Path(agent): Path<String>,
) -> Result<Json<Vec<TodoEntry>>, 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 {
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_todos::BUCKET).await {
Ok(store) => match store.get(&agent).await {
Ok(Some(bytes)) => serde_json::from_slice::<Todos>(&bytes)
.map_err(|e| {
tracing::warn!(%agent, error = %e, "agent todos: the published list is 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 todos: 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 todos: reading the agent's todos failed");
crate::routes::error_problem(StatusCode::INTERNAL_SERVER_ERROR, &detail)
}
#[cfg(test)]
mod tests {
use super::*;
use swarm_wire::agent_todos::Todo;
fn todo(id: i64, summary: &str, updated_unix: i64) -> Todo {
Todo {
id,
subsystem: "forge".to_owned(),
summary: summary.to_owned(),
source: None,
updated_unix,
}
}
/// An agent that published nothing has nothing to show.
#[test]
fn nothing_published_is_an_empty_list() {
assert!(build(None).is_empty());
}
#[test]
fn the_newest_todo_comes_first() {
let list = build(Some(Todos {
todos: vec![
todo(1, "old", 100),
todo(2, "new", 300),
todo(3, "mid", 200),
],
}));
let ids: Vec<i64> = list.iter().map(|e| e.id).collect();
assert_eq!(ids, [2, 3, 1]);
}
/// What the agent publishes is untrusted: the list and each text are cut.
#[test]
fn the_list_and_the_texts_are_cut() {
let many: Vec<Todo> = (0..i64::try_from(agent_todos::MAX_TODOS).expect("fits") + 20)
.map(|i| todo(i, &"w ".repeat(1000), i))
.collect();
let list = build(Some(Todos { todos: many }));
assert_eq!(list.len(), agent_todos::MAX_TODOS);
assert!(list[0].summary.chars().count() <= agent_todos::MAX_SUMMARY_CHARS);
}
#[test]
fn a_blank_source_is_left_out() {
let mut t = todo(1, "x", 1);
t.source = Some(" ".to_owned());
assert_eq!(build(Some(Todos { todos: vec![t] }))[0].source, None);
}
}

View file

@ -37,6 +37,7 @@ mod agent_renewal;
mod agent_role_ttl;
mod agent_state_stream;
mod agent_status;
mod agent_todos;
mod agents_md;
mod agents_md_initial;
mod alerts;

View file

@ -27,12 +27,12 @@ use crate::routes::hives::{HiveEntry, ServiceLink};
use crate::routes::{self, AppState, agents, config_prs, forge_admin, hives, jobq_graph};
use crate::{
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,
agent_login, agent_permissions, agent_renewal, agent_state_stream, agent_status, agent_todos,
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`.
@ -668,6 +668,7 @@ pub(crate) fn build_app(state: AppState) -> axum::Router {
.routes(routes!(subagent_term::list_subagents))
.routes(routes!(bash_task::list_bash_tasks))
.routes(routes!(agent_commands::list_commands))
.routes(routes!(agent_todos::list_todos))
.routes(routes!(subagent_term::stream_subagent_term))
.routes(routes!(agent_state_stream::stream_agent_state))
.routes(routes!(agent_input::post_agent_input))

View file

@ -91,6 +91,12 @@ pub(crate) fn spawn(client: async_nats::Client, wanted: Arc<WantedWriter>, hives
"agent commands: opening the bucket failed; next pass"
);
}
if let Err(e) = swarm_queue_client::agent_todos::open_or_create(&client).await {
tracing::warn!(
error = %swarm_queue_client::chain(&e),
"agent todos: 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!(