edgequake-llm 0.6.3

Multi-provider LLM abstraction library with caching, rate limiting, and cost tracking
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
//! Error types for VSCode Copilot provider.
//!
//! # Design Rationale
//!
//! WHY: We use a dedicated `VsCodeError` type rather than the generic `LlmError` because:
//! 1. VSCode/Copilot has specific error conditions (proxy unavailable, rate limiting)
//! 2. Error messages can include actionable hints (e.g., "Is copilot-api running?")
//! 3. Conversion to `LlmError` is automatic via `From` trait
//!
//! # Error Categories
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │                    VsCodeError Types                             │
//! ├─────────────────────────────────────────────────────────────────┤
//! │                                                                   │
//! │  Initialization Errors                                           │
//! │  ├── ClientInit      → HTTP client TLS/config issues            │
//! │  └── ProxyUnavailable → Proxy server not running                │
//! │                                                                   │
//! │  Runtime Errors                                                   │
//! │  ├── Network         → DNS, timeout, connection refused         │
//! │  ├── Authentication  → Invalid/expired token                    │
//! │  ├── RateLimited     → 429 Too Many Requests                    │
//! │  ├── InvalidRequest  → 400 Bad Request                          │
//! │  └── ServiceUnavailable → 503 Service Unavailable               │
//! │                                                                   │
//! │  Response Errors                                                  │
//! │  ├── ApiError        → Generic API error (500, etc.)            │
//! │  ├── Decode          → JSON deserialization failed              │
//! │  └── Stream          → SSE parsing error                        │
//! │                                                                   │
//! └─────────────────────────────────────────────────────────────────┘
//! ```
//!
//! # Error Recovery
//!
//! | Error | Retryable | Action |
//! |-------|-----------|--------|
//! | `RateLimited` | Yes | Wait with exponential backoff |
//! | `Network` | Yes | Retry after delay |
//! | `ServiceUnavailable` | Yes | Retry after delay |
//! | `Authentication` | No | Re-authenticate |
//! | `InvalidRequest` | No | Fix request parameters |
//! | `ClientInit` | No | Fix configuration |

use thiserror::Error;

pub type Result<T> = std::result::Result<T, VsCodeError>;

/// VSCode Copilot provider errors.
#[derive(Error, Debug)]
pub enum VsCodeError {
    /// Failed to initialize HTTP client.
    #[error("Failed to initialize client: {0}")]
    ClientInit(String),

    /// Proxy server is unavailable or not responding.
    #[error("Proxy unavailable: {0}. Is copilot-api running on localhost:4141?")]
    ProxyUnavailable(String),

    /// Network communication error.
    #[error("Network error: {0}")]
    Network(String),

    /// Authentication or authorization failed.
    #[error("Authentication failed: {0}")]
    Authentication(String),

    /// Rate limit exceeded.
    #[error("Rate limited: {message}")]
    RateLimited {
        /// Provider-supplied explanation, often including rate-limit code/scope.
        message: String,
        /// Suggested retry delay from the server, in seconds.
        retry_after_secs: Option<u64>,
    },

    /// Invalid request format or parameters.
    #[error("Invalid request: {0}")]
    InvalidRequest(String),

    /// Service temporarily unavailable.
    #[error("Service unavailable")]
    ServiceUnavailable,

    /// Generic API error.
    #[error("API error: {0}")]
    ApiError(String),

    /// Failed to decode response.
    #[error("Failed to decode response: {0}")]
    Decode(String),

    /// Streaming error.
    #[error("Stream error: {0}")]
    Stream(String),
}

impl VsCodeError {
    /// Returns true if this error is retryable.
    ///
    /// # WHY
    ///
    /// Consumers of this API need to know which errors warrant retry attempts
    /// versus which errors indicate permanent failures. This method encapsulates
    /// that knowledge so callers don't need to match on error variants.
    ///
    /// # Retryable Errors
    ///
    /// - `Network`: Temporary connectivity issues (DNS, timeout, connection refused)
    /// - `RateLimited`: short-lived 429 response - may succeed after backoff
    /// - `ServiceUnavailable`: 503 response - server temporarily down
    ///
    /// # Non-Retryable Errors
    ///
    /// - `ClientInit`: Configuration issue - won't resolve with retry
    /// - `ProxyUnavailable`: Proxy needs to be started
    /// - `Authentication`: Token invalid - need new token
    /// - `InvalidRequest`: Request parameters wrong - fix before retry
    /// - `ApiError`: Permanent server-side failure
    /// - `Decode`: Response format issue - server bug or version mismatch
    /// - `Stream`: SSE parsing error - unlikely to resolve
    ///
    /// # Example
    ///
    /// ```rust
    /// use edgequake_llm::providers::vscode::VsCodeError;
    ///
    /// let err = VsCodeError::RateLimited {
    ///     message: "burst limit".into(),
    ///     retry_after_secs: Some(5),
    /// };
    /// if err.is_retryable() {
    ///     // Apply exponential backoff and retry
    /// }
    /// ```
    pub fn is_retryable(&self) -> bool {
        match self {
            VsCodeError::Network(_) | VsCodeError::ServiceUnavailable => true,
            // WHY: short-lived 429s are worth retrying; multi-hour/daily/weekly
            // limits should fail fast with an actionable message instead of
            // burning three immediate retries.
            VsCodeError::RateLimited {
                retry_after_secs, ..
            } => match retry_after_secs {
                None => true,
                Some(secs) => *secs <= 30,
            },
            _ => false,
        }
    }
}

