leviath-cli 0.3.10

Command-line interface for Leviath agent framework
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
//! Config and models endpoints.

use axum::extract::State;
use axum::http::StatusCode;
use axum::response::Json;

use super::types::*;
use crate::config::Config;

/// Every `[model_providers]` entry as the API reports it, name-sorted.
///
/// Sorted because the config holds them in a `HashMap`, whose iteration order
/// differs between two calls on one machine, and a list that reorders itself
/// under a form is a list nobody can edit.
fn gateways_of(c: &Config) -> Vec<GatewayInfo> {
    let mut gateways: Vec<GatewayInfo> = c
        .model_providers
        .iter()
        .map(|(name, p)| GatewayInfo {
            name: name.clone(),
            base_url: p.base_url.clone(),
            has_api_key: p.api_key.is_some(),
            script: p.script.clone(),
            // Names only. See `GatewayInfo::extra_keys`: these values are
            // forwarded into a script and routinely hold credentials.
            extra_keys: {
                let mut keys: Vec<String> = p.extra.keys().cloned().collect();
                keys.sort();
                keys
            },
        })
        .collect();
    gateways.sort_by(|a, b| a.name.cmp(&b.name));
    gateways
}

/// Redacted view of a config — booleans for keys, never their values.
fn redact(c: &Config) -> RedactedConfig {
    RedactedConfig {
        default_provider: c.default_provider.clone(),
        has_anthropic_key: c.providers.anthropic_api_key.is_some(),
        has_openai_key: c.providers.openai_api_key.is_some(),
        has_google_key: c.providers.google_api_key.is_some(),
        has_openrouter_key: c.openrouter_api_key.is_some(),
        ollama_base_url: c.ollama_base_url.clone(),
        gateways: gateways_of(c),
        agent_paths: c.agent_paths.clone(),
        mcp_server_count: c.mcp_servers.len(),
        api_version: API_VERSION.to_string(),
        capabilities: API_CAPABILITIES.iter().map(|c| c.to_string()).collect(),
        limits: ApiLimits::current(),
    }
}

pub(super) async fn get_config(State(state): State<AppState>) -> Json<RedactedConfig> {
    Json(redact(&state.config))
}

/// `PUT /api/config` (admin-only). Loads the on-disk config, applies every
/// present field, and writes it back with the file's `0600` permissions — the
/// same file `lev setup` and MCP admin edits. Returns the new redacted config.
pub(super) async fn put_config(
    State(state): State<AppState>,
    Json(req): Json<WriteConfigReq>,
) -> Result<Json<RedactedConfig>, (StatusCode, Json<ErrorResponse>)> {
    let path = &state.mcp.config_path;
    let mut config = Config::load_from_path_public(path).map_err(|e| {
        err(
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("failed to read config: {e}"),
        )
    })?;

    if let Some(v) = req.default_provider {
        config.default_provider = v;
    }
    if let Some(v) = req.default_model {
        config.default_model = Some(v);
    }
    if let Some(v) = req.anthropic_key {
        config.providers.anthropic_api_key = Some(v);
    }
    if let Some(v) = req.openai_key {
        config.providers.openai_api_key = Some(v);
    }
    if let Some(v) = req.google_key {
        config.providers.google_api_key = Some(v);
    }
    if let Some(v) = req.openrouter_key {
        config.openrouter_api_key = Some(v);
    }
    if let Some(v) = req.ollama_base_url {
        config.ollama_base_url = Some(v);
    }
    // Field by field, like everything above: a gateway names only what it is
    // changing, so a console can edit a base URL without knowing the key or
    // sending it back through the browser.
    for gateway in req.gateways.unwrap_or_default() {
        let entry = config.model_providers.entry(gateway.name).or_default();
        if let Some(v) = gateway.base_url {
            entry.base_url = Some(v);
        }
        if let Some(v) = gateway.api_key {
            entry.api_key = Some(v);
        }
        if let Some(v) = gateway.script {
            entry.script = Some(v);
        }
    }
    // Removals run last, so one request that both edits and deletes cannot
    // depend on which half was applied first.
    for name in req.remove_gateways.unwrap_or_default() {
        config.model_providers.remove(&name);
    }

    config.save_to_path_public(path).map_err(|e| {
        err(
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("failed to write config: {e}"),
        )
    })?;
    Ok(Json(redact(&config)))
}

