recursive-agent 0.8.3

A Rust coding-agent platform: kernel, tools, multi-agent orchestration, HTTP API, MCP, and TUI
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
//! Crate-wide error and Result.
//!
//! Structured error types that library consumers can match on.
//! Every distinct failure mode has its own variant.

use crate::permissions::DecisionReason;
use thiserror::Error;

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

#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
    /// LLM provider returned an error (HTTP, parse, etc.)
    #[error("LLM error ({provider}): {message}")]
    Llm { provider: String, message: String },

    /// LLM rate limited — caller should retry after `retry_after_ms`
    #[error("LLM rate limited ({provider}): retry after {retry_after_ms}ms")]
    RateLimited {
        provider: String,
        retry_after_ms: u64,
    },

    /// Tool execution failure (spawn, timeout, I/O)
    ///
    /// `call_id` links this error back to the `tool_call_id` of the triggering
    /// `ToolCall`, enabling audit logs and session persistence to correlate the
    /// failure with the exact turn that requested the tool.
    #[error("tool error ({name}): {message}")]
    Tool {
        name: String,
        /// The tool_call_id from the triggering ToolCall, if available.
        call_id: Option<String>,
        message: String,
    },

    /// Invalid arguments passed to a tool
    #[error("bad tool arguments ({name}): {message}")]
    BadToolArgs { name: String, message: String },

    /// Tool rejected execution (policy, constraints, safety)
    #[error("tool rejected ({name}): {reason}")]
    ToolRejected { name: String, reason: String },

    /// Tool not found in registry
    #[error("tool `{0}` not found")]
    UnknownTool(String),

    /// Permission denied for a tool call
    #[error("permission denied: tool {name} ({reason:?})")]
    PermissionDenied {
        name: String,
        reason: DecisionReason,
    },

    /// Auto-classifier denial limit exceeded — agent should stop
    #[error("permission denial limit exceeded for tool {name}")]
    PermissionDeniedLimit { name: String },

    /// LLM response truncated by provider
    #[error("llm response truncated by provider (finish_reason = {0:?})")]
    ProviderTruncated(String),

    /// MCP protocol/transport error
    #[error("MCP error ({server}): {message}")]
    Mcp { server: String, message: String },

    /// Configuration error (missing env var, invalid value)
    #[error("config error: {message}")]
    Config { message: String },

    /// I/O error
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// HTTP client error
    #[error("HTTP error: {0}")]
    Http(#[from] reqwest::Error),

    /// JSON serialization/deserialization error
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),

    /// Operation cancelled via CancellationToken.
    #[error("cancelled")]
    Cancelled,

    /// Timeout after a specified duration
    #[error("timeout after {duration_ms}ms")]
    Timeout { duration_ms: u64 },

    /// Storage backend error (I/O, serialization, remote storage, etc.)
    #[error("storage error: {message}")]
    Storage { message: String },

    /// A named resource (team, task, etc.) was requested but does not exist.
    #[error("not found: {0}")]
    NotFound(String),

    /// Session metadata on disk has a `schema_version` newer than this
    /// build of the binary knows how to interpret. Raised by
    /// `SessionReader::load_meta` when it sees a version greater than
    /// the supported maximum — the safe action is to refuse to load
    /// the session, not to silently drop fields.
    #[error("session {session_id} has schema_version={found}, supported up to {supported}")]
    SchemaTooNew {
        session_id: String,
        found: u32,
        supported: u32,
    },

    /// Internal agent error — unexpected state that does not map to any typed
    /// variant. Prefer a specific variant; use `Internal` only as last resort.
    #[error("internal error ({context}): {message}")]
    Internal { context: String, message: String },
}

impl Error {
    /// Returns `true` if the error is safe to retry (rate limits, timeouts).
    pub fn is_retryable(&self) -> bool {
        matches!(self, Error::RateLimited { .. } | Error::Timeout { .. })
    }

    /// Returns `true` if the error is transient (network issues, timeouts).
    /// Transient errors may resolve without changing the request.
    pub fn is_transient(&self) -> bool {
        matches!(
            self,
            Error::RateLimited { .. } | Error::Timeout { .. } | Error::Http(_) | Error::Io(_)
        )
    }
}

