o402 0.1.5

OpenAI-compatible gateway, paid with x402.
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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
//! TOML config: whole-string `$ENV` interpolation, then `deny_unknown_fields`.

mod raw;
mod secret;

use std::fs;
use std::net::SocketAddr;
use std::path::Path;

use indexmap::IndexMap;
use serde::Deserialize;
use url::Url;

use self::raw::RawConfig;
pub(crate) use self::raw::is_loopback;
pub(crate) use self::secret::Secret;

/// Validated gateway configuration.
#[derive(Clone, Debug)]
pub struct Config {
    /// HTTP bind, body limit, CORS, shutdown.
    pub(crate) server: ServerConfig,
    /// Log level/format and optional metrics bind.
    pub(crate) observability: ObservabilityConfig,
    /// Payment gate. `/ready` uses `enabled`.
    pub(crate) payment: PaymentConfig,
    /// Upstream LLM providers.
    pub(crate) upstreams: Vec<UpstreamConfig>,
    /// Model catalog. Empty when payment is off and omitted from TOML.
    pub(crate) models: Vec<ModelConfig>,
    /// Pricing defaults. `None` when omitted and payment is off.
    pub(crate) pricing: Option<PricingConfig>,
}

/// `[server]` after defaults.
#[derive(Clone, Debug)]
pub(crate) struct ServerConfig {
    /// Listen address.
    pub(crate) bind: SocketAddr,
    /// Public origin used when payment is on.
    pub(crate) base_url: Option<Url>,
    /// Drain budget after SIGINT/SIGTERM.
    pub(crate) shutdown_timeout_secs: u64,
    /// Max buffered request body.
    pub(crate) body_limit_bytes: usize,
    /// Non-stream handler timeout.
    pub(crate) request_timeout_secs: u64,
    /// CORS origins. Empty means no CORS layer.
    pub(crate) cors_origins: Vec<String>,
}

/// `[observability]` after defaults.
#[derive(Clone, Debug)]
pub(crate) struct ObservabilityConfig {
    /// Used when `RUST_LOG` is unset.
    pub(crate) level: String,
    /// Subscriber format.
    pub(crate) format: LogFormat,
    /// Optional Prometheus bind. Off when `None`. Never the payment port.
    pub(crate) metrics_bind: Option<SocketAddr>,
}

/// Log encoder.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub(crate) enum LogFormat {
    /// `tracing-subscriber` JSON.
    #[default]
    Json,
    /// Human-readable fmt.
    Pretty,
}

/// `[payment]` after validation.
#[derive(Clone, Debug)]
pub(crate) struct PaymentConfig {
    /// When false, `/ready` is 200 and facilitator checks are skipped.
    pub(crate) enabled: bool,
    /// Missing-usage policy.
    pub(crate) missing_usage: UsagePolicy,
    /// Abort-usage policy.
    pub(crate) abort_usage: UsagePolicy,
    /// Price-tag timeout seconds.
    pub(crate) max_timeout_seconds: u64,
    /// Facilitator client settings.
    pub(crate) facilitator: Option<FacilitatorConfig>,
    /// Scheduler names.
    #[allow(dead_code, reason = "loaded from TOML")]
    pub(crate) settlement: SettlementConfig,
    /// CAIP-2 pattern → pay-to.
    pub(crate) pay_to: IndexMap<String, String>,
    /// Advertised accepts.
    pub(crate) accepts: Vec<AcceptConfig>,
}

/// `ceiling` or `floor` usage fallback.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub(crate) enum UsagePolicy {
    /// Charge the authorized ceiling.
    #[default]
    Ceiling,
    /// Charge the request floor.
    Floor,
}

/// Remote facilitator.
#[derive(Clone, Debug)]
pub(crate) struct FacilitatorConfig {
    /// Base URL. Present when payment is on.
    pub(crate) url: Option<Url>,
    /// HTTP timeout.
    pub(crate) timeout_secs: u64,
    /// `/supported` cache TTL.
    pub(crate) supported_cache_ttl_secs: u64,
    /// Path-keyed auth headers.
    pub(crate) auth: Option<FacilitatorAuth>,
}

