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