Skip to main content

zeph_core/agent/
session_config.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use std::sync::Arc;
5
6use crate::config::{
7    Config, DebugConfig, DocumentConfig, GraphConfig, LearningConfig, OrchestrationConfig,
8    PersonaConfig, SecurityConfig, TimeoutConfig,
9};
10use crate::vault::Secret;
11
12/// Reserve ratio for `with_context_budget`: fraction of budget reserved for LLM reply.
13///
14/// Extracted from the hardcoded `0.20` literal used in both `spawn_acp_agent` and `runner.rs`.
15pub const CONTEXT_BUDGET_RESERVE_RATIO: f32 = 0.20;
16
17/// All config-derived fields needed to configure an `Agent` session.
18///
19/// This is the single source of truth for config → agent wiring.
20/// Adding a new config field requires exactly three changes:
21///
22/// 1. Add the field here.
23/// 2. Map it in [`AgentSessionConfig::from_config`].
24/// 3. Apply it in [`super::Agent::apply_session_config`] (destructure triggers a compile error if
25///    you forget step 3 — see the S4 note in the critic handoff).
26///
27/// ## What is NOT here
28///
29/// - **Shared runtime objects** (`provider`, `registry`, `memory`, `mcp_manager`, etc.) — these
30///   are expensive to create and shared across sessions; they stay in `SharedAgentDeps`.
31/// - **ACP-specific fields** (`acp_max_sessions`, bearer token, etc.) — transport-level, not
32///   agent-level.
33/// - **Optional runtime providers** (`summary_provider`, `judge_provider`,
34///   `quarantine_provider`) — these contain HTTP client pools (`AnyProvider`) that carry runtime
35///   state; callers wire them separately via `with_summary_provider` / `with_judge_provider` /
36///   `apply_quarantine_provider`.
37/// - **`mcp_config`** — passed alongside runtime MCP objects in `with_mcp()`; separating it
38///   from `mcp_tools` / `mcp_manager` would make the call site awkward.
39/// - **Runner-only fields** (`compression`, `routing`, `autosave`, `hybrid_search`, `trust_config`,
40///   `disambiguation_threshold`, `logging_config`, `subagent`, `experiment`, `instruction`,
41///   `lsp_hooks`, `response_cache`, `cost_tracker`) — not used in ACP sessions; keeping them out
42///   avoids unused-field noise and prevents inadvertent ACP behavior changes.
43/// - **Scheduler runtime objects** (`scheduler_executor`, broadcast senders) — runtime state,
44///   not config-derived values.
45#[derive(Clone)]
46#[allow(clippy::struct_excessive_bools)]
47pub struct AgentSessionConfig {
48    // Tool behavior
49    pub max_tool_iterations: usize,
50    pub max_tool_retries: usize,
51    pub max_retry_duration_secs: u64,
52    pub retry_base_ms: u64,
53    pub retry_max_ms: u64,
54    pub parameter_reformat_provider: String,
55    pub tool_repeat_threshold: usize,
56    pub tool_summarization: bool,
57    pub tool_call_cutoff: usize,
58    pub max_tool_calls_per_session: Option<u32>,
59    pub overflow_config: zeph_tools::OverflowConfig,
60    pub permission_policy: zeph_tools::PermissionPolicy,
61
62    // Model
63    pub model_name: String,
64    pub embed_model: String,
65
66    // Semantic cache
67    pub semantic_cache_enabled: bool,
68    pub semantic_cache_threshold: f32,
69    pub semantic_cache_max_candidates: u32,
70
71    // Memory / compaction
72    pub budget_tokens: usize,
73    pub soft_compaction_threshold: f32,
74    pub hard_compaction_threshold: f32,
75    pub compaction_preserve_tail: usize,
76    pub compaction_cooldown_turns: u8,
77    pub prune_protect_tokens: usize,
78    pub redact_credentials: bool,
79
80    // Security
81    pub security: SecurityConfig,
82    pub timeouts: TimeoutConfig,
83
84    // Feature configs
85    pub learning: LearningConfig,
86    pub document_config: DocumentConfig,
87    pub graph_config: GraphConfig,
88    pub persona_config: PersonaConfig,
89    pub trajectory_config: crate::config::TrajectoryConfig,
90    pub category_config: crate::config::CategoryConfig,
91    pub tree_config: crate::config::TreeConfig,
92    pub microcompact_config: crate::config::MicrocompactConfig,
93    pub autodream_config: crate::config::AutoDreamConfig,
94    pub magic_docs_config: crate::config::MagicDocsConfig,
95    pub anomaly_config: zeph_tools::AnomalyConfig,
96    pub result_cache_config: zeph_tools::ResultCacheConfig,
97    pub utility_config: zeph_tools::UtilityScoringConfig,
98    pub orchestration_config: OrchestrationConfig,
99    pub debug_config: DebugConfig,
100    pub server_compaction: bool,
101
102    /// Inject `<budget>` XML into the volatile system prompt section (#2267).
103    pub budget_hint_enabled: bool,
104
105    /// Session recap settings (#3064).
106    pub recap: zeph_config::RecapConfig,
107
108    /// Custom secrets from config.
109    ///
110    /// Stored as `Arc` because `Secret` intentionally does not implement `Clone` —
111    /// the wrapper prevents accidental duplication. Iteration produces new `Secret`
112    /// values via `Secret::new(v.expose())` on the consumption side.
113    pub secrets: Arc<[(String, Secret)]>,
114}
115
116impl AgentSessionConfig {
117    /// Build from a resolved [`Config`] snapshot and a pre-computed `budget_tokens`.
118    ///
119    /// `budget_tokens` is passed as a parameter because its computation (`auto_budget_tokens`)
120    /// depends on the active provider and must happen before `AgentSessionConfig` is constructed.
121    #[must_use]
122    pub fn from_config(config: &Config, budget_tokens: usize) -> Self {
123        Self {
124            max_tool_iterations: config.agent.max_tool_iterations,
125            max_tool_retries: config.tools.retry.max_attempts,
126            max_retry_duration_secs: config.tools.retry.budget_secs,
127            retry_base_ms: config.tools.retry.base_ms,
128            retry_max_ms: config.tools.retry.max_ms,
129            parameter_reformat_provider: config.tools.retry.parameter_reformat_provider.clone(),
130            tool_repeat_threshold: config.agent.tool_repeat_threshold,
131            tool_summarization: config.tools.summarize_output,
132            tool_call_cutoff: config.memory.tool_call_cutoff,
133            max_tool_calls_per_session: config.tools.max_tool_calls_per_session,
134            overflow_config: config.tools.overflow.clone(),
135            permission_policy: config
136                .tools
137                .permission_policy(config.security.autonomy_level),
138            model_name: config.llm.effective_model().to_owned(),
139            embed_model: crate::provider_factory::effective_embedding_model(config),
140            semantic_cache_enabled: config.llm.semantic_cache_enabled,
141            semantic_cache_threshold: config.llm.semantic_cache_threshold,
142            semantic_cache_max_candidates: config.llm.semantic_cache_max_candidates,
143            budget_tokens,
144            soft_compaction_threshold: config.memory.soft_compaction_threshold,
145            hard_compaction_threshold: config.memory.hard_compaction_threshold,
146            compaction_preserve_tail: config.memory.compaction_preserve_tail,
147            compaction_cooldown_turns: config.memory.compaction_cooldown_turns,
148            prune_protect_tokens: config.memory.prune_protect_tokens,
149            redact_credentials: config.memory.redact_credentials,
150            security: config.security.clone(),
151            timeouts: config.timeouts,
152            learning: config.skills.learning.clone(),
153            document_config: config.memory.documents.clone(),
154            graph_config: config.memory.graph.clone(),
155            persona_config: config.memory.persona.clone(),
156            trajectory_config: config.memory.trajectory.clone(),
157            category_config: config.memory.category.clone(),
158            tree_config: config.memory.tree.clone(),
159            microcompact_config: config.memory.microcompact.clone(),
160            autodream_config: config.memory.autodream.clone(),
161            magic_docs_config: config.magic_docs.clone(),
162            anomaly_config: config.tools.anomaly.clone(),
163            result_cache_config: config.tools.result_cache.clone(),
164            utility_config: config.tools.utility.clone(),
165            orchestration_config: config.orchestration.clone(),
166            debug_config: config.debug.clone(),
167            server_compaction: config.llm.providers.iter().any(|e| e.server_compaction),
168            budget_hint_enabled: config.agent.budget_hint_enabled,
169            secrets: config
170                .secrets
171                .custom
172                .iter()
173                .map(|(k, v)| (k.clone(), Secret::new(v.expose().to_owned())))
174                .collect::<Vec<_>>()
175                .into(),
176            recap: config.session.recap.clone(),
177        }
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    #[test]
186    fn from_config_maps_all_fields() {
187        let config = Config::default();
188        let budget = 100_000;
189        let sc = AgentSessionConfig::from_config(&config, budget);
190
191        assert_eq!(sc.max_tool_iterations, config.agent.max_tool_iterations);
192        assert_eq!(sc.max_tool_retries, config.tools.retry.max_attempts);
193        assert_eq!(sc.max_retry_duration_secs, config.tools.retry.budget_secs);
194        assert_eq!(sc.retry_base_ms, config.tools.retry.base_ms);
195        assert_eq!(sc.retry_max_ms, config.tools.retry.max_ms);
196        assert_eq!(
197            sc.parameter_reformat_provider,
198            config.tools.retry.parameter_reformat_provider
199        );
200        assert_eq!(sc.tool_repeat_threshold, config.agent.tool_repeat_threshold);
201        assert_eq!(sc.tool_summarization, config.tools.summarize_output);
202        assert_eq!(sc.tool_call_cutoff, config.memory.tool_call_cutoff);
203        assert_eq!(sc.model_name, config.llm.effective_model());
204        assert_eq!(
205            sc.embed_model,
206            crate::provider_factory::effective_embedding_model(&config)
207        );
208        assert_eq!(sc.semantic_cache_enabled, config.llm.semantic_cache_enabled);
209        assert!(
210            (sc.semantic_cache_threshold - config.llm.semantic_cache_threshold).abs()
211                < f32::EPSILON
212        );
213        assert_eq!(
214            sc.semantic_cache_max_candidates,
215            config.llm.semantic_cache_max_candidates
216        );
217        assert_eq!(sc.budget_tokens, budget);
218        assert!(
219            (sc.soft_compaction_threshold - config.memory.soft_compaction_threshold).abs()
220                < f32::EPSILON
221        );
222        assert!(
223            (sc.hard_compaction_threshold - config.memory.hard_compaction_threshold).abs()
224                < f32::EPSILON
225        );
226        assert_eq!(
227            sc.compaction_preserve_tail,
228            config.memory.compaction_preserve_tail
229        );
230        assert_eq!(
231            sc.compaction_cooldown_turns,
232            config.memory.compaction_cooldown_turns
233        );
234        assert_eq!(sc.prune_protect_tokens, config.memory.prune_protect_tokens);
235        assert_eq!(sc.redact_credentials, config.memory.redact_credentials);
236        assert_eq!(sc.graph_config.enabled, config.memory.graph.enabled);
237        assert_eq!(
238            sc.orchestration_config.enabled,
239            config.orchestration.enabled
240        );
241        assert_eq!(
242            sc.orchestration_config.max_tasks,
243            config.orchestration.max_tasks
244        );
245        assert_eq!(sc.anomaly_config.enabled, config.tools.anomaly.enabled);
246        assert_eq!(
247            sc.result_cache_config.enabled,
248            config.tools.result_cache.enabled
249        );
250        assert_eq!(
251            sc.result_cache_config.ttl_secs,
252            config.tools.result_cache.ttl_secs
253        );
254        assert_eq!(sc.debug_config.enabled, config.debug.enabled);
255        assert_eq!(
256            sc.document_config.rag_enabled,
257            config.memory.documents.rag_enabled
258        );
259        assert_eq!(
260            sc.overflow_config.threshold,
261            config.tools.overflow.threshold
262        );
263        assert_eq!(
264            sc.permission_policy.autonomy_level(),
265            config.security.autonomy_level
266        );
267        assert_eq!(sc.security.autonomy_level, config.security.autonomy_level);
268        assert_eq!(sc.timeouts.llm_seconds, config.timeouts.llm_seconds);
269        assert_eq!(sc.learning.enabled, config.skills.learning.enabled);
270        assert_eq!(
271            sc.server_compaction,
272            config.llm.providers.iter().any(|e| e.server_compaction)
273        );
274        assert_eq!(sc.secrets.len(), config.secrets.custom.len());
275        assert_eq!(sc.recap.on_resume, config.session.recap.on_resume);
276        assert_eq!(sc.recap.max_tokens, config.session.recap.max_tokens);
277    }
278}