cpm-planner 0.4.3

Critical Path Method planner as an MCP server: schedules task graphs (slack, critical path, resource levelling, Monte Carlo), leases lock-aware parallel cohorts to agents, versions plan-as-code variants, and tracks earned value.
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
//! OpenRouter / Jev configuration and the [`JudgmentModel`] seam (P6, #26).
//!
//! [`LlmConfig::from_env`] reads the OpenRouter key and the Jev / generative
//! model settings. `Ok(None)` means "no key configured": callers report
//! `review_unavailable` rather than silently falling back.
//!
//! [`JudgmentModel`] is the one async seam `plan.review` depends on, so the
//! review logic is testable with a fake. [`jev::JevJudge`] implements it with
//! `rig-typesafeai` pointed at OpenRouter's System One endpoint, and
//! [`openrouter::chat_client`] builds the rig-core OpenRouter chat client for
//! future headless use.
//!
//! # Key hygiene
//!
//! The key lives in an [`ApiKey`] whose `Debug` is redacted and which has no
//! `Display`/`Serialize`. [`JudgmentError`] messages are scrubbed of the key
//! before they are built, so neither logs, errors, audit records nor tool
//! output can carry it.

pub mod jev;
pub mod openrouter;

use std::collections::BTreeMap;
use std::fmt;
use std::path::Path;
use std::time::Duration;

use async_trait::async_trait;
pub use rig_typesafeai::types::{Answer, Question, Usage};

/// Environment variable holding the OpenRouter key.
pub const OPENROUTER_API_KEY_ENV: &str = "OPENROUTER_API_KEY";
/// Environment variable naming a file that holds the OpenRouter key.
pub const OPENROUTER_KEY_FILE_ENV: &str = "CPM_OPENROUTER_KEY_FILE";
/// Environment variable overriding the Jev model id.
pub const JEV_MODEL_ENV: &str = "CPM_JEV_MODEL";
/// Environment variable overriding the Jev endpoint URL.
pub const JEV_ENDPOINT_ENV: &str = "CPM_JEV_ENDPOINT";
/// Environment variable bounding every LLM network call, in seconds.
pub const LLM_TIMEOUT_ENV: &str = "CPM_LLM_TIMEOUT_SECS";
/// Environment variable naming the generative (chat) model.
pub const LLM_MODEL_ENV: &str = "CPM_LLM_MODEL";

/// Default Jev model on OpenRouter.
pub const DEFAULT_JEV_MODEL: &str = "typesafe/jev-1.13";
/// Default Jev endpoint: OpenRouter's System One route.
pub const DEFAULT_JEV_ENDPOINT: &str = "https://openrouter.ai/api/v1/systemone";
/// Longest accepted [`JEV_MODEL_ENV`] value, in chars.
pub const MAX_MODEL_ID_CHARS: usize = 128;
/// Longest provider-reported model id kept in a review, in chars.
pub const MAX_REPORTED_MODEL_CHARS: usize = 64;
/// Default per-call timeout, seconds.
pub const DEFAULT_TIMEOUT_SECS: u64 = 30;
/// Inclusive bounds for [`LLM_TIMEOUT_ENV`], seconds.
pub const TIMEOUT_SECS_RANGE: std::ops::RangeInclusive<u64> = 1..=300;
/// Default generative model: a commodity model, not a frontier vendor.
pub const DEFAULT_LLM_MODEL: &str = "deepseek/deepseek-v4.1-flash";

/// Redaction marker used wherever the key would otherwise appear.
pub const REDACTED: &str = "[redacted]";
/// Upper bound on [`JudgmentError::message`], in chars (it becomes tool output).
pub const MAX_ERROR_MESSAGE_CHARS: usize = 300;
/// Largest key file accepted, in bytes.
pub const MAX_KEY_FILE_BYTES: u64 = 4096;
/// Shortest key prefix treated as a leak when it ends a truncated excerpt.
const MIN_KEY_FRAGMENT_CHARS: usize = 8;

/// The OpenRouter key. `Debug` is redacted; there is deliberately no
/// `Display` or `Serialize`.
#[derive(Clone, PartialEq, Eq)]
pub struct ApiKey(String);

impl ApiKey {
    /// The raw key. Every call site is a place the key can leak: only the
    /// HTTP clients should call this.
    pub fn expose(&self) -> &str {
        &self.0
    }

