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

Implementations§

Source§

impl AgentSession

Source

pub fn new(mgr: SessionManager) -> Self

Create a new AgentSession from a SessionManager (pi-compatible: keeps the manager).

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 set_registry(&mut self, registry: Arc<ProviderRegistry>)

Set the provider registry for per-message cost computation (pi-style).

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). Pi-compatible: reset overflow recovery when a user message arrives (matches pi’s _overflowRecoveryAttempted reset in message_start for user role).

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_manager(&self) -> &SessionManager

Borrow the underlying SessionManager.

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)

Flush is handled automatically by SessionManager on every append_message. Call this to force an early flush (e.g. before saving state externally).

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 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.

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. Pi-compatible: writes immediately to the session.

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. Pi-compatible: writes immediately to the session.

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 (pi-compatible: persists immediately). 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).

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.

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, custom_instructions: Option<&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, 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.

Source

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.

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