Skip to main content

AgentSession

Struct AgentSession 

Source
pub struct AgentSession {
    pub agent: Agent,
    pub cwd: String,
    /* private fields */
}
Expand description

Mode-agnostic agent session.

Not Clone. Modes hold it behind their own reference (Arc at the runtime layer if needed). Interior mutability covers pump/listener/queue state.

Fields§

§agent: Agent

Underlying agent turn loop.

§cwd: String

Working directory.

Implementations§

Source§

impl AgentSession

Source

pub async fn execute_bash<F>( &self, command: &str, on_chunk: Option<F>, options: ExecuteBashOptions, ) -> Result<BashResult, BashExecError>
where F: FnMut(&str) + Send + 'static,

Execute a bash command, stream output, and persist the result.

The command runs in AgentSession::cwd resolved against the settings-configured shell path and command prefix. on_chunk receives merged stdout/stderr chunks as UTF-8 strings as they arrive.

On non-zero exit / abort / timeout the returned Err carries the parsed BashResult so the caller can still inspect the output.

§Errors

Returns BashExecError::Execution when the command fails, or BashExecError::Session when persistence fails.

Source

pub async fn record_bash_result( &self, command: &str, result: BashResult, options: &ExecuteBashOptions, ) -> Result<(), BashExecError>

Record a bash result in session history.

Used by Self::execute_bash and by extensions that handle bash execution themselves. While the agent is streaming, the entry is queued and flushed on agent_end to preserve tool_use / tool_result ordering.

§Errors

Returns BashExecError::Session when persistence fails on the immediate (non-deferred) path.

Source

pub fn has_pending_bash_messages(&self) -> bool

Whether there are pending bash messages waiting to be flushed.

Source

pub async fn flush_pending_bash_messages(&self) -> Result<(), BashExecError>

Append pending bash messages in order, removing each only after its session append succeeds.

Called by the pump after agent_end (TypeScript _flushPendingBashMessages).

§Errors

Returns BashExecError::Session on the first persistence failure. The failed message and every unattempted message remain queued in their original order so a later flush can retry without loss.

Source§

impl AgentSession

Source

pub async fn compact( &self, custom_instructions: Option<&str>, ) -> Result<CompactionResult, CompactionError>

Manually compact the session context.

Disconnects the event pump, aborts any in-flight run, emits compaction_start{manual}, runs the pure compaction engine, persists the summary, rebuilds the agent transcript, and emits compaction_end{manual}. The pump is always reconnected in the finally block.

§Errors

Returns the exact contract strings from the pure engine: CompactionError::AlreadyCompacted / CompactionError::NothingToCompact when preparation yields None, CompactionError::Cancelled when the user aborts via AgentSession::abort_compaction or the extension returns cancel: true, and CompactionError::SummarizationFailed when the model/auth/stream resolution fails.

Source§

impl AgentSession

Source

pub fn has_extension_handlers(&self, event_type: &str) -> bool

Returns true when at least one extension handler is registered for event_type. Cheap delegation to the runner; safe to call from any thread without locking session state.

Source

pub async fn bind_extensions( &self, bindings: ExtensionBindings, ) -> Result<(), ExtensionBindError>

Bind extension UI/mode/error/shutdown listeners, emit the stored session_start event (first bind only), and drive resource discovery.

The whole lifecycle runs under the session bind_lock, so concurrent binds are serialized: the losing bind waits for the winner’s full session_start-then-discovery sequence. The stored event is consumed with Option::take, so repeated binds on the same session instance never re-emit.

§Errors

Returns ExtensionBindError::ResourceDiscover when the runner fails to discover resources.

Source

pub async fn extend_resources_from_extensions( &self, reason: &str, ) -> Result<(), ExtensionBindError>

Discover skills/prompts/themes from extensions and merge into the resource loader.

No-op when no resources_discover handlers are registered.

§Errors

Returns ExtensionBindError::ResourceDiscover when the runner fails.

Source

pub fn get_extension_source_label(extension_path: &str) -> String

Source label for an extension path (extension:<basename-without-ext>).

Angle-bracketed names (in-memory extensions) are emitted verbatim minus the brackets.

Source

pub async fn reload(&self) -> Result<(), ExtensionBindError>

Reload extensions.

Mirrors TS reload:

  1. Capture previous flag values (preserved across the swap).
  2. Emit session_shutdown{reload} on the old runner (self-gated on handler presence; host errors isolated).
  3. When a concrete host is present: prepare and flag-sync its replacement while the old host remains usable, then cut over providers, host runner, and tools before reaping the old transport.
  4. Emit session_start{reload} on the post-swap runner.
  5. Reload base resources and re-discover extension resources.
