File size: 69,220 Bytes
a03c24d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aetherius Terminal v3 (Gemini Edition)</title>
    <!-- highlight.js CSS for syntax highlighting -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
    <style>

        /* --- 1. Enhanced CSS with Theming Support --- */

        @import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;700&display=swap');



        :root {

            --bg-color: #1a1b26;

            --fg-color: #c0caf5;

            --panel-bg: #24283b;

            --border-color: #414868;

            --prompt-user-color: #f7768e;

            --prompt-path-color: #7aa2f7;

            --prompt-arrow-color: #bb9af7;

            --ai-color: #73daca;

            --warning-color: #e0af68;

            --error-color: #f7768e;

        }



        body {

            background-color: var(--bg-color);

            color: var(--fg-color);

            font-family: 'Fira Code', 'Menlo', 'Courier New', Courier, monospace;

            font-size: 14px;

            margin: 0;

            padding: 15px;

            box-sizing: border-box;

            transition: background-color 0.3s, color 0.3s;

        }



        #terminal {

            width: 100%;

            height: calc(100vh - 30px);

            display: flex;

            flex-direction: column;

        }



        #output {

            flex-grow: 1;

            overflow-y: auto;

            line-height: 1.6;

            padding-right: 10px;

        }

        

        .output-line { white-space: pre-wrap; word-wrap: break-word; }

        .grep-match {

            background-color: color-mix(in srgb, var(--warning-color) 40%, transparent);

            color: var(--fg-color);

            padding: 2px 4px;

            border-radius: 3px;

        }

        .grep-line {

            padding-left: 10px;

            border-left: 2px solid var(--warning-color);

        }



        .api-key-panel-container {

            margin-bottom: 15px;

            border: 1px solid var(--border-color);

            border-radius: 5px;

            background-color: var(--panel-bg);

            transition: height 0.3s ease-in-out;

            overflow: hidden; /* Hide overflowing content during transition */

        }



        .api-key-panel-header {

            display: flex;

            justify-content: space-between;

            align-items: center;

            padding: 10px;

            background-color: color-mix(in srgb, var(--panel-bg) 80%, var(--prompt-path-color) 20%);

            border-bottom: 1px solid var(--border-color);

            cursor: pointer;

            font-weight: bold;

            color: var(--fg-color);

        }



        .api-key-panel {

            padding: 10px;

            display: flex;

            flex-direction: column;

            gap: 10px;

        }



        .api-key-item {

            display: flex;

            align-items: center;

            gap: 10px;

            flex-wrap: wrap;

        }

        .api-key-item label {

            min-width: 120px; /* Align labels */

        }

        .api-key-item input {

            background-color: var(--bg-color);

            color: var(--fg-color);

            border: 1px solid var(--border-color);

            padding: 8px;

            border-radius: 4px;

            flex-grow: 1;

        }

        .api-key-item button {

            background-color: var(--prompt-path-color);

            color: var(--bg-color);

            border: none;

            padding: 8px 12px;

            border-radius: 4px;

            cursor: pointer;

            font-weight: bold;

        }

        .api-key-item .api-key-status { font-size: 0.9em; }



        #input-line { display: flex; align-items: center; }

        .prompt-user { color: var(--prompt-user-color); }

        .prompt-host { color: var(--fg-color); }

        .prompt-path { color: var(--prompt-path-color); }

        .prompt-arrow { color: var(--prompt-arrow-color); padding: 0 8px; font-weight: bold; }



        #command-input {

            background: transparent;

            border: none;

            color: var(--fg-color);

            font-family: inherit;

            font-size: inherit;

            flex-grow: 1;

        }

        #command-input:focus { outline: none; }

        #loading-indicator { display: none; margin-left: 10px; color: var(--warning-color); animation: pulse 1.5s infinite; }

        @keyframes pulse { 0% { opacity: 1; } 50% { opacity: 0.4; } 100% { opacity: 1; } }



        /* Formatting */

        .color-system { color: var(--prompt-arrow-color); }

        .color-ai { color: var(--ai-color); }

        .color-warning { color: var(--warning-color); }

        .color-error { color: var(--error-color); }

        .color-agent-name { color: var(--prompt-arrow-color); font-weight: bold; }

        .color-suggestion {

            border-left: 3px solid var(--ai-color);

            padding-left: 10px;

            margin: 5px 0;

            color: var(--ai-color);

            background-color: color-mix(in srgb, var(--bg-color) 90%, var(--ai-color) 10%);

        }

        .code-block {

            background-color: var(--panel-bg);

            border: 1px solid var(--border-color);

            padding: 1em;

            margin: 0.5em 0;

            border-radius: 5px;

            overflow-x: auto;

        }

        /* Style for highlighted code within code-block */

        .code-block pre code {

            display: block;

            padding: 0;

            background: none;

            color: var(--fg-color); /* Ensure text color matches theme for highlighted code */

        }

        b { color: var(--fg-color); font-weight: bold; }



        /* Modal for editing and confirmation */

        .modal {

            display: none; /* Hidden by default */

            position: fixed; /* Stay in place */

            z-index: 1; /* Sit on top */

            left: 0;

            top: 0;

            width: 100%; /* Full width */

            height: 100%; /* Full height */

            overflow: auto; /* Enable scroll if needed */

            background-color: rgba(0,0,0,0.7); /* Black w/ opacity */

            justify-content: center;

            align-items: center;

        }



        .modal-content {

            background-color: var(--panel-bg);

            margin: auto;

            padding: 20px;

            border: 1px solid var(--border-color);

            border-radius: 8px;

            width: 80%; /* Could be responsive */

            max-width: 800px;

            box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);

            display: flex;

            flex-direction: column;

            gap: 15px;

        }



        .modal-content textarea {

            width: 100%;

            min-height: 300px;

            background-color: var(--bg-color);

            color: var(--fg-color);

            border: 1px solid var(--border-color);

            padding: 10px;

            border-radius: 4px;

            font-family: 'Fira Code', monospace;

            font-size: 14px;

            resize: vertical;

        }



        .modal-buttons {

            display: flex;

            justify-content: flex-end;

            gap: 10px;

        }



        .modal-buttons button {

            background-color: var(--prompt-path-color);

            color: var(--bg-color);

            border: none;

            padding: 10px 15px;

            border-radius: 4px;

            cursor: pointer;

            font-weight: bold;

        }



        .modal-buttons button.cancel {

            background-color: var(--error-color);

        }

    </style>
