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