yoagent 0.12.0

Simple, effective agent loop with tool execution and event streaming
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
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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
//! Model configuration and provider compatibility flags.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Which API protocol a model uses.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApiProtocol {
    AnthropicMessages,
    OpenAiCompletions,
    OpenAiResponses,
    AzureOpenAiResponses,
    GoogleGenerativeAi,
    GoogleVertex,
    BedrockConverseStream,
}

impl std::fmt::Display for ApiProtocol {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::AnthropicMessages => write!(f, "anthropic_messages"),
            Self::OpenAiCompletions => write!(f, "openai_completions"),
            Self::OpenAiResponses => write!(f, "openai_responses"),
            Self::AzureOpenAiResponses => write!(f, "azure_openai_responses"),
            Self::GoogleGenerativeAi => write!(f, "google_generative_ai"),
            Self::GoogleVertex => write!(f, "google_vertex"),
            Self::BedrockConverseStream => write!(f, "bedrock_converse_stream"),
        }
    }
}

/// Cost per million tokens (input/output).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CostConfig {
    pub input_per_million: f64,
    pub output_per_million: f64,
    #[serde(default)]
    pub cache_read_per_million: f64,
    #[serde(default)]
    pub cache_write_per_million: f64,
}

impl CostConfig {
    /// Whether any rate is set. All-zero rates mean pricing is unknown
    /// (custom/local models), not that the model is free.
    pub fn is_configured(&self) -> bool {
        self.input_per_million != 0.0
            || self.output_per_million != 0.0
            || self.cache_read_per_million != 0.0
            || self.cache_write_per_million != 0.0
    }

    /// Dollar cost of a usage record at these per-million-token rates.
    ///
    /// Consumed by [`crate::Agent::session_cost_usd`]; also usable directly
    /// in `after_turn` callbacks for per-turn cost tracking.
    pub fn cost_usd(&self, usage: &crate::types::Usage) -> f64 {
        (usage.input as f64 * self.input_per_million
            + usage.output as f64 * self.output_per_million
            + usage.cache_read as f64 * self.cache_read_per_million
            + usage.cache_write as f64 * self.cache_write_per_million)
            / 1_000_000.0
    }
}

impl Default for CostConfig {
    fn default() -> Self {
        Self {
            input_per_million: 0.0,
            output_per_million: 0.0,
            cache_read_per_million: 0.0,
            cache_write_per_million: 0.0,
        }
    }
}

/// How a provider handles the `max_tokens` field.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum MaxTokensField {
    #[default]
    MaxTokens,
    MaxCompletionTokens,
}

/// How a provider formats thinking/reasoning output.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ThinkingFormat {
    #[default]
    OpenAi,
    Xai,
    Qwen,
}

/// Compatibility flags for OpenAI-compatible providers.
/// Different providers have different quirks even though they share the same base API.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenAiCompat {
    /// Supports the `store` parameter for conversation persistence.
    pub supports_store: bool,
    /// Supports `developer` role (system-level instructions).
    pub supports_developer_role: bool,
    /// Supports `reasoning_effort` parameter.
    pub supports_reasoning_effort: bool,
    /// Supports DeepSeek-style `thinking` mode control.
    #[serde(default)]
    pub supports_thinking_control: bool,
    /// Includes usage data in streaming responses.
    pub supports_usage_in_streaming: bool,
    /// Which field name to use for max tokens.
    pub max_tokens_field: MaxTokensField,
    /// Tool results must include a `name` field.
    pub requires_tool_result_name: bool,
    /// Must insert an assistant message after tool results.
    #[serde(default)]
    pub requires_assistant_after_tool_result: bool,
    /// How thinking/reasoning content is formatted in streaming.
    pub thinking_format: ThinkingFormat,
}

impl Default for OpenAiCompat {
    fn default() -> Self {
        Self {
            supports_store: false,
            supports_developer_role: false,
            supports_reasoning_effort: false,
            supports_thinking_control: false,
            supports_usage_in_streaming: true,
            max_tokens_field: MaxTokensField::MaxTokens,
            requires_tool_result_name: false,
            requires_assistant_after_tool_result: false,
            thinking_format: ThinkingFormat::OpenAi,
        }
    }
}

impl OpenAiCompat {
    /// Compat flags for native OpenAI.
    pub fn openai() -> Self {
        Self {
            supports_store: true,
            supports_developer_role: true,
            supports_reasoning_effort: true,
            supports_usage_in_streaming: true,
            max_tokens_field: MaxTokensField::MaxCompletionTokens,
            ..Default::default()
        }
    }

    /// Compat flags for the Meta Model API (Muse Spark).
    ///
    /// OpenAI-compatible chat completions. Meta documents `reasoning_effort`
    /// (default `medium` server-side) and streamed usage via
    /// `stream_options.include_usage`; `max_tokens` is deprecated in favor of
    /// `max_completion_tokens`.
    pub fn meta() -> Self {
        Self {
            supports_reasoning_effort: true,
            supports_usage_in_streaming: true,
            max_tokens_field: MaxTokensField::MaxCompletionTokens,
            ..Default::default()
        }
    }

