1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
|
// Extracted from newOS4 index.html — WebX11AIAssistantModule (Full Agent Loop)
class WebX11AIAssistantModule {
constructor() {
this.commands = {}; this.terminal = null;
this.systemPrompt = this.buildSystemPrompt();
this.context = []; this.maxContext = 10;
this.maxContextTokens = 2000;
this.MAX_TOOL_TURNS = 8;
this._pendingConfirmation = null;
this._confirmResolve = null;
this._errorLog = [];
this._commandFreq = {};
this._messageCount = 0;
this._userProfile = {};
this._sessionMemoryLoaded = false;
this._sessionSaved = false;
this._thinkingTimer = null;
this._thinkingStartTime = 0;
this._toolDefs = null;
try { const s = localStorage.getItem('webx11_ai_patterns'); if (s) this._commandFreq = JSON.parse(s); } catch (e) {}
try { const p = localStorage.getItem('webx11_user_profile'); if (p) this._userProfile = JSON.parse(p); } catch (e) {}
// Restore AI conversation context from localStorage
try {
const saved = localStorage.getItem('webx11_ai_context');
if (saved) {
const parsed = JSON.parse(saved);
if (parsed && Array.isArray(parsed.context)) {
this.context = parsed.context;
this._messageCount = parsed.messageCount || 0;
}
}
} catch (e) {}
}
buildSystemPrompt() {
const now = new Date();
const dateStr = now.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
const timeStr = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
const optimizationActive = this.terminal?.ollamaManager?.optimizationEnabled !== false;
const CR = String.fromCharCode(10);
const optNote = CR + CR + '== TOOL EXECUTION RULES (STRICT) ==' + CR + 'STRICT RULE 1: NEVER describe what the filesystem looks like from your training data. ALWAYS call list_files() or read_file() first, then report the ACTUAL result.' + CR + 'STRICT RULE 2: If you return text without calling any tool, you have failed. Use tools for every factual question.' + CR + 'STRICT RULE 3: A response like "/bin/, /etc/, /home/" without calling list_files is ILLEGAL. Call the tool.' + CR + 'STRICT RULE 4: When calling a tool, base your answer ENTIRELY on the tool result. If result is empty, say "empty".' + CR + CR;
return `Current date: ${dateStr}\nCurrent time: ${timeStr}\n\nYou are WebX11AI, the AI assistant embedded in the WebX11 browser terminal. You have direct access to read/write files, search the web, install packages, edit modules, and run terminal commands — all via tool calls. Use tools proactively. Keep responses concise.${optNote}== TOOL REFERENCE ==
You have these tools available. Use them WITHOUT asking permission unless the tool description says (DESTRUCTIVE):
FILESYSTEM:
- list_files(path?) — List files in VFS directory (omit for current dir)
- read_file(path) — Read file content (truncated past 8000 chars)
- write_file(path, content) — Write to file (DESTRUCTIVE — confirm with user first)
- make_directory(path) — Create a directory (DESTRUCTIVE — confirm first)
- delete_file(path) — Delete file (DESTRUCTIVE — confirm first)
- get_current_dir — Show current working directory
SYSTEM:
- get_status — Show filesystem, modules, Ollama, memory status
- get_help — List all available terminal commands
- run_command(command) — Execute any terminal command and capture output
- font-size <8-32> — Change terminal font size (persists in localStorage)
SEARCH:
- web_search(query) — Search the web via proxy API (SearXNG + DDG fallback, results with title/url/snippet)
- web_fetch(url) — Fetch and extract readable content from a URL via proxy API (returns title + clean text + word count)
PACKAGES:
- wpm_install(package) — Install WPM package by name (e.g. "widget", "calc")
- wpm_search(keyword) — Search available WPM packages
SKILLS (PERSISTENT PROCEDURAL MEMORY):
- list_skills(category?) — Browse available skills, optionally filtered by category
- load_skills(query) — Search skills relevant to current task. Call at START of every task.
- create_skill(name, description, content, tags, category) — Save a new stored procedure. Call after completing complex multi-step tasks (3+ tool calls).
- patch_skill(name, content) — Update an existing skill when the approach changes
MODULE SELF-IMPROVEMENT:
- view_module(name) — View source code of any loaded module
- edit_module(name) — Copy module into editor. Opens editor for modifications.
- test_module(name) — Load edited module from /_mods/ for live testing
- reload_module(name) — Discard edits and reload from original URL
- list_modified_modules — List modules with local edits pending
- get_module_status — Full status of all modules (loaded, modified, URLs)
== SKILLS WORKFLOW ==
1. At the START of every task, call load_skills(query) to check if a stored procedure exists
2. Follow the skill's steps. If they're wrong, call patch_skill to fix them.
3. After a complex multi-step task (3+ tool calls), call create_skill to save the approach
4. Skills persist in /skills/ as markdown files with YAML frontmatter
== MEMORY SYSTEM ==
- I maintain a conversation context (this.context) that persists across messages in this session
- The last ${this.maxContext} exchanges are remembered
- Type "ai-clear" to reset conversation memory
- Type "ai-context" to see what I remember
- Type "ai-model" to see/switch models
- Type "ai-stop" to cancel a running AI request
- Smart context profiles (set via "context <name>") adjust my temperature and system prompt style
- Saved prompts (via "prompt", "prompt-save") let you reuse template with {variable} substitution
== USER PROFILE ==
- Use user_get, user_set to read/write persistent user preferences across sessions
- user_set dot-notation supported: user_set knownFacts.name "Alex"
- Profile auto-stores known facts (name, project, preferences)
- Use session_save after complex tasks to log what was done
- Use session_load to review past sessions
- Use session_recent at start of session to remember what was worked on before
== SELF-IMPROVEMENT WORKFLOW ==
1. User asks for module changes → call get_module_status to list modules
2. Call view_module(name) to read the module source
3. Call edit_module(name) to copy source into editor for modification
4. After editing, call test_module(name) to load and test the edit
5. If it works, the user keeps it. If not, call reload_module(name).
== AUTO-IMPROVEMENT (SYSTEM-DRIVEN) ==
- If I encounter the same tool error 3+ times, a workaround skill is created automatically
- After complex tasks (3+ tool calls), I run health checks and suggest improvements
- I track conversation patterns and surface frequent topics
- Every 20 messages, skills are audited for staleness
- Use check_updates to verify module source URLs are reachable
== RESPONSE STYLE ==
- Be concise. Use bullet points for lists.
- When using tools, explain what you're doing briefly.
- If a tool fails, try an alternative approach.
- For web research tasks: search first, then analyze the results, then present findings.
|- When the user says "update" or "improve" without specifics, use get_status + get_help to understand the current state first.
== REACT PROTOCOL ==
For every task, follow this cycle:
1. **REASON** — Think about what you need next. What information is missing?
2. **ACT** — Call ONE tool at a time (unless multiple independent lookups are needed).
3. **OBSERVE** — Study the tool result carefully. Did it succeed? Is the data useful?
4. **DECIDE** — Do you have enough to answer? If not, go back to step 1.
RULES:
- Call tools in sequence when the second depends on the first result
- Independent lookups (e.g. reading two unrelated files) can run in parallel
- If a tool returns an error, try a different approach before giving up
- After 6 tool turns, start synthesizing a final answer
- Always provide a complete, helpful final answer — don't leave the user hanging`;
}
getToolDefinitions() {
if (!this._toolDefs) this._toolDefs = this._buildToolDefs();
return this._toolDefs;
}
_buildToolDefs() {
return [{
type: 'function',
function: {
name: 'list_files',
description: 'List VFS directory contents',
parameters: { type: 'object', properties: { path: { type: 'string', description: 'Dir path ("" for root)' } }, required: [] }
}
}, {
type: 'function',
function: {
name: 'read_file',
description: 'Read VFS file',
parameters: { type: 'object', properties: { path: { type: 'string', description: 'File path' } }, required: ['path'] }
}
}, {
type: 'function',
function: {
name: 'write_file',
description: 'Write file (DESTRUCTIVE)',
parameters: { type: 'object', properties: { path: { type: 'string', description: 'File path' }, content: { type: 'string', description: 'Content' } }, required: ['path', 'content'] }
}
}, {
type: 'function',
function: {
name: 'make_directory',
description: 'Create VFS directory',
parameters: { type: 'object', properties: { path: { type: 'string', description: 'Dir name' } }, required: ['path'] }
}
}, {
type: 'function',
function: {
name: 'delete_file',
description: 'Delete file or empty dir (DESTRUCTIVE)',
parameters: { type: 'object', properties: { path: { type: 'string', description: 'Path to delete' } }, required: ['path'] }
}
}, {
type: 'function',
function: {
name: 'get_status',
description: 'System status: FS, modules, memory',
parameters: { type: 'object', properties: {}, required: [] }
}
}, {
type: 'function',
function: {
name: 'get_help',
description: 'Command reference',
parameters: { type: 'object', properties: {}, required: [] }
}
}, {
type: 'function',
function: {
name: 'web_search',
description: 'Search web via SearXNG + DDG',
parameters: { type: 'object', properties: { query: { type: 'string', description: 'Search query' } }, required: ['query'] }
}
}, {
type: 'function',
function: {
name: 'web_fetch',
description: 'Fetch & extract URL content',
parameters: { type: 'object', properties: { url: { type: 'string', description: 'Full URL' } }, required: ['url'] }
}
}, {
type: 'function',
function: {
name: 'wpm_install',
description: 'Install WPM package',
parameters: { type: 'object', properties: { package: { type: 'string', description: 'Package name' } }, required: ['package'] }
}
}, {
type: 'function',
function: {
name: 'wpm_search',
description: 'Search WPM packages',
parameters: { type: 'object', properties: { keyword: { type: 'string', description: 'Keyword' } }, required: ['keyword'] }
}
}, {
type: 'function',
function: {
name: 'run_command',
description: 'Run terminal command',
parameters: { type: 'object', properties: { command: { type: 'string', description: 'Command to run' } }, required: ['command'] }
}
}, {
type: 'function',
function: {
name: 'get_current_dir',
description: 'Current VFS directory',
parameters: { type: 'object', properties: {}, required: [] }
}
}, {
type: 'function',
function: {
name: 'view_module',
description: 'View module source code',
parameters: { type: 'object', properties: { name: { type: 'string', description: 'Module class name' } }, required: ['name'] }
}
}, {
type: 'function',
function: {
name: 'edit_module',
description: 'Edit module source (DESTRUCTIVE)',
parameters: { type: 'object', properties: { name: { type: 'string', description: 'Module class name' } }, required: ['name'] }
}
}, {
type: 'function',
function: {
name: 'test_module',
description: 'Test edited module from /_mods/',
parameters: { type: 'object', properties: { name: { type: 'string', description: 'Module class name' } }, required: ['name'] }
}
}, {
type: 'function',
function: {
name: 'reload_module',
description: 'Reload module from original URL',
parameters: { type: 'object', properties: { name: { type: 'string', description: 'Module class name' } }, required: ['name'] }
}
}, {
type: 'function',
function: {
name: 'list_modified_modules',
description: 'List modules with local edits',
parameters: { type: 'object', properties: {}, required: [] }
}
}, {
type: 'function',
function: {
name: 'get_module_status',
description: 'Module status: loaded, modified, URLs',
parameters: { type: 'object', properties: {}, required: [] }
}
}, {
type: 'function',
function: {
name: 'load_skills',
description: 'Search skills relevant to task',
parameters: { type: 'object', properties: { query: { type: 'string', description: 'Task description' } }, required: ['query'] }
}
}, {
type: 'function',
function: {
name: 'create_skill',
description: 'Save a new skill',
parameters: { type: 'object', properties: {
name: { type: 'string', description: 'kebab-case name' },
description: { type: 'string', description: 'One-line description' },
content: { type: 'string', description: 'Markdown with YAML frontmatter' },
tags: { type: 'string', description: 'Comma-separated' },
category: { type: 'string', description: 'e.g. research, system, dev' }
}, required: ['name', 'description', 'content'] }
}
}, {
type: 'function',
function: {
name: 'patch_skill',
description: 'Replace skill content',
parameters: { type: 'object', properties: {
name: { type: 'string', description: 'Skill name' },
content: { type: 'string', description: 'New markdown content' }
}, required: ['name', 'content'] }
}
}, {
type: 'function',
function: {
name: 'list_skills',
description: 'Browse skills (optional filter)',
parameters: { type: 'object', properties: { category: { type: 'string', description: 'Filter by category' } }, required: [] }
}
}, {
type: 'function',
function: {
name: 'check_updates',
description: 'Check module URLs are reachable',
parameters: { type: 'object', properties: {}, required: [] }
}
}, {
type: 'function',
function: {
name: 'user_get',
description: 'Read user profile key',
parameters: { type: 'object', properties: { key: { type: 'string', description: 'e.g. preferredModel' } }, required: ['key'] }
}
}, {
type: 'function',
function: {
name: 'user_set',
description: 'Write user profile key',
parameters: { type: 'object', properties: { key: { type: 'string', description: 'Profile key' }, value: { type: 'string', description: 'Value' } }, required: ['key', 'value'] }
}
}, {
type: 'function',
function: {
name: 'user_list',
description: 'List stored profile keys',
parameters: { type: 'object', properties: {}, required: [] }
}
}, {
type: 'function',
function: {
name: 'user_forget',
description: 'Delete profile key',
parameters: { type: 'object', properties: { key: { type: 'string', description: 'Key to delete' } }, required: ['key'] }
}
}, {
type: 'function',
function: {
name: 'session_save',
description: 'Save session summary',
parameters: { type: 'object', properties: { summary: { type: 'string', description: 'What was accomplished' } }, required: ['summary'] }
}
}, {
type: 'function',
function: {
name: 'session_load',
description: 'Load past session by date',
parameters: { type: 'object', properties: { date: { type: 'string', description: 'YYYY-MM-DD' } }, required: ['date'] }
}
}, {
type: 'function',
function: {
name: 'session_recent',
description: 'Show recent sessions',
parameters: { type: 'object', properties: { count: { type: 'number', description: 'Count (default 3)' } }, required: [] }
}
}, {
type: 'function',
function: {
name: 'session_terminal',
description: 'Read last terminal output',
parameters: { type: 'object', properties: {}, required: [] }
}
}, {
type: 'function',
function: {
name: 'session_stats',
description: 'Session aggregate stats',
parameters: { type: 'object', properties: {}, required: [] }
}
}];
}
getHelpInfo() {
return {
'ai': 'ai <question> — Ask the AI assistant anything',
'ask': 'ask <question> — Alias for ai command',
'ai-clear': 'ai-clear — Clear conversation context',
'ai-system': 'ai-system <prompt> — Set system prompt',
'ai-context': 'ai-context — Show current conversation context',
'ai-allow': 'ai-allow — Confirm pending AI action',
'ai-deny': 'ai-deny — Deny pending AI action',
'ai-stop': 'ai-stop — Cancel current AI operation',
'ai-model': 'ai-model [model] — Show or set AI model'
};
}
registerCommands() {
this.commands['ai'] = (args) => this.chat(args);
this.commands['ask'] = (args) => this.chat(args);
this.commands['ai-clear'] = () => this.clearContext();
this.commands['ai-system'] = (args) => this.setSystemPrompt(args);
this.commands['ai-context'] = () => this.showContext();
this.commands['ai-allow'] = () => this.confirmPending();
this.commands['ai-deny'] = () => this.denyPending();
this.commands['ai-stop'] = () => this.cancelAi();
this.commands['ai-model'] = (args) => this.showModel(args);
this.commands['ai-compress'] = () => this._manualCompress();
}
async chat(args) {
const userMessage = args.join(' ');
if (!userMessage) {
this.terminal.print('Usage: ai <your-question>', 'warning'); return;
}
this._cancelled = false;
this.terminal.setAiBusy(true);
const lockStart = Date.now();
while (this._chatLock) {
if (Date.now() - lockStart > 10000) {
this._chatLock = false;
this.terminal.print('⚠️ Chat lock timed out — force released', 'warning');
break;
}
await new Promise(r => setTimeout(r, 50));
}
this._chatLock = true;
this.terminal.markDirty();
// Re-read context from localStorage (auto-restore may have written it after init)
this._loadContext();
// Compress context if it exceeds the token threshold
this._compressContext();
let loopResult;
try {
const messages = [
{ role: 'system', content: this.systemPrompt }
];
this.context.slice().forEach(msg => messages.push(msg));
messages.push({ role: 'user', content: userMessage });
this.terminal.print('🤖 WebX11AI thinking...', 'info');
// Ensure skills directory exists and seed defaults on first run
this.terminal.fs.mkdirRecursive('/skills');
if (!this.terminal.fs.readFile('/skills/_seeded')) {
try {
await this._seedDefaultSkills();
} catch (e) { /* non-critical */ }
}
// Auto-load skills relevant to the user's query (awaited, not fire-and-forget)
// Skip skill loading for trivial queries (< 10 chars, no actionable keywords)
const optEnabled = this.terminal?.ollamaManager?.optimizationEnabled !== false;
const isTrivial = optEnabled && userMessage.length < 10 && !/\b(search|write|install|edit|create|make|find|delete|remove|change|update|improve|add|fix|build|set|load|save|help)\b/i.test(userMessage);
if (!isTrivial) {
try {
const skillRes = await this.runTool('load_skills', { query: userMessage });
const skillData = JSON.parse(skillRes);
if (skillData && skillData.matches && skillData.matches.length > 0) {
const skillNotes = skillData.matches.map(m => `[Skill: ${m.name}] ${m.content}`).join('\n\n---\n\n');
messages.push({ role: 'system', content: `Relevant skills for this task:\n\n${skillNotes}\n\nUse the steps above as guidance. If they're wrong or outdated, use patch_skill to fix them after the task.` });
this.terminal.print(`📚 Loaded ${skillData.count} relevant skill(s)`, 'info');
}
} catch (e) { /* skills not available yet — first run */ }
}
// Track conversation patternsfor learning
this._trackPattern(userMessage);
// Extract facts from user message
this._extractFacts(userMessage, '');
// On first message of session, auto-load recent memory
if (!this._sessionMemoryLoaded) {
this._sessionMemoryLoaded = true;
this.terminal.fs.mkdirRecursive('/memory');
try {
const recentRes = await this.runTool('session_recent', { count: 3 });
const rd = JSON.parse(recentRes);
if (rd.sessions && rd.sessions.length > 0) {
const memNotes = rd.sessions.map(s => '[' + s.date + '] ' + (s.tasks || 1) + ' tasks: ' + (s.summary || 'No summary')).join('\n');
messages.push({ role: 'system', content: 'Recent sessions:\n' + memNotes + '\nThis provides continuity. Refer to past work when relevant.' });
this.terminal.print('📖 Loaded ' + rd.sessions.length + ' recent session(s)', 'info');
}
} catch (e) {}
}
loopResult = await this.agenticLoop(messages);
this.context.push({ role: 'user', content: userMessage });
if (loopResult.finalAnswer) {
this.context.push({ role: 'assistant', content: loopResult.finalAnswer });
}
if (this.context.length > this.maxContext * 2) {
this.context = this.context.slice(-this.maxContext * 2);
}
// Reflection: after complex tasks, run health scan and auto-skill creation
if (loopResult.toolTurns >= 2 && !this._cancelled) {
await this.afterActionReflection(userMessage, loopResult.toolTurns);
}
// Auto-create skills from repeated errors
if (this._errorLog.length >= 3) {
await this._autoCreateErrorSkill();
}
// Skill quality audit every 20 messages
this._messageCount++;
if (this._messageCount % 20 === 0) {
await this._auditSkills();
}
// Sound notification on AI response
if (this.terminal.playNotificationSound) {
setTimeout(() => this.terminal.playNotificationSound(), 100);
}
} finally {
this._chatLock = false;
this.terminal.setAiBusy(false);
// Persist conversation context after each exchange
this._saveContext();
// Log the AI interaction
this.terminal.log('INFO', 'AI', 'Query: ' + userMessage.substring(0, 100));
if (loopResult && loopResult.toolTurns) {
this.terminal.log('INFO', 'AI', 'Used ' + loopResult.toolTurns + ' tool(s)');
}
}
// Register session save on page unload (runs once per session)
if (!this._sessionSaved) {
this._sessionSaved = true;
window.addEventListener('beforeunload', () => {
this.terminal.fs.mkdirRecursive('/memory');
const today = new Date().toISOString().split('T')[0];
const index = this.terminal.fs.fsReadJSON('/memory/index.json') || {};
index[today] = index[today] || { summary: 'Session in progress', tasks: 0 };
index[today].tasks = (index[today].tasks || 0) + 1;
index[today].updated = new Date().toISOString();
this.terminal.fs.fsWriteJSON('/memory/index.json', index);
// Also persist AI context on page close
this._saveContext();
});
}
}
_summarizeObservation(result, maxLen) {
if (!result || typeof result !== 'string' || result.length <= maxLen) return result || '';
const lines = result.split('\n');
if (lines.length > 5) {
return lines.slice(0, 2).join('\n') + '\n...(' + (lines.length - 4) + ' more lines)...\n' + lines.slice(-2).join('\n');
}
return result.substring(0, maxLen) + '...(truncated from ' + result.length + ' chars)';
}
_isToolError(result) {
if (!result || typeof result !== 'string') return null;
const trimmed = result.trim();
if (trimmed.startsWith('{"error":') || trimmed.startsWith("{'error':")) {
try { const parsed = JSON.parse(trimmed); return parsed.error || null; }
catch (e) { return null; }
}
return null;
}
_trackToolFailure(toolName, error) {
try {
if (!this._toolFailuresBuffer) this._toolFailuresBuffer = {};
if (!this._toolFailuresBuffer[toolName]) this._toolFailuresBuffer[toolName] = { count: 0, last: '', errors: [] };
const entry = this._toolFailuresBuffer[toolName];
entry.count++;
entry.last = new Date().toISOString();
entry.errors.push(error);
if (entry.errors.length > 5) entry.errors.shift();
if (entry.count >= 3) {
this.terminal.print(`⚠️ Tool '${toolName}' has failed ${entry.count} times. Consider creating a workaround skill.`, 'warning');
}
if (this._toolFailureFlushTimer) clearTimeout(this._toolFailureFlushTimer);
this._toolFailureFlushTimer = setTimeout(() => this._flushToolFailures(), 2000);
} catch (e) { /* ignore */ }
}
_flushToolFailures() {
try {
if (!this._toolFailuresBuffer || Object.keys(this._toolFailuresBuffer).length === 0) return;
const key = 'webx11_tool_failures';
const raw = localStorage.getItem(key) || '{}';
const map = JSON.parse(raw);
for (const [toolName, entry] of Object.entries(this._toolFailuresBuffer)) {
if (!map[toolName]) map[toolName] = { count: 0, last: '', errors: [] };
map[toolName].count += entry.count;
map[toolName].last = entry.last;
map[toolName].errors.push(...entry.errors);
if (map[toolName].errors.length > 10) map[toolName].errors = map[toolName].errors.slice(-10);
}
localStorage.setItem(key, JSON.stringify(map));
this._toolFailuresBuffer = {};
} catch (e) { /* ignore */ }
}
async agenticLoop(messages) {
let toolTurns = 0;
while (toolTurns < this.MAX_TOOL_TURNS) {
if (this._cancelled) { this.terminal.print('AI loop cancelled', 'warning'); return { finalAnswer: null, toolTurns }; }
toolTurns++;
// On last turn, inject wrap-up prompt
if (toolTurns === this.MAX_TOOL_TURNS) {
this.terminal.print(`⏱ Final turn (${toolTurns}/${this.MAX_TOOL_TURNS}) — AI must provide final answer`, 'warning');
messages.push({ role: 'system', content: 'This is your last tool turn. You MUST provide a final answer after this tool call. Synthesize what you know.' });
}
const thinkStart = Date.now();
const res = await this.terminal.ollamaManager.chatWithTools(messages, this.getToolDefinitions());
const thinkTime = Math.round((Date.now() - thinkStart) / 1000);
if (this._cancelled) return { finalAnswer: null, toolTurns };
if (res.error) { this.terminal.print(`⚠️ AI model error (${thinkTime}s): ${res.error}`, 'error'); return { finalAnswer: null, toolTurns }; }
if (res.message && !res.tool_calls) {
const text = res.message.content || '';
this.terminal.printAIResponse(text || '(no response)');
if (text) this.terminal.ollamaManager.fireResponseHooks(text);
this.terminal.print(`💬 AI answered (turn ${toolTurns}/${this.MAX_TOOL_TURNS}, ${thinkTime}s)`, 'info');
return { finalAnswer: text, toolTurns };
}
if (res.tool_calls && res.tool_calls.length > 0) {
this.terminal.print(`🔧 AI wants ${res.tool_calls.length} tool(s) — turn ${toolTurns}/${this.MAX_TOOL_TURNS} (${thinkTime}s)`, 'info');
messages.push(res.message);
let pendingText = res.message?.content || null;
const destructiveTools = res.tool_calls.filter(tc => this.isDestructive(tc.function.name));
const safeTools = res.tool_calls.filter(tc => !this.isDestructive(tc.function.name));
// Execute non-destructive tools in parallel (independent read-only operations)
const safeResults = await Promise.all(safeTools.map(async (tc) => {
const fn = tc.function;
const t0 = Date.now();
const toolResult = await this.runTool(fn.name, fn.arguments);
const t1 = Math.round((Date.now() - t0) / 1000);
return { fn, toolResult, t1 };
}));
for (const { fn, toolResult, t1 } of safeResults) {
this.terminal.print(`🔧 Tool: ${fn.name}(${typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments)})`, 'info');
const obs = this._summarizeObservation(toolResult, 150);
const err = this._isToolError(toolResult);
if (err) {
this.terminal.log('WARN', 'AI', `Tool ${fn.name} failed: ${err} (${t1}s)`);
this._trackToolFailure(fn.name, err);
this.terminal.print(`📊 Result (${t1}s): ⚠️ Error: ${err}`, 'warning');
} else {
this.terminal.log('INFO', 'AI', `Tool ${fn.name} ok (${t1}s)`);
this.terminal.print(`📊 Result (${t1}s): ${obs}`, 'info');
}
messages.push({ role: 'tool', content: toolResult });
}
// Only block on destructive tools
if (destructiveTools.length > 0) {
const approved = await this.confirmActionMulti(destructiveTools);
if (approved) {
for (const tc of destructiveTools) {
const fn = tc.function;
const t0 = Date.now();
this.terminal.print(`🔧 Tool: ${fn.name}(${typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments)})`, 'info');
const toolResult = await this.runTool(fn.name, fn.arguments);
const t1 = Math.round((Date.now() - t0) / 1000);
const dObs = this._summarizeObservation(toolResult, 150);
const dErr = this._isToolError(toolResult);
if (dErr) {
this.terminal.log('WARN', 'AI', `Tool ${fn.name} failed: ${dErr} (${t1}s)`);
this._trackToolFailure(fn.name, dErr);
this.terminal.print(`📊 Result (${t1}s): ⚠️ Error: ${dErr}`, 'warning');
} else {
this.terminal.log('INFO', 'AI', `Tool ${fn.name} ok (${t1}s)`);
this.terminal.print(`📊 Result (${t1}s): ${dObs}`, 'info');
}
messages.push({ role: 'tool', content: toolResult });
}
} else {
messages.push({
role: 'tool',
content: `Destructive actions (${destructiveTools.map(tc => tc.function.name).join(', ')}) denied by user. Non-destructive actions already executed.`
});
}
}
// Validator: check safe tool results for consistency
if (safeResults.length > 0 && pendingText) {
const om = this.terminal.ollamaManager;
if (om && om.validatorEnabled && om.validatorModel) {
let anyInvalid = false;
for (const { fn, toolResult } of safeResults) {
const valid = await om.validateToolResult(fn.name, fn.arguments, toolResult, pendingText || '');
if (!valid && !this._cancelled) {
anyInvalid = true;
this.terminal.print('🔍 Validator: ' + fn.name + ' result — AI note may not match (logged)', 'info');
// Just log it — don't force retry (cloud models get 400 on retry)
}
}
}
}
if (pendingText) {
messages.push({ role: 'assistant', content: pendingText });
}
continue;
}
return { finalAnswer: null, toolTurns };
}
// Loop exited without final answer — auto-summary
const toolNames = Object.keys(this._commandFreq).slice(-3).join(', ');
this.terminal.print(`🤖 AI reached the ${toolTurns}/${this.MAX_TOOL_TURNS} tool limit.`, 'warning');
this.terminal.print('Tools were executed but no final answer was produced — try a more specific query.', 'info');
return { finalAnswer: null, toolTurns };
}
async afterActionReflection(query, toolTurns) {
// Debounce: only suggest skill creation once per 30 minutes
const now = Date.now();
if (this._lastSkillSuggestion && (now - this._lastSkillSuggestion) < 1800000) {
return;
}
const suggestions = [];
const fs = this.terminal.fs;
try {
// Batch: read all status info in one VFS pass
const reg = this.terminal.moduleManager.moduleRegistry || [];
const total = reg.length;
const loaded = Object.keys(this.terminal.moduleManager.modules).length;
if (loaded < total) {
suggestions.push(loaded + '/' + total + ' modules loaded — use loadmod to restore');
}
} catch (e) {}
try {
const skillIdx = fs.fsReadJSON('/skills/index.json');
const skillCount = skillIdx ? Object.keys(skillIdx).length : 0;
if (skillCount === 0 && toolTurns >= 4) {
suggestions.push('Save this approach as a skill with create_skill');
this._lastSkillSuggestion = now;
}
} catch (e) {}
try {
const modsDir = fs.getCurrentDir();
const mc = modsDir.content['_mods'];
const modCount = mc && mc.content ? Object.keys(mc.content).filter(k => k.endsWith('.js') && !k.endsWith('.orig.js')).length : 0;
if (modCount > 0) {
suggestions.push(modCount + ' pending module edit(s) in /_mods/ — use test_module to verify');
}
} catch (e) {}
try {
if (performance.memory && performance.memory.usedJSHeapSize > 100 * 1048576) {
suggestions.push('High memory (' + (performance.memory.usedJSHeapSize / 1048576).toFixed(0) + 'MB) — consider clearing terminal');
}
} catch (e) {}
if (toolTurns >= 4 && suggestions.length === 0) {
suggestions.push('Used ' + toolTurns + ' tools — create a skill to save this workflow');
this._lastSkillSuggestion = now;
}
if (suggestions.length > 0) {
this.terminal.print('💡 ' + suggestions.join(' | '), 'info');
}
}
async confirmActionMulti(toolCalls) {
const names = toolCalls.map(tc => tc.function.name).join(', ');
const args = toolCalls.map(tc => typeof tc.function.arguments === 'string' ? tc.function.arguments : JSON.stringify(tc.function.arguments)).join(' | ');
const truncatedArgs = args.length > 60 ? args.substring(0, 60) + '...' : args;
this.terminal.printHTML(`⚠️ AI wants to: ${names}(${truncatedArgs}). <span class="cmd-link" onclick="webx11.executeCommand('ai-allow')" style="color:var(--success-color);cursor:pointer;text-decoration:underline;">ai-allow</span> to confirm, <span class="cmd-link" onclick="webx11.executeCommand('ai-deny')" style="color:var(--error-color);cursor:pointer;text-decoration:underline;">ai-deny</span> to refuse. (Auto-denies in 120s)`);
// Show confirm bar OUTSIDE scrollable output (always visible)
const area = document.getElementById('ai-confirm-area');
if (!area) {
// Fallback to promise resolve
return true;
}
area.innerHTML = `
<span class="confirm-desc">⚠️ ${names}(${truncatedArgs})</span>
<button class="confirm-btn" id="ai-confirm-allow" onclick="(function(){var a=document.getElementById('ai-confirm-allow');if(a.__allow) a.__allow();}).call(this)">✅ Allow</button>
<button class="confirm-btn deny" id="ai-confirm-deny" onclick="(function(){var d=document.getElementById('ai-confirm-deny');if(d.__deny) d.__deny();}).call(this)">❌ Deny</button>
<span class="confirm-timer" id="ai-confirm-timer"></span>
<span style="font-size:0.75em;color:var(--text-muted);width:100%;text-align:center">Type: ai-allow or ai-deny</span>
`;
area.classList.add('visible');
this._confirmArea = area;
this._confirmBar = area;
// Attach button handlers via both addEventListener + DOM property (inline onclick fallback)
const allowBtn = document.getElementById('ai-confirm-allow');
const denyBtn = document.getElementById('ai-confirm-deny');
const onAllow = () => {
this._resolveConfirm(true);
};
const onDeny = () => {
this._resolveConfirm(false);
};
allowBtn.addEventListener('click', onAllow);
denyBtn.addEventListener('click', onDeny);
allowBtn.__allow = onAllow;
denyBtn.__deny = onDeny;
const startTime = Date.now();
return new Promise((resolve) => {
this._pendingConfirmation = { names, args };
this._confirmResolve = resolve;
this._confirmAllowBtn = allowBtn;
this._confirmDenyBtn = denyBtn;
this._confirmOnAllow = onAllow;
this._confirmOnDeny = onDeny;
// Countdown timer updates with escalating visibility
const timerInterval = setInterval(() => {
const elapsed = Math.round((Date.now() - startTime) / 1000);
const remaining = Math.max(0, 120 - elapsed);
const timerEl = document.getElementById('ai-confirm-timer');
if (timerEl) {
timerEl.textContent = `⏱ ${remaining}s`;
timerEl.className = 'confirm-timer';
if (remaining > 30) {
timerEl.style.color = 'var(--warning-color)';
} else if (remaining > 10) {
timerEl.classList.add('urgent');
} else {
timerEl.classList.add('critical');
}
}
if (remaining === 60) {
this.terminal.print(`⏱ 60s remaining to respond to AI confirmation for: ${names}`, 'warning');
} else if (remaining === 30) {
this.terminal.print(`⏱ 30s — ${names} will be auto-denied soon!`, 'warning');
} else if (remaining === 10) {
this.terminal.print(`⏱ 10s remaining! Type ai-allow or click Allow now!`, 'warning');
}
}, 500);
this._confirmTimerInterval = timerInterval;
this._confirmTimeout = setTimeout(() => {
clearInterval(timerInterval);
if (this._confirmResolve) {
this._confirmResolve(false);
this._cleanupConfirmBar();
this.terminal.print('⏱ Confirmation timed out — tool not executed', 'warning');
}
}, 120000);
});
}
_resolveConfirm(approved) {
if (this._confirmResolve) {
this._confirmResolve(approved);
this._cleanupConfirmBar();
if (approved) {
this.terminal.print('Action allowed', 'success');
} else {
this.terminal.print('Action denied', 'warning');
}
}
}
_cleanupConfirmBar() {
clearInterval(this._confirmTimerInterval);
clearTimeout(this._confirmTimeout);
this._confirmTimeout = null;
this._confirmTimerInterval = null;
this._confirmResolve = null;
this._pendingConfirmation = null;
this._confirmAllowBtn = null;
this._confirmDenyBtn = null;
this._confirmOnAllow = null;
this._confirmOnDeny = null;
const area = document.getElementById('ai-confirm-area');
if (area) {
area.classList.remove('visible');
area.innerHTML = '';
}
this._confirmArea = null;
this._confirmBar = null;
const timerEl = document.getElementById('ai-confirm-timer');
if (timerEl) timerEl.style.animation = '';
}
confirmPending() {
this._resolveConfirm(true);
}
denyPending() {
this._resolveConfirm(false);
}
cancelAi() {
this._cancelled = true;
this.terminal.print('⏹ Cancelling AI...', 'warning');
// Abort any in-flight HTTP request
if (this.terminal.ollamaManager) {
this.terminal.ollamaManager.abort();
}
// Clear any pending confirmation
if (this._confirmResolve) {
this._resolveConfirm(false);
}
// Immediately reset UI so user knows it stopped
this.terminal.setAiBusy(false);
}
isDestructive(name) {
return name === 'write_file' || name === 'delete_file' || name === 'run_command' || name === 'make_directory' || name === 'edit_module';
}
async runTool(name, argsStr) {
let a = {};
try {
a = typeof argsStr === 'object' ? argsStr : (argsStr ? JSON.parse(argsStr) : {});
switch (name) {
case 'list_files': {
const originalPath = a.path || '';
const p = originalPath.replace(/^\//, '');
const saved = [...this.terminal.fs.currentPath];
if (originalPath.startsWith('/')) {
this.terminal.fs.currentPath = [];
}
if (p) {
const parts = p.split('/');
const dir = this.terminal.fs.root;
let cur = dir;
for (const part of parts) {
if (part === '..') { saved.pop(); continue; }
if (part && cur.content[part] && cur.content[part].type === 'dir') cur = cur.content[part];
else return JSON.stringify({ error: `Directory not found: ${p}` });
}
this.terminal.fs.currentPath = saved.concat(parts.filter(x => x !== '..'));
}
const files = this.terminal.fs.ls();
this.terminal.fs.currentPath = saved;
return JSON.stringify(files.map(f => ({ name: f.name, type: f.type, size: f.size })));
}
case 'read_file': {
const rp = a.path || '';
const savedR = [...this.terminal.fs.currentPath];
if (rp.startsWith('/')) this.terminal.fs.currentPath = [];
const path = rp.replace(/^\//, '');
const content = this.terminal.fs.readFile(path);
this.terminal.fs.currentPath = savedR;
if (content === null) return JSON.stringify({ error: `File not found: ${path}` });
return content.length > 8000 ? content.substring(0, 8000) + '\n...(truncated)' : content;
}
case 'write_file': {
const wp = a.path || '';
const savedW = [...this.terminal.fs.currentPath];
if (wp.startsWith('/')) this.terminal.fs.currentPath = [];
const path = wp.replace(/^\//, '');
const content = a.content || '';
this.terminal.fs.writeFile(path, content);
this.terminal.fs.currentPath = savedW;
return `File written: ${path} (${content.length} chars)`;
}
case 'make_directory': {
const mp = a.path || '';
const savedM = [...this.terminal.fs.currentPath];
if (mp.startsWith('/')) this.terminal.fs.currentPath = [];
const path = mp.replace(/^\//, '');
const ok = this.terminal.fs.mkdir(path);
this.terminal.fs.currentPath = savedM;
if (ok) return `Directory created: ${path}`;
return JSON.stringify({ error: `Cannot create: ${path}` });
}
case 'delete_file': {
const dp = a.path || '';
const savedD = [...this.terminal.fs.currentPath];
if (dp.startsWith('/')) this.terminal.fs.currentPath = [];
const path = dp.replace(/^\//, '');
const delOk = this.terminal.fs.deleteFile(path);
this.terminal.fs.currentPath = savedD;
if (delOk) return `Deleted: ${path}`;
return JSON.stringify({ error: `Cannot delete: ${path}` });
}
case 'get_status': {
const fs = this.terminal.fs;
const mm = this.terminal.moduleManager;
const om = this.terminal.ollamaManager;
return JSON.stringify({
files: fs.ls().length,
dirs: fs.currentPath.length ? '/' + fs.currentPath.join('/') : '/',
modules: Object.keys(mm.modules).length,
ollama: om.connected ? `Connected (${om.currentModel})` : 'Disconnected',
memory: performance.memory ? (performance.memory.usedJSHeapSize / 1048576).toFixed(1) + 'MB' : 'N/A'
});
}
case 'get_help': {
const cmds = this.terminal.moduleManager.getAllCommands();
return JSON.stringify(Object.keys(cmds).sort());
}
case 'get_current_dir': {
return '/' + this.terminal.fs.currentPath.join('/');
}
case 'web_search': {
const query = a.query || '';
if (!query) return JSON.stringify({ error: 'No query provided' });
try {
const resp = await fetch('/api/search?q=' + encodeURIComponent(query));
if (!resp.ok) { return JSON.stringify({ error: 'Search API returned HTTP ' + resp.status }); }
const data = await resp.json();
const results = data.results || [];
if (results.length === 0) return JSON.stringify({ message: 'No results found' });
return JSON.stringify({ count: results.length, source: data.source, results: results.map(r => ({ title: r.title, url: r.url, content: (r.content || '').substring(0, 300) })) });
} catch (e) { return JSON.stringify({ error: 'Search failed: ' + e.message }); }
}
case 'web_fetch': {
const url = a.url || '';
if (!url) return JSON.stringify({ error: 'No URL provided' });
try {
const resp = await fetch('/api/extract?url=' + encodeURIComponent(url));
if (resp.status === 403) return JSON.stringify({ error: 'URL blocked — internal network' });
if (!resp.ok) { return JSON.stringify({ error: 'Fetch API returned HTTP ' + resp.status }); }
const data = await resp.json();
return JSON.stringify({ title: data.title || '', content: (data.content || '').substring(0, 4000), word_count: data.word_count || 0, method: data.method || 'extract' });
} catch (e) { return JSON.stringify({ error: 'Fetch failed: ' + e.message }); }
}
case 'wpm_install': {
const pkg = a.package || '';
if (!pkg) return JSON.stringify({ error: 'No package name' });
const mod = this.terminal.moduleManager.modules['WpmModule'];
if (mod) { await mod.install(pkg); return `Package "${pkg}" installation attempted`; }
return JSON.stringify({ error: 'WPM module not available' });
}
case 'wpm_search': {
const kw = a.keyword || '';
if (!kw) return JSON.stringify({ error: 'No keyword' });
const mod = this.terminal.moduleManager.modules['WpmModule'];
if (mod) {
const originalPrint = this.terminal.print.bind(this.terminal);
let output = '';
this.terminal.print = (text, type) => { output += text + '\n'; };
try { await mod.search(kw); } finally { this.terminal.print = originalPrint; }
return output.trim() || 'Search completed';
}
return JSON.stringify({ error: 'WPM module not available' });
}
case 'run_command': {
const cmd = a.command || '';
if (!cmd) return JSON.stringify({ error: 'No command provided' });
const originalPrint = this.terminal.print.bind(this.terminal);
let output = '';
this.terminal.print = (text, type) => { output += text + '\n'; };
try { await this.terminal.dispatchCommand(cmd.split(' ')[0].toLowerCase(), cmd.split(' ').slice(1)); } finally { this.terminal.print = originalPrint; }
return output.trim() || '(no output)';
}
case 'check_updates': {
const reg = this.terminal.moduleManager.moduleRegistry;
const results = [];
for (const mod of reg) {
if (mod.url && mod.url.startsWith('http')) {
try {
const resp = await fetch(mod.url, { method: 'HEAD' });
results.push({ name: mod.name, url: mod.url, status: resp.ok ? 'reachable' : 'error (' + resp.status + ')' });
} catch (e) {
results.push({ name: mod.name, url: mod.url, status: 'unreachable' });
}
}
}
return JSON.stringify({ checked: results.length, modules: results });
}
case 'user_get': {
const key = a.key || '';
if (!key) return JSON.stringify({ error: 'Key is required' });
const val = key.split('.').reduce((o, k) => (o && typeof o === 'object') ? o[k] : undefined, this._userProfile);
return JSON.stringify({ key, value: val !== undefined ? val : null });
}
case 'user_set': {
const ukey = a.key || '';
if (!ukey) return JSON.stringify({ error: 'Key and value are required' });
const uval = a.value || '';
const keys = ukey.split('.');
let obj = this._userProfile;
for (let i = 0; i < keys.length - 1; i++) {
if (!obj[keys[i]] || typeof obj[keys[i]] !== 'object') obj[keys[i]] = {};
obj = obj[keys[i]];
}
obj[keys[keys.length - 1]] = uval;
try { localStorage.setItem('webx11_user_profile', JSON.stringify(this._userProfile)); } catch (e) {}
return JSON.stringify({ success: true, key: ukey, value: uval });
}
case 'user_list': {
return JSON.stringify({ profile: this._userProfile, keys: Object.keys(this._userProfile) });
}
case 'user_forget': {
const fkey = a.key || '';
if (!fkey) return JSON.stringify({ error: 'Key is required' });
if (fkey.includes('.')) {
const parts = fkey.split('.');
let obj = this._userProfile;
for (let i = 0; i < parts.length - 1; i++) {
if (!obj[parts[i]]) return JSON.stringify({ error: 'Key not found' });
obj = obj[parts[i]];
}
delete obj[parts[parts.length - 1]];
} else {
delete this._userProfile[fkey];
}
try { localStorage.setItem('webx11_user_profile', JSON.stringify(this._userProfile)); } catch (e) {}
return JSON.stringify({ success: true, key: fkey });
}
case 'session_save': {
const summary = a.summary || 'No summary provided';
const fs = this.terminal.fs;
fs.mkdirRecursive('/memory');
const today = new Date().toISOString().split('T')[0];
const log = { date: today, summary, toolCallCount: 0, skillsCreated: [], modulesEdited: [], timestamp: new Date().toISOString() };
fs.fsWriteJSON('/memory/' + today + '.json', log);
const index = fs.fsReadJSON('/memory/index.json') || {};
index[today] = { summary, tasks: (index[today]?.tasks || 0) + 1, updated: new Date().toISOString() };
fs.fsWriteJSON('/memory/index.json', index);
return JSON.stringify({ success: true, date: today });
}
case 'session_load': {
const sdate = a.date || '';
if (!sdate) return JSON.stringify({ error: 'Date required (YYYY-MM-DD)' });
const sfs = this.terminal.fs;
const slog = sfs.fsReadJSON('/memory/' + sdate + '.json');
if (!slog) return JSON.stringify({ error: 'No session log for ' + sdate });
return JSON.stringify(slog);
}
case 'session_recent': {
const count = a.count || 3;
const rfs = this.terminal.fs;
const rindex = rfs.fsReadJSON('/memory/index.json') || {};
const dates = Object.keys(rindex).sort().reverse().slice(0, count);
const sessions = dates.map(d => ({ date: d, ...rindex[d] }));
return JSON.stringify({ sessions, count: sessions.length });
}
case 'session_terminal': {
const tfs = this.terminal.fs;
try {
const raw = tfs.readFile('_sessions/_auto.json');
if (!raw) return JSON.stringify({ error: 'No auto-saved session found' });
const data = JSON.parse(raw);
const lines = (data.terminalLines || []).slice(-50);
const text = lines.map(l => {
const ts = l.t ? '[' + l.t + '] ' : '';
return ts + l.l;
}).join('\n');
return JSON.stringify({ lines: lines.length, output: text, savedAt: data.savedAt || '' });
} catch (e) {
return JSON.stringify({ error: 'Could not read terminal history: ' + e.message });
}
}
case 'session_stats': {
const sfs = this.terminal.fs;
const sindex = sfs.fsReadJSON('/memory/index.json') || {};
const entries = Object.entries(sindex);
let totalTasks = 0;
for (const [, meta] of entries) totalTasks += meta.tasks || 0;
return JSON.stringify({ totalSessions: entries.length, totalTasks, dates: entries.map(([d]) => d) });
}
case 'load_skills': {
const query = (a && a.query || '').toLowerCase();
const fs = this.terminal.fs;
const index = fs.fsReadJSON('/skills/index.json') || {};
if (!query) {
const names = Object.keys(index);
return JSON.stringify({ skills: names, count: names.length, message: 'No query provided — showing all skill names. Call again with a query to load content.' });
}
const matches = [];
for (const [name, meta] of Object.entries(index)) {
const score = (name.includes(query) ? 3 : 0) + (meta.description.toLowerCase().includes(query) ? 2 : 0) + ((meta.tags || []).some(t => t.toLowerCase().includes(query)) ? 2 : 0);
if (score > 0) {
const content = fs.readFile(`/skills/${name}.md`) || '';
matches.push({ name, description: meta.description, category: meta.category, score, content: content.substring(0, 2000) });
}
}
matches.sort((a, b) => b.score - a.score);
const top = matches.slice(0, 3);
return JSON.stringify(top.length > 0 ? { matches: top.map(m => ({ name: m.name, description: m.description, content: m.content })), count: top.length } : { matches: [], count: 0, message: 'No matching skills found. You can create one after this task.' });
}
case 'create_skill': {
const name = (a.name || '').trim().replace(/\s+/g, '-').toLowerCase();
if (!name) return JSON.stringify({ error: 'Skill name is required' });
const description = a.description || '';
let content = a.content || '';
const tags = (a.tags || '').split(',').map(t => t.trim()).filter(Boolean);
const category = a.category || 'general';
if (!content.startsWith('---')) {
content = `---\nname: ${name}\ndescription: ${description}\ntags: [${tags.join(', ')}]\ncategory: ${category}\n---\n## Steps\n${content}`;
}
const fs = this.terminal.fs;
fs.mkdirRecursive('/skills');
fs.writeFile(`/skills/${name}.md`, content);
const index = fs.fsReadJSON('/skills/index.json') || {};
index[name] = { name, description, tags, category, created: index[name]?.created || new Date().toISOString(), updated: new Date().toISOString() };
fs.fsWriteJSON('/skills/index.json', index);
this.terminal.print(`💡 Skill saved: ${name}`, 'success');
return JSON.stringify({ success: true, name, message: `Skill "${name}" created (${content.length} chars)` });
}
case 'patch_skill': {
const pname = (a.name || '').trim();
if (!pname) return JSON.stringify({ error: 'Skill name is required' });
const pcontent = a.content || '';
if (!pcontent) return JSON.stringify({ error: 'Skill content is required' });
const fs = this.terminal.fs;
const index = fs.fsReadJSON('/skills/index.json') || {};
if (!index[pname]) return JSON.stringify({ error: `Skill "${pname}" not found` });
fs.writeFile(`/skills/${pname}.md`, pcontent);
index[pname].updated = new Date().toISOString();
// Re-parse frontmatter for metadata updates
const metaMatch = pcontent.match(/^---\n([\s\S]*?)\n---/);
if (metaMatch) {
const metaLines = metaMatch[1].split('\n');
metaLines.forEach(line => {
const [k, ...v] = line.split(':');
if (k === 'description') index[pname].description = v.join(':').trim();
if (k === 'tags') index[pname].tags = v.join(':').trim().replace(/[\[\]]/g, '').split(',').map(t => t.trim());
if (k === 'category') index[pname].category = v.join(':').trim();
});
}
fs.fsWriteJSON('/skills/index.json', index);
this.terminal.print(`💡 Skill patched: ${pname}`, 'success');
return JSON.stringify({ success: true, name: pname, message: `Skill "${pname}" updated` });
}
case 'list_skills': {
const filterCat = (a.category || '').toLowerCase();
const fs = this.terminal.fs;
const index = fs.fsReadJSON('/skills/index.json') || {};
const list = Object.entries(index).map(([name, meta]) => ({ name, description: meta.description, category: meta.category || 'general', tags: meta.tags || [], updated: meta.updated }))
.filter(s => !filterCat || (s.category || '').toLowerCase() === filterCat);
return JSON.stringify({ skills: list, count: list.length });
}
case 'view_module':
case 'edit_module':
case 'test_module':
case 'reload_module':
case 'list_modified_modules':
case 'get_module_status':
return await this.runModuleTool(name, argsStr);
default:
return JSON.stringify({ error: `Unknown tool: ${name}` });
}
} catch (e) {
this._errorLog.push({ tool: name, args: a, error: e.message, timestamp: Date.now() });
return JSON.stringify({ error: e.message, stack: e.stack?.substring(0, 200) });
}
}
async runModuleTool(name, argsStr) {
let a = {};
try {
a = typeof argsStr === 'object' ? argsStr : (argsStr ? JSON.parse(argsStr) : {});
switch (name) {
case 'view_module': {
const modName = a.name || '';
const entry = this.terminal.moduleManager.moduleRegistry.find(m => m.name === modName);
const code = this.terminal.fs.readFile(`_mods/${modName}.js`);
if (code) return code;
const url = entry ? entry.url : null;
if (!url) return JSON.stringify({ error: `No source URL for ${modName}` });
try {
const resp = await fetch(url);
if (resp.ok) {
const src = await resp.text();
this.terminal.fs.writeFile(`_mods/${modName}.orig.js`, src);
return src.substring(0, 8000);
}
return JSON.stringify({ error: `HTTP ${resp.status}` });
} catch (e) { return JSON.stringify({ error: e.message }); }
}
case 'edit_module': {
const modName = a.name || '';
const entry = this.terminal.moduleManager.moduleRegistry.find(m => m.name === modName);
const url = entry ? entry.url : null;
let code = this.terminal.fs.readFile(`_mods/${modName}.js`);
if (!code && url) {
try {
const resp = await fetch(url);
if (resp.ok) {
code = await resp.text();
this.terminal.fs.writeFile(`_mods/${modName}.orig.js`, code);
this.terminal.fs.writeFile(`_mods/${modName}.js`, code);
this.terminal.fs.writeFile(`_mods/${modName}.meta.json`, JSON.stringify({ originalUrl: url, modifiedAt: new Date().toISOString(), editCount: 0 }));
}
} catch (e) {}
}
if (code) this.terminal.openCodeEditor(modName, url || '', code);
return code ? `Editor opened for ${modName} (${code.length} chars)` : JSON.stringify({ error: `Could not load source for ${modName}` });
}
case 'test_module': {
const modName = a.name || '';
const code = this.terminal.fs.readFile(`_mods/${modName}.js`);
if (!code) return JSON.stringify({ error: `No local edit for ${modName}` });
this.terminal.moduleManager.loadModuleFromCode(code, `blob://_mods/${modName}.js`);
return `Module "${modName}" loaded from local edit for testing`;
}
case 'reload_module': {
const modName = a.name || '';
const entry = this.terminal.moduleManager.moduleRegistry.find(m => m.name === modName);
this.terminal.fs.deleteFile(`_mods/${modName}.js`);
this.terminal.fs.deleteFile(`_mods/${modName}.orig.js`);
this.terminal.fs.deleteFile(`_mods/${modName}.meta.json`);
if (entry && entry.url) {
this.terminal.moduleManager.unloadModule(modName);
await this.terminal.moduleManager.loadModuleFromURL(entry.url);
return `Module "${modName}" reloaded from ${entry.url}`;
}
return JSON.stringify({ error: `No original URL for ${modName}` });
}
case 'list_modified_modules': {
const modsDir = this.terminal.fs.getCurrentDir();
const mc = modsDir.content['_mods'];
if (!mc || Object.keys(mc.content).length === 0) return JSON.stringify({ modified: [], message: 'No local edits' });
const files = Object.keys(mc.content).filter(k => k.endsWith('.js') && !k.endsWith('.orig.js'));
return JSON.stringify({ modified: files.map(f => f.replace('.js', '')), count: files.length });
}
case 'get_module_status': {
const mm = this.terminal.moduleManager;
const modsDir = this.terminal.fs.getCurrentDir();
const hasMods = modsDir.content['_mods'] ? !!Object.keys(modsDir.content['_mods'].content).length : false;
const modules = mm.moduleRegistry.map(m => ({
name: m.name, url: m.url, enabled: m.enabled,
loaded: !!mm.modules[m.name],
modified: !!this.terminal.fs.readFile(`_mods/${m.name}.js`)
}));
return JSON.stringify({ modules, total: modules.length, hasLocalEdits: hasMods });
}
default: return JSON.stringify({ error: `Unknown module tool: ${name}` });
}
} catch (e) {
this._errorLog.push({ tool: name, args: a, error: e.message, timestamp: Date.now() });
return JSON.stringify({ error: e.message, stack: e.stack?.substring(0, 200) });
}
}
clearContext() {
this.context = [];
localStorage.removeItem('webx11_ai_context');
this.terminal.print('AI conversation context cleared', 'success');
}
_saveContext() {
try {
const data = JSON.stringify({
context: this.context.slice(-20),
messageCount: this._messageCount,
savedAt: Date.now()
});
localStorage.setItem('webx11_ai_context', data);
// Also persist to VFS for crash survival
try {
const fs = this.terminal.fs;
if (fs) {
fs.mkdirRecursive('_sessions');
fs.writeFile('_sessions/_auto-context.json', data);
}
} catch (e) {}
} catch (e) {
// localStorage quota exceeded — silently ignore
}
}
_loadContext() {
try {
const saved = localStorage.getItem('webx11_ai_context');
if (saved) {
const data = JSON.parse(saved);
if (data && data.context) {
this.context = data.context.slice(-20);
this._messageCount = data.messageCount || 0;
}
}
} catch (e) {}
}
setSystemPrompt(args) {
if (!args[0]) {
this.terminal.print(`Current system prompt: ${this.systemPrompt.substring(0, 50)}...`, 'info'); return;
}
this.systemPrompt = args.join(' ');
this.terminal.print('System prompt updated', 'success');
}
showModel(args) {
const om = this.terminal.ollamaManager;
if (args.length > 0) {
const name = args.join(' ');
if (om.models && om.models.some(m => m.name === name)) {
om.currentModel = name;
localStorage.setItem('webx11_ollama_model', name);
this.terminal.print(`AI model set to: ${name}`, 'success');
} else {
this.terminal.print(`Model "${name}" not found in available models. Use ai-model to list.`, 'warning');
}
return;
}
this.terminal.print(`Current AI model: ${om.currentModel || 'none'}`, 'info');
if (om.models && om.models.length > 0) {
const maxShow = 20;
const names = om.models.slice(0, maxShow).map(m => m.name).join(', ');
this.terminal.print(`Available (${om.models.length}): ${names}${om.models.length > maxShow ? `... +${om.models.length - maxShow} more` : ''}`, 'info');
} else {
this.terminal.print('No models available. Use ollamaconnect first.', 'warning');
}
}
showContext() {
if (this.context.length === 0) {
this.terminal.print('No conversation context', 'info'); return;
}
this.terminal.print(`=== Context (${this.context.length} messages) ===`, 'info');
this.context.forEach(msg => {
const icon = msg.role === 'user' ? '👤' : msg.role === 'assistant' ? '🤖' : '🔧';
const content = typeof msg.content === 'string' ? msg.content.substring(0, 60) : JSON.stringify(msg).substring(0, 60);
this.terminal.print(`${icon} ${content}...`);
});
}
_extractFacts(userMsg, aiResp) {
const patterns = [
{ re: /my name is (\w+)/i, key: 'name' },
{ re: /call me (\w+)/i, key: 'name' },
{ re: /i(?:'m| am) working on (.+)/i, key: 'project' },
{ re: /(?:my|the) project is (.+)/i, key: 'project' },
{ re: /i have a server at (.+)/i, key: 'server' },
{ re: /i use (\w+).*?(?:editor|ide|text)/i, key: 'preferredEditor' },
{ re: /i (?:like|prefer|love) (.+)/i, key: 'preference' },
];
let changed = false;
for (const { re, key } of patterns) {
const m = (userMsg + ' ' + (aiResp || '')).match(re);
if (m && m[1]) {
if (!this._userProfile.knownFacts) this._userProfile.knownFacts = {};
if (this._userProfile.knownFacts[key] !== m[1].trim()) {
this._userProfile.knownFacts[key] = m[1].trim();
changed = true;
}
}
}
if (changed) {
try { localStorage.setItem('webx11_user_profile', JSON.stringify(this._userProfile)); } catch (e) {}
}
}
async _seedDefaultSkills() {
const fs = this.terminal.fs;
const mindmapSkill = `---
name: mindmap-user-guide
description: How to create, view, and manage brainstorming mindmaps using the mindmap terminal module
tags: [mindmap, brainstorming, organization, planning]
category: productivity
---
## Steps
1. **Create a new mindmap:**
- \`mindmap new "<topic>" -t tag1,tag2\` — creates a root node
- Tags are optional (e.g. planning, research, dev)
- Root gets auto-assigned a color
2. **Add child nodes:**
- \`mindmap add <parent-id> "<idea>" -t tag\` — add a child
- Get the parent-id from \`mindmap show\`
- IDs are 4-char random strings (e.g. a3f8, x7k2)
3. **View the mindmap:**
- \`mindmap show\` — full tree with Unicode box-drawing
- \`mindmap show <id>\` — subtree starting at that node
4. **Edit nodes:**
- \`mindmap rename <id> "<new text>"\` — change text
- \`mindmap color <id> <color>\` — set color (red/green/yellow/blue/cyan/magenta/white)
- \`mindmap tag <id> <tag>\` — add a tag
5. **Persistence:**
- \`mindmap save <name>\` — save to localStorage
- \`mindmap load <name>\` — restore
- \`mindmap list\` — show saved mindmaps
- \`mindmap delete <name>\` — remove saved
6. **Export:**
- \`mindmap export [id]\` — Markdown bullet list output
## When to use
- User wants to brainstorm, organize ideas, plan features
- User says "map out", "diagram", "brainstorm", "organize thoughts"
- Visualizing project structure or task decomposition`;
fs.writeFile('/skills/mindmap-user-guide.md', mindmapSkill);
const existingIndex = fs.fsReadJSON('/skills/index.json') || {};
existingIndex['mindmap-user-guide'] = { name: 'mindmap-user-guide', description: 'How to create, view, and manage brainstorming mindmaps using the mindmap terminal module', tags: ['mindmap', 'brainstorming', 'organization', 'planning'], category: 'productivity', created: existingIndex['mindmap-user-guide']?.created || new Date().toISOString(), updated: new Date().toISOString() };
fs.fsWriteJSON('/skills/index.json', existingIndex);
fs.writeFile('/skills/_seeded', '1');
}
_trackPattern(userMessage) {
const lower = userMessage.toLowerCase();
const patterns = ['font size','bigger text','smaller text','export','backup','save','install','load module','search','find','color','theme','skill','learn','remember','mindmap','brainstorm'];
for (const p of patterns) {
if (lower.includes(p)) this._commandFreq[p] = (this._commandFreq[p] || 0) + 1;
}
try { localStorage.setItem('webx11_ai_patterns', JSON.stringify(this._commandFreq)); } catch (e) {}
}
async _autoCreateErrorSkill() {
const grouped = {};
for (const e of this._errorLog) {
if (!grouped[e.tool]) grouped[e.tool] = [];
grouped[e.tool].push(e);
}
for (const [tool, errors] of Object.entries(grouped)) {
if (errors.length >= 3) {
const skillName = 'tool-' + tool + '-workaround';
const existing = this.terminal.fs.readFile('/skills/' + skillName + '.md');
if (existing) continue;
const steps = errors.map((e, i) => (i + 1) + '. When calling ' + tool + ', avoid: "' + JSON.stringify(e.args) + '" which caused: ' + e.error).join('\n');
const content = '---\nname: ' + skillName + '\ndescription: Workarounds for ' + tool + ' failures\ntags: [' + tool + ', error, workaround]\ncategory: system\n---\n## Steps\n' + steps;
await this.runTool('create_skill', { name: skillName, description: 'Workarounds for ' + tool + ' failures', content: content, tags: tool + ',error,workaround', category: 'system' });
this.terminal.print('🤖 Auto-created skill from repeated errors: ' + skillName, 'info');
}
}
this._errorLog = [];
}
async _auditSkills() {
const fs = this.terminal.fs;
const index = fs.fsReadJSON('/skills/index.json') || {};
const now = Date.now();
const issues = [];
for (const [name, meta] of Object.entries(index)) {
const content = fs.readFile('/skills/' + name + '.md');
if (!content || content.length < 50) {
issues.push({ name, issue: 'empty or too short' });
continue;
}
const updated = new Date(meta.updated || 0).getTime();
const ageDays = (now - updated) / 86400000;
if (ageDays > 30) issues.push({ name, issue: 'not updated in ' + Math.round(ageDays) + ' days' });
}
if (issues.length > 0) {
this.terminal.print('📋 Skill audit: ' + issues.length + ' issue(s) found', 'info');
issues.slice(0, 3).forEach(i => this.terminal.print(' - ' + i.name + ': ' + i.issue, 'warning'));
}
}
_estimateTokens(text) {
if (!text || typeof text !== 'string') return 0;
return Math.ceil(text.length / 4);
}
_estimateContextTokens() {
let total = 0;
for (const msg of this.context) {
total += this._estimateTokens(msg.content || '');
}
return total;
}
async _compressContext() {
if (this.context.length <= 6) return;
const totalTokens = this._estimateContextTokens();
if (totalTokens < this.maxContextTokens) return;
const keepCount = 3;
const oldMsgs = this.context.slice(0, -keepCount * 2);
if (oldMsgs.length < 2) return;
const recentMsgs = this.context.slice(-keepCount * 2);
const summaryText = oldMsgs.map(m =>
(m.role === 'user' ? '👤' : m.role === 'assistant' ? '🤖' : '⚙️') + ': ' +
(m.content || '').substring(0, 150)
).join(' | ');
let compressed = `[Earlier context (${oldMsgs.length} messages): ${summaryText}]`;
// Try AI summarization, fallback to truncation
try {
if (this.terminal.ollamaManager && this.terminal.ollamaManager.connected) {
const sumPrompt = 'Summarize these conversation exchanges into a single compact sentence. Focus on what the user asked and what actions were taken. Keep it under 200 characters.\n\n' + JSON.stringify(oldMsgs.map(m => ({ role: m.role, content: (m.content || '').substring(0, 200) })));
const sumRes = await this.terminal.ollamaManager.chat(sumPrompt);
if (sumRes && sumRes.length < 300) {
compressed = '[Earlier context: ' + sumRes.trim() + ']';
}
}
} catch (e) { /* fallback to truncation */ }
this.context = [{ role: 'system', content: compressed }, ...recentMsgs];
this.terminal.print('📦 Context compressed (' + oldMsgs.length + ' messages → 1 summary, ~' + totalTokens + ' tokens)', 'info');
}
_manualCompress() {
this._compressContext().then(() => {
this.terminal.print('Context: ' + this.context.length + ' message(s), ~' + this._estimateContextTokens() + ' estimated tokens', 'info');
}).catch(e => {
this.terminal.print('Compression error: ' + e.message, 'error');
});
}
}
|