Skip to main content

a3s_code_core/
agent_api.rs

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