lm15 1.0.0-rc.7

One request and response model for every LLM provider (OpenAI, Anthropic, Gemini, xAI, Groq, Bedrock, Azure, Vertex, local servers), with visible adaptations. Implements the lm15 contract.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
//! A dialect reaches a cloud door through a host (spec/auth.md AUTH-10;
//! `lm15/cloud/hosts.py`). Three pure functions, in the order the emit
//! path calls them:
//!
//! 1. [`resolve_settings`] — the host's settings from the caller's values,
//!    then the environment (when the caller passes one; a bare adapter is
//!    given its settings explicitly, like its credential), then defaults.
//!    `region` and `resource` have no default on purpose.
//! 2. [`render_base_url`] — the base URL for the settings;
//!    `{location_host}` is derived from `location`.
//! 3. [`finish_request`] — the host's closed set of rewrites on the
//!    dialect-built request (endpoint path override, model into the path,
//!    `anthropic_version` into the body, required headers, `query-key`).
//!    Signing happens after serialization, in [`crate::wire::emit`].

use std::collections::BTreeMap;

use serde_json::Value;

use super::percent;
use crate::auth::{
    AccessPolicy, AnthropicVersionIn, AuthScheme, HostSpec, ModelPlacement, StreamFraming,
};
use crate::errors::{ErrorMeta, Lm15Error};

/// Resolved host settings by name (AUTH-10 `settings`).
pub type HostSettings = BTreeMap<String, String>;

fn not_configured(provider: &str, message: String) -> Lm15Error {
    let mut meta = ErrorMeta::new(message);
    meta.provider = Some(provider.to_string());
    Lm15Error::NotConfiguredError(meta)
}

/// Explicit values, then `env` (when given), then defaults
/// (`lm15/cloud/hosts.py:43-81`). A required setting with no value is a
/// `NotConfiguredError` naming the variable; an unknown setting name is a
/// `ConfigurationError` (the reference raises `ValueError`). With no host
/// the caller's settings pass through untouched.
pub fn resolve_settings(
    host: Option<&HostSpec>,
    given: &HostSettings,
    env: Option<&BTreeMap<String, String>>,
    provider: &str,
) -> Result<HostSettings, Lm15Error> {
    resolve_settings_with_endpoint(host, given, env, provider, None)
}

/// A setting the cloud's own configuration supplies (AUTH-10, amended
/// 2026-09-26).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProfileValue {
    /// The value and its origin in the AUTH-10 `from` vocabulary
    /// (`aws-profile`, `adc-env`, `env:CLOUDSDK_CORE_PROJECT`,
    /// `gcloud-config`, `adc-file`).
    Found(String, String),
    /// Only the metadata server could answer: the adapter asks it in its
    /// async `prepare` step, before the first request; the offline doctor
    /// reports it unprobed.
    Metadata,
}

/// Resolve settings while allowing an endpoint to replace root-only settings.
pub fn resolve_settings_with_endpoint(
    host: Option<&HostSpec>,
    given: &HostSettings,
    env: Option<&BTreeMap<String, String>>,
    provider: &str,
    endpoint: Option<&str>,
) -> Result<HostSettings, Lm15Error> {
    let mut trace = SettingsTrace::default();
    resolve_settings_traced(host, given, env, provider, endpoint, &mut trace)
}

/// Where each setting came from, and what could not be resolved yet
/// (AUTH-10, amended 2026-09-26).
#[derive(Debug, Clone, Default)]
pub struct SettingsTrace {
    /// In: the origin of values the caller injected into `given` from the
    /// cloud's own configuration (`adc-env`, `gcloud-config`, …); any
    /// other `given` value is `explicit`.
    pub injected: BTreeMap<String, String>,
    /// In: names the caller will supply later (the metadata server, asked
    /// in `prepare`); not required now, recorded `unprobed:metadata`.
    pub pending: std::collections::BTreeSet<String>,
    /// In: collect missing-setting errors in `problems` instead of
    /// returning the first (the doctor), and return what did resolve.
    pub collect: bool,
    /// Out: each setting's origin — `explicit`, `env:<VAR>`, an injected
    /// origin, `default`, `unprobed:metadata`, `missing`.
    pub sources: BTreeMap<String, String>,
    /// Out (with `collect`): the missing-setting errors.
    pub problems: Vec<Lm15Error>,
}

