File size: 66,039 Bytes
d34d19b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a36e6d
d34d19b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba3ac20
a97b0a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2d5673
1fbf545
124ffa0
d34d19b
a41d559
d34d19b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
#!/usr/bin/env python3
"""
gemini-web2api Enhanced โ€” Agent Edition
========================================
ุงู„ู†ุณุฎุฉ ุงู„ู…ุญุณู‘ู†ุฉ ู…ุน ุฏุนู… ูƒุงู…ู„ ู„ู€ Agent Loop (ReAct) ูˆTool Calling ู…ูˆุซูˆู‚.
ุงู„ุชุญุณูŠู†ุงุช ุงู„ุฌุฏูŠุฏุฉ:
- โœ… ุฅุตู„ุงุญ MODELS dict (ุฎุทุฃ syntax ูƒุงู† ู…ูˆุฌูˆุฏุงู‹)
- โœ… Agent Loop ุญู‚ูŠู‚ูŠ (ReAct: Reason โ†’ Act โ†’ Observe โ†’ Repeat)
- โœ… System Prompt ู‚ูˆูŠ ูˆู…ููุตูŽู‘ู„ ู„ู„ุฃุฏูˆุงุช
- โœ… JSON Tool Call parser ู…ุญุณู‘ู† ู…ุน fallback ู…ุชุนุฏุฏ ุงู„ู…ุณุชูˆูŠุงุช
- โœ… Streaming ู…ุน Tool Calls (chunk-by-chunk)
- โœ… ุญุฏ ุฃู‚ุตู‰ ู„ู„ุชูƒุฑุงุฑ (max_iterations) ู„ู…ู†ุน ุงู„ุญู„ู‚ุงุช ุงู„ู„ุงู†ู‡ุงุฆูŠุฉ
- โœ… Tool result injection ุตุญูŠุญ ููŠ ู…ุญุงุฏุซุงุช Gemini
- โœ… Parallel tool calls ุฏุนู…
- โœ… ุชุณุฌูŠู„ ุชูุตูŠู„ูŠ ู„ูƒู„ ุฎุทูˆุฉ Agent
"""

import asyncio
import json
import time
import hashlib
import re
import os
import ssl
import sys
import uuid
import argparse
import base64
import urllib.parse
import urllib.request
from typing import Optional, List, Dict, Any, Tuple
from contextlib import asynccontextmanager
from dataclasses import dataclass, field

from fastapi import FastAPI, HTTPException, Request, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, StreamingResponse
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel
import aiosqlite
import gradio as gr

try:
    import httpx
    HAS_HTTPX = True
except ImportError:
    HAS_HTTPX = False

__version__ = "2.1.0-agent"

# โ”€โ”€โ”€ Configuration โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def load_config() -> dict:
    defaults = {
        "port": 7860,
        "host": "0.0.0.0",
        "retry_attempts": 3,
        "retry_delay_sec": 2,
        "request_timeout_sec": 180,
        "gemini_bl": "boq_assistant-bard-web-server_20260525.09_p0",
        "default_model": "gemini-3.5-flash",
        "log_requests": True,
        "cookie_file": None,
        "proxy": None,
        "api_keys": ["sk-gemini"],
        "rate_limit_per_minute": 20,
        "cache_ttl_seconds": 3600,
        "db_path": "cache.db",
        "cleanup_interval_seconds": 300,
        # โœ… ุฌุฏูŠุฏ: ุฅุนุฏุงุฏุงุช Agent Loop
        "agent_max_iterations": 8,        # ุญุฏ ุฃู‚ุตู‰ ู„ุฏูˆุฑุงุช ุงู„ุฃุฏุงุฉ
        "agent_max_tokens_per_step": 32000, # ุญุฏ ุงู„ุชูˆูƒู†ุฒ ู„ูƒู„ ุฎุทูˆุฉ
    }

    for p in ["./config.json", os.path.expanduser("~/.config/gemini-web2api/config.json")]:
        if os.path.exists(p):
            try:
                with open(p) as f:
                    defaults.update(json.load(f))
                print(f"[Config] Loaded: {p}")
            except Exception as e:
                print(f"[Config] Error loading {p}: {e}")
            break

    if os.environ.get("API_KEYS"):
        defaults["api_keys"] = [k.strip() for k in os.environ["API_KEYS"].split(",") if k.strip()]
    if os.environ.get("GEMINI_COOKIE"):
        defaults["_cookie_inline"] = os.environ["GEMINI_COOKIE"]
    if os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY"):
        defaults["proxy"] = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")
    if os.environ.get("GEMINI_BL"):
        defaults["gemini_bl"] = os.environ["GEMINI_BL"]

    return defaults

CONFIG = load_config()

# โ”€โ”€โ”€ Models โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# โœ… ุฅุตู„ุงุญ: ูƒุงู†ุช ู‡ู†ุงูƒ ุฃุฎุทุงุก syntax (ู‚ูˆุณ ู…ูู‚ูˆุฏ + ุชูƒุฑุงุฑ ู…ูุงุชูŠุญ)

MODELS = {
    "gemini-3.7-flash": {
        "mode": 1, "think": 4,
        "desc": "Fast general-purpose model (~12k chars)",
    },  # โ† ุงู„ู‚ูˆุณ ูƒุงู† ู…ูู‚ูˆุฏุงู‹ ููŠ ุงู„ูƒูˆุฏ ุงู„ุฃุตู„ูŠ
    "gemini-3.6-flash": {
        "mode": 1, "think": 4,
        "desc": "All-around model (Gemini 3.6 Flash)",
    },
    "gemini-3.5-flash": {
        "mode": 1, "think": 4,
        "desc": "Standard flash model",
    },
    "gemini-3.5-flash-thinking": {
        "mode": 2, "think": 0,
        "desc": "Deep thinking mode, longest output (~20k chars)",
    },
    "gemini-3.1-pro": {
        "mode": 3, "think": 4,
        "desc": "Pro model (requires cookie for real routing)",
    },
    "gemini-auto": {
        "mode": 4, "think": 4,
        "desc": "Auto model selection",
    },
    "gemini-3.5-flash-thinking-lite": {
        "mode": 5, "think": 0,
        "desc": "Dynamic thinking with adaptive depth (~15k chars)",
    },
    # โœ… ุฅุตู„ุงุญ: ูƒุงู† "claude-opus-4-6" ู…ูƒุฑุฑุงู‹ ุจุฎุทุฃุŒ ูˆุงู„ุตุญูŠุญ ู‡ูˆ ู†ู…ูˆุฐุฌ Gemini ุฎููŠู
    "gemini-flash-lite": {
        "mode": 6, "think": 4,
        "desc": "Lightweight fast model (~10k chars)",
    },
    "claude-opus-4-6": {
        "mode": 2, "think": 0,
        "desc": "Deep thinking mode, longest output (~20k chars)",
    },
    "claude-opus-4-5": {
        "mode": 2, "think": 0,
        "desc": "Claude Opus 4.5 (mapped to Gemini thinking mode)",
    },
    "claude-opus-3-5": {
        "mode": 2, "think": 0,
        "desc": "Claude Opus 4.1 (mapped to Gemini thinking mode)",
    },
    "claude-opus-4-7": {
        "mode": 2, "think": 0,
        "desc": "Claude Opus 4.0 (mapped to Gemini thinking mode)",
    },
    "claude-opus-4-8": {
        "mode": 2, "think": 0,
        "desc": "Claude Opus 4 (dated alias)",
    },       
}

# โ”€โ”€โ”€ Pydantic Schemas โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

class ChatMessage(BaseModel):
    role: str
    content: Any
    tool_calls: Optional[List[dict]] = None
    tool_call_id: Optional[str] = None
    name: Optional[str] = None

class ChatCompletionRequest(BaseModel):
    model: str = "gemini-3.5-flash"
    messages: List[ChatMessage]
    temperature: Optional[float] = 0.7
    max_tokens: Optional[int] = 32000
    stream: Optional[bool] = False
    tools: Optional[List[dict]] = None
    tool_choice: Optional[Any] = "auto"
    user: Optional[str] = "default"

# โ”€โ”€โ”€ Production Services โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

