tea-coding 0.1.0

Coding profile, configuration, resources, and session service for tea-rs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
use serde::{Deserialize, Serialize};
use tea_coding_tools::{
    DEFAULT_FETCH_CACHE_ENTRIES, DEFAULT_FETCH_CACHE_ENTRY_BYTES, DEFAULT_FETCH_CACHE_TOTAL_BYTES,
    DEFAULT_FETCH_CACHE_TTL, DEFAULT_TAVILY_SEARCH_ENDPOINT,
};
use tea_mcp::McpServerConfig;
use tea_model::{WebSearchLocation, WebSearchOptions};

use crate::mcp_config::McpServerSettings;

/// Current persisted coding settings schema.
pub const CODING_SETTINGS_SCHEMA_VERSION: u32 = 1;
/// Default environment variable consulted by an embedding product for Tavily credentials.
pub const DEFAULT_WEB_SEARCH_API_KEY_ENVIRONMENT: &str = "TAVILY_API_KEY";
/// Default client web-search request timeout.
pub const DEFAULT_WEB_SEARCH_TIMEOUT_MILLIS: u64 = 30_000;
/// Maximum bytes in one configured API-key environment variable name.
pub const MAX_WEB_SEARCH_API_KEY_ENVIRONMENT_BYTES: usize = 128;

/// Behavior when project-local configuration exists without a saved decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ProjectTrustDefault {
    /// Interactive products may ask; headless products deny.
    #[default]
    Ask,
    /// Ignore all project-local settings and declarative resources.
    Ignore,
    /// Fail closed when project-local settings or resources are requested.
    Reject,
}

/// Versioned, secret-free resolved settings snapshot.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CodingSettings {
    /// Persisted schema version.
    pub schema_version: u32,
    /// Provider selector.
    pub provider: String,
    /// Model selector.
    pub model: String,
    /// Thinking mode selector.
    pub thinking: String,
    /// Canonical active tool names.
    pub active_tools: Vec<String>,
    /// Session database override, relative to injected state dir when absent.
    pub session_database: Option<String>,
    /// Maximum model retries.
    pub max_retries: u32,
    /// Base delay before the first model retry, in milliseconds.
    pub retry_base_delay_ms: u64,
    /// Maximum model retry delay, including provider hints, in milliseconds.
    pub retry_max_delay_ms: u64,
    /// Whether automatic compaction is enabled.
    pub compaction_enabled: bool,
    /// TUI settings.
    pub tui: TuiSettings,
    /// Declarative resource settings.
    pub resources: ResourceSettings,
    /// Registered web-search routing and backend controls.
    #[serde(default)]
    pub web_search: WebSearchSettings,
    /// Explicit client web-fetch backend and bounded cache controls.
    #[serde(default)]
    pub web_fetch: WebFetchSettings,
    /// Default project trust behavior.
    pub project_trust: ProjectTrustDefault,
    /// Validated runtime-only MCP server configs, omitted from durable settings.
    #[serde(skip, default)]
    pub mcp_servers: Vec<McpServerConfig>,
}

impl Default for CodingSettings {
    fn default() -> Self {
        Self {
            schema_version: CODING_SETTINGS_SCHEMA_VERSION,
            provider: "openai".to_owned(),
            model: "gpt-5.4".to_owned(),
            thinking: "medium".to_owned(),
            active_tools: vec!["read", "write", "edit", "bash"]
                .into_iter()
                .map(str::to_owned)
                .collect(),
            session_database: None,
            max_retries: 3,
            retry_base_delay_ms: 2_000,
            retry_max_delay_ms: 60_000,
            compaction_enabled: false,
            tui: TuiSettings::default(),
            resources: ResourceSettings::default(),
            web_search: WebSearchSettings::default(),
            web_fetch: WebFetchSettings::default(),
            project_trust: ProjectTrustDefault::Ask,
            mcp_servers: Vec::new(),
        }
    }
}

/// Route selected for web search when a real client backend is available.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum WebSearchRoutePreference {
    /// Prefer provider-hosted search and fall back to the client on unsupported models.
    #[default]
    PreferHosted,
    /// Always expose the client function route.
    ForceClient,
}

/// Client web-search backend selected by the embedding product.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum WebSearchClientBackend {
    /// Tavily's bounded search HTTP API.
    #[default]
    Tavily,
}

