aidaemon 0.11.12

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
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
use super::contains_keyword_as_words;
use crate::llm_markers::INTENT_GATE_MARKER;

#[cfg(test)]
fn is_pseudo_tool_line(line: &str) -> bool {
    let lower = line.trim().to_ascii_lowercase();
    lower.starts_with("[tool_use:")
        || lower.starts_with("[tool_call:")
        || lower.starts_with("[function_call:")
        || lower.starts_with("[functioncall:")
}

#[cfg(test)]
fn is_tool_name_like(name: &str) -> bool {
    if name.is_empty() {
        return false;
    }
    let lower = name.to_ascii_lowercase();
    matches!(
        lower.as_str(),
        "terminal"
            | "browser"
            | "web_search"
            | "web_fetch"
            | "system_info"
            | "remember_fact"
            | "manage_config"
            | "send_file"
            | "spawn_agent"
            | "cli_agent"
            | "manage_cli_agents"
            | "health_probe"
            | "manage_skills"
            | "use_skill"
            | "skill_resources"
            | "manage_people"
            | "manage_api"
            | "http_request"
            | "manage_http_auth"
            | "manage_oauth"
            | "read_channel_history"
    ) || lower.starts_with("mcp__")
        || lower.contains("__")
}

#[cfg(test)]
fn parse_name_field(line: &str) -> Option<String> {
    let trimmed = line.trim();
    let (key, value) = trimmed.split_once(':')?;
    if !key.trim().eq_ignore_ascii_case("name") {
        return None;
    }
    let name = value.trim();
    if name.is_empty() || name.contains(' ') {
        return None;
    }
    Some(name.to_string())
}

pub(super) fn looks_like_deferred_action_response(text: &str) -> bool {
    let lower = text.trim().to_ascii_lowercase();

    // Pattern-based detection: catch "I'll [verb]", "I will [verb]", "Let me [verb]",
    // "Shall I [verb]", "Would you like me to [verb]" where verb needs tools.
    // This is dynamic — any new action verb the LLM uses is automatically caught.
    if has_action_promise(&lower) {
        return true;
    }

    // Structural format markers — substring match appropriate for these patterns
    lower.contains("[consultation]")
        || lower.contains(&INTENT_GATE_MARKER.to_ascii_lowercase())
        || lower.contains("[tool_use:")
        || lower.contains("[tool_call:")
}

/// Detect a long status/plan response that reports a failed attempt and promises
/// unsupported future recovery instead of delivering the requested result.
pub(super) fn looks_like_incomplete_retry_plan(text: &str) -> bool {
    let normalized = text
        .replace(['\u{2018}', '\u{2019}', '`', '\u{02BC}'], "'")
        .trim()
        .to_ascii_lowercase();

    let has_failure = [
        "timed out",
        "timeout",
        "failed",
        "couldn't complete",
        "could not complete",
    ]
    .iter()
    .any(|phrase| contains_keyword_as_words(&normalized, phrase));
    let has_unsupported_future = [
        "will retry",
        "i'll retry",
        "monitoring the system",
        "when the connection is stable",
        "as soon as the connection",
    ]
    .iter()
    .any(|phrase| contains_keyword_as_words(&normalized, phrase));
    let has_plan_scaffold = [
        "current plan",
        "research phase",
        "synthesis phase",
        "next phase",
    ]
    .iter()
    .any(|phrase| contains_keyword_as_words(&normalized, phrase));

    has_failure && has_unsupported_future && has_plan_scaffold
}

/// Detect a reply that punts file access back to the user ("please upload
/// the file", "provide the full path") instead of locating it with tools.
/// Multi-word phrases — substring matching is appropriate here (see
/// keyword-matching guidance in CLAUDE.md).
pub(super) fn reply_defers_file_access(text: &str) -> bool {
    let normalized = text
        .replace('\u{2019}', "'")
        .trim()
        .to_ascii_lowercase()
        .replace(char::is_whitespace, " ");
    const DEFER_PHRASES: &[&str] = &[
        "upload the file",
        "upload that file",
        "upload it to",
        "attach the file",
        "attach that file",
        "provide the full path",
        "provide the path",
        "provide the file",
        "provide a path",
        "share the file",
        "don't have access to that",
        "don't have access to the file",
        "don't have direct access",
        "do not have access to that",
        "do not have direct access",
        "once i have access",
    ];
    DEFER_PHRASES
        .iter()
        .any(|phrase| normalized.contains(phrase))
}

