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_async("/my-project", None).await?;
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_facade;
41mod agent_loop_runtime;
42mod agent_sessions;
43mod capabilities;
44mod capability_facade;
45mod command_runtime;
46mod conversation_runtime;
47mod direct_tool_facade;
48mod direct_tools;
49mod governance_facade;
50mod hook_control;
51mod run_admission;
52mod run_facade;
53mod run_lifecycle;
54mod runtime;
55mod runtime_events;
56mod session_builder;
57mod session_clock;
58mod session_close;
59mod session_commands;
60mod session_config;
61mod session_extensions;
62mod session_facade;
63mod session_hitl;
64mod session_options;
65mod session_persistence;
66mod session_queue;
67mod session_runs;
68mod session_runtime;
69mod session_save;
70mod session_verification;
71mod session_view;
72mod workflow_facade;
73pub use agent_facade::{Agent, SessionBuilder};
74use direct_tools::DirectToolRuntime;
75use hook_control::HookControl;
76use runtime_events::ActiveToolState;
77use session_close::SessionCloseHandle;
78use session_extensions::SessionExtensionRuntime;
79use session_hitl::HitlControl;
80use session_queue::QueueControl;
81use session_runs::RunControl;
82use session_verification::VerificationRuntime;
83use session_view::SessionView;
84
85/// Canonicalize a path, stripping the Windows `\\?\` UNC prefix to avoid
86/// polluting workspace strings throughout the system (prompts, session data, etc.).
87fn safe_canonicalize(path: &Path) -> PathBuf {
88    match std::fs::canonicalize(path) {
89        Ok(p) => strip_unc_prefix(p),
90        Err(_) => path.to_path_buf(),
91    }
92}
93
94/// Strip the Windows extended-length path prefix (`\\?\`) that `canonicalize()` adds.
95/// On non-Windows this is a no-op.
96fn strip_unc_prefix(path: PathBuf) -> PathBuf {
97    #[cfg(windows)]
98    {
99        let s = path.to_string_lossy();
100        if let Some(stripped) = s.strip_prefix(r"\\?\") {
101            return PathBuf::from(stripped);
102        }
103    }
104    path
105}
106
107// ============================================================================
108// ToolCallResult
109// ============================================================================
110
111/// Result of a direct tool execution (no LLM).
112#[derive(Debug, Clone)]
113pub struct ToolCallResult {
114    pub name: String,
115    pub output: String,
116    pub exit_code: i32,
117    pub metadata: Option<serde_json::Value>,
118    /// Structured discriminant for tool failures. `None` when the tool
119    /// either succeeded or failed without a typed reason (the message in
120    /// `output` is then the only diagnostic). Populated for known
121    /// kinds such as `VersionConflict` so SDK callers can branch on the
122    /// `type` field instead of regex-matching `output`.
123    pub error_kind: Option<crate::tools::ToolErrorKind>,
124}
125
126/// Result of admitting a host-selected run identity for detached execution.
127///
128/// `Started` owns a supervisor task that drains the ordinary Code event stream
129/// into the authoritative run store. Dropping the handle detaches the task;
130/// call [`AgentSession::close`] for graceful cancellation and cleanup.
131pub enum AgentRunSpawn {
132    Started {
133        snapshot: crate::run::RunSnapshot,
134        worker: JoinHandle<()>,
135    },
136    Replayed {
137        snapshot: crate::run::RunSnapshot,
138    },
139}
140
141impl AgentRunSpawn {
142    pub const fn replayed(&self) -> bool {
143        matches!(self, Self::Replayed { .. })
144    }
145
146    pub fn snapshot(&self) -> &crate::run::RunSnapshot {
147        match self {
148            Self::Started { snapshot, .. } | Self::Replayed { snapshot } => snapshot,
149        }
150    }
151}
152
153// ============================================================================
154// ReadFileOptions
155// ============================================================================
156
157/// Optional line-range controls for direct `read` tool calls.
158#[derive(Debug, Clone, Copy, Default)]
159pub struct ReadFileOptions {
160    /// 0-indexed line offset to start reading from.
161    pub offset: Option<usize>,
162    /// Maximum number of lines to read.
163    pub limit: Option<usize>,
164}
165
166// ============================================================================
167// SessionOptions
168// ============================================================================
169
170/// Optional per-session overrides.
171#[derive(Clone, Default)]
172pub struct SessionOptions {
173    /// Override the default model. Format: `"provider/model"` (e.g., `"openai/gpt-4o"`).
174    pub model: Option<String>,
175    /// Extra directories to scan for agent files.
176    /// Merged with any global `agent_dirs` from [`CodeConfig`].
177    pub agent_dirs: Vec<PathBuf>,
178    /// Reproducible disposable workers registered for task delegation.
179    /// Explicit session workers override agents loaded from directories by name.
180    pub worker_agents: Vec<crate::subagent::WorkerAgentSpec>,
181    /// Optional queue configuration for lane-based tool execution.
182    ///
183    /// When set, enables priority-based tool scheduling with parallel execution
184    /// of read-only (Query-lane) tools, DLQ, metrics, and external task handling.
185    pub queue_config: Option<SessionQueueConfig>,
186    /// Optional security provider for taint tracking and output sanitization
187    pub security_provider: Option<Arc<dyn crate::security::SecurityProvider>>,
188    /// Optional host-supplied LLM client.
189    ///
190    /// When set, it is used directly, overriding the `provider/model`
191    /// factory resolution — the one Action-layer backend that was previously
192    /// only injectable in test code. Lets a host plug in a provider the
193    /// built-in factory does not cover, a deterministic record/replay client,
194    /// or an HTTP-layer proxy/audit wrapper. Mirrors `workspace_services`.
195    pub llm_client: Option<Arc<dyn crate::llm::LlmClient>>,
196    /// Optional context providers for RAG
197    pub context_providers: Vec<Arc<dyn crate::context::ContextProvider>>,
198    /// Optional confirmation manager for HITL
199    pub confirmation_manager: Option<Arc<dyn crate::hitl::ConfirmationProvider>>,
200    /// Optional confirmation policy (will be used to create ConfirmationManager if confirmation_manager is not set)
201    pub confirmation_policy: Option<crate::hitl::ConfirmationPolicy>,
202    /// Optional permission checker
203    pub permission_checker: Option<Arc<dyn crate::permissions::PermissionChecker>>,
204    /// Serializable permission policy used to build the checker, when available.
205    pub permission_policy: Option<crate::permissions::PermissionPolicy>,
206    /// Enable planning
207    pub planning_mode: PlanningMode,
208    /// Enable goal tracking
209    pub goal_tracking: bool,
210    /// Extra directories to scan for skill files (*.md).
211    /// Merged with any global `skill_dirs` from [`CodeConfig`].
212    pub skill_dirs: Vec<PathBuf>,
213    /// Optional skill registry for instruction injection
214    pub skill_registry: Option<Arc<crate::skills::SkillRegistry>>,
215    /// Whether active skill `allowed-tools` restrict ordinary session tool calls.
216    ///
217    /// Defaults to false so ordinary tools continue through permission policy,
218    /// hooks, and HITL. Set true to restore the legacy global active-skill
219    /// restriction behavior.
220    pub enforce_active_skill_tool_restrictions: Option<bool>,
221    /// Custom memory store override for long-term memory persistence.
222    ///
223    /// Sessions resolve a default store when this is not set.
224    pub memory_store: Option<Arc<dyn MemoryStore>>,
225    /// Host observers notified after successful durable memory writes.
226    pub memory_observers: Vec<Arc<dyn crate::memory::MemoryObserver>>,
227    /// Deferred file memory directory — constructed async in `build_session()`
228    pub(crate) file_memory_dir: Option<PathBuf>,
229    /// Optional session store for persistence
230    pub session_store: Option<Arc<dyn crate::store::SessionStore>>,
231    /// Deferred file session-store directory, initialized by the async builder.
232    pub(crate) file_session_store_dir: Option<PathBuf>,
233    /// Explicit session ID (auto-generated if not set)
234    pub session_id: Option<String>,
235    /// Multi-tenant identifier. Framework only transports this string;
236    /// the host decides what "tenant" means and how to
237    /// aggregate/bill on it. Emitted to hooks/traces, persisted in
238    /// `SessionData`, never interpreted by core.
239    pub tenant_id: Option<String>,
240    /// Identity of the principal that triggered this session (user id,
241    /// service account, etc). Treated as opaque.
242    pub principal: Option<String>,
243    /// Logical identifier of the agent template / definition the session
244    /// was instantiated from. Lets the host aggregate sessions by
245    /// "which agent recipe" independent of the concrete session id.
246    pub agent_template_id: Option<String>,
247    /// Distributed-trace correlation id. Propagated through hooks/traces
248    /// so a session's events join with upstream/downstream work in the
249    /// host's observability pipeline.
250    pub correlation_id: Option<String>,
251    /// Optional host-supplied budget / quota guard. The framework calls
252    /// into it before each LLM call (and reports actuals after) so the
253    /// host can refuse or rate-limit at the cluster level. Default is
254    /// `None` (no enforcement — equivalent to
255    /// [`NoopBudgetGuard`](crate::budget::NoopBudgetGuard)).
256    pub budget_guard: Option<Arc<dyn crate::budget::BudgetGuard>>,
257    /// Optional host-provided ID/Clock pair. Replaces the default
258    /// random-UUID + wall-clock pair, enabling deterministic replay
259    /// on another node. `None` keeps pre-P2 behaviour.
260    pub host_env: Option<Arc<crate::host_env::HostEnv>>,
261    /// Optional FIFO retention caps on the session's in-memory stores
262    /// (run records, run events, trace events, terminal subagent
263    /// tasks). `None` selects [`SessionRetentionLimits::default`](crate::retention::SessionRetentionLimits::default),
264    /// which is finite. Pass [`SessionRetentionLimits::unbounded`](crate::retention::SessionRetentionLimits::unbounded)
265    /// explicitly to retain everything.
266    pub retention_limits: Option<crate::retention::SessionRetentionLimits>,
267    /// Optional structured JSONL trajectory config.
268    ///
269    /// When set, a3s-code records user prompts, LLM turns, tool calls,
270    /// tool observations, token usage, and execution end status for RL
271    /// training or service data collection. If unset, the same config can
272    /// be enabled by `A3S_CODE_TRAJECTORY_PATH`.
273    pub rl_trajectory: Option<crate::rl_trajectory::RlTrajectoryConfig>,
274    /// Request token-level log probabilities from compatible LLM providers.
275    ///
276    /// This is off by default because many public providers reject logprob
277    /// requests with tool calls. Training/evaluation harnesses using compatible
278    /// OpenAI-style backends can enable it explicitly.
279    pub llm_logprobs: Option<bool>,
280    /// Number of alternative token logprobs to request per generated token.
281    pub llm_top_logprobs: Option<usize>,
282    /// Auto-save after each completed `send()` or default-history `stream()` call.
283    pub auto_save: bool,
284    /// Optional artifact retention limits for large tool/program outputs.
285    pub artifact_store_limits: Option<crate::tools::ArtifactStoreLimits>,
286    /// Max consecutive parse errors before aborting (overrides default of 2).
287    /// `None` uses the `AgentConfig` default.
288    pub max_parse_retries: Option<u32>,
289    /// Per-tool execution timeout in milliseconds.
290    /// `None` = no timeout (default).
291    pub tool_timeout_ms: Option<u64>,
292    /// Per-model API HTTP timeout in milliseconds.
293    /// `None` = no timeout (default).
294    pub llm_api_timeout_ms: Option<u64>,
295    /// Circuit-breaker threshold: max consecutive LLM API failures before
296    /// aborting in non-streaming mode (overrides default of 3).
297    /// `None` uses the `AgentConfig` default.
298    pub circuit_breaker_threshold: Option<u32>,
299    /// Max consecutive identical tool signatures before the guard turns the
300    /// duplicate call into a failed tool observation.
301    ///
302    /// `None` uses the `AgentConfig` default. Hosts can raise this for long
303    /// research sessions where repeating a read/search with the same arguments
304    /// is wasteful but should not make the whole run brittle.
305    pub duplicate_tool_call_threshold: Option<u32>,
306    /// Optional concrete sandbox implementation.
307    ///
308    /// When set, `bash` tool commands are routed through this sandbox instead
309    /// of `std::process::Command`. The host application constructs and owns
310    /// the implementation (e.g., an A3S Box–backed handle).
311    pub sandbox_handle: Option<Arc<dyn crate::sandbox::BashSandbox>>,
312    /// Optional host-provided workspace backend.
313    ///
314    /// When set, built-in tools such as `read`, `write`, `ls`, and `bash`
315    /// execute against these workspace capabilities instead of assuming the
316    /// server-local filesystem. This is the primary extension point for DFS,
317    /// browser, container, and remote workspace deployments.
318    pub workspace_services: Option<Arc<crate::workspace::WorkspaceServices>>,
319    /// Enable auto-compaction when context usage exceeds threshold.
320    pub auto_compact: bool,
321    /// Context usage percentage threshold for auto-compaction (0.0 - 1.0).
322    /// Default: 0.80 (80%).
323    pub auto_compact_threshold: Option<f32>,
324    /// Model context window used for automatic compaction accounting.
325    ///
326    /// When omitted, the configured model's declared context limit is used,
327    /// falling back to the agent default when the model has no declaration.
328    pub max_context_tokens: Option<usize>,
329    /// Inject a continuation message when the LLM stops without completing the task.
330    /// `None` uses the `AgentConfig` default (true).
331    pub continuation_enabled: Option<bool>,
332    /// Maximum continuation injections per execution.
333    /// `None` uses the `AgentConfig` default (3).
334    pub max_continuation_turns: Option<u32>,
335    /// Maximum execution time in milliseconds.
336    /// `None` = no timeout (default).
337    /// When set, the execution loop will abort if it exceeds this duration.
338    pub max_execution_time_ms: Option<u64>,
339    /// Optional MCP manager for connecting to external MCP servers.
340    ///
341    /// When set, all tools from connected MCP servers are registered and
342    /// available during agent execution with names like `mcp__server__tool`.
343    pub mcp_manager: Option<Arc<crate::mcp::manager::McpManager>>,
344    /// Sampling temperature (0.0–1.0). Overrides the provider default.
345    pub temperature: Option<f32>,
346    /// Extended thinking budget in tokens (Anthropic only).
347    pub thinking_budget: Option<usize>,
348    /// Per-session tool round limit override.
349    ///
350    /// When set, overrides the agent-level `max_tool_rounds` for this session only.
351    /// Maps directly from [`AgentDefinition::max_steps`](crate::subagent::AgentDefinition::max_steps)
352    /// when creating sessions
353    /// via [`Agent::session_for_agent`].
354    pub max_tool_rounds: Option<usize>,
355    /// Per-session parallel fan-out limit override.
356    ///
357    /// Applies to delegated `task` fan-out, the legacy `parallel_task` alias,
358    /// plan wave execution, and safe parallel write batches.
359    pub max_parallel_tasks: Option<usize>,
360    /// Per-session automatic subagent delegation override.
361    pub auto_delegation: Option<crate::config::AutoDelegationConfig>,
362    /// Per-session switch for model-visible manual child-agent tools.
363    ///
364    /// This overlays the effective automatic delegation config instead of
365    /// replacing it, so callers can hide `task` and its compatibility alias
366    /// while preserving other delegation settings.
367    pub manual_delegation_enabled: Option<bool>,
368    /// Per-session kill switch for automatic parallel child-agent fan-out.
369    ///
370    /// This overlays the effective automatic delegation config instead of
371    /// replacing it, so callers can disable auto fan-out without disabling
372    /// automatic delegation itself.
373    pub auto_parallel_delegation: Option<bool>,
374    /// Slot-based system prompt customization.
375    ///
376    /// When set, overrides the agent-level prompt slots for this session.
377    /// Users can customize role, guidelines, response style, and extra instructions
378    /// without losing the core agentic capabilities.
379    pub prompt_slots: Option<SystemPromptSlots>,
380    /// Optional external hook executor.
381    ///
382    /// When set, it replaces the built-in `HookEngine` for this session.
383    pub hook_executor: Option<Arc<dyn crate::hooks::HookExecutor>>,
384}
385
386// ============================================================================
387// AgentSession
388// ============================================================================
389
390/// Workspace-bound session. All LLM and tool operations happen here.
391///
392/// History is automatically accumulated after each `send()` call and after
393/// `stream()` completes when no custom history is supplied.
394/// Use `history()` to retrieve the current conversation log.
395///
396/// Conversation operations are single-flight, including slash commands and
397/// checkpoint resume. An overlapping call returns
398/// [`CodeError::SessionBusy`](crate::error::CodeError::SessionBusy) immediately.
399/// A streaming operation remains active until its returned handle completes.
400pub struct AgentSession {
401    llm_client: Arc<dyn LlmClient>,
402    /// Provider-reported generation capacity shared by every loop and
403    /// host-direct tool call created for this session.
404    model_generation_admission: crate::llm::ModelGenerationAdmission,
405    tool_executor: Arc<ToolExecutor>,
406    tool_context: ToolContext,
407    config: AgentConfig,
408    workspace: PathBuf,
409    /// Unique session identifier.
410    session_id: String,
411    /// Internal conversation history, auto-updated after each `send()` and default-history `stream()`.
412    history: Arc<RwLock<Vec<Message>>>,
413    /// Fail-fast single-flight admission for transcript-affecting operations.
414    run_admission: Arc<run_admission::RunAdmission>,
415    /// Optional lane queue for priority-based tool execution.
416    command_queue: Option<Arc<crate::session_lane_queue::SessionLaneQueue>>,
417    /// Long-term memory handle.
418    ///
419    /// Built sessions resolve a default memory store. This remains optional for
420    /// compatibility with lower-level/manual construction paths.
421    memory: Option<Arc<crate::memory::AgentMemory>>,
422    /// Optional session store for persistence.
423    session_store: Option<Arc<dyn crate::store::SessionStore>>,
424    /// Runtime-owned fields used to build lossless persistence generations.
425    persistence_state: Arc<RwLock<session_persistence::SessionPersistenceState>>,
426    /// Auto-save after each completed `send()` or default-history `stream()`.
427    auto_save: bool,
428    /// Hook engine for lifecycle event interception.
429    hook_engine: Arc<crate::hooks::HookEngine>,
430    /// Optional external hook executor. When set, replaces `hook_engine` as the
431    /// executor passed to each `AgentLoop`.
432    hook_executor: Option<Arc<dyn crate::hooks::HookExecutor>>,
433    /// Deferred init warning: emitted as PersistenceFailed on first send() if set.
434    init_warning: Option<String>,
435    /// Slash command registry for `/command` dispatch.
436    /// Uses interior mutability so commands can be registered on a shared `Arc<AgentSession>`.
437    command_registry: std::sync::Mutex<CommandRegistry>,
438    /// Model identifier for display (e.g., "anthropic/claude-sonnet-4-20250514").
439    model_name: String,
440    /// Session-private MCP manager used by live add/remove operations.
441    mcp_manager: Arc<crate::mcp::manager::McpManager>,
442    /// Read-only MCP sources inherited from the parent agent and session options.
443    inherited_mcp_managers: Vec<Arc<crate::mcp::manager::McpManager>>,
444    /// Ordered MCP capability sources inherited by delegated child runs.
445    mcp_managers: Vec<Arc<crate::mcp::manager::McpManager>>,
446    /// Shared agent registry — populated at session creation; extended via register_agent_dir().
447    agent_registry: Arc<crate::subagent::AgentRegistry>,
448    /// Cancellation token for the current operation (send/stream).
449    /// Stored so that cancel() can abort ongoing LLM calls.
450    cancel_token: Arc<tokio::sync::Mutex<Option<tokio_util::sync::CancellationToken>>>,
451    /// ID of the run currently attached to the active cancellation token.
452    current_run_id: Arc<tokio::sync::Mutex<Option<String>>>,
453    /// In-memory run snapshots and event replay buffer for this session.
454    run_store: Arc<crate::run::InMemoryRunStore>,
455    /// Materialized view of delegated subagent task lifecycle, populated from runtime events.
456    subagent_tasks: Arc<crate::subagent_task_tracker::InMemorySubagentTaskTracker>,
457    /// Currently executing tools observed from runtime events.
458    active_tools: Arc<tokio::sync::RwLock<HashMap<String, ActiveToolState>>>,
459    /// Compact execution traces for this session.
460    trace_sink: crate::trace::InMemoryTraceSink,
461    /// Structured completion evidence collected from agent and explicit verification runs.
462    verification_reports: Arc<RwLock<Vec<crate::verification::VerificationReport>>>,
463    /// Set once `close()` has been called. Subsequent send/stream calls
464    /// fast-fail with [`crate::error::CodeError::SessionClosed`].
465    closed: Arc<std::sync::atomic::AtomicBool>,
466    /// Session-level parent cancellation token.
467    ///
468    /// Every in-flight run (blocking send, stream, delegated subagent task)
469    /// derives its per-operation token from this one via `child_token()`,
470    /// so `session_cancel.cancel()` cascades to all of them. `close()` fires
471    /// this token first, after which any new `child_token()` returns an
472    /// already-cancelled token (defending against close/spawn races).
473    pub(crate) session_cancel: tokio_util::sync::CancellationToken,
474    /// Shared `Arc`-handle used by both [`AgentSession::close`] and the
475    /// parent [`Agent`]'s registry. The handle bundles every field needed
476    /// to perform the close sequence so the two entry points cannot drift.
477    close_handle: Arc<SessionCloseHandle>,
478    /// Runtime-mutable override for the budget guard. When set, takes
479    /// precedence over `config.budget_guard` on the next agent-loop
480    /// build. Lets SDK callers (Node especially) install a host-side
481    /// guard after `session()` has returned without ever putting a
482    /// JS callable into `SessionOptions`.
483    runtime_budget_guard: std::sync::Mutex<Option<Arc<dyn crate::budget::BudgetGuard>>>,
484    /// Multi-tenant label. Framework only carries the string; semantics
485    /// belong to the host.
486    pub(crate) tenant_id: Option<String>,
487    /// Principal that triggered the session (user / service / etc.).
488    pub(crate) principal: Option<String>,
489    /// Logical identifier of the agent template the session was
490    /// instantiated from.
491    pub(crate) agent_template_id: Option<String>,
492    /// Distributed-trace correlation id propagated to hooks / traces.
493    pub(crate) correlation_id: Option<String>,
494}
495
496// ============================================================================
497// Tests
498// ============================================================================
499
500#[cfg(test)]
501mod replacement_tests;
502#[cfg(test)]
503mod tests;