-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
351 lines (289 loc) · 12.6 KB
/
script.js
File metadata and controls
351 lines (289 loc) · 12.6 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
// MetaIntent Modern Interface
const API_ENDPOINT = 'https://0exoqpsrxa.execute-api.us-east-1.amazonaws.com/metaintent';
let sessionId = null;
let messageCount = 0;
function startDemo() {
document.getElementById('heroSection').classList.add('hidden');
document.getElementById('chatSection').classList.remove('hidden');
document.getElementById('chatInput').focus();
}
function closeChat() {
document.getElementById('chatSection').classList.add('hidden');
document.getElementById('heroSection').classList.remove('hidden');
}
async function sendMessage() {
const input = document.getElementById('chatInput').value.trim();
if (!input) return;
const sendBtn = document.getElementById('sendBtn');
if (sendBtn.disabled) return; // Prevent double-sending
sendBtn.disabled = true;
addMessage('user', input);
document.getElementById('chatInput').value = '';
messageCount++;
try {
const action = sessionId ? 'clarify' : 'start';
console.log('Sending:', { action, sessionId, input });
console.log('API Endpoint:', API_ENDPOINT);
const response = await fetch(API_ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({ action, sessionId, input }),
mode: 'cors'
});
console.log('Response status:', response.status);
console.log('Response headers:', response.headers);
let data;
try {
data = await response.json();
} catch (e) {
const errorText = await response.text();
console.error('Error parsing JSON:', e);
console.error('Raw response:', errorText);
throw new Error(`Invalid JSON response from server: ${errorText.substring(0, 100)}`);
}
if (!response.ok) {
console.error('Error response:', data);
throw new Error(data.message || data.error || `HTTP error! status: ${response.status}`);
}
console.log('Response data:', data);
// Handle session ID
if (!sessionId && data.sessionId) {
sessionId = data.sessionId;
console.log('Session ID:', sessionId);
}
// Check for errors
if (data.error) {
addMessage('ai', `Error: ${data.error}<br><br>Let's start fresh. What would you like to do?`);
sessionId = null; // Reset session
return;
}
// Update UI
updateStats(data);
// Add response
if (data.response) {
addMessage('ai', data.response);
}
// Show generate button when ready
if (data.status === 'ready' && !data.needsClarification) {
showGenerateButton();
}
// Check if Bedrock fallback was used (inform user if so)
if (data.response && data.response.includes('Fallback analysis')) {
console.log('LLM service unavailable, using local heuristics.');
}
} catch (error) {
console.error('Error details:', error);
console.error('Error type:', error.name);
console.error('Error message:', error.message);
let errorMsg = 'Connection error. ';
if (error.message.includes('Failed to fetch') || error.name === 'TypeError') {
errorMsg += 'This might be a network or CORS issue.<br><br>';
errorMsg += '✓ API is working (tested successfully)<br>';
errorMsg += '✓ Try opening DevTools (F12) → Console tab for details<br>';
errorMsg += '✓ Check if any browser extensions are blocking requests<br><br>';
errorMsg += `Error: ${error.message}`;
} else {
errorMsg += `<br>Error: ${error.message}`;
}
addMessage('ai', errorMsg);
sessionId = null; // Reset on error
} finally {
sendBtn.disabled = false;
}
}
function addMessage(role, content) {
const messagesDiv = document.getElementById('chatMessages');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${role}`;
// Format content properly
const formattedContent = content
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/\n/g, '<br>')
.replace(/•/g, '<br>•');
messageDiv.innerHTML = `
<div class="message-avatar">
<img src="metaintent_logo.png" alt="${role}">
</div>
<div class="message-content">
<div class="message-text">${formattedContent}</div>
</div>
`;
messagesDiv.appendChild(messageDiv);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
function updateStats(data) {
console.log('Updating stats with data:', data);
const clarity = Math.max(0, 100 - (data.ambiguityScore || 100));
document.getElementById('clarityValue').textContent = `${clarity}%`;
// Count total agents - handle both array and object
let agentCount = 0;
if (data.activeAgents) {
if (Array.isArray(data.activeAgents)) {
agentCount = data.activeAgents.length;
console.log('Agent count (array):', agentCount, 'Agents:', data.activeAgents);
} else if (typeof data.activeAgents === 'object') {
agentCount = Object.keys(data.activeAgents).length;
console.log('Agent count (object):', agentCount, 'Agents:', data.activeAgents);
}
}
// If status is ready/clarifying, show at least 1 agent was used
if (agentCount === 0 && (data.status === 'ready' || data.status === 'clarifying')) {
agentCount = 1;
}
// Safety check for iteration
let iteration = data.iteration !== undefined ? data.iteration : 0;
if (iteration === 0 && data.response) iteration = 1;
document.getElementById('agentsValue').textContent = agentCount;
document.getElementById('iterationValue').textContent = iteration;
console.log('Stats updated - Clarity:', clarity, 'Agents:', agentCount, 'Iteration:', iteration);
}
let isGenerating = false;
async function generateAgent() {
if (isGenerating) return; // Prevent multiple generations
isGenerating = true;
addMessage('ai', '🎨 Creating your custom agent...');
try {
const response = await fetch(API_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'generate', sessionId })
});
let data;
try {
data = await response.json();
} catch (e) {
const errorText = await response.text();
console.error('Error parsing JSON:', e);
throw new Error(`Invalid response from server`);
}
if (!response.ok) {
throw new Error(data.message || data.error || `HTTP error! status: ${response.status}`);
}
if (data.agentSpec) {
const spec = data.agentSpec;
let message = `<strong>✨ Your Custom Agent is Ready!</strong><br><br>`;
message += `<strong>Name:</strong> ${spec.name}<br>`;
message += `<strong>Purpose:</strong> ${spec.purpose}<br><br>`;
message += `<strong>Capabilities:</strong><br>`;
spec.capabilities.forEach(cap => {
message += `• ${cap}<br>`;
});
message += `<br><strong>Success Criteria:</strong><br>`;
spec.successCriteria.forEach(crit => {
message += `✓ ${crit}<br>`;
});
addMessage('ai', message);
} else {
addMessage('ai', data.formattedDisplay || 'Agent created!');
}
// Reset for new session
addMessage('ai', '<br>Want to create another agent? Just tell me what you need!');
sessionId = null;
} catch (error) {
console.error('Generation error:', error);
addMessage('ai', 'Had trouble generating the agent. Want to try again?');
} finally {
isGenerating = false;
}
}
function showGenerateButton() {
const messagesDiv = document.getElementById('chatMessages');
const buttonDiv = document.createElement('div');
buttonDiv.className = 'generate-button-container';
buttonDiv.innerHTML = `
<button class="btn-generate" onclick="generateAgent()">
✨ Generate My Agent Now
</button>
`;
messagesDiv.appendChild(buttonDiv);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
document.getElementById('chatInput')?.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
});
// Voice Input Functionality
let mediaRecorder = null;
let audioChunks = [];
async function toggleVoiceInput() {
const voiceBtn = document.getElementById('voiceBtn');
const voiceRecording = document.getElementById('voiceRecording');
if (mediaRecorder && mediaRecorder.state === 'recording') {
stopVoiceInput();
return;
}
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
audioChunks = [];
mediaRecorder.ondataavailable = (event) => {
audioChunks.push(event.data);
};
mediaRecorder.onstop = async () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
await processVoiceInput(audioBlob);
// Stop all tracks
stream.getTracks().forEach(track => track.stop());
};
mediaRecorder.start();
voiceBtn.classList.add('recording');
voiceRecording.classList.remove('hidden');
} catch (error) {
console.error('Error accessing microphone:', error);
addMessage('ai', '⚠️ Could not access microphone. Please check your browser permissions.');
}
}
function stopVoiceInput() {
if (mediaRecorder && mediaRecorder.state === 'recording') {
mediaRecorder.stop();
document.getElementById('voiceBtn').classList.remove('recording');
document.getElementById('voiceRecording').classList.add('hidden');
}
}
async function processVoiceInput(audioBlob) {
addMessage('ai', '🎤 Processing your voice input...');
try {
// For demo purposes, show a message that voice processing would happen here
// In production, you would send the audio to a speech-to-text service
addMessage('ai', '✨ Voice input feature is ready! In production, this would use AWS Transcribe or similar service to convert your speech to text and process it.');
// TODO: Implement actual speech-to-text API call
// Example: Send audioBlob to AWS Transcribe, Google Speech-to-Text, etc.
} catch (error) {
console.error('Error processing voice:', error);
addMessage('ai', '⚠️ Error processing voice input. Please try typing instead.');
}
}
// File Upload Functionality
let uploadedFile = null;
function handleFileUpload(event) {
const file = event.target.files[0];
if (!file) return;
uploadedFile = file;
// Show file preview
const filePreview = document.getElementById('filePreview');
const fileName = document.getElementById('fileName');
fileName.textContent = `📎 ${file.name} (${formatFileSize(file.size)})`;
filePreview.classList.remove('hidden');
// Add message about file
addMessage('user', `📎 Uploaded: ${file.name}`);
addMessage('ai', '✨ File received! I can process text files, PDFs, and images. In production, this would extract and analyze the content. What would you like me to do with this file?');
// TODO: Implement actual file processing
// For images: Use OCR (AWS Textract, Google Vision API)
// For PDFs/Docs: Extract text content
// For text files: Read directly
}
function removeFile() {
uploadedFile = null;
document.getElementById('filePreview').classList.add('hidden');
document.getElementById('fileInput').value = '';
}
function formatFileSize(bytes) {
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}