Skip to main content

AgentSession

Struct AgentSession 

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

One live session. Cheap to clone.

Implementations§

Source§

impl AgentSession

Source

pub async fn spawn_agent( &self, extension: &str, spec: AgentSpec, ) -> Result<Arc<ChildAgent>, HostError>

agents.spawn (runtime §12): creates a nested session owned by extension.

§Errors

Depth or concurrency limit, unknown model, session file failures.

Source

pub fn agents_list(&self) -> JsonValue

Nested agents of this session (agents.list): [{id, label, state, sessionFile}].

Source

pub fn child_agents(&self) -> Vec<Arc<ChildAgent>>

Open nested agents of this session.

Source

pub fn is_child(&self) -> bool

Whether this is a nested (child) session.

Source§

impl AgentSession

Source

pub fn agent_tree(&self) -> Vec<AgentInfo>

Every open nested agent of this session’s subtree, parents before children.

Source

pub fn find_agent(&self, id: &str) -> Option<Arc<ChildAgent>>

Finds a nested agent of this session’s subtree by id.

Source

pub fn follow_agents(&self, on: bool)

Turns live child event forwarding (OinoEvent::AgentEvent) on or off for the whole tree.

Source

pub fn follows_agents(&self) -> bool

Whether child events are forwarded.

Source§

impl AgentSession

Source

pub async fn execute_bash( &self, command: String, exclude_from_context: bool, id: Option<String>, ) -> Result<BashResult, SessionOpError>

user_bash handlers first ({result} short-circuits), then the configured shell with shellCommandPrefix; output streams as bash_execution_update and the result is recorded as a bashExecution message (!! excludes it from context).

§Errors

A failing user_bash handler or a command that could not run.

Source

pub fn record_bash_result( &self, command: &str, result: &BashResult, exclude_from_context: bool, )

Records a bashExecution message (deferred while streaming).

Source§

impl AgentSession

Source

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

Wait reasons reported at the last settle (empty when not waiting).

Source§

impl AgentSession

Source

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

Manual compaction; aborts the current run first, never retries.

§Errors

Already compacted, Nothing to compact (session too small), Compaction cancelled, or the summariser failure.

Source

pub fn set_auto_compaction_enabled(&self, enabled: bool)

Enables or disables automatic compaction (settings).

Source§

impl AgentSession

Source

pub fn runtime_handle(&self) -> Option<Handle>

The runtime the session was created on.

Source

pub async fn subscribe_topics( &self, subscribe: &[String], unsubscribe: &[String], ) -> Vec<TopicValue>

Adds and removes _oino/topics patterns (exact, prefix*, *) and returns the current sticky values matching the resulting subscription. Subscribing to topics::GIT_TOPIC refreshes it first.

Source

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

The current _oino/topics patterns.

Source

pub fn bus_get(&self, topic: &str) -> Option<TopicValue>

Last sticky value of topic (_oino/bus_get).

Source

pub async fn refresh_git_topic(&self)

Recomputes topics::GIT_TOPIC for the session cwd.

Source

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

Records a frontend attached through _oino/hello (client.name).

Source

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

Attached frontends for host-info (tui, desktop, mobile, rpc, acp, plus _oino/hello client names).

Source

pub fn extension_infos(&self) -> Vec<ExtensionInfo>

Loaded extensions plus the ids listed in disabledExtensions (_oino/extensions).

Source

pub fn set_extension_enabled( &self, id: &str, enabled: bool, ) -> Result<(), SessionOpError>

Adds id to or removes it from disabledExtensions (global settings). Takes effect for sessions created afterwards (_oino/set_extension_enabled).

§Errors

The settings file cannot be written.

Source

pub fn bind_bash_detach(&self, registry: BashDetachRegistry)

Binds the detach registry of the session’s built-in shell tools (once).

Source

pub async fn running_bash(&self) -> Vec<RunningBash>

Foreground bash calls still running (control.running-bash), oldest first.

Source

pub async fn detach_bash( &self, tool_call_id: &str, task_id: &str, reason: &str, ) -> Result<DetachedBash, HostError>

Detaches the running bash call tool_call_id into background task task_id: the call returns at once with the output so far plus a detach marker, the process keeps running and is handed over.

§Errors

HostError::Failed when no such call runs (or it finished meanwhile).

Source

pub fn checkpoints(&self) -> Vec<Checkpoint>

File checkpoints of this session, oldest first (_oino/checkpoints).

Source

pub fn rewind_files( &self, entry_id: &str, ) -> Result<RewindResult, SessionOpError>

Restores the files changed at or after the user message entry_id (file part of _oino/rewind) and drops those checkpoints.

§Errors

SessionOpError::Failed while streaming or without a checkpoint for the entry.

Source

pub fn has_checkpoint(&self, entry_id: &str) -> bool

