-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Expand file tree
/
Copy pathlib.rs
More file actions
3815 lines (3468 loc) Ā· 131 KB
/
lib.rs
File metadata and controls
3815 lines (3468 loc) Ā· 131 KB
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
//! Provider subsystem for model inference backends.
//!
//! This module implements the factory pattern for AI model providers. Each provider
//! implements the [`Provider`] trait defined in [`traits`], and is registered in the
//! factory function [`create_provider`] by its canonical string key (e.g., `"openai"`,
//! `"anthropic"`, `"ollama"`, `"gemini"`). Provider aliases are resolved internally
//! so that user-facing keys remain stable.
//!
//! The subsystem supports resilient multi-provider configurations through the
//! [`ReliableProvider`](reliable::ReliableProvider) wrapper, which handles fallback
//! chains and automatic retry. Model routing across providers is available via
//! [`create_routed_provider`].
//!
//! # Extension
//!
//! To add a new provider, implement [`Provider`] in a new submodule and register it
//! in [`create_provider_with_url`]. See `AGENTS.md` §7.1 for the full change playbook.
pub mod anthropic;
pub mod auth;
pub mod azure_openai;
pub mod bedrock;
pub mod claude_code;
pub mod compatible;
pub mod copilot;
pub mod gemini;
pub mod gemini_cli;
// glm.rs excluded ā not compiled in upstream (dead code with known issues)
pub mod kilocli;
pub mod multimodal;
pub mod ollama;
pub mod openai;
pub mod openai_codex;
pub mod openrouter;
pub mod reliable;
pub mod router;
pub mod telnyx;
pub mod traits;
#[allow(unused_imports)]
pub use traits::{
ChatMessage, ChatRequest, ChatResponse, ConversationMessage, Provider, ProviderCapabilityError,
ToolCall, ToolResultMessage,
};
use crate::auth::AuthService;
use compatible::{AuthStyle, OpenAiCompatibleProvider};
use reliable::ReliableProvider;
use serde::Deserialize;
use std::path::PathBuf;
const MAX_API_ERROR_CHARS: usize = 500;
const MINIMAX_INTL_BASE_URL: &str = "https://api.minimax.io/v1";
const MINIMAX_CN_BASE_URL: &str = "https://api.minimaxi.com/v1";
const MINIMAX_OAUTH_GLOBAL_TOKEN_ENDPOINT: &str = "https://api.minimax.io/oauth/token";
const MINIMAX_OAUTH_CN_TOKEN_ENDPOINT: &str = "https://api.minimaxi.com/oauth/token";
const MINIMAX_OAUTH_PLACEHOLDER: &str = "minimax-oauth";
const MINIMAX_OAUTH_CN_PLACEHOLDER: &str = "minimax-oauth-cn";
const MINIMAX_OAUTH_TOKEN_ENV: &str = "MINIMAX_OAUTH_TOKEN";
const MINIMAX_API_KEY_ENV: &str = "MINIMAX_API_KEY";
const MINIMAX_OAUTH_REFRESH_TOKEN_ENV: &str = "MINIMAX_OAUTH_REFRESH_TOKEN";
const MINIMAX_OAUTH_REGION_ENV: &str = "MINIMAX_OAUTH_REGION";
const MINIMAX_OAUTH_CLIENT_ID_ENV: &str = "MINIMAX_OAUTH_CLIENT_ID";
const MINIMAX_OAUTH_DEFAULT_CLIENT_ID: &str = "78257093-7e40-4613-99e0-527b14b39113";
const GLM_GLOBAL_BASE_URL: &str = "https://api.z.ai/api/paas/v4";
const GLM_CN_BASE_URL: &str = "https://open.bigmodel.cn/api/paas/v4";
const MOONSHOT_INTL_BASE_URL: &str = "https://api.moonshot.ai/v1";
const MOONSHOT_CN_BASE_URL: &str = "https://api.moonshot.cn/v1";
const QWEN_CN_BASE_URL: &str = "https://dashscope.aliyuncs.com/compatible-mode/v1";
const QWEN_INTL_BASE_URL: &str = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
const QWEN_US_BASE_URL: &str = "https://dashscope-us.aliyuncs.com/compatible-mode/v1";
const QWEN_OAUTH_BASE_FALLBACK_URL: &str = QWEN_CN_BASE_URL;
const BAILIAN_BASE_URL: &str = "https://coding.dashscope.aliyuncs.com/v1";
const QWEN_OAUTH_TOKEN_ENDPOINT: &str = "https://chat.qwen.ai/api/v1/oauth2/token";
const QWEN_OAUTH_PLACEHOLDER: &str = "qwen-oauth";
const QWEN_OAUTH_TOKEN_ENV: &str = "QWEN_OAUTH_TOKEN";
const QWEN_OAUTH_REFRESH_TOKEN_ENV: &str = "QWEN_OAUTH_REFRESH_TOKEN";
const QWEN_OAUTH_RESOURCE_URL_ENV: &str = "QWEN_OAUTH_RESOURCE_URL";
const QWEN_OAUTH_CLIENT_ID_ENV: &str = "QWEN_OAUTH_CLIENT_ID";
const QWEN_OAUTH_DEFAULT_CLIENT_ID: &str = "f0304373b74a44d2b584a3fb70ca9e56";
const QWEN_OAUTH_CREDENTIAL_FILE: &str = ".qwen/oauth_creds.json";
const ZAI_GLOBAL_BASE_URL: &str = "https://api.z.ai/api/coding/paas/v4";
const ZAI_CN_BASE_URL: &str = "https://open.bigmodel.cn/api/coding/paas/v4";
const QIANFAN_BASE_URL: &str = "https://qianfan.baidubce.com/v2";
const VERCEL_AI_GATEWAY_BASE_URL: &str = "https://ai-gateway.vercel.sh/v1";
const MANIFEST_BASE_URL: &str = "http://localhost:3001/v1";
pub fn is_minimax_intl_alias(name: &str) -> bool {
matches!(
name,
"minimax"
| "minimax-intl"
| "minimax-io"
| "minimax-global"
| "minimax-oauth"
| "minimax-portal"
| "minimax-oauth-global"
| "minimax-portal-global"
)
}
pub fn is_manifest_alias(name: &str) -> bool {
matches!(name, "manifest" | "manifest-router" | "mnfst")
}
pub fn is_minimax_cn_alias(name: &str) -> bool {
matches!(
name,
"minimax-cn" | "minimaxi" | "minimax-oauth-cn" | "minimax-portal-cn"
)
}
pub fn is_minimax_alias(name: &str) -> bool {
is_minimax_intl_alias(name) || is_minimax_cn_alias(name)
}
pub fn is_glm_global_alias(name: &str) -> bool {
matches!(name, "glm" | "zhipu" | "glm-global" | "zhipu-global")
}
pub fn is_glm_cn_alias(name: &str) -> bool {
matches!(name, "glm-cn" | "zhipu-cn" | "bigmodel")
}
pub fn is_glm_alias(name: &str) -> bool {
is_glm_global_alias(name) || is_glm_cn_alias(name)
}
pub fn is_moonshot_intl_alias(name: &str) -> bool {
matches!(
name,
"moonshot-intl" | "moonshot-global" | "kimi-intl" | "kimi-global"
)
}
pub fn is_moonshot_cn_alias(name: &str) -> bool {
matches!(name, "moonshot" | "kimi" | "moonshot-cn" | "kimi-cn")
}
pub fn is_moonshot_alias(name: &str) -> bool {
is_moonshot_intl_alias(name) || is_moonshot_cn_alias(name)
}
pub fn is_qwen_cn_alias(name: &str) -> bool {
matches!(name, "qwen" | "dashscope" | "qwen-cn" | "dashscope-cn")
}
pub fn is_qwen_intl_alias(name: &str) -> bool {
matches!(
name,
"qwen-intl" | "dashscope-intl" | "qwen-international" | "dashscope-international"
)
}
pub fn is_qwen_us_alias(name: &str) -> bool {
matches!(name, "qwen-us" | "dashscope-us")
}
pub fn is_qwen_oauth_alias(name: &str) -> bool {
matches!(name, "qwen-code" | "qwen-oauth" | "qwen_oauth")
}
pub fn is_bailian_alias(name: &str) -> bool {
matches!(name, "bailian" | "aliyun-bailian" | "aliyun")
}
pub fn is_qwen_alias(name: &str) -> bool {
is_qwen_cn_alias(name)
|| is_qwen_intl_alias(name)
|| is_qwen_us_alias(name)
|| is_qwen_oauth_alias(name)
}
pub fn is_zai_global_alias(name: &str) -> bool {
matches!(name, "zai" | "z.ai" | "zai-global" | "z.ai-global")
}
pub fn is_zai_cn_alias(name: &str) -> bool {
matches!(name, "zai-cn" | "z.ai-cn")
}
pub fn is_zai_alias(name: &str) -> bool {
is_zai_global_alias(name) || is_zai_cn_alias(name)
}
pub fn is_qianfan_alias(name: &str) -> bool {
matches!(name, "qianfan" | "baidu")
}
fn qianfan_base_url(api_url: Option<&str>) -> String {
api_url
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToString::to_string)
.unwrap_or_else(|| QIANFAN_BASE_URL.to_string())
}
pub fn is_doubao_alias(name: &str) -> bool {
matches!(name, "doubao" | "volcengine" | "ark" | "doubao-cn")
}
#[derive(Clone, Copy, Debug)]
enum MinimaxOauthRegion {
Global,
Cn,
}
impl MinimaxOauthRegion {
fn token_endpoint(self) -> &'static str {
match self {
Self::Global => MINIMAX_OAUTH_GLOBAL_TOKEN_ENDPOINT,
Self::Cn => MINIMAX_OAUTH_CN_TOKEN_ENDPOINT,
}
}
}
#[derive(Debug, Deserialize)]
struct MinimaxOauthRefreshResponse {
#[serde(default)]
status: Option<String>,
#[serde(default)]
access_token: Option<String>,
#[serde(default)]
base_resp: Option<MinimaxOauthBaseResponse>,
}
#[derive(Debug, Deserialize)]
struct MinimaxOauthBaseResponse {
#[serde(default)]
status_msg: Option<String>,
}
#[derive(Clone, Deserialize, Default)]
struct QwenOauthCredentials {
#[serde(default)]
access_token: Option<String>,
#[serde(default)]
refresh_token: Option<String>,
#[serde(default)]
resource_url: Option<String>,
#[serde(default)]
expiry_date: Option<i64>,
}
impl std::fmt::Debug for QwenOauthCredentials {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("QwenOauthCredentials")
.field("resource_url", &self.resource_url)
.field("expiry_date", &self.expiry_date)
.finish_non_exhaustive()
}
}
#[derive(Debug, Deserialize)]
struct QwenOauthTokenResponse {
#[serde(default)]
access_token: Option<String>,
#[serde(default)]
refresh_token: Option<String>,
#[serde(default)]
expires_in: Option<i64>,
#[serde(default)]
resource_url: Option<String>,
#[serde(default)]
error: Option<String>,
#[serde(default)]
error_description: Option<String>,
}
#[derive(Clone, Default)]
struct QwenOauthProviderContext {
credential: Option<String>,
base_url: Option<String>,
}
impl std::fmt::Debug for QwenOauthProviderContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("QwenOauthProviderContext")
.field("base_url", &self.base_url)
.finish_non_exhaustive()
}
}
fn read_non_empty_env(name: &str) -> Option<String> {
std::env::var(name)
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
}
fn is_minimax_oauth_placeholder(value: &str) -> bool {
value.eq_ignore_ascii_case(MINIMAX_OAUTH_PLACEHOLDER)
|| value.eq_ignore_ascii_case(MINIMAX_OAUTH_CN_PLACEHOLDER)
}
fn minimax_oauth_region(name: &str) -> MinimaxOauthRegion {
if let Some(region) = read_non_empty_env(MINIMAX_OAUTH_REGION_ENV) {
let normalized = region.to_ascii_lowercase();
if matches!(normalized.as_str(), "cn" | "china") {
return MinimaxOauthRegion::Cn;
}
if matches!(normalized.as_str(), "global" | "intl" | "international") {
return MinimaxOauthRegion::Global;
}
}
if is_minimax_cn_alias(name) {
MinimaxOauthRegion::Cn
} else {
MinimaxOauthRegion::Global
}
}
fn minimax_oauth_client_id() -> String {
read_non_empty_env(MINIMAX_OAUTH_CLIENT_ID_ENV)
.unwrap_or_else(|| MINIMAX_OAUTH_DEFAULT_CLIENT_ID.to_string())
}
fn qwen_oauth_client_id() -> String {
read_non_empty_env(QWEN_OAUTH_CLIENT_ID_ENV)
.unwrap_or_else(|| QWEN_OAUTH_DEFAULT_CLIENT_ID.to_string())
}
fn qwen_oauth_credentials_file_path() -> Option<PathBuf> {
std::env::var_os("HOME")
.map(PathBuf::from)
.or_else(|| std::env::var_os("USERPROFILE").map(PathBuf::from))
.map(|home| home.join(QWEN_OAUTH_CREDENTIAL_FILE))
}
fn normalize_qwen_oauth_base_url(raw: &str) -> Option<String> {
let trimmed = raw.trim().trim_end_matches('/');
if trimmed.is_empty() {
return None;
}
let with_scheme = if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
trimmed.to_string()
} else {
format!("https://{trimmed}")
};
let normalized = with_scheme.trim_end_matches('/').to_string();
if normalized.ends_with("/v1") {
Some(normalized)
} else {
Some(format!("{normalized}/v1"))
}
}
fn read_qwen_oauth_cached_credentials() -> Option<QwenOauthCredentials> {
let path = qwen_oauth_credentials_file_path()?;
let content = std::fs::read_to_string(path).ok()?;
serde_json::from_str::<QwenOauthCredentials>(&content).ok()
}
fn normalized_qwen_expiry_millis(raw: i64) -> i64 {
if raw < 10_000_000_000 {
raw.saturating_mul(1000)
} else {
raw
}
}
fn qwen_oauth_token_expired(credentials: &QwenOauthCredentials) -> bool {
let Some(expiry) = credentials.expiry_date else {
return false;
};
let expiry_millis = normalized_qwen_expiry_millis(expiry);
let now_millis = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.ok()
.and_then(|duration| i64::try_from(duration.as_millis()).ok())
.unwrap_or(i64::MAX);
expiry_millis <= now_millis.saturating_add(30_000)
}
fn refresh_qwen_oauth_access_token(refresh_token: &str) -> anyhow::Result<QwenOauthCredentials> {
let client_id = qwen_oauth_client_id();
let client = reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(15))
.connect_timeout(std::time::Duration::from_secs(5))
.build()
.unwrap_or_else(|_| reqwest::blocking::Client::new());
let response = client
.post(QWEN_OAUTH_TOKEN_ENDPOINT)
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Accept", "application/json")
.form(&[
("grant_type", "refresh_token"),
("refresh_token", refresh_token),
("client_id", client_id.as_str()),
])
.send()
.map_err(|error| anyhow::anyhow!("Qwen OAuth refresh request failed: {error}"))?;
let status = response.status();
let body = response
.text()
.unwrap_or_else(|_| "<failed to read Qwen OAuth response body>".to_string());
let parsed = serde_json::from_str::<QwenOauthTokenResponse>(&body).ok();
if !status.is_success() {
let detail = parsed
.as_ref()
.and_then(|payload| payload.error_description.as_deref())
.or_else(|| parsed.as_ref().and_then(|payload| payload.error.as_deref()))
.filter(|msg| !msg.trim().is_empty())
.unwrap_or(body.as_str());
anyhow::bail!("Qwen OAuth refresh failed (HTTP {status}): {detail}");
}
let payload =
parsed.ok_or_else(|| anyhow::anyhow!("Qwen OAuth refresh response is not JSON"))?;
if let Some(error_code) = payload
.error
.as_deref()
.filter(|value| !value.trim().is_empty())
{
let detail = payload.error_description.as_deref().unwrap_or(error_code);
anyhow::bail!("Qwen OAuth refresh failed: {detail}");
}
let access_token = payload
.access_token
.as_deref()
.map(str::trim)
.filter(|token| !token.is_empty())
.ok_or_else(|| anyhow::anyhow!("Qwen OAuth refresh response missing access_token"))?
.to_string();
let expiry_date = payload.expires_in.and_then(|seconds| {
let now_secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.ok()
.and_then(|duration| i64::try_from(duration.as_secs()).ok())?;
now_secs
.checked_add(seconds)
.and_then(|unix_secs| unix_secs.checked_mul(1000))
});
Ok(QwenOauthCredentials {
access_token: Some(access_token),
refresh_token: payload
.refresh_token
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToString::to_string),
resource_url: payload
.resource_url
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToString::to_string),
expiry_date,
})
}
fn resolve_qwen_oauth_context(credential_override: Option<&str>) -> QwenOauthProviderContext {
let override_value = credential_override
.map(str::trim)
.filter(|value| !value.is_empty());
let placeholder_requested = override_value
.map(|value| value.eq_ignore_ascii_case(QWEN_OAUTH_PLACEHOLDER))
.unwrap_or(false);
if let Some(explicit) = override_value
&& !placeholder_requested
{
return QwenOauthProviderContext {
credential: Some(explicit.to_string()),
base_url: None,
};
}
let mut cached = read_qwen_oauth_cached_credentials();
let env_token = read_non_empty_env(QWEN_OAUTH_TOKEN_ENV);
let env_refresh_token = read_non_empty_env(QWEN_OAUTH_REFRESH_TOKEN_ENV);
let env_resource_url = read_non_empty_env(QWEN_OAUTH_RESOURCE_URL_ENV);
if env_token.is_none() {
let refresh_token = env_refresh_token.clone().or_else(|| {
cached
.as_ref()
.and_then(|credentials| credentials.refresh_token.clone())
});
let should_refresh = cached.as_ref().is_some_and(qwen_oauth_token_expired)
|| cached
.as_ref()
.and_then(|credentials| credentials.access_token.as_deref())
.is_none_or(|value| value.trim().is_empty());
if should_refresh && let Some(refresh_token) = refresh_token.as_deref() {
match refresh_qwen_oauth_access_token(refresh_token) {
Ok(refreshed) => {
cached = Some(refreshed);
}
Err(error) => {
tracing::warn!(error = %error, "Qwen OAuth refresh failed");
}
}
}
}
let mut credential = env_token.or_else(|| {
cached
.as_ref()
.and_then(|credentials| credentials.access_token.clone())
});
credential = credential
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToString::to_string);
if credential.is_none() && !placeholder_requested {
credential = read_non_empty_env("DASHSCOPE_API_KEY");
}
let base_url = env_resource_url
.as_deref()
.and_then(normalize_qwen_oauth_base_url)
.or_else(|| {
cached
.as_ref()
.and_then(|credentials| credentials.resource_url.as_deref())
.and_then(normalize_qwen_oauth_base_url)
});
QwenOauthProviderContext {
credential,
base_url,
}
}
fn resolve_minimax_static_credential() -> Option<String> {
read_non_empty_env(MINIMAX_OAUTH_TOKEN_ENV).or_else(|| read_non_empty_env(MINIMAX_API_KEY_ENV))
}
fn refresh_minimax_oauth_access_token(name: &str, refresh_token: &str) -> anyhow::Result<String> {
let region = minimax_oauth_region(name);
let endpoint = region.token_endpoint();
let client_id = minimax_oauth_client_id();
let client = reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(15))
.connect_timeout(std::time::Duration::from_secs(5))
.build()
.unwrap_or_else(|_| reqwest::blocking::Client::new());
let response = client
.post(endpoint)
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Accept", "application/json")
.form(&[
("grant_type", "refresh_token"),
("refresh_token", refresh_token),
("client_id", client_id.as_str()),
])
.send()
.map_err(|error| anyhow::anyhow!("MiniMax OAuth refresh request failed: {error}"))?;
let status = response.status();
let body = response
.text()
.unwrap_or_else(|_| "<failed to read MiniMax OAuth response body>".to_string());
let parsed = serde_json::from_str::<MinimaxOauthRefreshResponse>(&body).ok();
if !status.is_success() {
let detail = parsed
.as_ref()
.and_then(|payload| payload.base_resp.as_ref())
.and_then(|base| base.status_msg.as_deref())
.filter(|msg| !msg.trim().is_empty())
.unwrap_or(body.as_str());
anyhow::bail!("MiniMax OAuth refresh failed (HTTP {status}): {detail}");
}
if let Some(payload) = parsed {
if let Some(status_text) = payload.status.as_deref()
&& !status_text.eq_ignore_ascii_case("success")
{
let detail = payload
.base_resp
.as_ref()
.and_then(|base| base.status_msg.as_deref())
.unwrap_or(status_text);
anyhow::bail!("MiniMax OAuth refresh failed: {detail}");
}
if let Some(token) = payload
.access_token
.as_deref()
.map(str::trim)
.filter(|token| !token.is_empty())
{
return Ok(token.to_string());
}
}
anyhow::bail!("MiniMax OAuth refresh response missing access_token");
}
fn resolve_minimax_oauth_refresh_token(name: &str) -> Option<String> {
let refresh_token = read_non_empty_env(MINIMAX_OAUTH_REFRESH_TOKEN_ENV)?;
match refresh_minimax_oauth_access_token(name, &refresh_token) {
Ok(token) => Some(token),
Err(error) => {
tracing::warn!(provider = name, error = %error, "MiniMax OAuth refresh failed");
None
}
}
}
pub fn canonical_china_provider_name(name: &str) -> Option<&'static str> {
if is_qwen_alias(name) {
Some("qwen")
} else if is_glm_alias(name) {
Some("glm")
} else if is_moonshot_alias(name) {
Some("moonshot")
} else if is_minimax_alias(name) {
Some("minimax")
} else if is_zai_alias(name) {
Some("zai")
} else if is_qianfan_alias(name) {
Some("qianfan")
} else if is_doubao_alias(name) {
Some("doubao")
} else if is_bailian_alias(name) {
Some("bailian")
} else {
None
}
}
fn minimax_base_url(name: &str) -> Option<&'static str> {
if is_minimax_cn_alias(name) {
Some(MINIMAX_CN_BASE_URL)
} else if is_minimax_intl_alias(name) {
Some(MINIMAX_INTL_BASE_URL)
} else {
None
}
}
fn glm_base_url(name: &str) -> Option<&'static str> {
if is_glm_cn_alias(name) {
Some(GLM_CN_BASE_URL)
} else if is_glm_global_alias(name) {
Some(GLM_GLOBAL_BASE_URL)
} else {
None
}
}
fn moonshot_base_url(name: &str) -> Option<&'static str> {
if is_moonshot_intl_alias(name) {
Some(MOONSHOT_INTL_BASE_URL)
} else if is_moonshot_cn_alias(name) {
Some(MOONSHOT_CN_BASE_URL)
} else {
None
}
}
fn qwen_base_url(name: &str) -> Option<&'static str> {
if is_qwen_cn_alias(name) || is_qwen_oauth_alias(name) {
Some(QWEN_CN_BASE_URL)
} else if is_qwen_intl_alias(name) {
Some(QWEN_INTL_BASE_URL)
} else if is_qwen_us_alias(name) {
Some(QWEN_US_BASE_URL)
} else {
None
}
}
fn zai_base_url(name: &str) -> Option<&'static str> {
if is_zai_cn_alias(name) {
Some(ZAI_CN_BASE_URL)
} else if is_zai_global_alias(name) {
Some(ZAI_GLOBAL_BASE_URL)
} else {
None
}
}
#[derive(Debug, Clone)]
pub struct ProviderRuntimeOptions {
pub auth_profile_override: Option<String>,
pub provider_api_url: Option<String>,
pub zeroclaw_dir: Option<PathBuf>,
pub secrets_encrypt: bool,
pub reasoning_enabled: Option<bool>,
pub reasoning_effort: Option<String>,
/// HTTP request timeout in seconds for LLM provider API calls.
/// `None` uses the provider's built-in default (120s for compatible providers).
pub provider_timeout_secs: Option<u64>,
/// Extra HTTP headers to include in provider API requests.
/// These are merged from the config file and `ZEROCLAW_EXTRA_HEADERS` env var.
pub extra_headers: std::collections::HashMap<String, String>,
/// Custom API path suffix for OpenAI-compatible providers
/// (e.g. "/v2/generate" instead of the default "/chat/completions").
pub api_path: Option<String>,
/// Maximum output tokens for LLM provider API requests.
/// `None` uses the provider's built-in default.
pub provider_max_tokens: Option<u32>,
/// When true, system messages are merged into the first user message before
/// sending. Propagated from `ModelProviderConfig::merge_system_into_user`.
pub merge_system_into_user: bool,
}
impl Default for ProviderRuntimeOptions {
fn default() -> Self {
Self {
auth_profile_override: None,
provider_api_url: None,
zeroclaw_dir: None,
secrets_encrypt: true,
reasoning_enabled: None,
reasoning_effort: None,
provider_timeout_secs: None,
extra_headers: std::collections::HashMap::new(),
api_path: None,
provider_max_tokens: None,
merge_system_into_user: false,
}
}
}
pub fn provider_runtime_options_from_config(
config: &zeroclaw_config::schema::Config,
) -> ProviderRuntimeOptions {
// Resolve merge_system_into_user from the active model provider profile by
// matching api_url ā apply_named_model_provider_profile() has already run
// and rewritten default_provider, but model_providers retains all profiles.
let merge_system_into_user = config
.api_url
.as_deref()
.map(str::trim)
.filter(|u| !u.is_empty())
.and_then(|active_url| {
config.model_providers.values().find(|p| {
p.base_url
.as_deref()
.map(str::trim)
.filter(|u| !u.is_empty())
.map(|u| u.trim_end_matches('/'))
== Some(active_url.trim_end_matches('/'))
})
})
.map(|p| p.merge_system_into_user)
.unwrap_or(false);
ProviderRuntimeOptions {
auth_profile_override: None,
provider_api_url: config.api_url.clone(),
zeroclaw_dir: config.config_path.parent().map(PathBuf::from),
secrets_encrypt: config.secrets.encrypt,
reasoning_enabled: config.runtime.reasoning_enabled,
reasoning_effort: config.runtime.reasoning_effort.clone(),
provider_timeout_secs: Some(config.provider_timeout_secs),
extra_headers: config.extra_headers.clone(),
api_path: config.api_path.clone(),
provider_max_tokens: config.provider_max_tokens,
merge_system_into_user,
}
}
fn is_secret_char(c: char) -> bool {
c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | ':')
}
fn token_end(input: &str, from: usize) -> usize {
let mut end = from;
for (i, c) in input[from..].char_indices() {
if is_secret_char(c) {
end = from + i + c.len_utf8();
} else {
break;
}
}
end
}
/// Scrub known secret-like token prefixes from provider error strings.
///
/// Redacts tokens with prefixes like `sk-`, `xoxb-`, `xoxp-`, `ghp_`, `gho_`,
/// `ghu_`, and `github_pat_`.
pub fn scrub_secret_patterns(input: &str) -> String {
const PREFIXES: [&str; 7] = [
"sk-",
"xoxb-",
"xoxp-",
"ghp_",
"gho_",
"ghu_",
"github_pat_",
];
let mut scrubbed = input.to_string();
for prefix in PREFIXES {
let mut search_from = 0;
loop {
let Some(rel) = scrubbed[search_from..].find(prefix) else {
break;
};
let start = search_from + rel;
let content_start = start + prefix.len();
let end = token_end(&scrubbed, content_start);
// Bare prefixes like "sk-" should not stop future scans.
if end == content_start {
search_from = content_start;
continue;
}
scrubbed.replace_range(start..end, "[REDACTED]");
search_from = start + "[REDACTED]".len();
}
}
scrubbed
}
/// Sanitize API error text by scrubbing secrets and truncating length.
pub fn sanitize_api_error(input: &str) -> String {
let scrubbed = scrub_secret_patterns(input);
if scrubbed.chars().count() <= MAX_API_ERROR_CHARS {
return scrubbed;
}
let mut end = MAX_API_ERROR_CHARS;
while end > 0 && !scrubbed.is_char_boundary(end) {
end -= 1;
}
format!("{}...", &scrubbed[..end])
}
/// Build a sanitized provider error from a failed HTTP response.
pub async fn api_error(provider: &str, response: reqwest::Response) -> anyhow::Error {
let status = response.status();
let body = response
.text()
.await
.unwrap_or_else(|_| "<failed to read provider error body>".to_string());
let sanitized = sanitize_api_error(&body);
anyhow::anyhow!("{provider} API error ({status}): {sanitized}")
}
/// Resolve API key for a provider from config and environment variables.
///
/// Resolution order:
/// 1. Explicitly provided `api_key` parameter (trimmed, filtered if empty)
/// 2. Provider-specific environment variable (e.g., `ANTHROPIC_OAUTH_TOKEN`, `OPENROUTER_API_KEY`)
/// 3. Generic fallback variables (`ZEROCLAW_API_KEY`, `API_KEY`)
///
/// For Anthropic, the provider-specific env var is `ANTHROPIC_OAUTH_TOKEN` (for setup-tokens)
/// followed by `ANTHROPIC_API_KEY` (for regular API keys).
///
/// For MiniMax, OAuth mode supports `api_key = "minimax-oauth"`, resolving credentials from
/// `MINIMAX_OAUTH_TOKEN` first, then `MINIMAX_API_KEY`, and finally
/// `MINIMAX_OAUTH_REFRESH_TOKEN` (automatic access-token refresh).
fn resolve_provider_credential(name: &str, credential_override: Option<&str>) -> Option<String> {
let mut minimax_oauth_placeholder_requested = false;
if let Some(raw_override) = credential_override {
let trimmed_override = raw_override.trim();
if !trimmed_override.is_empty() {
if is_minimax_alias(name) && is_minimax_oauth_placeholder(trimmed_override) {
minimax_oauth_placeholder_requested = true;
if let Some(credential) = resolve_minimax_static_credential() {
return Some(credential);
}
if let Some(credential) = resolve_minimax_oauth_refresh_token(name) {
return Some(credential);
}
} else if name == "anthropic" || name == "openai" || name == "groq" {
// For well-known providers, prefer provider-specific env vars over the
// global api_key override, since the global key may belong to a different
// provider (e.g. a custom: gateway). This enables multi-provider setups
// where the primary uses a custom gateway and fallbacks use named providers.
let env_candidates: &[&str] = match name {
"anthropic" => &["ANTHROPIC_OAUTH_TOKEN", "ANTHROPIC_API_KEY"],
"openai" => &["OPENAI_API_KEY"],
"groq" => &["GROQ_API_KEY"],
_ => &[],
};
for env_var in env_candidates {
if let Ok(val) = std::env::var(env_var) {
let trimmed = val.trim().to_string();
if !trimmed.is_empty() {
return Some(trimmed);
}
}
}
return Some(trimmed_override.to_owned());
} else {
return Some(trimmed_override.to_owned());
}
}
}
let provider_env_candidates: Vec<&str> = match name {
"anthropic" => vec!["ANTHROPIC_OAUTH_TOKEN", "ANTHROPIC_API_KEY"],
"openrouter" => vec!["OPENROUTER_API_KEY"],
"openai" => vec!["OPENAI_API_KEY"],
"ollama" => vec!["OLLAMA_API_KEY"],
"venice" => vec!["VENICE_API_KEY"],
"groq" => vec!["GROQ_API_KEY"],
"mistral" => vec!["MISTRAL_API_KEY"],
"deepseek" => vec!["DEEPSEEK_API_KEY"],
"xai" | "grok" => vec!["XAI_API_KEY"],
"together" | "together-ai" => vec!["TOGETHER_API_KEY"],
"fireworks" | "fireworks-ai" => vec!["FIREWORKS_API_KEY"],
"novita" => vec!["NOVITA_API_KEY"],
"perplexity" => vec!["PERPLEXITY_API_KEY"],
"cohere" => vec!["COHERE_API_KEY"],
"manifest" | "mnfst" | "manifest-router" => vec!["MANIFEST_API_KEY", "MNFST_API_KEY"],
name if is_moonshot_alias(name) => vec!["MOONSHOT_API_KEY"],
"kimi-code" | "kimi_coding" | "kimi_for_coding" => {
vec!["KIMI_CODE_API_KEY", "MOONSHOT_API_KEY"]
}
name if is_glm_alias(name) => vec!["GLM_API_KEY"],
name if is_minimax_alias(name) => vec![MINIMAX_OAUTH_TOKEN_ENV, MINIMAX_API_KEY_ENV],
// Bedrock supports Bearer token auth via BEDROCK_API_KEY env var, in addition
// to AWS AKSK (SigV4). If BEDROCK_API_KEY is set, return it; otherwise return
// None and let BedrockProvider handle SigV4 credential resolution internally.
"bedrock" | "aws-bedrock" => {
if let Ok(val) = std::env::var("BEDROCK_API_KEY") {
let trimmed = val.trim().to_string();
if !trimmed.is_empty() {
return Some(trimmed);
}
}
return None;
}
name if is_qianfan_alias(name) => vec!["QIANFAN_API_KEY"],
name if is_doubao_alias(name) => {
vec!["ARK_API_KEY", "VOLCENGINE_API_KEY", "DOUBAO_API_KEY"]
}
name if is_qwen_alias(name) => vec!["DASHSCOPE_API_KEY"],
name if is_bailian_alias(name) => vec!["BAILIAN_API_KEY", "DASHSCOPE_API_KEY"],
name if is_zai_alias(name) => vec!["ZAI_API_KEY"],
"nvidia" | "nvidia-nim" | "build.nvidia.com" => vec!["NVIDIA_API_KEY"],
"synthetic" => vec!["SYNTHETIC_API_KEY"],
"opencode" | "opencode-zen" => vec!["OPENCODE_API_KEY"],
"opencode-go" => vec!["OPENCODE_GO_API_KEY"],
"vercel" | "vercel-ai" => vec!["VERCEL_API_KEY"],
"cloudflare" | "cloudflare-ai" => vec!["CLOUDFLARE_API_KEY"],
"ovhcloud" | "ovh" => vec!["OVH_AI_ENDPOINTS_ACCESS_TOKEN"],
"astrai" => vec!["ASTRAI_API_KEY"],
"avian" => vec!["AVIAN_API_KEY"],
"deepmyst" | "deep-myst" => vec!["DEEPMYST_API_KEY"],
"llamacpp" | "llama.cpp" => vec!["LLAMACPP_API_KEY"],
"sglang" => vec!["SGLANG_API_KEY"],
"vllm" => vec!["VLLM_API_KEY"],
"aihubmix" => vec!["AIHUBMIX_API_KEY"],
"siliconflow" | "silicon-flow" => vec!["SILICONFLOW_API_KEY"],
"osaurus" => vec!["OSAURUS_API_KEY"],
"telnyx" => vec!["TELNYX_API_KEY"],
"azure_openai" | "azure-openai" | "azure" => vec!["AZURE_OPENAI_API_KEY"],
_ => vec![],
};
for env_var in provider_env_candidates {
if let Ok(value) = std::env::var(env_var) {
let value = value.trim();
if !value.is_empty() {
return Some(value.to_string());
}
}
}
if is_minimax_alias(name)
&& let Some(credential) = resolve_minimax_oauth_refresh_token(name)
{
return Some(credential);
}
if minimax_oauth_placeholder_requested && is_minimax_alias(name) {
return None;
}
for env_var in ["ZEROCLAW_API_KEY", "API_KEY"] {
if let Ok(value) = std::env::var(env_var) {