    /// Compat flags for xAI (Grok).
    pub fn xai() -> Self {
        Self {
            supports_usage_in_streaming: true,
            thinking_format: ThinkingFormat::Xai,
            ..Default::default()
        }
    }

    /// Compat flags for Groq.
    pub fn groq() -> Self {
        Self {
            supports_usage_in_streaming: true,
            ..Default::default()
        }
    }

    /// Compat flags for Cerebras.
    pub fn cerebras() -> Self {
        Self::default()
    }

    /// Compat flags for OpenRouter.
    pub fn openrouter() -> Self {
        Self {
            supports_usage_in_streaming: true,
            max_tokens_field: MaxTokensField::MaxCompletionTokens,
            ..Default::default()
        }
    }

    /// Compat flags for Mistral.
    pub fn mistral() -> Self {
        Self {
            supports_usage_in_streaming: true,
            max_tokens_field: MaxTokensField::MaxTokens,
            ..Default::default()
        }
    }

    /// Compat flags for DeepSeek.
    pub fn deepseek() -> Self {
        Self {
            supports_reasoning_effort: true,
            supports_thinking_control: true,
            supports_usage_in_streaming: true,
            max_tokens_field: MaxTokensField::MaxTokens,
            ..Default::default()
        }
    }

    /// Compat flags for Z.ai (Zhipu AI).
    pub fn zai() -> Self {
        Self {
            supports_usage_in_streaming: true,
            ..Default::default()
        }
    }

    /// Compat flags for MiniMax.
    pub fn minimax() -> Self {
        Self {
            supports_usage_in_streaming: true,
            ..Default::default()
        }
    }

    /// Compat flags for Qwen / DashScope.
    pub fn qwen() -> Self {
        Self {
            supports_usage_in_streaming: true,
            max_tokens_field: MaxTokensField::MaxTokens,
            thinking_format: ThinkingFormat::Qwen,
            ..Default::default()
        }
    }

    /// Compat flags for Ollama's OpenAI-compatible API.
    pub fn ollama() -> Self {
        Self {
            requires_assistant_after_tool_result: true,
            ..Default::default()
        }
    }
}

/// Quirk flags for the Anthropic Messages protocol (only for AnthropicMessages).
///
/// When `ModelConfig.anthropic` is `None`, providers use `AnthropicCompat::default()`,
/// which targets the current model generation (Claude 4.6+ / Fable 5).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AnthropicCompat {
    /// Use adaptive thinking (`thinking: {"type": "adaptive"}` plus
    /// `output_config.effort`). Required by Claude Fable 5, Opus 4.7/4.8, and
    /// Sonnet 5; recommended on Opus 4.6 / Sonnet 4.6. Set to `false` for
    /// pre-4.6 models, which only accept `{"type": "enabled", "budget_tokens": N}`.
    pub adaptive_thinking: bool,
    /// Send the API key as `Authorization: Bearer {key}` instead of the
    /// Anthropic-native `x-api-key` header. Needed for OpenAI-style gateways
    /// that speak the Anthropic Messages protocol (e.g. OpenCode Zen/Go).
    pub bearer_auth: bool,
}

impl Default for AnthropicCompat {
    fn default() -> Self {
        Self {
            adaptive_thinking: true,
            bearer_auth: false,
        }
    }
}

impl AnthropicCompat {
    /// Compat flags for pre-4.6 Claude models (budget-based extended thinking).
    pub fn legacy() -> Self {
        Self {
            adaptive_thinking: false,
            bearer_auth: false,
        }
    }
}

/// The two OpenCode gateways (<https://opencode.ai>).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OpenCodeGateway {
    /// Pay-per-use gateway (`opencode.ai/zen/v1`).
    Zen,
    /// Subscription gateway for open models (`opencode.ai/zen/go/v1`).
    Go,
}

impl OpenCodeGateway {
    fn provider_name(self) -> &'static str {
        match self {
            Self::Zen => "opencode-zen",
            Self::Go => "opencode-go",
        }
    }

    fn base_url(self) -> &'static str {
        match self {
            Self::Zen => "https://opencode.ai/zen/v1",
            Self::Go => "https://opencode.ai/zen/go/v1",
        }
    }
}

/// Full model configuration. Knows everything needed to make API calls.
///
/// Marked `#[non_exhaustive]`: fields may be added in minor releases (e.g.
/// the `anthropic` compat flags, slated for 0.9.0). Construct via the
/// `ModelConfig::*` preset constructors — or [`ModelConfig::custom`] for
/// protocols without a preset — and mutate fields to customize. Note that
/// downstream struct literals and functional-record-update
/// (`ModelConfig { .. }`) no longer compile; field mutation is the supported
/// pattern. New fields must carry `#[serde(default)]` so previously
/// persisted configs keep deserializing.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ModelConfig {
    /// Model identifier sent to the API (e.g. "gpt-4o", "claude-sonnet-4-20250514").
    pub id: String,
    /// Human-friendly name.
    pub name: String,
    /// Which API protocol to use.
    pub api: ApiProtocol,
    /// Provider name (e.g. "openai", "anthropic", "xai").
    pub provider: String,
    /// Base URL for API requests (without trailing slash).
    pub base_url: String,
    /// Whether this model supports reasoning/thinking. When `false` and a
    /// `thinking_level` is requested, the [`Agent`](crate::Agent) wrapper
    /// logs a warning; sub-agents and direct `agent_loop` calls do not. The
    /// request is still sent either way — gate behavior stays with the
    /// caller.
    pub reasoning: bool,
    /// Context window size in tokens.
    pub context_window: u32,
    /// Default max output tokens.
    pub max_tokens: u32,
    /// Cost configuration.
    #[serde(default)]
    pub cost: CostConfig,
    /// Additional headers to send with requests.
    #[serde(default)]
    pub headers: HashMap<String, String>,
    /// OpenAI-compat quirk flags (only for OpenAiCompletions protocol).
    #[serde(default)]
    pub compat: Option<OpenAiCompat>,
    /// Anthropic Messages quirk flags (only for AnthropicMessages protocol).
    /// `None` behaves like `AnthropicCompat::default()` (current generation).
    #[serde(default)]
    pub anthropic: Option<AnthropicCompat>,
}

