Skip to main content

a3s_code_core/agent_api/
agent_facade.rs

1use super::*;
2
3// ============================================================================
4// Agent
5// ============================================================================
6
7/// High-level agent facade.
8///
9/// Holds the LLM client and agent config. Workspace-independent.
10/// Use [`Agent::session()`] to bind to a workspace.
11pub struct Agent {
12    pub(super) code_config: CodeConfig,
13    pub(super) config: AgentConfig,
14    /// Shared priority admission for every session and independent task.
15    pub(super) task_scheduler: Arc<crate::task_scheduler::TaskScheduler>,
16    /// Global MCP manager loaded from config.mcp_servers
17    pub(super) global_mcp: Option<Arc<crate::mcp::manager::McpManager>>,
18    /// Pre-fetched MCP tool definitions from global_mcp (cached at creation time).
19    /// Wrapped in Mutex so `refresh_mcp_tools()` can update the cache without `&mut self`.
20    pub(super) global_mcp_tools: std::sync::Mutex<Vec<(String, crate::mcp::McpTool)>>,
21    /// Tracks session IDs reserved by in-progress builds and every live session
22    /// created by this agent. Build reservations prevent duplicate IDs and make
23    /// construction finalization atomic with [`Agent::close`]. Live sessions
24    /// are held via `Weak` refs and pruned on registry access after drop.
25    ///
26    /// Uses a synchronous lock so the sync `Agent::session()` factory can
27    /// insert without nesting tokio runtimes. The lock is only held for
28    /// brief insert/scan operations — async close work happens after the
29    /// lock is released.
30    pub(super) sessions: Arc<std::sync::Mutex<agent_sessions::SessionRegistry>>,
31    /// Set once `Agent::close()` has been called. Subsequent `session()` /
32    /// `resume_session()` calls fail fast with `CodeError::SessionClosed`.
33    pub(super) closed: Arc<std::sync::atomic::AtomicBool>,
34}
35
36/// Async-first session construction API.
37///
38/// Builder methods only record typed configuration. Filesystem access, queue
39/// startup, and MCP discovery happen once in [`build`](Self::build).
40#[must_use = "a session builder does nothing until build() is awaited"]
41pub struct SessionBuilder<'a> {
42    agent: &'a Agent,
43    workspace: String,
44    options: SessionOptions,
45}
46
47impl<'a> SessionBuilder<'a> {
48    fn new(agent: &'a Agent, workspace: impl Into<String>) -> Self {
49        Self {
50            agent,
51            workspace: workspace.into(),
52            options: SessionOptions::default(),
53        }
54    }
55
56    /// Replace the per-session option patch.
57    pub fn options(mut self, options: SessionOptions) -> Self {
58        self.options = options;
59        self
60    }
61
62    /// Resolve configuration, initialize async resources, and build the session.
63    pub async fn build(self) -> Result<AgentSession> {
64        agent_sessions::create_session_async(self.agent, self.workspace, Some(self.options)).await
65    }
66}
67
68impl std::fmt::Debug for Agent {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        f.debug_struct("Agent").finish()
71    }
72}
73
74impl Agent {
75    /// Create from a config file path or inline ACL-compatible string.
76    ///
77    /// Auto-detects `.acl` file paths vs inline ACL-compatible config.
78    pub async fn new(config_source: impl Into<String>) -> Result<Self> {
79        let config = agent_bootstrap::load_code_config(config_source.into())?;
80        Self::from_config(config).await
81    }
82
83    /// Create from a config file path or inline ACL-compatible string.
84    ///
85    /// Alias for [`Agent::new()`] — provides a consistent API with
86    /// the Python and Node.js SDKs.
87    pub async fn create(config_source: impl Into<String>) -> Result<Self> {
88        Self::new(config_source).await
89    }
90
91    /// Create from a [`CodeConfig`] struct.
92    pub async fn from_config(config: CodeConfig) -> Result<Self> {
93        agent_bootstrap::build_agent_from_config(config).await
94    }
95
96    /// Re-fetch tool definitions from all connected global MCP servers and
97    /// update the internal cache.
98    ///
99    /// Call this when an MCP server has added or removed tools since the
100    /// agent was created. The refreshed tools will be visible to all
101    /// **new** sessions created after this call; existing sessions are
102    /// unaffected (their `ToolExecutor` snapshot is already built).
103    pub async fn refresh_mcp_tools(&self) -> Result<()> {
104        agent_sessions::refresh_mcp_tools(self).await
105    }
106
107    /// Start async-first construction of a workspace-bound session.
108    pub fn session_builder(&self, workspace: impl Into<String>) -> SessionBuilder<'_> {
109        SessionBuilder::new(self, workspace)
110    }
111
112    /// Build a workspace-bound session asynchronously.
113    ///
114    /// A session ID may have only one live or in-progress session per `Agent`.
115    /// Reusing an occupied ID returns a typed session-configuration error.
116    pub async fn session_async(
117        &self,
118        workspace: impl Into<String>,
119        options: Option<SessionOptions>,
120    ) -> Result<AgentSession> {
121        agent_sessions::create_session_async(self, workspace, options).await
122    }
123
124    /// Open a protocol-owned session, resuming its complete persisted snapshot
125    /// when one exists and optionally creating a fresh session otherwise.
126    ///
127    /// This remains crate-private because public SDK callers should choose
128    /// explicitly between `session_async` and `resume_session_async`. The
129    /// native headless Harness needs the atomic policy so process restarts do
130    /// not bypass Code's existing session/run store.
131    pub(crate) async fn open_protocol_session_async(
132        &self,
133        workspace: impl Into<String>,
134        options: SessionOptions,
135        create_if_missing: bool,
136    ) -> Result<Option<AgentSession>> {
137        agent_sessions::open_protocol_session_async(self, workspace, options, create_if_missing)
138            .await
139    }
140
141    /// Bind to a workspace directory, returning an [`AgentSession`].
142    ///
143    /// This compatibility entry point never starts or blocks an async runtime.
144    /// It requires an explicit, pre-initialized `memory_store`; an optional
145    /// pre-initialized session store and cached global MCP tools are accepted.
146    /// File-store specs/defaults, queues, RL trajectory files, and host-supplied
147    /// MCP sources require [`session_builder`](Self::session_builder).
148    /// A session ID may have only one live or in-progress session per `Agent`.
149    pub fn session(
150        &self,
151        workspace: impl Into<String>,
152        options: Option<SessionOptions>,
153    ) -> Result<AgentSession> {
154        agent_sessions::create_session(self, workspace, options)
155    }
156
157    /// Create a session pre-configured from an
158    /// [`AgentDefinition`](crate::subagent::AgentDefinition).
159    ///
160    /// Maps the definition's `permissions`, `prompt`, `model`, and `max_steps`
161    /// directly into [`SessionOptions`], so markdown/YAML-defined subagents can
162    /// be used by delegation and advanced control-plane flows without manual wiring.
163    ///
164    /// The mapping follows the same logic as the built-in `task` tool:
165    /// - `permissions` → `permission_checker`
166    /// - `prompt`      → `prompt_slots.extra`
167    /// - `max_steps`   → `max_tool_rounds`
168    /// - `model`       → `model` (as `"provider/model"` string)
169    ///
170    /// `extra` can supply additional overrides (e.g. `planning_enabled`) that
171    /// take precedence over the definition's values.
172    pub fn session_for_agent(
173        &self,
174        workspace: impl Into<String>,
175        def: &crate::subagent::AgentDefinition,
176        extra: Option<SessionOptions>,
177    ) -> Result<AgentSession> {
178        agent_sessions::create_session_for_agent(self, workspace, def, extra)
179    }
180
181    /// Async-first variant of [`session_for_agent`](Self::session_for_agent).
182    pub async fn session_for_agent_async(
183        &self,
184        workspace: impl Into<String>,
185        def: &crate::subagent::AgentDefinition,
186        extra: Option<SessionOptions>,
187    ) -> Result<AgentSession> {
188        agent_sessions::create_session_for_agent_async(self, workspace, def, extra).await
189    }
190
191    /// Create a session from a reproducible disposable worker recipe.
192    ///
193    /// This is the cattle-mode companion to [`Agent::session_for_agent`]: callers
194    /// provide a small [`WorkerAgentSpec`](crate::subagent::WorkerAgentSpec), and
195    /// A3S Code compiles it into the same runtime definition used by delegated agents.
196    pub fn session_for_worker(
197        &self,
198        workspace: impl Into<String>,
199        spec: crate::subagent::WorkerAgentSpec,
200        extra: Option<SessionOptions>,
201    ) -> Result<AgentSession> {
202        let def = spec.into_agent_definition();
203        self.session_for_agent(workspace, &def, extra)
204    }
205
206    /// Async-first variant of [`session_for_worker`](Self::session_for_worker).
207    pub async fn session_for_worker_async(
208        &self,
209        workspace: impl Into<String>,
210        spec: crate::subagent::WorkerAgentSpec,
211        extra: Option<SessionOptions>,
212    ) -> Result<AgentSession> {
213        let def = spec.into_agent_definition();
214        self.session_for_agent_async(workspace, &def, extra).await
215    }
216
217    /// Resume a previously saved session by ID.
218    ///
219    /// Loads the session data from the store, rebuilds the `AgentSession` with
220    /// the saved conversation history, and returns it ready for continued use.
221    ///
222    /// The `options` must include a `session_store` (or `with_file_session_store`)
223    /// that contains the saved session.
224    ///
225    /// The resumed session uses the **workspace stored in the snapshot**, not a
226    /// workspace from `options`. The store is therefore a trust boundary: its
227    /// contents drive the resumed workspace and the persisted runtime policies.
228    /// The requested ID must not already be live or under construction on this
229    /// `Agent`.
230    ///
231    /// This synchronous compatibility entry point returns
232    /// [`CodeError::AsyncSessionBuildRequired`](crate::error::CodeError::AsyncSessionBuildRequired);
233    /// use [`resume_session_async`](Self::resume_session_async).
234    pub fn resume_session(
235        &self,
236        session_id: &str,
237        options: SessionOptions,
238    ) -> Result<AgentSession> {
239        agent_sessions::resume_session(self, session_id, options)
240    }
241
242    /// Resume a persisted session without blocking the async runtime.
243    ///
244    /// The requested ID must not already be live or under construction on this
245    /// `Agent`.
246    pub async fn resume_session_async(
247        &self,
248        session_id: &str,
249        options: SessionOptions,
250    ) -> Result<AgentSession> {
251        agent_sessions::resume_session_async(self, session_id, options).await
252    }
253
254    /// Rebuild a live persisted session with new options without exposing a
255    /// closed-session gap to the caller.
256    ///
257    /// The current session is saved first and remains live while the
258    /// replacement is constructed and restored. If construction fails, the
259    /// current session stays registered and usable. On success, the registry
260    /// is switched to the replacement before the old session is closed.
261    ///
262    /// Callers must serialize this operation with conversation work on
263    /// `current` (for example, only reconfigure an idle interactive session).
264    /// The replacement keeps the same session ID and persisted history.
265    pub async fn replace_session_async(
266        &self,
267        current: &AgentSession,
268        options: SessionOptions,
269    ) -> Result<AgentSession> {
270        agent_sessions::replace_session_async(self, current, options).await
271    }
272
273    /// Return the IDs of every live session created from this agent.
274    ///
275    /// "Live" means the caller still holds an [`AgentSession`] — sessions
276    /// that have been dropped are pruned lazily on each call. The list is
277    /// sorted to make output stable for tests/UIs.
278    pub async fn list_sessions(&self) -> Vec<String> {
279        agent_sessions::list_sessions(self).await
280    }
281
282    /// Close a specific live session by its session ID.
283    ///
284    /// Returns `true` when a live session with the given id was found and
285    /// transitioned from open to closed by this call; `false` when no live
286    /// session has that id, or when the session was already closed.
287    ///
288    /// This is the out-of-band counterpart to [`AgentSession::close`]: it
289    /// performs exactly the same cleanup but can be invoked without holding
290    /// a reference to the session itself — useful for control-plane code
291    /// that only knows the session ID.
292    pub async fn close_session(&self, session_id: &str) -> bool {
293        agent_sessions::close_session(self, session_id).await
294    }
295
296    /// Close every live session created from this agent and tear down
297    /// background resources owned by the agent (global MCP connections).
298    ///
299    /// After this call:
300    /// - Every live `AgentSession` is closed (same effect as calling
301    ///   [`AgentSession::close`] on each).
302    /// - Subsequent [`Agent::session`] / [`Agent::resume_session`] calls
303    ///   fail fast with [`CodeError::SessionClosed`](crate::error::CodeError::SessionClosed).
304    /// - Session builds admitted before close but not yet finalized are rejected
305    ///   at finalization and cannot return an open session.
306    ///
307    /// Idempotent: subsequent calls are no-ops and are guaranteed not to
308    /// panic.
309    pub async fn close(&self) {
310        agent_sessions::close_agent(self).await
311    }
312
313    /// Return current cross-session priority scheduler occupancy.
314    pub async fn task_scheduler_stats(
315        &self,
316    ) -> std::result::Result<
317        crate::task_scheduler::TaskSchedulerStats,
318        crate::task_scheduler::TaskSchedulerError,
319    > {
320        self.task_scheduler.stats().await
321    }
322
323    /// Return whether [`close`](Self::close) has been called on this agent.
324    pub fn is_closed(&self) -> bool {
325        self.closed.load(std::sync::atomic::Ordering::Acquire)
326    }
327
328    /// Disconnect every global MCP server whose last activity is older
329    /// than `idle_threshold_ms`. Returns the names of disconnected
330    /// servers (empty when there is no global MCP manager or when
331    /// nothing is idle).
332    ///
333    /// Hosts running thousands of long-lived sessions should call this
334    /// periodically (e.g. every 60s with a 5-min threshold) to release
335    /// file descriptors and background workers from quiet MCP servers
336    /// without losing the server's configuration. A subsequent tool
337    /// call on the same server will require an explicit reconnect.
338    pub async fn disconnect_idle_mcp(&self, idle_threshold_ms: u64) -> Vec<String> {
339        match &self.global_mcp {
340            Some(mcp) => mcp.disconnect_idle(idle_threshold_ms).await,
341            None => Vec::new(),
342        }
343    }
344
345    #[cfg(test)]
346    pub(super) fn build_session(
347        &self,
348        workspace: String,
349        llm_client: Arc<dyn LlmClient>,
350        opts: &SessionOptions,
351    ) -> Result<AgentSession> {
352        let mut opts = opts.clone().with_llm_client(llm_client);
353        if opts.memory_store.is_none() && opts.file_memory_dir.is_none() {
354            opts = opts.with_memory(Arc::new(a3s_memory::InMemoryStore::new()));
355        }
356        agent_sessions::create_session(self, workspace, Some(opts))
357    }
358}