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
//! Session context compilation from events.
//!
//! This module provides the SessionContext struct and compiler that
//! transforms raw events into a structured context for system prompt injection.

use std::sync::Arc;

use chrono::{DateTime, Duration, Utc};
use serde::Serialize;

use super::{
    DecisionPointData, ErrorData, Event, EventStore, EventType, SubAgentSpawnData, TaskEndData,
    TaskStartData, TaskStatus, ThinkingStartData, ToolCallData, ToolResultData,
};
use crate::utils::truncate_str;

/// Compiled session context for system prompt injection.
///
/// This provides the agent with awareness of its current and recent activity,
/// enabling it to answer questions like "what are you doing?" and "what was the error?"
#[derive(Debug, Clone, Serialize, Default)]
pub struct SessionContext {
    /// Currently running task (if any)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub current_task: Option<CurrentTask>,

    /// Last completed/ended task
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_completed_task: Option<CompletedTask>,

    /// Most recent error (if any in the time window)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_error: Option<RecentError>,

    /// Recent tool calls (limited to last N)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub recent_tools: Vec<RecentTool>,

    /// Recent warning/error-level diagnostics (limited to last N)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub recent_diagnostics: Vec<RecentDiagnostic>,

    /// Current thinking iteration (if task is running)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub current_iteration: Option<u32>,

    /// Active sub-agents (spawned but not completed)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub active_sub_agents: Vec<ActiveSubAgent>,

    /// Total events in the time window
    pub event_count: usize,
}

#[derive(Debug, Clone, Serialize)]
pub struct CurrentTask {
    pub task_id: String,
    pub description: String,
    pub started_at: DateTime<Utc>,
    pub elapsed_secs: u64,
    pub iterations: u32,
    pub tool_calls: u32,
}

#[derive(Debug, Clone, Serialize)]
pub struct CompletedTask {
    pub task_id: String,
    pub description: String,
    pub status: TaskStatus,
    pub duration_secs: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    pub completed_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize)]
pub struct RecentError {
    pub message: String,
    pub error_type: String,
    pub occurred_at: DateTime<Utc>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub task_context: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_name: Option<String>,
    pub recovered: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct RecentTool {
    pub name: String,
    pub summary: String,
    pub success: bool,
    pub timestamp: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize)]
pub struct RecentDiagnostic {
    pub severity: String,
    pub code: String,
    pub summary: String,
    pub timestamp: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ActiveSubAgent {
    pub child_session_id: String,
    pub mission: String,
    pub depth: u32,
    pub started_at: DateTime<Utc>,
}

impl SessionContext {
    /// Check if there's any meaningful context to include
    pub fn is_empty(&self) -> bool {
        self.current_task.is_none()
            && self.last_completed_task.is_none()
            && self.last_error.is_none()
            && self.recent_tools.is_empty()
            && self.recent_diagnostics.is_empty()
            && self.active_sub_agents.is_empty()
    }

    /// Format the context for system prompt injection
    pub fn format_for_prompt(&self) -> String {
        if self.is_empty() {
            return String::new();
        }

        let mut lines = vec!["## Current Session Activity".to_string()];
        let active_task_is_uploaded_artifact = self
            .current_task
            .as_ref()
            .is_some_and(|task| task.description.contains("[File received:"));

        // Current task
        if let Some(task) = &self.current_task {
            lines.push(format!(
                "- **Active task:** \"{}\" (running {}s, iteration {}, {} tool calls)",
                truncate_str(&task.description, 60),
                task.elapsed_secs,
                task.iterations,
                task.tool_calls
            ));
        }

        // Last completed task
        if !active_task_is_uploaded_artifact {
            if let Some(task) = &self.last_completed_task {
                let status_str = match task.status {
                    TaskStatus::Completed => "completed",
                    TaskStatus::Cancelled => "CANCELLED",
                    TaskStatus::Failed => "FAILED",
                };
                let error_suffix = task
                    .error
                    .as_ref()
                    .map(|e| format!(" - Error: {}", truncate_str(e, 50)))
                    .unwrap_or_default();
                lines.push(format!(
                    "- **Last task:** \"{}\" - {} ({}s){}",
                    truncate_str(&task.description, 50),
                    status_str,
                    task.duration_secs,
                    error_suffix
                ));
            }
        }

        // Last error
        if let Some(error) = &self.last_error {
            let tool_suffix = error
                .tool_name
                .as_ref()
                .map(|t| format!(" in {}", t))
                .unwrap_or_default();
            let recovered_suffix = if error.recovered { " (recovered)" } else { "" };
            lines.push(format!(
                "- **Recent error:** {}{}{}",
                truncate_str(&error.message, 60),
                tool_suffix,
                recovered_suffix
            ));
        }

        // Recent tools (summarized)
        if !self.recent_tools.is_empty() {
            let tool_summary: Vec<String> = self
                .recent_tools
                .iter()
                .take(5)
                .map(|t| {
                    let status = if t.success { "ok" } else { "err" };
                    format!("{}({})", t.name, status)
                })
                .collect();
            lines.push(format!("- **Recent tools:** {}", tool_summary.join(", ")));
        }

        if !self.recent_diagnostics.is_empty() {
            let diag_summary: Vec<String> = self
                .recent_diagnostics
                .iter()
                .take(3)
                .map(|d| format!("{}({})", truncate_str(&d.code, 40), d.severity))
                .collect();
            lines.push(format!(
                "- **Recent diagnostics:** {}",
                diag_summary.join(", ")
            ));
        }

        // Active sub-agents
        if !self.active_sub_agents.is_empty() {
            let sub_agent_summary: Vec<String> = self
                .active_sub_agents
                .iter()
                .map(|sa| format!("depth {}: \"{}\"", sa.depth, truncate_str(&sa.mission, 30)))
                .collect();
            lines.push(format!(
                "- **Sub-agents:** {}",
                sub_agent_summary.join("; ")
            ));
        }

        lines.push(String::new());
        lines.push(
            "IMPORTANT: This session activity is reference context only. \
             When the user sends a new message, respond to THAT message. \
             Do NOT continue or resume previous tasks unless the user explicitly asks \
             (e.g., \"continue\", \"keep going\", \"resume\"). \
             If the user asks about your recent activity (\"what did you do?\", \
             \"why didn't you respond?\"), explain using this context — do not take new actions."
                .to_string(),
        );

        lines.join("\n")
    }
}

/// Compiles SessionContext from raw events
pub struct SessionContextCompiler {
    store: Arc<EventStore>,
}

impl SessionContextCompiler {
    pub fn new(store: Arc<EventStore>) -> Self {
        Self { store }
    }