/// [`resolve_settings_with_endpoint`] that records each setting's origin.
pub fn resolve_settings_traced(
    host: Option<&HostSpec>,
    given: &HostSettings,
    env: Option<&BTreeMap<String, String>>,
    provider: &str,
    endpoint: Option<&str>,
    trace: &mut SettingsTrace,
) -> Result<HostSettings, Lm15Error> {
    if let Some(endpoint) = endpoint {
        join_endpoint(endpoint, "")?;
    }
    let Some(host) = host else {
        return Ok(given.clone());
    };
    let mut remaining = given.clone();
    let mut out = HostSettings::new();
    let mut missing: Option<Lm15Error> = None;
    for setting in host.settings {
        let mut value = remaining.remove(setting.name).filter(|v| !v.is_empty());
        let mut origin = value.as_ref().map(|_| {
            trace
                .injected
                .get(setting.name)
                .cloned()
                .unwrap_or_else(|| "explicit".into())
        });
        if value.is_none() {
            if let Some(env) = env {
                if let Some((var, v)) = setting.env.iter().find_map(|var| {
                    env.get(*var)
                        .filter(|v| !v.is_empty())
                        .map(|v| (*var, v.clone()))
                }) {
                    value = Some(v);
                    origin = Some(format!("env:{var}"));
                }
            }
        }
        if value.is_none() {
            if let Some(default) = setting.default {
                value = Some(default.to_string());
                origin = Some("default".into());
            }
        }
        if value.is_none() && trace.pending.contains(setting.name) {
            trace
                .sources
                .insert(setting.name.into(), "unprobed:metadata".into());
            continue;
        }
        let Some(value) = value else {
            let placeholder = format!("{{{}}}", setting.name);
            let (root, path) = split_template(host.base_url);
            let root_only = root.contains(&placeholder)
                && !path.contains(&placeholder)
                && !host
                    .required_headers
                    .iter()
                    .any(|(_, name)| *name == setting.name)
                && !(setting.name == "region" && host.sigv4_service.is_some());
            if endpoint.is_some() && root_only {
                continue;
            }
            let mut hint = if setting.env.is_empty() {
                format!("pass settings={{\"{}\": ...}}", setting.name)
            } else {
                format!("set {}", setting.env.join(" or "))
            };
            if setting.name == "project" {
                // The Google project also comes from gcloud, the credential
                // files and the metadata server; those said nothing (AUTH-10).
                hint.push_str(
                    ", run `gcloud config set project <id>`, or pass settings={\"project\": ...}",
                );
            }
            trace.sources.insert(setting.name.into(), "missing".into());
            if missing.is_none() {
                missing = Some(not_configured(
                    provider,
                    format!(
                        "{provider}: setting {:?} is required and has no default; {hint}",
                        setting.name
                    ),
                ));
            }
            continue;
        };
        trace.sources.insert(
            setting.name.into(),
            origin.unwrap_or_else(|| "explicit".into()),
        );
        out.insert(setting.name.to_string(), value);
    }
    if !remaining.is_empty() {
        let unknown: Vec<&str> = remaining.keys().map(String::as_str).collect();
        let known: Vec<&str> = host.setting_names().collect();
        let mut meta = ErrorMeta::new(format!(
            "{provider}: unknown host setting(s) {unknown:?}; known: {known:?}"
        ));
        meta.provider = Some(provider.to_string());
        return Err(Lm15Error::ConfigurationError(meta));
    }
    if let Some(err) = missing {
        if !trace.collect {
            return Err(err);
        }
        trace.problems.push(err);
    }
    Ok(out)
}

/// Vertex host for a location (`lm15/cloud/hosts.py:84-90`;
/// vertex-locations.md:40-63, :91).
pub fn location_host(location: &str) -> String {
    match location {
        "global" => "aiplatform.googleapis.com".to_string(),
        "us" | "eu" => format!("aiplatform.{location}.rep.googleapis.com"),
        other => format!("{other}-aiplatform.googleapis.com"),
    }
}

fn is_dns_label(value: &str) -> bool {
    !value.is_empty()
        && value
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-')
}

/// The base URL for the settings (`lm15/cloud/hosts.py:93-105`). A setting
/// that lands in a hostname (`region`, `resource`, `location`) must be a
/// DNS label (letters, digits, `-`): anything that could change the
/// authority — `/`, `@`, `?`, `#`, whitespace, `.` — is refused.
/// `project` is percent-encoded (it lands in a path).
pub fn render_base_url(host: &HostSpec, settings: &HostSettings) -> Result<String, Lm15Error> {
    resolve_base_url(host, settings, None)
}