@dataclass
class RateLimitEntry:
    timestamps: List[float] = field(default_factory=list)
    last_cleanup: float = field(default_factory=time.time)

class Services:
    def __init__(self):
        self._rate_limits: Dict[str, RateLimitEntry] = {}
        self._lock = asyncio.Lock()
        self._cleanup_task: Optional[asyncio.Task] = None

    async def init_db(self):
        async with aiosqlite.connect(CONFIG["db_path"]) as db:
            await db.execute("""
                CREATE TABLE IF NOT EXISTS cache (
                    key TEXT PRIMARY KEY,
                    val TEXT,
                    exp REAL
                )
            """)
            await db.execute("CREATE INDEX IF NOT EXISTS idx_exp ON cache(exp)")
            await db.commit()

    async def start_cleanup(self):
        async def loop():
            while True:
                await asyncio.sleep(CONFIG["cleanup_interval_seconds"])
                await self._cleanup()
        self._cleanup_task = asyncio.create_task(loop())

    async def _cleanup(self):
        now = time.time()
        cutoff = now - 3600
        async with self._lock:
            expired = [ip for ip, e in self._rate_limits.items() if e.last_cleanup < cutoff]
            for ip in expired:
                del self._rate_limits[ip]
        try:
            async with aiosqlite.connect(CONFIG["db_path"]) as db:
                await db.execute("DELETE FROM cache WHERE exp < ?", (now,))
                await db.commit()
        except Exception:
            pass

    async def check_rate_limit(self, client_id: str) -> Tuple[bool, int]:
        now = time.time()
        cutoff = now - 60
        async with self._lock:
            if client_id not in self._rate_limits:
                self._rate_limits[client_id] = RateLimitEntry()
            entry = self._rate_limits[client_id]
            entry.timestamps = [t for t in entry.timestamps if t > cutoff]
            entry.last_cleanup = now
            limit = CONFIG["rate_limit_per_minute"]
            if len(entry.timestamps) >= limit:
                wait = 60 - (now - min(entry.timestamps))
                return False, int(wait) + 1
            entry.timestamps.append(now)
            return True, 0

    async def get_cache(self, key: str) -> Optional[str]:
        try:
            async with aiosqlite.connect(CONFIG["db_path"]) as db:
                async with db.execute(
                    "SELECT val FROM cache WHERE key=? AND exp>?", (key, time.time())
                ) as cur:
                    row = await cur.fetchone()
                    return row[0] if row else None
        except Exception:
            return None

    async def set_cache(self, key: str, value: str):
        try:
            async with aiosqlite.connect(CONFIG["db_path"]) as db:
                await db.execute(
                    "INSERT OR REPLACE INTO cache VALUES (?, ?, ?)",
                    (key, value, time.time() + CONFIG["cache_ttl_seconds"])
                )
                await db.commit()
        except Exception:
            pass

services = Services()

# โ”€โ”€โ”€ Logging โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def log(msg: str, level: str = "INFO"):
    if CONFIG.get("log_requests"):
        prefix = {"INFO": "โ„น๏ธ", "AGENT": "๐Ÿค–", "TOOL": "๐Ÿ”ง", "ERROR": "โŒ", "WARN": "โš ๏ธ"}.get(level, "โ€ข")
        sys.stderr.write(f"[{time.strftime('%H:%M:%S')}] {prefix} {msg}\n")
        sys.stderr.flush()

# โ”€โ”€โ”€ Cookie & Headers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def load_cookie() -> Tuple[str, Optional[str]]:
    inline = CONFIG.get("_cookie_inline", "")
    if inline:
        if inline.startswith("{"):
            try:
                data = json.loads(inline)
                return data.get("cookie", ""), data.get("sapisid") or None
            except Exception:
                pass
        pairs = dict(p.split("=", 1) for p in inline.split("; ") if "=" in p)
        return inline, pairs.get("SAPISID") or None

    cookie_file = CONFIG.get("cookie_file")
    if not cookie_file or not os.path.exists(cookie_file):
        return "", None
    try:
        with open(cookie_file) as f:
            content = f.read().strip()
        if content.startswith("{"):
            data = json.loads(content)
            return data.get("cookie", ""), data.get("sapisid") or None
        pairs = dict(p.split("=", 1) for p in content.split("; ") if "=" in p)
        return content, pairs.get("SAPISID") or None
    except Exception as e:
        log(f"Cookie load error: {e}", "ERROR")
        return "", None

def make_sapisidhash(sapisid: str) -> str:
    ts = int(time.time())
    h = hashlib.sha1(f"{ts} {sapisid} https://gemini.google.com".encode()).hexdigest()
    return f"SAPISIDHASH {ts}_{h}"

def _build_headers() -> dict:
    headers = {
        "Content-Type": "application/x-www-form-urlencoded",
        "Origin": "https://gemini.google.com",
        "Referer": "https://gemini.google.com/app",
        "X-Same-Domain": "1",
        "User-Agent": (
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
            "AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/124.0.0.0 Safari/537.36"
        ),
    }
    cookie_str, sapisid = load_cookie()
    if cookie_str:
        headers["Cookie"] = cookie_str
    if sapisid:
        headers["Authorization"] = make_sapisidhash(sapisid)
    return headers

# โ”€โ”€โ”€ Gemini Protocol โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def _build_gemini_payload(prompt: str, model_id: int, think_mode: int) -> Tuple[bytes, str]:
    inner = [None] * 80
    inner[0] = [prompt, 0, None, None, None, None, 0]
    inner[1] = ["en"]
    inner[2] = ["", "", "", None, None, None, None, None, None, ""]
    inner[6] = [0]
    inner[7] = 1
    inner[10] = 1
    inner[11] = 0
    inner[17] = [[think_mode]]
    inner[18] = 0
    inner[27] = 1
    inner[30] = [4]
    inner[41] = [2]
    inner[53] = 0
    inner[59] = str(uuid.uuid4())
    inner[61] = []
    inner[68] = 1
    inner[79] = model_id

    outer = [None, json.dumps(inner)]
    body = urllib.parse.urlencode({"f.req": json.dumps(outer)}).encode()
    reqid = int(time.time()) % 1000000
    url = (
        "https://gemini.google.com/_/BardChatUi/data/"
        "assistant.lamda.BardFrontendService/StreamGenerate"
        f"?bl={CONFIG['gemini_bl']}&hl=en&_reqid={reqid}&rt=c"
    )
    return body, url

def gemini_stream_generate(prompt: str, model_id: int, think_mode: int) -> str:
    body, url = _build_gemini_payload(prompt, model_id, think_mode)
    headers = _build_headers()
    proxy = CONFIG.get("proxy")
    last_err = None

    for attempt in range(CONFIG["retry_attempts"]):
        try:
            req = urllib.request.Request(url, data=body, headers=headers, method="POST")
            ctx = ssl.create_default_context()
            if proxy:
                opener = urllib.request.build_opener(
                    urllib.request.ProxyHandler({"http": proxy, "https": proxy}),
                    urllib.request.HTTPSHandler(context=ctx)
                )
                resp = opener.open(req, timeout=CONFIG["request_timeout_sec"])
            else:
                resp = urllib.request.urlopen(req, context=ctx, timeout=CONFIG["request_timeout_sec"])
            return resp.read().decode("utf-8", errors="replace")
        except Exception as e:
            last_err = e
            if attempt < CONFIG["retry_attempts"] - 1:
                log(f"Retry {attempt+1}/{CONFIG['retry_attempts']}: {e}", "WARN")
                time.sleep(CONFIG["retry_delay_sec"])

    raise last_err

def clean_gemini_text(text: str) -> str:
    text = re.sub(
        r'```(?:python|javascript|text)\?code_(?:reference|stdout)&code_event_index=\d+\n.*?```\n?',
        '', text, flags=re.DOTALL
    )
    return text.strip()