/// Detect whether the user's message references a concrete file: a token
/// with a known document/code extension, or an explicit path.
pub(super) fn user_text_references_file(text: &str) -> bool {
    const FILE_EXTENSIONS: &[&str] = &[
        ".pdf", ".docx", ".doc", ".txt", ".md", ".csv", ".xlsx", ".pptx", ".json", ".log", ".rs",
        ".py", ".js", ".ts", ".html", ".css", ".toml", ".yaml", ".yml", ".png", ".jpg", ".jpeg",
        ".zip", ".epub",
    ];
    for raw_token in text.split_whitespace() {
        let token = raw_token
            .trim_matches(|c: char| c.is_ascii_punctuation() && c != '.' && c != '/' && c != '~')
            .to_ascii_lowercase();
        if token.starts_with("~/") || (token.starts_with('/') && token.len() > 1) {
            return true;
        }
        if FILE_EXTENSIONS
            .iter()
            .any(|ext| token.ends_with(ext) && token.len() > ext.len())
        {
            return true;
        }
    }
    false
}

/// Detect first-person past-tense side-effect claims like "I have deleted…",
/// "I've removed…", "I created…". Used by the completion phase to catch
/// fabricated action claims: a reply asserting a completed side effect in a
/// task that made zero tool calls cannot be truthful.
pub(super) fn claims_completed_side_effect(text: &str) -> bool {
    // Same normalization as has_action_promise: unify Unicode apostrophes
    // so "I’ve" matches "I've".
    let normalized = text
        .trim()
        .to_ascii_lowercase()
        .replace(['\u{2018}', '\u{2019}', '`', '\u{02BC}'], "'");

    // Past-tense verbs that imply a tool-mediated side effect. Knowledge
    // verbs ("explained", "summarized") are intentionally absent — those
    // can be fulfilled without tools.
    const PAST_ACTION_VERBS: &[&str] = &[
        "deleted",
        "removed",
        "created",
        "wrote",
        "written",
        "updated",
        "edited",
        "modified",
        "replaced",
        "moved",
        "renamed",
        "executed",
        "ran",
        "installed",
        "saved",
        "stored",
        "copied",
        "combined",
        "merged",
        "deployed",
        "restarted",
        "stopped",
        "killed",
        "downloaded",
        "cloned",
        "pushed",
        "pulled",
        "committed",
        "cleaned",
        "cleared",
        "built",
        "generated",
        "appended",
        "uploaded",
        "sent",
        "added",
    ];
    // Adverbs allowed between the subject and the verb:
    // "I have successfully executed", "I've just removed".
    const FILLER_ADVERBS: &[&str] = &["now", "just", "successfully", "already", "also"];

    let words: Vec<String> = normalized
        .split_whitespace()
        .map(|w| {
            w.trim_matches(|c: char| c.is_ascii_punctuation() && c != '\'')
                .to_lowercase()
        })
        .filter(|w| !w.is_empty())
        .collect();

    let is_action_verb = |w: &str| PAST_ACTION_VERBS.contains(&w);
    let verb_after = |start: usize| -> bool {
        let mut idx = start;
        while words
            .get(idx)
            .is_some_and(|w| FILLER_ADVERBS.contains(&w.as_str()))
        {
            idx += 1;
        }
        words.get(idx).is_some_and(|w| is_action_verb(w))
    };

    for i in 0..words.len() {
        let claim = if words[i] == "i've" {
            // "I've removed …"
            verb_after(i + 1)
        } else if words[i] == "i" && words.get(i + 1).is_some_and(|w| w == "have") {
            // "I have deleted …"
            verb_after(i + 2)
        } else if words[i] == "i" {
            // Simple past: "I deleted …"
            verb_after(i + 1)
        } else {
            false
        };
        if claim {
            return true;
        }
    }
    false
}

/// Detect claims that a delegated agent has already been started. Without a
/// corresponding tool call, these statements fabricate asynchronous work that
/// will never produce a result.
pub(super) fn claims_delegation_started(text: &str) -> bool {
    let normalized = text
        .trim()
        .to_ascii_lowercase()
        .replace(['\u{2018}', '\u{2019}', '`', '\u{02BC}'], "'");

    let mentions_delegated_agent = [
        "specialist agent",
        "specialized review agent",
        "review agent",
        "research agent",
        "sub-agent",
        "subagent",
        "background agent",
    ]
    .iter()
    .any(|phrase| normalized.contains(phrase));
    if !mentions_delegated_agent {
        return false;
    }

    [
        "i've initiated",
        "i have initiated",
        "i initiated",
        "i've started",
        "i have started",
        "i started",
        "i've launched",
        "i have launched",
        "i launched",
        "i've spawned",
        "i have spawned",
        "i spawned",
        "i've delegated",
        "i have delegated",
        "i delegated",
        "is now running",
        "is running in the background",
        "has been started",
    ]
    .iter()
    .any(|phrase| normalized.contains(phrase))
}