pub fn resolve_base_url(
    host: &HostSpec,
    settings: &HostSettings,
    endpoint: Option<&str>,
) -> Result<String, Lm15Error> {
    let mut values: BTreeMap<&str, String> = BTreeMap::new();
    for (name, value) in settings {
        values.insert(name.as_str(), value.clone());
    }
    for name in ["region", "resource", "location"] {
        if let Some(value) = values.get(name) {
            if !is_dns_label(value) {
                return Err(Lm15Error::not_configured(format!(
                    "host setting {name:?} must be a DNS label"
                )));
            }
        }
    }
    if let Some(project) = values.get("project") {
        values.insert("project", percent::encode(project, b""));
    }
    if let Some(location) = values.get("location") {
        if !values.contains_key("location_host") {
            values.insert("location_host", location_host(location));
        }
    }
    let template = if endpoint.is_some() {
        split_template(host.base_url).1
    } else {
        host.base_url
    };
    let rendered =
        render_template(template, |name| values.get(name).cloned()).map_err(|missing| {
            Lm15Error::not_configured(format!("host base URL needs setting {missing:?}"))
        })?;
    match endpoint {
        Some(endpoint) => join_endpoint(endpoint, &rendered),
        None => Ok(rendered),
    }
}

fn split_template(template: &str) -> (&str, &str) {
    let start = template.find("://").map(|n| n + 3).unwrap_or(0);
    let end = template[start..]
        .find('/')
        .map(|n| n + start)
        .unwrap_or(template.len());
    (&template[..end], &template[end..])
}

pub fn endpoint_from_env<'a>(
    host: &HostSpec,
    env: &'a BTreeMap<String, String>,
) -> Option<(&'static str, &'a str)> {
    host.endpoint_env.iter().find_map(|name| {
        env.get(*name)
            .map(|value| (*name, value.trim()))
            .filter(|(_, value)| !value.is_empty())
    })
}

/// Append a door path once, including endpoints that already carry its prefix.
/// Configuration is validated without echoing a possibly secret-bearing URL.
pub fn join_endpoint(endpoint: &str, path: &str) -> Result<String, Lm15Error> {
    let endpoint = endpoint.trim();
    let bad = || {
        Lm15Error::not_configured(
            "endpoint must be an http(s) URL with a host, without userinfo, query or fragment",
        )
    };
    if endpoint
        .bytes()
        .any(|b| b.is_ascii_control() || b.is_ascii_whitespace() || b == b'\\')
        || endpoint.contains(['?', '#'])
    {
        return Err(bad());
    }
    let (scheme, rest) = endpoint.split_once("://").ok_or_else(bad)?;
    if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") {
        return Err(bad());
    }
    let scheme = scheme.to_ascii_lowercase();
    let (authority, given) = rest.split_once('/').unwrap_or((rest, ""));
    if authority.is_empty() || authority.contains('@') {
        return Err(bad());
    }
    // Authority is ASCII DNS/IPv4 or bracketed IPv6, with an optional numeric port.
    let (host, port) = if authority.starts_with('[') {
        let end = authority.find(']').ok_or_else(bad)?;
        let host = &authority[1..end];
        if host.parse::<std::net::Ipv6Addr>().is_err() {
            return Err(bad());
        }
        let tail = &authority[end + 1..];
        if !tail.is_empty() && !tail.starts_with(':') {
            return Err(bad());
        }
        (host, tail.strip_prefix(':'))
    } else {
        let (host, port) = authority
            .split_once(':')
            .map(|(h, p)| (h, Some(p)))
            .unwrap_or((authority, None));
        if host.is_empty()
            || !host
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-'))
        {
            return Err(bad());
        }
        (host, port)
    };
    if host.is_empty() || port.is_some_and(|p| p.parse::<u16>().is_err()) {
        return Err(bad());
    }
    // Only trailing slashes are normalized. Interior empty segments and
    // percent escapes can be meaningful to a gateway and must stay verbatim.
    let given = given.trim_end_matches('/');
    let door = path.trim_matches('/');
    let overlap = (1..=door.len())
        .rev()
        .find(|&n| {
            door.is_char_boundary(n)
                && (n == door.len() || door.as_bytes()[n] == b'/')
                && given.ends_with(&door[..n])
                && (given.len() == n || given.as_bytes()[given.len() - n - 1] == b'/')
        })
        .unwrap_or(0);
    let joined = if door.is_empty() {
        given.to_string()
    } else if overlap != 0 {
        format!("{}{door}", &given[..given.len() - overlap])
    } else if given.is_empty() {
        door.to_string()
    } else {
        format!("{given}/{door}")
    };
    Ok(format!(
        "{scheme}://{authority}{}",
        if joined.is_empty() {
            String::new()
        } else {
            format!("/{joined}")
        }
    ))
}