    /// `text` with every occurrence of the key replaced by [`REDACTED`].
    pub fn scrub(&self, text: &str) -> String {
        if self.0.is_empty() {
            text.to_string()
        } else {
            text.replace(&self.0, REDACTED)
        }
    }

    /// At most `max_chars` of `text`, safe to show: the WHOLE text is
    /// scrubbed first, then truncated, and a trailing key prefix of
    /// `MIN_KEY_FRAGMENT_CHARS` (8)+ chars (a key cut by the boundary, or a
    /// partial key in the input) is dropped.
    pub fn excerpt(&self, text: &str, max_chars: usize) -> String {
        let scrubbed = self.scrub(text);
        let mut out: Vec<char> = scrubbed.chars().take(max_chars).collect();
        let key: Vec<char> = self.0.chars().collect();
        let longest = key.len().min(out.len());
        if let Some(len) = (MIN_KEY_FRAGMENT_CHARS..=longest)
            .rev()
            .find(|&len| out[out.len() - len..] == key[..len])
        {
            out.truncate(out.len() - len);
        }
        out.into_iter().collect()
    }
}

impl fmt::Debug for ApiKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(REDACTED)
    }
}

/// Why the LLM configuration is unusable.
///
/// Neither `Display` nor `Debug` carries a variable's value or the key-file
/// path: a key pasted into the wrong variable must not reach a log. Each
/// message names the variable and the rule it breaks.
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    /// `CPM_LLM_TIMEOUT_SECS` is not an integer in 1..=300. The value is not
    /// kept.
    #[error("{LLM_TIMEOUT_ENV} must be an integer number of seconds in 1..=300")]
    InvalidTimeout,
    /// `CPM_JEV_ENDPOINT` is not an acceptable URL. The value itself is not
    /// echoed (it may carry credentials).
    #[error(
        "{JEV_ENDPOINT_ENV} must be an https:// URL (http:// only for a loopback host) \
         without credentials: {reason}"
    )]
    InvalidEndpoint { reason: String },
    /// `CPM_JEV_MODEL` is not a plausible model id (at most
    /// [`MAX_MODEL_ID_CHARS`] chars of `[A-Za-z0-9._:/-]`), or it contains
    /// the configured key. The value is not kept.
    #[error("{JEV_MODEL_ENV} {reason}")]
    InvalidModel { reason: &'static str },
    /// `CPM_LLM_MODEL` names a frontier vendor this build refuses in favour
    /// of a commodity model. The id is kept: it already passed the model-id
    /// and key checks in `parse_model`.
    #[error("{LLM_MODEL_ENV} must name a commodity model, not a frontier vendor: {model}")]
    FrontierModel { model: String },
    /// `CPM_OPENROUTER_KEY_FILE` names something that cannot be used as a
    /// key file (missing, unreadable, not a regular file, too large). The
    /// path is not kept.
    #[error("{OPENROUTER_KEY_FILE_ENV}: key file cannot be read: {reason}")]
    KeyFile { reason: String },
    /// The key file was read but deliberately ignored. Distinct from "no key
    /// configured" so callers can say why. The path is not kept.
    #[error("{OPENROUTER_KEY_FILE_ENV}: key file ignored: {reason}")]
    KeyFileIgnored { reason: KeyFileIgnoredReason },
}

impl ConfigError {
    /// A short `plan.review` `review_unavailable` reason naming the setting.
    /// It carries neither the key nor any path or raw value (only the
    /// variable name and the validation reason).
    pub fn review_reason(&self) -> String {
        match self {
            Self::InvalidTimeout => format!(
                "{LLM_TIMEOUT_ENV} invalid: must be an integer number of seconds in 1..=300"
            ),
            Self::InvalidEndpoint { reason } => format!("{JEV_ENDPOINT_ENV} invalid: {reason}"),
            Self::InvalidModel { reason } => format!("{JEV_MODEL_ENV} invalid: {reason}"),
            Self::FrontierModel { model } => {
                format!("{LLM_MODEL_ENV} refused frontier model: {model}")
            }
            Self::KeyFile { reason } => {
                format!("key file unreadable: {reason} ({OPENROUTER_KEY_FILE_ENV})")
            }
            Self::KeyFileIgnored { reason } => {
                format!("key file ignored: {reason} ({OPENROUTER_KEY_FILE_ENV})")
            }
        }
    }
}

