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