/// `str.format(**values)` over `{name}` placeholders; the first missing
/// name is the error.
fn render_template(
    template: &str,
    lookup: impl Fn(&str) -> Option<String>,
) -> Result<String, String> {
    let mut out = String::with_capacity(template.len());
    let mut rest = template;
    while let Some(start) = rest.find('{') {
        out.push_str(&rest[..start]);
        let after = &rest[start + 1..];
        let Some(end) = after.find('}') else {
            out.push_str(&rest[start..]);
            return Ok(out);
        };
        let name = &after[..end];
        match lookup(name) {
            Some(value) => out.push_str(&value),
            None => return Err(name.to_string()),
        }
        rest = &after[end + 1..];
    }
    out.push_str(rest);
    Ok(out)
}

/// The request after the host's rewrites, before serialization.
#[derive(Debug, Clone, PartialEq)]
pub struct FinishedRequest {
    pub url: String,
    pub headers: Vec<(String, String)>,
    pub body: Option<Value>,
    pub params: Vec<(String, String)>,
}

/// The dialect-built request the host finishes.
#[derive(Debug, Clone, PartialEq)]
pub struct HostInput<'a> {
    /// The rendered base URL the request was built against.
    pub base_url: &'a str,
    /// The full URL the dialect built (base URL + its own path).
    pub url: String,
    pub headers: Vec<(String, String)>,
    pub body: Option<Value>,
    pub params: Vec<(String, String)>,
    /// The dialect's endpoint name (`messages`, `responses`,
    /// `chat/completions`, `generateContent`) for `host.paths`.
    pub endpoint: Option<&'a str>,
    pub stream: bool,
    /// The wire model, for `{model}` in a path override.
    pub model: Option<&'a str>,
}

fn remove_header(headers: &mut Vec<(String, String)>, name: &str) {
    headers.retain(|(k, _)| !k.eq_ignore_ascii_case(name));
}

