Skip to main content

a3s_code_core/agent_api/
session_facade.rs

1use super::*;
2
3impl std::fmt::Debug for AgentSession {
4    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5        f.debug_struct("AgentSession")
6            .field("session_id", &self.session_id)
7            .field("workspace", &self.workspace.display().to_string())
8            .field("auto_save", &self.auto_save)
9            .finish()
10    }
11}
12
13impl AgentSession {
14    /// Get a snapshot of command entries (name, description, optional usage).
15    ///
16    /// Acquires the command registry lock briefly and returns owned data.
17    pub fn command_registry(&self) -> std::sync::MutexGuard<'_, CommandRegistry> {
18        session_commands::registry(self)
19    }
20
21    /// Register a custom slash command.
22    ///
23    /// Takes `&self` so it can be called on a shared `Arc<AgentSession>`.
24    pub fn register_command(
25        &self,
26        cmd: Arc<dyn crate::commands::SlashCommand>,
27    ) -> crate::error::Result<()> {
28        self.close_handle
29            .mutate_immediate(|| session_commands::register(self, cmd))
30    }
31
32    /// Return whether [`close`](Self::close) has been called on this session.
33    ///
34    /// Once closed, `send`/`stream` and their attachment variants fast-fail
35    /// with [`crate::error::CodeError::SessionClosed`] instead of starting a
36    /// new run.
37    pub fn is_closed(&self) -> bool {
38        self.closed.load(std::sync::atomic::Ordering::Acquire)
39    }
40
41    /// Clone the session-level [`CancellationToken`](tokio_util::sync::CancellationToken).
42    ///
43    /// All in-flight runs derive their per-operation token from this one via
44    /// `child_token()`, so embedders can:
45    ///
46    /// - Observe the token (e.g. wire it into a host-side `select!`) to
47    ///   react to session shutdown without polling [`is_closed`](Self::is_closed);
48    /// - Call `.cancel()` on it to abort every operation in the session
49    ///   without going through `close()` (no run-store / hook side effects).
50    ///
51    /// For graceful shutdown prefer [`close`](Self::close), which also marks
52    /// runs as cancelled in the store and notifies the configured hook executor.
53    pub fn session_cancel_token(&self) -> tokio_util::sync::CancellationToken {
54        self.session_cancel.clone()
55    }
56
57    /// Return the host-defined tenant id, if any.
58    ///
59    /// The framework only transports this string — it never interprets
60    /// or enforces tenant boundaries itself. Use this from custom
61    /// `HookExecutor` / `PermissionChecker` / `BudgetGuard` impls to route logic
62    /// by tenant.
63    pub fn tenant_id(&self) -> Option<&str> {
64        self.tenant_id.as_deref()
65    }
66
67    /// Return the principal that triggered the session, if any.
68    pub fn principal(&self) -> Option<&str> {
69        self.principal.as_deref()
70    }
71
72    /// Return the id of the agent template/definition the session was
73    /// instantiated from, if any.
74    pub fn agent_template_id(&self) -> Option<&str> {
75        self.agent_template_id.as_deref()
76    }
77
78    /// Return the distributed-trace correlation id propagated through
79    /// this session's events, if any.
80    pub fn correlation_id(&self) -> Option<&str> {
81        self.correlation_id.as_deref()
82    }
83
84    /// Proactively close the session and release its in-flight work.
85    ///
86    /// On the first call this:
87    /// 1. flips the session into the **closed** state so further `send`/`stream`
88    ///    calls fast-fail with [`crate::error::CodeError::SessionClosed`];
89    /// 2. stops the optional lane queue from accepting new commands;
90    /// 3. fires the session-level cancellation token so every derived
91    ///    run/subagent token cascades to cancelled;
92    /// 4. marks the active run `Cancelled` in the run store and notifies the
93    ///    configured hook executor;
94    /// 5. cancels every still-running delegated subagent task spawned from
95    ///    this session;
96    /// 6. cancels all pending human-in-the-loop tool confirmations and external
97    ///    queue tasks, then drains commands admitted before close;
98    /// 7. disconnects MCP servers owned by this session, without touching
99    ///    inherited agent- or host-owned managers.
100    ///
101    /// Subsequent calls are no-ops and are guaranteed not to panic.
102    pub async fn close(&self) {
103        // Delegate to the shared handle so this entry point and
104        // `Agent::close_session(id)` cannot drift in behaviour.
105        self.close_handle.close().await;
106    }
107
108    /// Send a prompt and wait for the complete response.
109    ///
110    /// When `history` is `None`, uses (and auto-updates) the session's
111    /// internal conversation history. When `Some`, uses the provided
112    /// history instead (the internal history is **not** modified).
113    ///
114    /// If the prompt starts with `/`, it is dispatched as a slash command
115    /// and the result is returned without calling the LLM.
116    pub async fn send(&self, prompt: &str, history: Option<&[Message]>) -> Result<AgentResult> {
117        conversation_runtime::send(self, prompt, history).await
118    }
119
120    /// Resume a previously-checkpointed run on this session.
121    ///
122    /// Loads the latest [`LoopCheckpoint`](crate::loop_checkpoint::LoopCheckpoint)
123    /// stored under `checkpoint_run_id` and replays the agent loop from
124    /// that boundary state. A **new** run id is allocated for the
125    /// resumed work; the relationship between the old and new run is
126    /// host-tracked — the framework does not interpret
127    /// it.
128    ///
129    /// Returns an error when no `SessionStore` is configured on this
130    /// session, or when no checkpoint exists for `checkpoint_run_id`.
131    pub async fn resume_run(&self, checkpoint_run_id: &str) -> Result<AgentResult> {
132        conversation_runtime::resume_run(self, checkpoint_run_id).await
133    }
134
135    /// Send a prompt with image attachments and wait for the complete response.
136    ///
137    /// Images are included as multi-modal content blocks in the user message.
138    /// Requires a vision-capable model (e.g., Claude Sonnet, GPT-4o).
139    pub async fn send_with_attachments(
140        &self,
141        prompt: &str,
142        attachments: &[crate::llm::Attachment],
143        history: Option<&[Message]>,
144    ) -> Result<AgentResult> {
145        conversation_runtime::send_with_attachments(self, prompt, attachments, history).await
146    }
147
148    /// Stream a prompt with image attachments.
149    ///
150    /// Images are included as multi-modal content blocks in the user message.
151    /// Requires a vision-capable model (e.g., Claude Sonnet, GPT-4o).
152    pub async fn stream_with_attachments(
153        &self,
154        prompt: &str,
155        attachments: &[crate::llm::Attachment],
156        history: Option<&[Message]>,
157    ) -> Result<(mpsc::Receiver<AgentEvent>, JoinHandle<()>)> {
158        conversation_runtime::stream_with_attachments(self, prompt, attachments, history).await
159    }
160
161    /// Send a prompt and stream events back.
162    ///
163    /// When `history` is `None`, uses the session's internal history
164    /// and updates it when the stream completes.
165    /// When `Some`, uses the provided history instead.
166    ///
167    /// If the prompt starts with `/`, it is dispatched as a slash command
168    /// and the result is emitted as a single `TextDelta` + `End` event.
169    pub async fn stream(
170        &self,
171        prompt: &str,
172        history: Option<&[Message]>,
173    ) -> Result<(mpsc::Receiver<AgentEvent>, JoinHandle<()>)> {
174        conversation_runtime::stream(self, prompt, history).await
175    }
176
177    /// Cancel the current ongoing operation (send/stream).
178    ///
179    /// If an operation is in progress, this will trigger cancellation of the LLM streaming
180    /// and tool execution. The operation will terminate as soon as possible.
181    ///
182    /// Returns `true` if an operation was cancelled, `false` if no operation was in progress.
183    pub async fn cancel(&self) -> bool {
184        RunControl::from_session(self).cancel_current().await
185    }
186
187    /// Return a snapshot of the session's conversation history.
188    pub fn history(&self) -> Vec<Message> {
189        SessionView::from_session(self).history()
190    }
191
192    /// Return a reference to the session's memory.
193    ///
194    /// Normal sessions always have memory; `None` is reserved for
195    /// lower-level/manual construction compatibility.
196    pub fn memory(&self) -> Option<&Arc<crate::memory::AgentMemory>> {
197        SessionView::from_session(self).memory()
198    }
199
200    /// Return the session ID.
201    pub fn id(&self) -> &str {
202        SessionView::from_session(self).id()
203    }
204
205    /// Return the session workspace path.
206    pub fn workspace(&self) -> &std::path::Path {
207        SessionView::from_session(self).workspace()
208    }
209
210    /// Return any deferred init warning (e.g. memory store failed to initialize).
211    pub fn init_warning(&self) -> Option<&str> {
212        SessionView::from_session(self).init_warning()
213    }
214
215    /// Return the session ID.
216    pub fn session_id(&self) -> &str {
217        SessionView::from_session(self).id()
218    }
219
220    /// The session's persistence store, if one is configured — needed by the
221    /// resumable orchestration combinator to journal workflow progress.
222    pub fn session_store(&self) -> Option<Arc<dyn crate::store::SessionStore>> {
223        self.session_store.clone()
224    }
225
226    /// Return the definitions of all tools currently registered in this session.
227    ///
228    /// The list reflects the live state of the tool executor — tools added via
229    /// `add_mcp_server()` appear immediately; tools removed via
230    /// `remove_mcp_server()` disappear immediately.
231    pub fn tool_definitions(&self) -> Vec<crate::llm::ToolDefinition> {
232        DirectToolRuntime::from_session(self).definitions()
233    }
234
235    /// Return the names of all tools currently registered on this session.
236    ///
237    /// Equivalent to `tool_definitions().into_iter().map(|t| t.name).collect()`.
238    /// Tools added via [`add_mcp_server`] appear immediately; tools removed via
239    /// [`remove_mcp_server`] disappear immediately.
240    pub fn tool_names(&self) -> Vec<String> {
241        DirectToolRuntime::from_session(self).names()
242    }
243
244    /// Return a stored tool artifact by URI, if it exists in this session.
245    pub fn get_artifact(&self, artifact_uri: &str) -> Option<crate::tools::ToolArtifact> {
246        DirectToolRuntime::from_session(self).artifact(artifact_uri)
247    }
248
249    /// Return compact execution trace events recorded for this session.
250    pub fn trace_events(&self) -> Vec<crate::trace::TraceEvent> {
251        SessionView::from_session(self).trace_events()
252    }
253
254    /// Save the session to the configured store.
255    ///
256    /// Returns `Ok(())` if saved successfully, or if no store is configured (no-op).
257    pub async fn save(&self) -> Result<()> {
258        session_save::save(self).await
259    }
260}