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    crate::types::parse_ts(value).unwrap_or_else(Utc::now)
128}
129
130/// The filter after a session's latest episode, and its bind: past the last
131/// turn it covers, else past its end.
132fn after_bound(bound: Option<&EpisodeBound>) -> (&'static str, Option<Bind<'_>>) {
133    match bound {
134        Some(EpisodeBound {
135            end_event_id: Some(id),
136            ..
137        }) => (" AND id > ?", Some(Bind::Int(*id))),
138        Some(EpisodeBound {
139            end_time: Some(end),
140            ..
141        }) => (" AND created_at > ?", Some(Bind::Text(end))),
142        _ => ("", None),
143    }
144}
145
146/// Records each run's turns into a [`TranscriptLog`].
147pub struct TranscriptRecorder {
148    log: TranscriptLog,
149}
150
151#[async_trait]
152impl Hook for TranscriptRecorder {
153    fn name(&self) -> &'static str {
154        "memory_transcript"
155    }
156
157    async fn on_run_end(&self, ctx: &HookContext<'_>, _outcome: &RunOutcome) {
158        let Some(start) = ctx
159            .messages
160            .iter()
161            .rposition(|m| m.role == Role::User && m.origin != Some(MessageOrigin::Harness))
162        else {
163            return;
164        };
165        let now = Utc::now();
166        let names: std::collections::HashMap<&str, &str> = ctx
167            .messages
168            .iter()
169            .flat_map(|m| &m.tool_calls)
170            .map(|call| (call.id.as_str(), call.name.as_str()))
171            .collect();
172        for message in &ctx.messages[start..] {
173            let Some(turn) = logged(message, &names, now) else {
174                continue;
175            };
176            if let Err(error) = self.log.record(ctx.session_id, &turn).await {
177                tracing::warn!(%error, "Failed to record a transcript turn");
178                return;
179            }
180        }
181    }
182}
183
184fn logged(
185    message: &Message,
186    names: &std::collections::HashMap<&str, &str>,
187    at: DateTime<Utc>,
188) -> Option<LoggedTurn> {
189    let role = match message.role {
190        Role::User if message.origin.is_none() || message.origin == Some(MessageOrigin::User) => {
191            TurnRole::User
192        }
193        Role::Assistant => TurnRole::Assistant,
194        Role::Tool => TurnRole::Tool,
195        _ => return None,
196    };
197    let tool_name = (role == TurnRole::Tool)
198        .then(|| {
199            message
200                .tool_call_id
201                .as_deref()
202                .and_then(|id| names.get(id))
203                .map(|name| name.to_string())
204        })
205        .flatten();
206    Some(LoggedTurn {
207        role,
208        content: Some(message.content.clone()),
209        tool_calls: message
210            .tool_calls
211            .iter()
212            .map(|call| call.name.clone())
213            .collect(),
214        tool_name,
215        created_at: at,
216    })
217}
218
219#[async_trait]
220impl ConversationSource for TranscriptLog {
221    async fn sessions_with_turns_before(
222        &self,
223        cutoff: DateTime<Utc>,
224    ) -> anyhow::Result<Vec<String>> {
225        Ok(sqlx::query_scalar(
226            "SELECT DISTINCT session_id FROM memory_transcript WHERE created_at < ?",
227        )
228        .bind(cutoff.to_rfc3339())
229        .fetch_all(&self.pool)
230        .await?)
231    }
232
233    /// Every recorded turn is the owner's.
234    async fn is_memory_isolated(&self, _session_id: &str) -> anyhow::Result<bool> {
235        Ok(false)
236    }
237
238    async fn owner_only_since(
239        &self,
240        session_id: &str,
241        after_id: i64,
242        cutoff: DateTime<Utc>,
243    ) -> anyhow::Result<bool> {
244        let users: i64 = sqlx::query_scalar(
245            "SELECT COUNT(*) FROM memory_transcript
246             WHERE session_id = ? AND role = 'user' AND id > ? AND created_at < ?",
247        )
248        .bind(session_id)
249        .bind(after_id)
250        .bind(cutoff.to_rfc3339())
251        .fetch_one(&self.pool)
252        .await?;
253        Ok(users > 0)
254    }
255
256    async fn last_turn_id(
257        &self,
258        session_id: &str,
259        after_id: i64,
260        cutoff: DateTime<Utc>,
261    ) -> anyhow::Result<Option<i64>> {
262        Ok(sqlx::query_scalar(
263            "SELECT MAX(id) FROM memory_transcript
264             WHERE session_id = ? AND id > ? AND created_at < ?",
265        )
266        .bind(session_id)
267        .bind(after_id)
268        .bind(cutoff.to_rfc3339())
269        .fetch_one(&self.pool)
270        .await?)
271    }
272
273    async fn turns(
274        &self,
275        session_id: &str,
276        after_id: i64,
277        cutoff: DateTime<Utc>,
278        limit: usize,
279    ) -> anyhow::Result<Vec<HistoryTurn>> {
280        let cutoff = cutoff.to_rfc3339();
281        let sql = format!(
282            "SELECT {COLUMNS} FROM memory_transcript
283             WHERE session_id = ? AND id > ? AND created_at < ?
284             ORDER BY id ASC LIMIT ?"
285        );
286        let rows = self
287            .rows(
288                &sql,
289                &[
290                    Bind::Text(session_id),
291                    Bind::Int(after_id),
292                    Bind::Text(&cutoff),
293                    Bind::Int(limit as i64),
294                ],
295            )
296            .await?;
297        Ok(rows
298            .into_iter()
299            .map(|(id, turn)| HistoryTurn {
300                id,
301                role: turn.role,
302                content: turn.content,
303                created_at: turn.created_at,
304            })
305            .collect())
306    }
307
308    async fn visibility(&self, _session_id: &str) -> Option<ChannelVisibility> {
309        Some(ChannelVisibility::Private)
310    }
311
312    fn channel_id(&self, _session_id: &str) -> Option<String> {
313        None
314    }
315}
316
317#[async_trait]
318impl ConsolidationCursors for TranscriptLog {
319    async fn cursor(&self, session_id: &str) -> i64 {
320        sqlx::query_scalar("SELECT turn_id FROM memory_transcript_cursors WHERE session_id = ?")
321            .bind(session_id)
322            .fetch_optional(&self.pool)
323            .await
324            .ok()
325            .flatten()
326            .unwrap_or(0)
327    }
328
329    async fn set_cursor(&self, session_id: &str, turn_id: i64) -> anyhow::Result<()> {
330        sqlx::query(
331            "INSERT INTO memory_transcript_cursors (session_id, turn_id) VALUES (?, ?)
332             ON CONFLICT(session_id) DO UPDATE SET turn_id = excluded.turn_id",
333        )
334        .bind(session_id)
335        .bind(turn_id)
336        .execute(&self.pool)
337        .await?;
338        Ok(())
339    }
340}
341
342#[async_trait]
343impl ActivityLog for TranscriptLog {
344    async fn uncaptured_sessions(
345        &self,
346        episode_ends: &[(String, String)],
347        which: UncapturedSessions,
348    ) -> anyhow::Result<Vec<String>> {
349        let idle_before = which.idle_before.map(|at| at.to_rfc3339());
350        let sessions: Vec<String> =
351            sqlx::query_scalar("SELECT DISTINCT session_id FROM memory_transcript")
352                .fetch_all(&self.pool)
353                .await?;
354        let mut found = Vec::new();
355        for session_id in sessions {
356            let end = episode_ends
357                .iter()
358                .find(|(session, _)| *session == session_id)
359                .map(|(_, end)| end.clone())
360                .unwrap_or_default();
361            let mut sql = String::from(
362                "SELECT COUNT(*), MAX(created_at) FROM memory_transcript
363                 WHERE session_id = ? AND created_at > ?",
364            );
365            if idle_before.is_some() {
366                sql.push_str(" AND created_at < ?");
367            }
368            let mut query = sqlx::query_as::<_, (i64, Option<String>)>(sqlx::AssertSqlSafe(&*sql))
369                .bind(&session_id)
370                .bind(&end);
371            if let Some(idle_before) = &idle_before {
372                query = query.bind(idle_before);
373            }
374            let (count, last) = query.fetch_one(&self.pool).await?;
375            let idle = match (&idle_before, &last) {
376                (Some(before), Some(last)) => last < before,
377                _ => true,
378            };
379            if count as usize >= which.min_turns && idle {
380                found.push(session_id);
381            }
382        }
383        Ok(found)
384    }
385
386    async fn owner_only_after(
387        &self,
388        session_id: &str,
389        since: Option<&EpisodeBound>,
390    ) -> anyhow::Result<bool> {
391        let (filter, end) = after_bound(since);
392        let sql = format!(
393            "SELECT COUNT(*) FROM memory_transcript
394             WHERE session_id = ? AND role = 'user'{filter}"
395        );
396        let mut query = sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(&*sql)).bind(session_id);
397        query = match end {
398            Some(Bind::Text(end)) => query.bind(end),
399            Some(Bind::Int(id)) => query.bind(id),
400            None => query,
401        };
402        Ok(query.fetch_one(&self.pool).await? > 0)
403    }
404
405    async fn turns_after(
406        &self,
407        session_id: &str,
408        since: Option<&EpisodeBound>,
409        limit: usize,
410    ) -> anyhow::Result<Vec<LoggedTurn>> {
411        let (filter, end) = after_bound(since);
412        let sql = format!(
413            "SELECT {COLUMNS} FROM memory_transcript
414             WHERE session_id = ?{filter} ORDER BY id ASC LIMIT ?"
415        );
416        let mut binds = vec![Bind::Text(session_id)];
417        binds.extend(end);
418        binds.push(Bind::Int(limit as i64));
419        Ok(self
420            .rows(&sql, &binds)
421            .await?
422            .into_iter()
423            .map(|(_, turn)| turn)
424            .collect())
425    }
426
427    async fn recent_turns(
428        &self,
429        since: DateTime<Utc>,
430        limit: usize,
431    ) -> anyhow::Result<Vec<LoggedTurn>> {
432        let since = since.to_rfc3339();
433        let sql = format!(
434            "SELECT {COLUMNS} FROM memory_transcript
435             WHERE created_at >= ? ORDER BY created_at DESC LIMIT ?"
436        );
437        Ok(self
438            .rows(&sql, &[Bind::Text(&since), Bind::Int(limit as i64)])
439            .await?
440            .into_iter()
441            .map(|(_, turn)| turn)
442            .collect())
443    }
444
445    async fn recent_owner_messages(
446        &self,
447        since: DateTime<Utc>,
448        limit: usize,
449    ) -> anyhow::Result<Vec<LoggedTurn>> {
450        let since = since.to_rfc3339();
451        let sql = format!(
452            "SELECT {COLUMNS} FROM memory_transcript
453             WHERE created_at >= ? AND role = 'user' ORDER BY created_at DESC LIMIT ?"
454        );
455        Ok(self
456            .rows(&sql, &[Bind::Text(&since), Bind::Int(limit as i64)])
457            .await?
458            .into_iter()
459            .map(|(_, turn)| turn)
460            .collect())
461    }
462}
463
464/// Episodes record the turns they cover by id.
465#[async_trait]
466impl MessageLog for TranscriptLog {
467    async fn message_bounds(
468        &self,
469        session_id: &str,
470        start: DateTime<Utc>,
471        end: DateTime<Utc>,
472    ) -> anyhow::Result<(Option<i64>, Option<i64>)> {
473        Ok(sqlx::query_as(
474            "SELECT MIN(id), MAX(id) FROM memory_transcript
475             WHERE session_id = ? AND role IN ('user', 'assistant')
476               AND created_at >= ? AND created_at <= ?",
477        )
478        .bind(session_id)
479        .bind(start.to_rfc3339())
480        .bind(end.to_rfc3339())
481        .fetch_one(&self.pool)
482        .await?)
483    }
484
485    async fn retained(&self, ids: &[i64]) -> anyhow::Result<HashSet<i64>> {
486        let mut kept = HashSet::new();
487        for chunk in ids.chunks(500) {
488            let placeholders = vec!["?"; chunk.len()].join(", ");
489            let sql = format!("SELECT id FROM memory_transcript WHERE id IN ({placeholders})");
490            let mut query = sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(&*sql));
491            for id in chunk {
492                query = query.bind(id);
493            }
494            kept.extend(query.fetch_all(&self.pool).await?);
495        }
496        Ok(kept)
497    }
498}