1use std::path::PathBuf;
2use thiserror::Error;
3
4#[derive(Error, Debug)]
6pub enum WinxError {
7 #[error("Failed to initialize shell: {0}")]
9 ShellInitializationError(String),
10
11 #[error("Workspace path error: {0}")]
13 WorkspacePathError(String),
14
15 #[error("Failed to lock the bash state: {0}")]
17 BashStateLockError(String),
18
19 #[error("Bash state not initialized. Please call Initialize first with type=\"first_call\" and a valid workspace path.")]
21 BashStateNotInitialized,
22
23 #[error("Command execution failed: {0}")]
25 CommandExecutionError(String),
26
27 #[error("{0}")]
29 NoActiveCommand(String),
30
31 #[error("{0}")]
33 BackgroundSessionNotFound(String),
34
35 #[error("Failure: {action} cannot be empty")]
37 EmptyInteractiveInput { action: String },
38
39 #[error("{0}")]
41 InteractiveTargetNotRunning(String),
42
43 #[error("Failed to parse arguments: {0}")]
45 ArgumentParseError(String),
46
47 #[error("File access error for {path}: {message}")]
49 FileAccessError { path: PathBuf, message: String },
50
51 #[error("Security violation: {message}")]
53 PathSecurityError { path: PathBuf, message: String },
54
55 #[error("Temporary artifact policy rejected {path}: {message}")]
57 TemporaryArtifactPolicy { path: PathBuf, temporary_artifact_dir: PathBuf, message: String },
58
59 #[error("Command not allowed: {0}")]
61 CommandNotAllowed(String),
62
63 #[error("Thread ID mismatch: {0}")]
65 ThreadIdMismatch(String),
66
67 #[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 #[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 #[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 #[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("Deserialization error: {0}")]
101 DeserializationError(String),
102
103 #[error("Serialization error: {0}")]
105 SerializationError(String),
106
107 #[error("Search/replace syntax error: {0}")]
109 SearchReplaceSyntaxError(String),
110
111 #[error("Search block not found in content: {0}")]
113 SearchBlockNotFound(String),
114
115 #[error("Search block matched multiple times")]
117 SearchBlockAmbiguous { block_content: String, match_count: usize, suggestions: Vec<String> },
118
119 #[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 #[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("Invalid JSON: {0}")]
138 JsonParseError(String),
139
140 #[error("File {path} is too large: {size} bytes (max {max_size})")]
142 FileTooLarge { path: PathBuf, size: u64, max_size: u64 },
143
144 #[error("Failed to write file {path}: {message}")]
146 FileWriteError { path: PathBuf, message: String },
147
148 #[error("Failed to load data: {0}")]
150 DataLoadingError(String),
151
152 #[error("Invalid parameter: {field} - {message}")]
154 ParameterValidationError { field: String, message: String },
155
156 #[error("Required parameter missing: {field} - {message}")]
158 MissingParameterError { field: String, message: String },
159
160 #[error("Null or undefined value where object expected: {field}")]
162 NullValueError { field: String },
163
164 #[error("{message} - {suggestion}")]
166 RecoverableSuggestionError { message: String, suggestion: String },
167
168 #[error("Context save error: {0}")]
170 ContextSaveError(String),
171
172 #[error("Command timed out after {timeout_seconds}s: {command}")]
174 CommandTimeout { command: String, timeout_seconds: u64 },
175
176 #[error(
178 "Interactive command detected: {command}. Use appropriate flags or consider alternatives."
179 )]
180 InteractiveCommandDetected { command: String },
181
182 #[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 #[error("Failed to cleanup process: {message}")]
188 ProcessCleanupError { message: String },
189
190 #[error("Command output exceeded maximum size: {size} bytes (max {max_size})")]
192 BufferOverflow { size: usize, max_size: usize },
193
194 #[error("Failed to recover bash session: {message}")]
196 SessionRecoveryError { message: String },
197
198 #[error("Resource allocation failed: {message}")]
200 ResourceAllocationError { message: String },
201
202 #[error("IO error: {0}")]
204 IoError(#[from] std::io::Error),
205
206 #[error("Configuration error: {0}")]
208 ConfigurationError(String),
209
210 #[error("Parse error: {0}")]
212 ParseError(String),
213
214 #[error("Invalid input: {0}")]
216 InvalidInput(String),
217
218 #[error("File error: {0}")]
220 FileError(String),
221}
222
223pub type Result<T> = std::result::Result<T, WinxError>;
225
226impl From<anyhow::Error> for WinxError {
228 fn from(error: anyhow::Error) -> Self {
229 WinxError::CommandExecutionError(format!("{error:#}"))
233 }
234}
235
236pub 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
260impl Clone for WinxError {
262 #[allow(clippy::too_many_lines)] 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}