Skip to main content

pi_core/
session.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4use crate::events::ThinkingLevel;
5use crate::message::AgentMessage;
6
7/// An entry in the session tree.
8#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
9pub struct SessionEntry {
10    pub id: String,
11    #[serde(skip_serializing_if = "Option::is_none")]
12    pub parent_id: Option<String>,
13    pub kind: EntryKind,
14    pub timestamp: u64,
15}
16
17/// The kind of a session entry.
18#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
19#[serde(tag = "type", rename_all = "snake_case")]
20pub enum EntryKind {
21    Message {
22        #[serde(flatten)]
23        message: AgentMessage,
24    },
25    Compaction {
26        summary: String,
27        first_kept_entry_id: String,
28        tokens_before: u32,
29        #[serde(skip_serializing_if = "Option::is_none")]
30        details: Option<Value>,
31    },
32    BranchSummary {
33        summary: String,
34        #[serde(skip_serializing_if = "Option::is_none")]
35        details: Option<Value>,
36    },
37    ModelChange {
38        provider: String,
39        model_id: String,
40    },
41    ThinkingLevelChange(ThinkingLevel),
42    Custom {
43        custom_type: String,
44        #[serde(skip_serializing_if = "Option::is_none")]
45        data: Option<Value>,
46    },
47}
48
49/// In-memory session state managed by the core.
50#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51pub struct SessionState {
52    pub entries: Vec<SessionEntry>,
53    pub leaf_id: String,
54    #[serde(default)]
55    pub name: String,
56}
57
58impl SessionState {
59    /// Get the full branch from root to leaf.
60    pub fn get_branch(&self) -> Vec<&SessionEntry> {
61        let mut branch = Vec::new();
62        let mut current = self.entries.iter().find(|e| e.id == self.leaf_id);
63
64        while let Some(entry) = current {
65            branch.push(entry);
66            if let Some(pid) = &entry.parent_id {
67                current = self.entries.iter().find(|e| e.id == *pid);
68            } else {
69                break;
70            }
71        }
72
73        branch.reverse();
74        branch
75    }
76
77    /// Build the LLM-visible context from the current branch.
78    pub fn build_context(&self) -> Vec<AgentMessage> {
79        self.get_branch()
80            .iter()
81            .filter_map(|e| match &e.kind {
82                EntryKind::Message { message } => Some(message.clone()),
83                _ => None,
84            })
85            .collect()
86    }
87
88    /// Move to a target node, optionally creating a branch summary.
89    pub fn move_to(&mut self, target_id: &str, summary: Option<BranchSummary>) -> Option<String> {
90        let target = self.entries.iter().find(|e| e.id == target_id)?;
91        self.leaf_id = target_id.to_string();
92
93        if let Some(summary) = summary {
94            let summary_id = format!("summary-{}", self.entries.len());
95            let entry = SessionEntry {
96                id: summary_id.clone(),
97                parent_id: target.parent_id.clone(),
98                kind: EntryKind::BranchSummary {
99                    summary: summary.summary,
100                    details: summary.details,
101                },
102                timestamp: current_timestamp(),
103            };
104            self.entries.push(entry);
105            return Some(summary_id);
106        }
107
108        None
109    }
110}
111
112/// Summary created when navigating between branches.
113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
114pub struct BranchSummary {
115    pub summary: String,
116    #[serde(skip_serializing_if = "Option::is_none")]
117    pub details: Option<Value>,
118}
119
120/// Host-provided session storage trait.
121/// Core holds no I/O; the host implements persistence.
122pub trait SessionStorage: Send + Sync {
123    fn append_entry(&mut self, entry: SessionEntry) -> Result<String, SessionError>;
124    fn get_entry(&self, id: &str) -> Result<Option<SessionEntry>, SessionError>;
125    fn get_branch(&self, leaf_id: &str) -> Result<Vec<SessionEntry>, SessionError>;
126    fn move_to(
127        &mut self,
128        target_id: &str,
129        summary: Option<BranchSummary>,
130    ) -> Result<Option<String>, SessionError>;
131    fn set_leaf_id(&mut self, id: &str) -> Result<(), SessionError>;
132    fn get_leaf_id(&self) -> Result<String, SessionError>;
133    fn append_compaction(
134        &mut self,
135        summary: String,
136        first_kept: String,
137        tokens: u32,
138        details: Value,
139    ) -> Result<String, SessionError>;
140}
141
142/// Session storage errors.
143#[derive(Debug, Clone, PartialEq, thiserror::Error, Serialize, Deserialize)]
144pub enum SessionError {
145    #[error("entry not found: {0}")]
146    NotFound(String),
147    #[error("storage error: {message}")]
148    Storage { message: String },
149    #[error("invalid state: {message}")]
150    InvalidState { message: String },
151}
152
153fn current_timestamp() -> u64 {
154    crate::timestamp::current_timestamp()
155}