/// Secret-free resolved web-search settings.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase", deny_unknown_fields)]
pub struct WebSearchSettings {
    /// Route preference applied only when the client backend is enabled and injected.
    pub route_preference: WebSearchRoutePreference,
    /// Canonical domain allowlist shared by hosted and client search.
    pub allowed_domains: Vec<String>,
    /// Canonical domain blocklist shared by hosted and client search.
    pub blocked_domains: Vec<String>,
    /// Optional approximate location disclosed to capable hosted providers.
    pub location: Option<WebSearchLocationSettings>,
    /// Client-backend construction controls for embedding products.
    pub client: ClientWebSearchSettings,
}

impl Default for WebSearchSettings {
    fn default() -> Self {
        Self {
            route_preference: WebSearchRoutePreference::PreferHosted,
            allowed_domains: Vec::new(),
            blocked_domains: Vec::new(),
            location: None,
            client: ClientWebSearchSettings::default(),
        }
    }
}

impl WebSearchSettings {
    pub(crate) fn runtime_options(&self) -> Result<WebSearchOptions, tea_model::ModelRequestError> {
        let mut options = WebSearchOptions::new();
        if !self.allowed_domains.is_empty() {
            options = options.with_allowed_domains(self.allowed_domains.clone())?;
        }
        if !self.blocked_domains.is_empty() {
            options = options.with_blocked_domains(self.blocked_domains.clone())?;
        }
        if let Some(configured) = &self.location {
            let mut location = WebSearchLocation::new();
            if let Some(country) = &configured.country {
                location = location.with_country(country.clone())?;
            }
            if let Some(city) = &configured.city {
                location = location.with_city(city.clone())?;
            }
            if let Some(region) = &configured.region {
                location = location.with_region(region.clone())?;
            }
            if let Some(timezone) = &configured.timezone {
                location = location.with_timezone(timezone.clone())?;
            }
            options = options.with_location(location);
        }
        Ok(options)
    }
}

/// Approximate location fields used by hosted web search.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase", deny_unknown_fields)]
pub struct WebSearchLocationSettings {
    /// ISO 3166-1 alpha-2 uppercase country code.
    pub country: Option<String>,
    /// Approximate city name.
    pub city: Option<String>,
    /// Approximate region name.
    pub region: Option<String>,
    /// Canonical IANA-style timezone name.
    pub timezone: Option<String>,
}

/// Client web-search backend controls resolved without reading credentials.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase", deny_unknown_fields)]
pub struct ClientWebSearchSettings {
    /// Whether an embedding product may attach a real client backend.
    pub enabled: bool,
    /// Backend configuration contract expected by the injected provider.
    pub backend: WebSearchClientBackend,
    /// Validated Tavily-compatible HTTP endpoint.
    pub endpoint: String,
    /// Environment variable name resolved by the embedding product at construction time.
    pub api_key_environment: String,
    /// Per-request timeout in milliseconds.
    pub timeout_millis: u64,
}

impl Default for ClientWebSearchSettings {
    fn default() -> Self {
        Self {
            enabled: false,
            backend: WebSearchClientBackend::Tavily,
            endpoint: DEFAULT_TAVILY_SEARCH_ENDPOINT.to_owned(),
            api_key_environment: DEFAULT_WEB_SEARCH_API_KEY_ENVIRONMENT.to_owned(),
            timeout_millis: DEFAULT_WEB_SEARCH_TIMEOUT_MILLIS,
        }
    }
}

/// Client web-fetch backend selected by the embedding product.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum WebFetchBackend {
    /// Pinned, redirect-safe HTTP transport with bounded response extraction.
    #[default]
    Http,
}

/// Secret-free resolved web-fetch settings.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase", deny_unknown_fields)]
pub struct WebFetchSettings {
    /// Whether an embedding product may attach a real fetch backend.
    pub enabled: bool,
    /// Backend configuration contract expected by the injected provider.
    pub backend: WebFetchBackend,
    /// Bounded normalized-result cache controls.
    pub cache: WebFetchCacheSettings,
}

impl Default for WebFetchSettings {
    fn default() -> Self {
        Self {
            enabled: false,
            backend: WebFetchBackend::Http,
            cache: WebFetchCacheSettings::default(),
        }
    }
}

