-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
553 lines (502 loc) · 22.3 KB
/
script.js
File metadata and controls
553 lines (502 loc) · 22.3 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
// horus AI Assistant - Simple Voice ID Interface
// CONFIG is already loaded from config.js
// Simple response caching
const responseCache = new Map();
// Voice mapping is now handled by audio.js module
// Audio generation is now handled by audio.js module
// Add message to chat window
function addMessageToChat(message, type) {
const messagesContainer = document.getElementById('messages');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${type}-message`;
if (type === 'user') {
messageDiv.innerHTML = `<strong>You:</strong> ${message}`;
} else {
// Remove tags from AI messages for display
const cleanMessage = message.replace(/\[[^\]]+\]/g, '');
messageDiv.innerHTML = `<strong>AI:</strong> ${cleanMessage}`;
}
messagesContainer.appendChild(messageDiv);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
// Get AI response from Perplexity with streaming
async function getAIResponse(userInput) {
console.log('Getting AI response for:', userInput);
// Log user query
if (typeof TerminalLogContainer !== 'undefined') {
TerminalLogContainer.addLogEntry('user', `Query: "${userInput}"`);
TerminalLogContainer.addTerminalOutput('query', `Processing: ${userInput}`);
}
// Check cache first - simple optimization
const cacheKey = userInput.toLowerCase().trim();
if (responseCache.has(cacheKey)) {
console.log('Using cached response!');
const cachedResponse = responseCache.get(cacheKey);
// Log cache hit
if (typeof TerminalLogContainer !== 'undefined') {
TerminalLogContainer.addTerminalOutput('cache', 'Using cached response');
}
// Add to chat immediately
addMessageToChat(cachedResponse, 'ai');
// Process for audio using audio.js (keep tags for ElevenLabs)
const sentences = cachedResponse
.split('\n')
.filter(line => line.trim().startsWith('-'))
.map(line => line.trim().substring(2))
.filter(s => s.length > 0);
if (sentences.length > 0) {
const selectedAgent = document.getElementById('agentSelect').value;
const voiceId = AudioModule.voices[selectedAgent];
// Use audio.js streaming playback
await AudioModule.streamingAudioPlayback(sentences, voiceId, selectedAgent);
}
return cachedResponse;
}
// Create streaming UI
const messagesContainer = document.getElementById('messages');
const messageDiv = document.createElement('div');
messageDiv.className = 'message ai-message';
messageDiv.innerHTML = '<strong>AI:</strong> <span class="streaming-text"></span>';
messagesContainer.appendChild(messageDiv);
const streamingText = messageDiv.querySelector('.streaming-text');
try {
// Get AI response from ai.js
const aiResponse = await AI.getAIResponse(userInput);
// Handle both old format (string) and new format (object with content)
const response = typeof aiResponse === 'string' ? aiResponse : aiResponse.content;
// Update UI with clean text (no tags)
const cleanResponse = response
.split('\n')
.filter(line => line.trim().startsWith('-'))
.map(line => line.trim().substring(2))
.map(line => line.replace(/\[[^\]]+\]/g, ''))
.join(' ');
streamingText.textContent = cleanResponse;
messagesContainer.scrollTop = messagesContainer.scrollHeight;
// Cache the response
responseCache.set(cacheKey, response);
// Log AI response
if (typeof TerminalLogContainer !== 'undefined') {
TerminalLogContainer.addLogEntry('horus', 'AI response generated');
TerminalLogContainer.addTerminalOutput('ai response', 'Response complete');
}
// Process for audio using audio.js (keep tags for ElevenLabs)
const sentences = response
.split('\n')
.filter(line => line.trim().startsWith('-'))
.map(line => line.trim().substring(2))
.filter(s => s.length > 0);
if (sentences.length > 0) {
const selectedAgent = document.getElementById('agentSelect').value;
const voiceId = AudioModule.voices[selectedAgent];
// Use audio.js streaming playback
await AudioModule.streamingAudioPlayback(sentences, voiceId, selectedAgent);
}
return response;
} catch (error) {
console.error('AI Error:', error);
streamingText.textContent = 'Sorry, I encountered an error.';
addMessageToChat('Sorry, I encountered an error.', 'ai');
// Log error
if (typeof TerminalLogContainer !== 'undefined') {
TerminalLogContainer.addLogEntry('error', `AI error: ${error.message}`);
TerminalLogContainer.addTerminalOutput('error', `Error: ${error.message}`);
}
}
}
// Removed second Perplexity call - keeping it simple
// 15 Text Categories with 5 Audio Tags Each
const textCategories = {
greetings: `[cheerfully] Hello there! [excited] Great to see you! [warmly] Welcome back! [playfully] Hey buddy! [calm] Good to meet you!`,
goodbyes: `[warmly] See you later! [playfully] Catch you soon! [calm] Take care now! [cheerfully] Until next time! [whispers] Bye for now!`,
happy: `[laughs] That's fantastic! [excited] I'm thrilled! [cheerfully] This is wonderful! [playfully] Amazing news! [giggles] So happy!`,
sad: `[sorrowful] I'm so sorry... [whispers] That's heartbreaking... [calm] I understand your pain... [tired] This is difficult... [sighs] My condolences.`,
tension: `[nervous] This is concerning... [hesitates] I'm worried... [flatly] This is serious... [whispers] Something's wrong... [anxiously] I'm not sure...`,
excited: `[excited] This is incredible! [laughs] I can't believe it! [playfully] This is so cool! [cheerfully] Amazing! [giggles] So exciting!`,
anxious: `[nervous] I'm not sure... [hesitates] Maybe we should... [worried] I'm concerned... [anxiously] What if... [whispers] I'm scared...`,
thinking: `[humming] Hmm, let me think... [pauses] Let me process... [calm] Interesting question... [slowly] Let me analyze... [hesitates] Um, let me consider...`,
confident: `[confidently] I've got this! [assuredly] No problem! [calm] I can handle this... [cheerfully] Easy peasy! [playfully] Piece of cake!`,
surprised: `[gasps] Really? [excited] No way! [amazed] That's unexpected! [laughs] You're kidding! [playfully] Get out of here!`,
frustrated: `[frustrated] This is annoying... [sighs] I'm getting tired... [flatly] Not again... [tired] This is exhausting... [grumbles] Seriously?`,
relieved: `[sigh of relief] Finally! [calm] That's better... [cheerfully] Much better now! [laughs] Thank goodness! [playfully] Crisis averted!`,
mysterious: `[whispers] I know something... [mysteriously] There's more... [chuckles] You'll see... [playfully] Wait and watch... [secretively] Shh, listen...`,
professional: `[formally] I've prepared the report... [calm] Shall I proceed? [confidently] I've noted your request... [assuredly] Consider it done... [professionally] I'll handle this.`,
casual: `[chuckles] Hey dude! [playfully] What's up? [relaxed] Just hanging out... [cheerfully] How's it going? [casually] Not much, you?`
};
// Eleven v3 TTS with simple voice settings
// TTS generation is now handled by audio.js module
// Audio context is now handled by audio.js module
// Audio player variables are now handled by audio.js module
// Audio player initialization is now handled by audio.js module
// Audio player functions are now handled by audio.js module
// Audio analysis functions are now handled by audio.js module
// Simple audio playback with HTML5 Audio
// Audio playback is now handled by audio.js module
// Progress animation functions are now handled by audio.js module
// Test function is now handled by audio.js module
// Main play function - now uses hybrid approach
async function playSelected() {
const aiToggle = document.getElementById('aiToggle').classList.contains('active');
const selectedAgent = document.getElementById('agentSelect').value;
const voiceId = voices[selectedAgent];
if (aiToggle) {
// AI Mode - get user input from textarea
const userInput = document.getElementById('messageInput').value;
if (!userInput.trim()) {
console.error('Please enter a message for AI mode');
return;
}
// Check for map commands FIRST
console.log('Checking for map commands:', userInput);
if (typeof MapCommands !== 'undefined' && MapCommands.detect(userInput)) {
console.log('Map command detected, skipping AI response');
return; // Skip AI response, map handled it
}
console.log('No map command detected, proceeding with AI response');
try {
// Add user message to chat
addMessageToChat(userInput, 'user');
// Show loading indicator immediately
const messagesContainer = document.getElementById('messages');
const loadingDiv = document.createElement('div');
loadingDiv.id = 'loadingIndicator';
loadingDiv.className = 'loading-indicator';
messagesContainer.appendChild(loadingDiv);
// Start Perlin animation
startPerlinLoading(loadingDiv);
// Fade in after a small delay
setTimeout(() => {
loadingDiv.classList.add('visible');
}, 10);
// Get AI response with streaming (already adds to chat)
text = await getAIResponse(userInput);
} catch (error) {
console.error('AI Error:', error.message);
return;
}
} else {
// Manual Mode - use selected text category
const selectedText = document.getElementById('textSelect').value;
text = textCategories[selectedText];
try {
// For manual mode, process with audio.js streaming
const sentences = text
.split(/(?<=[.!?])\s+(?=\[)/) // Split after punctuation, before tags
.map(s => s.trim())
.filter(s => s.length > 0);
if (sentences.length > 0) {
// Use audio.js streaming playback (keeps tags for ElevenLabs)
await AudioModule.streamingAudioPlayback(sentences, voiceId, selectedAgent);
}
} catch (error) {
console.error('Error:', error.message);
}
}
}
// Toggle AI mode functionality
function toggleAIMode() {
const aiToggle = document.getElementById('aiToggle');
const textSelect = document.getElementById('textSelect');
const playBtn = document.getElementById('playBtn');
const inputArea = document.querySelector('.input-area');
const responseTypeLabel = document.querySelector('label[for="textSelect"]');
if (aiToggle.classList.contains('active')) {
// Turn OFF AI mode
aiToggle.classList.remove('active');
aiToggle.textContent = 'AI MODE';
textSelect.disabled = false;
textSelect.style.display = 'block';
textSelect.innerHTML = `
<option value="greetings" selected>Greetings</option>
<option value="goodbyes">Goodbyes</option>
<option value="happy">Happy</option>
<option value="sad">Sad</option>
<option value="tension">Tension</option>
<option value="excited">Excited</option>
<option value="anxious">Anxious</option>
<option value="thinking">Thinking</option>
<option value="confident">Confident</option>
<option value="surprised">Surprised</option>
<option value="frustrated">Frustrated</option>
<option value="relieved">Relieved</option>
<option value="mysterious">Mysterious</option>
<option value="professional">Professional</option>
<option value="casual">Casual</option>
`;
responseTypeLabel.textContent = 'Response Type';
playBtn.textContent = '▶';
// Show the response controls container (includes play button)
document.querySelector('.response-controls').style.display = 'flex';
inputArea.style.display = 'none';
// Remove AI mode class from container
document.querySelector('.container').classList.remove('ai-mode');
// Hide lego containers
hideLegoContainers();
// Hide orb when AI mode is off
destroyOrb();
// Hide messages div when AI mode is off
document.getElementById('messages').style.display = 'none';
// Log activity
if (typeof TerminalLogContainer !== 'undefined') {
TerminalLogContainer.addLogEntry('system', 'AI mode deactivated');
TerminalLogContainer.addTerminalOutput('ai mode off', 'AI mode disabled.');
}
// Reset audio player when switching modes
if (AudioModule.currentAudio) {
AudioModule.currentAudio.pause();
AudioModule.currentAudio = null;
AudioModule.hideAudioPlayer();
}
} else {
// Turn ON AI mode
aiToggle.classList.add('active');
aiToggle.textContent = 'AI MODE ON';
textSelect.style.display = 'none';
responseTypeLabel.textContent = 'Response type is being controlled by AI';
// Hide the entire response controls container (includes play button)
document.querySelector('.response-controls').style.display = 'none';
inputArea.style.display = 'flex';
// Add AI mode class to container
document.querySelector('.container').classList.add('ai-mode');
// Show orb when AI mode is on
initOrb();
// Reset orb for smooth fade in
if (orb) {
orb.reset();
}
// Show messages div when AI mode is on
document.getElementById('messages').style.display = 'block';
// Log activity
if (typeof TerminalLogContainer !== 'undefined') {
TerminalLogContainer.addLogEntry('system', 'AI mode activated');
TerminalLogContainer.addTerminalOutput('ai mode on', 'AI mode enabled. horus ready.');
}
// Lego containers will be controlled by keyboard (1,2,3,4 keys)
// Focus the input box automatically
setTimeout(() => {
document.getElementById('messageInput').focus();
}, 100);
}
}
// Initialize when page loads
document.addEventListener('DOMContentLoaded', () => {
console.log('horus AI system loaded');
// Initialize audio player
AudioModule.initAudioPlayer();
// Initialize terminal/log immediately (before AI mode)
if (typeof TerminalLogContainer !== 'undefined') {
TerminalLogContainer.init();
TerminalLogContainer.addLogEntry('system', 'System initialized');
}
// Setup AI toggle
document.getElementById('aiToggle').addEventListener('click', toggleAIMode);
// Auto-activate AI mode on load
setTimeout(() => {
toggleAIMode();
}, 100);
// Auto-open all panels on load (like CMD+0)
setTimeout(() => {
toggleAllLegoPanels();
}, 200); // Small delay after AI mode activation
// Setup keyboard shortcuts
document.addEventListener('keydown', function(e) {
// AI toggle (Shift+L)
if (e.shiftKey && (e.key === 'L' || e.key === 'l')) {
e.preventDefault();
toggleAIMode();
}
// Lego container controls remapped clockwise starting at top
if (e.key === '1') { // top
e.preventDefault();
toggleLegoContainer('top');
}
if (e.key === '2') { // top-right
e.preventDefault();
toggleLegoContainer('top-right');
}
if (e.key === '3') { // right
e.preventDefault();
toggleLegoContainer('right');
}
if (e.key === '4') { // bottom-right
e.preventDefault();
toggleLegoContainer('bottom-right');
}
if (e.key === '5') { // bottom
e.preventDefault();
toggleLegoContainer('bottom');
}
if (e.key === '6') { // bottom-left
e.preventDefault();
toggleLegoContainer('bottom-left');
}
if (e.key === '7') { // left
e.preventDefault();
toggleLegoContainer('left');
}
if (e.key === '8') { // top-left
e.preventDefault();
toggleLegoContainer('top-left');
}
// CMD/Meta variants: allow CMD+1..8 to mirror the above mapping
if (e.metaKey && e.key === '1') { e.preventDefault(); toggleLegoContainer('top'); }
if (e.metaKey && e.key === '2') { e.preventDefault(); toggleLegoContainer('top-right'); }
if (e.metaKey && e.key === '3') { e.preventDefault(); toggleLegoContainer('right'); }
if (e.metaKey && e.key === '4') { e.preventDefault(); toggleLegoContainer('bottom-right'); }
if (e.metaKey && e.key === '5') { e.preventDefault(); toggleLegoContainer('bottom'); }
if (e.metaKey && e.key === '6') { e.preventDefault(); toggleLegoContainer('bottom-left'); }
if (e.metaKey && e.key === '7') { e.preventDefault(); toggleLegoContainer('left'); }
if (e.metaKey && e.key === '8') { e.preventDefault(); toggleLegoContainer('top-left'); }
// CMD+0: simulate pressing all 1..8 in order (toggles all panels)
if (e.metaKey && e.key === '0') {
e.preventDefault();
toggleAllLegoPanels();
}
});
// Setup Enter key for input
document.getElementById('messageInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
const aiToggle = document.getElementById('aiToggle').classList.contains('active');
if (aiToggle) {
playSelected();
// Clear input field after sending
this.value = '';
}
}
});
// Setup Send button (only for manual mode)
document.getElementById('sendBtn').addEventListener('click', function() {
const aiToggle = document.getElementById('aiToggle').classList.contains('active');
if (!aiToggle) {
playSelected();
}
});
// Don't initialize orb by default - only when AI mode is on
});
// Audio queue processing functions are now handled by audio.js module
// Perlin loading animation is now handled by orb.js module
// Lego container keyboard controls
function toggleLegoContainer(position) {
const legoContainer = document.querySelector(`.lego-container[data-position="${position}"]`);
if (legoContainer) {
const type = legoContainer.getAttribute('data-type');
if (legoContainer.classList.contains('visible')) {
legoContainer.classList.remove('visible');
console.log(`Closed ${position} lego container (${type})`);
// Hide map when closing
if (type === 'map' && typeof MapContainer !== 'undefined') {
MapContainer.hide();
// Log map closing
if (typeof TerminalLogContainer !== 'undefined') {
TerminalLogContainer.addLogEntry('horus', 'Map container closed');
TerminalLogContainer.addTerminalOutput('close map', 'Map hidden');
}
}
// Hide terminal/log when closing
if (type === 'terminal-log' && typeof TerminalLogContainer !== 'undefined') {
TerminalLogContainer.hide();
}
// Hide whiteboard when closing
if (type === 'whiteboard' && typeof WhiteboardContainer !== 'undefined') {
WhiteboardContainer.hide();
}
// Hide browser when closing
if (type === 'browser' && typeof BrowserContainer !== 'undefined') {
BrowserContainer.hide();
}
// Hide corner panels when closing
if (type === 'weather' && typeof WeatherContainer !== 'undefined') {
WeatherContainer.hide();
}
if (type === 'email' && typeof EmailContainer !== 'undefined') {
EmailContainer.hide();
}
if (type === 'media-player' && typeof MediaPlayerContainer !== 'undefined') {
MediaPlayerContainer.hide();
}
if (type === 'notes' && typeof NotesContainer !== 'undefined') {
NotesContainer.hide();
}
// Log container closing
if (typeof TerminalLogContainer !== 'undefined' && type !== 'terminal-log') {
TerminalLogContainer.addLogEntry('system', `${type} container closed`);
}
} else {
legoContainer.classList.add('visible');
console.log(`Opened ${position} lego container (${type})`);
// Show map when opening
if (type === 'map' && typeof MapContainer !== 'undefined') {
setTimeout(() => {
MapContainer.init();
}, 100); // Small delay to ensure container is visible
// Log map opening
if (typeof TerminalLogContainer !== 'undefined') {
TerminalLogContainer.addLogEntry('horus', 'Map container opened');
TerminalLogContainer.addTerminalOutput('open map', 'Map initialized');
}
}
// Show terminal/log when opening
if (type === 'terminal-log' && typeof TerminalLogContainer !== 'undefined') {
setTimeout(() => {
TerminalLogContainer.init();
}, 100); // Small delay to ensure container is visible
}
// Show whiteboard when opening
if (type === 'whiteboard' && typeof WhiteboardContainer !== 'undefined') {
setTimeout(() => {
WhiteboardContainer.init();
}, 100); // Small delay to ensure container is visible
}
// Show browser when opening
if (type === 'browser' && typeof BrowserContainer !== 'undefined') {
setTimeout(() => {
BrowserContainer.init();
}, 100); // Small delay to ensure container is visible
}
// Show corner panels when opening
if (type === 'weather' && typeof WeatherContainer !== 'undefined') {
setTimeout(() => {
WeatherContainer.init();
}, 100);
}
if (type === 'email' && typeof EmailContainer !== 'undefined') {
setTimeout(() => {
EmailContainer.init();
}, 100);
}
if (type === 'media-player' && typeof MediaPlayerContainer !== 'undefined') {
setTimeout(() => {
MediaPlayerContainer.init();
}, 100);
}
if (type === 'notes' && typeof NotesContainer !== 'undefined') {
setTimeout(() => {
NotesContainer.init();
}, 100);
}
// Log container opening
if (typeof TerminalLogContainer !== 'undefined' && type !== 'terminal-log') {
TerminalLogContainer.addLogEntry('system', `${type} container opened`);
}
}
}
}
// Toggle all lego panels in clockwise order starting from top
function toggleAllLegoPanels() {
const positionsInOrder = [
'top', 'top-right', 'right', 'bottom-right',
'bottom', 'bottom-left', 'left', 'top-left'
];
const delayMs = 50;
positionsInOrder.forEach((pos, index) => {
setTimeout(() => toggleLegoContainer(pos), index * delayMs);
});
}
function hideLegoContainers() {
const legoContainers = document.querySelectorAll('.lego-container');
console.log('Hiding all lego containers:', legoContainers);
legoContainers.forEach(container => {
container.classList.remove('visible');
console.log('Removed visible class from lego container');
});
}