/// Format-only validation of a provider key (no network call, no persistence).
fn validate_key_format(provider: &str, key: &str) -> (bool, Option<String>) {
    match provider {
        "anthropic" => {
            if key.starts_with("sk-ant-") {
                (true, None)
            } else {
                (
                    false,
                    Some("Anthropic keys start with `sk-ant-`.".to_string()),
                )
            }
        }
        "openai" => {
            if key.starts_with("sk-") {
                (true, None)
            } else {
                (false, Some("OpenAI keys start with `sk-`.".to_string()))
            }
        }
        "google" | "openrouter" => {
            if key.trim().is_empty() {
                (false, Some("Key must not be empty.".to_string()))
            } else {
                (true, None)
            }
        }
        // A custom gateway is custom precisely because its key has no house
        // format to check, so an unknown name is no longer a rejection: the
        // only thing that can be said about the key is that it is not empty.
        _ => match key.trim().is_empty() {
            true => (false, Some("Key must not be empty.".to_string())),
            false => (true, None),
        },
    }
}

/// Format-only check of a gateway's base URL.
///
/// Shape only, like the key check beside it: no request is made, because
/// `POST /api/config/validate` promises not to touch the network and a form
/// that hangs on an unreachable host is worse than one that says nothing. The
/// scheme is what people actually get wrong - a bare `api.example.com`, or an
/// `ollama serve` address pasted without one.
fn validate_base_url(url: &str) -> (bool, Option<String>) {
    let trimmed = url.trim();
    if trimmed.is_empty() {
        return (false, Some("Base URL must not be empty.".to_string()));
    }
    match trimmed.starts_with("http://") || trimmed.starts_with("https://") {
        true => (true, None),
        false => (
            false,
            Some("Base URL must start with `http://` or `https://`.".to_string()),
        ),
    }
}

pub(super) async fn validate_config_key(Json(req): Json<ValidateKeyReq>) -> Json<ValidateKeyResp> {
    // The URL is checked first: a gateway with both wrong is more usefully
    // told about the address than about the key, since the key cannot be
    // judged beyond being present.
    if let Some(base_url) = &req.base_url {
        let (valid, message) = validate_base_url(base_url);
        if !valid {
            return Json(ValidateKeyResp { valid, message });
        }
    }
    let (valid, message) = validate_key_format(&req.provider, &req.key);
    Json(ValidateKeyResp { valid, message })
}

pub(super) async fn get_models(State(state): State<AppState>) -> Json<Vec<ModelEntry>> {
    models_with(&state, &leviath_providers::provider::build_http_client).await
}

