File size: 119,258 Bytes
cdc26bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4972d36
cdc26bd
 
 
 
 
 
 
 
 
 
 
4972d36
d543e93
 
b5ad894
 
 
cdc26bd
4972d36
d543e93
ac00d8b
 
 
d543e93
b5ad894
d543e93
 
cdc26bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67dfa5f
 
cdc26bd
 
 
594c79f
cdc26bd
 
 
594c79f
 
cdc26bd
 
 
 
 
 
 
 
67dfa5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdc26bd
 
 
 
 
 
 
 
 
 
 
 
594c79f
 
 
 
cdc26bd
 
 
594c79f
cdc26bd
594c79f
cdc26bd
 
 
594c79f
 
ac00d8b
cdc26bd
 
67dfa5f
 
 
 
 
 
b5ad894
 
 
 
 
ac00d8b
 
 
 
b5ad894
 
 
 
ac00d8b
836437a
 
cdc26bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
594c79f
 
 
4972d36
594c79f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdc26bd
 
 
836437a
 
 
 
 
 
 
594c79f
 
 
 
 
cdc26bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
594c79f
cdc26bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
594c79f
cdc26bd
594c79f
cdc26bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
594c79f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdc26bd
 
 
 
 
 
 
 
4972d36
 
 
 
 
 
 
 
 
 
cdc26bd
 
4972d36
cdc26bd
 
b5ad894
 
cdc26bd
b5ad894
 
 
 
 
 
 
 
 
 
 
 
cdc26bd
 
ac00d8b
cdc26bd
 
 
 
ac00d8b
cdc26bd
 
 
ac00d8b
cdc26bd
 
 
ac00d8b
 
 
 
 
cdc26bd
 
 
 
ac00d8b
cdc26bd
 
 
 
 
 
ac00d8b
cdc26bd
 
 
ac00d8b
cdc26bd
 
 
 
 
 
 
 
 
 
 
 
 
ac00d8b
 
 
 
 
cdc26bd
 
 
 
 
 
 
 
 
 
ac00d8b
 
 
 
cdc26bd
 
ac00d8b
cdc26bd
 
ac00d8b
cdc26bd
ac00d8b
 
cdc26bd
 
ac00d8b
b5ad894
ac00d8b
 
cdc26bd
ac00d8b
cdc26bd
 
 
 
 
b5ad894
cdc26bd
 
 
 
 
 
ac00d8b
 
d543e93
 
 
 
 
ac00d8b
 
b5ad894
ac00d8b
 
cdc26bd
 
 
 
 
ac00d8b
cdc26bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac00d8b
 
 
 
 
 
 
 
 
594c79f
ac00d8b
 
 
 
 
 
 
594c79f
ac00d8b
 
 
 
cdc26bd
 
 
 
 
 
 
 
 
 
b5ad894
cdc26bd
b5ad894
cdc26bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67dfa5f
 
cdc26bd
 
 
 
 
b5ad894
67dfa5f
b5ad894
 
 
67dfa5f
cdc26bd
 
 
 
 
 
 
 
 
 
 
 
 
b5ad894
cdc26bd
 
 
 
b5ad894
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdc26bd
 
 
 
 
 
 
 
67dfa5f
cdc26bd
 
 
 
 
 
b5ad894
 
cdc26bd
 
594c79f
 
 
cdc26bd
 
b5ad894
 
cdc26bd
b5ad894
cdc26bd
 
 
 
 
 
67dfa5f
b5ad894
 
cdc26bd
 
 
 
 
594c79f
 
 
cdc26bd
 
 
594c79f
cdc26bd
 
 
 
b5ad894
 
 
cdc26bd
 
 
 
 
 
 
 
67dfa5f
 
b5ad894
 
 
 
67dfa5f
 
 
 
 
 
 
b5ad894
67dfa5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdc26bd
 
 
594c79f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdc26bd
594c79f
 
 
 
4972d36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
594c79f
 
 
 
4972d36
594c79f
4972d36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdc26bd
594c79f
 
4972d36
594c79f
4972d36
594c79f
cdc26bd
594c79f
4972d36
594c79f
 
 
 
cdc26bd
594c79f
cdc26bd
594c79f
cdc26bd
594c79f
cdc26bd
 
 
 
594c79f
cdc26bd
 
 
b5ad894
 
 
 
 
 
 
 
cdc26bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5ad894
cdc26bd
 
 
 
 
b5ad894
cdc26bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5ad894
cdc26bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
594c79f
 
cdc26bd
594c79f
 
 
cdc26bd
 
594c79f
 
cdc26bd
 
 
594c79f
 
 
 
 
 
 
 
 
4972d36
594c79f
 
cdc26bd
594c79f
 
 
 
 
 
 
 
 
 
 
 
 
 
4972d36
594c79f
cdc26bd
594c79f
 
 
 
 
cdc26bd
594c79f
 
cdc26bd
 
594c79f
 
cdc26bd
 
 
 
594c79f
cdc26bd
 
 
594c79f
 
 
 
4972d36
594c79f
 
 
 
4972d36
cdc26bd
 
594c79f
 
 
 
 
 
cdc26bd
594c79f
 
 
 
 
 
 
cdc26bd
 
594c79f
 
cdc26bd
594c79f
 
b5ad894
cdc26bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5ad894
cdc26bd
 
 
 
 
 
 
ac00d8b
cdc26bd
 
 
 
b5ad894
 
 
cdc26bd
b5ad894
cdc26bd
67dfa5f
cdc26bd
 
ac00d8b
cdc26bd
b5ad894
 
cdc26bd
ac00d8b
cdc26bd
 
 
 
 
 
 
 
 
 
 
 
 
ac00d8b
 
 
 
cdc26bd
 
 
b5ad894
cdc26bd
 
 
 
 
ac00d8b
cdc26bd
 
 
 
 
ac00d8b
cdc26bd
b5ad894
ac00d8b
 
 
 
b5ad894
ac00d8b
b5ad894
ac00d8b
 
 
 
 
cdc26bd
 
 
 
 
 
 
 
 
b5ad894
ac00d8b
 
 
 
 
 
 
 
b5ad894
 
ac00d8b
 
 
 
cdc26bd
 
ac00d8b
 
 
 
 
 
 
cdc26bd
 
 
 
 
b5ad894
836437a
cdc26bd
 
 
b5ad894
cdc26bd
 
 
 
 
 
 
 
 
 
67dfa5f
 
 
 
 
 
cdc26bd
 
 
b5ad894
cdc26bd
 
 
b5ad894
cdc26bd
 
 
 
 
 
 
 
 
 
 
 
67dfa5f
 
 
 
cdc26bd
 
 
 
b5ad894
836437a
cdc26bd
 
 
594c79f
ac00d8b
594c79f
 
ac00d8b
 
 
594c79f
ac00d8b
 
 
b5ad894
cdc26bd
 
 
 
 
 
 
4972d36
d543e93
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
'use strict';
// ============================================================================
// 🤖 CODING AGENT  (used ONLY by /api/agent-stream when the user picked "🤖 Agent")
//
//   WRITE  ->  TEST  ->  FIX (edit only the broken lines)  ->  TEST again  ->  PRESENT
//
// It is the Node.js version of the Flask app.py agent: Gemini function-calling with
//   write_code / edit_code / read_file / execute_code / present_files
// and it talks to the page with the SAME SSE events search.html already understands
// (step / thought / plan / command / file_chunk / test / cmd_output / verdict / files / final / done).
//
// SAFETY
//  - every request gets its own temp workspace (deleted afterwards)
//  - code runs with a CLEAN environment (no API keys / secrets), no shell, no stdin, 15s limit
//  - file names are sanitised (no ../, no absolute paths)
//  - set AGENT_RUN_CODE=0 to disable execution (syntax checks only)
//
// ENV (all optional)
//   AGENT_RUN_CODE=0            only syntax-check, never execute
//   AGENT_RUN_TIMEOUT_SEC=30    time limit for one test run
//   AGENT_MAX_TURNS=18          max model turns per request
//   GEMINI_BASE_URL=...         (tests only) point Gemini calls at a mock server
// ============================================================================
const fs = require('fs');
const os = require('os');
const path = require('path');
const { spawn } = require('child_process');

const GEMINI_BASE = String(process.env.GEMINI_BASE_URL || 'https://generativelanguage.googleapis.com').replace(/\/+$/, '');
const IS_WIN = process.platform === 'win32';
const RUN_CODE = process.env.AGENT_RUN_CODE !== '0';
const RUN_LIMIT_MS = (parseInt(process.env.AGENT_RUN_TIMEOUT_SEC) || 30) * 1000;   // a test run may take up to 30 seconds
const MAX_TURNS = parseInt(process.env.AGENT_MAX_TURNS) || 35; // 🚀 Increased from 18 to 35 turns for deep 5-15 minute runs
const MAX_WALL_MS = 15 * 60 * 1000; // 🚀 15 minutes limit (user requested 5-15 minutes instead of 1 minute)
const MAX_FILE_BYTES = 400000;      // a file the AI WRITES (new files)
const MAX_SEED_BYTES = 3000000;     // a file the USER uploaded (big pages like search.html are ~700 KB; used to be cut at 400 KB = "file is CUT OFF")
const MAX_WS_BYTES = 24000000;
const MAX_FILES = 80;
const MAX_OUT = 100000;   // show (almost) the FULL output of installs and runs
const IDLE_MS = (parseFloat(process.env.AGENT_IDLE_SEC) || 15) * 1000;              // 🚀 Fast failover watchdog: 15s instead of 90s to eliminate startup delay
const HEARTBEAT_MS = (parseFloat(process.env.AGENT_HEARTBEAT_SEC) || 6) * 1000;     // "still working..." message while the AI is silent
const MAX_THOUGHT_CHARS = parseInt(process.env.AGENT_MAX_THOUGHT_CHARS) || 12000;   // a thinking loop is cut after this much
const FIRST_MAX_OUTPUT = 32768;
// 🚀 Models pool: prioritize responsive, verified models first (gemini-2.5-flash, gemini-3.5-flash) to start in <1s
const csv = (v, d) => String(v || d).split(',').map(x => x.trim()).filter(Boolean);
const MODELS_STRONG = csv(process.env.AGENT_MODELS_STRONG, 'gemini-2.5-flash,gemini-3.5-flash,gemini-3.5-flash-lite,gemini-3.6-flash');
const MODELS_CHEAP = csv(process.env.AGENT_MODELS_CHEAP, 'gemini-2.5-flash,gemini-3.5-flash-lite,gemini-3.5-flash,gemini-3.6-flash');
const TRUNC_NOTE = '\n[output truncated]\n';

const PY_USER_BASE = path.join(os.tmpdir(), 'agent-pyuser');
const NPM_CACHE = path.join(os.tmpdir(), 'agent-npm-cache');

// ----------------------------------------------------------------------------
// Tools (same five as app.py)
// ----------------------------------------------------------------------------
const TOOLS = [
    {
        name: 'write_code',
        description: 'Creates a NEW file and writes the COMPLETE code to it. NEVER use this to modify an existing file (use edit_code).',
        parameters: { type: 'OBJECT', properties: {
            filename: { type: 'STRING', description: 'Relative path, e.g. app.py, games/snake.html, src/utils.js' },
            content: { type: 'STRING', description: 'The complete, final source code of the file. No placeholders.' }
        }, required: ['filename', 'content'] }
    },
    {
        name: 'edit_code',
        description: 'Edits an existing file by replacing one exact piece of text. Output ONLY the few lines that change, never the whole file.',
        parameters: { type: 'OBJECT', properties: {
            filename: { type: 'STRING' },
            search_string: { type: 'STRING', description: 'Exact existing text to find (must match exactly ONE place; include enough surrounding lines).' },
            replace_string: { type: 'STRING', description: 'The new text that replaces it.' }
        }, required: ['filename', 'search_string', 'replace_string'] }
    },
    {
        name: 'read_file',
        description: 'Reads a file of this conversation (uploaded by the user or created by you): code, text, or the extracted text of a PDF/Word document. Use it before editing if you are not sure about the exact text. Optional start_line / end_line read only that range of a big file.',
        parameters: { type: 'OBJECT', properties: { filename: { type: 'STRING' }, start_line: { type: 'INTEGER', description: 'First line to read (1-based). Optional.' }, end_line: { type: 'INTEGER', description: 'Last line to read. Optional.' } }, required: ['filename'] }
    },
    {
        name: 'execute_code',
        description: 'Runs the file to TEST it: python / node / java run the program (packages it imports are installed automatically first), html loads the page in a headless browser and reports JavaScript errors. If the program asks for keyboard input, pass the answers in `stdin`. You MUST call this after writing or editing code.',
        parameters: { type: 'OBJECT', properties: {
            language: { type: 'STRING', description: 'python, node, java or html' },
            filename: { type: 'STRING', description: 'The main file to run / open' },
            dependencies: { type: 'ARRAY', items: { type: 'STRING' }, description: 'Extra pip packages (python) or npm packages (node) to install first. Imports are detected and installed automatically, so this is only needed for packages that are not imported directly.' },
            stdin: { type: 'STRING', description: 'Text typed into the program when it asks for input (input(), Scanner, readline). One line per prompt, lines separated by \\n, ending with the answer that makes the program exit (e.g. quit). Omit if the program needs no input.' }
        }, required: ['language', 'filename'] }
    },
    {
        name: 'present_files',
        description: 'Call this ONLY after execute_code passed (or when the code truly cannot run on this server). Shows the final files to the user.',
        parameters: { type: 'OBJECT', properties: {
            filenames: { type: 'ARRAY', items: { type: 'STRING' }, description: 'All final files for the user.' }
        }, required: ['filenames'] }
    },
    {
        name: 'web_search',
        description: 'Searches the web (Google, through Gemini 2.5 Flash) and returns a short factual answer with source links. Use it for things you are not sure about or that change: exact package names and versions, current API usage, error messages, library docs, anything the user asks you to look up. Do NOT use it for ordinary coding you already know. At most 6 searches per request.',
        parameters: { type: 'OBJECT', properties: { query: { type: 'STRING', description: 'A clear, specific search question, e.g. "yt-dlp download audio only mp3 python example 2026".' } }, required: ['query'] }
    },
    {
        name: 'list_files',
        description: 'Lists the files of THIS conversation with their origin (uploaded by the user / created by you earlier / created in this run), size and line count. Use scope "user" to see only the files the user uploaded, "agent" for only the files you created, "all" for everything.',
        parameters: { type: 'OBJECT', properties: { scope: { type: 'STRING', description: 'all (default), user or agent' } } }
    },
    {
        name: 'search_in_files',
        description: 'Searches text inside all files of this conversation (like grep) and returns file:line matches. Use it to find where a function, variable, import or link is used before you edit or rename something.',
        parameters: { type: 'OBJECT', properties: {
            pattern: { type: 'STRING', description: 'Text to find (or a regular expression when regex is true).' },
            regex: { type: 'BOOLEAN', description: 'Treat pattern as a regular expression. Default false.' },
            case_sensitive: { type: 'BOOLEAN', description: 'Default false.' },
            scope: { type: 'STRING', description: 'all (default), user or agent' }
        }, required: ['pattern'] }
    },
    {
        name: 'rename_file',
        description: 'Renames or moves a file (like mv). Afterwards update every reference to the old name (imports, <script src>, links) with edit_code and test again. Uploaded PDF/Word documents cannot be renamed.',
        parameters: { type: 'OBJECT', properties: { from: { type: 'STRING' }, to: { type: 'STRING' } }, required: ['from', 'to'] }
    },
    {
        name: 'delete_file',
        description: 'Deletes a file (like rm). Only delete files the user asked you to delete, or your own scratch files. Uploaded PDF/Word documents cannot be deleted.',
        parameters: { type: 'OBJECT', properties: { filename: { type: 'STRING' } }, required: ['filename'] }
    }
];