Whether a checkpoint exists for the user message entry_id.

Source§

impl AgentSession

Source

pub fn editor_text(&self) -> String

The composer text the frontend reported last (ui.editor-text).

Source

pub async fn completions( &self, text: &str, cursor: usize, ) -> Vec<CompletionGroup>

Merged completions for text with the cursor at character cursor (ui-protocol §7.3): slash commands, command arguments (complete-command), @ paths and every extension complete-input contributor, each within 100 ms.

Source

pub fn ui_action( &self, panel_id: &str, action_id: &str, value: Option<JsonValue>, ) -> Result<(), FrontendError>

Delivers a panel action (oino_ui_action{panelId, actionId, value?}) to the panel’s owner in a command-capable context. Returns once dispatched; handler failures become extension_error.

§Errors

FrontendError::NotFound for an unknown panel.

Source

pub fn ui_action_with(&self, action: &UiAction) -> Result<(), FrontendError>

Delivers a v2 action payload (_oino/ui_action, §4.6); $close also deletes the entry after the event is delivered (§6.6).

§Errors

FrontendError::NotFound for an unknown or disposed entry.

Source

pub fn ui_visible(&self, frontend: &str, entry_id: &str, visible: bool)

_oino/ui_visible (§6.5): aggregates over frontends and sends $show/$hide to the owner when the aggregate changes.

Source

pub fn ui_snapshot(&self) -> UiSnapshot

The current registry snapshot (_oino/ui_snapshot, _oino/ui_resync, §9.3).

Source

pub fn ui_resync(&self) -> UiSnapshot

_oino/ui_resync{rev}: the frontend saw a gap, so it always gets a full snapshot.

Source

pub fn ui_fire( &self, extension: &str, method: &str, params: JsonObject, ) -> Result<ProduceOutcome, RegistryError>

Applies one retained producer call (ui.fire, §6.3): the registry records it and publishes a patch; the legacy record is kept for v1 clients and the v1 replay.

§Errors

Invalid trees/patches, foreign ids and limit failures (§9.1); the failure is also published as extension_error.

Creates the turn-footer registry entry of a turn-footer renderer (§6.7).

Source

pub fn invoke_shortcut(&self, id: &str) -> Result<(), FrontendError>

Runs an extension shortcut (run-shortcut) in a shortcut context. Returns once dispatched; failures become extension_error.

§Errors

FrontendError::NotFound for an unknown shortcut id.

Source

pub async fn editor_event(&self, event: EditorEvent) -> bool

Records the composer text and delivers oino_editor to subscribed extensions. Consumable intents wait for the handlers and report whether one returned {consume: true} (first wins); the others are dispatched in the background and return false.

Source

pub async fn service_call( &self, target: Option<&str>, name: &str, payload: JsonValue, ) -> Result<JsonValue, FrontendError>

Calls service name (of target, or of the first extension serving it) as the frontend (caller = "oino.frontend").

§Errors

FrontendError::NotFound when nobody serves it, FrontendError::Failed for handler errors and the 30 s timeout.

Source

pub fn auth_providers(&self) -> Vec<AuthProviderInfo>

Registered providers with their sign-in support and credential state (/login).

Source

pub async fn login(&self, provider: &str) -> Result<(), FrontendError>

Signs in to provider with its component’s OAuth flow (dialogs go to this session’s frontend), stores the credential in auth.json and refreshes the provider’s models.

§Errors

Unknown provider, no OAuth support, flow failure or credential store failure.

Source

pub fn logout(&self, provider: &str) -> Result<(), FrontendError>

Removes the stored credential of provider (/logout).

§Errors

Unknown provider or credential store failure.

Source

pub fn render_spec( &self, request: &RenderRequest, ) -> Result<Option<JsonValue>, FrontendError>

_oino/render: the OUS node the owner of request.key renders for one transcript row (ui-protocol §6.4), or None for the frontend’s own rendering.

Render specs registered for a built-in tool (read/write/edit/bash/…) are render-only overrides: the extension needs the manifest’s tools.override for that name but does not register the tool itself (U1–U2).

§Errors

FrontendError::Failed when the owning instance cannot be reached.

Source

pub async fn set_api_key( &self, provider: &str, key: &str, ) -> Result<(), FrontendError>

Stores an API key for provider in auth.json.

§Errors

Empty key or credential store failure.

Source§

impl AgentSession

Source

pub async fn host_call( &self, extension: &str, cx: &CallContext, op: HostOp, ) -> Result<JsonValue, HostError>

Performs one host operation for extension (runtime §7.3 context rules apply).

§Errors

HostError::StaleContext after replacement, HostError::CommandContextRequired for session-replacing operations outside commands, and operation failures.

Source

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

Slash commands: extension commands, prompt templates, skills.

Source§

