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_close;
53mod session_commands;
54mod session_config;
55mod session_extensions;
56mod session_hitl;
57mod session_options;
58mod session_persistence;
59mod session_queue;
60mod session_runs;
61mod session_runtime;
62mod session_save;
63mod session_verification;
64mod session_view;
65use direct_tools::DirectToolRuntime;
66use hook_control::HookControl;
67use runtime_events::ActiveToolState;
68use session_close::SessionCloseHandle;
69use session_extensions::SessionExtensionRuntime;
70use session_hitl::HitlControl;
71use session_queue::QueueControl;
72use session_runs::RunControl;
73use session_verification::VerificationRuntime;
74use session_view::SessionView;
75
76/// Canonicalize a path, stripping the Windows `\\?\` UNC prefix to avoid
77/// polluting workspace strings throughout the system (prompts, session data, etc.).
78fn safe_canonicalize(path: &Path) -> PathBuf {
79 match std::fs::canonicalize(path) {
80 Ok(p) => strip_unc_prefix(p),
81 Err(_) => path.to_path_buf(),
82 }
83}
84
85/// Strip the Windows extended-length path prefix (`\\?\`) that `canonicalize()` adds.
86/// On non-Windows this is a no-op.
87fn strip_unc_prefix(path: PathBuf) -> PathBuf {
88 #[cfg(windows)]
89 {
90 let s = path.to_string_lossy();
91 if let Some(stripped) = s.strip_prefix(r"\\?\") {
92 return PathBuf::from(stripped);
93 }
94 }
95 path
96}
97
98// ============================================================================
99// ToolCallResult
100// ============================================================================
101
102/// Result of a direct tool execution (no LLM).
103#[derive(Debug, Clone)]
104pub struct ToolCallResult {
105 pub name: String,
106 pub output: String,
107 pub exit_code: i32,
108 pub metadata: Option<serde_json::Value>,
109 /// Structured discriminant for tool failures. `None` when the tool
110 /// either succeeded or failed without a typed reason (the message in
111 /// `output` is then the only diagnostic). Populated for known
112 /// kinds such as `VersionConflict` so SDK callers can branch on the
113 /// `type` field instead of regex-matching `output`.
114 pub error_kind: Option<crate::tools::ToolErrorKind>,
115}
116
117// ============================================================================
118// SessionOptions
119// ============================================================================
120
121/// Optional per-session overrides.
122#[derive(Clone, Default)]
123pub struct SessionOptions {
124 /// Override the default model. Format: `"provider/model"` (e.g., `"openai/gpt-4o"`).
125 pub model: Option<String>,
126 /// Extra directories to scan for agent files.
127 /// Merged with any global `agent_dirs` from [`CodeConfig`].
128 pub agent_dirs: Vec<PathBuf>,
129 /// Reproducible disposable workers registered for task delegation.
130 /// Explicit session workers override agents loaded from directories by name.
131 pub worker_agents: Vec<crate::subagent::WorkerAgentSpec>,
132 /// Optional queue configuration for lane-based tool execution.
133 ///
134 /// When set, enables priority-based tool scheduling with parallel execution
135 /// of read-only (Query-lane) tools, DLQ, metrics, and external task handling.
136 pub queue_config: Option<SessionQueueConfig>,
137 /// Optional security provider for taint tracking and output sanitization
138 pub security_provider: Option<Arc<dyn crate::security::SecurityProvider>>,
139 /// Optional host-supplied LLM client.
140 ///
141 /// When set, it is used directly, overriding the `provider/model`
142 /// factory resolution — the one Action-layer backend that was previously
143 /// only injectable in test code. Lets a host plug in a provider the
144 /// built-in factory does not cover, a deterministic record/replay client,
145 /// or an HTTP-layer proxy/audit wrapper. Mirrors `workspace_services`.
146 pub llm_client: Option<Arc<dyn crate::llm::LlmClient>>,
147 /// Optional context providers for RAG
148 pub context_providers: Vec<Arc<dyn crate::context::ContextProvider>>,
149 /// Optional confirmation manager for HITL
150 pub confirmation_manager: Option<Arc<dyn crate::hitl::ConfirmationProvider>>,
151 /// Optional confirmation policy (will be used to create ConfirmationManager if confirmation_manager is not set)
152 pub confirmation_policy: Option<crate::hitl::ConfirmationPolicy>,
153 /// Optional permission checker
154 pub permission_checker: Option<Arc<dyn crate::permissions::PermissionChecker>>,
155 /// Serializable permission policy used to build the checker, when available.
156 pub permission_policy: Option<crate::permissions::PermissionPolicy>,
157 /// Enable planning
158 pub planning_mode: PlanningMode,
159 /// Enable goal tracking
160 pub goal_tracking: bool,
161 /// Extra directories to scan for skill files (*.md).
162 /// Merged with any global `skill_dirs` from [`CodeConfig`].
163 pub skill_dirs: Vec<PathBuf>,
164 /// Optional skill registry for instruction injection
165 pub skill_registry: Option<Arc<crate::skills::SkillRegistry>>,
166 /// Optional memory store for long-term memory persistence
167 pub memory_store: Option<Arc<dyn MemoryStore>>,
168 /// Deferred file memory directory — constructed async in `build_session()`
169 pub(crate) file_memory_dir: Option<PathBuf>,
170 /// Optional session store for persistence
171 pub session_store: Option<Arc<dyn crate::store::SessionStore>>,
172 /// Explicit session ID (auto-generated if not set)
173 pub session_id: Option<String>,
174 /// Multi-tenant identifier. Framework only transports this string;
175 /// the host decides what "tenant" means and how to
176 /// aggregate/bill on it. Emitted to hooks/traces, persisted in
177 /// `SessionData`, never interpreted by core.
178 pub tenant_id: Option<String>,
179 /// Identity of the principal that triggered this session (user id,
180 /// service account, etc). Treated as opaque.
181 pub principal: Option<String>,
182 /// Logical identifier of the agent template / definition the session
183 /// was instantiated from. Lets the host aggregate sessions by
184 /// "which agent recipe" independent of the concrete session id.
185 pub agent_template_id: Option<String>,
186 /// Distributed-trace correlation id. Propagated through hooks/traces
187 /// so a session's events join with upstream/downstream work in the
188 /// host's observability pipeline.
189 pub correlation_id: Option<String>,
190 /// Optional host-supplied budget / quota guard. The framework calls
191 /// into it before each LLM call (and reports actuals after) so the
192 /// host can refuse or rate-limit at the cluster level. Default is
193 /// `None` (no enforcement — equivalent to
194 /// [`NoopBudgetGuard`](crate::budget::NoopBudgetGuard)).
195 pub budget_guard: Option<Arc<dyn crate::budget::BudgetGuard>>,
196 /// Optional host-provided ID/Clock pair. Replaces the default
197 /// random-UUID + wall-clock pair, enabling deterministic replay
198 /// on another node. `None` keeps pre-P2 behaviour.
199 pub host_env: Option<Arc<crate::host_env::HostEnv>>,
200 /// Optional FIFO retention caps on the session's in-memory stores
201 /// (run records, run events, trace events, terminal subagent
202 /// tasks). `None` (default) keeps everything — fine for short
203 /// sessions, a memory leak for hours-long cluster workloads.
204 pub retention_limits: Option<crate::retention::SessionRetentionLimits>,
205 /// Auto-save after each completed `send()` or default-history `stream()` call.
206 pub auto_save: bool,
207 /// Optional artifact retention limits for large tool/program outputs.
208 pub artifact_store_limits: Option<crate::tools::ArtifactStoreLimits>,
209 /// Max consecutive parse errors before aborting (overrides default of 2).
210 /// `None` uses the `AgentConfig` default.
211 pub max_parse_retries: Option<u32>,
212 /// Per-tool execution timeout in milliseconds.
213 /// `None` = no timeout (default).
214 pub tool_timeout_ms: Option<u64>,
215 /// Circuit-breaker threshold: max consecutive LLM API failures before
216 /// aborting in non-streaming mode (overrides default of 3).
217 /// `None` uses the `AgentConfig` default.
218 pub circuit_breaker_threshold: Option<u32>,
219 /// Optional concrete sandbox implementation.
220 ///
221 /// When set, `bash` tool commands are routed through this sandbox instead
222 /// of `std::process::Command`. The host application constructs and owns
223 /// the implementation (e.g., an A3S Box–backed handle).
224 pub sandbox_handle: Option<Arc<dyn crate::sandbox::BashSandbox>>,
225 /// Optional host-provided workspace backend.
226 ///
227 /// When set, built-in tools such as `read`, `write`, `ls`, and `bash`
228 /// execute against these workspace capabilities instead of assuming the
229 /// server-local filesystem. This is the primary extension point for DFS,
230 /// browser, container, and remote workspace deployments.
231 pub workspace_services: Option<Arc<crate::workspace::WorkspaceServices>>,
232 /// Enable auto-compaction when context usage exceeds threshold.
233 pub auto_compact: bool,
234 /// Context usage percentage threshold for auto-compaction (0.0 - 1.0).
235 /// Default: 0.80 (80%).
236 pub auto_compact_threshold: Option<f32>,
237 /// Inject a continuation message when the LLM stops without completing the task.
238 /// `None` uses the `AgentConfig` default (true).
239 pub continuation_enabled: Option<bool>,
240 /// Maximum continuation injections per execution.
241 /// `None` uses the `AgentConfig` default (3).
242 pub max_continuation_turns: Option<u32>,
243 /// Maximum execution time in milliseconds.
244 /// `None` = no timeout (default).
245 /// When set, the execution loop will abort if it exceeds this duration.
246 pub max_execution_time_ms: Option<u64>,
247 /// Optional MCP manager for connecting to external MCP servers.
248 ///
249 /// When set, all tools from connected MCP servers are registered and
250 /// available during agent execution with names like `mcp__server__tool`.
251 pub mcp_manager: Option<Arc<crate::mcp::manager::McpManager>>,
252 /// Sampling temperature (0.0–1.0). Overrides the provider default.
253 pub temperature: Option<f32>,
254 /// Extended thinking budget in tokens (Anthropic only).
255 pub thinking_budget: Option<usize>,
256 /// Per-session tool round limit override.
257 ///
258 /// When set, overrides the agent-level `max_tool_rounds` for this session only.
259 /// Maps directly from [`AgentDefinition::max_steps`] when creating sessions
260 /// via [`Agent::session_for_agent`].
261 pub max_tool_rounds: Option<usize>,
262 /// Per-session parallel fan-out limit override.
263 ///
264 /// Applies to delegated `parallel_task`, plan wave execution, and safe
265 /// parallel write batches.
266 pub max_parallel_tasks: Option<usize>,
267 /// Per-session automatic subagent delegation override.
268 pub auto_delegation: Option<crate::config::AutoDelegationConfig>,
269 /// Per-session kill switch for automatic parallel child-agent fan-out.
270 ///
271 /// This overlays the effective automatic delegation config instead of
272 /// replacing it, so callers can disable auto fan-out without disabling
273 /// automatic delegation itself.
274 pub auto_parallel_delegation: Option<bool>,
275 /// Slot-based system prompt customization.
276 ///
277 /// When set, overrides the agent-level prompt slots for this session.
278 /// Users can customize role, guidelines, response style, and extra instructions
279 /// without losing the core agentic capabilities.
280 pub prompt_slots: Option<SystemPromptSlots>,
281 /// Optional external hook executor (e.g. an AHP harness server).
282 ///
283 /// When set, **replaces** the built-in `HookEngine` for this session.
284 /// All 11 lifecycle events are forwarded to the executor instead of being
285 /// dispatched locally. The executor is also propagated to sub-agents via
286 /// the sentinel hook mechanism.
287 pub hook_executor: Option<Arc<dyn crate::hooks::HookExecutor>>,
288}
289
290// ============================================================================
291// Agent
292// ============================================================================
293
294/// High-level agent facade.
295///
296/// Holds the LLM client and agent config. Workspace-independent.
297/// Use [`Agent::session()`] to bind to a workspace.
298pub struct Agent {
299 code_config: CodeConfig,
300 config: AgentConfig,
301 /// Global MCP manager loaded from config.mcp_servers
302 global_mcp: Option<Arc<crate::mcp::manager::McpManager>>,
303 /// Pre-fetched MCP tool definitions from global_mcp (cached at creation time).
304 /// Wrapped in Mutex so `refresh_mcp_tools()` can update the cache without `&mut self`.
305 global_mcp_tools: std::sync::Mutex<Vec<(String, crate::mcp::McpTool)>>,
306 /// Tracks every live session created by this agent via `Weak` refs so
307 /// the agent can enumerate and forcibly close them. Sessions register
308 /// themselves at construction and become dangling `Weak`s on drop —
309 /// `list_sessions()` / `close_session()` prune dead entries on access.
310 ///
311 /// Uses a synchronous lock so the sync `Agent::session()` factory can
312 /// insert without nesting tokio runtimes. The lock is only held for
313 /// brief insert/scan operations — async close work happens after the
314 /// lock is released.
315 sessions: Arc<std::sync::Mutex<HashMap<String, std::sync::Weak<SessionCloseHandle>>>>,
316 /// Set once `Agent::close()` has been called. Subsequent `session()` /
317 /// `resume_session()` calls fail fast with `CodeError::SessionClosed`.
318 closed: Arc<std::sync::atomic::AtomicBool>,
319}
320
321impl std::fmt::Debug for Agent {
322 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
323 f.debug_struct("Agent").finish()
324 }
325}
326
327impl Agent {
328 /// Create from a config file path or inline ACL-compatible string.
329 ///
330 /// Auto-detects `.acl` file paths vs inline ACL-compatible config.
331 pub async fn new(config_source: impl Into<String>) -> Result<Self> {
332 let config = agent_bootstrap::load_code_config(config_source.into())?;
333 Self::from_config(config).await
334 }
335
336 /// Create from a config file path or inline ACL-compatible string.
337 ///
338 /// Alias for [`Agent::new()`] — provides a consistent API with
339 /// the Python and Node.js SDKs.
340 pub async fn create(config_source: impl Into<String>) -> Result<Self> {
341 Self::new(config_source).await
342 }
343
344 /// Create from a [`CodeConfig`] struct.
345 pub async fn from_config(config: CodeConfig) -> Result<Self> {
346 agent_bootstrap::build_agent_from_config(config).await
347 }
348
349 /// Re-fetch tool definitions from all connected global MCP servers and
350 /// update the internal cache.
351 ///
352 /// Call this when an MCP server has added or removed tools since the
353 /// agent was created. The refreshed tools will be visible to all
354 /// **new** sessions created after this call; existing sessions are
355 /// unaffected (their `ToolExecutor` snapshot is already built).
356 pub async fn refresh_mcp_tools(&self) -> Result<()> {
357 agent_sessions::refresh_mcp_tools(self).await
358 }
359
360 /// Bind to a workspace directory, returning an [`AgentSession`].
361 ///
362 /// Pass `None` for defaults, or `Some(SessionOptions)` to override
363 /// the model, agent directories for this session.
364 pub fn session(
365 &self,
366 workspace: impl Into<String>,
367 options: Option<SessionOptions>,
368 ) -> Result<AgentSession> {
369 agent_sessions::create_session(self, workspace, options)
370 }
371
372 /// Create a session pre-configured from an [`AgentDefinition`].
373 ///
374 /// Maps the definition's `permissions`, `prompt`, `model`, and `max_steps`
375 /// directly into [`SessionOptions`], so markdown/YAML-defined subagents can
376 /// be used by delegation and advanced control-plane flows without manual wiring.
377 ///
378 /// The mapping follows the same logic as the built-in `task` tool:
379 /// - `permissions` → `permission_checker`
380 /// - `prompt` → `prompt_slots.extra`
381 /// - `max_steps` → `max_tool_rounds`
382 /// - `model` → `model` (as `"provider/model"` string)
383 ///
384 /// `extra` can supply additional overrides (e.g. `planning_enabled`) that
385 /// take precedence over the definition's values.
386 pub fn session_for_agent(
387 &self,
388 workspace: impl Into<String>,
389 def: &crate::subagent::AgentDefinition,
390 extra: Option<SessionOptions>,
391 ) -> Result<AgentSession> {
392 agent_sessions::create_session_for_agent(self, workspace, def, extra)
393 }
394
395 /// Create a session from a reproducible disposable worker recipe.
396 ///
397 /// This is the cattle-mode companion to [`Agent::session_for_agent`]: callers
398 /// provide a small [`WorkerAgentSpec`](crate::subagent::WorkerAgentSpec), and
399 /// A3S Code compiles it into the same runtime definition used by delegated agents.
400 pub fn session_for_worker(
401 &self,
402 workspace: impl Into<String>,
403 spec: crate::subagent::WorkerAgentSpec,
404 extra: Option<SessionOptions>,
405 ) -> Result<AgentSession> {
406 let def = spec.into_agent_definition();
407 self.session_for_agent(workspace, &def, extra)
408 }
409
410 /// Resume a previously saved session by ID.
411 ///
412 /// Loads the session data from the store, rebuilds the `AgentSession` with
413 /// the saved conversation history, and returns it ready for continued use.
414 ///
415 /// The `options` must include a `session_store` (or `with_file_session_store`)
416 /// that contains the saved session.
417 ///
418 /// The resumed session uses the **workspace stored in the snapshot**, not a
419 /// workspace from `options`. The store is therefore a trust boundary: its
420 /// contents drive the resumed workspace and the persisted runtime policies.
421 ///
422 /// Runtime: this loads the snapshot via `block_in_place`, so it must be called
423 /// on a multi-threaded Tokio runtime (it panics on a current-thread runtime).
424 pub fn resume_session(
425 &self,
426 session_id: &str,
427 options: SessionOptions,
428 ) -> Result<AgentSession> {
429 agent_sessions::resume_session(self, session_id, options)
430 }
431
432 /// Return the IDs of every live session created from this agent.
433 ///
434 /// "Live" means the caller still holds an [`AgentSession`] — sessions
435 /// that have been dropped are pruned lazily on each call. The list is
436 /// sorted to make output stable for tests/UIs.
437 pub async fn list_sessions(&self) -> Vec<String> {
438 agent_sessions::list_sessions(self).await
439 }
440
441 /// Close a specific live session by its session ID.
442 ///
443 /// Returns `true` when a live session with the given id was found and
444 /// transitioned from open to closed by this call; `false` when no live
445 /// session has that id, or when the session was already closed.
446 ///
447 /// This is the out-of-band counterpart to [`AgentSession::close`]: it
448 /// performs exactly the same cleanup but can be invoked without holding
449 /// a reference to the session itself — useful for control-plane code
450 /// that only knows the session ID.
451 pub async fn close_session(&self, session_id: &str) -> bool {
452 agent_sessions::close_session(self, session_id).await
453 }
454
455 /// Close every live session created from this agent and tear down
456 /// background resources owned by the agent (global MCP connections).
457 ///
458 /// After this call:
459 /// - Every live `AgentSession` is closed (same effect as calling
460 /// [`AgentSession::close`] on each).
461 /// - Subsequent [`Agent::session`] / [`Agent::resume_session`] calls
462 /// fail fast with [`CodeError::SessionClosed`](crate::error::CodeError::SessionClosed).
463 ///
464 /// Idempotent: subsequent calls are no-ops and are guaranteed not to
465 /// panic.
466 pub async fn close(&self) {
467 agent_sessions::close_agent(self).await
468 }
469
470 /// Return whether [`close`](Self::close) has been called on this agent.
471 pub fn is_closed(&self) -> bool {
472 self.closed.load(std::sync::atomic::Ordering::Acquire)
473 }
474
475 /// Disconnect every global MCP server whose last activity is older
476 /// than `idle_threshold_ms`. Returns the names of disconnected
477 /// servers (empty when there is no global MCP manager or when
478 /// nothing is idle).
479 ///
480 /// Hosts running thousands of long-lived sessions should call this
481 /// periodically (e.g. every 60s with a 5-min threshold) to release
482 /// file descriptors and background workers from quiet MCP servers
483 /// without losing the server's configuration. A subsequent tool
484 /// call on the same server will require an explicit reconnect.
485 pub async fn disconnect_idle_mcp(&self, idle_threshold_ms: u64) -> Vec<String> {
486 match &self.global_mcp {
487 Some(mcp) => mcp.disconnect_idle(idle_threshold_ms).await,
488 None => Vec::new(),
489 }
490 }
491
492 #[cfg(test)]
493 fn build_session(
494 &self,
495 workspace: String,
496 llm_client: Arc<dyn LlmClient>,
497 opts: &SessionOptions,
498 ) -> Result<AgentSession> {
499 session_builder::build_agent_session(self, workspace, llm_client, opts)
500 }
501}
502
503// ============================================================================
504// AgentSession
505// ============================================================================
506
507/// Workspace-bound session. All LLM and tool operations happen here.
508///
509/// History is automatically accumulated after each `send()` call and after
510/// `stream()` completes when no custom history is supplied.
511/// Use `history()` to retrieve the current conversation log.
512pub struct AgentSession {
513 llm_client: Arc<dyn LlmClient>,
514 tool_executor: Arc<ToolExecutor>,
515 tool_context: ToolContext,
516 config: AgentConfig,
517 workspace: PathBuf,
518 /// Unique session identifier.
519 session_id: String,
520 /// Internal conversation history, auto-updated after each `send()` and default-history `stream()`.
521 history: Arc<RwLock<Vec<Message>>>,
522 /// Optional lane queue for priority-based tool execution.
523 command_queue: Option<Arc<crate::session_lane_queue::SessionLaneQueue>>,
524 /// Optional long-term memory.
525 memory: Option<Arc<crate::memory::AgentMemory>>,
526 /// Optional session store for persistence.
527 session_store: Option<Arc<dyn crate::store::SessionStore>>,
528 /// Auto-save after each completed `send()` or default-history `stream()`.
529 auto_save: bool,
530 /// Hook engine for lifecycle event interception.
531 hook_engine: Arc<crate::hooks::HookEngine>,
532 /// Optional external hook executor (e.g. AHP harness). When set, replaces
533 /// `hook_engine` as the executor passed to each `AgentLoop`.
534 ahp_executor: Option<Arc<dyn crate::hooks::HookExecutor>>,
535 /// Deferred init warning: emitted as PersistenceFailed on first send() if set.
536 init_warning: Option<String>,
537 /// Slash command registry for `/command` dispatch.
538 /// Uses interior mutability so commands can be registered on a shared `Arc<AgentSession>`.
539 command_registry: std::sync::Mutex<CommandRegistry>,
540 /// Model identifier for display (e.g., "anthropic/claude-sonnet-4-20250514").
541 model_name: String,
542 /// Shared MCP manager — all add_mcp_server / remove_mcp_server calls go here.
543 mcp_manager: Arc<crate::mcp::manager::McpManager>,
544 /// Shared agent registry — populated at session creation; extended via register_agent_dir().
545 agent_registry: Arc<crate::subagent::AgentRegistry>,
546 /// Cancellation token for the current operation (send/stream).
547 /// Stored so that cancel() can abort ongoing LLM calls.
548 cancel_token: Arc<tokio::sync::Mutex<Option<tokio_util::sync::CancellationToken>>>,
549 /// ID of the run currently attached to the active cancellation token.
550 current_run_id: Arc<tokio::sync::Mutex<Option<String>>>,
551 /// In-memory run snapshots and event replay buffer for this session.
552 run_store: Arc<crate::run::InMemoryRunStore>,
553 /// Materialized view of delegated subagent task lifecycle, populated from runtime events.
554 subagent_tasks: Arc<crate::subagent_task_tracker::InMemorySubagentTaskTracker>,
555 /// Currently executing tools observed from runtime events.
556 active_tools: Arc<tokio::sync::RwLock<HashMap<String, ActiveToolState>>>,
557 /// Compact execution traces for this session.
558 trace_sink: crate::trace::InMemoryTraceSink,
559 /// Structured completion evidence collected from agent and explicit verification runs.
560 verification_reports: Arc<RwLock<Vec<crate::verification::VerificationReport>>>,
561 /// Set once `close()` has been called. Subsequent send/stream calls
562 /// fast-fail with [`crate::error::CodeError::SessionClosed`].
563 closed: Arc<std::sync::atomic::AtomicBool>,
564 /// Session-level parent cancellation token.
565 ///
566 /// Every in-flight run (blocking send, stream, delegated subagent task)
567 /// derives its per-operation token from this one via `child_token()`,
568 /// so `session_cancel.cancel()` cascades to all of them. `close()` fires
569 /// this token first, after which any new `child_token()` returns an
570 /// already-cancelled token (defending against close/spawn races).
571 pub(crate) session_cancel: tokio_util::sync::CancellationToken,
572 /// Shared `Arc`-handle used by both [`AgentSession::close`] and the
573 /// parent [`Agent`]'s registry. The handle bundles every field needed
574 /// to perform the close sequence so the two entry points cannot drift.
575 close_handle: Arc<SessionCloseHandle>,
576 /// Runtime-mutable override for the budget guard. When set, takes
577 /// precedence over `config.budget_guard` on the next agent-loop
578 /// build. Lets SDK callers (Node especially) install a host-side
579 /// guard after `session()` has returned without ever putting a
580 /// JS callable into `SessionOptions`.
581 runtime_budget_guard: std::sync::Mutex<Option<Arc<dyn crate::budget::BudgetGuard>>>,
582 /// Multi-tenant label. Framework only carries the string; semantics
583 /// belong to the host.
584 pub(crate) tenant_id: Option<String>,
585 /// Principal that triggered the session (user / service / etc.).
586 pub(crate) principal: Option<String>,
587 /// Logical identifier of the agent template the session was
588 /// instantiated from.
589 pub(crate) agent_template_id: Option<String>,
590 /// Distributed-trace correlation id propagated to hooks / traces.
591 pub(crate) correlation_id: Option<String>,
592}
593
594impl std::fmt::Debug for AgentSession {
595 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
596 f.debug_struct("AgentSession")
597 .field("session_id", &self.session_id)
598 .field("workspace", &self.workspace.display().to_string())
599 .field("auto_save", &self.auto_save)
600 .finish()
601 }
602}
603
604impl AgentSession {
605 /// Get a snapshot of command entries (name, description, optional usage).
606 ///
607 /// Acquires the command registry lock briefly and returns owned data.
608 pub fn command_registry(&self) -> std::sync::MutexGuard<'_, CommandRegistry> {
609 session_commands::registry(self)
610 }
611
612 /// Register a custom slash command.
613 ///
614 /// Takes `&self` so it can be called on a shared `Arc<AgentSession>`.
615 pub fn register_command(&self, cmd: Arc<dyn crate::commands::SlashCommand>) {
616 session_commands::register(self, cmd);
617 }
618
619 /// Return whether [`close`](Self::close) has been called on this session.
620 ///
621 /// Once closed, `send`/`stream` and their attachment variants fast-fail
622 /// with [`crate::error::CodeError::SessionClosed`] instead of starting a
623 /// new run.
624 pub fn is_closed(&self) -> bool {
625 self.closed.load(std::sync::atomic::Ordering::Acquire)
626 }
627
628 /// Clone the session-level [`CancellationToken`](tokio_util::sync::CancellationToken).
629 ///
630 /// All in-flight runs derive their per-operation token from this one via
631 /// `child_token()`, so embedders can:
632 ///
633 /// - Observe the token (e.g. wire it into a host-side `select!`) to
634 /// react to session shutdown without polling [`is_closed`](Self::is_closed);
635 /// - Call `.cancel()` on it to abort every operation in the session
636 /// without going through `close()` (no run-store / hook side effects).
637 ///
638 /// For graceful shutdown prefer [`close`](Self::close), which also marks
639 /// runs as cancelled in the store and fires AHP hooks.
640 pub fn session_cancel_token(&self) -> tokio_util::sync::CancellationToken {
641 self.session_cancel.clone()
642 }
643
644 /// Return the host-defined tenant id, if any.
645 ///
646 /// The framework only transports this string — it never interprets
647 /// or enforces tenant boundaries itself. Use this from custom
648 /// `HookExecutor` / `PermissionChecker` / `BudgetGuard` impls to
649 /// route logic by tenant.
650 pub fn tenant_id(&self) -> Option<&str> {
651 self.tenant_id.as_deref()
652 }
653
654 /// Return the principal that triggered the session, if any.
655 pub fn principal(&self) -> Option<&str> {
656 self.principal.as_deref()
657 }
658
659 /// Return the id of the agent template/definition the session was
660 /// instantiated from, if any.
661 pub fn agent_template_id(&self) -> Option<&str> {
662 self.agent_template_id.as_deref()
663 }
664
665 /// Return the distributed-trace correlation id propagated through
666 /// this session's events, if any.
667 pub fn correlation_id(&self) -> Option<&str> {
668 self.correlation_id.as_deref()
669 }
670
671 /// Install or replace a runtime budget guard. Takes effect on the
672 /// next `send` / `stream` call (the guard is consulted at agent-
673 /// loop build time, not on the live execution). Setting `None`
674 /// clears the override so `config.budget_guard` takes over again.
675 ///
676 /// This is the entry point SDKs use to wire a host-supplied guard
677 /// after the session has already been constructed — useful when
678 /// the guard's transport (e.g. a JS callable) cannot live inside
679 /// the value-typed `SessionOptions`.
680 pub fn set_budget_guard(&self, guard: Option<Arc<dyn crate::budget::BudgetGuard>>) {
681 let mut slot = self
682 .runtime_budget_guard
683 .lock()
684 .unwrap_or_else(|p| p.into_inner());
685 *slot = guard;
686 }
687
688 /// Return the currently-installed runtime budget guard, if any.
689 /// `None` means the loop falls back to `config.budget_guard`.
690 pub fn budget_guard(&self) -> Option<Arc<dyn crate::budget::BudgetGuard>> {
691 self.runtime_budget_guard
692 .lock()
693 .unwrap_or_else(|p| p.into_inner())
694 .clone()
695 }
696
697 /// Proactively close the session and release its in-flight work.
698 ///
699 /// On the first call this:
700 /// 1. flips the session into the **closed** state so further `send`/`stream`
701 /// calls fast-fail with [`crate::error::CodeError::SessionClosed`];
702 /// 2. fires the session-level cancellation token so every derived
703 /// run/subagent token cascades to cancelled;
704 /// 3. marks the active run `Cancelled` in the run store and fires AHP
705 /// hook side effects;
706 /// 4. cancels every still-running delegated subagent task spawned from
707 /// this session;
708 /// 5. cancels all pending human-in-the-loop tool confirmations.
709 ///
710 /// Subsequent calls are no-ops and are guaranteed not to panic.
711 pub async fn close(&self) {
712 // Delegate to the shared handle so this entry point and
713 // `Agent::close_session(id)` cannot drift in behaviour.
714 self.close_handle.close().await;
715 }
716
717 /// Send a prompt and wait for the complete response.
718 ///
719 /// When `history` is `None`, uses (and auto-updates) the session's
720 /// internal conversation history. When `Some`, uses the provided
721 /// history instead (the internal history is **not** modified).
722 ///
723 /// If the prompt starts with `/`, it is dispatched as a slash command
724 /// and the result is returned without calling the LLM.
725 pub async fn send(&self, prompt: &str, history: Option<&[Message]>) -> Result<AgentResult> {
726 conversation_runtime::send(self, prompt, history).await
727 }
728
729 /// Resume a previously-checkpointed run on this session.
730 ///
731 /// Loads the latest [`LoopCheckpoint`](crate::loop_checkpoint::LoopCheckpoint)
732 /// stored under `checkpoint_run_id` and replays the agent loop from
733 /// that boundary state. A **new** run id is allocated for the
734 /// resumed work; the relationship between the old and new run is
735 /// host-tracked — the framework does not interpret
736 /// it.
737 ///
738 /// Returns an error when no `SessionStore` is configured on this
739 /// session, or when no checkpoint exists for `checkpoint_run_id`.
740 pub async fn resume_run(&self, checkpoint_run_id: &str) -> Result<AgentResult> {
741 conversation_runtime::resume_run(self, checkpoint_run_id).await
742 }
743
744 /// Send a prompt with image attachments and wait for the complete response.
745 ///
746 /// Images are included as multi-modal content blocks in the user message.
747 /// Requires a vision-capable model (e.g., Claude Sonnet, GPT-4o).
748 pub async fn send_with_attachments(
749 &self,
750 prompt: &str,
751 attachments: &[crate::llm::Attachment],
752 history: Option<&[Message]>,
753 ) -> Result<AgentResult> {
754 conversation_runtime::send_with_attachments(self, prompt, attachments, history).await
755 }
756
757 /// Stream a prompt with image attachments.
758 ///
759 /// Images are included as multi-modal content blocks in the user message.
760 /// Requires a vision-capable model (e.g., Claude Sonnet, GPT-4o).
761 pub async fn stream_with_attachments(
762 &self,
763 prompt: &str,
764 attachments: &[crate::llm::Attachment],
765 history: Option<&[Message]>,
766 ) -> Result<(mpsc::Receiver<AgentEvent>, JoinHandle<()>)> {
767 conversation_runtime::stream_with_attachments(self, prompt, attachments, history).await
768 }
769
770 /// Send a prompt and stream events back.
771 ///
772 /// When `history` is `None`, uses the session's internal history
773 /// and updates it when the stream completes.
774 /// When `Some`, uses the provided history instead.
775 ///
776 /// If the prompt starts with `/`, it is dispatched as a slash command
777 /// and the result is emitted as a single `TextDelta` + `End` event.
778 pub async fn stream(
779 &self,
780 prompt: &str,
781 history: Option<&[Message]>,
782 ) -> Result<(mpsc::Receiver<AgentEvent>, JoinHandle<()>)> {
783 conversation_runtime::stream(self, prompt, history).await
784 }
785
786 /// Cancel the current ongoing operation (send/stream).
787 ///
788 /// If an operation is in progress, this will trigger cancellation of the LLM streaming
789 /// and tool execution. The operation will terminate as soon as possible.
790 ///
791 /// Returns `true` if an operation was cancelled, `false` if no operation was in progress.
792 pub async fn cancel(&self) -> bool {
793 RunControl::from_session(self).cancel_current().await
794 }
795
796 /// Cancel a specific run only if it is still the active run.
797 ///
798 /// This is useful for SDK callers that hold a previously observed run ID:
799 /// stale run IDs will not cancel a newer operation.
800 pub async fn cancel_run(&self, run_id: &str) -> bool {
801 RunControl::from_session(self).cancel_run(run_id).await
802 }
803
804 /// Return snapshots for runs recorded by this session.
805 pub async fn runs(&self) -> Vec<crate::run::RunSnapshot> {
806 RunControl::from_session(self).runs().await
807 }
808
809 /// Return a snapshot for a recorded run.
810 pub async fn run_snapshot(&self, run_id: &str) -> Option<crate::run::RunSnapshot> {
811 RunControl::from_session(self).run_snapshot(run_id).await
812 }
813
814 /// Return recorded runtime events for a run.
815 pub async fn run_events(&self, run_id: &str) -> Vec<crate::run::RunEventRecord> {
816 RunControl::from_session(self).run_events(run_id).await
817 }
818
819 /// Return a handle for the currently running operation, if any.
820 pub async fn current_run(&self) -> Option<crate::run::RunHandle> {
821 RunControl::from_session(self).current_run().await
822 }
823
824 /// Return active tool calls observed for the currently running operation.
825 pub async fn active_tools(&self) -> Vec<crate::run::ActiveToolSnapshot> {
826 SessionView::from_session(self).active_tools().await
827 }
828
829 /// Look up a delegated subagent task by id. Returns `None` if no such task
830 /// has been observed in this session.
831 pub async fn subagent_task(
832 &self,
833 task_id: &str,
834 ) -> Option<crate::subagent_task_tracker::SubagentTaskSnapshot> {
835 self.subagent_tasks.get(task_id).await
836 }
837
838 /// Return snapshots of every delegated subagent task observed in this
839 /// session (including completed and failed ones), oldest first.
840 pub async fn subagent_tasks(&self) -> Vec<crate::subagent_task_tracker::SubagentTaskSnapshot> {
841 self.subagent_tasks.list_for_parent(&self.session_id).await
842 }
843
844 /// Return snapshots of subagent tasks still in `Running` state.
845 pub async fn pending_subagent_tasks(
846 &self,
847 ) -> Vec<crate::subagent_task_tracker::SubagentTaskSnapshot> {
848 use crate::subagent_task_tracker::SubagentStatus;
849 self.subagent_tasks
850 .list_for_parent(&self.session_id)
851 .await
852 .into_iter()
853 .filter(|task| task.status == SubagentStatus::Running)
854 .collect()
855 }
856
857 /// Cancel an in-flight delegated subagent task by id. Returns `true`
858 /// when a cancellation token was found and fired, `false` when the
859 /// task id is unknown or the task has already finished. The eventual
860 /// `SubagentEnd` from the cancelled child loop won't downgrade the
861 /// terminal status — it stays `Cancelled`.
862 pub async fn cancel_subagent_task(&self, task_id: &str) -> bool {
863 self.subagent_tasks.cancel(task_id).await
864 }
865
866 /// Return a shared handle to the session's subagent task tracker.
867 ///
868 /// Advanced: embedders implementing a custom subagent execution path
869 /// (i.e. spawning child loops outside the built-in `task` tool) can use
870 /// this to register cancellation tokens and feed `AgentEvent`s into the
871 /// tracker so the standard
872 /// [`subagent_task`](Self::subagent_task) / [`pending_subagent_tasks`](Self::pending_subagent_tasks) /
873 /// [`cancel_subagent_task`](Self::cancel_subagent_task) APIs and
874 /// [`close`](Self::close) keep working uniformly across execution paths.
875 pub fn subagent_tracker(
876 &self,
877 ) -> Arc<crate::subagent_task_tracker::InMemorySubagentTaskTracker> {
878 Arc::clone(&self.subagent_tasks)
879 }
880
881 /// Return a snapshot of the session's conversation history.
882 pub fn history(&self) -> Vec<Message> {
883 SessionView::from_session(self).history()
884 }
885
886 /// Return pending HITL tool confirmations for this session.
887 pub async fn pending_confirmations(&self) -> Vec<PendingConfirmationInfo> {
888 HitlControl::from_session(self)
889 .pending_confirmations()
890 .await
891 }
892
893 /// Resolve a pending HITL tool confirmation.
894 ///
895 /// Returns `Ok(true)` when a pending confirmation was found and completed,
896 /// `Ok(false)` when the tool ID is not pending or HITL is not configured.
897 pub async fn confirm_tool_use(
898 &self,
899 tool_id: &str,
900 approved: bool,
901 reason: Option<String>,
902 ) -> Result<bool> {
903 HitlControl::from_session(self)
904 .confirm_tool_use(tool_id, approved, reason)
905 .await
906 }
907
908 /// Cancel all pending HITL confirmations for this session.
909 pub async fn cancel_confirmations(&self) -> usize {
910 HitlControl::from_session(self).cancel_confirmations().await
911 }
912
913 /// Return a reference to the session's memory, if configured.
914 pub fn memory(&self) -> Option<&Arc<crate::memory::AgentMemory>> {
915 SessionView::from_session(self).memory()
916 }
917
918 /// Return the session ID.
919 pub fn id(&self) -> &str {
920 SessionView::from_session(self).id()
921 }
922
923 /// Return the session workspace path.
924 pub fn workspace(&self) -> &std::path::Path {
925 SessionView::from_session(self).workspace()
926 }
927
928 /// Return any deferred init warning (e.g. memory store failed to initialize).
929 pub fn init_warning(&self) -> Option<&str> {
930 SessionView::from_session(self).init_warning()
931 }
932
933 /// Return the session ID.
934 pub fn session_id(&self) -> &str {
935 SessionView::from_session(self).id()
936 }
937
938 /// An [`AgentExecutor`](crate::orchestration::AgentExecutor) backed by this
939 /// session — runs each orchestrated step as a child agent on this node,
940 /// inheriting the session's agent registry, LLM client, workspace, MCP
941 /// tools, and subagent tracker.
942 ///
943 /// This is what the orchestration combinators
944 /// ([`execute_steps_parallel`](crate::orchestration::execute_steps_parallel),
945 /// [`execute_pipeline`](crate::orchestration::execute_pipeline),
946 /// [`execute_steps_parallel_resumable`](crate::orchestration::execute_steps_parallel_resumable))
947 /// run against; a host can instead supply its own executor to place steps
948 /// across a cluster.
949 pub fn agent_executor(&self) -> Arc<dyn crate::orchestration::AgentExecutor> {
950 Arc::new(self.build_task_executor(self.parent_run_context()))
951 }
952
953 /// Build the in-box [`TaskExecutor`](crate::tools::TaskExecutor) for this
954 /// session, applying `parent` as the child-run capability context. Shared by
955 /// [`agent_executor`](Self::agent_executor) and [`workflow`](Self::workflow)
956 /// so both wire children identically.
957 fn build_task_executor(
958 &self,
959 parent: crate::child_run::ChildRunContext,
960 ) -> crate::tools::TaskExecutor {
961 crate::tools::TaskExecutor::with_mcp(
962 Arc::clone(&self.agent_registry),
963 Arc::clone(&self.llm_client),
964 self.workspace.display().to_string(),
965 Arc::clone(&self.mcp_manager),
966 )
967 .with_parent_context(parent)
968 .with_subagent_tracker(Arc::clone(&self.subagent_tasks))
969 .with_max_parallel_tasks(self.config.max_parallel_tasks)
970 }
971
972 /// A programmable [`Workflow`](crate::orchestration::Workflow) bound to this
973 /// session.
974 ///
975 /// Pre-wired with this session's executor (inheriting the same governance as
976 /// model-driven delegation), persistence store (so each
977 /// [`phase`](crate::orchestration::Workflow::phase) is a resume boundary),
978 /// per-step event stream, and a session-derived stable root id. Control flow
979 /// is ordinary Rust: `await` a verb, inspect the outcomes, decide what runs
980 /// next.
981 pub fn workflow(&self) -> crate::orchestration::Workflow {
982 self.workflow_with_token_budget(None)
983 }
984
985 /// Like [`workflow`](Self::workflow) but with a hard token ceiling shared
986 /// across every step. The cap is a best-effort *soft* cost ceiling — under a
987 /// wide fan-out a few in-flight turns can race past it before the shared
988 /// ledger catches up (see [`WorkflowBudget`](crate::orchestration::WorkflowBudget)).
989 pub fn workflow_with_token_budget(
990 &self,
991 limit_tokens: Option<u64>,
992 ) -> crate::orchestration::Workflow {
993 use crate::budget::BudgetGuard;
994
995 // One shared ledger for the whole workflow, wrapping the session's own
996 // budget guard (if any) so a host's per-tenant accounting keeps working.
997 let mut budget = crate::orchestration::WorkflowBudget::new(limit_tokens);
998 if let Some(inner) = self.config.budget_guard.clone() {
999 budget = budget.with_inner(inner);
1000 }
1001 let budget = Arc::new(budget);
1002
1003 // Install the shared ledger as the child runs' budget guard so every
1004 // step's per-turn LLM accounting feeds it.
1005 let mut parent = self.parent_run_context();
1006 parent.budget_guard = Some(Arc::clone(&budget) as Arc<dyn BudgetGuard>);
1007 let executor: Arc<dyn crate::orchestration::AgentExecutor> =
1008 Arc::new(self.build_task_executor(parent));
1009
1010 let mut builder = crate::orchestration::Workflow::builder(executor)
1011 .with_root_id(format!("wf-{}", self.session_id))
1012 .with_budget(Arc::clone(&budget));
1013 if let Some(store) = self.session_store.clone() {
1014 builder = builder.with_store(store);
1015 }
1016 if let Some(step_events) = self.tool_context.agent_event_tx.clone() {
1017 builder = builder.with_step_events(step_events);
1018 }
1019 builder.build()
1020 }
1021
1022 /// Build the [`ChildRunContext`](crate::child_run::ChildRunContext) that
1023 /// orchestrated / delegated child runs inherit from this session.
1024 ///
1025 /// Mirrors the context the model-driven `task` / `parallel_task` path
1026 /// installs (see `register_task_capability` in `agent_api/capabilities.rs`)
1027 /// so a step run through [`agent_executor`](Self::agent_executor) carries the
1028 /// SAME governance — security provider, skill restrictions, confirmation,
1029 /// the shared workspace, and the safety limits — instead of weaker, ambient
1030 /// authority. Sourced from the session's resolved config; `hook_engine`
1031 /// stays `None` to match the model-driven path.
1032 pub(crate) fn parent_run_context(&self) -> crate::child_run::ChildRunContext {
1033 crate::child_run::ChildRunContext {
1034 security_provider: self.config.security_provider.clone(),
1035 hook_engine: None,
1036 skill_registry: self.config.skill_registry.clone(),
1037 tool_timeout_ms: self.config.tool_timeout_ms,
1038 max_parallel_tasks: Some(self.config.max_parallel_tasks),
1039 max_execution_time_ms: self.config.max_execution_time_ms,
1040 circuit_breaker_threshold: Some(self.config.circuit_breaker_threshold),
1041 confirmation_manager: self.config.confirmation_manager.clone(),
1042 workspace_services: Some(Arc::clone(&self.tool_context.workspace_services)),
1043 budget_guard: self.config.budget_guard.clone(),
1044 }
1045 }
1046
1047 /// The session's persistence store, if one is configured — needed by the
1048 /// resumable orchestration combinator to journal workflow progress.
1049 pub fn session_store(&self) -> Option<Arc<dyn crate::store::SessionStore>> {
1050 self.session_store.clone()
1051 }
1052
1053 /// Return the definitions of all tools currently registered in this session.
1054 ///
1055 /// The list reflects the live state of the tool executor — tools added via
1056 /// `add_mcp_server()` appear immediately; tools removed via
1057 /// `remove_mcp_server()` disappear immediately.
1058 pub fn tool_definitions(&self) -> Vec<crate::llm::ToolDefinition> {
1059 DirectToolRuntime::from_session(self).definitions()
1060 }
1061
1062 /// Return the names of all tools currently registered on this session.
1063 ///
1064 /// Equivalent to `tool_definitions().into_iter().map(|t| t.name).collect()`.
1065 /// Tools added via [`add_mcp_server`] appear immediately; tools removed via
1066 /// [`remove_mcp_server`] disappear immediately.
1067 pub fn tool_names(&self) -> Vec<String> {
1068 DirectToolRuntime::from_session(self).names()
1069 }
1070
1071 /// Return a stored tool artifact by URI, if it exists in this session.
1072 pub fn get_artifact(&self, artifact_uri: &str) -> Option<crate::tools::ToolArtifact> {
1073 DirectToolRuntime::from_session(self).artifact(artifact_uri)
1074 }
1075
1076 /// Return compact execution trace events recorded for this session.
1077 pub fn trace_events(&self) -> Vec<crate::trace::TraceEvent> {
1078 SessionView::from_session(self).trace_events()
1079 }
1080
1081 /// Return structured verification reports recorded for this session.
1082 pub fn verification_reports(&self) -> Vec<crate::verification::VerificationReport> {
1083 VerificationRuntime::from_session(self).reports()
1084 }
1085
1086 /// Return a structured summary of all verification reports recorded for this session.
1087 pub fn verification_summary(&self) -> crate::verification::VerificationSummary {
1088 VerificationRuntime::from_session(self).summary()
1089 }
1090
1091 /// Return a concise human-readable verification summary for this session.
1092 pub fn verification_summary_text(&self) -> String {
1093 VerificationRuntime::from_session(self).summary_text()
1094 }
1095
1096 /// Add externally produced verification reports to this session's completion evidence.
1097 pub fn record_verification_reports(
1098 &self,
1099 reports: impl IntoIterator<Item = crate::verification::VerificationReport>,
1100 ) {
1101 VerificationRuntime::from_session(self).record(reports);
1102 }
1103
1104 // ========================================================================
1105 // Hook API
1106 // ========================================================================
1107
1108 /// Register a hook for lifecycle event interception.
1109 pub fn register_hook(&self, hook: crate::hooks::Hook) {
1110 HookControl::from_session(self).register_hook(hook);
1111 }
1112
1113 /// Unregister a hook by ID.
1114 pub fn unregister_hook(&self, hook_id: &str) -> Option<crate::hooks::Hook> {
1115 HookControl::from_session(self).unregister_hook(hook_id)
1116 }
1117
1118 /// Register a handler for a specific hook.
1119 pub fn register_hook_handler(
1120 &self,
1121 hook_id: &str,
1122 handler: Arc<dyn crate::hooks::HookHandler>,
1123 ) {
1124 HookControl::from_session(self).register_hook_handler(hook_id, handler);
1125 }
1126
1127 /// Unregister a hook handler by hook ID.
1128 pub fn unregister_hook_handler(&self, hook_id: &str) {
1129 HookControl::from_session(self).unregister_hook_handler(hook_id);
1130 }
1131
1132 /// Get the number of registered hooks.
1133 pub fn hook_count(&self) -> usize {
1134 HookControl::from_session(self).hook_count()
1135 }
1136
1137 /// Save the session to the configured store.
1138 ///
1139 /// Returns `Ok(())` if saved successfully, or if no store is configured (no-op).
1140 pub async fn save(&self) -> Result<()> {
1141 session_save::save(self).await
1142 }
1143
1144 /// Read a file from the workspace.
1145 pub async fn read_file(&self, path: &str) -> Result<String> {
1146 DirectToolRuntime::from_session(self).read_file(path).await
1147 }
1148
1149 /// Write a file in the workspace.
1150 pub async fn write_file(&self, path: &str, content: &str) -> Result<ToolCallResult> {
1151 DirectToolRuntime::from_session(self)
1152 .write_file(path, content)
1153 .await
1154 }
1155
1156 /// List a directory in the workspace.
1157 pub async fn ls(&self, path: Option<&str>) -> Result<ToolCallResult> {
1158 DirectToolRuntime::from_session(self).ls(path).await
1159 }
1160
1161 /// Edit a file by replacing text in the workspace.
1162 pub async fn edit_file(
1163 &self,
1164 path: &str,
1165 old_string: &str,
1166 new_string: &str,
1167 replace_all: bool,
1168 ) -> Result<ToolCallResult> {
1169 DirectToolRuntime::from_session(self)
1170 .edit_file(path, old_string, new_string, replace_all)
1171 .await
1172 }
1173
1174 /// Apply a unified diff patch to a workspace file.
1175 pub async fn patch_file(&self, path: &str, diff: &str) -> Result<ToolCallResult> {
1176 DirectToolRuntime::from_session(self)
1177 .patch_file(path, diff)
1178 .await
1179 }
1180
1181 /// Execute a bash command in the workspace.
1182 ///
1183 /// When a sandbox handle is configured via
1184 /// [`SessionOptions::with_sandbox_handle()`], the command is routed through
1185 /// that sandbox.
1186 pub async fn bash(&self, command: &str) -> Result<String> {
1187 DirectToolRuntime::from_session(self).bash(command).await
1188 }
1189
1190 /// Run verification commands through the session's tool execution path.
1191 pub async fn verify_commands(
1192 &self,
1193 subject: &str,
1194 commands: &[crate::verification::VerificationCommand],
1195 ) -> Result<crate::verification::VerificationReport> {
1196 VerificationRuntime::from_session(self)
1197 .verify_commands(subject, commands)
1198 .await
1199 }
1200
1201 /// Return project-aware verification command presets for this workspace.
1202 pub fn verification_presets(&self) -> Vec<crate::verification::VerificationPreset> {
1203 VerificationRuntime::from_session(self).presets()
1204 }
1205
1206 /// Search for files matching a glob pattern.
1207 pub async fn glob(&self, pattern: &str) -> Result<Vec<String>> {
1208 DirectToolRuntime::from_session(self).glob(pattern).await
1209 }
1210
1211 /// Search file contents with a regex pattern.
1212 pub async fn grep(&self, pattern: &str) -> Result<String> {
1213 DirectToolRuntime::from_session(self).grep(pattern).await
1214 }
1215
1216 /// Execute a tool by name, bypassing the LLM.
1217 pub async fn tool(&self, name: &str, args: serde_json::Value) -> Result<ToolCallResult> {
1218 DirectToolRuntime::from_session(self).call(name, args).await
1219 }
1220
1221 // ========================================================================
1222 // Advanced optional Queue API
1223 // ========================================================================
1224
1225 /// Returns whether this session has an advanced lane queue configured.
1226 pub fn has_queue(&self) -> bool {
1227 QueueControl::from_session(self).has_queue()
1228 }
1229
1230 /// Configure a lane's handler mode for explicit external/hybrid dispatch.
1231 ///
1232 /// Only effective when a queue is configured via `SessionOptions::with_queue_config`.
1233 pub async fn set_lane_handler(&self, lane: SessionLane, config: LaneHandlerConfig) {
1234 QueueControl::from_session(self)
1235 .set_lane_handler(lane, config)
1236 .await;
1237 }
1238
1239 /// Complete an external queue task by ID.
1240 ///
1241 /// Returns `true` if the task was found and completed, `false` if not found.
1242 pub async fn complete_external_task(&self, task_id: &str, result: ExternalTaskResult) -> bool {
1243 QueueControl::from_session(self)
1244 .complete_external_task(task_id, result)
1245 .await
1246 }
1247
1248 /// Get pending external queue tasks awaiting completion by an external handler.
1249 pub async fn pending_external_tasks(&self) -> Vec<ExternalTask> {
1250 QueueControl::from_session(self)
1251 .pending_external_tasks()
1252 .await
1253 }
1254
1255 /// Get optional queue statistics (pending, active, external counts per lane).
1256 pub async fn queue_stats(&self) -> SessionQueueStats {
1257 QueueControl::from_session(self).stats().await
1258 }
1259
1260 /// Get a metrics snapshot from the optional queue (if metrics are enabled).
1261 pub async fn queue_metrics(&self) -> Option<MetricsSnapshot> {
1262 QueueControl::from_session(self).metrics().await
1263 }
1264
1265 /// Get dead letters from the optional queue's DLQ (if DLQ is enabled).
1266 pub async fn dead_letters(&self) -> Vec<DeadLetter> {
1267 QueueControl::from_session(self).dead_letters().await
1268 }
1269
1270 // ========================================================================
1271 // MCP API
1272 // ========================================================================
1273
1274 /// Register all agents found in a directory with the live session.
1275 ///
1276 /// Scans `dir` for `*.yaml`, `*.yml`, and `*.md` agent definition files,
1277 /// parses them, and adds each one to the shared `AgentRegistry` used by the
1278 /// `task` tool. New agents are immediately usable via `task(agent="…")` in
1279 /// the same session — no restart required.
1280 ///
1281 /// Returns the number of agents successfully loaded from the directory.
1282 pub fn register_agent_dir(&self, dir: &std::path::Path) -> usize {
1283 SessionExtensionRuntime::from_session(self).register_agent_dir(dir)
1284 }
1285
1286 /// Register a disposable worker agent with the live session.
1287 ///
1288 /// The returned definition is immediately available to the `task` tool by
1289 /// worker name, so callers can create many reproducible workers without
1290 /// writing temporary agent files or restarting the session.
1291 pub fn register_worker_agent(
1292 &self,
1293 spec: crate::subagent::WorkerAgentSpec,
1294 ) -> crate::subagent::AgentDefinition {
1295 SessionExtensionRuntime::from_session(self).register_worker_agent(spec)
1296 }
1297
1298 /// Register multiple disposable worker agents with the live session.
1299 pub fn register_worker_agents<I>(&self, specs: I) -> Vec<crate::subagent::AgentDefinition>
1300 where
1301 I: IntoIterator<Item = crate::subagent::WorkerAgentSpec>,
1302 {
1303 SessionExtensionRuntime::from_session(self).register_worker_agents(specs)
1304 }
1305
1306 /// Add an MCP server to this session.
1307 ///
1308 /// Registers, connects, and makes all tools immediately available for the
1309 /// agent to call. Tool names follow the convention `mcp__<name>__<tool>`.
1310 ///
1311 /// Returns the number of tools registered from the server.
1312 pub async fn add_mcp_server(
1313 &self,
1314 config: crate::mcp::McpServerConfig,
1315 ) -> crate::error::Result<usize> {
1316 SessionExtensionRuntime::from_session(self)
1317 .add_mcp_server(config)
1318 .await
1319 }
1320
1321 /// The session's tool executor, for installing agent-dir `tools/` entries
1322 /// (e.g. a `kind = "script"` tool) into the live registry. Internal seam used
1323 /// by [`serve::install_agent_dir_tools`](crate::serve::install_agent_dir_tools)
1324 /// (the only caller, hence the `serve` gate).
1325 #[cfg(feature = "serve")]
1326 pub(crate) fn tool_executor(&self) -> &Arc<crate::tools::ToolExecutor> {
1327 &self.tool_executor
1328 }
1329
1330 /// Remove an MCP server from this session.
1331 ///
1332 /// Disconnects the server and unregisters all its tools from the executor.
1333 /// No-op if the server was never added.
1334 pub async fn remove_mcp_server(&self, server_name: &str) -> crate::error::Result<()> {
1335 SessionExtensionRuntime::from_session(self)
1336 .remove_mcp_server(server_name)
1337 .await
1338 }
1339
1340 /// Return the connection status of all MCP servers registered with this session.
1341 pub async fn mcp_status(
1342 &self,
1343 ) -> std::collections::HashMap<String, crate::mcp::McpServerStatus> {
1344 SessionExtensionRuntime::from_session(self)
1345 .mcp_status()
1346 .await
1347 }
1348}
1349
1350// ============================================================================
1351// Tests
1352// ============================================================================
1353
1354#[cfg(test)]
1355mod tests;