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("task_priority", &self.task_priority)
9 .field(
10 "cognitive_package_binding",
11 &self.current_cognitive_package_binding(),
12 )
13 .field("auto_save", &self.auto_save)
14 .finish()
15 }
16}
17
18impl AgentSession {
19 /// Return current occupancy of the scheduler shared with sibling sessions.
20 pub async fn task_scheduler_stats(
21 &self,
22 ) -> std::result::Result<
23 crate::task_scheduler::TaskSchedulerStats,
24 crate::task_scheduler::TaskSchedulerError,
25 > {
26 self.task_scheduler.stats().await
27 }
28
29 /// Get a snapshot of command entries (name, description, optional usage).
30 ///
31 /// Acquires the command registry lock briefly and returns owned data.
32 pub fn command_registry(&self) -> std::sync::MutexGuard<'_, CommandRegistry> {
33 session_commands::registry(self)
34 }
35
36 /// Register a custom slash command.
37 ///
38 /// Takes `&self` so it can be called on a shared `Arc<AgentSession>`.
39 pub fn register_command(
40 &self,
41 cmd: Arc<dyn crate::commands::SlashCommand>,
42 ) -> crate::error::Result<()> {
43 self.close_handle.mutate_immediate(|| {
44 self.ensure_compatibility_name_available(
45 crate::capability::CapabilityKind::Command,
46 cmd.name(),
47 )?;
48 session_commands::register(self, cmd);
49 Ok(())
50 })?
51 }
52
53 /// Return whether [`close`](Self::close) has been called on this session.
54 ///
55 /// Once closed, `send`/`stream` and their attachment variants fast-fail
56 /// with [`crate::error::CodeError::SessionClosed`] instead of starting a
57 /// new run.
58 pub fn is_closed(&self) -> bool {
59 self.closed.load(std::sync::atomic::Ordering::Acquire)
60 }
61
62 /// Clone the session-level [`CancellationToken`](tokio_util::sync::CancellationToken).
63 ///
64 /// All in-flight runs derive their per-operation token from this one via
65 /// `child_token()`, so embedders can:
66 ///
67 /// - Observe the token (e.g. wire it into a host-side `select!`) to
68 /// react to session shutdown without polling [`is_closed`](Self::is_closed);
69 /// - Call `.cancel()` on it to abort every operation in the session
70 /// without going through `close()` (no run-store / hook side effects).
71 ///
72 /// For graceful shutdown prefer [`close`](Self::close), which also marks
73 /// runs as cancelled in the store and notifies the configured hook executor.
74 pub fn session_cancel_token(&self) -> tokio_util::sync::CancellationToken {
75 self.session_cancel.clone()
76 }
77
78 /// Observe asynchronous semantic workspace indexing for this session.
79 ///
80 /// Disabled sessions return a stable `disabled` status without starting a
81 /// background task. Closing a configured session transitions the same
82 /// status to `closed` and releases its in-memory vector index.
83 pub fn workspace_retrieval_status(&self) -> crate::workspace::WorkspaceRetrievalStatus {
84 self.workspace_retrieval
85 .as_ref()
86 .map(|runtime| runtime.status())
87 .unwrap_or_else(crate::workspace::WorkspaceRetrievalStatus::disabled)
88 }
89
90 /// Run a structured semantic workspace query against this session.
91 ///
92 /// Returned source chunks are reread and digest-verified through the
93 /// session's workspace backend. Partial indexing, degradation, and
94 /// revision races are represented explicitly in the result's status and
95 /// fallback fields.
96 pub async fn semantic_search(
97 &self,
98 request: crate::workspace::WorkspaceSemanticSearchRequest,
99 ) -> crate::workspace::WorkspaceRetrievalResult<crate::workspace::WorkspaceSemanticSearchResult>
100 {
101 if self.is_closed() {
102 return Err(crate::workspace::WorkspaceRetrievalError::Unavailable);
103 }
104 self.tool_context
105 .workspace_services
106 .semantic_search(request, self.session_cancel.child_token())
107 .await
108 }
109
110 /// Run structured hybrid workspace retrieval for this session.
111 ///
112 /// Exact literal, BM25, optional Code Intelligence symbols, and semantic
113 /// candidates are fused by rank. Returned chunks are current-source
114 /// verified and include per-channel status and fallback metadata.
115 pub async fn hybrid_search(
116 &self,
117 request: crate::workspace::WorkspaceHybridSearchRequest,
118 ) -> crate::workspace::WorkspaceRetrievalResult<crate::workspace::WorkspaceHybridSearchResult>
119 {
120 if self.is_closed() {
121 return Err(crate::workspace::WorkspaceRetrievalError::Unavailable);
122 }
123 self.tool_context
124 .workspace_services
125 .hybrid_search(request, self.session_cancel.child_token())
126 .await
127 }
128
129 /// Return the host-defined tenant id, if any.
130 ///
131 /// The framework only transports this string — it never interprets
132 /// or enforces tenant boundaries itself. Use this from custom
133 /// `HookExecutor` / `PermissionChecker` / `BudgetGuard` impls to route logic
134 /// by tenant.
135 pub fn tenant_id(&self) -> Option<&str> {
136 self.tenant_id.as_deref()
137 }
138
139 /// Return the principal that triggered the session, if any.
140 pub fn principal(&self) -> Option<&str> {
141 self.principal.as_deref()
142 }
143
144 /// Return the id of the agent template/definition the session was
145 /// instantiated from, if any.
146 pub fn agent_template_id(&self) -> Option<&str> {
147 self.agent_template_id.as_deref()
148 }
149
150 /// Return the distributed-trace correlation id propagated through
151 /// this session's events, if any.
152 pub fn correlation_id(&self) -> Option<&str> {
153 self.correlation_id.as_deref()
154 }
155
156 /// Return the Session-static cognitive-package binding, if configured.
157 ///
158 /// This compatibility accessor does not observe a later atomic Knowledge
159 /// projection. New host code should use
160 /// [`current_cognitive_package_binding`](Self::current_cognitive_package_binding).
161 pub fn cognitive_package_binding(
162 &self,
163 ) -> Option<&crate::cognitive_context::CognitivePackageBindingV1> {
164 self.cognitive_context
165 .as_ref()
166 .map(crate::cognitive_context::CognitiveContextSession::binding)
167 }
168
169 /// Return the exact cognitive-package binding visible to the next Run.
170 ///
171 /// The returned value is owned because the current atomic catalog
172 /// generation is pinned only for this read. An admitted Run records its
173 /// own binding and remains on that generation across later cutover.
174 pub fn current_cognitive_package_binding(
175 &self,
176 ) -> Option<crate::cognitive_context::CognitivePackageBindingV1> {
177 let projection = self.capability_catalog.pin();
178 super::agent_loop_runtime::cognitive_binding_for_projection(self, projection.projection())
179 }
180
181 /// Proactively close the session and release its in-flight work.
182 ///
183 /// On the first call this:
184 /// 1. flips the session into the **closed** state so further `send`/`stream`
185 /// calls fast-fail with [`crate::error::CodeError::SessionClosed`];
186 /// 2. stops the optional lane queue from accepting new commands;
187 /// 3. waits for completed-turn memory extractions accepted before close,
188 /// up to the bounded shutdown deadline;
189 /// 4. fires the session-level cancellation token so every derived
190 /// run/subagent token cascades to cancelled;
191 /// 5. marks the active run `Cancelled` in the run store and notifies the
192 /// configured hook executor;
193 /// 6. cancels every still-running delegated subagent task spawned from
194 /// this session;
195 /// 7. cancels all pending human-in-the-loop tool confirmations and external
196 /// queue tasks, then drains commands admitted before close;
197 /// 8. disconnects MCP servers owned by this session, without touching
198 /// inherited agent- or host-owned managers.
199 ///
200 /// Subsequent calls are no-ops and are guaranteed not to panic.
201 pub async fn close(&self) {
202 // Delegate to the shared handle so this entry point and
203 // `Agent::close_session(id)` cannot drift in behaviour.
204 self.close_handle.close().await;
205 }
206
207 /// Send a prompt and wait for the complete response.
208 ///
209 /// When `history` is `None`, uses (and auto-updates) the session's
210 /// internal conversation history. When `Some`, uses the provided
211 /// history instead (the internal history is **not** modified).
212 ///
213 /// If the prompt starts with `/`, it is dispatched as a slash command
214 /// and the result is returned without calling the LLM.
215 pub async fn send(&self, prompt: &str, history: Option<&[Message]>) -> Result<AgentResult> {
216 conversation_runtime::send(self, prompt, history).await
217 }
218
219 /// Resume a previously-checkpointed run on this session.
220 ///
221 /// Loads the latest [`LoopCheckpoint`](crate::loop_checkpoint::LoopCheckpoint)
222 /// stored under `checkpoint_run_id` and replays the agent loop from
223 /// that boundary state. A **new** run id is allocated for the
224 /// resumed work; the relationship between the old and new run is
225 /// host-tracked — the framework does not interpret
226 /// it.
227 ///
228 /// Returns an error when no `SessionStore` is configured on this
229 /// session, or when no checkpoint exists for `checkpoint_run_id`.
230 pub async fn resume_run(&self, checkpoint_run_id: &str) -> Result<AgentResult> {
231 conversation_runtime::resume_run(self, checkpoint_run_id).await
232 }
233
234 /// Start one detached run with an exact host-selected run id.
235 ///
236 /// Replaying the same id, session, and prompt returns the existing run
237 /// without executing it again. Reusing the id for different immutable
238 /// input fails with [`crate::error::CodeError::RunIdentityConflict`].
239 /// This is the canonical entry point for headless `a3s code` hosts.
240 pub async fn spawn_run_with_id(&self, run_id: &str, prompt: &str) -> Result<AgentRunSpawn> {
241 conversation_runtime::spawn_run_with_id(self, run_id, prompt).await
242 }
243
244 /// Resume a durable checkpoint into one exact, fresh host-selected run id.
245 ///
246 /// The checkpoint run remains immutable. Replaying the same recovery run
247 /// id returns its existing snapshot and never executes the checkpoint
248 /// twice.
249 pub async fn spawn_recovery_with_run_id(
250 &self,
251 checkpoint_run_id: &str,
252 run_id: &str,
253 ) -> Result<AgentRunSpawn> {
254 conversation_runtime::spawn_recovery_with_run_id(self, checkpoint_run_id, run_id).await
255 }
256
257 pub(crate) async fn prepare_recovery_with_evidence(
258 &self,
259 evidence: &crate::session_checkpoint::SessionLogicalResumeEvidenceV1,
260 checkpoint_identity: &str,
261 run_id: &str,
262 ) -> std::result::Result<super::ExactRecoveryPreparation, super::ExactRecoveryError> {
263 conversation_runtime::prepare_recovery_with_evidence(
264 self,
265 evidence,
266 checkpoint_identity,
267 run_id,
268 )
269 .await
270 }
271
272 pub(crate) async fn prepare_recovery_from_checkpoint(
273 &self,
274 evidence: &crate::session_checkpoint::SessionLogicalResumeEvidenceV1,
275 checkpoint_identity: &str,
276 run_id: &str,
277 checkpoint: crate::loop_checkpoint::LoopCheckpoint,
278 ) -> std::result::Result<super::ExactRecoveryPreparation, super::ExactRecoveryError> {
279 conversation_runtime::prepare_recovery_from_checkpoint(
280 self,
281 evidence,
282 checkpoint_identity,
283 run_id,
284 checkpoint,
285 )
286 .await
287 }
288
289 pub(crate) async fn spawn_prepared_recovery(
290 &self,
291 prepared: super::PreparedExactRecovery,
292 ) -> std::result::Result<AgentRunSpawn, super::ExactRecoveryError> {
293 conversation_runtime::spawn_prepared_recovery(self, prepared).await
294 }
295
296 pub(crate) async fn record_workspace_change_set(
297 &self,
298 run_id: &str,
299 change_set: crate::run::RunWorkspaceChangeSet,
300 ) -> Result<crate::run::RunSnapshot> {
301 let snapshot = self
302 .run_store
303 .record_workspace_change_set(run_id, change_set)
304 .await
305 .map_err(|error| anyhow::anyhow!(error))?;
306 self.save().await?;
307 Ok(snapshot)
308 }
309
310 /// Send a prompt with image attachments and wait for the complete response.
311 ///
312 /// Images are included as multi-modal content blocks in the user message.
313 /// Requires a vision-capable model (e.g., Claude Sonnet, GPT-4o).
314 pub async fn send_with_attachments(
315 &self,
316 prompt: &str,
317 attachments: &[crate::llm::Attachment],
318 history: Option<&[Message]>,
319 ) -> Result<AgentResult> {
320 conversation_runtime::send_with_attachments(self, prompt, attachments, history).await
321 }
322
323 /// Stream a prompt with image attachments.
324 ///
325 /// Images are included as multi-modal content blocks in the user message.
326 /// Requires a vision-capable model (e.g., Claude Sonnet, GPT-4o).
327 pub async fn stream_with_attachments(
328 &self,
329 prompt: &str,
330 attachments: &[crate::llm::Attachment],
331 history: Option<&[Message]>,
332 ) -> Result<(mpsc::Receiver<AgentEvent>, JoinHandle<()>)> {
333 conversation_runtime::stream_with_attachments(self, prompt, attachments, history).await
334 }
335
336 /// Send a prompt and stream events back.
337 ///
338 /// When `history` is `None`, uses the session's internal history
339 /// and updates it when the stream completes.
340 /// When `Some`, uses the provided history instead.
341 ///
342 /// If the prompt starts with `/`, it is dispatched as a slash command
343 /// and the result is emitted as a single `TextDelta` + `End` event.
344 pub async fn stream(
345 &self,
346 prompt: &str,
347 history: Option<&[Message]>,
348 ) -> Result<(mpsc::Receiver<AgentEvent>, JoinHandle<()>)> {
349 conversation_runtime::stream(self, prompt, history).await
350 }
351
352 /// Cancel the current ongoing operation (send/stream).
353 ///
354 /// If an operation is in progress, this will trigger cancellation of the LLM streaming
355 /// and tool execution. The operation will terminate as soon as possible.
356 ///
357 /// Returns `true` if an operation was cancelled, `false` if no operation was in progress.
358 pub async fn cancel(&self) -> bool {
359 RunControl::from_session(self).cancel_current().await
360 }
361
362 /// Cancel the current operation and wait for its single-flight lease to be
363 /// released. Streaming workers first receive cooperative cancellation; a
364 /// worker that exceeds `grace` is aborted, then given `abort_grace` to run
365 /// destructors and release admission ownership.
366 ///
367 /// Returns `true` once the session is safe to reuse. A blocking `send`
368 /// future cannot be force-aborted by the session and may return `false` if
369 /// its caller does not poll it to completion.
370 pub async fn cancel_and_settle(
371 &self,
372 grace: std::time::Duration,
373 abort_grace: std::time::Duration,
374 ) -> bool {
375 let _ = self.cancel().await;
376 if self.run_admission.wait_until_idle(grace).await {
377 return true;
378 }
379 if !self.run_admission.abort_stream_workers() {
380 return false;
381 }
382 self.run_admission.wait_until_idle(abort_grace).await
383 }
384
385 /// Return a snapshot of the session's conversation history.
386 pub fn history(&self) -> Vec<Message> {
387 SessionView::from_session(self).history()
388 }
389
390 /// Return a reference to the session's memory.
391 ///
392 /// Normal sessions always have memory; `None` is reserved for
393 /// lower-level/manual construction compatibility.
394 pub fn memory(&self) -> Option<&Arc<crate::memory::AgentMemory>> {
395 SessionView::from_session(self).memory()
396 }
397
398 /// Return the session ID.
399 pub fn id(&self) -> &str {
400 SessionView::from_session(self).id()
401 }
402
403 /// Return the session workspace path.
404 pub fn workspace(&self) -> &std::path::Path {
405 SessionView::from_session(self).workspace()
406 }
407
408 /// Return any deferred init warning (e.g. memory store failed to initialize).
409 pub fn init_warning(&self) -> Option<&str> {
410 SessionView::from_session(self).init_warning()
411 }
412
413 /// Return the session ID.
414 pub fn session_id(&self) -> &str {
415 SessionView::from_session(self).id()
416 }
417
418 /// The session's persistence store, if one is configured — needed by the
419 /// resumable orchestration combinator to journal workflow progress.
420 pub fn session_store(&self) -> Option<Arc<dyn crate::store::SessionStore>> {
421 self.session_store.clone()
422 }
423
424 /// Return the governed source definitions available to this session.
425 ///
426 /// The list reflects the live state of the tool executor — tools added via
427 /// `add_mcp_server()` appear immediately; tools removed via
428 /// `remove_mcp_server()` disappear immediately. Hidden host compatibility
429 /// aliases remain executable by name but are omitted to avoid schema cost.
430 /// A Run applies [`Self::tool_presentation_profile`] and its frozen
431 /// permission visibility boundary before sending a subset to the model.
432 pub fn tool_definitions(&self) -> Vec<crate::llm::ToolDefinition> {
433 DirectToolRuntime::from_session(self).definitions()
434 }
435
436 /// Return the exact typed Tool-presentation profile configured for new
437 /// Runs in this session.
438 pub fn tool_presentation_profile(&self) -> &crate::tools::ToolPresentationProfileV1 {
439 &self.config.tool_presentation_profile
440 }
441
442 /// Preview the current model-facing definition projection for a prompt.
443 ///
444 /// Run admission snapshots permission providers, so this live preview is
445 /// diagnostic rather than execution authority.
446 pub fn presented_tool_definitions(
447 &self,
448 prompt: &str,
449 ) -> std::result::Result<Vec<crate::llm::ToolDefinition>, crate::tools::ToolPresentationError>
450 {
451 let mut source = self.tool_definitions();
452 if let Some(permission_checker) = &self.config.permission_checker {
453 source.retain(|tool| permission_checker.expose_to_model(&tool.name));
454 }
455 self.config
456 .tool_presentation_profile
457 .present_for_prompt(&source, prompt)
458 }
459
460 /// Return the names of all governed source tools on this session.
461 ///
462 /// Equivalent to `tool_definitions().into_iter().map(|t| t.name).collect()`.
463 /// Tools added via [`Self::add_mcp_server`] appear immediately; tools
464 /// removed via [`Self::remove_mcp_server`] disappear immediately. Use
465 /// [`Self::presented_tool_definitions`] to preview Profile projection.
466 pub fn tool_names(&self) -> Vec<String> {
467 DirectToolRuntime::from_session(self).names()
468 }
469
470 /// Return a stored tool artifact by URI, if it exists in this session.
471 pub fn get_artifact(&self, artifact_uri: &str) -> Option<crate::tools::ToolArtifact> {
472 DirectToolRuntime::from_session(self).artifact(artifact_uri)
473 }
474
475 /// Return compact execution trace events recorded for this session.
476 pub fn trace_events(&self) -> Vec<crate::trace::TraceEvent> {
477 SessionView::from_session(self).trace_events()
478 }
479
480 /// Save the session to the configured store.
481 ///
482 /// Returns `Ok(())` if saved successfully, or if no store is configured (no-op).
483 pub async fn save(&self) -> Result<()> {
484 session_save::save(self).await
485 }
486}