/// Facilitator auth header maps.
#[derive(Clone, Debug)]
pub(crate) struct FacilitatorAuth {
    /// `POST /verify` headers.
    pub(crate) verify: IndexMap<String, Secret<String>>,
    /// `POST /settle` headers.
    pub(crate) settle: IndexMap<String, Secret<String>>,
    /// `GET /supported` headers.
    pub(crate) supported: IndexMap<String, Secret<String>>,
}

/// Per-(scheme, stream) scheduler names.
#[allow(dead_code, reason = "loaded from TOML")]
#[derive(Clone, Copy, Debug)]
pub(crate) struct SettlementConfig {
    /// Exact non-stream.
    pub(crate) exact_non_stream: Scheduler,
    /// Exact stream.
    pub(crate) exact_stream: Scheduler,
    /// Upto non-stream.
    pub(crate) upto_non_stream: Scheduler,
    /// Upto stream.
    pub(crate) upto_stream: Scheduler,
}

/// o402 scheduler name (not r402 `SettlementMode`).
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
pub(crate) enum Scheduler {
    /// Verify → handler → settle; attach `PAYMENT-RESPONSE`.
    #[serde(rename = "sequential-wait-settle")]
    SequentialWaitSettle,
    /// Wait for upstream 2xx headers, spawn settle, return the body.
    #[serde(rename = "wait-2xx-then-spawn")]
    Wait2xxThenSpawn,
    /// Tee SSE, settle after body end or drop.
    #[serde(rename = "stream-then-settle")]
    StreamThenSettle,
}

/// One advertised accept.
#[derive(Clone, Debug)]
pub(crate) struct AcceptConfig {
    /// `exact` or `upto`.
    pub(crate) scheme: String,
    /// CAIP-2 network.
    pub(crate) network: String,
    /// Named ticker for this namespace.
    pub(crate) asset: Option<String>,
    /// Custom asset address.
    pub(crate) asset_address: Option<String>,
    /// Custom asset decimals.
    pub(crate) decimals: Option<u32>,
    /// EVM or Tron exact transfer method.
    pub(crate) transfer_method: Option<String>,
    /// EIP-712 name.
    pub(crate) eip712_name: Option<String>,
    /// EIP-712 version.
    pub(crate) eip712_version: Option<String>,
}

/// One upstream LLM provider.
#[derive(Clone, Debug)]
pub(crate) struct UpstreamConfig {
    /// Catalog name.
    pub(crate) name: String,
    /// Origin. Path is ignored at proxy time.
    pub(crate) base_url: Url,
    /// Upstream API key.
    pub(crate) api_key: Secret<String>,
    /// Request timeout including streams.
    pub(crate) timeout_secs: u64,
    /// Connect timeout.
    pub(crate) connect_timeout_secs: u64,
    /// Set for non-HTTPS non-loopback origins.
    #[allow(dead_code, reason = "enforced at load; not read at request time")]
    pub(crate) allow_insecure: bool,
}

/// One catalog model.
#[derive(Clone, Debug)]
pub(crate) struct ModelConfig {
    /// Client-facing id.
    pub(crate) id: String,
    /// Upstream name.
    pub(crate) upstream: String,
    /// Upstream model id override.
    pub(crate) upstream_model: Option<String>,
    /// OpenAI `owned_by`.
    pub(crate) owned_by: Option<String>,
    /// Scheme override.
    pub(crate) scheme: Option<String>,
    /// Uncached input rate.
    pub(crate) input_per_million: Option<String>,
    /// Output rate.
    pub(crate) output_per_million: Option<String>,
    /// Cached input rate.
    pub(crate) cached_input_per_million: Option<String>,
    /// Reasoning rate.
    pub(crate) reasoning_per_million: Option<String>,
    /// Request floor.
    pub(crate) request_floor: Option<String>,
    /// Ceiling multiplier.
    pub(crate) ceiling_multiplier: Option<String>,
    /// Hard ceiling.
    pub(crate) max_ceiling: Option<String>,
    /// Max input tokens.
    pub(crate) max_input_tokens: Option<u32>,
    /// Default max output tokens.
    pub(crate) default_max_output_tokens: Option<u32>,
    /// Exact per-request price.
    pub(crate) price: Option<String>,
}

