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