Skip to main content

AgentSession

Struct AgentSession 

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

Workspace-bound session. All LLM and tool operations happen here.

History is automatically accumulated after each send() call and after stream() completes when no custom history is supplied. Use history() to retrieve the current conversation log.

Implementations§

Source§

impl AgentSession

Source

pub fn command_registry(&self) -> MutexGuard<'_, CommandRegistry>

Get a snapshot of command entries (name, description, optional usage).

Acquires the command registry lock briefly and returns owned data.

Source

pub fn register_command(&self, cmd: Arc<dyn SlashCommand>)

Register a custom slash command.

Takes &self so it can be called on a shared Arc<AgentSession>.

Source

pub fn is_closed(&self) -> bool

Return whether close has been called on this session.

Once closed, send/stream and their attachment variants fast-fail with crate::error::CodeError::SessionClosed instead of starting a new run.

Source

pub fn session_cancel_token(&self) -> CancellationToken

Clone the session-level CancellationToken.

All in-flight runs derive their per-operation token from this one via child_token(), so embedders can:

  • Observe the token (e.g. wire it into a host-side select!) to react to session shutdown without polling is_closed;
  • Call .cancel() on it to abort every operation in the session without going through close() (no run-store / hook side effects).

For graceful shutdown prefer close, which also marks runs as cancelled in the store and fires AHP hooks.

Source

pub fn tenant_id(&self) -> Option<&str>

Return the host-defined tenant id, if any.

The framework only transports this string — it never interprets or enforces tenant boundaries itself. Use this from custom HookExecutor / PermissionChecker / BudgetGuard impls to route logic by tenant.

Source

pub fn principal(&self) -> Option<&str>

Return the principal that triggered the session, if any.

Source

pub fn agent_template_id(&self) -> Option<&str>

Return the id of the agent template/definition the session was instantiated from, if any.

Source

pub fn correlation_id(&self) -> Option<&str>

Return the distributed-trace correlation id propagated through this session’s events, if any.

Source

pub fn set_budget_guard(&self, guard: Option<Arc<dyn BudgetGuard>>)

Install or replace a runtime budget guard. Takes effect on the next send / stream call (the guard is consulted at agent- loop build time, not on the live execution). Setting None clears the override so config.budget_guard takes over again.

This is the entry point SDKs use to wire a host-supplied guard after the session has already been constructed — useful when the guard’s transport (e.g. a JS callable) cannot live inside the value-typed SessionOptions.

Source

pub fn budget_guard(&self) -> Option<Arc<dyn BudgetGuard>>

Return the currently-installed runtime budget guard, if any. None means the loop falls back to config.budget_guard.

Source

pub async fn close(&self)

Proactively close the session and release its in-flight work.

On the first call this:

  1. flips the session into the closed state so further send/stream calls fast-fail with crate::error::CodeError::SessionClosed;
  2. fires the session-level cancellation token so every derived run/subagent token cascades to cancelled;
  3. marks the active run Cancelled in the run store and fires AHP hook side effects;
  4. cancels every still-running delegated subagent task spawned from this session;
  5. cancels all pending human-in-the-loop tool confirmations.

Subsequent calls are no-ops and are guaranteed not to panic.

Source

pub async fn send( &self, prompt: &str, history: Option<&[Message]>, ) -> Result<AgentResult>

Send a prompt and wait for the complete response.

When history is None, uses (and auto-updates) the session’s internal conversation history. When Some, uses the provided history instead (the internal history is not modified).

If the prompt starts with /, it is dispatched as a slash command and the result is returned without calling the LLM.

Source

pub async fn resume_run(&self, checkpoint_run_id: &str) -> Result<AgentResult>

Resume a previously-checkpointed run on this session.

Loads the latest LoopCheckpoint stored under checkpoint_run_id and replays the agent loop from that boundary state. A new run id is allocated for the resumed work; the relationship between the old and new run is host-tracked (e.g. by 书安OS) — the framework does not interpret it.

Returns an error when no SessionStore is configured on this session, or when no checkpoint exists for checkpoint_run_id.

Source

pub async fn send_with_attachments( &self, prompt: &str, attachments: &[Attachment], history: Option<&[Message]>, ) -> Result<AgentResult>

Send a prompt with image attachments and wait for the complete response.

Images are included as multi-modal content blocks in the user message. Requires a vision-capable model (e.g., Claude Sonnet, GPT-4o).

Source

pub async fn stream_with_attachments( &self, prompt: &str, attachments: &[Attachment], history: Option<&[Message]>, ) -> Result<(Receiver<AgentEvent>, JoinHandle<()>)>

Stream a prompt with image attachments.

Images are included as multi-modal content blocks in the user message. Requires a vision-capable model (e.g., Claude Sonnet, GPT-4o).

Source

pub async fn stream( &self, prompt: &str, history: Option<&[Message]>, ) -> Result<(Receiver<AgentEvent>, JoinHandle<()>)>

Send a prompt and stream events back.

