aidaemon 0.11.7

A personal AI agent that runs as a background daemon, accessible via Telegram, Slack, or Discord, with tool use, MCP integration, and persistent memory
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
use std::fmt;

/// Classified provider error — tells the caller *why* the LLM call failed
/// so it can pick the right recovery strategy.
#[derive(Debug, Clone)]
pub struct ProviderError {
    pub kind: ProviderErrorKind,
    pub status: Option<u16>,
    pub message: String,
    pub malformed_reason: Option<MalformedResponseReason>,
    /// Seconds to wait before retrying (from 429 Retry-After header or body).
    pub retry_after_secs: Option<u64>,
    /// For 402 Billing errors: the max tokens the account can actually afford,
    /// parsed from messages like "can only afford 6917".
    pub affordable_tokens: Option<u32>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MalformedResponseReason {
    Parse,
    Shape,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProviderErrorKind {
    /// 401/403 — bad API key or permissions.
    Auth,
    /// 402 — billing/quota exhausted.
    Billing,
    /// 429 — rate limited; check retry_after_secs.
    RateLimit,
    /// 400 — malformed request (e.g. missing thought_signature, invalid schema).
    BadRequest,
    /// 404 or "model not found" — bad model name.
    NotFound,
    /// 408, request timeout, or provider took too long.
    Timeout,
    /// Connection refused, DNS failure, reset, etc.
    Network,
    /// 500/502/503/504 — provider-side outage.
    ServerError,
    /// Provider returned a malformed success payload.
    /// Recovery is reason-aware (parse may be transient; shape is often deterministic).
    MalformedResponse,
    /// Anything else.
    Unknown,
}

impl ProviderError {
    pub fn from_status(status: u16, body: &str) -> Self {
        let kind = match status {
            400 => ProviderErrorKind::BadRequest,
            401 | 403 => ProviderErrorKind::Auth,
            402 => ProviderErrorKind::Billing,
            404 => ProviderErrorKind::NotFound,
            408 => ProviderErrorKind::Timeout,
            429 => ProviderErrorKind::RateLimit,
            500 | 502 | 503 | 504 => ProviderErrorKind::ServerError,
            _ => ProviderErrorKind::Unknown,
        };

        // Try to extract retry_after from JSON body for 429s
        let retry_after_secs = if kind == ProviderErrorKind::RateLimit {
            extract_retry_after(body)
        } else {
            None
        };

        // For 402 billing errors, parse affordable token count from the message.
        // OpenRouter format: "can only afford 6917"
        let affordable_tokens = if kind == ProviderErrorKind::Billing {
            extract_affordable_tokens(body)
        } else {
            None
        };

        Self {
            kind,
            status: Some(status),
            message: truncate_body(body),
            malformed_reason: None,
            retry_after_secs,
            affordable_tokens,
        }
    }

    pub fn timeout_msg(message: impl Into<String>) -> Self {
        Self {
            kind: ProviderErrorKind::Timeout,
            status: None,
            message: message.into(),
            malformed_reason: None,
            retry_after_secs: None,
            affordable_tokens: None,
        }
    }

    pub fn network(err: &reqwest::Error) -> Self {
        let kind = if err.is_timeout() {
            ProviderErrorKind::Timeout
        } else {
            ProviderErrorKind::Network
        };
        Self {
            kind,
            status: None,
            message: err.to_string(),
            malformed_reason: None,
            retry_after_secs: None,
            affordable_tokens: None,
        }
    }

    pub fn malformed_parse(message: impl Into<String>) -> Self {
        Self {
            kind: ProviderErrorKind::MalformedResponse,
            status: Some(200),
            message: message.into(),
            malformed_reason: Some(MalformedResponseReason::Parse),
            retry_after_secs: None,
            affordable_tokens: None,
        }
    }

    pub fn malformed_shape(message: impl Into<String>) -> Self {
        Self {
            kind: ProviderErrorKind::MalformedResponse,
            status: Some(200),
            message: message.into(),
            malformed_reason: Some(MalformedResponseReason::Shape),
            retry_after_secs: None,
            affordable_tokens: None,
        }
    }

    /// User-facing summary suitable for sending back via Telegram.
    pub fn user_message(&self) -> String {
        match self.kind {
            ProviderErrorKind::Auth => {
                "LLM API authentication failed. Check your API key in config.toml.".to_string()
            }
            ProviderErrorKind::Billing => {
                "LLM API billing error — your account quota may be exhausted.".to_string()
            }
            ProviderErrorKind::RateLimit => {
                if let Some(secs) = self.retry_after_secs {
                    format!("Rate limited. Retrying in {}s...", secs)
                } else {
                    "Rate limited. Retrying shortly...".to_string()
                }
            }
            ProviderErrorKind::NotFound => {
                "Model not found. Falling back to previous model.".to_string()
            }
            ProviderErrorKind::Timeout => "LLM request timed out. Retrying...".to_string(),
            ProviderErrorKind::Network => {
                "Cannot reach LLM provider (network error). Will retry.".to_string()
            }
            ProviderErrorKind::ServerError => {
                "LLM provider is experiencing issues (server error). Will retry.".to_string()
            }
            ProviderErrorKind::MalformedResponse => {
                format!(
                    "LLM provider returned a malformed response. This may be a provider bug. Details: {}",
                    self.message
                )
            }
            ProviderErrorKind::BadRequest => {
                format!("LLM request was malformed (400). This may be a bug — please report it. Details: {}", self.message)
            }
            ProviderErrorKind::Unknown => format!("LLM error: {}", self.message),
        }
    }

    /// User-facing summary for cases where recovery has already failed and
    /// there are no more retries/fallbacks left to attempt.
    pub fn recovery_failed_message(&self) -> String {
        match self.kind {
            ProviderErrorKind::RateLimit => {
                "The LLM provider remained rate limited during recovery. Try again shortly."
                    .to_string()
            }
            ProviderErrorKind::NotFound => {
                "The configured LLM model could not be used, and fallback recovery did not succeed. Check model settings."
                    .to_string()
            }
            ProviderErrorKind::Timeout => {
                "LLM requests kept timing out during recovery. Try again shortly.".to_string()
            }
            ProviderErrorKind::Network => {
                "Could not reach the LLM provider during recovery. Check connectivity or try again shortly."
                    .to_string()
            }
            ProviderErrorKind::ServerError => {
                "The LLM provider kept returning server errors during recovery. Try again later or switch providers."
                    .to_string()
            }
            _ => self.user_message(),
        }
    }

    /// Whether this error is worth retrying (same request, same model).
    #[allow(dead_code)]
    pub fn is_retryable(&self) -> bool {
        matches!(
            self.kind,
            ProviderErrorKind::RateLimit
                | ProviderErrorKind::Timeout
                | ProviderErrorKind::Network
                | ProviderErrorKind::ServerError
        )
    }
}

impl fmt::Display for ProviderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(status) = self.status {
            write!(
                f,
                "Provider error ({}, {:?}): {}",
                status, self.kind, self.message
            )
        } else {
            write!(f, "Provider error ({:?}): {}", self.kind, self.message)
        }
    }
}

