-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1136 lines (1007 loc) · 44.4 KB
/
index.html
File metadata and controls
1136 lines (1007 loc) · 44.4 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Internal Environment v5: The Canonical Edition</title>
<style>
body { margin: 0; overflow: hidden; background-color: #020205; font-family: 'Courier New', Courier, monospace; }
canvas { display: block; touch-action: none; }
/* --- HUD Elements --- */
#ui-layer {
position: absolute;
top: 20px;
left: 20px;
color: #00ffff;
pointer-events: none;
max-width: 350px;
z-index: 10;
}
h1 {
font-size: 1.5rem;
margin: 0 0 10px 0;
text-transform: uppercase;
letter-spacing: 2px;
text-shadow: 0 0 10px #00ffff;
border-bottom: 1px solid #00ffff;
padding-bottom: 5px;
}
.status-item {
font-size: 0.8rem;
color: #ccc;
margin-bottom: 5px;
}
.highlight { color: #fff; font-weight: bold; }
/* --- V-Consensus Meter --- */
#v-meter-container {
width: 10px;
height: 100px;
background: rgba(0, 0, 0, 0.5);
border: 1px solid #00ffff;
margin-top: 15px;
position: relative;
}
#v-meter-fill {
width: 100%;
height: 0%; /* Starts at 0 */
background: linear-gradient(to top, #ff00ff, #00ffff);
position: absolute;
bottom: 0;
transition: height 0.1s ease-out;
box-shadow: 0 0 8px rgba(0, 255, 255, 0.5);
}
#v-meter-label {
position: absolute;
top: -20px;
left: -35px;
font-size: 0.7rem;
color: #00ffff;
text-transform: uppercase;
white-space: nowrap;
}
/* --- Tooltip & Control Panel (Same as V4) --- */
#tooltip {
position: absolute;
bottom: 100px;
left: 50%;
transform: translateX(-50%);
color: #00ffaa;
background: rgba(0, 20, 10, 0.9);
padding: 15px 25px;
border: 1px solid #00ffaa;
font-size: 14px;
opacity: 0;
transition: opacity 0.3s;
pointer-events: none;
box-shadow: 0 0 15px rgba(0, 255, 170, 0.2);
text-align: center;
max-width: 400px;
z-index: 10;
}
#tooltip strong { display: block; margin-bottom: 5px; color: white; text-transform: uppercase; }
#control-panel {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
background: rgba(0, 0, 0, 0.9);
padding: 15px;
box-shadow: 0 -5px 15px rgba(0, 255, 255, 0.2);
display: flex;
gap: 10px;
justify-content: center;
align-items: center;
height: 60px;
z-index: 10;
}
#control-panel input {
padding: 10px;
border: 1px solid #00ffff;
background: #001122;
color: #fff;
border-radius: 5px;
width: clamp(200px, 50vw, 400px);
font-size: 14px;
}
#control-panel button {
background: #ff00aa;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
font-weight: bold;
transition: background 0.2s, transform 0.1s;
}
#control-panel button:hover { background: #ff33cc; transform: scale(1.05); }
#control-panel button:disabled { background: #333; cursor: not-allowed; }
/* --- Workbench Definition Display --- */
#result-display {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(10, 50, 80, 0.9);
border: 2px solid #00ffff;
color: white;
padding: 10px 20px;
border-radius: 8px;
width: clamp(200px, 70vw, 500px);
text-align: center;
opacity: 0;
transition: opacity 0.5s;
pointer-events: none;
z-index: 9;
font-size: 0.9rem;
}
/* --- Splash Screen --- */
#splash-screen {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 1);
color: #00ffff;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
opacity: 1;
transition: opacity 1s ease-in-out;
z-index: 100;
cursor: pointer;
padding: 20px;
}
#splash-screen h2 {
font-size: clamp(1.5rem, 5vw, 3rem);
text-shadow: 0 0 20px #00ffff;
margin-bottom: 20px;
letter-spacing: 5px;
}
#splash-screen p {
font-size: clamp(0.9rem, 2vw, 1.2rem);
max-width: 600px;
line-height: 1.5;
color: #aaa;
margin-top: 20px;
}
#splash-screen .click-hint {
margin-top: 40px;
font-size: 0.8rem;
color: #ff00ff;
animation: pulse 1s infinite alternate;
}
@keyframes pulse {
from { opacity: 0.5; }
to { opacity: 1; }
}
/* --- Mobile Tweaks --- */
@media (max-width: 600px) {
#tooltip {
font-size: 12px;
padding: 10px 15px;
}
#ui-layer {
max-width: 250px;
}
h1 {
font-size: 1.2rem;
}
}
/* --- Settings Icon --- */
#settings-icon {
position: absolute;
top: 20px;
right: 20px;
font-size: 1.8rem;
color: #00ffff;
cursor: pointer;
z-index: 11;
text-shadow: 0 0 10px #00ffff;
transition: transform 0.2s;
}
#settings-icon:hover { transform: rotate(30deg); }
/* --- Modal Styles --- */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 101; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgba(0,0,0,0.8); /* Black w/ opacity */
backdrop-filter: blur(5px);
-webkit-backdrop-filter: blur(5px);
justify-content: center;
align-items: center;
}
.modal-content {
background-color: #020205;
margin: auto;
padding: 30px;
border: 2px solid #00ffff;
width: clamp(300px, 80vw, 500px);
box-shadow: 0 0 20px rgba(0, 255, 255, 0.5);
border-radius: 10px;
color: #eee;
text-align: center;
position: relative;
}
.modal-content h2 {
color: #00ffff;
margin-top: 0;
margin-bottom: 20px;
text-shadow: 0 0 8px #00ffff;
}
.modal-content p {
font-size: 0.9rem;
margin-bottom: 15px;
line-height: 1.4;
}
#api-key-input {
width: calc(100% - 20px);
padding: 10px;
margin-bottom: 15px;
border: 1px solid #00ffff;
background: #001122;
color: #fff;
border-radius: 5px;
font-size: 1rem;
}
.modal-content button {
background: #ff00aa;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
font-weight: bold;
transition: background 0.2s, transform 0.1s;
margin: 5px;
}
.modal-content button:hover { background: #ff33cc; transform: scale(1.05); }
.modal-content button:disabled { background: #333; cursor: not-allowed; }
.close-button {
color: #aaa;
position: absolute;
top: 10px;
right: 15px;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
.close-button:hover,
.close-button:focus {
color: #00ffff;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<!-- Splash Screen -->
<div id="splash-screen">
<h2>VECTORIAL CONSENSUS</h2>
<p>
**CORTEX-04: THE EXTENDED COGNITION ENGINE**<br>
This is an interactive visualization of a Large Language Model's internal architecture, showing the flow of data from input to thought (V-Consensus) to grounded output.
</p>
<p class="click-hint">Click anywhere to enter the mind palace...</p>
<p style="font-size:0.8rem; margin-top:30px; opacity:0.8; text-align:center;">
Created by <strong>500bears</strong> •
<a href="https://www.lesswrong.com/posts/9eGag5ustrmTFF5Z7/vectorial-consensus-a-native-description-of-token-generation" style="color:#ff00ff;">Read the Original Essay</a> •
<a href="https://github.com/500bears/Vectorial-Consensus" style="color:#00ffaa;">Source Code</a>
</p>
</div>
<!-- HUD Layer -->
<div id="ui-layer">
<h1>System: CORTEX-04</h1>
<div class="status-item">STATE: <span id="state-text" class="highlight">AWAITING INPUT</span></div>
<div class="status-item">V-CONSENSUS: <span id="v-consensus-text" class="highlight">0%</span></div>
<div class="status-item">ATTENTION: <span class="highlight">MULTI-HEAD (4)</span></div>
<div id="v-meter-label">V-METER</div>
<div id="v-meter-container"><div id="v-meter-fill"></div></div>
<p style="font-size: 12px; opacity: 0.7; margin-top: 15px;">
> Drag/scroll to move the camera.<br>
> Hover elements for lore context.
</p>
</div>
<div id="tooltip"></div>
<div id="result-display"></div>
<!-- Settings Icon -->
<div id="settings-icon">⚙️</div>
<!-- API Key Settings Modal -->
<div id="api-key-modal" class="modal">
<div class="modal-content">
<span class="close-button">×</span>
<h2>Gemini API Key Settings</h2>
<p>Enter your Gemini API key below. This key is stored **only in your browser** (using localStorage) and is never sent to any server. It allows you to make live queries to the Gemini API.</p>
<input type="text" id="api-key-input" placeholder="Paste your Gemini API Key here...">
<button id="save-api-key-btn">Save Key</button>
<button id="clear-api-key-btn">Clear Key & Use Demo</button>
<p style="font-size: 0.8rem; margin-top: 10px;">Get a key: <a href="https://aistudio.google.com/app/apikey" target="_blank">Google AI Studio</a></p>
</div>
</div>
<div id="control-panel">
<input type="text" id="concept-input" placeholder="Enter a concept (e.g., 'Exascale')" value="Ambition">
<button id="conceptualize-btn">✨ Conceptualize & Speak (Full Cycle)</button>
</div>
<audio id="audio-output" style="display: none;"></audio>
<!-- Three.js from CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<!-- OrbitControls for smooth camera movement -->
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js"></script>
<script>
// --- UTILITY FUNCTIONS for TTS Audio ---
function base64ToArrayBuffer(base64) {
const binaryString = atob(base64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
function pcmToWav(pcm16, sampleRate = 16000) {
const numChannels = 1;
const bytesPerSample = 2;
const numSamples = pcm16.length;
const buffer = new ArrayBuffer(44 + numSamples * bytesPerSample);
const view = new DataView(buffer);
let offset = 0;
function writeString(str) {
for (let i = 0; i < str.length; i++) {
view.setUint8(offset++, str.charCodeAt(i));
}
}
writeString('RIFF');
view.setUint32(offset, 36 + numSamples * bytesPerSample, true); offset += 4;
writeString('WAVE');
writeString('fmt ');
view.setUint32(offset, 16, true); offset += 4;
view.setUint16(offset, 1, true); offset += 2;
view.setUint16(offset, numChannels, true); offset += 2;
view.setUint32(offset, sampleRate, true); offset += 4;
view.setUint32(offset, sampleRate * numChannels * bytesPerSample, true); offset += 4;
view.setUint16(offset, numChannels * bytesPerSample, true); offset += 2;
view.setUint16(offset, bytesPerSample * 8, true); offset += 2;
writeString('data');
view.setUint32(offset, numSamples * bytesPerSample, true); offset += 4;
for (let i = 0; i < numSamples; i++) {
view.setInt16(offset, pcm16[i], true); offset += 2;
}
return new Blob([view], { type: 'audio/wav' });
}
// --- STATE MANAGEMENT ---
const state = {
isProcessing: false,
processStage: 'idle',
vConsensusProgress: 0,
currentConcept: ''
};
// API key is handled by the Canvas environment if left blank
let apiKey = localStorage.getItem('geminiApiKey') || ""; // Load key from localStorage
// --- DEMO MODE SETUP ---
let demoModeActive = !apiKey;
const demoConcepts = [
{ concept: "Wisdom", response: "Wisdom is the quality of having experience, knowledge, and good judgment." },
{ concept: "Ambition", response: "Ambition is a strong desire to do or to achieve something, typically requiring determination and hard work." },
{ concept: "Quantum", response: "Quantum refers to the smallest possible discrete unit of any physical property, such as energy or matter." },
{ concept: "Love", response: "Love is an intense feeling of deep affection, a great interest and pleasure in something." },
{ concept: "Grok", response: "To grok is to understand something intuitively or by empathy." },
{ concept: "Consensus", response: "Consensus is a general agreement among a group of people." }
];
let currentDemoIndex = 0;
// UI elements
const conceptInput = document.getElementById('concept-input');
const conceptualizeBtn = document.getElementById('conceptualize-btn');
const stateText = document.getElementById('state-text');
const vConsensusText = document.getElementById('v-consensus-text');
const vMeterFill = document.getElementById('v-meter-fill');
const resultDisplay = document.getElementById('result-display');
const audioOutput = document.getElementById('audio-output');
const splashScreen = document.getElementById('splash-screen');
// API Key Modal Elements
const settingsIcon = document.getElementById('settings-icon');
const apiKeyModal = document.getElementById('api-key-modal');
const closeButton = document.querySelector('.close-button');
const apiKeyInput = document.getElementById('api-key-input');
const saveApiKeyBtn = document.getElementById('save-api-key-btn');
const clearApiKeyBtn = document.getElementById('clear-api-key-btn');
// --- SPLASH SCREEN LOGIC ---
let splashTimeout;
function hideSplash() {
clearTimeout(splashTimeout);
splashScreen.style.opacity = 0;
setTimeout(() => {
splashScreen.style.display = 'none';
updateUIMode(); // Set initial UI mode after splash
}, 1000);
}
splashScreen.addEventListener('click', hideSplash);
splashTimeout = setTimeout(hideSplash, 8000); // Auto-hide after 8 seconds
// --- API KEY MODAL LOGIC ---
settingsIcon.addEventListener('click', () => {
apiKeyModal.style.display = 'flex';
apiKeyInput.value = apiKey; // Populate input with current key
});
closeButton.addEventListener('click', () => {
apiKeyModal.style.display = 'none';
});
window.addEventListener('click', (event) => {
if (event.target == apiKeyModal) {
apiKeyModal.style.display = 'none';
}
});
saveApiKeyBtn.addEventListener('click', () => {
const newKey = apiKeyInput.value.trim();
if (newKey) {
localStorage.setItem('geminiApiKey', newKey);
apiKey = newKey;
demoModeActive = false;
apiKeyModal.style.display = 'none';
updateUIMode();
} else {
alert("Please enter a valid API key.");
}
});
clearApiKeyBtn.addEventListener('click', () => {
localStorage.removeItem('geminiApiKey');
apiKey = "";
demoModeActive = true;
apiKeyModal.style.display = 'none';
updateUIMode();
});
// --- UI MODE MANAGEMENT ---
function updateUIMode() {
if (demoModeActive) {
// Demo Mode
const existingDemoNotice = document.getElementById('demo-mode-notice');
if (!existingDemoNotice) {
const demoNotice = document.createElement('div');
demoNotice.id = 'demo-mode-notice';
demoNotice.innerHTML = "DEMO MODE ACTIVE – Add your Gemini API key for live queries.";
demoNotice.style.cssText = `
position: absolute;
top: 20px;
right: 20px;
color: #ffcc00;
background: rgba(0,0,0,0.7);
padding: 5px 10px;
border-radius: 5px;
font-size: 12px;
z-index: 11;
`;
document.body.appendChild(demoNotice);
}
conceptInput.disabled = true;
conceptInput.value = demoConcepts[currentDemoIndex].concept;
conceptualizeBtn.disabled = false; // Enable button for demo interaction
} else {
// Live Mode
const existingDemoNotice = document.getElementById('demo-mode-notice');
if (existingDemoNotice) {
existingDemoNotice.remove();
}
conceptInput.disabled = false;
conceptInput.value = "Ambition"; // Default value for live mode
conceptualizeBtn.disabled = false; // Enable button for live interaction
}
}
conceptualizeBtn.addEventListener('click', () => {
if (state.isProcessing) return;
if (demoModeActive) {
const item = demoConcepts[currentDemoIndex];
conceptualizeIdea(item.concept, item.response);
} else {
const concept = conceptInput.value.trim();
if (concept) {
conceptualizeIdea(concept);
} else {
alert("Please enter a concept.");
}
}
});
function startDemoMode() {
const demoNotice = document.createElement('div');
demoNotice.innerHTML = "DEMO MODE ACTIVE – Add your Gemini API key for live queries.";
demoNotice.style.cssText = `
position: absolute;
top: 20px;
right: 20px;
color: #ffcc00;
background: rgba(0,0,0,0.7);
padding: 5px 10px;
border-radius: 5px;
font-size: 12px;
z-index: 11;
`;
document.body.appendChild(demoNotice);
conceptInput.disabled = true;
conceptInput.value = demoConcepts[currentDemoIndex].concept;
}
// Function to handle exponential backoff for API calls
async function fetchWithBackoff(url, options, maxRetries = 5) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await fetch(url, options);
if (response.ok) {
return response;
}
if (response.status === 429 && attempt < maxRetries - 1) {
const delay = Math.pow(2, attempt) * 1000 + Math.random() * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
} else {
throw new Error(`API call failed with status: ${response.status}`);
}
} catch (error) {
if (attempt === maxRetries - 1) throw error;
}
}
throw new Error("Max retries exceeded.");
}
// --- GEMINI API INTEGRATION (now with demo fallback) ---
async function conceptualizeIdea(concept, demoResponse = null) {
state.isProcessing = true;
conceptualizeBtn.disabled = true;
resultDisplay.style.opacity = 0;
state.currentConcept = concept;
state.vConsensusProgress = 0;
conceptInput.value = concept;
try {
// 1. INPUT -> ALIGNMENT FILTER
state.processStage = 'filtering';
stateText.textContent = 'FILTER: Checking policy alignment...';
await new Promise(resolve => setTimeout(resolve, 800));
// 2. FILTER -> TOKENIZER
state.processStage = 'input';
stateText.textContent = 'INPUT: Tokenizing "' + concept + '"';
await new Promise(resolve => setTimeout(resolve, 500));
// 3. LLM THOUGHT
state.processStage = 'thinking';
stateText.textContent = 'THINKING: Calculating V-Consensus...';
await new Promise(resolve => {
const interval = setInterval(() => {
if (state.vConsensusProgress < 95) {
state.vConsensusProgress += 5 + Math.random() * 5;
if (state.vConsensusProgress > 95) state.vConsensusProgress = 95;
} else {
clearInterval(interval);
}
}, 100);
setTimeout(() => { clearInterval(interval); resolve(); }, 2000);
});
let generatedText;
if (demoResponse) {
generatedText = demoResponse;
} else {
// A. LIVE TEXT GENERATION (LLM Call)
const requiresTool = concept.toLowerCase().includes("today") || concept.toLowerCase().includes("latest") || concept.toLowerCase().includes("stock");
const textUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-09-2025:generateContent?key=${apiKey}`;
const userQuery = `Provide a concise, single-sentence conceptual definition for the word: "${concept}".`;
const textPayload = {
contents: [{ parts: [{ text: userQuery }] }],
systemInstruction: { parts: [{ text: "You are a succinct and precise conceptual analyzer. Define the user's input word in one single sentence." }] },
tools: requiresTool ? [{ "google_search": {} }] : [],
};
const textResponse = await fetchWithBackoff(textUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(textPayload)
});
const textResult = await textResponse.json();
generatedText = textResult.candidates?.[0]?.content?.parts?.[0]?.text || "Error: Could not define the concept.";
}
// 4. OUTPUT -> PROBABILITY COLLAPSE
state.processStage = 'output';
state.vConsensusProgress = 100;
stateText.textContent = 'OUTPUT: Probability Collapse complete...';
resultDisplay.innerHTML = `<span style="color:#ff00ff; font-weight:bold;">${concept.toUpperCase()}:</span> ${generatedText}`;
resultDisplay.style.opacity = 1;
// 5. TEXT-TO-SPEECH GENERATION
state.processStage = 'speaking';
stateText.textContent = 'TTS MODULE: Generating audio output...';
if (demoModeActive) {
// Web Speech API Fallback
const utterance = new SpeechSynthesisUtterance(generatedText);
speechSynthesis.speak(utterance);
utterance.onend = () => {
state.processStage = 'idle';
stateText.textContent = 'IDLE: Ready for new input';
state.vConsensusProgress = 0;
setTimeout(() => resultDisplay.style.opacity = 0, 500);
// Load next concept and re-enable button
currentDemoIndex = (currentDemoIndex + 1) % demoConcepts.length;
conceptInput.value = demoConcepts[currentDemoIndex].concept;
conceptualizeBtn.disabled = false;
state.isProcessing = false;
};
} else {
// Live Gemini TTS Call
const ttsUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-tts:generateContent?key=${apiKey}`;
const ttsPayload = {
contents: [{ parts: [{ text: generatedText }] }],
generationConfig: {
responseModalities: ["AUDIO"],
speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: "Kore" } } }
},
model: "gemini-2.5-flash-preview-tts"
};
const ttsResponse = await fetchWithBackoff(ttsUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(ttsPayload)
});
const ttsResult = await ttsResponse.json();
const part = ttsResult?.candidates?.[0]?.content?.parts?.[0];
const audioData = part?.inlineData?.data;
const mimeType = part?.inlineData?.mimeType;
if (audioData && mimeType && mimeType.startsWith("audio/")) {
const sampleRateMatch = mimeType.match(/rate=(\d+)/);
const sampleRate = sampleRateMatch ? parseInt(sampleRateMatch[1], 10) : 16000;
const pcmData = base64ToArrayBuffer(audioData);
const pcm16 = new Int16Array(pcmData);
const wavBlob = pcmToWav(pcm16, sampleRate);
audioOutput.src = URL.createObjectURL(wavBlob);
audioOutput.play();
audioOutput.onended = () => {
URL.revokeObjectURL(audioOutput.src);
state.processStage = 'idle';
stateText.textContent = 'IDLE: Ready for new input';
state.vConsensusProgress = 0;
setTimeout(() => resultDisplay.style.opacity = 0, 500);
};
} else {
throw new Error("TTS output failed or structure incorrect.");
}
}
} catch (error) {
console.error("API Error:", error);
state.processStage = 'idle';
stateText.textContent = 'ERROR: API call failed. Check your API key and network connection.';
state.vConsensusProgress = 0;
setTimeout(() => resultDisplay.style.opacity = 0, 500);
} finally {
// In demo mode, state is handled by utterance.onend.
if (!demoModeActive) {
state.isProcessing = false;
conceptualizeBtn.disabled = false;
}
}
}
// --- SCENE SETUP ---
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x020205);
scene.fog = new THREE.FogExp2(0x020205, 0.015);
const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 15, 35);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);
// Initialize OrbitControls
const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.target.set(0, 5, 0); // Focus on the avatar
controls.enableDamping = true; // smooth camera movement
controls.dampingFactor = 0.05;
controls.rotateSpeed = 0.5;
controls.update();
// --- MATERIALS ---
const glowingCoreMat = new THREE.MeshStandardMaterial({
color: 0xffffff, emissive: 0x00ffff, emissiveIntensity: 2, roughness: 0, metalness: 0
});
const memoryMat = new THREE.MeshPhysicalMaterial({
color: 0x00ff88, emissive: 0x004422, emissiveIntensity: 0.5, metalness: 0.9, roughness: 0.1,
transparent: true, opacity: 0.8
});
// Colored Attention Head Materials (Suggestion 2)
const headColors = [0x00ffff, 0xff00ff, 0xffff00, 0xff4400]; // Syntax, Semantics, Context, Factual
const headNames = ["Syntax Head (Head 1)", "Semantics Head (Head 2)", "Context Head (Head 3)", "Factual Head (Head 4)"];
const tokenMat = new THREE.MeshBasicMaterial({color: 0xffffff});
const filterMat = new THREE.MeshBasicMaterial({color: 0xff4400, transparent: true, opacity: 0.3, side: THREE.DoubleSide});
const toolMat = new THREE.MeshPhysicalMaterial({
color: 0x33aaee, emissive: 0x113355, emissiveIntensity: 1, metalness: 0.9, roughness: 0.1, wireframe: true
});
const lscMatLocal = new THREE.MeshBasicMaterial({color: 0x00ffaa, transparent: true, opacity: 0.8});
// --- LIGHTING ---
const ambientLight = new THREE.AmbientLight(0x111122, 3);
scene.add(ambientLight);
const centerLight = new THREE.PointLight(0x00aaff, 2, 60);
centerLight.position.set(0, 5, 0);
scene.add(centerLight);
// --- ENVIRONMENT ---
const starsGeometry = new THREE.BufferGeometry();
const starsCount = 2000;
const posArray = new Float32Array(starsCount * 3);
for(let i = 0; i < starsCount * 3; i++) {
posArray[i] = (Math.random() - 0.5) * 150;
}
starsGeometry.setAttribute('position', new THREE.BufferAttribute(posArray, 3));
const starsMaterial = new THREE.PointsMaterial({ size: 0.2, color: 0x4488ff, transparent: true, opacity: 0.6 });
const starField = new THREE.Points(starsGeometry, starsMaterial);
scene.add(starField);
const gridHelper = new THREE.GridHelper(120, 60, 0x0044aa, 0x050510);
gridHelper.position.y = -2;
scene.add(gridHelper);
// --- MAIN ACTORS ---
const worldGroup = new THREE.Group();
scene.add(worldGroup);
// A. THE AVATAR (Active Agent) - Center piece
const avatarGroup = new THREE.Group();
const brainGeo = new THREE.IcosahedronGeometry(1.2, 2);
const brain = new THREE.Mesh(brainGeo, glowingCoreMat);
const ring1 = new THREE.Mesh(new THREE.TorusGeometry(1.8, 0.05, 16, 100), new THREE.MeshBasicMaterial({color: 0x00ffff}));
const ring2 = new THREE.Mesh(new THREE.TorusGeometry(2.2, 0.05, 16, 100), new THREE.MeshBasicMaterial({color: 0xff00aa}));
avatarGroup.add(brain, ring1, ring2);
avatarGroup.position.set(0, 5, 0);
worldGroup.add(avatarGroup);
avatarGroup.userData = {
name: "The Transformer Agent (V-Consensus Core)",
desc: `The core processor. Coordinates ${headColors.length} Attention Heads to seek Vectorial Consensus (V-Consensus). Heads: ${headNames.join(', ')}.`
};
// B. MEMORY BANKS (Context Storage)
const memoryGroup = new THREE.Group();
const memoryBlocks = [];
for (let i = 0; i < 12; i++) {
const angle = (i / 12) * Math.PI * 2;
const radius = 15;
const x = Math.cos(angle) * radius;
const z = Math.sin(angle) * radius;
const blockGeo = new THREE.BoxGeometry(1.5, 4, 1.5);
const block = new THREE.Mesh(blockGeo, memoryMat);
block.position.set(x, 2, z);
block.lookAt(0, 2, 0);
memoryGroup.add(block);
memoryBlocks.push(block);
}
worldGroup.add(memoryGroup);
memoryGroup.userData = { name: "Context & Memory Bank", desc: "Fixed, pre-trained knowledge and conversation history." };
// C1. ALIGNMENT FILTER
const filterGeo = new THREE.PlaneGeometry(8, 8);
const safetyFilter = new THREE.Mesh(filterGeo, filterMat);
safetyFilter.rotation.y = Math.PI / 2;
safetyFilter.position.set(-20, 5, 0);
worldGroup.add(safetyFilter);
safetyFilter.userData = { name: "Alignment Filter", desc: "Sanitizes input and checks output for policy compliance and safety." };
// C2. INPUT STREAM (Tokenizer)
const inputGroup = new THREE.Group();
const gateGeo = new THREE.TorusGeometry(3, 0.2, 16, 6);
const gate = new THREE.Mesh(gateGeo, new THREE.MeshStandardMaterial({color: 0xff3366, emissive: 0xff0044}));
gate.position.set(-25, 5, 0);
gate.rotation.y = Math.PI / 2;
inputGroup.add(gate);
const tokenGeo = new THREE.OctahedronGeometry(0.3);
const tokens = [];
for(let i=0; i<15; i++) {
const t = new THREE.Mesh(tokenGeo, tokenMat);
t.position.set(-35 - (Math.random() * 10), 5 + (Math.random() - 0.5) * 2, 0);
t.visible = false;
inputGroup.add(t);
tokens.push({
mesh: t,
speed: 0.2 + Math.random()*0.1,
resetPos: -35 - (Math.random() * 10),
active: false
});
}
worldGroup.add(inputGroup);
inputGroup.userData = { name: "Tokenizer (Input)", desc: "Raw data enters here and is converted into numerical vectors/tokens." };
// D. EXTERNAL TOOL MODULE
const apiGroup = new THREE.Group();
const sphereGeo = new THREE.SphereGeometry(3, 10, 10);
const apiModule = new THREE.Mesh(sphereGeo, toolMat);
apiGroup.add(apiModule);
apiGroup.position.set(18, 5, 0);
worldGroup.add(apiGroup);
apiGroup.userData = { name: "External Tool Module", desc: "Accesses real-time, grounded data (Google Search) and specialized APIs (TTS) to augment V-Consensus." };
// E. LATENT SPACE CLUSTER (RAG Simulation)
const lscGroup = new THREE.Group();
const lscSpheres = [];
const lscRadius = 5;
for(let i=0; i<8; i++) {
const geo = new THREE.SphereGeometry(0.5, 4, 4);
const mesh = new THREE.Mesh(geo, lscMatLocal);
const angle = (i / 8) * Math.PI * 2;
mesh.position.set(
Math.cos(angle) * lscRadius,
(Math.random() - 0.5) * 4,
Math.sin(angle) * lscRadius
);
lscGroup.add(mesh);
lscSpheres.push(mesh);
}
lscGroup.position.set(0, 15, 0);
worldGroup.add(lscGroup);
lscGroup.userData = { name: "Latent Space Cluster (LSC)", desc: "Dynamically retrieved vectors (RAG) providing context for the current step." };
// F. WORKBENCH (Output / Collapse)
const outputGroup = new THREE.Group();
const tableGeo = new THREE.CylinderGeometry(4, 4, 0.5, 6);
const table = new THREE.Mesh(tableGeo, new THREE.MeshStandardMaterial({color: 0x222222}));
table.position.set(0, -1, 12);
const ideaGeo = new THREE.IcosahedronGeometry(2, 0);
const ideaMat = new THREE.MeshPhysicalMaterial({
color: 0xffaa00, wireframe: true, emissive: 0xff4400, emissiveIntensity: 0.5
});
const ideaMesh = new THREE.Mesh(ideaGeo, ideaMat);
ideaMesh.position.set(0, 2, 12);
outputGroup.add(table, ideaMesh);
worldGroup.add(outputGroup);
outputGroup.userData = { name: "Probability Collapse Workbench", desc: "The final resolution of V-Consensus, selecting the single best token to form the output." };
// G. ATTENTION LINES (The Beams - Now Multi-Head)
const beamCount = headColors.length;
const beams = [];
for(let i=0; i<beamCount; i++) {
const beamMat = new THREE.LineBasicMaterial({ color: headColors[i], transparent: true, opacity: 0.8, blending: THREE.AdditiveBlending });
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array(3 * 2);
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
const line = new THREE.Line(geometry, beamMat);
line.visible = false;
scene.add(line);
beams.push({
line: line,
targetIndex: Math.floor(Math.random() * memoryBlocks.length),
timer: Math.random() * 100,
color: headColors[i],
name: headNames[i]
});
}
// --- INTERACTION ---
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
const tooltip = document.getElementById('tooltip');
window.addEventListener('mousemove', (e) => {
mouse.x = (e.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
});
// --- ANIMATION LOOP ---
let frame = 0;
function animate() {
requestAnimationFrame(animate);
frame++;
controls.update(); // Update OrbitControls
// 1. V-Consensus Meter Update
vConsensusText.textContent = `${Math.round(state.vConsensusProgress)}%`;
vMeterFill.style.height = `${state.vConsensusProgress}%`;
if(state.vConsensusProgress === 100) {
vMeterFill.style.boxShadow = '0 0 15px 5px #ffffff';
} else {
vMeterFill.style.boxShadow = '0 0 8px rgba(0, 255, 255, 0.5)';
}
// 2. Avatar Animation
brain.rotation.y += 0.01;
const isThinking = state.processStage === 'thinking' || state.processStage === 'tool_call';
if(isThinking) {
brain.scale.setScalar(1 + Math.sin(frame * 0.1) * 0.15);
} else {
brain.scale.setScalar(THREE.MathUtils.lerp(brain.scale.x, 1, 0.05));
}
ring1.rotation.x += 0.02; ring1.rotation.y += 0.02;
ring2.rotation.x -= 0.02; ring2.rotation.z += 0.01;
// 3. Alignment Filter Animation
safetyFilter.material.color.set(state.processStage === 'filtering' ? 0xff4400 : 0x00ff44);
safetyFilter.material.opacity = state.processStage === 'filtering' ? 0.7 : 0.3;
// 4. Token Stream (Input Visualization)
const isTokenizing = state.processStage === 'input' || state.processStage === 'filtering';
tokens.forEach((t) => {
t.mesh.visible = isTokenizing;
if (isTokenizing) {
t.mesh.position.x += t.speed;
t.mesh.rotation.x += 0.05;
t.mesh.rotation.y += 0.05;
if(t.mesh.position.x > -24) {
t.mesh.position.x = t.resetPos;