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