/// Apply the host's rewrites (`lm15/cloud/hosts.py:116-173`). `scheme` is
/// the AUTH-2 selection for the credential in flight (`query-key` puts an
/// `ApiKey` in `?key=`); `key` is that credential's value when the scheme
/// is `query-key`.
pub fn finish_request(
    policy: &AccessPolicy,
    settings: &HostSettings,
    input: HostInput<'_>,
    query_key: Option<&str>,
) -> Result<FinishedRequest, Lm15Error> {
    let HostInput {
        base_url,
        mut url,
        mut headers,
        mut body,
        mut params,
        endpoint,
        stream,
        model,
    } = input;
    let Some(host) = policy.host.as_ref() else {
        return Ok(FinishedRequest {
            url,
            headers,
            body,
            params,
        });
    };
    let provider = policy.provider;

    if host.stream_framing != StreamFraming::Sse && stream {
        let mut meta = ErrorMeta::new(format!(
            "{provider}: {} stream framing is not implemented yet (phase 2)",
            host.stream_framing.as_str()
        ));
        meta.provider = Some(provider.to_string());
        return Err(Lm15Error::UnsupportedFeatureError(meta));
    }

    if let Some(endpoint) = endpoint {
        let stream_key = format!("{endpoint}/stream");
        let key = if stream && host.path_for(&stream_key).is_some() {
            stream_key
        } else {
            endpoint.to_string()
        };
        if let Some(template) = host.path_for(&key) {
            let model = model.unwrap_or("");
            if template.contains("{model}") && model.is_empty() {
                return Err(Lm15Error::ConfigurationError(ErrorMeta::new(format!(
                    "{provider}: endpoint {endpoint:?} needs the model in the path"
                ))));
            }
            let path_model = if endpoint == "generateContent" {
                model.strip_prefix("models/").unwrap_or(model)
            } else {
                model
            };
            let encoded = percent::encode(path_model, b":@");
            let path = template.replace("{model}", &encoded);
            url = format!("{}{path}", base_url.trim_end_matches('/'));
        }
    }

    if let Some(Value::Object(object)) = body.as_mut() {
        if host.model_in == ModelPlacement::Path {
            object.shift_remove("model");
        }
        if let AnthropicVersionIn::Body(version) = host.anthropic_version_in {
            object.insert("anthropic_version".into(), Value::String(version.into()));
            remove_header(&mut headers, "anthropic-version");
        }
    }

    for (name, setting) in host.required_headers {
        let value = settings
            .get(*setting)
            .filter(|v| !v.is_empty())
            .ok_or_else(|| {
                not_configured(
                    provider,
                    format!("{provider}: header {name} needs setting {setting:?}"),
                )
            })?;
        remove_header(&mut headers, name);
        headers.push((name.to_string(), value.clone()));
    }

    if let Some(key) = query_key {
        if policy.auth_scheme.contains(&AuthScheme::QueryKey) {
            params.retain(|(k, _)| k != "key");
            params.push(("key".into(), key.to_string()));
        }
    }

    Ok(FinishedRequest {
        url,
        headers,
        body,
        params,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::auth::{AZURE, BEDROCK_CHAT, VERTEX, VERTEX_ANTHROPIC, VERTEX_EXPRESS};
    use serde_json::json;

    fn settings(pairs: &[(&str, &str)]) -> HostSettings {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect()
    }

    #[test]
    fn config_then_env_then_default() {
        let host = VERTEX.host.as_ref().unwrap();
        let env = settings(&[("GCLOUD_PROJECT", "from-env"), ("GOOGLE_CLOUD_PROJECT", "")]);
        let resolved =
            resolve_settings(Some(host), &HostSettings::new(), Some(&env), "vertex").unwrap();
        assert_eq!(resolved["project"], "from-env");
        assert_eq!(resolved["location"], "global");
        let given = settings(&[("project", "p"), ("location", "us-central1")]);
        let resolved = resolve_settings(Some(host), &given, Some(&env), "vertex").unwrap();
        assert_eq!(resolved["project"], "p");
        assert_eq!(resolved["location"], "us-central1");
    }

    #[test]
    fn region_and_resource_have_no_default() {
        let host = BEDROCK_CHAT.host.as_ref().unwrap();
        let err =
            resolve_settings(Some(host), &HostSettings::new(), None, "bedrock-chat").unwrap_err();
        assert_eq!(err.class_name(), "NotConfiguredError");
        assert!(err.message().contains("AWS_REGION"), "{err}");
        let host = AZURE.host.as_ref().unwrap();
        let err = resolve_settings(Some(host), &HostSettings::new(), None, "azure").unwrap_err();
        assert!(err.message().contains("resource"), "{err}");
        let given = settings(&[("resource", "r")]);
        let resolved = resolve_settings(Some(host), &given, None, "azure").unwrap();
        assert_eq!(
            resolved["authority_host"],
            "https://login.microsoftonline.com"
        );
        assert_eq!(resolved["scope"], "https://ai.azure.com/.default");
    }

    #[test]
    fn unknown_settings_are_refused_and_no_host_passes_through() {
        let host = BEDROCK_CHAT.host.as_ref().unwrap();
        let given = settings(&[("region", "us-east-1"), ("resource", "x")]);
        let err = resolve_settings(Some(host), &given, None, "bedrock-chat").unwrap_err();
        assert_eq!(err.class_name(), "ConfigurationError");
        assert_eq!(
            resolve_settings(None, &given, None, "openai").unwrap(),
            given
        );
    }

    #[test]
    fn renders_templates_and_derives_location_host() {
        let host = VERTEX.host.as_ref().unwrap();
        let url = render_base_url(
            host,
            &settings(&[("project", "my proj"), ("location", "global")]),
        )
        .unwrap();
        assert_eq!(
            url,
            "https://aiplatform.googleapis.com/v1/projects/my%20proj/locations/global/publishers/google"
        );
        let url =
            render_base_url(host, &settings(&[("project", "p"), ("location", "eu")])).unwrap();
        assert!(url.starts_with("https://aiplatform.eu.rep.googleapis.com/"));
        let url = render_base_url(
            host,
            &settings(&[("project", "p"), ("location", "us-central1")]),
        )
        .unwrap();
        assert!(url.starts_with("https://us-central1-aiplatform.googleapis.com/"));
        let url = render_base_url(
            BEDROCK_CHAT.host.as_ref().unwrap(),
            &settings(&[("region", "us-east-1")]),
        )
        .unwrap();
        assert_eq!(
            url,
            "https://bedrock-runtime.us-east-1.amazonaws.com/openai/v1"
        );
        assert!(render_base_url(host, &settings(&[("location", "global")])).is_err());
    }

    #[test]
    fn hostname_settings_must_be_dns_labels() {
        let host = AZURE.host.as_ref().unwrap();
        for bad in [
            "evil.example.com/",
            "a@b",
            "r?x",
            "r#x",
            "r x",
            "r.x",
            "",
            "r/../x",
        ] {
            let err = render_base_url(host, &settings(&[("resource", bad)])).unwrap_err();
            assert_eq!(err.class_name(), "NotConfiguredError", "{bad:?}");
        }
        assert!(render_base_url(host, &settings(&[("resource", "lm15-oai-29d280ed6f8e")])).is_ok());
    }

    fn input<'a>(
        base_url: &'a str,
        endpoint: &'a str,
        stream: bool,
        model: &'a str,
    ) -> HostInput<'a> {
        HostInput {
            base_url,
            url: format!("{base_url}/messages"),
            headers: vec![
                ("anthropic-version".into(), "2023-06-01".into()),
                ("content-type".into(), "application/json".into()),
            ],
            body: Some(json!({"model": model, "max_tokens": 5})),
            params: vec![],
            endpoint: Some(endpoint),
            stream,
            model: Some(model),
        }
    }

    #[test]
    fn vertex_anthropic_moves_model_and_version() {
        let base = "https://aiplatform.googleapis.com/v1/projects/p/locations/global";
        let out = finish_request(
            &VERTEX_ANTHROPIC,
            &settings(&[("project", "p"), ("location", "global")]),
            input(base, "messages", true, "claude-sonnet-4@20250514"),
            None,
        )
        .unwrap();
        assert_eq!(
            out.url,
            format!("{base}/publishers/anthropic/models/claude-sonnet-4@20250514:streamRawPredict")
        );
        assert_eq!(
            out.body,
            Some(json!({"max_tokens": 5, "anthropic_version": "vertex-2023-10-16"}))
        );
        assert!(out.headers.iter().all(|(k, _)| k != "anthropic-version"));
        let non_stream = finish_request(
            &VERTEX_ANTHROPIC,
            &HostSettings::new(),
            input(base, "messages", false, "m"),
            None,
        )
        .unwrap();
        assert!(non_stream.url.ends_with("/models/m:rawPredict"));
    }

    #[test]
    fn required_headers_and_query_key() {
        let aws = crate::auth::AWS_ANTHROPIC;
        let base = "https://aws-external-anthropic.us-east-1.api.aws/v1";
        let out = finish_request(
            &aws,
            &settings(&[("region", "us-east-1"), ("workspace", "ws-1")]),
            input(base, "messages", false, "m"),
            None,
        )
        .unwrap();
        assert!(out
            .headers
            .contains(&("anthropic-workspace-id".to_string(), "ws-1".to_string())));
        let err = finish_request(
            &aws,
            &settings(&[("region", "us-east-1")]),
            input(base, "messages", false, "m"),
            None,
        )
        .unwrap_err();
        assert_eq!(err.class_name(), "NotConfiguredError");

        let express = finish_request(
            &VERTEX_EXPRESS,
            &HostSettings::new(),
            input(
                "https://aiplatform.googleapis.com/v1/publishers/google",
                "generateContent",
                false,
                "models/gemini-2.5-flash",
            ),
            Some("k"),
        )
        .unwrap();
        assert_eq!(express.params, vec![("key".to_string(), "k".to_string())]);
        // No path override on this host: the dialect's URL stands.
        assert!(express.url.ends_with("/messages"));
        // A key on a door without query-key is not placed.
        let plain = finish_request(
            &AZURE,
            &HostSettings::new(),
            input(base, "messages", false, "m"),
            Some("k"),
        )
        .unwrap();
        assert!(plain.params.is_empty());
    }
}