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.
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 cron_scheduler(&self) -> &Arc<CronScheduler>
pub fn cron_scheduler(&self) -> &Arc<CronScheduler>
Access the session’s cron scheduler (backs /loop, /cron-list, /cron-cancel).
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 btw(&self, question: &str) -> Result<BtwResult>
pub async fn btw(&self, question: &str) -> Result<BtwResult>
Ask an ephemeral side question without affecting conversation history.
Takes a read-only snapshot of the current history, makes a separate LLM call with no tools, and returns the answer. History is never modified.
Safe to call concurrently with an ongoing send() — the
snapshot only acquires a read lock on the internal history.
§Example
let result = session.btw("what file was that error in?").await?;
println!("{}", result.answer);Sourcepub async fn btw_with_context(
&self,
question: &str,
runtime_context: Option<&str>,
) -> Result<BtwResult>
pub async fn btw_with_context( &self, question: &str, runtime_context: Option<&str>, ) -> Result<BtwResult>
Ask an ephemeral side question with optional caller-supplied runtime context.
This keeps the core BTW behavior, but allows hosts to inject extra execution-state context that is not persisted in conversation history.
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
(note: streaming does not auto-update internal history since
the result is consumed asynchronously via the channel).
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 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 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 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 is configured via SessionOptions::with_sandbox(),
the command is routed through the A3S Box sandbox.
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 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 (Internal/External/Hybrid).
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 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 tasks awaiting completion by an external handler.
Sourcepub async fn queue_stats(&self) -> SessionQueueStats
pub async fn queue_stats(&self) -> SessionQueueStats
Get 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 queue (if metrics are enabled).
Sourcepub async fn submit(
&self,
lane: SessionLane,
command: Box<dyn SessionCommand>,
) -> Result<Receiver<Result<Value>>>
pub async fn submit( &self, lane: SessionLane, command: Box<dyn SessionCommand>, ) -> Result<Receiver<Result<Value>>>
Submit a command directly to the session’s lane queue.
Returns Err if no queue is configured (i.e. session was created without
SessionOptions::with_queue_config). On success, returns a receiver that
resolves to the command’s result when execution completes.
Sourcepub async fn submit_batch(
&self,
lane: SessionLane,
commands: Vec<Box<dyn SessionCommand>>,
) -> Result<Vec<Receiver<Result<Value>>>>
pub async fn submit_batch( &self, lane: SessionLane, commands: Vec<Box<dyn SessionCommand>>, ) -> Result<Vec<Receiver<Result<Value>>>>
Submit multiple commands to the session’s lane queue in a single batch.
More efficient than calling submit() in a loop: handler config is fetched
once and task IDs are generated atomically. Returns Err if no queue is
configured. On success, returns one receiver per command in the same order
as the input slice.
Sourcepub async fn dead_letters(&self) -> Vec<DeadLetter>
pub async fn dead_letters(&self) -> Vec<DeadLetter>
Get dead letters from the 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 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.