/// Why a key file was ignored.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyFileIgnoredReason {
    /// Other users can read it (unix mode `o+r`); `chmod 600` to use it.
    WorldReadable,
    /// It holds only whitespace.
    Empty,
}

impl fmt::Display for KeyFileIgnoredReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::WorldReadable => "world-readable",
            Self::Empty => "empty",
        })
    }
}

/// OpenRouter / Jev settings. Only constructed when a key is configured.
#[derive(Clone, Debug)]
pub struct LlmConfig {
    api_key: ApiKey,
    jev_model: String,
    jev_endpoint: String,
    timeout: Duration,
    llm_model: String,
}

impl LlmConfig {
    /// Settings for `api_key` with every other field at its default.
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            api_key: ApiKey(api_key.into()),
            jev_model: DEFAULT_JEV_MODEL.to_string(),
            jev_endpoint: DEFAULT_JEV_ENDPOINT.to_string(),
            timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
            llm_model: DEFAULT_LLM_MODEL.to_string(),
        }
    }

    /// Read the process environment. `Ok(None)` = no key configured.
    pub fn from_env() -> Result<Option<Self>, ConfigError> {
        Self::from_lookup(|name| std::env::var(name).ok())
    }

    /// [`Self::from_env`] over an arbitrary variable lookup (tests).
    ///
    /// The key comes from `OPENROUTER_API_KEY`, else from the file named by
    /// `CPM_OPENROUTER_KEY_FILE` (contents trimmed). A world-readable (unix)
    /// or empty key file is [`ConfigError::KeyFileIgnored`] (not logged here:
    /// the caller logs it once).
    /// A blank env key counts as absent. The endpoint is validated here:
    /// https, or http to a loopback host, with no credentials.
    pub fn from_lookup(
        lookup: impl Fn(&str) -> Option<String>,
    ) -> Result<Option<Self>, ConfigError> {
        let non_blank = |name: &str| lookup(name).filter(|v| !v.trim().is_empty());

        let key = match non_blank(OPENROUTER_API_KEY_ENV) {
            Some(key) => Some(key.trim().to_string()),
            None => match non_blank(OPENROUTER_KEY_FILE_ENV) {
                Some(path) => read_key_file(Path::new(path.trim()))?,
                None => None,
            },
        };

        let timeout = match non_blank(LLM_TIMEOUT_ENV) {
            Some(raw) => parse_timeout(&raw)?,
            None => Duration::from_secs(DEFAULT_TIMEOUT_SECS),
        };
        let jev_endpoint = match non_blank(JEV_ENDPOINT_ENV) {
            Some(raw) => parse_endpoint(raw.trim())?,
            None => DEFAULT_JEV_ENDPOINT.to_string(),
        };
        let Some(key) = key else {
            return Ok(None);
        };
        let mut config = Self::new(key)
            .with_jev_endpoint(jev_endpoint)
            .with_timeout(timeout);
        if let Some(model) = non_blank(JEV_MODEL_ENV) {
            config.jev_model = parse_model(model.trim(), &config.api_key)?;
        }
        if let Some(model) = non_blank(LLM_MODEL_ENV) {
            config.llm_model = parse_generative_model(model.trim(), &config.api_key)?;
        }
        Ok(Some(config))
    }

    /// Replace the Jev endpoint (complete URL including the route). Not
    /// validated: programmatic callers (tests) own it; the env path is
    /// validated by [`Self::from_lookup`].
    pub fn with_jev_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.jev_endpoint = endpoint.into();
        self
    }

    /// Replace the Jev model id.
    pub fn with_jev_model(mut self, model: impl Into<String>) -> Self {
        self.jev_model = model.into();
        self
    }

    /// Replace the per-call timeout. The env var is bounded to 1..=300 s;
    /// programmatic callers (tests) may pick any duration.
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// The OpenRouter key (redacted `Debug`).
    pub fn api_key(&self) -> &ApiKey {
        &self.api_key
    }

    /// The Jev model id.
    pub fn jev_model(&self) -> &str {
        &self.jev_model
    }

    /// The complete Jev endpoint URL.
    pub fn jev_endpoint(&self) -> &str {
        &self.jev_endpoint
    }

    /// Host of the Jev endpoint, from the parsed URL (see [`endpoint_host`]).
    pub fn jev_endpoint_host(&self) -> Option<String> {
        endpoint_host(&self.jev_endpoint)
    }

    /// The bound applied to every network call.
    pub fn timeout(&self) -> Duration {
        self.timeout
    }

    /// The generative (chat) model id.
    pub fn llm_model(&self) -> &str {
        &self.llm_model
    }
}