// Convert VsCodeError to LlmError
impl From<VsCodeError> for crate::error::LlmError {
    fn from(err: VsCodeError) -> Self {
        match err {
            VsCodeError::ClientInit(msg) => Self::ConfigError(msg),
            VsCodeError::ProxyUnavailable(msg) => Self::NetworkError(msg),
            VsCodeError::Network(msg) => Self::NetworkError(msg),
            VsCodeError::Authentication(msg) => Self::AuthError(msg),
            VsCodeError::RateLimited { message, .. } => Self::RateLimited(message),
            VsCodeError::InvalidRequest(msg) => Self::InvalidRequest(msg),
            VsCodeError::ServiceUnavailable => {
                Self::NetworkError("Service unavailable".to_string())
            }
            VsCodeError::ApiError(msg) => Self::ApiError(msg),
            VsCodeError::Decode(msg) => Self::ApiError(format!("Decode: {}", msg)),
            VsCodeError::Stream(msg) => Self::ApiError(format!("Stream: {}", msg)),
        }
    }
}

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

    // ========================================================================
    // Display Trait Tests - Verify Error Messages
    // ========================================================================

    #[test]
    fn test_vscode_error_display_client_init() {
        let err = VsCodeError::ClientInit("TLS handshake failed".to_string());
        let msg = err.to_string();
        assert!(msg.contains("Failed to initialize client"));
        assert!(msg.contains("TLS handshake failed"));
    }

    #[test]
    fn test_vscode_error_display_proxy_unavailable() {
        let err = VsCodeError::ProxyUnavailable("connection refused".to_string());
        let msg = err.to_string();
        assert!(msg.contains("Proxy unavailable"));
        assert!(msg.contains("connection refused"));
        assert!(msg.contains("localhost:4141")); // Helpful hint
    }

    #[test]
    fn test_vscode_error_display_network() {
        let err = VsCodeError::Network("timeout after 30s".to_string());
        assert_eq!(err.to_string(), "Network error: timeout after 30s");
    }

    #[test]
    fn test_vscode_error_display_authentication() {
        let err = VsCodeError::Authentication("token expired".to_string());
        assert_eq!(err.to_string(), "Authentication failed: token expired");
    }

    #[test]
    fn test_vscode_error_display_rate_limited() {
        let err = VsCodeError::RateLimited {
            message: "weekly limit exceeded".to_string(),
            retry_after_secs: Some(3600),
        };
        assert_eq!(err.to_string(), "Rate limited: weekly limit exceeded");
    }

    #[test]
    fn test_vscode_error_display_service_unavailable() {
        let err = VsCodeError::ServiceUnavailable;
        assert_eq!(err.to_string(), "Service unavailable");
    }

    // ========================================================================
    // From<VsCodeError> for LlmError Conversion Tests
    // ========================================================================

    #[test]
    fn test_conversion_client_init_to_config_error() {
        let vscode_err = VsCodeError::ClientInit("init failed".to_string());
        let llm_err: LlmError = vscode_err.into();

        match llm_err {
            LlmError::ConfigError(msg) => assert_eq!(msg, "init failed"),
            other => panic!("Expected ConfigError, got {:?}", other),
        }
    }

    #[test]
    fn test_conversion_proxy_unavailable_to_network_error() {
        let vscode_err = VsCodeError::ProxyUnavailable("refused".to_string());
        let llm_err: LlmError = vscode_err.into();

        match llm_err {
            LlmError::NetworkError(msg) => assert_eq!(msg, "refused"),
            other => panic!("Expected NetworkError, got {:?}", other),
        }
    }

    #[test]
    fn test_conversion_network_to_network_error() {
        let vscode_err = VsCodeError::Network("dns lookup failed".to_string());
        let llm_err: LlmError = vscode_err.into();

        match llm_err {
            LlmError::NetworkError(msg) => assert_eq!(msg, "dns lookup failed"),
            other => panic!("Expected NetworkError, got {:?}", other),
        }
    }

    #[test]
    fn test_conversion_authentication_to_auth_error() {
        let vscode_err = VsCodeError::Authentication("invalid token".to_string());
        let llm_err: LlmError = vscode_err.into();

        match llm_err {
            LlmError::AuthError(msg) => assert_eq!(msg, "invalid token"),
            other => panic!("Expected AuthError, got {:?}", other),
        }
    }

    #[test]
    fn test_conversion_rate_limited() {
        let vscode_err = VsCodeError::RateLimited {
            message: "retry later".to_string(),
            retry_after_secs: Some(5),
        };
        let llm_err: LlmError = vscode_err.into();

        match llm_err {
            LlmError::RateLimited(msg) => assert!(msg.contains("retry later")),
            other => panic!("Expected RateLimited, got {:?}", other),
        }
    }

    #[test]
    fn test_conversion_invalid_request() {
        let vscode_err = VsCodeError::InvalidRequest("missing model".to_string());
        let llm_err: LlmError = vscode_err.into();

        match llm_err {
            LlmError::InvalidRequest(msg) => assert_eq!(msg, "missing model"),
            other => panic!("Expected InvalidRequest, got {:?}", other),
        }
    }

    #[test]
    fn test_conversion_service_unavailable() {
        let vscode_err = VsCodeError::ServiceUnavailable;
        let llm_err: LlmError = vscode_err.into();

        match llm_err {
            LlmError::NetworkError(msg) => assert!(msg.contains("unavailable")),
            other => panic!("Expected NetworkError, got {:?}", other),
        }
    }

    #[test]
    fn test_conversion_api_error() {
        let vscode_err = VsCodeError::ApiError("internal server error".to_string());
        let llm_err: LlmError = vscode_err.into();

        match llm_err {
            LlmError::ApiError(msg) => assert_eq!(msg, "internal server error"),
            other => panic!("Expected ApiError, got {:?}", other),
        }
    }

    #[test]
    fn test_conversion_decode_error() {
        let vscode_err = VsCodeError::Decode("invalid JSON".to_string());
        let llm_err: LlmError = vscode_err.into();

        match llm_err {
            LlmError::ApiError(msg) => {
                assert!(msg.contains("Decode"));
                assert!(msg.contains("invalid JSON"));
            }
            other => panic!("Expected ApiError, got {:?}", other),
        }
    }

    #[test]
    fn test_conversion_stream_error() {
        let vscode_err = VsCodeError::Stream("connection reset".to_string());
        let llm_err: LlmError = vscode_err.into();

        match llm_err {
            LlmError::ApiError(msg) => {
                assert!(msg.contains("Stream"));
                assert!(msg.contains("connection reset"));
            }
            other => panic!("Expected ApiError, got {:?}", other),
        }
    }

    // ========================================================================
    // is_retryable() Tests
    // WHY: Verify correct categorization of retryable vs non-retryable errors
    // ========================================================================

    #[test]
    fn test_is_retryable_network_error() {
        // WHY: Network errors are temporary and should be retried
        let err = VsCodeError::Network("connection timeout".to_string());
        assert!(err.is_retryable(), "Network errors should be retryable");
    }

    #[test]
    fn test_is_retryable_rate_limited() {
        // WHY: short-lived 429 responses should be retried.
        let err = VsCodeError::RateLimited {
            message: "burst limit".to_string(),
            retry_after_secs: Some(5),
        };
        assert!(err.is_retryable(), "Short rate limits should be retryable");
    }

    #[test]
    fn test_is_retryable_long_rate_limited_is_false() {
        // WHY: weekly/daily limits should fail fast with an actionable message.
        let err = VsCodeError::RateLimited {
            message: "weekly cap hit".to_string(),
            retry_after_secs: Some(60 * 60),
        };
        assert!(
            !err.is_retryable(),
            "Long rate limits should not be retried immediately"
        );
    }

    #[test]
    fn test_is_retryable_service_unavailable() {
        // WHY: 503 means server is temporarily down
        let err = VsCodeError::ServiceUnavailable;
        assert!(
            err.is_retryable(),
            "Service unavailable should be retryable"
        );
    }

    #[test]
    fn test_is_not_retryable_auth_error() {
        // WHY: Auth errors need new credentials, not retry
        let err = VsCodeError::Authentication("token expired".to_string());
        assert!(!err.is_retryable(), "Auth errors should not be retryable");
    }

    #[test]
    fn test_is_not_retryable_invalid_request() {
        // WHY: Invalid request needs to be fixed, not retried
        let err = VsCodeError::InvalidRequest("missing model".to_string());
        assert!(
            !err.is_retryable(),
            "Invalid request should not be retryable"
        );
    }

    #[test]
    fn test_is_not_retryable_client_init() {
        // WHY: Client init errors are configuration issues
        let err = VsCodeError::ClientInit("TLS failed".to_string());
        assert!(
            !err.is_retryable(),
            "Client init errors should not be retryable"
        );
    }

    #[test]
    fn test_is_not_retryable_api_error() {
        // WHY: Generic API errors (500) are typically permanent
        let err = VsCodeError::ApiError("internal error".to_string());
        assert!(!err.is_retryable(), "API errors should not be retryable");
    }

    #[test]
    fn test_is_not_retryable_decode_error() {
        // WHY: Decode errors indicate server response format issues
        let err = VsCodeError::Decode("invalid JSON".to_string());
        assert!(!err.is_retryable(), "Decode errors should not be retryable");
    }
}