When history is None, uses the session’s internal history and updates it when the stream completes. When Some, uses the provided history instead.

If the prompt starts with /, it is dispatched as a slash command and the result is emitted as a single TextDelta + End event.

Source

pub async fn cancel(&self) -> bool

Cancel the current ongoing operation (send/stream).

If an operation is in progress, this will trigger cancellation of the LLM streaming and tool execution. The operation will terminate as soon as possible.

Returns true if an operation was cancelled, false if no operation was in progress.

Source

pub async fn cancel_run(&self, run_id: &str) -> bool

Cancel a specific run only if it is still the active run.

This is useful for SDK callers that hold a previously observed run ID: stale run IDs will not cancel a newer operation.

Source

pub async fn runs(&self) -> Vec<RunSnapshot>

Return snapshots for runs recorded by this session.

Source

pub async fn run_snapshot(&self, run_id: &str) -> Option<RunSnapshot>

Return a snapshot for a recorded run.

Source

pub async fn run_events(&self, run_id: &str) -> Vec<RunEventRecord>

Return recorded runtime events for a run.

Source

pub async fn current_run(&self) -> Option<RunHandle>

Return a handle for the currently running operation, if any.

Source

pub async fn active_tools(&self) -> Vec<ActiveToolSnapshot>

Return active tool calls observed for the currently running operation.

Source

pub async fn subagent_task(&self, task_id: &str) -> Option<SubagentTaskSnapshot>

Look up a delegated subagent task by id. Returns None if no such task has been observed in this session.

Source

pub async fn subagent_tasks(&self) -> Vec<SubagentTaskSnapshot>

Return snapshots of every delegated subagent task observed in this session (including completed and failed ones), oldest first.

Source

pub async fn pending_subagent_tasks(&self) -> Vec<SubagentTaskSnapshot>

Return snapshots of subagent tasks still in Running state.

Source

pub async fn cancel_subagent_task(&self, task_id: &str) -> bool

Cancel an in-flight delegated subagent task by id. Returns true when a cancellation token was found and fired, false when the task id is unknown or the task has already finished. The eventual SubagentEnd from the cancelled child loop won’t downgrade the terminal status — it stays Cancelled.

Source

pub fn subagent_tracker(&self) -> Arc<InMemorySubagentTaskTracker>

Return a shared handle to the session’s subagent task tracker.

Advanced: embedders implementing a custom subagent execution path (i.e. spawning child loops outside the built-in task tool) can use this to register cancellation tokens and feed AgentEvents into the tracker so the standard subagent_task / pending_subagent_tasks / cancel_subagent_task APIs and close keep working uniformly across execution paths.

Source

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

Return a snapshot of the session’s conversation history.

Source

pub async fn pending_confirmations(&self) -> Vec<PendingConfirmationInfo>

Return pending HITL tool confirmations for this session.

Source

pub async fn confirm_tool_use( &self, tool_id: &str, approved: bool, reason: Option<String>, ) -> Result<bool>

Resolve a pending HITL tool confirmation.

Returns Ok(true) when a pending confirmation was found and completed, Ok(false) when the tool ID is not pending or HITL is not configured.

Source

pub async fn cancel_confirmations(&self) -> usize

Cancel all pending HITL confirmations for this session.

Source

pub fn memory(&self) -> Option<&Arc<AgentMemory>>

Return a reference to the session’s memory, if configured.

Source

pub fn id(&self) -> &str

Return the session ID.

Source

pub fn workspace(&self) -> &Path

Return the session workspace path.

Source

pub fn init_warning(&self) -> Option<&str>

Return any deferred init warning (e.g. memory store failed to initialize).

Source

pub fn session_id(&self) -> &str

Return the session ID.

Source

pub fn tool_definitions(&self) -> Vec<ToolDefinition>

Return the definitions of all tools currently registered in this session.

The list reflects the live state of the tool executor — tools added via add_mcp_server() appear immediately; tools removed via remove_mcp_server() disappear immediately.

Source

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

Return the names of all tools currently registered on this session.

Equivalent to tool_definitions().into_iter().map(|t| t.name).collect(). Tools added via [add_mcp_server] appear immediately; tools removed via [remove_mcp_server] disappear immediately.

Source

pub fn get_artifact(&self, artifact_uri: &str) -> Option<ToolArtifact>

Return a stored tool artifact by URI, if it exists in this session.

Source

pub fn trace_events(&self) -> Vec<TraceEvent>

Return compact execution trace events recorded for this session.

Source

pub fn verification_reports(&self) -> Vec<VerificationReport>

Return structured verification reports recorded for this session.

Source

pub fn verification_summary(&self) -> VerificationSummary

Return a structured summary of all verification reports recorded for this session.

Source

pub fn verification_summary_text(&self) -> String

Return a concise human-readable verification summary for this session.

Source

pub fn record_verification_reports( &self, reports: impl IntoIterator<Item = VerificationReport>, )

Add externally produced verification reports to this session’s completion evidence.