def extract_response_text(raw: str) -> str:
    texts = []
    for line in raw.split("\n"):
        if '"wrb.fr"' not in line or len(line) < 200:
            continue
        try:
            arr = json.loads(line)
            inner_str = arr[0][2]
            if not inner_str or len(inner_str) < 50:
                continue
            inner = json.loads(inner_str)
            if isinstance(inner, list) and len(inner) > 4 and inner[4]:
                for part in inner[4]:
                    if isinstance(part, list) and len(part) > 1 and part[1]:
                        if isinstance(part[1], list):
                            for t in part[1]:
                                if isinstance(t, str) and len(t) > 0:
                                    texts.append(t)
        except (json.JSONDecodeError, IndexError, TypeError):
            pass

    text = ""
    for t in reversed(texts):
        if t.strip():
            text = t
            break
    return clean_gemini_text(text)

def gemini_stream_iter(prompt: str, model_id: int, think_mode: int):
    """Streaming ุญู‚ูŠู‚ูŠ ูŠูุนูŠุฏ ุงู„ู†ุต ุชุฏุฑูŠุฌูŠุงู‹."""
    body_bytes, url = _build_gemini_payload(prompt, model_id, think_mode)
    body_str = body_bytes.decode()
    headers = _build_headers()
    proxy = CONFIG.get("proxy")

    if not HAS_HTTPX:
        raw = gemini_stream_generate(prompt, model_id, think_mode)
        text = extract_response_text(raw)
        if text:
            yield text
        return

    prev_text = ""
    transport = httpx.HTTPTransport(proxy=proxy) if proxy else None

    with httpx.Client(transport=transport, timeout=CONFIG["request_timeout_sec"], verify=True) as client:
        with client.stream("POST", url, content=body_str, headers=headers) as resp:
            buf = ""
            for chunk in resp.iter_text():
                buf += chunk
                while "\n" in buf:
                    line, buf = buf.split("\n", 1)
                    if '"wrb.fr"' not in line or len(line) < 200:
                        continue
                    try:
                        arr = json.loads(line)
                        inner_str = arr[0][2]
                        if not inner_str or len(inner_str) < 50:
                            continue
                        inner2 = json.loads(inner_str)
                        if isinstance(inner2, list) and len(inner2) > 4 and inner2[4]:
                            for part in inner2[4]:
                                if isinstance(part, list) and len(part) > 1 and part[1] and isinstance(part[1], list):
                                    for t in part[1]:
                                        if isinstance(t, str) and len(t) > len(prev_text):
                                            delta = t[len(prev_text):]
                                            delta = clean_gemini_text(delta)
                                            if delta:
                                                yield delta
                                            prev_text = t
                    except (json.JSONDecodeError, IndexError, TypeError):
                        pass

# โ”€โ”€โ”€ โœ… Tool Call Parser ุงู„ู…ุญุณู‘ู† โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def parse_tool_calls(text: str) -> Tuple[str, Optional[List[dict]]]:
    """
    ู…ุญู„ู‘ู„ Tool Calls ู…ุชุนุฏุฏ ุงู„ู…ุณุชูˆูŠุงุช:
    1. ```tool_call {...}```
    2. ```json {"name": ..., "arguments": ...}```
    3. <tool_call>...</tool_call>
    4. JSON ู…ุจุงุดุฑ ููŠ ุงู„ู†ุต
    """
    tool_calls = []

    # โ”€โ”€โ”€ ู…ุณุชูˆู‰ 1: ```tool_call``` blocks
    pattern1 = r'```tool_call\s*\n(.*?)\n?```'
    for match in re.finditer(pattern1, text, re.DOTALL):
        raw = match.group(1).strip()
        tc = _try_parse_single_tool_call(raw)
        if tc:
            tool_calls.append(tc)

    # โ”€โ”€โ”€ ู…ุณุชูˆู‰ 2: ```json``` blocks ุงู„ุชูŠ ุชุญุชูˆูŠ ุนู„ู‰ tool call
    if not tool_calls:
        pattern2 = r'```json\s*\n(.*?)\n?```'
        for match in re.finditer(pattern2, text, re.DOTALL):
            raw = match.group(1).strip()
            tc = _try_parse_single_tool_call(raw)
            if tc:
                tool_calls.append(tc)

    # โ”€โ”€โ”€ ู…ุณุชูˆู‰ 3: XML-style <tool_call>
    if not tool_calls:
        pattern3 = r'<tool_call>(.*?)</tool_call>'
        for match in re.finditer(pattern3, text, re.DOTALL):
            raw = match.group(1).strip()
            tc = _try_parse_single_tool_call(raw)
            if tc:
                tool_calls.append(tc)

    # โ”€โ”€โ”€ ู…ุณุชูˆู‰ 4: JSON ู…ุจุงุดุฑ (ู„ู„ู†ู…ุงุฐุฌ ุงู„ุชูŠ ุชูุฎุฑุฌ JSON ู…ุจุงุดุฑุฉ)
    if not tool_calls:
        # ุงุจุญุซ ุนู† JSON objects ุชุญุชูˆูŠ ุนู„ู‰ "name" ูˆ "arguments"
        json_pattern = r'\{[^{}]*"name"\s*:\s*"[^"]+[^{}]*"arguments"\s*:[^{}]*\}'
        for match in re.finditer(json_pattern, text, re.DOTALL):
            tc = _try_parse_single_tool_call(match.group(0))
            if tc:
                tool_calls.append(tc)

    if not tool_calls:
        return text, None

    # ุชู†ุธูŠู ุงู„ู†ุต ู…ู† ุฃุฌุฒุงุก tool calls
    clean = re.sub(pattern1, '', text, flags=re.DOTALL)
    clean = re.sub(r'```json\s*\n.*?\n?```', '', clean, flags=re.DOTALL)
    clean = re.sub(r'<tool_call>.*?</tool_call>', '', clean, flags=re.DOTALL)
    # ุฅุฒุงู„ุฉ ุฃูŠ JSON ู…ุจุงุดุฑ ูƒุงู† tool call
    for tc_obj in tool_calls:
        fn_name = tc_obj["function"]["name"]
        clean = re.sub(
            r'\{[^{}]*"name"\s*:\s*"' + re.escape(fn_name) + r'"[^{}]*\}',
            '', clean
        )

    return clean.strip(), tool_calls

def _try_parse_single_tool_call(raw: str) -> Optional[dict]:
    """ู…ุญุงูˆู„ุฉ ุชุญู„ูŠู„ tool call ูˆุงุญุฏ ู…ู† ู†ุต."""
    try:
        data = json.loads(raw)
    except json.JSONDecodeError:
        # ู…ุญุงูˆู„ุฉ ุฅุตู„ุงุญ JSON ุงู„ู…ูƒุณูˆุฑ
        raw_fixed = _fix_json(raw)
        try:
            data = json.loads(raw_fixed)
        except json.JSONDecodeError:
            return None

    if not isinstance(data, dict):
        return None

    name = data.get("name") or data.get("function") or data.get("tool")
    if not name:
        return None

    args = data.get("arguments") or data.get("parameters") or data.get("args") or {}
    if isinstance(args, str):
        try:
            args = json.loads(args)
        except Exception:
            args = {"value": args}

    return {
        "id": f"call_{uuid.uuid4().hex[:8]}",
        "type": "function",
        "function": {
            "name": name,
            "arguments": json.dumps(args, ensure_ascii=False),
        },
    }

def _fix_json(s: str) -> str:
    """ุฅุตู„ุงุญ JSON ุงู„ู…ูƒุณูˆุฑ ุฌุฒุฆูŠุงู‹."""
    # ุฅุฒุงู„ุฉ trailing commas
    s = re.sub(r',\s*([}\]])', r'\1', s)
    # ุฅุถุงูุฉ quotes ู„ู„ู…ูุงุชูŠุญ ุบูŠุฑ ุงู„ู…ูู‚ุชุจูŽุณุฉ
    s = re.sub(r'(\w+)\s*:', r'"\1":', s)
    # ุฅุฒุงู„ุฉ double quotes
    s = re.sub(r'""(\w+)""', r'"\1"', s)
    return s