impl std::error::Error for ProviderError {}

/// Try to parse retry_after from a JSON response body.
/// Handles: {"error": {"retry_after": 5}} and {"retry_after": 5}
fn extract_retry_after(body: &str) -> Option<u64> {
    let v: serde_json::Value = serde_json::from_str(body).ok()?;
    v["error"]["retry_after"]
        .as_u64()
        .or_else(|| v["retry_after"].as_u64())
        .or_else(|| {
            // Some providers use a float
            v["error"]["retry_after"]
                .as_f64()
                .or_else(|| v["retry_after"].as_f64())
                .map(|f| f.ceil() as u64)
        })
}

/// Parse affordable token count from a 402 billing error message.
/// Handles OpenRouter format: "can only afford 6917"
fn extract_affordable_tokens(body: &str) -> Option<u32> {
    // Try JSON first: {"error":{"message":"...can only afford 6917..."}}
    if let Ok(v) = serde_json::from_str::<serde_json::Value>(body) {
        let msg = v["error"]["message"]
            .as_str()
            .or_else(|| v["message"].as_str())
            .unwrap_or("");
        if let Some(n) = parse_affordable_from_text(msg) {
            return Some(n);
        }
    }
    // Fallback: search the raw body text
    parse_affordable_from_text(body)
}

fn parse_affordable_from_text(text: &str) -> Option<u32> {
    // Pattern: "can only afford <number>"
    let marker = "can only afford ";
    let pos = text.find(marker)?;
    let after = &text[pos + marker.len()..];
    let num_str: String = after.chars().take_while(|c| c.is_ascii_digit()).collect();
    num_str.parse::<u32>().ok().filter(|&n| n > 0)
}

/// Multi-word markers for provider-infrastructure failures (rate limits,
/// timeouts, network, server errors, auth, billing, model-unavailable).
/// These match the strings produced by `user_message()` /
/// `recovery_failed_message()` above plus common raw provider phrasing.
/// Multi-word `.contains()` matching is intentional here (see CLAUDE.md
/// keyword-matching exceptions): each phrase is specific enough to avoid
/// false positives on task-semantic failures.
///
/// `BadRequest` and `MalformedResponse` are deliberately excluded: they can
/// indicate persistent prompt/schema bugs rather than transient outages, so
/// retrying them blindly would loop.
#[allow(dead_code)]
const PROVIDER_INFRA_ERROR_MARKERS: &[&str] = &[
    "fallback recovery did not succeed",
    "remained rate limited during recovery",
    "kept timing out during recovery",
    "could not reach the llm provider",
    "kept returning server errors",
    "llm api authentication failed",
    "llm api billing error",
    "llm request timed out",
    "rate limited. retrying",
    "llm provider is experiencing issues",
    "cannot reach llm provider",
    "falling back to previous model",
];

