1use std::collections::{BTreeMap, BTreeSet};
12
13use serde::{Deserialize, Serialize};
14use serde_json::{Map, Value};
15
16pub mod capabilities;
18pub mod local;
20pub mod management;
21pub mod presets;
23pub mod protocol;
24pub mod transform;
26pub mod wire;
27
28pub const SETTINGS_SECTION: &str = "agent_providers";
31pub const HOSTED_SECTION: &str = "agent_providers_person";
34const CONFIG_KEY: &str = "config";
37const HOSTED_KEY: &str = "hosted";
39
40#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(remote = "Self", rename_all = "snake_case")]
43pub enum ProviderProtocol {
44 #[default]
46 OpenAiCompatible,
47 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(remote = "Self", rename_all = "snake_case")]
69pub enum EndpointLocation {
70 #[default]
72 Hosted,
73 ThisDevice,
75 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 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
138#[serde(remote = "Self")]
139pub struct SecretReference {
140 pub vault: String,
142 pub locator: String,
144}
145
146settings_store::read_through_json_value!(SecretReference);
147
148pub 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 pub fn workspace_vault(reference: &str) -> Self {
163 Self {
164 vault: WORKSPACE_VAULT.to_owned(),
165 locator: reference.to_owned(),
166 }
167 }
168
169 #[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
184pub const GOOGLE_SIGN_IN: &str = "google";
186
187#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
190pub enum SignInIssuer {
191 Google,
193 ChatGpt,
197 GitHubCopilot,
200 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 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 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
243#[serde(remote = "Self")]
244pub struct SignInCredential {
245 pub issuer: String,
249 #[serde(default, skip_serializing_if = "Option::is_none")]
254 pub billing_project: Option<String>,
255 #[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 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 pub fn issuer(&self) -> Option<SignInIssuer> {
283 SignInIssuer::from_id(&self.issuer)
284 }
285}
286
287pub fn sign_in_grant_id(profile_id: &str) -> String {
290 format!("agent-model-grant-{profile_id}")
291}
292
293pub const VERTEX_DEFAULT_LOCATION: &str = "global";
296pub const VERTEX_DEFAULT_MODEL: &str = "gemini-4-argon";
298
299pub 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
309pub 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
320pub 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
332pub 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
349pub 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
364#[serde(remote = "Self", default)]
365pub struct ModelDescriptor {
366 pub id: String,
368 pub label: String,
370 pub context_window: Option<u32>,
372 #[serde(default, skip_serializing_if = "Option::is_none")]
377 pub max_output_tokens: Option<u32>,
378 #[serde(skip_serializing_if = "Option::is_none")]
381 pub request_limits: Option<ModelRequestLimits>,
382 #[serde(skip_serializing_if = "Option::is_none")]
386 pub revision: Option<String>,
387 pub vision: bool,
391 #[serde(default)]
395 pub face_recognition: bool,
396 pub tool_calling: bool,
402 #[serde(skip_serializing_if = "CapabilitySource::is_unknown")]
406 pub capabilities_from: CapabilitySource,
407}
408
409settings_store::read_through_json_value!(ModelDescriptor);
410
411#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
414#[serde(remote = "Self", rename_all = "snake_case")]
415pub enum CapabilitySource {
416 Provider,
418 Family,
420 Person,
422 #[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#[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 #[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 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 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 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 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 #[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 #[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#[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 #[serde(skip_serializing_if = "Option::is_none")]
575 pub credential: Option<SecretReference>,
576 #[serde(skip_serializing_if = "Option::is_none")]
580 pub sign_in: Option<SignInCredential>,
581 pub enabled: bool,
582 pub models: Vec<ModelDescriptor>,
583 #[serde(skip_serializing_if = "Option::is_none")]
586 pub default_model: Option<String>,
587 #[serde(skip_serializing_if = "Option::is_none")]
591 pub token_limit_param: Option<TokenLimitParam>,
592 #[serde(skip_serializing_if = "Option::is_none")]
596 pub reasoning: Option<ReasoningSetting>,
597 #[serde(skip_serializing_if = "Vec::is_empty")]
602 pub omit_params: Vec<String>,
603 #[serde(skip_serializing_if = "Option::is_none")]
609 pub openai_api: Option<OpenAiApi>,
610 #[serde(skip_serializing_if = "Option::is_none")]
615 pub key_header: Option<KeyHeader>,
616 #[serde(skip_serializing_if = "Option::is_none")]
621 pub models_path: Option<String>,
622 #[serde(skip_serializing_if = "Vec::is_empty")]
630 pub headers: Vec<ProviderHeader>,
631}
632
633settings_store::read_through_json_value!(ProviderProfile);
634
635#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
637pub struct ProviderHeader {
638 pub name: String,
639 pub value: String,
640}
641
642const 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
687#[serde(remote = "Self")]
688pub enum KeyHeader {
689 #[serde(rename = "authorization")]
691 Bearer,
692 #[serde(rename = "x-api-key")]
694 XApiKey,
695 #[serde(rename = "api-key")]
697 ApiKey,
698}
699
700settings_store::read_through_json_value!(KeyHeader);
701
702impl KeyHeader {
703 pub const fn of(protocol: ProviderProtocol) -> Self {
705 match protocol {
706 ProviderProtocol::OpenAiCompatible => Self::Bearer,
707 ProviderProtocol::Anthropic => Self::XApiKey,
708 }
709 }
710
711 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
721pub const REQUIRED_PARAMS: &[&str] = &["model", "messages", "tools", "tool_choice"];
723
724#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
747#[serde(remote = "Self", rename_all = "snake_case")]
748pub enum OpenAiApi {
749 ChatCompletions,
751 Responses,
753}
754
755settings_store::read_through_json_value!(OpenAiApi);
756
757#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
759#[serde(remote = "Self")]
760pub enum ReasoningParam {
761 #[serde(rename = "reasoning_effort")]
763 ReasoningEffort,
764 #[serde(rename = "reasoning.effort")]
766 ReasoningObject,
767 #[serde(rename = "none")]
769 Omit,
770}
771
772settings_store::read_through_json_value!(ReasoningParam);
773
774#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
776#[serde(remote = "Self")]
777pub struct ReasoningSetting {
778 pub param: ReasoningParam,
779 #[serde(default, skip_serializing_if = "String::is_empty")]
783 pub effort: String,
784}
785
786settings_store::read_through_json_value!(ReasoningSetting);
787
788pub 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 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 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 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 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 #[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 pub fn signs_in_with_google(&self) -> bool {
935 self.sign_in_issuer() == Some(SignInIssuer::Google)
936 }
937
938 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#[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#[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#[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#[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#[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 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
1046 pub agent_models: BTreeMap<String, AgentModel>,
1047 #[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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
1075#[serde(remote = "Self", rename_all = "snake_case")]
1076pub enum Interaction {
1077 OneShot,
1080 Task,
1082 Subtask,
1084 Request,
1086 Classifier,
1088 Dictation,
1090}
1091
1092settings_store::read_through_json_value!(Interaction);
1093
1094impl Interaction {
1095 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 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 #[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 #[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 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 pub fn load_in(source: &dyn settings_store::SettingsSource) -> Self {
1176 Self::from_document(&source.load())
1177 }
1178
1179 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 #[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 #[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 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 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 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 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(¶m.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 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 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 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 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 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 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 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 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 #[must_use]
1540 pub fn sanitised(mut self) -> Self {
1541 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
1566fn 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
1580pub const NO_TOOL_CALLING: &str =
1582 "This model does not call tools, so an agent cannot plan with it.";
1583
1584#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1589pub enum ProviderChoiceError {
1590 NotAModel,
1593 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#[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
1624fn 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 config.profiles[1].enabled = false;
1761 assert_eq!(chosen(&config, "writer"), None);
1762 config.profiles[1].enabled = true;
1763
1764 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 config.profiles[0].enabled = false;
1804 assert!(config.interaction_selection(Interaction::OneShot).is_none());
1805 config.profiles[0].enabled = true;
1806 config.remove(&local.id);
1808 assert!(config.interaction_models.is_empty());
1809 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 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 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 #[test]
1991 fn provider_profiles_are_plainly_local_or_vault_backed_https() {
1992 {
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 {
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 {
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 {
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 #[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 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 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 #[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
2224pub 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}