Skip to main content

AgentSession

Struct AgentSession 

Source
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

Source

pub fn new(mgr: SessionManager) -> Self

Create a new AgentSession from a SessionManager (extracts inner Session + config).

Source

pub fn create(cwd: &Path, session_dir: Option<&Path>) -> Self

Create a new persisted session.

Source

pub fn open( path: &Path, session_dir: Option<&Path>, cwd_override: Option<&Path>, ) -> Self

Open a specific session file.

Source

pub fn in_memory(cwd: &Path) -> Self

Create an in-memory session (no persistence).

Source

pub fn continue_recent(cwd: &Path, session_dir: Option<&Path>) -> Self

Continue most recent session or create new.

Source

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.

Source

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.

Source

pub fn set_auto_compact(&mut self, enabled: bool)

Enable or disable auto-compaction.

Source

pub fn sync_thinking_level(&mut self)

Sync the thinking level from the session context. Should be called after the session context changes.

Source

pub fn compaction_settings_mut(&mut self) -> &mut CompactionSettings

Get the current compaction settings (mutable, for modification).

Source

pub fn compaction_settings(&self) -> &CompactionSettings

Get the current compaction settings.

Source

pub fn set_extensions(&mut self, extensions: Vec<Box<dyn Extension>>)

Set the list of extensions (for compaction hooks).

Source

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.

Source

pub fn on_compaction_event(&mut self, callback: CompactionEventCallback)

Register a compaction lifecycle event listener.

Source

pub fn reset_overflow_recovery(&mut self)

Reset overflow recovery state (called when starting a new turn).

Source

pub fn is_context_overflow_error(msg: &AgentMessage) -> bool

Check if a provider error indicates context overflow. Matches pi’s context overflow detection patterns.

Source

pub fn session(&self) -> &Session

Borrow the underlying session manager. Borrow the underlying Session.

Source

pub fn session_mut(&mut self) -> &mut Session

Mutably borrow the underlying Session.

Source

pub fn into_session(self) -> Session

Consume and return the inner Session.

Source

pub fn ensure_flushed(&mut self)

Ensure the session file has been written (lazy write on first assistant message).

Source

pub fn cwd(&self) -> &Path

Source

pub fn session_dir(&self) -> &Path

Source

pub fn is_persisted(&self) -> bool

Source

pub fn session_id(&self) -> String

Source

pub fn session_file(&self) -> Option<PathBuf>

Source

pub fn session_name(&self) -> Option<String>

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn send_user_message_obj(&mut self, msg: &AgentMessage) -> String

Append a user message (pre-constructed) to the session. Returns the entry id.

Source

pub fn on_agent_event(&mut self, event: &AgentEvent)

Process an agent event for automatic persistence (pi-compatible).

  • ToolResult events are persisted immediately (crash-safe).
  • MessageEnd persists every message in real-time (pi-compatible, crash-safe).
  • AgentEnd persists 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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub async fn summarize_branch_navigation( &mut self, old_leaf_id: Option<&str>, target_id: &str, ) -> Result<String, String>

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.

Source

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.

Source

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.

Source

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.

Source

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.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more