Skip to main content

AgentSession

Struct AgentSession 

Source
pub struct AgentSession { /* private fields */ }
Expand description

A running conversation. Cheap to clone, and clones share state.

Implementations§

Source§

impl AgentSession

Source

pub fn boundary_context( &self, boundary: Boundary, drafts: &[Value], ) -> Result<Value, String>

pi’s BoundaryContextPreview at boundary with drafts staged: the model context entry by entry, as messages and as the provider sees them, the pending messages, and whether the run can continue.

Source§

impl AgentSession

Source

pub fn cache_warming_mode(&self) -> CacheWarming

The cache warming mode, from the global settings only.

Source

pub fn set_cache_warming_mode(&self, mode: CacheWarming) -> Result<(), String>

pi’s setCacheWarmingMode: saves the mode in the global settings and applies it to the current run at once.

Source

pub fn cache_warming_status(&self) -> CacheWarmingStatus

Cache warming’s state and the policy inputs that produced it.

Source§

impl AgentSession

Source

pub fn extension_binding(&self) -> (Arc<dyn ExtensionUi>, Mode)

The UI and mode extensions are bound to.

Source

pub fn has_handlers(&self, kind: &str) -> bool

Whether any extension handles pi events of type kind and may hear them.

Source

pub async fn emit_extension_event( &self, event: &Value, cancel: CancellationToken, ) -> Option<Value>

Delivers pi event event to every extension that handles it, in order, as pi’s runner emit does. Only a session_before_* event has a result: the last one a handler gave, or the first that cancels, which stops delivery.

Source

pub async fn cancels(&self, change: &SessionChange) -> bool

pi’s session_before_switch or session_before_fork: whether an extension cancels change.

Source

pub fn ui_prompt_opened(&self, kind: &str, title: Option<&str>)

A blocking extension dialog of kind (select, confirm, input, editor or custom) with title opens. Extensions hear of the outermost as pi’s ui_prompt_start.

Source

pub fn ui_prompt_closed(&self)

A blocking extension dialog closed. When it was the outermost, extensions hear of it as pi’s ui_prompt_end.

Source

pub fn set_mcp_servers( &self, owner: u64, servers: Vec<RegisteredMcpServer>, ) -> Result<(), String>

Sets the MCP servers that extension runtime owner registered, and announces mcp_servers_change when they changed after the extensions started. Before then, as runtimes bind, the reports hold the servers registered while extensions loaded, which the MCP extension reads when the session starts. Nothing changes when a server’s name, or its tools’ namespace, belongs to another runtime, and the error is pi’s for that registration.

Source

pub fn check_mcp_server(&self, owner: u64, name: &str) -> Result<(), String>

pi’s checks of server name, which an extension of runtime owner registers, against the servers of the other runtimes, without registering it.

Source

pub fn mcp_servers(&self) -> Vec<RegisteredMcpServer>

pi’s getMcpServers: the servers extensions registered, in registration order.

Source

pub fn add_extension_load_error(&self, path: String, error: String)

Records the extension at path, whose factory failed with error as the extensions loaded for this session. The factories of every session after the first run again then, as pi loads the extensions for each runtime.

Source

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

The extensions that failed to load for this session, by path, with pi’s message, which pi’s interactive mode lists under [Extension issues].

Source

pub fn add_extension_warning(&self, path: String, warning: String)

Records the extension at path, which was not loaded for this session, with pi’s warning.

Source

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

The extensions that were not loaded for this session, by path, with pi’s warning, which pi’s interactive mode lists under [Extension issues].

Source

pub async fn flush_announcements(&self)

Waits until the events announced so far have reached extensions.

Source

pub async fn session_action( &self, action: SessionAction, ) -> Result<bool, String>

Carries out a session change an extension command asks for: whether an extension cancelled it. Without a mode, nothing changes, as pi’s default actions do.

Source

pub async fn bind_extensions( &self, ui: Arc<dyn ExtensionUi>, mode: Mode, actions: Option<SessionActions>, replaced: Option<(Replacement, Option<String>)>, )