/// `[pricing]` after validation.
#[derive(Clone, Debug)]
pub(crate) struct PricingConfig {
    /// Defaults inherited by models.
    pub(crate) default: Option<PricingDefault>,
}

/// `[pricing.default]` after validation.
#[derive(Clone, Debug)]
pub(crate) struct PricingDefault {
    /// Default scheme.
    pub(crate) scheme: Option<String>,
    /// Default floor.
    pub(crate) request_floor: Option<String>,
    /// Default uncached input rate.
    pub(crate) input_per_million: Option<String>,
    /// Default output rate.
    pub(crate) output_per_million: Option<String>,
    /// Default cached input rate.
    pub(crate) cached_input_per_million: Option<String>,
    /// Default reasoning rate.
    pub(crate) reasoning_per_million: Option<String>,
    /// Default ceiling multiplier.
    pub(crate) ceiling_multiplier: Option<String>,
    /// Default hard ceiling.
    pub(crate) max_ceiling: Option<String>,
    /// Default max input tokens.
    pub(crate) max_input_tokens: Option<u32>,
    /// Default max output tokens.
    pub(crate) default_max_output_tokens: Option<u32>,
    /// Default exact price.
    pub(crate) price: Option<String>,
}

/// Configuration loading errors.
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    /// File could not be read.
    #[error("failed to read config file '{path}': {source}")]
    Io {
        /// Path that failed.
        path: String,
        /// Underlying IO error.
        #[source]
        source: std::io::Error,
    },
    /// TOML syntax or `deny_unknown_fields`.
    #[error("failed to parse config file '{path}': {source}")]
    Parse {
        /// Path or `"<test>"`.
        path: String,
        /// TOML / serde error.
        #[source]
        source: toml::de::Error,
    },
    /// Whole-string `$VAR` / `${VAR}` with no such environment variable.
    #[error("env var '{name}' not found (referenced as '{reference}')")]
    MissingEnv {
        /// Variable name.
        name: String,
        /// Original token (`$VAR` or `${VAR}`).
        reference: String,
    },
    /// Semantic validation failed.
    #[error("{0}")]
    Validation(String),
}

impl Config {
    /// Load TOML from `path`, interpolate whole-string env refs, validate.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError`] when the file is missing, TOML is invalid,
    /// a referenced env var is unset, or a required field fails validation.
    pub fn from_path(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
        let path = path.as_ref();
        let origin = path.display().to_string();
        let text = fs::read_to_string(path).map_err(|source| ConfigError::Io {
            path: origin.clone(),
            source,
        })?;
        Self::from_toml(origin, &text, env_lookup)
    }

    fn from_toml(
        origin: String,
        text: &str,
        lookup: impl Fn(&str) -> Option<String>,
    ) -> Result<Self, ConfigError> {
        let value: toml::Value = toml::from_str(text).map_err(|source| ConfigError::Parse {
            path: origin.clone(),
            source,
        })?;
        let value = interpolate_value(&value, &lookup)?;
        let raw: RawConfig = value.try_into().map_err(|source| ConfigError::Parse {
            path: origin,
            source,
        })?;
        raw.into_config()
    }
}

fn env_lookup(key: &str) -> Option<String> {
    std::env::var(key).ok()
}

/// Replace a string only when the entire value is `$VAR` or `${VAR}`.
fn resolve_env_impl(
    value: &str,
    lookup: impl Fn(&str) -> Option<String>,
) -> Result<String, ConfigError> {
    if let Some(var_name) = value.strip_prefix("${").and_then(|s| s.strip_suffix('}')) {
        return lookup(var_name).ok_or_else(|| ConfigError::MissingEnv {
            name: var_name.to_owned(),
            reference: value.to_owned(),
        });
    }
    if let Some(var_name) = value.strip_prefix('$')
        && !var_name.is_empty()
        && var_name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_')
    {
        return lookup(var_name).ok_or_else(|| ConfigError::MissingEnv {
            name: var_name.to_owned(),
            reference: value.to_owned(),
        });
    }
    Ok(value.to_owned())
}

