recursive-agent 0.2.0

A minimal, orthogonal, self-improving coding agent kernel in Rust
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
//! LLM provider abstraction.
//!
//! A provider takes a transcript plus tool specs and returns either
//! free-form content, structured tool calls, or both. The trait is the
//! only thing the agent depends on; everything beyond it (HTTP, retries,
//! mocking) lives in adapters.

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::path::Path;

use crate::error::Error;
use crate::error::Result;
use crate::message::Message;

use tokio::sync::mpsc;

#[cfg(feature = "anthropic")]
pub mod anthropic;
pub mod mock;
pub mod openai;

#[cfg(feature = "anthropic")]
pub use anthropic::AnthropicProvider;
pub use mock::MockProvider;
pub use openai::OpenAiProvider;

/// Channel sender for streaming partial tokens during a streaming LLM call.
/// Each `String` is a delta chunk (partial token) emitted by the provider.
pub type StreamSender = mpsc::UnboundedSender<String>;

/// Token usage data from an LLM response.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenUsage {
    pub prompt_tokens: u32,
    pub completion_tokens: u32,
    pub total_tokens: u32,
    pub cache_hit_tokens: u32,
    pub cache_miss_tokens: u32,
}

impl TokenUsage {
    /// Saturating element-wise sum. Used to accumulate across LLM calls.
    pub fn accumulate(self, other: TokenUsage) -> TokenUsage {
        TokenUsage {
            prompt_tokens: self.prompt_tokens.saturating_add(other.prompt_tokens),
            completion_tokens: self
                .completion_tokens
                .saturating_add(other.completion_tokens),
            total_tokens: self.total_tokens.saturating_add(other.total_tokens),
            cache_hit_tokens: self.cache_hit_tokens.saturating_add(other.cache_hit_tokens),
            cache_miss_tokens: self
                .cache_miss_tokens
                .saturating_add(other.cache_miss_tokens),
        }
    }
}

/// Per-million-token pricing for one model. USD.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ModelPricing {
    pub input_per_million: f64,
    pub output_per_million: f64,
    /// Price per million tokens for cache-hit prompts.
    /// Defaults to 10% of input rate (DeepSeek's known discount).
    pub cache_hit_input_per_million: f64,
}

impl ModelPricing {
    /// USD cost for the given usage at this pricing.
    pub fn cost_usd(&self, usage: TokenUsage) -> f64 {
        let in_cost = if usage.cache_hit_tokens > 0 {
            // Apply cache-hit discount: use cache_hit_input_per_million for cached tokens
            let cache_hit =
                usage.cache_hit_tokens as f64 * self.cache_hit_input_per_million / 1_000_000.0;
            // Use full rate for cache-miss tokens (which is prompt - cache_hit)
            // Note: cache_miss_tokens may not equal prompt - cache_hit due to rounding,
            // but the difference is negligible for billing purposes
            let cache_miss = usage.cache_miss_tokens as f64 * self.input_per_million / 1_000_000.0;
            cache_hit + cache_miss
        } else {
            (usage.prompt_tokens as f64) * self.input_per_million / 1_000_000.0
        };
        let out_cost = (usage.completion_tokens as f64) * self.output_per_million / 1_000_000.0;
        in_cost + out_cost
    }
}

/// Returns pricing for known models, or None if unknown.
pub fn pricing_for(model: &str) -> Option<ModelPricing> {
    match model {
        "MiniMax-M2" => Some(ModelPricing {
            input_per_million: 0.30,
            output_per_million: 1.20,
            // No known cache discount; use full rate (conservative)
            cache_hit_input_per_million: 0.30,
        }),
        "deepseek-chat" | "deepseek-v4-flash" => Some(ModelPricing {
            input_per_million: 0.27,
            output_per_million: 1.10,
            // DeepSeek: cache hit = 10% of input rate
            cache_hit_input_per_million: 0.027,
        }),
        // V4-Pro is ~7× flash on input; placeholder until calibrated
        // against the DeepSeek billing dashboard.
        "deepseek-v4-pro" => Some(ModelPricing {
            input_per_million: 1.89,
            output_per_million: 7.70,
            // DeepSeek: cache hit = 10% of input rate
            cache_hit_input_per_million: 0.189,
        }),
        "glm-4-flash" => Some(ModelPricing {
            input_per_million: 0.10,
            output_per_million: 0.10,
            // No known cache discount; use full rate
            cache_hit_input_per_million: 0.10,
        }),
        // GLM-5.1 pricing is currently a placeholder pending official
        // confirmation; the per-run `cost: $X` line will be approximate
        // until calibrated against the Zhipu billing dashboard.
        "glm-5.1" => Some(ModelPricing {
            input_per_million: 0.50,
            output_per_million: 2.00,
            // No known cache discount; use full rate
            cache_hit_input_per_million: 0.50,
        }),
        _ => {
            // Unknown model: use conservative default (full rate for cache hits,
            // i.e., no discount). This matches the goal spec: "use full rate
            // (conservative)".
            None
        }
    }
}

