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. Input/output totals persist with
121/// the session; the cache totals do not (they restart at 0), so neither do
122/// the keep-warm cache buckets — `/stats` must still add up.
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: 0,
129        cache_creation: 0,
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: 0,
166            total_cache_creation_tokens: 0,
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.session_cost = self.session_cost;
207        self.session.keepwarm_cost = self.keepwarm_cost;
208        self.session.keepwarm_tokens = persisted_keepwarm_tokens(&self.keepwarm_tokens);
209        // Legacy field: an interrupted turn now lives in `api_messages`
210        // (`engine::interrupt`); never write a recap back.
211        self.session.abort_context = None;
212        self.session.updated_at = chrono::Utc::now();
213        self.session.auto_title();
214        Some(self.session.clone())
215    }
216
217    /// Persist a runtime-requested head using host metadata and latest usage.
218    /// The caller completes the receipt with this exact result and continues
219    /// consuming the runtime's typed terminal error on failure.
220    pub async fn persist_context_head(
221        &mut self,
222        session_id: &str,
223        messages: Vec<SharedMessage>,
224    ) -> std::io::Result<()> {
225        let mut candidate = self.session.clone();
226        candidate.api_messages = messages;
227        candidate.total_input_tokens = self.total_input_tokens;
228        candidate.total_output_tokens = self.total_output_tokens;
229        candidate.session_cost = self.session_cost;
230        candidate.keepwarm_cost = self.keepwarm_cost;
231        candidate.keepwarm_tokens = persisted_keepwarm_tokens(&self.keepwarm_tokens);
232        candidate.abort_context = None;
233        candidate.updated_at = chrono::Utc::now();
234        candidate.auto_title();
235        self.context_head
236            .persist(
237                &mut self.session,
238                &mut self.api_messages,
239                session_id,
240                candidate,
241            )
242            .await
243    }
244
245    /// Clear the current session and start fresh.
246    pub async fn clear(&mut self, runtime: &Runtime) {
247        self.save().await;
248        self.context_head = ContextHeadPersistence::default();
249        self.api_messages.clear();
250        self.total_input_tokens = 0;
251        self.total_output_tokens = 0;
252        self.total_cache_read_tokens = 0;
253        self.total_cache_creation_tokens = 0;
254        self.session_cost = 0.0;
255        self.keepwarm_cost = 0.0;
256        self.keepwarm_tokens = Default::default();
257        self.queued_message = None;
258        self.pending_events.clear();
259        self.session = Session::new(
260            runtime.model(),
261            runtime.thinking_level(),
262            runtime.system_prompt(),
263        );
264        runtime.reset_context_continuation(&self.session.id, &[]);
265    }
266
267    /// Serializable mirror for clients (`SessionEventWire::Conversation`).
268    /// `consecutive_auto_turns` is actor/App-side state, not conversation
269    /// state, so the caller supplies it.
270    pub fn snapshot(
271        &self,
272        consecutive_auto_turns: u32,
273    ) -> crate::session::ConversationSnapshot {
274        crate::session::ConversationSnapshot {
275            header: crate::session::SessionHeader::from(&self.session),
276            api_messages: self.api_messages.clone(),
277            messages_len: self.api_messages.len(),
278            tokens: crate::session::ConversationTokens {
279                input: self.total_input_tokens,
280                output: self.total_output_tokens,
281                cache_read: self.total_cache_read_tokens,
282                cache_creation: self.total_cache_creation_tokens,
283            },
284            cost: self.session_cost,
285            keepwarm_cost: self.keepwarm_cost,
286            keepwarm_tokens: self.keepwarm_tokens.clone(),
287            // Wire-compat field (protocol v3); always `None` now.
288            abort_context: None,
289            queued_message: self.queued_message.clone(),
290            pending_events_len: self.pending_events.len(),
291            consecutive_auto_turns,
292            messages_hash_memo: Default::default(),
293        }
294    }
295
296    /// Add usage from a model turn.
297    ///
298    /// `cache_creation_5m` / `cache_creation_1h` are the cache-write TTL
299    /// split. When either is present the cost uses the split rates
300    /// (5m: 1.25×, 1h: 2.0×); when both are `None` the aggregate
301    /// `cache_creation` is billed at the 5m rate (fail-cheap fallback).
302    #[allow(clippy::too_many_arguments)]
303    pub fn add_usage(
304        &mut self,
305        input_tokens: u64,
306        output_tokens: u64,
307        cache_read: u64,
308        cache_creation: u64,
309        cache_creation_5m: Option<u64>,
310        cache_creation_1h: Option<u64>,
311        model: &str,
312    ) {
313        self.total_input_tokens += input_tokens;
314        self.total_output_tokens += output_tokens;
315        self.total_cache_read_tokens += cache_read;
316        self.total_cache_creation_tokens += cache_creation;
317
318        self.session_cost += calculate_cost_optional_split(
319            model,
320            input_tokens,
321            output_tokens,
322            cache_read,
323            cache_creation,
324            cache_creation_5m,
325            cache_creation_1h,
326        );
327    }
328}
329
330#[cfg(test)]
331mod context_head_tests {
332    use super::*;
333    use agent_core::core::context_head::ContextHeadReceipt;
334    use agent_core::core::session_journal::{save_session_durable_in_dir, SessionPersistence};
335    use serde_json::json;
336    use std::sync::Arc;
337
338    fn fixture() -> (Session, Vec<SharedMessage>, Session) {
339        let mut old = Session::new("synthetic-model", "medium", Some("host authority"));
340        old.id = "synthetic-context-head".into();
341        old.name = Some("synthetic-name".into());
342        old.title = "original title".into();
343        old.parent_session = Some("synthetic-parent".into());
344        old.api_messages = vec![Arc::new(json!({"role":"user","content":"old head"}))];
345        let messages = old.api_messages.clone();
346        let mut candidate = old.clone();
347        candidate.api_messages = vec![Arc::new(json!({"role":"user","content":"candidate"}))];
348        candidate.total_input_tokens = 23;
349        candidate.total_output_tokens = 7;
350        candidate.session_cost = 0.125;
351        candidate.abort_context = Some("latest synthetic abort context".into());
352        (old, messages, candidate)
353    }
354
355    #[cfg(unix)]
356    #[tokio::test]
357    async fn context_head_ack_follows_durable_write_and_adoption() {
358        for mode in [SessionPersistence::Json, SessionPersistence::Journal] {
359            let dir = tempfile::tempdir().unwrap();
360            let (mut session, mut messages, candidate) = fixture();
361            let id = session.id.clone();
362            let expected = serde_json::to_value(&candidate).unwrap();
363            let mut state = ContextHeadPersistence::default();
364            let (receipt, mut acknowledged) = ContextHeadReceipt::channel();
365            let (started_tx, started_rx) = tokio::sync::oneshot::channel();
366            let (release_tx, release_rx) = tokio::sync::oneshot::channel();
367            let path = dir.path().to_owned();
368            let result = {
369                let persist = state.persist_with(
370                    &mut session,
371                    &mut messages,
372                    &id,
373                    candidate,
374                    |candidate| async move {
375                        started_tx.send(()).unwrap();
376                        release_rx.await.unwrap();
377                        save_session_durable_in_dir(&path, &candidate, mode).map(|_| ())
378                    },
379                );
380                tokio::pin!(persist);
381                tokio::select! {
382                    result = &mut persist => panic!("write unexpectedly completed: {result:?}"),
383                    _ = started_rx => {}
384                }
385                assert!(matches!(
386                    acknowledged.try_recv(),
387                    Err(tokio::sync::oneshot::error::TryRecvError::Empty)
388                ));
389                release_tx.send(()).unwrap();
390                persist.await
391            };
392            assert!(result.is_ok());
393            receipt.complete(result);
394            assert_eq!(acknowledged.await.unwrap(), Ok(()));
395            assert_eq!(serde_json::to_value(&session).unwrap(), expected);
396            assert_eq!(messages, session.api_messages);
397            assert!(!state.is_blocked(&session));
398            let loaded = Session::load_from_dir(dir.path(), &id).unwrap();
399            assert_eq!(loaded.api_messages, messages);
400            assert_eq!(loaded.system_prompt.as_deref(), Some("host authority"));
401            assert_eq!(loaded.name, session.name);
402            assert_eq!(loaded.total_input_tokens, 23);
403            assert_eq!(loaded.total_output_tokens, 7);
404            assert_eq!(loaded.abort_context, session.abort_context);
405        }
406    }
407
408    #[tokio::test]
409    async fn context_head_identity_mismatch_never_writes_or_adopts() {
410        let (mut session, mut messages, candidate) = fixture();
411        let before = serde_json::to_value(&session).unwrap();
412        let mut state = ContextHeadPersistence::default();
413        let (receipt, acknowledged) = ContextHeadReceipt::channel();
414        let result = state
415            .persist_with(
416                &mut session,
417                &mut messages,
418                "another-session",
419                candidate,
420                |_| async { panic!("identity rejection must not reach persistence") },
421            )
422            .await;
423        assert_eq!(
424            result.as_ref().unwrap_err().kind(),
425            std::io::ErrorKind::InvalidInput
426        );
427        receipt.complete(result);
428        assert!(acknowledged.await.unwrap().is_err());
429        assert_eq!(serde_json::to_value(&session).unwrap(), before);
430        assert_eq!(messages, session.api_messages);
431        assert!(state.is_blocked(&session));
432        let mut other = session.clone();
433        other.id = "new-session".into();
434        assert!(!state.is_blocked(&other));
435    }
436
437    /// `/resume` builds its conversation with `from_resumed` directly: a
438    /// legacy recap is migrated (dropped, marker appended), never carried.
439    #[test]
440    fn from_resumed_migrates_a_legacy_abort_context() {
441        let mut legacy = Session::new("synthetic-model", "low", None);
442        legacy.api_messages = vec![Arc::new(json!({"role":"user","content":"do X"}))];
443        legacy.abort_context = Some("(System note — ABORT CONTEXT: …)".into());
444        let conv = ConversationState::from_resumed(legacy);
445        assert!(conv.session.abort_context.is_none());
446        assert_eq!(conv.api_messages.len(), 2);
447        assert_eq!(
448            conv.api_messages[1]["content"],
449            crate::engine::interrupt::InterruptReason::Unknown.marker()
450        );
451        assert_eq!(conv.session.api_messages, conv.api_messages);
452        // Idempotent for an already-migrated session.
453        let again = ConversationState::from_resumed(conv.session.clone());
454        assert_eq!(again.api_messages, conv.api_messages);
455    }
456
457    #[cfg(unix)]
458    #[tokio::test]
459    async fn context_head_post_publish_error_is_not_rollback_or_success() {
460        let dir = tempfile::tempdir().unwrap();
461        let (session, _, candidate) = fixture();
462        let mut conv = ConversationState::from_resumed(session);
463        let id = conv.session.id.clone();
464        let expected = candidate.api_messages.clone();
465        let path = dir.path().to_owned();
466        let (receipt, acknowledged) = ContextHeadReceipt::channel();
467        let result = conv
468            .context_head
469            .persist_with(
470                &mut conv.session,
471                &mut conv.api_messages,
472                &id,
473                candidate,
474                |candidate| async move {
475                    save_session_durable_in_dir(&path, &candidate, SessionPersistence::Journal)?;
476                    Err(std::io::Error::other("synthetic error after publication"))
477                },
478            )
479            .await;
480        receipt.complete(result);
481        assert!(acknowledged.await.unwrap().is_err());
482        assert!(conv.context_head.is_blocked(&conv.session));
483        assert_eq!(conv.api_messages, expected);
484        assert_eq!(
485            Session::load_from_dir(dir.path(), &id)
486                .unwrap()
487                .api_messages,
488            expected
489        );
490        // Simulate stale failure repair/UI data. save() must return before it
491        // even copies this old state into the conservatively adopted Session.
492        conv.api_messages.clear();
493        conv.api_messages
494            .push(Arc::new(json!({"role":"user","content":"stale"})));
495        conv.save().await;
496        assert_eq!(conv.session.api_messages, expected);
497        let loaded = Session::load_from_dir(dir.path(), &id).unwrap();
498        let resumed = ConversationState::from_resumed(loaded);
499        assert!(!resumed.context_head.is_blocked(&resumed.session));
500    }
501
502    #[tokio::test]
503    async fn context_head_dropped_write_future_latches_without_mutating_old_head() {
504        let (mut session, mut messages, candidate) = fixture();
505        let before = serde_json::to_value(&session).unwrap();
506        let id = session.id.clone();
507        let mut state = ContextHeadPersistence::default();
508        {
509            let persist = state.persist_with(&mut session, &mut messages, &id, candidate, |_| {
510                std::future::pending::<std::io::Result<()>>()
511            });
512            tokio::pin!(persist);
513            assert!(futures::poll!(&mut persist).is_pending());
514        }
515        assert!(state.is_blocked(&session));
516        assert_eq!(serde_json::to_value(&session).unwrap(), before);
517        assert_eq!(messages, session.api_messages);
518    }
519}