Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/swarm-controller/src/agents/mod.rs

206 lines
7.6 KiB
Rust

//! The agents concern: creating and running agents, their state, limits,
//! permissions and streams, the schedules and the wanted placement, with
//! the `/api/agents` routes.
pub(crate) mod agent_archetype;
pub(crate) mod agent_commands;
pub(crate) mod agent_config_repo;
pub(crate) mod agent_control;
pub(crate) mod agent_custom;
pub(crate) mod agent_icon;
pub(crate) mod agent_input;
pub(crate) mod agent_limits;
pub(crate) mod agent_login;
pub(crate) mod agent_permissions;
pub(crate) mod agent_ssh;
pub(crate) mod agent_state_stream;
pub(crate) mod agent_status;
pub(crate) mod agent_todos;
pub(crate) mod agents_md;
pub(crate) mod agents_md_initial;
pub(crate) mod inference;
pub(crate) mod message_stream;
pub(crate) mod pause_hold;
pub(crate) mod routes;
pub(crate) mod schedules;
pub(crate) mod subagent_term;
pub(crate) mod term_stream;
pub(crate) mod wanted;
use std::sync::Arc;
use axum::extract::FromRef;
use crate::routes::AppState;
/// What the agent I/O handlers (commands, control, todos, input, the term,
/// message and state streams, subagents) may reach of [`AppState`]: the queue
/// reader, the identity bridge for the roster, the per-agent status reader and
/// the reported turn-state headers.
///
/// Derived per request from [`AppState`] (`FromRef`), so each field is a clone
/// of the same `Arc`. The SSE streams take their subscriber inside the handler
/// and hold nothing of this past it.
#[derive(Clone)]
pub(crate) struct AgentIoState {
pub(crate) status: Option<Arc<crate::status::StatusReader>>,
pub(crate) auth: Option<Arc<crate::auth::AuthBridge>>,
pub(crate) agent_status: Option<Arc<crate::agent_status::AgentStatusReader>>,
pub(crate) reported_inference: Option<Arc<crate::inference::Reported>>,
}
impl FromRef<AppState> for AgentIoState {
fn from_ref(state: &AppState) -> Self {
Self {
status: state.status.clone(),
auth: state.auth.clone(),
agent_status: state.agent_status.clone(),
reported_inference: state.reported_inference.clone(),
}
}
}
/// What the agent read routes (roster, icon, `AGENTS.md`) may reach of
/// [`AppState`]: the identity bridge and the icon and `AGENTS.md` readers.
///
/// Derived per request from [`AppState`] (`FromRef`), so each field is a clone
/// of the same `Arc`.
#[derive(Clone)]
pub(crate) struct AgentReadersState {
pub(crate) auth: Option<Arc<crate::auth::AuthBridge>>,
pub(crate) agent_icons: Option<Arc<crate::agent_icon::AgentIconReader>>,
pub(crate) agents_md: Option<Arc<crate::agents_md::AgentsMdReader>>,
}
impl FromRef<AppState> for AgentReadersState {
fn from_ref(state: &AppState) -> Self {
Self {
auth: state.auth.clone(),
agent_icons: state.agent_icons.clone(),
agents_md: state.agents_md.clone(),
}
}
}
/// What the agent settings handlers (schedules, limits, permissions,
/// inference) may reach of [`AppState`]: the queue reader, the wanted-state
/// writer and hive list that say which agents are live, and what the agents
/// reported (login capabilities, inference in use).
///
/// Derived per request from [`AppState`] (`FromRef`), so each field is a clone
/// of the same `Arc` and nothing is held twice.
#[derive(Clone)]
pub(crate) struct AgentSettingsState {
pub(crate) status: Option<Arc<crate::status::StatusReader>>,
pub(crate) wanted: Option<Arc<crate::wanted::WantedWriter>>,
pub(crate) hives: Arc<Vec<crate::routes::hives::HiveEntry>>,
pub(crate) agent_login: Option<Arc<agent_login::Reported>>,
pub(crate) reported_inference: Option<Arc<inference::Reported>>,
}
impl FromRef<AppState> for AgentSettingsState {
fn from_ref(state: &AppState) -> Self {
Self {
status: state.status.clone(),
wanted: state.wanted.clone(),
hives: Arc::clone(&state.hives),
agent_login: state.agent_login.clone(),
reported_inference: state.reported_inference.clone(),
}
}
}
impl AgentSettingsState {
/// The connected queue client, or the problem.
///
/// # Errors
/// A 503 when no queue is configured or it is not connected.
pub(crate) fn queue(&self) -> Result<async_nats::Client, (axum::http::StatusCode, String)> {
schedules::queue_of(self.status.as_ref())
}
/// Every agent some hive declares and has not destroyed.
///
/// # Errors
/// A 503 when no wanted-state writer is configured.
pub(crate) async fn live(
&self,
) -> Result<std::collections::BTreeSet<String>, problem_details::ProblemDetails> {
schedules::live_of(self.wanted.as_ref(), &self.hives).await
}
}
#[cfg(test)]
mod tests {
use axum::http::StatusCode;
use crate::routes::AppState;
use crate::routes::tests::state_with_roster;
async fn disconnected_client() -> async_nats::Client {
async_nats::ConnectOptions::new()
.retry_on_initial_connect()
.connect("127.0.0.1:1")
.await
.expect("retry_on_initial_connect returns without waiting for a real connection")
}
async fn get(state: AppState, path: &str) -> (StatusCode, String) {
use axum::body::Body;
use axum::http::Request;
use tower::ServiceExt as _;
let res = crate::startup::build_app(state)
.oneshot(Request::get(path).body(Body::empty()).expect("a request"))
.await
.expect("answers");
let code = res.status();
let body = axum::body::to_bytes(res.into_body(), usize::MAX)
.await
.expect("a body");
(code, String::from_utf8_lossy(&body).into_owned())
}
/// Through the real router, so `AgentIoState::from_ref` runs: a queue that
/// is configured but not connected answers 503 naming the connection, and
/// without one the 503 says none is configured.
#[tokio::test]
async fn agent_io_state_carries_the_queue_reader() {
let (state, _sched) = state_with_roster();
let (code, body) = get(state.clone(), "/api/agents/iris/subagents").await;
assert_eq!(code, StatusCode::SERVICE_UNAVAILABLE);
assert!(body.contains("no swarm queue is configured"), "{body}");
let state = AppState {
status: Some(std::sync::Arc::new(crate::status::StatusReader::new(
disconnected_client().await,
std::time::Duration::from_mins(1),
))),
..state
};
let (code, body) = get(state, "/api/agents/iris/subagents").await;
assert_eq!(code, StatusCode::SERVICE_UNAVAILABLE);
assert!(!body.contains("no swarm queue is configured"), "{body}");
}
/// Through the real router, so `AgentReadersState::from_ref` runs: an icon
/// reader on a client that never connected is asked and fails 503 with the
/// connection's reason; without one the 503 says no queue is wired up.
#[tokio::test]
async fn agent_readers_state_carries_the_icon_reader() {
let (state, _sched) = state_with_roster();
let (code, body) = get(state.clone(), "/api/agents/iris/icon").await;
assert_eq!(code, StatusCode::SERVICE_UNAVAILABLE);
assert!(body.contains("no swarm queue is wired up"), "{body}");
let state = AppState {
agent_icons: Some(std::sync::Arc::new(
crate::agent_icon::AgentIconReader::new(disconnected_client().await),
)),
..state
};
let (code, body) = get(state, "/api/agents/iris/icon").await;
assert_eq!(code, StatusCode::SERVICE_UNAVAILABLE);
assert!(!body.contains("no swarm queue is wired up"), "{body}");
}
}