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
Usage:
let mut agent_session = AgentSession::new(session);
// In your agent event handler:
agent_session.handle_event(&event);
// For model/thinking/tool changes at runtime:
agent_session.on_model_change("opencode_go", "deepseek-v4-pro");
agent_session.on_thinking_level_change("high");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 (extracts inner Session + config).
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 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).
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_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)
Ensure the session file has been written (lazy write on first assistant message).
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 flush_pending_writes(&mut self)
pub fn flush_pending_writes(&mut self)
Flush all queued writes to the underlying session storage.
Called at the end of on_agent_event and on_agent_end.
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. Returns true if a change entry was enqueued.
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. Returns true if a change entry was enqueued.
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. Returns true if a change entry was enqueued.
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 and register it as persisted. 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).
ToolResultevents are persisted immediately (crash-safe).MessageEndpersists every message in real-time (pi-compatible, crash-safe).AgentEndpersists any remaining assistant messages not yet captured.
Call this from your agent event handler alongside any UI updates.
This is the mode-agnostic persistence handler, matching pi’s _handleAgentEvent.
Sourcepub fn on_agent_end(&mut self, messages: &[AgentMessage])
pub fn on_agent_end(&mut self, messages: &[AgentMessage])
Persist all new messages from an agent run that haven’t been persisted yet (e.g. assistant messages not captured by event-driven persistence, or error messages).
Call this when the agent loop finishes, or let handle_event do it
automatically on AgentEnd.
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,
) -> Result<Option<String>, String>
pub async fn set_branch( &mut self, branch_from_id: &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. Returns the branch summary text if summarization was performed.
Sourcepub fn persist_tool_result(
&mut self,
tool_call_id: &str,
tool_name: &str,
content: String,
is_error: bool,
)
pub fn persist_tool_result( &mut self, tool_call_id: &str, tool_name: &str, content: String, is_error: bool, )
Persist a tool result message (public so the agent loop can persist crash-safely). Deduplicates by tool_call_id.
Sourcepub fn persist_extension_message(&mut self, msg: &AgentMessage)
pub fn persist_extension_message(&mut self, msg: &AgentMessage)
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.
Sourcepub fn persist_message_end(&mut self, msg: &AgentMessage)
pub fn persist_message_end(&mut self, msg: &AgentMessage)
Persist a single message on message_end (pi-compatible pattern).
Pi persists every message (user, assistant, toolResult) immediately on message_end,
not deferred to agent_end. This method handles dedup for tool results (already
persisted via persist_tool_result) and dedup by text for other message types.