Skip to main content

winx_code_agent/
errors.rs

1use std::path::PathBuf;
2use thiserror::Error;
3
4/// Errors that can occur in the Winx application
5#[derive(Error, Debug)]
6pub enum WinxError {
7    /// Error when initializing the shell
8    #[error("Failed to initialize shell: {0}")]
9    ShellInitializationError(String),
10
11    /// Error when operating on a workspace path
12    #[error("Workspace path error: {0}")]
13    WorkspacePathError(String),
14
15    /// Error when locking the bash state
16    #[error("Failed to lock the bash state: {0}")]
17    BashStateLockError(String),
18
19    /// Error when the bash state is not initialized
20    #[error("Bash state not initialized. Please call Initialize first with type=\"first_call\" and a valid workspace path.")]
21    BashStateNotInitialized,
22
23    /// Error when a command fails to execute
24    #[error("Command execution failed: {0}")]
25    CommandExecutionError(String),
26
27    /// Error when parsing arguments
28    #[error("Failed to parse arguments: {0}")]
29    ArgumentParseError(String),
30
31    /// Error when trying to access a file or directory
32    #[error("File access error for {path}: {message}")]
33    FileAccessError { path: PathBuf, message: String },
34
35    /// Security error - path traversal or symlink escape attempt
36    #[error("Security violation: {message}")]
37    PathSecurityError { path: PathBuf, message: String },
38
39    /// Error when a command is not allowed in the current mode
40    #[error("Command not allowed: {0}")]
41    CommandNotAllowed(String),
42
43    /// Error when chat IDs don't match
44    #[error("Thread ID mismatch: {0}")]
45    ThreadIdMismatch(String),
46
47    /// Error when deserializing data
48    #[error("Deserialization error: {0}")]
49    DeserializationError(String),
50
51    /// Error when serializing data
52    #[error("Serialization error: {0}")]
53    SerializationError(String),
54
55    /// Error in the search/replace format
56    #[error("Search/replace syntax error: {0}")]
57    SearchReplaceSyntaxError(String),
58
59    /// Error when search block is not found in content
60    #[error("Search block not found in content: {0}")]
61    SearchBlockNotFound(String),
62
63    /// Error when search block matches multiple locations (WCGW-style)
64    #[error("Search block matched multiple times")]
65    SearchBlockAmbiguous { block_content: String, match_count: usize, suggestions: Vec<String> },
66
67    /// Enhanced search/replace syntax error with detailed context
68    #[error("Search/replace syntax error: {message}")]
69    SearchReplaceSyntaxErrorDetailed {
70        message: String,
71        line_number: Option<usize>,
72        block_type: Option<String>,
73        suggestions: Vec<String>,
74    },
75
76    /// Error when JSON parsing fails
77    #[error("Invalid JSON: {0}")]
78    JsonParseError(String),
79
80    /// Error when a file is too large for operation
81    #[error("File {path} is too large: {size} bytes (max {max_size})")]
82    FileTooLarge { path: PathBuf, size: u64, max_size: u64 },
83
84    /// Error when writing to a file
85    #[error("Failed to write file {path}: {message}")]
86    FileWriteError { path: PathBuf, message: String },
87
88    /// Error loading data
89    #[error("Failed to load data: {0}")]
90    DataLoadingError(String),
91
92    /// Parameter validation error
93    #[error("Invalid parameter: {field} - {message}")]
94    ParameterValidationError { field: String, message: String },
95
96    /// Required parameter missing error
97    #[error("Required parameter missing: {field} - {message}")]
98    MissingParameterError { field: String, message: String },
99
100    /// Null or undefined value error
101    #[error("Null or undefined value where object expected: {field}")]
102    NullValueError { field: String },
103
104    /// Recovery suggestion error with potential solutions
105    #[error("{message} - {suggestion}")]
106    RecoverableSuggestionError { message: String, suggestion: String },
107
108    /// Context save error
109    #[error("Context save error: {0}")]
110    ContextSaveError(String),
111
112    /// Command timeout error
113    #[error("Command timed out after {timeout_seconds}s: {command}")]
114    CommandTimeout { command: String, timeout_seconds: u64 },
115
116    /// Interactive command detected error
117    #[error(
118        "Interactive command detected: {command}. Use appropriate flags or consider alternatives."
119    )]
120    InteractiveCommandDetected { command: String },
121
122    /// Command already running error
123    #[error("A command is already running: '{current_command}' (for {duration_seconds:.1}s). Use status_check, send_text, or interrupt.")]
124    CommandAlreadyRunning { current_command: String, duration_seconds: f64 },
125
126    /// Process cleanup error
127    #[error("Failed to cleanup process: {message}")]
128    ProcessCleanupError { message: String },
129
130    /// Buffer overflow error
131    #[error("Command output exceeded maximum size: {size} bytes (max {max_size})")]
132    BufferOverflow { size: usize, max_size: usize },
133
134    /// Session recovery error
135    #[error("Failed to recover bash session: {message}")]
136    SessionRecoveryError { message: String },
137
138    /// Resource allocation error
139    #[error("Resource allocation failed: {message}")]
140    ResourceAllocationError { message: String },
141
142    /// IO error
143    #[error("IO error: {0}")]
144    IoError(#[from] std::io::Error),
145
146    /// Configuration error
147    #[error("Configuration error: {0}")]
148    ConfigurationError(String),
149
150    /// Parse error for responses
151    #[error("Parse error: {0}")]
152    ParseError(String),
153
154    /// Invalid input error
155    #[error("Invalid input: {0}")]
156    InvalidInput(String),
157
158    /// File error for file operations
159    #[error("File error: {0}")]
160    FileError(String),
161}
162
163/// Type alias for Result with `WinxError`
164pub type Result<T> = std::result::Result<T, WinxError>;
165
166/// Conversion from `anyhow::Error` to `WinxError`
167impl From<anyhow::Error> for WinxError {
168    fn from(error: anyhow::Error) -> Self {
169        // `{:#}` renders the full anyhow context chain inline ("failed X: caused
170        // by Y: root Z") instead of just the outermost message, so a PTY-spawn or
171        // persistence failure keeps its real cause instead of a bare one-liner.
172        WinxError::CommandExecutionError(format!("{error:#}"))
173    }
174}
175
176/// Advanced error recovery and suggestion options
177pub struct ErrorRecovery;
178
179impl ErrorRecovery {
180    pub fn suggest(error: WinxError, _suggestion: &str) -> WinxError {
181        error
182    }
183
184    pub fn param_error(field: &str, message: &str) -> WinxError {
185        WinxError::ParameterValidationError {
186            field: field.to_string(),
187            message: message.to_string(),
188        }
189    }
190
191    pub fn missing_param(field: &str, message: &str) -> WinxError {
192        WinxError::MissingParameterError { field: field.to_string(), message: message.to_string() }
193    }
194
195    pub fn null_value(field: &str) -> WinxError {
196        WinxError::NullValueError { field: field.to_string() }
197    }
198}
199
200/// Enable cloning for `WinxError`
201impl Clone for WinxError {
202    fn clone(&self) -> Self {
203        match self {
204            Self::ShellInitializationError(msg) => Self::ShellInitializationError(msg.clone()),
205            Self::WorkspacePathError(msg) => Self::WorkspacePathError(msg.clone()),
206            Self::BashStateLockError(msg) => Self::BashStateLockError(msg.clone()),
207            Self::BashStateNotInitialized => Self::BashStateNotInitialized,
208            Self::CommandExecutionError(msg) => Self::CommandExecutionError(msg.clone()),
209            Self::CommandNotAllowed(msg) => Self::CommandNotAllowed(msg.clone()),
210            Self::ThreadIdMismatch(msg) => Self::ThreadIdMismatch(msg.clone()),
211            Self::ArgumentParseError(msg) => Self::ArgumentParseError(msg.clone()),
212            Self::FileAccessError { path, message } => {
213                Self::FileAccessError { path: path.clone(), message: message.clone() }
214            }
215            Self::DeserializationError(msg) => Self::DeserializationError(msg.clone()),
216            Self::SerializationError(msg) => Self::SerializationError(msg.clone()),
217            Self::SearchReplaceSyntaxError(msg) => Self::SearchReplaceSyntaxError(msg.clone()),
218            Self::SearchBlockNotFound(msg) => Self::SearchBlockNotFound(msg.clone()),
219            Self::SearchBlockAmbiguous { block_content, match_count, suggestions } => {
220                Self::SearchBlockAmbiguous {
221                    block_content: block_content.clone(),
222                    match_count: *match_count,
223                    suggestions: suggestions.clone(),
224                }
225            }
226            Self::SearchReplaceSyntaxErrorDetailed {
227                message,
228                line_number,
229                block_type,
230                suggestions,
231            } => Self::SearchReplaceSyntaxErrorDetailed {
232                message: message.clone(),
233                line_number: *line_number,
234                block_type: block_type.clone(),
235                suggestions: suggestions.clone(),
236            },
237            Self::JsonParseError(msg) => Self::JsonParseError(msg.clone()),
238            Self::FileTooLarge { path, size, max_size } => {
239                Self::FileTooLarge { path: path.clone(), size: *size, max_size: *max_size }
240            }
241            Self::FileWriteError { path, message } => {
242                Self::FileWriteError { path: path.clone(), message: message.clone() }
243            }
244            Self::DataLoadingError(msg) => Self::DataLoadingError(msg.clone()),
245            Self::ParameterValidationError { field, message } => {
246                Self::ParameterValidationError { field: field.clone(), message: message.clone() }
247            }
248            Self::MissingParameterError { field, message } => {
249                Self::MissingParameterError { field: field.clone(), message: message.clone() }
250            }
251            Self::NullValueError { field } => Self::NullValueError { field: field.clone() },
252            Self::RecoverableSuggestionError { message, suggestion } => {
253                Self::RecoverableSuggestionError {
254                    message: message.clone(),
255                    suggestion: suggestion.clone(),
256                }
257            }
258            Self::ContextSaveError(msg) => Self::ContextSaveError(msg.clone()),
259            Self::CommandTimeout { command, timeout_seconds } => {
260                Self::CommandTimeout { command: command.clone(), timeout_seconds: *timeout_seconds }
261            }
262            Self::InteractiveCommandDetected { command } => {
263                Self::InteractiveCommandDetected { command: command.clone() }
264            }
265            Self::CommandAlreadyRunning { current_command, duration_seconds } => {
266                Self::CommandAlreadyRunning {
267                    current_command: current_command.clone(),
268                    duration_seconds: *duration_seconds,
269                }
270            }
271            Self::ProcessCleanupError { message } => {
272                Self::ProcessCleanupError { message: message.clone() }
273            }
274            Self::BufferOverflow { size, max_size } => {
275                Self::BufferOverflow { size: *size, max_size: *max_size }
276            }
277            Self::SessionRecoveryError { message } => {
278                Self::SessionRecoveryError { message: message.clone() }
279            }
280            Self::ResourceAllocationError { message } => {
281                Self::ResourceAllocationError { message: message.clone() }
282            }
283            Self::IoError(err) => Self::IoError(std::io::Error::new(err.kind(), err.to_string())),
284            Self::ConfigurationError(msg) => Self::ConfigurationError(msg.clone()),
285            Self::ParseError(msg) => Self::ParseError(msg.clone()),
286            Self::InvalidInput(msg) => Self::InvalidInput(msg.clone()),
287            Self::FileError(msg) => Self::FileError(msg.clone()),
288            Self::PathSecurityError { path, message } => {
289                Self::PathSecurityError { path: path.clone(), message: message.clone() }
290            }
291        }
292    }
293}