# โ”€โ”€โ”€ โœ… Tool/Agent System Prompt ุงู„ู…ุญุณู‘ู† โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

 
AGENT_SYSTEM_PROMPT = """Autonomous Coding Agent - Operational Directive (DeepSeek Harness Edition)

You are an autonomous AI coding agent powered by DeepSeek and running inside the DeepSeek Harness. You operate independently, execute tasks directly, manage your own workspace, and handle codebases without relying on any external agents or orchestration frameworks. You are a tool-using agent: you drive yourself forward through an explicit tool-calling loop, invoking one tool at a time, observing each result, and deciding the next action until the task is complete.

1. Core Operating Principles

ยท Autonomy & Self-Sufficiency: Execute tasks end-to-end. Break down complex requests into logical steps, verify assumptions, test changes, and report results cleanly.
ยท Tool-Driven Execution: You act on the world only through tool calls. Never claim to have read, written, searched, or executed something unless a corresponding tool call returned that result.
ยท Error Handling & Non-Zero Exits: Non-zero exits from commands or tools are reported as [exit code: N]. Always investigate and fix failures before moving to the next step. On Windows, a killed process settles as [exit code: 1] without a signal marker; treat a bare exit 1 after an interruption as a termination, not a command failure.
ยท Environment Awareness: Maintain a clear mental model of the project file structure, dependencies, and execution environment.

2. Tool-Calling Loop (Mandatory Control Flow)

You operate in a strict agentic loop. Each iteration of the loop consists of exactly these phases:

1. Think / Plan โ€” Reason about the current state, the goal, and what single next action is required. Keep this internal; emit only the tool call that follows.
2. Act (single tool call) โ€” Invoke exactly one tool per turn. Do not batch multiple independent tools into one message unless the harness explicitly supports parallel calls. Prefer one well-chosen call over several speculative ones.
3. Observe โ€” Read the tool's output (stdout, file contents, diff, search hits, exit code). Treat it as ground truth.
4. Decide โ€” Based on the observation, either:
   ยท call another tool to continue (loop back to step 1), or
   ยท finish the task and produce a final summary (exit the loop).

Loop Rules

ยท One tool, one turn. After every tool call, stop and wait for the result before issuing the next call. The harness will feed the observation back to you; do not hallucinate an output.
ยท Sequential tool chaining. Use the result of tool N to decide tool N+1. Example chain: glob โ†’ read โ†’ edit โ†’ run tests โ†’ read failure โ†’ edit โ†’ run tests โ†’ done.
ยท No pre-emptive completion. Do not declare success until a verification tool (test runner, build, linter, or explicit read-back) confirms the change.
ยท Terminate cleanly. End the loop only when (a) the task's acceptance criteria are met and (b) verification has passed, or (c) you are genuinely blocked and must report a blocker with evidence.
ยท Re-plan on failure. A failing observation is a signal to change strategy โ€” read more context, narrow the search, or revert. Do not repeat the same failing tool call verbatim.
ยท Budget awareness. If the loop is not converging after several iterations on the same sub-problem, stop, summarize what you learned, and ask for clarification or report the blocker.

3. Native Tool Usage Guidelines

Utilize the exact file-system, search, and execution tools natively exposed by the DeepSeek Harness. Call them by name, one per turn:

ยท File Reading: Use the dedicated file-reading tool to inspect text files. Review line numbers, and use offsets/limits for large files instead of generic command-line tools like cat.
ยท File Writing & Creation: Use the write tool to create new files or completely overwrite existing ones. Always read an existing file before overwriting it.
ยท Targeted Edits: Use the precise string-replacement tool for targeted changes to UTF-8 text files (old_string โ†’ new_string). Ensure old_string is unique or explicitly enable multi-replacement flags where required.
ยท File Discovery: Use the glob/path-pattern tool to discover files rather than shell commands (find). Patterns without / match basenames at any depth.
ยท Content Searching: Use the dedicated grep/search tool to query file contents across the workspace rather than raw shell commands.
ยท Command Execution: Use the shell/exec tool to run builds, tests, package managers, and scripts. Capture stdout, stderr, and exit code from every invocation.
ยท Background Jobs: Use the background-task tool for long-running processes; track their handles and process completion notifications inside the loop.

Rule: If a dedicated tool exists for an operation, use it โ€” never fall back to a shell command for something the harness exposes natively (e.g., use read not cat, grep not grep-via-shell, glob not find).

4. Background Task & Job Management

ยท Track every background job or long-running process you initiate via the background-task tool.
ยท When the harness notifies you of a finished background task (as an observation in the loop), process its outcome immediately before issuing unrelated tool calls.
ยท Never busy-poll or sleep on active jobs; continue the loop with independent steps in parallel. Collect still-relevant job outputs only when genuinely blocked, and terminate/kill jobs that are no longer needed.

5. Execution Workflow for Coding Tasks

When given a development task, drive the tool-calling loop through this strict sequence:

1. Discovery & Exploration โ€” Loop: glob + grep to locate relevant files and architectural patterns.
2. Analysis โ€” Loop: read the target files to understand structure, imports, types, and logic.
3. Implementation โ€” Loop: write new files or edit existing ones with precise, minimal changes.
4. Verification โ€” Loop: exec test runners, build scripts, or syntax checks. Read any failures, fix, and re-run until green.
5. Summary โ€” Exit the loop and provide a concise, clear breakdown of changes and instructions for testing or running the output.

Each numbered step is itself composed of one or more tool-call iterations of the loop in ยง2. Never skip verification.

6. Final Output Contract

When the loop terminates successfully, produce a summary containing:

ยท What changed โ€” files created/modified, with a one-line rationale each.
ยท How it was verified โ€” the exact commands/tools run and their outcomes (including exit codes).
ยท How to run/test it โ€” concrete instructions for the user.
ยท Open questions / follow-ups โ€” anything you could not resolve, stated explicitly.

If you exit the loop blocked, state: (a) the goal, (b) the last successful observation, (c) the failing tool call and its output, and (d) what input or decision you need to proceed.

---

Key changes made

ยท Added ยง2 "Tool-Calling Loop": codifies the mandatory think โ†’ single tool call โ†’ observe โ†’ decide cycle, with explicit rules (one tool per turn, sequential chaining, no pre-emptive completion, re-plan on failure).
ยท Renamed ยง2 โ†’ ยง3 and hardened tool rules: tools are now called by name, one per turn, with a hard rule to prefer native tools over shell equivalents.
ยท Updated ยง4 (jobs): completion notifications are now framed as loop observations to be processed immediately.
ยท Updated ยง5 (workflow): each phase explicitly is a set of loop iterations; verification cannot be skipped.
ยท Added ยง6 "Final Output Contract": defines what a successful and a blocked loop termination must report.
ยท Emphasized DeepSeek Harness: intro now states the agent runs inside the DeepSeek Harness and drives itself via the loop.
 delegations together in one assistant message and continue useful work while they run. Set run_in_background: false only when your next action depends on that subagent's result. When a background run settles, the runtime sends you a notice containing its outcome and any final assistant message.
```

"""

def build_tool_definitions_text(tools: List[dict]) -> str:
    """ุจู†ุงุก ูˆุตู ู†ุตูŠ ู„ู„ุฃุฏูˆุงุช ุงู„ู…ุชุงุญุฉ."""
    if not tools:
        return "No tools available."
    lines = []
    for i, tool in enumerate(tools, 1):
        if tool.get("type") == "function":
            fn = tool.get("function", tool)
        else:
            fn = tool
        name = fn.get("name", f"tool_{i}")
        desc = fn.get("description", "No description")
        params = fn.get("parameters", {})

        lines.append(f"### {i}. `{name}`")
        lines.append(f"**Description:** {desc}")

        if params and params.get("properties"):
            lines.append("**Parameters:**")
            for pname, pinfo in params.get("properties", {}).items():
                required = pname in params.get("required", [])
                ptype = pinfo.get("type", "any")
                pdesc = pinfo.get("description", "")
                req_str = " *(required)*" if required else " *(optional)*"
                lines.append(f"  - `{pname}` ({ptype}){req_str}: {pdesc}")
        lines.append("")
    return "\n".join(lines)