§Errors

Returns ExtensionBindError on host restart or resource-discovery failure.

Source

pub async fn create_replaced_session_context( self: &Arc<Self>, ) -> ReplacedSessionContext

Build the ReplacedSessionContext for withSession callbacks.

The context retains the replacement session so its send methods cannot accidentally target a later runtime session.

Source

pub fn slash_commands(&self) -> Vec<SlashCommandInfo>

Build the current extension/prompt/skill slash-command catalog.

Source

pub fn report_extension_error( &self, extension_path: &str, event: &str, error: &str, )

Report a structured extension error to the registered listener.

Source

pub fn invoke_extension_shutdown_handler(&self)

Invoke the shutdown handler, if one is bound.

Source

pub fn extension_mode(&self) -> Option<ExtensionMode>

Snapshot of the currently bound extension mode.

Source

pub fn host_extension_runner(&self) -> Option<Arc<HostExtensionRunner>>

Concrete host runner handle (no trait downcast).

Source

pub fn set_host_extension_runner( &self, runner: Option<Arc<HostExtensionRunner>>, )

Replace the concrete host runner handle (reload path).

Source§

impl AgentSession

Source

pub async fn set_model(&self, model: Model) -> Result<(), ModelError>

Set the current model.

Validates auth via the attached runtime (when present), updates agent state, appends a model_change session entry, mutates settings, and re-clamps the thinking level to the new model’s capabilities.

§Errors

Returns ModelError::NoAuth when the runtime reports no configured credential for the model’s provider, or ModelError::Session when persistence fails (live agent state is left unchanged in that case).

Source

pub async fn cycle_model( &self, direction: CycleDirection, ) -> Option<ModelCycleResult>

Cycle to the next or previous model.

Uses scoped models (--models) when present, otherwise cycles across all auth-configured models from the runtime. Returns None when only one candidate is available.

Source

pub async fn set_thinking_level(&self, level: ModelThinkingLevel) -> bool

Set the thinking level.

Clamps to the current model’s supported levels. Only persists / emits when the effective level actually changes. The reference is synchronous because JavaScript is single-threaded; this Rust port is async so it can append to the session manager (held under a tokio::Mutex) and await extension emits without spawning.

Returns whether the live level now equals the requested effective level: true on commit or when no change was needed, false when the durable append failed (nothing was mutated or published).

Source

pub async fn cycle_thinking_level(&self) -> Option<ModelThinkingLevel>

Cycle to the next supported thinking level.

Returns the new level, None when the current model does not support reasoning, or None when the durable level-change append failed.

Source

pub fn available_thinking_levels(&self) -> Vec<ModelThinkingLevel>

Supported thinking levels for the current model.

Source

pub fn supports_thinking(&self) -> bool

Whether the current model supports reasoning.

Source§

impl AgentSession

Source

pub async fn prompt( self: &Arc<Self>, text: &str, options: PromptOptions, ) -> Result<(), PromptError>

Send a prompt to the agent. Handles extension commands, input transforms, skill/template expansion, streaming-queue routing, model + auth validation, pre-prompt compaction, before_agent_start injection, and the run loop.

§Errors
Source

pub fn steer( &self, text: &str, images: Vec<ImageContent>, ) -> Result<(), PromptError>

Queue a steering message; errors when text is a registered extension command (commands cannot be queued).

§Errors

PromptError::Message for extension-command rejection.

Source

pub fn follow_up( &self, text: &str, images: Vec<ImageContent>, ) -> Result<(), PromptError>

Queue a follow-up message; errors when text is a registered extension command.

§Errors

PromptError::Message for extension-command rejection.

Source

pub async fn send_custom_message( self: &Arc<Self>, message: CustomMessageInput, trigger_turn: bool, deliver_as: Option<DeliverAs>, ) -> Result<(), PromptError>

Send a custom message (extension-injected transcript entry). Delivery is selected by deliver_as and current streaming state.

§Errors

Returns PromptError when starting a requested agent turn fails or when the idle-path durable session append fails (no live state or public event is published in that case).

Source

pub async fn send_user_message( self: &Arc<Self>, text: &str, images: Vec<ImageContent>, deliver_as: Option<DeliverAs>, ) -> Result<(), PromptError>

Send a user message. While idle this triggers a new turn; while streaming it queues per deliver_as.

§Errors

Returns PromptError when prompt validation, extension handling, or the underlying agent run fails.

Source§

impl AgentSession

Source

pub fn retry_attempt(&self) -> u32

Current retry attempt (0 when not retrying).

Source§

impl AgentSession

Source

pub async fn get_session_stats(&self) -> SessionStats