Source

pub fn register_hook(&self, hook: Hook)

Register a hook for lifecycle event interception.

Source

pub fn unregister_hook(&self, hook_id: &str) -> Option<Hook>

Unregister a hook by ID.

Source

pub fn register_hook_handler( &self, hook_id: &str, handler: Arc<dyn HookHandler>, )

Register a handler for a specific hook.

Source

pub fn unregister_hook_handler(&self, hook_id: &str)

Unregister a hook handler by hook ID.

Source

pub fn hook_count(&self) -> usize

Get the number of registered hooks.

Source

pub async fn save(&self) -> Result<()>

Save the session to the configured store.

Returns Ok(()) if saved successfully, or if no store is configured (no-op).

Source

pub async fn read_file(&self, path: &str) -> Result<String>

Read a file from the workspace.

Source

pub async fn write_file( &self, path: &str, content: &str, ) -> Result<ToolCallResult>

Write a file in the workspace.

Source

pub async fn ls(&self, path: Option<&str>) -> Result<ToolCallResult>

List a directory in the workspace.

Source

pub async fn edit_file( &self, path: &str, old_string: &str, new_string: &str, replace_all: bool, ) -> Result<ToolCallResult>

Edit a file by replacing text in the workspace.

Source

pub async fn patch_file(&self, path: &str, diff: &str) -> Result<ToolCallResult>

Apply a unified diff patch to a workspace file.

Source

pub async fn bash(&self, command: &str) -> Result<String>

Execute a bash command in the workspace.

When a sandbox handle is configured via SessionOptions::with_sandbox_handle(), the command is routed through that sandbox.

Source

pub async fn verify_commands( &self, subject: &str, commands: &[VerificationCommand], ) -> Result<VerificationReport>

Run verification commands through the session’s tool execution path.

Source

pub fn verification_presets(&self) -> Vec<VerificationPreset>

Return project-aware verification command presets for this workspace.

Source

pub async fn glob(&self, pattern: &str) -> Result<Vec<String>>

Search for files matching a glob pattern.

Source

pub async fn grep(&self, pattern: &str) -> Result<String>

Search file contents with a regex pattern.

Source

pub async fn tool(&self, name: &str, args: Value) -> Result<ToolCallResult>

Execute a tool by name, bypassing the LLM.

Source

pub fn has_queue(&self) -> bool

Returns whether this session has an advanced lane queue configured.

Source

pub async fn set_lane_handler( &self, lane: SessionLane, config: LaneHandlerConfig, )

Configure a lane’s handler mode for explicit external/hybrid dispatch.

Only effective when a queue is configured via SessionOptions::with_queue_config.

Source

pub async fn complete_external_task( &self, task_id: &str, result: ExternalTaskResult, ) -> bool

Complete an external queue task by ID.

Returns true if the task was found and completed, false if not found.

Source

pub async fn pending_external_tasks(&self) -> Vec<ExternalTask>

Get pending external queue tasks awaiting completion by an external handler.

Source

pub async fn queue_stats(&self) -> SessionQueueStats

Get optional queue statistics (pending, active, external counts per lane).

Source

pub async fn queue_metrics(&self) -> Option<MetricsSnapshot>

Get a metrics snapshot from the optional queue (if metrics are enabled).

Source

pub async fn dead_letters(&self) -> Vec<DeadLetter>

Get dead letters from the optional queue’s DLQ (if DLQ is enabled).

Source

pub fn register_agent_dir(&self, dir: &Path) -> usize

Register all agents found in a directory with the live session.

Scans dir for *.yaml, *.yml, and *.md agent definition files, parses them, and adds each one to the shared AgentRegistry used by the task tool. New agents are immediately usable via task(agent="…") in the same session — no restart required.

Returns the number of agents successfully loaded from the directory.

Source

pub fn register_worker_agent(&self, spec: WorkerAgentSpec) -> AgentDefinition

Register a disposable worker agent with the live session.

The returned definition is immediately available to the task tool by worker name, so callers can create many reproducible workers without writing temporary agent files or restarting the session.

Source

pub fn register_worker_agents<I>(&self, specs: I) -> Vec<AgentDefinition>
where I: IntoIterator<Item = WorkerAgentSpec>,

Register multiple disposable worker agents with the live session.

Source

pub async fn add_mcp_server(&self, config: McpServerConfig) -> Result<usize>

Add an MCP server to this session.

Registers, connects, and makes all tools immediately available for the agent to call. Tool names follow the convention mcp__<name>__<tool>.

Returns the number of tools registered from the server.

Source

pub async fn remove_mcp_server(&self, server_name: &str) -> Result<()>

Remove an MCP server from this session.

Disconnects the server and unregisters all its tools from the executor. No-op if the server was never added.

Source

pub async fn mcp_status(&self) -> HashMap<String, McpServerStatus>

Return the connection status of all MCP servers registered with this session.

Trait Implementations§

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

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
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<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: 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: 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, 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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,