Gives extensions their UI, mode and the actions that carry out the session changes their commands ask for, and starts them: pi’s bindExtensions, which emits session_start with the reason this session replaced another and that session’s file, or startup when replaced is None.

Source

pub async fn shutdown(&self)

Stops extensions before the session ends: pi’s session_shutdown with the reason quit.

Source

pub async fn shutdown_for(&self, reason: Replacement, target: Option<String>)

Stops extensions before a session replaces this one for reason. target is the replacement’s session file, which pi does not report on reload.

Source

pub fn extensions(&self) -> &[Arc<dyn Extension>]

The session’s extensions.

Source

pub fn tool_renderer( &self, name: &str, ) -> Option<(Arc<dyn Extension>, ToolRenderers)>

The extension that draws tool name, and how.

Source

pub fn entry_renderer(&self, custom_type: &str) -> Option<Arc<dyn Extension>>

The extension that draws custom entries of type custom_type.

Source

pub fn markdown_transformers(&self) -> Vec<Arc<dyn Extension>>

The extensions that transform Markdown, in load order.

Source

pub fn code_renderers(&self) -> Vec<Arc<dyn Extension>>

The extensions that render code blocks, in load order.

Source

pub fn message_renderer(&self, custom_type: &str) -> Option<Arc<dyn Extension>>

The extension that draws custom messages of type custom_type.

Source

pub fn extension_shortcuts( &self, builtin: &[(String, Vec<String>)], ) -> (Vec<ShortcutBinding>, Vec<(String, String)>)

The shortcuts the session’s extensions bind, given the keys of each built-in action, and pi’s warnings about conflicts.

Source

pub async fn run_shortcut( &self, binding: &ShortcutBinding, ) -> Result<(), String>

Runs an extension shortcut’s handler and returns the handler’s error.

Source

pub fn extension_commands(&self) -> Vec<ResolvedCommand>

pi’s resolveRegisteredCommands: the extensions’ commands in load order, each with the name it is invoked by. A name registered more than once is invoked as name:1, name:2 and so on.

Source

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

pi’s slash commands, as RPC’s get_commands and pi.getCommands() list them: the extensions’ commands, then the prompt templates and the skills, each with where it comes from.

Source

pub fn is_extension_command(&self, text: &str) -> bool

Whether text invokes an extension command.

Source§

impl AgentSession

Source

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

pi’s setModel: switches to model and records it, then applies the thinking level for it. Fails when its provider has no credential.

Source

pub fn keep_selection(&self, from: &AgentSession)

Takes over the model, thinking level and scope of the session this one replaces on /reload, which pi keeps without recording anything.

Source

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

The models cycling moves through, from --models or the enabledModels setting, or empty when every available model is in scope.

Source

pub fn models_in_scope(&self) -> Vec<Model>

The scoped models, or every available model when the scope is empty.

Source

pub fn set_scoped_models(&self, models: Vec<ScopedModel>)

Replaces the scope. An empty list puts every available model in it.

Source

pub fn save_default_model(&self, model: &Model)

Saves model as the default in the global settings. A non-empty scope gains it, and so does a non-empty enabledModels setting, as in pi.

Source

pub fn cycle_model(&self, forward: bool) -> Option<(Model, bool)>

pi’s cycleModel, forward or backward, over the scoped models that have credentials, or over every available model when the scope is empty. Returns the new model and whether the scope applied, or None when there is at most one model to cycle through.

Source

pub fn set_thinking_level(&self, level: ThinkingLevel)

Sets the thinking level, clamped to what the model supports, and records and announces a change.

Source

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

The thinking levels the current model supports, or all of them without a model.

Source

pub fn cycle_thinking_level(&self) -> Option<ThinkingLevel>

pi’s cycleThinkingLevel: the next supported level, wrapping. None when the model does not reason.

Source

pub fn available_models(&self) -> Vec<Model>

Models with credentials, in catalog order.

Source

pub fn registry(&self) -> Arc<ModelRegistry> ⓘ

The model registry. Credentials it reads stay current with auth.json.

Source

pub fn apis(&self) -> Apis

The wire APIs requests stream through.

Source

