1use super::{CommandMessage, ExecutionResult};
4use chrono::{DateTime, Utc};
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7use std::path::PathBuf;
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct Agent {
12 pub id: String,
14
15 pub branch: String,
17
18 pub model: Option<String>,
20
21 pub description: Option<String>,
23
24 pub worktree_path: Option<PathBuf>,
26
27 pub status: AgentStatus,
29
30 pub last_activity: Option<DateTime<Utc>>,
32
33 pub tmux_pane: Option<String>,
35
36 pub config: AgentConfig,
38}
39
40#[allow(dead_code)]
41impl Agent {
42 pub fn new(id: impl Into<String>, branch: impl Into<String>) -> Self {
44 let id_str = id.into();
45 Self {
46 id: id_str.clone(),
47 branch: branch.into(),
48 model: None,
49 description: None,
50 worktree_path: Some(PathBuf::from(format!("agents/{}", id_str))),
51 status: AgentStatus::Inactive,
52 last_activity: None,
53 tmux_pane: None,
54 config: AgentConfig::default(),
55 }
56 }
57
58 pub fn workspace_path(&self) -> &PathBuf {
60 self.worktree_path.as_ref().unwrap()
61 }
62
63 pub fn update_activity(&mut self) {
65 self.last_activity = Some(Utc::now());
66 }
67
68 pub fn is_active(&self) -> bool {
70 matches!(self.status, AgentStatus::Active)
71 }
72
73 pub fn has_error(&self) -> bool {
75 matches!(self.status, AgentStatus::Error(_))
76 }
77
78 pub fn error_message(&self) -> Option<&str> {
80 match &self.status {
81 AgentStatus::Error(msg) => Some(msg),
82 _ => None,
83 }
84 }
85
86 pub fn validate(&self) -> Result<(), String> {
88 if self.id.is_empty() {
89 return Err("Agent ID cannot be empty".to_string());
90 }
91
92 if self.branch.is_empty() {
93 return Err("Agent branch cannot be empty".to_string());
94 }
95
96 if !self
98 .id
99 .chars()
100 .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
101 {
102 return Err(
103 "Agent ID can only contain alphanumeric characters, hyphens, and underscores"
104 .to_string(),
105 );
106 }
107
108 let workspace_path = self.workspace_path();
110 if !workspace_path.starts_with("agents/") {
111 return Err("Agent workspace must be within the agents/ directory".to_string());
112 }
113
114 if workspace_path
116 .components()
117 .any(|c| matches!(c, std::path::Component::ParentDir))
118 {
119 return Err(
120 "Agent workspace path cannot contain parent directory references".to_string(),
121 );
122 }
123
124 Ok(())
125 }
126
127 pub fn add_command(&mut self, _command: CommandMessage) {
129 self.update_activity();
130 }
132
133 pub fn add_result(&mut self, _result: ExecutionResult) {
135 self.update_activity();
136 }
138}
139
140#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
142pub enum AgentStatus {
143 #[default]
145 Inactive,
146 Active,
148 Paused,
150 Error(String),
152 Initializing,
154}
155
156#[derive(Debug, Clone, Serialize, Deserialize)]
158pub struct AgentConfig {
159 pub env_vars: HashMap<String, String>,
161
162 pub work_dir: Option<PathBuf>,
164
165 pub startup_commands: Vec<String>,
167
168 pub resource_limits: ResourceLimits,
170
171 pub shell: Option<String>,
173
174 pub default_timeout_secs: Option<u64>,
176
177 pub auto_sync: bool,
179
180 pub custom_settings: HashMap<String, serde_yaml::Value>,
182}
183
184impl Default for AgentConfig {
185 fn default() -> Self {
186 Self {
187 env_vars: HashMap::new(),
188 work_dir: None,
189 startup_commands: Vec::new(),
190 resource_limits: ResourceLimits::default(),
191 shell: None,
192 default_timeout_secs: Some(300), auto_sync: false,
194 custom_settings: HashMap::new(),
195 }
196 }
197}
198
199#[allow(dead_code)]
200impl AgentConfig {
201 pub fn default_workspace(&self) -> PathBuf {
203 PathBuf::from("agents/default")
204 }
205
206 pub fn timeout(&self) -> u64 {
208 self.default_timeout_secs
209 .or(self.resource_limits.operation_timeout_secs)
210 .unwrap_or(300)
211 }
212
213 pub fn shell_command(&self) -> &str {
215 self.shell.as_deref().unwrap_or("bash")
216 }
217
218 pub fn merge(&self, other: &AgentConfig) -> AgentConfig {
220 let mut merged = self.clone();
221
222 for (key, value) in &other.env_vars {
224 merged.env_vars.insert(key.clone(), value.clone());
225 }
226
227 if other.work_dir.is_some() {
229 merged.work_dir = other.work_dir.clone();
230 }
231 merged
232 .startup_commands
233 .extend(other.startup_commands.clone());
234 merged.resource_limits = merged.resource_limits.merge(&other.resource_limits);
235
236 if other.shell.is_some() {
237 merged.shell = other.shell.clone();
238 }
239 if other.default_timeout_secs.is_some() {
240 merged.default_timeout_secs = other.default_timeout_secs;
241 }
242 merged.auto_sync = other.auto_sync;
243
244 for (key, value) in &other.custom_settings {
246 merged.custom_settings.insert(key.clone(), value.clone());
247 }
248
249 merged
250 }
251}
252
253#[derive(Debug, Clone, Serialize, Deserialize)]
255pub struct ResourceLimits {
256 pub max_memory_mb: Option<u64>,
258
259 pub max_cpu_percent: Option<u8>,
261
262 pub operation_timeout_secs: Option<u64>,
264
265 pub max_concurrent_ops: Option<u32>,
267
268 pub max_disk_mb: Option<u64>,
270}
271
272impl Default for ResourceLimits {
273 fn default() -> Self {
274 Self {
275 max_memory_mb: Some(1024), max_cpu_percent: Some(80), operation_timeout_secs: Some(300), max_concurrent_ops: Some(3),
279 max_disk_mb: Some(5120), }
281 }
282}
283
284#[allow(dead_code)]
285impl ResourceLimits {
286 pub fn merge(&self, other: &ResourceLimits) -> ResourceLimits {
288 Self {
289 max_memory_mb: other.max_memory_mb.or(self.max_memory_mb),
290 max_cpu_percent: other.max_cpu_percent.or(self.max_cpu_percent),
291 operation_timeout_secs: other.operation_timeout_secs.or(self.operation_timeout_secs),
292 max_concurrent_ops: other.max_concurrent_ops.or(self.max_concurrent_ops),
293 max_disk_mb: other.max_disk_mb.or(self.max_disk_mb),
294 }
295 }
296
297 pub fn exceeds_memory_limit(&self, memory_mb: u64) -> bool {
299 self.max_memory_mb
300 .map(|limit| memory_mb > limit)
301 .unwrap_or(false)
302 }
303
304 pub fn exceeds_cpu_limit(&self, cpu_percent: f64) -> bool {
306 self.max_cpu_percent
307 .map(|limit| cpu_percent > limit as f64)
308 .unwrap_or(false)
309 }
310
311 pub fn exceeds_disk_limit(&self, disk_mb: u64) -> bool {
313 self.max_disk_mb
314 .map(|limit| disk_mb > limit)
315 .unwrap_or(false)
316 }
317}
318
319#[cfg(test)]
320mod tests {
321 use super::*;
322
323 #[test]
324 fn test_agent_creation() {
325 let agent = Agent::new("agent-1", "feature/test");
326 assert_eq!(agent.id, "agent-1");
327 assert_eq!(agent.branch, "feature/test");
328 assert_eq!(agent.status, AgentStatus::Inactive);
329 assert_eq!(agent.workspace_path(), &PathBuf::from("agents/agent-1"));
330 }
331
332 #[test]
333 fn test_agent_validation() {
334 let mut agent = Agent::new("valid-agent-1", "feature/test");
335 assert!(agent.validate().is_ok());
336
337 agent.id = "".to_string();
339 assert!(agent.validate().is_err());
340
341 agent.id = "invalid agent!".to_string();
343 assert!(agent.validate().is_err());
344
345 agent.id = "valid-agent".to_string();
347 agent.branch = "".to_string();
348 assert!(agent.validate().is_err());
349 }
350
351 #[test]
352 fn test_agent_status() {
353 let mut agent = Agent::new("agent-1", "feature/test");
354
355 assert!(!agent.is_active());
356 assert!(!agent.has_error());
357
358 agent.status = AgentStatus::Active;
359 assert!(agent.is_active());
360 assert!(!agent.has_error());
361
362 agent.status = AgentStatus::Error("Test error".to_string());
363 assert!(!agent.is_active());
364 assert!(agent.has_error());
365 assert_eq!(agent.error_message(), Some("Test error"));
366 }
367
368 #[test]
369 fn test_agent_config_merge() {
370 let mut config1 = AgentConfig::default();
371 config1
372 .env_vars
373 .insert("VAR1".to_string(), "value1".to_string());
374 config1.auto_sync = false;
375
376 let mut config2 = AgentConfig::default();
377 config2
378 .env_vars
379 .insert("VAR2".to_string(), "value2".to_string());
380 config2.auto_sync = true;
381
382 let merged = config1.merge(&config2);
383
384 assert_eq!(merged.env_vars.get("VAR1"), Some(&"value1".to_string()));
385 assert_eq!(merged.env_vars.get("VAR2"), Some(&"value2".to_string()));
386 assert!(merged.auto_sync);
387 }
388
389 #[test]
390 fn test_resource_limits() {
391 let limits = ResourceLimits::default();
392
393 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)); }
399}