impl ModelConfig {
    /// A minimal config for tests. `provider` is `"mock"`, cost rates are all
    /// zero, and `base_url` points at a non-routable host.
    ///
    /// Use it **only** with
    /// [`Agent::from_provider`](crate::Agent::from_provider) /
    /// [`SubAgentTool::from_provider`](crate::SubAgentTool::from_provider) and a
    /// [`MockProvider`](crate::provider::MockProvider): those take the provider
    /// explicitly, so the config's protocol is never consulted.
    ///
    /// **Do not** pass it to
    /// [`Agent::from_config`](crate::Agent::from_config) — that dispatches on
    /// the protocol (here `AnthropicMessages`) and would build the **real**
    /// Anthropic provider pointed at the non-routable `base_url`, so the first
    /// prompt fails with a network error instead of returning a mock response.
    pub fn mock() -> Self {
        Self::custom(
            ApiProtocol::AnthropicMessages,
            "mock",
            "http://mock.invalid",
            "mock",
            "Mock",
        )
    }

    /// Create a config for any protocol without a dedicated preset
    /// (Bedrock, Vertex, Azure, or future protocols).
    ///
    /// Since `ModelConfig` is `#[non_exhaustive]`, this is the construction
    /// path when no `ModelConfig::*` preset fits. Defaults: 128K context,
    /// 16K max output, no compat flags — mutate fields to adjust.
    pub fn custom(
        api: ApiProtocol,
        provider: impl Into<String>,
        base_url: impl Into<String>,
        model_id: impl Into<String>,
        name: impl Into<String>,
    ) -> Self {
        Self {
            id: model_id.into(),
            name: name.into(),
            api,
            provider: provider.into(),
            base_url: base_url.into(),
            reasoning: false,
            context_window: 128_000,
            max_tokens: 16_000,
            cost: CostConfig::default(),
            headers: HashMap::new(),
            compat: None,
            anthropic: None,
        }
    }

