File size: 56,498 Bytes
b0074f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
"""
Antigravity API Client - Handles communication with Google's Antigravity API
处理与 Google Antigravity API 的通信
"""

import asyncio
import hashlib
import json
import time
import traceback
import uuid
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional, Callable, Set, Tuple

from fastapi import Response
from config import (
    get_antigravity_api_url,
    get_auto_ban_error_codes,
    get_request_log_enabled,
    get_request_log_error_codes,
    get_usage_log_enabled,
)
from log import log

from src.credential_manager import (
    add_credential,
    get_valid_credential,
    refresh_token,
    should_refresh_token,
    update_credential_state,
)
from src.httpx_client import stream_post_async, post_async
from src.models import Model, model_to_dict
from src.storage.database import get_database
from src.utils import ANTIGRAVITY_USER_AGENT
from src.session_cache import derive_session_key
from src.usage_log import (
    extract_usage_tokens,
    new_request_id,
    record_usage_log,
)
from src.request_body_log import record_request_body

# 导入共同的基础功能
from src.api.utils import (
    handle_error_with_retry,
    get_retry_config,
    record_api_call_success,
    record_api_call_error,
    parse_and_log_cooldown,
)

# ==================== 全局凭证管理器 ====================


def _extract_first_user_text(request_payload: Dict[str, Any]) -> str:
    contents = request_payload.get("contents", [])
    if not isinstance(contents, list):
        return ""
    for content in contents:
        if not isinstance(content, dict) or content.get("role") != "user":
            continue
        parts = content.get("parts", [])
        if not isinstance(parts, list):
            continue
        for part in parts:
            if isinstance(part, dict) and part.get("text"):
                return str(part["text"])
    return ""


def _generate_request_id() -> str:
    """生成完整格式的 requestId,对齐参考实现:
    agent/{uuid}/{毫秒时间戳}/{trajectory_id}/{step}
    """
    trajectory_id = str(uuid.uuid4())
    step = 1
    ms = int(datetime.now(timezone.utc).timestamp() * 1000)
    return f"agent/{uuid.uuid4()}/{ms}/{trajectory_id}/{step}"


def _build_labels(model: str, trajectory_id: str, step: int) -> Dict[str, str]:
    used_claude = "claude" in model.lower()
    return {
        "last_step_index": str(step),
        "model_enum": model,
        "trajectory_id": trajectory_id,
        "used_claude": str(used_claude).lower(),
        "used_claude_conservative": str(used_claude).lower(),
    }


def _should_forward_antigravity_header(header_name: str) -> bool:
    normalized = header_name.strip().lower()
    if not normalized:
        return False
    if normalized.startswith("x-b3-"):
        return True
    return normalized in {
        "accept-language",
        "traceparent",
        "tracestate",
        "x-cloud-trace-context",
        "x-goog-api-client",
        "x-goog-request-params",
        "x-goog-user-project",
        "x-request-id",
    }


def _sanitize_antigravity_headers(extra_headers: Optional[Dict[str, str]]) -> Dict[str, str]:
    if not extra_headers:
        return {}
    sanitized: Dict[str, str] = {}
    for key, value in extra_headers.items():
        if _should_forward_antigravity_header(key):
            sanitized[key] = value
    return sanitized


async def wrap_cli_request(
    gemini_request: Dict[str, Any],
    model: str,
    project_id: str,
) -> Tuple[Dict[str, Any], str]:
    """
    将 Gemini 格式请求包装成 Antigravity CLI 格式。
    返回 (payload, request_id)。
    """
    # 浅拷贝 + 只重建需要修改的层(toolConfig/functionCallingConfig),
    # 避免对大 payload(长对话历史)做整体 deepcopy 的热路径开销;
    # contents 等未修改字段与调用方共享引用(调用方随后不再修改)
    inner = dict(gemini_request)
    first_user_text = _extract_first_user_text(inner)

    # 注入 sessionId
    session_id = str(inner.get("sessionId") or "").strip()
    if not session_id:
        if first_user_text:
            digest = hashlib.sha256(first_user_text.encode("utf-8")).digest()
            session_id_val = int.from_bytes(digest[:8], "big") & 0x7FFFFFFFFFFFFFFF
            session_id = f"-{session_id_val}"
        else:
            session_id = f"-{uuid.uuid4().int % 9_000_000_000_000_000_000}"
        inner["sessionId"] = session_id

    # 注入 labels
    inner["labels"] = _build_labels(model, session_id, 1)

    # toolConfig 默认 VALIDATED(重建这两层,不污染调用方的 dict)
    src_tool_config = inner.get("toolConfig") or {}
    src_func_config = src_tool_config.get("functionCallingConfig") or {}
    func_config = dict(src_func_config)
    func_config["mode"] = "VALIDATED"
    tool_config = dict(src_tool_config)
    tool_config["functionCallingConfig"] = func_config
    inner["toolConfig"] = tool_config

    request_id = _generate_request_id()

    payload = {
        "project": project_id,
        "requestId": request_id,
        "request": inner,
        "model": model,
        "requestType": "agent",
    }
    return payload, request_id


# ==================== 辅助函数 ====================

def build_antigravity_headers(
    access_token: str,
    extra_headers: Optional[Dict[str, str]] = None,
    model_name: str = "",
) -> Dict[str, str]:
    """构建 Antigravity CLI API 请求头。"""
    headers = {
        "User-Agent": ANTIGRAVITY_USER_AGENT,
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json",
        "Accept": "*/*",
        "Accept-Encoding": "gzip",
        "Connection": "close",
        "requestId": f"req-{uuid.uuid4()}",
    }

    for key, value in _sanitize_antigravity_headers(extra_headers).items():
        headers.setdefault(key, value)

    # 根据模型名称判断 request_type
    if model_name:
        if "image" in model_name.lower():
            headers["requestType"] = "image_gen"
        else:
            headers["requestType"] = "agent"

    return headers