    /// Compile session context from events within a time window
    pub async fn compile(
        &self,
        session_id: &str,
        window: Duration,
    ) -> anyhow::Result<SessionContext> {
        let since = Utc::now() - window;
        let events = self.store.query_events(session_id, since).await?;

        Ok(self.compile_from_events(&events))
    }

    /// Compile session context from a pre-fetched list of events
    pub fn compile_from_events(&self, events: &[Event]) -> SessionContext {
        let mut context = SessionContext {
            event_count: events.len(),
            ..Default::default()
        };

        if events.is_empty() {
            return context;
        }

        // Track task states
        let mut task_starts: std::collections::HashMap<String, (Event, TaskStartData)> =
            std::collections::HashMap::new();
        let mut task_ends: std::collections::HashMap<String, (Event, TaskEndData)> =
            std::collections::HashMap::new();
        let mut task_iterations: std::collections::HashMap<String, u32> =
            std::collections::HashMap::new();
        let mut task_tool_calls: std::collections::HashMap<String, u32> =
            std::collections::HashMap::new();

        // Track sub-agent states
        let mut sub_agent_starts: std::collections::HashMap<String, (Event, SubAgentSpawnData)> =
            std::collections::HashMap::new();
        let mut completed_sub_agents: std::collections::HashSet<String> =
            std::collections::HashSet::new();

        // Recent tools
        let mut recent_tools: Vec<RecentTool> = Vec::new();
        let mut recent_diagnostics: Vec<RecentDiagnostic> = Vec::new();

        // Last error
        let mut last_error: Option<(Event, ErrorData)> = None;

        // Process events
        for event in events {
            match event.event_type {
                EventType::TaskStart => {
                    if let Ok(data) = event.parse_data::<TaskStartData>() {
                        task_starts.insert(data.task_id.clone(), (event.clone(), data));
                    }
                }
                EventType::TaskEnd => {
                    if let Ok(data) = event.parse_data::<TaskEndData>() {
                        task_ends.insert(data.task_id.clone(), (event.clone(), data));
                    }
                }
                EventType::ThinkingStart => {
                    if let Ok(data) = event.parse_data::<ThinkingStartData>() {
                        *task_iterations.entry(data.task_id.clone()).or_insert(0) = data.iteration;
                    }
                }
                EventType::ToolCall => {
                    if let Ok(data) = event.parse_data::<ToolCallData>() {
                        if let Some(task_id) = &data.task_id {
                            *task_tool_calls.entry(task_id.clone()).or_insert(0) += 1;
                        }
                    }
                }
                EventType::ToolResult => {
                    if let Ok(data) = event.parse_data::<ToolResultData>() {
                        recent_tools.push(RecentTool {
                            name: data.name,
                            summary: truncate_str(&data.result, 50).to_string(),
                            success: data.success,
                            timestamp: event.created_at,
                        });
                    }
                }
                EventType::Error => {
                    if let Ok(data) = event.parse_data::<ErrorData>() {
                        last_error = Some((event.clone(), data));
                    }
                }
                EventType::DecisionPoint => {
                    if let Ok(data) = event.parse_data::<DecisionPointData>() {
                        if data.severity.is_warning_or_higher() {
                            recent_diagnostics.push(RecentDiagnostic {
                                severity: data.severity.as_str().to_string(),
                                code: data
                                    .code
                                    .unwrap_or_else(|| data.decision_type.as_str().to_string()),
                                summary: truncate_str(&data.summary, 80).to_string(),
                                timestamp: event.created_at,
                            });
                        }
                    }
                }
                EventType::SubAgentSpawn => {
                    if let Ok(data) = event.parse_data::<SubAgentSpawnData>() {
                        sub_agent_starts
                            .insert(data.child_session_id.clone(), (event.clone(), data));
                    }
                }
                EventType::SubAgentComplete => {
                    if let Ok(data) = event.parse_data::<super::SubAgentCompleteData>() {
                        completed_sub_agents.insert(data.child_session_id);
                    }
                }
                _ => {}
            }
        }

        // Find current task (started but not ended)
        let now = Utc::now();
        for (task_id, (start_event, start_data)) in &task_starts {
            if !task_ends.contains_key(task_id) {
                let elapsed = (now - start_event.created_at).num_seconds().max(0) as u64;
                context.current_task = Some(CurrentTask {
                    task_id: task_id.clone(),
                    description: start_data.description.clone(),
                    started_at: start_event.created_at,
                    elapsed_secs: elapsed,
                    iterations: task_iterations.get(task_id).copied().unwrap_or(0),
                    tool_calls: task_tool_calls.get(task_id).copied().unwrap_or(0),
                });
                context.current_iteration = task_iterations.get(task_id).copied();
                break; // Only one current task
            }
        }

        // Find last completed task
        if let Some((_task_id, (end_event, end_data))) =
            task_ends.iter().max_by_key(|(_, (e, _))| e.created_at)
        {
            let description = task_starts
                .get(&end_data.task_id)
                .map(|(_, d)| d.description.clone())
                .unwrap_or_else(|| "Unknown task".to_string());

            context.last_completed_task = Some(CompletedTask {
                task_id: end_data.task_id.clone(),
                description,
                status: end_data.status,
                duration_secs: end_data.duration_secs,
                error: end_data.error.clone(),
                completed_at: end_event.created_at,
            });
        }

        // Set last error
        if let Some((error_event, error_data)) = last_error {
            context.last_error = Some(RecentError {
                message: error_data.message,
                error_type: format!("{:?}", error_data.error_type),
                occurred_at: error_event.created_at,
                task_context: error_data.context,
                tool_name: error_data.tool_name,
                recovered: error_data.recovered,
            });
        }

        // Set recent tools (last 10, most recent first)
        recent_tools.reverse();
        recent_tools.truncate(10);
        context.recent_tools = recent_tools;

        recent_diagnostics.reverse();
        recent_diagnostics.truncate(5);
        context.recent_diagnostics = recent_diagnostics;

        // Find active sub-agents
        for (child_session_id, (spawn_event, spawn_data)) in sub_agent_starts {
            if !completed_sub_agents.contains(&child_session_id) {
                context.active_sub_agents.push(ActiveSubAgent {
                    child_session_id,
                    mission: spawn_data.mission,
                    depth: spawn_data.depth,
                    started_at: spawn_event.created_at,
                });
            }
        }

        context
    }
}

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

