pub struct AgentSession { /* private fields */ }Expand description
Bridges the agent loop events and session persistence.
Handles:
- Event-driven message persistence (persist tool results as they arrive)
- Automatic model/thinking/tool change detection and persistence
Implementations§
Source§impl AgentSession
impl AgentSession
Sourcepub fn new(mgr: SessionManager) -> Self
pub fn new(mgr: SessionManager) -> Self
Create a new AgentSession from a SessionManager (pi-compatible: keeps the manager).
Sourcepub fn open(
path: &Path,
session_dir: Option<&Path>,
cwd_override: Option<&Path>,
) -> Self
pub fn open( path: &Path, session_dir: Option<&Path>, cwd_override: Option<&Path>, ) -> Self
Open a specific session file.
Sourcepub fn continue_recent(cwd: &Path, session_dir: Option<&Path>) -> Self
pub fn continue_recent(cwd: &Path, session_dir: Option<&Path>) -> Self
Continue most recent session or create new.
Sourcepub fn fork_from(
source_path: &Path,
target_cwd: &Path,
session_dir: Option<&Path>,
options: Option<&NewSessionOptions>,
) -> Result<Self>
pub fn fork_from( source_path: &Path, target_cwd: &Path, session_dir: Option<&Path>, options: Option<&NewSessionOptions>, ) -> Result<Self>
Fork a session from another project directory.
Sourcepub fn set_compaction_config(
&mut self,
api_key: String,
model_name: &str,
context_window: u64,
model_config: Option<ModelConfig>,
)
pub fn set_compaction_config( &mut self, api_key: String, model_name: &str, context_window: u64, model_config: Option<ModelConfig>, )
Configure compaction with API key, model, context window, and model config.
Sourcepub fn set_auto_compact(&mut self, enabled: bool)
pub fn set_auto_compact(&mut self, enabled: bool)
Enable or disable auto-compaction.
Sourcepub fn set_registry(&mut self, registry: Arc<ProviderRegistry>)
pub fn set_registry(&mut self, registry: Arc<ProviderRegistry>)
Set the provider registry for per-message cost computation (pi-style).
Sourcepub fn sync_thinking_level(&mut self)
pub fn sync_thinking_level(&mut self)
Sync the thinking level from the session context. Should be called after the session context changes.
Sourcepub fn compaction_settings_mut(&mut self) -> &mut CompactionSettings
pub fn compaction_settings_mut(&mut self) -> &mut CompactionSettings
Get the current compaction settings (mutable, for modification).
Sourcepub fn compaction_settings(&self) -> &CompactionSettings
pub fn compaction_settings(&self) -> &CompactionSettings
Get the current compaction settings.
Sourcepub fn set_extensions(&mut self, extensions: Vec<Box<dyn Extension>>)
pub fn set_extensions(&mut self, extensions: Vec<Box<dyn Extension>>)
Set the list of extensions (for compaction hooks).
Sourcepub fn abort_compaction(&self)
pub fn abort_compaction(&self)
Abort any in-progress compaction (matching pi’s abortCompaction()).
The cancellation will be picked up by extension hooks on their next
cancel.is_cancelled() check.
Sourcepub fn on_compaction_event(&mut self, callback: CompactionEventCallback)
pub fn on_compaction_event(&mut self, callback: CompactionEventCallback)
Register a compaction lifecycle event listener.
Sourcepub fn reset_overflow_recovery(&mut self)
pub fn reset_overflow_recovery(&mut self)
Reset overflow recovery state (called when starting a new turn). Pi-compatible: reset overflow recovery when a user message arrives (matches pi’s _overflowRecoveryAttempted reset in message_start for user role).
Sourcepub fn is_context_overflow_error(msg: &AgentMessage) -> bool
pub fn is_context_overflow_error(msg: &AgentMessage) -> bool
Check if a provider error indicates context overflow. Matches pi’s context overflow detection patterns.
Sourcepub fn session(&self) -> &Session
pub fn session(&self) -> &Session
Borrow the underlying session manager. Borrow the underlying Session.
Sourcepub fn session_manager(&self) -> &SessionManager
pub fn session_manager(&self) -> &SessionManager
Borrow the underlying SessionManager.
Sourcepub fn session_mut(&mut self) -> &mut Session
pub fn session_mut(&mut self) -> &mut Session
Mutably borrow the underlying Session.
Sourcepub fn into_session(self) -> Session
pub fn into_session(self) -> Session
Consume and return the inner Session.
Sourcepub fn ensure_flushed(&mut self)
pub fn ensure_flushed(&mut self)
Flush is handled automatically by SessionManager on every append_message.
Call this to force an early flush (e.g. before saving state externally).
pub fn cwd(&self) -> &Path
pub fn session_dir(&self) -> &Path
pub fn is_persisted(&self) -> bool
pub fn session_id(&self) -> String
pub fn session_file(&self) -> Option<PathBuf>
pub fn session_name(&self) -> Option<String>
Sourcepub fn on_model_change(&mut self, provider: &str, model_id: &str) -> bool
pub fn on_model_change(&mut self, provider: &str, model_id: &str) -> bool
Persist a model change if it differs from the last known model. Pi-compatible: writes immediately to the session.
Sourcepub fn on_thinking_level_change(&mut self, level: &str) -> bool
pub fn on_thinking_level_change(&mut self, level: &str) -> bool
Persist a thinking level change if it differs from the last known level. Pi-compatible: writes immediately to the session.
Sourcepub fn on_active_tools_change(&mut self, tools: &[String]) -> bool
pub fn on_active_tools_change(&mut self, tools: &[String]) -> bool
Persist an active tools change if it differs from the last known set. Pi-compatible: writes immediately to the session.
Sourcepub fn new_session(&mut self)
pub fn new_session(&mut self)
Reset the session (creates a new empty session) and clear all tracked state so the new session starts fresh.
Sourcepub fn send_user_message(&mut self, content: &str) -> String
pub fn send_user_message(&mut self, content: &str) -> String
Append a user message to the session (pi-compatible: persists immediately). Returns the entry id.
Sourcepub fn send_user_message_obj(&mut self, msg: &AgentMessage) -> String
pub fn send_user_message_obj(&mut self, msg: &AgentMessage) -> String
Append a user message (pre-constructed) to the session. Returns the entry id.
Sourcepub fn on_agent_event(&mut self, event: &AgentEvent)
pub fn on_agent_event(&mut self, event: &AgentEvent)
Process an agent event for automatic persistence (pi-compatible).
Pi persists every message (user, assistant, tool result, custom) immediately
on message_end, not deferred to agent_end. Extension messages use
custom_message entries (excluded from LLM context); all others use regular
message entries.
Cost is computed per-message at creation time using the model’s cost config
from the provider registry (pi-style: calculateCost in models.ts).
Call this from your agent event handler.
Sourcepub async fn check_auto_compact(&mut self) -> Result<bool, String>
pub async fn check_auto_compact(&mut self) -> Result<bool, String>
Check if compaction should run and execute it if needed.
Should be called after the agent finishes a turn (after on_agent_end).
Returns true if compaction was performed.
Sourcepub async fn check_overflow_compact(
&mut self,
will_retry: bool,
) -> Result<bool, String>
pub async fn check_overflow_compact( &mut self, will_retry: bool, ) -> Result<bool, String>
Run compaction after a context overflow error.
If will_retry is true, the agent turn will be retried after compaction.
Returns Ok(true) if compaction was performed, Ok(false) if recovery already attempted.
Sourcepub async fn run_manual_compact(
&mut self,
custom_instructions: Option<&str>,
) -> Result<String, String>
pub async fn run_manual_compact( &mut self, custom_instructions: Option<&str>, ) -> Result<String, String>
Run compaction manually (ignores auto-compact setting). Returns the compaction summary text, or an error message.
Summarise the abandoned branch when navigating to a different node.
Collects entries between old_leaf_id and the common ancestor with
target_id, summarises them via the provider, and appends a
BranchSummaryEntry to the session.
Returns the summary text, or an error message.
Sourcepub async fn set_branch(
&mut self,
branch_from_id: &str,
custom_instructions: Option<&str>,
) -> Result<Option<String>, String>
pub async fn set_branch( &mut self, branch_from_id: &str, custom_instructions: Option<&str>, ) -> Result<Option<String>, String>
Move the leaf pointer to an earlier entry (starts a new branch).
Optionally summarizes the abandoned path if a provider is configured.
custom_instructions are passed to the summarization prompt (pi-compatible).
Returns the branch summary text if summarization was performed.
Sourcepub fn persist_extension_message(&mut self, msg: &AgentMessage)
pub fn persist_extension_message(&mut self, msg: &AgentMessage)
Persist a tool result message (public so the agent loop can persist crash-safely).
Deduplicates by tool_call_id.
Persist an Extension message as a custom_message session entry (pi-compatible).
Extension messages are NOT persisted as regular messages — they use the
custom_message entry type which supports custom_type, display, and details.