Aggregate session statistics across all persisted entries.

Counts / totals include compacted-away history so cost reflects what was actually billed. See Self::get_context_usage for the live context estimate used by the UI.

Source

pub async fn get_context_usage(&self) -> Option<ContextUsage>

Estimate current context usage against the active model’s window.

Returns None when the current model has no contextWindow (or no model is set). After the latest compaction on the active branch, the estimate is None until a post-compaction assistant response provides a fresh usage baseline (TypeScript getContextUsage).

Source§

impl AgentSession

Source

pub async fn emit_agent_settled(self: &Arc<Self>)

Emit agent_settled exactly once for the current session-level run.

Callers (prompt lifecycle) invoke this after retries/follow-ups complete. Extension handler is awaited before public listeners.

Source§

impl AgentSession

Source

pub fn refresh_tool_registry(&self, options: &RefreshToolRegistryOptions)

Refresh the tool registry from the current extension snapshot.

Rebuilds:

  • tool_registry: built-in + extension + SDK custom tools (insertion ordered, first-wins on duplicate names), filtered by allow/exclude.
  • active_tool_names: previous active list plus any newly-registered allow/extension tools, filtered through the new registry.

Finally calls Self::set_active_tools_by_name to apply the result to the agent state.

Source

pub fn get_active_tool_names(&self) -> Vec<String>

Active tool names — the live agent tool list in registration order.

Source

pub fn get_all_tools(&self) -> Vec<ToolInfo>

All configured tools with name / description / parameter schema.

Order matches the registry insertion order: built-ins first, then extension tools in alphabetical name order.

Source

pub fn get_tool(&self, name: &str) -> Option<Arc<dyn AgentTool>>

Look up a tool by name.

Source

pub fn set_active_tools_by_name(&self, tool_names: Vec<String>)

Set the active tool set by name.

Unknown names are ignored. Order is preserved. The agent tool list, the prepare-next-turn hook snapshot, and the cached active names are refreshed in lockstep.

System-prompt rebuild boundary: the TypeScript reference also calls _rebuildSystemPrompt(validToolNames). That rebuild needs context files, skills, and snippets owned by the system_prompt slice.

Source§

impl AgentSession

Source

pub async fn navigate_tree( self: &Arc<Self>, target_id: &str, options: NavigateTreeOptions, auth: SummarizationAuth, summarizer: Option<&SummarizeStreamFn>, ) -> Result<NavigateTreeResult, TreeError>

Navigate the session tree to target_id.

Ordering matches navigateTree in TS:

  1. No-op when already at target.
  2. Validate target entry exists.
  3. Collect entries on the abandoned path.
  4. Query session_before_tree handler presence (cancellable when the typed variant lands).
  5. Run summarizer when requested.
  6. Position the leaf (branch / reset / branch-with-summary).
  7. Attach label to summary or target entry.
  8. Rebuild agent messages from session context.
  9. Signal session_tree handler presence.
§Errors

See TreeError.

Source

pub fn abort_branch_summary(&self)

Abort in-flight branch summarization.

Source

pub async fn get_user_messages_for_forking(&self) -> Vec<ForkableUserMessage>

Collect user messages on the current branch available for forking.

Order matches TS: walk all entries, keep message entries with role user and non-empty text.

Source

pub async fn export_to_html( &self, output_path: Option<&str>, tool_pre_renderer: Option<ToolHtmlPreRenderer>, ) -> Result<String, ExportError>

Export the session to a self-contained HTML file.

Captures the live agent state (system prompt + active tools), resolves the configured theme name, and optionally pre-renders extension tool calls / results into HTML fragments via tool_pre_renderer.

§Errors

See ExportError.

Source

pub async fn export_to_jsonl( &self, output_path: Option<&str>, ) -> Result<String, SessionTransferError>

Export the current branch to a linearized JSONL file.

§Errors

See SessionTransferError.

Source

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

Last assistant message text (skipping aborted empty messages).

Returns None when no usable assistant message exists.

Source

pub async fn set_session_name(&self, name: &str) -> Result<(), SessionError>

Set the session display name (sanitized: newlines collapse to spaces).

Persists a session_info entry and emits session_info_changed.

§Errors

Returns SessionError on persistence failure.

Source§

impl AgentSession

Source

pub fn new(config: AgentSessionConfig) -> Result<Arc<Self>, AgentSessionError>

Construct a session, install hooks, and spawn the event pump.

§Errors

Returns AgentSessionError::MissingAgentOrProvider when neither an agent nor a provider is supplied.

Source

pub fn agent(&self) -> &Agent

Underlying agent.

Source

pub fn extension_runner(&self) -> Arc<dyn ExtensionRunner>