</head>
<body>

    <div id="terminal">
        <div class="api-key-panel-container">
            <div class="api-key-panel-header" id="api-key-header">
                <span>API Keys</span>
                <span id="api-key-toggle-icon"></span>
            </div>
            <div class="api-key-panel" id="api-key-panel-content">
                <div class="api-key-item">
                    <label for="gemini-api-key-input">Gemini API Key:</label>
                    <input type="password" id="gemini-api-key-input" placeholder="Paste your Google AI Studio API Key here">
                    <button data-api-id="gemini" class="api-key-save-btn">Save Key</button>
                    <span id="gemini-api-key-status" class="api-key-status color-warning">Awaiting key...</span>
                </div>
                <div class="api-key-item">
                    <label for="gemini-pro-api-key-input">Gemini Pro API Key:</label>
                    <input type="password" id="gemini-pro-api-key-input" placeholder="Optional: Another Gemini API Key">
                    <button data-api-id="gemini-pro" class="api-key-save-btn">Save Key</button>
                    <span id="gemini-pro-api-key-status" class="api-key-status color-warning">Optional key...</span>
                </div>
                <!-- New API Key inputs -->
                <div class="api-key-item">
                    <label for="chatgpt-api-key-input">ChatGPT API Key:</label>
                    <input type="password" id="chatgpt-api-key-input" placeholder="Optional: OpenAI API Key for ChatGPT">
                    <button data-api-id="chatgpt" class="api-key-save-btn">Save Key</button>
                    <span id="chatgpt-api-key-status" class="api-key-status color-warning">Optional key...</span>
                </div>
                <div class="api-key-item">
                    <label for="grok-api-key-input">Grok API Key:</label>
                    <input type="password" id="grok-api-key-input" placeholder="Optional: Grok API Key">
                    <button data-api-id="grok" class="api-key-save-btn">Save Key</button>
                    <span id="grok-api-key-status" class="api-key-status color-warning">Optional key...</span>
                </div>
                <div class="api-key-item">
                    <label for="deepseek-api-key-input">DeepSeek API Key:</label>
                    <input type="password" id="deepseek-api-key-input" placeholder="Optional: DeepSeek API Key">
                    <button data-api-id="deepseek" class="api-key-save-btn">Save Key</button>
                    <span id="deepseek-api-key-status" class="api-key-status color-warning">Optional key...</span>
                </div>
            </div>
        </div>
        
        <div id="output"></div>

        <div id="input-line">
            <span id="prompt-context">
                <!-- Prompt will be dynamically generated here -->
            </span>
            <span class="prompt-arrow">></span>
            <input type="text" id="command-input" autofocus autocomplete="off">
            <span id="loading-indicator">AI is thinking...</span>
        </div>
    </div>

    <!-- Edit Modal -->
    <div id="edit-modal" class="modal">
        <div class="modal-content">
            <h3 id="modal-file-name">Editing File: </h3>
            <textarea id="edit-textarea"></textarea>
            <div class="modal-buttons">
                <button id="save-edit-btn">Save</button>
                <button id="cancel-edit-btn" class="cancel">Cancel</button>
            </div>
        </div>
    </div>

    <!-- Confirmation Modal (for rm) -->
    <div id="confirm-modal" class="modal">
        <div class="modal-content">
            <h3 id="confirm-message">Are you sure?</h3>
            <div class="modal-buttons">
                <button id="confirm-yes-btn">Yes</button>
                <button id="confirm-no-btn" class="cancel">No</button>
            </div>
        </div>
    </div>

<!-- highlight.js for syntax highlighting -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<!-- languages for highlight.js. Add more if needed -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/javascript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/python.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/xml.min.js"></script> <!-- For HTML -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/bash.min.js"></script> <!-- For simulated output -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/css.min.js"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/json.min.js"></script> 
<script>