fn parse_timeout(raw: &str) -> Result<Duration, ConfigError> {
    raw.trim()
        .parse::<u64>()
        .ok()
        .filter(|secs| TIMEOUT_SECS_RANGE.contains(secs))
        .map(Duration::from_secs)
        .ok_or(ConfigError::InvalidTimeout)
}

/// A model id: 1..=[`MAX_MODEL_ID_CHARS`] chars of `[A-Za-z0-9._:/-]`, not
/// containing `key`.
fn parse_model(raw: &str, key: &ApiKey) -> Result<String, ConfigError> {
    let invalid = |reason| Err(ConfigError::InvalidModel { reason });
    if raw.chars().count() > MAX_MODEL_ID_CHARS {
        return invalid("must be at most 128 characters");
    }
    if !raw
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | ':' | '/' | '-'))
    {
        return invalid("may only contain A-Z a-z 0-9 . _ : / -");
    }
    if !key.expose().is_empty() && raw.contains(key.expose()) {
        return invalid("must not contain the OpenRouter key");
    }
    Ok(raw.to_string())
}

/// Validate a [`LLM_MODEL_ENV`] value and refuse frontier vendors, matching
/// Junior's `model-policy.ts`. `openai/gpt-oss*` is the one `openai/`
/// exception.
fn parse_generative_model(raw: &str, key: &ApiKey) -> Result<String, ConfigError> {
    let model = parse_model(raw, key)?;
    if frontier_vendor(&model).is_some() {
        return Err(ConfigError::FrontierModel { model });
    }
    Ok(model)
}

/// The frontier vendor prefix `model` belongs to, if any.
fn frontier_vendor(model: &str) -> Option<&'static str> {
    if model.starts_with("openai/gpt-oss") {
        return None;
    }
    ["anthropic/", "openai/", "google/", "x-ai/", "xai/"]
        .into_iter()
        .find(|prefix| model.starts_with(prefix))
}

fn parse_endpoint(raw: &str) -> Result<String, ConfigError> {
    let invalid = |reason: &str| ConfigError::InvalidEndpoint {
        reason: reason.to_string(),
    };
    // url's ParseError messages are generic ("invalid port number") and
    // never echo the input.
    let url = url::Url::parse(raw).map_err(|e| invalid(&e.to_string()))?;
    if !url.username().is_empty() || url.password().is_some() {
        return Err(invalid("credentials in the URL are not allowed"));
    }
    let loopback = match url.host() {
        Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"),
        Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
        Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
        None => return Err(invalid("missing host")),
    };
    match url.scheme() {
        "https" => Ok(raw.to_string()),
        "http" if loopback => Ok(raw.to_string()),
        "http" => Err(invalid("http:// is only allowed for a loopback host")),
        _ => Err(invalid("unsupported scheme")),
    }
}

/// Read and trim the key file. It must be a regular file of at most
/// [`MAX_KEY_FILE_BYTES`]; a world-readable (unix) or empty file is
/// [`ConfigError::KeyFileIgnored`]. Nothing is logged here (the caller logs
/// the error once); errors carry neither the path nor the key.
fn read_key_file(path: &Path) -> Result<Option<String>, ConfigError> {
    use std::io::Read;
    let key_file_error = |reason: String| ConfigError::KeyFile { reason };
    let io_error = |e: std::io::Error| key_file_error(e.kind().to_string());
    let ignored = |reason: KeyFileIgnoredReason| ConfigError::KeyFileIgnored { reason };

    let mut options = std::fs::OpenOptions::new();
    options.read(true);
    // Non-blocking open so a FIFO cannot hang startup; the handle is then
    // checked to be a regular file, so the file checked is the file read.
    #[cfg(unix)]
    std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, libc::O_NONBLOCK);
    let file = options.open(path).map_err(io_error)?;
    let metadata = file.metadata().map_err(io_error)?;
    if !metadata.is_file() {
        return Err(key_file_error("not a regular file".to_string()));
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if metadata.permissions().mode() & 0o004 != 0 {
            return Err(ignored(KeyFileIgnoredReason::WorldReadable));
        }
    }
    let mut bytes = Vec::new();
    file.take(MAX_KEY_FILE_BYTES + 1)
        .read_to_end(&mut bytes)
        .map_err(io_error)?;
    if bytes.len() as u64 > MAX_KEY_FILE_BYTES {
        return Err(key_file_error(format!(
            "larger than {MAX_KEY_FILE_BYTES} bytes"
        )));
    }
    let contents =
        String::from_utf8(bytes).map_err(|_| key_file_error("not valid UTF-8".to_string()))?;
    let key = contents.trim();
    if key.is_empty() {
        return Err(ignored(KeyFileIgnoredReason::Empty));
    }
    Ok(Some(key.to_string()))
}

