Skip to main content

agent_provider_config/
lib.rs

1//! Provider-neutral configuration for Tilo agents.
2//!
3//! This crate stores *descriptions* of model providers, never a
4//! bearer token. A profile can point at a system-vault item via
5//! [`SecretReference`], or name a sign-in held by account credentials via
6//! [`SignInCredential`], while the process that owns the secret service is
7//! responsible for resolving either at call time. Keeping this
8//! boundary here makes the same profile safe to render in Settings, sync as
9//! non-secret device intent, or hand to a sandboxed agent.
10
11use std::collections::{BTreeMap, BTreeSet};
12
13use serde::{Deserialize, Serialize};
14use serde_json::{Map, Value};
15
16/// What a model can do: read from a provider's list, or known by family.
17pub mod capabilities;
18/// Whole model turns in either provider dialect, for clients without the gateway.
19pub mod local;
20pub mod management;
21/// Known providers a new profile starts from.
22pub mod presets;
23pub mod protocol;
24/// Single-shot model calls in either provider dialect.
25pub mod transform;
26pub mod wire;
27
28/// The section holding the providers of this device and its network, and
29/// the default: this device's.
30pub const SETTINGS_SECTION: &str = "agent_providers";
31/// The section holding the hosted providers: they name no device, so it is
32/// the person's.
33pub const HOSTED_SECTION: &str = "agent_providers_person";
34/// The key holding the providers of this device and its network, and the
35/// default, in [`SETTINGS_SECTION`].
36const CONFIG_KEY: &str = "config";
37/// The key holding the hosted providers in [`HOSTED_SECTION`].
38const HOSTED_KEY: &str = "hosted";
39
40/// The request dialect spoken by a provider endpoint.
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(remote = "Self", rename_all = "snake_case")]
43pub enum ProviderProtocol {
44    /// `/v1/chat/completions` and related OpenAI-compatible endpoints.
45    #[default]
46    OpenAiCompatible,
47    /// Anthropic's `/v1/messages` API.
48    Anthropic,
49}
50
51settings_store::read_through_json_value!(ProviderProtocol);
52
53impl ProviderProtocol {
54    pub const ALL: &'static [Self] = &[Self::OpenAiCompatible, Self::Anthropic];
55
56    pub const fn label(self) -> &'static str {
57        match self {
58            Self::OpenAiCompatible => "OpenAI-compatible",
59            Self::Anthropic => "Anthropic",
60        }
61    }
62}
63
64/// Where an endpoint runs. This is an explicit trust cue in the UI: a local
65/// vLLM server must remain distinct from a hosted API even though it shares the
66/// `OpenAI` wire protocol.
67#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(remote = "Self", rename_all = "snake_case")]
69pub enum EndpointLocation {
70    /// A provider-operated internet endpoint.
71    #[default]
72    Hosted,
73    /// A loopback endpoint on this Tilo device, e.g. vLLM or Ollama.
74    ThisDevice,
75    /// An endpoint on a LAN, VPN, or a user-managed server.
76    PrivateNetwork,
77}
78
79settings_store::read_through_json_value!(EndpointLocation);
80
81impl EndpointLocation {
82    pub const ALL: &'static [Self] = &[Self::Hosted, Self::ThisDevice, Self::PrivateNetwork];
83
84    pub const fn label(self) -> &'static str {
85        match self {
86            Self::Hosted => "Hosted provider",
87            Self::ThisDevice => "This device (local)",
88            Self::PrivateNetwork => "Private network",
89        }
90    }
91
92    pub const fn needs_tls(self) -> bool {
93        matches!(self, Self::Hosted)
94    }
95
96    /// Where `endpoint` runs, as its address says: on this device (a
97    /// loopback address or `localhost`), on a private network (a private or
98    /// link-local address, a `.local` or `.lan` name), else hosted. `None`
99    /// for what is not an address. A typed endpoint takes the location its
100    /// address has, so a server on the person's network is not held to a
101    /// hosted provider's TLS, and an internet host never escapes it.
102    pub fn of_endpoint(endpoint: &str) -> Option<Self> {
103        let url = url::Url::parse(endpoint.trim()).ok()?;
104        Some(match url.host()? {
105            url::Host::Domain(name) => {
106                let name = name.trim_end_matches('.').to_ascii_lowercase();
107                let last = name.rsplit('.').next().unwrap_or_default();
108                if last == "localhost" {
109                    Self::ThisDevice
110                } else if !name.contains('.') || matches!(last, "local" | "lan") {
111                    Self::PrivateNetwork
112                } else {
113                    Self::Hosted
114                }
115            }
116            url::Host::Ipv4(address) if address.is_loopback() => Self::ThisDevice,
117            url::Host::Ipv4(address) if address.is_private() || address.is_link_local() => {
118                Self::PrivateNetwork
119            }
120            url::Host::Ipv6(address) if address.is_loopback() => Self::ThisDevice,
121            url::Host::Ipv6(address)
122                if address.is_unique_local() || address.is_unicast_link_local() =>
123            {
124                Self::PrivateNetwork
125            }
126            url::Host::Ipv4(_) | url::Host::Ipv6(_) => Self::Hosted,
127        })
128    }
129}
130
131/// A stable pointer to a secret held outside this configuration document.
132///
133/// `locator` is an opaque non-secret item name such as
134/// `agent-provider/01J.../api-key`. It is not an environment
135/// variable name: the desktop broker can apply per-agent access policy before
136/// handing the secret to an outbound request.
137#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
138#[serde(remote = "Self")]
139pub struct SecretReference {
140    /// The broker/vault namespace, usually `tilo.secret-service`.
141    pub vault: String,
142    /// Opaque item locator within `vault`; never the secret value.
143    pub locator: String,
144}
145
146settings_store::read_through_json_value!(SecretReference);
147
148/// The namespace of a [`SecretReference`] that names an entry of the workspace's vault.
149pub const WORKSPACE_VAULT: &str = "tilo.vault";
150
151impl SecretReference {
152    pub fn provider_api_key(profile_id: &str) -> Self {
153        Self {
154            vault: "tilo.secret-service".to_string(),
155            locator: format!("agent-provider/{profile_id}/api-key"),
156        }
157    }
158
159    /// The entry of the workspace's vault a provider's key is, by the entry's reference
160    /// (`vault.item:<entry id>`): what a host that keeps a workspace's providers names, so the
161    /// key lives in the workspace's one vault and is read from it at each call.
162    pub fn workspace_vault(reference: &str) -> Self {
163        Self {
164            vault: WORKSPACE_VAULT.to_owned(),
165            locator: reference.to_owned(),
166        }
167    }
168
169    /// The reference of the workspace vault's entry this names, where it names one
170    /// ([`Self::workspace_vault`]).
171    #[must_use]
172    pub fn workspace_vault_item(&self) -> Option<&str> {
173        (self.vault == WORKSPACE_VAULT && self.is_valid()).then_some(self.locator.as_str())
174    }
175
176    pub fn is_valid(&self) -> bool {
177        !self.vault.trim().is_empty()
178            && !self.locator.trim().is_empty()
179            && !self.locator.contains('\n')
180            && !self.locator.contains('\r')
181    }
182}
183
184/// The issuer of a [`SignInCredential`] that signs in with Google.
185pub const GOOGLE_SIGN_IN: &str = "google";
186
187/// Who a [`SignInCredential`] signs the person in with. Each decides how the
188/// gateway turns the sealed grant into a request credential.
189#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
190pub enum SignInIssuer {
191    /// Google: Vertex AI, or the Gemini API, billed to a Cloud project.
192    Google,
193    /// The person's `OpenAI` account, for their `ChatGPT` subscription. Not an
194    /// `OpenAI` API key: requests go to the `ChatGPT` backend
195    /// ([`presets::CHATGPT_ENDPOINT`]) in the `OpenAI` Responses format.
196    ChatGpt,
197    /// GitHub, for a Copilot subscription: the gateway trades the GitHub
198    /// grant for a short-lived Copilot token.
199    GitHubCopilot,
200    /// Hugging Face, for inference billed to the person's account.
201    HuggingFace,
202}
203
204impl SignInIssuer {
205    pub const ALL: [Self; 4] = [
206        Self::Google,
207        Self::ChatGpt,
208        Self::GitHubCopilot,
209        Self::HuggingFace,
210    ];
211
212    /// The stored issuer name.
213    pub const fn id(self) -> &'static str {
214        match self {
215            Self::Google => GOOGLE_SIGN_IN,
216            Self::ChatGpt => "chatgpt",
217            Self::GitHubCopilot => "github-copilot",
218            Self::HuggingFace => "huggingface",
219        }
220    }
221
222    pub fn from_id(id: &str) -> Option<Self> {
223        Self::ALL.into_iter().find(|issuer| issuer.id() == id)
224    }
225
226    /// Who the person signs in with.
227    pub const fn label(self) -> &'static str {
228        match self {
229            Self::Google => "Google",
230            Self::ChatGpt => "ChatGPT",
231            Self::GitHubCopilot => "GitHub",
232            Self::HuggingFace => "Hugging Face",
233        }
234    }
235}
236
237/// A sign-in held by account credentials in place of an API key: the gateway
238/// mints a short-lived access token from it for each request and refreshes
239/// it when due. The grant itself lives in this device's vault under
240/// [`sign_in_grant_id`], derived from the profile id so a profile cannot
241/// name another account's grant (Gmail's, say).
242#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
243#[serde(remote = "Self")]
244pub struct SignInCredential {
245    /// Who signed the person in: a [`SignInIssuer::id`]. Kept as text so a
246    /// reader that does not know a newer issuer still reads the profile,
247    /// and shows it as unsupported rather than losing the configuration.
248    pub issuer: String,
249    /// The Google Cloud project billed for requests made with a person's own
250    /// credentials, sent as `x-goog-user-project`. Without it Google bills
251    /// the project of Tilo's `OAuth` client, which the person cannot use.
252    /// Google sign-ins only.
253    #[serde(default, skip_serializing_if = "Option::is_none")]
254    pub billing_project: Option<String>,
255    /// Where the grant is kept when it is not in this device's vault: an entry of the
256    /// workspace's vault, as a host that keeps a workspace's providers names it
257    /// ([`SecretReference::workspace_vault`]). Absent on a device, which keeps its own.
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub kept: Option<SecretReference>,
260}
261
262settings_store::read_through_json_value!(SignInCredential);
263
264impl SignInCredential {
265    /// A sign-in with `issuer` and no billing project.
266    pub fn new(issuer: SignInIssuer) -> Self {
267        Self {
268            issuer: issuer.id().to_string(),
269            billing_project: None,
270            kept: None,
271        }
272    }
273
274    pub fn google(billing_project: impl Into<String>) -> Self {
275        Self {
276            billing_project: Some(billing_project.into()),
277            ..Self::new(SignInIssuer::Google)
278        }
279    }
280
281    /// The issuer, `None` for one this build does not know.
282    pub fn issuer(&self) -> Option<SignInIssuer> {
283        SignInIssuer::from_id(&self.issuer)
284    }
285}
286
287/// The vault id of `profile_id`'s sign-in grant. Its own namespace, apart
288/// from the API keys (`agent-provider-…`), so neither can address the other.
289pub fn sign_in_grant_id(profile_id: &str) -> String {
290    format!("agent-model-grant-{profile_id}")
291}
292
293/// Vertex AI's default location; Google's newest models are served there
294/// first, some only there.
295pub const VERTEX_DEFAULT_LOCATION: &str = "global";
296/// The model a new Vertex AI provider offers.
297pub const VERTEX_DEFAULT_MODEL: &str = "gemini-4-argon";
298
299/// Whether `project` is a Google Cloud project id: lowercase letters,
300/// digits and hyphens, or a domain-scoped id (`example.com:project`).
301pub fn is_cloud_project_id(project: &str) -> bool {
302    !project.is_empty()
303        && project.len() <= 100
304        && project.bytes().all(|byte| {
305            byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"-.:".contains(&byte)
306        })
307}
308
309/// Whether `location` is a Vertex AI location name (`global`,
310/// `us-central1`, `europe-west4`).
311pub fn is_vertex_location(location: &str) -> bool {
312    !location.is_empty()
313        && location.len() <= 40
314        && location
315            .bytes()
316            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
317        && !location.starts_with('-')
318}
319
320/// Vertex AI's OpenAI-compatible endpoint for `project` in `location`. The
321/// global location is served from the global host, every other one from
322/// its regional host.
323pub fn vertex_endpoint(project: &str, location: &str) -> String {
324    let host = if location == VERTEX_DEFAULT_LOCATION {
325        "aiplatform.googleapis.com".to_string()
326    } else {
327        format!("{location}-aiplatform.googleapis.com")
328    };
329    format!("https://{host}/v1/projects/{project}/locations/{location}/endpoints/openapi")
330}
331
332/// The project and location of a [`vertex_endpoint`], or `None` for any
333/// other endpoint.
334pub fn vertex_target(endpoint: &str) -> Option<(String, String)> {
335    let rest = endpoint.trim().strip_prefix("https://")?;
336    let (host, path) = rest.split_once('/')?;
337    let path = path.trim_end_matches('/');
338    let path = path.strip_suffix("/chat/completions").unwrap_or(path);
339    let path = path.strip_prefix("v1/projects/")?;
340    let (project, path) = path.split_once("/locations/")?;
341    let location = path.strip_suffix("/endpoints/openapi")?;
342    let canonical = vertex_endpoint(project, location);
343    (is_cloud_project_id(project)
344        && is_vertex_location(location)
345        && canonical.strip_prefix("https://")?.split_once('/')?.0 == host)
346        .then(|| (project.to_string(), location.to_string()))
347}
348
349/// The id Vertex AI's OpenAI-compatible endpoint takes for `model`: a
350/// publisher-qualified id as given, a bare Gemini name under `google/`.
351pub fn vertex_model_id(model: &str) -> String {
352    let model = model.trim();
353    if model.contains('/') {
354        model.to_string()
355    } else {
356        format!("google/{model}")
357    }
358}
359
360/// One model advertised by a profile. A model list is metadata, not a
361/// capability grant: individual agent tasks still require their own action
362/// permissions.
363#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
364#[serde(remote = "Self", default)]
365pub struct ModelDescriptor {
366    /// Provider-native model id sent over the wire.
367    pub id: String,
368    /// User-facing label. Defaults to `id` for imported/minimal profiles.
369    pub label: String,
370    /// Best known input-context size. `None` means unknown, not unlimited.
371    pub context_window: Option<u32>,
372    /// The model's own declared output limit: the most tokens one answer may
373    /// take, its reasoning included. `None` means its list said nothing, not
374    /// unlimited; a caller then asks for
375    /// [`ModelDescriptor::DEFAULT_OUTPUT_TOKENS`].
376    #[serde(default, skip_serializing_if = "Option::is_none")]
377    pub max_output_tokens: Option<u32>,
378    /// Optional Settings-owned request policy. Runtime context is a configured
379    /// deployment limit, separate from this model's source context capacity.
380    #[serde(skip_serializing_if = "Option::is_none")]
381    pub request_limits: Option<ModelRequestLimits>,
382    /// Immutable release revision when this model comes from the signed local
383    /// model catalogue. Hosted providers often cannot supply one, so absence
384    /// means "not attested", never "latest".
385    #[serde(skip_serializing_if = "Option::is_none")]
386    pub revision: Option<String>,
387    /// A declared capability, not an inference from a model's friendly name.
388    /// For locally managed models this value is copied from the signed
389    /// catalogue; hosted profiles remain an explicit user/provider claim.
390    pub vision: bool,
391    /// Signed declaration that this exact local model exposes the bounded
392    /// Photos face-detection/embedding/clustering protocol. This is separate
393    /// from generic vision: image descriptions must never enable biometrics.
394    #[serde(default)]
395    pub face_recognition: bool,
396    /// Whether the model calls tools. An agent plans by calling actions, so
397    /// a model without it cannot be chosen for one
398    /// ([`ProviderConfig::set_agent_model`]). Unknown reads as `true`: a
399    /// model nothing says anything about is offered, and the provider's
400    /// own refusal names it.
401    pub tool_calling: bool,
402    /// Who said what `vision` and `tool_calling` hold: the provider's model
403    /// list, Tilo's table of model families, or the person. A person's
404    /// answer is never replaced by a later list.
405    #[serde(skip_serializing_if = "CapabilitySource::is_unknown")]
406    pub capabilities_from: CapabilitySource,
407}
408
409settings_store::read_through_json_value!(ModelDescriptor);
410
411/// Where a model's `vision` and `tool_calling` came from
412/// ([`ModelDescriptor::capabilities_from`]).
413#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
414#[serde(remote = "Self", rename_all = "snake_case")]
415pub enum CapabilitySource {
416    /// The provider's model list said so.
417    Provider,
418    /// Tilo's table of known model families ([`capabilities::family`]).
419    Family,
420    /// The person set them.
421    Person,
422    /// Nothing said: `vision` off, `tool_calling` on. Also what a source
423    /// this build does not know reads as, so a newer writer's settings
424    /// still read.
425    #[default]
426    #[serde(other)]
427    Unknown,
428}
429
430settings_store::read_through_json_value!(CapabilitySource);
431
432impl CapabilitySource {
433    pub const fn is_unknown(&self) -> bool {
434        matches!(self, Self::Unknown)
435    }
436}
437
438impl Default for ModelDescriptor {
439    fn default() -> Self {
440        Self {
441            id: String::new(),
442            label: String::new(),
443            context_window: None,
444            max_output_tokens: None,
445            request_limits: None,
446            revision: None,
447            vision: false,
448            face_recognition: false,
449            tool_calling: true,
450            capabilities_from: CapabilitySource::Unknown,
451        }
452    }
453}
454
455/// Explicit request limits for one selected model; not a capability or runtime
456/// attestation. None on a descriptor preserves legacy request shaping.
457#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
458#[serde(remote = "Self", deny_unknown_fields)]
459pub struct ModelRequestLimits {
460    pub max_output_tokens: u32,
461    #[serde(default, skip_serializing_if = "Option::is_none")]
462    pub runtime_context_tokens: Option<u32>,
463    /// Owner-configured Plan deadline ceiling; absent preserves 60 seconds.
464    #[serde(default, skip_serializing_if = "Option::is_none")]
465    pub plan_timeout_ms: Option<u32>,
466}
467
468settings_store::read_through_json_value!(ModelRequestLimits);
469
470impl ModelRequestLimits {
471    /// Validate bounded settings without estimating the token count of a prompt.
472    pub fn validate(&self, source_context: Option<u32>) -> Result<(), &'static str> {
473        if self.max_output_tokens == 0 || self.max_output_tokens > 65_536 {
474            return Err("Output allowance must be between 1 and 65536 tokens.");
475        }
476        if let Some(context) = self.runtime_context_tokens
477            && (context == 0
478                || context > 1_048_576
479                || self.max_output_tokens >= context
480                || source_context.is_some_and(|source| context > source))
481        {
482            return Err("Runtime context must fit the model and leave room beyond output.");
483        }
484        if self
485            .plan_timeout_ms
486            .is_some_and(|timeout| timeout == 0 || timeout > 900_000)
487        {
488            return Err("Plan timeout must be between 1 and 900000 milliseconds.");
489        }
490        Ok(())
491    }
492}
493
494impl ModelDescriptor {
495    /// What one answer may take when nothing declared the model's limit: one
496    /// whole turn of a task — a plan with full arguments, or an answer — and
497    /// a reasoning model's thinking before it, which counts against the same
498    /// bound. A metered endpoint reserves credit for all of it.
499    pub const DEFAULT_OUTPUT_TOKENS: u32 = 16_384;
500
501    pub fn new(id: impl Into<String>) -> Self {
502        let id = id.into();
503        Self {
504            label: id.clone(),
505            id,
506            ..Self::default()
507        }
508    }
509
510    /// A hosted model named by hand: what its family is known to do
511    /// ([`capabilities::family`]), else nothing known.
512    pub fn named(id: impl Into<String>) -> Self {
513        let mut model = Self::new(id);
514        capabilities::apply_family(&mut model);
515        model
516    }
517
518    /// Whether the person set this model's capabilities.
519    pub const fn capabilities_set_by_person(&self) -> bool {
520        matches!(self.capabilities_from, CapabilitySource::Person)
521    }
522
523    pub fn display_label(&self) -> &str {
524        if self.label.trim().is_empty() {
525            &self.id
526        } else {
527            &self.label
528        }
529    }
530
531    /// The most tokens one answer may take: the model's own declared limit,
532    /// else [`Self::DEFAULT_OUTPUT_TOKENS`]. Never more than its context
533    /// leaves room for after its input, when both are known, so a small local
534    /// context never makes a request the server must refuse.
535    #[must_use]
536    pub fn output_tokens(&self) -> u32 {
537        let declared = self
538            .max_output_tokens
539            .unwrap_or(Self::DEFAULT_OUTPUT_TOKENS);
540        self.context_window
541            .map_or(declared, |context| declared.min(context))
542    }
543
544    /// How many characters of conversation this model reads at once, by what its descriptor
545    /// knows of its context, about four characters a token; a model that says nothing reads a
546    /// generous default. A turn keeps its conversation within this bound so that a small local
547    /// window is never overflowed.
548    #[must_use]
549    pub fn context_chars(&self) -> usize {
550        let tokens = self
551            .request_limits
552            .as_ref()
553            .and_then(|limits| limits.runtime_context_tokens)
554            .or(self.context_window)
555            .unwrap_or(128_000);
556        let headroom = tokens.saturating_sub(self.max_output_tokens.unwrap_or(8_192));
557        usize::try_from(headroom)
558            .unwrap_or(usize::MAX)
559            .saturating_mul(3)
560    }
561}
562
563/// A configured model-provider endpoint.
564#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
565#[serde(remote = "Self", default)]
566pub struct ProviderProfile {
567    pub id: String,
568    pub label: String,
569    pub protocol: ProviderProtocol,
570    pub endpoint: String,
571    pub location: EndpointLocation,
572    /// Absent for an unauthenticated local endpoint. The secret
573    /// itself is never accepted or serialised by this type.
574    #[serde(skip_serializing_if = "Option::is_none")]
575    pub credential: Option<SecretReference>,
576    /// A sign-in in place of an API key (Google Vertex AI). Absent in
577    /// settings written before sign-in existed, so they read unchanged; a
578    /// reader that predates it ignores the field and asks for a key.
579    #[serde(skip_serializing_if = "Option::is_none")]
580    pub sign_in: Option<SignInCredential>,
581    pub enabled: bool,
582    pub models: Vec<ModelDescriptor>,
583    /// The default model id within `models`. Missing/unknown is represented
584    /// by `None`, so callers prompt instead of silently choosing a model.
585    #[serde(skip_serializing_if = "Option::is_none")]
586    pub default_model: Option<String>,
587    /// How an OpenAI-compatible request names its output-token limit. The
588    /// model gateway owns the outbound request and renames whichever limit the
589    /// caller sent to this one. `None` sends the caller's name unchanged.
590    #[serde(skip_serializing_if = "Option::is_none")]
591    pub token_limit_param: Option<TokenLimitParam>,
592    /// The reasoning setting the gateway sends with every OpenAI-compatible
593    /// request of this profile, whatever the caller asked for. `None` sends
594    /// nothing (the provider's default).
595    #[serde(skip_serializing_if = "Option::is_none")]
596    pub reasoning: Option<ReasoningSetting>,
597    /// Top-level request fields this provider rejects, removed by the gateway
598    /// after it has shaped the request (e.g. `stream_options`,
599    /// `parallel_tool_calls`). Each is a plain JSON key; `model`,
600    /// `messages`, `tools` and `tool_choice` cannot be listed.
601    #[serde(skip_serializing_if = "Vec::is_empty")]
602    pub omit_params: Vec<String>,
603    /// The `OpenAI` API an OpenAI-compatible profile's agent turns take.
604    /// `None` takes Responses at `OpenAI`'s own API, whose reasoning models
605    /// call tools only there, and chat completions at any other endpoint
606    /// ([`transform::openai_api`]). A `ChatGPT` sign-in always takes
607    /// Responses.
608    #[serde(skip_serializing_if = "Option::is_none")]
609    pub openai_api: Option<OpenAiApi>,
610    /// The header carrying the API key, when it is not the protocol's own
611    /// (`Authorization: Bearer` for OpenAI-compatible, `x-api-key` for
612    /// Anthropic): Azure's `api-key`, or a bearer token at an
613    /// Anthropic-compatible endpoint.
614    #[serde(skip_serializing_if = "Option::is_none")]
615    pub key_header: Option<KeyHeader>,
616    /// Where the provider lists its models, when it is not the protocol's
617    /// own ([`transform::models_url`]): relative to the endpoint, or from
618    /// its origin when it starts with `/`. An empty path says the provider
619    /// lists none: its models are typed.
620    #[serde(skip_serializing_if = "Option::is_none")]
621    pub models_path: Option<String>,
622    /// Headers sent with every request to this provider beside its key: what
623    /// a provider asks of each call, such as the organisation or workspace a
624    /// key with access to several bills (`anthropic-workspace-id`,
625    /// `openai-organization`). They are settings, shown wherever the provider
626    /// is, never secrets: the key has its own place, and
627    /// [`ProviderHeader::check`] refuses the headers the key and the protocol
628    /// own.
629    #[serde(skip_serializing_if = "Vec::is_empty")]
630    pub headers: Vec<ProviderHeader>,
631}
632
633settings_store::read_through_json_value!(ProviderProfile);
634
635/// One header a provider is sent with every request ([`ProviderProfile::headers`]).
636#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
637pub struct ProviderHeader {
638    pub name: String,
639    pub value: String,
640}
641
642/// Headers a provider's own settings may not send: the ones its key travels in, the
643/// protocol's version, and the ones the HTTP client writes itself.
644const OWNED_HEADERS: &[&str] = &[
645    "authorization",
646    "x-api-key",
647    "api-key",
648    "anthropic-version",
649    "host",
650    "content-type",
651    "content-length",
652    "transfer-encoding",
653    "connection",
654    "cookie",
655];
656
657impl ProviderHeader {
658    /// Whether this header may be sent as a provider's setting.
659    ///
660    /// # Errors
661    /// The words a person reads: a name that is no HTTP header name, one the key or the
662    /// protocol sends, or a value no header can carry.
663    pub fn check(&self) -> Result<(), String> {
664        let name = self.name.trim();
665        let token = |byte: u8| byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte);
666        if name.is_empty() || !name.bytes().all(token) {
667            return Err(format!("{name:?} is not the name of a header"));
668        }
669        if OWNED_HEADERS.contains(&name.to_ascii_lowercase().as_str()) {
670            return Err(format!(
671                "{name} is sent by Tilo itself: the provider's key has its own setting"
672            ));
673        }
674        if !self
675            .value
676            .bytes()
677            .all(|byte| byte == b'\t' || (b' '..=b'~').contains(&byte))
678        {
679            return Err(format!("The value of {name} cannot be sent in a header"));
680        }
681        Ok(())
682    }
683}
684
685/// The request header an API key travels in ([`ProviderProfile::key_header`]).
686#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
687#[serde(remote = "Self")]
688pub enum KeyHeader {
689    /// `Authorization: Bearer <key>`.
690    #[serde(rename = "authorization")]
691    Bearer,
692    /// `x-api-key: <key>`, Anthropic's.
693    #[serde(rename = "x-api-key")]
694    XApiKey,
695    /// `api-key: <key>`, Azure `OpenAI`'s.
696    #[serde(rename = "api-key")]
697    ApiKey,
698}
699
700settings_store::read_through_json_value!(KeyHeader);
701
702impl KeyHeader {
703    /// The header a `protocol` sends its key in unless told otherwise.
704    pub const fn of(protocol: ProviderProtocol) -> Self {
705        match protocol {
706            ProviderProtocol::OpenAiCompatible => Self::Bearer,
707            ProviderProtocol::Anthropic => Self::XApiKey,
708        }
709    }
710
711    /// The header's name, as sent.
712    pub const fn name(self) -> &'static str {
713        match self {
714            Self::Bearer => "authorization",
715            Self::XApiKey => "x-api-key",
716            Self::ApiKey => "api-key",
717        }
718    }
719}
720
721/// Request fields a profile may not strip: without them there is no request.
722pub const REQUIRED_PARAMS: &[&str] = &["model", "messages", "tools", "tool_choice"];
723
724/// The output-token-limit field of an OpenAI-compatible provider.
725#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
726#[serde(remote = "Self")]
727pub enum TokenLimitParam {
728    #[serde(rename = "max_tokens")]
729    MaxTokens,
730    #[serde(rename = "max_completion_tokens")]
731    MaxCompletionTokens,
732}
733
734settings_store::read_through_json_value!(TokenLimitParam);
735
736impl TokenLimitParam {
737    pub fn key(self) -> &'static str {
738        match self {
739            Self::MaxTokens => "max_tokens",
740            Self::MaxCompletionTokens => "max_completion_tokens",
741        }
742    }
743}
744
745/// The request API of an OpenAI-compatible endpoint's agent turns.
746#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
747#[serde(remote = "Self", rename_all = "snake_case")]
748pub enum OpenAiApi {
749    /// `POST /chat/completions`, which every compatible server speaks.
750    ChatCompletions,
751    /// `POST /responses`.
752    Responses,
753}
754
755settings_store::read_through_json_value!(OpenAiApi);
756
757/// Where a provider takes its reasoning effort.
758#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
759#[serde(remote = "Self")]
760pub enum ReasoningParam {
761    /// `OpenAI` Chat Completions: top-level `"reasoning_effort": "<effort>"`.
762    #[serde(rename = "reasoning_effort")]
763    ReasoningEffort,
764    /// `OpenRouter`'s unified object: `"reasoning": {"effort": "<effort>"}`.
765    #[serde(rename = "reasoning.effort")]
766    ReasoningObject,
767    /// Send no reasoning field at all, and strip any the caller sent.
768    #[serde(rename = "none")]
769    Omit,
770}
771
772settings_store::read_through_json_value!(ReasoningParam);
773
774/// A profile's reasoning setting, applied by the gateway.
775#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
776#[serde(remote = "Self")]
777pub struct ReasoningSetting {
778    pub param: ReasoningParam,
779    /// One of [`REASONING_EFFORTS`]; unused when `param` is `none`. Not every
780    /// model accepts every value (GPT-5.4 rejects `minimal`, gpt-oss cannot
781    /// disable reasoning so its lowest is `low`).
782    #[serde(default, skip_serializing_if = "String::is_empty")]
783    pub effort: String,
784}
785
786settings_store::read_through_json_value!(ReasoningSetting);
787
788/// The reasoning efforts a profile may name.
789pub const REASONING_EFFORTS: &[&str] = &["none", "minimal", "low", "medium", "high", "xhigh"];
790
791#[cfg(feature = "model")]
792tilo_resource::json_model!(ProviderProfile);
793
794impl Default for ProviderProfile {
795    fn default() -> Self {
796        Self {
797            id: String::new(),
798            label: String::new(),
799            protocol: ProviderProtocol::default(),
800            endpoint: String::new(),
801            location: EndpointLocation::default(),
802            credential: None,
803            sign_in: None,
804            enabled: true,
805            models: Vec::new(),
806            default_model: None,
807            token_limit_param: None,
808            reasoning: None,
809            omit_params: Vec::new(),
810            openai_api: None,
811            key_header: None,
812            models_path: None,
813            headers: Vec::new(),
814        }
815    }
816}
817
818impl ProviderProfile {
819    /// A blank hosted profile with an allocated id and a vault reference. The
820    /// caller can open a system credential prompt for that reference; no UI
821    /// needs to retain the typed API key in its widget state or CRDT.
822    pub fn hosted(protocol: ProviderProtocol) -> Self {
823        let id = uuid::Uuid::new_v4().to_string();
824        let (label, endpoint, default_model) = match protocol {
825            ProviderProtocol::OpenAiCompatible => (
826                "OpenAI-compatible provider",
827                "https://api.openai.com/v1",
828                None,
829            ),
830            ProviderProtocol::Anthropic => ("Anthropic", "https://api.anthropic.com", None),
831        };
832        Self {
833            id: id.clone(),
834            label: label.to_string(),
835            protocol,
836            endpoint: endpoint.to_string(),
837            location: EndpointLocation::Hosted,
838            credential: Some(SecretReference::provider_api_key(&id)),
839            sign_in: None,
840            enabled: true,
841            models: Vec::new(),
842            default_model,
843            token_limit_param: None,
844            reasoning: None,
845            omit_params: Vec::new(),
846            openai_api: None,
847            key_header: None,
848            models_path: None,
849            headers: Vec::new(),
850        }
851    }
852
853    /// An OpenAI-compatible local profile suitable for vLLM. It is
854    /// unauthenticated by default because a loopback server need not have a
855    /// token; users can attach a vault reference if their deployment requires
856    /// one.
857    pub fn local_vllm() -> Self {
858        let id = uuid::Uuid::new_v4().to_string();
859        Self {
860            id,
861            label: "Local vLLM".to_string(),
862            protocol: ProviderProtocol::OpenAiCompatible,
863            endpoint: "http://127.0.0.1:8000/v1".to_string(),
864            location: EndpointLocation::ThisDevice,
865            credential: None,
866            sign_in: None,
867            enabled: true,
868            models: Vec::new(),
869            default_model: None,
870            token_limit_param: None,
871            reasoning: None,
872            omit_params: Vec::new(),
873            openai_api: None,
874            key_header: None,
875            models_path: None,
876            headers: Vec::new(),
877        }
878    }
879
880    /// A Google Vertex AI profile for `project` in `location`, offering
881    /// `model`, signed in with Google rather than an API key. It speaks
882    /// Vertex AI's OpenAI-compatible endpoint, which accepts every field the
883    /// gateway sends (`stream_options`, `parallel_tool_calls`,
884    /// `max_completion_tokens`, `reasoning_effort`), so nothing is omitted.
885    pub fn google_vertex(project: &str, location: &str, model: &str) -> Self {
886        let id = uuid::Uuid::new_v4().to_string();
887        let model = ModelDescriptor {
888            label: model.trim().to_string(),
889            ..ModelDescriptor::new(vertex_model_id(model))
890        };
891        Self {
892            id,
893            label: "Google Vertex AI".to_string(),
894            protocol: ProviderProtocol::OpenAiCompatible,
895            endpoint: vertex_endpoint(project, location),
896            location: EndpointLocation::Hosted,
897            credential: None,
898            sign_in: Some(SignInCredential::google(project)),
899            enabled: true,
900            default_model: Some(model.id.clone()),
901            models: vec![model],
902            token_limit_param: None,
903            reasoning: None,
904            omit_params: Vec::new(),
905            openai_api: None,
906            key_header: None,
907            models_path: None,
908            headers: Vec::new(),
909        }
910    }
911
912    /// A Gemini API profile signed in with Google, billed to `project`.
913    pub fn google_gemini(project: &str) -> Self {
914        Self {
915            sign_in: Some(SignInCredential::google(project)),
916            credential: None,
917            ..presets::Preset::GEMINI.profile()
918        }
919    }
920
921    /// Whether this profile speaks to Google's own Gemini endpoint
922    /// ([`presets::GEMINI_ENDPOINT`]), whatever path it names there.
923    #[must_use]
924    pub fn is_googles_endpoint(&self) -> bool {
925        let googles = url::Url::parse(presets::GEMINI_ENDPOINT).ok();
926        url::Url::parse(self.endpoint.trim()).is_ok_and(|url| {
927            url.scheme() == "https"
928                && url.domain().is_some()
929                && url.domain() == googles.as_ref().and_then(url::Url::domain)
930        })
931    }
932
933    /// Whether this profile signs in with Google instead of using a key.
934    pub fn signs_in_with_google(&self) -> bool {
935        self.sign_in_issuer() == Some(SignInIssuer::Google)
936    }
937
938    /// Who this profile signs in with, `None` for a key, no credential or
939    /// an issuer this build does not know.
940    pub fn sign_in_issuer(&self) -> Option<SignInIssuer> {
941        self.sign_in.as_ref().and_then(SignInCredential::issuer)
942    }
943
944    pub fn display_label(&self) -> &str {
945        if self.label.trim().is_empty() {
946            &self.id
947        } else {
948            &self.label
949        }
950    }
951
952    pub fn is_local_vllm_candidate(&self) -> bool {
953        self.protocol == ProviderProtocol::OpenAiCompatible
954            && self.location == EndpointLocation::ThisDevice
955            && (self.endpoint.contains(":8000") || self.label.to_ascii_lowercase().contains("vllm"))
956    }
957}
958
959/// Whether `profile` is a model runner the gateway supervises on this device:
960/// OpenAI-compatible and reachable only on loopback. Work that must stay on
961/// the device (its image operations, private history prose) admits nothing
962/// else, and apps discovering such a model apply this same rule so they never
963/// offer one the gateway would refuse.
964#[must_use]
965pub fn is_supervised_loopback(profile: &ProviderProfile) -> bool {
966    profile.location == EndpointLocation::ThisDevice
967        && profile.protocol == ProviderProtocol::OpenAiCompatible
968        && loopback_http_endpoint(&profile.endpoint)
969}
970
971fn loopback_http_endpoint(endpoint: &str) -> bool {
972    let Ok(url) = url::Url::parse(endpoint) else {
973        return false;
974    };
975    if !matches!(url.scheme(), "http" | "https") || url.username() != "" || url.password().is_some()
976    {
977        return false;
978    }
979    match url.host() {
980        Some(url::Host::Domain("localhost")) => true,
981        Some(url::Host::Ipv4(address)) => address.is_loopback(),
982        Some(url::Host::Ipv6(address)) => address.is_loopback(),
983        _ => false,
984    }
985}
986
987/// Whether `endpoint` names a literal loopback address on this device: an
988/// `http`/`https` URL whose host is `127.0.0.1` or `::1`, with no userinfo.
989/// A name, even `localhost`, is resolved by something outside the device's
990/// own network stack, so it does not qualify.
991#[must_use]
992pub fn literal_loopback_endpoint(endpoint: &str) -> bool {
993    let Ok(url) = url::Url::parse(endpoint) else {
994        return false;
995    };
996    if !matches!(url.scheme(), "http" | "https") || url.username() != "" || url.password().is_some()
997    {
998        return false;
999    }
1000    match url.host() {
1001        Some(url::Host::Ipv4(address)) => address.is_loopback(),
1002        Some(url::Host::Ipv6(address)) => address.is_loopback(),
1003        _ => false,
1004    }
1005}
1006
1007/// Whether `profile` is an endpoint on this device that authenticates no
1008/// one: no credential and no sign-in, classified as this device, at a
1009/// literal loopback address. The model gateway resolves a key for every
1010/// other profile and refuses a provider without one, and the request
1011/// headers send none for this one. One rule decides both, so a keyless
1012/// local plan and the request it sends cannot disagree.
1013#[must_use]
1014pub fn is_unauthenticated_local(profile: &ProviderProfile) -> bool {
1015    profile.location == EndpointLocation::ThisDevice
1016        && profile.credential.is_none()
1017        && profile.sign_in.is_none()
1018        && literal_loopback_endpoint(&profile.endpoint)
1019}
1020
1021/// The hosted providers of a configuration, as they roam with the person:
1022/// each names an endpoint on the internet and a reference to its key, never
1023/// the key, which each device keeps in its own vault.
1024#[cfg_attr(feature = "model", derive(tilo_resource::Model))]
1025#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1026#[serde(remote = "Self", default)]
1027pub struct HostedProfiles {
1028    pub profiles: Vec<ProviderProfile>,
1029}
1030
1031settings_store::read_through_json_value!(HostedProfiles);
1032
1033/// A portable profile list, the user's deliberate default and the models
1034/// they chose for particular agents and for each kind of interaction. Kept
1035/// separate from a request: a request records the model it was asked of, so
1036/// changing these does not change work already in progress.
1037#[cfg_attr(feature = "model", derive(tilo_resource::Model))]
1038#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1039#[serde(remote = "Self", default)]
1040pub struct ProviderConfig {
1041    pub profiles: Vec<ProviderProfile>,
1042    #[serde(skip_serializing_if = "Option::is_none")]
1043    pub default_profile: Option<String>,
1044    /// The model an agent plans with in place of the default, by agent id.
1045    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
1046    pub agent_models: BTreeMap<String, AgentModel>,
1047    /// The model one kind of interaction runs on, by [`Interaction::id`]. A
1048    /// kind with no choice follows the default, or the agent's own model.
1049    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
1050    pub interaction_models: BTreeMap<String, AgentModel>,
1051}
1052
1053settings_store::read_through_json_value!(ProviderConfig);
1054
1055/// A model of one profile, chosen for an agent or for a kind of interaction.
1056#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1057#[serde(remote = "Self", default)]
1058pub struct AgentModel {
1059    pub profile: String,
1060    pub model: String,
1061}
1062
1063settings_store::read_through_json_value!(AgentModel);
1064
1065#[cfg(feature = "model")]
1066tilo_resource::json_model!(AgentModel);
1067
1068/// What a person is asking of a model, as far as choosing a model goes.
1069///
1070/// One kind is one exchange with a different appetite: a translation or a
1071/// dictated sentence is one short answer, a task runs for a plan and many
1072/// steps. Each kind carries its own default model, and a request may name
1073/// another one for itself.
1074#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
1075#[serde(remote = "Self", rename_all = "snake_case")]
1076pub enum Interaction {
1077    /// One short answer computed from an input: translate, summarise,
1078    /// extract, classify, rewrite.
1079    OneShot,
1080    /// An instruction worked through the actions a person allows.
1081    Task,
1082    /// A part of a task.
1083    Subtask,
1084    /// A person's message to their agent, answered rather than acted on.
1085    Request,
1086    /// One label chosen for an input.
1087    Classifier,
1088    /// Tidying text a person dictated.
1089    Dictation,
1090}
1091
1092settings_store::read_through_json_value!(Interaction);
1093
1094impl Interaction {
1095    /// Every kind, in the order Settings lists them.
1096    pub const ALL: &'static [Self] = &[
1097        Self::OneShot,
1098        Self::Task,
1099        Self::Subtask,
1100        Self::Request,
1101        Self::Classifier,
1102        Self::Dictation,
1103    ];
1104
1105    /// This kind's stable id, which is the key its choice is stored under.
1106    pub const fn id(self) -> &'static str {
1107        match self {
1108            Self::OneShot => "one_shot",
1109            Self::Task => "task",
1110            Self::Subtask => "subtask",
1111            Self::Request => "request",
1112            Self::Classifier => "classifier",
1113            Self::Dictation => "dictation",
1114        }
1115    }
1116
1117    /// The kind stored under `id`, if this build knows it.
1118    #[must_use]
1119    pub fn from_id(id: &str) -> Option<Self> {
1120        Self::ALL.iter().copied().find(|kind| kind.id() == id)
1121    }
1122}
1123
1124impl std::fmt::Display for Interaction {
1125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1126        f.write_str(self.id())
1127    }
1128}
1129
1130impl ProviderConfig {
1131    /// The model and where it runs, chosen for `kind`; `None` while nothing
1132    /// is chosen for it, or the choice names a provider that is switched off
1133    /// or no longer offers that model.
1134    #[must_use]
1135    pub fn interaction_selection(
1136        &self,
1137        kind: Interaction,
1138    ) -> Option<(&ProviderProfile, &ModelDescriptor)> {
1139        let chosen = self.interaction_models.get(kind.id())?;
1140        let profile = self
1141            .profiles
1142            .iter()
1143            .find(|profile| profile.id == chosen.profile && profile.enabled)?;
1144        let model = profile.models.iter().find(|m| m.id == chosen.model)?;
1145        Some((profile, model))
1146    }
1147
1148    /// Choose `chosen` of a profile for `kind`, or with `None` let that kind
1149    /// follow the default again.
1150    pub fn set_interaction_model(
1151        &mut self,
1152        kind: Interaction,
1153        chosen: Option<AgentModel>,
1154    ) -> Result<(), &'static str> {
1155        let Some(chosen) = chosen else {
1156            self.interaction_models.remove(kind.id());
1157            return Ok(());
1158        };
1159        if !self.profiles.iter().any(|profile| {
1160            profile.id == chosen.profile && profile.models.iter().any(|m| m.id == chosen.model)
1161        }) {
1162            return Err("That provider does not offer this model.");
1163        }
1164        self.interaction_models.insert(kind.id().to_owned(), chosen);
1165        Ok(())
1166    }
1167}
1168
1169impl ProviderConfig {
1170    pub fn load() -> Self {
1171        Self::from_document(&settings_store::load())
1172    }
1173
1174    /// The configuration in `source`: another profile's settings.
1175    pub fn load_in(source: &dyn settings_store::SettingsSource) -> Self {
1176        Self::from_document(&source.load())
1177    }
1178
1179    /// The configuration `document` holds: this device's providers and the
1180    /// person's hosted ones.
1181    pub(crate) fn from_document(document: &Map<String, Value>) -> Self {
1182        let leaf = |section: &str, key: &str| {
1183            document
1184                .get(section)
1185                .and_then(|section| section.get(key))
1186                .cloned()
1187        };
1188        let local = leaf(SETTINGS_SECTION, CONFIG_KEY)
1189            .and_then(|value| serde_json::from_value::<Self>(value).ok())
1190            .unwrap_or_default();
1191        let hosted = leaf(HOSTED_SECTION, HOSTED_KEY)
1192            .and_then(|value| serde_json::from_value::<HostedProfiles>(value).ok())
1193            .unwrap_or_default();
1194        Self::from_stored(local, hosted).sanitised()
1195    }
1196
1197    /// This configuration as it is stored: the providers of this device and
1198    /// its network with the default, which stay on the device, and the
1199    /// hosted providers, which roam with the person.
1200    #[must_use]
1201    pub fn stored(self) -> (Self, HostedProfiles) {
1202        let (hosted, local): (Vec<_>, Vec<_>) = self
1203            .profiles
1204            .into_iter()
1205            .partition(|profile| profile.location == EndpointLocation::Hosted);
1206        (
1207            Self {
1208                profiles: local,
1209                default_profile: self.default_profile,
1210                agent_models: self.agent_models,
1211                interaction_models: self.interaction_models,
1212            },
1213            HostedProfiles { profiles: hosted },
1214        )
1215    }
1216
1217    /// The configuration stored as `local` and `hosted`; a profile stored in
1218    /// both is the local one.
1219    #[must_use]
1220    pub fn from_stored(local: Self, hosted: HostedProfiles) -> Self {
1221        let mut profiles = local.profiles;
1222        for profile in hosted.profiles {
1223            if !profiles.iter().any(|known| known.id == profile.id) {
1224                profiles.push(profile);
1225            }
1226        }
1227        Self {
1228            profiles,
1229            default_profile: local.default_profile,
1230            agent_models: local.agent_models,
1231            interaction_models: local.interaction_models,
1232        }
1233    }
1234
1235    /// This configuration as its two sections store it: this device's
1236    /// ([`SETTINGS_SECTION`]) and the person's ([`HOSTED_SECTION`]).
1237    fn sections(&self) -> std::io::Result<(Map<String, Value>, Map<String, Value>)> {
1238        let (local, hosted) = self.clone().sanitised().stored();
1239        let leaf = |key: &str, value: Value| Map::from_iter([(key.to_string(), value)]);
1240        Ok((
1241            leaf(
1242                CONFIG_KEY,
1243                serde_json::to_value(local).map_err(std::io::Error::other)?,
1244            ),
1245            leaf(
1246                HOSTED_KEY,
1247                serde_json::to_value(hosted).map_err(std::io::Error::other)?,
1248            ),
1249        ))
1250    }
1251
1252    /// Merge our single configuration payload into the shared settings file.
1253    /// Other Settings panes retain their sections, and no secret can enter the
1254    /// document because `ProviderProfile` exposes a reference only.
1255    pub fn save(&self) -> std::io::Result<()> {
1256        let source = settings_store::source()
1257            .ok_or_else(|| std::io::Error::other("no settings in this process"))?;
1258        self.save_in(source.as_ref())
1259    }
1260
1261    /// Save this configuration to `source`: another profile's settings.
1262    pub fn save_in(&self, source: &dyn settings_store::SettingsSource) -> std::io::Result<()> {
1263        let (local, hosted) = self.sections()?;
1264        source.update_sections(
1265            vec![
1266                (SETTINGS_SECTION.to_owned(), local),
1267                (HOSTED_SECTION.to_owned(), hosted),
1268            ],
1269            &settings_store::ChangeOrigin::default(),
1270        )
1271    }
1272
1273    /// Validate storage and runtime-safe invariants, returning user-facing
1274    /// diagnostics. Invalid imported records remain visible in Settings but
1275    /// are never offered as an active agent provider.
1276    pub fn validation_errors(&self) -> Vec<ProfileIssue> {
1277        let mut issues = Vec::new();
1278        let mut ids = BTreeSet::new();
1279        for profile in &self.profiles {
1280            if profile.id.trim().is_empty() || !ids.insert(profile.id.clone()) {
1281                issues.push(ProfileIssue::new(&profile.id, "Profile needs a unique id."));
1282            }
1283            if profile.label.trim().is_empty() {
1284                issues.push(ProfileIssue::new(&profile.id, "Profile needs a name."));
1285            }
1286            if profile.endpoint.trim().is_empty() {
1287                issues.push(ProfileIssue::new(&profile.id, "Profile needs an endpoint."));
1288            }
1289            endpoint_issues(profile, &mut issues);
1290            if profile
1291                .credential
1292                .as_ref()
1293                .is_some_and(|reference| !reference.is_valid())
1294            {
1295                issues.push(ProfileIssue::new(
1296                    &profile.id,
1297                    "Credential reference is incomplete.",
1298                ));
1299            }
1300            sign_in_issues(profile, &mut issues);
1301            let model_ids: BTreeSet<_> =
1302                profile.models.iter().map(|model| model.id.trim()).collect();
1303            if model_ids.len() != profile.models.len() || model_ids.contains("") {
1304                issues.push(ProfileIssue::new(
1305                    &profile.id,
1306                    "Every model needs a unique id.",
1307                ));
1308            }
1309            for model in &profile.models {
1310                if let Some(limits) = &model.request_limits
1311                    && let Err(message) = limits.validate(model.context_window)
1312                {
1313                    issues.push(ProfileIssue::new(&profile.id, message));
1314                }
1315            }
1316            if profile.reasoning.as_ref().is_some_and(|reasoning| {
1317                reasoning.param != ReasoningParam::Omit
1318                    && !REASONING_EFFORTS.contains(&reasoning.effort.as_str())
1319            }) {
1320                issues.push(ProfileIssue::new(
1321                    &profile.id,
1322                    "Reasoning effort must be a supported value.",
1323                ));
1324            }
1325            if profile.omit_params.iter().any(|param| {
1326                param.is_empty()
1327                    || param.len() > 64
1328                    || !param.bytes().all(|byte| {
1329                        byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_'
1330                    })
1331                    || REQUIRED_PARAMS.contains(&param.as_str())
1332            }) {
1333                issues.push(ProfileIssue::new(
1334                    &profile.id,
1335                    "Omitted request fields must be plain optional field names.",
1336                ));
1337            }
1338            if profile
1339                .default_model
1340                .as_ref()
1341                .is_some_and(|id| !model_ids.contains(id.as_str()))
1342            {
1343                issues.push(ProfileIssue::new(
1344                    &profile.id,
1345                    "Default model is not in this profile.",
1346                ));
1347            }
1348        }
1349        for (agent, chosen) in &self.agent_models {
1350            if agent.trim().is_empty() || self.offers_nothing(chosen) {
1351                issues.push(ProfileIssue::new(
1352                    &chosen.profile,
1353                    "An agent's model is not offered by its provider.",
1354                ));
1355            }
1356        }
1357        self.choice_issues(&mut issues);
1358        if self
1359            .default_profile
1360            .as_ref()
1361            .is_some_and(|id| !self.profiles.iter().any(|p| &p.id == id && p.enabled))
1362        {
1363            issues.push(ProfileIssue::new(
1364                "default",
1365                "Choose an enabled default provider.",
1366            ));
1367        }
1368        issues
1369    }
1370
1371    /// The profile and model `agent` plans with: the one chosen for it, else
1372    /// the default profile's default model. `None` while the choice names a
1373    /// provider that is switched off, or nothing is chosen at all: a caller
1374    /// asks rather than guessing another model.
1375    pub fn selection_for(&self, agent: &str) -> Option<(&ProviderProfile, &ModelDescriptor)> {
1376        let (profile, model) = if let Some(chosen) = self.agent_models.get(agent) {
1377            let profile = self
1378                .profiles
1379                .iter()
1380                .find(|profile| profile.id == chosen.profile && profile.enabled)?;
1381            (profile, &chosen.model)
1382        } else {
1383            let profile = self.active_profile()?;
1384            (profile, profile.default_model.as_ref()?)
1385        };
1386        Some((profile, profile.models.iter().find(|m| &m.id == model)?))
1387    }
1388
1389    /// Choose `model` of `profile` for `agent`, or with `None` let it follow
1390    /// the default again.
1391    ///
1392    /// # Errors
1393    /// When `agent` is empty, `profile` does not offer `model`, or the model
1394    /// does not call tools ([`NO_TOOL_CALLING`]).
1395    pub fn set_agent_model(
1396        &mut self,
1397        agent: &str,
1398        chosen: Option<AgentModel>,
1399    ) -> Result<(), &'static str> {
1400        let Some(chosen) = chosen else {
1401            self.agent_models.remove(agent);
1402            return Ok(());
1403        };
1404        if agent.trim().is_empty() {
1405            return Err("Name the agent.");
1406        }
1407        let model = self
1408            .profiles
1409            .iter()
1410            .filter(|profile| profile.id == chosen.profile)
1411            .find_map(|profile| profile.models.iter().find(|m| m.id == chosen.model))
1412            .ok_or("That provider does not offer this model.")?;
1413        if !model.tool_calling {
1414            return Err(NO_TOOL_CALLING);
1415        }
1416        self.agent_models.insert(agent.to_owned(), chosen);
1417        Ok(())
1418    }
1419
1420    /// The agents that plan with `model` of `profile`.
1421    pub fn agents_planning_with<'a>(
1422        &'a self,
1423        profile: &'a str,
1424        model: &'a str,
1425    ) -> impl Iterator<Item = &'a str> + 'a {
1426        self.agent_models
1427            .iter()
1428            .filter(move |(_, chosen)| chosen.profile == profile && chosen.model == model)
1429            .map(|(agent, _)| agent.as_str())
1430    }
1431
1432    /// Whether no profile offers the model `chosen` names.
1433    fn offers_nothing(&self, chosen: &AgentModel) -> bool {
1434        !self.profiles.iter().any(|profile| {
1435            profile.id == chosen.profile && profile.models.iter().any(|m| m.id == chosen.model)
1436        })
1437    }
1438
1439    /// Diagnose the models chosen for kinds of interaction: one this build
1440    /// does not know, or one no profile offers.
1441    fn choice_issues(&self, issues: &mut Vec<ProfileIssue>) {
1442        for (kind, chosen) in &self.interaction_models {
1443            if Interaction::from_id(kind).is_none() || self.offers_nothing(chosen) {
1444                issues.push(ProfileIssue::new(
1445                    &chosen.profile,
1446                    "A default model for a kind of interaction is not offered here.",
1447                ));
1448            }
1449        }
1450    }
1451
1452    pub fn active_profile(&self) -> Option<&ProviderProfile> {
1453        self.default_profile.as_ref().and_then(|id| {
1454            self.profiles
1455                .iter()
1456                .find(|profile| profile.id == *id && profile.enabled)
1457        })
1458    }
1459
1460    pub fn upsert(&mut self, profile: ProviderProfile) {
1461        if let Some(existing) = self
1462            .profiles
1463            .iter_mut()
1464            .find(|existing| existing.id == profile.id)
1465        {
1466            *existing = profile;
1467        } else {
1468            self.profiles.push(profile);
1469        }
1470    }
1471
1472    /// The profile `id` as it may change, or [`ProviderChoiceError::ProviderGone`]
1473    /// when nothing has its id. The one way a caller reaches a profile to
1474    /// change it, so the pane and a service change it the same way.
1475    ///
1476    /// # Errors
1477    /// [`ProviderChoiceError::ProviderGone`] when no profile has the id.
1478    pub fn profile_mut(&mut self, id: &str) -> Result<&mut ProviderProfile, ProviderChoiceError> {
1479        self.profiles
1480            .iter_mut()
1481            .find(|profile| profile.id == id)
1482            .ok_or(ProviderChoiceError::ProviderGone)
1483    }
1484
1485    /// Make `model` the default of `provider`, which offers it afterwards
1486    /// even if it was written by hand rather than listed by the provider.
1487    /// `listed` is what the provider's list says of it; without one, a model
1488    /// the profile does not have yet gets what its family is known to do
1489    /// ([`ModelDescriptor::named`]). The one choice the pane's "Use model"
1490    /// and the canvas composer's switcher make.
1491    ///
1492    /// # Errors
1493    /// [`ProviderChoiceError::NotAModel`] when `model` is blank, longer than
1494    /// 256 bytes, or holds a control character, and
1495    /// [`ProviderChoiceError::ProviderGone`] when no profile has the
1496    /// provider's id.
1497    pub fn take_model(
1498        &mut self,
1499        provider: &str,
1500        model: &str,
1501        listed: Option<ModelDescriptor>,
1502    ) -> Result<(), ProviderChoiceError> {
1503        let model = model.trim();
1504        if model.is_empty() || model.len() > 256 || model.contains(char::is_control) {
1505            return Err(ProviderChoiceError::NotAModel);
1506        }
1507        let profile = self.profile_mut(provider)?;
1508        match profile.models.iter_mut().find(|known| known.id == model) {
1509            // What the provider now says about a model the person already
1510            // has; their own answer stays.
1511            Some(known) => {
1512                if let Some(listed) = &listed {
1513                    capabilities::refresh(known, listed);
1514                }
1515            }
1516            None => profile
1517                .models
1518                .push(listed.unwrap_or_else(|| ModelDescriptor::named(model.to_owned()))),
1519        }
1520        profile.default_model = Some(model.to_owned());
1521        Ok(())
1522    }
1523
1524    pub fn remove(&mut self, id: &str) -> Option<ProviderProfile> {
1525        let index = self.profiles.iter().position(|profile| profile.id == id)?;
1526        let removed = self.profiles.remove(index);
1527        if self.default_profile.as_deref() == Some(id) {
1528            self.default_profile = None;
1529        }
1530        self.agent_models.retain(|_, chosen| chosen.profile != id);
1531        self.interaction_models
1532            .retain(|_, chosen| chosen.profile != id);
1533        Some(removed)
1534    }
1535
1536    /// The configuration as it is stored and read: profiles without an id,
1537    /// models without an id, and defaults and agents' models naming no model
1538    /// are dropped.
1539    #[must_use]
1540    pub fn sanitised(mut self) -> Self {
1541        // Do not turn unknown/malformed input into a usable provider.
1542        self.profiles
1543            .retain(|profile| !profile.id.trim().is_empty());
1544        for profile in &mut self.profiles {
1545            profile.models.retain(|model| !model.id.trim().is_empty());
1546            if profile
1547                .default_model
1548                .as_ref()
1549                .is_some_and(|default| !profile.models.iter().any(|model| &model.id == default))
1550            {
1551                profile.default_model = None;
1552            }
1553        }
1554        let unknown = |chosen: &AgentModel| {
1555            !self.profiles.iter().any(|profile| {
1556                profile.id == chosen.profile && profile.models.iter().any(|m| m.id == chosen.model)
1557            })
1558        };
1559        self.agent_models.retain(|_, chosen| !unknown(chosen));
1560        self.interaction_models
1561            .retain(|kind, chosen| Interaction::from_id(kind).is_some() && !unknown(chosen));
1562        self
1563    }
1564}
1565
1566/// What is wrong with `profile`'s endpoint beyond its absence: no TLS to a
1567/// hosted provider.
1568fn endpoint_issues(profile: &ProviderProfile, issues: &mut Vec<ProfileIssue>) {
1569    if profile.endpoint.trim().is_empty() {
1570        return;
1571    }
1572    if !is_safe_endpoint(&profile.endpoint, profile.location) {
1573        issues.push(ProfileIssue::new(
1574            &profile.id,
1575            "Endpoint must be HTTPS unless it is a local or private endpoint.",
1576        ));
1577    }
1578}
1579
1580/// Why a model cannot plan for an agent: an agent acts by calling tools.
1581pub const NO_TOOL_CALLING: &str =
1582    "This model does not call tools, so an agent cannot plan with it.";
1583
1584/// Why a person's choice of a provider or a model was refused, as
1585/// [`ProviderConfig::take_model`] answers it: each carries no words, leaving
1586/// the words to whoever shows them (the pane's localized keys, the canvas
1587/// composer's own).
1588#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1589pub enum ProviderChoiceError {
1590    /// The model is blank, longer than 256 bytes, or holds a control
1591    /// character.
1592    NotAModel,
1593    /// No profile has the provider's id.
1594    ProviderGone,
1595}
1596
1597impl std::fmt::Display for ProviderChoiceError {
1598    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1599        f.write_str(match self {
1600            Self::NotAModel => "Enter a model ID on one line.",
1601            Self::ProviderGone => "Provider is no longer available.",
1602        })
1603    }
1604}
1605
1606impl std::error::Error for ProviderChoiceError {}
1607
1608/// A profile validation diagnosis fit for an inline Settings status line.
1609#[derive(Clone, Debug, PartialEq, Eq)]
1610pub struct ProfileIssue {
1611    pub profile_id: String,
1612    pub message: String,
1613}
1614
1615impl ProfileIssue {
1616    fn new(profile_id: &str, message: &str) -> Self {
1617        Self {
1618            profile_id: profile_id.to_string(),
1619            message: message.to_string(),
1620        }
1621    }
1622}
1623
1624/// What is wrong with `profile`'s sign-in, if it has one.
1625fn sign_in_issues(profile: &ProviderProfile, issues: &mut Vec<ProfileIssue>) {
1626    if let Some(sign_in) = &profile.sign_in {
1627        if profile.credential.is_some() {
1628            issues.push(ProfileIssue::new(
1629                &profile.id,
1630                "Profile uses both an API key and a sign-in.",
1631            ));
1632        }
1633        if sign_in.issuer().is_none() {
1634            issues.push(ProfileIssue::new(
1635                &profile.id,
1636                "Profile signs in with an unsupported provider.",
1637            ));
1638        }
1639        if sign_in.billing_project.is_some() && sign_in.issuer() != Some(SignInIssuer::Google) {
1640            issues.push(ProfileIssue::new(
1641                &profile.id,
1642                "Only a Google sign-in names a billing project.",
1643            ));
1644        }
1645        if sign_in
1646            .billing_project
1647            .as_deref()
1648            .is_some_and(|project| !is_cloud_project_id(project))
1649        {
1650            issues.push(ProfileIssue::new(
1651                &profile.id,
1652                "Billing project is not a Google Cloud project id.",
1653            ));
1654        }
1655    }
1656}
1657
1658fn is_safe_endpoint(endpoint: &str, location: EndpointLocation) -> bool {
1659    let endpoint = endpoint.trim();
1660    if endpoint.is_empty() || endpoint.contains(char::is_whitespace) {
1661        return false;
1662    }
1663    if location.needs_tls() {
1664        endpoint.starts_with("https://")
1665    } else {
1666        endpoint.starts_with("https://") || endpoint.starts_with("http://")
1667    }
1668}
1669
1670#[cfg(test)]
1671mod tests {
1672    use super::*;
1673
1674    #[test]
1675    fn a_typed_endpoint_runs_where_its_address_says() {
1676        let at = EndpointLocation::of_endpoint;
1677        assert_eq!(
1678            at("http://127.0.0.1:8000/v1"),
1679            Some(EndpointLocation::ThisDevice)
1680        );
1681        assert_eq!(
1682            at("http://localhost:4000"),
1683            Some(EndpointLocation::ThisDevice)
1684        );
1685        assert_eq!(
1686            at("http://[::1]:8080/v1"),
1687            Some(EndpointLocation::ThisDevice)
1688        );
1689        assert_eq!(
1690            at("http://192.168.1.20:8000/v1"),
1691            Some(EndpointLocation::PrivateNetwork)
1692        );
1693        assert_eq!(
1694            at("http://gpu-box.local:8000/v1"),
1695            Some(EndpointLocation::PrivateNetwork)
1696        );
1697        assert_eq!(
1698            at("http://your-server:8000/v1"),
1699            Some(EndpointLocation::PrivateNetwork)
1700        );
1701        assert_eq!(
1702            at("https://api.z.ai/api/anthropic"),
1703            Some(EndpointLocation::Hosted)
1704        );
1705        assert_eq!(at("http://8.8.8.8/v1"), Some(EndpointLocation::Hosted));
1706        assert_eq!(at("not an address"), None);
1707    }
1708
1709    #[test]
1710    fn an_agent_plans_with_its_own_model_and_otherwise_the_default() {
1711        let mut first = ProviderProfile::hosted(ProviderProtocol::Anthropic);
1712        first.models = vec![ModelDescriptor::new("large"), ModelDescriptor::new("small")];
1713        first.default_model = Some("large".into());
1714        let mut second = ProviderProfile::local_vllm();
1715        second.models = vec![ModelDescriptor::new("local")];
1716        let mut config = ProviderConfig {
1717            default_profile: Some(first.id.clone()),
1718            profiles: vec![first.clone(), second.clone()],
1719            ..Default::default()
1720        };
1721        let chosen = |config: &ProviderConfig, agent| {
1722            config
1723                .selection_for(agent)
1724                .map(|(profile, model)| (profile.id.clone(), model.id.clone()))
1725        };
1726        assert_eq!(
1727            chosen(&config, "writer"),
1728            Some((first.id.clone(), "large".into()))
1729        );
1730
1731        let local = AgentModel {
1732            profile: second.id.clone(),
1733            model: "local".into(),
1734        };
1735        config
1736            .set_agent_model("writer", Some(local.clone()))
1737            .unwrap();
1738        assert_eq!(
1739            chosen(&config, "writer"),
1740            Some((second.id.clone(), "local".into()))
1741        );
1742        assert_eq!(
1743            chosen(&config, "other"),
1744            Some((first.id.clone(), "large".into()))
1745        );
1746        let unknown = AgentModel {
1747            profile: second.id.clone(),
1748            model: "large".into(),
1749        };
1750        assert!(config.set_agent_model("writer", Some(unknown)).is_err());
1751
1752        let (stored, hosted) = config.clone().stored();
1753        assert_eq!(stored.agent_models["writer"], local);
1754        assert_eq!(
1755            ProviderConfig::from_stored(stored, hosted).agent_models,
1756            config.agent_models
1757        );
1758
1759        // A switched-off provider is not swapped for another one.
1760        config.profiles[1].enabled = false;
1761        assert_eq!(chosen(&config, "writer"), None);
1762        config.profiles[1].enabled = true;
1763
1764        // A model the provider no longer offers is forgotten, as is every
1765        // choice of a removed provider; the agent follows the default again.
1766        config.profiles[1].models.clear();
1767        assert!(config.clone().sanitised().agent_models.is_empty());
1768        config.remove(&second.id);
1769        assert!(config.agent_models.is_empty());
1770        config.set_agent_model("writer", None).unwrap();
1771        assert_eq!(chosen(&config, "writer"), Some((first.id, "large".into())));
1772    }
1773
1774    #[test]
1775    fn a_kind_of_interaction_without_a_choice_follows_the_default() {
1776        let mut local = ProviderProfile::local_vllm();
1777        local.models = vec![ModelDescriptor::new("small")];
1778        let mut hosted = ProviderProfile::hosted(ProviderProtocol::Anthropic);
1779        hosted.models = vec![ModelDescriptor::new("large")];
1780        hosted.default_model = Some("large".into());
1781        let mut config = ProviderConfig {
1782            default_profile: Some(hosted.id.clone()),
1783            profiles: vec![local.clone(), hosted],
1784            ..Default::default()
1785        };
1786        assert!(config.interaction_selection(Interaction::OneShot).is_none());
1787        config
1788            .set_interaction_model(
1789                Interaction::OneShot,
1790                Some(AgentModel {
1791                    profile: local.id.clone(),
1792                    model: "small".into(),
1793                }),
1794            )
1795            .unwrap();
1796        let chosen = config.interaction_selection(Interaction::OneShot);
1797        assert_eq!(chosen.map(|(_, model)| model.id.as_str()), Some("small"));
1798        assert!(
1799            config.interaction_selection(Interaction::Task).is_none(),
1800            "a kind keeps no choice of another kind"
1801        );
1802        // A switched-off provider is not swapped for another one.
1803        config.profiles[0].enabled = false;
1804        assert!(config.interaction_selection(Interaction::OneShot).is_none());
1805        config.profiles[0].enabled = true;
1806        // A removed provider takes its choices with it.
1807        config.remove(&local.id);
1808        assert!(config.interaction_models.is_empty());
1809        // A choice the provider no longer offers is forgotten, and a kind
1810        // this build does not know is not kept.
1811        config.interaction_models.insert(
1812            Interaction::Task.id().into(),
1813            AgentModel {
1814                profile: "gone".into(),
1815                model: "large".into(),
1816            },
1817        );
1818        config
1819            .interaction_models
1820            .insert("an-older-kind".into(), AgentModel::default());
1821        let stored = serde_json::to_value(config.clone().sanitised()).unwrap();
1822        assert!(stored.get("interaction_models").is_none());
1823        assert_eq!(Interaction::from_id("one_shot"), Some(Interaction::OneShot));
1824        assert_eq!(Interaction::from_id("an-older-kind"), None);
1825    }
1826
1827    #[test]
1828    fn model_request_limits_preserve_legacy_and_validate_runtime_room() {
1829        let legacy = ModelDescriptor::new("m");
1830        assert!(
1831            serde_json::to_value(&legacy)
1832                .unwrap()
1833                .get("request_limits")
1834                .is_none()
1835        );
1836        let mut profile = ProviderProfile::local_vllm();
1837        profile.models = vec![legacy];
1838        let mut config = ProviderConfig {
1839            profiles: vec![profile],
1840            default_profile: None,
1841            ..Default::default()
1842        };
1843        for (output, context, source, valid) in [
1844            (512, Some(4096), Some(262_144), true),
1845            (512, None, None, true),
1846            (0, Some(4096), None, false),
1847            (65_537, None, None, false),
1848            (4096, Some(4096), None, false),
1849            (512, Some(1_048_577), None, false),
1850            (512, Some(8192), Some(4096), false),
1851        ] {
1852            config.profiles[0].models[0].context_window = source;
1853            config.profiles[0].models[0].request_limits = Some(ModelRequestLimits {
1854                max_output_tokens: output,
1855                runtime_context_tokens: context,
1856                plan_timeout_ms: None,
1857            });
1858            assert_eq!(config.validation_errors().is_empty(), valid);
1859        }
1860        for (timeout, valid) in [
1861            (None, true),
1862            (Some(1), true),
1863            (Some(900_000), true),
1864            (Some(0), false),
1865            (Some(900_001), false),
1866        ] {
1867            let limits = ModelRequestLimits {
1868                max_output_tokens: 512,
1869                runtime_context_tokens: Some(4096),
1870                plan_timeout_ms: timeout,
1871            };
1872            assert_eq!(limits.validate(None).is_ok(), valid);
1873            if timeout.is_none() {
1874                assert_eq!(
1875                    serde_json::to_value(&limits).unwrap(),
1876                    serde_json::json!({"max_output_tokens":512,"runtime_context_tokens":4096})
1877                );
1878            }
1879        }
1880        for malformed in [
1881            serde_json::json!(true),
1882            serde_json::json!("1000"),
1883            serde_json::json!(-1),
1884        ] {
1885            assert!(
1886                serde_json::from_value::<ModelRequestLimits>(serde_json::json!({
1887                "max_output_tokens":512,"plan_timeout_ms":malformed}))
1888                .is_err()
1889            );
1890        }
1891        assert!(
1892            serde_json::from_value::<ModelRequestLimits>(
1893                serde_json::json!({"max_output_tokens":false})
1894            )
1895            .is_err()
1896        );
1897        assert!(
1898            serde_json::from_value::<ModelRequestLimits>(
1899                serde_json::json!({"max_output_tokens":512,"hidden_override":true})
1900            )
1901            .is_err()
1902        );
1903    }
1904
1905    #[test]
1906    fn request_shape_is_profile_configuration_not_host_inference() {
1907        let mut profile = ProviderProfile::hosted(ProviderProtocol::OpenAiCompatible);
1908        profile.label = "OpenRouter".into();
1909        profile.endpoint = "https://openrouter.ai/api/v1".into();
1910        profile.models = vec![ModelDescriptor::new("openai/gpt-oss-safeguard-20b")];
1911        profile.token_limit_param = Some(TokenLimitParam::MaxTokens);
1912        profile.reasoning = Some(ReasoningSetting {
1913            param: ReasoningParam::ReasoningObject,
1914            effort: "low".into(),
1915        });
1916        let config = ProviderConfig {
1917            profiles: vec![profile.clone()],
1918            default_profile: None,
1919            ..Default::default()
1920        };
1921        assert!(config.validation_errors().is_empty());
1922        let encoded = serde_json::to_value(&config).unwrap();
1923        assert_eq!(encoded["profiles"][0]["token_limit_param"], "max_tokens");
1924        assert_eq!(
1925            encoded["profiles"][0]["reasoning"],
1926            serde_json::json!({"param": "reasoning.effort", "effort": "low"})
1927        );
1928        let decoded: ProviderConfig = serde_json::from_value(encoded).unwrap();
1929        assert_eq!(decoded, config);
1930
1931        let mut invalid = profile.clone();
1932        invalid.reasoning = Some(ReasoningSetting {
1933            param: ReasoningParam::ReasoningEffort,
1934            effort: "maximal".into(),
1935        });
1936        let config = ProviderConfig {
1937            profiles: vec![invalid],
1938            default_profile: None,
1939            ..Default::default()
1940        };
1941        assert_eq!(config.validation_errors().len(), 1);
1942        let mut omitted = profile.clone();
1943        omitted.reasoning = Some(ReasoningSetting {
1944            param: ReasoningParam::Omit,
1945            effort: String::new(),
1946        });
1947        let config = ProviderConfig {
1948            profiles: vec![omitted],
1949            default_profile: None,
1950            ..Default::default()
1951        };
1952        assert!(config.validation_errors().is_empty());
1953
1954        for bad in ["messages", "Stream", ""] {
1955            let mut invalid = profile.clone();
1956            invalid.omit_params = vec![bad.into()];
1957            let config = ProviderConfig {
1958                profiles: vec![invalid],
1959                default_profile: None,
1960                ..Default::default()
1961            };
1962            assert_eq!(config.validation_errors().len(), 1, "{bad:?}");
1963        }
1964        let mut cerebras = profile.clone();
1965        cerebras.omit_params = vec!["stream_options".into(), "parallel_tool_calls".into()];
1966        let config = ProviderConfig {
1967            profiles: vec![cerebras],
1968            default_profile: None,
1969            ..Default::default()
1970        };
1971        assert!(config.validation_errors().is_empty());
1972
1973        // Hosted endpoints still require TLS, whatever the host.
1974        let mut plain = profile;
1975        plain.endpoint = "http://openrouter.ai/api/v1".into();
1976        let config = ProviderConfig {
1977            profiles: vec![plain],
1978            default_profile: None,
1979            ..Default::default()
1980        };
1981        assert!(!config.validation_errors().is_empty());
1982        // Absent fields keep older settings documents byte-compatible.
1983        let minimal = serde_json::to_value(ProviderProfile::local_vllm()).unwrap();
1984        assert!(minimal.get("reasoning").is_none() && minimal.get("token_limit_param").is_none());
1985    }
1986
1987    /// Local vLLM is OpenAI-compatible and plainly local, hosted profiles hold only a vault
1988    /// reference, a hosted HTTP endpoint is rejected but loopback HTTP is not, and a bad default is
1989    /// not active.
1990    #[test]
1991    fn provider_profiles_are_plainly_local_or_vault_backed_https() {
1992        // Phase: local_vllm_is_openai_compatible_and_plainly_local.
1993        {
1994            let profile = ProviderProfile::local_vllm();
1995            assert_eq!(profile.protocol, ProviderProtocol::OpenAiCompatible);
1996            assert_eq!(profile.location, EndpointLocation::ThisDevice);
1997            assert!(profile.endpoint.starts_with("http://127.0.0.1"));
1998            assert!(profile.is_local_vllm_candidate());
1999            assert!(profile.credential.is_none());
2000        }
2001
2002        // Phase: hosted_profiles_hold_only_a_vault_reference.
2003        {
2004            let profile = ProviderProfile::hosted(ProviderProtocol::Anthropic);
2005            let json = serde_json::to_string(&profile).unwrap();
2006            assert!(json.contains("tilo.secret-service"));
2007            assert!(json.contains("agent-provider/"));
2008            assert!(!json.contains("sk-ant-"));
2009            assert!(!json.contains("api_key\":\""));
2010        }
2011
2012        // Phase: hosted_http_endpoint_is_rejected_but_loopback_http_is_not.
2013        {
2014            let mut profile = ProviderProfile::hosted(ProviderProtocol::Anthropic);
2015            profile.endpoint = "http://api.example.test".into();
2016            let config = ProviderConfig {
2017                profiles: vec![profile],
2018                ..ProviderConfig::default()
2019            };
2020            assert!(!config.validation_errors().is_empty());
2021            let local = ProviderConfig {
2022                profiles: vec![ProviderProfile::local_vllm()],
2023                ..ProviderConfig::default()
2024            };
2025            assert!(local.validation_errors().is_empty());
2026        }
2027
2028        // Phase: bad_default_is_not_active.
2029        {
2030            let config = ProviderConfig {
2031                default_profile: Some("gone".into()),
2032                profiles: vec![ProviderProfile::local_vllm()],
2033                ..Default::default()
2034            };
2035            assert!(config.active_profile().is_none());
2036            assert!(
2037                config
2038                    .validation_errors()
2039                    .iter()
2040                    .any(|issue| issue.profile_id == "default")
2041            );
2042        }
2043    }
2044
2045    /// Settings written before sign-in existed read unchanged, a sign-in
2046    /// round-trips, and a profile without one writes no new field.
2047    #[test]
2048    fn sign_in_profiles_are_backward_compatible_settings() {
2049        let older = serde_json::json!({
2050            "profiles": [{
2051                "id": "p", "label": "OpenRouter", "protocol": "open_ai_compatible",
2052                "endpoint": "https://openrouter.ai/api/v1", "location": "hosted",
2053                "credential": {"vault": "tilo.secret-service", "locator": "agent-provider/p/api-key"},
2054                "enabled": true, "models": [{"id": "m"}], "default_model": "m"
2055            }],
2056            "default_profile": "p"
2057        });
2058        let config: ProviderConfig = serde_json::from_value(older).unwrap();
2059        assert_eq!(config.profiles.len(), 1);
2060        assert!(config.profiles[0].sign_in.is_none());
2061        assert!(config.validation_errors().is_empty());
2062        let written = serde_json::to_value(&config).unwrap();
2063        assert!(written["profiles"][0].get("sign_in").is_none());
2064
2065        let vertex = ProviderProfile::google_vertex("tilo-509618", "global", "gemini-4-argon");
2066        assert!(vertex.credential.is_none());
2067        assert!(vertex.signs_in_with_google());
2068        assert_eq!(
2069            vertex.default_model.as_deref(),
2070            Some("google/gemini-4-argon")
2071        );
2072        assert_eq!(vertex.models[0].label, "gemini-4-argon");
2073        let config = ProviderConfig {
2074            profiles: vec![vertex.clone()],
2075            default_profile: Some(vertex.id.clone()),
2076            ..Default::default()
2077        };
2078        assert!(config.validation_errors().is_empty());
2079        let written = serde_json::to_value(&config).unwrap();
2080        assert_eq!(
2081            written["profiles"][0]["sign_in"],
2082            serde_json::json!({"issuer": "google", "billing_project": "tilo-509618"})
2083        );
2084        assert_eq!(
2085            serde_json::from_value::<ProviderConfig>(written).unwrap(),
2086            config
2087        );
2088
2089        for (credential, issuer, project, issues) in [
2090            (true, GOOGLE_SIGN_IN, Some("tilo-509618"), 1),
2091            (false, "elsewhere", None, 1),
2092            (false, GOOGLE_SIGN_IN, Some("Not A Project"), 1),
2093            (false, "chatgpt", None, 0),
2094            (false, "chatgpt", Some("tilo-509618"), 1),
2095        ] {
2096            let mut invalid = vertex.clone();
2097            invalid.credential = credential.then(|| SecretReference::provider_api_key(&invalid.id));
2098            invalid.sign_in = Some(SignInCredential {
2099                issuer: issuer.into(),
2100                billing_project: project.map(Into::into),
2101                kept: None,
2102            });
2103            let config = ProviderConfig {
2104                profiles: vec![invalid],
2105                default_profile: None,
2106                ..Default::default()
2107            };
2108            assert_eq!(
2109                config.validation_errors().len(),
2110                issues,
2111                "{issuer} {project:?}"
2112            );
2113        }
2114        // An issuer a newer build added still reads: the profile is kept
2115        // and shown unsupported, the rest of the configuration intact.
2116        let newer = serde_json::json!({"profiles": [{
2117            "id": "n", "label": "Newer", "endpoint": "https://example.com/v1",
2118            "sign_in": {"issuer": "from-the-future"}
2119        }]});
2120        let config: ProviderConfig = serde_json::from_value(newer).unwrap();
2121        assert_eq!(config.profiles[0].sign_in_issuer(), None);
2122        for issuer in SignInIssuer::ALL {
2123            assert_eq!(SignInIssuer::from_id(issuer.id()), Some(issuer));
2124        }
2125        assert_ne!(sign_in_grant_id("p"), "agent-provider-p");
2126    }
2127
2128    #[test]
2129    fn vertex_endpoints_name_their_project_and_location() {
2130        assert_eq!(
2131            vertex_endpoint("tilo-509618", "global"),
2132            "https://aiplatform.googleapis.com/v1/projects/tilo-509618/locations/global/endpoints/openapi"
2133        );
2134        assert_eq!(
2135            vertex_endpoint("p-1", "europe-west4"),
2136            "https://europe-west4-aiplatform.googleapis.com/v1/projects/p-1/locations/europe-west4/endpoints/openapi"
2137        );
2138        for (project, location) in [("tilo-509618", "global"), ("example.com:p", "us-central1")] {
2139            assert_eq!(
2140                vertex_target(&vertex_endpoint(project, location)),
2141                Some((project.to_string(), location.to_string()))
2142            );
2143        }
2144        assert_eq!(
2145            vertex_target(&format!(
2146                "{}/chat/completions",
2147                vertex_endpoint("p", "global")
2148            )),
2149            Some(("p".into(), "global".into()))
2150        );
2151        // A regional location on the global host, or any other endpoint, is
2152        // not a Vertex target.
2153        assert_eq!(
2154            vertex_target(
2155                "https://aiplatform.googleapis.com/v1/projects/p/locations/us-central1/endpoints/openapi"
2156            ),
2157            None
2158        );
2159        assert_eq!(vertex_target("https://api.openai.com/v1"), None);
2160        assert_eq!(vertex_model_id("gemini-4-argon"), "google/gemini-4-argon");
2161        assert_eq!(vertex_model_id(" meta/llama-4 "), "meta/llama-4");
2162        assert!(is_vertex_location("us-east5") && !is_vertex_location("US"));
2163        assert!(!is_vertex_location("a/b") && !is_vertex_location(""));
2164        assert!(is_cloud_project_id("tilo-509618") && !is_cloud_project_id("a/b"));
2165    }
2166
2167    #[test]
2168    fn save_round_trip_preserves_other_settings_and_never_needs_a_secret() {
2169        let dir = tempfile::tempdir().unwrap();
2170        let path = settings_store::profile(dir.path());
2171        let mut existing = Map::new();
2172        existing.insert("appearance".into(), serde_json::json!({"theme": "dark"}));
2173        settings_store::SettingsSource::update_section(
2174            &path,
2175            "appearance",
2176            existing
2177                .remove("appearance")
2178                .unwrap()
2179                .as_object()
2180                .cloned()
2181                .unwrap(),
2182        )
2183        .unwrap();
2184        let profile = ProviderProfile::hosted(ProviderProtocol::OpenAiCompatible);
2185        let config = ProviderConfig {
2186            default_profile: Some(profile.id.clone()),
2187            profiles: vec![profile],
2188            ..Default::default()
2189        };
2190        config.save_in(&path).unwrap();
2191        assert_eq!(ProviderConfig::load_in(&path), config);
2192        let body =
2193            serde_json::Value::Object(settings_store::SettingsSource::load(&path)).to_string();
2194        assert!(body.contains("appearance"));
2195        assert!(!body.contains("sk-live-secret"));
2196    }
2197
2198    /// A hosted provider is stored apart from the ones on this device, so it
2199    /// roams with the person while a loopback endpoint and the default stay.
2200    #[test]
2201    fn hosted_providers_are_stored_apart_from_this_devices() {
2202        let dir = tempfile::tempdir().unwrap();
2203        let path = settings_store::profile(dir.path());
2204        let hosted = ProviderProfile::hosted(ProviderProtocol::Anthropic);
2205        let local = ProviderProfile::local_vllm();
2206        let config = ProviderConfig {
2207            default_profile: Some(local.id.clone()),
2208            profiles: vec![local.clone(), hosted.clone()],
2209            ..Default::default()
2210        };
2211        config.save_in(&path).unwrap();
2212        assert_eq!(ProviderConfig::load_in(&path), config);
2213        let document = settings_store::SettingsSource::load(&path);
2214        let stored: ProviderConfig =
2215            serde_json::from_value(document[SETTINGS_SECTION][CONFIG_KEY].clone()).unwrap();
2216        let roaming: HostedProfiles =
2217            serde_json::from_value(document[HOSTED_SECTION][HOSTED_KEY].clone()).unwrap();
2218        assert_eq!(stored.profiles, vec![local]);
2219        assert_eq!(stored.default_profile, config.default_profile);
2220        assert_eq!(roaming.profiles, vec![hosted]);
2221    }
2222}
2223
2224/// Typed local-speech configuration and its private worker wire format.
2225pub mod speech;
2226
2227#[cfg(test)]
2228mod loopback_tests {
2229    use super::*;
2230
2231    #[test]
2232    fn on_device_work_never_routes_to_a_lan_or_hosted_endpoint() {
2233        assert!(loopback_http_endpoint("http://127.0.0.1:8123/v1"));
2234        assert!(loopback_http_endpoint("http://[::1]:8123/v1"));
2235        assert!(!loopback_http_endpoint("http://192.168.1.20:8123/v1"));
2236        assert!(!loopback_http_endpoint("https://models.example.test/v1"));
2237        assert!(!loopback_http_endpoint(
2238            "http://localhost.evil.test:8123/v1"
2239        ));
2240    }
2241}