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 pub fn resume_session(
418 &self,
419 session_id: &str,
420 options: SessionOptions,
421 ) -> Result<AgentSession> {
422 agent_sessions::resume_session(self, session_id, options)
423 }
424
425 /// Return the IDs of every live session created from this agent.
426 ///
427 /// "Live" means the caller still holds an [`AgentSession`] — sessions
428 /// that have been dropped are pruned lazily on each call. The list is
429 /// sorted to make output stable for tests/UIs.
430 pub async fn list_sessions(&self) -> Vec<String> {
431 agent_sessions::list_sessions(self).await
432 }
433
434 /// Close a specific live session by its session ID.
435 ///
436 /// Returns `true` when a live session with the given id was found and
437 /// transitioned from open to closed by this call; `false` when no live
438 /// session has that id, or when the session was already closed.
439 ///
440 /// This is the out-of-band counterpart to [`AgentSession::close`]: it
441 /// performs exactly the same cleanup but can be invoked without holding
442 /// a reference to the session itself — useful for control-plane code
443 /// that only knows the session ID.
444 pub async fn close_session(&self, session_id: &str) -> bool {
445 agent_sessions::close_session(self, session_id).await
446 }
447
448 /// Close every live session created from this agent and tear down
449 /// background resources owned by the agent (global MCP connections).
450 ///
451 /// After this call:
452 /// - Every live `AgentSession` is closed (same effect as calling
453 /// [`AgentSession::close`] on each).
454 /// - Subsequent [`Agent::session`] / [`Agent::resume_session`] calls
455 /// fail fast with [`CodeError::SessionClosed`](crate::error::CodeError::SessionClosed).
456 ///
457 /// Idempotent: subsequent calls are no-ops and are guaranteed not to
458 /// panic.
459 pub async fn close(&self) {
460 agent_sessions::close_agent(self).await
461 }
462
463 /// Return whether [`close`](Self::close) has been called on this agent.
464 pub fn is_closed(&self) -> bool {
465 self.closed.load(std::sync::atomic::Ordering::Acquire)
466 }
467
468 /// Disconnect every global MCP server whose last activity is older
469 /// than `idle_threshold_ms`. Returns the names of disconnected
470 /// servers (empty when there is no global MCP manager or when
471 /// nothing is idle).
472 ///
473 /// Hosts running thousands of long-lived sessions should call this
474 /// periodically (e.g. every 60s with a 5-min threshold) to release
475 /// file descriptors and background workers from quiet MCP servers
476 /// without losing the server's configuration. A subsequent tool
477 /// call on the same server will require an explicit reconnect.
478 pub async fn disconnect_idle_mcp(&self, idle_threshold_ms: u64) -> Vec<String> {
479 match &self.global_mcp {
480 Some(mcp) => mcp.disconnect_idle(idle_threshold_ms).await,
481 None => Vec::new(),
482 }
483 }
484
485 #[cfg(test)]
486 fn build_session(
487 &self,
488 workspace: String,
489 llm_client: Arc<dyn LlmClient>,
490 opts: &SessionOptions,
491 ) -> Result<AgentSession> {
492 session_builder::build_agent_session(self, workspace, llm_client, opts)
493 }
494}
495
496// ============================================================================
497// AgentSession
498// ============================================================================
499
500/// Workspace-bound session. All LLM and tool operations happen here.
501///
502/// History is automatically accumulated after each `send()` call and after
503/// `stream()` completes when no custom history is supplied.
504/// Use `history()` to retrieve the current conversation log.
505pub struct AgentSession {
506 llm_client: Arc<dyn LlmClient>,
507 tool_executor: Arc<ToolExecutor>,
508 tool_context: ToolContext,
509 config: AgentConfig,
510 workspace: PathBuf,
511 /// Unique session identifier.
512 session_id: String,
513 /// Internal conversation history, auto-updated after each `send()` and default-history `stream()`.
514 history: Arc<RwLock<Vec<Message>>>,
515 /// Optional lane queue for priority-based tool execution.
516 command_queue: Option<Arc<crate::session_lane_queue::SessionLaneQueue>>,
517 /// Optional long-term memory.
518 memory: Option<Arc<crate::memory::AgentMemory>>,
519 /// Optional session store for persistence.
520 session_store: Option<Arc<dyn crate::store::SessionStore>>,
521 /// Auto-save after each completed `send()` or default-history `stream()`.
522 auto_save: bool,
523 /// Hook engine for lifecycle event interception.
524 hook_engine: Arc<crate::hooks::HookEngine>,
525 /// Optional external hook executor (e.g. AHP harness). When set, replaces
526 /// `hook_engine` as the executor passed to each `AgentLoop`.
527 ahp_executor: Option<Arc<dyn crate::hooks::HookExecutor>>,
528 /// Deferred init warning: emitted as PersistenceFailed on first send() if set.
529 init_warning: Option<String>,
530 /// Slash command registry for `/command` dispatch.
531 /// Uses interior mutability so commands can be registered on a shared `Arc<AgentSession>`.
532 command_registry: std::sync::Mutex<CommandRegistry>,
533 /// Model identifier for display (e.g., "anthropic/claude-sonnet-4-20250514").
534 model_name: String,
535 /// Shared MCP manager — all add_mcp_server / remove_mcp_server calls go here.
536 mcp_manager: Arc<crate::mcp::manager::McpManager>,
537 /// Shared agent registry — populated at session creation; extended via register_agent_dir().
538 agent_registry: Arc<crate::subagent::AgentRegistry>,
539 /// Cancellation token for the current operation (send/stream).
540 /// Stored so that cancel() can abort ongoing LLM calls.
541 cancel_token: Arc<tokio::sync::Mutex<Option<tokio_util::sync::CancellationToken>>>,
542 /// ID of the run currently attached to the active cancellation token.
543 current_run_id: Arc<tokio::sync::Mutex<Option<String>>>,
544 /// In-memory run snapshots and event replay buffer for this session.
545 run_store: Arc<crate::run::InMemoryRunStore>,
546 /// Materialized view of delegated subagent task lifecycle, populated from runtime events.
547 subagent_tasks: Arc<crate::subagent_task_tracker::InMemorySubagentTaskTracker>,
548 /// Currently executing tools observed from runtime events.
549 active_tools: Arc<tokio::sync::RwLock<HashMap<String, ActiveToolState>>>,
550 /// Compact execution traces for this session.
551 trace_sink: crate::trace::InMemoryTraceSink,
552 /// Structured completion evidence collected from agent and explicit verification runs.
553 verification_reports: Arc<RwLock<Vec<crate::verification::VerificationReport>>>,
554 /// Set once `close()` has been called. Subsequent send/stream calls
555 /// fast-fail with [`crate::error::CodeError::SessionClosed`].
556 closed: Arc<std::sync::atomic::AtomicBool>,
557 /// Session-level parent cancellation token.
558 ///
559 /// Every in-flight run (blocking send, stream, delegated subagent task)
560 /// derives its per-operation token from this one via `child_token()`,
561 /// so `session_cancel.cancel()` cascades to all of them. `close()` fires
562 /// this token first, after which any new `child_token()` returns an
563 /// already-cancelled token (defending against close/spawn races).
564 pub(crate) session_cancel: tokio_util::sync::CancellationToken,
565 /// Shared `Arc`-handle used by both [`AgentSession::close`] and the
566 /// parent [`Agent`]'s registry. The handle bundles every field needed
567 /// to perform the close sequence so the two entry points cannot drift.
568 close_handle: Arc<SessionCloseHandle>,
569 /// Runtime-mutable override for the budget guard. When set, takes
570 /// precedence over `config.budget_guard` on the next agent-loop
571 /// build. Lets SDK callers (Node especially) install a host-side
572 /// guard after `session()` has returned without ever putting a
573 /// JS callable into `SessionOptions`.
574 runtime_budget_guard: std::sync::Mutex<Option<Arc<dyn crate::budget::BudgetGuard>>>,
575 /// Multi-tenant label. Framework only carries the string; semantics
576 /// belong to the host.
577 pub(crate) tenant_id: Option<String>,
578 /// Principal that triggered the session (user / service / etc.).
579 pub(crate) principal: Option<String>,
580 /// Logical identifier of the agent template the session was
581 /// instantiated from.
582 pub(crate) agent_template_id: Option<String>,
583 /// Distributed-trace correlation id propagated to hooks / traces.
584 pub(crate) correlation_id: Option<String>,
585}
586
587impl std::fmt::Debug for AgentSession {
588 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
589 f.debug_struct("AgentSession")
590 .field("session_id", &self.session_id)
591 .field("workspace", &self.workspace.display().to_string())
592 .field("auto_save", &self.auto_save)
593 .finish()
594 }
595}
596
597impl AgentSession {
598 /// Get a snapshot of command entries (name, description, optional usage).
599 ///
600 /// Acquires the command registry lock briefly and returns owned data.
601 pub fn command_registry(&self) -> std::sync::MutexGuard<'_, CommandRegistry> {
602 session_commands::registry(self)
603 }
604
605 /// Register a custom slash command.
606 ///
607 /// Takes `&self` so it can be called on a shared `Arc<AgentSession>`.
608 pub fn register_command(&self, cmd: Arc<dyn crate::commands::SlashCommand>) {
609 session_commands::register(self, cmd);
610 }
611
612 /// Return whether [`close`](Self::close) has been called on this session.
613 ///
614 /// Once closed, `send`/`stream` and their attachment variants fast-fail
615 /// with [`crate::error::CodeError::SessionClosed`] instead of starting a
616 /// new run.
617 pub fn is_closed(&self) -> bool {
618 self.closed.load(std::sync::atomic::Ordering::Acquire)
619 }
620
621 /// Clone the session-level [`CancellationToken`](tokio_util::sync::CancellationToken).
622 ///
623 /// All in-flight runs derive their per-operation token from this one via
624 /// `child_token()`, so embedders can:
625 ///
626 /// - Observe the token (e.g. wire it into a host-side `select!`) to
627 /// react to session shutdown without polling [`is_closed`](Self::is_closed);
628 /// - Call `.cancel()` on it to abort every operation in the session
629 /// without going through `close()` (no run-store / hook side effects).
630 ///
631 /// For graceful shutdown prefer [`close`](Self::close), which also marks
632 /// runs as cancelled in the store and fires AHP hooks.
633 pub fn session_cancel_token(&self) -> tokio_util::sync::CancellationToken {
634 self.session_cancel.clone()
635 }
636
637 /// Return the host-defined tenant id, if any.
638 ///
639 /// The framework only transports this string — it never interprets
640 /// or enforces tenant boundaries itself. Use this from custom
641 /// `HookExecutor` / `PermissionChecker` / `BudgetGuard` impls to
642 /// route logic by tenant.
643 pub fn tenant_id(&self) -> Option<&str> {
644 self.tenant_id.as_deref()
645 }
646
647 /// Return the principal that triggered the session, if any.
648 pub fn principal(&self) -> Option<&str> {
649 self.principal.as_deref()
650 }
651
652 /// Return the id of the agent template/definition the session was
653 /// instantiated from, if any.
654 pub fn agent_template_id(&self) -> Option<&str> {
655 self.agent_template_id.as_deref()
656 }
657
658 /// Return the distributed-trace correlation id propagated through
659 /// this session's events, if any.
660 pub fn correlation_id(&self) -> Option<&str> {
661 self.correlation_id.as_deref()
662 }
663
664 /// Install or replace a runtime budget guard. Takes effect on the
665 /// next `send` / `stream` call (the guard is consulted at agent-
666 /// loop build time, not on the live execution). Setting `None`
667 /// clears the override so `config.budget_guard` takes over again.
668 ///
669 /// This is the entry point SDKs use to wire a host-supplied guard
670 /// after the session has already been constructed — useful when
671 /// the guard's transport (e.g. a JS callable) cannot live inside
672 /// the value-typed `SessionOptions`.
673 pub fn set_budget_guard(&self, guard: Option<Arc<dyn crate::budget::BudgetGuard>>) {
674 let mut slot = self
675 .runtime_budget_guard
676 .lock()
677 .unwrap_or_else(|p| p.into_inner());
678 *slot = guard;
679 }
680
681 /// Return the currently-installed runtime budget guard, if any.
682 /// `None` means the loop falls back to `config.budget_guard`.
683 pub fn budget_guard(&self) -> Option<Arc<dyn crate::budget::BudgetGuard>> {
684 self.runtime_budget_guard
685 .lock()
686 .unwrap_or_else(|p| p.into_inner())
687 .clone()
688 }
689
690 /// Proactively close the session and release its in-flight work.
691 ///
692 /// On the first call this:
693 /// 1. flips the session into the **closed** state so further `send`/`stream`
694 /// calls fast-fail with [`crate::error::CodeError::SessionClosed`];
695 /// 2. fires the session-level cancellation token so every derived
696 /// run/subagent token cascades to cancelled;
697 /// 3. marks the active run `Cancelled` in the run store and fires AHP
698 /// hook side effects;
699 /// 4. cancels every still-running delegated subagent task spawned from
700 /// this session;
701 /// 5. cancels all pending human-in-the-loop tool confirmations.
702 ///
703 /// Subsequent calls are no-ops and are guaranteed not to panic.
704 pub async fn close(&self) {
705 // Delegate to the shared handle so this entry point and
706 // `Agent::close_session(id)` cannot drift in behaviour.
707 self.close_handle.close().await;
708 }
709
710 /// Send a prompt and wait for the complete response.
711 ///
712 /// When `history` is `None`, uses (and auto-updates) the session's
713 /// internal conversation history. When `Some`, uses the provided
714 /// history instead (the internal history is **not** modified).
715 ///
716 /// If the prompt starts with `/`, it is dispatched as a slash command
717 /// and the result is returned without calling the LLM.
718 pub async fn send(&self, prompt: &str, history: Option<&[Message]>) -> Result<AgentResult> {
719 conversation_runtime::send(self, prompt, history).await
720 }
721
722 /// Resume a previously-checkpointed run on this session.
723 ///
724 /// Loads the latest [`LoopCheckpoint`](crate::loop_checkpoint::LoopCheckpoint)
725 /// stored under `checkpoint_run_id` and replays the agent loop from
726 /// that boundary state. A **new** run id is allocated for the
727 /// resumed work; the relationship between the old and new run is
728 /// host-tracked — the framework does not interpret
729 /// it.
730 ///
731 /// Returns an error when no `SessionStore` is configured on this
732 /// session, or when no checkpoint exists for `checkpoint_run_id`.
733 pub async fn resume_run(&self, checkpoint_run_id: &str) -> Result<AgentResult> {
734 conversation_runtime::resume_run(self, checkpoint_run_id).await
735 }
736
737 /// Send a prompt with image attachments and wait for the complete response.
738 ///
739 /// Images are included as multi-modal content blocks in the user message.
740 /// Requires a vision-capable model (e.g., Claude Sonnet, GPT-4o).
741 pub async fn send_with_attachments(
742 &self,
743 prompt: &str,
744 attachments: &[crate::llm::Attachment],
745 history: Option<&[Message]>,
746 ) -> Result<AgentResult> {
747 conversation_runtime::send_with_attachments(self, prompt, attachments, history).await
748 }
749
750 /// Stream a prompt with image attachments.
751 ///
752 /// Images are included as multi-modal content blocks in the user message.
753 /// Requires a vision-capable model (e.g., Claude Sonnet, GPT-4o).
754 pub async fn stream_with_attachments(
755 &self,
756 prompt: &str,
757 attachments: &[crate::llm::Attachment],
758 history: Option<&[Message]>,
759 ) -> Result<(mpsc::Receiver<AgentEvent>, JoinHandle<()>)> {
760 conversation_runtime::stream_with_attachments(self, prompt, attachments, history).await
761 }
762
763 /// Send a prompt and stream events back.
764 ///
765 /// When `history` is `None`, uses the session's internal history
766 /// and updates it when the stream completes.
767 /// When `Some`, uses the provided history instead.
768 ///
769 /// If the prompt starts with `/`, it is dispatched as a slash command
770 /// and the result is emitted as a single `TextDelta` + `End` event.
771 pub async fn stream(
772 &self,
773 prompt: &str,
774 history: Option<&[Message]>,
775 ) -> Result<(mpsc::Receiver<AgentEvent>, JoinHandle<()>)> {
776 conversation_runtime::stream(self, prompt, history).await
777 }
778
779 /// Cancel the current ongoing operation (send/stream).
780 ///
781 /// If an operation is in progress, this will trigger cancellation of the LLM streaming
782 /// and tool execution. The operation will terminate as soon as possible.
783 ///
784 /// Returns `true` if an operation was cancelled, `false` if no operation was in progress.
785 pub async fn cancel(&self) -> bool {
786 RunControl::from_session(self).cancel_current().await
787 }
788
789 /// Cancel a specific run only if it is still the active run.
790 ///
791 /// This is useful for SDK callers that hold a previously observed run ID:
792 /// stale run IDs will not cancel a newer operation.
793 pub async fn cancel_run(&self, run_id: &str) -> bool {
794 RunControl::from_session(self).cancel_run(run_id).await
795 }
796
797 /// Return snapshots for runs recorded by this session.
798 pub async fn runs(&self) -> Vec<crate::run::RunSnapshot> {
799 RunControl::from_session(self).runs().await
800 }
801
802 /// Return a snapshot for a recorded run.
803 pub async fn run_snapshot(&self, run_id: &str) -> Option<crate::run::RunSnapshot> {
804 RunControl::from_session(self).run_snapshot(run_id).await
805 }
806
807 /// Return recorded runtime events for a run.
808 pub async fn run_events(&self, run_id: &str) -> Vec<crate::run::RunEventRecord> {
809 RunControl::from_session(self).run_events(run_id).await
810 }
811
812 /// Return a handle for the currently running operation, if any.
813 pub async fn current_run(&self) -> Option<crate::run::RunHandle> {
814 RunControl::from_session(self).current_run().await
815 }
816
817 /// Return active tool calls observed for the currently running operation.
818 pub async fn active_tools(&self) -> Vec<crate::run::ActiveToolSnapshot> {
819 SessionView::from_session(self).active_tools().await
820 }
821
822 /// Look up a delegated subagent task by id. Returns `None` if no such task
823 /// has been observed in this session.
824 pub async fn subagent_task(
825 &self,
826 task_id: &str,
827 ) -> Option<crate::subagent_task_tracker::SubagentTaskSnapshot> {
828 self.subagent_tasks.get(task_id).await
829 }
830
831 /// Return snapshots of every delegated subagent task observed in this
832 /// session (including completed and failed ones), oldest first.
833 pub async fn subagent_tasks(&self) -> Vec<crate::subagent_task_tracker::SubagentTaskSnapshot> {
834 self.subagent_tasks.list_for_parent(&self.session_id).await
835 }
836
837 /// Return snapshots of subagent tasks still in `Running` state.
838 pub async fn pending_subagent_tasks(
839 &self,
840 ) -> Vec<crate::subagent_task_tracker::SubagentTaskSnapshot> {
841 use crate::subagent_task_tracker::SubagentStatus;
842 self.subagent_tasks
843 .list_for_parent(&self.session_id)
844 .await
845 .into_iter()
846 .filter(|task| task.status == SubagentStatus::Running)
847 .collect()
848 }
849
850 /// Cancel an in-flight delegated subagent task by id. Returns `true`
851 /// when a cancellation token was found and fired, `false` when the
852 /// task id is unknown or the task has already finished. The eventual
853 /// `SubagentEnd` from the cancelled child loop won't downgrade the
854 /// terminal status — it stays `Cancelled`.
855 pub async fn cancel_subagent_task(&self, task_id: &str) -> bool {
856 self.subagent_tasks.cancel(task_id).await
857 }
858
859 /// Return a shared handle to the session's subagent task tracker.
860 ///
861 /// Advanced: embedders implementing a custom subagent execution path
862 /// (i.e. spawning child loops outside the built-in `task` tool) can use
863 /// this to register cancellation tokens and feed `AgentEvent`s into the
864 /// tracker so the standard
865 /// [`subagent_task`](Self::subagent_task) / [`pending_subagent_tasks`](Self::pending_subagent_tasks) /
866 /// [`cancel_subagent_task`](Self::cancel_subagent_task) APIs and
867 /// [`close`](Self::close) keep working uniformly across execution paths.
868 pub fn subagent_tracker(
869 &self,
870 ) -> Arc<crate::subagent_task_tracker::InMemorySubagentTaskTracker> {
871 Arc::clone(&self.subagent_tasks)
872 }
873
874 /// Return a snapshot of the session's conversation history.
875 pub fn history(&self) -> Vec<Message> {
876 SessionView::from_session(self).history()
877 }
878
879 /// Return pending HITL tool confirmations for this session.
880 pub async fn pending_confirmations(&self) -> Vec<PendingConfirmationInfo> {
881 HitlControl::from_session(self)
882 .pending_confirmations()
883 .await
884 }
885
886 /// Resolve a pending HITL tool confirmation.
887 ///
888 /// Returns `Ok(true)` when a pending confirmation was found and completed,
889 /// `Ok(false)` when the tool ID is not pending or HITL is not configured.
890 pub async fn confirm_tool_use(
891 &self,
892 tool_id: &str,
893 approved: bool,
894 reason: Option<String>,
895 ) -> Result<bool> {
896 HitlControl::from_session(self)
897 .confirm_tool_use(tool_id, approved, reason)
898 .await
899 }
900
901 /// Cancel all pending HITL confirmations for this session.
902 pub async fn cancel_confirmations(&self) -> usize {
903 HitlControl::from_session(self).cancel_confirmations().await
904 }
905
906 /// Return a reference to the session's memory, if configured.
907 pub fn memory(&self) -> Option<&Arc<crate::memory::AgentMemory>> {
908 SessionView::from_session(self).memory()
909 }
910
911 /// Return the session ID.
912 pub fn id(&self) -> &str {
913 SessionView::from_session(self).id()
914 }
915
916 /// Return the session workspace path.
917 pub fn workspace(&self) -> &std::path::Path {
918 SessionView::from_session(self).workspace()
919 }
920
921 /// Return any deferred init warning (e.g. memory store failed to initialize).
922 pub fn init_warning(&self) -> Option<&str> {
923 SessionView::from_session(self).init_warning()
924 }
925
926 /// Return the session ID.
927 pub fn session_id(&self) -> &str {
928 SessionView::from_session(self).id()
929 }
930
931 /// An [`AgentExecutor`](crate::orchestration::AgentExecutor) backed by this
932 /// session — runs each orchestrated step as a child agent on this node,
933 /// inheriting the session's agent registry, LLM client, workspace, MCP
934 /// tools, and subagent tracker.
935 ///
936 /// This is what the orchestration combinators
937 /// ([`execute_steps_parallel`](crate::orchestration::execute_steps_parallel),
938 /// [`execute_pipeline`](crate::orchestration::execute_pipeline),
939 /// [`execute_steps_parallel_resumable`](crate::orchestration::execute_steps_parallel_resumable))
940 /// run against; a host can instead supply its own executor to place steps
941 /// across a cluster.
942 pub fn agent_executor(&self) -> Arc<dyn crate::orchestration::AgentExecutor> {
943 Arc::new(self.build_task_executor(self.parent_run_context()))
944 }
945
946 /// Build the in-box [`TaskExecutor`](crate::tools::TaskExecutor) for this
947 /// session, applying `parent` as the child-run capability context. Shared by
948 /// [`agent_executor`](Self::agent_executor) and [`workflow`](Self::workflow)
949 /// so both wire children identically.
950 fn build_task_executor(
951 &self,
952 parent: crate::child_run::ChildRunContext,
953 ) -> crate::tools::TaskExecutor {
954 crate::tools::TaskExecutor::with_mcp(
955 Arc::clone(&self.agent_registry),
956 Arc::clone(&self.llm_client),
957 self.workspace.display().to_string(),
958 Arc::clone(&self.mcp_manager),
959 )
960 .with_parent_context(parent)
961 .with_subagent_tracker(Arc::clone(&self.subagent_tasks))
962 .with_max_parallel_tasks(self.config.max_parallel_tasks)
963 }
964
965 /// A programmable [`Workflow`](crate::orchestration::Workflow) bound to this
966 /// session.
967 ///
968 /// Pre-wired with this session's executor (inheriting the same governance as
969 /// model-driven delegation), persistence store (so each
970 /// [`phase`](crate::orchestration::Workflow::phase) is a resume boundary),
971 /// per-step event stream, and a session-derived stable root id. Control flow
972 /// is ordinary Rust: `await` a verb, inspect the outcomes, decide what runs
973 /// next.
974 pub fn workflow(&self) -> crate::orchestration::Workflow {
975 self.workflow_with_token_budget(None)
976 }
977
978 /// Like [`workflow`](Self::workflow) but with a hard token ceiling shared
979 /// across every step. The cap is a best-effort *soft* cost ceiling — under a
980 /// wide fan-out a few in-flight turns can race past it before the shared
981 /// ledger catches up (see [`WorkflowBudget`](crate::orchestration::WorkflowBudget)).
982 pub fn workflow_with_token_budget(
983 &self,
984 limit_tokens: Option<u64>,
985 ) -> crate::orchestration::Workflow {
986 use crate::budget::BudgetGuard;
987
988 // One shared ledger for the whole workflow, wrapping the session's own
989 // budget guard (if any) so a host's per-tenant accounting keeps working.
990 let mut budget = crate::orchestration::WorkflowBudget::new(limit_tokens);
991 if let Some(inner) = self.config.budget_guard.clone() {
992 budget = budget.with_inner(inner);
993 }
994 let budget = Arc::new(budget);
995
996 // Install the shared ledger as the child runs' budget guard so every
997 // step's per-turn LLM accounting feeds it.
998 let mut parent = self.parent_run_context();
999 parent.budget_guard = Some(Arc::clone(&budget) as Arc<dyn BudgetGuard>);
1000 let executor: Arc<dyn crate::orchestration::AgentExecutor> =
1001 Arc::new(self.build_task_executor(parent));
1002
1003 let mut builder = crate::orchestration::Workflow::builder(executor)
1004 .with_root_id(format!("wf-{}", self.session_id))
1005 .with_budget(Arc::clone(&budget));
1006 if let Some(store) = self.session_store.clone() {
1007 builder = builder.with_store(store);
1008 }
1009 if let Some(step_events) = self.tool_context.agent_event_tx.clone() {
1010 builder = builder.with_step_events(step_events);
1011 }
1012 builder.build()
1013 }
1014
1015 /// Build the [`ChildRunContext`](crate::child_run::ChildRunContext) that
1016 /// orchestrated / delegated child runs inherit from this session.
1017 ///
1018 /// Mirrors the context the model-driven `task` / `parallel_task` path
1019 /// installs (see `register_task_capability` in `agent_api/capabilities.rs`)
1020 /// so a step run through [`agent_executor`](Self::agent_executor) carries the
1021 /// SAME governance — security provider, skill restrictions, confirmation,
1022 /// the shared workspace, and the safety limits — instead of weaker, ambient
1023 /// authority. Sourced from the session's resolved config; `hook_engine`
1024 /// stays `None` to match the model-driven path.
1025 pub(crate) fn parent_run_context(&self) -> crate::child_run::ChildRunContext {
1026 crate::child_run::ChildRunContext {
1027 security_provider: self.config.security_provider.clone(),
1028 hook_engine: None,
1029 skill_registry: self.config.skill_registry.clone(),
1030 tool_timeout_ms: self.config.tool_timeout_ms,
1031 max_parallel_tasks: Some(self.config.max_parallel_tasks),
1032 max_execution_time_ms: self.config.max_execution_time_ms,
1033 circuit_breaker_threshold: Some(self.config.circuit_breaker_threshold),
1034 confirmation_manager: self.config.confirmation_manager.clone(),
1035 workspace_services: Some(Arc::clone(&self.tool_context.workspace_services)),
1036 budget_guard: self.config.budget_guard.clone(),
1037 }
1038 }
1039
1040 /// The session's persistence store, if one is configured — needed by the
1041 /// resumable orchestration combinator to journal workflow progress.
1042 pub fn session_store(&self) -> Option<Arc<dyn crate::store::SessionStore>> {
1043 self.session_store.clone()
1044 }
1045
1046 /// Return the definitions of all tools currently registered in this session.
1047 ///
1048 /// The list reflects the live state of the tool executor — tools added via
1049 /// `add_mcp_server()` appear immediately; tools removed via
1050 /// `remove_mcp_server()` disappear immediately.
1051 pub fn tool_definitions(&self) -> Vec<crate::llm::ToolDefinition> {
1052 DirectToolRuntime::from_session(self).definitions()
1053 }
1054
1055 /// Return the names of all tools currently registered on this session.
1056 ///
1057 /// Equivalent to `tool_definitions().into_iter().map(|t| t.name).collect()`.
1058 /// Tools added via [`add_mcp_server`] appear immediately; tools removed via
1059 /// [`remove_mcp_server`] disappear immediately.
1060 pub fn tool_names(&self) -> Vec<String> {
1061 DirectToolRuntime::from_session(self).names()
1062 }
1063
1064 /// Return a stored tool artifact by URI, if it exists in this session.
1065 pub fn get_artifact(&self, artifact_uri: &str) -> Option<crate::tools::ToolArtifact> {
1066 DirectToolRuntime::from_session(self).artifact(artifact_uri)
1067 }
1068
1069 /// Return compact execution trace events recorded for this session.
1070 pub fn trace_events(&self) -> Vec<crate::trace::TraceEvent> {
1071 SessionView::from_session(self).trace_events()
1072 }
1073
1074 /// Return structured verification reports recorded for this session.
1075 pub fn verification_reports(&self) -> Vec<crate::verification::VerificationReport> {
1076 VerificationRuntime::from_session(self).reports()
1077 }
1078
1079 /// Return a structured summary of all verification reports recorded for this session.
1080 pub fn verification_summary(&self) -> crate::verification::VerificationSummary {
1081 VerificationRuntime::from_session(self).summary()
1082 }
1083
1084 /// Return a concise human-readable verification summary for this session.
1085 pub fn verification_summary_text(&self) -> String {
1086 VerificationRuntime::from_session(self).summary_text()
1087 }
1088
1089 /// Add externally produced verification reports to this session's completion evidence.
1090 pub fn record_verification_reports(
1091 &self,
1092 reports: impl IntoIterator<Item = crate::verification::VerificationReport>,
1093 ) {
1094 VerificationRuntime::from_session(self).record(reports);
1095 }
1096
1097 // ========================================================================
1098 // Hook API
1099 // ========================================================================
1100
1101 /// Register a hook for lifecycle event interception.
1102 pub fn register_hook(&self, hook: crate::hooks::Hook) {
1103 HookControl::from_session(self).register_hook(hook);
1104 }
1105
1106 /// Unregister a hook by ID.
1107 pub fn unregister_hook(&self, hook_id: &str) -> Option<crate::hooks::Hook> {
1108 HookControl::from_session(self).unregister_hook(hook_id)
1109 }
1110
1111 /// Register a handler for a specific hook.
1112 pub fn register_hook_handler(
1113 &self,
1114 hook_id: &str,
1115 handler: Arc<dyn crate::hooks::HookHandler>,
1116 ) {
1117 HookControl::from_session(self).register_hook_handler(hook_id, handler);
1118 }
1119
1120 /// Unregister a hook handler by hook ID.
1121 pub fn unregister_hook_handler(&self, hook_id: &str) {
1122 HookControl::from_session(self).unregister_hook_handler(hook_id);
1123 }
1124
1125 /// Get the number of registered hooks.
1126 pub fn hook_count(&self) -> usize {
1127 HookControl::from_session(self).hook_count()
1128 }
1129
1130 /// Save the session to the configured store.
1131 ///
1132 /// Returns `Ok(())` if saved successfully, or if no store is configured (no-op).
1133 pub async fn save(&self) -> Result<()> {
1134 session_save::save(self).await
1135 }
1136
1137 /// Read a file from the workspace.
1138 pub async fn read_file(&self, path: &str) -> Result<String> {
1139 DirectToolRuntime::from_session(self).read_file(path).await
1140 }
1141
1142 /// Write a file in the workspace.
1143 pub async fn write_file(&self, path: &str, content: &str) -> Result<ToolCallResult> {
1144 DirectToolRuntime::from_session(self)
1145 .write_file(path, content)
1146 .await
1147 }
1148
1149 /// List a directory in the workspace.
1150 pub async fn ls(&self, path: Option<&str>) -> Result<ToolCallResult> {
1151 DirectToolRuntime::from_session(self).ls(path).await
1152 }
1153
1154 /// Edit a file by replacing text in the workspace.
1155 pub async fn edit_file(
1156 &self,
1157 path: &str,
1158 old_string: &str,
1159 new_string: &str,
1160 replace_all: bool,
1161 ) -> Result<ToolCallResult> {
1162 DirectToolRuntime::from_session(self)
1163 .edit_file(path, old_string, new_string, replace_all)
1164 .await
1165 }
1166
1167 /// Apply a unified diff patch to a workspace file.
1168 pub async fn patch_file(&self, path: &str, diff: &str) -> Result<ToolCallResult> {
1169 DirectToolRuntime::from_session(self)
1170 .patch_file(path, diff)
1171 .await
1172 }
1173
1174 /// Execute a bash command in the workspace.
1175 ///
1176 /// When a sandbox handle is configured via
1177 /// [`SessionOptions::with_sandbox_handle()`], the command is routed through
1178 /// that sandbox.
1179 pub async fn bash(&self, command: &str) -> Result<String> {
1180 DirectToolRuntime::from_session(self).bash(command).await
1181 }
1182
1183 /// Run verification commands through the session's tool execution path.
1184 pub async fn verify_commands(
1185 &self,
1186 subject: &str,
1187 commands: &[crate::verification::VerificationCommand],
1188 ) -> Result<crate::verification::VerificationReport> {
1189 VerificationRuntime::from_session(self)
1190 .verify_commands(subject, commands)
1191 .await
1192 }
1193
1194 /// Return project-aware verification command presets for this workspace.
1195 pub fn verification_presets(&self) -> Vec<crate::verification::VerificationPreset> {
1196 VerificationRuntime::from_session(self).presets()
1197 }
1198
1199 /// Search for files matching a glob pattern.
1200 pub async fn glob(&self, pattern: &str) -> Result<Vec<String>> {
1201 DirectToolRuntime::from_session(self).glob(pattern).await
1202 }
1203
1204 /// Search file contents with a regex pattern.
1205 pub async fn grep(&self, pattern: &str) -> Result<String> {
1206 DirectToolRuntime::from_session(self).grep(pattern).await
1207 }
1208
1209 /// Execute a tool by name, bypassing the LLM.
1210 pub async fn tool(&self, name: &str, args: serde_json::Value) -> Result<ToolCallResult> {
1211 DirectToolRuntime::from_session(self).call(name, args).await
1212 }
1213
1214 // ========================================================================
1215 // Advanced optional Queue API
1216 // ========================================================================
1217
1218 /// Returns whether this session has an advanced lane queue configured.
1219 pub fn has_queue(&self) -> bool {
1220 QueueControl::from_session(self).has_queue()
1221 }
1222
1223 /// Configure a lane's handler mode for explicit external/hybrid dispatch.
1224 ///
1225 /// Only effective when a queue is configured via `SessionOptions::with_queue_config`.
1226 pub async fn set_lane_handler(&self, lane: SessionLane, config: LaneHandlerConfig) {
1227 QueueControl::from_session(self)
1228 .set_lane_handler(lane, config)
1229 .await;
1230 }
1231
1232 /// Complete an external queue task by ID.
1233 ///
1234 /// Returns `true` if the task was found and completed, `false` if not found.
1235 pub async fn complete_external_task(&self, task_id: &str, result: ExternalTaskResult) -> bool {
1236 QueueControl::from_session(self)
1237 .complete_external_task(task_id, result)
1238 .await
1239 }
1240
1241 /// Get pending external queue tasks awaiting completion by an external handler.
1242 pub async fn pending_external_tasks(&self) -> Vec<ExternalTask> {
1243 QueueControl::from_session(self)
1244 .pending_external_tasks()
1245 .await
1246 }
1247
1248 /// Get optional queue statistics (pending, active, external counts per lane).
1249 pub async fn queue_stats(&self) -> SessionQueueStats {
1250 QueueControl::from_session(self).stats().await
1251 }
1252
1253 /// Get a metrics snapshot from the optional queue (if metrics are enabled).
1254 pub async fn queue_metrics(&self) -> Option<MetricsSnapshot> {
1255 QueueControl::from_session(self).metrics().await
1256 }
1257
1258 /// Get dead letters from the optional queue's DLQ (if DLQ is enabled).
1259 pub async fn dead_letters(&self) -> Vec<DeadLetter> {
1260 QueueControl::from_session(self).dead_letters().await
1261 }
1262
1263 // ========================================================================
1264 // MCP API
1265 // ========================================================================
1266
1267 /// Register all agents found in a directory with the live session.
1268 ///
1269 /// Scans `dir` for `*.yaml`, `*.yml`, and `*.md` agent definition files,
1270 /// parses them, and adds each one to the shared `AgentRegistry` used by the
1271 /// `task` tool. New agents are immediately usable via `task(agent="…")` in
1272 /// the same session — no restart required.
1273 ///
1274 /// Returns the number of agents successfully loaded from the directory.
1275 pub fn register_agent_dir(&self, dir: &std::path::Path) -> usize {
1276 SessionExtensionRuntime::from_session(self).register_agent_dir(dir)
1277 }
1278
1279 /// Register a disposable worker agent with the live session.
1280 ///
1281 /// The returned definition is immediately available to the `task` tool by
1282 /// worker name, so callers can create many reproducible workers without
1283 /// writing temporary agent files or restarting the session.
1284 pub fn register_worker_agent(
1285 &self,
1286 spec: crate::subagent::WorkerAgentSpec,
1287 ) -> crate::subagent::AgentDefinition {
1288 SessionExtensionRuntime::from_session(self).register_worker_agent(spec)
1289 }
1290
1291 /// Register multiple disposable worker agents with the live session.
1292 pub fn register_worker_agents<I>(&self, specs: I) -> Vec<crate::subagent::AgentDefinition>
1293 where
1294 I: IntoIterator<Item = crate::subagent::WorkerAgentSpec>,
1295 {
1296 SessionExtensionRuntime::from_session(self).register_worker_agents(specs)
1297 }
1298
1299 /// Add an MCP server to this session.
1300 ///
1301 /// Registers, connects, and makes all tools immediately available for the
1302 /// agent to call. Tool names follow the convention `mcp__<name>__<tool>`.
1303 ///
1304 /// Returns the number of tools registered from the server.
1305 pub async fn add_mcp_server(
1306 &self,
1307 config: crate::mcp::McpServerConfig,
1308 ) -> crate::error::Result<usize> {
1309 SessionExtensionRuntime::from_session(self)
1310 .add_mcp_server(config)
1311 .await
1312 }
1313
1314 /// Remove an MCP server from this session.
1315 ///
1316 /// Disconnects the server and unregisters all its tools from the executor.
1317 /// No-op if the server was never added.
1318 pub async fn remove_mcp_server(&self, server_name: &str) -> crate::error::Result<()> {
1319 SessionExtensionRuntime::from_session(self)
1320 .remove_mcp_server(server_name)
1321 .await
1322 }
1323
1324 /// Return the connection status of all MCP servers registered with this session.
1325 pub async fn mcp_status(
1326 &self,
1327 ) -> std::collections::HashMap<String, crate::mcp::McpServerStatus> {
1328 SessionExtensionRuntime::from_session(self)
1329 .mcp_status()
1330 .await
1331 }
1332}
1333
1334// ============================================================================
1335// Tests
1336// ============================================================================
1337
1338#[cfg(test)]
1339mod tests;