Skip to main content

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