fn interpolate_value(
    val: &toml::Value,
    lookup: &impl Fn(&str) -> Option<String>,
) -> Result<toml::Value, ConfigError> {
    match val {
        toml::Value::String(s) => Ok(toml::Value::String(resolve_env_impl(s, lookup)?)),
        toml::Value::Array(arr) => {
            let resolved = arr
                .iter()
                .map(|v| interpolate_value(v, lookup))
                .collect::<Result<Vec<_>, _>>()?;
            Ok(toml::Value::Array(resolved))
        }
        toml::Value::Table(table) => {
            let mut out = toml::map::Map::new();
            for (key, value) in table {
                out.insert(key.clone(), interpolate_value(value, lookup)?);
            }
            Ok(toml::Value::Table(out))
        }
        other => Ok(other.clone()),
    }
}

#[cfg(test)]
impl Config {
    pub(crate) fn from_toml_str(text: &str) -> Result<Self, ConfigError> {
        Self::from_toml("<test>".to_owned(), text, env_lookup)
    }

    pub(crate) fn from_toml_str_with(
        text: &str,
        lookup: impl Fn(&str) -> Option<String>,
    ) -> Result<Self, ConfigError> {
        Self::from_toml("<test>".to_owned(), text, lookup)
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::fs;
    use std::path::Path;

    use super::{Config, ConfigError, UsagePolicy};

    const UNPAID: &str = r#"
[payment]
enabled = false

[[upstreams]]
name = "openai"
base_url = "https://api.openai.com"
api_key = "sk-test"
"#;

    fn lookup(map: &BTreeMap<String, String>) -> impl Fn(&str) -> Option<String> + '_ {
        |key| map.get(key).cloned()
    }

    fn unpaid_with_key(api_key: &str) -> String {
        format!(
            r#"
[payment]
enabled = false

[[upstreams]]
name = "openai"
base_url = "https://api.openai.com"
api_key = "{api_key}"
"#
        )
    }

    #[test]
    fn unpaid_defaults_bind() {
        let cfg = Config::from_toml_str(UNPAID).expect("unpaid");
        assert_eq!(cfg.server.bind.to_string(), "0.0.0.0:8080", "default bind");
        assert!(cfg.observability.metrics_bind.is_none(), "metrics off");
        assert!(!cfg.payment.enabled, "payment off");
        assert_eq!(cfg.upstreams.len(), 1, "one upstream");
    }

    #[test]
    fn metrics_bind_parsed() {
        let toml = format!(
            r#"
[observability]
metrics_bind = "127.0.0.1:9090"
{UNPAID}
"#
        );
        let cfg = Config::from_toml_str(&toml).expect("metrics");
        assert_eq!(
            cfg.observability.metrics_bind.expect("set").to_string(),
            "127.0.0.1:9090",
            "metrics bind"
        );
    }

    #[test]
    fn metrics_bind_must_differ_from_server_bind() {
        let toml = format!(
            r#"
[server]
bind = "0.0.0.0:8080"

[observability]
metrics_bind = "0.0.0.0:8080"
{UNPAID}
"#
        );
        let err = Config::from_toml_str(&toml).expect_err("same bind");
        assert!(
            err.to_string().contains("metrics_bind"),
            "overlap, got {err}"
        );
    }

    #[test]
    fn metrics_bind_rejects_unspecified_vs_loopback_same_port() {
        let toml = format!(
            r#"
[server]
bind = "0.0.0.0:8080"

[observability]
metrics_bind = "127.0.0.1:8080"
{UNPAID}
"#
        );
        let err = Config::from_toml_str(&toml).expect_err("overlap");
        assert!(
            err.to_string().contains("metrics_bind"),
            "unspecified vs loopback, got {err}"
        );
    }

    #[test]
    fn metrics_bind_allows_distinct_ports() {
        let toml = format!(
            r#"
[server]
bind = "0.0.0.0:8080"

[observability]
metrics_bind = "127.0.0.1:9090"
{UNPAID}
"#
        );
        let cfg = Config::from_toml_str(&toml).expect("distinct ports");
        assert_eq!(
            cfg.observability.metrics_bind.expect("set").to_string(),
            "127.0.0.1:9090",
            "metrics on 9090"
        );
    }