/// Load pricing from a YAML file.
/// The file should have a "models" key mapping model names to pricing structs.
/// Returns a HashMap of model name -> ModelPricing.
pub fn load_pricing_from_yaml(path: &Path) -> Result<HashMap<String, ModelPricing>> {
    use std::fs;
    use std::io::{self, BufRead};

    let file = fs::File::open(path).map_err(Error::Io)?;
    let reader = io::BufReader::new(file);

    let mut models: HashMap<String, ModelPricing> = HashMap::new();
    let mut current_model: Option<String> = None;
    let mut current_pricing: Option<ModelPricingBuilder> = None;
    let mut in_models_section = false;

    // Simple YAML parser for the flat structure we expect.
    // Lines are either:
    //   models:
    //   <model_name>:
    //     key: value
    for line in reader.lines() {
        let line = line.map_err(Error::Io)?;

        // Skip empty lines and comments
        if line.trim().is_empty() || line.trim().starts_with('#') {
            continue;
        }

        // Count leading spaces to determine indentation level
        let leading_spaces = line.len() - line.trim_start().len();
        let trimmed = line.trim();

        // Top-level "models:" key
        if trimmed == "models:" {
            in_models_section = true;
            continue;
        }

        // If we're in the models section
        if in_models_section {
            // Model name line: 2 spaces indent, ends with colon
            // e.g., "  deepseek-chat:" -> model name is "deepseek-chat"
            if leading_spaces == 2 && trimmed.ends_with(':') {
                // Save previous model if any
                if let (Some(name), Some(builder)) = (current_model.take(), current_pricing.take())
                {
                    if let Some(pricing) = builder.build() {
                        models.insert(name, pricing);
                    }
                }
                // Extract model name (remove trailing colon)
                let model_name = trimmed.trim_end_matches(':').to_string();
                current_model = Some(model_name);
                current_pricing = Some(ModelPricingBuilder::default());
                continue;
            }

            // Field line: 4+ spaces indent, contains "key: value"
            // e.g., "    input_per_million: 0.27"
            if leading_spaces >= 4 && current_model.is_some() {
                if let Some(ref mut builder) = current_pricing {
                    if let Some((key, value)) = trimmed.split_once(':') {
                        let key = key.trim();
                        // Strip inline comments: "0.027  # 10% of input" → "0.027"
                        let value = value.split('#').next().unwrap_or(value).trim();
                        if let Err(e) = builder.parse_field(key, value) {
                            return Err(Error::Config {
                                message: format!("error parsing {}: {}", path.display(), e),
                            });
                        }
                    }
                }
            }
        }
    }

    // Save last model
    if let (Some(name), Some(builder)) = (current_model, current_pricing) {
        if let Some(pricing) = builder.build() {
            models.insert(name, pricing);
        }
    }

    Ok(models)
}

/// Helper to build ModelPricing from YAML fields.
#[derive(Default)]
struct ModelPricingBuilder {
    input_per_million: Option<f64>,
    output_per_million: Option<f64>,
    cache_hit_input_per_million: Option<f64>,
}

impl ModelPricingBuilder {
    fn parse_field(&mut self, key: &str, value: &str) -> Result<(), String> {
        let value: f64 = value
            .parse()
            .map_err(|_| format!("invalid float: {}", value))?;
        match key {
            "input_per_million" => self.input_per_million = Some(value),
            "output_per_million" => self.output_per_million = Some(value),
            "cache_hit_input_per_million" => self.cache_hit_input_per_million = Some(value),
            _ => return Err(format!("unknown field: {}", key)),
        }
        Ok(())
    }