/// Bounded in-memory cache controls for normalized fetch results.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase", deny_unknown_fields)]
pub struct WebFetchCacheSettings {
    /// Cache lifetime in whole seconds.
    pub ttl_seconds: u64,
    /// Maximum cached result count.
    pub max_entries: usize,
    /// Maximum aggregate cache bytes.
    pub max_total_bytes: usize,
    /// Maximum bytes retained by one entry.
    pub max_entry_bytes: usize,
}

impl Default for WebFetchCacheSettings {
    fn default() -> Self {
        Self {
            ttl_seconds: DEFAULT_FETCH_CACHE_TTL.as_secs(),
            max_entries: DEFAULT_FETCH_CACHE_ENTRIES,
            max_total_bytes: DEFAULT_FETCH_CACHE_TOTAL_BYTES,
            max_entry_bytes: DEFAULT_FETCH_CACHE_ENTRY_BYTES,
        }
    }
}

/// Nested TUI settings merged independently by layer.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase", deny_unknown_fields)]
pub struct TuiSettings {
    /// Codex-style inline viewport or explicit fullscreen compatibility mode.
    pub viewport: String,
    /// Whether thinking blocks start collapsed.
    pub collapse_thinking: bool,
    /// Whether the terminal UI avoids animated status indicators.
    pub reduced_motion: bool,
    /// Submit key binding.
    pub submit_key: String,
    /// Newline key binding.
    pub newline_key: String,
    /// Active-run abort key binding.
    pub abort_key: String,
    /// Editor clear key binding.
    pub clear_key: String,
    /// Application exit key binding.
    pub exit_key: String,
    /// Model selector key binding.
    pub model_key: String,
    /// Thinking-collapse key binding.
    pub toggle_thinking_key: String,
    /// Tool-collapse key binding.
    pub toggle_tools_key: String,
    /// Copy key binding.
    pub copy_key: String,
    /// Active-run steering key binding.
    pub steering_key: String,
    /// Active-run follow-up key binding.
    pub follow_up_key: String,
    /// Queued-message retrieval key binding.
    pub retrieve_queued_key: String,
}

impl Default for TuiSettings {
    fn default() -> Self {
        Self {
            viewport: "inline".to_owned(),
            collapse_thinking: false,
            reduced_motion: false,
            submit_key: "enter".to_owned(),
            newline_key: "shift+enter".to_owned(),
            abort_key: "escape".to_owned(),
            clear_key: "ctrl+l".to_owned(),
            exit_key: "ctrl+d".to_owned(),
            model_key: "ctrl+o".to_owned(),
            toggle_thinking_key: "ctrl+t".to_owned(),
            toggle_tools_key: "ctrl+g".to_owned(),
            copy_key: "ctrl+y".to_owned(),
            steering_key: "enter".to_owned(),
            follow_up_key: "alt+enter".to_owned(),
            retrieve_queued_key: "ctrl+r".to_owned(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::TuiSettings;

    #[test]
    fn tui_defaults_to_codex_style_inline_viewport() {
        assert_eq!(TuiSettings::default().viewport, "inline");
    }
}

/// Declarative resource discovery settings.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ResourceSettings {
    /// Whether workspace context files are loaded.
    pub context_files: bool,
    /// Additional bounded skill paths.
    pub skill_paths: Vec<String>,
    /// Whether prompt templates are loaded.
    pub prompt_templates: bool,
}

impl Default for ResourceSettings {
    fn default() -> Self {
        Self {
            context_files: true,
            skill_paths: Vec::new(),
            prompt_templates: true,
        }
    }
}

/// Sparse one-layer settings overlay.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SettingsLayer {
    /// Optional schema version for files.
    pub schema_version: Option<u32>,
    /// Provider override.
    pub provider: Option<String>,
    /// Model override.
    pub model: Option<String>,
    /// Thinking override.
    pub thinking: Option<String>,
    /// Active tools replacement.
    pub active_tools: Option<Vec<String>>,
    /// Session database override.
    pub session_database: Option<String>,
    /// Retry override.
    pub max_retries: Option<u32>,
    /// Base model-retry delay override, in milliseconds.
    pub retry_base_delay_ms: Option<u64>,
    /// Maximum model-retry delay override, in milliseconds.
    pub retry_max_delay_ms: Option<u64>,
    /// Compaction override.
    pub compaction_enabled: Option<bool>,
    /// Nested TUI overlay.
    pub tui: Option<TuiSettingsLayer>,
    /// Nested resource overlay.
    pub resources: Option<ResourceSettingsLayer>,
    /// Nested web-search overlay.
    pub web_search: Option<WebSearchSettingsLayer>,
    /// Nested web-fetch overlay.
    pub web_fetch: Option<WebFetchSettingsLayer>,
    /// Project trust default override.
    pub project_trust: Option<ProjectTrustDefault>,
    /// Full MCP server replacements merged by canonical server ID.
    pub mcp_servers: Option<Vec<McpServerSettings>>,
}

/// Sparse web-search settings overlay.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WebSearchSettingsLayer {
    /// Route-preference override.
    pub route_preference: Option<WebSearchRoutePreference>,
    /// Domain allowlist replacement.
    pub allowed_domains: Option<Vec<String>>,
    /// Domain blocklist replacement.
    pub blocked_domains: Option<Vec<String>>,
    /// Nested approximate-location overlay.
    pub location: Option<WebSearchLocationSettingsLayer>,
    /// Nested client-backend overlay.
    pub client: Option<ClientWebSearchSettingsLayer>,
}

