-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.html
More file actions
790 lines (684 loc) · 37.9 KB
/
agent.html
File metadata and controls
790 lines (684 loc) · 37.9 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
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prompt Engineering Architect | Iterative Engineering</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
colors: {
background: '#0f0f23',
surface: '#1e1e2e',
primary: '#89b4fa',
secondary: '#f9e2af',
text: '#cdd6f4',
muted: '#6c7086',
success: '#a6e3a1',
danger: '#f38ba8'
},
fontFamily: {
sans: ['Inter', 'sans-serif'],
mono: ['JetBrains Mono', 'monospace'],
}
}
}
}
</script>
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<!-- Prism.js for Syntax Highlighting -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-jinja2.min.js"></script>
<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body { font-family: 'Inter', sans-serif; background-color: var(--tw-color-background); }
.mono { font-family: 'JetBrains Mono', monospace; }
/* Custom Scrollbar */
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background: #1e1e2e; }
::-webkit-scrollbar-thumb { background: #45475a; border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: #585b70; }
/* Editor Styles */
.editor-container { position: relative; min-height: 200px; }
.editor-textarea {
background: transparent;
color: transparent;
caret-color: #cdd6f4;
z-index: 1;
}
.editor-highlight {
z-index: 0;
pointer-events: none;
}
.editor-layer {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
padding: 1rem;
font-family: 'JetBrains Mono', monospace;
font-size: 0.875rem;
line-height: 1.5;
white-space: pre-wrap;
word-wrap: break-word;
overflow: hidden;
}
/* Animations */
.fade-in { animation: fadeIn 0.3s ease-in-out; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }
/* Spinner */
.loader {
border: 3px solid #1e1e2e;
border-top: 3px solid #89b4fa;
border-radius: 50%;
width: 20px;
height: 20px;
animation: spin 1s linear infinite;
}
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
/* Archie Chat Widget */
#archie-chat {
position: fixed;
bottom: 20px;
right: 20px;
width: 350px;
height: 500px;
background: #1e1e2e;
border: 1px solid #45475a;
border-radius: 12px;
display: flex;
flex-col: column;
z-index: 50;
box-shadow: 0 10px 25px rgba(0,0,0,0.5);
overflow: hidden;
display: none;
}
#archie-chat.active { display: flex; flex-direction: column; }
#archie-toggle {
position: fixed;
bottom: 20px;
right: 20px;
width: 56px;
height: 56px;
background: #89b4fa;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
z-index: 51;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
transition: transform 0.2s;
}
#archie-toggle:hover { transform: scale(1.05); }
.message { margin-bottom: 12px; padding: 8px 12px; border-radius: 8px; font-size: 0.875rem; max-width: 85%; }
.message.user { background: #45475a; align-self: flex-end; color: #cdd6f4; }
.message.archie { background: #313244; align-self: flex-start; color: #89b4fa; border: 1px solid #45475a; }
</style>
</head>
<body class="bg-background text-text h-screen flex flex-col overflow-hidden transition-colors duration-300">
<!-- Top Toolbar -->
<header class="h-14 bg-surface border-b border-gray-800 flex items-center justify-between px-4 z-20 shrink-0">
<div class="flex items-center gap-3">
<div class="w-8 h-8 rounded bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center text-white font-bold">P</div>
<h1 class="font-bold text-lg tracking-tight hidden md:block">Prompt Architect</h1>
<span class="px-2 py-0.5 rounded text-xs bg-gray-800 text-muted border border-gray-700">v1.2.0</span>
</div>
<div class="flex items-center gap-3">
<button id="commitBtn" onclick="commitVersion()" class="flex items-center gap-2 px-3 py-1.5 bg-green-600/20 text-green-400 hover:bg-green-600/30 border border-green-600/30 rounded text-sm transition-colors" title="Ctrl+S">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path><polyline points="17 21 17 13 7 13 7 21"></polyline><polyline points="7 3 7 8 15 8"></polyline></svg>
Commit
</button>
<button onclick="toggleTheme()" class="p-2 hover:bg-gray-700/50 rounded-full transition-colors text-muted hover:text-text">
<svg id="themeIcon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>
</button>
</div>
</header>
<!-- Main Workspace -->
<div class="flex-1 flex overflow-hidden">
<!-- Sidebar Navigation -->
<nav class="w-16 md:w-64 bg-surface border-r border-gray-800 flex flex-col shrink-0 transition-all duration-300">
<div class="flex flex-col gap-1 p-2">
<button onclick="switchTab('system')" id="tab-system" class="nav-btn active flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-gray-700/30 text-left transition-colors text-primary bg-gray-700/20">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2a10 10 0 1 0 10 10H12V2z"></path><path d="M12 2a10 10 0 0 1 10 10"></path><path d="M12 22c5.523 0 10-4.477 10-10"></path></svg>
<span class="hidden md:block text-sm font-medium">System Prompt</span>
</button>
<button onclick="switchTab('user')" id="tab-user" class="nav-btn flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-gray-700/30 text-left transition-colors text-muted">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
<span class="hidden md:block text-sm font-medium">User Prompt</span>
</button>
<button onclick="switchTab('template')" id="tab-template" class="nav-btn flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-gray-700/30 text-left transition-colors text-muted">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line><line x1="10" y1="9" x2="8" y2="9"></line></svg>
<span class="hidden md:block text-sm font-medium">Template (Jinja2)</span>
</button>
<div class="h-px bg-gray-800 my-1 mx-2"></div>
<button onclick="switchTab('facts')" id="tab-facts" class="nav-btn flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-gray-700/30 text-left transition-colors text-muted">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
<span class="hidden md:block text-sm font-medium">Fact Store</span>
</button>
<button onclick="switchTab('versions')" id="tab-versions" class="nav-btn flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-gray-700/30 text-left transition-colors text-muted">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="1 4 1 10 7 10"></polyline><polyline points="23 20 23 14 17 14"></polyline><path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"></path></svg>
<span class="hidden md:block text-sm font-medium">History</span>
</button>
</div>
<div class="mt-auto p-4 border-t border-gray-800 hidden md:block">
<div class="text-xs text-muted mb-2">Shortcuts</div>
<div class="flex justify-between text-xs text-gray-500 mb-1"><span>Commit</span> <span class="bg-gray-800 px-1 rounded">Ctrl+S</span></div>
<div class="flex justify-between text-xs text-gray-500"><span>Run</span> <span class="bg-gray-800 px-1 rounded">Ctrl+R</span></div>
</div>
</nav>
<!-- Main Editor & Preview Area (Center) -->
<main class="flex-1 flex flex-col min-w-0 bg-background relative">
<!-- Editor Pane -->
<div class="flex-1 flex flex-col border-b border-gray-800 min-h-[40%]">
<div class="flex items-center justify-between px-4 py-2 bg-surface/50 border-b border-gray-800">
<h2 id="editor-title" class="text-sm font-semibold text-text">System Prompt</h2>
<span class="text-xs text-muted" id="autosave-status">Autosaved</span>
</div>
<div class="flex-1 relative editor-container bg-background">
<!-- Standard Textarea for Input -->
<textarea id="main-editor" class="editor-layer editor-textarea w-full h-full resize-none focus:outline-none" spellcheck="false"></textarea>
<!-- Syntax Highlight Layer -->
<pre id="editor-highlight" class="editor-layer editor-highlight"><code id="highlight-code" class="language-jinja2"></code></pre>
<!-- Fact Store View (Hidden by default) -->
<div id="facts-view" class="absolute inset-0 bg-background z-10 hidden flex flex-col p-4 overflow-y-auto">
<div class="flex gap-2 mb-4">
<input id="fact-search-input" type="text" placeholder="Search Google to update context..." class="flex-1 bg-surface border border-gray-700 rounded px-3 py-2 text-sm focus:border-primary focus:outline-none">
<button onclick="searchFacts()" class="bg-primary/20 text-primary border border-primary/30 px-4 py-2 rounded text-sm hover:bg-primary/30 transition-colors flex items-center gap-2">
<span id="search-spinner" class="loader hidden w-3 h-3"></span> Search
</button>
</div>
<div id="facts-list" class="space-y-2">
<!-- Facts injected here -->
</div>
</div>
<!-- Versions View (Hidden by default) -->
<div id="versions-view" class="absolute inset-0 bg-background z-10 hidden flex flex-col p-4 overflow-y-auto">
<h3 class="text-sm font-semibold mb-3 text-muted">Commit History</h3>
<div id="versions-list" class="space-y-3">
<!-- Versions injected here -->
</div>
</div>
</div>
</div>
<!-- Preview / Assembly Pane -->
<div class="h-[35%] flex flex-col bg-surface/20">
<div class="px-4 py-2 border-y border-gray-800 bg-surface/50 flex justify-between items-center">
<span class="text-xs font-mono uppercase tracking-wider text-muted">Assembled Prompt Preview</span>
<span class="text-xs text-yellow-500/80 hidden" id="preview-warning">Template Error</span>
</div>
<div class="flex-1 p-4 overflow-y-auto font-mono text-sm text-gray-400 whitespace-pre-wrap" id="assembled-preview">
<!-- Live assembly goes here -->
</div>
</div>
</main>
<!-- Output & Metrics Panel (Right) -->
<aside class="w-80 md:w-96 bg-surface border-l border-gray-800 flex flex-col shrink-0 z-10">
<div class="px-4 py-3 border-b border-gray-800 flex justify-between items-center bg-surface">
<h3 class="font-semibold text-sm">Output</h3>
<button onclick="runGeneration()" id="run-btn" class="bg-primary text-background font-bold text-xs px-3 py-1.5 rounded hover:opacity-90 transition-opacity flex items-center gap-2" title="Ctrl+R">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg>
Run
</button>
</div>
<div class="flex-1 overflow-y-auto p-4 relative">
<div id="output-loader" class="hidden absolute inset-0 bg-surface/80 flex flex-col items-center justify-center z-20 backdrop-blur-sm">
<div class="loader mb-2"></div>
<span class="text-xs text-primary animate-pulse">Generating...</span>
</div>
<div id="llm-output" class="prose prose-invert prose-sm max-w-none text-gray-300">
<p class="text-muted italic text-center mt-10">Ready to generate.<br>Configure prompt components and click Run.</p>
</div>
</div>
<div class="h-48 border-t border-gray-800 bg-surface/50 p-4 flex flex-col">
<h4 class="text-xs font-mono uppercase text-muted mb-2">Metrics</h4>
<div class="flex-1 relative">
<canvas id="metricsChart"></canvas>
</div>
<div class="flex justify-between text-xs mt-2 text-gray-500 font-mono">
<span id="metric-tokens">Tokens: 0</span>
<span id="metric-latency">Latency: 0ms</span>
</div>
</div>
</aside>
</div>
<!-- Archie Chat Widget UI -->
<div id="archie-toggle" onclick="toggleArchieChat()">
<span class="text-2xl">🧙♂️</span>
</div>
<div id="archie-chat">
<div class="p-3 border-b border-gray-800 bg-surface/80 flex justify-between items-center">
<div class="flex items-center gap-2">
<span class="text-lg">🧙♂️</span>
<span class="font-bold text-sm">Archie</span>
</div>
<button onclick="toggleArchieChat()" class="text-muted hover:text-text">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
</div>
<div id="archie-messages" class="flex-1 overflow-y-auto p-4 flex flex-col gap-2 bg-background/50">
<div class="message archie">Hello! I'm Archie. How can I help you today?</div>
</div>
<div class="p-3 border-t border-gray-800 bg-surface/80">
<div class="flex gap-2">
<input id="archie-input" type="text" placeholder="Type a message..." class="flex-1 bg-background border border-gray-700 rounded px-3 py-2 text-sm focus:outline-none focus:border-primary" onkeydown="if(event.key==='Enter') sendToArchie()">
<button onclick="sendToArchie()" class="bg-primary text-background p-2 rounded hover:opacity-90 transition-opacity">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
</button>
</div>
</div>
</div>
<!-- Scripts -->
<script>
// --- Configuration & State ---
const DEFAULT_STATE = {
systemPrompt: "You are a helpful AI assistant specialized in creative writing.",
userPrompt: "Write a haiku about a futuristic city.",
template:
`System: {{ system_prompt }}
Context Facts:
{{ context }}
User: {{ user_prompt }}
Response:`,
facts: [
{ id: 1, text: "Gemini is a multimodal AI model from Google." },
{ id: 2, text: "Prompt Engineering requires iterative refinement." }
],
versions: [],
theme: 'dark'
};
let state = JSON.parse(localStorage.getItem('promptArchitectState')) || DEFAULT_STATE;
let currentTab = 'system';
let isGenerating = false;
let chartInstance = null;
let autoSaveTimer = null;
// --- DOM Elements ---
const els = {
editor: document.getElementById('main-editor'),
highlight: document.getElementById('highlight-code'),
preview: document.getElementById('assembled-preview'),
output: document.getElementById('llm-output'),
title: document.getElementById('editor-title'),
factSearch: document.getElementById('fact-search-input'),
factsList: document.getElementById('facts-list'),
versionsList: document.getElementById('versions-list'),
metricTokens: document.getElementById('metric-tokens'),
metricLatency: document.getElementById('metric-latency'),
loader: document.getElementById('output-loader'),
searchSpinner: document.getElementById('search-spinner'),
tabs: {
system: document.getElementById('tab-system'),
user: document.getElementById('tab-user'),
template: document.getElementById('tab-template'),
facts: document.getElementById('tab-facts'),
versions: document.getElementById('tab-versions')
},
views: {
facts: document.getElementById('facts-view'),
versions: document.getElementById('versions-view')
}
};
// --- Initialization ---
function init() {
// Apply theme
if (state.theme === 'light') document.documentElement.classList.remove('dark');
// Setup Chart
const ctx = document.getElementById('metricsChart').getContext('2d');
chartInstance = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Context Sim', 'Coherence', 'Creativity'],
datasets: [{
label: 'Score',
data: [0, 0, 0],
backgroundColor: '#89b4fa',
borderRadius: 4
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: { legend: { display: false } },
scales: {
y: { beginAtZero: true, max: 100, grid: { color: '#313244' } },
x: { grid: { display: false } }
}
}
});
// Event Listeners
els.editor.addEventListener('input', handleEditorInput);
els.editor.addEventListener('scroll', syncScroll);
document.addEventListener('keydown', handleShortcuts);
// Initial Render
switchTab('system');
updatePreview();
renderFacts();
renderVersions();
}
// --- Core Logic ---
function handleEditorInput(e) {
const val = e.target.value;
// Update State based on active tab
if (currentTab === 'system') state.systemPrompt = val;
else if (currentTab === 'user') state.userPrompt = val;
else if (currentTab === 'template') state.template = val;
// Trigger updates
updateHighlighting(val);
updatePreview();
debouncedSave();
}
function switchTab(tab) {
currentTab = tab;
// Update UI Styling
Object.values(els.tabs).forEach(el => {
el.classList.remove('text-primary', 'bg-gray-700/20');
el.classList.add('text-muted');
});
els.tabs[tab].classList.remove('text-muted');
els.tabs[tab].classList.add('text-primary', 'bg-gray-700/20');
// Hide/Show Views
els.views.facts.classList.add('hidden');
els.views.versions.classList.add('hidden');
els.editor.classList.remove('hidden');
document.getElementById('editor-highlight').parentElement.classList.remove('hidden');
// Set Content
if (tab === 'system') {
els.title.textContent = 'System Prompt';
els.editor.value = state.systemPrompt;
els.highlight.className = 'language-markdown';
} else if (tab === 'user') {
els.title.textContent = 'User Prompt';
els.editor.value = state.userPrompt;
els.highlight.className = 'language-markdown';
} else if (tab === 'template') {
els.title.textContent = 'Prompt Template (Jinja2)';
els.editor.value = state.template;
els.highlight.className = 'language-jinja2';
} else if (tab === 'facts') {
els.title.textContent = 'Fact Store (Context)';
els.editor.classList.add('hidden');
document.getElementById('editor-highlight').parentElement.classList.add('hidden');
els.views.facts.classList.remove('hidden');
} else if (tab === 'versions') {
els.title.textContent = 'Version History';
els.editor.classList.add('hidden');
document.getElementById('editor-highlight').parentElement.classList.add('hidden');
els.views.versions.classList.remove('hidden');
renderVersions();
}
if (tab !== 'facts' && tab !== 'versions') {
updateHighlighting(els.editor.value);
}
}
function updateHighlighting(text) {
// Escape HTML to prevent injection in preview
const escaped = text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
// Highlight standard jinja braces if in template mode
if (currentTab === 'template') {
// Simple regex for custom highlighting if prism fails or for specific keywords
}
els.highlight.innerHTML = escaped; // Let Prism handle it
if(window.Prism) Prism.highlightElement(els.highlight);
}
function syncScroll() {
document.getElementById('editor-highlight').scrollTop = els.editor.scrollTop;
document.getElementById('editor-highlight').scrollLeft = els.editor.scrollLeft;
}
function assemblePrompt() {
let compiled = state.template;
// 1. Inject System Prompt
compiled = compiled.replace(/{{\s*system_prompt\s*}}/g, state.systemPrompt);
// 2. Inject User Prompt
compiled = compiled.replace(/{{\s*user_prompt\s*}}/g, state.userPrompt);
// 3. Inject Context
const contextString = state.facts.map(f => `- ${f.text}`).join('\n');
compiled = compiled.replace(/{{\s*context\s*}}/g, contextString);
// 4. Handle arbitrary variables (mock)
// compiled = compiled.replace(/{{\s*(\w+)\s*}}/g, "[Missing Variable: $1]");
return compiled;
}
function updatePreview() {
const fullPrompt = assemblePrompt();
els.preview.textContent = fullPrompt;
}
// --- Data Persistence ---
function debouncedSave() {
document.getElementById('autosave-status').textContent = 'Saving...';
clearTimeout(autoSaveTimer);
autoSaveTimer = setTimeout(() => {
localStorage.setItem('promptArchitectState', JSON.stringify(state));
document.getElementById('autosave-status').textContent = 'Autosaved';
}, 1000);
}
function commitVersion() {
const note = prompt("Commit message:", "Update prompt structure");
if (!note) return;
const version = {
id: Date.now(),
timestamp: new Date().toLocaleString(),
note: note,
snapshot: JSON.parse(JSON.stringify(state)) // Deep copy
};
state.versions.unshift(version);
localStorage.setItem('promptArchitectState', JSON.stringify(state));
// Visual feedback
const btn = document.getElementById('commitBtn');
const originalText = btn.innerHTML;
btn.innerHTML = `<span class="text-green-400">Saved!</span>`;
setTimeout(() => btn.innerHTML = originalText, 1500);
renderVersions();
}
function restoreVersion(id) {
if(!confirm("Restore this version? Current unsaved changes will be lost.")) return;
const v = state.versions.find(ver => ver.id === id);
if(v) {
// Keep versions history, overwrite content
const history = state.versions;
state = JSON.parse(JSON.stringify(v.snapshot));
state.versions = history;
// Refresh UI
switchTab(currentTab);
updatePreview();
renderFacts();
alert("Version restored.");
}
}
// --- API Integration (Gemini) ---
async function callGemini(payload) {
const apiKey = ""; // The execution environment provides the key at runtime.
const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-09-2025:generateContent?key=${apiKey}`;
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!response.ok) {
const err = await response.json();
throw new Error(err.error?.message || "API Request Failed");
}
return await response.json();
}
async function runGeneration() {
if (isGenerating) return;
const promptText = assemblePrompt();
// UI State
isGenerating = true;
els.loader.classList.remove('hidden');
document.getElementById('run-btn').classList.add('opacity-50', 'cursor-not-allowed');
const startTime = Date.now();
try {
const data = await callGemini({
contents: [{ parts: [{ text: promptText }] }]
});
const generatedText = data.candidates?.[0]?.content?.parts?.[0]?.text || "No response generated.";
// Render Markdown-ish
els.output.innerHTML = `<div class="whitespace-pre-wrap">${generatedText}</div>`;
// Update Metrics (Mock logic for demo)
const latency = Date.now() - startTime;
const tokens = Math.ceil(generatedText.length / 4);
els.metricLatency.textContent = `Latency: ${latency}ms`;
els.metricTokens.textContent = `Tokens: ~${tokens}`;
// Update Chart with randomized "Scores" to simulate evaluation
chartInstance.data.datasets[0].data = [
Math.floor(Math.random() * 20 + 80), // 80-100
Math.floor(Math.random() * 30 + 70), // 70-100
Math.floor(Math.random() * 40 + 60) // 60-100
];
chartInstance.update();
} catch (e) {
els.output.innerHTML = `<div class="text-danger p-4 border border-danger/20 bg-danger/10 rounded">Error: ${e.message}</div>`;
} finally {
isGenerating = false;
els.loader.classList.add('hidden');
document.getElementById('run-btn').classList.remove('opacity-50', 'cursor-not-allowed');
}
}
async function searchFacts() {
const query = els.factSearch.value.trim();
if (!query) return;
els.searchSpinner.classList.remove('hidden');
try {
// Use Gemini with Grounding to find facts
const payload = {
contents: [{ parts: [{ text: `Find 3 concise, interesting facts about: ${query}. Return ONLY a JSON array of strings.` }] }],
tools: [{ google_search: {} }]
};
const data = await callGemini(payload);
// Attempt to parse JSON from the response text
let text = data.candidates?.[0]?.content?.parts?.[0]?.text || "[]";
// Cleanup markdown code blocks if present
text = text.replace(/```json/g, '').replace(/```/g, '');
let newFacts = [];
try {
newFacts = JSON.parse(text);
if(!Array.isArray(newFacts)) throw new Error("Not array");
} catch {
// Fallback if parsing fails: Split by newlines
newFacts = text.split('\n').filter(line => line.length > 5).map(line => line.replace(/^- /, ''));
}
// Add to state
newFacts.forEach(factText => {
state.facts.push({ id: Date.now() + Math.random(), text: factText });
});
renderFacts();
updatePreview(); // Re-assemble prompt with new context
debouncedSave();
els.factSearch.value = '';
} catch (e) {
alert("Search failed: " + e.message);
} finally {
els.searchSpinner.classList.add('hidden');
}
}
// --- Render Helpers ---
function renderFacts() {
els.factsList.innerHTML = state.facts.map(f => `
<div class="bg-surface border border-gray-700 p-3 rounded flex justify-between items-start group hover:border-primary/50 transition-colors">
<p class="text-sm text-gray-300 pr-2">${f.text}</p>
<button onclick="deleteFact(${f.id})" class="text-gray-600 hover:text-danger opacity-0 group-hover:opacity-100 transition-opacity">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
</div>
`).join('');
}
function deleteFact(id) {
state.facts = state.facts.filter(f => f.id !== id);
renderFacts();
updatePreview();
debouncedSave();
}
function renderVersions() {
if (state.versions.length === 0) {
els.versionsList.innerHTML = `<div class="text-center text-muted text-sm mt-10">No commits yet. Make changes and hit Commit.</div>`;
return;
}
els.versionsList.innerHTML = state.versions.map(v => `
<div class="bg-surface border border-gray-700 p-3 rounded hover:border-gray-500 transition-colors">
<div class="flex justify-between items-start mb-1">
<span class="font-bold text-sm text-text">${v.note}</span>
<span class="text-xs text-muted">${v.timestamp}</span>
</div>
<div class="flex justify-end mt-2">
<button onclick="restoreVersion(${v.id})" class="text-xs bg-gray-800 hover:bg-primary hover:text-background text-primary border border-gray-700 px-2 py-1 rounded transition-colors">Restore</button>
</div>
</div>
`).join('');
}
function toggleTheme() {
state.theme = state.theme === 'dark' ? 'light' : 'dark';
if (state.theme === 'dark') {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
debouncedSave();
}
function handleShortcuts(e) {
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
e.preventDefault();
commitVersion();
}
if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
e.preventDefault();
runGeneration();
}
}
// Start
window.onload = init;
// Expose functions globally
window.switchTab = switchTab;
window.commitVersion = commitVersion;
window.toggleTheme = toggleTheme;
window.runGeneration = runGeneration;
window.searchFacts = searchFacts;
window.deleteFact = deleteFact;
window.restoreVersion = restoreVersion;
// --- Archie Chat Widget Logic ---
function toggleArchieChat() {
const chat = document.getElementById('archie-chat');
chat.classList.toggle('active');
}
async function sendToArchie() {
const input = document.getElementById('archie-input');
const container = document.getElementById('archie-messages');
const message = input.value.trim();
if (!message) return;
// 1. Add User Message to UI
const userMsg = document.createElement('div');
userMsg.className = 'message user fade-in';
userMsg.textContent = message;
container.appendChild(userMsg);
input.value = '';
container.scrollTop = container.scrollHeight;
try {
// 2. Send to our new /clawd-bridge endpoint
const response = await fetch('/clawd-bridge', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: message })
});
if (!response.ok) throw new Error('Bridge unreachable');
const data = await response.json();
// 3. Add Archie's Ack to UI
const archieMsg = document.createElement('div');
archieMsg.className = 'message archie fade-in';
// The bridge returns { status: 'success', result: { ok: true, result: ... } }
// For now, we show an ack since actual injection results are async
archieMsg.textContent = "Archie: Got it! Check your WhatsApp/Session for my full reply.";
container.appendChild(archieMsg);
container.scrollTop = container.scrollHeight;
} catch (e) {
const errMsg = document.createElement('div');
errMsg.className = 'message archie text-danger';
errMsg.textContent = 'Error: ' + e.message;
container.appendChild(errMsg);
}
}
</script>
</body>
</html>