impl AgentSession

Source

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

Under a virtual selection: the physical model of the latest successful response.

Source

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

Thinking levels the current model supports (all levels without a model).

Source

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

Validates auth, records model_change, applies the thinking level.

§Errors

No API key for {provider}/{id} when the provider has no credentials.

Source

pub async fn cycle_model( &self, direction: CycleDirection, persist: bool, ) -> Result<Option<CycleModelResult>, SessionOpError>

C y c l e M o d e l.

§Errors

Persisting the selection failed.

Source

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

Clamps, records only changes; returns the effective level.

Source

pub async fn cycle_thinking_level(&self, persist: bool) -> Option<ThinkingLevel>

Cycles the thinking level; None when the model has no reasoning.

Source§

impl AgentSession

Source

pub async fn execute_nested_tool( &self, parent: &str, name: &str, args: JsonObject, cancel: CancellationToken, ) -> ToolCallOutcome

ctx.executeTool(name, args) for the running call parent.

Source§

impl AgentSession

Source

pub fn prompt( &self, text: String, options: PromptOptions, ) -> BoxFuture<'_, Result<PromptDisposition, SessionOpError>>

Sends a prompt: extension commands run immediately, input handlers may transform or handle it, skills and templates expand, and while streaming it is queued per streaming_behavior. Returns once the run started (await AgentSession::wait_for_idle for completion).

§Errors

Fixed errors: streaming without behaviour, no model, no API key, compaction running.

Source

pub async fn steer( &self, text: String, images: Vec<ImageContent>, source: InputSource, ) -> Result<PromptDisposition, SessionOpError>

Queues a steering message.

§Errors

SessionOpError::CommandNotAllowed for extension commands.

Source

pub async fn follow_up( &self, text: String, images: Vec<ImageContent>, source: InputSource, ) -> Result<PromptDisposition, SessionOpError>

Queues a follow-up message.

§Errors

SessionOpError::CommandNotAllowed for extension commands.

Source

pub fn send_custom_message( &self, draft: CustomMessageDraft, trigger_turn: bool, deliver_as: Option<Delivery>, ) -> BoxFuture<'_, Result<(), SessionOpError>>

sendCustomMessage (four cases, see runtime §2).

§Errors

Run start failures.

Source

pub async fn send_user_message( &self, content: UserContentField, deliver_as: Option<Delivery>, expand_prompt_templates: bool, ) -> Result<PromptDisposition, SessionOpError>

Always triggers a turn (queued while streaming).

§Errors

As AgentSession::prompt.

Source

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

The last assistant message of the transcript.

Source§

impl AgentSession

Source

pub async fn edit_queue(&self, edit: QueueEdit) -> Result<(), SessionOpError>

Applies one queue edit and publishes queue_update.

§Errors

SessionOpError::Failed for an index out of range; prompt errors for send-now while idle.

Source§

impl AgentSession

Source

pub fn set_auto_retry_enabled(&self, enabled: bool)

Enables or disables automatic retry (settings).

Source§

impl AgentSession

Source

pub fn session_stats(&self) -> SessionStats

Session stats (all entries, including compacted history and usage entries).

Source

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

Returns the context usage.

Source

pub async fn export_jsonl( &self, path: Option<PathBuf>, ) -> Result<PathBuf, SessionOpError>

A fresh header plus the current branch, re-linked linearly.

§Errors

Serialisation or write failures.

Source

pub async fn export_html( &self, path: Option<PathBuf>, ) -> Result<PathBuf, SessionOpError>

Exports the current branch as a self-contained HTML page (exportToHtml structure: header, messages, tool calls, collapsed thinking, embedded CSS).

§Errors

Write failures.

Source§

impl AgentSession

Source

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

Names of the active tools (declared to the model).

Source

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

Tools callable through nested calls: active direct tools plus codemode/deferred.

Source

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

Every registered tool.

Source

pub fn set_active_tools_by_name(&self, names: &[String])

Sets the active tools by name.

Source

pub fn system_prompt_options(&self) -> BuildSystemPromptOptions

Base prompt options.

Source

pub fn system_prompt(&self) -> String

Current effective system prompt, including changes not yet sent.

Source§

impl AgentSession

Source

pub fn user_messages_for_forking(&self) -> Vec<ForkMessage>

User messages of the whole session.

Source

pub async fn navigate_tree( &self, target_id: &EntryId, options: NavigateTreeOptions, ) -> Result<NavigateTreeResult, SessionOpError>

Navigates the entry tree.

§Errors

Fixed texts for streaming, compaction, unknown targets and summariser failures.

Source§

impl AgentSession

Source

pub fn new(config: SessionConfig) -> Self

Creates a session (new AgentSession + createAgentSession agent wiring). Call AgentSession::bind_extensions afterwards to emit session_start.

