Skip to main content

aidaemon_memory/full/
transcript.rs

1//! A conversation log for hosts that keep none: the owner's turns, recorded
2//! at the end of each run, in the memory database. It is what the
3//! background jobs ([`MemoryJobs`](super::jobs::MemoryJobs)) read when
4//! [`FullMemory::with_background`](super::FullMemory::with_background) runs
5//! them for an SDK agent. A host with its own log (the daemon's events)
6//! implements [`ActivityLog`] over it instead.
7
8use std::collections::HashSet;
9
10use aidaemon_core::{
11    ChannelVisibility, Hook, HookContext, Message, MessageOrigin, Role, RunOutcome,
12};
13use async_trait::async_trait;
14use chrono::{DateTime, Utc};
15use sqlx::{Row, SqlitePool};
16
17use crate::history::{
18    ActivityLog, ConsolidationCursors, ConversationSource, HistoryTurn, LoggedTurn, MessageLog,
19    TurnRole, UncapturedSessions,
20};
21use crate::records::EpisodeBound;
22
23/// The owner's conversation turns, in two tables of their own
24/// (`memory_transcript`, `memory_transcript_cursors`) created on open.
25#[derive(Clone)]
26pub struct TranscriptLog {
27    pool: SqlitePool,
28}
29
30impl TranscriptLog {
31    pub async fn open(pool: SqlitePool) -> anyhow::Result<Self> {
32        sqlx::query(
33            "CREATE TABLE IF NOT EXISTS memory_transcript (
34                id INTEGER PRIMARY KEY AUTOINCREMENT,
35                session_id TEXT NOT NULL,
36                role TEXT NOT NULL,
37                content TEXT,
38                tool_calls TEXT NOT NULL DEFAULT '[]',
39                tool_name TEXT,
40                created_at TEXT NOT NULL
41            )",
42        )
43        .execute(&pool)
44        .await?;
45        sqlx::query(
46            "CREATE INDEX IF NOT EXISTS idx_memory_transcript_session
47             ON memory_transcript(session_id, created_at)",
48        )
49        .execute(&pool)
50        .await?;
51        sqlx::query(
52            "CREATE TABLE IF NOT EXISTS memory_transcript_cursors (
53                session_id TEXT PRIMARY KEY,
54                turn_id INTEGER NOT NULL
55            )",
56        )
57        .execute(&pool)
58        .await?;
59        Ok(Self { pool })
60    }
61
62    /// Append one turn.
63    pub async fn record(&self, session_id: &str, turn: &LoggedTurn) -> anyhow::Result<i64> {
64        Ok(sqlx::query(
65            "INSERT INTO memory_transcript
66                (session_id, role, content, tool_calls, tool_name, created_at)
67             VALUES (?, ?, ?, ?, ?, ?)",
68        )
69        .bind(session_id)
70        .bind(turn.role.as_str())
71        .bind(&turn.content)
72        .bind(serde_json::to_string(&turn.tool_calls)?)
73        .bind(&turn.tool_name)
74        .bind(turn.created_at.to_rfc3339())
75        .execute(&self.pool)
76        .await?
77        .last_insert_rowid())
78    }
79
80    /// A run-end hook that records the run's turns: its last user message
81    /// and everything after it.
82    pub fn recorder(&self) -> TranscriptRecorder {
83        TranscriptRecorder { log: self.clone() }
84    }
85
86    async fn rows(&self, sql: &str, binds: &[Bind<'_>]) -> anyhow::Result<Vec<(i64, LoggedTurn)>> {
87        let mut query = sqlx::query(sqlx::AssertSqlSafe(sql));
88        for bind in binds {
89            query = match bind {
90                Bind::Text(text) => query.bind(*text),
91                Bind::Int(int) => query.bind(*int),
92            };
93        }
94        let mut turns = Vec::new();
95        for row in query.fetch_all(&self.pool).await? {
96            let role = match row.get::<String, _>("role").as_str() {
97                "user" => TurnRole::User,
98                "assistant" => TurnRole::Assistant,
99                "tool" => TurnRole::Tool,
100                _ => continue,
101            };
102            let created: String = row.get("created_at");
103            turns.push((
104                row.get("id"),
105                LoggedTurn {
106                    role,
107                    content: row.get("content"),
108                    tool_calls: serde_json::from_str(&row.get::<String, _>("tool_calls"))
109                        .unwrap_or_default(),
110                    tool_name: row.get("tool_name"),
111                    created_at: parse_time(&created),
112                },
113            ));
114        }
115        Ok(turns)
116    }
117}
118
119enum Bind<'a> {
120    Text(&'a str),
121    Int(i64),
122}
123
124const COLUMNS: &str = "id, role, content, tool_calls, tool_name, created_at";
125
126fn parse_time(value: &str) -> DateTime<Utc> {
127    DateTime::parse_from_rfc3339(value)
128        .map(|at| at.with_timezone(&Utc))
129        .unwrap_or_else(|_| Utc::now())
130}
131
132/// The filter after a session's latest episode, and its bind: past the last
133/// turn it covers, else past its end.
134fn after_bound(bound: Option<&EpisodeBound>) -> (&'static str, Option<Bind<'_>>) {
135    match bound {
136        Some(EpisodeBound {
137            end_event_id: Some(id),
138            ..
139        }) => (" AND id > ?", Some(Bind::Int(*id))),
140        Some(EpisodeBound {
141            end_time: Some(end),
142            ..
143        }) => (" AND created_at > ?", Some(Bind::Text(end))),
144        _ => ("", None),
145    }
146}
147
148/// Records each run's turns into a [`TranscriptLog`].
149pub struct TranscriptRecorder {
150    log: TranscriptLog,
151}
152
153#[async_trait]
154impl Hook for TranscriptRecorder {
155    fn name(&self) -> &'static str {
156        "memory_transcript"
157    }
158
159    async fn on_run_end(&self, ctx: &HookContext<'_>, _outcome: &RunOutcome) {
160        let Some(start) = ctx
161            .messages
162            .iter()
163            .rposition(|m| m.role == Role::User && m.origin != Some(MessageOrigin::Harness))
164        else {
165            return;
166        };
167        let now = Utc::now();
168        let names: std::collections::HashMap<&str, &str> = ctx
169            .messages
170            .iter()
171            .flat_map(|m| &m.tool_calls)
172            .map(|call| (call.id.as_str(), call.name.as_str()))
173            .collect();
174        for message in &ctx.messages[start..] {
175            let Some(turn) = logged(message, &names, now) else {
176                continue;
177            };
178            if let Err(error) = self.log.record(ctx.session_id, &turn).await {
179                tracing::warn!(%error, "Failed to record a transcript turn");
180                return;
181            }
182        }
183    }
184}
185
186fn logged(
187    message: &Message,
188    names: &std::collections::HashMap<&str, &str>,
189    at: DateTime<Utc>,
190) -> Option<LoggedTurn> {
191    let role = match message.role {
192        Role::User if message.origin.is_none() || message.origin == Some(MessageOrigin::User) => {
193            TurnRole::User
194        }
195        Role::Assistant => TurnRole::Assistant,
196        Role::Tool => TurnRole::Tool,
197        _ => return None,
198    };
199    let tool_name = (role == TurnRole::Tool)
200        .then(|| {
201            message
202                .tool_call_id
203                .as_deref()
204                .and_then(|id| names.get(id))
205                .map(|name| name.to_string())
206        })
207        .flatten();
208    Some(LoggedTurn {
209        role,
210        content: Some(message.content.clone()),
211        tool_calls: message
212            .tool_calls
213            .iter()
214            .map(|call| call.name.clone())
215            .collect(),
216        tool_name,
217        created_at: at,
218    })
219}
220
221#[async_trait]
222impl ConversationSource for TranscriptLog {
223    async fn sessions_with_turns_before(
224        &self,
225        cutoff: DateTime<Utc>,
226    ) -> anyhow::Result<Vec<String>> {
227        Ok(sqlx::query_scalar(
228            "SELECT DISTINCT session_id FROM memory_transcript WHERE created_at < ?",
229        )
230        .bind(cutoff.to_rfc3339())
231        .fetch_all(&self.pool)
232        .await?)
233    }
234
235    /// Every recorded turn is the owner's.
236    async fn is_memory_isolated(&self, _session_id: &str) -> anyhow::Result<bool> {
237        Ok(false)
238    }
239
240    async fn owner_only_since(
241        &self,
242        session_id: &str,
243        after_id: i64,
244        cutoff: DateTime<Utc>,
245    ) -> anyhow::Result<bool> {
246        let users: i64 = sqlx::query_scalar(
247            "SELECT COUNT(*) FROM memory_transcript
248             WHERE session_id = ? AND role = 'user' AND id > ? AND created_at < ?",
249        )
250        .bind(session_id)
251        .bind(after_id)
252        .bind(cutoff.to_rfc3339())
253        .fetch_one(&self.pool)
254        .await?;
255        Ok(users > 0)
256    }
257
258    async fn last_turn_id(
259        &self,
260        session_id: &str,
261        after_id: i64,
262        cutoff: DateTime<Utc>,
263    ) -> anyhow::Result<Option<i64>> {
264        Ok(sqlx::query_scalar(
265            "SELECT MAX(id) FROM memory_transcript
266             WHERE session_id = ? AND id > ? AND created_at < ?",
267        )
268        .bind(session_id)
269        .bind(after_id)
270        .bind(cutoff.to_rfc3339())
271        .fetch_one(&self.pool)
272        .await?)
273    }
274
275    async fn turns(
276        &self,
277        session_id: &str,
278        after_id: i64,
279        cutoff: DateTime<Utc>,
280        limit: usize,
281    ) -> anyhow::Result<Vec<HistoryTurn>> {
282        let cutoff = cutoff.to_rfc3339();
283        let sql = format!(
284            "SELECT {COLUMNS} FROM memory_transcript
285             WHERE session_id = ? AND id > ? AND created_at < ?
286             ORDER BY id ASC LIMIT ?"
287        );
288        let rows = self
289            .rows(
290                &sql,
291                &[
292                    Bind::Text(session_id),
293                    Bind::Int(after_id),
294                    Bind::Text(&cutoff),
295                    Bind::Int(limit as i64),
296                ],
297            )
298            .await?;
299        Ok(rows
300            .into_iter()
301            .map(|(id, turn)| HistoryTurn {
302                id,
303                role: turn.role,
304                content: turn.content,
305                created_at: turn.created_at,
306            })
307            .collect())
308    }
309
310    async fn visibility(&self, _session_id: &str) -> Option<ChannelVisibility> {
311        Some(ChannelVisibility::Private)
312    }
313
314    fn channel_id(&self, _session_id: &str) -> Option<String> {
315        None
316    }
317}
318
319#[async_trait]
320impl ConsolidationCursors for TranscriptLog {
321    async fn cursor(&self, session_id: &str) -> i64 {
322        sqlx::query_scalar("SELECT turn_id FROM memory_transcript_cursors WHERE session_id = ?")
323            .bind(session_id)
324            .fetch_optional(&self.pool)
325            .await
326            .ok()
327            .flatten()
328            .unwrap_or(0)
329    }
330
331    async fn set_cursor(&self, session_id: &str, turn_id: i64) -> anyhow::Result<()> {
332        sqlx::query(
333            "INSERT INTO memory_transcript_cursors (session_id, turn_id) VALUES (?, ?)
334             ON CONFLICT(session_id) DO UPDATE SET turn_id = excluded.turn_id",
335        )
336        .bind(session_id)
337        .bind(turn_id)
338        .execute(&self.pool)
339        .await?;
340        Ok(())
341    }
342}
343
344#[async_trait]
345impl ActivityLog for TranscriptLog {
346    async fn uncaptured_sessions(
347        &self,
348        episode_ends: &[(String, String)],
349        which: UncapturedSessions,
350    ) -> anyhow::Result<Vec<String>> {
351        let idle_before = which.idle_before.map(|at| at.to_rfc3339());
352        let sessions: Vec<String> =
353            sqlx::query_scalar("SELECT DISTINCT session_id FROM memory_transcript")
354                .fetch_all(&self.pool)
355                .await?;
356        let mut found = Vec::new();
357        for session_id in sessions {
358            let end = episode_ends
359                .iter()
360                .find(|(session, _)| *session == session_id)
361                .map(|(_, end)| end.clone())
362                .unwrap_or_default();
363            let mut sql = String::from(
364                "SELECT COUNT(*), MAX(created_at) FROM memory_transcript
365                 WHERE session_id = ? AND created_at > ?",
366            );
367            if idle_before.is_some() {
368                sql.push_str(" AND created_at < ?");
369            }
370            let mut query = sqlx::query_as::<_, (i64, Option<String>)>(sqlx::AssertSqlSafe(&*sql))
371                .bind(&session_id)
372                .bind(&end);
373            if let Some(idle_before) = &idle_before {
374                query = query.bind(idle_before);
375            }
376            let (count, last) = query.fetch_one(&self.pool).await?;
377            let idle = match (&idle_before, &last) {
378                (Some(before), Some(last)) => last < before,
379                _ => true,
380            };
381            if count as usize >= which.min_turns && idle {
382                found.push(session_id);
383            }
384        }
385        Ok(found)
386    }
387
388    async fn owner_only_after(
389        &self,
390        session_id: &str,
391        since: Option<&EpisodeBound>,
392    ) -> anyhow::Result<bool> {
393        let (filter, end) = after_bound(since);
394        let sql = format!(
395            "SELECT COUNT(*) FROM memory_transcript
396             WHERE session_id = ? AND role = 'user'{filter}"
397        );
398        let mut query = sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(&*sql)).bind(session_id);
399        query = match end {
400            Some(Bind::Text(end)) => query.bind(end),
401            Some(Bind::Int(id)) => query.bind(id),
402            None => query,
403        };
404        Ok(query.fetch_one(&self.pool).await? > 0)
405    }
406
407    async fn turns_after(
408        &self,
409        session_id: &str,
410        since: Option<&EpisodeBound>,
411        limit: usize,
412    ) -> anyhow::Result<Vec<LoggedTurn>> {
413        let (filter, end) = after_bound(since);
414        let sql = format!(
415            "SELECT {COLUMNS} FROM memory_transcript
416             WHERE session_id = ?{filter} ORDER BY id ASC LIMIT ?"
417        );
418        let mut binds = vec![Bind::Text(session_id)];
419        binds.extend(end);
420        binds.push(Bind::Int(limit as i64));
421        Ok(self
422            .rows(&sql, &binds)
423            .await?
424            .into_iter()
425            .map(|(_, turn)| turn)
426            .collect())
427    }
428
429    async fn recent_turns(
430        &self,
431        since: DateTime<Utc>,
432        limit: usize,
433    ) -> anyhow::Result<Vec<LoggedTurn>> {
434        let since = since.to_rfc3339();
435        let sql = format!(
436            "SELECT {COLUMNS} FROM memory_transcript
437             WHERE created_at >= ? ORDER BY created_at DESC LIMIT ?"
438        );
439        Ok(self
440            .rows(&sql, &[Bind::Text(&since), Bind::Int(limit as i64)])
441            .await?
442            .into_iter()
443            .map(|(_, turn)| turn)
444            .collect())
445    }
446
447    async fn recent_owner_messages(
448        &self,
449        since: DateTime<Utc>,
450        limit: usize,
451    ) -> anyhow::Result<Vec<LoggedTurn>> {
452        let since = since.to_rfc3339();
453        let sql = format!(
454            "SELECT {COLUMNS} FROM memory_transcript
455             WHERE created_at >= ? AND role = 'user' ORDER BY created_at DESC LIMIT ?"
456        );
457        Ok(self
458            .rows(&sql, &[Bind::Text(&since), Bind::Int(limit as i64)])
459            .await?
460            .into_iter()
461            .map(|(_, turn)| turn)
462            .collect())
463    }
464}
465
466/// Episodes record the turns they cover by id.
467#[async_trait]
468impl MessageLog for TranscriptLog {
469    async fn message_bounds(
470        &self,
471        session_id: &str,
472        start: DateTime<Utc>,
473        end: DateTime<Utc>,
474    ) -> anyhow::Result<(Option<i64>, Option<i64>)> {
475        Ok(sqlx::query_as(
476            "SELECT MIN(id), MAX(id) FROM memory_transcript
477             WHERE session_id = ? AND role IN ('user', 'assistant')
478               AND created_at >= ? AND created_at <= ?",
479        )
480        .bind(session_id)
481        .bind(start.to_rfc3339())
482        .bind(end.to_rfc3339())
483        .fetch_one(&self.pool)
484        .await?)
485    }
486
487    async fn retained(&self, ids: &[i64]) -> anyhow::Result<HashSet<i64>> {
488        let mut kept = HashSet::new();
489        for chunk in ids.chunks(500) {
490            let placeholders = vec!["?"; chunk.len()].join(", ");
491            let sql = format!("SELECT id FROM memory_transcript WHERE id IN ({placeholders})");
492            let mut query = sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(&*sql));
493            for id in chunk {
494                query = query.bind(id);
495            }
496            kept.extend(query.fetch_all(&self.pool).await?);
497        }
498        Ok(kept)
499    }
500}