use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::watch;
use super::config::MultiAgentConfig;
use super::path::AgentPath;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AgentStatus {
Queued,
Running,
Done,
Failed,
Cancelled,
Closed,
Paused,
Unknown,
}
impl AgentStatus {
pub fn name(&self) -> &'static str {
match self {
Self::Queued => "queued",
Self::Running => "running",
Self::Done => "done",
Self::Failed => "failed",
Self::Cancelled => "cancelled",
Self::Closed => "closed",
Self::Paused => "paused",
Self::Unknown => "unknown",
}
}
pub fn from_name(name: &str) -> AgentStatus {
match name {
"queued" => Self::Queued,
"running" => Self::Running,
"done" => Self::Done,
"failed" => Self::Failed,
"cancelled" => Self::Cancelled,
"closed" => Self::Closed,
"paused" => Self::Paused,
_ => Self::Unknown,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ResultKind {
Success,
Failed(String),
Cancelled,
}
pub fn derive_status(
registered: bool,
in_flight: bool,
queue_len: usize,
last_result: Option<&ResultKind>,
) -> AgentStatus {
match (registered, in_flight, queue_len) {
(false, _, _) => AgentStatus::Closed,
(_, true, _) => AgentStatus::Running,
(_, false, 0) => match last_result {
Some(ResultKind::Failed(_)) => AgentStatus::Failed,
Some(ResultKind::Cancelled) => AgentStatus::Cancelled,
_ => AgentStatus::Done,
},
(_, false, _) => AgentStatus::Queued,
}
}
#[derive(Clone, Debug)]
pub struct AgentEntry {
pub path: AgentPath,
pub depth: i32,
pub queue_len: usize,
pub in_flight: bool,
pub running_since: Option<Instant>,
pub closing: bool,
pub results_posted: usize,
pub results_handed_over: usize,
pub tool_calls: usize,
pub last_activity: Option<Instant>,
pub task: Option<String>,
pub last_result: Option<ResultKind>,
pub last_error: Option<String>,
}
impl AgentEntry {
pub fn status(&self) -> AgentStatus {
if self.closing {
return AgentStatus::Closed;
}
derive_status(
true,
self.in_flight,
self.queue_len,
self.last_result.as_ref(),
)
}
}
#[derive(Clone, Debug)]
pub struct AgentLifecycleEvent {
pub path: AgentPath,
pub from: AgentStatus,
pub to: AgentStatus,
pub reason: &'static str,
}
#[derive(Clone, Debug, Default)]
pub struct RegistrySnapshot {
pub agents: Vec<AgentSnapshot>,
}
#[derive(Clone, Debug)]
pub struct AgentSnapshot {
pub path: String,
pub status: String,
pub running_secs: Option<u64>,
pub last_activity_secs: Option<u64>,
pub tool_calls: usize,
pub task: Option<String>,
pub pending_results: usize,
pub last_error: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SpawnError {
MaxAgentsReached { max: usize },
DepthLimitReached { max: i32, attempted: i32 },
AlreadyExists,
}
impl std::fmt::Display for SpawnError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::MaxAgentsReached { max } => {
write!(f, "max agents reached (limit: {})", max)
}
Self::DepthLimitReached { max, attempted } => {
write!(
f,
"agent depth limit reached (max: {}, attempted: {})",
max, attempted
)
}
Self::AlreadyExists => {
write!(f, "agent with this path already exists")
}
}
}
}
pub struct AgentRegistry {
config: MultiAgentConfig,
agents: HashMap<AgentPath, AgentEntry>,
events: VecDeque<AgentLifecycleEvent>,
snapshot_tx: watch::Sender<Arc<RegistrySnapshot>>,
}
const EVENT_RING_CAP: usize = 2048;
impl AgentRegistry {
pub fn new(config: MultiAgentConfig) -> Self {
let (snapshot_tx, _) = watch::channel(Arc::new(RegistrySnapshot::default()));
Self {
config,
agents: HashMap::new(),
events: VecDeque::new(),
snapshot_tx,
}
}
pub fn can_spawn(&self, depth: i32) -> Result<(), SpawnError> {
if self.config.enabled && self.agents.len() >= self.config.max_sub_agents {
return Err(SpawnError::MaxAgentsReached {
max: self.config.max_sub_agents,
});
}
if self.config.enabled && depth > self.config.max_agent_depth {
return Err(SpawnError::DepthLimitReached {
max: self.config.max_agent_depth,
attempted: depth,
});
}
Ok(())
}
pub fn register(&mut self, path: &AgentPath, depth: i32) -> Result<(), SpawnError> {
self.can_spawn(depth)?;
if self.agents.contains_key(path) {
return Err(SpawnError::AlreadyExists);
}
self.agents.insert(
path.clone(),
AgentEntry {
path: path.clone(),
depth,
queue_len: 0,
in_flight: false,
running_since: None,
closing: false,
results_posted: 0,
results_handed_over: 0,
tool_calls: 0,
last_activity: None,
task: None,
last_result: None,
last_error: None,
},
);
Ok(())
}
pub fn close(&mut self, path: &AgentPath) -> Option<AgentEntry> {
let entry = self.agents.remove(path)?;
self.push_event(AgentLifecycleEvent {
path: path.clone(),
from: entry.status(),
to: AgentStatus::Closed,
reason: "unregistered",
});
self.publish_snapshot();
Some(entry)
}
fn transition(
&mut self,
path: &AgentPath,
reason: &'static str,
apply: impl FnOnce(&mut AgentEntry),
) -> bool {
let Some(entry) = self.agents.get_mut(path) else {
return false;
};
let from = entry.status();
apply(entry);
let to = entry.status();
if from != to {
self.push_event(AgentLifecycleEvent {
path: path.clone(),
from,
to,
reason,
});
self.publish_snapshot();
}
true
}
pub fn note_enqueued(&mut self, path: &AgentPath) -> bool {
self.transition(path, "task_enqueued", |e| {
e.queue_len += 1;
})
}
pub fn note_dequeued(&mut self, path: &AgentPath) -> bool {
self.transition(path, "task_dequeued", |e| {
e.queue_len = e.queue_len.saturating_sub(1);
e.in_flight = true;
e.running_since = Some(Instant::now());
})
}
pub fn note_posted(&mut self, path: &AgentPath, result: ResultKind) -> bool {
self.transition(path, "result_posted", |e| {
e.in_flight = false;
e.results_posted += 1;
e.running_since = None;
e.last_error = match &result {
ResultKind::Failed(error) => Some(error.clone()),
_ => None,
};
e.last_result = Some(result);
})
}
pub fn note_closing(&mut self, path: &AgentPath) -> bool {
self.transition(path, "closing", |e| {
e.closing = true;
e.in_flight = false;
e.queue_len = 0;
e.running_since = None;
})
}
pub fn note_send_failed(&mut self, path: &AgentPath) -> bool {
self.transition(path, "task_send_failed", |e| {
e.queue_len = e.queue_len.saturating_sub(1);
})
}
pub fn note_batch_handed_over(&mut self, path: &AgentPath) -> bool {
let Some(entry) = self.agents.get_mut(path) else {
return false;
};
entry.results_handed_over = entry.results_posted;
self.publish_snapshot();
true
}
pub fn set_task(&mut self, path: &AgentPath, task: String) -> bool {
match self.agents.get_mut(path) {
Some(entry) => {
if entry.task.is_none() {
entry.task = Some(task);
}
true
}
None => false,
}
}
pub fn touch(&mut self, path: &AgentPath) -> bool {
match self.agents.get_mut(path) {
Some(entry) => {
entry.last_activity = Some(Instant::now());
true
}
None => false,
}
}
pub fn record_tool_call(&mut self, path: &AgentPath) -> bool {
match self.agents.get_mut(path) {
Some(entry) => {
entry.tool_calls += 1;
entry.last_activity = Some(Instant::now());
true
}
None => false,
}
}
pub fn busy_count(&self) -> usize {
self.agents
.values()
.filter(|e| !e.closing && (e.in_flight || e.queue_len > 0))
.count()
}
pub fn quiescent(&self) -> bool {
let all_quiet = self
.agents
.values()
.all(|e| e.closing || (!e.in_flight && e.queue_len == 0 && e.results_posted >= 1));
if !all_quiet {
let blocking: Vec<String> = self
.agents
.values()
.filter(|e| !e.closing && (e.in_flight || e.queue_len > 0 || e.results_posted < 1))
.map(|e| {
format!(
"{}: in_flight={}, queue_len={}, results_posted={}",
e.path, e.in_flight, e.queue_len, e.results_posted
)
})
.collect();
tracing::info!(
blocking_agents = ?blocking,
"registry: quiescent=false"
);
}
all_quiet
}
pub fn get(&self, path: &AgentPath) -> Option<&AgentEntry> {
self.agents.get(path)
}
pub fn list(&self) -> Vec<&AgentEntry> {
let mut entries: Vec<&AgentEntry> = self.agents.values().collect();
entries.sort_by(|a, b| a.path.cmp(&b.path));
entries
}
pub fn count(&self) -> usize {
self.agents.len()
}
pub fn is_empty(&self) -> bool {
self.agents.is_empty()
}
pub fn contains(&self, path: &AgentPath) -> bool {
self.agents.contains_key(path)
}
pub fn snapshot(&self) -> RegistrySnapshot {
RegistrySnapshot {
agents: self
.list()
.into_iter()
.map(|e| AgentSnapshot {
path: e.path.to_string(),
status: e.status().name().to_string(),
running_secs: if e.status() == AgentStatus::Running {
e.running_since.map(|t| t.elapsed().as_secs())
} else {
None
},
last_activity_secs: e.last_activity.map(|t| t.elapsed().as_secs()),
tool_calls: e.tool_calls,
task: e.task.clone(),
pending_results: e.results_posted.saturating_sub(e.results_handed_over),
last_error: e.last_error.clone(),
})
.collect(),
}
}
pub fn subscribe(&self) -> watch::Receiver<Arc<RegistrySnapshot>> {
self.snapshot_tx.subscribe()
}
pub fn latest_snapshot(&self) -> Arc<RegistrySnapshot> {
self.snapshot_tx.borrow().clone()
}
pub fn recent_events(&self, max: usize) -> Vec<AgentLifecycleEvent> {
let skip = self.events.len().saturating_sub(max);
self.events.iter().skip(skip).cloned().collect()
}
fn push_event(&mut self, event: AgentLifecycleEvent) {
if self.events.len() >= EVENT_RING_CAP {
self.events.pop_front();
}
self.events.push_back(event);
}
fn publish_snapshot(&mut self) {
let snapshot = Arc::new(self.snapshot());
self.snapshot_tx.send_replace(snapshot);
}
pub fn config(&self) -> &MultiAgentConfig {
&self.config
}
}
#[cfg(test)]
mod tests;