/// Jev's answers to one batched evaluation.
#[derive(Debug, Clone)]
pub struct Decisions {
    /// One answer per question id, keyed exactly as asked.
    pub answers: BTreeMap<String, Answer>,
    /// The model id the provider reports having used.
    pub model: String,
    /// Token accounting when the provider reports it.
    pub usage: Option<Usage>,
}

/// Failure class of a [`JudgmentError`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum JudgmentErrorKind {
    /// The provider rejected the key (401/403).
    Unauthorized,
    /// The provider throttled the call (429).
    RateLimited,
    /// No reply within `CPM_LLM_TIMEOUT_SECS`.
    Timeout,
    /// Any other provider-side failure (5xx, other non-success statuses).
    Upstream,
    /// The reply arrived but does not decode or does not answer the request.
    Decode,
    /// No reply: connection refused/reset, DNS, TLS.
    Transport,
    /// The questions or state were rejected locally before sending.
    InvalidRequest,
}

impl JudgmentErrorKind {
    /// Stable snake_case name used in `review_unavailable` reasons.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Unauthorized => "unauthorized",
            Self::RateLimited => "rate_limited",
            Self::Timeout => "timeout",
            Self::Upstream => "upstream",
            Self::Decode => "decode",
            Self::Transport => "transport",
            Self::InvalidRequest => "invalid_request",
        }
    }
}

impl fmt::Display for JudgmentErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A classed judgment failure. `message` never contains the key, is at most
/// [`MAX_ERROR_MESSAGE_CHARS`] chars, and carries only a short reason (an
/// HTTP status, a decode reason) — never the upstream body.
///
/// The fields are private and the only constructor,
/// [`JudgmentError::scrubbed`], scrubs the message of the key, so no caller
/// can build an error carrying it.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{kind}: {message}")]
pub struct JudgmentError {
    kind: JudgmentErrorKind,
    message: String,
}

impl JudgmentError {
    /// Build an error whose message is [`ApiKey::excerpt`]ed: scrubbed of
    /// `key`, then cut to [`MAX_ERROR_MESSAGE_CHARS`].
    pub fn scrubbed(kind: JudgmentErrorKind, message: impl AsRef<str>, key: &ApiKey) -> Self {
        Self {
            kind,
            message: key.excerpt(message.as_ref(), MAX_ERROR_MESSAGE_CHARS),
        }
    }

    /// The failure class.
    pub fn kind(&self) -> JudgmentErrorKind {
        self.kind
    }

    /// A safe, human-readable detail.
    pub fn message(&self) -> &str {
        &self.message
    }
}

/// A calibrated-judgment model: one batched call answering runtime-defined
/// questions about one shared state.
#[async_trait]
pub trait JudgmentModel: Send + Sync {
    /// Ask every question in `questions` about `state` in a single call.
    async fn decide(
        &self,
        state: serde_json::Value,
        questions: BTreeMap<String, Question>,
    ) -> Result<Decisions, JudgmentError>;

    /// Host of the endpoint this model calls, for the review report. `None`
    /// when unknown (fakes) or unparseable.
    fn endpoint_host(&self) -> Option<String> {
        None
    }

    /// The model id this judge is configured to ask, for audit records when
    /// the provider never reported one. `None` when unknown (fakes).
    fn model_id(&self) -> Option<String> {
        None
    }
}

/// Host of `endpoint` as [`url::Url`] parses it (lower-cased, no port,
/// userinfo, path or query). `None` when it does not parse or has no host.
pub fn endpoint_host(endpoint: &str) -> Option<String> {
    url::Url::parse(endpoint)
        .ok()
        .and_then(|url| url.host_str().map(str::to_string))
}