document.addEventListener('DOMContentLoaded', () => {

    // --- 2. State, Elements, and Configuration ---

    // DOM Elements

    const terminal = document.getElementById('terminal');

    const output = document.getElementById('output');

    const commandInput = document.getElementById('command-input');

    const apiKeySaveBtns = document.querySelectorAll('.api-key-save-btn');

    const promptContext = document.getElementById('prompt-context');

    const loadingIndicator = document.getElementById('loading-indicator');

    const root = document.documentElement;



    // UI elements for API key panel

    const apiKeyHeader = document.getElementById('api-key-header');

    const apiKeyPanelContent = document.getElementById('api-key-panel-content');

    const apiKeyToggleIcon = document.getElementById('api-key-toggle-icon');



    // Edit Modal Elements

    const editModal = document.getElementById('edit-modal');

    const modalFileName = document.getElementById('modal-file-name');

    const editTextArea = document.getElementById('edit-textarea');

    const saveEditBtn = document.getElementById('save-edit-btn');

    const cancelEditBtn = document.getElementById('cancel-edit-btn');

    let currentEditFilePath = null; // Stores the path of the file being edited



    // Confirmation Modal Elements

    const confirmModal = document.getElementById('confirm-modal');

    const confirmMessage = document.getElementById('confirm-message');

    const confirmYesBtn = document.getElementById('confirm-yes-btn');

    const confirmNoBtn = document.getElementById('confirm-no-btn');

    let confirmCallback = null; // Callback function for confirmation



    // State

    // Stores multiple API Keys, keyed by API ID

    let API_KEYS = {

        'gemini': null, // Default Gemini API Key

        'gemini-pro': null, // Another Gemini Pro API Key

        'chatgpt': null, // New ChatGPT API Key

        'grok': null, // New Grok API Key

        'deepseek': null // New DeepSeek API Key

    };

    let commandHistory = [];

    let historyIndex = -1;

    let context = {

        path: "/home/user",

        project_type: "Generic",

        git_status: "Not a Git repository."

    };

    let aliases = {};

    // Simulated file system, loads from localStorage

    let FAKE_FILESYSTEM = {};

    const HOME_DIR = "/home/user";

    const FILESYSTEM_KEY = 'aetherius_filesystem_v3'; // localStorage key for FS persistence



    // Configuration



    // Helper function to initialize the file system

    function buildFS() {

        const savedFS = localStorage.getItem(FILESYSTEM_KEY);

        if (savedFS) {

            try {

                FAKE_FILESYSTEM = JSON.parse(savedFS);

                appendLine("File system loaded from local storage.", "color-system");

            } catch (e) {

                appendLine("Failed to load file system, creating a new one.", "color-error");

                initDefaultFS();

            }

        } else {

            initDefaultFS();

        }

    }



    // Initializes default file system

    function initDefaultFS() {

        FAKE_FILESYSTEM['/'] = {type: "dir", children: {"home": {type: "dir", children: {"user": {type: "dir", children: {}}}}}};

        let user_home = FAKE_FILESYSTEM['/'].children.home.children.user;

        user_home.children.projects = {type: "dir", children: {

            "python_cli": { type: "dir", children: { "main.py": {type: "file", content: "print('hello world')"}, "requirements.txt": {type: "file", content:"requests==2.25.1"}, ".git":{type:"dir"}}},

            "my_website": { type: "dir", children: { "index.html": {type: "file", content:"<h1>Hi</h1>"}, "package.json": {type: "file", content:'{"name": "my_website"}'}}}

        }};

        user_home.children.documents = { type: "dir", children: { "notes.txt": { type: "file", content: "My important notes." } } };

        saveFS(); // Save default FS immediately

    }



    // Save file system to localStorage

    function saveFS() {

        localStorage.setItem(FILESYSTEM_KEY, JSON.stringify(FAKE_FILESYSTEM));

    }



    // AI Agent Prompts

    const GEMINI_PROMPTS = {

        command_translator: `You are Aetherius, an expert AI terminal assistant. Translate the user's natural language into a single-line Linux bash command. RULES: - ONLY output the shell command. - No explanations or markdown. - Use context for accuracy. - If the request requires multiple steps, chain commands with '&&'. - If untranslatable, output 'AETHERIUS_CANNOT_TRANSLATE'.`,

        coder: `You are the @coder agent, an expert programmer. Answer the user's question clearly. Use markdown for code blocks.`,

        sysadmin: `You are the @sysadmin agent, an expert in systems administration, networking, and DevOps. Answer the user's question clearly. Use markdown for code blocks.`,

        git: `You are the @git agent. The user is asking for a Git command. Based on their request and the provided simulated git status, generate the most likely git command. Only output the command itself.`,

        designer: `You are the @designer agent, an expert in UI/UX and web design. Provide design suggestions or HTML/CSS snippets based on the user's request. Use markdown for code blocks.`,

        data: `You are the @data agent, an expert in data analysis and visualization. Provide insights or Python code snippets for data processing. Use markdown for code blocks.`,

        // New agent prompts - actual responses will fall back to Gemini

        chatgpt: `You are the @chatgpt agent, powered by a large language model. Provide concise and helpful responses. Use markdown for code blocks.`,

        grok: `You are the @grok agent, a highly capable and intelligent AI. Provide insightful and creative responses. Use markdown for code blocks.`,

        deepseek: `You are the @deepseek agent, specializing in code generation and analysis. Provide code solutions or explain complex programming concepts. Use markdown for code blocks.`,

        // Code generation agent

        code_generator: `You are the @gen_code agent, an expert software engineer. Generate a complete code snippet based on the user's request. Output ONLY the code within a markdown block. Do NOT include any explanations or conversational text outside the code block. Use the project_type context for language preference if applicable.`,

        // Code execution simulation agent

        code_runner: `You are an AI that simulates the execution of code. The user will provide a code snippet and a project type. Your task is to output what the console output would look like if this code were executed in that environment. Output ONLY the simulated console output. Do NOT include any explanations or markdown.`,

        // Debugging agent

        debugger: `You are the @debug agent, an expert in finding and explaining code errors. Analyze the provided code for potential bugs, suggest fixes, and explain the reasoning. Use markdown for code examples and explanations.`,

        // Refactoring agent

        refactorer: `You are the @refactor agent, an expert in code quality and refactoring. Analyze the provided code and suggest improvements for readability, efficiency, and maintainability. Provide refactored code snippets in markdown.`,

        // Testing agent

        tester: `You are the @test agent, an expert in writing unit tests. Generate comprehensive unit tests for the provided code snippet, suitable for the detected project type. Output ONLY the test code within a markdown block.`,

        // Code explainer agent

        code_explainer: `You are the @explain_code agent, an expert at explaining code. Explain the provided code snippet clearly and concisely. Use markdown for code examples and explanations.`,

        // Linter/Formatter agent

        linter_formatter: `You are the @lint_format agent, an expert in code style and best practices. Analyze the provided code and suggest linting and formatting improvements. Provide improved code snippets in markdown if applicable.`,

        // Project initialization agent

        project_initializer: `You are the @init agent. The user wants to initialize a new project. Based on the specified project type (e.g., 'python-app', 'web-app'), generate the boilerplate files and directory structure. Output the commands to create files/directories and their content. If it's a web-app, suggest basic HTML/CSS. If Python, suggest a main.py and requirements.txt. Respond concisely, use markdown for code.`,

    };

    

    const THEMES = {

        "default": {}, /* Uses :root defaults */

        "tokyo-night": {

            '--bg-color': '#1a1b26', '--fg-color': '#c0caf5', '--panel-bg': '#24283b', '--border-color': '#414868',

            '--prompt-user-color': '#f7768e', '--prompt-path-color': '#7aa2f7', '--prompt-arrow-color': '#bb9af7',

            '--ai-color': '#73daca', '--warning-color': '#e0af68', '--error-color': '#f7768e'

        },

        "gruvbox-dark": {

            '--bg-color': '#282828', '--fg-color': '#ebdbb2', '--panel-bg': '#3c3836', '--border-color': '#504945',

            '--prompt-user-color': '#fb4934', '--prompt-path-color': '#83a598', '--prompt-arrow-color': '#d3869b',

            '--ai-color': '#b8bb26', '--warning-color': '#fabd2f', '--error-color': '#fb4934'

        },

        "solarized-dark": {

            '--bg-color': '#002b36', '--fg-color': '#839496', '--panel-bg': '#073642', '--border-color': '#586e75',

            '--prompt-user-color': '#d33682', '--prompt-path-color': '#268bd2', '--prompt-arrow-color': '#6c71c4',

            '--ai-color': '#2aa198', '--warning-color': '#b58900', '--error-color': '#dc322f'

        }

    };



    // --- 3. Core Functionality ---

    const appendLine = (text, className) => {

        const line = document.createElement('div');

        line.innerHTML = text; // Allows HTML rendering for formatting

        if (className) line.classList.add(className);

        line.classList.add('output-line');

        output.appendChild(line);

        terminal.scrollTop = output.scrollHeight;

    };

    

    const displayWelcomeMessage = () => {

        output.innerHTML = '';

        appendLine(`Welcome to <span class="color-ai">Aetherius Terminal v3 (Gemini Edition)</span>`, 'color-system');

        appendLine(`This is a <span class="color-warning">browser-based simulation</span>. No real commands are executed.`, 'color-warning');

        appendLine(`<b>New in v3:</b> Themes, aliases, neofetch, cat, touch, man, AI command chaining, <span class="color-ai">direct code generation</span>, <span class="color-ai">edit</span>, <span class="color-ai">run</span>, <span class="color-ai">@debug</span>, <span class="color-ai">@refactor</span>, <span class="color-ai">@test</span>, <span class="color-ai">@explain_code</span>, <span class="color-ai">@lint_format</span>, <span class="color-ai">init</span>, <span class="color-ai">grep</span>, <span class="color-ai">download</span>, file system persistence and more file commands.`, 'color-system');

        appendLine(`Enter <span class="color-ai">help</span> for available commands.`, 'color-system');

        appendLine(' ');

    };



    const updatePrompt = () => {

        const displayPath = context.path.replace(HOME_DIR, "~");

        promptContext.innerHTML = `<span class="prompt-user">user@aetherius</span><span class="prompt-host">:</span><span class="prompt-path">${displayPath}</span>`;

    };

    

    const saveApiKey = (apiId, keyInputId, statusElementId) => {

        const keyInput = document.getElementById(keyInputId);

        const apiKeyStatus = document.getElementById(statusElementId);

        const key = keyInput.value.trim();



        if (key) {

            API_KEYS[apiId] = key;

            apiKeyStatus.textContent = "Key Loaded";

            apiKeyStatus.className = 'api-key-status color-ai';

            appendLine(`API Key for ${apiId} loaded successfully. AI features are now enabled.`, "color-system");

        } else {

            API_KEYS[apiId] = null; // Clear key if input is empty

            apiKeyStatus.textContent = "Key cannot be empty";

            apiKeyStatus.className = 'api-key-status color-warning';

            appendLine(`API Key for ${apiId} cleared.`, "color-system");

        }

    };

    

    // Calls AI API with fallback logic

    const callAIAPI = async (prompt, systemInstruction, model = 'gemini-1.5-flash', apiId = 'gemini') => {

        let apiKey = API_KEYS[apiId];

        let actualModelUsed = model;

        let actualApiIdUsed = apiId;



        // Fallback logic: If the requested API key is not set, try to use Gemini's key

        if (!apiKey) {

            if (API_KEYS['gemini']) {

                apiKey = API_KEYS['gemini'];

                actualApiIdUsed = 'gemini';

                actualModelUsed = 'gemini-1.5-flash'; // Fallback to basic Gemini

                appendLine(`Warning: ${apiId} API Key not set. Falling back to Gemini API.`, "color-warning");

            } else if (API_KEYS['gemini-pro']) {

                apiKey = API_KEYS['gemini-pro'];

                actualApiIdUsed = 'gemini-pro';

                actualModelUsed = 'gemini-1.5-pro'; // Fallback to Gemini Pro if available

                appendLine(`Warning: ${apiId} API Key not set. Falling back to Gemini Pro API.`, "color-warning");

            } else {

                appendLine(`Error: No API Key available for ${apiId} or Gemini. Please set at least one.`, "color-error");

                return null;

            }

        }



        loadingIndicator.style.display = 'inline';

        const API_URL = `https://generativelanguage.googleapis.com/v1beta/models/${actualModelUsed}-latest:generateContent?key=${apiKey}`;

        

        const requestBody = {

            contents: [{ parts: [{ text: `${systemInstruction}\n\nContext:\n- Path: ${context.path}\n- Project Type: ${context.project_type}\n- Git: ${context.git_status}\n\nUser's Request: "${prompt}"` }] }],

            generationConfig: { temperature: 0.1, maxOutputTokens: 2048 }

        };

        

        try {

            const response = await fetch(API_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(requestBody) });

            if (!response.ok) {

                const errorData = await response.json();

                throw new Error(errorData.error.message || `HTTP error! status: ${response.status}`);

            }

            const data = await response.json();

            // Handle cases where the model returns no candidates (e.g., safety filters)

            if (!data.candidates || data.candidates.length === 0) {

                 throw new Error("API returned no content. The model may have filtered the response.");

            }

            return data.candidates[0].content.parts[0].text.trim();

        } catch (error) {

            appendLine(`API Error (${actualApiIdUsed} / ${actualModelUsed}): ${error.message}`, "color-error");

            return null;

        } finally {

            loadingIndicator.style.display = 'none';

        }

    };



    const formatHelp = (entries) => {

        let output = '<b>Aetherius Help</b>\n';

        entries.forEach(([cmd, desc]) => {

            output += `  <span class="color-ai">${cmd.padEnd(20)}</span> - ${desc}\n`;

        });

        return output;

    };

    

    // --- 4. File System and Command Helpers ---

    // Helper function to traverse the simulated file system and return a node

    const getNode = (path, createIfMissing = false, type = 'file') => {

        const resolvedPath = path.startsWith('/') ? path : (context.path === '/' ? '' : context.path) + '/' + path;

        const parts = resolvedPath.split('/').filter(p => p);

        let current = FAKE_FILESYSTEM['/'];

        let fullPathSegments = []; // To build full path for error messages



        for (let i = 0; i < parts.length; i++) {

            const part = parts[i];

            fullPathSegments.push(part);

            if (current && current.type === 'dir' && current.children) {

                if (!current.children[part]) {

                    if (createIfMissing && i === parts.length - 1) { // Last part, create it

                        if (type === 'dir') {

                            current.children[part] = { type: 'dir', children: {} };

                        } else { // default to file

                            current.children[part] = { type: 'file', content: '' };

                        }

                        saveFS();

                    } else {

                        return null; // Path does not exist and not creating

                    }

                }

                current = current.children[part];

            } else {

                return null; // Parent is not a directory or doesn't exist

            }

        }

        return current;

    };

    

    // Helper function to get parent node and target name

    const getParentNodeAndName = (path) => {

        let parentPath = path.substring(0, path.lastIndexOf('/')) || '/';

        const name = path.substring(path.lastIndexOf('/') + 1);

        const parentNode = getNode(parentPath);

        return { parentNode, name };

    }



    // Command to display code with highlighting

    const displayCode = (code, language = 'plaintext') => {

        const pre = document.createElement('pre');

        const codeElement = document.createElement('code');

        codeElement.className = `language-${language}`; // highlight.js class

        codeElement.textContent = code; // Use textContent to prevent XSS

        pre.appendChild(codeElement);

        const codeBlockDiv = document.createElement('div');

        codeBlockDiv.classList.add('code-block');

        codeBlockDiv.appendChild(pre);

        output.appendChild(codeBlockDiv);

        hljs.highlightElement(codeElement); // Highlight the code

        terminal.scrollTop = output.scrollHeight;

    };



    // Displays a confirmation modal

    const showConfirmModal = (message, callback) => {

        confirmMessage.textContent = message;

        confirmCallback = callback;

        confirmModal.style.display = 'flex';

        confirmYesBtn.focus(); // Focus on Yes button for quick action

    };



    // Command Implementations

    const COMMANDS = {

        help: () => appendLine(formatHelp([

            ["help", "Shows this message"],

            ["clear", "Clears the screen"],

            ["ls [-a]", "Lists files in the current directory"],

            ["cd [dir]", "Changes directory. Supports .., ~, /"],

            ["pwd", "Prints working directory"],

            ["touch [file]", "Creates an empty file"],

            ["cat [file]", "Displays file content with highlighting"],

            ["edit [file]", "Edits content of a file (opens modal)"],

            ["run [file]", "Simulates running a code file"],

            ["saveas <src> <dest>", "Saves content of <src> file to <dest>"],

            ["rm <file/dir>", "Removes a file or empty directory"],

            ["mkdir <dir>", "Creates a new directory"],

            ["mv <src> <dest>", "Moves or renames a file/directory"],

            ["grep <pattern> <file>", "Searches for a pattern in a file"], // New

            ["download <file>", "Downloads a file from the terminal"],      // New

            ["init <type> [name]", "Initializes a new project boilerplate"], // New

            ["history", "Displays command history"],

            ["alias", "Manage command aliases"],

            ["theme [name]", "Changes the color theme"],

            ["neofetch", "Show system information"],

            ["man [cmd]", "Display manual page for a command"],

            ["@coder [q]", "Ask a programming question (uses Gemini Pro if available)"],

            ["@sysadmin [q]", "Ask a systems/DevOps question (uses Gemini)"],

            ["@git [q]", "Ask for a git command (uses Gemini)"],

            ["@designer [q]", "Ask a UI/UX or web design question (uses Gemini)"],

            ["@data [q]", "Ask a data analysis question (uses Gemini)"],

            ["@gen_code [q]", "Generate code snippet directly (uses Gemini Pro if available)"],

            ["@debug [file]", "Debugs code in a file (AI simulation)"],

            ["@refactor [file]", "Refactors code in a file (AI simulation)"],

            ["@test [file]", "Generates tests for code in a file (AI simulation)"],

            ["@explain_code [file]", "Explains code in a file (AI simulation)"], // New

            ["@lint_format [file]", "Suggests linting/formatting for code (AI sim)"], // New

            ["@chatgpt [q]", "Ask ChatGPT a question (simulated by Gemini)"],

            ["@grok [q]", "Ask Grok a question (simulated by Gemini)"],

            ["@deepseek [q]", "Ask DeepSeek a question (simulated by Gemini for code)"]

        ])),

        clear: () => displayWelcomeMessage(),

        pwd: () => appendLine(context.path),

        ls: (args) => {

            const node = getNode(context.path);

            let children = node && node.children ? Object.keys(node.children) : [];

            if (!args.includes('-a')) {

                children = children.filter(c => !c.startsWith('.'));

            }

            appendLine(children.length > 0 ? children.map(c => getNode(context.path + '/' + c).type === 'dir' ? `<span class="prompt-path">${c}/</span>` : c).join('  ') : '');

        },

        cd: (args) => { 

            let target = args[0] || '~';

            if(target === '~') target = HOME_DIR;

            

            let newPath = target.startsWith('/') ? target : (context.path === '/' ? '' : context.path) + '/' + target;



            let parts = newPath.split('/').reduce((acc, part) => {

                if (part === '..') acc.pop();

                else if (part !== '' && part !== '.') acc.push(part);

                return acc;

            }, []);

            newPath = '/' + parts.join('/');

            

            const targetNode = getNode(newPath);

            if (targetNode && targetNode.type === 'dir') {

                context.path = newPath;

                const childrenNames = Object.keys(targetNode.children || {});

                if(childrenNames.includes('package.json')) context.project_type = 'Node.js';

                else if(childrenNames.includes('requirements.txt')) context.project_type = 'Python';

                else if(childrenNames.includes('.git')) context.git_status = "On branch 'main', 2 changes."

                else { context.project_type = 'Generic'; context.git_status = "Not a Git repository.";}

            } else {

                appendLine(`cd: no such file or directory: ${target}`, "color-error");

            }

            updatePrompt();

        },

        touch: (args) => {

            if (!args[0]) { appendLine("touch: missing file operand", "color-error"); return; }

            const { parentNode, name } = getParentNodeAndName(context.path + '/' + args[0]);

            if (parentNode && parentNode.type === "dir" && !parentNode.children[name]) {

                parentNode.children[name] = { type: 'file', content: '' };

                appendLine(`File '${args[0]}' created.`, "color-system");

                saveFS();

            } else if (parentNode && parentNode.children[name]) {

                appendLine(`File '${args[0]}' already exists.`, "color-warning");

            } else {

                appendLine(`touch: cannot create file '${args[0]}': No such file or directory`, "color-error");

            }

        },

        cat: (args) => {

            if (!args[0]) { appendLine("cat: missing file operand", "color-error"); return; }

            const node = getNode(context.path + '/' + args[0]);

            if(node && node.type === 'file') {

                let language = 'plaintext';

                if (args[0].endsWith('.js')) language = 'javascript';

                else if (args[0].endsWith('.py')) language = 'python';

                else if (args[0].endsWith('.html') || args[0].endsWith('.xml')) language = 'xml';

                else if (args[0].endsWith('.css')) language = 'css';

                else if (args[0].endsWith('.json')) language = 'json';

                

                displayCode(node.content, language);

            } else {

                appendLine(`cat: ${args[0]}: No such file or directory`, "color-error");

            }

        },

        edit: (args) => {

            if (!args[0]) { appendLine("edit: missing file operand", "color-error"); return; }

            const targetPath = context.path + '/' + args[0];

            const node = getNode(targetPath);



            if (node && node.type === 'file') {

                currentEditFilePath = targetPath;

                modalFileName.textContent = `Editing File: ${args[0]}`;

                editTextArea.value = node.content;

                editModal.style.display = 'flex'; // Show the modal

                editTextArea.focus();

            } else {

                appendLine(`edit: ${args[0]}: No such file or directory or not a file`, "color-error");

            }

        },

        run: async (args) => {

            if (!args[0]) { appendLine("run: missing file operand", "color-error"); return; }

            const targetPath = context.path + '/' + args[0];

            const node = getNode(targetPath);



            if (node && node.type === 'file') {

                appendLine(`Simulating execution of '${args[0]}' in ${context.project_type} environment...`, "color-system");

                const codeToRun = node.content;

                const promptForRun = `Simulate running the following code in a ${context.project_type} environment and provide its console output. ONLY output the console output. Do NOT include any explanations or markdown.\n\nCode:\n${codeToRun}`;

                

                const response = await callAIAPI(promptForRun, GEMINI_PROMPTS.code_runner, 'gemini-1.5-pro', 'gemini-pro'); 

                if (response) {

                    appendLine(`--- Simulated Output for '${args[0]}' ---`, 'color-system');

                    displayCode(response, 'bash'); 

                    appendLine(`--- End Simulated Output ---`, 'color-system');

                } else {

                    appendLine(`Failed to simulate execution for '${args[0]}'.`, "color-error");

                }



            } else {

                appendLine(`run: ${args[0]}: No such file or directory or not a file`, "color-error");

            }

        },

        saveas: (args) => {

            if (args.length !== 2) { appendLine("Usage: saveas <source_file> <destination_file>", "color-error"); return; }

            const sourcePath = context.path + '/' + args[0];

            const destPath = context.path + '/' + args[1];

            

            const sourceNode = getNode(sourcePath);

            if (!sourceNode || sourceNode.type !== 'file') {

                appendLine(`saveas: source file not found or not a file: ${args[0]}`, "color-error");

                return;

            }



            const { parentNode: destParentNode, name: destName } = getParentNodeAndName(destPath);

            if (!destParentNode || destParentNode.type !== 'dir') {

                appendLine(`saveas: destination directory not found: ${args[1]}`, "color-error");

                return;

            }



            if (destParentNode.children[destName]) {

                appendLine(`saveas: destination file already exists: ${args[1]}`, "color-warning");

                // Optionally ask for overwrite confirmation

            }

            

            destParentNode.children[destName] = { type: 'file', content: sourceNode.content };

            appendLine(`File '${args[0]}' saved as '${args[1]}'.`, "color-system");

            saveFS();

        },

        rm: (args) => {

            if (!args[0]) { appendLine("rm: missing operand", "color-error"); return; }

            const targetPath = context.path + '/' + args[0];

            const node = getNode(targetPath);

            if (!node) {

                appendLine(`rm: cannot remove '${args[0]}': No such file or directory`, "color-error");

                return;

            }



            if (node.type === 'dir' && Object.keys(node.children).length > 0) {

                appendLine(`rm: cannot remove '${args[0]}': Directory not empty`, "color-error");

                appendLine("Use 'rm -r' to remove non-empty directories (not implemented in simulation).", "color-warning");

                return;

            }

            

            showConfirmModal(`Are you sure you want to remove '${args[0]}'?`, (confirmed) => {

                if (confirmed) {

                    const { parentNode, name } = getParentNodeAndName(targetPath);

                    if (parentNode && parentNode.children) {

                        delete parentNode.children[name];

                        appendLine(`Removed '${args[0]}'.`, "color-system");

                        saveFS();

                    }

                } else {

                    appendLine("Removal cancelled.", "color-warning");

                }

                commandInput.focus(); // Restore focus

            });

        },

        mkdir: (args) => {

            if (!args[0]) { appendLine("mkdir: missing operand", "color-error"); return; }

            const targetPath = context.path + '/' + args[0];

            const { parentNode, name } = getParentNodeAndName(targetPath);

            if (!parentNode || parentNode.type !== 'dir') {

                appendLine(`mkdir: cannot create directory '${args[0]}': No such file or directory`, "color-error");

                return;

            }

            if (parentNode.children[name]) {

                appendLine(`mkdir: cannot create directory '${args[0]}': File exists`, "color-error");

                return;

            }

            parentNode.children[name] = { type: 'dir', children: {} };

            appendLine(`Directory '${args[0]}' created.`, "color-system");

            saveFS();

        },

        mv: (args) => {

            if (args.length !== 2) { appendLine("Usage: mv <source> <destination>", "color-error"); return; }

            const sourcePath = context.path + '/' + args[0];

            const destPath = context.path + '/' + args[1];



            const sourceNode = getNode(sourcePath);

            if (!sourceNode) {

                appendLine(`mv: cannot stat '${args[0]}': No such file or directory`, "color-error");

                return;

            }



            const { parentNode: sourceParentNode, name: sourceName } = getParentNodeAndName(sourcePath);

            const { parentNode: destParentNode, name: destName } = getParentNodeAndName(destPath);



            // Handle rename within same directory or move to new directory

            if (destParentNode && destParentNode.type === 'dir') {

                if (destParentNode.children[destName]) {

                    appendLine(`mv: cannot overwrite existing '${args[1]}'`, "color-error");

                    return;

                }

                destParentNode.children[destName] = sourceNode;

                delete sourceParentNode.children[sourceName];

                appendLine(`Moved '${args[0]}' to '${args[1]}'.`, "color-system");

                saveFS();

            } else {

                appendLine(`mv: cannot move to '${args[1]}': No such file or directory`, "color-error");

            }

        },

        grep: (args) => {

            if (args.length !== 2) { appendLine("Usage: grep <pattern> <file>", "color-error"); return; }

            const pattern = new RegExp(args[0], 'g'); // Global search

            const filePath = context.path + '/' + args[1];

            const fileNode = getNode(filePath);



            if (!fileNode || fileNode.type !== 'file') {

                appendLine(`grep: ${args[1]}: No such file or not a file`, "color-error");

                return;

            }



            const lines = fileNode.content.split('\n');

            let foundMatches = false;

            lines.forEach((line, index) => {

                if (line.match(pattern)) {

                    foundMatches = true;

                    const highlightedLine = line.replace(pattern, (match) => `<span class="grep-match">${match}</span>`);

                    appendLine(`<span class="grep-line">${filePath}:${index + 1}: ${highlightedLine}</span>`);

                }

            });

            if (!foundMatches) {

                appendLine(`No matches found for '${args[0]}' in '${args[1]}'.`, "color-system");

            }

        },

        download: (args) => {

            if (!args[0]) { appendLine("download: missing file operand", "color-error"); return; }

            const filePath = context.path + '/' + args[0];

            const fileNode = getNode(filePath);



            if (!fileNode || fileNode.type !== 'file') {

                appendLine(`download: ${args[0]}: No such file or not a file`, "color-error");

                return;

            }



            const fileName = args[0].split('/').pop(); // Get just the file name

            const blob = new Blob([fileNode.content], { type: 'text/plain' }); // Default to text/plain

            const url = URL.createObjectURL(blob);

            

            const a = document.createElement('a');

            a.href = url;

            a.download = fileName;

            document.body.appendChild(a); // Append to body to make it clickable

            a.click();

            document.body.removeChild(a); // Clean up

            URL.revokeObjectURL(url); // Release the URL object

            

            appendLine(`Downloading '${fileName}'...`, "color-system");

        },

        init: (args) => {

            if (args.length < 1 || args.length > 2) { appendLine("Usage: init <project_type> [name]", "color-error"); return; }

            const projectType = args[0].toLowerCase();

            const projectName = args[1] || `${projectType}-project`;

            const projectPath = context.path + '/' + projectName;



            if (getNode(projectPath)) {

                appendLine(`init: directory '${projectName}' already exists.`, "color-error");

                return;

            }



            // Call AI to generate boilerplate

            appendLine(`Initializing new '${projectType}' project as '${projectName}'...`, "color-system");

            const prompt = `Generate boilerplate for a new '${projectType}' project named '${projectName}'. Provide touch and echo commands for creating files and their content. If 'web-app', include index.html, style.css, script.js. If 'python-app', include main.py, requirements.txt.`;

            callAIAPI(prompt, GEMINI_PROMPTS.project_initializer, 'gemini-1.5-pro', 'gemini-pro')

                .then(response => {

                    if (response) {

                        appendLine(`AI's Initialization Plan:`, 'color-ai');

                        // Split AI's response into lines and execute commands

                        const commands = response.split('\n').filter(line => line.trim().startsWith('touch') || line.trim().startsWith('echo'));

                        commands.forEach(cmdLine => {

                            if (cmdLine.startsWith('touch ')) {

                                const filePath = cmdLine.substring(6).trim(); // Remove 'touch '

                                getNode(projectPath + '/' + filePath, true, 'file'); // Create the file

                                appendLine(`Created: ${projectPath + '/' + filePath}`, 'color-system');

                            } else if (cmdLine.startsWith('echo ')) {

                                const match = cmdLine.match(/echo "(.*?)" > (.*)/);

                                if (match) {

                                    const content = match[1].replace(/\\n/g, '\n'); // Handle escaped newlines

                                    const filePath = match[2].trim();

                                    const fileNode = getNode(projectPath + '/' + filePath);

                                    if (fileNode && fileNode.type === 'file') {

                                        fileNode.content = content;

                                        appendLine(`Populated: ${projectPath + '/' + filePath}`, 'color-system');

                                    } else {

                                        appendLine(`Error: Could not populate ${projectPath + '/' + filePath}. File not found or not created by touch.`, 'color-error');

                                    }

                                }

                            }

                        });

                        saveFS(); // Save the new project structure

                    } else {

                        appendLine(`AI failed to generate initialization boilerplate.`, "color-error");

                    }

                });

        },

        history: () => {

            if (commandHistory.length === 0) {

                appendLine("No command history yet.", "color-system");

                return;

            }

            commandHistory.forEach((cmd, index) => {

                appendLine(`${String(commandHistory.length - index).padStart(4, ' ')}  ${cmd}`);

            });

        },

        theme: (args) => {

            const themeName = args[0];

            if (THEMES[themeName]) {

                Object.entries(THEMES[themeName]).forEach(([key, value]) => root.style.setProperty(key, value));

                appendLine(`Theme changed to <span class="color-ai">${themeName}</span>.`, "color-system");

            } else {

                appendLine(`Theme not found. Available themes: ${Object.keys(THEMES).join(', ')}`, "color-error");

            }

        },

        alias: (args) => {

            if (args.length === 0) {

                Object.entries(aliases).forEach(([name, cmd]) => appendLine(`alias ${name}='${cmd}'`));

                return;

            }

            const declaration = args.join(' ');

            const match = declaration.match(/^([a-zA-Z0-9]+)='(.*?)'$/);

            if(match) {

                aliases[match[1]] = match[2];

                appendLine(`Alias created: ${match[1]} -> ${match[2]}`, 'color-system');

            } else {

                appendLine(`Usage: alias [name]='[command]'`, 'color-error');

            }

        },

        neofetch: () => {

            appendLine(`

<span class="prompt-user">user@aetherius</span>

------------------

<span class="color-system">OS</span>: Aetherius Terminal v3 (Web)

<span class="color-system">Host</span>: Your Browser

<span class="color-system">Kernel</span>: JavaScript

<span class="color-system">Uptime</span>: since page load

<span class="color-system">Shell</span>: aetherius.js

<span class="color-system">AI Model (Gemini)</span>: ${API_KEYS['gemini'] ? 'gemini-1.5-flash' : 'N/A'}

<span class="color-system">AI Model (Gemini Pro)</span>: ${API_KEYS['gemini-pro'] ? 'gemini-1.5-pro' : 'N/A'}

<span class="color-system">AI Model (ChatGPT)</span>: ${API_KEYS['chatgpt'] ? 'Simulated' : 'N/A'}

<span class="color-system">AI Model (Grok)</span>: ${API_KEYS['grok'] ? 'Simulated' : 'N/A'}

<span class="color-system">AI Model (DeepSeek)</span>: ${API_KEYS['deepseek'] ? 'Simulated' : 'N/A'}

            `);

        },

        man: (args) => { 

             appendLine(`Manual for <span class='color-ai'>${args[0]}</span>:\nNo detailed manual pages yet. Try 'help'.`, 'color-system') 

        },

    };



    // --- 5. Main Execution Loop ---

    const processCommand = async (commandStr) => {

        appendLine(`<span id="prompt-context">${promptContext.innerHTML}</span><span class="prompt-arrow">></span> ${commandStr}`, "");

        if(commandStr) {

            commandHistory = commandHistory.filter(c => c !== commandStr);

            commandHistory.unshift(commandStr);

            if(commandHistory.length > 50) commandHistory.pop();

        }

        historyIndex = -1;



        let [cmd, ...args] = commandStr.trim().split(/\s+/);

        if (!cmd) return;

        

        // Alias replacement

        if (aliases[cmd]) {

            const aliasedCommand = aliases[cmd];

            appendLine(`~ executing alias: <span class="color-ai">${aliasedCommand}</span>`, 'color-system');

            [cmd, ...args] = aliasedCommand.trim().split(/\s+/);

        }



        if (cmd.startsWith('@')) {

            const agent = cmd.toLowerCase();

            let promptKey;

            let modelToUse = 'gemini-1.5-flash'; // Default model

            let apiIdToUse = 'gemini'; // Default API ID

            let fileContentForAI = null; // Used for agents that read file content



            switch(agent) {

                case '@coder':

                    promptKey = 'coder';

                    if (API_KEYS['gemini-pro']) {

                        modelToUse = 'gemini-1.5-pro';

                        apiIdToUse = 'gemini-pro';

                    }

                    break;

                case '@sysadmin':

                    promptKey = 'sysadmin';

                    break;

                case '@git':

                    promptKey = 'git';

                    break;

                case '@designer':

                    promptKey = 'designer';

                    break;

                case '@data':

                    promptKey = 'data';

                    break;

                case '@gen_code': 

                    promptKey = 'code_generator';

                    if (API_KEYS['gemini-pro']) {

                        modelToUse = 'gemini-1.5-pro';

                        apiIdToUse = 'gemini-pro';

                    }

                    break;

                case '@debug': 

                case '@refactor': 

                case '@test':

                case '@explain_code': // New agent

                case '@lint_format': // New agent

                    if (!args[0]) { appendLine(`${agent}: missing file operand. Usage: ${agent} <file>`, "color-error"); return; }

                    const fileNode = getNode(context.path + '/' + args[0]);

                    if (!fileNode || fileNode.type !== 'file') {

                        appendLine(`${agent}: ${args[0]}: No such file or not a file`, "color-error");

                        return;

                    }

                    fileContentForAI = fileNode.content; // Capture file content

                    if (API_KEYS['gemini-pro']) { // These agents benefit from Pro model

                        modelToUse = 'gemini-1.5-pro';

                        apiIdToUse = 'gemini-pro';

                    }



                    if (agent === '@debug') promptKey = 'debugger';

                    else if (agent === '@refactor') promptKey = 'refactorer';

                    else if (agent === '@test') promptKey = 'tester';

                    else if (agent === '@explain_code') promptKey = 'code_explainer';

                    else if (agent === '@lint_format') promptKey = 'linter_formatter';

                    

                    // Modify prompt for these agents to include file content

                    args = [`${args.join(' ')}\n\nCode from ${args[0]} (Type: ${context.project_type}):\n\n\`\`\`${fileContentForAI}\`\`\``];

                    break;

                case '@chatgpt':

                    promptKey = 'chatgpt';

                    apiIdToUse = 'chatgpt'; 

                    break;

                case '@grok':

                    promptKey = 'grok';

                    apiIdToUse = 'grok';

                    break;

                case '@deepseek':

                    promptKey = 'deepseek';

                    apiIdToUse = 'deepseek';

                    if (API_KEYS['gemini-pro']) { 

                        modelToUse = 'gemini-1.5-pro';

                    }

                    break;

                default:

                    appendLine(`Unknown agent: ${agent}`, "color-error");

                    return;

            }

            

            appendLine(`Querying <span class="color-agent-name">${agent}</span> agent (using ${apiIdToUse} - simulated by Gemini)...`, 'color-system');

            // Note: callAIAPI handles API Key prioritization and fallback internally

            const response = await callAIAPI(args.join(' '), GEMINI_PROMPTS[promptKey], modelToUse, apiIdToUse);

            if(response) {

                // Determine if response is a code block and highlight it

                const codeBlockMatch = response.match(/```(.*?)```/gs);

                if (codeBlockMatch) {

                    const codeContent = codeBlockMatch[0].replace(/```(.*)?\n/, '').replace(/```$/, '').trim();

                    let language = 'plaintext';

                    const langMatch = codeBlockMatch[0].match(/```(\w+)\n/);

                    if (langMatch && hljs.getLanguage(langMatch[1])) {

                        language = langMatch[1];

                    } else { // Fallback based on common coding contexts

                        if (agent === '@coder' || agent === '@gen_code' || agent === '@deepseek' || context.project_type === 'Python') {

                            language = 'python';

                        } else if (context.project_type === 'Node.js') {

                            language = 'javascript';

                        } else if (agent === '@designer') {

                            language = 'xml'; // For HTML

                        }

                    }

                    // Display non-code parts if any

                    const preCodeText = response.substring(0, response.indexOf(codeBlockMatch[0])).trim();

                    if (preCodeText) appendLine(preCodeText, 'color-ai');



                    displayCode(codeContent, language);



                    const postCodeText = response.substring(response.indexOf(codeBlockMatch[0]) + codeBlockMatch[0].length).trim();

                    if (postCodeText) appendLine(postCodeText, 'color-ai');



                } else {

                    appendLine(response, 'color-ai'); // Display as plain text if no code block

                }

            }

        } else if (COMMANDS[cmd]) {

            COMMANDS[cmd](args);

        } else {

            // If command is not a built-in command and not an explicit AI agent, attempt code generation

            appendLine("Command not recognized. Attempting to send as code generation request to AI...", 'color-system');

            const codeResponse = await callAIAPI(commandStr, GEMINI_PROMPTS.code_generator, 'gemini-1.5-pro', 'gemini-pro'); 

            if (codeResponse) {

                const codeBlockMatch = codeResponse.match(/```(.*?)```/gs);

                if (codeBlockMatch) {

                    const codeContent = codeBlockMatch[0].replace(/```(.*)?\n/, '').replace(/```$/, '').trim();

                    let language = 'plaintext';

                    const langMatch = codeBlockMatch[0].match(/```(\w+)\n/);

                    if (langMatch && hljs.getLanguage(langMatch[1])) {

                        language = langMatch[1];

                    } else { // Fallback based on common coding contexts

                        if (context.project_type === 'Python') {

                            language = 'python';

                        } else if (context.project_type === 'Node.js') {

                            language = 'javascript';

                        } else {

                            language = 'plaintext';

                        }

                    }

                    appendLine(`AI auto-generated code:`, 'color-ai');

                    displayCode(codeContent, language);

                    appendLine(`You can try to 'edit [filename]' to save it, then 'run [filename]' to simulate execution.`, 'color-system');



                } else {

                    // If AI did not generate a code block, fall back to trying command translation

                    appendLine(`AI did not directly generate code. Attempting as command translation request...`, 'color-system');

                    const proposedCommand = await callAIAPI(commandStr, GEMINI_PROMPTS.command_translator, 'gemini-1.5-flash', 'gemini');

                    if (proposedCommand) {

                        if (proposedCommand === 'AETHERIUS_CANNOT_TRANSLATE') {

                            appendLine("Could not translate to command or generate code. For general questions, try agents like <span class='color-ai'>@coder</span>.", 'color-warning');

                        } else {

                            appendLine(`AI Suggestion:<div class="color-suggestion">${proposedCommand}</div>(This is a <span class="color-warning">simulation</span>. No real commands are executed.)`, 'color-system');

                        }

                    } else {

                        appendLine("AI failed to respond to your request.", "color-error");

                    }

                }

            } else {

                appendLine("AI failed to generate a response.", "color-error");

            }

        }

    };

    

    // --- 6. Event Listeners ---

    // API Key panel toggle functionality

    apiKeyHeader.addEventListener('click', () => {

        if (apiKeyPanelContent.style.display === 'none' || apiKeyPanelContent.style.display === '') {

            apiKeyPanelContent.style.display = 'flex';

            apiKeyToggleIcon.textContent = '▼';

            localStorage.setItem('api_key_panel_expanded', 'true');

        } else {

            apiKeyPanelContent.style.display = 'none';

            apiKeyToggleIcon.textContent = '▲';

            localStorage.setItem('api_key_panel_expanded', 'false');

        }

    });



    // Add event listeners for all save buttons

    apiKeySaveBtns.forEach(button => {

        button.addEventListener('click', () => {

            const apiId = button.dataset.apiId;

            const keyInputId = `${apiId}-api-key-input`;

            const statusElementId = `${apiId}-api-key-status`;

            saveApiKey(apiId, keyInputId, statusElementId);

        });

    });



    // Add Enter key listener for all API Key input fields

    document.querySelectorAll('.api-key-item input[type="password"]').forEach(input => {

        input.addEventListener('keydown', (e) => {

            if (e.key === 'Enter') {

                const apiId = e.target.id.replace('-api-key-input', '');

                const keyInputId = e.target.id;

                const statusElementId = `${apiId}-api-key-status`;

                saveApiKey(apiId, keyInputId, statusElementId);

            }

        });

    });



    // Edit Modal Event Listeners

    saveEditBtn.addEventListener('click', () => {

        if (currentEditFilePath) {

            const { parentNode, name } = getParentNodeAndName(currentEditFilePath);

            if (parentNode && parentNode.children && parentNode.children[name]) {

                parentNode.children[name].content = editTextArea.value;

                appendLine(`File '${name}' saved successfully.`, "color-system");

                saveFS(); // Save FS after editing

            }

            editModal.style.display = 'none'; // Hide the modal

            currentEditFilePath = null;

            commandInput.focus(); // Return focus to command input

        }

    });



    cancelEditBtn.addEventListener('click', () => {

        editModal.style.display = 'none'; // Hide the modal

        currentEditFilePath = null;

        appendLine(`Edit cancelled.`, "color-warning");

        commandInput.focus(); // Return focus to command input

    });



    // Allow Tab key within textarea for actual indentation

    editTextArea.addEventListener('keydown', (e) => {

        if (e.key === 'Tab') {

            e.preventDefault();

            const start = editTextArea.selectionStart;

            const end = editTextArea.selectionEnd;

            const value = editTextArea.value;



            editTextArea.value = value.substring(0, start) + '\t' + value.substring(end);

            editTextArea.selectionStart = editTextArea.selectionEnd = start + 1;

        }

    });



    // Confirmation Modal Event Listeners

    confirmYesBtn.addEventListener('click', () => {

        if (confirmCallback) {

            confirmCallback(true);

        }

        confirmModal.style.display = 'none';

        confirmCallback = null;

    });



    confirmNoBtn.addEventListener('click', () => {

        if (confirmCallback) {

            confirmCallback(false);

        }

        confirmModal.style.display = 'none';

        confirmCallback = null;

    });





    commandInput.addEventListener('keydown', (e) => {

        const handleKeyDown = {

            'Enter': () => {

                if(commandInput.value.trim() !== ''){

                    e.preventDefault();

                    processCommand(commandInput.value);

                    commandInput.value = '';

                }

            },

            'ArrowUp': () => {

                e.preventDefault();

                if (historyIndex < commandHistory.length - 1) {

                    historyIndex++;

                    commandInput.value = commandHistory[historyIndex];

                }

            },

            'ArrowDown': () => {

                e.preventDefault();

                if (historyIndex > 0) {

                    historyIndex--;

                    commandInput.value = commandHistory[historyIndex];

                } else {

                    historyIndex = -1;

                    commandInput.value = '';

                }

            },

            'Tab': (event) => {

                event.preventDefault(); // Prevent default tab behavior

                const text = commandInput.value;

                const node = getNode(context.path);

                const fileItems = node && node.children ? Object.keys(node.children) : [];

                // Include all agent commands and new commands for autocompletion

                const allCompletions = [...Object.keys(COMMANDS), ...Object.keys(aliases), ...fileItems, ...Object.keys(THEMES), 

                                        '@coder', '@sysadmin', '@git', '@designer', '@data', '@gen_code', '@debug', '@refactor', '@test', '@explain_code', '@lint_format', '@chatgpt', '@grok', '@deepseek']; 

                const matches = allCompletions.filter(item => item.startsWith(text));

                

                if (matches.length === 1) {

                    commandInput.value = matches[0] + ' ';

                } else if (matches.length > 1) {

                    appendLine(matches.join('  '), 'color-ai');

                }

            }

        };

        if (handleKeyDown[e.key]) handleKeyDown[e.key]();

    });

    

    terminal.addEventListener('click', (e) => {

      // Don't steal focus from text selection

      if(window.getSelection().toString() === ''){

          commandInput.focus()

      }

    });

    

    // --- 7. App Initialization ---

    buildFS(); // Load or build filesystem

    displayWelcomeMessage();

    updatePrompt();

    // Restore API Key panel state

    const panelExpanded = localStorage.getItem('api_key_panel_expanded');

    if (panelExpanded === 'false') {

        apiKeyPanelContent.style.display = 'none';

        apiKeyToggleIcon.textContent = '▲';

    } else {

        apiKeyPanelContent.style.display = 'flex';

        apiKeyToggleIcon.textContent = '▼';

    }



    // Attempt to focus on the command input field on initial load

    commandInput.focus();

});

</script>
</body>
</html>