sprit-mutilagent 0.3.2

A robust command-line toolkit for managing multiple AI coding agents in isolated tmux sessions with comprehensive workspace management and health monitoring
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
//! Error handling for the Sprite multi-agent workflow toolkit.
//!
//! This module defines custom error types for clear, actionable
//! error messages while using anyhow for error propagation throughout the application.

/// Main error type for the Sprite application.
#[derive(Debug)]
#[allow(dead_code)]
pub enum SpriteError {
    /// Configuration-related errors
    Config {
        message: String,
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Git operation errors
    Git {
        operation: String,
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Tmux operation errors
    Tmux {
        operation: String,
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Agent management errors
    Agent {
        message: String,
        agent_id: Option<String>,
    },

    /// Session management errors
    Session {
        message: String,
        session_name: Option<String>,
    },

    /// File system errors
    FileSystem {
        operation: String,
        path: String,
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Validation errors
    Validation {
        message: String,
        field: Option<String>,
        value: Option<String>,
    },

    /// Process execution errors
    Process {
        command: String,
        exit_code: Option<i32>,
        stdout: String,
        stderr: String,
    },

    /// I/O errors
    Io {
        operation: String,
        source: std::io::Error,
    },

    /// YAML parsing errors
    Yaml {
        message: String,
        line: Option<usize>,
        column: Option<usize>,
    },

    /// Security errors
    Security {
        message: String,
        violation_type: SecurityViolationType,
    },

    /// Network/communication errors
    Communication {
        message: String,
        target: Option<String>,
    },
}

/// Types of security violations for better error categorization.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub enum SecurityViolationType {
    PathTraversal,
    InvalidPath,
    UnauthorizedAccess,
    CommandInjection,
    UnsafeCommand,
    InvalidInput,
    MalformedSessionName,
    WorkspaceValidation,
    InsecurePermissions,
    InsecureEnvironment,
}

#[allow(dead_code)]
impl SpriteError {
    /// Create a configuration error with a message.
    pub fn config(message: impl Into<String>) -> Self {
        Self::Config {
            message: message.into(),
            source: None,
        }
    }

    /// Create a configuration error with a message and source error.
    pub fn config_with_source(
        message: impl Into<String>,
        source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
    ) -> Self {
        Self::Config {
            message: message.into(),
            source: Some(source.into()),
        }
    }

    /// Create a git operation error.
    pub fn git(operation: impl Into<String>) -> Self {
        Self::Git {
            operation: operation.into(),
            source: None,
        }
    }

    /// Create a git operation error with a source error.
    pub fn git_with_source(
        operation: impl Into<String>,
        source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
    ) -> Self {
        Self::Git {
            operation: operation.into(),
            source: Some(source.into()),
        }
    }

    /// Create a tmux operation error.
    pub fn tmux(operation: impl Into<String>) -> Self {
        Self::Tmux {
            operation: operation.into(),
            source: None,
        }
    }

    /// Create a tmux operation error with a source error.
    pub fn tmux_with_source(
        operation: impl Into<String>,
        source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
    ) -> Self {
        Self::Tmux {
            operation: operation.into(),
            source: Some(source.into()),
        }
    }

    /// Create an agent error.
    pub fn agent(message: impl Into<String>, agent_id: Option<impl Into<String>>) -> Self {
        Self::Agent {
            message: message.into(),
            agent_id: agent_id.map(|id| id.into()),
        }
    }

    /// Create a session error.
    pub fn session(message: impl Into<String>, session_name: Option<impl Into<String>>) -> Self {
        Self::Session {
            message: message.into(),
            session_name: session_name.map(|name| name.into()),
        }
    }

    /// Create a file system error.
    pub fn filesystem(operation: impl Into<String>, path: impl Into<String>) -> Self {
        Self::FileSystem {
            operation: operation.into(),
            path: path.into(),
            source: None,
        }
    }

    /// Create a file system error with a source error.
    pub fn filesystem_with_source(
        operation: impl Into<String>,
        path: impl Into<String>,
        source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
    ) -> Self {
        Self::FileSystem {
            operation: operation.into(),
            path: path.into(),
            source: Some(source.into()),
        }
    }

    /// Create a validation error.
    pub fn validation(
        message: impl Into<String>,
        field: Option<impl Into<String>>,
        value: Option<impl Into<String>>,
    ) -> Self {
        Self::Validation {
            message: message.into(),
            field: field.map(|f| f.into()),
            value: value.map(|v| v.into()),
        }
    }

    /// Create a process execution error.
    pub fn process(
        command: impl Into<String>,
        exit_code: Option<i32>,
        stdout: impl Into<String>,
        stderr: impl Into<String>,
    ) -> Self {
        Self::Process {
            command: command.into(),
            exit_code,
            stdout: stdout.into(),
            stderr: stderr.into(),
        }
    }

    /// Create an I/O error.
    pub fn io(operation: impl Into<String>, source: std::io::Error) -> Self {
        Self::Io {
            operation: operation.into(),
            source,
        }
    }

    /// Create a YAML parsing error.
    pub fn yaml(message: impl Into<String>, line: Option<usize>, column: Option<usize>) -> Self {
        Self::Yaml {
            message: message.into(),
            line,
            column,
        }
    }

    /// Create a security error.
    pub fn security(message: impl Into<String>, violation_type: SecurityViolationType) -> Self {
        Self::Security {
            message: message.into(),
            violation_type,
        }
    }

    /// Create a communication error.
    pub fn communication(message: impl Into<String>, target: Option<impl Into<String>>) -> Self {
        Self::Communication {
            message: message.into(),
            target: target.map(|t| t.into()),
        }
    }

    /// Create a config not found error.
    pub fn config_not_found(path: impl Into<String>) -> Self {
        Self::Config {
            message: format!("Configuration file not found: {}", path.into()),
            source: None,
        }
    }

    /// Create an agent not found error.
    pub fn agent_not_found(agent_id: impl Into<String>) -> Self {
        let id = agent_id.into();
        Self::Agent {
            message: format!("Agent '{}' not found", id),
            agent_id: Some(id.clone()),
        }
    }

    /// Create an agent not active error.
    pub fn agent_not_active(agent_id: impl Into<String>) -> Self {
        let id = agent_id.into();
        Self::Agent {
            message: format!("Agent '{}' is not active", id),
            agent_id: Some(id.clone()),
        }
    }

    /// Create a session not found error.
    pub fn session_not_found(message: impl Into<String>) -> Self {
        Self::Session {
            message: message.into(),
            session_name: None,
        }
    }

    /// Create a sync operation error.
    pub fn sync(message: impl Into<String>) -> Self {
        Self::Git {
            operation: message.into(),
            source: None,
        }
    }

    /// Create a pane not found error.
    pub fn pane_not_found(message: impl Into<String>) -> Self {
        Self::Tmux {
            operation: message.into(),
            source: None,
        }
    }

    /// Get a user-friendly suggestion for resolving this error.
    pub fn suggestion(&self) -> Option<String> {
        match self {
            Self::Config { message, .. } => {
                if message.contains("not found") {
                    Some("Run 'sprite init' to create a default configuration.".to_string())
                } else if message.contains("invalid") {
                    Some("Check your configuration file syntax and required fields.".to_string())
                } else {
                    None
                }
            }
            Self::Git { operation, .. } => {
                if operation.contains("worktree") {
                    Some("Make sure you're in a git repository and the branch exists.".to_string())
                } else {
                    Some("Check your git repository status and permissions.".to_string())
                }
            }
            Self::Tmux { operation, .. } => {
                if operation.contains("session") {
                    Some("Use 'sprite start' to create a new session.".to_string())
                } else {
                    Some("Make sure tmux is installed and running.".to_string())
                }
            }
            Self::Agent { agent_id, .. } => {
                if let Some(id) = agent_id {
                    Some(format!(
                        "Check if agent '{}' exists and is properly configured.",
                        id
                    ))
                } else {
                    Some("Verify your agent configuration in agents.yaml.".to_string())
                }
            }
            Self::Session { session_name, .. } => {
                if let Some(name) = session_name {
                    Some(format!(
                        "Use 'sprite attach {}' to connect to the session.",
                        name
                    ))
                } else {
                    Some("Use 'sprite start' to create a new session.".to_string())
                }
            }
            Self::FileSystem {
                operation, path, ..
            } => {
                if operation.contains("create") || operation.contains("write") {
                    Some(format!(
                        "Check permissions for path '{}' and parent directories.",
                        path
                    ))
                } else {
                    Some(format!("Verify that '{}' exists and is accessible.", path))
                }
            }
            Self::Validation { field, .. } => {
                if let Some(f) = field {
                    Some(format!(
                        "Check the value of field '{}' in your configuration.",
                        f
                    ))
                } else {
                    Some("Review your configuration for invalid values.".to_string())
                }
            }
            Self::Process { command, .. } => Some(format!(
                "Check if '{}' is installed and in your PATH.",
                command
            )),
            Self::Security { violation_type, .. } => match violation_type {
                SecurityViolationType::PathTraversal => {
                    Some("Use relative paths within the project directory only.".to_string())
                }
                SecurityViolationType::InvalidPath => {
                    Some("Check that the path is valid and within allowed boundaries.".to_string())
                }
                SecurityViolationType::UnauthorizedAccess => {
                    Some("Check file permissions and access rights.".to_string())
                }
                SecurityViolationType::CommandInjection => {
                    Some("Avoid special shell characters in agent names and commands.".to_string())
                }
                SecurityViolationType::UnsafeCommand => Some(
                    "Use only safe, approved commands. Avoid shell metacharacters.".to_string(),
                ),
                SecurityViolationType::InvalidInput => Some(
                    "Check that input contains only allowed characters and formats.".to_string(),
                ),
                SecurityViolationType::MalformedSessionName => {
                    Some("Use alphanumeric session names with hyphens only.".to_string())
                }
                SecurityViolationType::WorkspaceValidation => {
                    Some("Ensure all workspaces are within the agents/ directory.".to_string())
                }
                SecurityViolationType::InsecurePermissions => {
                    Some("Restrict file permissions to prevent unauthorized access.".to_string())
                }
                SecurityViolationType::InsecureEnvironment => Some(
                    "Run with appropriate user permissions and secure environment settings."
                        .to_string(),
                ),
            },
            Self::Communication { target, .. } => {
                if let Some(t) = target {
                    Some(format!("Check if agent '{}' is running and accessible.", t))
                } else {
                    Some("Verify that all agents are running and responsive.".to_string())
                }
            }
            Self::Io { operation, .. } => Some(format!(
                "Check file permissions and disk space for operation: {}",
                operation
            )),
            Self::Yaml { line, column, .. } => {
                let mut suggestion = "Check your YAML syntax.".to_string();
                if let Some(l) = line {
                    suggestion.push_str(&format!(" Error at line {}.", l));
                    if let Some(c) = column {
                        suggestion.push_str(&format!(" Column {}.", c));
                    }
                }
                Some(suggestion)
            }
        }
    }

    /// Get the exit code for this error type.
    pub fn exit_code(&self) -> i32 {
        match self {
            Self::Config { .. } => 2,
            Self::Git { .. } => 3,
            Self::Tmux { .. } => 4,
            Self::Agent { .. } => 5,
            Self::Session { .. } => 6,
            Self::FileSystem { .. } => 7,
            Self::Validation { .. } => 8,
            Self::Process { exit_code, .. } => exit_code.unwrap_or(9),
            Self::Io { .. } => 10,
            Self::Yaml { .. } => 11,
            Self::Security { .. } => 12,
            Self::Communication { .. } => 13,
        }
    }
}

/// Type alias for Result with our error type.
#[allow(dead_code)]
pub type Result<T> = anyhow::Result<T, SpriteError>;

/// Convert std::io::Error to our error type.
impl From<std::io::Error> for SpriteError {
    fn from(err: std::io::Error) -> Self {
        Self::io("I/O operation", err)
    }
}

/// Convert serde_yaml::Error to our error type.
impl From<serde_yaml::Error> for SpriteError {
    fn from(err: serde_yaml::Error) -> Self {
        let location = err.location();
        let line = location.as_ref().map(|loc| loc.line());
        let column = location.as_ref().map(|loc| loc.column());
        Self::yaml(err.to_string(), line, column)
    }
}

/// Display implementation that includes suggestions.
impl std::fmt::Display for SpriteError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Config { message, .. } => write!(f, "Configuration error: {}", message),
            Self::Git { operation, .. } => write!(f, "Git operation failed: {}", operation),
            Self::Tmux { operation, .. } => write!(f, "Tmux operation failed: {}", operation),
            Self::Agent { message, .. } => write!(f, "Agent error: {}", message),
            Self::Session { message, .. } => write!(f, "Session error: {}", message),
            Self::FileSystem {
                operation, path, ..
            } => {
                write!(f, "File system error: {} on '{}' failed", operation, path)
            }
            Self::Validation { message, .. } => write!(f, "Validation error: {}", message),
            Self::Process { command, .. } => write!(f, "Command execution failed: {}", command),
            Self::Io { operation, .. } => write!(f, "I/O error: {}", operation),
            Self::Yaml { message, .. } => write!(f, "YAML parsing error: {}", message),
            Self::Security { message, .. } => write!(f, "Security error: {}", message),
            Self::Communication { message, .. } => write!(f, "Communication error: {}", message),
        }?;

        if let Some(suggestion) = self.suggestion() {
            write!(f, "\n\nSuggestion: {}", suggestion)?;
        }
        Ok(())
    }
}