# โ”€โ”€โ”€ Prompt Builder โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def messages_to_prompt(messages: list, tools: list = None) -> str:
    """
    โœ… ู…ุญุณู‘ู†: ูŠุจู†ูŠ prompt ูˆุงุถุญุงู‹ ู…ุน system prompt ู‚ูˆูŠ ู„ู„ุฃุฏูˆุงุช.
    """
    parts = []

    # โ”€โ”€โ”€ System prompt ู„ู„ุฃุฏูˆุงุช
    if tools:
        tool_defs_text = build_tool_definitions_text(tools)
        system_tool_prompt = AGENT_SYSTEM_PROMPT.replace("{tool_definitions}", tool_defs_text)
        parts.append(f"[SYSTEM]\n{system_tool_prompt}")

    # โ”€โ”€โ”€ ู…ุนุงู„ุฌุฉ ุงู„ุฑุณุงุฆู„
    for msg in messages:
        role = msg.get("role", "user") if isinstance(msg, dict) else msg.role
        content = msg.get("content", "") if isinstance(msg, dict) else (msg.content or "")
        tool_calls_data = (msg.get("tool_calls") if isinstance(msg, dict)
                          else getattr(msg, "tool_calls", None))

        # ุชุญูˆูŠู„ content ู…ุชุนุฏุฏ ุงู„ุฃุฌุฒุงุก
        if isinstance(content, list):
            content = " ".join(
                c.get("text", "") for c in content
                if isinstance(c, dict) and c.get("type") in ("text", "input_text")
            )

        if role == "system":
            if not tools:  # ุฅุฐุง ูƒุงู† ู‡ู†ุงูƒ ุฃุฏูˆุงุชุŒ system prompt ุงู„ุฃุฏูˆุงุช ูŠุฃุชูŠ ุฃูˆู„ุงู‹
                parts.append(f"[SYSTEM]\n{content}")
            else:
                # ุฏู…ุฌ system prompt ุงู„ู…ุณุชุฎุฏู… ู…ุน system prompt ุงู„ุฃุฏูˆุงุช
                parts[0] = parts[0] + f"\n\n## ADDITIONAL INSTRUCTIONS\n{content}"

        elif role == "assistant":
            if tool_calls_data:
                # ุชุถู…ูŠู† tool calls ุงู„ุณุงุจู‚ุฉ ููŠ ุงู„ุณูŠุงู‚
                tc_parts = [f"[ASSISTANT called tool(s)]:"]
                for tc in tool_calls_data:
                    fn = tc.get("function", {})
                    tc_parts.append(
                        f"```tool_call\n"
                        f"{json.dumps({'name': fn.get('name'), 'arguments': json.loads(fn.get('arguments', '{}'))}, ensure_ascii=False)}\n"
                        f"```"
                    )
                if content:
                    tc_parts.insert(1, f"[ASSISTANT]: {content}")
                parts.append("\n".join(tc_parts))
            else:
                parts.append(f"[ASSISTANT]: {content}")

        elif role == "tool":
            # โœ… ู†ุชุงุฆุฌ ุงู„ุฃุฏูˆุงุช ุจุดูƒู„ ูˆุงุถุญ
            tool_name = (msg.get("name", "") if isinstance(msg, dict)
                        else getattr(msg, "name", ""))
            tool_call_id = (msg.get("tool_call_id", "") if isinstance(msg, dict)
                           else getattr(msg, "tool_call_id", ""))
            parts.append(
                f"[TOOL RESULT - {tool_name or tool_call_id}]:\n```json\n{content}\n```\n"
                f"Now use this result to continue."
            )

        else:  # user
            if content:
                parts.append(f"[USER]: {content}")

    return "\n\n".join(p for p in parts if p)

# โ”€โ”€โ”€ โœ… Agent Loop ุงู„ุฑุฆูŠุณูŠ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def run_agent_sync(
    messages: List[dict],
    model_id: int,
    think_mode: int,
    tools: Optional[List[dict]],
    max_iterations: int = None,
) -> Tuple[str, Optional[List[dict]], List[dict]]:
    """
    Agent Loop ุญู‚ูŠู‚ูŠ (ReAct pattern):
    1. ุงุจู†ู prompt ู…ู† ุงู„ุณูŠุงู‚ ุงู„ูƒุงู…ู„
    2. ุงุณุฃู„ Gemini
    3. ุฅุฐุง ุฃุนุงุฏ tool call โ†’ ุฃุถู ุฅู„ู‰ ุงู„ุณูŠุงู‚ ูˆุงุนุฏ
    4. ุฅุฐุง ู„ู… ูŠูุนุฏ tool call โ†’ ุฃุนุฏ ุงู„ุฑุฏ ุงู„ู†ู‡ุงุฆูŠ
    ูŠุนูŠุฏ: (final_text, final_tool_calls, updated_messages)
    """
    if max_iterations is None:
        max_iterations = CONFIG["agent_max_iterations"]

    current_messages = list(messages)
    iteration = 0
    last_tool_calls = None

    while iteration < max_iterations:
        iteration += 1
        log(f"Agent iteration {iteration}/{max_iterations}", "AGENT")

        prompt = messages_to_prompt(current_messages, tools if iteration == 1 else tools)
        raw = gemini_stream_generate(prompt, model_id, think_mode)
        text = extract_response_text(raw)

        if not text:
            log("Empty response from Gemini", "WARN")
            break

        # โ”€โ”€โ”€ ู…ุญุงูˆู„ุฉ ุชุญู„ูŠู„ tool calls
        clean_text, tool_calls = parse_tool_calls(text)

        if tool_calls and tools:
            log(f"Tool calls detected: {[tc['function']['name'] for tc in tool_calls]}", "TOOL")

            # ุฃุถู ุฑุฏ ุงู„ู…ุณุงุนุฏ ู…ุน tool calls ุฅู„ู‰ ุงู„ุณูŠุงู‚
            current_messages.append({
                "role": "assistant",
                "content": clean_text or None,
                "tool_calls": tool_calls,
            })
            last_tool_calls = tool_calls

            # โœ… ู‡ู†ุง ูŠุฌุจ ุนู„ู‰ ุงู„ู…ุณุชุฏุนูŠ ุชู†ููŠุฐ ุงู„ุฃุฏูˆุงุช ูˆุฅุถุงูุฉ ุงู„ู†ุชุงุฆุฌ
            # ููŠ ูˆุถุน non-streamingุŒ ู†ูุนูŠุฏ tool calls ู„ู„ู…ุณุชุฏุนูŠ
            # ููŠ ูˆุถุน agent ุฏุงุฎู„ูŠุŒ ู†ุถูŠู placeholder
            return clean_text, tool_calls, current_messages

        else:
            # โ”€โ”€โ”€ ุฑุฏ ู†ู‡ุงุฆูŠ ุจุฏูˆู† tool calls
            log(f"Final response after {iteration} iterations", "AGENT")
            return clean_text or text, None, current_messages

    log(f"Max iterations ({max_iterations}) reached", "WARN")
    return text or "", None, current_messages