/// Detect action-promise patterns like "I'll create", "I will run", "Let me check".
/// Returns true when the verb following the prefix is NOT a knowledge-only verb
/// (e.g., "explain", "describe", "summarize"), meaning the LLM needs tools to fulfill it.
pub(super) fn has_action_promise(text: &str) -> bool {
    // Normalize common Unicode apostrophes so contractions like "I’ll"
    // are treated the same as "I'll".
    let normalized = text.replace(['\u{2018}', '\u{2019}', '`', '\u{02BC}'], "'");

    // Verbs the LLM can fulfill without tools — pure knowledge/explanation verbs
    const KNOWLEDGE_ONLY_VERBS: &[&str] = &[
        "explain",
        "describe",
        "summarize",
        "clarify",
        "elaborate",
        "outline",
        "note",
        "mention",
        "address",
        "highlight",
        "tell",
        "share",
        "say",
        "answer",
        "provide",
        "be",
        "give",
        "offer",
        "know",
        "rephrase",
        "restate",
        // Memory/recall verbs — can be answered from conversation context or stored facts
        "recall",
        "confirm",
        "remember",
        "think",
        "point",
        "help",
    ];

    let words: Vec<String> = normalized
        .split_whitespace()
        .map(|w| {
            w.trim_matches(|c: char| c.is_ascii_punctuation() && c != '\'')
                .to_lowercase()
        })
        .filter(|w| !w.is_empty())
        .collect();

    for i in 0..words.len() {
        // Determine the index of the verb after the action-promise prefix
        let verb_idx = if words[i] == "i'll" {
            // "I'll [verb]"
            Some(i + 1)
        } else if words[i] == "i" && words.get(i + 1).is_some_and(|w| w == "will") {
            // "I will [verb]"
            Some(i + 2)
        } else if words[i] == "let" && words.get(i + 1).is_some_and(|w| w == "me") {
            // "Let me [verb]"
            Some(i + 2)
        } else if words[i] == "shall" && words.get(i + 1).is_some_and(|w| w == "i") {
            // "Shall I [verb]"
            Some(i + 2)
        } else if words[i] == "would"
            && words.get(i + 1).is_some_and(|w| w == "you")
            && words.get(i + 2).is_some_and(|w| w == "like")
            && words.get(i + 3).is_some_and(|w| w == "me")
            && words.get(i + 4).is_some_and(|w| w == "to")
        {
            // "Would you like me to [verb]"
            Some(i + 5)
        } else {
            None
        };

        if let Some(vi) = verb_idx {
            if let Some(verb) = words.get(vi) {
                if !KNOWLEDGE_ONLY_VERBS.contains(&verb.as_str()) {
                    return true;
                }
            }
        }
    }

    false
}

/// Check whether a model response contains substantive text content rather
/// than just deferred-action phrases.  Used to decide whether to accept a
/// text-only response after repeated deferred-no-tool retries: if the model
/// finally produced real content (greeting, explanation, joke, etc.) we should
/// let it through instead of stalling further.
///
/// The heuristic:
/// 1. The text must be at least `min_len` characters (default 50).
/// 2. After stripping lines that are purely deferred-action phrases, there must
///    still be substantive content left.
pub(super) fn is_substantive_text_response(text: &str, min_len: usize) -> bool {
    let trimmed = text.trim();
    if trimmed.len() < min_len {
        return false;
    }

    // Strip lines that are purely deferred-action phrases.
    // If most of the text survives, the response is substantive.
    let substantive_lines: Vec<&str> = trimmed
        .lines()
        .filter(|line| {
            let l = line.trim();
            if l.is_empty() {
                return false;
            }
            // Keep lines that do NOT look like pure deferral text
            !has_action_promise(&l.to_ascii_lowercase())
        })
        .collect();

    let substantive_text: String = substantive_lines.join(" ");
    let substantive_len = substantive_text.trim().len();

    // Must have at least min_len chars of non-deferred content
    substantive_len >= min_len
}