    fn build(self) -> Option<ModelPricing> {
        Some(ModelPricing {
            input_per_million: self.input_per_million?,
            output_per_million: self.output_per_million?,
            cache_hit_input_per_million: self
                .cache_hit_input_per_million
                .unwrap_or(self.input_per_million.unwrap_or(0.0)),
        })
    }
}

/// JSON-schema description of a tool, sent verbatim to the model.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolSpec {
    pub name: String,
    pub description: String,
    /// JSON Schema object describing the tool's input.
    pub parameters: Value,
}

/// A structured request to invoke one of the registered tools.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCall {
    pub id: String,
    pub name: String,
    /// Raw JSON arguments as produced by the model.
    pub arguments: Value,
}

/// Request for a structured JSON response conforming to a JSON schema.
pub struct StructuredRequest {
    pub messages: Vec<Message>,
    /// JSON Schema describing the expected response shape.
    pub schema: Value,
    /// Name for the schema (sent to the provider as `schema_name`).
    pub schema_name: String,
}

/// One step of model output.
#[derive(Debug, Clone)]
pub struct Completion {
    pub content: String,
    pub tool_calls: Vec<ToolCall>,
    pub finish_reason: Option<String>,
    pub usage: Option<TokenUsage>,
}

#[async_trait]
pub trait LlmProvider: Send + Sync {
    async fn complete(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<Completion>;

    /// Request a JSON response conforming to a caller-supplied schema.
    /// Default impl returns an error. Providers that support structured
    /// output (e.g. OpenAI-compatible) override this.
    async fn complete_structured(&self, _req: StructuredRequest) -> Result<Value> {
        Err(Error::Config {
            message: "provider does not support structured output".into(),
        })
    }

    /// Stream a completion token-by-token.
    ///
    /// The default implementation delegates to [`LlmProvider::complete`] and emits the
    /// entire content as a single delta via the channel (if configured).
    /// Providers that support native SSE streaming should override this.
    ///
    /// The `stream_tx` channel receives partial-token deltas as they are
    /// parsed. The returned `Completion` is the fully accumulated result.
    async fn stream(
        &self,
        messages: &[Message],
        tools: &[ToolSpec],
        stream_tx: Option<StreamSender>,
    ) -> Result<Completion> {
        let completion = self.complete(messages, tools).await?;
        if let Some(tx) = stream_tx {
            if !completion.content.is_empty() {
                let _ = tx.send(completion.content.clone());
            }
        }
        Ok(completion)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn mock_structured_returns_default_error() {
        // MockProvider overrides complete_structured. When no structured
        // responses are configured, it returns an error (triggering fallback).
        let provider = MockProvider::new(vec![]).with_structured_responses(vec![]);
        let req = StructuredRequest {
            messages: vec![Message::user("hi".to_string())],
            schema: serde_json::json!({"type": "object", "properties": {"answer": {"type": "string"}}}),
            schema_name: "test_schema".to_string(),
        };
        let result = provider.complete_structured(req).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("no structured responses configured"),
            "error should mention no structured responses: {msg}"
        );
    }

    #[test]
    fn token_usage_default_is_all_zeros() {
        let u = TokenUsage::default();
        assert_eq!(u.prompt_tokens, 0);
        assert_eq!(u.completion_tokens, 0);
        assert_eq!(u.total_tokens, 0);
    }

    #[test]
    fn token_usage_accumulate_is_saturating() {
        let u1 = TokenUsage {
            prompt_tokens: 10,
            completion_tokens: 5,
            total_tokens: 15,
            cache_hit_tokens: 0,
            cache_miss_tokens: 0,
        };
        let u2 = TokenUsage {
            prompt_tokens: 20,
            completion_tokens: 30,
            total_tokens: 50,
            cache_hit_tokens: 0,
            cache_miss_tokens: 0,
        };
        let acc = u1.accumulate(u2);
        assert_eq!(acc.prompt_tokens, 30);
        assert_eq!(acc.completion_tokens, 35);
        assert_eq!(acc.total_tokens, 65);
    }

    #[test]
    fn token_usage_accumulate_is_commutative() {
        let u1 = TokenUsage {
            prompt_tokens: 10,
            completion_tokens: 5,
            total_tokens: 15,
            cache_hit_tokens: 0,
            cache_miss_tokens: 0,
        };
        let u2 = TokenUsage {
            prompt_tokens: 20,
            completion_tokens: 30,
            total_tokens: 50,
            cache_hit_tokens: 0,
            cache_miss_tokens: 0,
        };
        assert_eq!(u1.accumulate(u2), u2.accumulate(u1));
    }

    #[test]
    fn token_usage_accumulate_saturates() {
        let u1 = TokenUsage {
            prompt_tokens: u32::MAX,
            completion_tokens: 1,
            total_tokens: u32::MAX,
            cache_hit_tokens: 0,
            cache_miss_tokens: 0,
        };
        let u2 = TokenUsage {
            prompt_tokens: 1,
            completion_tokens: u32::MAX,
            total_tokens: u32::MAX,
            cache_hit_tokens: 0,
            cache_miss_tokens: 0,
        };
        let acc = u1.accumulate(u2);
        assert_eq!(acc.prompt_tokens, u32::MAX);
        assert_eq!(acc.completion_tokens, u32::MAX);
        assert_eq!(acc.total_tokens, u32::MAX);
    }

    #[test]
    fn cost_usd_handles_zero_usage() {
        let pricing = ModelPricing {
            input_per_million: 1.0,
            output_per_million: 2.0,
            cache_hit_input_per_million: 0.1, // 10% discount
        };
        let usage = TokenUsage::default();
        let cost = pricing.cost_usd(usage);
        assert!((cost - 0.0).abs() < 1e-9);
    }

    #[test]
    fn cost_usd_computes_simple_case() {
        let pricing = ModelPricing {
            input_per_million: 1.0,
            output_per_million: 1.0,
            cache_hit_input_per_million: 0.1,
        };
        // 1M input tokens, 0 output
        let usage = TokenUsage {
            prompt_tokens: 1_000_000,
            completion_tokens: 0,
            total_tokens: 1_000_000,
            cache_hit_tokens: 0,
            cache_miss_tokens: 0,
        };
        let cost = pricing.cost_usd(usage);
        assert!((cost - 1.0).abs() < 1e-9);
    }

    #[test]
    fn cost_usd_mixes_input_and_output() {
        let pricing = ModelPricing {
            input_per_million: 1.0,
            output_per_million: 2.0,
            cache_hit_input_per_million: 0.1,
        };
        // 500K input + 250K output
        let usage = TokenUsage {
            prompt_tokens: 500_000,
            completion_tokens: 250_000,
            total_tokens: 750_000,
            cache_hit_tokens: 0,
            cache_miss_tokens: 0,
        };
        let cost = pricing.cost_usd(usage);
        // 0.5 * 1.0 + 0.25 * 2.0 = 0.5 + 0.5 = 1.0
        assert!((cost - 1.0).abs() < 1e-9);
    }

    #[test]
    fn pricing_for_known_models() {
        let p1 = pricing_for("MiniMax-M2");
        assert!(p1.is_some());
        assert!((p1.unwrap().input_per_million - 0.30).abs() < 1e-9);

        let p2 = pricing_for("deepseek-chat");
        assert!(p2.is_some());
        assert!((p2.unwrap().input_per_million - 0.27).abs() < 1e-9);
    }

    #[test]
    fn pricing_for_unknown_returns_none() {
        let p = pricing_for("unknown-model-xyz");
        assert!(p.is_none());
    }

    #[test]
    fn token_usage_accumulate_cache_fields() {
        let u1 = TokenUsage {
            prompt_tokens: 100,
            completion_tokens: 50,
            total_tokens: 150,
            cache_hit_tokens: 60,
            cache_miss_tokens: 40,
        };
        let u2 = TokenUsage {
            prompt_tokens: 200,
            completion_tokens: 100,
            total_tokens: 300,
            cache_hit_tokens: 120,
            cache_miss_tokens: 80,
        };
        let acc = u1.accumulate(u2);
        assert_eq!(acc.cache_hit_tokens, 180);
        assert_eq!(acc.cache_miss_tokens, 120);
        assert_eq!(acc.prompt_tokens, 300);
        assert_eq!(acc.completion_tokens, 150);
        assert_eq!(acc.total_tokens, 450);
    }

    /// Backward compat: cache_hit_tokens = 0 should return same as before.
    #[test]
    fn cost_usd_with_no_cache_hit_matches_old_behavior() {
        let pricing = ModelPricing {
            input_per_million: 1.0,
            output_per_million: 2.0,
            cache_hit_input_per_million: 0.1, // 10% discount
        };
        // No cache hits
        let usage = TokenUsage {
            prompt_tokens: 1_000_000,
            completion_tokens: 500_000,
            total_tokens: 1_500_000,
            cache_hit_tokens: 0,
            cache_miss_tokens: 1_000_000,
        };
        // Old calculation: 1M * $1/M + 500K * $2/M = $1.00 + $1.00 = $2.00
        let cost = pricing.cost_usd(usage);
        assert!((cost - 2.0).abs() < 1e-9);
    }

    /// Cache hit tokens get discounted rate (DeepSeek 10% of input rate).
    #[test]
    fn cost_usd_with_cache_hit_applies_discount() {
        // DeepSeek pricing: $0.27/M input, $0.027/M for cache hits
        let pricing = ModelPricing {
            input_per_million: 0.27,
            output_per_million: 1.10,
            cache_hit_input_per_million: 0.027,
        };
        // 900 cache hit + 100 cache miss = 1000 prompt tokens
        let usage = TokenUsage {
            prompt_tokens: 1_000,
            completion_tokens: 500,
            total_tokens: 1_500,
            cache_hit_tokens: 900,
            cache_miss_tokens: 100,
        };
        let cost = pricing.cost_usd(usage);
        // Cache hit: 900 * 0.027/1M = 0.0000243
        // Cache miss: 100 * 0.27/1M = 0.000027
        // Output: 500 * 1.10/1M = 0.00055
        // Total: 0.0000243 + 0.000027 + 0.00055 = 0.0006013
        let expected =
            900.0 * 0.027 / 1_000_000.0 + 100.0 * 0.27 / 1_000_000.0 + 500.0 * 1.10 / 1_000_000.0;
        assert!((cost - expected).abs() < 1e-9);
    }

    /// Verify known model has correct cache-hit pricing.
    #[test]
    fn pricing_for_deepseek_has_cache_discount() {
        let pricing = pricing_for("deepseek-chat").expect("deepseek-chat should be known");
        // Input: $0.27/M, cache hit should be 10% = $0.027/M
        assert!((pricing.input_per_million - 0.27).abs() < 1e-9);
        assert!((pricing.cache_hit_input_per_million - 0.027).abs() < 1e-9);
    }

    /// Unknown model returns None (cost won't be printed - conservative).
    #[test]
    fn pricing_for_unknown_model_returns_none() {
        let p = pricing_for("unknown-model-xyz");
        assert!(p.is_none());
    }

    /// Verify accumulated TokenUsage preserves cache_hit_tokens sum.
    #[test]
    fn token_usage_accumulate_preserves_cache_tokens() {
        let u1 = TokenUsage {
            prompt_tokens: 1000,
            completion_tokens: 100,
            total_tokens: 1100,
            cache_hit_tokens: 900,
            cache_miss_tokens: 100,
        };
        let u2 = TokenUsage {
            prompt_tokens: 2000,
            completion_tokens: 200,
            total_tokens: 2200,
            cache_hit_tokens: 1800,
            cache_miss_tokens: 200,
        };
        let acc = u1.accumulate(u2);
        assert_eq!(acc.cache_hit_tokens, 2700);
        assert_eq!(acc.cache_miss_tokens, 300);
        assert_eq!(acc.prompt_tokens, 3000);
    }

    /// Test loading pricing from YAML file.
    #[test]
    fn load_pricing_from_yaml_parses_file() {
        let temp_dir = std::env::temp_dir();
        let yaml_path = temp_dir.join("test_pricing.yaml");
        std::fs::write(
            &yaml_path,
            r#"
models:
  test-model:
    input_per_million: 1.0
    output_per_million: 2.0
    cache_hit_input_per_million: 0.1
"#,
        )
        .unwrap();

        let result = load_pricing_from_yaml(&yaml_path);
        assert!(result.is_ok(), "load should succeed: {:?}", result.err());
        let pricing = result.unwrap();
        assert!(
            pricing.contains_key("test-model"),
            "should contain test-model: {:?}",
            pricing.keys().collect::<Vec<_>>()
        );
        let p = pricing.get("test-model").unwrap();
        assert!((p.input_per_million - 1.0).abs() < 1e-9);
        assert!((p.output_per_million - 2.0).abs() < 1e-9);
        assert!((p.cache_hit_input_per_million - 0.1).abs() < 1e-9);

        std::fs::remove_file(&yaml_path).ok();
    }

    /// Test external pricing overrides hardcoded values.
    #[test]
    fn load_pricing_from_yaml_overrides_hardcoded() {
        let temp_dir = std::env::temp_dir();
        let yaml_path = temp_dir.join("test_pricing_override.yaml");
        // Override deepseek-chat with a different rate
        std::fs::write(
            &yaml_path,
            r#"
models:
  deepseek-chat:
    input_per_million: 99.0
    output_per_million: 99.0
    cache_hit_input_per_million: 9.9
"#,
        )
        .unwrap();

        let result = load_pricing_from_yaml(&yaml_path);
        assert!(result.is_ok());
        let pricing = result.unwrap();
        let p = pricing
            .get("deepseek-chat")
            .expect("should have deepseek-chat");
        // Verify the override is loaded
        assert!((p.input_per_million - 99.0).abs() < 1e-9);

        // Hardcoded should still work for other models
        assert!(pricing.contains_key("deepseek-chat"));
        // MiniMax-M2 is not in the external file, so it shouldn't be here
        assert!(!pricing.contains_key("MiniMax-M2"));

        std::fs::remove_file(&yaml_path).ok();
    }

    /// Test missing model falls back to hardcoded.
    #[test]
    fn load_pricing_from_yaml_missing_model_falls_back() {
        // When loading external pricing, models not in the external file
        // should return None from pricing_for, which falls back to hardcoded.
        // This is tested by verifying pricing_for still returns hardcoded
        // values for models not in the external file.
        let temp_dir = std::env::temp_dir();
        let yaml_path = temp_dir.join("test_pricing_partial.yaml");
        // Only include one model
        std::fs::write(
            &yaml_path,
            r#"
models:
  test-only:
    input_per_million: 1.0
    output_per_million: 1.0
    cache_hit_input_per_million: 0.1
"#,
        )
        .unwrap();

        let result = load_pricing_from_yaml(&yaml_path);
        assert!(result.is_ok());
        let external = result.unwrap();

        // External has only test-only
        assert!(
            external.contains_key("test-only"),
            "should have test-only: {:?}",
            external.keys().collect::<Vec<_>>()
        );
        // MiniMax-M2 is NOT in external, so pricing_for should return hardcoded
        let fallback = pricing_for("MiniMax-M2");
        assert!(fallback.is_some());
        assert!((fallback.unwrap().input_per_million - 0.30).abs() < 1e-9);

        std::fs::remove_file(&yaml_path).ok();
    }

    /// Test malformed YAML returns descriptive error.
    #[test]
    fn load_pricing_from_yaml_malformed_error() {
        let temp_dir = std::env::temp_dir();
        let yaml_path = temp_dir.join("test_pricing_malformed.yaml");
        // Invalid YAML (invalid float value)
        std::fs::write(
            &yaml_path,
            r#"
models:
  bad-model:
    input_per_million: not_a_number
"#,
        )
        .unwrap();

        let result = load_pricing_from_yaml(&yaml_path);
        assert!(result.is_err(), "should fail with bad data");
        let err = result.unwrap_err();
        // Should contain some error message
        let err_str = err.to_string();
        assert!(
            err_str.contains("error parsing") || err_str.contains("invalid float"),
            "error should mention parsing issue: {}",
            err_str
        );

        std::fs::remove_file(&yaml_path).ok();
    }
}