/// Sparse approximate-location overlay.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WebSearchLocationSettingsLayer {
    /// Country override.
    pub country: Option<String>,
    /// City override.
    pub city: Option<String>,
    /// Region override.
    pub region: Option<String>,
    /// Timezone override.
    pub timezone: Option<String>,
}

/// Sparse client web-search backend overlay.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ClientWebSearchSettingsLayer {
    /// Client-backend enablement override.
    pub enabled: Option<bool>,
    /// Client-backend selector override.
    pub backend: Option<WebSearchClientBackend>,
    /// Endpoint override.
    pub endpoint: Option<String>,
    /// API-key environment variable name override.
    pub api_key_environment: Option<String>,
    /// Request-timeout override in milliseconds.
    pub timeout_millis: Option<u64>,
}

/// Sparse web-fetch settings overlay.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WebFetchSettingsLayer {
    /// Backend enablement override.
    pub enabled: Option<bool>,
    /// Backend selector override.
    pub backend: Option<WebFetchBackend>,
    /// Nested bounded-cache overlay.
    pub cache: Option<WebFetchCacheSettingsLayer>,
}

/// Sparse normalized-result cache overlay.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WebFetchCacheSettingsLayer {
    /// Cache lifetime override in whole seconds.
    pub ttl_seconds: Option<u64>,
    /// Maximum entry-count override.
    pub max_entries: Option<usize>,
    /// Maximum aggregate-byte override.
    pub max_total_bytes: Option<usize>,
    /// Maximum per-entry byte override.
    pub max_entry_bytes: Option<usize>,
}

/// Sparse TUI overlay.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct TuiSettingsLayer {
    /// Viewport override.
    pub viewport: Option<String>,
    /// Collapse override.
    pub collapse_thinking: Option<bool>,
    /// Reduced-motion override.
    pub reduced_motion: Option<bool>,
    /// Submit key override.
    pub submit_key: Option<String>,
    /// Newline key override.
    pub newline_key: Option<String>,
    /// Abort key override.
    pub abort_key: Option<String>,
    /// Clear key override.
    pub clear_key: Option<String>,
    /// Exit key override.
    pub exit_key: Option<String>,
    /// Model selector key override.
    pub model_key: Option<String>,
    /// Thinking toggle key override.
    pub toggle_thinking_key: Option<String>,
    /// Tool toggle key override.
    pub toggle_tools_key: Option<String>,
    /// Copy key override.
    pub copy_key: Option<String>,
    /// Steering key override.
    pub steering_key: Option<String>,
    /// Follow-up key override.
    pub follow_up_key: Option<String>,
    /// Queue retrieval key override.
    pub retrieve_queued_key: Option<String>,
}

/// Sparse resource overlay.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ResourceSettingsLayer {
    /// Context-file override.
    pub context_files: Option<bool>,
    /// Skill paths replacement.
    pub skill_paths: Option<Vec<String>>,
    /// Prompt-template override.
    pub prompt_templates: Option<bool>,
}