pub fn update_providers<T>( &self, change: impl FnOnce(&mut ModelRegistry, &mut Apis) -> T, ) -> T

Applies change, a provider that an extension registers or unregisters after extensions load, to the model registry and the wire APIs. The current model takes the registry’s new definition of it, as in pi.

Source

pub async fn refresh_model_catalogs( &self, options: RefreshOptions, ) -> CatalogRefresh

Refreshes the model catalogs that change between releases: restores the stored ones and, when options allow the network, fetches those of configured providers, as pi’s ModelRuntime.refresh. The session then lists the new models. Concurrent refreshes run one after another.

Source

pub fn with_registry<T>(&self, f: impl FnOnce(&ModelRegistry) -> T) -> T

Runs f with the model registry.

Source§

impl AgentSession

Source

pub fn abort_retry(&self)

Cancels the wait before an automatic retry. The failed response stands.

Source

pub async fn bug_report_summary( &self, hint: Option<&str>, cancel: CancellationToken, ) -> Result<String, String>

pi’s summarizeForBugReport: a bug report the current model writes from the end of the context, with the user’s hint, or why it could not. cancel stops the request.

Source

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

Compacts the session now, optionally focused by custom_instructions. Aborts a running response first.

Source§

impl AgentSession

Source

pub fn context_usage(&self) -> Option<ContextUsage>

Context use of the current branch: tokens is None after a compaction until the model responds again. None without a model or window.

Source

pub fn usage_totals(&self) -> UsageTotals

Token and cost totals over every entry of the session file, and the cache hit rate of the latest assistant message.

Source

pub fn session_stats(&self) -> SessionStats

pi’s getSessionStats counts and getUsageCostBreakdown, over every entry of the session file.

Source§

impl AgentSession

Source

pub fn new(config: SessionConfig) -> AgentSession

Starts a session. A new session records its model and thinking level.

Source

pub fn docs(&self) -> &Locations

Where the model and the sign-in help find the docs.

Source

pub fn subscribe(&self, listener: Listener)

Adds a listener for every event.

Source

pub fn with_session<T>(&self, f: impl FnOnce(&mut SessionManager) -> T) -> T

Runs f with the session file. The session’s first failed write is reported to the user, after f, by whichever call finds it.

Source

pub fn take_session(&self) -> SessionManager

Moves the session file out, leaving an empty in-memory one, so a new AgentSession can take it over.

Source

pub fn model(&self) -> Option<Model>

The current model.

Source

pub fn thinking_level(&self) -> ThinkingLevel

The current thinking level.

Source

pub fn is_streaming(&self) -> bool

Whether a run is in progress.

Source

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

The model context of the current branch.

Source

pub fn last_assistant(&self) -> Option<AssistantMessage>

The text of the last assistant message.

Source

pub fn set_name(&self, name: &str)

Names the session. Extensions hear of it as pi’s session_info_changed.

Source

pub fn settings_manager(&self) -> SettingsManager

A copy of the session’s settings manager, for work that reads both scopes, such as package checks.

Source

pub fn settings(&self) -> Settings

A snapshot of the merged settings.

Source

pub fn http_idle_timeout_ms(&self) -> u64

pi’s getHttpIdleTimeoutMs for these settings. Startup rejects an invalid value, so it reads as the default here.

Source

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

Settings files that failed to load, as pi’s warnings word them.

Source

pub fn project_trusted(&self) -> bool

Whether this session loads the project’s settings and resources.

Source

pub fn project_dir(&self) -> PathBuf

The directory this session’s project files come from.

Source

pub fn set_global_setting( &self, key: &str, value: Option<Value>, ) -> Result<(), String>

Sets a global setting and writes settings.json.

Source

pub fn resources(&self) -> Resources

The prompt resources: those the session was built with, and those its extensions discovered.

Source

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

Empties the steering and follow-up queues and returns their texts.

Source

pub fn pending_message_count(&self) -> usize

Queued steering and follow-up messages.

Source

pub fn steering_mode(&self) -> Option<Value>

How queued steering messages are delivered: all, or one at a time for any other value. It is the mode last set, as pi’s agent keeps it, and None once set to nothing.

