Skip to main content

a3s_code_core/agent_api/
session_options.rs

1//! Session option builder interface.
2//!
3//! `SessionOptions` is the host-facing capability configuration for a session.
4//! Keeping the builder implementation here lets `agent_api.rs` keep the type
5//! shape visible while moving option construction behavior behind this module.
6
7use super::SessionOptions;
8use crate::prompts::{PlanningMode, SystemPromptSlots};
9use crate::queue::SessionQueueConfig;
10use crate::subagent::WorkerAgentSpec;
11use a3s_memory::MemoryStore;
12use std::path::PathBuf;
13use std::sync::Arc;
14
15impl std::fmt::Debug for SessionOptions {
16    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17        f.debug_struct("SessionOptions")
18            .field("model", &self.model)
19            .field("agent_dirs", &self.agent_dirs)
20            .field("worker_agents", &self.worker_agents.len())
21            .field("skill_dirs", &self.skill_dirs)
22            .field("queue_config", &self.queue_config)
23            .field("security_provider", &self.security_provider.is_some())
24            .field("context_providers", &self.context_providers.len())
25            .field("confirmation_manager", &self.confirmation_manager.is_some())
26            .field("permission_checker", &self.permission_checker.is_some())
27            .field("permission_policy", &self.permission_policy.is_some())
28            .field("planning_mode", &self.planning_mode)
29            .field("goal_tracking", &self.goal_tracking)
30            .field(
31                "skill_registry",
32                &self
33                    .skill_registry
34                    .as_ref()
35                    .map(|r| format!("{} skills", r.len())),
36            )
37            .field("memory_store", &self.memory_store.is_some())
38            .field("session_store", &self.session_store.is_some())
39            .field("session_id", &self.session_id)
40            .field("auto_save", &self.auto_save)
41            .field("artifact_store_limits", &self.artifact_store_limits)
42            .field("max_parse_retries", &self.max_parse_retries)
43            .field("tool_timeout_ms", &self.tool_timeout_ms)
44            .field("circuit_breaker_threshold", &self.circuit_breaker_threshold)
45            .field("sandbox_handle", &self.sandbox_handle.is_some())
46            .field("auto_compact", &self.auto_compact)
47            .field("auto_compact_threshold", &self.auto_compact_threshold)
48            .field("continuation_enabled", &self.continuation_enabled)
49            .field("max_continuation_turns", &self.max_continuation_turns)
50            .field("mcp_manager", &self.mcp_manager.is_some())
51            .field("temperature", &self.temperature)
52            .field("thinking_budget", &self.thinking_budget)
53            .field("max_tool_rounds", &self.max_tool_rounds)
54            .field("prompt_slots", &self.prompt_slots.is_some())
55            .finish()
56    }
57}
58
59impl SessionOptions {
60    pub fn new() -> Self {
61        Self::default()
62    }
63
64    pub fn with_model(mut self, model: impl Into<String>) -> Self {
65        self.model = Some(model.into());
66        self
67    }
68
69    pub fn with_agent_dir(mut self, dir: impl Into<PathBuf>) -> Self {
70        self.agent_dirs.push(dir.into());
71        self
72    }
73
74    /// Register a cattle-style worker with this session's task delegation registry.
75    pub fn with_worker_agent(mut self, spec: WorkerAgentSpec) -> Self {
76        self.worker_agents.push(spec);
77        self
78    }
79
80    /// Register multiple cattle-style workers with this session.
81    pub fn with_worker_agents<I>(mut self, specs: I) -> Self
82    where
83        I: IntoIterator<Item = WorkerAgentSpec>,
84    {
85        self.worker_agents.extend(specs);
86        self
87    }
88
89    pub fn with_queue_config(mut self, config: SessionQueueConfig) -> Self {
90        self.queue_config = Some(config);
91        self
92    }
93
94    /// Enable default security provider with taint tracking and output sanitization
95    pub fn with_default_security(mut self) -> Self {
96        self.security_provider = Some(Arc::new(crate::security::DefaultSecurityProvider::new()));
97        self
98    }
99
100    /// Set a custom security provider
101    pub fn with_security_provider(
102        mut self,
103        provider: Arc<dyn crate::security::SecurityProvider>,
104    ) -> Self {
105        self.security_provider = Some(provider);
106        self
107    }
108
109    /// Add a file system context provider for simple RAG
110    pub fn with_fs_context(mut self, root_path: impl Into<PathBuf>) -> Self {
111        let config = crate::context::FileSystemContextConfig::new(root_path);
112        self.context_providers
113            .push(Arc::new(crate::context::FileSystemContextProvider::new(
114                config,
115            )));
116        self
117    }
118
119    /// Add a custom context provider
120    pub fn with_context_provider(
121        mut self,
122        provider: Arc<dyn crate::context::ContextProvider>,
123    ) -> Self {
124        self.context_providers.push(provider);
125        self
126    }
127
128    /// Set a confirmation manager for HITL
129    pub fn with_confirmation_manager(
130        mut self,
131        manager: Arc<dyn crate::hitl::ConfirmationProvider>,
132    ) -> Self {
133        self.confirmation_manager = Some(manager);
134        self
135    }
136
137    /// Set a confirmation policy for HITL
138    ///
139    /// The policy will be used to create a ConfirmationManager when the session is built.
140    /// This is the preferred way to configure HITL from the Node SDK.
141    pub fn with_confirmation_policy(mut self, policy: crate::hitl::ConfirmationPolicy) -> Self {
142        self.confirmation_policy = Some(policy);
143        self
144    }
145
146    /// Set a serializable permission policy for tool execution.
147    pub fn with_permission_policy(mut self, policy: crate::permissions::PermissionPolicy) -> Self {
148        self.permission_checker = Some(Arc::new(policy.clone()));
149        self.permission_policy = Some(policy);
150        self
151    }
152
153    /// Set a permission checker
154    pub fn with_permission_checker(
155        mut self,
156        checker: Arc<dyn crate::permissions::PermissionChecker>,
157    ) -> Self {
158        self.permission_checker = Some(checker);
159        self
160    }
161
162    /// Set planning mode
163    pub fn with_planning_mode(mut self, mode: PlanningMode) -> Self {
164        self.planning_mode = mode;
165        self
166    }
167
168    /// Enable planning (shortcut for `with_planning_mode(PlanningMode::Enabled)`)
169    pub fn with_planning(mut self, enabled: bool) -> Self {
170        self.planning_mode = if enabled {
171            PlanningMode::Enabled
172        } else {
173            PlanningMode::Disabled
174        };
175        self
176    }
177
178    /// Enable goal tracking
179    pub fn with_goal_tracking(mut self, enabled: bool) -> Self {
180        self.goal_tracking = enabled;
181        self
182    }
183
184    /// Add a skill registry with built-in skills
185    pub fn with_builtin_skills(mut self) -> Self {
186        self.skill_registry = Some(Arc::new(crate::skills::SkillRegistry::with_builtins()));
187        self
188    }
189
190    /// Add a custom skill registry
191    pub fn with_skill_registry(mut self, registry: Arc<crate::skills::SkillRegistry>) -> Self {
192        self.skill_registry = Some(registry);
193        self
194    }
195
196    /// Add skill directories to scan for skill files (*.md).
197    /// Merged with any global `skill_dirs` from [`CodeConfig`] at session build time.
198    pub fn with_skill_dirs(mut self, dirs: impl IntoIterator<Item = impl Into<PathBuf>>) -> Self {
199        self.skill_dirs.extend(dirs.into_iter().map(Into::into));
200        self
201    }
202
203    /// Load skills from a directory (eager — scans immediately into a registry).
204    pub fn with_skills_from_dir(mut self, dir: impl AsRef<std::path::Path>) -> Self {
205        let registry = self
206            .skill_registry
207            .unwrap_or_else(|| Arc::new(crate::skills::SkillRegistry::new()));
208        if let Err(e) = registry.load_from_dir(&dir) {
209            tracing::warn!(
210                dir = %dir.as_ref().display(),
211                error = %e,
212                "Failed to load skills from directory — continuing without them"
213            );
214        }
215        self.skill_registry = Some(registry);
216        self
217    }
218
219    /// Set a custom memory store
220    pub fn with_memory(mut self, store: Arc<dyn MemoryStore>) -> Self {
221        self.memory_store = Some(store);
222        self
223    }
224
225    /// Use a file-based memory store at the given directory.
226    ///
227    /// The store is created lazily when the session is built (requires async).
228    /// This stores the directory path; `FileMemoryStore::new()` is called during
229    /// session construction.
230    pub fn with_file_memory(mut self, dir: impl Into<PathBuf>) -> Self {
231        self.file_memory_dir = Some(dir.into());
232        self
233    }
234
235    /// Set a session store for persistence
236    pub fn with_session_store(mut self, store: Arc<dyn crate::store::SessionStore>) -> Self {
237        self.session_store = Some(store);
238        self
239    }
240
241    /// Use a file-based session store at the given directory
242    pub fn with_file_session_store(mut self, dir: impl Into<PathBuf>) -> Self {
243        let dir = dir.into();
244        match tokio::runtime::Handle::try_current() {
245            Ok(handle) => {
246                match tokio::task::block_in_place(|| {
247                    handle.block_on(crate::store::FileSessionStore::new(dir))
248                }) {
249                    Ok(store) => {
250                        self.session_store =
251                            Some(Arc::new(store) as Arc<dyn crate::store::SessionStore>);
252                    }
253                    Err(e) => {
254                        tracing::warn!("Failed to create file session store: {}", e);
255                    }
256                }
257            }
258            Err(_) => {
259                tracing::warn!(
260                    "No async runtime available for file session store — persistence disabled"
261                );
262            }
263        }
264        self
265    }
266
267    /// Set an explicit session ID (auto-generated UUID if not set)
268    pub fn with_session_id(mut self, id: impl Into<String>) -> Self {
269        self.session_id = Some(id.into());
270        self
271    }
272
273    /// Enable auto-save after each `send()` call
274    pub fn with_auto_save(mut self, enabled: bool) -> Self {
275        self.auto_save = enabled;
276        self
277    }
278
279    /// Set artifact retention limits for this session.
280    pub fn with_artifact_store_limits(mut self, limits: crate::tools::ArtifactStoreLimits) -> Self {
281        self.artifact_store_limits = Some(limits);
282        self
283    }
284
285    /// Set the maximum number of consecutive malformed-tool-args errors before
286    /// the agent loop bails.
287    ///
288    /// Default: 2 (the LLM gets two chances to self-correct before the session
289    /// is aborted).
290    pub fn with_parse_retries(mut self, max: u32) -> Self {
291        self.max_parse_retries = Some(max);
292        self
293    }
294
295    /// Set a per-tool execution timeout.
296    ///
297    /// When set, each tool execution is wrapped in `tokio::time::timeout`.
298    /// A timeout produces an error message that is fed back to the LLM
299    /// (the session continues).
300    pub fn with_tool_timeout(mut self, timeout_ms: u64) -> Self {
301        self.tool_timeout_ms = Some(timeout_ms);
302        self
303    }
304
305    /// Set the circuit-breaker threshold.
306    ///
307    /// In non-streaming mode, the agent retries transient LLM API failures up
308    /// to this many times (with exponential backoff) before aborting.
309    /// Default: 3 attempts.
310    pub fn with_circuit_breaker(mut self, threshold: u32) -> Self {
311        self.circuit_breaker_threshold = Some(threshold);
312        self
313    }
314
315    /// Enable all resilience defaults with sensible values:
316    ///
317    /// - `max_parse_retries = 2`
318    /// - `tool_timeout_ms = 120_000` (2 minutes)
319    /// - `circuit_breaker_threshold = 3`
320    pub fn with_resilience_defaults(self) -> Self {
321        self.with_parse_retries(2)
322            .with_tool_timeout(120_000)
323            .with_circuit_breaker(3)
324    }
325
326    /// Provide a concrete [`BashSandbox`] implementation for this session.
327    ///
328    /// When set, `bash` tool commands are routed through the given sandbox
329    /// instead of `std::process::Command`. The host application is responsible
330    /// for constructing and lifecycle-managing the sandbox.
331    ///
332    /// [`BashSandbox`]: crate::sandbox::BashSandbox
333    pub fn with_sandbox_handle(mut self, handle: Arc<dyn crate::sandbox::BashSandbox>) -> Self {
334        self.sandbox_handle = Some(handle);
335        self
336    }
337
338    /// Enable auto-compaction when context usage exceeds threshold.
339    ///
340    /// When enabled, the agent loop automatically prunes large tool outputs
341    /// and summarizes old messages when context usage exceeds the threshold.
342    pub fn with_auto_compact(mut self, enabled: bool) -> Self {
343        self.auto_compact = enabled;
344        self
345    }
346
347    /// Set the auto-compact threshold (0.0 - 1.0). Default: 0.80 (80%).
348    pub fn with_auto_compact_threshold(mut self, threshold: f32) -> Self {
349        self.auto_compact_threshold = Some(threshold.clamp(0.0, 1.0));
350        self
351    }
352
353    /// Enable or disable continuation injection (default: enabled).
354    ///
355    /// When enabled, the loop injects a continuation message when the LLM stops
356    /// calling tools before the task appears complete, nudging it to keep working.
357    pub fn with_continuation(mut self, enabled: bool) -> Self {
358        self.continuation_enabled = Some(enabled);
359        self
360    }
361
362    /// Set the maximum number of continuation injections per execution (default: 3).
363    pub fn with_max_continuation_turns(mut self, turns: u32) -> Self {
364        self.max_continuation_turns = Some(turns);
365        self
366    }
367
368    /// Set an MCP manager to connect to external MCP servers.
369    ///
370    /// All tools from connected servers will be available during execution
371    /// with names like `mcp__<server>__<tool>`.
372    pub fn with_mcp(mut self, manager: Arc<crate::mcp::manager::McpManager>) -> Self {
373        self.mcp_manager = Some(manager);
374        self
375    }
376
377    pub fn with_temperature(mut self, temperature: f32) -> Self {
378        self.temperature = Some(temperature);
379        self
380    }
381
382    pub fn with_thinking_budget(mut self, budget: usize) -> Self {
383        self.thinking_budget = Some(budget);
384        self
385    }
386
387    /// Override the maximum number of tool execution rounds for this session.
388    ///
389    /// Useful when binding a markdown-defined subagent to a session —
390    /// pass the agent definition's `max_steps` value here to enforce its step budget.
391    pub fn with_max_tool_rounds(mut self, rounds: usize) -> Self {
392        self.max_tool_rounds = Some(rounds);
393        self
394    }
395
396    /// Set slot-based system prompt customization for this session.
397    ///
398    /// Allows customizing role, guidelines, response style, and extra instructions
399    /// without overriding the core agentic capabilities.
400    pub fn with_prompt_slots(mut self, slots: SystemPromptSlots) -> Self {
401        self.prompt_slots = Some(slots);
402        self
403    }
404
405    /// Replace the built-in hook engine with an external hook executor.
406    ///
407    /// Use this to attach an AHP harness server (or any custom `HookExecutor`)
408    /// to the session. All lifecycle events will be forwarded to the executor
409    /// instead of the in-process `HookEngine`.
410    pub fn with_hook_executor(mut self, executor: Arc<dyn crate::hooks::HookExecutor>) -> Self {
411        self.hook_executor = Some(executor);
412        self
413    }
414}