    #[test]
    fn whole_string_interpolation() {
        let env = BTreeMap::from([("OPENAI_API_KEY".to_owned(), "sk-from-env".to_owned())]);
        let cfg = Config::from_toml_str_with(&unpaid_with_key("$OPENAI_API_KEY"), lookup(&env))
            .expect("interpolated");
        let key = cfg.upstreams.first().expect("upstream").api_key.expose();
        assert_eq!(key, "sk-from-env", "$VAR");
    }

    #[test]
    fn brace_interpolation() {
        let env = BTreeMap::from([("OPENAI_API_KEY".to_owned(), "sk-braces".to_owned())]);
        let cfg = Config::from_toml_str_with(&unpaid_with_key("${OPENAI_API_KEY}"), lookup(&env))
            .expect("interpolated");
        let key = cfg.upstreams.first().expect("upstream").api_key.expose();
        assert_eq!(key, "sk-braces", "${{VAR}}");
    }

    #[test]
    fn bearer_prefix_stays_literal() {
        let env = BTreeMap::from([("X".to_owned(), "leaked".to_owned())]);
        let cfg = Config::from_toml_str_with(&unpaid_with_key("Bearer $X"), lookup(&env))
            .expect("literal");
        let key = cfg.upstreams.first().expect("upstream").api_key.expose();
        assert_eq!(key, "Bearer $X", "embedded $VAR is not expanded");
    }

    #[test]
    fn missing_var_is_error() {
        let env = BTreeMap::new();
        let err = Config::from_toml_str_with(&unpaid_with_key("$MISSING_O402"), lookup(&env))
            .expect_err("missing");
        assert!(
            matches!(
                &err,
                ConfigError::MissingEnv { name, reference }
                    if name == "MISSING_O402" && reference == "$MISSING_O402"
            ),
            "expected MissingEnv, got {err}"
        );
    }

    #[test]
    fn deny_unknown_keys() {
        let toml = format!(
            r#"
[server]
bind = "0.0.0.0:8080"
not_a_field = true
{UNPAID}
"#
        );
        let err = Config::from_toml_str(&toml).expect_err("unknown");
        let msg = err.to_string();
        assert!(
            msg.contains("not_a_field") || msg.contains("unknown"),
            "serde unknown-field message, got {msg}"
        );
    }

    #[test]
    fn payment_on_without_facilitator_fails() {
        let toml = r#"
[server]
base_url = "https://o402.example.com"

[payment]
enabled = true

[[upstreams]]
name = "openai"
base_url = "https://api.openai.com"
api_key = "sk-test"
"#;
        let err = Config::from_toml_str(toml).expect_err("facilitator");
        assert!(
            err.to_string().contains("facilitator"),
            "facilitator required, got {err}"
        );
    }

    #[test]
    fn unpaid_example_file_loads() {
        let text = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/unpaid.example.toml"));
        let env = BTreeMap::from([("OPENAI_API_KEY".to_owned(), "sk-example".to_owned())]);
        let cfg = Config::from_toml_str_with(text, lookup(&env)).expect("example");
        assert!(!cfg.payment.enabled, "example is unpaid");
        assert_eq!(
            cfg.upstreams.first().expect("upstream").api_key.expose(),
            "sk-example",
            "example interpolates OPENAI_API_KEY"
        );
        assert_eq!(cfg.models.len(), 1, "example catalogs a model");
        assert_eq!(
            cfg.models.first().expect("model").id,
            "gpt-4o-mini",
            "example model id"
        );
    }

