Skip to main content

tea_coding/config/
types.rs

1use serde::{Deserialize, Serialize};
2use tea_coding_tools::{
3    DEFAULT_FETCH_CACHE_ENTRIES, DEFAULT_FETCH_CACHE_ENTRY_BYTES, DEFAULT_FETCH_CACHE_TOTAL_BYTES,
4    DEFAULT_FETCH_CACHE_TTL, DEFAULT_TAVILY_SEARCH_ENDPOINT,
5};
6use tea_mcp::McpServerConfig;
7use tea_model::{WebSearchLocation, WebSearchOptions};
8
9use crate::mcp_config::McpServerSettings;
10
11/// Current persisted coding settings schema.
12pub const CODING_SETTINGS_SCHEMA_VERSION: u32 = 1;
13/// Default environment variable consulted by an embedding product for Tavily credentials.
14pub const DEFAULT_WEB_SEARCH_API_KEY_ENVIRONMENT: &str = "TAVILY_API_KEY";
15/// Default client web-search request timeout.
16pub const DEFAULT_WEB_SEARCH_TIMEOUT_MILLIS: u64 = 30_000;
17/// Maximum bytes in one configured API-key environment variable name.
18pub const MAX_WEB_SEARCH_API_KEY_ENVIRONMENT_BYTES: usize = 128;
19
20/// Behavior when project-local configuration exists without a saved decision.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
22#[serde(rename_all = "snake_case")]
23pub enum ProjectTrustDefault {
24    /// Interactive products may ask; headless products deny.
25    #[default]
26    Ask,
27    /// Ignore all project-local settings and declarative resources.
28    Ignore,
29    /// Fail closed when project-local settings or resources are requested.
30    Reject,
31}
32
33/// Versioned, secret-free resolved settings snapshot.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "camelCase", deny_unknown_fields)]
36pub struct CodingSettings {
37    /// Persisted schema version.
38    pub schema_version: u32,
39    /// Provider selector.
40    pub provider: String,
41    /// Model selector.
42    pub model: String,
43    /// Thinking mode selector.
44    pub thinking: String,
45    /// Canonical active tool names.
46    pub active_tools: Vec<String>,
47    /// Session database override, relative to injected state dir when absent.
48    pub session_database: Option<String>,
49    /// Maximum model retries.
50    pub max_retries: u32,
51    /// Base delay before the first model retry, in milliseconds.
52    pub retry_base_delay_ms: u64,
53    /// Maximum model retry delay, including provider hints, in milliseconds.
54    pub retry_max_delay_ms: u64,
55    /// Whether automatic compaction is enabled.
56    pub compaction_enabled: bool,
57    /// TUI settings.
58    pub tui: TuiSettings,
59    /// Declarative resource settings.
60    pub resources: ResourceSettings,
61    /// Registered web-search routing and backend controls.
62    #[serde(default)]
63    pub web_search: WebSearchSettings,
64    /// Explicit client web-fetch backend and bounded cache controls.
65    #[serde(default)]
66    pub web_fetch: WebFetchSettings,
67    /// Default project trust behavior.
68    pub project_trust: ProjectTrustDefault,
69    /// Validated runtime-only MCP server configs, omitted from durable settings.
70    #[serde(skip, default)]
71    pub mcp_servers: Vec<McpServerConfig>,
72}
73
74impl Default for CodingSettings {
75    fn default() -> Self {
76        Self {
77            schema_version: CODING_SETTINGS_SCHEMA_VERSION,
78            provider: "openai".to_owned(),
79            model: "gpt-5.4".to_owned(),
80            thinking: "medium".to_owned(),
81            active_tools: vec!["read", "write", "edit", "bash"]
82                .into_iter()
83                .map(str::to_owned)
84                .collect(),
85            session_database: None,
86            max_retries: 3,
87            retry_base_delay_ms: 2_000,
88            retry_max_delay_ms: 60_000,
89            compaction_enabled: false,
90            tui: TuiSettings::default(),
91            resources: ResourceSettings::default(),
92            web_search: WebSearchSettings::default(),
93            web_fetch: WebFetchSettings::default(),
94            project_trust: ProjectTrustDefault::Ask,
95            mcp_servers: Vec::new(),
96        }
97    }
98}
99
100/// Route selected for web search when a real client backend is available.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
102#[serde(rename_all = "snake_case")]
103pub enum WebSearchRoutePreference {
104    /// Prefer provider-hosted search and fall back to the client on unsupported models.
105    #[default]
106    PreferHosted,
107    /// Always expose the client function route.
108    ForceClient,
109}
110
111/// Client web-search backend selected by the embedding product.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
113#[serde(rename_all = "snake_case")]
114pub enum WebSearchClientBackend {
115    /// Tavily's bounded search HTTP API.
116    #[default]
117    Tavily,
118}
119
120/// Secret-free resolved web-search settings.
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122#[serde(default, rename_all = "camelCase", deny_unknown_fields)]
123pub struct WebSearchSettings {
124    /// Route preference applied only when the client backend is enabled and injected.
125    pub route_preference: WebSearchRoutePreference,
126    /// Canonical domain allowlist shared by hosted and client search.
127    pub allowed_domains: Vec<String>,
128    /// Canonical domain blocklist shared by hosted and client search.
129    pub blocked_domains: Vec<String>,
130    /// Optional approximate location disclosed to capable hosted providers.
131    pub location: Option<WebSearchLocationSettings>,
132    /// Client-backend construction controls for embedding products.
133    pub client: ClientWebSearchSettings,
134}
135
136impl Default for WebSearchSettings {
137    fn default() -> Self {
138        Self {
139            route_preference: WebSearchRoutePreference::PreferHosted,
140            allowed_domains: Vec::new(),
141            blocked_domains: Vec::new(),
142            location: None,
143            client: ClientWebSearchSettings::default(),
144        }
145    }
146}
147
148impl WebSearchSettings {
149    pub(crate) fn runtime_options(&self) -> Result<WebSearchOptions, tea_model::ModelRequestError> {
150        let mut options = WebSearchOptions::new();
151        if !self.allowed_domains.is_empty() {
152            options = options.with_allowed_domains(self.allowed_domains.clone())?;
153        }
154        if !self.blocked_domains.is_empty() {
155            options = options.with_blocked_domains(self.blocked_domains.clone())?;
156        }
157        if let Some(configured) = &self.location {
158            let mut location = WebSearchLocation::new();
159            if let Some(country) = &configured.country {
160                location = location.with_country(country.clone())?;
161            }
162            if let Some(city) = &configured.city {
163                location = location.with_city(city.clone())?;
164            }
165            if let Some(region) = &configured.region {
166                location = location.with_region(region.clone())?;
167            }
168            if let Some(timezone) = &configured.timezone {
169                location = location.with_timezone(timezone.clone())?;
170            }
171            options = options.with_location(location);
172        }
173        Ok(options)
174    }
175}
176
177/// Approximate location fields used by hosted web search.
178#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
179#[serde(default, rename_all = "camelCase", deny_unknown_fields)]
180pub struct WebSearchLocationSettings {
181    /// ISO 3166-1 alpha-2 uppercase country code.
182    pub country: Option<String>,
183    /// Approximate city name.
184    pub city: Option<String>,
185    /// Approximate region name.
186    pub region: Option<String>,
187    /// Canonical IANA-style timezone name.
188    pub timezone: Option<String>,
189}
190
191/// Client web-search backend controls resolved without reading credentials.
192#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(default, rename_all = "camelCase", deny_unknown_fields)]
194pub struct ClientWebSearchSettings {
195    /// Whether an embedding product may attach a real client backend.
196    pub enabled: bool,
197    /// Backend configuration contract expected by the injected provider.
198    pub backend: WebSearchClientBackend,
199    /// Validated Tavily-compatible HTTP endpoint.
200    pub endpoint: String,
201    /// Environment variable name resolved by the embedding product at construction time.
202    pub api_key_environment: String,
203    /// Per-request timeout in milliseconds.
204    pub timeout_millis: u64,
205}
206
207impl Default for ClientWebSearchSettings {
208    fn default() -> Self {
209        Self {
210            enabled: false,
211            backend: WebSearchClientBackend::Tavily,
212            endpoint: DEFAULT_TAVILY_SEARCH_ENDPOINT.to_owned(),
213            api_key_environment: DEFAULT_WEB_SEARCH_API_KEY_ENVIRONMENT.to_owned(),
214            timeout_millis: DEFAULT_WEB_SEARCH_TIMEOUT_MILLIS,
215        }
216    }
217}
218
219/// Client web-fetch backend selected by the embedding product.
220#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
221#[serde(rename_all = "snake_case")]
222pub enum WebFetchBackend {
223    /// Pinned, redirect-safe HTTP transport with bounded response extraction.
224    #[default]
225    Http,
226}
227
228/// Secret-free resolved web-fetch settings.
229#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230#[serde(default, rename_all = "camelCase", deny_unknown_fields)]
231pub struct WebFetchSettings {
232    /// Whether an embedding product may attach a real fetch backend.
233    pub enabled: bool,
234    /// Backend configuration contract expected by the injected provider.
235    pub backend: WebFetchBackend,
236    /// Bounded normalized-result cache controls.
237    pub cache: WebFetchCacheSettings,
238}
239
240impl Default for WebFetchSettings {
241    fn default() -> Self {
242        Self {
243            enabled: false,
244            backend: WebFetchBackend::Http,
245            cache: WebFetchCacheSettings::default(),
246        }
247    }
248}
249
250/// Bounded in-memory cache controls for normalized fetch results.
251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
252#[serde(default, rename_all = "camelCase", deny_unknown_fields)]
253pub struct WebFetchCacheSettings {
254    /// Cache lifetime in whole seconds.
255    pub ttl_seconds: u64,
256    /// Maximum cached result count.
257    pub max_entries: usize,
258    /// Maximum aggregate cache bytes.
259    pub max_total_bytes: usize,
260    /// Maximum bytes retained by one entry.
261    pub max_entry_bytes: usize,
262}
263
264impl Default for WebFetchCacheSettings {
265    fn default() -> Self {
266        Self {
267            ttl_seconds: DEFAULT_FETCH_CACHE_TTL.as_secs(),
268            max_entries: DEFAULT_FETCH_CACHE_ENTRIES,
269            max_total_bytes: DEFAULT_FETCH_CACHE_TOTAL_BYTES,
270            max_entry_bytes: DEFAULT_FETCH_CACHE_ENTRY_BYTES,
271        }
272    }
273}
274
275/// Nested TUI settings merged independently by layer.
276#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
277#[serde(default, rename_all = "camelCase", deny_unknown_fields)]
278pub struct TuiSettings {
279    /// Codex-style inline viewport or explicit fullscreen compatibility mode.
280    pub viewport: String,
281    /// Whether thinking blocks start collapsed.
282    pub collapse_thinking: bool,
283    /// Whether the terminal UI avoids animated status indicators.
284    pub reduced_motion: bool,
285    /// Submit key binding.
286    pub submit_key: String,
287    /// Newline key binding.
288    pub newline_key: String,
289    /// Active-run abort key binding.
290    pub abort_key: String,
291    /// Editor clear key binding.
292    pub clear_key: String,
293    /// Application exit key binding.
294    pub exit_key: String,
295    /// Model selector key binding.
296    pub model_key: String,
297    /// Thinking-collapse key binding.
298    pub toggle_thinking_key: String,
299    /// Tool-collapse key binding.
300    pub toggle_tools_key: String,
301    /// Copy key binding.
302    pub copy_key: String,
303    /// Active-run steering key binding.
304    pub steering_key: String,
305    /// Active-run follow-up key binding.
306    pub follow_up_key: String,
307    /// Queued-message retrieval key binding.
308    pub retrieve_queued_key: String,
309}
310
311impl Default for TuiSettings {
312    fn default() -> Self {
313        Self {
314            viewport: "inline".to_owned(),
315            collapse_thinking: false,
316            reduced_motion: false,
317            submit_key: "enter".to_owned(),
318            newline_key: "shift+enter".to_owned(),
319            abort_key: "escape".to_owned(),
320            clear_key: "ctrl+l".to_owned(),
321            exit_key: "ctrl+d".to_owned(),
322            model_key: "ctrl+o".to_owned(),
323            toggle_thinking_key: "ctrl+t".to_owned(),
324            toggle_tools_key: "ctrl+g".to_owned(),
325            copy_key: "ctrl+y".to_owned(),
326            steering_key: "enter".to_owned(),
327            follow_up_key: "alt+enter".to_owned(),
328            retrieve_queued_key: "ctrl+r".to_owned(),
329        }
330    }
331}
332
333#[cfg(test)]
334mod tests {
335    use super::TuiSettings;
336
337    #[test]
338    fn tui_defaults_to_codex_style_inline_viewport() {
339        assert_eq!(TuiSettings::default().viewport, "inline");
340    }
341}
342
343/// Declarative resource discovery settings.
344#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
345#[serde(rename_all = "camelCase", deny_unknown_fields)]
346pub struct ResourceSettings {
347    /// Whether workspace context files are loaded.
348    pub context_files: bool,
349    /// Additional bounded skill paths.
350    pub skill_paths: Vec<String>,
351    /// Whether prompt templates are loaded.
352    pub prompt_templates: bool,
353}
354
355impl Default for ResourceSettings {
356    fn default() -> Self {
357        Self {
358            context_files: true,
359            skill_paths: Vec::new(),
360            prompt_templates: true,
361        }
362    }
363}
364
365/// Sparse one-layer settings overlay.
366#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
367#[serde(rename_all = "camelCase", deny_unknown_fields)]
368pub struct SettingsLayer {
369    /// Optional schema version for files.
370    pub schema_version: Option<u32>,
371    /// Provider override.
372    pub provider: Option<String>,
373    /// Model override.
374    pub model: Option<String>,
375    /// Thinking override.
376    pub thinking: Option<String>,
377    /// Active tools replacement.
378    pub active_tools: Option<Vec<String>>,
379    /// Session database override.
380    pub session_database: Option<String>,
381    /// Retry override.
382    pub max_retries: Option<u32>,
383    /// Base model-retry delay override, in milliseconds.
384    pub retry_base_delay_ms: Option<u64>,
385    /// Maximum model-retry delay override, in milliseconds.
386    pub retry_max_delay_ms: Option<u64>,
387    /// Compaction override.
388    pub compaction_enabled: Option<bool>,
389    /// Nested TUI overlay.
390    pub tui: Option<TuiSettingsLayer>,
391    /// Nested resource overlay.
392    pub resources: Option<ResourceSettingsLayer>,
393    /// Nested web-search overlay.
394    pub web_search: Option<WebSearchSettingsLayer>,
395    /// Nested web-fetch overlay.
396    pub web_fetch: Option<WebFetchSettingsLayer>,
397    /// Project trust default override.
398    pub project_trust: Option<ProjectTrustDefault>,
399    /// Full MCP server replacements merged by canonical server ID.
400    pub mcp_servers: Option<Vec<McpServerSettings>>,
401}
402
403/// Sparse web-search settings overlay.
404#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
405#[serde(rename_all = "camelCase", deny_unknown_fields)]
406pub struct WebSearchSettingsLayer {
407    /// Route-preference override.
408    pub route_preference: Option<WebSearchRoutePreference>,
409    /// Domain allowlist replacement.
410    pub allowed_domains: Option<Vec<String>>,
411    /// Domain blocklist replacement.
412    pub blocked_domains: Option<Vec<String>>,
413    /// Nested approximate-location overlay.
414    pub location: Option<WebSearchLocationSettingsLayer>,
415    /// Nested client-backend overlay.
416    pub client: Option<ClientWebSearchSettingsLayer>,
417}
418
419/// Sparse approximate-location overlay.
420#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
421#[serde(rename_all = "camelCase", deny_unknown_fields)]
422pub struct WebSearchLocationSettingsLayer {
423    /// Country override.
424    pub country: Option<String>,
425    /// City override.
426    pub city: Option<String>,
427    /// Region override.
428    pub region: Option<String>,
429    /// Timezone override.
430    pub timezone: Option<String>,
431}
432
433/// Sparse client web-search backend overlay.
434#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
435#[serde(rename_all = "camelCase", deny_unknown_fields)]
436pub struct ClientWebSearchSettingsLayer {
437    /// Client-backend enablement override.
438    pub enabled: Option<bool>,
439    /// Client-backend selector override.
440    pub backend: Option<WebSearchClientBackend>,
441    /// Endpoint override.
442    pub endpoint: Option<String>,
443    /// API-key environment variable name override.
444    pub api_key_environment: Option<String>,
445    /// Request-timeout override in milliseconds.
446    pub timeout_millis: Option<u64>,
447}
448
449/// Sparse web-fetch settings overlay.
450#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
451#[serde(rename_all = "camelCase", deny_unknown_fields)]
452pub struct WebFetchSettingsLayer {
453    /// Backend enablement override.
454    pub enabled: Option<bool>,
455    /// Backend selector override.
456    pub backend: Option<WebFetchBackend>,
457    /// Nested bounded-cache overlay.
458    pub cache: Option<WebFetchCacheSettingsLayer>,
459}
460
461/// Sparse normalized-result cache overlay.
462#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
463#[serde(rename_all = "camelCase", deny_unknown_fields)]
464pub struct WebFetchCacheSettingsLayer {
465    /// Cache lifetime override in whole seconds.
466    pub ttl_seconds: Option<u64>,
467    /// Maximum entry-count override.
468    pub max_entries: Option<usize>,
469    /// Maximum aggregate-byte override.
470    pub max_total_bytes: Option<usize>,
471    /// Maximum per-entry byte override.
472    pub max_entry_bytes: Option<usize>,
473}
474
475/// Sparse TUI overlay.
476#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
477#[serde(rename_all = "camelCase", deny_unknown_fields)]
478pub struct TuiSettingsLayer {
479    /// Viewport override.
480    pub viewport: Option<String>,
481    /// Collapse override.
482    pub collapse_thinking: Option<bool>,
483    /// Reduced-motion override.
484    pub reduced_motion: Option<bool>,
485    /// Submit key override.
486    pub submit_key: Option<String>,
487    /// Newline key override.
488    pub newline_key: Option<String>,
489    /// Abort key override.
490    pub abort_key: Option<String>,
491    /// Clear key override.
492    pub clear_key: Option<String>,
493    /// Exit key override.
494    pub exit_key: Option<String>,
495    /// Model selector key override.
496    pub model_key: Option<String>,
497    /// Thinking toggle key override.
498    pub toggle_thinking_key: Option<String>,
499    /// Tool toggle key override.
500    pub toggle_tools_key: Option<String>,
501    /// Copy key override.
502    pub copy_key: Option<String>,
503    /// Steering key override.
504    pub steering_key: Option<String>,
505    /// Follow-up key override.
506    pub follow_up_key: Option<String>,
507    /// Queue retrieval key override.
508    pub retrieve_queued_key: Option<String>,
509}
510
511/// Sparse resource overlay.
512#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
513#[serde(rename_all = "camelCase", deny_unknown_fields)]
514pub struct ResourceSettingsLayer {
515    /// Context-file override.
516    pub context_files: Option<bool>,
517    /// Skill paths replacement.
518    pub skill_paths: Option<Vec<String>>,
519    /// Prompt-template override.
520    pub prompt_templates: Option<bool>,
521}