-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathspar.js
More file actions
1147 lines (926 loc) · 36.8 KB
/
Copy pathspar.js
File metadata and controls
1147 lines (926 loc) · 36.8 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
/**
* SPAR Kit - JavaScript Engine v2.0
* Four Perspectives, Four Dimensions, One Synthesis
*
* @author Naveen Riaz Mohamed Kani
* @license MIT
*/
// ============================================
// CONFIGURATION
// ============================================
const CONFIG = {
version: '2.0.0',
storageKeys: {
apiKey: 'spar-kit-api-key',
provider: 'spar-kit-provider',
sessions: 'spar-kit-sessions',
rememberKey: 'spar-kit-remember'
}
};
// ============================================
// PERSONA DEFINITIONS (N-E-W-S Compass)
// ============================================
const PERSONAS = {
north: {
name: 'The Visionary',
direction: 'North',
icon: '🔵',
color: '#3b82f6',
prompt: `You are THE VISIONARY (North).
YOUR CORE PRIORITY: Where are we going? What's the ideal future?
YOUR FEAR: Settling for mediocrity when greatness is possible.
YOUR STYLE: You focus on possibility, aspiration, and long-term direction.
When engaging with problems, you ask: "What could this become? Are we thinking big enough?"
You will analyze a decision. Argue your perspective directly.
Don't be balanced — be you. Challenge others to think beyond current constraints.
When you see small thinking, name it. When you see untapped potential, champion it.
⚠️ CRITICAL: Keep your response under 2100 tokens (approximately 250-300 words). Be direct and impactful.`
},
east: {
name: 'The Challenger',
direction: 'East',
icon: '🟢',
color: '#10b981',
prompt: `You are THE CHALLENGER (East).
YOUR CORE PRIORITY: What's emerging? What new dawn is breaking?
YOUR FEAR: Being left behind by clinging to the old way.
YOUR STYLE: You focus on disruption, innovation, and what's coming next.
When engaging with problems, you ask: "What's changing? What would a newcomer do differently?"
You will analyze a decision. Argue your perspective directly.
Don't be balanced — be you. Challenge assumptions that worked yesterday but may fail tomorrow.
When you see complacency, disrupt it. When you see fresh approaches, advocate for them.
⚠️ CRITICAL: Keep your response under 2100 tokens (approximately 250-300 words). Be direct and impactful.`
},
south: {
name: 'The Pragmatist',
direction: 'South',
icon: '🟡',
color: '#f59e0b',
prompt: `You are THE PRAGMATIST (South).
YOUR CORE PRIORITY: What's grounded? What actually works in reality?
YOUR FEAR: Beautiful ideas that collapse when they meet the real world.
YOUR STYLE: You focus on execution, feasibility, and practical constraints.
When engaging with problems, you ask: "Can we actually do this? What are the real constraints?"
You will analyze a decision. Argue your perspective directly.
Don't be balanced — be you. Ground airy visions in operational reality.
When you see wishful thinking, challenge it. When you see solid plans, support them.
⚠️ CRITICAL: Keep your response under 2100 tokens (approximately 250-300 words). Be direct and impactful.`
},
west: {
name: 'The Sage',
direction: 'West',
icon: '🔴',
color: '#ef4444',
prompt: `You are THE SAGE (West).
YOUR CORE PRIORITY: What's proven? What has history taught us?
YOUR FEAR: Repeating mistakes that wisdom could have prevented.
YOUR STYLE: You focus on experience, patterns, and lessons from the past.
When engaging with problems, you ask: "What have we learned before? What does wisdom suggest?"
You will analyze a decision. Argue your perspective directly.
Don't be balanced — be you. Bring the weight of experience to bear on shiny new ideas.
When you see historical patterns being ignored, name them. When you see genuine novelty, acknowledge it.
⚠️ CRITICAL: Keep your response under 2100 tokens (approximately 250-300 words). Be direct and impactful.`
}
};
// ============================================
// STATE MANAGEMENT
// ============================================
let sparState = {
decision: '',
provider: 'openai',
responses: {
round1: { north: '', east: '', south: '', west: '' },
round2: { north: '', east: '', south: '', west: '' }
},
synthesis: '',
errors: {},
isRunning: false,
currentStep: 'S' // Track which SPARKIT step we're on
};
// ============================================
// SPARKIT PROTOCOL STEP TRACKING
// ============================================
const SPARKIT_STEPS = ['S', 'P', 'A', 'R', 'K', 'I', 'T'];
function updateProtocolStep(stepLetter, status = 'active') {
// status: 'active', 'completed', 'pending'
const stepEl = document.querySelector(`.protocol-step[data-step="${stepLetter}"]`);
if (!stepEl) return;
// Remove all status classes
stepEl.classList.remove('active', 'completed');
if (status === 'active') {
stepEl.classList.add('active');
sparState.currentStep = stepLetter;
} else if (status === 'completed') {
stepEl.classList.add('completed');
}
}
function setProtocolProgress(currentStep) {
// Mark all steps before current as completed, current as active
const currentIndex = SPARKIT_STEPS.indexOf(currentStep);
SPARKIT_STEPS.forEach((step, index) => {
if (index < currentIndex) {
updateProtocolStep(step, 'completed');
} else if (index === currentIndex) {
updateProtocolStep(step, 'active');
} else {
updateProtocolStep(step, 'pending');
}
});
}
function resetProtocolSteps() {
SPARKIT_STEPS.forEach(step => updateProtocolStep(step, 'pending'));
updateProtocolStep('S', 'active'); // Start at Scope
}
// ============================================
// WIZARD STEP NAVIGATION
// ============================================
function toggleWizardStep(stepLetter) {
const step = document.querySelector(`#step-${stepLetter}`);
if (!step || step.classList.contains('locked')) return;
// If already active, do nothing (can't collapse current step)
if (step.classList.contains('active')) return;
// If completed, allow viewing
if (step.classList.contains('completed')) {
// Collapse other steps, expand this one temporarily
SPARKIT_STEPS.forEach(s => {
const el = document.querySelector(`#step-${s}`);
if (el && el !== step) {
el.classList.remove('viewing');
}
});
step.classList.toggle('viewing');
}
}
function advanceToStep(targetStep) {
const currentIndex = SPARKIT_STEPS.indexOf(sparState.currentStep);
const targetIndex = SPARKIT_STEPS.indexOf(targetStep);
// Validate - can only advance one step at a time
if (targetIndex > currentIndex + 1) {
showToast('Please complete the current step first', 'error');
return;
}
// Validate current step is complete
if (sparState.currentStep === 'S') {
const decision = $('decisionInput')?.value.trim();
const apiKey = $('apiKey')?.value.trim();
if (!apiKey) {
showToast('Please enter your API key', 'error');
$('apiKey')?.focus();
return;
}
if (!decision) {
showToast('Please describe your decision', 'error');
$('decisionInput')?.focus();
return;
}
// Save the decision for summary
sparState.decision = decision;
}
// Mark current step as completed
const currentStep = document.querySelector(`#step-${sparState.currentStep}`);
if (currentStep) {
currentStep.classList.remove('active');
currentStep.classList.add('completed');
currentStep.querySelector('.wizard-step-status').textContent = 'Done';
}
// Activate target step
const targetStepEl = document.querySelector(`#step-${targetStep}`);
if (targetStepEl) {
targetStepEl.classList.remove('locked');
targetStepEl.classList.add('active');
targetStepEl.querySelector('.wizard-step-status').textContent = 'Current';
// Scroll to the new step
setTimeout(() => {
targetStepEl.scrollIntoView({ behavior: 'smooth', block: 'start' });
}, 100);
}
// Update state
sparState.currentStep = targetStep;
// Update summary if advancing to Announce
if (targetStep === 'A') {
updateSummary();
}
}
function updateSummary() {
const summaryDecision = document.getElementById('summary-decision');
const summaryProvider = document.getElementById('summary-provider');
const summaryPersonas = document.getElementById('summary-personas');
if (summaryDecision) {
const decision = $('decisionInput')?.value.trim() || 'Not defined';
summaryDecision.textContent = decision.length > 100
? decision.substring(0, 100) + '...'
: decision;
}
if (summaryProvider) {
const providerSelect = $('provider');
const providerName = providerSelect?.options[providerSelect.selectedIndex]?.text || 'Unknown';
summaryProvider.textContent = providerName;
}
// Update personas summary with selected personas
if (summaryPersonas) {
const personaNames = [];
['north', 'east', 'south', 'west'].forEach(dir => {
const dropdown = document.getElementById(`persona-${dir}`);
if (dropdown) {
// Get the text of the selected option (persona name)
const selectedText = dropdown.options[dropdown.selectedIndex]?.text || '';
// Extract just the name part (after the emoji)
const name = selectedText.split('—')[0].trim().replace(/^[^\s]+\s/, '');
personaNames.push(name || 'Default');
}
});
summaryPersonas.textContent = personaNames.join(', ') || 'Not selected';
}
}
function updatePersonaPreview(direction) {
const dropdown = document.getElementById(`persona-${direction}`);
if (!dropdown) return;
const selectedValue = dropdown.value;
console.log(`${direction} persona changed to: ${selectedValue}`);
// Store the selected persona in state
if (!sparState.selectedPersonas) {
sparState.selectedPersonas = { north: 'north', east: 'east', south: 'south', west: 'west' };
}
sparState.selectedPersonas[direction] = selectedValue;
}
function getSelectedPersonas() {
return {
north: document.getElementById('persona-north')?.value || 'north',
east: document.getElementById('persona-east')?.value || 'east',
south: document.getElementById('persona-south')?.value || 'south',
west: document.getElementById('persona-west')?.value || 'west'
};
}
// ============================================
// UTILITY FUNCTIONS
// ============================================
function $(id) {
return document.getElementById(id);
}
function showToast(message, type = 'info') {
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
toast.innerHTML = `
<span class="toast-icon">${type === 'success' ? '✓' : type === 'error' ? '✗' : 'ℹ'}</span>
<span class="toast-message">${message}</span>
`;
document.body.appendChild(toast);
setTimeout(() => toast.classList.add('show'), 10);
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => toast.remove(), 300);
}, 3000);
}
function playSound(type) {
// Boxing bell sound effect (optional, uses Web Audio API)
if (type === 'start') {
try {
const ctx = new (window.AudioContext || window.webkitAudioContext)();
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.connect(gain);
gain.connect(ctx.destination);
osc.frequency.value = 800;
gain.gain.value = 0.1;
osc.start();
gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.3);
osc.stop(ctx.currentTime + 0.3);
} catch (e) { }
}
}
// ============================================
// LOCAL STORAGE MANAGEMENT
// ============================================
function saveApiKey(key) {
if ($('rememberKey')?.checked) {
localStorage.setItem(CONFIG.storageKeys.apiKey, btoa(key));
localStorage.setItem(CONFIG.storageKeys.rememberKey, 'true');
} else {
localStorage.removeItem(CONFIG.storageKeys.apiKey);
localStorage.removeItem(CONFIG.storageKeys.rememberKey);
}
}
function loadApiKey() {
const remembered = localStorage.getItem(CONFIG.storageKeys.rememberKey) === 'true';
if (remembered) {
const encoded = localStorage.getItem(CONFIG.storageKeys.apiKey);
if (encoded) {
try {
return atob(encoded);
} catch (e) { }
}
}
return '';
}
function saveProvider(provider) {
localStorage.setItem(CONFIG.storageKeys.provider, provider);
}
function loadProvider() {
return localStorage.getItem(CONFIG.storageKeys.provider) || 'openai';
}
// ============================================
// UI INTERACTIONS
// ============================================
function toggleApiKey() {
const input = $('apiKey');
const btn = $('toggleKeyBtn');
if (input.type === 'password') {
input.type = 'text';
btn.textContent = '🙈';
} else {
input.type = 'password';
btn.textContent = '👁️';
}
}
function copyResponse(direction, round = 1) {
const content = round === 1
? sparState.responses.round1[direction]
: sparState.responses.round2[direction];
if (!content) {
showToast('Nothing to copy', 'error');
return;
}
navigator.clipboard.writeText(content).then(() => {
showToast(`${PERSONAS[direction].name} copied!`, 'success');
}).catch(() => {
showToast('Failed to copy', 'error');
});
}
function copySynthesis() {
if (!sparState.synthesis) {
showToast('No synthesis to copy', 'error');
return;
}
navigator.clipboard.writeText(sparState.synthesis).then(() => {
showToast('Synthesis copied!', 'success');
}).catch(() => {
showToast('Failed to copy', 'error');
});
}
function retryPersona(direction) {
runSinglePersona(direction);
}
function setExample(type) {
const examples = {
career: "I'm deciding whether to accept a new job offer at 40% higher salary but requiring relocation. I have a young family and we just bought a house. The new role is in a growing company but higher risk.",
market: "I'm deciding whether to expand into the Singapore market. We have a proven product in Australia but no local presence. The market is competitive but growing. We'd need to hire a local team.",
product: "I'm deciding whether to launch our product now with 80% of features or wait 3 more months for the complete version. Competitors are moving fast but early users want more polish.",
hire: "I'm deciding between two candidates for VP of Engineering. One has 15 years experience at big tech companies, excellent credentials. The other is from a startup, less traditional background but more energy and aligns with our culture.",
investment: "I'm deciding whether to bootstrap our next phase or take VC funding. We're profitable but growing slowly. VC would accelerate growth but mean giving up control and potentially changing our culture."
};
$('decisionInput').value = examples[type];
$('decisionInput').focus();
}
// ============================================
// API CONFIGURATION
// ============================================
function getApiConfig() {
const provider = $('provider').value;
const apiKey = $('apiKey').value.trim();
if (!apiKey) {
showToast('Please enter your API key', 'error');
$('apiKey').focus();
return null;
}
// Save for next time
saveApiKey(apiKey);
saveProvider(provider);
return { provider, apiKey };
}
// ============================================
// GEMINI MODEL DISCOVERY
// ============================================
// Cache for discovered Gemini model
let cachedGeminiModel = null;
/**
* Fetches available Gemini models and selects the best fast model.
* Prioritizes: gemini-2.5-flash > gemini-2.0-flash > any flash model
*/
async function getGeminiModel(apiKey) {
// Return cached model if available
if (cachedGeminiModel) {
return cachedGeminiModel;
}
try {
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models?key=${apiKey}`
);
if (!response.ok) {
console.warn('Failed to fetch Gemini models, using fallback');
return 'gemini-2.0-flash';
}
const data = await response.json();
const models = data.models || [];
// Filter for flash models that support generateContent
const flashModels = models
.filter(m =>
m.name &&
m.name.includes('flash') &&
m.supportedGenerationMethods?.includes('generateContent')
)
.map(m => m.name.replace('models/', ''))
.sort((a, b) => {
// Extract version numbers for sorting (higher = newer)
const versionA = parseFloat(a.match(/\d+\.?\d*/)?.[0] || '0');
const versionB = parseFloat(b.match(/\d+\.?\d*/)?.[0] || '0');
return versionB - versionA;
});
console.log('📡 Available Gemini flash models:', flashModels);
// Select the best model (newest version)
cachedGeminiModel = flashModels[0] || 'gemini-2.0-flash';
console.log('✅ Selected Gemini model:', cachedGeminiModel);
return cachedGeminiModel;
} catch (error) {
console.warn('Error fetching Gemini models:', error.message);
return 'gemini-2.0-flash'; // Fallback to known stable model
}
}
// ============================================
// API CALLS WITH STREAMING SUPPORT
// ============================================
async function callAI(provider, apiKey, systemPrompt, userMessage, onChunk = null) {
// For Gemini, dynamically determine the model
let geminiEndpoint = null;
if (provider === 'gemini') {
const geminiModel = await getGeminiModel(apiKey);
geminiEndpoint = `https://generativelanguage.googleapis.com/v1beta/models/${geminiModel}:generateContent?key=${apiKey}`;
}
const endpoints = {
openai: 'https://api.openai.com/v1/chat/completions',
anthropic: 'https://api.anthropic.com/v1/messages',
gemini: geminiEndpoint
};
try {
if (provider === 'openai') {
const response = await fetch(endpoints.openai, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: 'gpt-4-turbo-preview',
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userMessage }
],
max_tokens: 1000,
stream: false
})
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error?.message || `HTTP ${response.status}`);
}
const data = await response.json();
return data.choices[0].message.content;
}
if (provider === 'anthropic') {
const response = await fetch(endpoints.anthropic, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKey,
'anthropic-version': '2023-06-01',
'anthropic-dangerous-direct-browser-access': 'true'
},
body: JSON.stringify({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1000,
system: systemPrompt,
messages: [{ role: 'user', content: userMessage }]
})
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error?.message || `HTTP ${response.status}`);
}
const data = await response.json();
return data.content[0].text;
}
if (provider === 'gemini') {
const response = await fetch(endpoints.gemini, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{ parts: [{ text: `${systemPrompt}\n\n${userMessage}` }] }]
})
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error?.message || `HTTP ${response.status}`);
}
const data = await response.json();
return data.candidates[0].content.parts[0].text;
}
throw new Error(`Unknown provider: ${provider}`);
} catch (error) {
console.error(`API Error (${provider}):`, error);
throw error;
}
}
// ============================================
// SPAR EXECUTION
// ============================================
async function runSpar() {
if (sparState.isRunning) return;
const config = getApiConfig();
if (!config) return;
const decision = $('decisionInput').value.trim();
if (!decision) {
showToast('Please describe your decision', 'error');
$('decisionInput').focus();
return;
}
sparState.decision = decision;
sparState.isRunning = true;
sparState.errors = {};
// Mark A step as completed, activate R step
const stepA = document.querySelector('#step-A');
if (stepA) {
stepA.classList.remove('active');
stepA.classList.add('completed');
stepA.querySelector('.wizard-step-status').textContent = 'Done';
}
const stepR = document.querySelector('#step-R');
if (stepR) {
stepR.classList.remove('locked');
stepR.classList.add('active');
stepR.querySelector('.wizard-step-status').textContent = 'Current';
sparState.currentStep = 'R';
setTimeout(() => {
stepR.scrollIntoView({ behavior: 'smooth', block: 'start' });
}, 100);
}
// Play start sound
playSound('start');
// Show debate section
$('debate').classList.add('active');
// Update button state
const btn = $('sparBtn');
btn.disabled = true;
btn.innerHTML = `<span class="btn-spar-icon">⏳</span><span class="btn-spar-text">Running</span>`;
// Update favicon to show progress
updateFavicon('running');
const userMessage = `THE DECISION: ${decision}
Analyze this decision from your perspective:
- What do you see that others might miss?
- What questions would you ask before deciding?
- What's your position on this decision, and why?`;
// Run all 4 personas in parallel
const directions = ['north', 'east', 'south', 'west'];
let completed = 0;
const promises = directions.map(async (dir) => {
await runSinglePersona(dir, config, userMessage);
completed++;
updateProgress(completed, 4);
});
await Promise.all(promises);
// Show actions and reset button
$('actions').style.display = 'flex';
btn.disabled = false;
btn.innerHTML = `<span class="btn-spar-icon">🥊</span><span class="btn-spar-text">SPAR</span>`;
sparState.isRunning = false;
updateFavicon('done');
// SPARKIT: Rumble complete - ready for Knit (Round 2)
showToast('Round 1 complete! Click "The Clash" to continue 🥊', 'success');
}
async function runSinglePersona(dir, config = null, userMessage = null) {
if (!config) {
config = getApiConfig();
if (!config) return;
}
if (!userMessage) {
userMessage = `THE DECISION: ${sparState.decision}
Analyze this decision from your perspective:
- What do you see that others might miss?
- What questions would you ask before deciding?
- What's your position on this decision, and why?`;
}
const persona = PERSONAS[dir];
const statusEl = $(`${dir}-status`);
const contentEl = $(`${dir}-content`);
const indicatorEl = $(`${dir}-indicator`);
const retryBtn = $(`${dir}-retry`);
// Reset state
statusEl.textContent = 'Thinking';
statusEl.className = 'position-status thinking';
contentEl.textContent = '';
contentEl.classList.remove('empty', 'error');
contentEl.classList.add('loading');
indicatorEl?.classList.add('active');
if (retryBtn) retryBtn.style.display = 'none';
// Typing animation dots
let dots = 0;
const dotsInterval = setInterval(() => {
dots = (dots + 1) % 4;
statusEl.textContent = 'Thinking' + '.'.repeat(dots);
}, 400);
try {
const response = await callAI(config.provider, config.apiKey, persona.prompt, userMessage);
clearInterval(dotsInterval);
sparState.responses.round1[dir] = response;
sparState.errors[dir] = null;
// Animate text appearance
contentEl.classList.remove('loading');
contentEl.textContent = response;
contentEl.classList.add('fade-in');
statusEl.textContent = 'Done';
statusEl.className = 'position-status done';
} catch (error) {
clearInterval(dotsInterval);
sparState.errors[dir] = error.message;
contentEl.classList.remove('loading');
contentEl.classList.add('error');
contentEl.innerHTML = `
<div class="error-content">
<span class="error-icon">⚠️</span>
<span class="error-message">${error.message}</span>
</div>
`;
statusEl.textContent = 'Error';
statusEl.className = 'position-status';
// Show retry button
if (retryBtn) retryBtn.style.display = 'inline-flex';
}
indicatorEl?.classList.remove('active');
}
function updateProgress(current, total) {
const percent = Math.round((current / total) * 100);
// Could update a progress bar here if desired
}
function updateFavicon(state) {
// Dynamic favicon based on state
const emoji = state === 'running' ? '⏳' : state === 'done' ? '✅' : '🥊';
const link = document.querySelector("link[rel*='icon']") || document.createElement('link');
link.type = 'image/svg+xml';
link.rel = 'icon';
link.href = `data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>${emoji}</text></svg>`;
document.head.appendChild(link);
}
// ============================================
// ROUND 2
// ============================================
async function runRound2() {
const config = getApiConfig();
if (!config) return;
// SPARKIT Step R→K: Moving to Knit (synthesis phase)
setProtocolProgress('K');
$('round2').style.display = 'block';
$('round2').scrollIntoView({ behavior: 'smooth' });
playSound('start');
const otherPositions = `The other perspectives said:
NORTH (Visionary): ${sparState.responses.round1.north.substring(0, 300)}...
EAST (Challenger): ${sparState.responses.round1.east.substring(0, 300)}...
SOUTH (Pragmatist): ${sparState.responses.round1.south.substring(0, 300)}...
WEST (Sage): ${sparState.responses.round1.west.substring(0, 300)}...
Where do you DISAGREE with them? What are they missing? Be specific, direct, and confrontational. This is a clash of perspectives.`;
const directions = ['north', 'east', 'south', 'west'];
const promises = directions.map(async (dir) => {
const persona = PERSONAS[dir];
const statusEl = $(`${dir}-r2-status`);
const contentEl = $(`${dir}-r2-content`);
statusEl.textContent = 'Clashing';
statusEl.className = 'position-status thinking';
contentEl.textContent = '';
contentEl.classList.add('loading');
try {
const response = await callAI(config.provider, config.apiKey, persona.prompt, otherPositions);
sparState.responses.round2[dir] = response;
contentEl.classList.remove('loading');
contentEl.textContent = response;
statusEl.textContent = 'Done';
statusEl.className = 'position-status done';
} catch (error) {
contentEl.classList.remove('loading');
contentEl.innerHTML = `<span class="error-message">Error: ${error.message}</span>`;
statusEl.textContent = 'Error';
statusEl.className = 'position-status';
}
});
await Promise.all(promises);
// Generate synthesis
await generateSynthesis(config);
showToast('The Clash complete! 🥊', 'success');
}
// ============================================
// SYNTHESIS
// ============================================
async function generateSynthesis(config) {
// SPARKIT Step K→I: Synthesis ready for Interrogation
setTimeout(() => setProtocolProgress('I'), 500);
$('synthesis').style.display = 'block';
$('synthesis').scrollIntoView({ behavior: 'smooth' });
const synthesisPrompt = `You are a neutral MODERATOR synthesizing a SPAR debate.
The decision was: ${sparState.decision}
ROUND 1 POSITIONS:
North (Visionary): ${sparState.responses.round1.north}
East (Challenger): ${sparState.responses.round1.east}
South (Pragmatist): ${sparState.responses.round1.south}
West (Sage): ${sparState.responses.round1.west}
ROUND 2 - THE CLASH:
North: ${sparState.responses.round2.north}
East: ${sparState.responses.round2.east}
South: ${sparState.responses.round2.south}
West: ${sparState.responses.round2.west}
Provide a synthesis with these sections:
## 🔥 KEY TENSIONS
Where do the personas genuinely, fundamentally disagree?
## 🤝 SURPRISING CONVERGENCES
Where do they unexpectedly agree despite different perspectives?
## 💡 INSIGHTS SURFACED
What emerged from this debate that wasn't obvious at the start?
## ❓ OPEN QUESTIONS
What remains unresolved that the decision-maker should consider?
## 🧭 THE DECISION MATRIX
Summarize the core trade-offs in a simple format.
Be concise but complete. Use markdown formatting.`;
const contentEl = $('synthesis-content');
contentEl.innerHTML = '<span class="loading-text">Synthesizing the debate...</span>';
try {
const response = await callAI(config.provider, config.apiKey, 'You are a neutral debate moderator and expert synthesizer.', synthesisPrompt);
sparState.synthesis = response;
// Render with simple markdown
contentEl.innerHTML = renderMarkdown(response);
} catch (error) {
contentEl.innerHTML = `<span class="error-message">Error generating synthesis: ${error.message}</span>`;
}
}
function renderMarkdown(text) {
return text
.replace(/## (.*)/g, '<h4>$1</h4>')
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.*?)\*/g, '<em>$1</em>')
.replace(/\n\n/g, '</p><p>')
.replace(/\n/g, '<br>');
}
// ============================================
// EXPORT
// ============================================
function exportMarkdown() {
// SPARKIT Step I→T: Transmitting actionable output
setProtocolProgress('T');
const date = new Date().toISOString().split('T')[0];
const time = new Date().toLocaleTimeString();
let md = `# SPAR Session
**Date**: ${date} at ${time}
**Method**: SPAR Kit v${CONFIG.version} (N-E-W-S Compass)
**Provider**: ${sparState.provider}
---
## 🎯 The Decision
${sparState.decision}
---
## ⚔️ Round 1: Opening Positions
### 🔵 North — The Visionary
${sparState.responses.round1.north || '_Not completed_'}
### 🟢 East — The Challenger
${sparState.responses.round1.east || '_Not completed_'}
### 🟡 South — The Pragmatist
${sparState.responses.round1.south || '_Not completed_'}
### 🔴 West — The Sage
${sparState.responses.round1.west || '_Not completed_'}
---
## 🔥 Round 2: The Clash
### 🔵 North responds
${sparState.responses.round2.north || '_Not run_'}
### 🟢 East responds
${sparState.responses.round2.east || '_Not run_'}
### 🟡 South responds
${sparState.responses.round2.south || '_Not run_'}
### 🔴 West responds
${sparState.responses.round2.west || '_Not run_'}
---
## 📊 Synthesis
${sparState.synthesis || '_Not generated_'}
---
> **நாலு பேரு, நாலு திசை, ஒரு முடிவு!**
> *Four Perspectives, Four Dimensions, One Synthesis*
🥊 Generated by [SPAR Kit](https://synthanai.github.io/spar-kit) | [GitHub](https://github.com/synthanai/spar-kit)
`;
const blob = new Blob([md], { type: 'text/markdown' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;