use std::sync::Arc;
use axum::Json;
use axum::Router;
use axum::extract::{Path as UrlPath, State};
use axum::routing::get;
use serde::{Deserialize, Serialize};
use super::paths;
use super::routes::{Caller, ControlBackend};
use crate::agents::AgentView;
use crate::error::{AGENT_NOT_FOUND_CODE, KernelError, Result};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentsResponse {
pub agents: Vec<AgentView>,
}
type Backend = State<Arc<dyn ControlBackend>>;
pub(super) fn routes() -> Router<Arc<dyn ControlBackend>> {
Router::new().route(paths::AGENTS, get(list)).route(paths::AGENT, get(one))
}
fn table(backend: &dyn ControlBackend) -> Result<&crate::agents::Agents> {
backend.kernel().map(crate::Kernel::agents).ok_or_else(|| KernelError::Config {
reason: "this control plane serves no kernel, so it keeps no agents".into(),
})
}
async fn list(State(backend): Backend, caller: Caller) -> Result<Json<AgentsResponse>> {
caller.require_operator("read the agents")?;
let agents = table(backend.as_ref())?.list().await?;
Ok(Json(AgentsResponse { agents }))
}
async fn one(
State(backend): Backend,
caller: Caller,
UrlPath(id): UrlPath<String>,
) -> Result<Json<AgentView>> {
caller.require_operator("read an agent")?;
match table(backend.as_ref())?.get(&id).await? {
Some(view) => Ok(Json(view)),
None => Err(KernelError::Core(adk_core::AdkError::new(
adk_core::ErrorComponent::Server,
adk_core::ErrorCategory::NotFound,
AGENT_NOT_FOUND_CODE,
format!("no agent `{id}`; list them with `adk-rust agents`"),
))),
}
}