    /// Create a new Anthropic model config.
    pub fn anthropic(id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            api: ApiProtocol::AnthropicMessages,
            provider: "anthropic".into(),
            base_url: "https://api.anthropic.com/v1".into(),
            reasoning: true,
            context_window: 200_000,
            max_tokens: 16_000,
            cost: CostConfig::default(),
            headers: HashMap::new(),
            anthropic: None,
            compat: None,
        }
    }

    /// Claude Fable 5 — Anthropic's most capable model.
    /// 1M context; defaults to 64K of the model's 128K max output.
    pub fn claude_fable_5() -> Self {
        Self {
            context_window: 1_000_000,
            max_tokens: 64_000,
            cost: CostConfig {
                input_per_million: 10.0,
                output_per_million: 50.0,
                cache_read_per_million: 1.0,
                cache_write_per_million: 12.5,
            },
            ..Self::anthropic("claude-fable-5", "Claude Fable 5")
        }
    }

    /// Claude Opus 4.8. 1M context; defaults to 64K of the model's 128K max output.
    pub fn claude_opus_4_8() -> Self {
        Self {
            context_window: 1_000_000,
            max_tokens: 64_000,
            cost: CostConfig {
                input_per_million: 5.0,
                output_per_million: 25.0,
                cache_read_per_million: 0.5,
                cache_write_per_million: 6.25,
            },
            ..Self::anthropic("claude-opus-4-8", "Claude Opus 4.8")
        }
    }

    /// Claude Sonnet 5. 1M context; defaults to 64K of the model's 128K max output.
    pub fn claude_sonnet_5() -> Self {
        Self {
            context_window: 1_000_000,
            max_tokens: 64_000,
            cost: CostConfig {
                input_per_million: 3.0,
                output_per_million: 15.0,
                cache_read_per_million: 0.3,
                cache_write_per_million: 3.75,
            },
            ..Self::anthropic("claude-sonnet-5", "Claude Sonnet 5")
        }
    }

    /// Claude Haiku 4.5. 200K context; defaults to 32K of the model's 64K max output.
    pub fn claude_haiku_4_5() -> Self {
        Self {
            context_window: 200_000,
            max_tokens: 32_000,
            cost: CostConfig {
                input_per_million: 1.0,
                output_per_million: 5.0,
                cache_read_per_million: 0.1,
                cache_write_per_million: 1.25,
            },
            ..Self::anthropic("claude-haiku-4-5", "Claude Haiku 4.5")
        }
    }

    /// GPT-5.5. ~1M context; defaults to 64K of the model's 128K max output.
    /// Uses the Chat Completions API.
    pub fn gpt_5_5() -> Self {
        Self {
            reasoning: true,
            context_window: 1_000_000,
            max_tokens: 64_000,
            cost: CostConfig {
                input_per_million: 5.0,
                output_per_million: 30.0,
                cache_read_per_million: 0.5,
                cache_write_per_million: 0.0,
            },
            ..Self::openai("gpt-5.5", "GPT-5.5")
        }
    }

    /// Create a new OpenAI model config.
    pub fn openai(id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            api: ApiProtocol::OpenAiCompletions,
            provider: "openai".into(),
            base_url: "https://api.openai.com/v1".into(),
            reasoning: false,
            context_window: 128_000,
            max_tokens: 4096,
            cost: CostConfig::default(),
            headers: HashMap::new(),
            anthropic: None,
            compat: Some(OpenAiCompat::openai()),
        }
    }

    /// Create a config for a local OpenAI-compatible server (LM Studio, Ollama, etc.).
    /// No API key required — sends an empty Bearer token.
    pub fn local(base_url: impl Into<String>, model_id: impl Into<String>) -> Self {
        Self {
            id: model_id.into(),
            name: "Local Model".into(),
            api: ApiProtocol::OpenAiCompletions,
            provider: "local".into(),
            base_url: base_url.into(),
            reasoning: false,
            context_window: 128_000,
            max_tokens: 4096,
            cost: CostConfig::default(),
            headers: HashMap::new(),
            anthropic: None,
            compat: Some(OpenAiCompat::default()),
        }
    }

    /// Create a config for a model served by OpenCode Zen
    /// (<https://opencode.ai/docs/zen>), OpenCode's pay-per-use gateway.
    ///
    /// Zen serves each model family over a different protocol; the protocol is
    /// selected from the model id:
    /// - `gpt-*` → OpenAI Responses API (pair with `OpenAiResponsesProvider`)
    /// - `claude-*`, `qwen*` → Anthropic Messages API (pair with `AnthropicProvider`)
    /// - everything else (DeepSeek, MiniMax, GLM, Kimi, ...) → Chat Completions
    ///   (pair with `OpenAiCompatProvider`)
    ///
    /// Gemini models are not supported — Zen serves them over a Google-native
    /// endpoint shape yoagent does not target. A `gemini-*` id falls through to
    /// Chat Completions (with a warning) and will likely fail at request time.
    ///
    /// The routing mirrors the Zen endpoint tables as of mid-2026; if a model
    /// errors, verify its protocol against `https://opencode.ai/zen/v1/models`.
    ///
    /// Context window and max output default conservatively (128K / 16K);
    /// override the fields for models with larger limits.
    pub fn opencode_zen(model_id: impl Into<String>) -> Self {
        Self::opencode(model_id.into(), OpenCodeGateway::Zen)
    }

    /// Create a config for a model served by OpenCode Go
    /// (<https://opencode.ai/docs/go>), OpenCode's subscription gateway for
    /// open models.
    ///
    /// Protocol is selected from the model id:
    /// - `qwen*`, `minimax-*` → Anthropic Messages API (pair with `AnthropicProvider`)
    /// - everything else (GLM, Kimi, DeepSeek, MiMo, ...) → Chat Completions
    ///   (pair with `OpenAiCompatProvider`)
    pub fn opencode_go(model_id: impl Into<String>) -> Self {
        Self::opencode(model_id.into(), OpenCodeGateway::Go)
    }

    fn opencode(id: String, gateway: OpenCodeGateway) -> Self {
        let lower = id.to_ascii_lowercase();
        if lower.starts_with("gemini-") {
            tracing::warn!(
                "OpenCode serves Gemini models over a Google-native endpoint yoagent \
                 does not target; '{}' is routed to /chat/completions and will likely \
                 fail at request time",
                id
            );
        }
        let anthropic_protocol = match gateway {
            OpenCodeGateway::Zen => lower.starts_with("claude-") || lower.starts_with("qwen"),
            OpenCodeGateway::Go => lower.starts_with("qwen") || lower.starts_with("minimax-"),
        };
        let (api, reasoning, compat, anthropic) = if anthropic_protocol {
            (
                ApiProtocol::AnthropicMessages,
                true,
                None,
                // Gateways use OpenAI-style Bearer auth, not x-api-key.
                Some(AnthropicCompat {
                    adaptive_thinking: true,
                    bearer_auth: true,
                }),
            )
        } else if gateway == OpenCodeGateway::Zen && lower.starts_with("gpt-") {
            (ApiProtocol::OpenAiResponses, true, None, None)
        } else {
            (
                ApiProtocol::OpenAiCompletions,
                false,
                Some(OpenAiCompat::default()),
                None,
            )
        };
        Self {
            id: id.clone(),
            name: id,
            api,
            provider: gateway.provider_name().into(),
            base_url: gateway.base_url().into(),
            reasoning,
            context_window: 128_000,
            max_tokens: 16_000,
            cost: CostConfig::default(),
            headers: HashMap::new(),
            compat,
            anthropic,
        }
    }

    /// Create a config for a custom OpenAI-compatible endpoint with explicit compat flags.
    pub fn openai_compat(
        base_url: impl Into<String>,
        model_id: impl Into<String>,
        provider: impl Into<String>,
        compat: OpenAiCompat,
    ) -> Self {
        let id = model_id.into();
        Self {
            id: id.clone(),
            name: id,
            api: ApiProtocol::OpenAiCompletions,
            provider: provider.into(),
            base_url: base_url.into(),
            reasoning: false,
            context_window: 128_000,
            max_tokens: 4096,
            cost: CostConfig::default(),
            headers: HashMap::new(),
            anthropic: None,
            compat: Some(compat),
        }
    }

    /// Create a config for Ollama's OpenAI-compatible API.
    ///
    /// Default local base URL: `http://localhost:11434/v1`.
    pub fn ollama(base_url: impl Into<String>, model_id: impl Into<String>) -> Self {
        let id = model_id.into();
        Self {
            id: id.clone(),
            name: id,
            api: ApiProtocol::OpenAiCompletions,
            provider: "ollama".into(),
            base_url: base_url.into(),
            reasoning: false,
            context_window: 128_000,
            max_tokens: 4096,
            cost: CostConfig::default(),
            headers: HashMap::new(),
            anthropic: None,
            compat: Some(OpenAiCompat::ollama()),
        }
    }

    /// Create a new Z.ai (Zhipu AI) model config.
    ///
    /// Models: `glm-4.7`, `glm-4.5-air`, `glm-5`, etc.
    pub fn zai(id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            api: ApiProtocol::OpenAiCompletions,
            provider: "zai".into(),
            base_url: "https://api.z.ai/api/paas/v4".into(),
            reasoning: false,
            context_window: 128_000,
            max_tokens: 4096,
            cost: CostConfig::default(),
            headers: HashMap::new(),
            anthropic: None,
            compat: Some(OpenAiCompat::zai()),
        }
    }

    /// Create a new Meta Model API config (Muse Spark).
    ///
    /// Models: `muse-spark-1.1` — 1,048,576-token context; 128K max output
    /// per Meta's integration examples (no official model card yet).
    /// US-only public preview as of July 2026. OpenAI-compatible endpoint at
    /// `https://api.meta.ai/v1`. Key resolves from `META_API_KEY`, then
    /// Meta's documented `MODEL_API_KEY`.
    ///
    /// Reasoning: Meta's endpoint defaults to `reasoning_effort: medium`
    /// server-side. Set a [`ThinkingLevel`](crate::types::ThinkingLevel) to
    /// tune it; `Off` omits the field, which means Meta's default (medium)
    /// applies — not "no reasoning".
    pub fn meta(id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            api: ApiProtocol::OpenAiCompletions,
            provider: "meta".into(),
            base_url: "https://api.meta.ai/v1".into(),
            reasoning: true,
            context_window: 1_048_576,
            max_tokens: 131_072,
            cost: CostConfig {
                input_per_million: 1.25,
                output_per_million: 4.25,
                cache_read_per_million: 0.15,
                cache_write_per_million: 0.0,
            },
            headers: HashMap::new(),
            anthropic: None,
            compat: Some(OpenAiCompat::meta()),
        }
    }

    /// Create a new MiniMax model config.
    ///
    /// Models: `MiniMax-Text-01`, `MiniMax-M1`, etc.
    pub fn minimax(id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            api: ApiProtocol::OpenAiCompletions,
            provider: "minimax".into(),
            base_url: "https://api.minimaxi.chat/v1".into(),
            reasoning: false,
            context_window: 1_000_000,
            max_tokens: 4096,
            cost: CostConfig::default(),
            headers: HashMap::new(),
            anthropic: None,
            compat: Some(OpenAiCompat::minimax()),
        }
    }

    /// Create a new Qwen / DashScope model config.
    ///
    /// Models: `qwen3.6-plus`, `qwen3.5-plus`, `qwen-plus`, `qwen-flash`, etc.
    pub fn qwen(id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            api: ApiProtocol::OpenAiCompletions,
            provider: "qwen".into(),
            base_url: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1".into(),
            reasoning: true,
            context_window: 128_000,
            max_tokens: 4096,
            cost: CostConfig::default(),
            headers: HashMap::new(),
            anthropic: None,
            compat: Some(OpenAiCompat::qwen()),
        }
    }

    /// Create a new xAI (Grok) model config.
    ///
    /// Models: `grok-4-1-fast`, `grok-4-1`, etc.
    pub fn xai(id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            api: ApiProtocol::OpenAiCompletions,
            provider: "xai".into(),
            base_url: "https://api.x.ai/v1".into(),
            reasoning: false,
            context_window: 131_072,
            max_tokens: 4096,
            cost: CostConfig::default(),
            headers: HashMap::new(),
            anthropic: None,
            compat: Some(OpenAiCompat::xai()),
        }
    }

    /// Create a new Groq model config.
    ///
    /// Models: `llama-3.3-70b-versatile`, `mixtral-8x7b-32768`, etc.
    pub fn groq(id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            api: ApiProtocol::OpenAiCompletions,
            provider: "groq".into(),
            base_url: "https://api.groq.com/openai/v1".into(),
            reasoning: false,
            context_window: 128_000,
            max_tokens: 4096,
            cost: CostConfig::default(),
            headers: HashMap::new(),
            anthropic: None,
            compat: Some(OpenAiCompat::groq()),
        }
    }

    /// Create a new DeepSeek model config.
    ///
    /// Models: `deepseek-v4-flash`, `deepseek-v4-pro`, etc.
    ///
    /// Legacy aliases `deepseek-chat` and `deepseek-reasoner` are accepted by
    /// DeepSeek for now, but are scheduled for deprecation on 2026-07-24.
    pub fn deepseek(id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            api: ApiProtocol::OpenAiCompletions,
            provider: "deepseek".into(),
            base_url: "https://api.deepseek.com".into(),
            reasoning: true,
            context_window: 1_000_000,
            max_tokens: 384_000,
            cost: CostConfig::default(),
            headers: HashMap::new(),
            anthropic: None,
            compat: Some(OpenAiCompat::deepseek()),
        }
    }

    /// Create a new Mistral model config.
    ///
    /// Models: `mistral-large-latest`, `mistral-small-latest`, etc.
    pub fn mistral(id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            api: ApiProtocol::OpenAiCompletions,
            provider: "mistral".into(),
            base_url: "https://api.mistral.ai/v1".into(),
            reasoning: false,
            context_window: 128_000,
            max_tokens: 4096,
            cost: CostConfig::default(),
            headers: HashMap::new(),
            anthropic: None,
            compat: Some(OpenAiCompat::mistral()),
        }
    }

    /// Create a new Google Generative AI (Gemini) model config.
    pub fn google(id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            api: ApiProtocol::GoogleGenerativeAi,
            provider: "google".into(),
            base_url: "https://generativelanguage.googleapis.com".into(),
            reasoning: false,
            context_window: 1_000_000,
            max_tokens: 8192,
            cost: CostConfig::default(),
            headers: HashMap::new(),
            anthropic: None,
            compat: None,
        }
    }
}

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

    #[test]
    fn meta_preset_matches_launch_specs() {
        let mc = ModelConfig::meta("muse-spark-1.1", "Muse Spark 1.1");
        assert_eq!(mc.provider, "meta");
        assert_eq!(mc.api, ApiProtocol::OpenAiCompletions);
        assert_eq!(mc.base_url, "https://api.meta.ai/v1");
        assert_eq!(mc.context_window, 1_048_576);
        assert_eq!(mc.max_tokens, 131_072);
        assert!(mc.cost.is_configured());
        assert_eq!(mc.cost.input_per_million, 1.25);
        assert_eq!(mc.cost.output_per_million, 4.25);
        // Meta documents a cached-input rate; cache writes are not charged.
        assert_eq!(mc.cost.cache_read_per_million, 0.15);
        assert_eq!(mc.cost.cache_write_per_million, 0.0);
        let compat = mc.compat.expect("compat flags set");
        assert!(matches!(
            compat.max_tokens_field,
            MaxTokensField::MaxCompletionTokens
        ));
        // Documented in Meta's chat-completions schemas.
        assert!(compat.supports_reasoning_effort);
        assert!(compat.supports_usage_in_streaming);
    }

    #[test]
    fn test_model_config_anthropic() {
        let config = ModelConfig::anthropic("claude-sonnet-5", "Claude Sonnet 5");
        assert_eq!(config.api, ApiProtocol::AnthropicMessages);
        assert_eq!(config.provider, "anthropic");
        assert_eq!(config.base_url, "https://api.anthropic.com/v1");
        assert!(config.compat.is_none());
        assert!(config.anthropic.is_none());
    }

    #[test]
    fn test_cost_usd() {
        let cost = CostConfig {
            input_per_million: 3.0,
            output_per_million: 15.0,
            cache_read_per_million: 0.3,
            cache_write_per_million: 3.75,
        };
        let usage = crate::types::Usage {
            input: 1_000_000,
            output: 100_000,
            cache_read: 2_000_000,
            cache_write: 400_000,
            total_tokens: 0,
        };
        // 3.0 + 1.5 + 0.6 + 1.5 = 6.6
        assert!((cost.cost_usd(&usage) - 6.6).abs() < 1e-9);
        // zero rates (default) => zero cost
        assert_eq!(CostConfig::default().cost_usd(&usage), 0.0);
    }

    #[test]
    fn test_new_generation_presets() {
        let fable = ModelConfig::claude_fable_5();
        assert_eq!(fable.id, "claude-fable-5");
        assert_eq!(fable.api, ApiProtocol::AnthropicMessages);
        assert_eq!(fable.context_window, 1_000_000);
        assert_eq!(fable.cost.input_per_million, 10.0);
        assert_eq!(fable.cost.output_per_million, 50.0);

        let opus = ModelConfig::claude_opus_4_8();
        assert_eq!(opus.id, "claude-opus-4-8");
        assert_eq!(opus.context_window, 1_000_000);
        assert_eq!(opus.cost.input_per_million, 5.0);

        let sonnet = ModelConfig::claude_sonnet_5();
        assert_eq!(sonnet.id, "claude-sonnet-5");
        assert_eq!(sonnet.cost.output_per_million, 15.0);

        let haiku = ModelConfig::claude_haiku_4_5();
        assert_eq!(haiku.id, "claude-haiku-4-5");
        assert_eq!(haiku.context_window, 200_000);

        let gpt = ModelConfig::gpt_5_5();
        assert_eq!(gpt.id, "gpt-5.5");
        assert_eq!(gpt.api, ApiProtocol::OpenAiCompletions);
        assert_eq!(gpt.context_window, 1_000_000);
        assert_eq!(gpt.cost.output_per_million, 30.0);
        assert!(gpt.compat.is_some());
    }

    #[test]
    fn test_opencode_zen_protocol_selection() {
        // GPT models → Responses API
        let gpt = ModelConfig::opencode_zen("gpt-5.5");
        assert_eq!(gpt.api, ApiProtocol::OpenAiResponses);
        assert_eq!(gpt.provider, "opencode-zen");
        assert_eq!(gpt.base_url, "https://opencode.ai/zen/v1");

        // Claude and Qwen models → Anthropic Messages with Bearer auth
        for id in ["claude-sonnet-5", "qwen3.7-max"] {
            let config = ModelConfig::opencode_zen(id);
            assert_eq!(config.api, ApiProtocol::AnthropicMessages, "{id}");
            let compat = config.anthropic.expect("anthropic compat set");
            assert!(compat.bearer_auth);
        }

        // Everything else → Chat Completions
        for id in ["deepseek-v4-pro", "minimax-m3", "glm-5.2", "kimi-k2.7-code"] {
            let config = ModelConfig::opencode_zen(id);
            assert_eq!(config.api, ApiProtocol::OpenAiCompletions, "{id}");
            assert!(config.compat.is_some());
        }
    }

    #[test]
    fn test_opencode_go_protocol_selection() {
        // Qwen and MiniMax models → Anthropic Messages with Bearer auth
        for id in ["qwen3.7-max", "minimax-m3"] {
            let config = ModelConfig::opencode_go(id);
            assert_eq!(config.api, ApiProtocol::AnthropicMessages, "{id}");
            assert_eq!(config.base_url, "https://opencode.ai/zen/go/v1");
            assert!(config.anthropic.expect("anthropic compat set").bearer_auth);
        }

        // Everything else → Chat Completions (Go has no GPT models)
        for id in [
            "glm-5.2",
            "kimi-k2.7-code",
            "deepseek-v4-flash",
            "mimo-v2.5",
        ] {
            let config = ModelConfig::opencode_go(id);
            assert_eq!(config.api, ApiProtocol::OpenAiCompletions, "{id}");
            assert_eq!(config.provider, "opencode-go", "{id}");
        }
    }

    #[test]
    fn test_model_config_openai() {
        let config = ModelConfig::openai("gpt-4o", "GPT-4o");
        assert_eq!(config.api, ApiProtocol::OpenAiCompletions);
        let compat = config.compat.unwrap();
        assert!(compat.supports_store);
        assert!(compat.supports_developer_role);
        assert_eq!(compat.max_tokens_field, MaxTokensField::MaxCompletionTokens);
    }

    #[test]
    fn test_openai_compat_variants() {
        let xai = OpenAiCompat::xai();
        assert_eq!(xai.thinking_format, ThinkingFormat::Xai);
        assert!(!xai.supports_store);

        let groq = OpenAiCompat::groq();
        assert!(groq.supports_usage_in_streaming);
        assert!(!groq.supports_store);

        let deepseek = OpenAiCompat::deepseek();
        assert_eq!(deepseek.max_tokens_field, MaxTokensField::MaxTokens);
        assert!(deepseek.supports_reasoning_effort);
        assert!(deepseek.supports_thinking_control);

        let zai = OpenAiCompat::zai();
        assert!(zai.supports_usage_in_streaming);
        assert!(!zai.supports_store);

        let minimax = OpenAiCompat::minimax();
        assert!(minimax.supports_usage_in_streaming);
        assert!(!minimax.supports_store);

        let ollama = OpenAiCompat::ollama();
        assert!(ollama.requires_assistant_after_tool_result);
        assert!(!ollama.requires_tool_result_name);

        let qwen = OpenAiCompat::qwen();
        assert_eq!(qwen.thinking_format, ThinkingFormat::Qwen);
        assert_eq!(qwen.max_tokens_field, MaxTokensField::MaxTokens);
        assert!(qwen.supports_usage_in_streaming);
        assert!(!qwen.supports_reasoning_effort);
        assert!(!qwen.supports_thinking_control);
    }

    #[test]
    fn test_model_config_deserializes_without_anthropic_field() {
        // Configs persisted before 0.9.0 have no `anthropic` field.
        let mut value = serde_json::to_value(ModelConfig::anthropic("m", "M")).unwrap();
        value.as_object_mut().unwrap().remove("anthropic");
        let config: ModelConfig = serde_json::from_value(value).unwrap();
        assert!(config.anthropic.is_none());
    }

    #[test]
    fn test_anthropic_compat_deserializes_from_partial_json() {
        // Container-level serde(default): missing fields use Default (adaptive on).
        let compat: AnthropicCompat = serde_json::from_value(serde_json::json!({})).unwrap();
        assert!(compat.adaptive_thinking);
        assert!(!compat.bearer_auth);

        let compat: AnthropicCompat =
            serde_json::from_value(serde_json::json!({"bearer_auth": true})).unwrap();
        assert!(compat.adaptive_thinking);
        assert!(compat.bearer_auth);
    }

    #[test]
    fn test_openai_compat_deserializes_without_assistant_after_tool_result_flag() {
        let compat: OpenAiCompat = serde_json::from_value(serde_json::json!({
            "supports_store": false,
            "supports_developer_role": false,
            "supports_reasoning_effort": false,
            "supports_thinking_control": false,
            "supports_usage_in_streaming": true,
            "max_tokens_field": "max_tokens",
            "requires_tool_result_name": false,
            "thinking_format": "open_ai"
        }))
        .unwrap();

        assert!(!compat.requires_assistant_after_tool_result);
    }

    #[test]
    fn test_model_config_local_remains_neutral() {
        let config = ModelConfig::local("http://localhost:1234/v1", "local-model");
        assert_eq!(config.api, ApiProtocol::OpenAiCompletions);
        assert_eq!(config.provider, "local");
        assert_eq!(config.base_url, "http://localhost:1234/v1");
        let compat = config.compat.unwrap();
        assert!(!compat.requires_assistant_after_tool_result);
    }

    #[test]
    fn test_model_config_ollama() {
        let config = ModelConfig::ollama("http://localhost:11434/v1", "llama3.1:8b");
        assert_eq!(config.api, ApiProtocol::OpenAiCompletions);
        assert_eq!(config.provider, "ollama");
        assert_eq!(config.id, "llama3.1:8b");
        assert_eq!(config.name, "llama3.1:8b");
        assert_eq!(config.base_url, "http://localhost:11434/v1");
        let compat = config.compat.unwrap();
        assert!(compat.requires_assistant_after_tool_result);
    }

    #[test]
    fn test_model_config_openai_compat() {
        let config = ModelConfig::openai_compat(
            "http://localhost:1234/v1",
            "qwen3-local",
            "qwen",
            OpenAiCompat::qwen(),
        );
        assert_eq!(config.api, ApiProtocol::OpenAiCompletions);
        assert_eq!(config.provider, "qwen");
        assert_eq!(config.id, "qwen3-local");
        assert_eq!(config.name, "qwen3-local");
        assert_eq!(config.base_url, "http://localhost:1234/v1");
        let compat = config.compat.unwrap();
        assert_eq!(compat.thinking_format, ThinkingFormat::Qwen);
    }

    #[test]
    fn test_model_config_qwen() {
        let config = ModelConfig::qwen("qwen3.6-plus", "Qwen 3.6 Plus");
        assert_eq!(config.api, ApiProtocol::OpenAiCompletions);
        assert_eq!(config.provider, "qwen");
        assert_eq!(
            config.base_url,
            "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
        );
        assert!(config.reasoning);
        let compat = config.compat.unwrap();
        assert_eq!(compat.thinking_format, ThinkingFormat::Qwen);
        assert_eq!(compat.max_tokens_field, MaxTokensField::MaxTokens);
    }

    #[test]
    fn test_model_config_zai() {
        let config = ModelConfig::zai("glm-4.7", "GLM 4.7");
        assert_eq!(config.api, ApiProtocol::OpenAiCompletions);
        assert_eq!(config.provider, "zai");
        assert_eq!(config.base_url, "https://api.z.ai/api/paas/v4");
        assert!(config.compat.is_some());
    }

    #[test]
    fn test_model_config_minimax() {
        let config = ModelConfig::minimax("MiniMax-Text-01", "MiniMax Text 01");
        assert_eq!(config.api, ApiProtocol::OpenAiCompletions);
        assert_eq!(config.provider, "minimax");
        assert_eq!(config.base_url, "https://api.minimaxi.chat/v1");
        assert_eq!(config.context_window, 1_000_000);
        assert!(config.compat.is_some());
    }

    #[test]
    fn test_model_config_deepseek() {
        let config = ModelConfig::deepseek("deepseek-v4-flash", "DeepSeek V4 Flash");
        assert_eq!(config.api, ApiProtocol::OpenAiCompletions);
        assert_eq!(config.provider, "deepseek");
        assert_eq!(config.base_url, "https://api.deepseek.com");
        assert_eq!(config.context_window, 1_000_000);
        assert_eq!(config.max_tokens, 384_000);
        assert!(config.reasoning);
        assert!(config.compat.is_some());
    }

    #[test]
    fn test_api_protocol_display() {
        assert_eq!(
            ApiProtocol::AnthropicMessages.to_string(),
            "anthropic_messages"
        );
        assert_eq!(
            ApiProtocol::OpenAiCompletions.to_string(),
            "openai_completions"
        );
        assert_eq!(
            ApiProtocol::GoogleGenerativeAi.to_string(),
            "google_generative_ai"
        );
    }

    #[test]
    fn test_cost_config_default() {
        let cost = CostConfig::default();
        assert_eq!(cost.input_per_million, 0.0);
        assert_eq!(cost.output_per_million, 0.0);
    }
}