Source

pub fn follow_up_mode(&self) -> Option<Value>

How queued follow-up messages are delivered, as AgentSession::steering_mode.

Source

pub fn set_steering_mode(&self, mode: Option<Value>) -> Result<(), String>

Sets the steering mode, any value as pi takes it, and saves it in the global settings. None removes the setting.

Source

pub fn set_follow_up_mode(&self, mode: Option<Value>) -> Result<(), String>

Sets the follow-up mode as AgentSession::set_steering_mode does.

Source

pub fn auto_compaction_enabled(&self) -> Value

pi’s autoCompactionEnabled: the setting as saved, true when unset or null. Compaction runs when it is truthy.

Source

pub fn set_auto_compaction(&self, enabled: Option<Value>) -> Result<(), String>

Saves whether automatic compaction runs in the global settings, any value as pi takes it. None removes the setting.

Source

pub fn set_auto_retry(&self, enabled: Option<Value>) -> Result<(), String>

Saves whether automatic retries run, as AgentSession::set_auto_compaction does.

Source

pub fn set_nested_global_setting( &self, field: &str, key: &str, value: Value, ) -> Result<(), String>

Sets key inside the global object setting field and writes settings.json.

Source

pub fn is_compacting(&self) -> bool

Whether a compaction or branch summary is running.

Source

pub async fn wait_for_idle(&self)

Waits until no run is in progress.

Source

pub async fn execute_bash( &self, command: &str, exclude_from_context: Option<bool>, id: Option<String>, operations: Option<BashOperations>, on_chunk: impl FnMut(&str), ) -> Result<BashResult, String>

Runs a user ! command in the session’s directory, with the session’s shell or through an extension’s operations, streaming output to on_chunk and as bash_execution_update events tagged id, and records it. exclude_from_context (!!) keeps the output from the model and is recorded as given. While a run streams, the record waits for its end.

Source

pub async fn user_bash( &self, command: &str, exclude_from_context: bool, ) -> Result<UserBash, String>

pi’s user_bash event for a ! command: whether an extension ran it, runs it through its operations, or leaves it to the session’s shell. Fails with the error of a handler, which extension error reporting has already shown.

Source

pub fn record_bash( &self, command: &str, result: &BashResult, exclude_from_context: Option<bool>, )

pi’s recordBashResult: records a ! command’s result, after the current run when one streams.

Source

pub fn abort_bash(&self)

Cancels running ! commands.

Source

pub fn is_bash_running(&self) -> bool

Whether a ! command is running.

Source

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

User messages of every branch with text, in file order, as fork points.

Source

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

pi’s getLastAssistantText: the text of the last assistant message, skipping aborted ones without content, or None when that message has no text.

Source

pub fn run_cancel(&self) -> Option<CancellationToken>

What AgentSession::abort cancels: the current run’s token, or None while no run is active, as pi’s agent.signal.

Source

pub fn abort(&self)

Cancels the current run.

Source

pub fn deliver_custom_message( &self, message: CustomMessage, trigger_turn: Option<bool>, deliver_as: Option<&str>, ) -> Option<impl Future<Output = ()> + Send + 'static>

The part of pi’s sendCustomMessage that happens at once. The message is queued, held or recorded and reported before this returns:

  • deliver_as nextTurn holds the message for the next prompt.
  • While a run streams, it steers (or follows up) unless trigger_turn is false, in which case it is appended when the turn ends.
  • Otherwise trigger_turn returns the run it starts, which the caller defers as pi does (see AgentSession::settled_turn), and without one it is appended at once.
Source

pub fn settled_turn( &self, ) -> Option<impl Future<Output = Option<Sender<()>>> + Send + 'static>

pi defers a prompt started while agent_settled handlers run: the run that settled starts it once they return, and ends after it. None outside those handlers. Otherwise the prompt’s place is taken now, and the future resolves when it may start, to a guard it holds until it ends.

Source

pub async fn queue_input( &self, text: &str, images: Vec<ImageContent>, behavior: StreamingBehavior, source: InputSource, ) -> Result<PromptDisposition, String>