Source

pub async fn bind_extensions( &self, reason: &str, previous_session_file: Option<PathBuf>, )

bindExtensions tail: emits session_start and merges resources_discover results into the resources.

Source

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

session_shutdown{reason:"reload"}, settings and resources reload, tool registry rebuild, then session_start{reason:"reload"} and resources_discover.

§Errors

Never fails today; kept fallible for the package reload path.

Source

pub fn runner(&self) -> ExtensionRunner

The extension runner of this session.

Source

pub fn subscribe(&self) -> EventStream

Ordered client event stream (bounded, coalescing).

Source

pub fn hub(&self) -> &EventHub

The event hub (runtime rebinding).

Source

pub fn ui(&self) -> UiBridge

Frontend → extension UI plumbing.

Source

pub fn agent(&self) -> &Agent

The underlying agent.

Source

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

Runs f with the session manager locked.

Source

pub fn with_settings<R>(&self, f: impl FnOnce(&mut SettingsManager) -> R) -> R

Runs f with the settings manager locked.

Source

pub fn models(&self) -> &ModelRegistry

Model registry.

Source

pub fn cwd(&self) -> &Path

Session cwd.

Source

pub fn agent_dir(&self) -> &Path

Agent dir.

Source

pub fn mode(&self) -> ExtensionMode

Run mode.

Source

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

Current model (None until one is selected).

Source

pub fn thinking_level(&self) -> ThinkingLevel

Current thinking level.

Source

pub fn is_streaming(&self) -> bool

Whether an agent run (or post-run continuation) is active.

Source

pub fn is_compacting(&self) -> bool

Whether a compaction or branch summary is running.

Source

pub fn is_idle(&self) -> bool

Returns whether the session is idle.

Source

pub fn is_retrying(&self) -> bool

Whether an automatic retry is waiting.

Source

pub fn is_bash_running(&self) -> bool

Whether a ! command runs.

Source

pub fn retry_attempt(&self) -> u32

Current retry attempt (0 when not retrying).

Source

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

The finalized transcript (session projection).

Source

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

Session file, when persisted.

Source

pub fn session_id(&self) -> String

Session id.

Source

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

Session display name.

Source

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

Steering texts queued.

Source

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

Follow-up texts queued.

Source

pub fn pending_message_count(&self) -> usize

Number of queued texts.

Source

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

Clears both queues and returns their texts.

Source

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

Text of the last assistant message.

Source

pub fn steering_mode(&self) -> QueueMode

Steering drain mode.

Source

pub fn follow_up_mode(&self) -> QueueMode

Follow-up drain mode.

Source

pub fn set_steering_mode(&self, mode: QueueMode)

Sets the steering mode and saves it to settings.

Source

pub fn set_follow_up_mode(&self, mode: QueueMode)

Sets the follow-up mode and saves it to settings.

Source

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

Replaces the --models scope.

Source

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

The --models scope.

Source

pub fn refresh_context(&self)

Rebuilds the finalized transcript from the session projection (the _refreshFinalizedContext).

Source

pub fn entries(&self) -> Vec<SessionEntry>

Copy of the session entries (get_entries).

Source

pub fn run_state(&self) -> RunState

Coarse run state.

Source

pub async fn wait_for_idle(&self)

Resolves once the session is idle.

Source

pub async fn abort(&self)

Aborts the current operation and waits for idle.

Source

pub fn abort_retry(&self)

Cancels the retry wait.

Source

pub fn abort_compaction(&self)

Cancels manual or automatic compaction.

Source

pub fn abort_branch_summary(&self)

Cancels branch summarisation.

Source

pub fn abort_bash(&self)

Cancels running ! commands.

Source

pub async fn dispose(&self)

Disposes the session: aborts everything and invalidates extension contexts.

Source

pub fn spawn_isolated( &self, task: IsolatedTask, fut: impl Future<Output = ()> + Send + 'static, ) -> JoinHandle<()> ⓘ

Spawns a session task with per-session panic isolation (X-PANIC, core spec §2.3): a panic is caught, logged with the session id and published as OinoEvent::SessionCrashed. A crashed IsolatedTask::Drive task additionally resets the run book and repairs dangling tool calls, so the session stays open and the next prompt works — state is rebuilt from the log. Other sessions run as separate tasks and are unaffected.

Returns the wrapper task’s handle; aborting it aborts fut.

Source

pub async fn set_session_name( &self, name: Option<String>, ) -> Result<(), SessionOpError>

Sets the session name.

§Errors

Persisting the session_info entry failed.

Source

pub async fn set_label( &self, entry: &EntryId, label: Option<String>, ) -> Result<(), SessionOpError>

Sets or clears a label.

§Errors

Unknown entry or persistence failure.

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
Source§

impl Debug for AgentSession

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. 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> 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> 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