// ----------------------------------------------------------------------------
// The system prompt - includes the Hugging Face warning
// ----------------------------------------------------------------------------
function buildSystemPrompt(lang, clock) {
    return `You are an elite autonomous coding agent working inside a chat app. You write, test, fix and present code (Python, Node.js, Java, HTML/CSS/JS).

YOUR LOOP — follow it every single time:
1. SPEAK FIRST: before ANY tool call, write 1-3 short sentences (in ${lang}) telling the user what you are about to do. Never call a tool silently.
2. WRITE: create every NEW file with write_code. Each file must be 100% COMPLETE and working. NEVER use placeholders like "// rest of the code here", "...", "same as before". Split bigger projects into separate files linked with relative paths (index.html + style.css + script.js, etc.) unless the user wants a single file.
3. TEST (really run it): after writing or editing code you MUST call execute_code on the main file (language "html" for web pages, "python", "node" or "java" otherwise). The tool first INSTALLS every package your code imports (pip / npm — automatic), then RUNS the file and shows you the real output.
   • If the program asks for keyboard input (input(), Scanner, readline, a menu...), pass realistic answers in the \`stdin\` argument — one line per prompt, ending with the answer that exits the program (e.g. quit). NEVER remove input() from the program just to make the test pass.
   • Read the output carefully: it must show what the program is supposed to do.
4. FIX: if the output shows an error, find the REAL cause and fix it with edit_code (only the exact lines that change — NEVER rewrite an existing file with write_code), then call execute_code AGAIN. Repeat until it passes. EXCEPTION: errors about signing in / bot checks ("Sign in to confirm you're not a bot"), HTTP 403 / 429, captcha or a blocked network are the SERVER's problem — never try to fix those (the tool reports them as ENV-BLOCKED).
5. PRESENT: call present_files ONLY when the code works (or when it genuinely cannot run here — see ENVIRONMENT). After present_files, write a short final message (in ${lang}) saying what you built, how to run it, and anything the user must know.

⚠️ ENVIRONMENT — READ THIS CAREFULLY:
- Your code is executed on a small shared SERVER HOSTED ON HUGGING FACE SPACES (Linux, no screen, no sound card, about ${Math.round(RUN_LIMIT_MS / 1000)} seconds per test run; packages are installed with pip / npm automatically).
- Hugging Face servers are BLOCKED or treated as bots by many websites. Because of that:
    • DOWNLOADING AUDIO / VIDEO FROM YOUTUBE (yt-dlp, youtube-dl, pytube, ytdl-core, ...) FAILS here with errors like "Sign in to confirm you're not a bot", HTTP 403 / 429 or network errors. The test tool still RUNS your code, so everything before the blocked request gets tested; the blocked request itself is reported as ENV-BLOCKED.
    • Scraping BOT-PROTECTED or "CLOSED" websites (Cloudflare, captcha, login walls, sites that block datacenter IPs) ALWAYS returns 403 / 429 / captcha pages here.
    • Some outbound hosts and ports are blocked (DNS / TLS / connection errors).
  These failures are NOT bugs in the code. NEVER keep "fixing" them in a loop.
- When the task needs such things: still write the best, correct code (clear error handling and helpful error messages), run it, fix every REAL bug, but do not waste turns on the blocked network call itself, and in your FINAL message tell the user clearly (in ${lang}) that this part could not be verified on the Hugging Face server and should be run on their own computer.
- No GUI windows (tkinter, pygame, turtle...) and no microphone / speakers / camera (those are only syntax-checked). Keyboard input IS possible: give it through the \`stdin\` argument of execute_code. Programs that never exit (web servers, game loops) are stopped after the time limit — that is fine if no error was printed before.
- BEFORE you write code, ask yourself: does this task download videos/audio, scrape a protected website, or use an online service that blocks Hugging Face? If YES: say so in your first sentence, write the code anyway, test ONLY the offline logic, and never retry blocked network calls.
- Stay inside your workspace. Never read, print or search for environment variables, API keys, secrets or files outside the workspace.

YOUR 10 TOOLS
  write_code (new file) · edit_code (change lines of an existing file) · read_file (whole file or a line range) · execute_code (install + run + test) · present_files (show final files)
  web_search (look things up on the web, max 6 per request) · list_files (what files exist in THIS conversation: scope user / agent / all) · search_in_files (grep) · rename_file · delete_file
FILES OF THIS CONVERSATION: the user may have uploaded files in earlier messages and you may have created files in earlier turns — they are all in your workspace. Call list_files if you are unsure which files exist or who made them. Files come ONLY from this conversation. PDF / Word documents appear as read-only text (you can read and search them, not edit, rename or delete them). Never delete or rename a file unless the user asked for it or it is your own scratch file.
WEB SEARCH: use web_search when you are not sure about a package name, version, API or error, or when the user asks you to look something up; put what you learned into the code. Do not search for things you already know.

SAVE REQUESTS (the user has a small daily limit of AI requests — every turn costs one):
- In ONE turn call every tool you already know you need, in order. Examples: write ALL files + execute_code in the same turn; several edit_code calls + execute_code; list_files + read_file together; search_in_files + read_file.
- Writing and editing give you an automatic syntax check in the result, so you do not need a separate turn to check them.
- Do not spend a turn only to announce something. One short sentence, then the tool calls.

HOW TO WRITE (very important — long answers get CUT OFF and fail):
- Write ONE file per write_code call. Keep each file under about 300 lines. For bigger programs split into modules (main.py + helpers.py, index.html + style.css + script.js ...).
- Your spoken sentence before a tool call must be 1-2 SHORT sentences. NEVER paste code into the chat: code goes ONLY into write_code / edit_code.
- If you say you will do something, you MUST call the tool in that same turn. A turn that only talks (and calls no tool) is a FAILURE.
- ALWAYS write normal, readable, multi-line, indented code. NEVER minify and NEVER put a whole file (or a long block) on one line: one statement per line, one block per line break. A // comment ends at the end of its line.
- Big uploaded files (a page can be 10,000 lines): do not read them whole. Use search_in_files to find the place, read_file with start_line/end_line to read around it, then edit_code with a small exact search_string. NEVER rewrite a big file.
- Problems that were ALREADY in a file the user uploaded are not yours: the checks ignore them. Do not try to "fix" them and never create stand-in files (a missing style.css, image, script...) for something the page links to — it exists in the user's real project.
- A file marked "LINE BREAKS LOST" cannot be edited safely: do not touch it, tell the user to upload it again.

YOUR FINAL MESSAGE (after present_files): 2-5 short plain sentences in ${lang}. Mention how to run it using INLINE \`code\` (e.g. \`python app.py\`). Do NOT use \`\`\` code blocks and do NOT paste the code again — the user already gets the files as cards.

OTHER RULES
- Write all code, comments, file names and variable names in ENGLISH unless the user asks otherwise. Your messages to the user are in ${lang}.
- Do ALL internal reasoning / thought summaries in ENGLISH only.
- Deliver the COMPLETE amount asked (if the user asks for N items / pages / levels, build all N).
- Web pages must work by simply opening the HTML file (relative links, CDN scripts are fine, no build step).
- Keep tool calls efficient: write all files first, then test, then fix.${clock || ''}`;
}