    #[test]
    fn test_empty_context() {
        let ctx = SessionContext::default();
        assert!(ctx.is_empty());
        assert_eq!(ctx.format_for_prompt(), "");
    }

    #[test]
    fn test_context_formatting() {
        let ctx = SessionContext {
            current_task: Some(CurrentTask {
                task_id: "task_1".to_string(),
                description: "Add blog posts".to_string(),
                started_at: Utc::now(),
                elapsed_secs: 120,
                iterations: 5,
                tool_calls: 8,
            }),
            last_error: Some(RecentError {
                message: "Command failed".to_string(),
                error_type: "ToolError".to_string(),
                occurred_at: Utc::now(),
                task_context: None,
                tool_name: Some("terminal".to_string()),
                recovered: false,
            }),
            recent_tools: vec![RecentTool {
                name: "terminal".to_string(),
                summary: "git status".to_string(),
                success: true,
                timestamp: Utc::now(),
            }],
            recent_diagnostics: vec![RecentDiagnostic {
                severity: "warning".to_string(),
                code: "soft_iteration_warning".to_string(),
                summary: "Soft iteration warning threshold reached".to_string(),
                timestamp: Utc::now(),
            }],
            ..Default::default()
        };

        let formatted = ctx.format_for_prompt();
        assert!(formatted.contains("Active task"));
        assert!(formatted.contains("Add blog posts"));
        assert!(formatted.contains("Recent error"));
        assert!(formatted.contains("terminal"));
        assert!(formatted.contains("Recent diagnostics"));
        assert!(formatted.contains("soft_iteration_warning"));
    }
}