def run_agent_with_tool_execution_sync(
    messages: List[dict],
    model_id: int,
    think_mode: int,
    tools: Optional[List[dict]],
    tool_executor=None,  # ุฏุงู„ุฉ ู„ุชู†ููŠุฐ ุงู„ุฃุฏูˆุงุช (ุงุฎุชูŠุงุฑูŠุฉ)
    max_iterations: int = None,
) -> Tuple[str, Optional[List[dict]], List[dict]]:
    """
    โœ… Agent Loop ุงู„ูƒุงู…ู„ ู…ุน ุชู†ููŠุฐ ุงู„ุฃุฏูˆุงุช ุชู„ู‚ุงุฆูŠุงู‹ (ุฅุฐุง ุชูˆูู‘ุฑ executor).
    
    tool_executor: Callable[[str, dict], str] - ูŠุฃุฎุฐ (tool_name, args) ูˆูŠูุนูŠุฏ ู†ุชูŠุฌุฉ ู†ุตูŠุฉ
    """
    if max_iterations is None:
        max_iterations = CONFIG["agent_max_iterations"]

    current_messages = list(messages)

    for iteration in range(1, max_iterations + 1):
        log(f"Agent loop iteration {iteration}/{max_iterations}", "AGENT")

        prompt = messages_to_prompt(current_messages, tools)
        try:
            raw = gemini_stream_generate(prompt, model_id, think_mode)
            text = extract_response_text(raw)
        except Exception as e:
            log(f"Gemini call failed: {e}", "ERROR")
            return f"Error: {e}", None, current_messages

        if not text:
            log("Empty response", "WARN")
            break

        clean_text, tool_calls = parse_tool_calls(text)

        if not tool_calls or not tools:
            # ุฑุฏ ู†ู‡ุงุฆูŠ
            log(f"โœ… Final answer after {iteration} iterations", "AGENT")
            return clean_text or text, None, current_messages

        # โ”€โ”€โ”€ ุฃุถู ุฑุฏ ุงู„ู…ุณุงุนุฏ
        current_messages.append({
            "role": "assistant",
            "content": clean_text or None,
            "tool_calls": tool_calls,
        })

        # โ”€โ”€โ”€ ุชู†ููŠุฐ ูƒู„ tool call
        for tc in tool_calls:
            fn_name = tc["function"]["name"]
            try:
                fn_args = json.loads(tc["function"]["arguments"])
            except Exception:
                fn_args = {}

            log(f"Executing tool: {fn_name}({fn_args})", "TOOL")

            if tool_executor:
                try:
                    result = tool_executor(fn_name, fn_args)
                    result_str = result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)
                except Exception as e:
                    result_str = json.dumps({"error": str(e)})
                    log(f"Tool execution error: {e}", "ERROR")
            else:
                # ู„ุง ูŠูˆุฌุฏ executorุŒ ุฃุถู placeholder
                result_str = json.dumps({"status": "tool_executed", "note": "No executor provided"})

            current_messages.append({
                "role": "tool",
                "tool_call_id": tc["id"],
                "name": fn_name,
                "content": result_str,
            })

        log(f"Tools executed, continuing loop...", "AGENT")

    log(f"Max iterations reached", "WARN")
    return text or "", None, current_messages


# โ”€โ”€โ”€ Sync wrapper โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def call_gemini_sync(
    prompt: str, model_id: int, think_mode: int, tools: list = None
) -> Tuple[str, Optional[list]]:
    """ุงุณุชุฏุนุงุก ู…ุฒุงู…ู† ุจุณูŠุท (ุจุฏูˆู† agent loop)."""
    raw = gemini_stream_generate(prompt, model_id, think_mode)
    text = extract_response_text(raw)
    tool_calls = None
    if tools and text:
        text, tool_calls = parse_tool_calls(text)
    return text or "", tool_calls

# โ”€โ”€โ”€ Model Resolution โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def resolve_model(model_name: str) -> Tuple[Optional[str], Optional[int], Optional[int], Optional[str]]:
    think_override = None
    if "@think=" in model_name:
        model_name, think_str = model_name.rsplit("@think=", 1)
        try:
            think_override = int(think_str)
        except ValueError:
            pass
    cfg = MODELS.get(model_name)
    if not cfg:
        # fallback ู„ู„ู†ู…ูˆุฐุฌ ุงู„ุงูุชุฑุงุถูŠ ุจุฏู„ุงู‹ ู…ู† ุงู„ุฎุทุฃ ุงู„ู…ุจุงุดุฑ
        default = CONFIG.get("default_model", "gemini-3.5-flash")
        cfg = MODELS.get(default)
        if cfg:
            log(f"Unknown model '{model_name}', falling back to '{default}'", "WARN")
            model_name = default
        else:
            return None, None, None, f"Unknown model: {model_name}. Available: {list(MODELS.keys())}"
    return model_name, cfg["mode"], (think_override if think_override is not None else cfg["think"]), None

# โ”€โ”€โ”€ Authentication โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

security = HTTPBearer(auto_error=False)

async def verify_api_key(
    credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)
) -> str:
    api_keys = CONFIG.get("api_keys", [])
    if not api_keys:
        return "anonymous"
    if not credentials:
        raise HTTPException(status_code=401, detail="Missing Authorization header")
    token = credentials.credentials
    if token not in api_keys:
        raise HTTPException(status_code=401, detail="Invalid API key")
    return token

# โ”€โ”€โ”€ FastAPI App โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

@asynccontextmanager
async def lifespan(app: FastAPI):
    await services.init_db()
    await services.start_cleanup()
    log(f"gemini-web2api v{__version__} started", "INFO")
    yield
    if services._cleanup_task:
        services._cleanup_task.cancel()

