Skip to main content

agent_engine/engine/
session.rs

1//! Engine-level session management — save, load, resume, clear.
2//!
3//! Owns the conversation state that both TUI and headless modes need:
4//! messages, token counts, cost.
5
6use crate::pricing::calculate_cost_optional_split;
7use crate::SharedMessage;
8use crate::{Runtime, Session};
9
10/// Session-scoped durability barrier state, shared by persistent frontends.
11/// A failed (or dropped in-flight) publication requires explicit reload/new
12/// session before saving or scheduling more inference. Never rollback-save an
13/// old head: `save_durable` can fail after publishing its replacement.
14#[derive(Default)]
15pub struct ContextHeadPersistence {
16    blocked_session: Option<String>,
17}
18
19impl ContextHeadPersistence {
20    pub fn is_blocked(&self, session: &Session) -> bool {
21        self.blocked_session.as_deref() == Some(session.id.as_str())
22    }
23
24    /// Candidate metadata must come from the host's current session, never
25    /// from message content. The event supplies only identity and messages.
26    pub async fn persist(
27        &mut self,
28        session: &mut Session,
29        messages: &mut Vec<SharedMessage>,
30        session_id: &str,
31        candidate: Session,
32    ) -> std::io::Result<()> {
33        self.persist_with(
34            session,
35            messages,
36            session_id,
37            candidate,
38            |candidate| async move { candidate.save_durable().await },
39        )
40        .await
41    }
42
43    async fn persist_with<F, Fut>(
44        &mut self,
45        session: &mut Session,
46        messages: &mut Vec<SharedMessage>,
47        session_id: &str,
48        candidate: Session,
49        save: F,
50    ) -> std::io::Result<()>
51    where
52        F: FnOnce(Session) -> Fut,
53        Fut: std::future::Future<Output = std::io::Result<()>>,
54    {
55        if self.is_blocked(session) {
56            return Err(std::io::Error::other(
57                "context head is unverified; reload the session before continuing",
58            ));
59        }
60        // Latch before any await, including on identity rejection. Dropping
61        // this future cannot authorize a later ordinary save of the old head.
62        self.blocked_session = Some(session.id.clone());
63        if session_id != session.id || candidate.id != session.id {
64            return Err(std::io::Error::new(
65                std::io::ErrorKind::InvalidInput,
66                "context head checkpoint does not match the current session",
67            ));
68        }
69        let result = save(candidate.clone()).await;
70        // Success adopts the durable head. An attempted-save error adopts it
71        // ONLY as conservative recovery state (not a successful commit): a
72        // rename may already have happened. The latch remains set, so neither
73        // post-turn saves nor automatic inference can act on this ambiguity.
74        *messages = candidate.api_messages.clone();
75        *session = candidate;
76        if result.is_ok() {
77            self.blocked_session = None;
78        }
79        result
80    }
81}
82
83/// Conversation state tracked by the engine.
84pub struct ConversationState {
85    pub session: Session,
86    pub context_head: ContextHeadPersistence,
87    pub api_messages: Vec<SharedMessage>,
88    pub total_input_tokens: u64,
89    pub total_output_tokens: u64,
90    pub total_cache_read_tokens: u64,
91    pub total_cache_creation_tokens: u64,
92    pub session_cost: f64,
93    /// Prompt-cache keep-warm spend (task #444), already INCLUDED in
94    /// `session_cost` and shown separately; persisted with it
95    /// (`Session::keepwarm_cost`).
96    pub keepwarm_cost: f64,
97    /// Keep-warm ping tokens, already INCLUDED in the `total_*` counters
98    /// above and shown separately so `/stats` adds up.
99    pub keepwarm_tokens: crate::session::ConversationTokens,
100    /// Message queued to send after current stream completes.
101    pub queued_message: Option<String>,
102    /// Events buffered during streaming — drained on stream completion.
103    pub pending_events: Vec<String>,
104}
105
106/// The keep-warm token subtotal as persisted in the snapshot
107/// (`Session::keepwarm_tokens`, snapshot-only — never journaled).
108fn persisted_keepwarm_tokens(
109    t: &crate::session::ConversationTokens,
110) -> agent_core::core::session::KeepwarmTokens {
111    agent_core::core::session::KeepwarmTokens {
112        input: t.input,
113        output: t.output,
114        cache_read: t.cache_read,
115        cache_creation: t.cache_creation,
116    }
117}
118
119/// The keep-warm subtotal a resumed conversation starts with: each bucket
120/// clamped under the total it is part of, so `/stats` still adds up. The
121/// cache totals persist with the session (snapshot-only); a session saved
122/// before they did resumes them at 0, and its keep-warm cache buckets too.
123fn resumed_keepwarm_tokens(session: &Session) -> crate::session::ConversationTokens {
124    let kw = session.keepwarm_tokens;
125    crate::session::ConversationTokens {
126        input: kw.input.min(session.total_input_tokens),
127        output: kw.output.min(session.total_output_tokens),
128        cache_read: kw.cache_read.min(session.total_cache_read_tokens),
129        cache_creation: kw.cache_creation.min(session.total_cache_creation_tokens),
130    }
131}
132
133impl ConversationState {
134    /// Create a new conversation with a fresh session.
135    pub fn new(session: Session) -> Self {
136        Self {
137            session,
138            context_head: ContextHeadPersistence::default(),
139            api_messages: Vec::new(),
140            total_input_tokens: 0,
141            total_output_tokens: 0,
142            total_cache_read_tokens: 0,
143            total_cache_creation_tokens: 0,
144            session_cost: 0.0,
145            keepwarm_cost: 0.0,
146            keepwarm_tokens: Default::default(),
147            queued_message: None,
148            pending_events: Vec::new(),
149        }
150    }
151
152    /// Create from a resumed session. A session saved before interruption
153    /// markers existed (legacy `abort_context` recap) is migrated here too —
154    /// `/resume` loads sessions without going through `engine::setup` —
155    /// idempotently: an already-migrated session is untouched.
156    pub fn from_resumed(mut session: Session) -> Self {
157        crate::engine::interrupt::migrate_legacy_abort_context(
158            &mut session.api_messages,
159            &mut session.abort_context,
160        );
161        Self {
162            api_messages: session.api_messages.clone(),
163            total_input_tokens: session.total_input_tokens,
164            total_output_tokens: session.total_output_tokens,
165            total_cache_read_tokens: session.total_cache_read_tokens,
166            total_cache_creation_tokens: session.total_cache_creation_tokens,
167            session_cost: session.session_cost,
168            keepwarm_cost: session.keepwarm_cost.min(session.session_cost).max(0.0),
169            keepwarm_tokens: resumed_keepwarm_tokens(&session),
170            queued_message: None,
171            pending_events: Vec::new(),
172            session,
173            context_head: ContextHeadPersistence::default(),
174        }
175    }
176
177    /// Save the current conversation state to disk. Returns whether it was
178    /// written: `false` when there is nothing to save (empty history), the
179    /// context head is unverified (`context_head`), or the write failed
180    /// (logged).
181    pub async fn save(&mut self) -> bool {
182        let Some(session) = self.prepare_save() else {
183            return false;
184        };
185        match session.save().await {
186            Ok(()) => true,
187            Err(e) => {
188                tracing::error!("Failed to save session: {}", e);
189                false
190            }
191        }
192    }
193
194    /// Fold the live state into `self.session` and return the snapshot to
195    /// write — or `None` when there is nothing to save (empty history) or
196    /// the context head is unverified. The session actor hands the snapshot
197    /// to its background writer (`session::persister`) instead of awaiting
198    /// the I/O. The clone is cheap: messages are `Arc`-shared.
199    pub fn prepare_save(&mut self) -> Option<Session> {
200        if self.context_head.is_blocked(&self.session) || self.api_messages.is_empty() {
201            return None;
202        }
203        self.session.api_messages = self.api_messages.clone();
204        self.session.total_input_tokens = self.total_input_tokens;
205        self.session.total_output_tokens = self.total_output_tokens;
206        self.session.total_cache_read_tokens = self.total_cache_read_tokens;
207        self.session.total_cache_creation_tokens = self.total_cache_creation_tokens;
208        self.session.session_cost = self.session_cost;
209        self.session.keepwarm_cost = self.keepwarm_cost;
210        self.session.keepwarm_tokens = persisted_keepwarm_tokens(&self.keepwarm_tokens);
211        // Legacy field: an interrupted turn now lives in `api_messages`
212        // (`engine::interrupt`); never write a recap back.
213        self.session.abort_context = None;
214        self.session.updated_at = chrono::Utc::now();
215        self.session.auto_title();
216        Some(self.session.clone())
217    }
218
219    /// Persist a runtime-requested head using host metadata and latest usage.
220    /// The caller completes the receipt with this exact result and continues
221    /// consuming the runtime's typed terminal error on failure.
222    pub async fn persist_context_head(
223        &mut self,
224        session_id: &str,
225        messages: Vec<SharedMessage>,
226    ) -> std::io::Result<()> {
227        let mut candidate = self.session.clone();
228        candidate.api_messages = messages;
229        candidate.total_input_tokens = self.total_input_tokens;
230        candidate.total_output_tokens = self.total_output_tokens;
231        candidate.total_cache_read_tokens = self.total_cache_read_tokens;
232        candidate.total_cache_creation_tokens = self.total_cache_creation_tokens;
233        candidate.session_cost = self.session_cost;
234        candidate.keepwarm_cost = self.keepwarm_cost;
235        candidate.keepwarm_tokens = persisted_keepwarm_tokens(&self.keepwarm_tokens);
236        candidate.abort_context = None;
237        candidate.updated_at = chrono::Utc::now();
238        candidate.auto_title();
239        self.context_head
240            .persist(
241                &mut self.session,
242                &mut self.api_messages,
243                session_id,
244                candidate,
245            )
246            .await
247    }
248
249    /// Clear the current session and start fresh.
250    pub async fn clear(&mut self, runtime: &Runtime) {
251        self.save().await;
252        self.context_head = ContextHeadPersistence::default();
253        self.api_messages.clear();
254        self.total_input_tokens = 0;
255        self.total_output_tokens = 0;
256        self.total_cache_read_tokens = 0;
257        self.total_cache_creation_tokens = 0;
258        self.session_cost = 0.0;
259        self.keepwarm_cost = 0.0;
260        self.keepwarm_tokens = Default::default();
261        self.queued_message = None;
262        self.pending_events.clear();
263        self.session = Session::new(
264            runtime.model(),
265            runtime.thinking_level(),
266            runtime.system_prompt(),
267        );
268        runtime.reset_context_continuation(&self.session.id, &[]);
269    }
270
271    /// Serializable mirror for clients (`SessionEventWire::Conversation`).
272    /// `consecutive_auto_turns` is actor/App-side state, not conversation
273    /// state, so the caller supplies it.
274    pub fn snapshot(
275        &self,
276        consecutive_auto_turns: u32,
277    ) -> crate::session::ConversationSnapshot {
278        crate::session::ConversationSnapshot {
279            header: crate::session::SessionHeader::from(&self.session),
280            api_messages: self.api_messages.clone(),
281            messages_len: self.api_messages.len(),
282            tokens: crate::session::ConversationTokens {
283                input: self.total_input_tokens,
284                output: self.total_output_tokens,
285                cache_read: self.total_cache_read_tokens,
286                cache_creation: self.total_cache_creation_tokens,
287            },
288            cost: self.session_cost,
289            keepwarm_cost: self.keepwarm_cost,
290            keepwarm_tokens: self.keepwarm_tokens.clone(),
291            // Wire-compat field (protocol v3); always `None` now.
292            abort_context: None,
293            queued_message: self.queued_message.clone(),
294            pending_events_len: self.pending_events.len(),
295            consecutive_auto_turns,
296            messages_hash_memo: Default::default(),
297        }
298    }
299
300    /// Add usage from a model turn.
301    ///
302    /// `cache_creation_5m` / `cache_creation_1h` are the cache-write TTL
303    /// split. When either is present the cost uses the split rates
304    /// (5m: 1.25×, 1h: 2.0×); when both are `None` the aggregate
305    /// `cache_creation` is billed at the 5m rate (fail-cheap fallback).
306    #[allow(clippy::too_many_arguments)]
307    pub fn add_usage(
308        &mut self,
309        input_tokens: u64,
310        output_tokens: u64,
311        cache_read: u64,
312        cache_creation: u64,
313        cache_creation_5m: Option<u64>,
314        cache_creation_1h: Option<u64>,
315        model: &str,
316    ) {
317        self.total_input_tokens += input_tokens;
318        self.total_output_tokens += output_tokens;
319        self.total_cache_read_tokens += cache_read;
320        self.total_cache_creation_tokens += cache_creation;
321
322        self.session_cost += calculate_cost_optional_split(
323            model,
324            input_tokens,
325            output_tokens,
326            cache_read,
327            cache_creation,
328            cache_creation_5m,
329            cache_creation_1h,
330        );
331    }
332}
333
334#[cfg(test)]
335mod context_head_tests {
336    use super::*;
337    use agent_core::core::context_head::ContextHeadReceipt;
338    use agent_core::core::session_journal::{save_session_durable_in_dir, SessionPersistence};
339    use serde_json::json;
340    use std::sync::Arc;
341
342    fn fixture() -> (Session, Vec<SharedMessage>, Session) {
343        let mut old = Session::new("synthetic-model", "medium", Some("host authority"));
344        old.id = "synthetic-context-head".into();
345        old.name = Some("synthetic-name".into());
346        old.title = "original title".into();
347        old.parent_session = Some("synthetic-parent".into());
348        old.api_messages = vec![Arc::new(json!({"role":"user","content":"old head"}))];
349        let messages = old.api_messages.clone();
350        let mut candidate = old.clone();
351        candidate.api_messages = vec![Arc::new(json!({"role":"user","content":"candidate"}))];
352        candidate.total_input_tokens = 23;
353        candidate.total_output_tokens = 7;
354        candidate.session_cost = 0.125;
355        candidate.abort_context = Some("latest synthetic abort context".into());
356        (old, messages, candidate)
357    }
358
359    #[cfg(unix)]
360    #[tokio::test]
361    async fn context_head_ack_follows_durable_write_and_adoption() {
362        for mode in [SessionPersistence::Json, SessionPersistence::Journal] {
363            let dir = tempfile::tempdir().unwrap();
364            let (mut session, mut messages, candidate) = fixture();
365            let id = session.id.clone();
366            let expected = serde_json::to_value(&candidate).unwrap();
367            let mut state = ContextHeadPersistence::default();
368            let (receipt, mut acknowledged) = ContextHeadReceipt::channel();
369            let (started_tx, started_rx) = tokio::sync::oneshot::channel();
370            let (release_tx, release_rx) = tokio::sync::oneshot::channel();
371            let path = dir.path().to_owned();
372            let result = {
373                let persist = state.persist_with(
374                    &mut session,
375                    &mut messages,
376                    &id,
377                    candidate,
378                    |candidate| async move {
379                        started_tx.send(()).unwrap();
380                        release_rx.await.unwrap();
381                        save_session_durable_in_dir(&path, &candidate, mode).map(|_| ())
382                    },
383                );
384                tokio::pin!(persist);
385                tokio::select! {
386                    result = &mut persist => panic!("write unexpectedly completed: {result:?}"),
387                    _ = started_rx => {}
388                }
389                assert!(matches!(
390                    acknowledged.try_recv(),
391                    Err(tokio::sync::oneshot::error::TryRecvError::Empty)
392                ));
393                release_tx.send(()).unwrap();
394                persist.await
395            };
396            assert!(result.is_ok());
397            receipt.complete(result);
398            assert_eq!(acknowledged.await.unwrap(), Ok(()));
399            assert_eq!(serde_json::to_value(&session).unwrap(), expected);
400            assert_eq!(messages, session.api_messages);
401            assert!(!state.is_blocked(&session));
402            let loaded = Session::load_from_dir(dir.path(), &id).unwrap();
403            assert_eq!(loaded.api_messages, messages);
404            assert_eq!(loaded.system_prompt.as_deref(), Some("host authority"));
405            assert_eq!(loaded.name, session.name);
406            assert_eq!(loaded.total_input_tokens, 23);
407            assert_eq!(loaded.total_output_tokens, 7);
408            assert_eq!(loaded.abort_context, session.abort_context);
409        }
410    }
411
412    #[tokio::test]
413    async fn context_head_identity_mismatch_never_writes_or_adopts() {
414        let (mut session, mut messages, candidate) = fixture();
415        let before = serde_json::to_value(&session).unwrap();
416        let mut state = ContextHeadPersistence::default();
417        let (receipt, acknowledged) = ContextHeadReceipt::channel();
418        let result = state
419            .persist_with(
420                &mut session,
421                &mut messages,
422                "another-session",
423                candidate,
424                |_| async { panic!("identity rejection must not reach persistence") },
425            )
426            .await;
427        assert_eq!(
428            result.as_ref().unwrap_err().kind(),
429            std::io::ErrorKind::InvalidInput
430        );
431        receipt.complete(result);
432        assert!(acknowledged.await.unwrap().is_err());
433        assert_eq!(serde_json::to_value(&session).unwrap(), before);
434        assert_eq!(messages, session.api_messages);
435        assert!(state.is_blocked(&session));
436        let mut other = session.clone();
437        other.id = "new-session".into();
438        assert!(!state.is_blocked(&other));
439    }
440
441    /// The cache totals persist with the session, so a daemon reload, an
442    /// unpark or `/resume` keeps the footer's cache hit rate. The keep-warm
443    /// cache buckets come back clamped under the totals they are part of.
444    #[test]
445    fn cache_totals_survive_save_and_resume() {
446        let mut s = Session::new("synthetic-model", "low", None);
447        s.api_messages = vec![Arc::new(json!({"role":"user","content":"q"}))];
448        let mut conv = ConversationState::from_resumed(s);
449        conv.add_usage(120, 40, 85_679, 6_250, None, None, "synthetic-model");
450        conv.keepwarm_tokens.cache_read = 4_000;
451        conv.keepwarm_tokens.cache_creation = 9_999; // stale label, above its total
452        let saved = conv.prepare_save().expect("non-empty history saves");
453        assert_eq!(saved.total_cache_read_tokens, 85_679);
454        assert_eq!(saved.total_cache_creation_tokens, 6_250);
455
456        let resumed = ConversationState::from_resumed(saved);
457        assert_eq!(resumed.total_cache_read_tokens, 85_679);
458        assert_eq!(resumed.total_cache_creation_tokens, 6_250);
459        assert_eq!(resumed.keepwarm_tokens.cache_read, 4_000);
460        assert_eq!(resumed.keepwarm_tokens.cache_creation, 6_250);
461        let wire = resumed.snapshot(0);
462        assert_eq!(wire.tokens.cache_read, 85_679);
463        assert_eq!(wire.tokens.cache_creation, 6_250);
464    }
465
466    /// `/resume` builds its conversation with `from_resumed` directly: a
467    /// legacy recap is migrated (dropped, marker appended), never carried.
468    #[test]
469    fn from_resumed_migrates_a_legacy_abort_context() {
470        let mut legacy = Session::new("synthetic-model", "low", None);
471        legacy.api_messages = vec![Arc::new(json!({"role":"user","content":"do X"}))];
472        legacy.abort_context = Some("(System note — ABORT CONTEXT: …)".into());
473        let conv = ConversationState::from_resumed(legacy);
474        assert!(conv.session.abort_context.is_none());
475        assert_eq!(conv.api_messages.len(), 2);
476        assert_eq!(
477            conv.api_messages[1]["content"],
478            crate::engine::interrupt::InterruptReason::Unknown.marker()
479        );
480        assert_eq!(conv.session.api_messages, conv.api_messages);
481        // Idempotent for an already-migrated session.
482        let again = ConversationState::from_resumed(conv.session.clone());
483        assert_eq!(again.api_messages, conv.api_messages);
484    }
485
486    #[cfg(unix)]
487    #[tokio::test]
488    async fn context_head_post_publish_error_is_not_rollback_or_success() {
489        let dir = tempfile::tempdir().unwrap();
490        let (session, _, candidate) = fixture();
491        let mut conv = ConversationState::from_resumed(session);
492        let id = conv.session.id.clone();
493        let expected = candidate.api_messages.clone();
494        let path = dir.path().to_owned();
495        let (receipt, acknowledged) = ContextHeadReceipt::channel();
496        let result = conv
497            .context_head
498            .persist_with(
499                &mut conv.session,
500                &mut conv.api_messages,
501                &id,
502                candidate,
503                |candidate| async move {
504                    save_session_durable_in_dir(&path, &candidate, SessionPersistence::Journal)?;
505                    Err(std::io::Error::other("synthetic error after publication"))
506                },
507            )
508            .await;
509        receipt.complete(result);
510        assert!(acknowledged.await.unwrap().is_err());
511        assert!(conv.context_head.is_blocked(&conv.session));
512        assert_eq!(conv.api_messages, expected);
513        assert_eq!(
514            Session::load_from_dir(dir.path(), &id)
515                .unwrap()
516                .api_messages,
517            expected
518        );
519        // Simulate stale failure repair/UI data. save() must return before it
520        // even copies this old state into the conservatively adopted Session.
521        conv.api_messages.clear();
522        conv.api_messages
523            .push(Arc::new(json!({"role":"user","content":"stale"})));
524        conv.save().await;
525        assert_eq!(conv.session.api_messages, expected);
526        let loaded = Session::load_from_dir(dir.path(), &id).unwrap();
527        let resumed = ConversationState::from_resumed(loaded);
528        assert!(!resumed.context_head.is_blocked(&resumed.session));
529    }
530
531    #[tokio::test]
532    async fn context_head_dropped_write_future_latches_without_mutating_old_head() {
533        let (mut session, mut messages, candidate) = fixture();
534        let before = serde_json::to_value(&session).unwrap();
535        let id = session.id.clone();
536        let mut state = ContextHeadPersistence::default();
537        {
538            let persist = state.persist_with(&mut session, &mut messages, &id, candidate, |_| {
539                std::future::pending::<std::io::Result<()>>()
540            });
541            tokio::pin!(persist);
542            assert!(futures::poll!(&mut persist).is_pending());
543        }
544        assert!(state.is_blocked(&session));
545        assert_eq!(serde_json::to_value(&session).unwrap(), before);
546        assert_eq!(messages, session.api_messages);
547    }
548}