def _is_retryable_status(status_code: int, disable_error_codes: List[int]) -> bool:
    """统一判断是否属于可重试状态码。"""
    return status_code in (429, 503) or status_code in disable_error_codes


async def _switch_credential_for_retry(
    *,
    next_cred_task: Optional[asyncio.Task],
    retry_interval: float,
    refresh_credential_fast: Callable[[], Any],
    apply_cred_result: Callable[[Tuple[str, Dict[str, Any]]], bool],
    log_prefix: str,
) -> Tuple[bool, Optional[asyncio.Task]]:
    """优先使用预热凭证,失败后退回同步刷新。"""
    if next_cred_task is not None:
        try:
            cred_result = await next_cred_task
            next_cred_task = None
            if cred_result and apply_cred_result(cred_result):
                await asyncio.sleep(retry_interval)
                return True, next_cred_task
        except Exception as e:
            log.warning(f"{log_prefix} 预热凭证任务失败: {e}")
            next_cred_task = None

    await asyncio.sleep(retry_interval)
    if await refresh_credential_fast():
        return True, next_cred_task

    return False, next_cred_task


# ==================== 新的流式和非流式请求函数 ====================

def _derive_session_key(model_name: str, body: Dict[str, Any]) -> Optional[str]:
    """从 API 请求体派生会话 key(凭证亲和 cache 模式使用)

    body 格式: {"model": ..., "request": <Gemini 规范化请求>}
    hash(模型 + systemInstruction 或 第一条 user 消息) —— 后者必须是经过所有格式处理后的内容
    """
    inner = body.get("request") if isinstance(body.get("request"), dict) else body
    return derive_session_key(model_name, inner)