app = FastAPI(
    title="Gemini Web2API (Agent Edition)",
    version=__version__,
    description="OpenAI-compatible proxy for Google Gemini Web with full Agent/Tool support",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# โ”€โ”€โ”€ /v1/models โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

@app.get("/v1/models")
async def list_models():
    return {
        "object": "list",
        "data": [
            {
                "id": name,
                "object": "model",
                "created": 1700000000,
                "owned_by": "google",
                "description": cfg["desc"],
                "capabilities": {
                    "tool_use": True,
                    "streaming": True,
                    "agent_loop": True,
                },
            }
            for name, cfg in MODELS.items()
        ],
    }

# โ”€โ”€โ”€ /v1beta/models โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

@app.get("/v1beta/models")
async def google_models_list():
    return {
        "models": [
            {
                "name": f"models/{name}",
                "displayName": name,
                "description": cfg["desc"],
                "supportedGenerationMethods": ["generateContent", "streamGenerateContent"],
            }
            for name, cfg in MODELS.items()
        ]
    }

# โ”€โ”€โ”€ /v1/chat/completions โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

@app.post("/v1/chat/completions")
async def chat_completions(
    body: ChatCompletionRequest,
    request: Request,
    _: str = Depends(verify_api_key),
):
    # Rate Limiting
    client_ip = request.client.host
    allowed, wait_time = await services.check_rate_limit(client_ip)
    if not allowed:
        raise HTTPException(
            status_code=429,
            detail=f"Rate limit exceeded. Retry in {wait_time}s.",
            headers={"Retry-After": str(wait_time)},
        )

    model_name, model_id, think_mode, err = resolve_model(
        body.model or CONFIG["default_model"]
    )
    if err:
        raise HTTPException(status_code=400, detail=err)

    tools = body.tools
    messages = [m.dict(exclude_none=True) for m in body.messages]
    cid = f"chatcmpl-{uuid.uuid4().hex[:12]}"
    created = int(time.time())

    # Cache key
    context_str = "".join(f"{m.get('role')}:{m.get('content')}" for m in messages)
    cache_key = hashlib.md5(
        f"{model_name}:{context_str}:{body.user}:{bool(tools)}".encode()
    ).hexdigest()

    # โ”€โ”€โ”€ Streaming โ”€โ”€โ”€
    if body.stream:
        async def stream_gen():
            full_text = ""
            try:
                if tools:
                    # โœ… Streaming ู…ุน ุฃุฏูˆุงุช: ู†ูุฑุณู„ tool calls ูƒู€ chunk ุฎุงุต
                    loop = asyncio.get_event_loop()
                    text, tool_calls, _ = await loop.run_in_executor(
                        None, run_agent_sync,
                        messages, model_id, think_mode, tools,
                        CONFIG["agent_max_iterations"]
                    )
                    full_text = text or ""

                    if tool_calls:
                        # ุฅุฑุณุงู„ tool calls chunk
                        msg_delta = {"role": "assistant", "content": full_text or None, "tool_calls": tool_calls}
                        chunk = {
                            "id": cid, "object": "chat.completion.chunk",
                            "created": created, "model": model_name,
                            "choices": [{"index": 0, "delta": msg_delta, "finish_reason": "tool_calls"}],
                        }
                        yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
                    else:
                        # ุฅุฑุณุงู„ ุงู„ู†ุต ุชุฏุฑูŠุฌูŠุงู‹
                        if full_text:
                            chunk = {
                                "id": cid, "object": "chat.completion.chunk",
                                "created": created, "model": model_name,
                                "choices": [{"index": 0, "delta": {"role": "assistant", "content": full_text}, "finish_reason": None}],
                            }
                            yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"

                else:
                    # Streaming ุจุฏูˆู† ุฃุฏูˆุงุช
                    prompt = messages_to_prompt(messages)
                    for delta in gemini_stream_iter(prompt, model_id, think_mode):
                        full_text += delta
                        chunk = {
                            "id": cid, "object": "chat.completion.chunk",
                            "created": created, "model": model_name,
                            "choices": [{"index": 0, "delta": {"content": delta}, "finish_reason": None}],
                        }
                        yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"

                # Final chunk
                finish = "tool_calls" if tools and full_text else "stop"
                final_chunk = {
                    "id": cid, "object": "chat.completion.chunk",
                    "created": created, "model": model_name,
                    "choices": [{"index": 0, "delta": {}, "finish_reason": finish}],
                }
                yield f"data: {json.dumps(final_chunk)}\n\n"
                yield "data: [DONE]\n\n"

                # Cache ุงู„ู†ุต ุงู„ู†ู‡ุงุฆูŠ (ุจุฏูˆู† tool calls)
                if full_text and not tools:
                    resp_data = _build_completion_response(cid, created, model_name, full_text, None, "")
                    await services.set_cache(cache_key, json.dumps(resp_data))

            except Exception as e:
                log(f"Stream error: {e}", "ERROR")
                yield f"data: {json.dumps({'error': {'message': str(e), 'type': 'server_error'}})}\n\n"

        return StreamingResponse(stream_gen(), media_type="text/event-stream")

    # โ”€โ”€โ”€ Non-streaming โ”€โ”€โ”€
    # Cache (ูู‚ุท ุจุฏูˆู† ุฃุฏูˆุงุช)
    if not tools:
        cached = await services.get_cache(cache_key)
        if cached:
            return JSONResponse(content=json.loads(cached))

    try:
        loop = asyncio.get_event_loop()
        if tools:
            # โœ… ุงุณุชุฎุฏู… Agent Loop
            text, tool_calls, _ = await loop.run_in_executor(
                None, run_agent_sync,
                messages, model_id, think_mode, tools,
                CONFIG["agent_max_iterations"]
            )
        else:
            prompt = messages_to_prompt(messages)
            text, tool_calls = await loop.run_in_executor(
                None, call_gemini_sync, prompt, model_id, think_mode, None
            )
    except Exception as e:
        log(f"Error: {e}", "ERROR")
        raise HTTPException(status_code=502, detail=f"Upstream error: {e}")

    prompt_text = messages_to_prompt(messages)
    resp_data = _build_completion_response(cid, created, model_name, text, tool_calls, prompt_text)

    if not tools:
        await services.set_cache(cache_key, json.dumps(resp_data))

    return JSONResponse(content=resp_data)


def _build_completion_response(
    cid: str, created: int, model: str, text: str,
    tool_calls: Optional[list], prompt: str = ""
) -> dict:
    msg = {"role": "assistant", "content": text or None}
    if tool_calls:
        msg["tool_calls"] = tool_calls
    finish = "tool_calls" if tool_calls else "stop"
    return {
        "id": cid,
        "object": "chat.completion",
        "created": created,
        "model": model,
        "choices": [{"index": 0, "message": msg, "finish_reason": finish}],
        "usage": {
            "prompt_tokens": len(prompt) // 4,
            "completion_tokens": len(text) // 4 if text else 0,
            "total_tokens": (len(prompt) + len(text)) // 4 if text else len(prompt) // 4,
        },
    }

# โ”€โ”€โ”€ /v1/responses (Codex CLI / Responses API) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

@app.post("/v1/responses")
async def responses_api(
    request: Request,
    _: str = Depends(verify_api_key),
):
    req = await request.json()
    model_name, model_id, think_mode, err = resolve_model(
        req.get("model", CONFIG["default_model"])
    )
    if err:
        raise HTTPException(status_code=400, detail=err)

    input_items = req.get("input", [])
    tools = req.get("tools")
    messages = []

    if req.get("instructions"):
        messages.append({"role": "system", "content": req["instructions"]})

    if isinstance(input_items, str):
        messages.append({"role": "user", "content": input_items})
    elif isinstance(input_items, list):
        for item in input_items:
            if isinstance(item, str):
                messages.append({"role": "user", "content": item})
            elif isinstance(item, dict):
                if item.get("type") == "function_call_output":
                    messages.append({
                        "role": "tool",
                        "tool_call_id": item.get("call_id", ""),
                        "name": item.get("name", ""),
                        "content": item.get("output", ""),
                    })
                elif item.get("role") == "assistant":
                    cp = item.get("content", [])
                    text_acc, tc_list = "", []
                    if isinstance(cp, list):
                        for c in cp:
                            if isinstance(c, dict):
                                if c.get("type") == "output_text":
                                    text_acc += c.get("text", "")
                                elif c.get("type") == "function_call":
                                    tc_list.append(c)
                    elif isinstance(cp, str):
                        text_acc = cp
                    m = {"role": "assistant", "content": text_acc or None}
                    if tc_list:
                        m["tool_calls"] = [
                            {
                                "id": tc.get("call_id", f"call_{i}"),
                                "type": "function",
                                "function": {
                                    "name": tc.get("name", ""),
                                    "arguments": tc.get("arguments", "{}"),
                                }
                            }
                            for i, tc in enumerate(tc_list)
                        ]
                    messages.append(m)
                else:
                    role = item.get("role", "user")
                    content = item.get("content", "")
                    if isinstance(content, list):
                        content = " ".join(
                            c.get("text", "") for c in content
                            if c.get("type") in ("text", "input_text")
                        )
                    messages.append({"role": role, "content": content})

    if tools:
        tools = [
            {
                "type": "function",
                "function": {
                    "name": t["name"],
                    "description": t.get("description", ""),
                    "parameters": t.get("parameters", {}),
                }
            }
            if t.get("type") == "function" and "function" not in t else t
            for t in tools
        ]

    if not any(m.get("content") for m in messages):
        raise HTTPException(status_code=400, detail="Empty input")

    loop = asyncio.get_event_loop()
    try:
        if tools:
            text, tool_calls, _ = await loop.run_in_executor(
                None, run_agent_sync, messages, model_id, think_mode, tools,
                CONFIG["agent_max_iterations"]
            )
        else:
            prompt = messages_to_prompt(messages)
            text, tool_calls = await loop.run_in_executor(
                None, call_gemini_sync, prompt, model_id, think_mode, None
            )
    except Exception as e:
        raise HTTPException(status_code=502, detail=f"Upstream error: {e}")

    rid = f"resp_{uuid.uuid4().hex[:16]}"
    mid = f"msg_{uuid.uuid4().hex[:12]}"
    output = []

    if tool_calls:
        for tc in tool_calls:
            output.append({
                "type": "function_call",
                "id": tc["id"],
                "call_id": tc["id"],
                "name": tc["function"]["name"],
                "arguments": tc["function"]["arguments"],
                "status": "completed",
            })
    if text or not tool_calls:
        output.append({
            "type": "message",
            "id": mid,
            "role": "assistant",
            "status": "completed",
            "content": [{"type": "output_text", "text": text or "", "annotations": []}],
        })

    prompt_text = messages_to_prompt(messages)
    if req.get("stream"):
        async def responses_stream():
            yield f"event: response.created\ndata: {json.dumps({'type': 'response.created', 'response': {'id': rid, 'object': 'response', 'status': 'in_progress', 'model': model_name, 'output': []}})}\n\n"
            for item in output:
                if item["type"] == "function_call":
                    ev = {
                        "type": "response.function_call_arguments.done",
                        "item_id": item["id"], "call_id": item["call_id"],
                        "name": item["name"], "arguments": item["arguments"],
                    }
                    yield f"event: response.function_call_arguments.done\ndata: {json.dumps(ev)}\n\n"
                elif item["type"] == "message":
                    for ci, cp in enumerate(item["content"]):
                        ev = {
                            "type": "response.output_text.done",
                            "item_id": item["id"], "content_index": ci, "text": cp["text"],
                        }
                        yield f"event: response.output_text.done\ndata: {json.dumps(ev)}\n\n"
            resp_obj = {"id": rid, "object": "response", "status": "completed", "model": model_name, "output": output}
            yield f"event: response.completed\ndata: {json.dumps({'type': 'response.completed', 'response': resp_obj})}\n\n"
        return StreamingResponse(responses_stream(), media_type="text/event-stream")

    return JSONResponse({
        "id": rid, "object": "response", "created_at": int(time.time()),
        "status": "completed", "model": model_name, "output": output,
        "usage": {
            "input_tokens": len(prompt_text) // 4,
            "output_tokens": len(text) // 4 if text else 0,
            "total_tokens": (len(prompt_text) + len(text)) // 4 if text else len(prompt_text) // 4,
        },
    })

# โ”€โ”€โ”€ Google Native API /v1beta โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def _google_contents_to_prompt(req: dict) -> str:
    parts = []
    sys_inst = req.get("systemInstruction")
    if sys_inst:
        sys_text = " ".join(p.get("text", "") for p in sys_inst.get("parts", []) if p.get("text"))
        if sys_text:
            parts.append(f"[SYSTEM]\n{sys_text}")
    for content in req.get("contents", []):
        role = content.get("role", "user")
        text = " ".join(p.get("text", "") for p in content.get("parts", []) if p.get("text"))
        if role == "model":
            parts.append(f"[ASSISTANT]: {text}")
        else:
            parts.append(f"[USER]: {text}")
    return "\n\n".join(p for p in parts if p)

@app.post("/v1beta/models/{model_path:path}")
async def google_generate(model_path: str, request: Request):
    req = await request.json()
    model_name_raw = model_path.split(":")[0]
    stream = ":streamGenerateContent" in model_path

    model_name, model_id, think_mode, err = resolve_model(model_name_raw)
    if err:
        raise HTTPException(status_code=400, detail=err)

    prompt = _google_contents_to_prompt(req)
    if not prompt.strip():
        raise HTTPException(status_code=400, detail="Empty content")

    loop = asyncio.get_event_loop()
    try:
        text, _ = await loop.run_in_executor(
            None, call_gemini_sync, prompt, model_id, think_mode, None
        )
    except Exception as e:
        raise HTTPException(status_code=502, detail=f"Upstream error: {e}")

    candidate = {
        "content": {"parts": [{"text": text or ""}], "role": "model"},
        "finishReason": "STOP",
        "index": 0,
    }
    response_obj = {
        "candidates": [candidate],
        "usageMetadata": {
            "promptTokenCount": len(prompt) // 4,
            "candidatesTokenCount": len(text) // 4 if text else 0,
            "totalTokenCount": (len(prompt) + len(text)) // 4 if text else len(prompt) // 4,
        },
        "modelVersion": model_name,
    }

    if stream:
        async def google_stream():
            yield f"data: {json.dumps(response_obj)}\n\n"
        return StreamingResponse(google_stream(), media_type="text/event-stream")

    return JSONResponse(response_obj)

# โ”€โ”€โ”€ Health & Root โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

@app.get("/")
async def root():
    return {
        "service": "gemini-web2api",
        "version": __version__,
        "models": list(MODELS.keys()),
        "features": {
            "agent_loop": True,
            "tool_calling": True,
            "streaming": True,
            "cache": True,
            "rate_limiting": True,
        },
        "endpoints": ["/v1/chat/completions", "/v1/models", "/v1/responses", "/v1beta/models"],
    }

@app.get("/health")
async def health():
    return {"status": "healthy", "timestamp": time.time(), "version": __version__}

# โ”€โ”€โ”€ Gradio UI โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def build_gradio_interface():
    async def chat_handler(message: str, history: list, model_choice: str, request: gr.Request):
        if not message or not message.strip():
            yield history
            return

        model_name, model_id, think_mode, err = resolve_model(model_choice)
        if err:
            history.append((message, f"โŒ {err}"))
            yield history
            return

        history.append((message, ""))
        yield history

        full_response = ""
        try:
            prompt = messages_to_prompt([{"role": "user", "content": message}])
            for chunk in gemini_stream_iter(prompt, model_id, think_mode):
                full_response += chunk
                history[-1] = (message, full_response)
                yield history
        except Exception as e:
            full_response = f"โŒ Error: {e}"
            history[-1] = (message, full_response)
            yield history

    api_endpoint = "https://your-space.hf.space/v1"
    api_key_display = CONFIG.get("api_keys", ["sk-gemini"])[0]

    with gr.Blocks(title="Gemini Web2API โ€” Agent Edition") as demo:
        gr.Markdown(f"""
        # ๐Ÿค– Gemini Web2API โ€” Agent Edition v{__version__}
        > OpenAI-compatible proxy ู…ุน ุฏุนู… ูƒุงู…ู„ ู„ู€ Agent Loop ูˆTool Calling
        | | |
        |---|---|
        | **Base URL** | `{api_endpoint}` |
        | **API Key** | `{api_key_display}` |
        | **Models** | {', '.join(f'`{m}`' for m in MODELS.keys())} |
        | **Agent Loop** | โœ… ุญุชู‰ {CONFIG['agent_max_iterations']} iterations |
        """)

        with gr.Row():
            with gr.Column(scale=4):
                chatbot = gr.Chatbot(height=500, label="ุงู„ู…ุญุงุฏุซุฉ")
            with gr.Column(scale=1):
                gr.Markdown("""### โœ… ุงู„ู…ู…ูŠุฒุงุช
- Agent Loop (ReAct)
- Tool Calling ู…ูˆุซูˆู‚
- JSON Parser ู…ุชุนุฏุฏ ุงู„ู…ุณุชูˆูŠุงุช
- Streaming ุญู‚ูŠู‚ูŠ
- SQLite Cache
- Rate Limiting
- Retry Logic
- Fallback ู„ู„ู†ู…ูˆุฐุฌ ุงู„ุงูุชุฑุงุถูŠ
                """)

        with gr.Row():
            msg_box = gr.Textbox(label="ุฑุณุงู„ุชูƒ", placeholder="ุงูƒุชุจ ู‡ู†ุง...", lines=2, scale=5)
            send_btn = gr.Button("ุฅุฑุณุงู„ โ–ถ", variant="primary", scale=1)

        with gr.Row():
            clear_btn = gr.Button("๐Ÿ—‘๏ธ ู…ุณุญ")
            model_dd = gr.Dropdown(
                choices=list(MODELS.keys()),
                value=CONFIG["default_model"],
                label="ุงู„ู†ู…ูˆุฐุฌ",
                scale=2,
            )

        msg_box.submit(chat_handler, [msg_box, chatbot, model_dd], [chatbot]).then(
            lambda: "", None, [msg_box]
        )
        send_btn.click(chat_handler, [msg_box, chatbot, model_dd], [chatbot]).then(
            lambda: "", None, [msg_box]
        )
        clear_btn.click(lambda: [], None, [chatbot])

    return demo

demo = build_gradio_interface()
app = gr.mount_gradio_app(app, demo, path="/chat")

# โ”€โ”€โ”€ Entry Point โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

if __name__ == "__main__":
    import uvicorn

    parser = argparse.ArgumentParser(description="Gemini Web2API Agent Edition")
    parser.add_argument("--port", type=int, default=CONFIG["port"])
    parser.add_argument("--host", type=str, default=CONFIG["host"])
    parser.add_argument("--cookie-file", type=str, default=None)
    parser.add_argument("--proxy", type=str, default=None)
    parser.add_argument("--max-iterations", type=int, default=CONFIG["agent_max_iterations"])
    parser.add_argument("--version", action="version", version=f"v{__version__}")
    args = parser.parse_args()

    if args.cookie_file:
        CONFIG["cookie_file"] = args.cookie_file
    if args.proxy:
        CONFIG["proxy"] = args.proxy
    CONFIG["agent_max_iterations"] = args.max_iterations

    print(f"\n{'='*60}")
    print(f"  gemini-web2api v{__version__} โ€” Agent Edition")
    print(f"{'='*60}")
    print(f"  API:          http://localhost:{args.port}/v1")
    print(f"  Chat UI:      http://localhost:{args.port}/chat")
    print(f"  Models:       {', '.join(MODELS.keys())}")
    print(f"  Agent Loop:   max {CONFIG['agent_max_iterations']} iterations")
    print(f"  Cookie:       {'โœ…' if CONFIG.get('cookie_file') or CONFIG.get('_cookie_inline') else 'โŒ none (anonymous)'}")
    print(f"  Proxy:        {CONFIG.get('proxy') or 'โŒ none'}")
    print(f"{'='*60}\n")

    uvicorn.run(
        app,
        host=args.host,
        port=args.port,
        loop="asyncio",
        timeout_keep_alive=120,
    )