Skip to main content

tea_cli/
bootstrap.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::fs;
3use std::io::Read as _;
4use std::path::{Path, PathBuf};
5use std::str::FromStr;
6use std::sync::Arc;
7use std::time::Duration;
8
9use tea_coding::config::{
10    CodingSettings, ModelDefinition, ProviderConfig, ProviderValueResolver, ProvidersConfigLoad,
11    SettingsLayer, WebFetchBackend, WebFetchSettings, WebSearchClientBackend, WebSearchSettings,
12    load_providers_file, load_settings_file, merge_settings,
13};
14use tea_coding::mcp_config::{
15    McpEnvironmentValue, ProcessMcpEnvironmentResolver, resolve_mcp_environment,
16};
17use tea_coding::resources::ResourceCatalog;
18use tea_coding::{
19    AppPaths, CodingAgentBuilder, CodingAgentService, CodingCredentialResolver, InteractionMode,
20    McpEnvironmentResolver, PersistedTrustDecision, ProjectAccess, ProjectTrustStore, TrustRequest,
21};
22use tea_coding_tools::{
23    BashConfig, BashOutputDirectory, BashShell, FetchCacheConfig, FetchCacheScope, FetchProvider,
24    FetchResultCache, HttpFetchProvider, SearchProvider, TavilyApiKey, TavilySearchConfig,
25    TavilySearchProvider, WorkspaceRoot,
26};
27use tea_mcp::{MAX_MCP_STARTUP_CONCURRENCY, McpManager, McpServerConfig, McpServerLaunch};
28use tea_model::{
29    BoxModelStream, ModelCancellation, ModelCapabilities, ModelDisplayName, ModelEvent,
30    ModelFailure, ModelFailureCode, ModelProvider, ModelRequest, ModelResponseInfo, ModelSpec,
31    ProviderId, ReasoningEffort, ReasoningProfile,
32};
33use tea_policy::{ActorId, WorkspaceId};
34use tea_protocol::ProtocolTimestamp;
35use tea_protocol::{ModelId, RetryClass, TokenCount};
36use tea_provider_anthropic::{
37    AnthropicProviderBuilder, CredentialResolver as _,
38    MapCredentialResolver as AnthropicCredentialResolver,
39};
40use tea_provider_http::{ProviderHttpConfig, UserAgent};
41use tea_provider_openai::{MapCredentialResolver, OpenAiProviderBuilder, OpenAiReasoningEffortMap};
42use tea_session_sqlite::SqliteSessionStore;
43use tea_tools::{ToolName, ToolTrust};
44
45use crate::args::{CliArgs, SessionSelection, TrustArg};
46use crate::{CliFailure, ExitCategory};
47
48/// Process values read once at the outward CLI boundary.
49#[derive(Clone)]
50pub struct BootstrapEnvironment {
51    current_dir: PathBuf,
52    home_dir: Option<PathBuf>,
53    values: BTreeMap<String, String>,
54    live_mcp_environment: bool,
55}
56
57impl std::fmt::Debug for BootstrapEnvironment {
58    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        formatter
60            .debug_struct("BootstrapEnvironment")
61            .field("current_dir", &self.current_dir)
62            .field("home_dir", &self.home_dir)
63            .field("values", &"**REDACTED**")
64            .field(
65                "mcp_environment",
66                &if self.live_mcp_environment {
67                    "process"
68                } else {
69                    "injected"
70                },
71            )
72            .finish()
73    }
74}
75
76impl BootstrapEnvironment {
77    /// Creates a fully injected environment for hermetic embedding/tests.
78    #[must_use]
79    pub fn new(
80        current_dir: impl Into<PathBuf>,
81        home_dir: Option<PathBuf>,
82        values: BTreeMap<String, String>,
83    ) -> Self {
84        Self {
85            current_dir: current_dir.into(),
86            home_dir,
87            values,
88            live_mcp_environment: false,
89        }
90    }
91
92    /// Captures the process environment once for later hermetic resolution.
93    ///
94    /// # Errors
95    ///
96    /// Returns a configuration failure when the current directory is unavailable.
97    pub fn from_process() -> Result<Self, CliFailure> {
98        let current_dir = std::env::current_dir()
99            .map_err(|_| config_failure("current directory is unavailable"))?;
100        let home_dir = process_home_dir();
101        let values = std::env::vars_os()
102            .filter_map(|(key, value)| Some((key.into_string().ok()?, value.into_string().ok()?)))
103            .collect();
104        let mut environment = Self::new(current_dir, home_dir, values);
105        environment.live_mcp_environment = true;
106        Ok(environment)
107    }
108
109    fn value(&self, key: &str) -> Option<&str> {
110        self.values.get(key).map(String::as_str)
111    }
112}
113
114fn process_home_dir() -> Option<PathBuf> {
115    home_dir_from(|key| std::env::var_os(key))
116}
117
118fn home_dir_from(mut value: impl FnMut(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
119    if let Some(home) = value("HOME").filter(|path| !path.is_empty()) {
120        return Some(PathBuf::from(home));
121    }
122    if let Some(profile) = value("USERPROFILE").filter(|path| !path.is_empty()) {
123        return Some(PathBuf::from(profile));
124    }
125    let drive = value("HOMEDRIVE").filter(|path| !path.is_empty())?;
126    let path = value("HOMEPATH").filter(|path| !path.is_empty())?;
127    let mut home = PathBuf::from(drive);
128    home.push(path);
129    Some(home)
130}
131
132impl McpEnvironmentResolver for BootstrapEnvironment {
133    fn resolve(
134        &self,
135        name: &str,
136    ) -> Result<Option<McpEnvironmentValue>, tea_coding::mcp_config::McpEnvironmentError> {
137        if self.live_mcp_environment {
138            return ProcessMcpEnvironmentResolver.resolve(name);
139        }
140        self.values
141            .get(name)
142            .map(|value| McpEnvironmentValue::try_new(name, value))
143            .transpose()
144    }
145}
146
147/// Injectable product bootstrap; production uses the live provider by default.
148#[derive(Debug, Clone)]
149pub struct CliBootstrap {
150    environment: BootstrapEnvironment,
151    providers: Vec<Arc<dyn ModelProvider>>,
152}
153
154/// The product surface responsible for a model request.
155#[derive(Clone, Copy, Debug, PartialEq, Eq)]
156enum ClientSurface {
157    Cli,
158    Tui,
159}
160
161impl ClientSurface {
162    const fn name(self) -> &'static str {
163        match self {
164            Self::Cli => "tea-cli",
165            Self::Tui => "tea-tui",
166        }
167    }
168}
169
170/// A workspace whose project-local resources require an interactive trust decision.
171#[derive(Clone, Debug, PartialEq, Eq)]
172pub(crate) struct WorkspaceTrustPrompt {
173    workspace: PathBuf,
174    trust_file: PathBuf,
175}
176
177impl WorkspaceTrustPrompt {
178    /// Returns the canonical workspace path displayed to the user.
179    #[must_use]
180    pub(crate) fn workspace(&self) -> &Path {
181        &self.workspace
182    }
183}
184
185impl CliBootstrap {
186    /// Creates a bootstrap from an injected environment.
187    #[must_use]
188    pub fn new(environment: BootstrapEnvironment) -> Self {
189        Self {
190            environment,
191            providers: Vec::new(),
192        }
193    }
194
195    /// Injects an additional provider (for embedding and hermetic tests).
196    #[must_use]
197    pub fn with_provider(mut self, provider: Arc<dyn ModelProvider>) -> Self {
198        self.providers.push(provider);
199        self
200    }
201
202    /// Returns the late MCP environment resolver owned by this bootstrap.
203    #[must_use]
204    pub fn mcp_environment_resolver(&self) -> &dyn McpEnvironmentResolver {
205        &self.environment
206    }
207
208    /// Reads one bounded UTF-8 prompt file through the workspace capability.
209    ///
210    /// # Errors
211    ///
212    /// Rejects absolute, traversing, escaping, changed, non-file, invalid UTF-8,
213    /// or oversized input.
214    pub fn read_prompt_file(&self, args: &CliArgs, path: &str) -> Result<String, CliFailure> {
215        let workspace_path = args
216            .cwd
217            .as_deref()
218            .unwrap_or(self.environment.current_dir.as_path());
219        let workspace = WorkspaceRoot::new(workspace_path)
220            .map_err(|_| config_failure("workspace directory is invalid"))?;
221        let resolved = workspace
222            .resolve_existing(path)
223            .map_err(|_| CliFailure::usage("prompt file path is invalid"))?;
224        let mut file = fs::File::open(resolved.host_path())
225            .map_err(|_| CliFailure::usage("prompt file could not be read"))?;
226        let metadata = file
227            .metadata()
228            .map_err(|_| CliFailure::usage("prompt file could not be read"))?;
229        workspace
230            .verify_opened_existing(&resolved, &metadata)
231            .map_err(|_| CliFailure::usage("prompt file changed during read"))?;
232        if !metadata.is_file()
233            || metadata.len() > crate::modes::print::MAX_INITIAL_PROMPT_BYTES as u64
234        {
235            return Err(CliFailure::usage("prompt file exceeds input size limit"));
236        }
237        let mut bytes = Vec::with_capacity(usize::try_from(metadata.len()).unwrap_or(0));
238        file.by_ref()
239            .take(crate::modes::print::MAX_INITIAL_PROMPT_BYTES as u64 + 1)
240            .read_to_end(&mut bytes)
241            .map_err(|_| CliFailure::usage("prompt file could not be read"))?;
242        workspace
243            .revalidate_existing(&resolved)
244            .map_err(|_| CliFailure::usage("prompt file changed during read"))?;
245        if u64::try_from(bytes.len()).ok() != Some(metadata.len()) {
246            return Err(CliFailure::usage("prompt file changed during read"));
247        }
248        if bytes.len() > crate::modes::print::MAX_INITIAL_PROMPT_BYTES {
249            return Err(CliFailure::usage("prompt file exceeds input size limit"));
250        }
251        String::from_utf8(bytes).map_err(|_| CliFailure::usage("prompt file is not valid UTF-8"))
252    }
253
254    /// Builds one mode-neutral coding service and resolves session selection.
255    ///
256    /// # Errors
257    ///
258    /// Returns stable trust/config/provider/internal failures without secret values.
259    pub fn build(
260        &self,
261        args: &CliArgs,
262    ) -> Result<(CodingAgentService, SessionSelection), CliFailure> {
263        let prepared = self.prepare(args, ClientSurface::Cli)?;
264        if !prepared.mcp_servers.is_empty() {
265            return Err(config_failure(
266                "MCP servers require asynchronous CLI bootstrap",
267            ));
268        }
269        let service = prepared.builder.build().map_err(CliFailure::from)?;
270        Ok((service, prepared.selection))
271    }
272
273    /// Asynchronously initializes MCP servers before immutable runtime binding.
274    ///
275    /// # Errors
276    ///
277    /// Returns a stable CLI failure when configuration, environment resolution,
278    /// server startup, or runtime assembly fails.
279    pub async fn build_async(
280        &self,
281        args: &CliArgs,
282    ) -> Result<(CodingAgentService, SessionSelection), CliFailure> {
283        let (service, selection, _) = self
284            .build_async_for_surface(args, ClientSurface::Cli)
285            .await?;
286        Ok((service, selection))
287    }
288
289    /// Builds the service used by the interactive terminal interface.
290    pub(crate) async fn build_tui_async(
291        &self,
292        args: &CliArgs,
293    ) -> Result<(CodingAgentService, SessionSelection, Vec<String>), CliFailure> {
294        self.build_async_for_surface(args, ClientSurface::Tui).await
295    }
296
297    /// Returns the trust prompt required before interactive bootstrap may continue.
298    pub(crate) fn workspace_trust_prompt(
299        &self,
300        args: &CliArgs,
301    ) -> Result<Option<WorkspaceTrustPrompt>, CliFailure> {
302        let (workspace, paths) = self.workspace_and_paths(args)?;
303        let access = Self::resolve_project_access(args, ClientSurface::Tui, &workspace, &paths)?;
304        Ok(
305            (access == ProjectAccess::Ask).then(|| WorkspaceTrustPrompt {
306                workspace: workspace.host_path().to_path_buf(),
307                trust_file: paths.trust_file(),
308            }),
309        )
310    }
311
312    /// Returns the global sparse settings file used by persistent TUI choices.
313    pub(crate) fn global_settings_path(&self, args: &CliArgs) -> Result<PathBuf, CliFailure> {
314        self.app_paths(args).map(|paths| paths.settings_file())
315    }
316
317    /// Persists an accepted interactive workspace trust decision.
318    pub(crate) fn accept_workspace_trust(prompt: &WorkspaceTrustPrompt) -> Result<(), CliFailure> {
319        ProjectTrustStore::new(prompt.trust_file.clone())
320            .set(&prompt.workspace, PersistedTrustDecision::Trusted)
321            .map_err(CliFailure::from)
322    }
323
324    async fn build_async_for_surface(
325        &self,
326        args: &CliArgs,
327        surface: ClientSurface,
328    ) -> Result<(CodingAgentService, SessionSelection, Vec<String>), CliFailure> {
329        let prepared = self.prepare(args, surface)?;
330        let manager = self
331            .start_mcp_manager(&prepared.mcp_servers, &prepared.active_mcp_tools)
332            .await?;
333        let mut builder = prepared.builder;
334        if let Some(manager) = &manager {
335            builder = builder.mcp_manager(Arc::clone(manager));
336        }
337        match builder.build().map_err(CliFailure::from) {
338            Ok(service) => Ok((service, prepared.selection, prepared.provider_notices)),
339            Err(error) => {
340                if let Some(manager) = manager {
341                    let _ = manager.shutdown().await;
342                }
343                Err(error)
344            }
345        }
346    }
347
348    #[allow(clippy::too_many_lines)] // Bootstrap order preserves trust and resource boundaries.
349    fn prepare(
350        &self,
351        args: &CliArgs,
352        surface: ClientSurface,
353    ) -> Result<PreparedBootstrap, CliFailure> {
354        let selection = args.session_selection()?;
355        if args.profile_id()?.as_str() != "coding-agent" {
356            return Err(config_failure("profile is not registered"));
357        }
358        let (workspace, paths) = self.workspace_and_paths(args)?;
359        let access = Self::resolve_project_access(args, surface, &workspace, &paths)?;
360        if access == ProjectAccess::Ask {
361            return Err(config_failure("workspace trust confirmation is required"));
362        }
363        let global = load_settings_file(&paths.settings_file()).map_err(CliFailure::from)?;
364        let global_providers = load_providers_file(&paths.providers_file());
365        let mut project = if access == tea_coding::ProjectAccess::Trusted {
366            load_project_settings(&workspace)?
367        } else {
368            None
369        };
370        let project_providers = if access == tea_coding::ProjectAccess::Trusted {
371            load_project_providers(&workspace)?
372        } else {
373            ProvidersConfigLoad::default()
374        };
375        let providers_config_error =
376            global_providers.error.is_some() || project_providers.error.is_some();
377        let mut provider_notices = Vec::new();
378        if providers_config_error {
379            if surface == ClientSurface::Tui {
380                provider_notices
381                    .push("custom provider configuration could not be loaded".to_owned());
382            } else {
383                eprintln!("warning: custom provider configuration could not be loaded");
384            }
385        }
386        let providers = global_providers.config.merged(project_providers.config);
387        if let Some(project) = &mut project {
388            // Durable state locations are host-owned, never project-controlled.
389            project.session_database = None;
390        }
391        let environment = self.environment_settings();
392        let cli = cli_settings(args)?;
393        let settings = merge_settings(
394            CodingSettings::default(),
395            global.as_ref(),
396            project.as_ref(),
397            Some(&environment),
398            Some(&cli),
399        )
400        .map_err(CliFailure::from)?;
401        let mcp_servers = configured_mcp_servers(&settings, project.as_ref());
402        let active_mcp_tools = active_mcp_tools(&settings, &mcp_servers)?;
403        if !matches!(settings.provider.as_str(), "openai" | "anthropic")
404            && !providers.providers.contains_key(&settings.provider)
405            && !self
406                .providers
407                .iter()
408                .any(|provider| provider.provider_id().as_str() == settings.provider)
409            && surface != ClientSurface::Tui
410        {
411            return Err(config_failure(if providers_config_error {
412                "custom provider configuration is invalid"
413            } else {
414                "provider is not supported"
415            }));
416        }
417
418        let mut global_skills = vec![paths.data_dir().join("skills")];
419        for path in &settings.resources.skill_paths {
420            global_skills.push(
421                workspace
422                    .resolve_existing(path)
423                    .map_err(|_| config_failure("configured skill path is invalid"))?
424                    .host_path()
425                    .to_path_buf(),
426            );
427        }
428        let project_skills = if access == tea_coding::ProjectAccess::Trusted {
429            optional_project_directory(&workspace, ".tea/skills")?
430                .into_iter()
431                .collect::<Vec<_>>()
432        } else {
433            Vec::new()
434        };
435        let global_prompts = paths.data_dir().join("prompts");
436        let project_prompts = if access == tea_coding::ProjectAccess::Trusted {
437            optional_project_directory(&workspace, ".tea/prompts")?
438        } else {
439            None
440        };
441        let mut resources = ResourceCatalog::discover(
442            workspace.host_path(),
443            workspace.host_path(),
444            access,
445            &global_skills,
446            &project_skills,
447            Some(&global_prompts),
448            project_prompts.as_deref(),
449        )
450        .map_err(CliFailure::from)?;
451        resources.apply_settings(
452            settings.resources.context_files,
453            settings.resources.prompt_templates,
454        );
455        resources
456            .add_explicit_context_files(&workspace, &args.context_files)
457            .map_err(CliFailure::from)?;
458
459        let store = if selection == SessionSelection::NoSession {
460            Arc::new(
461                SqliteSessionStore::in_memory()
462                    .map_err(|_| internal_failure("session store initialization failed"))?,
463            )
464        } else {
465            let database = session_database(args, &settings, &paths)?;
466            Arc::new(
467                SqliteSessionStore::open(path_text(&database)?)
468                    .map_err(|_| internal_failure("session store initialization failed"))?,
469            )
470        };
471        let overflow = paths.state_dir().join("bash-output");
472        create_private_directory(&overflow)?;
473        let bash = BashConfig::new(
474            shell(&self.environment)?,
475            BashOutputDirectory::new(&overflow)
476                .map_err(|_| config_failure("bash output directory is invalid"))?,
477            Duration::from_mins(2),
478        )
479        .map_err(|_| config_failure("bash configuration is invalid"))?;
480        let http_config = ProviderHttpConfig::new()
481            .with_user_agent(client_user_agent(surface, &self.environment));
482        let search_provider =
483            client_web_search_provider(&settings.web_search, &self.environment, &http_config)?;
484        let workspace_id = workspace_id(workspace.host_path())?;
485        let fetch_provider = client_web_fetch_provider(
486            &settings.web_fetch,
487            &settings.active_tools,
488            &workspace_id,
489            &http_config,
490        )?;
491        let provider = (|| -> Result<Arc<dyn ModelProvider>, CliFailure> {
492            if let Some(provider) = self
493                .providers
494                .iter()
495                .find(|provider| provider.provider_id().as_str() == settings.provider)
496            {
497                return Ok(Arc::clone(provider));
498            }
499            if settings.provider != "anthropic"
500                && let Some(config) = providers.providers.get(&settings.provider)
501            {
502                return custom_openai_provider(
503                    &settings.provider,
504                    &settings.model,
505                    config,
506                    args.api_key.as_ref(),
507                    &self.environment,
508                    http_config.clone(),
509                );
510            }
511            match settings.provider.as_str() {
512                "openai" => builtin_openai_provider(
513                    &settings.model,
514                    args.api_key.as_ref(),
515                    &self.environment,
516                    http_config.clone(),
517                ),
518                "anthropic" => builtin_anthropic_provider(
519                    &settings.model,
520                    args.api_key.as_ref(),
521                    &self.environment,
522                    http_config.clone(),
523                ),
524                _ => Err(config_failure(if providers_config_error {
525                    "custom provider configuration is invalid"
526                } else {
527                    "provider is not supported"
528                })),
529            }
530        })();
531        let provider = match provider {
532            Ok(provider) => provider,
533            Err(error) if surface == ClientSurface::Tui => {
534                provider_notices.push(format!("provider unavailable: {}", error.message()));
535                unavailable_provider(&settings, error.message())?
536            }
537            Err(error) => return Err(error),
538        };
539        let mut additional_providers = self
540            .providers
541            .iter()
542            .filter(|candidate| !Arc::ptr_eq(candidate, &provider))
543            .cloned()
544            .collect::<Vec<_>>();
545        for (provider_id, config) in &providers.providers {
546            if provider_id == provider.provider_id().as_str()
547                || additional_providers
548                    .iter()
549                    .any(|provider| provider.provider_id().as_str() == provider_id)
550            {
551                continue;
552            }
553            let Some(model_id) = config.models.first().map(|model| model.id.as_str()) else {
554                continue;
555            };
556            if let Ok(additional) = custom_openai_provider(
557                provider_id,
558                model_id,
559                config,
560                None,
561                &self.environment,
562                http_config.clone(),
563            ) {
564                additional_providers.push(additional);
565            }
566        }
567        for (provider_id, model_key, key_key, constructor) in [
568            (
569                "openai",
570                "TEA_OPENAI_MODEL",
571                "TEA_OPENAI_API_KEY",
572                builtin_openai_provider as BuiltinProviderConstructor,
573            ),
574            (
575                "anthropic",
576                "TEA_ANTHROPIC_MODEL",
577                "TEA_ANTHROPIC_API_KEY",
578                builtin_anthropic_provider as BuiltinProviderConstructor,
579            ),
580        ] {
581            if provider_id == provider.provider_id().as_str()
582                || additional_providers
583                    .iter()
584                    .any(|candidate| candidate.provider_id().as_str() == provider_id)
585            {
586                continue;
587            }
588            let Some(model_id) = self.environment.value(model_key) else {
589                continue;
590            };
591            if self.environment.value(key_key).is_none() {
592                continue;
593            }
594            if let Ok(additional) =
595                constructor(model_id, None, &self.environment, http_config.clone())
596            {
597                additional_providers.push(additional);
598            }
599        }
600        let mut builder = CodingAgentBuilder::new(
601            provider,
602            workspace.clone(),
603            resources,
604            store,
605            bash,
606            settings,
607            ActorId::from_str("local:user")
608                .map_err(|_| internal_failure("actor identity failed"))?,
609            workspace_id,
610        );
611        for provider in additional_providers {
612            builder = builder.provider(provider);
613        }
614        if let Some(search_provider) = search_provider {
615            builder = builder.search_provider(search_provider);
616        }
617        if let Some(fetch_provider) = fetch_provider {
618            builder = builder.fetch_provider(fetch_provider);
619        }
620        Ok(PreparedBootstrap {
621            builder,
622            selection,
623            mcp_servers,
624            active_mcp_tools,
625            provider_notices,
626        })
627    }
628
629    fn workspace_and_paths(&self, args: &CliArgs) -> Result<(WorkspaceRoot, AppPaths), CliFailure> {
630        let workspace_path = args
631            .cwd
632            .as_deref()
633            .unwrap_or(self.environment.current_dir.as_path());
634        let workspace = WorkspaceRoot::new(workspace_path)
635            .map_err(|_| config_failure("workspace directory is invalid"))?;
636        let paths = self.app_paths(args)?;
637        create_private_directories(&paths)?;
638        Ok((workspace, paths))
639    }
640
641    fn resolve_project_access(
642        args: &CliArgs,
643        surface: ClientSurface,
644        workspace: &WorkspaceRoot,
645        paths: &AppPaths,
646    ) -> Result<ProjectAccess, CliFailure> {
647        let has_project_resources = [
648            workspace.host_path().join("AGENTS.md"),
649            workspace.host_path().join("CLAUDE.md"),
650            workspace.host_path().join(".tea"),
651        ]
652        .iter()
653        .any(|path| path.exists());
654        if args.trust == TrustArg::Default && !has_project_resources {
655            return Ok(ProjectAccess::Ignored);
656        }
657        let mode = match surface {
658            ClientSurface::Cli => InteractionMode::NonInteractive,
659            ClientSurface::Tui => InteractionMode::Interactive,
660        };
661        ProjectTrustStore::new(paths.trust_file())
662            .resolve(workspace.host_path(), trust_request(args.trust), mode)
663            .map_err(CliFailure::from)
664    }
665
666    async fn start_mcp_manager(
667        &self,
668        servers: &[(McpServerConfig, ToolTrust)],
669        active_tools: &[ToolName],
670    ) -> Result<Option<Arc<McpManager>>, CliFailure> {
671        if servers.is_empty() {
672            return Ok(None);
673        }
674        let mut launches = Vec::with_capacity(servers.len());
675        for (server, trust) in servers {
676            let environment = resolve_mcp_environment(server, self.mcp_environment_resolver())
677                .map_err(|_| config_failure("MCP environment is unavailable"))?;
678            launches.push(
679                McpServerLaunch::new(server.clone(), *trust, environment.into_variables())
680                    .map_err(mcp_failure)?,
681            );
682        }
683        let observed_at = mcp_timestamp()?;
684        let manager = McpManager::start(
685            launches,
686            active_tools.iter().cloned(),
687            MAX_MCP_STARTUP_CONCURRENCY,
688            observed_at,
689        )
690        .await
691        .map_err(mcp_failure)?;
692        Ok(Some(Arc::new(manager)))
693    }
694
695    fn app_paths(&self, args: &CliArgs) -> Result<AppPaths, CliFailure> {
696        let home = self.environment.home_dir.as_deref();
697        let config = path_override(
698            args.config_dir.as_ref(),
699            self.environment.value("TEA_CONFIG_DIR"),
700            home.map(|path| path.join(".tea")),
701        )?;
702        let state = path_override(
703            args.state_dir.as_ref(),
704            self.environment.value("TEA_STATE_DIR"),
705            home.map(|path| path.join(".local/state/tea")),
706        )?;
707        let data = path_override(
708            args.data_dir.as_ref(),
709            self.environment.value("TEA_DATA_DIR"),
710            home.map(|path| path.join(".local/share/tea")),
711        )?;
712        AppPaths::new(config, state, data).map_err(CliFailure::from)
713    }
714
715    fn environment_settings(&self) -> SettingsLayer {
716        SettingsLayer {
717            provider: self.environment.value("TEA_PROVIDER").map(str::to_owned),
718            model: self
719                .environment
720                .value("TEA_MODEL")
721                .or_else(|| self.environment.value("TEA_OPENAI_MODEL"))
722                .or_else(|| self.environment.value("TEA_ANTHROPIC_MODEL"))
723                .map(str::to_owned),
724            thinking: self
725                .environment
726                .value("TEA_REASONING_EFFORT")
727                .or_else(|| self.environment.value("TEA_OPENAI_REASONING_EFFORT"))
728                .map(str::to_owned),
729            ..Default::default()
730        }
731    }
732}
733
734struct PreparedBootstrap {
735    builder: CodingAgentBuilder,
736    selection: SessionSelection,
737    mcp_servers: Vec<(McpServerConfig, ToolTrust)>,
738    active_mcp_tools: Vec<ToolName>,
739    provider_notices: Vec<String>,
740}
741
742#[derive(Debug)]
743struct UnavailableProvider {
744    provider_id: ProviderId,
745    models: Vec<ModelSpec>,
746    message: String,
747}
748
749impl ModelProvider for UnavailableProvider {
750    fn provider_id(&self) -> &ProviderId {
751        &self.provider_id
752    }
753
754    fn models(&self) -> &[ModelSpec] {
755        &self.models
756    }
757
758    fn stream(&self, _request: ModelRequest, _cancellation: ModelCancellation) -> BoxModelStream {
759        let failure = ModelFailure::new(
760            ModelFailureCode::Unavailable,
761            self.message.clone(),
762            RetryClass::Never,
763        )
764        .expect("bounded provider failure is valid");
765        Box::pin(futures_util::stream::iter([
766            ModelEvent::Started(ModelResponseInfo::new()),
767            ModelEvent::Failed(failure),
768        ]))
769    }
770}
771
772fn unavailable_provider(
773    settings: &CodingSettings,
774    reason: &str,
775) -> Result<Arc<dyn ModelProvider>, CliFailure> {
776    let provider_id = ProviderId::from_str(&settings.provider)
777        .map_err(|_| config_failure("provider selector is invalid"))?;
778    let model = ModelSpec::new(
779        ModelId::from_str(&settings.model)
780            .map_err(|_| config_failure("model selector is invalid"))?,
781        provider_id.clone(),
782        ModelDisplayName::from_str("Unavailable model")
783            .map_err(|_| internal_failure("model catalog failed"))?,
784        TokenCount::new(128_000).map_err(|_| internal_failure("model catalog failed"))?,
785        TokenCount::new(16_384).map_err(|_| internal_failure("model catalog failed"))?,
786        ModelCapabilities::text().with_tools(true),
787    )
788    .map_err(|_| internal_failure("model catalog failed"))?;
789    Ok(Arc::new(UnavailableProvider {
790        provider_id,
791        models: vec![model],
792        message: format!("provider is unavailable: {reason}"),
793    }))
794}
795
796fn configured_mcp_servers(
797    settings: &CodingSettings,
798    project: Option<&SettingsLayer>,
799) -> Vec<(McpServerConfig, ToolTrust)> {
800    let project_ids = project
801        .and_then(|layer| layer.mcp_servers.as_ref())
802        .into_iter()
803        .flatten()
804        .map(|server| server.id.as_str())
805        .collect::<BTreeSet<_>>();
806    settings
807        .mcp_servers
808        .iter()
809        .cloned()
810        .map(|server| {
811            let trust = if project_ids.contains(server.id().as_str()) {
812                ToolTrust::Workspace
813            } else {
814                ToolTrust::User
815            };
816            (server, trust)
817        })
818        .collect()
819}
820
821fn active_mcp_tools(
822    settings: &CodingSettings,
823    servers: &[(McpServerConfig, ToolTrust)],
824) -> Result<Vec<ToolName>, CliFailure> {
825    let aliases = servers
826        .iter()
827        .flat_map(|(server, _)| {
828            server
829                .tools()
830                .iter()
831                .filter_map(|tool| tool.resolved_alias(server.id()))
832        })
833        .collect::<BTreeSet<_>>();
834    settings
835        .active_tools
836        .iter()
837        .map(|alias| {
838            ToolName::from_str(alias).map_err(|_| config_failure("active tool is invalid"))
839        })
840        .collect::<Result<Vec<_>, _>>()
841        .map(|tools| {
842            tools
843                .into_iter()
844                .filter(|tool| aliases.contains(tool))
845                .collect()
846        })
847}
848
849fn mcp_timestamp() -> Result<ProtocolTimestamp, CliFailure> {
850    chrono::Utc::now()
851        .to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
852        .parse()
853        .map_err(|_| internal_failure("MCP clock is unavailable"))
854}
855
856fn mcp_failure(error: tea_mcp::McpError) -> CliFailure {
857    CliFailure::new(ExitCategory::TrustOrConfig, error.to_string())
858}
859
860fn load_project_settings(workspace: &WorkspaceRoot) -> Result<Option<SettingsLayer>, CliFailure> {
861    match workspace.resolve_existing(".tea/settings.json") {
862        Ok(path) => {
863            workspace
864                .revalidate_existing(&path)
865                .map_err(|_| config_failure("project settings path changed"))?;
866            let settings = load_settings_file(path.host_path()).map_err(CliFailure::from)?;
867            workspace
868                .revalidate_existing(&path)
869                .map_err(|_| config_failure("project settings path changed"))?;
870            Ok(settings)
871        }
872        Err(error) if error.code() == tea_coding_tools::WorkspacePathErrorCode::TargetNotFound => {
873            Ok(None)
874        }
875        Err(_) => Err(config_failure("project settings path is invalid")),
876    }
877}
878
879fn load_project_providers(workspace: &WorkspaceRoot) -> Result<ProvidersConfigLoad, CliFailure> {
880    match workspace.resolve_existing(".tea/providers.json") {
881        Ok(path) => {
882            workspace
883                .revalidate_existing(&path)
884                .map_err(|_| config_failure("project provider path changed"))?;
885            let providers = load_providers_file(path.host_path());
886            workspace
887                .revalidate_existing(&path)
888                .map_err(|_| config_failure("project provider path changed"))?;
889            Ok(providers)
890        }
891        Err(error) if error.code() == tea_coding_tools::WorkspacePathErrorCode::TargetNotFound => {
892            Ok(ProvidersConfigLoad::default())
893        }
894        Err(_) => Err(config_failure("project provider path is invalid")),
895    }
896}
897
898fn optional_project_directory(
899    workspace: &WorkspaceRoot,
900    path: &str,
901) -> Result<Option<PathBuf>, CliFailure> {
902    match workspace.resolve_existing(path) {
903        Ok(path) if path.host_path().is_dir() => Ok(Some(path.host_path().to_path_buf())),
904        Ok(_) => Err(config_failure("project resource path is not a directory")),
905        Err(error) if error.code() == tea_coding_tools::WorkspacePathErrorCode::TargetNotFound => {
906            Ok(None)
907        }
908        Err(_) => Err(config_failure("project resource path is invalid")),
909    }
910}
911
912fn trust_request(value: TrustArg) -> TrustRequest {
913    match value {
914        TrustArg::Default => TrustRequest::Default,
915        TrustArg::Once => TrustRequest::TrustOnce,
916        TrustArg::Persist => TrustRequest::TrustPersisted,
917        TrustArg::Reject => TrustRequest::Reject,
918        TrustArg::Ignore => TrustRequest::Ignore,
919    }
920}
921
922fn cli_settings(args: &CliArgs) -> Result<SettingsLayer, CliFailure> {
923    let session_database = args
924        .session_db
925        .as_deref()
926        .map(path_text)
927        .transpose()?
928        .map(str::to_owned);
929    Ok(SettingsLayer {
930        provider: args.provider.clone(),
931        model: args.model.clone(),
932        thinking: args
933            .reasoning_effort
934            .map(|effort| effort.as_str().to_owned()),
935        active_tools: (!args.tools.is_empty()).then(|| args.tools.clone()),
936        session_database,
937        ..Default::default()
938    })
939}
940
941fn session_database(
942    args: &CliArgs,
943    settings: &CodingSettings,
944    paths: &AppPaths,
945) -> Result<PathBuf, CliFailure> {
946    let configured = args.session_db.as_ref().map_or_else(
947        || settings.session_database.as_ref().map(PathBuf::from),
948        |path| Some(path.clone()),
949    );
950    let path = configured.map_or_else(
951        || paths.session_database(),
952        |path| {
953            if path.is_absolute() {
954                path
955            } else {
956                paths.state_dir().join(path)
957            }
958        },
959    );
960    if let Some(parent) = path.parent() {
961        create_private_directory(parent)?;
962    }
963    Ok(path)
964}
965
966fn path_override(
967    argument: Option<&PathBuf>,
968    environment: Option<&str>,
969    fallback: Option<PathBuf>,
970) -> Result<PathBuf, CliFailure> {
971    argument
972        .cloned()
973        .or_else(|| environment.map(PathBuf::from))
974        .or(fallback)
975        .filter(|path| path.is_absolute())
976        .ok_or_else(|| config_failure("absolute application paths are required"))
977}
978
979fn create_private_directories(paths: &AppPaths) -> Result<(), CliFailure> {
980    for path in [paths.config_dir(), paths.state_dir(), paths.data_dir()] {
981        create_private_directory(path)?;
982    }
983    Ok(())
984}
985
986fn create_private_directory(path: &Path) -> Result<(), CliFailure> {
987    if path.exists() {
988        return path
989            .is_dir()
990            .then_some(())
991            .ok_or_else(|| config_failure("application directory is invalid"));
992    }
993    let mut builder = fs::DirBuilder::new();
994    builder.recursive(true);
995    #[cfg(unix)]
996    {
997        use std::os::unix::fs::DirBuilderExt as _;
998        builder.mode(0o700);
999    }
1000    builder
1001        .create(path)
1002        .map_err(|_| config_failure("application directory is unavailable"))
1003}
1004
1005#[cfg(unix)]
1006fn shell(environment: &BootstrapEnvironment) -> Result<BashShell, CliFailure> {
1007    BashShell::new(
1008        environment.value("TEA_SHELL").unwrap_or("/bin/sh"),
1009        environment.value("TEA_SHELL_FLAG").unwrap_or("-c"),
1010    )
1011    .map_err(|_| config_failure("configured shell is invalid"))
1012}
1013
1014#[cfg(windows)]
1015fn shell(environment: &BootstrapEnvironment) -> Result<BashShell, CliFailure> {
1016    let executable = environment
1017        .value("TEA_SHELL")
1018        .map(PathBuf::from)
1019        .or_else(|| environment.value("COMSPEC").map(PathBuf::from))
1020        .ok_or_else(|| config_failure("configured shell is unavailable"))?;
1021    BashShell::new(
1022        executable,
1023        environment.value("TEA_SHELL_FLAG").unwrap_or("/C"),
1024    )
1025    .map_err(|_| config_failure("configured shell is invalid"))
1026}
1027
1028fn custom_openai_provider(
1029    provider_id: &str,
1030    model_id: &str,
1031    provider: &ProviderConfig,
1032    cli_api_key: Option<&tea_provider_openai::ApiKey>,
1033    environment: &BootstrapEnvironment,
1034    http_config: ProviderHttpConfig,
1035) -> Result<Arc<dyn ModelProvider>, CliFailure> {
1036    let provider_id = ProviderId::from_str(provider_id)
1037        .map_err(|_| config_failure("provider selector is invalid"))?;
1038    let value_resolver = ProviderValueResolver::new(provider_environment(environment));
1039    let mut values = environment.values.clone();
1040    values.insert("TEA_OPENAI_MODEL".to_owned(), model_id.to_owned());
1041    insert_provider_value(
1042        &mut values,
1043        "TEA_OPENAI_BASE_URL",
1044        provider.base_url.as_deref(),
1045    );
1046    insert_provider_value(
1047        &mut values,
1048        "TEA_OPENAI_API_KEY_HEADER",
1049        provider.api_key_header.as_deref(),
1050    );
1051    insert_provider_value(
1052        &mut values,
1053        "TEA_OPENAI_API_KEY_PREFIX",
1054        provider.api_key_prefix.as_deref(),
1055    );
1056    insert_provider_value(
1057        &mut values,
1058        "TEA_OPENAI_API_MODE",
1059        provider.api_mode.as_deref(),
1060    );
1061    insert_provider_value(&mut values, "TEA_OPENAI_ORG_ID", provider.org_id.as_deref());
1062    insert_provider_value(
1063        &mut values,
1064        "TEA_OPENAI_PROJECT_ID",
1065        provider.project_id.as_deref(),
1066    );
1067    insert_provider_value(
1068        &mut values,
1069        "TEA_OPENAI_REASONING_EFFORT",
1070        provider.reasoning_effort.as_deref(),
1071    );
1072    if let Some(vision) = provider.vision {
1073        values.insert("TEA_OPENAI_VISION".to_owned(), vision.to_string());
1074    }
1075    if let Some(timeout_millis) = provider.timeout_millis {
1076        values.insert(
1077            "TEA_OPENAI_REQUEST_TIMEOUT_MS".to_owned(),
1078            timeout_millis.to_string(),
1079        );
1080    }
1081    if let Some(api_key) = cli_api_key {
1082        values.insert("TEA_OPENAI_API_KEY".to_owned(), api_key.as_str().to_owned());
1083    } else if let Some(api_key) = &provider.api_key {
1084        values.insert(
1085            "TEA_OPENAI_API_KEY".to_owned(),
1086            value_resolver.resolve(api_key).ok_or_else(|| {
1087                provider_failure("configured provider API key could not be resolved")
1088            })?,
1089        );
1090    }
1091    let config = CodingCredentialResolver::new(Arc::new(MapCredentialResolver::for_provider(
1092        provider_id.clone(),
1093        values,
1094    )))
1095    .resolve()
1096    .map_err(CliFailure::from)?;
1097    let catalog = custom_model_specs(&provider_id, provider)?;
1098    if !catalog
1099        .models
1100        .iter()
1101        .any(|model| model.model_id().as_str() == model_id)
1102    {
1103        return Err(config_failure("model is not configured for provider"));
1104    }
1105    Ok(Arc::new(
1106        OpenAiProviderBuilder::new()
1107            .with_config(Arc::new(config))
1108            .with_catalog(catalog.models)
1109            .with_reasoning_effort_maps(catalog.reasoning_effort_maps)
1110            .with_http_config(http_config)
1111            .build()
1112            .map_err(|_| provider_failure("provider configuration failed"))?,
1113    ))
1114}
1115
1116type BuiltinProviderConstructor = fn(
1117    &str,
1118    Option<&tea_provider_openai::ApiKey>,
1119    &BootstrapEnvironment,
1120    ProviderHttpConfig,
1121) -> Result<Arc<dyn ModelProvider>, CliFailure>;
1122
1123fn builtin_openai_provider(
1124    model_id: &str,
1125    cli_api_key: Option<&tea_provider_openai::ApiKey>,
1126    environment: &BootstrapEnvironment,
1127    http_config: ProviderHttpConfig,
1128) -> Result<Arc<dyn ModelProvider>, CliFailure> {
1129    let mut values = environment.values.clone();
1130    values.insert("TEA_OPENAI_MODEL".to_owned(), model_id.to_owned());
1131    if let Some(api_key) = cli_api_key {
1132        values.insert("TEA_OPENAI_API_KEY".to_owned(), api_key.as_str().to_owned());
1133    }
1134    let config = CodingCredentialResolver::new(Arc::new(MapCredentialResolver::new(values)))
1135        .resolve()
1136        .map_err(CliFailure::from)?;
1137    let catalog = tea_provider_openai::catalog::default_catalog(&config)
1138        .map_err(|_| provider_failure("provider model catalog failed"))?;
1139    Ok(Arc::new(
1140        OpenAiProviderBuilder::new()
1141            .with_config(Arc::new(config))
1142            .with_catalog(catalog)
1143            .with_http_config(http_config)
1144            .build()
1145            .map_err(|_| provider_failure("provider configuration failed"))?,
1146    ))
1147}
1148
1149fn builtin_anthropic_provider(
1150    model_id: &str,
1151    cli_api_key: Option<&tea_provider_openai::ApiKey>,
1152    environment: &BootstrapEnvironment,
1153    http_config: ProviderHttpConfig,
1154) -> Result<Arc<dyn ModelProvider>, CliFailure> {
1155    let mut values = environment.values.clone();
1156    values.insert("TEA_ANTHROPIC_MODEL".to_owned(), model_id.to_owned());
1157    if let Some(api_key) = cli_api_key {
1158        values.insert(
1159            "TEA_ANTHROPIC_API_KEY".to_owned(),
1160            api_key.as_str().to_owned(),
1161        );
1162    }
1163    let config = AnthropicCredentialResolver::new(values)
1164        .resolve()
1165        .map_err(|_| provider_failure("provider configuration failed"))?;
1166    Ok(Arc::new(
1167        AnthropicProviderBuilder::new()
1168            .with_config(Arc::new(config))
1169            .with_http_config(http_config)
1170            .build()
1171            .map_err(|_| provider_failure("provider configuration failed"))?,
1172    ))
1173}
1174
1175fn provider_environment(environment: &BootstrapEnvironment) -> BTreeMap<String, String> {
1176    environment.values.clone()
1177}
1178
1179fn client_web_search_provider(
1180    settings: &WebSearchSettings,
1181    environment: &BootstrapEnvironment,
1182    http: &ProviderHttpConfig,
1183) -> Result<Option<Arc<dyn SearchProvider>>, CliFailure> {
1184    if !settings.client.enabled {
1185        return Ok(None);
1186    }
1187    let Some(api_key) = environment
1188        .value(&settings.client.api_key_environment)
1189        .filter(|value| !value.trim().is_empty())
1190    else {
1191        return Ok(None);
1192    };
1193    let api_key = TavilyApiKey::new(api_key.to_owned())
1194        .map_err(|_| provider_failure("client web search credential is invalid"))?;
1195    let provider: Arc<dyn SearchProvider> = match settings.client.backend {
1196        WebSearchClientBackend::Tavily => {
1197            let config = TavilySearchConfig::new(
1198                &settings.client.endpoint,
1199                Duration::from_millis(settings.client.timeout_millis),
1200            )
1201            .map_err(|_| config_failure("client web search configuration is invalid"))?;
1202            Arc::new(
1203                TavilySearchProvider::new(config, api_key, http).map_err(|_| {
1204                    provider_failure("client web search provider initialization failed")
1205                })?,
1206            )
1207        }
1208    };
1209    Ok(Some(provider))
1210}
1211
1212fn client_web_fetch_provider(
1213    settings: &WebFetchSettings,
1214    active_tools: &[String],
1215    workspace_id: &WorkspaceId,
1216    http: &ProviderHttpConfig,
1217) -> Result<Option<Arc<dyn FetchProvider>>, CliFailure> {
1218    if !settings.enabled || !active_tools.iter().any(|tool| tool == "web_fetch") {
1219        return Ok(None);
1220    }
1221    let cache_config = FetchCacheConfig::new(
1222        Duration::from_secs(settings.cache.ttl_seconds),
1223        settings.cache.max_entries,
1224        settings.cache.max_total_bytes,
1225        settings.cache.max_entry_bytes,
1226    )
1227    .map_err(|_| config_failure("client web fetch cache configuration is invalid"))?;
1228    let scope = FetchCacheScope::new(workspace_id.as_str(), "coding-agent")
1229        .map_err(|_| config_failure("client web fetch cache scope is invalid"))?;
1230    let cache = Arc::new(FetchResultCache::new(cache_config));
1231    let provider: Arc<dyn FetchProvider> = match settings.backend {
1232        WebFetchBackend::Http => Arc::new(HttpFetchProvider::production(scope, cache, http)),
1233    };
1234    Ok(Some(provider))
1235}
1236
1237fn insert_provider_value(values: &mut BTreeMap<String, String>, key: &str, value: Option<&str>) {
1238    if let Some(value) = value {
1239        values.insert(key.to_owned(), value.to_owned());
1240    }
1241}
1242
1243struct CustomModelCatalog {
1244    models: Vec<ModelSpec>,
1245    reasoning_effort_maps: BTreeMap<ModelId, OpenAiReasoningEffortMap>,
1246}
1247
1248fn custom_model_specs(
1249    provider_id: &ProviderId,
1250    provider: &ProviderConfig,
1251) -> Result<CustomModelCatalog, CliFailure> {
1252    if provider.models.is_empty() {
1253        return Err(config_failure("configured provider has no models"));
1254    }
1255    let mut models = Vec::with_capacity(provider.models.len());
1256    let mut reasoning_effort_maps = BTreeMap::new();
1257    for model in &provider.models {
1258        let (spec, map) = custom_model_spec(provider_id, provider, model)?;
1259        if let Some(map) = map {
1260            reasoning_effort_maps.insert(spec.model_id().clone(), map);
1261        }
1262        models.push(spec);
1263    }
1264    Ok(CustomModelCatalog {
1265        models,
1266        reasoning_effort_maps,
1267    })
1268}
1269
1270fn custom_model_spec(
1271    provider_id: &ProviderId,
1272    provider: &ProviderConfig,
1273    model: &ModelDefinition,
1274) -> Result<(ModelSpec, Option<OpenAiReasoningEffortMap>), CliFailure> {
1275    let reasoning = custom_model_reasoning(provider, model)?;
1276    let mut capabilities = ModelCapabilities::text().with_tools(true);
1277    if provider.vision.unwrap_or(false) {
1278        capabilities = capabilities.with_image_input();
1279    }
1280    if reasoning.is_some() {
1281        capabilities = capabilities.with_reasoning();
1282    }
1283    for hosted_tool in &model.capabilities.hosted_tools {
1284        capabilities = capabilities.with_hosted_tool(hosted_tool.kind());
1285    }
1286    let spec = ModelSpec::new(
1287        ModelId::from_str(&model.id)
1288            .map_err(|_| config_failure("configured model identifier is invalid"))?,
1289        provider_id.clone(),
1290        ModelDisplayName::from_str(model.display_name.as_deref().unwrap_or(&model.id))
1291            .map_err(|_| config_failure("configured model name is invalid"))?,
1292        TokenCount::new(model.context_window_tokens.unwrap_or(128_000))
1293            .map_err(|_| config_failure("configured model context window is invalid"))?,
1294        TokenCount::new(model.max_output_tokens.unwrap_or(16_384))
1295            .map_err(|_| config_failure("configured model output limit is invalid"))?,
1296        capabilities,
1297    )
1298    .map_err(|_| config_failure("configured model limits are invalid"))?;
1299    let Some((profile, map)) = reasoning else {
1300        return Ok((spec, None));
1301    };
1302    Ok((spec.with_reasoning_profile(profile), Some(map)))
1303}
1304
1305fn custom_model_reasoning(
1306    provider: &ProviderConfig,
1307    model: &ModelDefinition,
1308) -> Result<Option<(ReasoningProfile, OpenAiReasoningEffortMap)>, CliFailure> {
1309    if let Some(reasoning) = &model.capabilities.reasoning {
1310        let (profile, entries) = reasoning
1311            .resolved()
1312            .ok_or_else(|| config_failure("configured model reasoning profile is invalid"))?;
1313        let map = OpenAiReasoningEffortMap::new(entries)
1314            .map_err(|_| config_failure("configured model reasoning wire map is invalid"))?;
1315        return Ok(Some((profile, map)));
1316    }
1317    let Some(default_effort) = provider
1318        .reasoning_effort
1319        .as_deref()
1320        .and_then(|value| ReasoningEffort::from_str(value).ok())
1321    else {
1322        return Ok(None);
1323    };
1324    let provisional =
1325        ReasoningProfile::new(ReasoningEffort::Medium, ReasoningEffort::SHORTCUT_LEVELS)
1326            .map_err(|_| config_failure("legacy reasoning default is invalid"))?;
1327    let default_effort = provisional.resolve(default_effort).effective();
1328    let profile = ReasoningProfile::new(default_effort, ReasoningEffort::SHORTCUT_LEVELS)
1329        .map_err(|_| config_failure("legacy reasoning default is invalid"))?;
1330    let map = OpenAiReasoningEffortMap::new(
1331        ReasoningEffort::SHORTCUT_LEVELS
1332            .into_iter()
1333            .filter(|effort| *effort != ReasoningEffort::Off)
1334            .map(|effort| (effort, effort.as_str().to_owned())),
1335    )
1336    .map_err(|_| config_failure("legacy reasoning wire map is invalid"))?;
1337    Ok(Some((profile, map)))
1338}
1339
1340fn client_user_agent(surface: ClientSurface, environment: &BootstrapEnvironment) -> UserAgent {
1341    let version = env!("CARGO_PKG_VERSION");
1342    let os_info = os_info::get();
1343    let client = surface.name();
1344    let value = format!(
1345        "{client}/{version} ({} {}; {}) {} ({client}; {version})",
1346        os_info.os_type(),
1347        os_info.version(),
1348        os_info.architecture().unwrap_or("unknown"),
1349        terminal_user_agent_token(environment),
1350    );
1351    UserAgent::new(value).expect("built-in user agent is valid")
1352}
1353
1354fn terminal_user_agent_token(environment: &BootstrapEnvironment) -> String {
1355    if let Some(program) = environment_value(environment, "TERM_PROGRAM") {
1356        return match environment_value(environment, "TERM_PROGRAM_VERSION") {
1357            Some(version) => format!("{program}/{version}"),
1358            None => program.to_owned(),
1359        };
1360    }
1361    if let Some(version) = environment_value(environment, "WEZTERM_VERSION") {
1362        return format!("WezTerm/{version}");
1363    }
1364    if has_environment_value(environment, "ITERM_SESSION_ID")
1365        || has_environment_value(environment, "ITERM_PROFILE")
1366        || has_environment_value(environment, "ITERM_PROFILE_NAME")
1367    {
1368        return "iTerm.app".to_owned();
1369    }
1370    if has_environment_value(environment, "TERM_SESSION_ID") {
1371        return "Apple_Terminal".to_owned();
1372    }
1373    if has_environment_value(environment, "KITTY_WINDOW_ID")
1374        || environment_value(environment, "TERM").is_some_and(|term| term.contains("kitty"))
1375    {
1376        return "kitty".to_owned();
1377    }
1378    if has_environment_value(environment, "ALACRITTY_SOCKET")
1379        || environment_value(environment, "TERM").is_some_and(|term| term == "alacritty")
1380    {
1381        return "Alacritty".to_owned();
1382    }
1383    if let Some(version) = environment_value(environment, "KONSOLE_VERSION") {
1384        return format!("Konsole/{version}");
1385    }
1386    if has_environment_value(environment, "GNOME_TERMINAL_SCREEN") {
1387        return "gnome-terminal".to_owned();
1388    }
1389    if let Some(version) = environment_value(environment, "VTE_VERSION") {
1390        return format!("VTE/{version}");
1391    }
1392    if has_environment_value(environment, "WT_SESSION") {
1393        return "WindowsTerminal".to_owned();
1394    }
1395    environment_value(environment, "TERM").map_or_else(|| "unknown".to_owned(), str::to_owned)
1396}
1397
1398fn has_environment_value(environment: &BootstrapEnvironment, key: &str) -> bool {
1399    environment_value(environment, key).is_some()
1400}
1401
1402fn environment_value<'a>(environment: &'a BootstrapEnvironment, key: &str) -> Option<&'a str> {
1403    environment
1404        .value(key)
1405        .map(str::trim)
1406        .filter(|value| !value.is_empty())
1407        .map(sanitize_user_agent_token)
1408        .filter(|value| !value.is_empty())
1409}
1410
1411fn sanitize_user_agent_token(value: &str) -> &str {
1412    if value
1413        .bytes()
1414        .all(|byte| byte.is_ascii() && !byte.is_ascii_control())
1415    {
1416        value
1417    } else {
1418        ""
1419    }
1420}
1421
1422fn workspace_id(path: &Path) -> Result<WorkspaceId, CliFailure> {
1423    let bytes = path_text(path)?.as_bytes();
1424    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
1425    for byte in bytes {
1426        hash ^= u64::from(*byte);
1427        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
1428    }
1429    WorkspaceId::from_str(&format!("workspace/{hash:016x}"))
1430        .map_err(|_| internal_failure("workspace identity failed"))
1431}
1432
1433fn path_text(path: &Path) -> Result<&str, CliFailure> {
1434    path.to_str()
1435        .filter(|value| value.len() <= 4096 && !value.chars().any(char::is_control))
1436        .ok_or_else(|| config_failure("filesystem path is invalid"))
1437}
1438
1439fn config_failure(message: &'static str) -> CliFailure {
1440    CliFailure::new(ExitCategory::TrustOrConfig, message)
1441}
1442
1443fn provider_failure(message: &'static str) -> CliFailure {
1444    CliFailure::new(ExitCategory::Provider, message)
1445}
1446
1447fn internal_failure(message: &'static str) -> CliFailure {
1448    CliFailure::new(ExitCategory::Internal, message)
1449}
1450
1451#[cfg(test)]
1452mod tests {
1453    use super::*;
1454    use clap::Parser as _;
1455
1456    fn model_ref(provider_id: &str, model_id: &str) -> tea_protocol::ModelRef {
1457        tea_protocol::ModelRef::new(provider_id.parse().unwrap(), model_id.parse().unwrap())
1458    }
1459
1460    fn test_environment(
1461        values: impl IntoIterator<Item = (&'static str, &'static str)>,
1462    ) -> BootstrapEnvironment {
1463        BootstrapEnvironment::new(
1464            ".",
1465            None,
1466            values
1467                .into_iter()
1468                .map(|(key, value)| (key.to_owned(), value.to_owned()))
1469                .collect(),
1470        )
1471    }
1472
1473    #[test]
1474    fn user_agent_identifies_the_cli_and_tui_surfaces() {
1475        let environment = test_environment([
1476            ("TERM_PROGRAM", "iTerm.app"),
1477            ("TERM_PROGRAM_VERSION", "3.6.11"),
1478        ]);
1479        let os_info = os_info::get();
1480        let version = env!("CARGO_PKG_VERSION");
1481
1482        for (surface, name) in [
1483            (ClientSurface::Cli, "tea-cli"),
1484            (ClientSurface::Tui, "tea-tui"),
1485        ] {
1486            let expected = format!(
1487                "{name}/{version} ({} {}; {}) iTerm.app/3.6.11 ({name}; {version})",
1488                os_info.os_type(),
1489                os_info.version(),
1490                os_info.architecture().unwrap_or("unknown"),
1491            );
1492            assert_eq!(
1493                client_user_agent(surface, &environment),
1494                UserAgent::new(expected).unwrap()
1495            );
1496        }
1497    }
1498
1499    #[test]
1500    fn terminal_user_agent_token_follows_codex_environment_priority() {
1501        let environment = test_environment([
1502            ("TERM_PROGRAM", "iTerm.app"),
1503            ("TERM_PROGRAM_VERSION", "3.6.11"),
1504            ("WEZTERM_VERSION", "20250730"),
1505        ]);
1506        assert_eq!(terminal_user_agent_token(&environment), "iTerm.app/3.6.11");
1507
1508        let environment = test_environment([("ITERM_SESSION_ID", "w0t0p0")]);
1509        assert_eq!(terminal_user_agent_token(&environment), "iTerm.app");
1510
1511        let environment = test_environment([("TERM_PROGRAM", "invalid\r\nvalue")]);
1512        assert_eq!(terminal_user_agent_token(&environment), "unknown");
1513    }
1514
1515    #[test]
1516    fn reasoning_effort_layers_are_provider_neutral_and_cli_wins() {
1517        let environment = test_environment([
1518            ("TEA_REASONING_EFFORT", "max"),
1519            ("TEA_OPENAI_REASONING_EFFORT", "low"),
1520        ]);
1521        let bootstrap = CliBootstrap::new(environment);
1522        assert_eq!(
1523            bootstrap.environment_settings().thinking.as_deref(),
1524            Some("max")
1525        );
1526
1527        let args = CliArgs::try_parse_from(["tea", "--reasoning-effort", "xhigh"]).unwrap();
1528        let settings = merge_settings(
1529            CodingSettings::default(),
1530            Some(&SettingsLayer {
1531                thinking: Some("minimal".to_owned()),
1532                ..Default::default()
1533            }),
1534            None,
1535            Some(&bootstrap.environment_settings()),
1536            Some(&cli_settings(&args).unwrap()),
1537        )
1538        .unwrap();
1539        assert_eq!(settings.thinking, "xhigh");
1540
1541        let legacy = test_environment([("TEA_OPENAI_REASONING_EFFORT", "high")]);
1542        let legacy = CliBootstrap::new(legacy);
1543        assert_eq!(
1544            legacy.environment_settings().thinking.as_deref(),
1545            Some("high")
1546        );
1547    }
1548
1549    #[test]
1550    fn builtin_openai_bootstrap_preserves_the_adapter_reasoning_profile() {
1551        let root = std::env::temp_dir().join(format!(
1552            "tea-cli-openai-reasoning-bootstrap-{}",
1553            uuid::Uuid::now_v7().hyphenated()
1554        ));
1555        let config = root.join("config");
1556        let state = root.join("state");
1557        let data = root.join("data");
1558        fs::create_dir_all(&root).unwrap();
1559        let bootstrap = CliBootstrap::new(BootstrapEnvironment::new(
1560            &root,
1561            Some(root.clone()),
1562            [("TEA_OPENAI_API_KEY".to_owned(), "test-model-key".to_owned())]
1563                .into_iter()
1564                .collect(),
1565        ));
1566        let args = CliArgs::try_parse_from([
1567            "tea",
1568            "--no-session",
1569            "--trust",
1570            "ignore",
1571            "--cwd",
1572            root.to_str().unwrap(),
1573            "--config-dir",
1574            config.to_str().unwrap(),
1575            "--state-dir",
1576            state.to_str().unwrap(),
1577            "--data-dir",
1578            data.to_str().unwrap(),
1579        ])
1580        .unwrap();
1581
1582        let (service, _) = bootstrap.build(&args).unwrap();
1583        let model = model_ref(&service.settings().provider, &service.settings().model);
1584        let profile = service
1585            .model_spec(&model)
1586            .unwrap()
1587            .reasoning_profile()
1588            .unwrap();
1589        assert_eq!(profile.default_effort(), ReasoningEffort::Medium);
1590        assert_eq!(
1591            profile.supported_efforts(),
1592            &[
1593                ReasoningEffort::Off,
1594                ReasoningEffort::Minimal,
1595                ReasoningEffort::Low,
1596                ReasoningEffort::Medium,
1597                ReasoningEffort::High,
1598            ]
1599        );
1600        fs::remove_dir_all(root).unwrap();
1601    }
1602
1603    #[test]
1604    fn client_web_search_provider_requires_enablement_and_an_injected_key() {
1605        let mut settings = tea_coding::config::WebSearchSettings::default();
1606        settings.client.api_key_environment = "SEARCH_TEST_KEY".to_owned();
1607        let environment = test_environment([("SEARCH_TEST_KEY", "test-search-key")]);
1608        let http = ProviderHttpConfig::new();
1609
1610        assert!(
1611            client_web_search_provider(&settings, &environment, &http)
1612                .unwrap()
1613                .is_none()
1614        );
1615
1616        settings.client.enabled = true;
1617        assert!(
1618            client_web_search_provider(&settings, &environment, &http)
1619                .unwrap()
1620                .is_some()
1621        );
1622        assert!(
1623            client_web_search_provider(&settings, &test_environment([]), &http)
1624                .unwrap()
1625                .is_none()
1626        );
1627        assert!(
1628            client_web_search_provider(
1629                &settings,
1630                &test_environment([("SEARCH_TEST_KEY", "   ")]),
1631                &http,
1632            )
1633            .unwrap()
1634            .is_none()
1635        );
1636    }
1637
1638    #[test]
1639    fn bootstrap_injects_force_client_search_without_activating_it() {
1640        let root = std::env::temp_dir().join(format!(
1641            "tea-cli-client-search-bootstrap-{}",
1642            uuid::Uuid::now_v7().hyphenated()
1643        ));
1644        let config = root.join("config");
1645        let state = root.join("state");
1646        let data = root.join("data");
1647        fs::create_dir_all(&config).unwrap();
1648        fs::write(
1649            config.join("settings.json"),
1650            r#"{
1651                "schemaVersion": 1,
1652                "webSearch": {
1653                    "routePreference": "force_client",
1654                    "client": {
1655                        "enabled": true,
1656                        "apiKeyEnvironment": "SEARCH_BOOTSTRAP_KEY"
1657                    }
1658                }
1659            }"#,
1660        )
1661        .unwrap();
1662        let args = CliArgs::try_parse_from([
1663            "tea",
1664            "--no-session",
1665            "--trust",
1666            "ignore",
1667            "--cwd",
1668            root.to_str().unwrap(),
1669            "--config-dir",
1670            config.to_str().unwrap(),
1671            "--state-dir",
1672            state.to_str().unwrap(),
1673            "--data-dir",
1674            data.to_str().unwrap(),
1675        ])
1676        .unwrap();
1677
1678        let missing = CliBootstrap::new(BootstrapEnvironment::new(
1679            &root,
1680            Some(root.clone()),
1681            [("TEA_OPENAI_API_KEY".to_owned(), "test-model-key".to_owned())]
1682                .into_iter()
1683                .collect(),
1684        ));
1685        let error = missing.build(&args).unwrap_err();
1686        assert_eq!(error.category(), ExitCategory::TrustOrConfig);
1687        assert_eq!(
1688            error.message(),
1689            "client web search requires an injected search provider"
1690        );
1691
1692        let configured = CliBootstrap::new(BootstrapEnvironment::new(
1693            &root,
1694            Some(root.clone()),
1695            [
1696                ("TEA_OPENAI_API_KEY".to_owned(), "test-model-key".to_owned()),
1697                (
1698                    "SEARCH_BOOTSTRAP_KEY".to_owned(),
1699                    "test-search-key".to_owned(),
1700                ),
1701            ]
1702            .into_iter()
1703            .collect(),
1704        ));
1705        let (service, _) = configured.build(&args).unwrap();
1706        assert_eq!(
1707            service.settings().active_tools,
1708            ["read", "write", "edit", "bash"]
1709        );
1710        fs::remove_dir_all(root).unwrap();
1711    }
1712
1713    #[test]
1714    fn app_paths_use_dot_tea_and_preserve_config_override_precedence() {
1715        let home = std::env::temp_dir().join("tea-cli-app-paths-home");
1716        let env_config = home.join("env-config");
1717        let cli_config = home.join("cli-config");
1718        let args = CliArgs::try_parse_from(["tea"]).unwrap();
1719        let bootstrap = CliBootstrap::new(BootstrapEnvironment::new(
1720            &home,
1721            Some(home.clone()),
1722            BTreeMap::new(),
1723        ));
1724
1725        let paths = bootstrap.app_paths(&args).unwrap();
1726        assert_eq!(paths.config_dir(), home.join(".tea"));
1727        assert_eq!(paths.state_dir(), home.join(".local/state/tea"));
1728        assert_eq!(paths.data_dir(), home.join(".local/share/tea"));
1729
1730        let bootstrap = CliBootstrap::new(BootstrapEnvironment::new(
1731            &home,
1732            Some(home.clone()),
1733            [(
1734                "TEA_CONFIG_DIR".to_owned(),
1735                env_config.display().to_string(),
1736            )]
1737            .into_iter()
1738            .collect(),
1739        ));
1740        assert_eq!(bootstrap.app_paths(&args).unwrap().config_dir(), env_config);
1741
1742        let args =
1743            CliArgs::try_parse_from(["tea", "--config-dir", cli_config.to_str().unwrap()]).unwrap();
1744        assert_eq!(bootstrap.app_paths(&args).unwrap().config_dir(), cli_config);
1745    }
1746
1747    #[test]
1748    fn home_directory_resolution_supports_windows_environment() {
1749        let profile = std::ffi::OsString::from(r"C:\Users\tea");
1750        assert_eq!(
1751            home_dir_from(|key| (key == "USERPROFILE").then(|| profile.clone())),
1752            Some(PathBuf::from(&profile))
1753        );
1754
1755        let home = std::ffi::OsString::from("/explicit/home");
1756        assert_eq!(
1757            home_dir_from(|key| match key {
1758                "HOME" => Some(home.clone()),
1759                "USERPROFILE" => Some(profile.clone()),
1760                _ => None,
1761            }),
1762            Some(PathBuf::from(home))
1763        );
1764
1765        let drive = std::ffi::OsString::from("profile-root");
1766        let path = std::ffi::OsString::from("tea-user");
1767        assert_eq!(
1768            home_dir_from(|key| match key {
1769                "HOMEDRIVE" => Some(drive.clone()),
1770                "HOMEPATH" => Some(path.clone()),
1771                _ => None,
1772            }),
1773            Some(PathBuf::from(drive).join(path))
1774        );
1775    }
1776
1777    #[test]
1778    fn tui_prompts_before_project_files_are_loaded_and_acceptance_persists() {
1779        let root = std::env::temp_dir().join(format!(
1780            "tea-cli-workspace-trust-bootstrap-{}",
1781            uuid::Uuid::now_v7().hyphenated()
1782        ));
1783        let config = root.join("config");
1784        let state = root.join("state");
1785        let data = root.join("data");
1786        fs::create_dir_all(root.join(".tea")).unwrap();
1787        fs::write(root.join(".tea/settings.json"), "not valid json").unwrap();
1788        let bootstrap = CliBootstrap::new(BootstrapEnvironment::new(
1789            &root,
1790            Some(root.clone()),
1791            BTreeMap::new(),
1792        ));
1793        let args = CliArgs::try_parse_from([
1794            "tea",
1795            "--no-session",
1796            "--cwd",
1797            root.to_str().unwrap(),
1798            "--config-dir",
1799            config.to_str().unwrap(),
1800            "--state-dir",
1801            state.to_str().unwrap(),
1802            "--data-dir",
1803            data.to_str().unwrap(),
1804        ])
1805        .unwrap();
1806
1807        let prompt = bootstrap.workspace_trust_prompt(&args).unwrap().unwrap();
1808        assert_eq!(prompt.workspace(), fs::canonicalize(&root).unwrap());
1809        let error = bootstrap.prepare(&args, ClientSurface::Tui).err().unwrap();
1810        assert_eq!(error.category(), ExitCategory::TrustOrConfig);
1811        assert_eq!(error.message(), "workspace trust confirmation is required");
1812
1813        CliBootstrap::accept_workspace_trust(&prompt).unwrap();
1814        assert!(bootstrap.workspace_trust_prompt(&args).unwrap().is_none());
1815        assert_eq!(
1816            ProjectTrustStore::new(state.join("project-trust.json"))
1817                .get(&root)
1818                .unwrap(),
1819            Some(PersistedTrustDecision::Trusted)
1820        );
1821        fs::remove_dir_all(root).unwrap();
1822    }
1823
1824    #[test]
1825    fn bootstrap_builds_anthropic_provider_from_injected_configuration() {
1826        let root = std::env::temp_dir().join(format!(
1827            "tea-cli-anthropic-bootstrap-{}",
1828            uuid::Uuid::now_v7().hyphenated()
1829        ));
1830        fs::create_dir_all(&root).unwrap();
1831        let config = root.join("config");
1832        let state = root.join("state");
1833        let data = root.join("data");
1834        let model = "claude-sonnet-4-20250514";
1835        let bootstrap = CliBootstrap::new(BootstrapEnvironment::new(
1836            &root,
1837            Some(root.clone()),
1838            [
1839                ("TEA_PROVIDER".to_owned(), "anthropic".to_owned()),
1840                (
1841                    "TEA_ANTHROPIC_API_KEY".to_owned(),
1842                    "test-anthropic-key".to_owned(),
1843                ),
1844                ("TEA_ANTHROPIC_MODEL".to_owned(), model.to_owned()),
1845            ]
1846            .into_iter()
1847            .collect(),
1848        ));
1849        let args = CliArgs::try_parse_from([
1850            "tea",
1851            "--no-session",
1852            "--provider",
1853            "anthropic",
1854            "--model",
1855            model,
1856            "--trust",
1857            "ignore",
1858            "--cwd",
1859            root.to_str().unwrap(),
1860            "--config-dir",
1861            config.to_str().unwrap(),
1862            "--state-dir",
1863            state.to_str().unwrap(),
1864            "--data-dir",
1865            data.to_str().unwrap(),
1866        ])
1867        .unwrap();
1868
1869        let (service, _) = bootstrap.build(&args).unwrap();
1870        assert_eq!(service.settings().provider, "anthropic");
1871        assert_eq!(service.models(), &[model_ref("anthropic", model)]);
1872        fs::remove_dir_all(root).unwrap();
1873    }
1874
1875    #[test]
1876    fn bootstrap_builds_custom_provider_with_cli_credential_precedence() {
1877        let root = std::env::temp_dir().join(format!(
1878            "tea-cli-custom-provider-bootstrap-{}",
1879            uuid::Uuid::now_v7().hyphenated()
1880        ));
1881        let config = root.join("config");
1882        let state = root.join("state");
1883        let data = root.join("data");
1884        fs::create_dir_all(&config).unwrap();
1885        fs::write(
1886            config.join("providers.json"),
1887            r#"{
1888                "providers": {
1889                    "ollama": {
1890                        "name": "Ollama",
1891                        "base_url": "http://localhost:11434/v1",
1892                        "api_key": "$MISSING_KEY",
1893                        "api_mode": "responses",
1894                        "reasoning_effort": "max",
1895                        "vision": true,
1896                        "models": [{
1897                            "id": "llama3.1:8b",
1898                            "display_name": "Llama 3.1 8B",
1899                            "context_window_tokens": 64000,
1900                            "max_output_tokens": 8000,
1901                            "capabilities": {
1902                                "hosted_tools": ["web_search"]
1903                            }
1904                        }]
1905                    }
1906                }
1907            }"#,
1908        )
1909        .unwrap();
1910        let bootstrap = CliBootstrap::new(BootstrapEnvironment::new(
1911            &root,
1912            Some(root.clone()),
1913            BTreeMap::new(),
1914        ));
1915        let args = CliArgs::try_parse_from([
1916            "tea",
1917            "--no-session",
1918            "--provider",
1919            "ollama",
1920            "--model",
1921            "llama3.1:8b",
1922            "--api-key",
1923            "cli-secret-key",
1924            "--trust",
1925            "ignore",
1926            "--cwd",
1927            root.to_str().unwrap(),
1928            "--config-dir",
1929            config.to_str().unwrap(),
1930            "--state-dir",
1931            state.to_str().unwrap(),
1932            "--data-dir",
1933            data.to_str().unwrap(),
1934        ])
1935        .unwrap();
1936        assert!(!format!("{args:?}").contains("cli-secret-key"));
1937
1938        let (service, _) = bootstrap.build(&args).unwrap();
1939        assert_eq!(service.settings().provider, "ollama");
1940        assert_eq!(service.models(), &[model_ref("ollama", "llama3.1:8b")]);
1941        let model = model_ref("ollama", "llama3.1:8b");
1942        let capabilities = service.model_capabilities(&model).unwrap();
1943        assert!(capabilities.accepts_images());
1944        assert!(capabilities.supports_reasoning());
1945        assert!(capabilities.supports_hosted_tool(tea_model::HostedToolKind::WebSearch));
1946        assert_eq!(
1947            service
1948                .model_spec(&model)
1949                .unwrap()
1950                .reasoning_profile()
1951                .unwrap()
1952                .default_effort(),
1953            ReasoningEffort::High
1954        );
1955        fs::remove_dir_all(root).unwrap();
1956    }
1957
1958    #[test]
1959    fn bootstrap_registers_all_available_custom_providers_with_same_model_id() {
1960        let root = std::env::temp_dir().join(format!(
1961            "tea-cli-multi-provider-bootstrap-{}",
1962            uuid::Uuid::now_v7().hyphenated()
1963        ));
1964        let config = root.join("config");
1965        let state = root.join("state");
1966        let data = root.join("data");
1967        fs::create_dir_all(&config).unwrap();
1968        fs::write(
1969            config.join("providers.json"),
1970            r#"{
1971                "providers": {
1972                    "one": {
1973                        "api_key": "key-one",
1974                        "models": [{"id": "shared"}]
1975                    },
1976                    "two": {
1977                        "api_key": "key-two",
1978                        "models": [{"id": "shared"}]
1979                    }
1980                }
1981            }"#,
1982        )
1983        .unwrap();
1984        let bootstrap = CliBootstrap::new(BootstrapEnvironment::new(
1985            &root,
1986            Some(root.clone()),
1987            BTreeMap::new(),
1988        ));
1989        let args = CliArgs::try_parse_from([
1990            "tea",
1991            "--no-session",
1992            "--provider",
1993            "one",
1994            "--model",
1995            "shared",
1996            "--trust",
1997            "ignore",
1998            "--cwd",
1999            root.to_str().unwrap(),
2000            "--config-dir",
2001            config.to_str().unwrap(),
2002            "--state-dir",
2003            state.to_str().unwrap(),
2004            "--data-dir",
2005            data.to_str().unwrap(),
2006        ])
2007        .unwrap();
2008
2009        let (service, _) = bootstrap.build(&args).unwrap();
2010        assert_eq!(
2011            service.models(),
2012            &[model_ref("one", "shared"), model_ref("two", "shared")]
2013        );
2014        assert!(service.model_spec(&model_ref("one", "shared")).is_some());
2015        assert!(service.model_spec(&model_ref("two", "shared")).is_some());
2016        fs::remove_dir_all(root).unwrap();
2017    }
2018
2019    #[test]
2020    fn bootstrap_rejects_active_hosted_tool_missing_from_custom_model_capabilities() {
2021        let root = std::env::temp_dir().join(format!(
2022            "tea-cli-custom-hosted-capability-bootstrap-{}",
2023            uuid::Uuid::now_v7().hyphenated()
2024        ));
2025        let config = root.join("config");
2026        let state = root.join("state");
2027        let data = root.join("data");
2028        fs::create_dir_all(&config).unwrap();
2029        fs::write(
2030            config.join("settings.json"),
2031            r#"{
2032                "schemaVersion": 1,
2033                "provider": "gateway",
2034                "model": "gpt-test",
2035                "activeTools": ["web_search"]
2036            }"#,
2037        )
2038        .unwrap();
2039        fs::write(
2040            config.join("providers.json"),
2041            r#"{
2042                "providers": {
2043                    "gateway": {
2044                        "base_url": "https://gateway.example/v1",
2045                        "api_key": "test-key",
2046                        "api_mode": "responses",
2047                        "models": [{"id": "gpt-test"}]
2048                    }
2049                }
2050            }"#,
2051        )
2052        .unwrap();
2053        let bootstrap = CliBootstrap::new(BootstrapEnvironment::new(
2054            &root,
2055            Some(root.clone()),
2056            BTreeMap::new(),
2057        ));
2058        let args = CliArgs::try_parse_from([
2059            "tea",
2060            "--no-session",
2061            "--trust",
2062            "ignore",
2063            "--cwd",
2064            root.to_str().unwrap(),
2065            "--config-dir",
2066            config.to_str().unwrap(),
2067            "--state-dir",
2068            state.to_str().unwrap(),
2069            "--data-dir",
2070            data.to_str().unwrap(),
2071        ])
2072        .unwrap();
2073
2074        let error = bootstrap.build(&args).unwrap_err();
2075        assert_eq!(error.category(), ExitCategory::TrustOrConfig);
2076        assert_eq!(
2077            error.message(),
2078            "active tool web_search has no execution route supported by selected model gpt-test; declare the model capability or configure a supported client route"
2079        );
2080        fs::remove_dir_all(root).unwrap();
2081    }
2082
2083    #[tokio::test(flavor = "current_thread")]
2084    async fn tui_defers_missing_custom_provider_credentials() {
2085        let root = std::env::temp_dir().join(format!(
2086            "tea-cli-unavailable-provider-bootstrap-{}",
2087            uuid::Uuid::now_v7().hyphenated()
2088        ));
2089        let config = root.join("config");
2090        let state = root.join("state");
2091        let data = root.join("data");
2092        fs::create_dir_all(&config).unwrap();
2093        fs::write(
2094            config.join("providers.json"),
2095            r#"{
2096                "providers": {
2097                    "local": {
2098                        "api_key": "$MISSING_TUI_PROVIDER_KEY",
2099                        "models": [{"id": "local-model"}]
2100                    }
2101                }
2102            }"#,
2103        )
2104        .unwrap();
2105        let bootstrap = CliBootstrap::new(BootstrapEnvironment::new(
2106            &root,
2107            Some(root.clone()),
2108            BTreeMap::new(),
2109        ));
2110        let args = CliArgs::try_parse_from([
2111            "tea",
2112            "--no-session",
2113            "--provider",
2114            "local",
2115            "--model",
2116            "local-model",
2117            "--trust",
2118            "ignore",
2119            "--cwd",
2120            root.to_str().unwrap(),
2121            "--config-dir",
2122            config.to_str().unwrap(),
2123            "--state-dir",
2124            state.to_str().unwrap(),
2125            "--data-dir",
2126            data.to_str().unwrap(),
2127        ])
2128        .unwrap();
2129
2130        let headless_error = bootstrap.build(&args).unwrap_err();
2131        assert_eq!(headless_error.category(), ExitCategory::Provider);
2132        let (service, _, notices) = bootstrap.build_tui_async(&args).await.unwrap();
2133        assert_eq!(service.models(), &[model_ref("local", "local-model")]);
2134        assert_eq!(
2135            notices,
2136            ["provider unavailable: configured provider API key could not be resolved"]
2137        );
2138        service.shutdown().await;
2139        fs::remove_dir_all(root).unwrap();
2140    }
2141
2142    #[tokio::test(flavor = "current_thread")]
2143    async fn tui_defers_custom_provider_model_mismatch() {
2144        let root = std::env::temp_dir().join(format!(
2145            "tea-cli-unconfigured-model-bootstrap-{}",
2146            uuid::Uuid::now_v7().hyphenated()
2147        ));
2148        let config = root.join("config");
2149        let state = root.join("state");
2150        let data = root.join("data");
2151        fs::create_dir_all(&config).unwrap();
2152        fs::write(
2153            config.join("providers.json"),
2154            r#"{
2155                "providers": {
2156                    "local": {
2157                        "api_key": "configured-secret",
2158                        "models": [{"id": "available-model"}]
2159                    }
2160                }
2161            }"#,
2162        )
2163        .unwrap();
2164        let bootstrap = CliBootstrap::new(BootstrapEnvironment::new(
2165            &root,
2166            Some(root.clone()),
2167            BTreeMap::new(),
2168        ));
2169        let args = CliArgs::try_parse_from([
2170            "tea",
2171            "--no-session",
2172            "--provider",
2173            "local",
2174            "--model",
2175            "missing-model",
2176            "--trust",
2177            "ignore",
2178            "--cwd",
2179            root.to_str().unwrap(),
2180            "--config-dir",
2181            config.to_str().unwrap(),
2182            "--state-dir",
2183            state.to_str().unwrap(),
2184            "--data-dir",
2185            data.to_str().unwrap(),
2186        ])
2187        .unwrap();
2188
2189        let headless_error = bootstrap.build(&args).unwrap_err();
2190        assert_eq!(headless_error.category(), ExitCategory::TrustOrConfig);
2191        assert_eq!(
2192            headless_error.message(),
2193            "model is not configured for provider"
2194        );
2195        let (service, _, notices) = bootstrap.build_tui_async(&args).await.unwrap();
2196        assert_eq!(service.models(), &[model_ref("local", "missing-model")]);
2197        assert_eq!(
2198            notices,
2199            ["provider unavailable: model is not configured for provider"]
2200        );
2201        assert!(
2202            notices
2203                .iter()
2204                .all(|notice| !notice.contains("configured-secret"))
2205        );
2206        service.shutdown().await;
2207        fs::remove_dir_all(root).unwrap();
2208    }
2209
2210    #[test]
2211    fn project_provider_configuration_requires_trust() {
2212        let root = std::env::temp_dir().join(format!(
2213            "tea-cli-project-provider-bootstrap-{}",
2214            uuid::Uuid::now_v7().hyphenated()
2215        ));
2216        let config = root.join("config");
2217        let state = root.join("state");
2218        let data = root.join("data");
2219        fs::create_dir_all(root.join(".tea")).unwrap();
2220        fs::write(
2221            root.join(".tea/providers.json"),
2222            r#"{"providers":{"local":{"api_key":"local","models":[{"id":"local-model"}]}}}"#,
2223        )
2224        .unwrap();
2225        let bootstrap = CliBootstrap::new(BootstrapEnvironment::new(
2226            &root,
2227            Some(root.clone()),
2228            BTreeMap::new(),
2229        ));
2230        let common = [
2231            "tea",
2232            "--no-session",
2233            "--provider",
2234            "local",
2235            "--model",
2236            "local-model",
2237            "--cwd",
2238            root.to_str().unwrap(),
2239            "--config-dir",
2240            config.to_str().unwrap(),
2241            "--state-dir",
2242            state.to_str().unwrap(),
2243            "--data-dir",
2244            data.to_str().unwrap(),
2245        ];
2246        let ignored =
2247            CliArgs::try_parse_from(common.into_iter().chain(["--trust", "ignore"])).unwrap();
2248        assert!(bootstrap.build(&ignored).is_err());
2249        let trusted =
2250            CliArgs::try_parse_from(common.into_iter().chain(["--trust", "once"])).unwrap();
2251        let (service, _) = bootstrap.build(&trusted).unwrap();
2252        assert_eq!(service.settings().provider, "local");
2253        fs::remove_dir_all(root).unwrap();
2254    }
2255}