//! Model-facing conversation: one shared owner session per key, stored in SQLite. //! Unlike the journal it keeps the exact text sent to the model, including per-turn context. use std::path::Path; use anyhow::Result; use capri_llm::Message; use rusqlite::{params, Connection, OptionalExtension}; /// Approximate prompt size of a stored message, in characters. pub fn size(message: &Message) -> usize { message.content.len() + message.tool_calls.len() * 200 } /// The summary as the first model message (OpenClaw compaction format). pub fn summary_message(summary: &str) -> Message { Message::new( "user", format!("The conversation history before this point was compacted into the following summary:\n\n\n{summary}\n"), ) } pub struct Session { db: Connection, key: String, pub id: String, } impl Session { pub fn open(file: &Path, key: &str) -> Result { let db = Connection::open(file)?; db.execute_batch( "PRAGMA journal_mode=WAL; CREATE TABLE IF NOT EXISTS sessions(id TEXT PRIMARY KEY, key TEXT NOT NULL, created_at TEXT NOT NULL, archived_at TEXT); CREATE TABLE IF NOT EXISTS entries(seq INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL REFERENCES sessions(id), kind TEXT NOT NULL, body TEXT NOT NULL, turn_id TEXT, created_at TEXT NOT NULL); CREATE INDEX IF NOT EXISTS entries_session ON entries(session_id, seq);", )?; let id: Option = db .query_row( "SELECT id FROM sessions WHERE key=?1 AND archived_at IS NULL ORDER BY created_at DESC LIMIT 1", [key], |r| r.get(0), ) .optional()?; let mut session = Self { db, key: key.into(), id: id.unwrap_or_default() }; if session.id.is_empty() { session.start()?; } Ok(session) } fn start(&mut self) -> Result<()> { self.id = uuid::Uuid::new_v4().to_string(); self.db.execute( "INSERT INTO sessions(id, key, created_at) VALUES (?1, ?2, ?3)", params![self.id, self.key, chrono::Utc::now().to_rfc3339()], )?; Ok(()) } /// Appends messages of one turn in a single transaction. `kind` is `user`, `assistant`, /// `tool_result` or `injected`. pub fn append(&mut self, turn_id: Option<&str>, entries: &[(&str, Message)]) -> Result<()> { let tx = self.db.transaction()?; let now = chrono::Utc::now().to_rfc3339(); for (kind, message) in entries { let mut message = message.clone(); message.thinking.clear(); // private reasoning is never kept tx.execute( "INSERT INTO entries(session_id, kind, body, turn_id, created_at) VALUES (?1, ?2, ?3, ?4, ?5)", params![self.id, kind, serde_json::to_string(&message)?, turn_id, now], )?; } tx.commit()?; Ok(()) } /// Messages after the latest compaction boundary, with their sequence numbers, and that /// compaction's summary. pub fn since_boundary(&self) -> Result<(Vec<(i64, Message)>, Option)> { let boundary: Option<(String,)> = self .db .query_row( "SELECT body FROM entries WHERE session_id=?1 AND kind='compaction' ORDER BY seq DESC LIMIT 1", [&self.id], |r| Ok((r.get(0)?,)), ) .optional()?; let (summary, first_kept) = match boundary { Some((body,)) => { let v: serde_json::Value = serde_json::from_str(&body)?; (v["summary"].as_str().map(str::to_string), v["firstKeptSeq"].as_i64().unwrap_or(0)) } None => (None, 0), }; let mut stmt = self.db.prepare("SELECT seq, body FROM entries WHERE session_id=?1 AND seq>=?2 AND kind!='compaction' ORDER BY seq")?; let rows = stmt.query_map(params![self.id, first_kept], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)))?; let mut out = Vec::new(); for row in rows { let (seq, body) = row?; out.push((seq, serde_json::from_str(&body)?)); } Ok((out, summary)) } /// Records a compaction: entries before `first_kept_seq` are represented by `summary`. /// The original entries stay on disk (memory search keeps them). pub fn compact(&mut self, summary: &str, first_kept_seq: i64) -> Result<()> { let body = serde_json::json!({"summary": summary, "firstKeptSeq": first_kept_seq}).to_string(); self.db.execute( "INSERT INTO entries(session_id, kind, body, created_at) VALUES (?1, 'compaction', ?2, ?3)", params![self.id, body, chrono::Utc::now().to_rfc3339()], )?; Ok(()) } /// Model view: the compaction summary (if any) then the kept messages, newest last, cut to /// `max_chars` from the oldest side; never starts on a tool result or assistant message. pub fn model_view(&self, max_chars: usize) -> Result> { let (entries, summary) = self.since_boundary()?; let mut used = summary.as_ref().map_or(0, String::len); let mut view: Vec = Vec::new(); for (_, message) in entries.into_iter().rev() { used += size(&message); if used > max_chars { break; } view.push(message); } view.reverse(); while view.first().is_some_and(|m| m.role != "user") { view.remove(0); } if let Some(summary) = summary { view.insert(0, summary_message(&summary)); } Ok(view) } /// Archives the active session and starts a new one (kept on disk for memory search). pub fn reset(&mut self) -> Result<()> { self.db.execute( "UPDATE sessions SET archived_at=?2 WHERE id=?1", params![self.id, chrono::Utc::now().to_rfc3339()], )?; self.start() } } #[cfg(test)] mod tests { use super::*; #[test] fn append_view_reset() { let dir = tempfile::tempdir().unwrap(); let file = dir.path().join("s.sqlite"); let mut s = Session::open(&file, "agent:capri:main").unwrap(); s.append(Some("t1"), &[("user", Message::new("user", "hello")), ("assistant", Message::new("assistant", "hi"))]).unwrap(); s.append(Some("t2"), &[("user", Message::new("user", "how are you")), ("assistant", Message::new("assistant", "fine"))]).unwrap(); let s = Session::open(&file, "agent:capri:main").unwrap(); let all = s.model_view(10_000).unwrap(); assert_eq!(all.len(), 4); let recent = s.model_view(20).unwrap(); assert_eq!(recent.iter().map(|m| m.content.as_str()).collect::>(), ["how are you", "fine"]); let mut s = s; let old = s.id.clone(); s.reset().unwrap(); assert_ne!(s.id, old); assert!(s.model_view(10_000).unwrap().is_empty()); } #[test] fn compaction_boundary() { let dir = tempfile::tempdir().unwrap(); let mut s = Session::open(&dir.path().join("s.sqlite"), "k").unwrap(); for i in 0..3 { s.append(None, &[("user", Message::new("user", format!("q{i}"))), ("assistant", Message::new("assistant", format!("a{i}")))]).unwrap(); } let (all, none) = s.since_boundary().unwrap(); assert!(none.is_none()); let keep = all[4].0; // keep q2/a2 s.compact("earlier: q0 q1", keep).unwrap(); let view = s.model_view(10_000).unwrap(); assert_eq!(view.len(), 3); assert!(view[0].content.contains("\nearlier: q0 q1\n")); assert_eq!(view[1].content, "q2"); } }