/// Implement std::error::Error trait for SpriteError.
impl std::error::Error for SpriteError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Config { source, .. } => source
                .as_ref()
                .map(|e| e.as_ref() as &dyn std::error::Error),
            Self::Git { source, .. } => source
                .as_ref()
                .map(|e| e.as_ref() as &dyn std::error::Error),
            Self::Tmux { source, .. } => source
                .as_ref()
                .map(|e| e.as_ref() as &dyn std::error::Error),
            Self::FileSystem { source, .. } => source
                .as_ref()
                .map(|e| e.as_ref() as &dyn std::error::Error),
            Self::Io { source, .. } => Some(source),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_error_creation() {
        let err = SpriteError::config("Test config error");
        assert!(matches!(err, SpriteError::Config { .. }));
        assert_eq!(err.exit_code(), 2);
    }

    #[test]
    fn test_error_with_agent_id() {
        let err = SpriteError::agent("Agent not found", Some("agent-1"));
        match err {
            SpriteError::Agent { agent_id, .. } => {
                assert_eq!(agent_id.as_deref(), Some("agent-1"));
            }
            _ => panic!("Expected Agent error"),
        }
    }

    #[test]
    fn test_error_suggestion() {
        let err = SpriteError::config("Configuration file not found");
        let suggestion = err.suggestion();
        assert!(suggestion.is_some());
        assert!(suggestion.unwrap().contains("sprite init"));
    }

    #[test]
    fn test_error_display() {
        let err = SpriteError::git("failed to create worktree");
        let display = format!("{}", err);
        assert!(display.contains("Git operation failed"));
        assert!(display.contains("Suggestion:"));
    }

    #[test]
    fn test_security_violation_types() {
        let err = SpriteError::security("Path contains '..'", SecurityViolationType::PathTraversal);
        assert!(matches!(err, SpriteError::Security { .. }));
        assert_eq!(err.exit_code(), 12);

        let suggestion = err.suggestion();
        assert!(suggestion.is_some());
        assert!(suggestion.unwrap().contains("relative paths"));
    }

    #[test]
    fn test_yaml_error_with_location() {
        let err = SpriteError::yaml("Invalid mapping", Some(10), Some(5));
        assert!(matches!(
            err,
            SpriteError::Yaml {
                line: Some(10),
                column: Some(5),
                ..
            }
        ));

        let suggestion = err.suggestion();
        assert!(suggestion.is_some());
        assert!(suggestion.clone().unwrap().contains("line 10"));
        assert!(suggestion.clone().unwrap().contains("Column 5"));
    }
}