/// [`get_models`], with client construction injected so the "no usable HTTPS
/// client" answer is reachable from a test.
pub(super) async fn models_with(
    state: &AppState,
    build_client: leviath_providers::provider::HttpClientFactory<'_>,
) -> Json<Vec<ModelEntry>> {
    // Nothing to list if no client could be built; the endpoint answers with an
    // empty set rather than failing the request, matching how it treats a
    // provider whose `list_models` errors.
    let Ok(registry) = crate::commands::run::session::build_provider_registry_from_config_with(
        &state.config,
        build_client,
    ) else {
        return Json(Vec::new());
    };
    let mut models = Vec::new();

    for provider_name in registry.provider_names() {
        let provider = registry
            .get(provider_name)
            .expect("provider_names returns registered names");
        if let Ok(list) = provider.list_models().await {
            for m in list {
                models.push(ModelEntry {
                    id: m.id,
                    provider: m.provider,
                    display_name: m.display_name,
                    max_context_tokens: m.capabilities.max_context_tokens,
                    max_output_tokens: m.capabilities.max_output_tokens,
                    supports_tools: m.capabilities.supports_tools,
                });
            }
        }
    }

    Json(models)
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::Router;
    use axum::body::Body;
    use axum::http::Request;
    use axum::routing::get;
    use std::sync::Arc;
    use tokio::sync::broadcast;
    use tower::ServiceExt;

    use crate::commands::serve::types::ServerEvent;
    use crate::config::Config;

    /// A default config whose ollama endpoint cannot answer.
    ///
    /// Ollama is always registered, so on a machine running `ollama serve` its
    /// `list_models` *succeeds* and the `if let Ok(list)` in `models_with` never
    /// takes its other arm - which made `cargo xtask coverage --package
    /// leviath-cli` fail locally while passing in CI, where nothing is
    /// listening. Port 1 is reserved and never bound, so the result stops
    /// depending on what happens to be running on the developer's machine.
    fn state_without_a_reachable_ollama() -> AppState {
        let (tx, _) = broadcast::channel::<ServerEvent>(64);
        AppState {
            config: Arc::new(Config {
                ollama_base_url: Some("http://127.0.0.1:1".to_string()),
                ..Config::default()
            }),
            event_tx: tx,
            control: crate::commands::serve::testutil::no_daemon_client(),
            mcp: crate::commands::serve::mcp::McpAdmin::default(),
            limits: Default::default(),
        }
    }

    fn test_state() -> AppState {
        let (tx, _) = broadcast::channel::<ServerEvent>(64);
        AppState {
            config: Arc::new(Config::default()),
            event_tx: tx,
            control: crate::commands::serve::testutil::no_daemon_client(),
            mcp: crate::commands::serve::mcp::McpAdmin::default(),
            limits: Default::default(),
        }
    }

    fn test_state_with_keys() -> AppState {
        let (tx, _) = broadcast::channel::<ServerEvent>(64);
        AppState {
            config: Arc::new(Config {
                providers: crate::config::ProviderConfig {
                    anthropic_api_key: Some("sk-ant-test".to_string()),
                    openai_api_key: Some("sk-openai-test".to_string()),
                    google_api_key: None,
                    claude_code_enabled: false,
                    claude_code_binary: None,
                    claude_code_effort: None,
                    anthropic_cache_ttl: None,
                    fallback_order: Vec::new(),
                },
                openrouter_api_key: Some("sk-or-test".to_string()),
                ollama_base_url: Some("http://localhost:11434".to_string()),
                mcp_servers: vec![],
                ..Default::default()
            }),
            event_tx: tx,
            control: crate::commands::serve::testutil::no_daemon_client(),
            mcp: crate::commands::serve::mcp::McpAdmin::default(),
            limits: Default::default(),
        }
    }

    // ─── get_config endpoint ──────────────────────────────────────────────────

    #[tokio::test]
    async fn get_config_default_returns_ok() {
        let app = Router::new()
            .route("/api/config", get(get_config))
            .with_state(test_state());
        let req = Request::builder()
            .uri("/api/config")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let config: RedactedConfig = serde_json::from_slice(&body).unwrap();
        assert_eq!(config.default_provider, "anthropic");
        assert!(!config.has_anthropic_key);
        assert!(!config.has_openai_key);
        assert!(!config.has_openrouter_key);
        assert!(config.ollama_base_url.is_none());
    }

    /// The console used to feature-detect by calling a route and reading a 404
    /// as "unsupported" - which is also what a missing run looks like, and
    /// costs one round trip per feature.
    #[tokio::test]
    async fn get_config_advertises_the_api_version_capabilities_and_limits() {
        let app = Router::new()
            .route("/api/config", get(get_config))
            .with_state(test_state());
        let req = Request::builder()
            .uri("/api/config")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let config: RedactedConfig = serde_json::from_slice(&body).unwrap();

        assert_eq!(config.api_version, API_VERSION);
        for expected in [
            "runs.envelope",
            "runs.search",
            "runs.files.listing",
            "blueprints.envelope",
            "context.history.page",
        ] {
            assert!(
                config.capabilities.iter().any(|c| c == expected),
                "missing capability {expected}"
            );
        }

        // The numbers are what make this useful rather than decorative: a
        // client that knows a feature exists still has to know its caps, and
        // every one it guesses would be hardcoded and eventually wrong.
        assert_eq!(
            config.limits.max_limit,
            crate::commands::serve::runs::MAX_LIMIT
        );
        assert_eq!(
            config.limits.max_file_bytes,
            crate::commands::serve::agents::MAX_FILE_READ_BYTES
        );
        assert_eq!(
            config.limits.max_tracked_modified_files,
            leviath_core::run_meta::MAX_TRACKED_MODIFIED_FILES
        );
    }

    #[tokio::test]
    async fn get_config_with_keys_shows_has_key_true() {
        let app = Router::new()
            .route("/api/config", get(get_config))
            .with_state(test_state_with_keys());
        let req = Request::builder()
            .uri("/api/config")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let config: RedactedConfig = serde_json::from_slice(&body).unwrap();
        assert!(config.has_anthropic_key);
        assert!(config.has_openai_key);
        assert!(config.has_openrouter_key);
        assert_eq!(
            config.ollama_base_url.as_deref(),
            Some("http://localhost:11434")
        );
        // Must not contain actual key values
        let raw = std::str::from_utf8(&body).unwrap();
        assert!(!raw.contains("sk-ant-test"));
        assert!(!raw.contains("sk-openai-test"));
    }

    #[tokio::test]
    async fn get_config_agent_paths_included() {
        let (tx, _) = broadcast::channel::<ServerEvent>(64);
        let state = AppState {
            config: Arc::new(Config {
                agent_paths: vec![
                    std::path::PathBuf::from("/my/agents"),
                    std::path::PathBuf::from("/other/agents"),
                ],
                ..Default::default()
            }),
            event_tx: tx,
            control: crate::commands::serve::testutil::no_daemon_client(),
            mcp: crate::commands::serve::mcp::McpAdmin::default(),
            limits: Default::default(),
        };
        let app = Router::new()
            .route("/api/config", get(get_config))
            .with_state(state);
        let req = Request::builder()
            .uri("/api/config")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let config: RedactedConfig = serde_json::from_slice(&body).unwrap();
        assert_eq!(config.agent_paths.len(), 2);
    }

    // ─── get_models endpoint ──────────────────────────────────────────────────

    /// AppState whose registry has a provider that actually enumerates models,
    /// so the `/api/models` handler's list-building loop runs. `claude-code`
    /// needs no API key and `list_models` returns its three known models.
    fn test_state_listing_models() -> AppState {
        let (tx, _) = broadcast::channel::<ServerEvent>(64);
        AppState {
            config: Arc::new(Config {
                providers: crate::config::ProviderConfig {
                    claude_code_enabled: true,
                    ..Config::default().providers
                },
                ..Config::default()
            }),
            event_tx: tx,
            control: crate::commands::serve::testutil::no_daemon_client(),
            mcp: crate::commands::serve::mcp::McpAdmin::default(),
            limits: Default::default(),
        }
    }

    #[tokio::test]
    async fn get_models_returns_ok() {
        // A reachable ollama would make `list_models` succeed and leave the
        // other arm of `if let Ok(list)` unrun - see `state_without_a_reachable_ollama`.
        let app = Router::new()
            .route("/api/models", get(get_models))
            .with_state(state_without_a_reachable_ollama());
        let req = Request::builder()
            .uri("/api/models")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let models: Vec<serde_json::Value> = serde_json::from_slice(&body).unwrap();
        // With default config (no API keys, claude-code off), providers may
        // return empty lists, but the endpoint itself should succeed.
        let _ = models;
    }

    #[tokio::test]
    async fn get_models_enumerates_when_a_provider_lists_models() {
        let app = Router::new()
            .route("/api/models", get(get_models))
            .with_state(test_state_listing_models());
        let req = Request::builder()
            .uri("/api/models")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let models: Vec<serde_json::Value> = serde_json::from_slice(&body).unwrap();
        // claude-code enumerates its three known models, so the handler's
        // per-model mapping loop actually runs and produces entries.
        assert!(!models.is_empty());
        assert!(models.iter().any(|m| m["provider"] == "claude-code"));
        assert!(models.iter().all(|m| m["id"].is_string()));
    }

    #[test]
    fn redacted_config_hides_keys() {
        let config = RedactedConfig {
            default_provider: "anthropic".to_string(),
            has_anthropic_key: true,
            has_openai_key: false,
            has_google_key: false,
            has_openrouter_key: false,
            ollama_base_url: None,
            gateways: Vec::new(),
            agent_paths: vec![],
            mcp_server_count: 2,
            api_version: API_VERSION.to_string(),
            capabilities: API_CAPABILITIES.iter().map(|c| c.to_string()).collect(),
            limits: ApiLimits::current(),
        };
        let json = serde_json::to_string(&config).unwrap();
        // Must NOT contain actual key values
        assert!(!json.contains("sk-"));
        assert!(json.contains("\"has_anthropic_key\":true"));
        assert!(json.contains("\"has_openai_key\":false"));
        assert!(json.contains("\"mcp_server_count\":2"));
    }

    #[test]
    fn redacted_config_with_ollama_url() {
        let config = RedactedConfig {
            default_provider: "ollama".to_string(),
            has_anthropic_key: false,
            has_openai_key: false,
            has_google_key: false,
            has_openrouter_key: false,
            ollama_base_url: Some("http://localhost:11434".to_string()),
            gateways: Vec::new(),
            agent_paths: vec![],
            mcp_server_count: 0,
            api_version: API_VERSION.to_string(),
            capabilities: API_CAPABILITIES.iter().map(|c| c.to_string()).collect(),
            limits: ApiLimits::current(),
        };
        let json = serde_json::to_string(&config).unwrap();
        assert!(json.contains("\"ollama_base_url\":\"http://localhost:11434\""));
    }

    // ─── put_config endpoint ──────────────────────────────────────────────────

    fn state_with_config_path(path: std::path::PathBuf) -> AppState {
        let (tx, _) = broadcast::channel::<ServerEvent>(64);
        AppState {
            config: Arc::new(Config::default()),
            event_tx: tx,
            control: crate::commands::serve::testutil::no_daemon_client(),
            mcp: crate::commands::serve::mcp::McpAdmin {
                config_path: path,
                ..Default::default()
            },
            limits: Default::default(),
        }
    }

    async fn put_config_request(state: AppState, body: &str) -> axum::http::Response<Body> {
        let app = Router::new()
            .route("/api/config", axum::routing::put(put_config))
            .with_state(state);
        let req = Request::builder()
            .method("PUT")
            .uri("/api/config")
            .header("content-type", "application/json")
            .body(Body::from(body.to_string()))
            .unwrap();
        app.oneshot(req).await.unwrap()
    }

    #[tokio::test]
    async fn put_config_writes_all_present_fields_and_redacts() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        Config::default().save_to_path_public(&path).unwrap();

        let body = serde_json::json!({
            "default_provider": "openai",
            "default_model": "gpt-5",
            "anthropic_key": "sk-ant-x",
            "openai_key": "sk-openai-x",
            "google_key": "g-x",
            "openrouter_key": "or-x",
            "ollama_base_url": "http://ollama:11434"
        })
        .to_string();
        let resp = put_config_request(state_with_config_path(path.clone()), &body).await;
        assert_eq!(resp.status(), axum::http::StatusCode::OK);

        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let raw = std::str::from_utf8(&bytes).unwrap();
        assert!(!raw.contains("sk-ant-x"), "must not leak key values");
        let rc: RedactedConfig = serde_json::from_slice(&bytes).unwrap();
        assert!(
            rc.has_anthropic_key && rc.has_openai_key && rc.has_google_key && rc.has_openrouter_key
        );
        assert_eq!(rc.default_provider, "openai");

        let saved = Config::load_from_path_public(&path).unwrap();
        assert_eq!(
            saved.providers.anthropic_api_key.as_deref(),
            Some("sk-ant-x")
        );
        assert_eq!(
            saved.providers.openai_api_key.as_deref(),
            Some("sk-openai-x")
        );
        assert_eq!(saved.providers.google_api_key.as_deref(), Some("g-x"));
        assert_eq!(saved.openrouter_api_key.as_deref(), Some("or-x"));
        assert_eq!(saved.default_model.as_deref(), Some("gpt-5"));
        assert_eq!(
            saved.ollama_base_url.as_deref(),
            Some("http://ollama:11434")
        );
    }

    #[tokio::test]
    async fn put_config_empty_body_leaves_existing_config_untouched() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        let base = Config {
            providers: crate::config::ProviderConfig {
                anthropic_api_key: Some("sk-ant-keep".to_string()),
                openai_api_key: None,
                google_api_key: None,
                claude_code_enabled: false,
                claude_code_binary: None,
                claude_code_effort: None,
                anthropic_cache_ttl: None,
                fallback_order: Vec::new(),
            },
            ..Default::default()
        };
        base.save_to_path_public(&path).unwrap();

        let resp = put_config_request(state_with_config_path(path.clone()), "{}").await;
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let saved = Config::load_from_path_public(&path).unwrap();
        assert_eq!(
            saved.providers.anthropic_api_key.as_deref(),
            Some("sk-ant-keep")
        );
    }

    /// A gateway can be created, then edited field by field, then removed,
    /// without the caller ever holding its key.
    ///
    /// This is the whole point of the partial update reaching gateways: a
    /// browser form that had to send the key back to change a URL would have
    /// to have been given the key, which `GET /api/config` deliberately never
    /// does.
    #[tokio::test]
    async fn put_config_edits_a_gateway_without_being_told_its_key() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        Config::default().save_to_path_public(&path).unwrap();
        let state = || state_with_config_path(path.clone());

        // Create.
        let resp = put_config_request(
            state(),
            r#"{"gateways":[{"name":"groq","base_url":"https://api.groq.com","api_key":"sk-secret","script":"groq.rhai"}]}"#,
        )
        .await;
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let saved = Config::load_from_path_public(&path).unwrap();
        assert_eq!(
            saved.model_providers["groq"].script.as_deref(),
            Some("groq.rhai"),
            "the script backing the gateway is written too"
        );

        // Edit only the URL. The key is not sent, and must survive.
        let resp = put_config_request(
            state(),
            r#"{"gateways":[{"name":"groq","base_url":"https://eu.groq.com"}]}"#,
        )
        .await;
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let saved = Config::load_from_path_public(&path).unwrap();
        let gateway = &saved.model_providers["groq"];
        assert_eq!(gateway.base_url.as_deref(), Some("https://eu.groq.com"));
        assert_eq!(
            gateway.api_key.as_deref(),
            Some("sk-secret"),
            "an unsent key is left alone, not cleared"
        );

        // A second gateway leaves the first alone.
        let resp = put_config_request(state(), r#"{"gateways":[{"name":"other"}]}"#).await;
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let saved = Config::load_from_path_public(&path).unwrap();
        assert_eq!(saved.model_providers.len(), 2);

        // Remove takes a list of its own, because omitting a gateway above
        // means "leave it alone" and so can never mean "delete it".
        let resp = put_config_request(state(), r#"{"remove_gateways":["other"]}"#).await;
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let saved = Config::load_from_path_public(&path).unwrap();
        assert!(saved.model_providers.contains_key("groq"));
        assert!(!saved.model_providers.contains_key("other"));
    }

    /// The response a write returns reports the gateway the same redacted way
    /// a read does, so a form can render straight from it.
    #[tokio::test]
    async fn put_config_returns_the_gateway_redacted() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        Config::default().save_to_path_public(&path).unwrap();

        let resp = put_config_request(
            state_with_config_path(path),
            r#"{"gateways":[{"name":"groq","api_key":"sk-secret"}]}"#,
        )
        .await;
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["gateways"][0]["name"], serde_json::json!("groq"));
        assert_eq!(json["gateways"][0]["has_api_key"], serde_json::json!(true));
        assert!(
            !String::from_utf8_lossy(&body).contains("sk-secret"),
            "the write's own response must not hand the key back"
        );
    }

    #[tokio::test]
    async fn put_config_read_failure_is_500() {
        // config_path points at a directory, so reading it as a file fails.
        let dir = tempfile::tempdir().unwrap();
        let resp = put_config_request(state_with_config_path(dir.path().to_path_buf()), "{}").await;
        assert_eq!(resp.status(), axum::http::StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[tokio::test]
    async fn put_config_write_failure_is_500() {
        // The config file's parent is itself a file, so saving fails while
        // reading (a non-existent file) succeeds as defaults.
        let dir = tempfile::tempdir().unwrap();
        let blocker = dir.path().join("blocker");
        std::fs::write(&blocker, b"x").unwrap();
        let path = blocker.join("config.toml");
        let resp = put_config_request(state_with_config_path(path), "{}").await;
        assert_eq!(resp.status(), axum::http::StatusCode::INTERNAL_SERVER_ERROR);
    }

    // ─── config key validation ────────────────────────────────────────────────

    #[test]
    fn validate_key_format_covers_every_provider() {
        assert_eq!(validate_key_format("anthropic", "sk-ant-1"), (true, None));
        assert!(!validate_key_format("anthropic", "nope").0);
        assert_eq!(validate_key_format("openai", "sk-1"), (true, None));
        assert!(!validate_key_format("openai", "nope").0);
        assert_eq!(validate_key_format("google", "g"), (true, None));
        assert!(!validate_key_format("google", "  ").0);
        assert_eq!(validate_key_format("openrouter", "or"), (true, None));
        // A name this build does not know is a custom gateway, not a mistake.
        // Its key has no house format, so the only judgement available is
        // whether one was given at all.
        assert_eq!(validate_key_format("my-gateway", "anything"), (true, None));
        assert!(!validate_key_format("my-gateway", "   ").0);
    }

    // ─── custom gateways ──────────────────────────────────────────────────────

    /// The key never leaves the process, and neither does anything in `extra`.
    ///
    /// `extra` is forwarded into a provider script, so people keep credentials
    /// there. Reporting its names is what a form needs; reporting its values
    /// would be the same disclosure the `has_*_key` booleans exist to prevent.
    #[test]
    fn a_gateways_secrets_are_reported_as_presence_not_value() {
        let mut config = Config::default();
        config.model_providers.insert(
            "groq".to_string(),
            crate::config::ModelProviderConfig {
                script: Some("groq.rhai".to_string()),
                api_key: Some("sk-secret-value".to_string()),
                base_url: Some("https://api.groq.com".to_string()),
                rate_limit: None,
                extra: [(
                    "signing_secret".to_string(),
                    toml::Value::String("hunter2".to_string()),
                )]
                .into_iter()
                .collect(),
            },
        );

        let redacted = redact(&config);
        let gateway = &redacted.gateways[0];
        assert_eq!(gateway.name, "groq");
        assert_eq!(gateway.base_url.as_deref(), Some("https://api.groq.com"));
        assert!(gateway.has_api_key);
        assert_eq!(gateway.extra_keys, vec!["signing_secret".to_string()]);

        // The whole serialized document, because a leak anywhere in it is a
        // leak: a field added later would otherwise carry the value silently.
        let json = serde_json::to_string(&redacted).expect("serializes");
        assert!(!json.contains("sk-secret-value"), "{json}");
        assert!(!json.contains("hunter2"), "{json}");
    }

    /// Name-sorted, because the config holds gateways in a `HashMap` and a
    /// list that reorders itself between two reads cannot be edited in a form.
    #[test]
    fn gateways_are_reported_in_a_stable_order() {
        let mut config = Config::default();
        for name in ["zulu", "alpha", "mike"] {
            config
                .model_providers
                .insert(name.to_string(), Default::default());
        }
        let names: Vec<String> = gateways_of(&config).into_iter().map(|g| g.name).collect();
        assert_eq!(names, vec!["alpha", "mike", "zulu"]);
    }

    #[test]
    fn a_config_with_no_gateways_reports_none() {
        assert_eq!(gateways_of(&Config::default()), Vec::new());
    }

    /// A base URL is checked for shape only, and the scheme is the part people
    /// actually leave off.
    #[test]
    fn a_base_url_is_checked_for_its_scheme() {
        assert_eq!(validate_base_url("https://api.example.com"), (true, None));
        assert_eq!(validate_base_url("http://localhost:11434"), (true, None));
        assert!(!validate_base_url("api.example.com").0);
        assert!(!validate_base_url("  ").0);
    }

    #[tokio::test]
    async fn validate_config_key_endpoint_returns_result() {
        let app = Router::new().route(
            "/api/config/validate",
            axum::routing::post(validate_config_key),
        );
        let req = Request::builder()
            .method("POST")
            .uri("/api/config/validate")
            .header("content-type", "application/json")
            .body(Body::from(
                serde_json::json!({"provider":"anthropic","key":"bad"}).to_string(),
            ))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let v: ValidateKeyResp = serde_json::from_slice(&bytes).unwrap();
        assert!(!v.valid);
        assert!(v.message.is_some());
    }

    /// A gateway is checked on its URL as well as its key, and the URL is what
    /// answers when it is wrong.
    #[tokio::test]
    async fn validate_config_key_endpoint_checks_a_gateways_base_url() {
        let check = |body: serde_json::Value| async move {
            let app = Router::new().route(
                "/api/config/validate",
                axum::routing::post(validate_config_key),
            );
            let req = Request::builder()
                .method("POST")
                .uri("/api/config/validate")
                .header("content-type", "application/json")
                .body(Body::from(body.to_string()))
                .unwrap();
            let resp = app.oneshot(req).await.unwrap();
            let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .unwrap();
            serde_json::from_slice::<ValidateKeyResp>(&bytes).unwrap()
        };

        // A URL with no scheme is rejected, and the message names the URL
        // rather than the key, which is the part that is fine.
        let bad = check(serde_json::json!({
            "provider": "my-gateway",
            "key": "anything",
            "base_url": "api.example.com",
        }))
        .await;
        assert!(!bad.valid);
        assert!(
            bad.message.unwrap_or_default().contains("Base URL"),
            "the address is what is wrong"
        );

        // A good URL falls through to the key check, which for a custom
        // gateway only asks that a key was given at all.
        let good = check(serde_json::json!({
            "provider": "my-gateway",
            "key": "anything",
            "base_url": "https://api.example.com",
        }))
        .await;
        assert!(good.valid, "{:?}", good.message);

        // And an empty key still fails once the URL is fine.
        let empty = check(serde_json::json!({
            "provider": "my-gateway",
            "key": "  ",
            "base_url": "https://api.example.com",
        }))
        .await;
        assert!(!empty.valid);
    }

    #[tokio::test]
    async fn the_models_endpoint_is_empty_when_no_https_client_can_be_built() {
        let state = test_state();
        let Json(models) = super::models_with(&state, &|_t| {
            Err(leviath_providers::provider::malformed_url_error())
        })
        .await;
        assert!(models.is_empty());
    }
}