Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
2795 lines (2388 loc) · 104 KB
/
Copy pathapp.js
File metadata and controls
2795 lines (2388 loc) · 104 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
// ============================
// Helpers
// ============================
function scrollToBottom(smooth){
const container = document.querySelector('.messages-container');
if(smooth) container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' });
else container.scrollTop = container.scrollHeight;
}
function autoResize(){
inputEl.style.height = 'auto';
inputEl.style.height = Math.min(inputEl.scrollHeight, 200) + 'px';
}
function updateChatTitle(chat, content){
if(chat.title === 'New Chat'){
chat.title = content.slice(0, 40);
topbarTitle.textContent = chat.title;
}
}
function updateModelLabel(){
modelLabel.textContent = `${state.provider} • ${state.model}`;
}
// ============================
// ---- Markdown parser (safe for code blocks) ----
function markdownToHtml(text) {
if (!text) return '';
const codeBlocks = [];
let html = text;
html = html.replace(/```(\w*)\n?([\s\S]*?)```/g, (_, lang, code) => {
const placeholder = `%%CODEBLOCK${codeBlocks.length}%%`;
codeBlocks.push(
`<pre><code class="language-${lang}">${escapeHtml(code.trim())}</code></pre>`
);
return placeholder;
});
html = html.replace(/`([^`]+)`/g, (_, code) => {
const placeholder = `%%INLINECODE${codeBlocks.length}%%`;
codeBlocks.push(`<code>${escapeHtml(code)}</code>`);
return placeholder;
});
html = html
.replace(/^### (.+)$/gm, '<h3>$1</h3>')
.replace(/^## (.+)$/gm, '<h2>$1</h2>')
.replace(/^# (.+)$/gm, '<h1>$1</h1>')
.replace(/^> (.+)$/gm, '<blockquote>$1</blockquote>')
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
.replace(/__(.+?)__/g, '<strong>$1</strong>')
.replace(/\*(.+?)\*/g, '<em>$1</em>')
.replace(/_(.+?)_/g, '<em>$1</em>')
.replace(/^---$/gm, '<hr>')
.replace(/^\d+\. (.+)$/gm, '<li>$1</li>')
.replace(/^[\-\*] (.+)$/gm, '<li>$1</li>');
html = html.replace(/(<li>[\s\S]*?<\/li>)/g, '<ul>$1</ul>');
html = html.split(/\n{2,}/).map(p => `<p>${p}</p>`).join('');
codeBlocks.forEach((codeHtml, idx) => {
html = html.replace(`%%CODEBLOCK${idx}%%`, codeHtml);
html = html.replace(`%%INLINECODE${idx}%%`, codeHtml);
});
return html;
}
const escapeHtml = (str) => {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
};
// ============================
// AI Tool Commands
// ============================
const AI_TOOLS = {
create_file(args, body) {
const filename = args[0];
if (!filename) return { ok: false, msg: 'No filename provided.' };
const content = body ?? args.slice(1).join(' ');
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
return {
ok: true,
msg: `File **${escapeHtml(filename)}** created and downloaded (${content.length} bytes).`
};
},
open_url(args) {
const url = args[0];
if (!url) return { ok: false, msg: 'No URL provided.' };
window.open(url, '_blank', 'noopener');
return { ok: true, msg: `Opened URL: ${escapeHtml(url)}` };
},
alert(args, body) {
const msg = body ?? args.join(' ');
alert(msg);
return { ok: true, msg: `Alert shown: "${escapeHtml(msg)}"` };
},
set_title(args, body) {
const title = body ?? args.join(' ');
const chat = getActiveChat();
if (chat) {
chat.title = title;
topbarTitle.textContent = title;
saveChats();
renderChatList();
}
return { ok: true, msg: `Chat title set to **${escapeHtml(title)}**.` };
},
};
function processAiTools(text) {
const toolResults = [];
const cleanText = text.replace(/<tool:(\w+)([^>]*)>([\s\S]*?)<\/tool>/gi, (_, name, argsStr, body) => {
const args = argsStr.trim().split(/\s+/).filter(Boolean);
const fn = AI_TOOLS[name.toLowerCase()];
if (!fn) {
toolResults.push({ ok: false, name, msg: `Unknown tool: \`${name}\`` });
return '';
}
try {
const result = fn(args, body);
toolResults.push({ name, ...result });
} catch(e) {
toolResults.push({ ok: false, name, msg: `Tool \`${name}\` threw: ${e.message}` });
}
return '';
});
const cleanText2 = cleanText.replace(/^@@(\w+)\s+(.*)$/gm, (_, name, rest) => {
const fn = AI_TOOLS[name.toLowerCase()];
if (!fn) {
toolResults.push({ ok: false, name, msg: `Unknown tool: \`${name}\`` });
return '';
}
try {
const parts = rest.split(/\s+/);
const args = [parts[0]];
const body = parts.slice(1).join(' ');
const result = fn(args, body);
toolResults.push({ name, ...result });
} catch(e) {
toolResults.push({ ok: false, name, msg: `Tool \`${name}\` threw: ${e.message}` });
}
return '';
});
return { cleanText: cleanText2.trim(), toolResults };
}
function buildToolFeedbackMessage(toolResults) {
if (!toolResults.length) return null;
const lines = toolResults.map(r => {
const icon = r.ok ? '✅' : '❌';
return `${icon} **\`${r.name}\`** — ${r.msg}`;
});
return `🔧 **Tool results:**\n\n${lines.join('\n')}`;
}
// ============================
// Providers
// ============================
const PROVIDERS = {
anthropic: { name: 'Anthropic', endpoint: 'https://api.anthropic.com/v1/messages' },
openai: { name: 'OpenAI', endpoint: 'https://api.openai.com/v1/chat/completions' },
cerebras: { name: 'Cerebras', endpoint: 'https://api.cerebras.ai/v1/chat/completions' },
corelyn: { name: 'Corelyn', endpoint: 'https://api.corelyn.ro/chat/completions' }
};
// ============================
// State
// ============================
let state = {
apiKey: localStorage.getItem('nc_apikey') || '',
provider: localStorage.getItem('nc_provider') || 'corelyn',
model: localStorage.getItem('nc_model') || 'cerebras/llama3.1-8b',
systemPrompt: localStorage.getItem('nc_systemprompt') || `You are Corelyn, a useful AI assistant.
If user asks to generate code, give actually working valid code, no AI slop.
Respond only in markdown.
You have access to special tool commands you can embed in your response.
Use them like this:
<tool:create_file filename.txt>file content here</tool>
<tool:open_url https://example.com></tool>
<tool:alert some message to show></tool>
<tool:set_title New conversation title></tool>
Or using shorthand on its own line:
@@create_file banana.txt This is the file content
The tool tags are invisible to the user — they get executed automatically.
Only use tools when the user explicitly asks for file creation, opening URLs, etc.
When users ask you to create an image, respond in SVG code with NO brackets like the code MD brackets
and save it using the create_file tool. Example:
<tool:create_file image.svg>
<svg width="800" height="800" viewBox="0 0 400 400" xmlns="http://www.w3.org/2000/svg" class="icon logo">
<circle cx="200" cy="200" r="150" stroke="#000000" stroke-width="2" fill="none"/>
<text x="200" y="210" font-size="60" text-anchor="middle" fill="#000000">Corelyn</text>
</svg>
</tool>`,
triggers: JSON.parse(localStorage.getItem('nc_triggers') || '[]'),
chats: JSON.parse(localStorage.getItem('nc_chats') || '[]'),
activeChatId: null,
streaming: false,
// ── New feature flags ──
deepThink: false,
webSearch: false,
attachedFiles: []
};
// ============================
// DOM
// ============================
const $ = id => document.getElementById(id);
const messagesEl = $('messages');
const welcomeEl = $('welcomeScreen');
const inputEl = $('userInput');
const sendBtn = $('sendBtn');
const chatListEl = $('chatList');
const topbarTitle = $('topbarTitle');
const modelLabel = $('modelLabel');
const modelDropdown = $('modelDropdown');
const modelSelector = $('modelSelector');
const sidebar = $('sidebar');
const sidebarToggle = $('sidebarToggle');
// Settings Modal
const settingsModal = $('settingsModal');
const openSettingsBtn = $('openSettingsBtn');
const closeSettingsBtn = $('closeSettings');
const saveSettingsBtn = $('saveSettingsBtn');
const apiKeyInput = $('apiKeyInput');
const providerSelect = $('providerSelect');
const systemPromptInput = $('systemPromptInput');
const triggerListEl = $('triggerList');
const addTriggerBtn = $('addTriggerBtn');
// Did not know where to add this
const donateModal = document.getElementById("donateModal");
const openDonateBtn = document.getElementById("openDonateBtn");
const closeDonate = document.getElementById("closeDonate");
const dontShowDonate = document.getElementById("dontShowDonate");
const modelSelect = document.getElementById("modelSelect");
// ── Corelyn Cloud Auth (Google -> auto-generate API key) ──
const authModal = $('authModal');
const closeAuthModalBtn = $('closeAuthModal');
const authTosCheckbox = $('authTosCheckbox');
const authAccountView = $('authAccountView');
const authLoadingView = $('authLoadingView');
const authErrorView = $('authErrorView');
const authErrorText = $('authErrorText');
const authRetryBtn = $('authRetryBtn');
const authCloseFromErrorBtn = $('authCloseFromError');
const authGoogleBtn = $('authGoogleBtn');
const providerModels = {
corelyn: [
"nvidia/moonshotai/kimi-k2.5",
"nvidia/qwen/qwen3.5-397b-a17b",
"nvidia/microsoft/phi-3.5-mini-instruct",
"nvidia/meta/llama-3.2-1b-instruct",
"nvidia/deepseek-ai/deepseek-v3.1",
"nvidia/z-ai/glm5",
"nvidia/mistralai/mistral-7b-instruct-v0.2",
"nvidia/google/gemma-7b",
"nvidia/tiiuae/falcon3-7b-instruct",
"nvidia/minimaxai/minimax-m2.5",
"nvidia/nvidia/nemotron-3-super-120b-a12",
"cerebras/llama3.1-8b"
],
openai: [
"gpt-4o",
"gpt-4o-mini",
"gpt-4.1",
"gpt-4.1-mini",
"gpt-4.1-nano",
"o4-mini",
"o3-mini"
],
anthropic: [
"claude-3-opus",
"claude-3-sonnet",
"claude-3-haiku",
"claude-3.5-sonnet",
"claude-3.5-haiku"
],
cerebras: [
"llama3.1-8b",
"qwen-3-235b-a22b-instruct-2507"
]
};
function updateModels() {
const provider = providerSelect.value;
modelSelect.innerHTML = "";
const models = providerModels[provider] || [];
models.forEach(model => {
const option = document.createElement("option");
option.value = model;
option.textContent = model;
modelSelect.appendChild(option);
});
}
providerSelect.addEventListener("change", updateModels);
// initialize on page load
updateModels();
// hide donate button if user disabled it
if (localStorage.getItem("hideDonateModal") === "true") {
openDonateBtn.style.display = "none";
}
// open modal
openDonateBtn.onclick = () => {
donateModal.style.display = "flex";
};
// close modal
closeDonate.onclick = () => {
if (dontShowDonate.checked) {
localStorage.setItem("hideDonateModal", "true");
// hide button immediately
openDonateBtn.style.display = "none";
}
donateModal.style.display = "none";
};
// close when clicking outside modal
window.onclick = (e) => {
if (e.target === donateModal) {
donateModal.style.display = "none";
}
};
// ============================
// ── FEATURE: Web Search ──
// ============================
async function fetchWebSearchContext(query) {
const results = await Promise.allSettled([
fetchDDGAnswer(query),
fetchWikipediaSummary(query),
]);
const snippets = [];
for (const r of results) {
if (r.status === 'fulfilled' && r.value) snippets.push(r.value);
}
if (!snippets.length) {
console.warn('Web search: no results from any source');
return null;
}
return `[Web search results for: "${query}"]\n\n${snippets.join('\n\n')}\n[End of search results]`;
}
async function fetchDDGAnswer(query) {
try {
const url = `https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_html=1&skip_disambig=1&no_redirect=1`;
const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
if (!res.ok) return null;
const data = await res.json();
const parts = [];
if (data.Answer) parts.push(`**Instant answer:** ${data.Answer}`);
if (data.Abstract) parts.push(`**Summary:** ${data.Abstract}${data.AbstractURL ? ` — [source](${data.AbstractURL})` : ''}`);
const topics = (data.RelatedTopics || [])
.filter(t => t.Text && !t.Topics)
.slice(0, 4)
.map(t => `- ${t.Text}`);
if (topics.length) parts.push(`**Related topics:**\n${topics.join('\n')}`);
return parts.length ? `### DuckDuckGo\n${parts.join('\n\n')}` : null;
} catch (e) {
console.warn('DDG search failed:', e.message);
return null;
}
}
async function fetchWikipediaSummary(query) {
try {
const searchUrl = `https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${encodeURIComponent(query)}&srlimit=1&format=json&origin=*`;
const searchRes = await fetch(searchUrl, { signal: AbortSignal.timeout(5000) });
if (!searchRes.ok) return null;
const searchData = await searchRes.json();
const title = searchData?.query?.search?.[0]?.title;
if (!title) return null;
const summaryUrl = `https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(title)}`;
const summaryRes = await fetch(summaryUrl, { signal: AbortSignal.timeout(5000) });
if (!summaryRes.ok) return null;
const summaryData = await summaryRes.json();
const extract = summaryData?.extract;
if (!extract) return null;
const short = extract.length > 600 ? extract.slice(0, 600) + '…' : extract;
return `### Wikipedia — ${title}\n${short}\n[Read more](${summaryData.content_urls?.desktop?.page || ''})`;
} catch (e) {
console.warn('Wikipedia search failed:', e.message);
return null;
}
}
// ============================
// ── FEATURE: File Upload ──
// ============================
function injectFileUploadUI() {
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.id = 'fileUploadInput';
fileInput.multiple = true;
fileInput.accept = '.txt,.md,.js,.ts,.py,.json,.csv,.html,.css,.xml,.yaml,.yml,.pdf,.png,.jpg,.jpeg,.gif,.webp';
fileInput.style.display = 'none';
document.body.appendChild(fileInput);
const attachBtn = document.createElement('button');
attachBtn.id = 'attachBtn';
attachBtn.className = 'input-feature-btn';
attachBtn.title = 'Attach files';
attachBtn.innerHTML = `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"/></svg>`;
const deepThinkBtn = document.createElement('button');
deepThinkBtn.id = 'deepThinkBtn';
deepThinkBtn.className = 'input-feature-btn';
deepThinkBtn.title = 'Deep Think — makes the AI reason step-by-step';
deepThinkBtn.innerHTML = `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l3 3"/></svg>`;
const webSearchBtn = document.createElement('button');
webSearchBtn.id = 'webSearchBtn';
webSearchBtn.className = 'input-feature-btn';
webSearchBtn.title = 'Web Search — fetch live context before answering';
webSearchBtn.innerHTML = `<svg width="16" height="16" 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"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>`;
const filePreviewBar = document.createElement('div');
filePreviewBar.id = 'filePreviewBar';
filePreviewBar.className = 'file-preview-bar';
filePreviewBar.style.display = 'none';
const inputWrapper = sendBtn.parentElement;
inputWrapper.insertBefore(attachBtn, sendBtn);
inputWrapper.insertBefore(deepThinkBtn, sendBtn);
inputWrapper.insertBefore(webSearchBtn, sendBtn);
const inputArea = document.querySelector('.input-area') || inputWrapper.parentElement;
inputArea.insertBefore(filePreviewBar, inputArea.firstChild);
attachBtn.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', async () => {
const files = Array.from(fileInput.files);
if (!files.length) return;
for (const file of files) {
await readAndAttachFile(file);
}
fileInput.value = '';
renderFilePreviewBar();
});
deepThinkBtn.addEventListener('click', () => {
state.deepThink = !state.deepThink;
deepThinkBtn.classList.toggle('active', state.deepThink);
deepThinkBtn.title = state.deepThink ? 'Deep Think ON' : 'Deep Think — makes the AI reason step-by-step';
showToast(state.deepThink ? '🧠 Deep Think enabled' : '🧠 Deep Think disabled');
});
webSearchBtn.addEventListener('click', () => {
state.webSearch = !state.webSearch;
webSearchBtn.classList.toggle('active', state.webSearch);
webSearchBtn.title = state.webSearch ? 'Web Search ON' : 'Web Search — fetch live context before answering';
showToast(state.webSearch ? '🔎 Web Search enabled' : '🔎 Web Search disabled');
});
injectFeatureStyles();
}
async function readAndAttachFile(file) {
return new Promise((resolve) => {
const isImage = file.type.startsWith('image/');
const reader = new FileReader();
reader.onload = (e) => {
if (isImage) {
state.attachedFiles.push({ name: file.name, type: file.type, content: e.target.result, isImage: true });
} else {
state.attachedFiles.push({ name: file.name, type: file.type || 'text/plain', content: e.target.result, isImage: false });
}
resolve();
};
reader.onerror = () => { showToast(`Failed to read ${file.name}`, 'error'); resolve(); };
if (isImage) { reader.readAsDataURL(file); } else { reader.readAsText(file); }
});
}
function renderFilePreviewBar() {
const bar = $('filePreviewBar');
if (!bar) return;
if (!state.attachedFiles.length) { bar.style.display = 'none'; bar.innerHTML = ''; return; }
bar.style.display = 'flex';
bar.innerHTML = '';
state.attachedFiles.forEach((f, i) => {
const chip = document.createElement('div');
chip.className = 'file-chip';
const icon = f.isImage ? '🖼️' : getFileIcon(f.name);
chip.innerHTML = `<span class="file-chip-icon">${icon}</span><span class="file-chip-name" title="${escapeHtml(f.name)}">${escapeHtml(f.name.length > 20 ? f.name.slice(0,18)+'…' : f.name)}</span><button class="file-chip-remove" data-i="${i}" title="Remove">×</button>`;
chip.querySelector('.file-chip-remove').addEventListener('click', (e) => {
e.stopPropagation();
state.attachedFiles.splice(i, 1);
renderFilePreviewBar();
});
bar.appendChild(chip);
});
}
function getFileIcon(name) {
const ext = name.split('.').pop().toLowerCase();
const map = { js:'📜', ts:'📜', py:'🐍', json:'📋', csv:'📊', html:'🌐', css:'🎨', md:'📝', txt:'📄', pdf:'📕', xml:'📋', yaml:'📋', yml:'📋' };
return map[ext] || '📎';
}
const MAX_FILE_CHARS = 40000;
function buildFileContext(filesSnapshot) {
const files = filesSnapshot || state.attachedFiles;
const textFiles = files.filter(f => !f.isImage);
if (!textFiles.length) return '';
const parts = textFiles.map(f => {
let content = f.content.replace(/\0/g, '').replace(/\r\n/g, '\n');
const truncated = content.length > MAX_FILE_CHARS;
if (truncated) content = content.slice(0, MAX_FILE_CHARS) + `\n\n[...truncated at ${MAX_FILE_CHARS} chars]`;
return `--- File: ${f.name} ---\n${content}\n--- End of ${f.name} ---`;
});
return '\n\n[Attached files:]\n' + parts.join('\n\n');
}
function buildContentBlocks(textContent, filesSnapshot, provider) {
const files = filesSnapshot || [];
const imageFiles = files.filter(f => f.isImage);
if (!imageFiles.length) return textContent;
const blocks = [];
if (provider === 'anthropic') {
imageFiles.forEach(f => {
const mediaType = f.type || 'image/jpeg';
const base64 = f.content.split(',')[1] || f.content;
blocks.push({ type: 'image', source: { type: 'base64', media_type: mediaType, data: base64 } });
});
blocks.push({ type: 'text', text: textContent });
} else {
const contentArr = [];
imageFiles.forEach(f => { contentArr.push({ type: 'image_url', image_url: { url: f.content } }); });
contentArr.push({ type: 'text', text: textContent });
return contentArr;
}
return blocks;
}
// ============================
// ── FEATURE: Deep Think ──
// ============================
const DEEP_THINK_PREFIX = `Before answering, reason through this step-by-step inside a <thinking> block:
<thinking>
1. What is the user really asking?
2. What do I know that's relevant?
3. What are the edge cases or nuances?
4. What is the best approach?
</thinking>
Then give your final answer after the thinking block. Be thorough and accurate.
`;
function buildSystemPrompt() {
const base = state.systemPrompt;
return state.deepThink ? DEEP_THINK_PREFIX + base : base;
}
// ============================
// Init
// ============================
function init() {
renderChatList();
if (state.chats.length > 0) loadChat(state.chats[0].id);
setupEventListeners();
updateModelLabel();
if (!state.apiKey) ensureApiKey();
injectFileUploadUI();
injectMessageActionStyles();
}
function promptForKeyManual() {
const key = window.prompt('Enter API Key:', '');
if (key && key.trim()) {
state.apiKey = key.trim();
localStorage.setItem('nc_apikey', state.apiKey);
}
}
// ============================
// Corelyn Cloud Auth Flow
// ============================
const CORELYN_API_BASE = 'https://api.corelyn.ro';
const CORELYN_GOOGLE_CLIENT_ID = '1095022231097-m2jpnjm7fkh0k2kd46hca3p4i8b6v3k0.apps.googleusercontent.com';
const CORELYN_USER_TOKEN_KEY = 'corelyn_user_token';
let apiKeyEnsurePromise = null;
let apiKeyEnsureResolve = null;
let googleButtonInitialized = false;
function showAuthView(viewName) {
const views = [authAccountView, authLoadingView, authErrorView].filter(Boolean);
views.forEach(v => (v.style.display = 'none'));
if (viewName === 'account' && authAccountView) authAccountView.style.display = '';
if (viewName === 'loading' && authLoadingView) authLoadingView.style.display = '';
if (viewName === 'error' && authErrorView) authErrorView.style.display = '';
}
function openAuthModal() {
if (!authModal) return;
authModal.style.display = 'flex';
}
function closeAuthModal() {
if (!authModal) return;
authModal.style.display = 'none';
}
function resolveApiKeyEnsure(value) {
if (!apiKeyEnsureResolve) return;
const r = apiKeyEnsureResolve;
apiKeyEnsureResolve = null;
r(value);
}
function setStateApiKey(newKey) {
state.apiKey = newKey;
localStorage.setItem('nc_apikey', state.apiKey);
if (apiKeyInput) apiKeyInput.value = state.apiKey;
sendBtn.disabled = !inputEl.value.trim();
}
async function fetchCorelynKeyFromToken(token) {
const res = await fetch(`${CORELYN_API_BASE}/get-key`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token })
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data?.error || `Failed to fetch key (${res.status})`);
if (data?.error) throw new Error(data.error);
if (!data?.key) throw new Error('No key returned from server.');
return data.key;
}
async function handleGoogleLogin(response) {
showAuthView('loading');
try {
const credential = response?.credential;
if (!credential) throw new Error('Missing Google credential.');
const res = await fetch(`${CORELYN_API_BASE}/google-login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ credential })
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data?.error || `Google login failed (${res.status})`);
if (data?.error) throw new Error(data.error);
if (!data?.token) throw new Error('Server did not return a token.');
localStorage.setItem(CORELYN_USER_TOKEN_KEY, data.token);
const apiKey = await fetchCorelynKeyFromToken(data.token);
setStateApiKey(apiKey);
closeAuthModal();
resolveApiKeyEnsure(apiKey);
} catch (err) {
const msg = err?.message || 'Failed to generate API key.';
if (authErrorText) authErrorText.textContent = msg;
showAuthView('error');
}
}
function initGoogleAuthButton() {
if (googleButtonInitialized) return;
if (!authGoogleBtn) return;
if (!window.google?.accounts?.id) {
setTimeout(initGoogleAuthButton, 250);
return;
}
window.google.accounts.id.initialize({
client_id: CORELYN_GOOGLE_CLIENT_ID,
callback: handleGoogleLogin
});
window.google.accounts.id.renderButton(authGoogleBtn, {
theme: 'filled_black',
size: 'large',
text: 'signin_with',
shape: 'rectangular'
});
googleButtonInitialized = true;
}
function openGoogleForApiKey() {
if (!authModal) return Promise.resolve(null);
return new Promise(async (resolve) => {
apiKeyEnsureResolve = resolve;
// Bind close/retry handlers (override, no duplication).
if (closeAuthModalBtn) closeAuthModalBtn.onclick = () => { closeAuthModal(); resolveApiKeyEnsure(null); };
if (authCloseFromErrorBtn) authCloseFromErrorBtn.onclick = () => { closeAuthModal(); resolveApiKeyEnsure(null); };
if (authRetryBtn) {
authRetryBtn.onclick = async () => {
const token = localStorage.getItem(CORELYN_USER_TOKEN_KEY);
if (!token) {
showAuthView('account');
return;
}
showAuthView('loading');
try {
const apiKey = await fetchCorelynKeyFromToken(token);
setStateApiKey(apiKey);
closeAuthModal();
resolveApiKeyEnsure(apiKey);
} catch (err) {
const msg = err?.message || 'Failed to fetch API key.';
if (authErrorText) authErrorText.textContent = msg;
showAuthView('error');
}
};
}
openAuthModal();
showAuthView('account');
initGoogleAuthButton();
// ToS checkbox gates the Google sign-in button
const tosAlreadyAgreed = localStorage.getItem('corelyn_tos_agreed') === 'true';
const googleBtnEl = authGoogleBtn;
function applyTosGate(agreed) {
if (!googleBtnEl) return;
googleBtnEl.style.opacity = agreed ? '1' : '0.35';
googleBtnEl.style.pointerEvents = agreed ? '' : 'none';
googleBtnEl.title = agreed ? '' : 'Please agree to the Terms of Service first';
}
if (authTosCheckbox) {
authTosCheckbox.checked = tosAlreadyAgreed;
applyTosGate(tosAlreadyAgreed);
authTosCheckbox.onchange = () => {
const agreed = authTosCheckbox.checked;
if (agreed) localStorage.setItem('corelyn_tos_agreed', 'true');
else localStorage.removeItem('corelyn_tos_agreed');
applyTosGate(agreed);
};
}
// If user already has a token saved, we can skip the account view.
const existingToken = localStorage.getItem(CORELYN_USER_TOKEN_KEY);
if (existingToken) {
showAuthView('loading');
try {
const apiKey = await fetchCorelynKeyFromToken(existingToken);
setStateApiKey(apiKey);
closeAuthModal();
resolveApiKeyEnsure(apiKey);
} catch (err) {
localStorage.removeItem(CORELYN_USER_TOKEN_KEY);
const msg = err?.message || 'Token invalid. Please sign in again.';
if (authErrorText) authErrorText.textContent = msg;
showAuthView('error');
}
}
});
}
async function ensureApiKey() {
if (state.apiKey) return state.apiKey;
if (apiKeyEnsurePromise) return apiKeyEnsurePromise;
apiKeyEnsurePromise = (async () => {
// Corelyn-generated keys only work with the Corelyn provider.
if (state.provider !== 'corelyn') {
state.provider = 'corelyn';
localStorage.setItem('nc_provider', state.provider);
if (providerSelect) {
providerSelect.value = 'corelyn';
updateModels();
if (modelSelect) modelSelect.value = state.model;
}
const corelynModels = providerModels.corelyn || [];
const fallbackModel = 'cerebras/llama3.1-8b';
if (corelynModels.length && !corelynModels.includes(state.model)) {
state.model = corelynModels.includes(fallbackModel) ? fallbackModel : corelynModels[0];
localStorage.setItem('nc_model', state.model);
}
updateModelLabel();
}
// Try token-first (same idea as cloud.html, but without the redirect).
const token = localStorage.getItem(CORELYN_USER_TOKEN_KEY);
if (token) {
try {
const apiKey = await fetchCorelynKeyFromToken(token);
setStateApiKey(apiKey);
return apiKey;
} catch (err) {
localStorage.removeItem(CORELYN_USER_TOKEN_KEY);
}
}
return await openGoogleForApiKey();
})();
try {
return await apiKeyEnsurePromise;
} finally {
apiKeyEnsurePromise = null;
}
}
// ============================
// Chat Management
// ============================
function createChat() {
const chat = { id: Date.now().toString(), title: 'New Chat', messages: [], createdAt: Date.now() };
state.chats.unshift(chat);
saveChats();
renderChatList();
loadChat(chat.id);
}
function loadChat(id) {
state.activeChatId = id;
const chat = getChat(id);
if (!chat) return;
topbarTitle.textContent = chat.title;
messagesEl.innerHTML = '';
if (chat.messages.length === 0) {
welcomeEl.style.display = 'flex';
messagesEl.style.display = 'none';
} else {
welcomeEl.style.display = 'none';
messagesEl.style.display = 'flex';
chat.messages.forEach(msg => {
if (msg.role === 'tool-feedback') {
renderToolFeedback(msg.content);
} else {
renderMessage(msg.role, msg.content);
}
});
attachRunButtons();
}
renderChatList();
scrollToBottom(true);
}
function getChat(id) { return state.chats.find(c => c.id === id); }
function getActiveChat() { return getChat(state.activeChatId); }
function deleteChat(id) {
state.chats = state.chats.filter(c => c.id !== id);
saveChats();
if (state.activeChatId === id) {
if (state.chats.length > 0) loadChat(state.chats[0].id);
else { state.activeChatId = null; messagesEl.innerHTML = ''; welcomeEl.style.display = 'flex'; topbarTitle.textContent = 'New Conversation'; }
}
renderChatList();
}
function saveChats() { localStorage.setItem('nc_chats', JSON.stringify(state.chats)); }
function renderChatList() {
chatListEl.innerHTML = '';
if (state.chats.length === 0) { chatListEl.innerHTML = '<div style="padding:10px;font-size:12px;color:var(--text-muted);">No chats yet</div>'; return; }
state.chats.forEach(chat => {
const item = document.createElement('div');
item.className = 'chat-item' + (chat.id === state.activeChatId ? ' active' : '');
item.dataset.id = chat.id;
const title = document.createElement('span');
title.className = 'chat-item-title'; title.textContent = chat.title;
const del = document.createElement('button'); del.className = 'chat-item-del'; del.innerHTML = '×'; del.onclick = e => { e.stopPropagation(); deleteChat(chat.id); };
item.appendChild(title); item.appendChild(del); item.onclick = () => loadChat(chat.id);
chatListEl.appendChild(item);
});
}
// ============================
// Messaging
// ============================
async function sendMessage(content) {
if (!content.trim() || state.streaming) return;
if (!state.apiKey) {
await ensureApiKey();
if (!state.apiKey) return;
}
if (!state.activeChatId) createChat();
const chat = getActiveChat(); if (!chat) return;
welcomeEl.style.display = 'none'; messagesEl.style.display = 'flex';
const filesSnapshot = [...state.attachedFiles];
const fileContext = buildFileContext(filesSnapshot);
state.attachedFiles = [];
renderFilePreviewBar();
const displayContent = filesSnapshot.length
? content + '\n\n' + filesSnapshot.map(f => `📎 ${f.name}`).join('\n')
: content;
chat.messages.push({ role: 'user', content: displayContent });
await renderMessageAsync('user', displayContent);
updateChatTitle(chat, content);
saveChats();
inputEl.value = ''; autoResize(); sendBtn.disabled = true;
const typingEl = showTyping();
state.streaming = true;
try {
let searchContext = '';
if (state.webSearch) {
typingEl.querySelector('.bubble').innerHTML = getThinkingHtml('🔎 Searching the web…');
searchContext = await fetchWebSearchContext(content) || '';
if (!searchContext) showToast('🔎 Web search returned no results', 'error');