返回 CodeWhale
runtime_options.rs
根目录 / crates / config / src / runtime_options.rs
1 use crate::provider_kind::ProviderKind;
2 use crate::telemetry::TelemetrySource;
3 use anyhow::Result;
4 use std::collections::BTreeMap;
5
6 pub(crate) fn base_url_uses_local_host(base_url: &str) -> bool {
7 let Some(host) = base_url_host(base_url) else {
8 return false;
9 };
10 let host = host.trim_matches(['[', ']']).to_ascii_lowercase();
11 if matches!(host.as_str(), "localhost" | "0.0.0.0") {
12 return true;
13 }
14 host.parse::<std::net::IpAddr>()
15 .is_ok_and(|addr| addr.is_loopback() || addr.is_unspecified())
16 }
17
18 pub fn base_url_host(base_url: &str) -> Option<&str> {
19 let without_scheme = base_url
20 .split_once("://")
21 .map_or(base_url, |(_, rest)| rest);
22 let authority = without_scheme.split('/').next()?.rsplit('@').next()?;
23 if let Some(rest) = authority.strip_prefix('[') {
24 return rest.split_once(']').map(|(host, _)| host);
25 }
26 authority.split(':').next().filter(|host| !host.is_empty())
27 }
28
29 #[derive(Debug, Clone, Default)]
30 pub struct CliRuntimeOverrides {
31 pub provider: Option<ProviderKind>,
32 pub model: Option<String>,
33 pub api_key: Option<String>,
34 pub base_url: Option<String>,
35 pub auth_mode: Option<String>,
36 pub log_level: Option<String>,
37 pub telemetry: Option<bool>,
38 pub approval_policy: Option<String>,
39 pub sandbox_mode: Option<String>,
40 pub yolo: Option<bool>,
41 pub verbosity: Option<String>,
42 }
43
44 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
45 pub enum RuntimeApiKeySource {
46 Cli,
47 ConfigFile,
48 Keyring,
49 Env,
50 }
51
52 impl RuntimeApiKeySource {
53 #[must_use]
54 pub fn as_env_value(self) -> &'static str {
55 match self {
56 Self::Cli => "cli",
57 Self::ConfigFile => "config",
58 Self::Keyring => "keyring",
59 Self::Env => "env",
60 }
61 }
62 }
63
64 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
65 pub enum ProviderSource {
66 Cli,
67 Env(&'static str),
68 Config,
69 }
70
71 /// Where the resolved runtime model id came from.
72 ///
73 /// This mirrors the precedence chain in
74 /// `ConfigToml::resolve_runtime_options_with_secrets` so diagnostics can say
75 /// *why* a model was chosen instead of presenting a built-in default as if the
76 /// user had asked for it. [`Self::ProviderDefault`] is the only variant that
77 /// means "nothing was configured".
78 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
79 pub enum ModelSource {
80 /// `--model` on the command line.
81 Cli,
82 /// A `CODEWHALE_*` environment variable.
83 Env,
84 /// `[providers.<name>].model`.
85 ProviderConfig,
86 /// The root `default_text_model` key, which is DeepSeek-scoped.
87 RootDefaultTextModel,
88 /// The provider-neutral root `model` key.
89 RootModel,
90 /// Nothing was configured; this is the built-in default for the provider.
91 ProviderDefault,
92 }
93
94 impl ModelSource {
95 /// Whether the id was chosen by the user rather than substituted by us.
96 #[must_use]
97 pub fn is_explicit(self) -> bool {
98 !matches!(self, Self::ProviderDefault)
99 }
100
101 #[must_use]
102 pub fn as_str(self) -> &'static str {
103 match self {
104 Self::Cli => "--model",
105 Self::Env => "environment",
106 Self::ProviderConfig => "config [providers.*].model",
107 Self::RootDefaultTextModel => "config default_text_model",
108 Self::RootModel => "config model",
109 Self::ProviderDefault => "provider default",
110 }
111 }
112 }
113
114 #[derive(Debug, Clone)]
115 pub struct ResolvedRuntimeOptions {
116 pub provider: ProviderKind,
117 pub provider_source: ProviderSource,
118 pub model: String,
119 pub model_source: ModelSource,
120 pub model_error: Option<String>,
121 pub api_key: Option<String>,
122 pub api_key_source: Option<RuntimeApiKeySource>,
123 pub base_url: String,
124 pub auth_mode: Option<String>,
125 pub insecure_skip_tls_verify: bool,
126 pub log_level: Option<String>,
127 pub telemetry: bool,
128 /// Where the resolved telemetry consent came from (cli | env | config |
129 /// default), so doctor and config displays can state the truth about a
130 /// machine that never opted in (#5441).
131 pub telemetry_source: TelemetrySource,
132 /// A human wrote `telemetry = false` into the config file.
133 ///
134 /// This is the *persistent* opt-out, and it is deliberately narrower than
135 /// "telemetry resolved to false". A run-scoped kill switch also resolves
136 /// false; treating that as a revocation would destroy the identity and
137 /// buffered events of a user who merely set `CODEWHALE_TELEMETRY=0` for one
138 /// command. Run-scoped kill switches
139 /// (`--telemetry false`, the environment variable) stop the run and leave
140 /// every byte on disk alone; only this flag authorizes the wipe.
141 pub telemetry_explicit_off: bool,
142 /// Where a telemetry batch would be sent, if telemetry were on.
143 ///
144 /// Already resolved: `DEFAULT_TELEMETRY_ENDPOINT` when nobody configured
145 /// one, the configured value when somebody did, and `None` when somebody
146 /// configured an empty one — which means the dry-run sink, not "unset".
147 /// Which schemes are actually contactable is decided where a batch would be
148 /// sent, not here — a user must be able to stage a value.
149 pub telemetry_endpoint: Option<String>,
150 pub approval_policy: Option<String>,
151 pub sandbox_mode: Option<String>,
152 pub yolo: Option<bool>,
153 pub verbosity: Option<String>,
154 pub http_headers: BTreeMap<String, String>,
155 /// Executable route minted by [`crate::route::RouteResolver`].
156 pub route: Result<crate::route::ReadyRouteCandidate, crate::route::RouteError>,
157 }
158
159 impl ResolvedRuntimeOptions {
160 pub fn ensure_valid_model(&self) -> Result<()> {
161 if let Some(error) = self.model_error.as_deref() {
162 anyhow::bail!("{error}");
163 }
164 Ok(())
165 }
166 }
167
167 lines RUST