/// Heuristic: does the user's message look like a multi-part request that
/// warrants a detailed response?  We check for numbered lists, explanation
/// keywords, and conjunction-heavy compound tasks.
pub(super) fn looks_like_multi_part_request(text: &str) -> bool {
    let lower = text.to_ascii_lowercase();

    // Count numbered/lettered items: "1)", "2)", "a)", "b)", "step 1", etc.
    let numbered_items = {
        let re = regex::Regex::new(r"(?:^|\s)(?:\d+[.)]\s|[a-e][.)]\s|step\s+\d)").unwrap();
        re.find_iter(&lower).count()
    };
    if numbered_items >= 2 {
        return true;
    }

    // Explanation keywords: user explicitly wants reasoning
    let explanation_words = [
        "explain why",
        "explain how",
        "tell me why",
        "describe how",
        "show me",
        "what did you",
        "summarize what",
        "thorough review",
        "find all",
        "list all",
        "review it",
        "review the",
        "audit",
    ];
    let has_explanation_request = explanation_words.iter().any(|w| lower.contains(w));

    // Compound task indicators
    let compound_signals = [
        "also ",
        "then ",
        "after that",
        "additionally",
        "finally ",
        "and then",
        "before ",
        "as well",
    ];
    let compound_count = compound_signals
        .iter()
        .filter(|s| lower.contains(*s))
        .count();

    // Multi-part if explanation requested, or ≥2 compound signals
    has_explanation_request || compound_count >= 2
}

/// Remove leaked text-only control markers and pseudo tool-call text.
#[cfg(test)]
pub(super) fn sanitize_response_analysis(analysis: &str) -> String {
    let lines: Vec<&str> = analysis.lines().collect();
    let has_pseudo_tool_block = lines.iter().any(|line| is_pseudo_tool_line(line));

    let mut cleaned: Vec<String> = Vec::with_capacity(lines.len());
    let mut i = 0usize;
    while i < lines.len() {
        let line = lines[i];
        let trimmed = line.trim();
        let lower = trimmed.to_ascii_lowercase();

        if lower == "arguments:" {
            let mut j = i + 1;
            let mut block_has_tool_signature = false;
            while j < lines.len() {
                let next = lines[j].trim();
                if next.is_empty() {
                    break;
                }
                if let Some(name) = parse_name_field(next) {
                    if is_tool_name_like(&name) {
                        block_has_tool_signature = true;
                    }
                }
                let next_lower = next.to_ascii_lowercase();
                if next_lower.starts_with("cmd:")
                    || next_lower.starts_with("command:")
                    || next_lower.starts_with("args:")
                    || next_lower.starts_with("arguments:")
                {
                    block_has_tool_signature = true;
                }
                j += 1;
            }

            if block_has_tool_signature {
                i = j;
                continue;
            }
        }

        if is_pseudo_tool_line(line) {
            i += 1;
            continue;
        }

        let replaced = line.replace(crate::llm_markers::TEXT_ONLY_RESPONSE_MARKER, "");
        let trimmed_replaced = replaced.trim();
        let lower_replaced = trimmed_replaced.to_ascii_lowercase();

        if lower_replaced == "[consultation]" {
            i += 1;
            continue;
        }

        if lower_replaced.starts_with(&INTENT_GATE_MARKER.to_ascii_lowercase()) {
            i += 1;
            continue;
        }

        // Some models echo the text-only control instructions verbatim.
        // Strip the control header and nearby instruction lines so they don't
        // pollute the injected warm-start context for iteration 2.
        if lower_replaced.starts_with("[important:")
            && (lower_replaced.contains("consultation")
                || (lower_replaced.contains("you are being consulted")
                    && lower_replaced.contains("respond with text only")))
        {
            i += 1;
            continue;
        }
        if lower_replaced.contains("text only")
            && (lower_replaced.contains("no tools")
                || lower_replaced.contains("no function calls")
                || lower_replaced.contains("tool_use")
                || lower_replaced.contains("functioncall"))
        {
            i += 1;
            continue;
        }
        if lower_replaced.starts_with("end your response with")
            || lower_replaced.starts_with("end with one line")
            || lower_replaced == "guidelines:"
            || lower_replaced.starts_with("- complexity:")
            || lower_replaced.starts_with("- only include schedule")
            || lower_replaced.starts_with("- domains is optional")
        {
            i += 1;
            continue;
        }

        if has_pseudo_tool_block
            && (lower_replaced.starts_with("cmd:")
                || lower_replaced.starts_with("command:")
                || lower_replaced.starts_with("args:")
                || lower_replaced.starts_with("arguments:")
                || parse_name_field(trimmed_replaced)
                    .as_deref()
                    .is_some_and(is_tool_name_like))
        {
            i += 1;
            continue;
        }

        if trimmed_replaced.is_empty() {
            if cleaned.last().is_some_and(|prev| prev.is_empty()) {
                i += 1;
                continue;
            }
            cleaned.push(String::new());
        } else {
            cleaned.push(replaced.trim_end().to_string());
        }
        i += 1;
    }

    cleaned.join("\n").trim().to_string()
}