use super::{CommandMessage, ExecutionResult};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Agent {
pub id: String,
pub branch: String,
pub model: Option<String>,
pub description: Option<String>,
pub worktree_path: Option<PathBuf>,
pub status: AgentStatus,
pub last_activity: Option<DateTime<Utc>>,
pub tmux_pane: Option<String>,
pub config: AgentConfig,
}
#[allow(dead_code)]
impl Agent {
pub fn new(id: impl Into<String>, branch: impl Into<String>) -> Self {
let id_str = id.into();
Self {
id: id_str.clone(),
branch: branch.into(),
model: None,
description: None,
worktree_path: Some(PathBuf::from(format!("agents/{}", id_str))),
status: AgentStatus::Inactive,
last_activity: None,
tmux_pane: None,
config: AgentConfig::default(),
}
}
pub fn workspace_path(&self) -> &PathBuf {
self.worktree_path.as_ref().unwrap()
}
pub fn update_activity(&mut self) {
self.last_activity = Some(Utc::now());
}
pub fn is_active(&self) -> bool {
matches!(self.status, AgentStatus::Active)
}
pub fn has_error(&self) -> bool {
matches!(self.status, AgentStatus::Error(_))
}
pub fn error_message(&self) -> Option<&str> {
match &self.status {
AgentStatus::Error(msg) => Some(msg),
_ => None,
}
}
pub fn validate(&self) -> Result<(), String> {
if self.id.is_empty() {
return Err("Agent ID cannot be empty".to_string());
}
if self.branch.is_empty() {
return Err("Agent branch cannot be empty".to_string());
}
if !self
.id
.chars()
.all(|c| c.is_alphanumeric() || c == '-' || c == '_')
{
return Err(
"Agent ID can only contain alphanumeric characters, hyphens, and underscores"
.to_string(),
);
}
let workspace_path = self.workspace_path();
if !workspace_path.starts_with("agents/") {
return Err("Agent workspace must be within the agents/ directory".to_string());
}
if workspace_path
.components()
.any(|c| matches!(c, std::path::Component::ParentDir))
{
return Err(
"Agent workspace path cannot contain parent directory references".to_string(),
);
}
Ok(())
}
pub fn add_command(&mut self, _command: CommandMessage) {
self.update_activity();
}
pub fn add_result(&mut self, _result: ExecutionResult) {
self.update_activity();
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub enum AgentStatus {
#[default]
Inactive,
Active,
Paused,
Error(String),
Initializing,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
pub env_vars: HashMap<String, String>,
pub work_dir: Option<PathBuf>,
pub startup_commands: Vec<String>,
pub resource_limits: ResourceLimits,
pub shell: Option<String>,
pub default_timeout_secs: Option<u64>,
pub auto_sync: bool,
pub custom_settings: HashMap<String, serde_yaml::Value>,
}
impl Default for AgentConfig {
fn default() -> Self {
Self {
env_vars: HashMap::new(),
work_dir: None,
startup_commands: Vec::new(),
resource_limits: ResourceLimits::default(),
shell: None,
default_timeout_secs: Some(300), auto_sync: false,
custom_settings: HashMap::new(),
}
}
}
#[allow(dead_code)]
impl AgentConfig {
pub fn default_workspace(&self) -> PathBuf {
PathBuf::from("agents/default")
}
pub fn timeout(&self) -> u64 {
self.default_timeout_secs
.or(self.resource_limits.operation_timeout_secs)
.unwrap_or(300)
}
pub fn shell_command(&self) -> &str {
self.shell.as_deref().unwrap_or("bash")
}
pub fn merge(&self, other: &AgentConfig) -> AgentConfig {
let mut merged = self.clone();
for (key, value) in &other.env_vars {
merged.env_vars.insert(key.clone(), value.clone());
}
if other.work_dir.is_some() {
merged.work_dir = other.work_dir.clone();
}
merged
.startup_commands
.extend(other.startup_commands.clone());
merged.resource_limits = merged.resource_limits.merge(&other.resource_limits);
if other.shell.is_some() {
merged.shell = other.shell.clone();
}
if other.default_timeout_secs.is_some() {
merged.default_timeout_secs = other.default_timeout_secs;
}
merged.auto_sync = other.auto_sync;
for (key, value) in &other.custom_settings {
merged.custom_settings.insert(key.clone(), value.clone());
}
merged
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceLimits {
pub max_memory_mb: Option<u64>,
pub max_cpu_percent: Option<u8>,
pub operation_timeout_secs: Option<u64>,
pub max_concurrent_ops: Option<u32>,
pub max_disk_mb: Option<u64>,
}
impl Default for ResourceLimits {
fn default() -> Self {
Self {
max_memory_mb: Some(1024), max_cpu_percent: Some(80), operation_timeout_secs: Some(300), max_concurrent_ops: Some(3),
max_disk_mb: Some(5120), }
}
}
#[allow(dead_code)]
impl ResourceLimits {
pub fn merge(&self, other: &ResourceLimits) -> ResourceLimits {
Self {
max_memory_mb: other.max_memory_mb.or(self.max_memory_mb),
max_cpu_percent: other.max_cpu_percent.or(self.max_cpu_percent),
operation_timeout_secs: other.operation_timeout_secs.or(self.operation_timeout_secs),
max_concurrent_ops: other.max_concurrent_ops.or(self.max_concurrent_ops),
max_disk_mb: other.max_disk_mb.or(self.max_disk_mb),
}
}
pub fn exceeds_memory_limit(&self, memory_mb: u64) -> bool {
self.max_memory_mb
.map(|limit| memory_mb > limit)
.unwrap_or(false)
}
pub fn exceeds_cpu_limit(&self, cpu_percent: f64) -> bool {
self.max_cpu_percent
.map(|limit| cpu_percent > limit as f64)
.unwrap_or(false)
}
pub fn exceeds_disk_limit(&self, disk_mb: u64) -> bool {
self.max_disk_mb
.map(|limit| disk_mb > limit)
.unwrap_or(false)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_agent_creation() {
let agent = Agent::new("agent-1", "feature/test");
assert_eq!(agent.id, "agent-1");
assert_eq!(agent.branch, "feature/test");
assert_eq!(agent.status, AgentStatus::Inactive);
assert_eq!(agent.workspace_path(), &PathBuf::from("agents/agent-1"));
}
#[test]
fn test_agent_validation() {
let mut agent = Agent::new("valid-agent-1", "feature/test");
assert!(agent.validate().is_ok());
agent.id = "".to_string();
assert!(agent.validate().is_err());
agent.id = "invalid agent!".to_string();
assert!(agent.validate().is_err());
agent.id = "valid-agent".to_string();
agent.branch = "".to_string();
assert!(agent.validate().is_err());
}
#[test]
fn test_agent_status() {
let mut agent = Agent::new("agent-1", "feature/test");
assert!(!agent.is_active());
assert!(!agent.has_error());
agent.status = AgentStatus::Active;
assert!(agent.is_active());
assert!(!agent.has_error());
agent.status = AgentStatus::Error("Test error".to_string());
assert!(!agent.is_active());
assert!(agent.has_error());
assert_eq!(agent.error_message(), Some("Test error"));
}
#[test]
fn test_agent_config_merge() {
let mut config1 = AgentConfig::default();
config1
.env_vars
.insert("VAR1".to_string(), "value1".to_string());
config1.auto_sync = false;
let mut config2 = AgentConfig::default();
config2
.env_vars
.insert("VAR2".to_string(), "value2".to_string());
config2.auto_sync = true;
let merged = config1.merge(&config2);
assert_eq!(merged.env_vars.get("VAR1"), Some(&"value1".to_string()));
assert_eq!(merged.env_vars.get("VAR2"), Some(&"value2".to_string()));
assert!(merged.auto_sync);
}
#[test]
fn test_resource_limits() {
let limits = ResourceLimits::default();
assert!(!limits.exceeds_memory_limit(512)); assert!(limits.exceeds_memory_limit(2048));
assert!(!limits.exceeds_cpu_limit(50.0)); assert!(limits.exceeds_cpu_limit(90.0)); }
}