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 for an internal execution reason.
24    #[error("Command execution failed: {0}")]
25    CommandExecutionError(String),
26
27    /// A status/input action targeted a shell with no running command.
28    #[error("{0}")]
29    NoActiveCommand(String),
30
31    /// A background command identifier is unknown or has already exited.
32    #[error("{0}")]
33    BackgroundSessionNotFound(String),
34
35    /// An interactive input action was supplied without any payload.
36    #[error("Failure: {action} cannot be empty")]
37    EmptyInteractiveInput { action: String },
38
39    /// Interactive bytes were sent to an idle shell instead of a running program.
40    #[error("{0}")]
41    InteractiveTargetNotRunning(String),
42
43    /// Error when parsing arguments
44    #[error("Failed to parse arguments: {0}")]
45    ArgumentParseError(String),
46
47    /// Error when trying to access a file or directory
48    #[error("File access error for {path}: {message}")]
49    FileAccessError { path: PathBuf, message: String },
50
51    /// Security error - path traversal or symlink escape attempt
52    #[error("Security violation: {message}")]
53    PathSecurityError { path: PathBuf, message: String },
54
55    /// A model-owned helper violated the managed `.winx/tmp/<session>` contract.
56    #[error("Temporary artifact policy rejected {path}: {message}")]
57    TemporaryArtifactPolicy { path: PathBuf, temporary_artifact_dir: PathBuf, message: String },
58
59    /// Error when a command is not allowed in the current mode
60    #[error("Command not allowed: {0}")]
61    CommandNotAllowed(String),
62
63    /// Error when chat IDs don't match
64    #[error("Thread ID mismatch: {0}")]
65    ThreadIdMismatch(String),
66
67    /// A remote stateful call omitted the explicit workspace half of its
68    /// session binding.
69    #[error(
70        "Remote session binding is incomplete for thread_id `{thread_id}`: pass the exact workspace_root returned by Initialize. No operation was executed. workspace_root identifies the project session; it does not restrict target paths."
71    )]
72    WorkspaceBindingRequired { thread_id: String },
73
74    /// The supplied workspace and thread cannot belong to the same affinity
75    /// key, so executing the request could select another project's shell.
76    #[error(
77        "Session coherence check failed: thread_id `{thread_id}` does not belong to workspace_root `{workspace_root}`. No operation was executed. Initialize that workspace and preserve the returned thread_id/workspace_root pair."
78    )]
79    WorkspaceThreadMismatch { thread_id: String, workspace_root: PathBuf },
80
81    /// The requested binding disagrees with the workspace stored in the
82    /// selected durable session.
83    #[error(
84        "Session coherence check failed: thread_id `{thread_id}` is bound to `{bound_workspace}`, not `{requested_workspace}`. No operation was executed. Initialize the intended workspace and use its returned pair."
85    )]
86    WorkspaceBindingMismatch {
87        thread_id: String,
88        requested_workspace: PathBuf,
89        bound_workspace: PathBuf,
90    },
91
92    /// Remote sessions never change project identity in place. A new first
93    /// call gives the target workspace its own coherent session binding.
94    #[error(
95        "Remote workspace changes require a new session binding. No operation was executed. Call Initialize with type=\"first_call\" for `{workspace_root}` and use the new thread_id/workspace_root pair."
96    )]
97    WorkspaceChangeRequiresNewSession { workspace_root: PathBuf },
98
99    /// Error when deserializing data
100    #[error("Deserialization error: {0}")]
101    DeserializationError(String),
102
103    /// Error when serializing data
104    #[error("Serialization error: {0}")]
105    SerializationError(String),
106
107    /// Error in the search/replace format
108    #[error("Search/replace syntax error: {0}")]
109    SearchReplaceSyntaxError(String),
110
111    /// Error when search block is not found in content
112    #[error("Search block not found in content: {0}")]
113    SearchBlockNotFound(String),
114
115    /// Error when search block matches multiple locations (WCGW-style)
116    #[error("Search block matched multiple times")]
117    SearchBlockAmbiguous { block_content: String, match_count: usize, suggestions: Vec<String> },
118
119    /// Path-aware context for a planning failure in an atomic multi-file edit.
120    /// The boxed source preserves the original recovery class instead of
121    /// flattening it into an argument/string error.
122    #[error(
123        "MultiFileEdit aborted before writing anything - file {index} ({path}) failed validation: {source}"
124    )]
125    MultiFilePlanError { index: usize, path: PathBuf, source: Box<WinxError> },
126
127    /// Enhanced search/replace syntax error with detailed context
128    #[error("Search/replace syntax error: {message}")]
129    SearchReplaceSyntaxErrorDetailed {
130        message: String,
131        line_number: Option<usize>,
132        block_type: Option<String>,
133        suggestions: Vec<String>,
134    },
135
136    /// Error when JSON parsing fails
137    #[error("Invalid JSON: {0}")]
138    JsonParseError(String),
139
140    /// Error when a file is too large for operation
141    #[error("File {path} is too large: {size} bytes (max {max_size})")]
142    FileTooLarge { path: PathBuf, size: u64, max_size: u64 },
143
144    /// Error when writing to a file
145    #[error("Failed to write file {path}: {message}")]
146    FileWriteError { path: PathBuf, message: String },
147
148    /// Error loading data
149    #[error("Failed to load data: {0}")]
150    DataLoadingError(String),
151
152    /// Parameter validation error
153    #[error("Invalid parameter: {field} - {message}")]
154    ParameterValidationError { field: String, message: String },
155
156    /// Required parameter missing error
157    #[error("Required parameter missing: {field} - {message}")]
158    MissingParameterError { field: String, message: String },
159
160    /// Null or undefined value error
161    #[error("Null or undefined value where object expected: {field}")]
162    NullValueError { field: String },
163
164    /// Recovery suggestion error with potential solutions
165    #[error("{message} - {suggestion}")]
166    RecoverableSuggestionError { message: String, suggestion: String },
167
168    /// Context save error
169    #[error("Context save error: {0}")]
170    ContextSaveError(String),
171
172    /// Command timeout error
173    #[error("Command timed out after {timeout_seconds}s: {command}")]
174    CommandTimeout { command: String, timeout_seconds: u64 },
175
176    /// Interactive command detected error
177    #[error(
178        "Interactive command detected: {command}. Use appropriate flags or consider alternatives."
179    )]
180    InteractiveCommandDetected { command: String },
181
182    /// Command already running error
183    #[error("A command is already running: '{current_command}' (for {duration_seconds:.1}s). Use status_check, send_text, or interrupt.")]
184    CommandAlreadyRunning { current_command: String, duration_seconds: f64 },
185
186    /// Process cleanup error
187    #[error("Failed to cleanup process: {message}")]
188    ProcessCleanupError { message: String },
189
190    /// Buffer overflow error
191    #[error("Command output exceeded maximum size: {size} bytes (max {max_size})")]
192    BufferOverflow { size: usize, max_size: usize },
193
194    /// Session recovery error
195    #[error("Failed to recover bash session: {message}")]
196    SessionRecoveryError { message: String },
197
198    /// Resource allocation error
199    #[error("Resource allocation failed: {message}")]
200    ResourceAllocationError { message: String },
201
202    /// IO error
203    #[error("IO error: {0}")]
204    IoError(#[from] std::io::Error),
205
206    /// Configuration error
207    #[error("Configuration error: {0}")]
208    ConfigurationError(String),
209
210    /// Parse error for responses
211    #[error("Parse error: {0}")]
212    ParseError(String),
213
214    /// Invalid input error
215    #[error("Invalid input: {0}")]
216    InvalidInput(String),
217
218    /// File error for file operations
219    #[error("File error: {0}")]
220    FileError(String),
221}
222
223/// Type alias for Result with `WinxError`
224pub type Result<T> = std::result::Result<T, WinxError>;
225
226/// Conversion from `anyhow::Error` to `WinxError`
227impl From<anyhow::Error> for WinxError {
228    fn from(error: anyhow::Error) -> Self {
229        // `{:#}` renders the full anyhow context chain inline ("failed X: caused
230        // by Y: root Z") instead of just the outermost message, so a PTY-spawn or
231        // persistence failure keeps its real cause instead of a bare one-liner.
232        WinxError::CommandExecutionError(format!("{error:#}"))
233    }
234}
235
236/// Advanced error recovery and suggestion options
237pub struct ErrorRecovery;
238
239impl ErrorRecovery {
240    pub fn suggest(error: WinxError, _suggestion: &str) -> WinxError {
241        error
242    }
243
244    pub fn param_error(field: &str, message: &str) -> WinxError {
245        WinxError::ParameterValidationError {
246            field: field.to_string(),
247            message: message.to_string(),
248        }
249    }
250
251    pub fn missing_param(field: &str, message: &str) -> WinxError {
252        WinxError::MissingParameterError { field: field.to_string(), message: message.to_string() }
253    }
254
255    pub fn null_value(field: &str) -> WinxError {
256        WinxError::NullValueError { field: field.to_string() }
257    }
258}
259
260/// Enable cloning for `WinxError`
261impl Clone for WinxError {
262    #[allow(clippy::too_many_lines)] // exhaustive variant-preserving clone
263    fn clone(&self) -> Self {
264        match self {
265            Self::ShellInitializationError(msg) => Self::ShellInitializationError(msg.clone()),
266            Self::WorkspacePathError(msg) => Self::WorkspacePathError(msg.clone()),
267            Self::BashStateLockError(msg) => Self::BashStateLockError(msg.clone()),
268            Self::BashStateNotInitialized => Self::BashStateNotInitialized,
269            Self::CommandExecutionError(msg) => Self::CommandExecutionError(msg.clone()),
270            Self::NoActiveCommand(msg) => Self::NoActiveCommand(msg.clone()),
271            Self::BackgroundSessionNotFound(msg) => Self::BackgroundSessionNotFound(msg.clone()),
272            Self::EmptyInteractiveInput { action } => {
273                Self::EmptyInteractiveInput { action: action.clone() }
274            }
275            Self::InteractiveTargetNotRunning(msg) => {
276                Self::InteractiveTargetNotRunning(msg.clone())
277            }
278            Self::CommandNotAllowed(msg) => Self::CommandNotAllowed(msg.clone()),
279            Self::ThreadIdMismatch(msg) => Self::ThreadIdMismatch(msg.clone()),
280            Self::WorkspaceBindingRequired { thread_id } => {
281                Self::WorkspaceBindingRequired { thread_id: thread_id.clone() }
282            }
283            Self::WorkspaceThreadMismatch { thread_id, workspace_root } => {
284                Self::WorkspaceThreadMismatch {
285                    thread_id: thread_id.clone(),
286                    workspace_root: workspace_root.clone(),
287                }
288            }
289            Self::WorkspaceBindingMismatch { thread_id, requested_workspace, bound_workspace } => {
290                Self::WorkspaceBindingMismatch {
291                    thread_id: thread_id.clone(),
292                    requested_workspace: requested_workspace.clone(),
293                    bound_workspace: bound_workspace.clone(),
294                }
295            }
296            Self::WorkspaceChangeRequiresNewSession { workspace_root } => {
297                Self::WorkspaceChangeRequiresNewSession { workspace_root: workspace_root.clone() }
298            }
299            Self::ArgumentParseError(msg) => Self::ArgumentParseError(msg.clone()),
300            Self::FileAccessError { path, message } => {
301                Self::FileAccessError { path: path.clone(), message: message.clone() }
302            }
303            Self::TemporaryArtifactPolicy { path, temporary_artifact_dir, message } => {
304                Self::TemporaryArtifactPolicy {
305                    path: path.clone(),
306                    temporary_artifact_dir: temporary_artifact_dir.clone(),
307                    message: message.clone(),
308                }
309            }
310            Self::DeserializationError(msg) => Self::DeserializationError(msg.clone()),
311            Self::SerializationError(msg) => Self::SerializationError(msg.clone()),
312            Self::SearchReplaceSyntaxError(msg) => Self::SearchReplaceSyntaxError(msg.clone()),
313            Self::SearchBlockNotFound(msg) => Self::SearchBlockNotFound(msg.clone()),
314            Self::SearchBlockAmbiguous { block_content, match_count, suggestions } => {
315                Self::SearchBlockAmbiguous {
316                    block_content: block_content.clone(),
317                    match_count: *match_count,
318                    suggestions: suggestions.clone(),
319                }
320            }
321            Self::MultiFilePlanError { index, path, source } => Self::MultiFilePlanError {
322                index: *index,
323                path: path.clone(),
324                source: Box::new((**source).clone()),
325            },
326            Self::SearchReplaceSyntaxErrorDetailed {
327                message,
328                line_number,
329                block_type,
330                suggestions,
331            } => Self::SearchReplaceSyntaxErrorDetailed {
332                message: message.clone(),
333                line_number: *line_number,
334                block_type: block_type.clone(),
335                suggestions: suggestions.clone(),
336            },
337            Self::JsonParseError(msg) => Self::JsonParseError(msg.clone()),
338            Self::FileTooLarge { path, size, max_size } => {
339                Self::FileTooLarge { path: path.clone(), size: *size, max_size: *max_size }
340            }
341            Self::FileWriteError { path, message } => {
342                Self::FileWriteError { path: path.clone(), message: message.clone() }
343            }
344            Self::DataLoadingError(msg) => Self::DataLoadingError(msg.clone()),
345            Self::ParameterValidationError { field, message } => {
346                Self::ParameterValidationError { field: field.clone(), message: message.clone() }
347            }
348            Self::MissingParameterError { field, message } => {
349                Self::MissingParameterError { field: field.clone(), message: message.clone() }
350            }
351            Self::NullValueError { field } => Self::NullValueError { field: field.clone() },
352            Self::RecoverableSuggestionError { message, suggestion } => {
353                Self::RecoverableSuggestionError {
354                    message: message.clone(),
355                    suggestion: suggestion.clone(),
356                }
357            }
358            Self::ContextSaveError(msg) => Self::ContextSaveError(msg.clone()),
359            Self::CommandTimeout { command, timeout_seconds } => {
360                Self::CommandTimeout { command: command.clone(), timeout_seconds: *timeout_seconds }
361            }
362            Self::InteractiveCommandDetected { command } => {
363                Self::InteractiveCommandDetected { command: command.clone() }
364            }
365            Self::CommandAlreadyRunning { current_command, duration_seconds } => {
366                Self::CommandAlreadyRunning {
367                    current_command: current_command.clone(),
368                    duration_seconds: *duration_seconds,
369                }
370            }
371            Self::ProcessCleanupError { message } => {
372                Self::ProcessCleanupError { message: message.clone() }
373            }
374            Self::BufferOverflow { size, max_size } => {
375                Self::BufferOverflow { size: *size, max_size: *max_size }
376            }
377            Self::SessionRecoveryError { message } => {
378                Self::SessionRecoveryError { message: message.clone() }
379            }
380            Self::ResourceAllocationError { message } => {
381                Self::ResourceAllocationError { message: message.clone() }
382            }
383            Self::IoError(err) => Self::IoError(std::io::Error::new(err.kind(), err.to_string())),
384            Self::ConfigurationError(msg) => Self::ConfigurationError(msg.clone()),
385            Self::ParseError(msg) => Self::ParseError(msg.clone()),
386            Self::InvalidInput(msg) => Self::InvalidInput(msg.clone()),
387            Self::FileError(msg) => Self::FileError(msg.clone()),
388            Self::PathSecurityError { path, message } => {
389                Self::PathSecurityError { path: path.clone(), message: message.clone() }
390            }
391        }
392    }
393}