    #[test]
    fn paid_example_file_loads() {
        let text = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/paid.example.toml"));
        let env = BTreeMap::from([
            (
                "O402_EVM_PAY_TO".to_owned(),
                "0x0000000000000000000000000000000000000001".to_owned(),
            ),
            (
                "O402_SOLANA_PAY_TO".to_owned(),
                "11111111111111111111111111111111".to_owned(),
            ),
            ("OPENAI_API_KEY".to_owned(), "sk-example".to_owned()),
            ("BIFROST_API_KEY".to_owned(), "sk-o402".to_owned()),
            (
                "FACILITATOR_AUTH_HEADER".to_owned(),
                "Bearer example-token".to_owned(),
            ),
        ]);
        let cfg = Config::from_toml_str_with(text, lookup(&env)).expect("example");
        assert!(cfg.payment.enabled, "example is paid");
        assert_eq!(
            cfg.payment.abort_usage,
            UsagePolicy::Floor,
            "stop charges floor"
        );
        assert_eq!(cfg.models.len(), 0, "catalog optional");
        assert_eq!(
            cfg.upstreams.first().expect("upstream").name,
            "bifrost",
            "bifrost upstream"
        );
        assert_eq!(
            cfg.payment
                .accepts
                .iter()
                .filter(|accept| accept.scheme == "upto")
                .count(),
            2,
            "evm upto accepts"
        );
        assert!(
            cfg.payment
                .accepts
                .iter()
                .any(|accept| accept.scheme == "exact" && accept.network.starts_with("solana:")),
            "svm exact"
        );
        drop(crate::http::app(cfg).expect("example router"));
    }

    #[test]
    fn crate_examples_match_deploy() {
        let root = Path::new(env!("CARGO_MANIFEST_DIR"));
        for (crate_rel, deploy_rel) in [
            (
                "unpaid.example.toml",
                "../../deploy/gateway.unpaid.example.toml",
            ),
            ("paid.example.toml", "../../deploy/gateway.example.toml"),
        ] {
            let deploy = root.join(deploy_rel);
            if !deploy.exists() {
                continue;
            }
            let packaged = fs::read_to_string(root.join(crate_rel)).expect(crate_rel);
            let operator = fs::read_to_string(&deploy).expect(deploy_rel);
            assert_eq!(packaged, operator, "{crate_rel} vs {deploy_rel}");
        }
    }

    fn paid_exact(accepts: &str, extra_model: &str) -> String {
        format!(
            r#"
[server]
base_url = "https://o402.example.com"

[payment]
enabled = true

[payment.facilitator]
url = "http://127.0.0.1:9"

[payment.pay_to]
"eip155:*" = "0x0000000000000000000000000000000000000001"

{accepts}

[pricing.default]
scheme = "exact"
price = "0.001"
request_floor = "0.00001"
input_per_million = "0.15"
output_per_million = "0.60"
max_input_tokens = 128000
default_max_output_tokens = 16384

[[upstreams]]
name = "openai"
base_url = "https://api.openai.com"
api_key = "sk-test"

[[models]]
id = "gpt-4o-mini"
upstream = "openai"
{extra_model}
"#
        )
    }

    #[test]
    fn empty_accepts_when_enabled_fails() {
        let err = Config::from_toml_str(&paid_exact("", "")).expect_err("empty");
        assert!(
            err.to_string().contains("accepts"),
            "empty accepts, got {err}"
        );
    }

    #[test]
    fn svm_upto_is_rejected() {
        let toml = paid_exact(
            r#"
[[payment.accepts]]
scheme = "upto"
network = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"
asset = "usdc"
"#,
            "",
        );
        let err = Config::from_toml_str(&toml).expect_err("svm upto");
        assert!(
            err.to_string().contains("eip155"),
            "svm upto rejected, got {err}"
        );
    }

    #[test]
    fn eip155_upto_accept_loads() {
        let toml = r#"
[server]
base_url = "https://o402.example.com"

[payment]
enabled = true

[payment.facilitator]
url = "http://127.0.0.1:9"

[payment.pay_to]
"eip155:*" = "0x0000000000000000000000000000000000000001"

[[payment.accepts]]
scheme = "upto"
network = "eip155:8453"
asset = "usdc"

[pricing.default]
scheme = "upto"
price = "0.001"
request_floor = "0.00001"
input_per_million = "0.15"
output_per_million = "0.60"
max_input_tokens = 128000
default_max_output_tokens = 16384

[[upstreams]]
name = "openai"
base_url = "https://api.openai.com"
api_key = "sk-test"

[[models]]
id = "gpt-4o-mini"
upstream = "openai"
"#;
        let cfg = Config::from_toml_str(toml).expect("upto");
        assert_eq!(
            cfg.payment
                .accepts
                .first()
                .map(|accept| accept.scheme.as_str()),
            Some("upto"),
            "upto accept"
        );
    }