/// Return `true` when `err` looks like an LLM context-window-exceeded error.
///
/// OpenAI-compatible providers (GLM, DeepSeek, …) return HTTP 400 whose body
/// contains an error code or human-readable message indicating the prompt is
/// too long. We match several common patterns across providers:
///
/// | Provider | Typical signal |
/// |---|---|
/// | OpenAI / NIM | `"context_length_exceeded"` (error `code`) |
/// | OpenAI / NIM | `"maximum context length"` (human message) |
/// | Some providers | `"context window"` |
/// | DeepSeek | `"prompt is too long"` |
/// | Some providers | `"tokens exceeds"` |
///
/// The function intentionally casts to lowercase before matching so it is
/// resilient to capitalisation differences across providers.
pub fn is_context_window_exceeded(err: &Error) -> bool {
    if let Error::Llm { message, .. } = err {
        let msg = message.to_lowercase();
        msg.contains("context_length_exceeded")
            || msg.contains("maximum context length")
            || msg.contains("context window")
            || msg.contains("prompt is too long")
            || msg.contains("tokens exceeds")
            || msg.contains("exceeds the model")
    } else {
        false
    }
}

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

    #[test]
    fn test_llm_error_format() {
        let err = Error::Llm {
            provider: "openai".into(),
            message: "rate limit hit".into(),
        };
        let msg = err.to_string();
        assert!(msg.contains("openai"));
        assert!(msg.contains("rate limit"));
    }

    #[test]
    fn test_rate_limited_format() {
        let err = Error::RateLimited {
            provider: "deepseek".into(),
            retry_after_ms: 5000,
        };
        let msg = err.to_string();
        assert!(msg.contains("deepseek"));
        assert!(msg.contains("5000"));
    }

    #[test]
    fn test_tool_error_format() {
        let err = Error::Tool {
            name: "Bash".into(),
            call_id: None,
            message: "command not found".into(),
        };
        let msg = err.to_string();
        assert!(msg.contains("Bash"));
        assert!(msg.contains("command not found"));
    }

    #[test]
    fn test_bad_tool_args_format() {
        let err = Error::BadToolArgs {
            name: "Read".into(),
            message: "missing path".into(),
        };
        let msg = err.to_string();
        assert!(msg.contains("Read"));
        assert!(msg.contains("missing path"));
    }

    #[test]
    fn test_permission_denied_format() {
        let err = Error::PermissionDenied {
            name: "Bash".into(),
            reason: crate::permissions::DecisionReason::Mode(
                crate::permissions::PermissionMode::DontAsk,
            ),
        };
        let msg = err.to_string();
        assert!(msg.contains("Bash"));
        assert!(msg.contains("DontAsk"));
    }

    #[test]
    fn test_mcp_error_format() {
        let err = Error::Mcp {
            server: "filesystem".into(),
            message: "connection refused".into(),
        };
        let msg = err.to_string();
        assert!(msg.contains("filesystem"));
        assert!(msg.contains("connection refused"));
    }

    #[test]
    fn test_config_error_format() {
        let err = Error::Config {
            message: "missing RECURSIVE_API_KEY".into(),
        };
        let msg = err.to_string();
        assert!(msg.contains("missing RECURSIVE_API_KEY"));
    }

    #[test]
    fn test_cancelled_format() {
        let err = Error::Cancelled;
        let msg = err.to_string();
        assert!(msg.contains("cancelled"));
    }

    #[test]
    fn test_timeout_format() {
        let err = Error::Timeout { duration_ms: 30000 };
        let msg = err.to_string();
        assert!(msg.contains("30000"));
    }

    #[test]
    fn test_is_retryable() {
        assert!(Error::RateLimited {
            provider: "x".into(),
            retry_after_ms: 1000
        }
        .is_retryable());
        assert!(Error::Timeout { duration_ms: 5000 }.is_retryable());
        assert!(!Error::Tool {
            name: "x".into(),
            call_id: None,
            message: "fail".into()
        }
        .is_retryable());
        assert!(!Error::Config {
            message: "bad".into()
        }
        .is_retryable());
    }

    #[test]
    fn test_is_transient() {
        assert!(Error::RateLimited {
            provider: "x".into(),
            retry_after_ms: 1000
        }
        .is_transient());
        assert!(Error::Timeout { duration_ms: 5000 }.is_transient());
        // reqwest::Error is transient by definition (network issues).
        // We verify the variant match in the is_transient implementation itself.
        assert!(!Error::Tool {
            name: "x".into(),
            call_id: None,
            message: "fail".into()
        }
        .is_transient());
        assert!(!Error::Config {
            message: "bad".into()
        }
        .is_transient());
    }

    #[test]
    fn test_from_io_error() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let err: Error = io_err.into();
        assert!(matches!(err, Error::Io(_)));
        assert!(err.to_string().contains("file not found"));
    }

    #[test]
    fn test_unknown_tool_format() {
        let err = Error::UnknownTool("nonexistent".into());
        let msg = err.to_string();
        assert!(msg.contains("nonexistent"));
    }

    #[test]
    fn test_provider_truncated_format() {
        let err = Error::ProviderTruncated("length".into());
        let msg = err.to_string();
        assert!(msg.contains("length"));
    }

    #[test]
    fn test_tool_rejected_format() {
        // kills `ToolRejected` match-arm replacement mutations
        let err = Error::ToolRejected {
            name: "Bash".into(),
            reason: "policy violation".into(),
        };
        let msg = err.to_string();
        assert!(
            msg.contains("Bash"),
            "name must appear in ToolRejected display"
        );
        assert!(
            msg.contains("policy violation"),
            "reason must appear in ToolRejected display"
        );
    }

    #[test]
    fn test_permission_denied_limit_format() {
        // kills `PermissionDeniedLimit` match-arm replacement mutations
        let err = Error::PermissionDeniedLimit {
            name: "Write".into(),
        };
        let msg = err.to_string();
        assert!(
            msg.contains("Write"),
            "name must appear in PermissionDeniedLimit display"
        );
    }

    #[test]
    fn test_schema_too_new_format() {
        // kills `SchemaTooNew` match-arm replacement mutations
        let err = Error::SchemaTooNew {
            session_id: "sess-123".into(),
            found: 5,
            supported: 2,
        };
        let msg = err.to_string();
        assert!(
            msg.contains("sess-123"),
            "session_id must appear in SchemaTooNew display"
        );
        assert!(msg.contains("5"), "found version must appear");
        assert!(msg.contains("2"), "supported version must appear");
    }

    #[test]
    fn test_internal_error_format() {
        // kills `Internal` match-arm replacement mutations
        let err = Error::Internal {
            context: "run_inner".into(),
            message: "unexpected None".into(),
        };
        let msg = err.to_string();
        assert!(
            msg.contains("run_inner"),
            "context must appear in Internal display"
        );
        assert!(
            msg.contains("unexpected None"),
            "message must appear in Internal display"
        );
    }

    #[test]
    fn test_storage_error_format() {
        let err = Error::Storage {
            message: "disk full".into(),
        };
        let msg = err.to_string();
        assert!(msg.contains("disk full"));
    }

    #[test]
    fn test_not_found_format() {
        let err = Error::NotFound("task-abc".into());
        let msg = err.to_string();
        assert!(msg.contains("task-abc"));
    }

    #[test]
    fn test_is_retryable_for_non_retryable_variants() {
        // kills mutations that make non-retryable errors retryable
        assert!(!Error::UnknownTool("Bash".into()).is_retryable());
        assert!(!Error::BadToolArgs {
            name: "r".into(),
            message: "m".into()
        }
        .is_retryable());
    }

    #[test]
    fn test_is_transient_for_non_transient_variants() {
        // kills mutations that expand the is_transient match arms
        assert!(!Error::UnknownTool("Bash".into()).is_transient());
        assert!(!Error::Config {
            message: "bad config".into()
        }
        .is_transient());
    }

    // ── is_context_window_exceeded ────────────────────────────────────

    #[test]
    fn context_overflow_matches_known_patterns() {
        let cases = [
            "HTTP 400: {\"error\":{\"code\":\"context_length_exceeded\",\"message\":\"too long\"}}",
            "HTTP 400: This model's maximum context length is 200000 tokens",
            "HTTP 400: prompt is too long for the model",
            "HTTP 400: tokens exceeds model limit",
            "HTTP 400: exceeds the model context window",
        ];
        for msg in &cases {
            let err = Error::Llm {
                provider: "test".into(),
                message: msg.to_string(),
            };
            assert!(
                is_context_window_exceeded(&err),
                "should detect context overflow in: {msg}"
            );
        }
    }

    #[test]
    fn context_overflow_ignores_unrelated_errors() {
        let cases = [
            "HTTP 400: invalid request body",
            "HTTP 401: unauthorized",
            "HTTP 429: rate limit exceeded",
            "network error: connection refused",
        ];
        for msg in &cases {
            let err = Error::Llm {
                provider: "test".into(),
                message: msg.to_string(),
            };
            assert!(
                !is_context_window_exceeded(&err),
                "should NOT detect context overflow in: {msg}"
            );
        }
    }

    #[test]
    fn context_overflow_ignores_non_llm_errors() {
        assert!(!is_context_window_exceeded(&Error::Timeout {
            duration_ms: 30_000
        }));
        let err = Error::Config {
            message: "context_length_exceeded".into(),
        };
        assert!(
            !is_context_window_exceeded(&err),
            "Config errors must not be detected even if they contain the keyword"
        );
    }
}