def _base_log_entry(
    model_name: str,
    email: str,
    is_stream: bool,
    log_ctx: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """构建请求日志条目的公共字段

    model_name: 后端实际使用的真实模型名(映射后)
    log_ctx.client_model: 客户端请求的原始模型名(可能带功能前缀)
    """
    ctx = log_ctx or {}
    return {
        "request_id": ctx.get("request_id") or new_request_id(),
        "api_format": ctx.get("api_format", ""),
        "client_ip": ctx.get("client_ip", ""),
        "model_name": ctx.get("client_model") or model_name,
        "upstream_model_name": model_name,
        "credential_email": email,
        "is_stream": is_stream,
    }


async def _record_request_body_detail(
    status_code: int,
    error_message: str,
    log_entry: Dict[str, Any],
    *,
    url: str,
    headers: Optional[Dict[str, str]],
    payload: Any,
    response_body: str,
    is_stream: bool,
) -> str:
    """
    请求体详细日志:开关开启且状态码命中配置错误码时写盘(JSON 文件),
    数据库只保存文件索引路径。任何异常不影响主流程。
    """
    try:
        if not await get_request_log_enabled():
            return ""
        if status_code not in await get_request_log_error_codes():
            return ""

        rel_path = await record_request_body(
            request_id=str(log_entry.get("request_id", "")),
            model_name=str(log_entry.get("model_name", "")),
            upstream_model_name=str(log_entry.get("upstream_model_name", "")),
            credential_email=str(log_entry.get("credential_email", "")),
            is_stream=is_stream,
            status_code=status_code,
            url=url,
            headers=headers,
            payload=payload,
            response_body=response_body,
            error_message=error_message,
        )
        return rel_path or ""
    except Exception as e:
        log.debug(f"请求体详细日志写入失败(不影响主流程): {e}")
        return ""


async def stream_request(
    body: Dict[str, Any],
    native: bool = False,
    headers: Optional[Dict[str, str]] = None,
    log_ctx: Optional[Dict[str, Any]] = None,
):
    """
    流式请求函数

    Args:
        body: 请求体
        native: 是否返回原生bytes流,False则返回str流
        headers: 额外的请求头

    Yields:
        Response对象(错误时)或 bytes流/str流(成功时)
    """
    model_name = body.get("model", "")

    # 请求日志:开始时间与基础条目(成功/失败均会记录一次)
    log_entry = _base_log_entry(model_name, "", True, log_ctx)
    log_start_time = time.time()

    # 凭证亲和: 从请求内容派生会话 key
    session_key = _derive_session_key(model_name, body)

    # 1. 获取有效凭证
    cred_result = await get_valid_credential(
        model_name=model_name, session_key=session_key
    )

    if not cred_result:
        # 如果返回值是None,直接返回错误500
        log.error("[ANTIGRAVITY STREAM] 当前无可用凭证")
        log_entry.update({
            "status_code": 500, "success": False,
            "error_message": "当前无可用凭证", "use_time": time.time() - log_start_time,
        })
        await record_usage_log(log_entry)
        yield Response(
            content=json.dumps({"error": "当前无可用凭证"}),
            status_code=500,
            media_type="application/json"
        )
        return

    current_file, credential_data = cred_result
    log_entry["credential_email"] = current_file
    access_token = credential_data.get("access_token") or credential_data.get("token")
    project_id = credential_data.get("project_id", "")

    if not access_token:
        log.error(f"[ANTIGRAVITY STREAM] No access token in credential: {current_file}")
        # 记录失败日志(含涉及的凭证)
        log_entry.update({
            "status_code": 500, "success": False,
            "error_message": "凭证中没有访问令牌", "use_time": time.time() - log_start_time,
        })
        await record_usage_log(log_entry)
        yield Response(
            content=json.dumps({"error": "凭证中没有访问令牌"}),
            status_code=500,
            media_type="application/json"
        )
        return

    # 2. 构建URL和请求头(端点来自配置,支持面板热更新)
    target_url = f"{await get_antigravity_api_url()}/v1internal:streamGenerateContent?alt=sse"

    auth_headers = build_antigravity_headers(access_token, headers, model_name)

    # 构建 CLI 格式请求体
    inner_request = body.get("request", body)
    final_payload, _ = await wrap_cli_request(inner_request, model_name, project_id)

    # 3. 调用stream_post_async进行请求
    retry_config = await get_retry_config()
    max_retries = retry_config["max_retries"]
    retry_interval = retry_config["retry_interval"]

    DISABLE_ERROR_CODES = await get_auto_ban_error_codes()  # 禁用凭证的错误码
    last_error_response = None  # 记录最后一次的错误响应
    last_error_body = ""  # 详细日志:最后一次的错误响应体
    next_cred_task = None  # 预热的下一个凭证任务
    excluded_emails: Set[str] = {current_file} if current_file else set()

    # 内部函数:快速更新凭证(只更新token和project_id,避免重建整个请求)
    async def refresh_credential_fast(strict_exclude: bool = False):
        nonlocal current_file, access_token, auth_headers, project_id, final_payload
        cred_result = await get_valid_credential(
            model_name=model_name,
            session_key=session_key,
            exclude_emails=excluded_emails,
        )
        if not cred_result and not strict_exclude:
            # 若排除已尝试凭证后无候选,退回不排除(例如仅有一个可用凭证时的普通重试)
            cred_result = await get_valid_credential(
                model_name=model_name, session_key=session_key
            )
        if not cred_result:
            return None
        current_file, credential_data = cred_result
        if current_file:
            excluded_emails.add(current_file)
        access_token = credential_data.get("access_token") or credential_data.get("token")
        project_id = credential_data.get("project_id", "")
        if not access_token:
            return None
        # 只更新token和project_id,不重建整个headers和payload
        auth_headers["Authorization"] = f"Bearer {access_token}"
        final_payload["project"] = project_id
        return True

    async def refresh_credential_fast_strict():
        return await refresh_credential_fast(strict_exclude=True)

    def apply_cred_result(cred_result: Tuple[str, Dict[str, Any]]) -> bool:
        nonlocal current_file, access_token, project_id, auth_headers, final_payload
        current_file, credential_data = cred_result
        if current_file:
            excluded_emails.add(current_file)
        access_token = credential_data.get("access_token") or credential_data.get("token")
        project_id = credential_data.get("project_id", "")
        if not access_token or not project_id:
            return False
        auth_headers["Authorization"] = f"Bearer {access_token}"
        final_payload["project"] = project_id
        return True

    for attempt in range(max_retries + 1):
        success_recorded = False  # 标记是否已记录成功
        need_retry = False  # 标记是否需要重试
        usage_tokens: Dict[str, int] = {}  # 从流中提取的 token 用量
        attempt_start_time = time.time()  # 本次上游调用开始时间

        async def _log_stream_result(status_code: int, success: bool, error_message: str = "") -> None:
            """
            写入一次上游调用的请求日志(调用一次谷歌 API 产生一条日志;
            重试会在后续 attempt 各自再记一条,属于正常行为)。
            """
            # 请求体详细日志:命中配置错误码时写盘,数据库只存文件索引
            request_log_file = await _record_request_body_detail(
                status_code,
                error_message,
                log_entry,
                url=target_url,
                headers=auth_headers,
                payload=final_payload,
                response_body=last_error_body,
                is_stream=True,
            )

            # 每条日志记录本次调用实际使用的凭证
            await record_usage_log({
                **log_entry,
                "credential_email": current_file,
                "status_code": status_code,
                "success": success,
                "use_time": time.time() - attempt_start_time,
                "error_message": error_message[:500],
                "request_log_file": request_log_file,
                **usage_tokens,
            })

        try:
            async for chunk in stream_post_async(
                url=target_url,
                body=final_payload,
                native=native,
                headers=auth_headers
            ):
                # 判断是否是Response对象
                if isinstance(chunk, Response):
                    status_code = chunk.status_code
                    last_error_response = chunk  # 记录最后一次错误

                    # 缓存错误解析结果,避免重复decode
                    error_body = None
                    try:
                        error_body = chunk.body.decode('utf-8') if isinstance(chunk.body, bytes) else str(chunk.body)
                    except Exception:
                        error_body = ""
                    last_error_body = error_body or ""

                    # 404 模型不可用:立即更新该凭证的模型列表,并尝试切换到其他支持该模型的凭证重试
                    if status_code == 404:
                        log.warning(
                            f"[ANTIGRAVITY STREAM] 模型 {model_name} 在凭证 {current_file} 上返回 404,更新凭证模型列表并尝试切换凭证"
                        )
                        await _handle_model_not_found_for_credential(current_file, model_name)
                        await _log_stream_result(status_code, False, error_body[:500] or "HTTP 404")

                        if attempt < max_retries:
                            switched, next_cred_task = await _switch_credential_for_retry(
                                next_cred_task=None,
                                retry_interval=0.0,
                                refresh_credential_fast=lambda: refresh_credential_fast_strict(),
                                apply_cred_result=apply_cred_result,
                                log_prefix="[ANTIGRAVITY STREAM]",
                            )
                            if switched:
                                log.info(
                                    f"[ANTIGRAVITY STREAM] 404 已切换至新凭证 {current_file} 重试 (attempt {attempt + 2}/{max_retries + 1})"
                                )
                                continue
                        log.error(f"[ANTIGRAVITY STREAM] 无其他支持模型 {model_name} 的凭证,返回 404")
                        yield chunk
                        return

                    # 如果错误码是429、503或者在禁用码当中,做好记录后进行重试
                    if _is_retryable_status(status_code, DISABLE_ERROR_CODES):
                        log.warning(f"[ANTIGRAVITY STREAM] 流式请求失败 (status={status_code}), 凭证: {current_file}, 响应: {error_body[:500] if error_body else '无'}")

                        # 解析冷却时间
                        cooldown_until = None
                        if (status_code == 429 or status_code == 503) and error_body:
                            try:
                                cooldown_until = await parse_and_log_cooldown(error_body)
                            except Exception:
                                pass

                        # 预热下一个凭证
                        if next_cred_task is None and attempt < max_retries:
                            next_cred_task = asyncio.create_task(
                                get_valid_credential(
                                    model_name=model_name,
                                    session_key=session_key,
                                    exclude_emails=excluded_emails,
                                )
                            )

                        # 记录错误并切换凭证
                        await record_api_call_error(current_file, status_code, cooldown_until, model_name=model_name,
                            error_message=error_body
                        )
                        # 本次上游调用产生一条日志(重试会再各记一条)
                        await _log_stream_result(status_code, False, error_body[:500] or f"HTTP {status_code}")

                        # 检查是否应该重试
                        should_retry = await handle_error_with_retry(status_code, current_file, retry_config["retry_enabled"], attempt, max_retries, retry_interval)

                        if should_retry and attempt < max_retries:
                            need_retry = True
                            break  # 跳出内层循环,准备重试
                        else:
                            # 不重试,直接返回原始错误
                            log.error(f"[ANTIGRAVITY STREAM] 达到最大重试次数或不应重试,返回原始错误")
                            yield chunk
                            return
                    else:
                        # 错误码不在禁用码当中,直接返回,无需重试
                        log.error(f"[ANTIGRAVITY STREAM] 流式请求失败,非重试错误码 (status={status_code}), 凭证: {current_file}, 响应: {error_body[:500] if error_body else '无'}")
                        await record_api_call_error(current_file, status_code, None, model_name=model_name,
                            error_message=error_body
                        )
                        await _log_stream_result(status_code, False, error_body[:500] or f"HTTP {status_code}")
                        yield chunk
                        return
                else:
                    # 不是Response,说明是真流,直接yield返回
                    # 只在第一个chunk时记录成功
                    if not success_recorded:
                        await record_api_call_success(current_file, model_name=model_name)
                        success_recorded = True
                        log.debug(f"[ANTIGRAVITY STREAM] 开始接收流式响应,模型: {model_name}")

                    # 从流块中提取 token 用量(热路径优化):
                    # usageMetadata 几乎只出现在流尾块。先用低开销的子串探测,
                    # 命中才做完整 JSON 解析,避免对每个 chunk 两次 json.loads
                    if native is False and "usageMetadata" in chunk:
                        extracted = extract_usage_tokens(chunk)
                        if extracted:
                            usage_tokens = extracted

                    yield chunk

            # 流式请求完成,检查结果
            if success_recorded:
                log.debug(f"[ANTIGRAVITY STREAM] 流式响应完成,模型: {model_name}")
                await _log_stream_result(200, True)
                return
            elif not need_retry:
                # 没有收到任何数据(空回复),需要重试
                log.warning(f"[ANTIGRAVITY STREAM] 收到空回复,无任何内容,凭证: {current_file}")
                await record_api_call_error(current_file, 200, None, model_name=model_name,
                    error_message="Empty response from API"
                )
                # 本次上游调用(空回复)产生一条日志
                await _log_stream_result(200, False, "Empty response from API")

                if attempt < max_retries:
                    need_retry = True
                else:
                    log.error(f"[ANTIGRAVITY STREAM] 空回复达到最大重试次数")
                    yield Response(
                        content=json.dumps({"error": "服务返回空回复"}),
                        status_code=500,
                        media_type="application/json"
                    )
                    return
            
            # 统一处理重试
            if need_retry:
                log.info(f"[ANTIGRAVITY STREAM] 重试请求 (attempt {attempt + 2}/{max_retries + 1})...")

                switched, next_cred_task = await _switch_credential_for_retry(
                    next_cred_task=next_cred_task,
                    retry_interval=retry_interval,
                    refresh_credential_fast=refresh_credential_fast,
                    apply_cred_result=apply_cred_result,
                    log_prefix="[ANTIGRAVITY STREAM]",
                )
                if not switched:
                    # 换凭证失败,本次未调用谷歌 API,不产生日志
                    log.error("[ANTIGRAVITY STREAM] 重试时无可用凭证或令牌")
                    yield Response(
                        content=json.dumps({"error": "当前无可用凭证"}),
                        status_code=500,
                        media_type="application/json"
                    )
                    return
                continue  # 重试

        except GeneratorExit:
            # 下游提前关闭了本生成器(转换器断流、抗截断续传、客户端断开等)。
            # 已收到上游数据却未走到正常收尾时,补记一条成功日志,避免请求
            # 日志丢失(issue #438);GeneratorExit 不可吞,必须 re-raise
            if success_recorded:
                log.debug("[ANTIGRAVITY STREAM] 生成器被提前关闭,补记成功日志")
                await _log_stream_result(200, True)
            raise

        except Exception as e:
            log.error(f"[ANTIGRAVITY STREAM] 流式请求异常: {e}, 凭证: {current_file}")
            if attempt < max_retries:
                log.info(f"[ANTIGRAVITY STREAM] 异常后重试 (attempt {attempt + 2}/{max_retries + 1})...")
                # 本次上游调用(异常)产生一条日志
                await _log_stream_result(500, False, f"异常: {e}")
                await asyncio.sleep(retry_interval)
                continue
            else:
                # 所有重试都失败,返回最后一次的错误(如果有)
                log.error(f"[ANTIGRAVITY STREAM] 所有重试均失败,最后异常: {e}")
                await _log_stream_result(500, False, f"异常: {e}")
                if last_error_response:
                    yield last_error_response
                else:
                    # 如果没有记录到错误响应,返回500错误
                    yield Response(
                        content=json.dumps({"error": f"流式请求异常: {str(e)}"}),
                        status_code=500,
                        media_type="application/json"
                    )
                return

    # 所有重试均已耗尽(for循环正常结束)——每次上游调用均已各自记录日志,
    # 这里不额外记录,直接返回最后一次的错误响应
    log.error("[ANTIGRAVITY STREAM] 所有重试均失败")
    if last_error_response:
        yield last_error_response
    else:
        yield Response(
            content=json.dumps({"error": "请求失败,所有重试均已耗尽"}),
            status_code=429,
            media_type="application/json"
        )


async def non_stream_request(
    body: Dict[str, Any],
    headers: Optional[Dict[str, str]] = None,
    log_ctx: Optional[Dict[str, Any]] = None,
) -> Response:
    """
    非流式请求函数

    Args:
        body: 请求体
        headers: 额外的请求头
        log_ctx: 请求日志上下文(api_format / client_ip / request_id)

    Returns:
        Response对象
    """
    model_name = body.get("model", "")

    # 请求日志:开始时间与基础条目(成功/失败均会记录一次)
    log_entry = _base_log_entry(model_name, "", False, log_ctx)
    log_start_time = time.time()

    # 详细日志上下文(发往上游的 URL/请求头/请求体;请求派发前为空)
    target_url = ""
    auth_headers: Optional[Dict[str, str]] = None
    final_payload: Dict[str, Any] = {}
    last_error_body = ""  # 详细日志:最后一次的错误响应体
    current_file = ""  # 当前使用的凭证(未获取前为空)
    attempt_start_time = time.time()  # 本次上游调用开始时间(循环内每次重置)

    async def _log_result(status_code: int, success: bool, response_content: Any = None, error_message: str = "") -> None:
        """
        写入一次上游调用的请求日志(调用一次谷歌 API 产生一条日志;
        重试会在后续 attempt 各自再记一条,属于正常行为)。
        """
        # 请求体详细日志:命中配置错误码时写盘,数据库只存文件索引
        request_log_file = await _record_request_body_detail(
            status_code,
            error_message,
            log_entry,
            url=target_url,
            headers=auth_headers,
            payload=final_payload,
            response_body=last_error_body,
            is_stream=False,
        )

        # usage_log 关闭时跳过 token 解析(避免无谓的整包 JSON 解析)
        tokens = {}
        if success and await get_usage_log_enabled():
            tokens = extract_usage_tokens(response_content)
        # 每条日志记录本次调用实际使用的凭证
        await record_usage_log({
            **log_entry,
            "credential_email": current_file,
            "status_code": status_code,
            "success": success,
            "use_time": time.time() - attempt_start_time,
            "error_message": error_message[:500],
            "request_log_file": request_log_file,
            **tokens,
        })

    # 凭证亲和: 从请求内容派生会话 key
    session_key = _derive_session_key(model_name, body)

    # 1. 获取有效凭证
    cred_result = await get_valid_credential(
        model_name=model_name, session_key=session_key
    )

    if not cred_result:
        # 如果返回值是None,直接返回错误500
        log.error("[ANTIGRAVITY] 当前无可用凭证")
        await _log_result(500, False, error_message="当前无可用凭证")
        return Response(
            content=json.dumps({"error": "当前无可用凭证"}),
            status_code=500,
            media_type="application/json"
        )

    current_file, credential_data = cred_result
    log_entry["credential_email"] = current_file
    access_token = credential_data.get("access_token") or credential_data.get("token")
    project_id = credential_data.get("project_id", "")

    if not access_token:
        log.error(f"[ANTIGRAVITY] No access token in credential: {current_file}")
        # 记录失败日志(含涉及的凭证)
        await _log_result(500, False, error_message="凭证中没有访问令牌")
        return Response(
            content=json.dumps({"error": "凭证中没有访问令牌"}),
            status_code=500,
            media_type="application/json"
        )

    # 2. 构建URL和请求头(端点来自配置,支持面板热更新)
    target_url = f"{await get_antigravity_api_url()}/v1internal:generateContent"

    auth_headers = build_antigravity_headers(access_token, headers, model_name)

    # 构建 CLI 格式请求体
    inner_request = body.get("request", body)
    final_payload, _ = await wrap_cli_request(inner_request, model_name, project_id)

    # 3. 调用post_async进行请求
    retry_config = await get_retry_config()
    max_retries = retry_config["max_retries"]
    retry_interval = retry_config["retry_interval"]

    DISABLE_ERROR_CODES = await get_auto_ban_error_codes()  # 禁用凭证的错误码
    last_error_response = None  # 记录最后一次的错误响应
    next_cred_task = None  # 预热的下一个凭证任务
    excluded_emails: Set[str] = {current_file} if current_file else set()

    # 内部函数:快速更新凭证(只更新token和project_id,避免重建整个请求)
    async def refresh_credential_fast(strict_exclude: bool = False):
        nonlocal current_file, access_token, auth_headers, project_id, final_payload
        cred_result = await get_valid_credential(
            model_name=model_name,
            session_key=session_key,
            exclude_emails=excluded_emails,
        )
        if not cred_result and not strict_exclude:
            cred_result = await get_valid_credential(
                model_name=model_name, session_key=session_key
            )
        if not cred_result:
            return None
        current_file, credential_data = cred_result
        if current_file:
            excluded_emails.add(current_file)
        access_token = credential_data.get("access_token") or credential_data.get("token")
        project_id = credential_data.get("project_id", "")
        if not access_token:
            return None
        # 只更新token和project_id,不重建整个headers和payload
        auth_headers["Authorization"] = f"Bearer {access_token}"
        final_payload["project"] = project_id
        return True

    async def refresh_credential_fast_strict():
        return await refresh_credential_fast(strict_exclude=True)

    def apply_cred_result(cred_result: Tuple[str, Dict[str, Any]]) -> bool:
        nonlocal current_file, access_token, project_id, auth_headers, final_payload
        current_file, credential_data = cred_result
        if current_file:
            excluded_emails.add(current_file)
        access_token = credential_data.get("access_token") or credential_data.get("token")
        project_id = credential_data.get("project_id", "")
        if not access_token or not project_id:
            return False
        auth_headers["Authorization"] = f"Bearer {access_token}"
        final_payload["project"] = project_id
        return True

    for attempt in range(max_retries + 1):
        need_retry = False  # 标记是否需要重试
        attempt_start_time = time.time()  # 本次上游调用开始时间
        
        try:
            response = await post_async(
                url=target_url,
                json=final_payload,
                headers=auth_headers
            )

            status_code = response.status_code

            # 成功
            if status_code == 200:
                # 检查是否为空回复
                if not response.content or len(response.content) == 0:
                    log.warning(f"[ANTIGRAVITY] 收到200响应但内容为空,凭证: {current_file}")
                    
                    # 记录错误
                    await record_api_call_error(current_file, 200, None, model_name=model_name,
                        error_message="Empty response from API"
                    )
                    # 本次上游调用(空回复)产生一条日志
                    await _log_result(200, False, error_message="Empty response from API")
                    
                    if attempt < max_retries:
                        need_retry = True
                    else:
                        log.error(f"[ANTIGRAVITY] 空回复达到最大重试次数")
                        return Response(
                            content=json.dumps({"error": "服务返回空回复"}),
                            status_code=500,
                            media_type="application/json"
                        )
                else:
                    # 正常响应
                    await record_api_call_success(current_file, model_name=model_name)
                    await _log_result(200, True, response_content=response.content)
                    return Response(
                        content=response.content,
                        status_code=200,
                        headers=dict(response.headers)
                    )

            # 失败 - 记录最后一次错误
            if status_code != 200:
                last_error_response = Response(
                    content=response.content,
                    status_code=status_code,
                    headers=dict(response.headers)
                )

                # 判断是否需要重试
                # 缓存错误文本,避免重复解析
                error_text = ""
                try:
                    error_text = response.text
                except Exception:
                    pass
                last_error_body = error_text

                # 404 模型不可用:立即更新该凭证的模型列表,并尝试切换到其他支持该模型的凭证重试
                if status_code == 404:
                    log.warning(
                        f"[ANTIGRAVITY] 模型 {model_name} 在凭证 {current_file} 上返回 404,更新凭证模型列表并尝试切换凭证"
                    )
                    await _handle_model_not_found_for_credential(current_file, model_name)
                    await _log_result(status_code, False, error_message=error_text[:500] or "HTTP 404")

                    if attempt < max_retries:
                        switched, next_cred_task = await _switch_credential_for_retry(
                            next_cred_task=None,
                            retry_interval=0.0,
                            refresh_credential_fast=refresh_credential_fast_strict,
                            apply_cred_result=apply_cred_result,
                            log_prefix="[ANTIGRAVITY]",
                        )
                        if switched:
                            log.info(
                                f"[ANTIGRAVITY] 404 已切换至新凭证 {current_file} 重试 (attempt {attempt + 2}/{max_retries + 1})"
                            )
                            continue
                    log.error(f"[ANTIGRAVITY] 无其他支持模型 {model_name} 的凭证,返回 404")
                    return last_error_response

                if _is_retryable_status(status_code, DISABLE_ERROR_CODES):
                    log.warning(f"[ANTIGRAVITY] 非流式请求失败 (status={status_code}), 凭证: {current_file}, 响应: {error_text[:500] if error_text else '无'}")

                    # 解析冷却时间
                    cooldown_until = None
                    if (status_code == 429 or status_code == 503) and error_text:
                        try:
                            cooldown_until = await parse_and_log_cooldown(error_text)
                        except Exception:
                            pass

                    # 并行预热下一个凭证,不阻塞当前处理
                    if next_cred_task is None and attempt < max_retries:
                        next_cred_task = asyncio.create_task(
                                get_valid_credential(
                                    model_name=model_name,
                                    session_key=session_key,
                                    exclude_emails=excluded_emails,
                                )
                            )

                    # 记录错误并切换凭证
                    await record_api_call_error(current_file, status_code, cooldown_until, model_name=model_name,
                        error_message=error_text
                    )
                    # 本次上游调用产生一条日志(重试会再各记一条)
                    await _log_result(status_code, False, error_message=error_text[:500] or f"HTTP {status_code}")

                    # 检查是否应该重试
                    should_retry = await handle_error_with_retry(status_code, current_file, retry_config["retry_enabled"], attempt, max_retries, retry_interval)

                    if should_retry and attempt < max_retries:
                        need_retry = True
                    else:
                        # 不重试,直接返回原始错误
                        log.error(f"[ANTIGRAVITY] 达到最大重试次数或不应重试,返回原始错误")
                        return last_error_response
                else:
                    # 错误码不在禁用码当中,直接返回,无需重试
                    log.error(f"[ANTIGRAVITY] 非流式请求失败,非重试错误码 (status={status_code}), 凭证: {current_file}, 响应: {error_text[:500] if error_text else '无'}")
                    await record_api_call_error(current_file, status_code, None, model_name=model_name,
                        error_message=error_text
                    )
                    await _log_result(status_code, False, error_message=error_text[:500] or f"HTTP {status_code}")
                    return last_error_response
            
            # 统一处理重试
            if need_retry:
                log.info(f"[ANTIGRAVITY] 重试请求 (attempt {attempt + 2}/{max_retries + 1})...")

                switched, next_cred_task = await _switch_credential_for_retry(
                    next_cred_task=next_cred_task,
                    retry_interval=retry_interval,
                    refresh_credential_fast=refresh_credential_fast,
                    apply_cred_result=apply_cred_result,
                    log_prefix="[ANTIGRAVITY]",
                )
                if not switched:
                    # 换凭证失败,本次未调用谷歌 API,不产生日志
                    log.error("[ANTIGRAVITY] 重试时无可用凭证或令牌")
                    return Response(
                        content=json.dumps({"error": "当前无可用凭证"}),
                        status_code=500,
                        media_type="application/json"
                    )
                continue  # 重试

        except Exception as e:
            log.error(f"[ANTIGRAVITY] 非流式请求异常: {e}, 凭证: {current_file}")
            if attempt < max_retries:
                log.info(f"[ANTIGRAVITY] 异常后重试 (attempt {attempt + 2}/{max_retries + 1})...")
                # 本次上游调用(异常)产生一条日志
                await _log_result(500, False, error_message=f"异常: {e}")
                await asyncio.sleep(retry_interval)
                continue
            else:
                # 所有重试都失败,返回最后一次的错误(如果有)或500错误
                log.error(f"[ANTIGRAVITY] 所有重试均失败,最后异常: {e}")
                await _log_result(500, False, error_message=f"异常: {e}")
                if last_error_response:
                    return last_error_response
                else:
                    return Response(
                        content=json.dumps({"error": f"非流式请求异常: {str(e)}"}),
                        status_code=500,
                        media_type="application/json"
                    )

    # 所有重试都失败(for循环正常结束)——每次上游调用均已各自记录日志,
    # 这里不额外记录,直接返回最后一次的原始错误
    log.error("[ANTIGRAVITY] 所有重试均失败")
    if last_error_response:
        return last_error_response
    else:
        return Response(
            content=json.dumps({"error": "所有重试均失败"}),
            status_code=500,
            media_type="application/json"
        )


# ==================== 模型和配额查询 ====================

# 模型列表白名单家族(名字包含即放行)
_MODEL_FAMILY_WHITELIST = ("claude", "gemini", "gpt", "argon")


def _is_listable_model(model_id: str) -> bool:
    """模型列表过滤:剔除 disabled 模型与白名单家族之外的杂牌模型"""
    lowered = (model_id or "").lower()
    if "disabled" in lowered:
        return False
    return any(family in lowered for family in _MODEL_FAMILY_WHITELIST)


def _extract_model_ids_from_raw(data: Dict[str, Any]) -> List[str]:
    """从上游 fetchAvailableModels 响应字典中提取并过滤模型 ID 列表(含衍生模型)"""
    model_ids: List[str] = []
    seen: Set[str] = set()
    raw_models = data.get("models") if isinstance(data, dict) else None
    if isinstance(raw_models, dict):
        for model_id in raw_models.keys():
            if not _is_listable_model(model_id):
                continue
            if model_id not in seen:
                seen.add(model_id)
                model_ids.append(model_id)

        # 添加额外的 claude-sonnet-4-6-thinking 模型
        if "claude-sonnet-4-6" in raw_models and "claude-sonnet-4-6-thinking" not in seen:
            seen.add("claude-sonnet-4-6-thinking")
            model_ids.append("claude-sonnet-4-6-thinking")

        # 添加额外的 claude-opus-4-6 模型
        if "claude-opus-4-6-thinking" in raw_models and "claude-opus-4-6" not in seen:
            seen.add("claude-opus-4-6")
            model_ids.append("claude-opus-4-6")

    return model_ids


async def fetch_credential_models(access_token: str) -> Optional[List[str]]:
    """
    获取单个凭证支持的模型 ID 列表(经过白名单过滤并补全衍生模型)。

    Returns:
        成功返回 List[str],请求失败返回 None
    """
    if not access_token:
        return None

    headers = build_antigravity_headers(access_token, model_name="agent")
    try:
        response = await post_async(
            url=f"{await get_antigravity_api_url()}/v1internal:fetchAvailableModels",
            json={},
            headers=headers,
            timeout=20.0,
        )
        if response.status_code == 200:
            data = response.json()
            return _extract_model_ids_from_raw(data)
        log.warning(
            f"[ANTIGRAVITY] fetch_credential_models failed ({response.status_code}): "
            f"{response.text[:300]}"
        )
        return None
    except Exception as e:
        log.warning(f"[ANTIGRAVITY] fetch_credential_models exception: {e}")
        return None


async def refresh_credential_models(
    email: str,
    credential_data: Optional[Dict[str, Any]] = None,
) -> Optional[List[str]]:
    """
    刷新指定凭证支持的模型列表并持久化到数据库。

    Returns:
        成功返回更新后的模型 ID 列表,失败返回 None
    """
    if not email:
        return None
    database = await get_database()
    if credential_data is None:
        credential_data = await database.get_credential(email)
    if not credential_data:
        return None

    if await should_refresh_token(credential_data):
        refreshed = await refresh_token(credential_data, email)
        if not refreshed:
            return None
        credential_data = refreshed

    access_token = credential_data.get("access_token") or credential_data.get("token")
    if not access_token:
        return None

    models = await fetch_credential_models(access_token)
    if models is not None:
        await update_credential_state(email, {"supported_models": models})
        log.info(f"[ANTIGRAVITY] 已更新凭证 {email} 支持的模型列表 ({len(models)} 个)")
    return models


async def _handle_model_not_found_for_credential(email: str, model_name: str) -> None:
    """
    当某凭证请求特定模型返回 404 时:
    1. 立即从该凭证的 supported_models 中剔除该模型(如果已有记录)
    2. 异步触发重新拉取该凭证的真实可用模型列表并落库
    """
    if not email:
        return
    try:
        database = await get_database()
        await database.remove_model_from_credential(email, model_name)
    except Exception as e:
        log.debug(f"[ANTIGRAVITY] 移除凭证模型失败 {email}: {e}")

    asyncio.create_task(refresh_credential_models(email))


async def fetch_available_models() -> List[Dict[str, Any]]:
    """
    获取所有可用凭证支持的模型并集,返回符合 OpenAI API 规范的格式。
    - 优先汇总数据库中所有启用凭证的 supported_models 并集;
    - 若存在尚未探测过模型列表的启用凭证,并发探测并写入数据库后再汇总;
    - 若数据库并集仍为空,回退到使用单个可用凭证实时请求。
    """
    database = await get_database()
    union_models, unprobed_emails = await database.get_enabled_credentials_models_info()

    # 对尚未探测过模型列表的启用凭证进行并发探测(限制并发避免瞬时突发过多请求)
    if unprobed_emails:
        sem = asyncio.Semaphore(5)

        async def _probe_one(target_email: str) -> Optional[List[str]]:
            async with sem:
                return await refresh_credential_models(target_email)

        probe_Targets = unprobed_emails[:20]  # 单次最多探测 20 个未初始化凭证,防止阻塞过久
        await asyncio.gather(*(_probe_one(e) for e in probe_Targets), return_exceptions=True)
        union_models, _ = await database.get_enabled_credentials_models_info()

    # 若仍为空(如所有凭证首次请求均失败),兜底用单个有效凭证请求一次
    if not union_models:
        cred_result = await get_valid_credential()
        if not cred_result:
            log.error("[ANTIGRAVITY] No valid credentials available for fetching models")
            return []

        current_file, credential_data = cred_result
        models = await refresh_credential_models(current_file, credential_data)
        if models:
            union_models = models
        else:
            return []

    current_timestamp = int(datetime.now(timezone.utc).timestamp())
    model_list = [
        model_to_dict(
            Model(
                id=model_id,
                object="model",
                created=current_timestamp,
                owned_by="google",
            )
        )
        for model_id in union_models
    ]

    log.info(f"[ANTIGRAVITY] Fetched {len(model_list)} available models (union across credentials)")
    return model_list


async def fetch_quota_info(access_token: str, project_id: str = "") -> Dict[str, Any]:
    """
    获取指定凭证的额度信息(使用 retrieveUserQuotaSummary 获取 weekly+5h 分组配额)

    Args:
        access_token: Antigravity 访问令牌
        project_id: 凭证对应的项目 ID

    Returns:
        包含额度信息的字典,格式为:
        {
            "success": True/False,
            "models": {
                "bucket_id": {
                    "remaining": 0.95,
                    "resetTime": "12-20 10:30",
                    "resetTimeRaw": "2025-12-20T02:30:00Z",
                    "resetDays": 5,
                    "window": "weekly",
                    "group": "gemini 3 pro"
                }
            },
            "minResetDays": 5,
            "accountTier": "pro"/"normal",
            "isPro": True/False,
            "quotaGroups": [...],
            "source": "retrieveUserQuotaSummary",
            "error": "错误信息" (仅在失败时)
        }
    """

    headers = build_antigravity_headers(access_token, model_name="agent")

    url = f"{await get_antigravity_api_url()}/v1internal:retrieveUserQuotaSummary"
    payload: Dict[str, Any] = {}
    if project_id:
        payload["project"] = project_id

    log.info(f"[ANTIGRAVITY QUOTA] fetch_quota_info: project={project_id}, url={url}")

    try:
        response = await post_async(
            url=url,
            json=payload,
            headers=headers,
            timeout=30.0
        )

        if response.status_code != 200:
            error_text = response.text[:500]
            log.error(f"[ANTIGRAVITY QUOTA] fetch_quota_info 失败: {response.status_code} - {error_text}")
            return {"success": False, "error": f"API返回错误: {response.status_code} - {error_text}"}

        data = response.json()
        log.debug(f"[ANTIGRAVITY QUOTA] Raw response: {json.dumps(data, ensure_ascii=False)[:500]}")

        # 解析分组配额(weekly + 5h 双窗口)
        quota_groups: List[Dict[str, Any]] = []
        for g in data.get("groups", []):
            buckets = []
            for b in g.get("buckets", []):
                buckets.append({
                    "bucketId": b.get("bucketId", ""),
                    "displayName": b.get("displayName", ""),
                    "window": b.get("window", ""),
                    "resetTime": b.get("resetTime", ""),
                    "remainingFraction": b.get("remainingFraction", 0),
                    "description": b.get("description"),
                })
            quota_groups.append({
                "displayName": g.get("displayName", ""),
                "description": g.get("description"),
                "buckets": buckets,
            })

        # 从分组配额中推断账号类型和重置天数
        min_reset_days = None
        for group in quota_groups:
            for bucket in group.get("buckets", []):
                reset_time = bucket.get("resetTime", "")
                if reset_time:
                    try:
                        reset_dt = datetime.fromisoformat(reset_time.replace('Z', '+00:00'))
                        now = datetime.now(timezone.utc)
                        delta = reset_dt - now
                        reset_days = max(0, delta.days)
                        if min_reset_days is None or reset_days < min_reset_days:
                            min_reset_days = reset_days
                    except Exception:
                        pass

        # 判断账号类型: 根据 weekly 窗口重置周期推断
        is_pro = min_reset_days is not None and min_reset_days <= 1
        account_tier = "pro" if is_pro else "normal"

        # 构建配额映射(从分组数据展开,兼容旧格式)
        quota_info: Dict[str, Dict[str, Any]] = {}
        for group in quota_groups:
            group_name = group.get("displayName", "").lower()
            for bucket in group.get("buckets", []):
                bucket_id = bucket.get("bucketId", "")
                remaining = bucket.get("remainingFraction", 0)
                reset_time = bucket.get("resetTime", "")
                window = bucket.get("window", "")

                # 转换为北京时间
                reset_time_beijing = 'N/A'
                reset_days = None
                if reset_time:
                    try:
                        utc_date = datetime.fromisoformat(reset_time.replace('Z', '+00:00'))
                        # 转换为北京时间 (UTC+8)
                        beijing_date = utc_date + timedelta(hours=8)
                        reset_time_beijing = beijing_date.strftime('%m-%d %H:%M')
                        now = datetime.now(timezone.utc)
                        delta = utc_date - now
                        reset_days = max(0, delta.days)
                    except Exception as e:
                        log.warning(f"[ANTIGRAVITY QUOTA] Failed to parse reset time: {e}")

                quota_info[bucket_id] = {
                    "remaining": remaining,
                    "resetTime": reset_time_beijing,
                    "resetTimeRaw": reset_time,
                    "resetDays": reset_days,
                    "window": window,
                    "group": group_name,
                }

        log.info(
            f"[ANTIGRAVITY QUOTA] 解析到 {len(quota_groups)} 个分组, "
            f"{len(quota_info)} 个配额桶, tier={account_tier}"
        )
        return {
            "success": True,
            "models": quota_info,
            "minResetDays": min_reset_days,
            "accountTier": account_tier,
            "isPro": is_pro,
            "quotaGroups": quota_groups,
            "source": "retrieveUserQuotaSummary",
        }
    except Exception as e:
        log.error(f"[ANTIGRAVITY QUOTA] Failed to fetch quota: {e}")
        log.error(f"[ANTIGRAVITY QUOTA] Traceback: {traceback.format_exc()}")
        return {
            "success": False,
            "error": str(e)
        }