    #[test]
    fn upto_without_input_rate_fails() {
        let toml = r#"
[server]
base_url = "https://o402.example.com"

[payment]
enabled = true

[payment.facilitator]
url = "http://127.0.0.1:9"

[payment.pay_to]
"eip155:*" = "0x0000000000000000000000000000000000000001"

[[payment.accepts]]
scheme = "upto"
network = "eip155:8453"
asset = "usdc"

[pricing.default]
scheme = "upto"
max_input_tokens = 128000

[[upstreams]]
name = "openai"
base_url = "https://api.openai.com"
api_key = "sk-test"

[[models]]
id = "gpt-4o-mini"
upstream = "openai"
"#;
        let err = Config::from_toml_str(toml).expect_err("input");
        assert!(
            err.to_string().contains("input_per_million")
                || err.to_string().contains("pricing.default"),
            "upto input, got {err}"
        );
    }

    #[test]
    fn upto_chat_without_output_rate_fails() {
        let toml = r#"
[server]
base_url = "https://o402.example.com"

[payment]
enabled = true

[payment.facilitator]
url = "http://127.0.0.1:9"

[payment.pay_to]
"eip155:*" = "0x0000000000000000000000000000000000000001"

[[payment.accepts]]
scheme = "upto"
network = "eip155:8453"
asset = "usdc"

[pricing.default]
scheme = "upto"
input_per_million = "0.15"
max_input_tokens = 128000

[[upstreams]]
name = "openai"
base_url = "https://api.openai.com"
api_key = "sk-test"

[[models]]
id = "gpt-4o-mini"
upstream = "openai"
default_max_output_tokens = 16384
"#;
        let err = Config::from_toml_str(toml).expect_err("output");
        assert!(
            err.to_string().contains("output_per_million")
                || err.to_string().contains("pricing.default"),
            "upto output, got {err}"
        );
    }

    #[test]
    fn upto_chat_inherits_default_output_rate() {
        let toml = r#"
[server]
base_url = "https://o402.example.com"

[payment]
enabled = true

[payment.facilitator]
url = "http://127.0.0.1:9"

[payment.pay_to]
"eip155:*" = "0x0000000000000000000000000000000000000001"

[[payment.accepts]]
scheme = "upto"
network = "eip155:8453"
asset = "usdc"

[pricing.default]
scheme = "upto"
price = "0.001"
request_floor = "0.00001"
input_per_million = "0.15"
output_per_million = "0.60"
cached_input_per_million = "0.075"
reasoning_per_million = "0.60"
max_ceiling = "5.00"
max_input_tokens = 128000
default_max_output_tokens = 16384

[[upstreams]]
name = "openai"
base_url = "https://api.openai.com"
api_key = "sk-test"

[[models]]
id = "gpt-4o-mini"
upstream = "openai"
"#;
        let cfg = Config::from_toml_str(toml).expect("inherit");
        let rates =
            crate::payment::tags::validate_payment(&cfg.payment, &cfg.models, cfg.pricing.as_ref())
                .expect("rates");
        let mini = rates.models.get("gpt-4o-mini").expect("mini");
        assert_eq!(mini.ppm.output, 600_000, "inherited output ppm");
        assert_eq!(
            crate::payment::price::ceiling_or_price(
                mini,
                u128::from(mini.default_max_output),
                false,
            ),
            29_040,
            "inherit-all chat ceiling"
        );
    }

    #[test]
    fn exact_without_price_fails() {
        let toml = r#"
[server]
base_url = "https://o402.example.com"

[payment]
enabled = true

[payment.facilitator]
url = "http://127.0.0.1:9"

[payment.pay_to]
"eip155:*" = "0x0000000000000000000000000000000000000001"

[[payment.accepts]]
scheme = "exact"
network = "eip155:8453"
asset = "usdc"

[pricing.default]
scheme = "exact"

[[upstreams]]
name = "openai"
base_url = "https://api.openai.com"
api_key = "sk-test"

[[models]]
id = "gpt-4o-mini"
upstream = "openai"
"#;
        let err = Config::from_toml_str(toml).expect_err("price");
        assert!(err.to_string().contains("price"), "exact price, got {err}");
    }
}