Skip to main content

sprite/models/
agent.rs

1//! Agent data structures for the Sprite multi-agent workflow toolkit.
2
3use super::{CommandMessage, ExecutionResult};
4use chrono::{DateTime, Utc};
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7use std::path::PathBuf;
8
9/// Represents an AI coding agent with its workspace configuration and operational parameters.
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct Agent {
12    /// Unique identifier for the agent (number or name)
13    pub id: String,
14
15    /// Git branch name for this agent's work
16    pub branch: String,
17
18    /// AI model to use (e.g., "claude-sonnet-4", "gpt-4")
19    pub model: Option<String>,
20
21    /// Role or specialization description
22    pub description: Option<String>,
23
24    /// Local workspace path (defaults to agents/{id})
25    pub worktree_path: Option<PathBuf>,
26
27    /// Current status of the agent
28    pub status: AgentStatus,
29
30    /// Last activity timestamp
31    pub last_activity: Option<DateTime<Utc>>,
32
33    /// tmux pane identifier
34    pub tmux_pane: Option<String>,
35
36    /// Agent-specific configuration
37    pub config: AgentConfig,
38}
39
40#[allow(dead_code)]
41impl Agent {
42    /// Create a new agent with basic configuration.
43    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    /// Get the workspace path for this agent.
59    pub fn workspace_path(&self) -> &PathBuf {
60        self.worktree_path.as_ref().unwrap()
61    }
62
63    /// Update the agent's last activity timestamp.
64    pub fn update_activity(&mut self) {
65        self.last_activity = Some(Utc::now());
66    }
67
68    /// Check if the agent is currently active.
69    pub fn is_active(&self) -> bool {
70        matches!(self.status, AgentStatus::Active)
71    }
72
73    /// Check if the agent is in an error state.
74    pub fn has_error(&self) -> bool {
75        matches!(self.status, AgentStatus::Error(_))
76    }
77
78    /// Get the error message if the agent is in an error state.
79    pub fn error_message(&self) -> Option<&str> {
80        match &self.status {
81            AgentStatus::Error(msg) => Some(msg),
82            _ => None,
83        }
84    }
85
86    /// Validate the agent configuration.
87    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        // Validate ID format (alphanumeric with hyphens/underscores)
97        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        // Validate workspace path
109        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        // Check for path traversal
115        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    /// Add a command to the agent's command history.
128    pub fn add_command(&mut self, _command: CommandMessage) {
129        self.update_activity();
130        // TODO: Implement command history storage
131    }
132
133    /// Add an execution result to the agent's history.
134    pub fn add_result(&mut self, _result: ExecutionResult) {
135        self.update_activity();
136        // TODO: Implement result history storage
137    }
138}
139
140/// Current status of an agent.
141#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
142pub enum AgentStatus {
143    /// Agent is configured but not running
144    #[default]
145    Inactive,
146    /// Agent is running and active
147    Active,
148    /// Agent is paused/suspended
149    Paused,
150    /// Agent encountered an error
151    Error(String),
152    /// Agent is being setup/initialized
153    Initializing,
154}
155
156/// Agent-specific configuration settings.
157#[derive(Debug, Clone, Serialize, Deserialize)]
158pub struct AgentConfig {
159    /// Shell environment variables
160    pub env_vars: HashMap<String, String>,
161
162    /// Default working directory within workspace
163    pub work_dir: Option<PathBuf>,
164
165    /// Startup commands to run when agent starts
166    pub startup_commands: Vec<String>,
167
168    /// Resource limits
169    pub resource_limits: ResourceLimits,
170
171    /// Preferred shell for this agent
172    pub shell: Option<String>,
173
174    /// Timeout for commands in seconds
175    pub default_timeout_secs: Option<u64>,
176
177    /// Whether to automatically sync changes
178    pub auto_sync: bool,
179
180    /// Custom settings for the agent
181    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), // 5 minutes default
193            auto_sync: false,
194            custom_settings: HashMap::new(),
195        }
196    }
197}
198
199#[allow(dead_code)]
200impl AgentConfig {
201    /// Get the default workspace path for an agent with the given ID.
202    pub fn default_workspace(&self) -> PathBuf {
203        PathBuf::from("agents/default")
204    }
205
206    /// Get the effective timeout value.
207    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    /// Get the effective shell command.
214    pub fn shell_command(&self) -> &str {
215        self.shell.as_deref().unwrap_or("bash")
216    }
217
218    /// Merge this configuration with another, with the other taking precedence.
219    pub fn merge(&self, other: &AgentConfig) -> AgentConfig {
220        let mut merged = self.clone();
221
222        // Merge environment variables
223        for (key, value) in &other.env_vars {
224            merged.env_vars.insert(key.clone(), value.clone());
225        }
226
227        // Override fields if present in other
228        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        // Merge custom settings
245        for (key, value) in &other.custom_settings {
246            merged.custom_settings.insert(key.clone(), value.clone());
247        }
248
249        merged
250    }
251}
252
253/// Resource limits for an agent.
254#[derive(Debug, Clone, Serialize, Deserialize)]
255pub struct ResourceLimits {
256    /// Maximum memory usage in MB
257    pub max_memory_mb: Option<u64>,
258
259    /// Maximum CPU percentage
260    pub max_cpu_percent: Option<u8>,
261
262    /// Timeout for operations in seconds
263    pub operation_timeout_secs: Option<u64>,
264
265    /// Maximum number of concurrent operations
266    pub max_concurrent_ops: Option<u32>,
267
268    /// Maximum disk usage in MB
269    pub max_disk_mb: Option<u64>,
270}
271
272impl Default for ResourceLimits {
273    fn default() -> Self {
274        Self {
275            max_memory_mb: Some(1024),         // 1GB default
276            max_cpu_percent: Some(80),         // 80% default
277            operation_timeout_secs: Some(300), // 5 minutes default
278            max_concurrent_ops: Some(3),
279            max_disk_mb: Some(5120), // 5GB default
280        }
281    }
282}
283
284#[allow(dead_code)]
285impl ResourceLimits {
286    /// Merge this resource limits with another, with the other taking precedence.
287    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    /// Check if a memory usage value exceeds the limit.
298    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    /// Check if a CPU usage value exceeds the limit.
305    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    /// Check if a disk usage value exceeds the limit.
312    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        // Test empty ID
338        agent.id = "".to_string();
339        assert!(agent.validate().is_err());
340
341        // Test invalid ID format
342        agent.id = "invalid agent!".to_string();
343        assert!(agent.validate().is_err());
344
345        // Test empty branch
346        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)); // 512MB < 1GB limit
394        assert!(limits.exceeds_memory_limit(2048)); // 2GB > 1GB limit
395
396        assert!(!limits.exceeds_cpu_limit(50.0)); // 50% < 80% limit
397        assert!(limits.exceeds_cpu_limit(90.0)); // 90% > 80% limit
398    }
399}