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
impl AgentSession
Sourcepub fn command_registry(&self) -> MutexGuard<'_, CommandRegistry>
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.
Sourcepub fn register_command(&self, cmd: Arc<dyn SlashCommand>)
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>.
Sourcepub fn is_closed(&self) -> bool
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.
Sourcepub fn session_cancel_token(&self) -> CancellationToken
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 pollingis_closed; - Call
.cancel()on it to abort every operation in the session without going throughclose()(no run-store / hook side effects).
For graceful shutdown prefer close, which also marks
runs as cancelled in the store and fires AHP hooks.
Sourcepub fn tenant_id(&self) -> Option<&str>
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.
Sourcepub fn principal(&self) -> Option<&str>
pub fn principal(&self) -> Option<&str>
Return the principal that triggered the session, if any.
Sourcepub fn agent_template_id(&self) -> Option<&str>
pub fn agent_template_id(&self) -> Option<&str>
Return the id of the agent template/definition the session was instantiated from, if any.
Sourcepub fn correlation_id(&self) -> Option<&str>
pub fn correlation_id(&self) -> Option<&str>
Return the distributed-trace correlation id propagated through this session’s events, if any.
Sourcepub fn set_budget_guard(&self, guard: Option<Arc<dyn BudgetGuard>>)
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.
Sourcepub fn budget_guard(&self) -> Option<Arc<dyn BudgetGuard>>
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.
Sourcepub async fn close(&self)
pub async fn close(&self)
Proactively close the session and release its in-flight work.
On the first call this:
- flips the session into the closed state so further
send/streamcalls fast-fail withcrate::error::CodeError::SessionClosed; - fires the session-level cancellation token so every derived run/subagent token cascades to cancelled;
- marks the active run
Cancelledin the run store and fires AHP hook side effects; - cancels every still-running delegated subagent task spawned from this session;
- cancels all pending human-in-the-loop tool confirmations.
Subsequent calls are no-ops and are guaranteed not to panic.
Sourcepub async fn send(
&self,
prompt: &str,
history: Option<&[Message]>,
) -> Result<AgentResult>
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.
Sourcepub async fn resume_run(&self, checkpoint_run_id: &str) -> Result<AgentResult>
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.
Sourcepub async fn send_with_attachments(
&self,
prompt: &str,
attachments: &[Attachment],
history: Option<&[Message]>,
) -> Result<AgentResult>
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).
Sourcepub async fn stream_with_attachments(
&self,
prompt: &str,
attachments: &[Attachment],
history: Option<&[Message]>,
) -> Result<(Receiver<AgentEvent>, JoinHandle<()>)>
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).
Sourcepub async fn stream(
&self,
prompt: &str,
history: Option<&[Message]>,
) -> Result<(Receiver<AgentEvent>, JoinHandle<()>)>
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.
Sourcepub async fn cancel(&self) -> bool
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.
Sourcepub async fn cancel_run(&self, run_id: &str) -> bool
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.
Sourcepub async fn runs(&self) -> Vec<RunSnapshot>
pub async fn runs(&self) -> Vec<RunSnapshot>
Return snapshots for runs recorded by this session.
Sourcepub async fn run_snapshot(&self, run_id: &str) -> Option<RunSnapshot>
pub async fn run_snapshot(&self, run_id: &str) -> Option<RunSnapshot>
Return a snapshot for a recorded run.
Sourcepub async fn run_events(&self, run_id: &str) -> Vec<RunEventRecord>
pub async fn run_events(&self, run_id: &str) -> Vec<RunEventRecord>
Return recorded runtime events for a run.
Sourcepub async fn current_run(&self) -> Option<RunHandle>
pub async fn current_run(&self) -> Option<RunHandle>
Return a handle for the currently running operation, if any.
Sourcepub async fn active_tools(&self) -> Vec<ActiveToolSnapshot>
pub async fn active_tools(&self) -> Vec<ActiveToolSnapshot>
Return active tool calls observed for the currently running operation.
Sourcepub async fn subagent_task(&self, task_id: &str) -> Option<SubagentTaskSnapshot>
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.
Sourcepub async fn subagent_tasks(&self) -> Vec<SubagentTaskSnapshot>
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.
Sourcepub async fn pending_subagent_tasks(&self) -> Vec<SubagentTaskSnapshot>
pub async fn pending_subagent_tasks(&self) -> Vec<SubagentTaskSnapshot>
Return snapshots of subagent tasks still in Running state.
Sourcepub async fn cancel_subagent_task(&self, task_id: &str) -> bool
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.
Sourcepub fn subagent_tracker(&self) -> Arc<InMemorySubagentTaskTracker> ⓘ
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.
Sourcepub async fn pending_confirmations(&self) -> Vec<PendingConfirmationInfo>
pub async fn pending_confirmations(&self) -> Vec<PendingConfirmationInfo>
Return pending HITL tool confirmations for this session.
Sourcepub async fn confirm_tool_use(
&self,
tool_id: &str,
approved: bool,
reason: Option<String>,
) -> Result<bool>
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.
Sourcepub async fn cancel_confirmations(&self) -> usize
pub async fn cancel_confirmations(&self) -> usize
Cancel all pending HITL confirmations for this session.
Sourcepub fn memory(&self) -> Option<&Arc<AgentMemory>>
pub fn memory(&self) -> Option<&Arc<AgentMemory>>
Return a reference to the session’s memory, if configured.
Sourcepub fn init_warning(&self) -> Option<&str>
pub fn init_warning(&self) -> Option<&str>
Return any deferred init warning (e.g. memory store failed to initialize).
Sourcepub fn session_id(&self) -> &str
pub fn session_id(&self) -> &str
Return the session ID.
Sourcepub fn tool_definitions(&self) -> Vec<ToolDefinition>
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.
Sourcepub fn tool_names(&self) -> Vec<String>
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.
Sourcepub fn get_artifact(&self, artifact_uri: &str) -> Option<ToolArtifact>
pub fn get_artifact(&self, artifact_uri: &str) -> Option<ToolArtifact>
Return a stored tool artifact by URI, if it exists in this session.
Sourcepub fn trace_events(&self) -> Vec<TraceEvent>
pub fn trace_events(&self) -> Vec<TraceEvent>
Return compact execution trace events recorded for this session.
Sourcepub fn verification_reports(&self) -> Vec<VerificationReport>
pub fn verification_reports(&self) -> Vec<VerificationReport>
Return structured verification reports recorded for this session.
Sourcepub fn verification_summary(&self) -> VerificationSummary
pub fn verification_summary(&self) -> VerificationSummary
Return a structured summary of all verification reports recorded for this session.
Sourcepub fn verification_summary_text(&self) -> String
pub fn verification_summary_text(&self) -> String
Return a concise human-readable verification summary for this session.
Sourcepub fn record_verification_reports(
&self,
reports: impl IntoIterator<Item = VerificationReport>,
)
pub fn record_verification_reports( &self, reports: impl IntoIterator<Item = VerificationReport>, )
Add externally produced verification reports to this session’s completion evidence.
Sourcepub fn register_hook(&self, hook: Hook)
pub fn register_hook(&self, hook: Hook)
Register a hook for lifecycle event interception.
Sourcepub fn unregister_hook(&self, hook_id: &str) -> Option<Hook>
pub fn unregister_hook(&self, hook_id: &str) -> Option<Hook>
Unregister a hook by ID.
Sourcepub fn register_hook_handler(
&self,
hook_id: &str,
handler: Arc<dyn HookHandler>,
)
pub fn register_hook_handler( &self, hook_id: &str, handler: Arc<dyn HookHandler>, )
Register a handler for a specific hook.
Sourcepub fn unregister_hook_handler(&self, hook_id: &str)
pub fn unregister_hook_handler(&self, hook_id: &str)
Unregister a hook handler by hook ID.
Sourcepub fn hook_count(&self) -> usize
pub fn hook_count(&self) -> usize
Get the number of registered hooks.
Sourcepub async fn save(&self) -> Result<()>
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).
Sourcepub async fn write_file(
&self,
path: &str,
content: &str,
) -> Result<ToolCallResult>
pub async fn write_file( &self, path: &str, content: &str, ) -> Result<ToolCallResult>
Write a file in the workspace.
Sourcepub async fn ls(&self, path: Option<&str>) -> Result<ToolCallResult>
pub async fn ls(&self, path: Option<&str>) -> Result<ToolCallResult>
List a directory in the workspace.
Sourcepub async fn edit_file(
&self,
path: &str,
old_string: &str,
new_string: &str,
replace_all: bool,
) -> Result<ToolCallResult>
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.
Sourcepub async fn patch_file(&self, path: &str, diff: &str) -> Result<ToolCallResult>
pub async fn patch_file(&self, path: &str, diff: &str) -> Result<ToolCallResult>
Apply a unified diff patch to a workspace file.
Sourcepub async fn bash(&self, command: &str) -> Result<String>
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.
Sourcepub async fn verify_commands(
&self,
subject: &str,
commands: &[VerificationCommand],
) -> Result<VerificationReport>
pub async fn verify_commands( &self, subject: &str, commands: &[VerificationCommand], ) -> Result<VerificationReport>
Run verification commands through the session’s tool execution path.
Sourcepub fn verification_presets(&self) -> Vec<VerificationPreset>
pub fn verification_presets(&self) -> Vec<VerificationPreset>
Return project-aware verification command presets for this workspace.
Sourcepub async fn glob(&self, pattern: &str) -> Result<Vec<String>>
pub async fn glob(&self, pattern: &str) -> Result<Vec<String>>
Search for files matching a glob pattern.
Sourcepub async fn grep(&self, pattern: &str) -> Result<String>
pub async fn grep(&self, pattern: &str) -> Result<String>
Search file contents with a regex pattern.
Sourcepub async fn tool(&self, name: &str, args: Value) -> Result<ToolCallResult>
pub async fn tool(&self, name: &str, args: Value) -> Result<ToolCallResult>
Execute a tool by name, bypassing the LLM.
Sourcepub fn has_queue(&self) -> bool
pub fn has_queue(&self) -> bool
Returns whether this session has an advanced lane queue configured.
Sourcepub async fn set_lane_handler(
&self,
lane: SessionLane,
config: LaneHandlerConfig,
)
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.
Sourcepub async fn complete_external_task(
&self,
task_id: &str,
result: ExternalTaskResult,
) -> bool
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.
Sourcepub async fn pending_external_tasks(&self) -> Vec<ExternalTask>
pub async fn pending_external_tasks(&self) -> Vec<ExternalTask>
Get pending external queue tasks awaiting completion by an external handler.
Sourcepub async fn queue_stats(&self) -> SessionQueueStats
pub async fn queue_stats(&self) -> SessionQueueStats
Get optional queue statistics (pending, active, external counts per lane).
Sourcepub async fn queue_metrics(&self) -> Option<MetricsSnapshot>
pub async fn queue_metrics(&self) -> Option<MetricsSnapshot>
Get a metrics snapshot from the optional queue (if metrics are enabled).
Sourcepub async fn dead_letters(&self) -> Vec<DeadLetter>
pub async fn dead_letters(&self) -> Vec<DeadLetter>
Get dead letters from the optional queue’s DLQ (if DLQ is enabled).
Sourcepub fn register_agent_dir(&self, dir: &Path) -> usize
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.
Sourcepub fn register_worker_agent(&self, spec: WorkerAgentSpec) -> AgentDefinition
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.
Sourcepub fn register_worker_agents<I>(&self, specs: I) -> Vec<AgentDefinition>where
I: IntoIterator<Item = WorkerAgentSpec>,
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.
Sourcepub async fn add_mcp_server(&self, config: McpServerConfig) -> Result<usize>
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.
Sourcepub async fn remove_mcp_server(&self, server_name: &str) -> Result<()>
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.
Sourcepub async fn mcp_status(&self) -> HashMap<String, McpServerStatus>
pub async fn mcp_status(&self) -> HashMap<String, McpServerStatus>
Return the connection status of all MCP servers registered with this session.
Trait Implementations§
Auto Trait Implementations§
impl !Freeze for AgentSession
impl !RefUnwindSafe for AgentSession
impl Send for AgentSession
impl Sync for AgentSession
impl Unpin for AgentSession
impl UnsafeUnpin for AgentSession
impl !UnwindSafe for AgentSession
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> FutureExt for T
impl<T> FutureExt for T
Source§fn with_context(self, otel_cx: Context) -> WithContext<Self>
fn with_context(self, otel_cx: Context) -> WithContext<Self>
Source§fn with_current_context(self) -> WithContext<Self>
fn with_current_context(self) -> WithContext<Self>
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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