a3s_code_core/agent_api.rs
1//! Agent Facade API
2//!
3//! High-level, ergonomic API for using A3S Code as an embedded library.
4//!
5//! ## Example
6//!
7//! ```rust,no_run
8//! use a3s_code_core::Agent;
9//!
10//! # async fn run() -> anyhow::Result<()> {
11//! let agent = Agent::new("agent.acl").await?;
12//! let session = agent.session("/my-project", None)?;
13//! let result = session.send("Explain the auth module", None).await?;
14//! println!("{}", result.text);
15//! # Ok(())
16//! # }
17//! ```
18
19use crate::agent::{AgentConfig, AgentEvent, AgentResult};
20use crate::commands::CommandRegistry;
21use crate::config::CodeConfig;
22use crate::error::Result;
23use crate::hitl::PendingConfirmationInfo;
24use crate::llm::{LlmClient, Message};
25use crate::prompts::{PlanningMode, SystemPromptSlots};
26use crate::queue::{
27 ExternalTask, ExternalTaskResult, LaneHandlerConfig, SessionLane, SessionQueueConfig,
28 SessionQueueStats,
29};
30use crate::tools::{ToolContext, ToolExecutor};
31use a3s_lane::{DeadLetter, MetricsSnapshot};
32use a3s_memory::MemoryStore;
33use std::collections::HashMap;
34use std::path::{Path, PathBuf};
35use std::sync::{Arc, RwLock};
36use tokio::sync::mpsc;
37use tokio::task::JoinHandle;
38mod agent_binding;
39mod agent_bootstrap;
40mod agent_loop_runtime;
41mod agent_sessions;
42mod capabilities;
43mod command_runtime;
44mod conversation_runtime;
45mod direct_tools;
46mod hook_control;
47mod run_lifecycle;
48mod runtime;
49mod runtime_events;
50mod session_builder;
51mod session_clock;
52mod session_commands;
53mod session_config;
54mod session_extensions;
55mod session_hitl;
56mod session_options;
57mod session_persistence;
58mod session_queue;
59mod session_runs;
60mod session_runtime;
61mod session_save;
62mod session_verification;
63mod session_view;
64use direct_tools::DirectToolRuntime;
65use hook_control::HookControl;
66use runtime_events::ActiveToolState;
67use session_extensions::SessionExtensionRuntime;
68use session_hitl::HitlControl;
69use session_queue::QueueControl;
70use session_runs::RunControl;
71use session_verification::VerificationRuntime;
72use session_view::SessionView;
73
74/// Canonicalize a path, stripping the Windows `\\?\` UNC prefix to avoid
75/// polluting workspace strings throughout the system (prompts, session data, etc.).
76fn safe_canonicalize(path: &Path) -> PathBuf {
77 match std::fs::canonicalize(path) {
78 Ok(p) => strip_unc_prefix(p),
79 Err(_) => path.to_path_buf(),
80 }
81}
82
83/// Strip the Windows extended-length path prefix (`\\?\`) that `canonicalize()` adds.
84/// On non-Windows this is a no-op.
85fn strip_unc_prefix(path: PathBuf) -> PathBuf {
86 #[cfg(windows)]
87 {
88 let s = path.to_string_lossy();
89 if let Some(stripped) = s.strip_prefix(r"\\?\") {
90 return PathBuf::from(stripped);
91 }
92 }
93 path
94}
95
96// ============================================================================
97// ToolCallResult
98// ============================================================================
99
100/// Result of a direct tool execution (no LLM).
101#[derive(Debug, Clone)]
102pub struct ToolCallResult {
103 pub name: String,
104 pub output: String,
105 pub exit_code: i32,
106 pub metadata: Option<serde_json::Value>,
107}
108
109// ============================================================================
110// SessionOptions
111// ============================================================================
112
113/// Optional per-session overrides.
114#[derive(Clone, Default)]
115pub struct SessionOptions {
116 /// Override the default model. Format: `"provider/model"` (e.g., `"openai/gpt-4o"`).
117 pub model: Option<String>,
118 /// Extra directories to scan for agent files.
119 /// Merged with any global `agent_dirs` from [`CodeConfig`].
120 pub agent_dirs: Vec<PathBuf>,
121 /// Reproducible disposable workers registered for task delegation.
122 /// Explicit session workers override agents loaded from directories by name.
123 pub worker_agents: Vec<crate::subagent::WorkerAgentSpec>,
124 /// Optional queue configuration for lane-based tool execution.
125 ///
126 /// When set, enables priority-based tool scheduling with parallel execution
127 /// of read-only (Query-lane) tools, DLQ, metrics, and external task handling.
128 pub queue_config: Option<SessionQueueConfig>,
129 /// Optional security provider for taint tracking and output sanitization
130 pub security_provider: Option<Arc<dyn crate::security::SecurityProvider>>,
131 /// Optional context providers for RAG
132 pub context_providers: Vec<Arc<dyn crate::context::ContextProvider>>,
133 /// Optional confirmation manager for HITL
134 pub confirmation_manager: Option<Arc<dyn crate::hitl::ConfirmationProvider>>,
135 /// Optional confirmation policy (will be used to create ConfirmationManager if confirmation_manager is not set)
136 pub confirmation_policy: Option<crate::hitl::ConfirmationPolicy>,
137 /// Optional permission checker
138 pub permission_checker: Option<Arc<dyn crate::permissions::PermissionChecker>>,
139 /// Serializable permission policy used to build the checker, when available.
140 pub permission_policy: Option<crate::permissions::PermissionPolicy>,
141 /// Enable planning
142 pub planning_mode: PlanningMode,
143 /// Enable goal tracking
144 pub goal_tracking: bool,
145 /// Extra directories to scan for skill files (*.md).
146 /// Merged with any global `skill_dirs` from [`CodeConfig`].
147 pub skill_dirs: Vec<PathBuf>,
148 /// Optional skill registry for instruction injection
149 pub skill_registry: Option<Arc<crate::skills::SkillRegistry>>,
150 /// Optional memory store for long-term memory persistence
151 pub memory_store: Option<Arc<dyn MemoryStore>>,
152 /// Deferred file memory directory — constructed async in `build_session()`
153 pub(crate) file_memory_dir: Option<PathBuf>,
154 /// Optional session store for persistence
155 pub session_store: Option<Arc<dyn crate::store::SessionStore>>,
156 /// Explicit session ID (auto-generated if not set)
157 pub session_id: Option<String>,
158 /// Auto-save after each completed `send()` or default-history `stream()` call.
159 pub auto_save: bool,
160 /// Optional artifact retention limits for large tool/program outputs.
161 pub artifact_store_limits: Option<crate::tools::ArtifactStoreLimits>,
162 /// Max consecutive parse errors before aborting (overrides default of 2).
163 /// `None` uses the `AgentConfig` default.
164 pub max_parse_retries: Option<u32>,
165 /// Per-tool execution timeout in milliseconds.
166 /// `None` = no timeout (default).
167 pub tool_timeout_ms: Option<u64>,
168 /// Circuit-breaker threshold: max consecutive LLM API failures before
169 /// aborting in non-streaming mode (overrides default of 3).
170 /// `None` uses the `AgentConfig` default.
171 pub circuit_breaker_threshold: Option<u32>,
172 /// Optional concrete sandbox implementation.
173 ///
174 /// When set, `bash` tool commands are routed through this sandbox instead
175 /// of `std::process::Command`. The host application constructs and owns
176 /// the implementation (e.g., an A3S Box–backed handle).
177 pub sandbox_handle: Option<Arc<dyn crate::sandbox::BashSandbox>>,
178 /// Optional host-provided workspace backend.
179 ///
180 /// When set, built-in tools such as `read`, `write`, `ls`, and `bash`
181 /// execute against these workspace capabilities instead of assuming the
182 /// server-local filesystem. This is the primary extension point for DFS,
183 /// browser, container, and remote workspace deployments.
184 pub workspace_services: Option<Arc<crate::workspace::WorkspaceServices>>,
185 /// Enable auto-compaction when context usage exceeds threshold.
186 pub auto_compact: bool,
187 /// Context usage percentage threshold for auto-compaction (0.0 - 1.0).
188 /// Default: 0.80 (80%).
189 pub auto_compact_threshold: Option<f32>,
190 /// Inject a continuation message when the LLM stops without completing the task.
191 /// `None` uses the `AgentConfig` default (true).
192 pub continuation_enabled: Option<bool>,
193 /// Maximum continuation injections per execution.
194 /// `None` uses the `AgentConfig` default (3).
195 pub max_continuation_turns: Option<u32>,
196 /// Maximum execution time in milliseconds.
197 /// `None` = no timeout (default).
198 /// When set, the execution loop will abort if it exceeds this duration.
199 pub max_execution_time_ms: Option<u64>,
200 /// Optional MCP manager for connecting to external MCP servers.
201 ///
202 /// When set, all tools from connected MCP servers are registered and
203 /// available during agent execution with names like `mcp__server__tool`.
204 pub mcp_manager: Option<Arc<crate::mcp::manager::McpManager>>,
205 /// Sampling temperature (0.0–1.0). Overrides the provider default.
206 pub temperature: Option<f32>,
207 /// Extended thinking budget in tokens (Anthropic only).
208 pub thinking_budget: Option<usize>,
209 /// Per-session tool round limit override.
210 ///
211 /// When set, overrides the agent-level `max_tool_rounds` for this session only.
212 /// Maps directly from [`AgentDefinition::max_steps`] when creating sessions
213 /// via [`Agent::session_for_agent`].
214 pub max_tool_rounds: Option<usize>,
215 /// Slot-based system prompt customization.
216 ///
217 /// When set, overrides the agent-level prompt slots for this session.
218 /// Users can customize role, guidelines, response style, and extra instructions
219 /// without losing the core agentic capabilities.
220 pub prompt_slots: Option<SystemPromptSlots>,
221 /// Optional external hook executor (e.g. an AHP harness server).
222 ///
223 /// When set, **replaces** the built-in `HookEngine` for this session.
224 /// All 11 lifecycle events are forwarded to the executor instead of being
225 /// dispatched locally. The executor is also propagated to sub-agents via
226 /// the sentinel hook mechanism.
227 pub hook_executor: Option<Arc<dyn crate::hooks::HookExecutor>>,
228}
229
230// ============================================================================
231// Agent
232// ============================================================================
233
234/// High-level agent facade.
235///
236/// Holds the LLM client and agent config. Workspace-independent.
237/// Use [`Agent::session()`] to bind to a workspace.
238pub struct Agent {
239 code_config: CodeConfig,
240 config: AgentConfig,
241 /// Global MCP manager loaded from config.mcp_servers
242 global_mcp: Option<Arc<crate::mcp::manager::McpManager>>,
243 /// Pre-fetched MCP tool definitions from global_mcp (cached at creation time).
244 /// Wrapped in Mutex so `refresh_mcp_tools()` can update the cache without `&mut self`.
245 global_mcp_tools: std::sync::Mutex<Vec<(String, crate::mcp::McpTool)>>,
246}
247
248impl std::fmt::Debug for Agent {
249 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
250 f.debug_struct("Agent").finish()
251 }
252}
253
254impl Agent {
255 /// Create from a config file path or inline ACL-compatible string.
256 ///
257 /// Auto-detects `.acl` file paths vs inline ACL-compatible config.
258 pub async fn new(config_source: impl Into<String>) -> Result<Self> {
259 let config = agent_bootstrap::load_code_config(config_source.into())?;
260 Self::from_config(config).await
261 }
262
263 /// Create from a config file path or inline ACL-compatible string.
264 ///
265 /// Alias for [`Agent::new()`] — provides a consistent API with
266 /// the Python and Node.js SDKs.
267 pub async fn create(config_source: impl Into<String>) -> Result<Self> {
268 Self::new(config_source).await
269 }
270
271 /// Create from a [`CodeConfig`] struct.
272 pub async fn from_config(config: CodeConfig) -> Result<Self> {
273 agent_bootstrap::build_agent_from_config(config).await
274 }
275
276 /// Re-fetch tool definitions from all connected global MCP servers and
277 /// update the internal cache.
278 ///
279 /// Call this when an MCP server has added or removed tools since the
280 /// agent was created. The refreshed tools will be visible to all
281 /// **new** sessions created after this call; existing sessions are
282 /// unaffected (their `ToolExecutor` snapshot is already built).
283 pub async fn refresh_mcp_tools(&self) -> Result<()> {
284 agent_sessions::refresh_mcp_tools(self).await
285 }
286
287 /// Bind to a workspace directory, returning an [`AgentSession`].
288 ///
289 /// Pass `None` for defaults, or `Some(SessionOptions)` to override
290 /// the model, agent directories for this session.
291 pub fn session(
292 &self,
293 workspace: impl Into<String>,
294 options: Option<SessionOptions>,
295 ) -> Result<AgentSession> {
296 agent_sessions::create_session(self, workspace, options)
297 }
298
299 /// Create a session pre-configured from an [`AgentDefinition`].
300 ///
301 /// Maps the definition's `permissions`, `prompt`, `model`, and `max_steps`
302 /// directly into [`SessionOptions`], so markdown/YAML-defined subagents can
303 /// be used by delegation and advanced control-plane flows without manual wiring.
304 ///
305 /// The mapping follows the same logic as the built-in `task` tool:
306 /// - `permissions` → `permission_checker`
307 /// - `prompt` → `prompt_slots.extra`
308 /// - `max_steps` → `max_tool_rounds`
309 /// - `model` → `model` (as `"provider/model"` string)
310 ///
311 /// `extra` can supply additional overrides (e.g. `planning_enabled`) that
312 /// take precedence over the definition's values.
313 pub fn session_for_agent(
314 &self,
315 workspace: impl Into<String>,
316 def: &crate::subagent::AgentDefinition,
317 extra: Option<SessionOptions>,
318 ) -> Result<AgentSession> {
319 agent_sessions::create_session_for_agent(self, workspace, def, extra)
320 }
321
322 /// Create a session from a reproducible disposable worker recipe.
323 ///
324 /// This is the cattle-mode companion to [`Agent::session_for_agent`]: callers
325 /// provide a small [`WorkerAgentSpec`](crate::subagent::WorkerAgentSpec), and
326 /// A3S Code compiles it into the same runtime definition used by delegated agents.
327 pub fn session_for_worker(
328 &self,
329 workspace: impl Into<String>,
330 spec: crate::subagent::WorkerAgentSpec,
331 extra: Option<SessionOptions>,
332 ) -> Result<AgentSession> {
333 let def = spec.into_agent_definition();
334 self.session_for_agent(workspace, &def, extra)
335 }
336
337 /// Resume a previously saved session by ID.
338 ///
339 /// Loads the session data from the store, rebuilds the `AgentSession` with
340 /// the saved conversation history, and returns it ready for continued use.
341 ///
342 /// The `options` must include a `session_store` (or `with_file_session_store`)
343 /// that contains the saved session.
344 pub fn resume_session(
345 &self,
346 session_id: &str,
347 options: SessionOptions,
348 ) -> Result<AgentSession> {
349 agent_sessions::resume_session(self, session_id, options)
350 }
351
352 #[cfg(test)]
353 fn build_session(
354 &self,
355 workspace: String,
356 llm_client: Arc<dyn LlmClient>,
357 opts: &SessionOptions,
358 ) -> Result<AgentSession> {
359 session_builder::build_agent_session(self, workspace, llm_client, opts)
360 }
361}
362
363// ============================================================================
364// AgentSession
365// ============================================================================
366
367/// Workspace-bound session. All LLM and tool operations happen here.
368///
369/// History is automatically accumulated after each `send()` call and after
370/// `stream()` completes when no custom history is supplied.
371/// Use `history()` to retrieve the current conversation log.
372pub struct AgentSession {
373 llm_client: Arc<dyn LlmClient>,
374 tool_executor: Arc<ToolExecutor>,
375 tool_context: ToolContext,
376 config: AgentConfig,
377 workspace: PathBuf,
378 /// Unique session identifier.
379 session_id: String,
380 /// Internal conversation history, auto-updated after each `send()` and default-history `stream()`.
381 history: Arc<RwLock<Vec<Message>>>,
382 /// Optional lane queue for priority-based tool execution.
383 command_queue: Option<Arc<crate::session_lane_queue::SessionLaneQueue>>,
384 /// Optional long-term memory.
385 memory: Option<Arc<crate::memory::AgentMemory>>,
386 /// Optional session store for persistence.
387 session_store: Option<Arc<dyn crate::store::SessionStore>>,
388 /// Auto-save after each completed `send()` or default-history `stream()`.
389 auto_save: bool,
390 /// Hook engine for lifecycle event interception.
391 hook_engine: Arc<crate::hooks::HookEngine>,
392 /// Optional external hook executor (e.g. AHP harness). When set, replaces
393 /// `hook_engine` as the executor passed to each `AgentLoop`.
394 ahp_executor: Option<Arc<dyn crate::hooks::HookExecutor>>,
395 /// Deferred init warning: emitted as PersistenceFailed on first send() if set.
396 init_warning: Option<String>,
397 /// Slash command registry for `/command` dispatch.
398 /// Uses interior mutability so commands can be registered on a shared `Arc<AgentSession>`.
399 command_registry: std::sync::Mutex<CommandRegistry>,
400 /// Model identifier for display (e.g., "anthropic/claude-sonnet-4-20250514").
401 model_name: String,
402 /// Shared MCP manager — all add_mcp_server / remove_mcp_server calls go here.
403 mcp_manager: Arc<crate::mcp::manager::McpManager>,
404 /// Shared agent registry — populated at session creation; extended via register_agent_dir().
405 agent_registry: Arc<crate::subagent::AgentRegistry>,
406 /// Cancellation token for the current operation (send/stream).
407 /// Stored so that cancel() can abort ongoing LLM calls.
408 cancel_token: Arc<tokio::sync::Mutex<Option<tokio_util::sync::CancellationToken>>>,
409 /// ID of the run currently attached to the active cancellation token.
410 current_run_id: Arc<tokio::sync::Mutex<Option<String>>>,
411 /// In-memory run snapshots and event replay buffer for this session.
412 run_store: Arc<crate::run::InMemoryRunStore>,
413 /// Currently executing tools observed from runtime events.
414 active_tools: Arc<tokio::sync::RwLock<HashMap<String, ActiveToolState>>>,
415 /// Compact execution traces for this session.
416 trace_sink: crate::trace::InMemoryTraceSink,
417 /// Structured completion evidence collected from agent and explicit verification runs.
418 verification_reports: Arc<RwLock<Vec<crate::verification::VerificationReport>>>,
419}
420
421impl std::fmt::Debug for AgentSession {
422 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
423 f.debug_struct("AgentSession")
424 .field("session_id", &self.session_id)
425 .field("workspace", &self.workspace.display().to_string())
426 .field("auto_save", &self.auto_save)
427 .finish()
428 }
429}
430
431impl AgentSession {
432 /// Get a snapshot of command entries (name, description, optional usage).
433 ///
434 /// Acquires the command registry lock briefly and returns owned data.
435 pub fn command_registry(&self) -> std::sync::MutexGuard<'_, CommandRegistry> {
436 session_commands::registry(self)
437 }
438
439 /// Register a custom slash command.
440 ///
441 /// Takes `&self` so it can be called on a shared `Arc<AgentSession>`.
442 pub fn register_command(&self, cmd: Arc<dyn crate::commands::SlashCommand>) {
443 session_commands::register(self, cmd);
444 }
445
446 /// Cancel any active operation and release session resources.
447 pub async fn close(&self) {
448 let _ = self.cancel().await;
449 }
450
451 /// Send a prompt and wait for the complete response.
452 ///
453 /// When `history` is `None`, uses (and auto-updates) the session's
454 /// internal conversation history. When `Some`, uses the provided
455 /// history instead (the internal history is **not** modified).
456 ///
457 /// If the prompt starts with `/`, it is dispatched as a slash command
458 /// and the result is returned without calling the LLM.
459 pub async fn send(&self, prompt: &str, history: Option<&[Message]>) -> Result<AgentResult> {
460 conversation_runtime::send(self, prompt, history).await
461 }
462
463 /// Send a prompt with image attachments and wait for the complete response.
464 ///
465 /// Images are included as multi-modal content blocks in the user message.
466 /// Requires a vision-capable model (e.g., Claude Sonnet, GPT-4o).
467 pub async fn send_with_attachments(
468 &self,
469 prompt: &str,
470 attachments: &[crate::llm::Attachment],
471 history: Option<&[Message]>,
472 ) -> Result<AgentResult> {
473 conversation_runtime::send_with_attachments(self, prompt, attachments, history).await
474 }
475
476 /// Stream a prompt with image attachments.
477 ///
478 /// Images are included as multi-modal content blocks in the user message.
479 /// Requires a vision-capable model (e.g., Claude Sonnet, GPT-4o).
480 pub async fn stream_with_attachments(
481 &self,
482 prompt: &str,
483 attachments: &[crate::llm::Attachment],
484 history: Option<&[Message]>,
485 ) -> Result<(mpsc::Receiver<AgentEvent>, JoinHandle<()>)> {
486 conversation_runtime::stream_with_attachments(self, prompt, attachments, history).await
487 }
488
489 /// Send a prompt and stream events back.
490 ///
491 /// When `history` is `None`, uses the session's internal history
492 /// and updates it when the stream completes.
493 /// When `Some`, uses the provided history instead.
494 ///
495 /// If the prompt starts with `/`, it is dispatched as a slash command
496 /// and the result is emitted as a single `TextDelta` + `End` event.
497 pub async fn stream(
498 &self,
499 prompt: &str,
500 history: Option<&[Message]>,
501 ) -> Result<(mpsc::Receiver<AgentEvent>, JoinHandle<()>)> {
502 conversation_runtime::stream(self, prompt, history).await
503 }
504
505 /// Cancel the current ongoing operation (send/stream).
506 ///
507 /// If an operation is in progress, this will trigger cancellation of the LLM streaming
508 /// and tool execution. The operation will terminate as soon as possible.
509 ///
510 /// Returns `true` if an operation was cancelled, `false` if no operation was in progress.
511 pub async fn cancel(&self) -> bool {
512 RunControl::from_session(self).cancel_current().await
513 }
514
515 /// Cancel a specific run only if it is still the active run.
516 ///
517 /// This is useful for SDK callers that hold a previously observed run ID:
518 /// stale run IDs will not cancel a newer operation.
519 pub async fn cancel_run(&self, run_id: &str) -> bool {
520 RunControl::from_session(self).cancel_run(run_id).await
521 }
522
523 /// Return snapshots for runs recorded by this session.
524 pub async fn runs(&self) -> Vec<crate::run::RunSnapshot> {
525 RunControl::from_session(self).runs().await
526 }
527
528 /// Return a snapshot for a recorded run.
529 pub async fn run_snapshot(&self, run_id: &str) -> Option<crate::run::RunSnapshot> {
530 RunControl::from_session(self).run_snapshot(run_id).await
531 }
532
533 /// Return recorded runtime events for a run.
534 pub async fn run_events(&self, run_id: &str) -> Vec<crate::run::RunEventRecord> {
535 RunControl::from_session(self).run_events(run_id).await
536 }
537
538 /// Return a handle for the currently running operation, if any.
539 pub async fn current_run(&self) -> Option<crate::run::RunHandle> {
540 RunControl::from_session(self).current_run().await
541 }
542
543 /// Return active tool calls observed for the currently running operation.
544 pub async fn active_tools(&self) -> Vec<crate::run::ActiveToolSnapshot> {
545 SessionView::from_session(self).active_tools().await
546 }
547
548 /// Return a snapshot of the session's conversation history.
549 pub fn history(&self) -> Vec<Message> {
550 SessionView::from_session(self).history()
551 }
552
553 /// Return pending HITL tool confirmations for this session.
554 pub async fn pending_confirmations(&self) -> Vec<PendingConfirmationInfo> {
555 HitlControl::from_session(self)
556 .pending_confirmations()
557 .await
558 }
559
560 /// Resolve a pending HITL tool confirmation.
561 ///
562 /// Returns `Ok(true)` when a pending confirmation was found and completed,
563 /// `Ok(false)` when the tool ID is not pending or HITL is not configured.
564 pub async fn confirm_tool_use(
565 &self,
566 tool_id: &str,
567 approved: bool,
568 reason: Option<String>,
569 ) -> Result<bool> {
570 HitlControl::from_session(self)
571 .confirm_tool_use(tool_id, approved, reason)
572 .await
573 }
574
575 /// Cancel all pending HITL confirmations for this session.
576 pub async fn cancel_confirmations(&self) -> usize {
577 HitlControl::from_session(self).cancel_confirmations().await
578 }
579
580 /// Return a reference to the session's memory, if configured.
581 pub fn memory(&self) -> Option<&Arc<crate::memory::AgentMemory>> {
582 SessionView::from_session(self).memory()
583 }
584
585 /// Return the session ID.
586 pub fn id(&self) -> &str {
587 SessionView::from_session(self).id()
588 }
589
590 /// Return the session workspace path.
591 pub fn workspace(&self) -> &std::path::Path {
592 SessionView::from_session(self).workspace()
593 }
594
595 /// Return any deferred init warning (e.g. memory store failed to initialize).
596 pub fn init_warning(&self) -> Option<&str> {
597 SessionView::from_session(self).init_warning()
598 }
599
600 /// Return the session ID.
601 pub fn session_id(&self) -> &str {
602 SessionView::from_session(self).id()
603 }
604
605 /// Return the definitions of all tools currently registered in this session.
606 ///
607 /// The list reflects the live state of the tool executor — tools added via
608 /// `add_mcp_server()` appear immediately; tools removed via
609 /// `remove_mcp_server()` disappear immediately.
610 pub fn tool_definitions(&self) -> Vec<crate::llm::ToolDefinition> {
611 DirectToolRuntime::from_session(self).definitions()
612 }
613
614 /// Return the names of all tools currently registered on this session.
615 ///
616 /// Equivalent to `tool_definitions().into_iter().map(|t| t.name).collect()`.
617 /// Tools added via [`add_mcp_server`] appear immediately; tools removed via
618 /// [`remove_mcp_server`] disappear immediately.
619 pub fn tool_names(&self) -> Vec<String> {
620 DirectToolRuntime::from_session(self).names()
621 }
622
623 /// Return a stored tool artifact by URI, if it exists in this session.
624 pub fn get_artifact(&self, artifact_uri: &str) -> Option<crate::tools::ToolArtifact> {
625 DirectToolRuntime::from_session(self).artifact(artifact_uri)
626 }
627
628 /// Return compact execution trace events recorded for this session.
629 pub fn trace_events(&self) -> Vec<crate::trace::TraceEvent> {
630 SessionView::from_session(self).trace_events()
631 }
632
633 /// Return structured verification reports recorded for this session.
634 pub fn verification_reports(&self) -> Vec<crate::verification::VerificationReport> {
635 VerificationRuntime::from_session(self).reports()
636 }
637
638 /// Return a structured summary of all verification reports recorded for this session.
639 pub fn verification_summary(&self) -> crate::verification::VerificationSummary {
640 VerificationRuntime::from_session(self).summary()
641 }
642
643 /// Return a concise human-readable verification summary for this session.
644 pub fn verification_summary_text(&self) -> String {
645 VerificationRuntime::from_session(self).summary_text()
646 }
647
648 /// Add externally produced verification reports to this session's completion evidence.
649 pub fn record_verification_reports(
650 &self,
651 reports: impl IntoIterator<Item = crate::verification::VerificationReport>,
652 ) {
653 VerificationRuntime::from_session(self).record(reports);
654 }
655
656 // ========================================================================
657 // Hook API
658 // ========================================================================
659
660 /// Register a hook for lifecycle event interception.
661 pub fn register_hook(&self, hook: crate::hooks::Hook) {
662 HookControl::from_session(self).register_hook(hook);
663 }
664
665 /// Unregister a hook by ID.
666 pub fn unregister_hook(&self, hook_id: &str) -> Option<crate::hooks::Hook> {
667 HookControl::from_session(self).unregister_hook(hook_id)
668 }
669
670 /// Register a handler for a specific hook.
671 pub fn register_hook_handler(
672 &self,
673 hook_id: &str,
674 handler: Arc<dyn crate::hooks::HookHandler>,
675 ) {
676 HookControl::from_session(self).register_hook_handler(hook_id, handler);
677 }
678
679 /// Unregister a hook handler by hook ID.
680 pub fn unregister_hook_handler(&self, hook_id: &str) {
681 HookControl::from_session(self).unregister_hook_handler(hook_id);
682 }
683
684 /// Get the number of registered hooks.
685 pub fn hook_count(&self) -> usize {
686 HookControl::from_session(self).hook_count()
687 }
688
689 /// Save the session to the configured store.
690 ///
691 /// Returns `Ok(())` if saved successfully, or if no store is configured (no-op).
692 pub async fn save(&self) -> Result<()> {
693 session_save::save(self).await
694 }
695
696 /// Read a file from the workspace.
697 pub async fn read_file(&self, path: &str) -> Result<String> {
698 DirectToolRuntime::from_session(self).read_file(path).await
699 }
700
701 /// Write a file in the workspace.
702 pub async fn write_file(&self, path: &str, content: &str) -> Result<ToolCallResult> {
703 DirectToolRuntime::from_session(self)
704 .write_file(path, content)
705 .await
706 }
707
708 /// List a directory in the workspace.
709 pub async fn ls(&self, path: Option<&str>) -> Result<ToolCallResult> {
710 DirectToolRuntime::from_session(self).ls(path).await
711 }
712
713 /// Edit a file by replacing text in the workspace.
714 pub async fn edit_file(
715 &self,
716 path: &str,
717 old_string: &str,
718 new_string: &str,
719 replace_all: bool,
720 ) -> Result<ToolCallResult> {
721 DirectToolRuntime::from_session(self)
722 .edit_file(path, old_string, new_string, replace_all)
723 .await
724 }
725
726 /// Apply a unified diff patch to a workspace file.
727 pub async fn patch_file(&self, path: &str, diff: &str) -> Result<ToolCallResult> {
728 DirectToolRuntime::from_session(self)
729 .patch_file(path, diff)
730 .await
731 }
732
733 /// Execute a bash command in the workspace.
734 ///
735 /// When a sandbox handle is configured via
736 /// [`SessionOptions::with_sandbox_handle()`], the command is routed through
737 /// that sandbox.
738 pub async fn bash(&self, command: &str) -> Result<String> {
739 DirectToolRuntime::from_session(self).bash(command).await
740 }
741
742 /// Run verification commands through the session's tool execution path.
743 pub async fn verify_commands(
744 &self,
745 subject: &str,
746 commands: &[crate::verification::VerificationCommand],
747 ) -> Result<crate::verification::VerificationReport> {
748 VerificationRuntime::from_session(self)
749 .verify_commands(subject, commands)
750 .await
751 }
752
753 /// Return project-aware verification command presets for this workspace.
754 pub fn verification_presets(&self) -> Vec<crate::verification::VerificationPreset> {
755 VerificationRuntime::from_session(self).presets()
756 }
757
758 /// Search for files matching a glob pattern.
759 pub async fn glob(&self, pattern: &str) -> Result<Vec<String>> {
760 DirectToolRuntime::from_session(self).glob(pattern).await
761 }
762
763 /// Search file contents with a regex pattern.
764 pub async fn grep(&self, pattern: &str) -> Result<String> {
765 DirectToolRuntime::from_session(self).grep(pattern).await
766 }
767
768 /// Execute a tool by name, bypassing the LLM.
769 pub async fn tool(&self, name: &str, args: serde_json::Value) -> Result<ToolCallResult> {
770 DirectToolRuntime::from_session(self).call(name, args).await
771 }
772
773 // ========================================================================
774 // Advanced optional Queue API
775 // ========================================================================
776
777 /// Returns whether this session has an advanced lane queue configured.
778 pub fn has_queue(&self) -> bool {
779 QueueControl::from_session(self).has_queue()
780 }
781
782 /// Configure a lane's handler mode for explicit external/hybrid dispatch.
783 ///
784 /// Only effective when a queue is configured via `SessionOptions::with_queue_config`.
785 pub async fn set_lane_handler(&self, lane: SessionLane, config: LaneHandlerConfig) {
786 QueueControl::from_session(self)
787 .set_lane_handler(lane, config)
788 .await;
789 }
790
791 /// Complete an external queue task by ID.
792 ///
793 /// Returns `true` if the task was found and completed, `false` if not found.
794 pub async fn complete_external_task(&self, task_id: &str, result: ExternalTaskResult) -> bool {
795 QueueControl::from_session(self)
796 .complete_external_task(task_id, result)
797 .await
798 }
799
800 /// Get pending external queue tasks awaiting completion by an external handler.
801 pub async fn pending_external_tasks(&self) -> Vec<ExternalTask> {
802 QueueControl::from_session(self)
803 .pending_external_tasks()
804 .await
805 }
806
807 /// Get optional queue statistics (pending, active, external counts per lane).
808 pub async fn queue_stats(&self) -> SessionQueueStats {
809 QueueControl::from_session(self).stats().await
810 }
811
812 /// Get a metrics snapshot from the optional queue (if metrics are enabled).
813 pub async fn queue_metrics(&self) -> Option<MetricsSnapshot> {
814 QueueControl::from_session(self).metrics().await
815 }
816
817 /// Get dead letters from the optional queue's DLQ (if DLQ is enabled).
818 pub async fn dead_letters(&self) -> Vec<DeadLetter> {
819 QueueControl::from_session(self).dead_letters().await
820 }
821
822 // ========================================================================
823 // MCP API
824 // ========================================================================
825
826 /// Register all agents found in a directory with the live session.
827 ///
828 /// Scans `dir` for `*.yaml`, `*.yml`, and `*.md` agent definition files,
829 /// parses them, and adds each one to the shared `AgentRegistry` used by the
830 /// `task` tool. New agents are immediately usable via `task(agent="…")` in
831 /// the same session — no restart required.
832 ///
833 /// Returns the number of agents successfully loaded from the directory.
834 pub fn register_agent_dir(&self, dir: &std::path::Path) -> usize {
835 SessionExtensionRuntime::from_session(self).register_agent_dir(dir)
836 }
837
838 /// Register a disposable worker agent with the live session.
839 ///
840 /// The returned definition is immediately available to the `task` tool by
841 /// worker name, so callers can create many reproducible workers without
842 /// writing temporary agent files or restarting the session.
843 pub fn register_worker_agent(
844 &self,
845 spec: crate::subagent::WorkerAgentSpec,
846 ) -> crate::subagent::AgentDefinition {
847 SessionExtensionRuntime::from_session(self).register_worker_agent(spec)
848 }
849
850 /// Register multiple disposable worker agents with the live session.
851 pub fn register_worker_agents<I>(&self, specs: I) -> Vec<crate::subagent::AgentDefinition>
852 where
853 I: IntoIterator<Item = crate::subagent::WorkerAgentSpec>,
854 {
855 SessionExtensionRuntime::from_session(self).register_worker_agents(specs)
856 }
857
858 /// Add an MCP server to this session.
859 ///
860 /// Registers, connects, and makes all tools immediately available for the
861 /// agent to call. Tool names follow the convention `mcp__<name>__<tool>`.
862 ///
863 /// Returns the number of tools registered from the server.
864 pub async fn add_mcp_server(
865 &self,
866 config: crate::mcp::McpServerConfig,
867 ) -> crate::error::Result<usize> {
868 SessionExtensionRuntime::from_session(self)
869 .add_mcp_server(config)
870 .await
871 }
872
873 /// Remove an MCP server from this session.
874 ///
875 /// Disconnects the server and unregisters all its tools from the executor.
876 /// No-op if the server was never added.
877 pub async fn remove_mcp_server(&self, server_name: &str) -> crate::error::Result<()> {
878 SessionExtensionRuntime::from_session(self)
879 .remove_mcp_server(server_name)
880 .await
881 }
882
883 /// Return the connection status of all MCP servers registered with this session.
884 pub async fn mcp_status(
885 &self,
886 ) -> std::collections::HashMap<String, crate::mcp::McpServerStatus> {
887 SessionExtensionRuntime::from_session(self)
888 .mcp_status()
889 .await
890 }
891}
892
893// ============================================================================
894// Tests
895// ============================================================================
896
897#[cfg(test)]
898mod tests;