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("llm_client", &self.llm_client.is_some())
25            .field("context_providers", &self.context_providers.len())
26            .field("confirmation_manager", &self.confirmation_manager.is_some())
27            .field("permission_checker", &self.permission_checker.is_some())
28            .field("permission_policy", &self.permission_policy.is_some())
29            .field("planning_mode", &self.planning_mode)
30            .field("goal_tracking", &self.goal_tracking)
31            .field(
32                "skill_registry",
33                &self
34                    .skill_registry
35                    .as_ref()
36                    .map(|r| format!("{} skills", r.len())),
37            )
38            .field(
39                "enforce_active_skill_tool_restrictions",
40                &self.enforce_active_skill_tool_restrictions,
41            )
42            .field("memory_store", &self.memory_store.is_some())
43            .field("session_store", &self.session_store.is_some())
44            .field("session_id", &self.session_id)
45            .field("auto_save", &self.auto_save)
46            .field("artifact_store_limits", &self.artifact_store_limits)
47            .field("max_parse_retries", &self.max_parse_retries)
48            .field("tool_timeout_ms", &self.tool_timeout_ms)
49            .field("circuit_breaker_threshold", &self.circuit_breaker_threshold)
50            .field("sandbox_handle", &self.sandbox_handle.is_some())
51            .field("workspace_services", &self.workspace_services.is_some())
52            .field("auto_compact", &self.auto_compact)
53            .field("auto_compact_threshold", &self.auto_compact_threshold)
54            .field("continuation_enabled", &self.continuation_enabled)
55            .field("max_continuation_turns", &self.max_continuation_turns)
56            .field("mcp_manager", &self.mcp_manager.is_some())
57            .field("temperature", &self.temperature)
58            .field("thinking_budget", &self.thinking_budget)
59            .field("max_tool_rounds", &self.max_tool_rounds)
60            .field("max_parallel_tasks", &self.max_parallel_tasks)
61            .field("auto_delegation", &self.auto_delegation)
62            .field("auto_parallel_delegation", &self.auto_parallel_delegation)
63            .field("prompt_slots", &self.prompt_slots.is_some())
64            .finish()
65    }
66}
67
68impl SessionOptions {
69    pub fn new() -> Self {
70        Self::default()
71    }
72
73    pub fn with_model(mut self, model: impl Into<String>) -> Self {
74        self.model = Some(model.into());
75        self
76    }
77
78    pub fn with_agent_dir(mut self, dir: impl Into<PathBuf>) -> Self {
79        self.agent_dirs.push(dir.into());
80        self
81    }
82
83    /// Register a cattle-style worker with this session's task delegation registry.
84    pub fn with_worker_agent(mut self, spec: WorkerAgentSpec) -> Self {
85        self.worker_agents.push(spec);
86        self
87    }
88
89    /// Register multiple cattle-style workers with this session.
90    pub fn with_worker_agents<I>(mut self, specs: I) -> Self
91    where
92        I: IntoIterator<Item = WorkerAgentSpec>,
93    {
94        self.worker_agents.extend(specs);
95        self
96    }
97
98    pub fn with_queue_config(mut self, config: SessionQueueConfig) -> Self {
99        self.queue_config = Some(config);
100        self
101    }
102
103    /// Enable default security provider with taint tracking and output sanitization
104    pub fn with_default_security(mut self) -> Self {
105        self.security_provider = Some(Arc::new(crate::security::DefaultSecurityProvider::new()));
106        self
107    }
108
109    /// Set a custom security provider
110    pub fn with_security_provider(
111        mut self,
112        provider: Arc<dyn crate::security::SecurityProvider>,
113    ) -> Self {
114        self.security_provider = Some(provider);
115        self
116    }
117
118    /// Provide a custom LLM client for this session.
119    ///
120    /// When set, this client is used directly, overriding the `provider/model`
121    /// factory resolution. Use it to plug in a provider the built-in factory
122    /// does not cover, a deterministic record/replay client for tests, or an
123    /// HTTP-layer proxy/audit wrapper. Mirrors [`Self::with_workspace_backend`];
124    /// the `provider/model` config path remains the default when unset.
125    pub fn with_llm_client(mut self, client: Arc<dyn crate::llm::LlmClient>) -> Self {
126        self.llm_client = Some(client);
127        self
128    }
129
130    /// Add a file system context provider for simple RAG
131    pub fn with_fs_context(mut self, root_path: impl Into<PathBuf>) -> Self {
132        let config = crate::context::FileSystemContextConfig::new(root_path);
133        self.context_providers
134            .push(Arc::new(crate::context::FileSystemContextProvider::new(
135                config,
136            )));
137        self
138    }
139
140    /// Add a custom context provider
141    pub fn with_context_provider(
142        mut self,
143        provider: Arc<dyn crate::context::ContextProvider>,
144    ) -> Self {
145        self.context_providers.push(provider);
146        self
147    }
148
149    /// Set a confirmation manager for HITL
150    pub fn with_confirmation_manager(
151        mut self,
152        manager: Arc<dyn crate::hitl::ConfirmationProvider>,
153    ) -> Self {
154        self.confirmation_manager = Some(manager);
155        self
156    }
157
158    /// Set a confirmation policy for HITL
159    ///
160    /// The policy will be used to create a ConfirmationManager when the session is built.
161    /// This is the preferred way to configure HITL from the Node SDK.
162    pub fn with_confirmation_policy(mut self, policy: crate::hitl::ConfirmationPolicy) -> Self {
163        self.confirmation_policy = Some(policy);
164        self
165    }
166
167    /// Set a serializable permission policy for tool execution.
168    pub fn with_permission_policy(mut self, policy: crate::permissions::PermissionPolicy) -> Self {
169        self.permission_checker = Some(Arc::new(policy.clone()));
170        self.permission_policy = Some(policy);
171        self
172    }
173
174    /// Set a permission checker
175    pub fn with_permission_checker(
176        mut self,
177        checker: Arc<dyn crate::permissions::PermissionChecker>,
178    ) -> Self {
179        self.permission_checker = Some(checker);
180        self
181    }
182
183    /// Set planning mode
184    pub fn with_planning_mode(mut self, mode: PlanningMode) -> Self {
185        self.planning_mode = mode;
186        self
187    }
188
189    /// Enable planning (shortcut for `with_planning_mode(PlanningMode::Enabled)`)
190    pub fn with_planning(mut self, enabled: bool) -> Self {
191        self.planning_mode = if enabled {
192            PlanningMode::Enabled
193        } else {
194            PlanningMode::Disabled
195        };
196        self
197    }
198
199    /// Enable goal tracking
200    pub fn with_goal_tracking(mut self, enabled: bool) -> Self {
201        self.goal_tracking = enabled;
202        self
203    }
204
205    /// Add a skill registry with built-in skills
206    pub fn with_builtin_skills(mut self) -> Self {
207        self.skill_registry = Some(Arc::new(crate::skills::SkillRegistry::with_builtins()));
208        self
209    }
210
211    /// Add a custom skill registry
212    pub fn with_skill_registry(mut self, registry: Arc<crate::skills::SkillRegistry>) -> Self {
213        self.skill_registry = Some(registry);
214        self
215    }
216
217    /// Enable or disable legacy global active-skill `allowed-tools` restrictions.
218    ///
219    /// The default is disabled: active skills do not block ordinary session
220    /// tools before the host permission/AHP/HITL approval chain runs.
221    pub fn with_active_skill_tool_restrictions(mut self, enabled: bool) -> Self {
222        self.enforce_active_skill_tool_restrictions = Some(enabled);
223        self
224    }
225
226    /// Add skill directories to scan for skill files (*.md).
227    /// Merged with any global `skill_dirs` from [`CodeConfig`] at session build time.
228    pub fn with_skill_dirs(mut self, dirs: impl IntoIterator<Item = impl Into<PathBuf>>) -> Self {
229        self.skill_dirs.extend(dirs.into_iter().map(Into::into));
230        self
231    }
232
233    /// Load skills from a directory (eager — scans immediately into a registry).
234    pub fn with_skills_from_dir(mut self, dir: impl AsRef<std::path::Path>) -> Self {
235        let registry = self
236            .skill_registry
237            .unwrap_or_else(|| Arc::new(crate::skills::SkillRegistry::new()));
238        if let Err(e) = registry.load_from_dir(&dir) {
239            tracing::warn!(
240                dir = %dir.as_ref().display(),
241                error = %e,
242                "Failed to load skills from directory — continuing without them"
243            );
244        }
245        self.skill_registry = Some(registry);
246        self
247    }
248
249    /// Set a custom memory store
250    pub fn with_memory(mut self, store: Arc<dyn MemoryStore>) -> Self {
251        self.memory_store = Some(store);
252        self
253    }
254
255    /// Use a file-based memory store at the given directory.
256    ///
257    /// The store is created lazily when the session is built (requires async).
258    /// This stores the directory path; `FileMemoryStore::new()` is called during
259    /// session construction.
260    pub fn with_file_memory(mut self, dir: impl Into<PathBuf>) -> Self {
261        self.file_memory_dir = Some(dir.into());
262        self
263    }
264
265    /// Set a session store for persistence
266    pub fn with_session_store(mut self, store: Arc<dyn crate::store::SessionStore>) -> Self {
267        self.session_store = Some(store);
268        self
269    }
270
271    /// Use a file-based session store at the given directory
272    pub fn with_file_session_store(mut self, dir: impl Into<PathBuf>) -> Self {
273        let dir = dir.into();
274        match tokio::runtime::Handle::try_current() {
275            Ok(handle) => {
276                match tokio::task::block_in_place(|| {
277                    handle.block_on(crate::store::FileSessionStore::new(dir))
278                }) {
279                    Ok(store) => {
280                        self.session_store =
281                            Some(Arc::new(store) as Arc<dyn crate::store::SessionStore>);
282                    }
283                    Err(e) => {
284                        tracing::warn!("Failed to create file session store: {}", e);
285                    }
286                }
287            }
288            Err(_) => {
289                tracing::warn!(
290                    "No async runtime available for file session store — persistence disabled"
291                );
292            }
293        }
294        self
295    }
296
297    /// Set an explicit session ID (auto-generated UUID if not set)
298    pub fn with_session_id(mut self, id: impl Into<String>) -> Self {
299        self.session_id = Some(id.into());
300        self
301    }
302
303    /// Tag the session with a host-defined tenant id. Opaque to the
304    /// framework — propagated to `SessionData`, hooks, and traces.
305    pub fn with_tenant_id(mut self, tenant: impl Into<String>) -> Self {
306        self.tenant_id = Some(tenant.into());
307        self
308    }
309
310    /// Tag the session with the id of the principal (user / service
311    /// account / etc.) that triggered it.
312    pub fn with_principal(mut self, principal: impl Into<String>) -> Self {
313        self.principal = Some(principal.into());
314        self
315    }
316
317    /// Tag the session with the id of the agent template / definition it
318    /// was instantiated from.
319    pub fn with_agent_template_id(mut self, template_id: impl Into<String>) -> Self {
320        self.agent_template_id = Some(template_id.into());
321        self
322    }
323
324    /// Attach a distributed-trace correlation id so this session's events
325    /// can be joined with upstream/downstream work.
326    pub fn with_correlation_id(mut self, corr: impl Into<String>) -> Self {
327        self.correlation_id = Some(corr.into());
328        self
329    }
330
331    /// Install a host-supplied [`BudgetGuard`](crate::budget::BudgetGuard).
332    ///
333    /// The guard is consulted before every LLM call (and after, for
334    /// usage accounting). When unset, no budget enforcement happens.
335    pub fn with_budget_guard(mut self, guard: Arc<dyn crate::budget::BudgetGuard>) -> Self {
336        self.budget_guard = Some(guard);
337        self
338    }
339
340    /// Install a host-provided [`HostEnv`](crate::host_env::HostEnv) for
341    /// deterministic ID generation and time. Replaces the framework
342    /// default of `uuid::Uuid::new_v4()` + wall clock — used by
343    /// host replay infrastructure to recreate a run bit-identical on
344    /// another node.
345    pub fn with_host_env(mut self, env: Arc<crate::host_env::HostEnv>) -> Self {
346        self.host_env = Some(env);
347        self
348    }
349
350    /// Install FIFO retention caps for the session's in-memory stores.
351    ///
352    /// Without these caps the in-memory run store, trace sink, and
353    /// subagent task tracker grow unboundedly across long-running
354    /// sessions. Hosts running thousands of long-lived sessions per
355    /// node should set sensible caps (e.g. retain the last 100 runs,
356    /// 5000 events per run, 10000 trace events, 1000 terminal subagent
357    /// tasks). When unset, the framework keeps every record — the
358    /// pre-existing behaviour.
359    pub fn with_retention_limits(
360        mut self,
361        limits: crate::retention::SessionRetentionLimits,
362    ) -> Self {
363        self.retention_limits = Some(limits);
364        self
365    }
366
367    /// Enable auto-save after each `send()` call
368    pub fn with_auto_save(mut self, enabled: bool) -> Self {
369        self.auto_save = enabled;
370        self
371    }
372
373    /// Set artifact retention limits for this session.
374    pub fn with_artifact_store_limits(mut self, limits: crate::tools::ArtifactStoreLimits) -> Self {
375        self.artifact_store_limits = Some(limits);
376        self
377    }
378
379    /// Set the maximum number of consecutive malformed-tool-args errors before
380    /// the agent loop bails.
381    ///
382    /// Default: 2 (the LLM gets two chances to self-correct before the session
383    /// is aborted).
384    pub fn with_parse_retries(mut self, max: u32) -> Self {
385        self.max_parse_retries = Some(max);
386        self
387    }
388
389    /// Set a per-tool execution timeout.
390    ///
391    /// When set, each tool execution is wrapped in `tokio::time::timeout`.
392    /// A timeout produces an error message that is fed back to the LLM
393    /// (the session continues).
394    pub fn with_tool_timeout(mut self, timeout_ms: u64) -> Self {
395        self.tool_timeout_ms = Some(timeout_ms);
396        self
397    }
398
399    /// Set the circuit-breaker threshold.
400    ///
401    /// In non-streaming mode, the agent retries transient LLM API failures up
402    /// to this many times (with exponential backoff) before aborting.
403    /// Default: 3 attempts.
404    pub fn with_circuit_breaker(mut self, threshold: u32) -> Self {
405        self.circuit_breaker_threshold = Some(threshold);
406        self
407    }
408
409    /// Enable all resilience defaults with sensible values:
410    ///
411    /// - `max_parse_retries = 2`
412    /// - `tool_timeout_ms = 120_000` (2 minutes)
413    /// - `circuit_breaker_threshold = 3`
414    pub fn with_resilience_defaults(self) -> Self {
415        self.with_parse_retries(2)
416            .with_tool_timeout(120_000)
417            .with_circuit_breaker(3)
418    }
419
420    /// Provide a concrete [`BashSandbox`] implementation for this session.
421    ///
422    /// When set, `bash` tool commands are routed through the given sandbox
423    /// instead of `std::process::Command`. The host application is responsible
424    /// for constructing and lifecycle-managing the sandbox.
425    ///
426    /// [`BashSandbox`]: crate::sandbox::BashSandbox
427    pub fn with_sandbox_handle(mut self, handle: Arc<dyn crate::sandbox::BashSandbox>) -> Self {
428        self.sandbox_handle = Some(handle);
429        self
430    }
431
432    /// Provide a workspace backend for this session.
433    ///
434    /// Built-in tools keep their stable names and schemas, while their backing
435    /// implementation can target a DFS, browser workspace, remote runner, or
436    /// any other host-provided backend.
437    pub fn with_workspace_backend(
438        mut self,
439        services: Arc<crate::workspace::WorkspaceServices>,
440    ) -> Self {
441        self.workspace_services = Some(services);
442        self
443    }
444
445    /// Enable auto-compaction when context usage exceeds threshold.
446    ///
447    /// When enabled, the agent loop automatically prunes large tool outputs
448    /// and summarizes old messages when context usage exceeds the threshold.
449    pub fn with_auto_compact(mut self, enabled: bool) -> Self {
450        self.auto_compact = enabled;
451        self
452    }
453
454    /// Set the auto-compact threshold (0.0 - 1.0). Default: 0.80 (80%).
455    pub fn with_auto_compact_threshold(mut self, threshold: f32) -> Self {
456        self.auto_compact_threshold = Some(threshold.clamp(0.0, 1.0));
457        self
458    }
459
460    /// Enable or disable continuation injection (default: enabled).
461    ///
462    /// When enabled, the loop injects a continuation message when the LLM stops
463    /// calling tools before the task appears complete, nudging it to keep working.
464    pub fn with_continuation(mut self, enabled: bool) -> Self {
465        self.continuation_enabled = Some(enabled);
466        self
467    }
468
469    /// Set the maximum number of continuation injections per execution (default: 3).
470    pub fn with_max_continuation_turns(mut self, turns: u32) -> Self {
471        self.max_continuation_turns = Some(turns);
472        self
473    }
474
475    /// Set an MCP manager to connect to external MCP servers.
476    ///
477    /// All tools from connected servers will be available during execution
478    /// with names like `mcp__<server>__<tool>`.
479    pub fn with_mcp(mut self, manager: Arc<crate::mcp::manager::McpManager>) -> Self {
480        self.mcp_manager = Some(manager);
481        self
482    }
483
484    pub fn with_temperature(mut self, temperature: f32) -> Self {
485        self.temperature = Some(temperature);
486        self
487    }
488
489    pub fn with_thinking_budget(mut self, budget: usize) -> Self {
490        self.thinking_budget = Some(budget);
491        self
492    }
493
494    /// Override the maximum number of tool execution rounds for this session.
495    ///
496    /// Useful when binding a markdown-defined subagent to a session —
497    /// pass the agent definition's `max_steps` value here to enforce its step budget.
498    pub fn with_max_tool_rounds(mut self, rounds: usize) -> Self {
499        self.max_tool_rounds = Some(rounds);
500        self
501    }
502
503    /// Override the maximum number of sibling parallel branches for this session.
504    pub fn with_max_parallel_tasks(mut self, tasks: usize) -> Self {
505        self.max_parallel_tasks = Some(tasks.max(1));
506        self
507    }
508
509    /// Override automatic subagent delegation for this session.
510    pub fn with_auto_delegation(mut self, config: crate::config::AutoDelegationConfig) -> Self {
511        self.auto_delegation = Some(config);
512        self
513    }
514
515    /// Enable or disable automatic subagent delegation for this session.
516    pub fn with_auto_delegation_enabled(mut self, enabled: bool) -> Self {
517        let mut config = self.auto_delegation.take().unwrap_or_default();
518        config.enabled = enabled;
519        self.auto_delegation = Some(config);
520        self
521    }
522
523    /// Globally enable or disable automatic parallel child-agent fan-out.
524    ///
525    /// Manual `parallel_task` calls remain available when this is false.
526    pub fn with_auto_parallel_delegation(mut self, enabled: bool) -> Self {
527        if let Some(config) = &mut self.auto_delegation {
528            config.auto_parallel = enabled;
529        }
530        self.auto_parallel_delegation = Some(enabled);
531        self
532    }
533
534    /// Set slot-based system prompt customization for this session.
535    ///
536    /// Allows customizing role, guidelines, response style, and extra instructions
537    /// without overriding the core agentic capabilities.
538    pub fn with_prompt_slots(mut self, slots: SystemPromptSlots) -> Self {
539        self.prompt_slots = Some(slots);
540        self
541    }
542
543    /// Replace the built-in hook engine with an external hook executor.
544    ///
545    /// Use this to attach an AHP harness server (or any custom `HookExecutor`)
546    /// to the session. All lifecycle events will be forwarded to the executor
547    /// instead of the in-process `HookEngine`.
548    pub fn with_hook_executor(mut self, executor: Arc<dyn crate::hooks::HookExecutor>) -> Self {
549        self.hook_executor = Some(executor);
550        self
551    }
552}