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 /// Inject a continuation message when the LLM stops without completing the task.
296 /// `None` uses the `AgentConfig` default (true).
297 pub continuation_enabled: Option<bool>,
298 /// Maximum continuation injections per execution.
299 /// `None` uses the `AgentConfig` default (3).
300 pub max_continuation_turns: Option<u32>,
301 /// Maximum execution time in milliseconds.
302 /// `None` = no timeout (default).
303 /// When set, the execution loop will abort if it exceeds this duration.
304 pub max_execution_time_ms: Option<u64>,
305 /// Optional MCP manager for connecting to external MCP servers.
306 ///
307 /// When set, all tools from connected MCP servers are registered and
308 /// available during agent execution with names like `mcp__server__tool`.
309 pub mcp_manager: Option<Arc<crate::mcp::manager::McpManager>>,
310 /// Sampling temperature (0.0–1.0). Overrides the provider default.
311 pub temperature: Option<f32>,
312 /// Extended thinking budget in tokens (Anthropic only).
313 pub thinking_budget: Option<usize>,
314 /// Per-session tool round limit override.
315 ///
316 /// When set, overrides the agent-level `max_tool_rounds` for this session only.
317 /// Maps directly from [`AgentDefinition::max_steps`] when creating sessions
318 /// via [`Agent::session_for_agent`].
319 pub max_tool_rounds: Option<usize>,
320 /// Per-session parallel fan-out limit override.
321 ///
322 /// Applies to delegated `parallel_task`, plan wave execution, and safe
323 /// parallel write batches.
324 pub max_parallel_tasks: Option<usize>,
325 /// Per-session automatic subagent delegation override.
326 pub auto_delegation: Option<crate::config::AutoDelegationConfig>,
327 /// Per-session switch for model-visible manual child-agent tools.
328 ///
329 /// This overlays the effective automatic delegation config instead of
330 /// replacing it, so callers can hide `task` / `parallel_task` while
331 /// preserving other delegation settings.
332 pub manual_delegation_enabled: Option<bool>,
333 /// Per-session kill switch for automatic parallel child-agent fan-out.
334 ///
335 /// This overlays the effective automatic delegation config instead of
336 /// replacing it, so callers can disable auto fan-out without disabling
337 /// automatic delegation itself.
338 pub auto_parallel_delegation: Option<bool>,
339 /// Slot-based system prompt customization.
340 ///
341 /// When set, overrides the agent-level prompt slots for this session.
342 /// Users can customize role, guidelines, response style, and extra instructions
343 /// without losing the core agentic capabilities.
344 pub prompt_slots: Option<SystemPromptSlots>,
345 /// Optional external hook executor.
346 ///
347 /// When set, it replaces the built-in `HookEngine` for this session.
348 pub hook_executor: Option<Arc<dyn crate::hooks::HookExecutor>>,
349}
350
351// ============================================================================
352// AgentSession
353// ============================================================================
354
355/// Workspace-bound session. All LLM and tool operations happen here.
356///
357/// History is automatically accumulated after each `send()` call and after
358/// `stream()` completes when no custom history is supplied.
359/// Use `history()` to retrieve the current conversation log.
360///
361/// Conversation operations are single-flight, including slash commands and
362/// checkpoint resume. An overlapping call returns
363/// [`CodeError::SessionBusy`](crate::error::CodeError::SessionBusy) immediately.
364/// A streaming operation remains active until its returned handle completes.
365pub struct AgentSession {
366 llm_client: Arc<dyn LlmClient>,
367 tool_executor: Arc<ToolExecutor>,
368 tool_context: ToolContext,
369 config: AgentConfig,
370 workspace: PathBuf,
371 /// Unique session identifier.
372 session_id: String,
373 /// Internal conversation history, auto-updated after each `send()` and default-history `stream()`.
374 history: Arc<RwLock<Vec<Message>>>,
375 /// Fail-fast single-flight admission for transcript-affecting operations.
376 run_admission: Arc<run_admission::RunAdmission>,
377 /// Optional lane queue for priority-based tool execution.
378 command_queue: Option<Arc<crate::session_lane_queue::SessionLaneQueue>>,
379 /// Long-term memory handle.
380 ///
381 /// Built sessions resolve a default memory store. This remains optional for
382 /// compatibility with lower-level/manual construction paths.
383 memory: Option<Arc<crate::memory::AgentMemory>>,
384 /// Optional session store for persistence.
385 session_store: Option<Arc<dyn crate::store::SessionStore>>,
386 /// Runtime-owned fields used to build lossless persistence generations.
387 persistence_state: Arc<RwLock<session_persistence::SessionPersistenceState>>,
388 /// Auto-save after each completed `send()` or default-history `stream()`.
389 auto_save: bool,
390 /// Hook engine for lifecycle event interception.
391 hook_engine: Arc<crate::hooks::HookEngine>,
392 /// Optional external hook executor. When set, replaces `hook_engine` as the
393 /// executor passed to each `AgentLoop`.
394 hook_executor: Option<Arc<dyn crate::hooks::HookExecutor>>,
395 /// Deferred init warning: emitted as PersistenceFailed on first send() if set.
396 init_warning: Option<String>,
397 /// Slash command registry for `/command` dispatch.
398 /// Uses interior mutability so commands can be registered on a shared `Arc<AgentSession>`.
399 command_registry: std::sync::Mutex<CommandRegistry>,
400 /// Model identifier for display (e.g., "anthropic/claude-sonnet-4-20250514").
401 model_name: String,
402 /// Session-private MCP manager used by live add/remove operations.
403 mcp_manager: Arc<crate::mcp::manager::McpManager>,
404 /// Read-only MCP sources inherited from the parent agent and session options.
405 inherited_mcp_managers: Vec<Arc<crate::mcp::manager::McpManager>>,
406 /// Ordered MCP capability sources inherited by delegated child runs.
407 mcp_managers: Vec<Arc<crate::mcp::manager::McpManager>>,
408 /// Shared agent registry — populated at session creation; extended via register_agent_dir().
409 agent_registry: Arc<crate::subagent::AgentRegistry>,
410 /// Cancellation token for the current operation (send/stream).
411 /// Stored so that cancel() can abort ongoing LLM calls.
412 cancel_token: Arc<tokio::sync::Mutex<Option<tokio_util::sync::CancellationToken>>>,
413 /// ID of the run currently attached to the active cancellation token.
414 current_run_id: Arc<tokio::sync::Mutex<Option<String>>>,
415 /// In-memory run snapshots and event replay buffer for this session.
416 run_store: Arc<crate::run::InMemoryRunStore>,
417 /// Materialized view of delegated subagent task lifecycle, populated from runtime events.
418 subagent_tasks: Arc<crate::subagent_task_tracker::InMemorySubagentTaskTracker>,
419 /// Currently executing tools observed from runtime events.
420 active_tools: Arc<tokio::sync::RwLock<HashMap<String, ActiveToolState>>>,
421 /// Compact execution traces for this session.
422 trace_sink: crate::trace::InMemoryTraceSink,
423 /// Structured completion evidence collected from agent and explicit verification runs.
424 verification_reports: Arc<RwLock<Vec<crate::verification::VerificationReport>>>,
425 /// Set once `close()` has been called. Subsequent send/stream calls
426 /// fast-fail with [`crate::error::CodeError::SessionClosed`].
427 closed: Arc<std::sync::atomic::AtomicBool>,
428 /// Session-level parent cancellation token.
429 ///
430 /// Every in-flight run (blocking send, stream, delegated subagent task)
431 /// derives its per-operation token from this one via `child_token()`,
432 /// so `session_cancel.cancel()` cascades to all of them. `close()` fires
433 /// this token first, after which any new `child_token()` returns an
434 /// already-cancelled token (defending against close/spawn races).
435 pub(crate) session_cancel: tokio_util::sync::CancellationToken,
436 /// Shared `Arc`-handle used by both [`AgentSession::close`] and the
437 /// parent [`Agent`]'s registry. The handle bundles every field needed
438 /// to perform the close sequence so the two entry points cannot drift.
439 close_handle: Arc<SessionCloseHandle>,
440 /// Runtime-mutable override for the budget guard. When set, takes
441 /// precedence over `config.budget_guard` on the next agent-loop
442 /// build. Lets SDK callers (Node especially) install a host-side
443 /// guard after `session()` has returned without ever putting a
444 /// JS callable into `SessionOptions`.
445 runtime_budget_guard: std::sync::Mutex<Option<Arc<dyn crate::budget::BudgetGuard>>>,
446 /// Multi-tenant label. Framework only carries the string; semantics
447 /// belong to the host.
448 pub(crate) tenant_id: Option<String>,
449 /// Principal that triggered the session (user / service / etc.).
450 pub(crate) principal: Option<String>,
451 /// Logical identifier of the agent template the session was
452 /// instantiated from.
453 pub(crate) agent_template_id: Option<String>,
454 /// Distributed-trace correlation id propagated to hooks / traces.
455 pub(crate) correlation_id: Option<String>,
456}
457
458// ============================================================================
459// Tests
460// ============================================================================
461
462#[cfg(test)]
463mod tests;