Extension runner snapshot.

Source

pub fn hooks(&self) -> Arc<SessionHooks>

SessionHooks handle (for reload / sibling modules).

Source

pub fn session_manager(&self) -> Arc<AsyncMutex<SessionManager>>

Session manager async mutex (single-writer).

Source

pub fn model(&self) -> Model

Current model from agent state.

Source

pub fn thinking_level(&self) -> ModelThinkingLevel

Current thinking level.

Source

pub fn is_admission_active(&self) -> bool

Whether a session run has been admitted, including preflight, retry, compaction, and post-run continuation phases.

Source

pub fn is_streaming(&self) -> bool

Whether the agent is currently streaming.

Source

pub fn is_idle(&self) -> bool

Whether the agent has no active run.

Source

pub fn is_compacting(&self) -> bool

Whether session-level auto-compaction is in progress.

Source

pub fn is_retrying(&self) -> bool

Whether auto-retry sleep is in progress.

Source

pub fn is_bash_running(&self) -> bool

Whether bash is running.

Source

pub fn is_summarizing(&self) -> bool

Whether branch summarization is in progress.

Source

pub async fn session_file(&self) -> Option<String>

Session file path, if any.

Source

pub async fn session_id(&self) -> String

Session id.

Source

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

Session display name.

Source

pub fn scoped_models(&self) -> Vec<ScopedModel>

Scoped models list.

Source

pub fn pending_message_count(&self) -> usize

Pending steering + follow-up count.

Source

pub fn pending_messages(&self) -> (Vec<String>, Vec<String>)

Pending steering and follow-up message mirrors.

Source

pub fn active_tool_names(&self) -> Vec<String>

Active tool names.

Source

pub fn message_count(&self) -> usize

Transcript message count.

Source

pub fn messages(&self) -> Vec<AgentMessage>

Clone of current transcript.

Source

pub fn steering_mode(&self) -> QueueMode

Steering queue mode.

Source

pub fn follow_up_mode(&self) -> QueueMode

Follow-up queue mode.

Source

pub fn auto_compaction_enabled(&self) -> bool

Auto-compaction enabled flag.

Source

pub fn auto_retry_enabled(&self) -> bool

Auto-retry enabled flag.

Source

pub fn model_runtime_handle(&self) -> Option<Arc<ModelRuntime>>

Typed model-runtime handle.

Source

pub fn subscribe<F>(&self, listener: F) -> impl Fn() + Send + Sync + 'static
where F: Fn(&AgentSessionEvent) + Send + Sync + 'static,

Subscribe to public session events. Returns an unsubscribe token.

Listeners are invoked without holding the inner mutex.

Source

pub fn register_event_backpressure_hook( &self, hook: EventBackpressureHook, ) -> Box<dyn Fn() + Send + Sync>

Register an awaited event-production barrier.

The event pump and compaction paths invoke these hooks after synchronous public listeners. The returned closure removes the hook by stable id.

Source

pub fn clear_queue(&self)

Clear both mirror queues and emit queue_update.

Source

pub fn abort_retry(&self)

Abort in-flight retry sleep.

Source

pub fn abort_compaction(&self)

Abort manual compaction.

Source

pub fn abort_bash(&self)

Abort bash.

Source

pub async fn abort(&self)

Abort every active session operation, then wait for session idle.

Source

pub async fn wait_for_idle(&self)

Wait until the session-level run is idle (no active retries/continuations).

Source

pub async fn dispose(&self)

Dispose this session’s local resources.

Cancels session-owned operations, disconnects the event pump, aborts and drains the agent, invalidates the extension context, then awaits host process reap exactly once when a concrete host is present — even if no session_shutdown handlers were registered. The runtime replacement layer owns the single reason-specific extension shutdown event and must emit it before calling this method when handlers exist.

Source

pub fn lock_settings(&self) -> MutexGuard<'_, SettingsManager>

Lock the settings manager with poison recovery.

Callers must drop the guard before any .await. Read what you need into locals first when the surrounding function is async.

Source

pub fn set_auto_retry_enabled(&self, enabled: bool)

Set auto-retry enabled.

Updates the runtime cache used by prepare_retry / will_retry and the settings document (TypeScript setAutoRetryEnabled writes settings).

Source

pub fn set_auto_compaction_enabled(&self, enabled: bool)

Set auto-compaction enabled.

Updates both the runtime cache and the persisted settings document.

Source

pub fn set_steering_mode(&self, mode: QueueMode)

Set steering mode on the agent.

Source

pub fn set_follow_up_mode(&self, mode: QueueMode)

Set follow-up mode on the agent.

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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