/// True when an error string describes a transient/provider-infrastructure
/// failure rather than a semantic task failure. Used by the goal dispatch
/// circuit breaker: infra failures should be retried later, never counted
/// as goal-level "no progress".
#[allow(dead_code)]
pub fn is_provider_infra_error_text(text: &str) -> bool {
    let lower = text.to_ascii_lowercase();
    PROVIDER_INFRA_ERROR_MARKERS
        .iter()
        .any(|marker| lower.contains(marker))
}

/// Truncate a string to at most `max_len` bytes, respecting UTF-8 char boundaries.
/// Avoids panicking on multi-byte characters.
fn truncate_body(body: &str) -> String {
    const MAX_LEN: usize = 300;
    if body.len() <= MAX_LEN {
        return body.to_string();
    }
    // Find a valid UTF-8 char boundary at or before MAX_LEN
    let mut end = MAX_LEN;
    while end > 0 && !body.is_char_boundary(end) {
        end -= 1;
    }
    format!("{}...", &body[..end])
}

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

    #[test]
    fn transient_server_error_message_mentions_retry() {
        let err = ProviderError::from_status(
            500,
            "{\"error\":{\"message\":\"Internal Server Error\",\"code\":500}}",
        );
        assert_eq!(
            err.user_message(),
            "LLM provider is experiencing issues (server error). Will retry."
        );
    }

    #[test]
    fn terminal_server_error_message_does_not_promise_retry() {
        let err = ProviderError::from_status(
            500,
            "{\"error\":{\"message\":\"Internal Server Error\",\"code\":500}}",
        );
        let msg = err.recovery_failed_message();
        assert!(msg.contains("server errors during recovery"));
        assert!(!msg.contains("Will retry"));
    }

    #[test]
    fn terminal_rate_limit_message_does_not_promise_retry() {
        let err = ProviderError::from_status(429, "{\"error\":{\"retry_after\":5}}");
        let msg = err.recovery_failed_message();
        assert!(msg.contains("remained rate limited during recovery"));
        assert!(!msg.contains("Retrying"));
    }

    #[test]
    fn billing_402_parses_affordable_tokens_from_openrouter() {
        let body = r#"{"error":{"message":"This request requires more credits, or fewer max_tokens. You requested up to 16384 tokens, but can only afford 6917. To increase, visit https://openrouter.ai/settings/credits","code":402}}"#;
        let err = ProviderError::from_status(402, body);
        assert_eq!(err.kind, ProviderErrorKind::Billing);
        assert_eq!(err.affordable_tokens, Some(6917));
    }

    #[test]
    fn billing_402_no_affordable_tokens_when_missing() {
        let body = r#"{"error":{"message":"Insufficient credits","code":402}}"#;
        let err = ProviderError::from_status(402, body);
        assert_eq!(err.kind, ProviderErrorKind::Billing);
        assert_eq!(err.affordable_tokens, None);
    }

    #[test]
    fn billing_402_affordable_zero_returns_none() {
        let body = r#"{"error":{"message":"can only afford 0 tokens","code":402}}"#;
        let err = ProviderError::from_status(402, body);
        assert_eq!(err.affordable_tokens, None);
    }

    #[test]
    fn infra_classifier_matches_recovery_failure_strings() {
        // Exact string observed in production task.error rows (goal 6bfe3a13).
        assert!(is_provider_infra_error_text(
            "The configured LLM model could not be used, and fallback recovery did not succeed. Check model settings."
        ));
        assert!(is_provider_infra_error_text(
            "The LLM provider remained rate limited during recovery. Try again shortly."
        ));
        assert!(is_provider_infra_error_text(
            "LLM requests kept timing out during recovery. Try again shortly."
        ));
        assert!(is_provider_infra_error_text(
            "Could not reach the LLM provider during recovery. Check connectivity or try again shortly."
        ));
        assert!(is_provider_infra_error_text(
            "The LLM provider kept returning server errors during recovery. Try again later or switch providers."
        ));
        assert!(is_provider_infra_error_text(
            "LLM API authentication failed. Check your API key in config.toml."
        ));
        assert!(is_provider_infra_error_text(
            "LLM API billing error — your account quota may be exhausted."
        ));
        assert!(is_provider_infra_error_text(
            "Model not found. Falling back to previous model."
        ));
    }

    #[test]
    fn infra_classifier_rejects_semantic_failures() {
        assert!(!is_provider_infra_error_text(
            "The file /tmp/report.csv does not exist"
        ));
        assert!(!is_provider_infra_error_text(
            "Verification failed: tweet was not posted"
        ));
        assert!(!is_provider_infra_error_text(""));
        assert!(!is_provider_infra_error_text(
            "Task cancelled: goal stalled (no progress after 3 dispatch cycles)"
        ));
    }
}