pi’s steer and followUp: an extension command cannot be queued. Otherwise the input handlers see the message first, then it is queued with templates and skills expanded.

Source

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

Queues a message to steer the current run after its current tool calls.

Source

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

Queues a message for when the current run would otherwise end.

Source

pub fn base_prompt_options(&self) -> SystemPromptOptions

pi’s base prompt options, which ctx.getSystemPromptOptions() gives commands as a live object: the session’s resources, the active tools, and the snippet and guidelines of every registered tool, without what a run adds, as a command last edited them.

Source

pub fn set_base_prompt_options(&self, options: SystemPromptOptions)

Keeps a command’s edits to the base prompt options until the base changes, as pi’s live options keep them until it rebuilds them.

Source

pub fn system_prompt(&self) -> Result<String, String>

pi’s systemPrompt: the prompt of the current run’s options, as the run sends it, or of the base options while no run is active.

Source

pub fn render_prompt( &self, options: &SystemPromptOptions, ) -> Result<String, String>

pi’s buildSystemPrompt: the system prompt options give, or their forced prompt if they have one.

Source

pub fn queue_now(&self, text: &str, options: &PromptOptions) -> bool

AgentSession::prompt_with while a run streams, when the message has a streaming behavior and neither an input handler nor an extension command takes it. It is queued before this returns, as pi queues it before any later event. Returns whether it was.

Source

pub async fn prompt( &self, text: &str, images: Vec<ImageContent>, ) -> Result<(), String>

Sends a user prompt and runs until the agent settles. Templates and /skill: commands expand first.

Source

pub async fn prompt_with( &self, text: &str, options: PromptOptions, preflight: impl FnOnce(PromptDisposition), ) -> Result<(), String>

pi’s prompt: while a run streams, the options’ streaming behavior queues the message, and without one it is an error. Otherwise the message starts a run that lasts until the agent settles. preflight learns which, before any event of the run. A prompt started while agent_settled handlers run waits until they return.

Source

pub async fn navigate_tree( &self, target_id: &str, options: TreeNavigation, ) -> Result<TreeOutcome, String>

Moves to another point of the session tree, as /tree does. A user or custom message target puts the leaf on its parent and returns its text for the editor. With summarize, the abandoned branch is summarized at the new position. label labels the summary, or the target without one.

Source

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

The session header line as JSON mode prints it.

Source

pub fn set_active_tools(&self, names: Vec<String>)

Sets the active tools, ignoring unknown and hidden names.

Source

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

The active tool names.

Source

pub fn export_context(&self) -> (Option<String>, Vec<Value>)

What pi’s HTML export takes from a live session: the system prompt as the model reads it, and the active tools’ names, descriptions and parameter schemas.

Source

pub fn tools(&self) -> &Tools

The session’s tools.

Source

pub fn append_custom_entry( &self, custom_type: &str, data: Option<Value>, ) -> Result<(), String>

pi’s appendEntry for extensions: appends custom entry custom_type and reports it as entry_appended.

Source

pub fn callable_tools(&self) -> Vec<RegisteredTool>

The tools other tools may call, in registration order, as pi’s _getCallableTools: every codemode and deferred tool and the active direct ones.

Source

pub async fn execute_tool( &self, caller: &str, name: &str, args: Value, cancel: CancellationToken, updates: Option<UpdateSink>, allowed: impl Fn(&RegisteredTool) -> bool + Send, ) -> ToolCallOutcome

Runs tool name on behalf of the tool call caller, as pi’s ctx.executeTool(): the call gets the id <caller>/<n>, runs through the tool pipeline and hooks against AgentSession::callable_tools, emits tool_execution_* events with parentToolCallId, and is recorded on the caller’s tool result message. Failures come back as error results. updates also receives the tool’s partial results. Only the tools allowed accepts are found, as the call resolves its tool.

Source

pub fn downgrade(&self) -> WeakSession

A handle that does not keep the session alive.

Source

pub fn cwd(&self) -> &Path

The working directory.

Trait Implementations§

Source§

impl Clone for AgentSession

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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