Repository navigation
Expand file tree
/
Copy pathloader.js
More file actions
1293 lines (1131 loc) · 59 KB
/
Copy pathloader.js
File metadata and controls
1293 lines (1131 loc) · 59 KB
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
/**
* =============
* LOADING SCREEN MODULE - loader.js - V 2.4.3
* =============
* V2.4.3 - Updated to handle new agent_tools.json
* and dynamic princi2.txt parsing
* =============
*/
// Initialize loading screen
const LoadingScreen = {
loadingComplete: false,
dataFetched: {
commands: false,
actions: false,
principles: false,
apiConfig: false,
memories: false,
lastMessages: false,
htmlFiles: false,
tools: false
},
loadingScreenData: {
commands: null,
commandsCount: 0,
actions: null,
actionsCount: 0,
memories: null,
memoriesCount: 0
},
currentNewsIndex: 1,
totalNewsNotes: 3,
init: function() {
this.updateLoadingScreenLayout();
this.setupEventHandlers();
this.loadHTMLSections(); // Load HTML sections first
this.initializeNewsNavigation();
this.generatePanelToggles();
this.setupLoginButton();
// Start fetching data after short delay
setTimeout(() => {
this.fetchCommandsCount();
this.fetchActionsList();
this.fetchPrinciplesList();
this.fetchAPIConfig();
this.fetchMemoriesCount();
this.fetchLastMessages();
this.fetchToolsList();
}, 300);
},
loadHTMLSections: function() {
const sections = [
{ file: 'mission.html', container: 'loader-mission-container' },
{ file: 'system.html', container: 'loader-system-container' },
{ file: 'user.html', container: 'loader-user-container' },
// REMOVED: { file: 'features.html', container: 'loader-features-container' },
{ file: 'status.html', container: 'loader-status-container' }
];
const loadPromises = sections.map(section => {
return fetch(section.file)
.then(response => {
if (!response.ok) {
throw new Error(`Failed to load ${section.file}`);
}
return response.text();
})
.then(html => {
const container = document.getElementById(section.container);
if (container) {
container.innerHTML = html;
}
})
.catch(error => {
console.warn(`Failed to load ${section.file}:`, error);
const container = document.getElementById(section.container);
if (container) {
container.innerHTML = `<div class="loader-error">Failed to load ${section.file}</div>`;
}
});
});
Promise.all(loadPromises).then(() => {
console.log('All HTML sections loaded');
// After loading HTML, process any dynamic content
this.generateUserStats();
// REMOVED: this.generateFeatures();
this.setupTabs();
this.displayFeatures(); // NEW: Display features in the tab
this.dataFetched.htmlFiles = true;
this.checkAllDataLoaded();
}).catch(error => {
console.error('Error loading HTML sections:', error);
this.dataFetched.htmlFiles = true;
this.checkAllDataLoaded();
});
},
setupLoginButton: function() {
const showLoginBtn = document.getElementById('showLoginBtn');
if (showLoginBtn) {
showLoginBtn.addEventListener('click', () => {
if (typeof authManager !== 'undefined') {
authManager.showLoginModal();
} else {
console.error("authManager not defined when trying to show login modal from loader.");
}
});
}
},
generatePanelToggles: function() {
document.querySelectorAll('[data-panel-toggles]').forEach(container => {
const area = container.dataset.panelToggles;
const icons = container.dataset.icons?.split(',') || [];
const panels = Object.entries(CONFIG.panels)
.filter(([id, cfg]) => cfg.area === area)
.map(([id, cfg], index) => ({
id,
icon: icons[index] || '📋',
title: cfg.title || 'Panel'
}));
container.innerHTML = panels.map(p =>
`<div class="panel-toggle" id="toggle-${p.id}" data-target="${p.id}"
role="button" aria-controls="${p.id}" aria-expanded="false"
tabindex="0" title="Toggle ${p.title}">
<span class="toggle-arrow" aria-hidden="true">${p.icon}</span>
</div>`
).join('');
});
},
generateUserStats: function() {
const container = document.querySelector('[data-user-stats]');
if (!container) return;
const stats = Array.from(container.querySelectorAll('[data-stat]')).map(el => {
const parts = el.dataset.stat.split(',');
const iscat = parts[0] === 'cat';
return iscat ?
`<div class="loader-user-stat-item loader-cat-stat">
<div class="loader-user-stat-content">
<div class="loader-user-stat-label">${parts[1]}</div>
<div class="loader-user-stat-details loader-cat-details">
<span>• ${parts[2]}</span>
<span>• ${parts[3]}</span>
</div>
</div>
</div>` :
`<div class="loader-user-stat-item">
<div class="loader-user-stat-content">
<div class="loader-user-stat-number">${parts[0]}</div>
<div class="loader-user-stat-label">${parts[1]}</div>
<div class="loader-user-stat-details">
<span>• ${parts[2]}</span>
<span>• ${parts[3]}</span>
</div>
</div>
</div>`;
});
container.innerHTML = stats.join('');
},
// REMOVED generateFeatures method - no longer needed
setupEventHandlers: function() {
// Handle resize
window.addEventListener('resize', () => {
clearTimeout(this.resizeTimeout);
this.resizeTimeout = setTimeout(() => this.updateLoadingScreenLayout(), 100);
});
// Handle orientation changes
window.addEventListener('orientationchange', () => {
setTimeout(() => this.updateLoadingScreenLayout(), 100);
});
},
checkAllDataLoaded: function() {
const allLoaded = Object.values(this.dataFetched).every(v => v === true);
if (allLoaded && !this.loadingComplete) {
this.loadingComplete = true;
this.showLoadingComplete();
}
},
showLoadingComplete: function() {
const spinner = document.getElementById('loaderSpinner');
const checkmark = document.getElementById('loaderCheckmark');
const loaderText = document.getElementById('loaderText');
const spinnerContainer = document.querySelector('.loader-spinner-container');
if (spinner && checkmark) {
spinner.style.display = 'none';
checkmark.style.display = 'block';
if (spinnerContainer) spinnerContainer.classList.add('has-checkmark');
if (loaderText) loaderText.textContent = 'Loading Complete!';
}
},
// Updated fetchRedditNews function with better content handling
fetchRedditNews: async function() {
try {
// Reddit's JSON API endpoint for your subreddit
const response = await fetch('https://www.reddit.com/r/m0dai.json?limit=10');
const data = await response.json();
// Transform Reddit posts into news items
const newsItems = data.data.children
.filter(post => !post.data.stickied) // Skip pinned posts
.slice(0, 5) // Get top 5 posts
.map((post, index) => {
const postData = post.data;
const date = new Date(postData.created_utc * 1000);
const formattedDate = date.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric'
});
// Get the body text
let body = postData.selftext || postData.title;
let wasTruncated = false;
// Process bullet points if they exist
if (body.includes('*') || body.includes('•') || body.includes('-')) {
// Try to preserve bullet point structure
const lines = body.split('\n');
let processedBody = '';
let charCount = 0;
const maxChars = 500; // Increased from 150 to 500
for (let line of lines) {
const trimmedLine = line.trim();
if (trimmedLine) {
// Check if we're about to exceed the limit
if (charCount + trimmedLine.length > maxChars && processedBody) {
// Mark as truncated but don't add text here
wasTruncated = true;
break;
}
// Format bullet points nicely
if (trimmedLine.startsWith('*') || trimmedLine.startsWith('•') || trimmedLine.startsWith('-')) {
processedBody += (processedBody ? '\n' : '') + '• ' + trimmedLine.substring(1).trim();
} else {
processedBody += (processedBody ? '\n' : '') + trimmedLine;
}
charCount += trimmedLine.length;
}
}
body = processedBody;
} else {
// For non-bullet content, just truncate at a reasonable length
if (body.length > 500) {
// Try to cut at a sentence boundary
const truncated = body.substring(0, 500);
const lastPeriod = truncated.lastIndexOf('.');
const lastExclamation = truncated.lastIndexOf('!');
const lastQuestion = truncated.lastIndexOf('?');
const lastSentenceEnd = Math.max(lastPeriod, lastExclamation, lastQuestion);
if (lastSentenceEnd > 300) {
body = truncated.substring(0, lastSentenceEnd + 1);
} else {
body = truncated;
}
wasTruncated = true;
}
}
// Create news item HTML with better formatting
return `
<div class="loader-news-item ${index === 0 ? 'active' : ''}" data-news-id="${index + 1}">
<div class="loader-news-date">${formattedDate}</div>
<div class="loader-news-title">
<a href="https://reddit.com${postData.permalink}" target="_blank" rel="noopener noreferrer" style="color: inherit; text-decoration: none;">
${this.escapeHtml(postData.title)}
</a>
</div>
<div class="loader-news-body" style="white-space: pre-line;">
${this.escapeHtml(body)}${wasTruncated ? ` ... <a href="https://reddit.com${postData.permalink}" target="_blank" rel="noopener noreferrer" style="color: #1e88e5; text-decoration: none;">(see full post on Reddit)</a>` : ''}
<div style="margin-top: 8px; font-size: 0.8em; opacity: 0.7;">
👍 ${postData.score} | 💬 ${postData.num_comments} comments
</div>
</div>
</div>
`;
});
// Update the news content area
const newsContent = document.getElementById('newsContent');
if (newsContent && newsItems.length > 0) {
newsContent.innerHTML = newsItems.join('');
this.totalNewsNotes = newsItems.length;
this.currentNewsIndex = 1;
// Update indicator
const indicator = document.getElementById('newsIndicator');
if (indicator) {
indicator.textContent = `1 / ${this.totalNewsNotes}`;
}
}
// Add a fallback static item if no posts found or error
if (!newsItems.length) {
this.showFallbackNews();
}
} catch (error) {
console.warn('Failed to fetch Reddit news:', error);
this.showFallbackNews();
}
},
// News Fallback
showFallbackNews: function() {
const newsContent = document.getElementById('newsContent');
if (newsContent) {
newsContent.innerHTML = `
<div class="loader-news-item active" data-news-id="1">
<div class="loader-news-date">${new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</div>
<div class="loader-news-title">Welcome to m0d.ai</div>
<div class="loader-news-body">
Visit our subreddit for the latest updates and discussions:
<a href="https://www.reddit.com/r/m0dai/" target="_blank" rel="noopener noreferrer">r/m0dai on Reddit</a>
</div>
</div>
`;
this.totalNewsNotes = 1;
this.currentNewsIndex = 1;
}
},
// Updated initializeNewsNavigation function
initializeNewsNavigation: function() {
const prevBtn = document.getElementById('newsPrevBtn');
const nextBtn = document.getElementById('newsNextBtn');
const indicator = document.getElementById('newsIndicator');
if (!prevBtn || !nextBtn || !indicator) return;
// Fetch Reddit posts first
this.fetchRedditNews();
const updateNewsDisplay = () => {
indicator.textContent = `${this.currentNewsIndex} / ${this.totalNewsNotes}`;
document.querySelectorAll('.loader-news-item').forEach(item => {
item.classList.remove('active');
});
const currentItem = document.querySelector(`.loader-news-item[data-news-id="${this.currentNewsIndex}"]`);
if (currentItem) currentItem.classList.add('active');
prevBtn.disabled = this.currentNewsIndex === 1;
nextBtn.disabled = this.currentNewsIndex === this.totalNewsNotes;
};
prevBtn.addEventListener('click', () => {
if (this.currentNewsIndex > 1) {
this.currentNewsIndex--;
updateNewsDisplay();
}
});
nextBtn.addEventListener('click', () => {
if (this.currentNewsIndex < this.totalNewsNotes) {
this.currentNewsIndex++;
updateNewsDisplay();
}
});
// Refresh SubReddit News
setInterval(() => {
this.fetchRedditNews();
}, 300000); // 5 minutes
},
setupTabs: function() {
const tabs = {
actions: { tab: 'actionsTab', content: 'actionsList' },
commands: { tab: 'commandsTab', content: 'commandsList' },
memories: { tab: 'memoriesTab', content: 'memoriesList' },
tools: { tab: 'toolsTab', content: 'toolsList' },
principles: { tab: 'principlesTab', content: 'principlesTabList' }, // Duplicate of standalone principles card
features: { tab: 'featuresTab', content: 'featuresTabList' } // NEW TAB
};
Object.entries(tabs).forEach(([name, ids]) => {
const tab = document.getElementById(ids.tab);
if (tab) {
tab.addEventListener('click', (e) => {
e.preventDefault(); // Prevent any default behavior
// Update active states
document.querySelectorAll('.loader-tab').forEach(t => {
t.classList.remove('active');
// Remove inline styles that might conflict
t.style.fontWeight = '';
t.style.color = '';
t.style.borderBottom = '';
});
tab.classList.add('active');
// Hide all content
Object.values(tabs).forEach(t => {
const content = document.getElementById(t.content);
if (content) content.style.display = 'none';
});
// Show selected content
const content = document.getElementById(ids.content);
if (content) {
content.style.display = 'block';
// Prevent layout shift by ensuring content is ready
requestAnimationFrame(() => {
content.scrollTop = 0;
});
}
});
}
});
},
fetchLastMessages: function() {
// Generate random online users
const randomUserCount = Math.floor(Math.random() * 10) + 1;
const onlineUsersElement = document.getElementById('onlineUsersText');
if (onlineUsersElement) {
onlineUsersElement.textContent = `${randomUserCount} placeholderusers online`;
}
// Fetch API config
fetch('/api/config')
.then(response => response.json())
.then(data => {
const providerElement = document.getElementById('apiProviderText');
const modelElement = document.getElementById('apiModelText');
if (providerElement && modelElement && data.api) {
const provider = data.api.active_provider || 'Unknown';
const model = data.api.providers?.[provider]?.model_name || 'Unknown Model';
providerElement.textContent = provider;
modelElement.textContent = model;
}
})
.catch(error => {
console.warn('Failed to fetch API config:', error);
const providerElement = document.getElementById('apiProviderText');
const modelElement = document.getElementById('apiModelText');
if (providerElement) providerElement.textContent = 'Error';
if (modelElement) modelElement.textContent = 'Unable to load';
});
// Fetch last AI message
fetch('/website_output.txt')
.then(response => response.text())
.then(text => {
const element = document.getElementById('lastAIMessage');
if (element) {
const trimmedText = text.trim();
const maxLength = 100;
element.textContent = trimmedText ?
(trimmedText.length > maxLength ?
trimmedText.substring(0, maxLength) + '...' : trimmedText) :
'No AI message yet';
}
})
.catch(() => {
const element = document.getElementById('lastAIMessage');
if (element) element.textContent = 'Unable to load';
});
// Fetch last user message
fetch('/cleanuser.txt')
.then(response => response.text())
.then(text => {
const element = document.getElementById('lastUserMessage');
if (element) {
const trimmedText = text.trim();
const maxLength = 100;
element.textContent = trimmedText ?
(trimmedText.length > maxLength ?
trimmedText.substring(0, maxLength) + '...' : trimmedText) :
'No user message yet';
}
this.dataFetched.lastMessages = true;
this.checkAllDataLoaded();
})
.catch(() => {
const element = document.getElementById('lastUserMessage');
if (element) element.textContent = 'Unable to load';
this.dataFetched.lastMessages = true;
this.checkAllDataLoaded();
});
},
fetchCommandsCount: function() {
fetch('/commands.json')
.then(response => response.json())
.then(data => {
let totalCommands = 0;
Object.values(data).forEach(category => {
totalCommands += Object.keys(category).length;
});
this.loadingScreenData.commands = data;
this.loadingScreenData.commandsCount = totalCommands;
const tabCount = document.getElementById('commandsTabCount');
if (tabCount) tabCount.textContent = `(${totalCommands})`;
this.displayCommands(data);
this.dataFetched.commands = true;
this.checkAllDataLoaded();
})
.catch(error => {
console.warn('Failed to fetch commands:', error);
const tabCount = document.getElementById('commandsTabCount');
if (tabCount) tabCount.textContent = '(Error)';
this.dataFetched.commands = true;
this.checkAllDataLoaded();
});
},
// Helper function to escape HTML entities
escapeHtml: function(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, m => map[m]);
},
displayCommands: function(data) {
const listElement = document.getElementById('commandsList');
if (!listElement) return;
listElement.innerHTML = '';
listElement.className = 'loader-data-value loader-commands-list';
const categoryIcons = {
'System': '⚙️',
'Action': '🎯',
'Controls': '🎮',
'Utilities': '🛠️',
'Commands': '📋',
'Default': '📌'
};
Object.entries(data).forEach(([category, commands]) => {
const categoryDiv = document.createElement('div');
categoryDiv.className = 'loader-command-category';
categoryDiv.innerHTML = `
<div class="loader-command-category-title">
<span class="loader-command-category-icon">${categoryIcons[category] || categoryIcons['Default']}</span>
<span>${this.escapeHtml(category)}</span>
</div>
<div class="loader-commands-grid">
${Object.entries(commands).map(([cmd, cmdData]) => `
<div class="loader-command-item">
<span class="loader-command-bullet">›</span>
<span class="loader-command-name">${this.escapeHtml(cmd)}</span>
${cmdData.description ? `<span class="loader-command-description">${this.escapeHtml(cmdData.description)}</span>` : ''}
</div>
`).join('')}
</div>
`;
listElement.appendChild(categoryDiv);
});
},
fetchAPIConfig: function() {
this.dataFetched.apiConfig = true;
this.checkAllDataLoaded();
},
fetchActionsList: function() {
fetch('/actions.json')
.then(response => response.json())
.then(data => {
const element = document.getElementById('actionsList');
const sortedActions = Object.entries(data).sort((a, b) => {
const aPriority = a[1].priority !== undefined && a[1].priority !== null ? a[1].priority : 999;
const bPriority = b[1].priority !== undefined && b[1].priority !== null ? b[1].priority : 999;
return aPriority - bPriority;
});
this.loadingScreenData.actions = sortedActions;
this.loadingScreenData.actionsCount = sortedActions.length;
const tabCount = document.getElementById('actionsTabCount');
if (tabCount) tabCount.textContent = `(${sortedActions.length})`;
if (element) {
// Group actions by priority ranges
const priorityGroups = {
'Core (Priority 0)': [],
'High Priority (1-3)': [],
'Medium Priority (4-6)': [],
'Low Priority (7-9)': [],
'Other': []
};
sortedActions.forEach(([name, info]) => {
const priority = info.priority !== undefined && info.priority !== null ? info.priority : 999;
if (priority === 0) {
priorityGroups['Core (Priority 0)'].push([name, info]);
} else if (priority <= 3) {
priorityGroups['High Priority (1-3)'].push([name, info]);
} else if (priority <= 6) {
priorityGroups['Medium Priority (4-6)'].push([name, info]);
} else if (priority <= 9) {
priorityGroups['Low Priority (7-9)'].push([name, info]);
} else {
priorityGroups['Other'].push([name, info]);
}
});
let html = '';
Object.entries(priorityGroups).forEach(([groupName, actions]) => {
if (actions.length > 0) {
html += `
<div class="loader-action-category">
<div class="loader-action-category-title">
<span>${groupName} - ${actions.length} action${actions.length !== 1 ? 's' : ''}</span>
</div>
<div class="loader-action-items">
${actions.map(([name, info]) => `
<div class="loader-action-item">
<span class="loader-action-priority">${info.priority !== undefined && info.priority !== null ? `P${info.priority}` : 'P?'}</span>
<span class="loader-action-name">[${name.toUpperCase()}]</span>
<span class="loader-action-description">${info.description || `${name} action module`}</span>
</div>
`).join('')}
</div>
</div>
`;
}
});
element.innerHTML = html;
}
this.dataFetched.actions = true;
this.checkAllDataLoaded();
})
.catch(error => {
console.warn('Failed to fetch actions:', error);
const element = document.getElementById('actionsList');
if (element) element.textContent = 'Error loading actions';
const tabCount = document.getElementById('actionsTabCount');
if (tabCount) tabCount.textContent = '(Error)';
this.dataFetched.actions = true;
this.checkAllDataLoaded();
});
},
// NEW: Dynamic principles fetcher that parses princi2.txt
fetchPrinciplesList: function() {
fetch('/princi2.txt')
.then(response => response.text())
.then(data => {
const tabElement = document.getElementById('principlesTabList');
const tabCount = document.getElementById('principlesTabCount');
// Parse principles from the text format
const principles = this.parsePrinciplesFromText(data);
// Update tab count
if (tabCount) {
tabCount.textContent = `(${principles.length})`;
}
// Group principles by their Group/Tier
const principlesByGroup = {};
principles.forEach(principle => {
const group = principle.group || 'Uncategorized';
if (!principlesByGroup[group]) {
principlesByGroup[group] = [];
}
principlesByGroup[group].push(principle);
});
// Create the HTML - now dynamically based on parsed groups
if (tabElement) {
let html = `
<div style="padding: 0.5rem;">
<div class="loader-principles-intro" style="margin-bottom: 1rem;">
<p style="font-size: 0.875rem; color: #666; font-style: italic;">
${principles.length} principles across ${Object.keys(principlesByGroup).length} tiers guide every interaction, decision, and evolution of the system
</p>
</div>
`;
// Sort groups by tier number (extract from group name)
const sortedGroups = Object.keys(principlesByGroup).sort((a, b) => {
const tierA = this.extractTierNumber(a);
const tierB = this.extractTierNumber(b);
return tierA - tierB;
});
// Display each group
sortedGroups.forEach(group => {
const groupPrinciples = principlesByGroup[group];
// Sort principles within group by priority (highest first)
groupPrinciples.sort((a, b) => (b.priority || 0) - (a.priority || 0));
html += `
<div style="margin-bottom: 1.5rem;">
<h4 style="font-size: 0.9rem; color: #4a76a8; margin-bottom: 0.75rem; padding: 0.5rem; background: #e3f2fd; border-radius: 4px;">
${this.escapeHtml(group)} (${groupPrinciples.length})
</h4>
<div class="loader-principles-list">
`;
groupPrinciples.forEach(principle => {
const priorityColor = principle.priority >= 7 ? '#e53e3e' :
principle.priority >= 5 ? '#ed8936' :
principle.priority >= 3 ? '#4a76a8' : '#718096';
html += `
<div class="loader-principle-item" style="position: relative; padding-right: 2rem;">
<span class="loader-principle-name">${this.escapeHtml(principle.id)} - ${this.escapeHtml(principle.name)}</span>
<span style="position: absolute; top: 0.75rem; right: 0.5rem; font-size: 0.7rem; color: ${priorityColor}; font-weight: bold;">P${principle.priority || '?'}</span>
</div>
`;
});
html += `
</div>
</div>
`;
});
html += '</div>';
tabElement.innerHTML = html;
}
this.dataFetched.principles = true;
this.checkAllDataLoaded();
})
.catch(error => {
console.warn('Failed to fetch principles:', error);
const tabElement = document.getElementById('principlesTabList');
if (tabElement) tabElement.textContent = 'Error loading principles';
const tabCount = document.getElementById('principlesTabCount');
if (tabCount) tabCount.textContent = '(Error)';
this.dataFetched.principles = true;
this.checkAllDataLoaded();
});
},
// NEW: Parser for princi2.txt format
parsePrinciplesFromText: function(text) {
const principles = [];
const lines = text.split('\n');
let currentPrinciple = null;
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
// Check if this is a principle ID line (e.g., "P034 – Progenitor Identity & Authority")
const principleMatch = line.match(/^(P\d+)\s*–\s*(.+)$/);
if (principleMatch) {
// Save previous principle if exists
if (currentPrinciple) {
principles.push(currentPrinciple);
}
// Start new principle
currentPrinciple = {
id: principleMatch[1],
name: principleMatch[2].trim(),
group: null,
priority: null,
description: ''
};
continue;
}
// Parse Group line
if (line.startsWith('Group:') && currentPrinciple) {
currentPrinciple.group = line.substring(6).trim();
continue;
}
// Parse Priority line
if (line.startsWith('Priority:') && currentPrinciple) {
const priorityMatch = line.match(/Priority:\s*(\d+)/);
if (priorityMatch) {
currentPrinciple.priority = parseInt(priorityMatch[1]);
}
continue;
}
// Parse Description line
if (line.startsWith('Description:') && currentPrinciple) {
currentPrinciple.description = line.substring(12).trim();
// Continue reading multi-line descriptions
let j = i + 1;
while (j < lines.length && lines[j].trim() && !lines[j].trim().match(/^P\d+\s*–/)) {
currentPrinciple.description += ' ' + lines[j].trim();
j++;
}
i = j - 1; // Skip the lines we just read
continue;
}
}
// Don't forget the last principle
if (currentPrinciple) {
principles.push(currentPrinciple);
}
return principles;
},
// Helper to extract tier number from group name
extractTierNumber: function(groupName) {
const match = groupName.match(/Tier\s*(\d+)/i);
return match ? parseInt(match[1]) : 999;
},
fetchMemoriesCount: function() {
fetch('/api/memory')
.then(response => response.json())
.then(data => {
let totalMemories = 0;
if (data.facts) {
Object.values(data.facts).forEach(category => {
totalMemories += Object.keys(category).length;
});
}
if (data.conversations) {
totalMemories += Object.keys(data.conversations).length;
}
if (data.preferences) {
totalMemories += Object.keys(data.preferences).length;
}
this.loadingScreenData.memories = data;
this.loadingScreenData.memoriesCount = totalMemories;
const tabCount = document.getElementById('memoriesTabCount');
if (tabCount) {
tabCount.textContent = `(${totalMemories})`;
}
this.displayMemories(data);
this.dataFetched.memories = true;
this.checkAllDataLoaded();
})
.catch(error => {
console.warn('Failed to fetch memories:', error);
const tabCount = document.getElementById('memoriesTabCount');
if (tabCount) tabCount.textContent = '(N/A)';
this.dataFetched.memories = true;
this.checkAllDataLoaded();
});
},
displayMemories: function(data) {
const listElement = document.getElementById('memoriesList');
if (!listElement) return;
listElement.innerHTML = '';
listElement.className = 'loader-data-value loader-memories-list';
// Facts Category
if (data.facts && Object.keys(data.facts).length > 0) {
const factsCategory = document.createElement('div');
factsCategory.className = 'loader-memory-category';
let factsHtml = `
<div class="loader-memory-category-title">
<span class="loader-memory-category-icon">📚</span>
<span>Facts</span>
<span class="loader-memory-category-count">${Object.values(data.facts).reduce((sum, cat) => sum + Object.keys(cat).length, 0)} items</span>
</div>
`;
Object.entries(data.facts).forEach(([category, facts]) => {
factsHtml += `
<div class="loader-memory-subcategory">
<div class="loader-memory-subcategory-title">${category} (${Object.keys(facts).length})</div>
<div class="loader-memory-items">
${Object.entries(facts).map(([key, factData]) => {
// Handle both direct values and objects with 'value' property
let value = '';
if (typeof factData === 'object' && factData !== null && 'value' in factData) {
value = factData.value;
} else {
value = factData;
}
return `
<div class="loader-memory-item">
<span class="loader-memory-bullet">›</span>
<span class="loader-memory-key">${key}:</span>
<span class="loader-memory-value">${value}</span>
</div>
`;
}).join('')}
</div>
</div>
`;
});
factsCategory.innerHTML = factsHtml;
listElement.appendChild(factsCategory);
}
// Conversations Category
if (data.conversations && Object.keys(data.conversations).length > 0) {
const convoCategory = document.createElement('div');
convoCategory.className = 'loader-memory-category';
convoCategory.innerHTML = `
<div class="loader-memory-category-title">
<span class="loader-memory-category-icon">💬</span>
<span>Conversations</span>
<span class="loader-memory-category-count">${Object.keys(data.conversations).length} items</span>
</div>
<div class="loader-memory-items">
${Object.entries(data.conversations).map(([key, value]) => `
<div class="loader-memory-item">
<span class="loader-memory-bullet">›</span>
<span class="loader-memory-key">${key}:</span>
<span class="loader-memory-value">${typeof value === 'object' ? JSON.stringify(value) : value}</span>
</div>
`).join('')}
</div>
`;
listElement.appendChild(convoCategory);
}
// Preferences Category
if (data.preferences && Object.keys(data.preferences).length > 0) {
const prefCategory = document.createElement('div');
prefCategory.className = 'loader-memory-category';
prefCategory.innerHTML = `
<div class="loader-memory-category-title">
<span class="loader-memory-category-icon">⚙️</span>
<span>Preferences</span>
<span class="loader-memory-category-count">${Object.keys(data.preferences).length} items</span>
</div>
<div class="loader-memory-items">
${Object.entries(data.preferences).map(([key, value]) => `
<div class="loader-memory-item">
<span class="loader-memory-bullet">›</span>
<span class="loader-memory-key">${key}:</span>
<span class="loader-memory-value">${typeof value === 'object' ? JSON.stringify(value) : value}</span>
</div>
`).join('')}
</div>
`;
listElement.appendChild(prefCategory);
}
},
// Updated fetchToolsList to handle new agent_tools.json structure
fetchToolsList: function() {
fetch('/agent_tools.json')
.then(response => response.json())
.then(data => {
let totalTools = 0;
// NEW STRUCTURE: Count tools from the 'tools' object
if (data.tools && typeof data.tools === 'object') {
totalTools = Object.keys(data.tools).length;
}
this.loadingScreenData.tools = data;
this.loadingScreenData.toolsCount = totalTools;
const tabCount = document.getElementById('toolsTabCount');
if (tabCount) tabCount.textContent = `(${totalTools})`;
this.displayTools(data);
this.dataFetched.tools = true;
this.checkAllDataLoaded();
})