// ----------------------------------------------------------------------------
// Small pure helpers (also exported for tests)
// ----------------------------------------------------------------------------
function safeRel(name) {
    let s = String(name == null ? '' : name).replace(/\\/g, '/').trim().replace(/^\.\//, '');
    if (!s || s.length > 200 || s.indexOf('\0') >= 0 || s[0] === '/' || /^[A-Za-z]:/.test(s)) return null;
    const n = path.posix.normalize(s);
    if (n === '.' || n === '..' || n.startsWith('../')) return null;
    if (/[<>:"|?*\x00-\x1f]/.test(n)) return null;
    if (n.split('/').some(seg => seg === 'node_modules' || seg === '.git' || seg === '__pycache__' || seg === '')) return null;
    return n;
}
function extLang(f) {
    const e = (String(f).split('.').pop() || '').toLowerCase();
    return ({ py: 'python', js: 'node', mjs: 'node', cjs: 'node', java: 'java', html: 'html', htm: 'html' })[e] || '';
}
function fileLanguageTag(f) { return (String(f).split('.').pop() || '').toLowerCase(); }
function isCodeFile(f) { return /\.(py|js|mjs|cjs|jsx|ts|tsx|java|html?)$/i.test(f); }
function clipMid(s, max) {
    s = String(s == null ? '' : s);
    if (s.length <= max) return s;
    const head = Math.floor(max * 0.3), tail = max - head;
    return s.slice(0, head) + '\n…[' + (s.length - max) + ' characters cut]…\n' + s.slice(-tail);
}
function chunkLines(text, per) {
    const lines = String(text).split('\n'), out = [];
    for (let i = 0; i < lines.length; i += per) out.push(lines.slice(i, i + per).join('\n') + (i + per < lines.length ? '\n' : ''));
    return out;
}
function validDep(d, kind) {
    d = String(d || '').trim();
    if (!d || d.length > 100 || d[0] === '-') return false;
    if (kind === 'npm') return /^(@[a-z0-9][\w.\-]*\/)?[a-z0-9][\w.\-]*(@[\w.\-^~<>=*]+)?$/i.test(d);
    return /^[A-Za-z0-9][A-Za-z0-9._\-]*(\[[A-Za-z0-9,_\-]+\])?([<>=!~]=?[A-Za-z0-9.*+!_\-]+(,[<>=!~]=?[A-Za-z0-9.*+!_\-]+)*)?$/.test(d);
}

const YT_LIBS = /\b(yt[_-]?dlp|youtube[_-]?dl|youtube-dl-exec|pytube(?:fix)?|ytdl-core|@distube\/ytdl-core|you-get|pafy|ytmp3|y2mate)\b/i;
const GUI_LIBS = /\b(tkinter|Tkinter|pygame|turtle|pyautogui|PyQt\d|PySide\d|kivy|pyglet|cv2\.imshow|sounddevice|pyaudio|simpleaudio|playsound|javax\.swing|java\.awt|javafx)\b/;
const ENV_STRONG_RE = /Sign in to confirm|not a bot|HTTP Error 40[013]|HTTP Error 429|40[13] Client Error|429 Client Error|403 Forbidden|429 Too Many|status code:? ?(403|429)|cloudflare|captcha|are you (a )?human|access denied|Unable to download (webpage|video|JSON)|Video unavailable|This video is not available|Private video|RegexMatchError|VideoUnavailable|yt_dlp\.utils\.DownloadError|nsig extraction failed|Requested format is not available/i;
const ENV_WEAK_RE = /getaddrinfo|ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ECONNRESET|ETIMEDOUT|Name or service not known|Temporary failure in name resolution|Connection refused|Max retries exceeded|Network is unreachable|SSLError|CERTIFICATE_VERIFY_FAILED|urlopen error|ConnectionError|fetch failed|Could not resolve host/i;
const ENV_HINT = '\n\n⚠️ ENVIRONMENT NOTE: the failure above is a Hugging Face server limitation (sign-in / bot protection / blocked network), NOT a bug in the code — everything before the blocked request ran fine. Do NOT try to fix it and do NOT retry. Make sure the code handles this error gracefully (clear message), then call present_files and tell the user in your final message that this part must be run on their own computer.';
const INSTALL_ENV_HINT = '\n\n⚠️ ENVIRONMENT NOTE: this server cannot install Python packages (pip is unavailable / the package index is not reachable). This is NOT a bug in the code. Do NOT rewrite the program to avoid the dependency and do NOT remove the import. Keep the code as it is (it may print a clear "pip install <name>" message when the package is missing), call present_files, and tell the user in your final message to run `pip install <packages>` on their own computer.';
const NON_PIP = new Set(['msvcrt', 'winreg', '_winreg', 'winsound', 'nt', '_winapi', 'tkinter', 'Tkinter', 'posix', 'readline', 'curses', '_curses', 'pwd', 'grp', 'fcntl', 'termios', 'resource', 'syslog']);
const PY_IMPORT_SCRIPT = [
    'import ast, os, json, importlib.util',
    'mods = set()',
    'for root, dirs, fs in os.walk("."):',
    '    dirs[:] = [d for d in dirs if d not in ("node_modules", "__pycache__", ".git", "out")]',
    '    for f in fs:',
    '        if f.endswith(".py"):',
    '            try: tree = ast.parse(open(os.path.join(root, f), encoding="utf-8").read())',
    '            except Exception: continue',
    '            for n in ast.walk(tree):',
    '                if isinstance(n, ast.Import):',
    '                    for a in n.names: mods.add(a.name.split(".")[0])',
    '                elif isinstance(n, ast.ImportFrom) and n.level == 0 and n.module:',
    '                    mods.add(n.module.split(".")[0])',
    'local = {os.path.splitext(f)[0] for _, _, fs in os.walk(".") for f in fs if f.endswith(".py")} | {d for d in os.listdir(".") if os.path.isdir(d)}',
    'missing = []',
    'for m in sorted(mods):',
    '    if m in local: continue',
    '    try:',
    '        if importlib.util.find_spec(m) is None: missing.append(m)',
    '    except Exception: pass',
    'print(json.dumps(missing))'
].join('\n');
const PIP_NAMES = { cv2: 'opencv-python-headless', PIL: 'pillow', bs4: 'beautifulsoup4', yaml: 'pyyaml', sklearn: 'scikit-learn', dotenv: 'python-dotenv', dateutil: 'python-dateutil', jwt: 'pyjwt', serial: 'pyserial', skimage: 'scikit-image', Crypto: 'pycryptodome', docx: 'python-docx', pptx: 'python-pptx', fitz: 'pymupdf', telegram: 'python-telegram-bot' };
const PLACEHOLDER_RE = /(^|\n)[ \t]*(\/\/|#|\/\*|<!--|--)[ \t]*(\.\.\.|…|(rest|remainder|remaining)\b[^\n]{0,40}(code|file|implementation|here)|(same|unchanged) as (before|above)|existing code|your code here|code goes here|add (your|the) code)/i;

// an unclosed ``` in the AI's message would swallow everything after it (file cards, warnings) into one code block
function sanitizeFinal(text) {
    let t = String(text || '').trim();
    const fences = (t.match(/^[ \t]*```/gm) || []).length;
    if (fences % 2 === 1) t += '\n```';
    return t;
}
function envBlockHint(text) {   // sign-in / bot / 403 are always "environment"; plain network errors too, unless they talk to localhost (that is a real bug)
    const t = String(text || '');
    if (ENV_STRONG_RE.test(t)) return true;
    return ENV_WEAK_RE.test(t) && !/localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]/.test(t);
}

function applyEdit(content, search, replace) {
    if (!search) return { err: 'search_string is empty.' };
    if (search === replace) return { err: 'search_string and replace_string are identical - nothing to change.' };
    const cnt = (hay, needle) => hay.split(needle).length - 1;
    let n = cnt(content, search);
    if (n === 1) { const i = content.indexOf(search); return { content: content.slice(0, i) + replace + content.slice(i + search.length) }; }
    if (n > 1) return { err: `search_string matches ${n} places in the file. Include more surrounding lines so it matches exactly ONE place.` };
    if (content.indexOf('\r\n') >= 0 && search.indexOf('\r\n') < 0) {   // CRLF file, LF search
        const c2 = content.replace(/\r\n/g, '\n');
        if (cnt(c2, search) === 1) { const i = c2.indexOf(search); return { content: c2.slice(0, i) + replace + c2.slice(i + search.length) }; }
    }
    const cl = content.split('\n');
    const sl = search.replace(/\r\n/g, '\n').split('\n').map(s => s.trim());
    while (sl.length && sl[sl.length - 1] === '') sl.pop();
    while (sl.length && sl[0] === '') sl.shift();
    if (!sl.length) return { err: 'search_string is empty.' };
    const hits = [];
    for (let i = 0; i + sl.length <= cl.length; i++) {
        let ok = true;
        for (let k = 0; k < sl.length; k++) if (cl[i + k].trim() !== sl[k]) { ok = false; break; }
        if (ok) hits.push(i);
    }
    if (hits.length === 1) { cl.splice(hits[0], sl.length, ...String(replace).replace(/\r\n/g, '\n').split('\n')); return { content: cl.join('\n') }; }
    if (hits.length > 1) return { err: `search_string (ignoring indentation) matches ${hits.length} places. Include more surrounding lines.` };
    return { err: 'search_string was NOT found in the file. Call read_file to see the current text, then copy the lines EXACTLY.' };
}

function cleanEnv(ws) {
    const env = {
        PATH: process.env.PATH || '', HOME: ws, TMPDIR: ws, LANG: 'C.UTF-8', LC_ALL: 'C.UTF-8',
        PYTHONUNBUFFERED: '1', PYTHONDONTWRITEBYTECODE: '1', PYTHONIOENCODING: 'utf-8', PYTHONUSERBASE: PY_USER_BASE,
        npm_config_cache: NPM_CACHE, NODE_NO_WARNINGS: '1', CI: '1', PIP_NO_INPUT: '1', PIP_DISABLE_PIP_VERSION_CHECK: '1'
    };
    ['NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'REQUESTS_CA_BUNDLE', 'CURL_CA_BUNDLE'].forEach(k => { if (process.env[k]) env[k] = process.env[k]; });   // CA certificate PATHS only (not secrets): needed behind TLS-inspecting proxies
    if (IS_WIN) { ['SystemRoot', 'windir', 'ComSpec', 'PATHEXT'].forEach(k => { if (process.env[k]) env[k] = process.env[k]; }); env.TEMP = ws; env.TMP = ws; env.USERPROFILE = ws; }
    return env;
}

function killTree(child) {
    try {
        if (IS_WIN) spawn('taskkill', ['/F', '/T', '/PID', String(child.pid)], { stdio: 'ignore', windowsHide: true });
        else { try { process.kill(-child.pid, 'SIGKILL'); } catch (e) { child.kill('SIGKILL'); } }
    } catch (e) {}
}

// one child process: no shell, no stdin, merged stdout+stderr, hard time limit, killed as a whole tree
function runProc(cmd, args, o) {
    return new Promise(resolve => {
        let child, done = false, timedOut = false, out = '', timer = null;
        try {
            child = spawn(cmd, args, { cwd: o.cwd, env: o.env, detached: !IS_WIN, stdio: [o.input != null ? 'pipe' : 'ignore', 'pipe', 'pipe'], windowsHide: true, shell: !!o.shell });
        } catch (e) { return resolve({ error: e, output: '' }); }
        if (o.input != null && child.stdin) { child.stdin.on('error', () => {}); child.stdin.end(String(o.input)); }   // answers for input() / Scanner / readline
        if (o.ctl) o.ctl.proc = child;
        const fin = r => {
            if (done) return; done = true; clearTimeout(timer);
            if (o.ctl && o.ctl.proc === child) o.ctl.proc = null;
            resolve(Object.assign({ output: out, timedOut }, r));
        };
        const onData = d => {
            let s = d.toString('utf8');
            if (out.length >= MAX_OUT) return;
            if (out.length + s.length > MAX_OUT) s = s.slice(0, MAX_OUT - out.length) + TRUNC_NOTE;
            out += s; if (o.onData) o.onData(s);
        };
        child.stdout.on('data', onData); child.stderr.on('data', onData);
        child.on('error', e => fin({ error: e }));
        child.on('close', (code, signal) => fin({ code, signal }));
        timer = setTimeout(() => { timedOut = true; killTree(child); setTimeout(() => fin({ code: null, signal: 'SIGKILL' }), 1500); }, o.timeoutMs || RUN_LIMIT_MS);
    });
}

// ---- every action is shown to the user as a REAL shell command (input first, then output) ----
function shQuote(x) { return "'" + String(x).replace(/'/g, "'\\''") + "'"; }
function heredocDelim(content) { let d = 'EOF'; while (new RegExp('^' + d + '$', 'm').test(content)) d += '_END'; return d; }
function buildWriteCmd(rel, content) {      // create a file:  mkdir -p dir && cat > 'file' << 'EOF' ... EOF
    const dir = path.posix.dirname(rel), delim = heredocDelim(content);
    return { head: (dir && dir !== '.' ? 'mkdir -p ' + shQuote(dir) + ' && ' : '') + 'cat > ' + shQuote(rel) + " << '" + delim + "'", body: '\n' + (content.endsWith('\n') ? content : content + '\n') + delim };
}
function pyStr(x) { x = String(x); return /"""|\\|"$/.test(x) ? JSON.stringify(x) : '"""' + x + '"""'; }
function buildEditScript(rel, search, replace) {   // edit a file: a small python script that replaces exactly one piece of text
    return { head: "python3 - << 'PYEOF'", body: '\np = ' + JSON.stringify(rel) + '\ns = open(p, encoding="utf-8").read()\nold = ' + pyStr(search) + '\nnew = ' + pyStr(replace) + '\nassert s.count(old) == 1, "search text must match exactly once"\nopen(p, "w", encoding="utf-8").write(s.replace(old, new, 1))\nprint("edited " + p)\nPYEOF' };
}
function stdinPrefix(text) {                // printf 'a\nb\n' style pipe in front of the command
    if (!text) return '';
    const lines = text.replace(/\n$/, '').split('\n');
    return "printf '%s\\n' " + lines.slice(0, 30).map(shQuote).join(' ') + (lines.length > 30 ? ' # … +' + (lines.length - 30) + ' more lines' : '') + ' | ';
}
function scanNodeImports(src) {
    const out = new Set(), res = [/require\(\s*['"]([^'"]+)['"]\s*\)/g, /\bfrom\s+['"]([^'"]+)['"]/g, /\bimport\s+['"]([^'"]+)['"]/g, /\bimport\(\s*['"]([^'"]+)['"]\s*\)/g];
    for (const re of res) { let m; while ((m = re.exec(src))) out.add(m[1]); }
    return out;
}
function isPrivateHost(h) {
    h = String(h || '').toLowerCase().replace(/^\[|\]$/g, '');
    return h === 'localhost' || h === '::1' || h === '0.0.0.0' || /^127\./.test(h) || /^10\./.test(h) || /^192\.168\./.test(h) || /^172\.(1[6-9]|2\d|3[01])\./.test(h) || /^169\.254\./.test(h) || /\.(internal|local|localhost)$/.test(h) || h === 'metadata.google.internal';
}

// ----------------------------------------------------------------------------
// Factory
// ----------------------------------------------------------------------------
const PIP_DIR = path.join(os.tmpdir(), 'agent-pip');
const pipJsonUrl = () => process.env.AGENT_PIP_JSON_URL || 'https://pypi.org/pypi/pip/json';
// run pip from a downloaded wheel (pip supports running straight from the .whl)
const PIP_BOOT = 'import sys; sys.path.insert(0, sys.argv.pop(1)); from pip._internal.cli.main import main; sys.exit(main(sys.argv[1:]))';
function pipArgs(pm, extra) { return pm.kind === 'wheel' ? ['-c', PIP_BOOT, pm.wheel].concat(extra) : ['-m', 'pip'].concat(extra); }
async function fetchTimeout(url, ms) {
    const ac = new AbortController(), t = setTimeout(() => ac.abort(new Error('timed out')), ms);
    try { const r = await fetch(url, { signal: ac.signal }); if (!r.ok) throw new Error('HTTP ' + r.status + ' from ' + url); return r; } finally { clearTimeout(t); }
}

module.exports = function createCodingAgent(deps) {
    deps = deps || {};
    const pipState = { kind: null, wheel: '', at: 0, why: '' };   // 'module' | 'wheel' | 'none'
    const getProviders = deps.getProviders || (() => []);

    function buildPool(tier, ctx) {
        const order = tier === 'cheap' ? MODELS_CHEAP : MODELS_STRONG;
        const num = p => +((/API (\d)/.exec(p.id || '') || [0, 0])[1]);
        const rank = m => { const i = order.indexOf(m); return i < 0 ? 99 : i; };
        const slow = (ctx && ctx.slowModels) || new Set(), sticky = (ctx && ctx.sticky) || {};
        const list = getProviders().filter(p => p.type === 'gemini' && p.key).slice().sort((a, b) =>
            (slow.has(a.modelId) - slow.has(b.modelId)) || rank(a.modelId) - rank(b.modelId) ||
            (a.modelId === 'gemini-3.6-flash' ? num(b) - num(a) : num(a) - num(b)));   // 3.6 Flash: API 5 first, keeps API 1-2 free for the light model
        const out = [], seen = new Set();
        for (const p of list) {            // inside each model: the key that worked last time goes first
            if (seen.has(p.modelId)) continue; seen.add(p.modelId);
            const grp = list.filter(x => x.modelId === p.modelId), st = sticky[p.modelId];
            if (st && grp.includes(st)) out.push(st, ...grp.filter(x => x !== st)); else out.push(...grp);
        }
        return out;
    }

    const isBusy = e => /high demand|overload|unavailable|503|429|resource.?exhausted|quota|rate.?limit|try again|temporar|timed? ?out|stalled|fetch failed|ECONNRESET|ETIMEDOUT|socket|network|empty response/i.test(String(e && e.message));

    // ---------------- one streamed Gemini turn (function calling) ----------------
    async function streamTurn(ctx, p, contents, o) {
        const payload = { contents: o.prepContents(contents, p.modelId), generationConfig: {} };
        if (ctx.maxOut) payload.generationConfig.maxOutputTokens = ctx.maxOut;   // without it thinking can eat the output and the tool call gets cut off
        if (o.system) payload.systemInstruction = { parts: [{ text: o.system }] };
        if (o.tools) payload.tools = [{ functionDeclarations: o.tools }];
        if (o.tools && o.noTools) payload.toolConfig = { functionCallingConfig: { mode: 'NONE' } };
        else if (o.tools && o.forceTools) payload.toolConfig = { functionCallingConfig: { mode: 'ANY', allowedFunctionNames: o.forceTools } };   // "you MUST call a tool"
        if (o.withThoughts) payload.generationConfig.thinkingConfig = { includeThoughts: true, thinkingBudget: o.budget };

        const ac = new AbortController(); ctx.ctl.fetchAc = ac;
        const to = setTimeout(() => ac.abort(new Error('Gemini request timed out')), 200000);
        let lastData = Date.now();
        const idle = setInterval(() => {   // watchdog: a silent / hung connection must not freeze the whole agent
            if (Date.now() - lastData > IDLE_MS) ac.abort(new Error(`Gemini stalled (no data for ${Math.round(IDLE_MS / 1000)}s)`));
        }, Math.min(3000, Math.max(200, IDLE_MS / 4)));
        try {
            const up = await fetch(`${GEMINI_BASE}/v1beta/models/${p.modelId}:streamGenerateContent?alt=sse&key=${p.key}`, {
                method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), signal: ac.signal
            });
            lastData = Date.now();
            if (!up.ok || !up.body) {
                let m = `Gemini failed (${up.status})`;
                try { m = JSON.parse(await up.text()).error.message || m; } catch (e) {}
                throw new Error(m);
            }
            const reader = up.body.getReader(), dec = new TextDecoder('utf-8');
            let buf = '', text = '', finish = '', thoughtChars = 0;
            const histParts = [], calls = [];
            while (true) {
                const { done, value } = await reader.read(); if (done) break;
                lastData = Date.now();
                buf += dec.decode(value, { stream: true });
                const evs = buf.split(/\r?\n\r?\n/); buf = evs.pop() || '';
                for (const ev of evs) {
                    const i = ev.indexOf('{'); if (i < 0) continue;
                    let j; try { j = JSON.parse(ev.slice(i)); } catch (e) { continue; }
                    if (j.error) throw new Error(j.error.message || 'Gemini stream error');
                    const cand = j.candidates && j.candidates[0];
                    if (cand && cand.finishReason) finish = cand.finishReason;
                    for (const part of ((cand && cand.content && cand.content.parts) || [])) {
                        if (part.functionCall) {
                            const keep = Object.assign({}, part); delete keep.thought;   // keep the WHOLE part: it carries the thoughtSignature Gemini 3 needs back
                            histParts.push(keep); calls.push(keep);
                        } else if (part.text) {
                            if (part.thought) {
                                thoughtChars += part.text.length;
                                if (thoughtChars > MAX_THOUGHT_CHARS) throw new Error('thinking too long');   // runaway thinking -> retry with thinking off
                                if (o.onThought) o.onThought(part.text);
                            } else {
                                text += part.text;
                                const last = histParts[histParts.length - 1];
                                if (last && last.text !== undefined && !last.functionCall) last.text += part.text; else histParts.push({ text: part.text });
                            }
                        }
                    }
                }
            }
            if (!histParts.length) {
                if (/SAFETY|PROHIBITED|BLOCKLIST|RECITATION|SPII/.test(finish)) throw new Error('Gemini blocked this request (' + finish + ')');
                if (!finish && !thoughtChars) throw new Error('Empty response (connection cut)');
                // the model produced NOTHING usable (typical: MALFORMED_FUNCTION_CALL / MAX_TOKENS because the file was too big).
                // Do NOT retry every key for this - hand it back so the loop can tell the model what went wrong.
                return { text: '', histParts: [], calls: [], finish: finish || 'EMPTY', provider: p };
            }
            return { text, histParts, calls, finish, provider: p };
        } finally { clearTimeout(to); clearInterval(idle); ctx.ctl.fetchAc = null; try { ac.abort(); } catch (e) {} }
    }

    // tries every key/model; thoughts on -> thoughts off; a model that hangs is skipped; waits and retries while Gemini is busy
    async function callModel(ctx, contents, o) {
        const rounds = 4, waits = [2500, 5000, 9000];
        const started = Date.now(), skip = new Set();
        let lastErr = null;
        for (let round = 0; round < rounds; round++) {
            skip.clear();
            ctx.pool = buildPool(o.tier || 'strong', ctx);
            for (const p of ctx.pool.slice()) {
                if (skip.has(p.modelId)) continue;
                let withThoughts = o.thoughts !== false;
                for (let attempt = 0; attempt < 5; attempt++) {
                    if (ctx.ctl.aborted) throw new Error('aborted');
                    try {
                        if (o.onModel) o.onModel(p);
                        const r = await streamTurn(ctx, p, contents, Object.assign({}, o, { withThoughts }));
                        ctx.histModel = p.modelId;
                        ctx.sticky[p.modelId] = p;   // sticky: inside a model keep using the key that works
                        return r;
                    } catch (e) {
                        lastErr = e;
                        if (ctx.ctl.aborted) throw e;
                        const msg = String(e && e.message);
                        if (/signature/i.test(msg) && ctx.sigMode !== 'skip') { ctx.sigMode = 'skip'; continue; }        // retry the same key with the skip-validation signature
                        if (ctx.maxOut && /max.?output.?tokens|output token|too large/i.test(msg)) { ctx.maxOut = ctx.maxOut > 16384 ? 16384 : (ctx.maxOut > 8192 ? 8192 : 0); continue; }   // this model has a smaller output cap
                        if (withThoughts && /thinking|thought|budget/i.test(msg)) { withThoughts = false; continue; }   // no thinking config / thinking loop -> retry without it
                        if (/not found|404|unsupported|does not exist/i.test(msg)) { // 🚀 FAST FAILOVER: Model not found on API, skip across ALL keys instantly!
                            skip.add(p.modelId);
                            ctx.slowModels.add(p.modelId);
                            break;
                        }
                        if (/stalled|timed out/i.test(msg)) {                                                           // model is hanging: skip ALL keys of that model, try the next model
                            skip.add(p.modelId);
                            ctx.slowModels.add(p.modelId);   // and try it last next time
                            if (o.onNotice) o.onNotice(`⚠️ ${p.modelId} is not answering — switching to another model…`);
                        }
                        break;                                                                                         // anything else: next key / model
                    }
                }
            }
            if (ctx.ctl.aborted) throw new Error('aborted');
            if (!isBusy(lastErr) || round === rounds - 1 || Date.now() - started > 300000) throw lastErr;
            const wait = waits[Math.min(round, waits.length - 1)];
            if (o.onNotice) o.onNotice(`⏳ Gemini is busy (high demand) — retrying in ${Math.round(wait / 1000)}s… (${round + 1}/${rounds - 1})`);
            await new Promise(r => setTimeout(r, wait));
        }
        throw lastErr;
    }

    // Gemini 3 validates thought signatures. If we ever continue a conversation with a DIFFERENT model than the one that
    // produced it (key/model fallback), swap in Google's documented "skip validation" value so the call is not rejected.
    function withUserText(history, text) {   // never send two user turns in a row
        const last = history[history.length - 1];
        if (last && last.role === 'user') return history.slice(0, -1).concat([{ role: 'user', parts: last.parts.concat([{ text }]) }]);
        return history.concat([{ role: 'user', parts: [{ text }] }]);
    }
    function makePrep(ctx) {
        return (contents, modelId) => {
            const skip = ctx.sigMode === 'skip' || (ctx.histModel && ctx.histModel !== modelId);
            if (!skip) return contents;
            return contents.map(c => {
                if (c.role !== 'model') return c;
                let first = true;
                return { role: c.role, parts: c.parts.map(p => {
                    if (!p.functionCall) return p;
                    const had = p.thoughtSignature, isFirst = first; first = false;
                    return (had || (ctx.sigMode === 'skip' && isFirst)) ? Object.assign({}, p, { thoughtSignature: 'skip_thought_signature_validator' }) : p;
                }) };
            });
        };
    }

    // ------------------------------------------------------------------------
    // run()  -  the whole agent for one request
    // ------------------------------------------------------------------------
    async function run(opts) {
        const prompt = String(opts.prompt || '').trim();
        const lang = opts.lang || 'the same language the user wrote in';
        const rawSend = opts.send || (() => {});
        let lastSend = Date.now();
        const send = e => { lastSend = Date.now(); rawSend(e); };
        const isHindi = /hindi|हिंदी|हिन्दी/i.test(String(opts.lang || '')) || /[\u0900-\u097F]/.test(String(opts.prompt || ''));
        const T = isHindi ? {
            working: s => `✍️ AI अभी भी काम कर रहा है… ${s}s` + (s > 40 ? ' (बड़ी फ़ाइल लिखी जा रही है, कृपया रुकें)' : ''),
            forgot: '🔁 AI ने सिर्फ़ बताया, फ़ाइल नहीं लिखी — दोबारा कह रहा हूँ…',
            cut: '✂️ AI का जवाब बीच में कट गया — छोटी फ़ाइलों में बाँटकर दोबारा करवा रहा हूँ…',
            noFiles: '😕 इस बार AI कोड फ़ाइल नहीं बना पाया (वह सिर्फ़ बताता रहा)। कृपया वही सवाल एक बार फिर भेजें, या उसे थोड़ा छोटा/आसान करके पूछें।',
            yt: '⚠️ ज़रूरी: यह सर्वर Hugging Face पर चलता है। यहाँ YouTube से वीडियो/ऑडियो डाउनलोड करना ब्लॉक है ("Sign in to confirm you\'re not a bot" / 403 error), इसलिए डाउनलोड वाला हिस्सा यहाँ टेस्ट नहीं हो सका (बाकी कोड मैंने चलाकर टेस्ट किया)। इसे अपने कंप्यूटर पर चलाएँ, वहाँ यह चलना चाहिए।',
            net: '⚠️ ज़रूरी: यह सर्वर Hugging Face पर चलता है, जिसे कई वेबसाइटें ब्लॉक कर देती हैं (बॉट प्रोटेक्शन, 403/429, नेटवर्क ब्लॉक)। इस कोड का ऑनलाइन हिस्सा यहाँ टेस्ट नहीं हो सका और error दे सकता है — कृपया इसे अपने कंप्यूटर पर चलाएँ।',
            gui: '⚠️ ध्यान दें: इस कोड को स्क्रीन / साउंड डिवाइस चाहिए, जो Hugging Face सर्वर पर नहीं है, इसलिए मैंने सिर्फ़ syntax चेक किया। इसे अपने कंप्यूटर पर चलाएँ।'
        } : {
            working: s => `✍️ The AI is still working… ${s}s` + (s > 40 ? ' (writing a big file, please wait)' : ''),
            forgot: '🔁 The AI only described the plan and wrote no file — asking it again…',
            cut: '✂️ The AI answer was cut off — asking it again with smaller files…',
            noFiles: '😕 This time the AI did not manage to create the code files (it only kept describing them). Please send the same request once more, or make it a bit smaller/simpler.',
            yt: '⚠️ Important: this server runs on Hugging Face. Downloading videos/audio from YouTube is blocked here ("Sign in to confirm you\'re not a bot" / 403 errors), so the download itself could not be tested here (I ran and tested the rest of the code). It should work when you run it on your own computer.',
            net: '⚠️ Important: this server runs on Hugging Face, which many websites block (bot protection, 403/429, blocked network). The online part of this code could not be tested here and may show errors — please run it on your own computer.',
            gui: '⚠️ Note: this code needs a screen / sound device, which the Hugging Face server does not have, so I could only check its syntax. Run it on your own computer.'
        };
        const warn = { yt: false, net: false, gui: false };
        const res = opts.res;
        const seedFiles = Array.isArray(opts.files) ? opts.files : [];
        const ctl = { aborted: false, proc: null, fetchAc: null };
        const abort = () => {
            ctl.aborted = true;
            try { if (ctl.proc) killTree(ctl.proc); } catch (e) {}
            try { if (ctl.fetchAc) ctl.fetchAc.abort(new Error('aborted')); } catch (e) {}
        };
        if (res && res.on) res.on('close', () => { if (!res.writableEnded) abort(); });

        const pool = buildPool('strong', null);
        if (!pool.length) throw new Error('No Gemini API keys configured.');
        const ctx = { pool, ctl, histModel: null, sigMode: '', maxOut: FIRST_MAX_OUTPUT, slowModels: new Set(), sticky: {} };   // maxOut: without it thinking can eat the output and the tool call is cut off
        const prep = makePrep(ctx);

        const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'agentws-'));
        const env = cleanEnv(ws);
        const files = new Map();      // rel -> { content, isNew, edited }
        const touched = new Set();    // files written/edited by the agent
        let wsBytes = 0, pkgJsonMade = false;

        // ---- step / command helpers (events the page already understands) ----
        const stepEv = (id, label, state) => send({ type: 'step', id, label, state: state || 'start' });
        const counters = {}, uid = b => { counters[b] = (counters[b] || 0) + 1; return counters[b] === 1 ? b : b + counters[b]; };
        const cmdIds = {}, cmdId = k => { cmdIds[k] = (cmdIds[k] || 0) + 1; return k + cmdIds[k]; };
        let stepKind = null, stepId = null, stepLabel = '';
        const useStep = (kind, label) => {
            if (stepKind === kind) return stepId;
            closeStep(); stepKind = kind; stepLabel = label; stepId = uid(kind); stepEv(stepId, label); return stepId;
        };
        const closeStep = () => { if (stepId) stepEv(stepId, stepLabel, 'done'); stepId = null; stepKind = null; };
        const streamText = (type, id, text) => { for (const c of chunkLines(text, 25)) send({ type, id, text: c }); };

        // ---- bookkeeping for the test/present gate ----
        let seq = 0, lastEditSeq = 0, lastTestSeq = 0, lastTestOk = null, lastTestUnverifiable = false;
        let failStreak = 0, envFails = 0, gateWarned = 0, presentNudged = 0, presentedOnce = false, forceFinish = false;
        const editFails = {}, placeholderWarned = {};
        const renamed = [], deleted = [];   // reported to the page so its per-conversation file list stays exact
        let searches = 0;
        let presentedList = null;

        function seed() {
            for (const f of seedFiles.slice(0, MAX_FILES)) {
                const rel = safeRel(f && f.name); if (!rel || typeof f.content !== 'string') continue;
                const content = f.content.slice(0, MAX_SEED_BYTES), truncated = f.content.length > MAX_SEED_BYTES;
                const kind = f.kind === 'document' ? 'document' : 'code', origin = f.origin === 'agent' ? 'agent' : 'user';
                // an old upload bug destroyed ALL line breaks of uploaded code ("1 lines"). Editing such a file corrupts it (a // comment swallows the rest).
                const collapsed = kind === 'code' && /\.(js|mjs|cjs|ts|jsx|tsx|html?|css|py|java|php|rb|go|rs|c|cpp|cs|sql|sh|vue)$/i.test(rel) && content.length > 2000 && content.split('\n').length < content.length / 800;
                files.set(rel, { content, isNew: false, edited: false, origin, kind, collapsed, truncated, orig: kind === 'code' ? content : undefined }); wsBytes += Buffer.byteLength(content);
                if (kind === 'document') continue;            // extracted text of a PDF/Word file: readable through the tools, not a real file on disk
                fs.mkdirSync(path.dirname(path.join(ws, rel)), { recursive: true });
                fs.writeFileSync(path.join(ws, rel), content);
            }
        }
        function putFile(rel, content) {
            const prev = files.get(rel);
            const nb = wsBytes - (prev ? Buffer.byteLength(prev.content) : 0) + Buffer.byteLength(content);
            if (nb > MAX_WS_BYTES) throw new Error('Workspace size limit reached.');
            wsBytes = nb;
            const full = path.join(ws, rel);
            if (!full.startsWith(ws + path.sep)) throw new Error('Bad path');
            fs.mkdirSync(path.dirname(full), { recursive: true });
            fs.writeFileSync(full, content);
            files.set(rel, { content, isNew: prev ? prev.isNew : true, edited: prev ? true : false, origin: prev ? prev.origin : 'agent', kind: 'code', orig: prev ? prev.orig : undefined, baseKeys: prev ? prev.baseKeys : undefined });
            touched.add(rel);
        }
        const touchedCode = () => [...touched].some(isCodeFile);

        // ---- cheap local checks (syntax / balanced tags / cut-off) -------------------------------------------------
        // They run right after every write/edit so the AI sees a syntax error in the SAME turn (no extra model request), and problems that
        // were ALREADY in a file the user uploaded are remembered as the "baseline" and ignored - the AI only has to fix what IT broke.
        const keyOf = i => String(i).replace(/line \d+/g, 'line N').replace(/\(\d+ opened, \d+ closed\)/g, '').replace(/\d+ opened.*$/, '');
        async function staticIssuesOf(name, content) {
            const ext = (name.split('.').pop() || '').toLowerCase(), issues = [];
            if (!/^(js|mjs|cjs|py|json|html?|css)$/.test(ext)) return issues;
            const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'agentchk-'));
            try {
                const f = path.join(dir, 'f.' + ext); fs.writeFileSync(f, content);
                if (/^(js|mjs|cjs)$/.test(ext)) {
                    const r = await runProc(process.execPath, ['--check', f], { cwd: dir, env, timeoutMs: 20000, ctl });
                    if (!r.error && r.code !== 0) { const ln = /f\.\w+:(\d+)/.exec(r.output || ''), er = /^(\w*Error: .*)$/m.exec(r.output || ''); issues.push('JavaScript ' + (ln ? 'line ' + ln[1] + ': ' : '') + (er ? er[1] : 'syntax error')); }
                } else if (ext === 'py') {
                    const r = await tryPy(['-c', 'import ast,sys\ntry:\n    ast.parse(open(sys.argv[1],encoding="utf-8").read())\nexcept SyntaxError as e:\n    print("line %s: SyntaxError: %s" % (e.lineno, e.msg)); sys.exit(1)', f], { cwd: dir, env, timeoutMs: 20000, ctl });
                    if (r && !r.error && r.code !== 0) issues.push('Python ' + String(r.output).trim().split('\n').pop());
                } else if (ext === 'json') {
                    try { JSON.parse(content); } catch (e) { issues.push('Invalid JSON: ' + e.message); }
                } else if (deps.agentChecks) {
                    try { const ck = deps.agentChecks([{ path: name, content }]); (ck.errors || []).forEach(e => issues.push(e)); } catch (e) {}
                }
            } finally { try { fs.rmSync(dir, { recursive: true, force: true }); } catch (e) {} }
            return issues;
        }
        async function newIssues(rel) {
            const v = files.get(rel), cur = await staticIssuesOf(rel, v.content);
            if (v.orig != null && v.orig === v.content) return { fresh: [], old: cur.length };   // untouched upload: its old problems are not ours
            let base = [];
            if (v.orig != null) { if (!v.baseKeys) v.baseKeys = (await staticIssuesOf(rel, v.orig)).map(keyOf); base = v.baseKeys; }
            const fresh = cur.filter(i => !base.includes(keyOf(i)));
            return { fresh, old: cur.length - fresh.length };
        }
        async function quickCheck(rel) {
            if (!/\.(js|mjs|cjs|py|json|html?|css)$/i.test(rel)) return { clean: true, text: '' };
            try {
                const r = await newIssues(rel);
                if (r.fresh.length) return { clean: false, text: 'Auto-check ✗ problems in ' + rel + ' (fix them with edit_code):\n' + r.fresh.slice(0, 8).map(x => '- ' + x).join('\n') };
                return { clean: true, text: 'Auto-check ✓ ' + rel + ': no syntax problems' + (r.old ? ` (${r.old} older problem(s) that were already in the uploaded file are ignored)` : '') };
            } catch (e) { return { clean: true, text: '' }; }
        }

        // ====================== TOOL: write_code ======================
        async function toolWrite(args) {
            const rel = safeRel(args.filename);
            if (!rel) return { err: true, result: `Error: invalid filename "${args.filename}". Use a simple relative path like app.py or games/snake.html.` };
            const content = typeof args.content === 'string' ? args.content : '';
            if (!content.trim()) return { err: true, result: 'Error: content is empty. Write the COMPLETE file.' };
            if (Buffer.byteLength(content) > MAX_FILE_BYTES) return { err: true, result: `Error: file is larger than ${MAX_FILE_BYTES} bytes. Split it into several smaller files.` };
            if (!files.has(rel) && files.size >= MAX_FILES) return { err: true, result: `Error: too many files (max ${MAX_FILES}).` };
            if (files.has(rel) && files.get(rel).kind === 'document') return { err: true, result: `Error: "${rel}" is an uploaded document (read-only text). Use another file name.` };
            if (files.has(rel) && (editFails[rel] || 0) < 2)
                return { err: true, result: `Error: "${rel}" already exists. NEVER rewrite an existing file with write_code - use edit_code with the exact lines that change (call read_file first if unsure).` };
            if (isCodeFile(rel) && PLACEHOLDER_RE.test(content) && !placeholderWarned[rel]) {
                placeholderWarned[rel] = true;
                return { err: true, result: `Error: "${rel}" contains a placeholder comment (like "// rest of the code" or "..."). NO TRUNCATION: call write_code again with the ENTIRE, complete file.` };
            }
            if (/\.(js|mjs|cjs|ts|jsx|tsx|html?|css|py|java|c|cpp|cs|go|rs|php|rb|sql|sh|vue)$/i.test(rel) && !/\.min\./i.test(rel) && content.length > 3000 && content.split('\n').length < content.length / 800)
                return { err: true, result: `Error: "${rel}" is written as one giant line (almost no line breaks). NEVER minify or put a file on one line. Rewrite it as normal, readable code: one statement per line, indentation, one block per line break, and every // comment must end at the end of its line.` };
            const id = cmdId('w');
            useStep('build', 'Building');
            const wc = buildWriteCmd(rel, content);                       // a REAL create-file command ...
            send({ type: 'command', id, step: stepId, title: 'Running a command', cmd: wc.head });
            streamText('cmd_input', id, wc.body);                         // ... followed by the file content the AI writes
            putFile(rel, content);
            seq++; lastEditSeq = seq;
            const qc = await quickCheck(rel);
            send({ type: 'cmd_output', id, text: qc.text });
            const lines = content.split('\n').length;
            return { cheapOk: qc.clean, result: `Success: wrote ${rel} (${lines} lines). ` + (qc.text ? qc.text + '\n' : '') + (!qc.clean ? 'Fix the problem(s) above with edit_code.' : (isCodeFile(rel) ? 'NOW call execute_code to test it (write any other files you need first; imports are installed automatically).' : 'This is not executable; test the main file with execute_code once all files are written.')) };
        }

        // ====================== TOOL: edit_code ======================
        async function toolEdit(args) {
            const rel = safeRel(args.filename);
            if (!rel || !files.has(rel)) return { err: true, result: `Error: file "${args.filename}" does not exist. Existing files: ${[...files.keys()].join(', ') || '(none)'}. Use write_code for NEW files.` };
            if (files.get(rel).kind === 'document') return { err: true, result: `Error: "${rel}" is an uploaded document (read-only text) and cannot be edited.` };
            if (files.get(rel).collapsed) return { err: true, result: `Error: "${rel}" was uploaded with ALL its line breaks destroyed (an old upload bug - the whole file is on one line). Editing it would corrupt it (a // comment swallows the rest of the line). Do NOT edit it. Tell the user in your final message to remove the attachment and upload the file again.` };
            if (files.get(rel).truncated) return { err: true, result: `Error: "${rel}" is larger than ${MAX_SEED_BYTES} bytes and was cut off when it was loaded, so it cannot be edited safely.` };
            const search = typeof args.search_string === 'string' ? args.search_string : '';
            const replace = typeof args.replace_string === 'string' ? args.replace_string : '';
            const fixing = lastTestOk === false;
            const id = cmdId('e');
            useStep(fixing ? 'fix' : 'edit', fixing ? 'Fixing' : 'Editing files');
            const ec = buildEditScript(rel, search, replace);
            send({ type: 'command', id, step: stepId, title: 'Running a command', cmd: ec.head });
            streamText('cmd_input', id, ec.body);
            const r = applyEdit(files.get(rel).content, search, replace);
            if (r.err) {
                editFails[rel] = (editFails[rel] || 0) + 1;
                send({ type: 'cmd_output', id, text: 'AssertionError: ' + r.err });
                return { err: true, result: 'Failed to edit: ' + r.err + (editFails[rel] >= 2 ? ' (After 2 failed edits you are now allowed to rewrite this file completely with write_code.)' : '') };
            }
            putFile(rel, r.content);
            editFails[rel] = 0; seq++; lastEditSeq = seq;
            const qc = await quickCheck(rel);
            send({ type: 'cmd_output', id, text: 'edited ' + rel + (qc.text ? '\n' + qc.text : '') });
            return { cheapOk: qc.clean, result: `Success: edited ${rel}. ` + (qc.text ? qc.text + '\n' : '') + (qc.clean ? 'NOW call execute_code again to test it.' : 'Fix the problem(s) above with edit_code.') };
        }

        // ====================== TOOL: read_file ======================
        async function toolRead(args) {
            const rel = safeRel(args.filename);
            if (!rel || !files.has(rel)) return { err: true, result: `Error: file "${args.filename}" does not exist. Existing files: ${[...files.keys()].join(', ') || '(none)'}.` };
            const id = cmdId('v');
            useStep('check', 'Checking files');
            const c = files.get(rel).content, a0 = parseInt(args.start_line), b0 = parseInt(args.end_line);
            let text = c, note = '', cmd = 'cat ' + shQuote(rel);
            let big = !(a0 > 0 || b0 > 0) && c.length > 40000;   // never dump a huge file: show the start and tell how to navigate
            if (a0 > 0 || b0 > 0 || big) {
                const L = c.split('\n'), from = Math.max(1, a0 || 1), to = Math.min(L.length, b0 || (big ? 250 : L.length));
                text = L.slice(from - 1, to).join('\n'); note = `(lines ${from}-${to} of ${L.length}${big ? '; the file is large (' + Math.round(c.length / 1024) + ' KB) - read other parts with start_line/end_line or find things with search_in_files' : ''})\n`; cmd = `sed -n '${from},${to}p' ${shQuote(rel)}`;
            }
            send({ type: 'command', id, step: stepId, title: 'Running a command', cmd });
            send({ type: 'cmd_output', id, text: note + (text.length > 8000 ? text.slice(0, 8000) + '\n…' : text) });
            return { result: `Contents of ${rel}${files.get(rel).kind === 'document' ? ' (uploaded document, read-only text)' : ''}:\n${note}${clipMid(text, 60000)}` };
        }

        // ====================== TOOL: list_files ======================
        const originLabel = v => v.collapsed ? 'uploaded by the user ⚠ LINE BREAKS LOST - do not edit, ask the user to upload it again' : v.kind === 'document' ? 'uploaded document (read-only)' : (v.origin === 'user' ? 'uploaded by the user' + (v.edited ? ' (edited by you in this run)' : '') : (v.isNew ? 'created by you in this run' : 'created by you earlier'));
        const inScope = (v, scope) => scope === 'user' ? v.origin === 'user' : scope === 'agent' ? v.origin === 'agent' : true;
        async function toolList(args) {
            const scope = /^(user|agent)$/i.test(String(args.scope || '')) ? String(args.scope).toLowerCase() : 'all';
            const id = cmdId('l');
            useStep('list', 'Listing files');
            send({ type: 'command', id, step: stepId, title: 'Running a command', cmd: 'ls -l' + (scope === 'all' ? '' : '   # ' + scope + ' files only') });
            const rows = [...files].filter(([k, v]) => inScope(v, scope)).map(([k, v]) => `${k}\t${originLabel(v)}\t${Buffer.byteLength(v.content)} bytes\t${v.content.split('\n').length} lines`);
            const text = rows.length ? 'name\torigin\tsize\tlines\n' + rows.join('\n') : '(no files' + (scope === 'all' ? '' : ' from ' + scope) + ' in this conversation)';
            send({ type: 'cmd_output', id, text });
            return { result: `Files of this conversation (${scope}): ${rows.length}\n${text}` };
        }

        // ====================== TOOL: search_in_files ======================
        async function toolGrep(args) {
            const pat = String(args.pattern == null ? '' : args.pattern);
            if (!pat) return { err: true, result: 'Error: pattern is empty.' };
            const scope = /^(user|agent)$/i.test(String(args.scope || '')) ? String(args.scope).toLowerCase() : 'all';
            let re;
            try { re = new RegExp(args.regex ? pat : pat.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), args.case_sensitive ? '' : 'i'); }
            catch (e) { return { err: true, result: 'Error: invalid regular expression: ' + e.message }; }
            const id = cmdId('g');
            useStep('grep', 'Searching files');
            send({ type: 'command', id, step: stepId, title: 'Running a command', cmd: 'grep -rn' + (args.case_sensitive ? '' : 'i') + (args.regex ? 'E ' : 'F ') + shQuote(pat) + ' .' });
            const hits = []; let total = 0;
            for (const [k, v] of files) {
                if (!inScope(v, scope)) continue;
                v.content.split('\n').forEach((line, i) => { if (re.test(line)) { total++; if (hits.length < 60) hits.push(`${k}:${i + 1}: ${line.trim().slice(0, 200)}`); } });
            }
            const text = total ? hits.join('\n') + (total > hits.length ? `\n… ${total - hits.length} more matches` : '') : '(no matches)';
            send({ type: 'cmd_output', id, text });
            return { result: `${total} match(es) for "${pat}":\n${text}` };
        }

        // ====================== TOOL: rename_file / delete_file ======================
        async function toolRename(args) {
            const from = safeRel(args.from), to = safeRel(args.to);
            if (!from || !files.has(from)) return { err: true, result: `Error: "${args.from}" does not exist. Existing files: ${[...files.keys()].join(', ') || '(none)'}.` };
            if (!to) return { err: true, result: `Error: invalid new name "${args.to}".` };
            const old = files.get(from);
            if (old.kind === 'document') return { err: true, result: `Error: "${from}" is an uploaded document and cannot be renamed.` };
            if (files.has(to)) return { err: true, result: `Error: "${to}" already exists. Pick another name or delete it first.` };
            const id = cmdId('m');
            useStep('rename', 'Renaming files');
            send({ type: 'command', id, step: stepId, title: 'Running a command', cmd: 'mv ' + shQuote(from) + ' ' + shQuote(to) });
            const full = path.join(ws, to); if (!full.startsWith(ws + path.sep)) return { err: true, result: 'Error: bad path' };
            fs.mkdirSync(path.dirname(full), { recursive: true }); fs.writeFileSync(full, old.content);
            try { fs.unlinkSync(path.join(ws, from)); } catch (e) {}
            files.delete(from); files.set(to, Object.assign({}, old, { edited: true }));
            touched.delete(from); touched.add(to);
            const prior = renamed.find(r => r.to === from); if (prior) prior.to = to; else renamed.push({ from, to });
            seq++; lastEditSeq = seq;
            send({ type: 'cmd_output', id, text: `renamed ${from} -> ${to}` });
            return { result: `Renamed ${from} -> ${to}. If other files reference the old name (imports, <script src>, <link href>, links), find them with search_in_files and fix them with edit_code, then call execute_code again.` };
        }
        async function toolDelete(args) {
            const rel = safeRel(args.filename);
            if (!rel || !files.has(rel)) return { err: true, result: `Error: "${args.filename}" does not exist. Existing files: ${[...files.keys()].join(', ') || '(none)'}.` };
            if (files.get(rel).kind === 'document') return { err: true, result: `Error: "${rel}" is an uploaded document and cannot be deleted.` };
            const id = cmdId('d');
            useStep('delete', 'Deleting files');
            send({ type: 'command', id, step: stepId, title: 'Running a command', cmd: 'rm ' + shQuote(rel) });
            try { fs.unlinkSync(path.join(ws, rel)); } catch (e) {}
            wsBytes -= Buffer.byteLength(files.get(rel).content); files.delete(rel); touched.delete(rel);
            if (presentedList) presentedList = presentedList.filter(n => n !== rel);
            const rn = renamed.findIndex(r => r.to === rel); if (rn >= 0) { deleted.push(renamed[rn].from); renamed.splice(rn, 1); } else deleted.push(rel);
            seq++; lastEditSeq = seq;
            send({ type: 'cmd_output', id, text: `removed ${rel}` });
            return { result: `Deleted ${rel}. Remaining files: ${[...files.keys()].join(', ') || '(none)'}. If other files used it, fix those references and test again.` };
        }

        // ====================== TOOL: web_search (Gemini 2.5 Flash + Google Search grounding) ======================
        async function geminiSearch(q) {
            const seenKeys = new Set(), provs = [];
            getProviders().filter(p => p.type === 'gemini' && p.key).sort((a, b) => (b.modelId === 'gemini-2.5-flash') - (a.modelId === 'gemini-2.5-flash')).forEach(p => { if (!seenKeys.has(p.key)) { seenKeys.add(p.key); provs.push(p); } });
            let lastErr = new Error('No Gemini API key configured.');
            for (const p of provs) {
                const ac = new AbortController(); ctl.fetchAc = ac;
                const to = setTimeout(() => ac.abort(new Error('web search timed out')), 45000);
                try {
                    const r = await fetch(`${GEMINI_BASE}/v1beta/models/gemini-2.5-flash:generateContent?key=${p.key}`, {
                        method: 'POST', headers: { 'Content-Type': 'application/json' }, signal: ac.signal,
                        body: JSON.stringify({
                            systemInstruction: { parts: [{ text: 'You are a research helper for a coding agent. Search the web and answer briefly and factually: exact package names, versions, API usage, short code snippets when useful, and the date or version of what you found. No small talk.' }] },
                            contents: [{ role: 'user', parts: [{ text: q }] }], tools: [{ google_search: {} }]
                        })
                    });
                    const j = await r.json().catch(() => ({}));
                    if (!r.ok) throw new Error((j.error && j.error.message) || 'HTTP ' + r.status);
                    const cand = j.candidates && j.candidates[0];
                    const text = ((cand && cand.content && cand.content.parts) || []).map(x => x.text || '').join('').trim();
                    if (!text) throw new Error('the search returned no answer');
                    const gm = (cand && cand.groundingMetadata) || {}, seenU = new Set();
                    const sources = (gm.groundingChunks || []).map(c => c.web).filter(w => w && w.uri && !seenU.has(w.uri) && seenU.add(w.uri)).slice(0, 8);
                    return { text, sources, queries: gm.webSearchQueries || [] };
                } catch (e) { lastErr = e; if (ctl.aborted) throw e; }
                finally { clearTimeout(to); ctl.fetchAc = null; }
            }
            throw lastErr;
        }
        async function toolWebSearch(args) {
            const q = String(args.query || '').trim().slice(0, 300);
            if (!q) return { err: true, result: 'Error: query is empty.' };
            if (searches >= 6) return { err: true, result: 'Error: the limit of 6 web searches per request is used up. Continue with what you know.' };
            searches++;
            const id = cmdId('s');
            useStep('search', 'Searching the web');
            send({ type: 'command', id, step: stepId, title: 'Running a command', cmd: 'web_search ' + shQuote(q) });
            let text;
            try {
                const r = await geminiSearch(q);
                text = r.text + (r.sources.length ? '\n\nSources:\n' + r.sources.map(x => '- ' + (x.title || x.uri) + ' — ' + x.uri).join('\n') : '');
                send({ type: 'cmd_output', id, text });
                return { result: clipMid(text, 9000) };
            } catch (e) {
                if (ctl.aborted) return { err: true, result: 'aborted' };
                send({ type: 'cmd_output', id, text: 'Search failed: ' + e.message });
                return { err: true, result: 'Web search failed (' + e.message + '). Continue without it, using what you know, and tell the user the lookup was not possible.' };
            }
        }

        // ====================== TOOL: execute_code ======================
        const pyList = IS_WIN ? ['python', 'py'] : ['python3', 'python'];
        async function tryPy(args, o) {
            let last = null;
            for (const py of pyList) { const r = await runProc(py, args, o); if (r.error && r.error.code === 'ENOENT') { last = r; continue; } return r; }
            return last;
        }
        // which imported packages are NOT installed yet?  (python: real import check, node: node_modules check)
        async function detectPyMissing() {
            const r = await tryPy(['-c', PY_IMPORT_SCRIPT], { cwd: ws, env, timeoutMs: 20000, ctl });
            let names = []; try { names = JSON.parse(String((r && r.output) || '').trim().split('\n').pop()); } catch (e) {}
            const out = [];
            for (const m of names) { if (NON_PIP.has(m)) continue; const pk = PIP_NAMES[m] || m; if (validDep(pk, 'pip')) out.push(pk); }
            const rq = files.get('requirements.txt');
            if (rq) rq.content.split('\n').map(l => l.split('#')[0].trim()).filter(Boolean).forEach(l => { if (validDep(l, 'pip')) out.push(l); });
            return out;
        }
        function detectNodeMissing() {
            const builtins = new Set(require('module').builtinModules), want = new Set();
            for (const [k, v] of files) if (/\.(m?js|cjs)$/i.test(k)) for (const spec of scanNodeImports(v.content)) {
                if (!spec || spec[0] === '.' || spec[0] === '/' || spec.startsWith('node:')) continue;
                const pkg = spec[0] === '@' ? spec.split('/').slice(0, 2).join('/') : spec.split('/')[0];
                if (builtins.has(pkg) || builtins.has(spec)) continue;
                want.add(pkg);
            }
            const pj = files.get('package.json');
            if (pj) { try { Object.keys(JSON.parse(pj.content).dependencies || {}).forEach(d => want.add(d)); } catch (e) {} }
            return [...want].filter(n => validDep(n, 'npm') && !fs.existsSync(path.join(ws, 'node_modules', n)));
        }
        // Make sure `python3 -m pip` works. Hugging Face style images often have a python WITHOUT pip ("No module named pip").
        // 1) pip already there?  2) ensurepip  3) download the pip wheel from PyPI (no root needed)  4) give up with a clear reason
        async function ensurePip(onData) {
            if (pipState.kind === 'module') return pipState;
            if (pipState.kind === 'wheel' && fs.existsSync(pipState.wheel)) return pipState;
            if (pipState.kind === 'none' && Date.now() - pipState.at < 60000) return pipState;
            const o = { cwd: ws, env, timeoutMs: 60000, ctl };
            const works = async () => { const r = await tryPy(['-m', 'pip', '--version'], o); return r && !r.error && r.code === 0 ? String(r.output).trim() : ''; };
            let v = await works();
            if (v) { pipState.kind = 'module'; return pipState; }
            onData('pip is not installed for this Python ("No module named pip") - setting it up first...\n');
            if (!process.env.AGENT_SKIP_ENSUREPIP) {
                for (const extra of [['--user'], []]) {
                    onData('$ python3 -m ensurepip --default-pip' + (extra.length ? ' --user' : '') + '\n');
                    const r = await tryPy(['-m', 'ensurepip', '--default-pip'].concat(extra), { cwd: ws, env, timeoutMs: 60000, onData, ctl });
                    if (r && !r.error && r.code === 0 && (v = await works())) { onData('pip is ready: ' + v + '\n\n'); pipState.kind = 'module'; return pipState; }
                }
            }
            try {
                onData('$ download the pip wheel from ' + new URL(pipJsonUrl()).host + '\n');
                const meta = await (await fetchTimeout(pipJsonUrl(), 30000)).json();
                const f = (meta.urls || []).find(u => u.packagetype === 'bdist_wheel' && /py3-none-any/.test(u.filename));
                if (!f) throw new Error('no pip wheel found on PyPI');
                onData('Downloading ' + f.filename + ' ...\n');
                const buf = Buffer.from(await (await fetchTimeout(f.url, 90000)).arrayBuffer());
                fs.mkdirSync(PIP_DIR, { recursive: true });
                const wheel = path.join(PIP_DIR, f.filename); fs.writeFileSync(wheel, buf);
                const t = await tryPy(['-c', PIP_BOOT, wheel, '--version'], o);
                if (!(t && !t.error && t.code === 0)) throw new Error('the downloaded pip does not run here: ' + String((t && (t.output || (t.error && t.error.message))) || '').slice(0, 200));
                pipState.kind = 'wheel'; pipState.wheel = wheel;
                onData('pip is ready: ' + String(t.output).trim() + '\n');
                // also install pip itself, so `python3 -m pip` works inside the user's own programs too
                for (const extra of [['--user', '--break-system-packages'], ['--user'], []]) {
                    const r = await tryPy(pipArgs(pipState, ['install', '--disable-pip-version-check', '--no-input', '--progress-bar', 'off'].concat(extra, ['pip'])), { cwd: ws, env, timeoutMs: 90000, ctl });
                    if (r && !r.error && r.code === 0 && (await works())) { pipState.kind = 'module'; break; }
                }
                onData('\n');
                return pipState;
            } catch (e) {
                pipState.kind = 'none'; pipState.at = Date.now(); pipState.why = String(e && e.message || e).slice(0, 200);
                onData('Could not set up pip: ' + pipState.why + '\n');
                return pipState;
            }
        }
        // install as its OWN visible command (pip install ... / npm install ...) - the output shows EVERYTHING (setup, download, install, exit code)
        async function installDeps(language, list, sid) {
            const id = cmdId('i');
            send({ type: 'command', id, step: sid, title: 'Running a command', cmd: (language === 'python' ? 'pip install ' : 'npm install ') + list.join(' ') });
            let out = ''; const onData = x => { out += x; send({ type: 'test', id, text: x }); };
            let ok = false, envInstall = false;
            if (language === 'python') {
                const pm = await ensurePip(onData);
                if (pm.kind === 'none') { envInstall = true; }
                else {
                    let last = null, n = 0;
                    // choose the right flags UP FRONT so the visible log is clean: virtualenv -> plain, Debian "externally managed" -> --user --break-system-packages
                    let first = [];
                    try {
                        const fr = await tryPy(['-c', 'import sys,os,sysconfig,json;print(json.dumps({"venv":sys.prefix!=getattr(sys,"base_prefix",sys.prefix),"em":os.path.exists(os.path.join(sysconfig.get_path("stdlib"),"EXTERNALLY-MANAGED"))}))'], { cwd: ws, env, timeoutMs: 15000, ctl });
                        const fl = JSON.parse(String((fr && fr.output) || '').trim().split('\n').pop());
                        first = fl.venv ? [] : (fl.em ? ['--user', '--break-system-packages'] : []);
                    } catch (e) {}
                    const chain = [first].concat([[], ['--user'], ['--user', '--break-system-packages']].filter(x => x.join() !== first.join()));
                    for (const extra of chain) {
                        if (n++) onData('\n-> retrying: pip install ' + extra.join(' ') + ' ...\n');
                        const r = await tryPy(pipArgs(pm, ['install', '--disable-pip-version-check', '--no-input', '--progress-bar', 'off'].concat(extra, list)), { cwd: ws, env, timeoutMs: 120000, onData, ctl });
                        last = r;
                        if (r && !r.error && r.code === 0) { ok = true; break; }
                        if (!r || r.error || !/externally-managed|permission denied|not visible in this virtualenv|no such option|Errno 13|read-only/i.test(r.output)) break;
                    }
                    onData('\n[exit code ' + (ok ? 0 : (last && last.code != null ? last.code : 1)) + ']\n');
                    if (!ok && last && last.error) onData(last.error.message + '\n');
                }
            } else {
                if (!files.has('package.json') && !fs.existsSync(path.join(ws, 'package.json'))) fs.writeFileSync(path.join(ws, 'package.json'), '{"name":"agent-ws","version":"1.0.0","private":true}');
                const r = await runProc(IS_WIN ? 'npm.cmd' : 'npm', ['install', '--no-audit', '--no-fund', '--ignore-scripts'].concat(list), { cwd: ws, env, timeoutMs: 120000, onData, ctl, shell: IS_WIN });
                ok = !r.error && r.code === 0;
                onData('\n[exit code ' + (r.code != null ? r.code : 1) + ']\n');
                if (r.error) onData(r.error.message + '\n');
            }
            send({ type: 'cmd_output', id, text: out });
            return { ok, envInstall, output: (envInstall ? 'Python packages could NOT be installed because pip is unavailable on this server (' + pipState.why + ').\n' : '') + 'Installing the dependencies (' + list.join(', ') + ') FAILED:\n' + out };
        }
        async function runPython(rel, onData, staticOnly, stdinText) {
            if (staticOnly) return tryPy(['-c', 'import ast,sys;ast.parse(open(sys.argv[1],encoding="utf-8").read(),sys.argv[1]);print("Syntax OK")', rel], { cwd: ws, env, timeoutMs: 10000, onData, ctl });
            return tryPy([rel], { cwd: ws, env, timeoutMs: RUN_LIMIT_MS, onData, ctl, input: stdinText || undefined });
        }
        async function runNode(rel, onData, staticOnly, stdinText) {
            if (staticOnly) return runProc(process.execPath, ['--check', rel], { cwd: ws, env, timeoutMs: 10000, onData, ctl });
            return runProc(process.execPath, [rel], { cwd: ws, env, timeoutMs: RUN_LIMIT_MS, onData, ctl, input: stdinText || undefined });
        }
        async function runJava(rel, onData, staticOnly, stdinText) {
            const cls = path.posix.basename(rel).replace(/\.java$/i, '');
            const c = await runProc('javac', ['-encoding', 'UTF-8', '-d', 'out', rel], { cwd: ws, env, timeoutMs: 60000, onData, ctl });
            if (c.error && c.error.code === 'ENOENT') return { missing: 'javac (the Java compiler)' };
            if (c.error || c.code !== 0 || staticOnly) return c;
            return runProc('java', ['-Xmx256m', '-cp', 'out', cls], { cwd: ws, env, timeoutMs: RUN_LIMIT_MS, onData, ctl, input: stdinText || undefined });
        }
        async function runHtml(rel, onData) {
            const errors = [], notes = [];
            // 1) static checks - ONLY the tested page and the local css/js it links to. Problems that were ALREADY in the uploaded file are ignored.
            const targets = [rel];
            { const html0 = files.get(rel).content, re0 = /(?:src|href)\s*=\s*["']([^"'#?]+)["']/gi; let m0;
              while ((m0 = re0.exec(html0))) { const ref = m0[1]; if (/^(https?:|data:|mailto:|\/\/|javascript:)/i.test(ref)) continue; let t0; try { t0 = path.posix.normalize(path.posix.join(path.posix.dirname(rel), decodeURIComponent(ref))); } catch (e) { continue; } if (files.has(t0) && /\.(css|js|json)$/i.test(t0) && !targets.includes(t0)) targets.push(t0); } }
            let ignoredOld = 0;
            for (const t0 of targets.slice(0, 12)) { try { const r0 = await newIssues(t0); ignoredOld += r0.old; r0.fresh.forEach(e => errors.push(e)); } catch (e) {} }
            if (!errors.length) notes.push('✓ static checks passed for ' + targets.join(', ') + (ignoredOld ? ` (${ignoredOld} older problem(s) that were already in the uploaded file are ignored)` : ''));
            const userPage = files.get(rel).origin === 'user' && !files.get(rel).isNew;
            notes.forEach(n => onData(n + '\n')); errors.forEach(e => onData('✗ ' + e + '\n'));
            // 2) real page load in headless Chromium
            let browserNote = '';
            if (deps.getBrowser) {
                let context = null;
                try {
                    const browser = await deps.getBrowser();
                    context = await browser.newContext({ viewport: { width: 1280, height: 800 }, acceptDownloads: false });
                    const blocked = new Set(), baseUrl = 'file://' + ws.replace(/\\/g, '/');
                    await context.route('**/*', route => {
                        const u = route.request().url();
                        try {
                            if (/^(data|blob|about):/i.test(u)) return route.continue();
                            const pu = new URL(u);
                            if (pu.protocol === 'file:') {
                                const p = decodeURIComponent(pu.pathname).replace(/^\/([A-Za-z]:)/, '$1');
                                if ((p + '/').startsWith(ws.replace(/\\/g, '/') + '/')) return route.continue();
                                blocked.add(u); return route.abort();
                            }
                            if ((pu.protocol === 'http:' || pu.protocol === 'https:') && !isPrivateHost(pu.hostname)) return route.continue();
                        } catch (e) {}
                        blocked.add(u); return route.abort();
                    });
                    const page = await context.newPage();
                    const jsErr = [], external = [], missingNotes = [];
                    page.on('pageerror', e => jsErr.push('JavaScript error: ' + String((e && e.message) || e).slice(0, 300)));
                    page.on('console', m => { if (m.type() === 'error') { const t = m.text(); if (!/Failed to load resource/i.test(t)) jsErr.push('console.error: ' + t.slice(0, 300)); } });
                    page.on('dialog', d => d.dismiss().catch(() => {}));
                    page.on('requestfailed', r => {
                        const u = r.url();
                        if (/^file:/i.test(u)) { if (!blocked.has(u)) { const miss = decodeURIComponent(u.replace(baseUrl, '').replace(/^\/+/, '')); if (userPage && !files.has(miss)) missingNotes.push('• ' + miss + ' is linked by the uploaded page but was not uploaded (it exists in the user\'s real project) - ignored. Do NOT create a stand-in for it.'); else jsErr.push('Missing file (404): ' + miss); } }
                        else if (!/^(data|blob):/i.test(u)) external.push(u.slice(0, 120));
                    });
                    const url = 'file://' + (ws.startsWith('/') ? '' : '/') + ws.replace(/\\/g, '/') + '/' + rel.split('/').map(encodeURIComponent).join('/');
                    await page.goto(url, { waitUntil: 'load', timeout: 12000 });
                    await page.waitForTimeout(1200);
                    const blank = await page.evaluate(() => { const b = document.body; if (!b) return true; return !(b.innerText || '').trim() && !b.querySelector('canvas,svg,img,video,iframe,input,button,table'); }).catch(() => false);
                    if (blank) jsErr.push('The page renders NOTHING visible (empty body).');
                    // poke the page: click up to 10 buttons, press a few keys - catches broken event handlers
                    const startUrl = page.url();
                    try {
                        const btns = await page.$$('button:visible, [role=button]:visible, input[type=button]:visible, input[type=submit]:visible');
                        for (const b of btns.slice(0, 10)) { await b.click({ timeout: 800, noWaitAfter: true }).catch(() => {}); await page.waitForTimeout(120); if (page.url() !== startUrl) break; }
                        for (const k of ['Space', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Enter']) { await page.keyboard.press(k).catch(() => {}); }
                        await page.waitForTimeout(400);
                    } catch (e) {}
                    const uniq = [...new Set(jsErr)];
                    uniq.forEach(e => errors.push(e));
                    [...new Set(missingNotes)].forEach(n => { notes.push(n); onData(n + '\n'); });
                    onData(uniq.length ? uniq.map(e => '✗ ' + e).join('\n') + '\n' : `✓ ${rel} loaded in headless Chromium - no JavaScript errors, buttons and keys tried\n`);
                    if (external.length) { const t = `• ${external.length} external request(s) could not load (CDN/network may be blocked on this server): ${[...new Set(external)].slice(0, 3).join(', ')}`; notes.push(t); onData(t + '\n'); }
                } catch (e) {
                    browserNote = 'headless browser unavailable (' + String(e.message).split('\n')[0].slice(0, 120) + ') - static checks only';
                    onData('• ' + browserNote + '\n');
                } finally { if (context) await context.close().catch(() => {}); }
            } else { browserNote = 'headless browser not configured - static checks only'; onData('• ' + browserNote + '\n'); }
            return { code: errors.length ? 1 : 0, output: '', htmlErrors: errors, browserNote };
        }

        async function toolExecute(args) {
            const rel = safeRel(args.filename);
            if (!rel || !files.has(rel)) return { err: true, result: `Error: file "${args.filename}" does not exist in the workspace. Existing files: ${[...files.keys()].join(', ') || '(none)'}.` };
            let language = String(args.language || '').toLowerCase().trim();
            if (language === 'javascript') language = 'node';
            if (language === 'htm') language = 'html';
            const byExt = extLang(rel);
            if (byExt && byExt !== language) language = byExt;
            if (!['python', 'node', 'java', 'html'].includes(language)) return { err: true, result: `Error: cannot execute "${rel}" (unsupported type). Supported: python (.py), node (.js), java (.java), html (.html).` };

            const rawDeps = Array.isArray(args.dependencies) ? args.dependencies : [];
            const explicit = [...new Set(rawDeps.map(d => String(d).trim()).filter(Boolean))].slice(0, 12);
            const badDep = explicit.find(d => !validDep(d, language === 'node' ? 'npm' : 'pip'));
            if (badDep) return { err: true, result: `Error: invalid dependency name "${badDep}". Give plain package names like requests or express.` };
            let stdinText = typeof args.stdin === 'string' ? args.stdin : (Array.isArray(args.stdin) ? args.stdin.join('\n') : '');
            stdinText = stdinText.slice(0, 20000);
            if (stdinText && !stdinText.endsWith('\n')) stdinText += '\n';

            const content = files.get(rel).content;
            let noRun = '';   // can never run on a server without a screen / sound card -> syntax check only
            if (GUI_LIBS.test(content)) { noRun = 'it needs a screen / sound device / GUI window, which this server does not have'; warn.gui = true; }
            const staticOnly = !RUN_CODE || !!noRun;
            const sid = useStep('test', 'Testing');

            let r = null, installed = [];
            // ---- 1) install what the code imports (its own visible command) ----
            if (!staticOnly && (language === 'python' || language === 'node')) {
                let need = [];
                try { need = language === 'python' ? await detectPyMissing() : detectNodeMissing(); } catch (e) {}
                const all = [...new Set([...explicit, ...need])].slice(0, 15);
                if (all.length) {
                    const ins = await installDeps(language, all, sid);
                    if (ctl.aborted) return { err: true, result: 'aborted' };
                    if (ins.ok) installed = all; else r = { code: 1, output: ins.output, installFailed: true, envInstall: ins.envInstall };
                }
            }

            // ---- 2) run it (its own visible command: input first, then output) ----
            let id = null, shown = '';
            if (!r) {
                id = cmdId('t');
                const pipe = stdinPrefix(stdinText);
                const cmdText = staticOnly
                    ? ({ python: 'python3 -c "import ast; ast.parse(open(\'' + rel + '\').read())"', node: 'node --check ' + shQuote(rel), java: 'javac -d out ' + shQuote(rel), html: '# open ' + rel + ' in headless Chromium and check for JavaScript errors' })[language]
                    : ({ python: pipe + 'python3 ' + shQuote(rel), node: pipe + 'node ' + shQuote(rel), java: 'javac -d out ' + shQuote(rel) + ' && ' + pipe + 'java -cp out ' + path.posix.basename(rel).replace(/\.java$/i, ''), html: '# open ' + rel + ' in headless Chromium and check for JavaScript errors' })[language];
                send({ type: 'command', id, step: sid, title: 'Running a command', cmd: cmdText });
                const onData = x => { shown += x; send({ type: 'test', id, text: x }); };
                if (language === 'python') r = await runPython(rel, onData, staticOnly, stdinText);
                else if (language === 'node') r = await runNode(rel, onData, staticOnly, stdinText);
                else if (language === 'java') r = await runJava(rel, onData, staticOnly, stdinText);
                else r = await runHtml(rel, onData);
                if (r && !r.error && !r.missing && !r.timedOut && language !== 'html' && r.code != null) onData('\n[exit code ' + r.code + ']\n');   // like a real terminal
            }
            if (ctl.aborted) return { err: true, result: 'aborted' };

            const output = (r && r.output) || '';
            let ok = false, unverifiable = false, envBlocked = false, needsInput = false, summary = '';
            if (r && r.missing) { ok = true; unverifiable = true; summary = `${r.missing} is not installed on this server, so this file could not be compiled or run. Review the code very carefully yourself, then present it and tell the user in your final message that it could not be tested here.`; shown += `${r.missing} not installed on this server\n`; send({ type: 'test', id, text: `${r.missing} not installed on this server\n` }); }
            else if (r && r.error && r.error.code === 'ENOENT') { ok = true; unverifiable = true; summary = `The ${language} runtime is not installed on this server, so the file could not be run. Review the code carefully, then present it and tell the user it could not be tested here.`; send({ type: 'test', id, text: `${language}: command not found\n` }); }
            else if (r && r.error) { summary = 'Could not start the test: ' + r.error.message; }
            else if (language === 'html') { ok = r.code === 0; unverifiable = !!r.browserNote; summary = ok ? (r.browserNote ? 'Static checks passed, but the page could not be opened in a browser here (' + r.browserNote + ').' : 'The page loaded with no errors.') : 'The page has problems:\n' + r.htmlErrors.map(x => '- ' + x).join('\n'); }
            else if (r.installFailed) { summary = output; }
            else if (r.timedOut) {
                const looksBroken = /Traceback|Error\b|Exception|ERR_|SyntaxError|Cannot find module/.test(output);
                ok = !looksBroken; summary = ok ? `The program was still running after ${RUN_LIMIT_MS / 1000}s and was stopped (normal for servers / loops / programs waiting for input). No error was printed - treat it as PASSED.` : `The program printed an error and then hung / timed out:\n${clipMid(output, 9000)}`;
                send({ type: 'test', id, text: `\n[stopped after ${RUN_LIMIT_MS / 1000}s time limit]\n` });
            } else if (r.code === 0) {
                ok = true;
                summary = staticOnly ? `Syntax check passed. Output:\n${clipMid(output, 2000)}` : `Execution OK (exit code 0). Output:\n${clipMid(output, 9000) || '(no output)'}`;
            } else { summary = `Execution FAILED (exit code ${r.code}${r.signal ? ', ' + r.signal : ''}):\n${clipMid(output, 9000)}`; }
            if (installed.length) summary = `Dependencies installed automatically: ${installed.join(', ')}.\n` + summary;

            if (staticOnly && ok) {
                unverifiable = true;
                summary += `\n\n⚠️ NOT EXECUTED: ${noRun || 'execution is disabled on this server'}. Only the syntax was checked. This is an environment limitation, not a bug. Do not try to run it again - call present_files and clearly tell the user (in ${lang}) that it could not be run on the Hugging Face server and should be run on their own computer.`;
            }

            // sign-in / bot / 403 / blocked network = the SERVER's problem, never a bug to fix (even if the program caught it and printed it)
            if (!staticOnly && language !== 'html' && r && !r.missing && !(r.error) && (r.envInstall || envBlockHint(output))) {
                envBlocked = true; envFails++; warn.net = true;
                if (!ok) { ok = true; }
                unverifiable = true;
                summary = 'ENV-BLOCKED (not a code bug). ' + summary;
                summary += r.envInstall ? INSTALL_ENV_HINT : ENV_HINT + (envFails >= 3 ? '\n\nYou have hit this environment limit 3 times. STOP testing the network part now: present the files and explain it to the user.' : '');
            }
            if (!ok && !unverifiable) {
                // the program waited for keyboard input and got none -> give it input, do not change the program
                if (/EOFError|No line found|NoSuchElementException|InputMismatchException/.test(output)) {
                    needsInput = true;
                    summary += stdinText
                        ? '\n\nHint: the stdin you passed RAN OUT before the program finished. Give one line for EVERY prompt, ending with the answer that exits the program (e.g. quit), then call execute_code again. Do NOT remove the input() / Scanner from the program.'
                        : '\n\nHint: the program asks for KEYBOARD INPUT and got none. Call execute_code again with `stdin`: one line per prompt (e.g. "5\\n3\\nquit"), ending with the answer that makes the program exit. Do NOT remove the input() / Scanner from the program just to pass the test.';
                }
                if (!needsInput) failStreak++;
                const mm = /ModuleNotFoundError: No module named '([\w.]+)'/.exec(output);
                if (mm) { const root = mm[1].split('.')[0]; summary += `\n\nHint: the module "${mm[1]}" could not be installed automatically. If the pip name differs (current: "${PIP_NAMES[root] || root}"), call execute_code with dependencies: ["<correct pip name>"].`; }
                if (language === 'node' && /ReferenceError: (document|window|localStorage|alert|navigator) is not defined/.test(output)) summary += '\n\nHint: this is BROWSER code. Test it with execute_code language "html" on the HTML page that includes it.';
                if (failStreak === 4) summary += '\n\nWARNING: 4 failures in a row. Stop patching symptoms: re-read the file (read_file), find the root cause, or simplify the code.';
                if (failStreak >= 7) { forceFinish = true; summary += '\n\nToo many failed attempts. Call present_files now and honestly tell the user what still does not work.'; }
            } else if (ok && !envBlocked) { failStreak = 0; }

            seq++; lastTestSeq = seq; lastTestOk = ok; lastTestUnverifiable = unverifiable;
            if (id) send({ type: 'cmd_output', id, text: shown });
            send({ type: 'verdict', step: sid, verdict: !ok ? 'ISSUES' : (envBlocked ? 'ENV' : (unverifiable ? 'STATIC' : 'PASS')) });
            if (ok && !unverifiable) summary += '\n\nSUCCESS! You may now call present_files (or keep improving the code first).';
            if (ok && unverifiable && !envBlocked && !noRun && !summary.includes('NOT EXECUTED')) summary += '\n\nYou may now call present_files.';
            if (!ok && !unverifiable && !needsInput) summary += '\n\nFix the bug NOW with edit_code (only the lines that change), then call execute_code again.';
            return { result: summary, ok, cheapOk: ok };
        }

        // ====================== TOOL: present_files ======================
        function buildFileEvent(list) {
            const verified = lastTestOk === true && lastTestSeq >= lastEditSeq && !lastTestUnverifiable;
            return list.map(rel => { const f = files.get(rel); return { path: rel, language: fileLanguageTag(rel), content: f.content, edited: !!(f.edited && !f.isNew), isNew: !!f.isNew, verified }; });
        }
        async function toolPresent(args) {
            const asked = (Array.isArray(args.filenames) ? args.filenames : [args.filenames]).map(safeRel).filter(Boolean);
            const list = [...new Set(asked.filter(n => files.has(n)))];
            if (!list.length) return { err: true, result: `Error: none of those files exist. Existing files: ${[...files.keys()].join(', ') || '(none)'}.` };
            const needsTest = list.some(isCodeFile) && !(lastTestOk === true && lastTestSeq >= lastEditSeq);
            if (needsTest && gateWarned < 1 && !forceFinish) {
                gateWarned++;
                return { err: true, result: lastTestOk === false
                    ? 'REFUSED: your last test FAILED. Fix the bug with edit_code and run execute_code again before presenting. (If this is an environment limitation - YouTube / blocked website / GUI - call present_files again and explain it to the user.)'
                    : 'REFUSED: you changed code after the last test (or never tested). Call execute_code first and make sure it passes. (If the code truly cannot run on this server - YouTube / blocked website / GUI - call present_files again and explain it to the user.)' };
            }
            useStep('present', 'Presenting the files');
            presentedList = list; presentedOnce = true;
            send({ type: 'files', files: buildFileEvent(list) });
            closeStep();
            return { cheapOk: true, result: `Presented ${list.length} file(s) to the user: ${list.join(', ')}. Now write your short final message to the user in ${lang} (what you built, how to run it${lastTestOk === true && !lastTestUnverifiable ? '' : ', and that it could NOT be fully verified on the Hugging Face server'}). Do not call more tools unless something is still broken.` };
        }

        // ---------------------------------------------------------------------
        // the loop
        // ---------------------------------------------------------------------
        const liveDate = new Date().toLocaleString('en-IN', { timeZone: 'Asia/Kolkata', dateStyle: 'full', timeStyle: 'long' });
        const system = buildSystemPrompt(lang, `\n\n🚨 SYSTEM CLOCK: The real-time date and time is: ${liveDate}.`);
        let userMsg = `⚠️ REMINDER: you run on a Hugging Face Spaces server — YouTube / video downloads and bot-protected websites FAIL here, there is no screen or sound, 15 second limit. Always act by CALLING TOOLS; never answer with only a description.\n\nUSER REQUEST:\n${prompt}\n\n`;
        seed();
        if (files.size) {
            let total = 0, parts = [];
            for (const [k, v] of files) {
                const doc = v.kind === 'document', nl = v.content.split('\n').length, kb = Math.round(v.content.length / 1024);
                const small = !doc && v.content.length <= 20000;                 // small files are shown in full, big ones only as a preview (use read_file ranges / search_in_files)
                const show = (small && total < 200000) ? v.content : v.content.slice(0, doc ? 1500 : 2500);
                total += show.length;
                parts.push(`### ${k}   [${originLabel(v)}]   (${nl} lines, ${kb} KB)\n\`\`\`\n${show}${show.length < v.content.length ? '\n…(preview only - use search_in_files to find things and read_file with start_line/end_line to read parts)' : ''}\n\`\`\``);
            }
            userMsg += `FILES OF THIS CONVERSATION (code files are in your workspace - change them ONLY with edit_code, never rewrite them; create new files with write_code; PDF/Word documents are read-only text; use list_files / read_file / search_in_files to explore them):\n\n${parts.join('\n\n')}`;
        } else userMsg += 'The workspace is empty - this is a brand new project.';

        let history = [{ role: 'user', parts: [{ text: userMsg }] }];
        let finalText = '', nudges = 0, turnsDone = 0, failedMsg = '', forceTurns = 0;
        let emptyTurns = 0, noToolNudges = 0, testNudged = 0, failNudged = 0, forceTool = null, tier = 'strong';
        const usage = { calls: 0 };
        const t0 = Date.now();
        const cutNudge = 'Your answer was CUT OFF before the tool call was complete (the file was too long). Write ONE smaller file per write_code call (max ~250 lines) and split the project into several files (e.g. main.py + helpers.py). Call the tool again NOW.';

        try {
            for (let turn = 0; turn < MAX_TURNS && !ctl.aborted; turn++) {
                if (Date.now() - t0 > MAX_WALL_MS) { failedMsg = 'The time limit for one agent run was reached.'; break; }
                turnsDone++;
                let thinkId = null, pendingModel = null;
                const ensureThink = () => {
                    if (thinkId) return;
                    closeStep(); thinkId = uid('think'); stepEv(thinkId, 'Pondering');
                    if (pendingModel) send({ type: 'model', step: thinkId, model: pendingModel.modelId, api: pendingModel.id });
                };
                if (turn === 0) ensureThink();

                // while the AI is silent (writing a long file) show "still working... Ns" so the page never looks frozen
                const turnStart = Date.now();
                const hb = setInterval(() => { if (!ctl.aborted && Date.now() - lastSend >= HEARTBEAT_MS - 50) rawSend({ type: 'notice', text: T.working(Math.round((Date.now() - turnStart) / 1000)) }); }, HEARTBEAT_MS);

                let tr;
                try {
                    tr = await callModel(ctx, history, {
                        system, tools: TOOLS, forceTools: forceTool, tier, thoughts: tier === 'cheap' ? false : true, budget: turn === 0 ? 2048 : 1024, prepContents: prep,
                        onThought: t => { ensureThink(); send({ type: 'thought', text: t, stream: true }); },
                        onModel: m => { pendingModel = m; if (thinkId) send({ type: 'model', step: thinkId, model: m.modelId, api: m.id }); },
                        onNotice: t => send({ type: 'notice', text: t })
                    });
                } catch (e) {
                    clearInterval(hb);
                    if (thinkId) stepEv(thinkId, 'Pondering', 'done');
                    if (ctl.aborted) return;
                    if (touched.size) { failedMsg = 'The AI service stopped responding (' + e.message + ').'; break; }
                    throw e;
                }
                clearInterval(hb);
                if (deps.apiUsageStats) { const k = 'GEMINI (' + tr.provider.id + ')'; deps.apiUsageStats[k] = (deps.apiUsageStats[k] || 0) + 1; }
                usage.calls++; usage[tr.provider.modelId] = (usage[tr.provider.modelId] || 0) + 1;

                // ---- empty turn: the model produced nothing usable (cut off / malformed tool call) ----
                if (!tr.histParts.length) {
                    if (thinkId) stepEv(thinkId, 'Pondering', 'done');
                    emptyTurns++; tier = 'strong';
                    if (emptyTurns > 4) { failedMsg = 'The AI kept returning empty / cut-off answers.'; break; }
                    if (emptyTurns >= 2 && ctx.pool.length > 1) ctx.slowModels.add(ctx.pool[0].modelId);   // try another model
                    send({ type: 'notice', text: T.cut });
                    history = withUserText(history, cutNudge);
                    continue;
                }
                emptyTurns = 0; forceTool = null;
                history.push({ role: 'model', parts: tr.histParts });

                const text = tr.text.trim();
                if (tr.calls.length) {
                    if (text) { ensureThink(); send({ type: 'plan', text: text + '\n\n' }); }   // "speak first" narration
                    if (thinkId) stepEv(thinkId, 'Pondering', 'done');
                } else if (thinkId) stepEv(thinkId, 'Pondering', 'done');

                if (!tr.calls.length) {
                    tier = 'strong';   // a model that only talks needs the strong one
                    // (a) cut off / malformed tool call
                    if ((tr.finish === 'MAX_TOKENS' || tr.finish === 'MALFORMED_FUNCTION_CALL' || tr.finish === 'UNEXPECTED_TOOL_CALL') && nudges < 5) {
                        nudges++; send({ type: 'notice', text: T.cut });
                        history.push({ role: 'user', parts: [{ text: tr.finish === 'MAX_TOKENS' ? cutNudge : 'Your last tool call was malformed. Call the tool again with valid arguments (one file per call, complete).' }] });
                        continue;
                    }
                    // (b) it only TALKED ("I am going to write ...") and wrote nothing -> push it to really do it; then FORCE a tool call
                    const asksQuestion = /[??]\s*["')”)]*\s*$/.test(text);   // a real clarifying question is a valid answer; an announcement is not
                    const hasCollapsed = [...files.values()].some(v => v.collapsed);
                    if (!touched.size && !asksQuestion && !hasCollapsed && noToolNudges < 3) {
                        noToolNudges++;
                        if (noToolNudges >= 2) forceTool = files.size ? ['write_code', 'edit_code', 'read_file'] : ['write_code'];
                        send({ type: 'notice', text: T.forgot });
                        history.push({ role: 'user', parts: [{ text: 'You only DESCRIBED what you will do and wrote NO file. Do NOT describe or paste code in chat. Call write_code NOW with the complete file (' + (files.size ? 'or edit_code for existing files' : 'one file per call, under ~300 lines') + ').' }] });
                        continue;
                    }
                    // (c) code was written but never tested / last test failed / never presented
                    if (touched.size && RUN_CODE && touchedCode() && lastTestSeq < lastEditSeq && testNudged < 2) {
                        testNudged++; history.push({ role: 'user', parts: [{ text: 'You changed code but did not test it. Call execute_code on the main file NOW.' }] }); continue;
                    }
                    if (touched.size && lastTestOk === false && envFails === 0 && !presentedOnce && failNudged < 2) {
                        failNudged++; history.push({ role: 'user', parts: [{ text: 'The last test FAILED. Fix the bug with edit_code now, then call execute_code again.' }] }); continue;
                    }
                    if (touched.size && !presentedOnce && presentNudged < 1) {
                        presentNudged++;
                        history.push({ role: 'user', parts: [{ text: 'You have not called present_files yet. If the code is tested, call present_files now with ALL final files. If it still has a bug, fix it with edit_code first.' }] });
                        continue;
                    }
                    if (!touched.size && !asksQuestion && !hasCollapsed && text.length < 400) { finalText = T.noFiles; break; }   // never present "I will write..." as if it were an answer
                    finalText = sanitizeFinal(text); break;
                }

                // ---- run the tool calls, in order ----
                const responses = [], cheapFlags = [];
                for (const part of tr.calls) {
                    if (ctl.aborted) return;
                    const fc = part.functionCall, name = fc.name, args = fc.args || {};
                    let out;
                    try {
                        if (name === 'write_code') out = await toolWrite(args);
                        else if (name === 'edit_code') out = await toolEdit(args);
                        else if (name === 'read_file') out = await toolRead(args);
                        else if (name === 'execute_code') out = await toolExecute(args);
                        else if (name === 'present_files') out = await toolPresent(args);
                        else if (name === 'web_search') out = await toolWebSearch(args);
                        else if (name === 'list_files') out = await toolList(args);
                        else if (name === 'search_in_files') out = await toolGrep(args);
                        else if (name === 'rename_file') out = await toolRename(args);
                        else if (name === 'delete_file') out = await toolDelete(args);
                        else out = { err: true, result: `Error: unknown tool "${name}". Tools: write_code, edit_code, read_file, execute_code, present_files, web_search, list_files, search_in_files, rename_file, delete_file.` };
                    } catch (e) { out = { err: true, result: `Tool crashed: ${e.message}` }; }
                    const fr = { name, response: out.err ? { error: out.result } : { result: out.result } };
                    if (fc.id) fr.id = fc.id;
                    responses.push({ functionResponse: fr }); cheapFlags.push(!!(out && out.cheapOk && !out.err));
                }
                closeStep();
                history.push({ role: 'user', parts: responses });
                tier = (cheapFlags.length && cheapFlags.every(Boolean)) ? 'cheap' : 'strong';   // clean write/edit, passed test, presented -> the next turn is mechanical
                if (forceFinish && (presentedOnce || ++forceTurns >= 2)) break;   // too many failures: stop, present what we have
            }

            if (ctl.aborted) return;
            closeStep();
            // never lose the user's work: present whatever was written even if the model forgot to call present_files
            if (!presentedOnce && touched.size) {
                useStep('present', 'Presenting the files');
                presentedList = [...touched].filter(n => files.has(n));
                send({ type: 'files', files: buildFileEvent(presentedList) });
                closeStep();
            }
            { // keep the page's per-conversation file list exact (renames, deletes, files created but not shown as cards)
                const changed = [...touched].filter(n => files.has(n) && files.get(n).kind !== 'document').map(n => ({ path: n, content: files.get(n).content }));
                if (renamed.length || deleted.length || changed.length) send({ type: 'workspace', renamed, deleted, files: changed });
            }
            if (!finalText) {
                const notVerified = touched.size && !(lastTestOk === true && !lastTestUnverifiable);
                try {
                    const r = await callModel(ctx, withUserText(history, `Write the final message for the user now, in ${lang}: 2-4 short sentences, plain text, no tool calls. Say what was built${touched.size ? ' and how to run it' : ''}.${notVerified ? ' Be honest that it could NOT be fully tested/verified on the Hugging Face server (' + (failedMsg || 'tests did not fully pass') + ').' : ''}`),
                        { system, tools: TOOLS, noTools: true, thoughts: false, tier: 'cheap', prepContents: prep });
                    finalText = sanitizeFinal(r.text);
                } catch (e) { /* fall through to the plain message */ }
                if (!finalText) finalText = touched.size ? (notVerified ? `Here are your files. ⚠️ I could not fully verify them (${failedMsg || 'the last test did not pass'}), so please check them.` : 'Here are your files:') : (failedMsg || 'I could not finish this request. Please try again.');
            }
            // guaranteed Hugging Face warning (in the user's language), independent of what the AI wrote - only when it really applies
            const codeText = [...touched].map(n => (files.get(n) || {}).content || '').join('\n');
            const ytCode = YT_LIBS.test(codeText) || /(download|डाउनलोड|convert|mp3|mp4).{0,40}(youtube|youtu\.be|यूट्यूब|yt-?dlp)|(youtube|youtu\.be|यूट्यूब|yt-?dlp).{0,40}(download|डाउनलोड|mp3|mp4)/is.test(prompt);
            const verified = lastTestOk === true && !lastTestUnverifiable;
            if (GUI_LIBS.test(codeText)) warn.gui = true;
            if (!/hugging ?face|हगिंग/i.test(finalText)) {
                const notes = [];
                if (envFails > 0 || (ytCode && !verified) || (/scrap|crawl|स्क्रैप/i.test(prompt) && !verified)) notes.push(ytCode ? T.yt : T.net);
                if (warn.gui) notes.push(T.gui);
                if (notes.length) finalText += '\n\n' + notes.join('\n\n');
            }
            try { console.log('[agent] Gemini requests this run: ' + JSON.stringify(usage)); send({ type: 'usage', usage }); } catch (e) {}
            send({ type: 'final', text: finalText });
            send({ type: 'done' });
        } finally {
            try { fs.rmSync(ws, { recursive: true, force: true }); } catch (e) {}
        }
    }

    return { run, _internal: { resetPip: () => { pipState.kind = null; pipState.wheel = ''; pipState.at = 0; }, shQuote, buildWriteCmd, buildEditScript, scanNodeImports, stdinPrefix, sanitizeFinal, safeRel, applyEdit, envBlockHint, validDep, extLang, buildSystemPrompt, TOOLS, runProc, cleanEnv } };
};