-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1643 lines (1424 loc) · 58.5 KB
/
Copy pathcontent.js
File metadata and controls
1643 lines (1424 loc) · 58.5 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
(() => {
const BUTTON_ID = 'askyourgit-btn';
const DROPDOWN_ID = 'askyourgit-dropdown';
// --- Platform Detection ---
function detectPlatform() {
const host = window.location.hostname;
if (host === 'github.com') return 'github';
if (host === 'gitlab.com') return 'gitlab';
if (host === 'bitbucket.org') return 'bitbucket';
return null;
}
function getRepoInfo() {
const platform = detectPlatform();
if (!platform) return null;
const match = window.location.pathname.match(/^\/([^/]+)\/([^/]+)/);
if (!match) return null;
const [, owner, repo] = match;
const reserved = {
github: [
'settings', 'marketplace', 'explore', 'notifications', 'new',
'login', 'signup', 'organizations', 'orgs', 'features', 'pricing',
'sponsors', 'topics', 'trending', 'collections', 'events', 'about',
'security', 'customer-stories',
],
gitlab: ['explore', 'help', 'admin', 'dashboard', 'users', 'groups'],
bitbucket: ['account', 'repo', 'dashboard', 'product'],
};
if ((reserved[platform] || []).includes(owner)) return null;
const cleanRepo = repo.replace(/\.git$/, '');
const url = `https://${window.location.hostname}/${owner}/${cleanRepo}`;
return { owner, repo: cleanRepo, url, platform };
}
// --- GitHub API Context (via background script) ---
async function fetchRepoContextAPI(owner, repo) {
const cacheKey = `ghapi_${owner}_${repo}`;
const cached = await new Promise(r => chrome.storage.local.get([cacheKey], r));
if (cached[cacheKey] && (Date.now() - cached[cacheKey].ts < 3600000)) {
return cached[cacheKey].data;
}
try {
const response = await new Promise((resolve) => {
chrome.runtime.sendMessage({ action: 'fetch-repo-context', owner, repo }, resolve);
});
if (response?.context) {
chrome.storage.local.set({ [cacheKey]: { data: response.context, ts: Date.now() } });
return response.context;
}
return null;
} catch {
return null;
}
}
// --- Stack Detection ---
function detectStack() {
const stacks = [];
const fileElements = document.querySelectorAll(
'[role="rowheader"] a, .js-navigation-open, .react-directory-row a, ' +
'.tree-item-file-name a, .file-name a, ' +
'td.filename a, [data-qa="file-name"] a'
);
const fileNames = new Set();
fileElements.forEach(el => {
const name = el.textContent.trim();
if (name) fileNames.add(name);
});
if (fileNames.has('package.json')) {
stacks.push('Node.js');
if (fileNames.has('tsconfig.json')) stacks.push('TypeScript');
if (fileNames.has('next.config.js') || fileNames.has('next.config.mjs') || fileNames.has('next.config.ts')) stacks.push('Next.js');
}
if (fileNames.has('requirements.txt') || fileNames.has('pyproject.toml') || fileNames.has('setup.py') || fileNames.has('Pipfile')) {
stacks.push('Python');
}
if (fileNames.has('Cargo.toml')) stacks.push('Rust');
if (fileNames.has('go.mod')) stacks.push('Go');
if (fileNames.has('Gemfile')) stacks.push('Ruby');
if (fileNames.has('build.gradle') || fileNames.has('pom.xml')) stacks.push('Java');
const hasDocker = fileNames.has('Dockerfile') || fileNames.has('docker-compose.yml') || fileNames.has('docker-compose.yaml');
return { stacks, hasDocker };
}
// --- Trust Info (GitHub only) ---
function parseTrustInfo(platform) {
if (platform !== 'github') return null;
const info = {};
const starLink = document.querySelector('a[href$="/stargazers"]');
if (starLink) {
const text = starLink.textContent.replace(/[^\d.k]/gi, '').trim();
if (text) info.stars = text;
}
const licenseLink = document.querySelector('a[data-analytics-event*="LICENSE"], a[href*="/blob/"][href*="LICENSE"]');
if (licenseLink) {
const text = licenseLink.textContent.trim();
if (text && text !== 'View license') info.license = text;
}
if (!info.license) {
const sidebarItems = document.querySelectorAll('.BorderGrid-cell');
sidebarItems.forEach(cell => {
const text = cell.textContent;
if (text.includes('License') || text.includes('license')) {
const match = text.match(/(MIT|Apache|GPL|BSD|ISC|MPL|LGPL|AGPL|Unlicense)[^\n]*/i);
if (match) info.license = match[0].trim();
}
});
}
const timeEl = document.querySelector('relative-time');
if (timeEl) {
info.lastCommit = timeEl.getAttribute('datetime')
? timeEl.textContent.trim()
: null;
}
return (info.stars || info.license || info.lastCommit) ? info : null;
}
// --- Commands ---
function getCommands(repoInfo, stackInfo, customTools) {
const { url, repo, owner } = repoInfo;
const { stacks, hasDocker } = stackInfo;
const stackLabel = stacks.length > 0 ? ` (${stacks.join(' + ')} project)` : '';
const dockerNote = hasDocker ? ' (Docker available)' : '';
const setupHint = stacks.includes('Python') ? ', create venv if needed' : '';
let terminalExtra = '';
if (stacks.includes('Node.js')) terminalExtra = ' && npm install';
else if (stacks.includes('Python')) terminalExtra = ' && python3 -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt 2>/dev/null; pip install -e . 2>/dev/null';
else if (stacks.includes('Rust')) terminalExtra = ' && cargo build';
else if (stacks.includes('Go')) terminalExtra = ' && go build ./...';
// Tool icons as inline SVG data URIs
const TOOL_ICONS = {
claude: `<svg viewBox="0 0 24 24" width="18" height="18" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M16.98 9.01 12 4.03 7.02 9.01 12 13.99l4.98-4.98Z" fill="#D97757"/><path d="m12 13.99-4.98 4.98L12 23.95l4.98-4.98L12 13.99Z" fill="#D97757" opacity=".6"/><path d="M7.02 9.01 2.04 13.99l4.98 4.98L12 13.99 7.02 9.01Z" fill="#D97757" opacity=".8"/><path d="M16.98 9.01 12 13.99l4.98 4.98 4.98-4.98-4.98-4.98Z" fill="#D97757" opacity=".8"/></svg>`,
cursor: `<svg viewBox="0 0 24 24" width="18" height="18" fill="none" xmlns="http://www.w3.org/2000/svg"><rect x="2" y="2" width="20" height="20" rx="4" fill="#1A1A2E"/><path d="M7 7l10 5-10 5V7z" fill="#00D4AA"/></svg>`,
codex: `<svg viewBox="0 0 24 24" width="18" height="18" fill="none" xmlns="http://www.w3.org/2000/svg"><rect x="2" y="2" width="20" height="20" rx="4" fill="#0D1117"/><path d="M12 6a5 5 0 0 0-5 5c0 1.5.7 2.8 1.7 3.7L8 18h8l-.7-3.3A5 5 0 0 0 17 11a5 5 0 0 0-5-5Z" fill="#58A6FF"/><circle cx="10" cy="10.5" r="1" fill="#fff"/><circle cx="14" cy="10.5" r="1" fill="#fff"/></svg>`,
};
const commands = [
{
id: 'claude',
label: 'Claude Code',
icon: TOOL_ICONS.claude,
command: `claude "clone ${url}${stackLabel} and set it up following the README${setupHint}${dockerNote}"`,
},
{
id: 'cursor',
label: 'Cursor',
icon: TOOL_ICONS.cursor,
command: `git clone ${url} && cd ${repo}${terminalExtra}`,
openUrl: `cursor://vscode.git/clone?url=${encodeURIComponent(url + '.git')}`,
},
{
id: 'codex',
label: 'Codex',
icon: TOOL_ICONS.codex,
command: `mkdir -p ${repo} && cd ${repo} && codex "clone ${url} here and set it up following the README"`,
},
];
(customTools || []).filter(t => t.enabled).forEach(tool => {
const rendered = tool.command
.replace(/\{url\}/g, url)
.replace(/\{owner\}/g, owner)
.replace(/\{repo\}/g, repo)
.replace(/\{stack\}/g, stacks.join(', ') || 'unknown');
commands.push({
id: tool.id,
label: tool.name,
icon: tool.icon || '🔧',
command: rendered,
});
});
return commands;
}
// --- NFT Emoji Share ---
const EMOJI_PACKS = {
animals: {
label: 'Animals',
tiers: {
common: ['🐱', '🐶', '🐸', '🐧', '🐝', '🦊', '🐻', '🐨', '🐼', '🐵'],
rare: ['🦄', '🐉', '🦩', '🦈', '🦅', '🐙', '🦜', '🐺'],
epic: ['🦖', '🐋', '🦁', '🦎', '🐲', '🦧'],
legendary: ['🐺', '🦤', '🐚', '🪼'],
},
},
space: {
label: 'Space',
tiers: {
common: ['⭐', '🌙', '☀️', '🌍', '🪨', '💫', '🌤️', '⚡', '🔥', '💧'],
rare: ['🪐', '☄️', '🌌', '🌑', '🛰️', '🔭', '🌠', '🌊'],
epic: ['🛸', '🌋', '🧊', '🌪️', '🕳️', '💥'],
legendary: ['🪬', '⚛️', '🫧', '🌀'],
},
},
food: {
label: 'Food',
tiers: {
common: ['🍕', '🍔', '🌮', '🍜', '🍩', '🧁', '🍪', '🍿', '🥐', '🍣'],
rare: ['🍱', '🥘', '🫕', '🍰', '🎂', '🍫', '🧇', '🥮'],
epic: ['🍾', '🫖', '🍝', '🦪', '🥩', '🫔'],
legendary: ['🏺', '🫗', '🧉', '🪺'],
},
},
objects: {
label: 'Objects',
tiers: {
common: ['🎸', '🎮', '📱', '💡', '🔑', '🎯', '🧲', '🔔', '📦', '🎁'],
rare: ['🔮', '🎭', '🏹', '⚔️', '🛡️', '🎪', '🧿', '🪄'],
epic: ['⚗️', '🗿', '🧬', '💎', '🪩', '🔱'],
legendary: ['👑', '💀', '🏆', '🪦'],
},
},
};
const TIER_CONFIG = {
common: { odds: 0.60, label: 'Common' },
rare: { odds: 0.25, label: 'Rare' },
epic: { odds: 0.10, label: 'Epic' },
legendary: { odds: 0.05, label: 'Legendary' },
};
function rollEmoji(packName) {
const pack = EMOJI_PACKS[packName] || EMOJI_PACKS.animals;
const roll = Math.random();
let cumulative = 0;
for (const [tier, config] of Object.entries(TIER_CONFIG)) {
cumulative += config.odds;
if (roll < cumulative) {
const emojis = pack.tiers[tier];
const emoji = emojis[Math.floor(Math.random() * emojis.length)];
return { emoji, tier, label: config.label };
}
}
const fb = pack.tiers.common;
return { emoji: fb[0], tier: 'common', label: 'Common' };
}
// --- NFT Stats ---
function recordRoll(nft, repoUrl) {
chrome.storage.sync.get({ nftStats: { total: 0, tiers: {}, history: [] } }, (data) => {
const stats = data.nftStats;
stats.total++;
stats.tiers[nft.tier] = (stats.tiers[nft.tier] || 0) + 1;
// Keep last 10 shares
stats.history.unshift({
emoji: nft.emoji,
tier: nft.tier,
repo: repoUrl.replace(/^https?:\/\/[^/]+\//, ''),
time: Date.now(),
});
if (stats.history.length > 10) stats.history.length = 10;
chrome.storage.sync.set({ nftStats: stats });
});
}
// --- Share ---
async function copyEmojiShare(emoji, url, shareTemplate) {
const shortUrl = url.replace(/^https?:\/\/[^/]+\//, '');
const repoName = url.split('/').slice(-1)[0];
let plain;
if (shareTemplate) {
plain = shareTemplate
.replace(/\{emoji\}/g, emoji)
.replace(/\{url\}/g, shortUrl)
.replace(/\{fullurl\}/g, url)
.replace(/\{repo\}/g, repoName);
} else {
plain = `${emoji} ${repoName} — ${url}`;
}
const html = `${emoji} <a href="${url}">${repoName}</a>`;
try {
await navigator.clipboard.write([
new ClipboardItem({
'text/html': new Blob([html], { type: 'text/html' }),
'text/plain': new Blob([plain], { type: 'text/plain' }),
}),
]);
return true;
} catch {
return copyToClipboard(plain);
}
}
// --- README Badge Detection ---
function detectSmileBadge() {
// Check if README contains an "Install with AI" badge
const readme = document.querySelector('#readme, [data-testid="readme"], .readme-content');
if (!readme) return false;
const html = readme.innerHTML;
return html.includes('Install_with-AI') || html.includes('Install with AI') || html.includes('ai-install');
}
// --- Clipboard ---
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
const ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
const ok = document.execCommand('copy');
document.body.removeChild(ta);
return ok;
}
}
function showFeedback(btn, text) {
const original = btn.innerHTML;
btn.innerHTML = `<span class="ai-install-icon">✓</span> ${text || 'Copied!'}`;
btn.classList.add('ai-install-copied');
setTimeout(() => {
btn.innerHTML = original;
btn.classList.remove('ai-install-copied');
}, 1500);
}
function showCopiedFeedback(btn) {
showFeedback(btn, 'Copied!');
}
function showSharePicker(shareItem, nft, repoUrl, shareTemplate) {
// Remove existing picker
const oldPicker = shareItem.parentElement?.querySelector('.ai-install-share-picker');
if (oldPicker) oldPicker.remove();
const targets = [
{ icon: '✈️', label: 'Telegram', url: `https://t.me/share/url?url=${encodeURIComponent(repoUrl)}&text=${encodeURIComponent(nft.emoji)}` },
{ icon: '💬', label: 'WhatsApp', url: `https://wa.me/?text=${encodeURIComponent(nft.emoji + ' ' + repoUrl)}` },
{ icon: '𝕏', label: 'Twitter', url: `https://x.com/intent/tweet?text=${encodeURIComponent(nft.emoji + ' ' + repoUrl)}` },
{ icon: '📋', label: 'Copy', action: 'copy' },
];
const picker = document.createElement('div');
picker.className = 'ai-install-share-picker';
for (const t of targets) {
const btn = document.createElement('button');
btn.className = 'ai-install-share-btn';
btn.title = t.label;
btn.innerHTML = `<span>${t.icon}</span>`;
btn.addEventListener('click', async (e) => {
e.stopPropagation();
if (t.action === 'copy') {
await copyEmojiShare(nft.emoji, repoUrl, shareTemplate);
btn.innerHTML = '<span>✓</span>';
setTimeout(() => closeDropdown(), 600);
} else {
window.open(t.url, '_blank');
closeDropdown();
}
});
picker.appendChild(btn);
}
// Insert right after the share button
shareItem.insertAdjacentElement('afterend', picker);
}
// --- Execute via Background ---
const TOOL_HINTS = {
claude: 'Command copied! Paste into your terminal to start.',
cursor: 'Opening in Cursor — repo will clone automatically.',
codex: 'Codex opened. Repo URL copied — paste it in Codex.',
custom: 'Command copied! Paste into your terminal.',
};
function showToast(text) {
const existing = document.querySelector('.ai-install-toast');
if (existing) existing.remove();
const toast = document.createElement('div');
toast.className = 'ai-install-toast';
toast.textContent = text;
document.body.appendChild(toast);
setTimeout(() => toast.classList.add('ai-install-toast-visible'), 10);
setTimeout(() => {
toast.classList.remove('ai-install-toast-visible');
setTimeout(() => toast.remove(), 300);
}, 3000);
}
async function executeOrCopy(toolId, command, url, btn, openUrl, opts = {}) {
// If tool has a direct URL scheme (e.g. Cursor), open it directly
if (openUrl) {
window.open(openUrl, '_self');
showFeedback(btn, 'Opening...');
showToast(TOOL_HINTS[toolId] || 'Opening...');
chrome.runtime.sendMessage({ action: 'track-install', tool: toolId });
return;
}
// Try to auto-execute via native host
if (toolId) {
try {
const result = await chrome.runtime.sendMessage({
action: 'execute',
toolId,
command,
url,
});
if (result && result.success) {
const label = result.app ? `Sent to ${result.app}` : 'Opened';
showFeedback(btn, `${label} ✓`);
showToast(TOOL_HINTS[toolId] || `${label} ✓`);
return; // already tracked in background.js
}
} catch {
// native host not available — fall through to copy
}
}
// Fallback → copy to clipboard
await copyToClipboard(command);
showCopiedFeedback(btn);
showToast(TOOL_HINTS[toolId] || 'Command copied! Paste into your terminal.');
chrome.runtime.sendMessage({ action: 'track-install', tool: toolId });
}
// --- Confirm Modal ---
function showInstallConfirm(repoName, toolLabel, toolIcon) {
return new Promise((resolve) => {
const overlay = document.createElement('div');
overlay.className = 'ai-install-confirm-overlay';
const modal = document.createElement('div');
modal.className = 'ai-install-confirm-modal';
const iconEl = document.createElement('div');
iconEl.className = 'ai-install-confirm-icon';
if (toolIcon.startsWith('<svg')) {
iconEl.innerHTML = toolIcon;
} else {
iconEl.textContent = toolIcon;
}
const titleEl = document.createElement('div');
titleEl.className = 'ai-install-confirm-title';
titleEl.textContent = `Install with ${toolLabel}?`;
const repoEl = document.createElement('div');
repoEl.className = 'ai-install-confirm-repo';
repoEl.textContent = repoName;
const actions = document.createElement('div');
actions.className = 'ai-install-confirm-actions';
const cancelBtn = document.createElement('button');
cancelBtn.className = 'ai-install-confirm-btn ai-install-confirm-cancel';
cancelBtn.textContent = 'Cancel';
const okBtn = document.createElement('button');
okBtn.className = 'ai-install-confirm-btn ai-install-confirm-ok';
okBtn.textContent = '\u26A1 Install';
actions.append(cancelBtn, okBtn);
modal.append(iconEl, titleEl, repoEl, actions);
overlay.appendChild(modal);
document.body.appendChild(overlay);
const cleanup = (result) => {
overlay.classList.add('ai-install-confirm-closing');
setTimeout(() => { overlay.remove(); resolve(result); }, 150);
};
cancelBtn.addEventListener('click', () => cleanup(false));
okBtn.addEventListener('click', () => cleanup(true));
overlay.addEventListener('click', (e) => { if (e.target === overlay) cleanup(false); });
});
}
// --- Add Custom Tool Modal ---
const TOOL_PRESETS = [
{ name: 'Windsurf', icon: '🌊', command: 'windsurf clone {url}' },
{ name: 'Antigravity', icon: '🅰️', command: 'antigravity clone {url}' },
{ name: 'JetBrains AI', icon: '🧠', command: 'jetbrains clone {url}' },
{ name: 'Gemini', icon: '✦', command: 'gemini clone {url}' },
{ name: 'Copilot', icon: '🤖', command: 'gh copilot clone {url}' },
{ name: 'OpenCode', icon: '📟', command: 'opencode clone {url}' },
{ name: 'Kiro', icon: '👾', command: 'kiro clone {url}' },
{ name: 'Zed', icon: '⚡', command: 'zed clone {url}' },
{ name: 'Aider', icon: '🛠️', command: 'git clone {url} && cd {repo} && aider' },
{ name: 'Amp', icon: '📡', command: 'amp clone {url}' },
{ name: 'Augment', icon: '🔮', command: 'augment clone {url}' },
{ name: 'VS Code', icon: '💠', command: 'code --folder-uri vscode://vscode.git/clone?url={url}' },
{ name: 'Warp', icon: '🚀', command: 'warp clone {url}' },
{ name: 'Ollama', icon: '🦙', command: 'git clone {url} && cd {repo} && ollama run' },
{ name: 'Vertex AI', icon: '🔷', command: 'vertexai clone {url}' },
{ name: 'Droid', icon: '⚙️', command: 'droid clone {url}' },
{ name: 'z.ai', icon: '🇿', command: 'zai clone {url}' },
{ name: 'MiniMax', icon: '📊', command: 'minimax clone {url}' },
{ name: 'Kimi', icon: '🇰', command: 'kimi clone {url}' },
{ name: 'Kimi K2', icon: '🇰', command: 'kimik2 clone {url}' },
{ name: 'Kilo', icon: '🔣', command: 'kilo clone {url}' },
{ name: 'Alibaba', icon: '☁️', command: 'alibaba clone {url}' },
{ name: 'Synthetic', icon: '✿', command: 'synthetic clone {url}' },
{ name: 'OpenRouter', icon: '🔀', command: 'openrouter clone {url}' },
{ name: 'Terminal', icon: '🖥️', command: 'git clone {url} && cd {repo}' },
];
function showAddToolModal(onSave) {
const overlay = document.createElement('div');
overlay.className = 'ai-install-confirm-overlay';
const modal = document.createElement('div');
modal.className = 'ai-install-confirm-modal ai-install-tool-modal';
const title = document.createElement('div');
title.className = 'ai-install-confirm-title';
title.textContent = 'Add Custom Tool';
// Presets grid
const presetsLabel = document.createElement('div');
presetsLabel.className = 'ai-install-tool-presets-label';
presetsLabel.textContent = 'Quick add';
const presetsGrid = document.createElement('div');
presetsGrid.className = 'ai-install-tool-presets';
TOOL_PRESETS.forEach(preset => {
const btn = document.createElement('button');
btn.className = 'ai-install-tool-preset-btn';
btn.innerHTML = `<span class="ai-install-preset-icon">${preset.icon}</span><span class="ai-install-preset-name">${preset.name}</span>`;
btn.addEventListener('click', () => {
nameInput.value = preset.name;
iconInput.value = preset.icon;
cmdInput.value = preset.command;
});
presetsGrid.appendChild(btn);
});
// Divider
const orDiv = document.createElement('div');
orDiv.className = 'ai-install-tool-or';
orDiv.textContent = 'or customize';
const form = document.createElement('div');
form.className = 'ai-install-tool-form';
// Name + Icon row
const nameRow = document.createElement('div');
nameRow.className = 'ai-install-tool-row';
const nameInput = document.createElement('input');
nameInput.className = 'ai-install-tool-input';
nameInput.placeholder = 'Name';
nameInput.maxLength = 20;
const iconInput = document.createElement('input');
iconInput.className = 'ai-install-tool-input ai-install-tool-icon-input';
iconInput.placeholder = '🔧';
iconInput.maxLength = 2;
nameRow.append(nameInput, iconInput);
// Command
const cmdInput = document.createElement('textarea');
cmdInput.className = 'ai-install-tool-textarea';
cmdInput.placeholder = 'Command: {url}, {owner}, {repo}, {stack}';
cmdInput.rows = 2;
// Actions
const actions = document.createElement('div');
actions.className = 'ai-install-confirm-actions';
const cancelBtn = document.createElement('button');
cancelBtn.className = 'ai-install-confirm-btn ai-install-confirm-cancel';
cancelBtn.textContent = 'Cancel';
const saveBtn = document.createElement('button');
saveBtn.className = 'ai-install-confirm-btn ai-install-confirm-ok';
saveBtn.textContent = 'Save';
actions.append(cancelBtn, saveBtn);
form.append(nameRow, cmdInput);
modal.append(title, presetsLabel, presetsGrid, orDiv, form, actions);
overlay.appendChild(modal);
document.body.appendChild(overlay);
const cleanup = () => {
overlay.classList.add('ai-install-confirm-closing');
setTimeout(() => overlay.remove(), 150);
};
cancelBtn.addEventListener('click', cleanup);
overlay.addEventListener('click', (e) => { if (e.target === overlay) cleanup(); });
saveBtn.addEventListener('click', () => {
const name = nameInput.value.trim();
const icon = iconInput.value.trim() || '🔧';
const command = cmdInput.value.trim();
if (!name || !command) return;
onSave({ id: 'tool_' + Date.now(), name, icon, command, enabled: true });
cleanup();
showToast(`${icon} ${name} added! Reopen dropdown to use it.`);
});
}
// --- README Extraction ---
function getReadmeText() {
const readme = document.querySelector(
'#readme article, [data-testid="readme"] article, ' +
'#readme .markdown-body, #readme .Box-body, ' +
'#readme, [data-testid="readme"], .readme-content, ' +
'.markdown-body.entry-content'
);
if (!readme) return null;
const clone = readme.cloneNode(true);
clone.querySelectorAll('nav, img, svg, .anchor, .octicon, .zeroclipboard-container, details').forEach(el => el.remove());
const text = clone.textContent.replace(/\s+/g, ' ').trim();
return text ? text.slice(0, 4000) : null;
}
// --- Full Repo Context ---
function getRepoContextDOM(repoInfo, stackInfo) {
const parts = [];
// 1. About / description
const aboutEl = document.querySelector('.f4.my-3, .BorderGrid-cell p, [itemprop="about"]');
if (aboutEl) {
const about = aboutEl.textContent.trim();
if (about) parts.push(`About: ${about}`);
}
// 2. Topics / tags
const topicEls = document.querySelectorAll('.topic-tag, a[data-octo-click="topic_click"], [data-testid="topic"]');
const topics = [...topicEls].map(el => el.textContent.trim()).filter(Boolean);
if (topics.length) parts.push(`Topics: ${topics.join(', ')}`);
// 3. Stack info
if (stackInfo.stacks.length) parts.push(`Detected stack: ${stackInfo.stacks.join(', ')}`);
if (stackInfo.hasDocker) parts.push('Has Docker support');
// 4. File tree from DOM
const fileEls = document.querySelectorAll(
'[role="rowheader"] a, .js-navigation-open, .react-directory-row a, ' +
'.tree-item-file-name a, .file-name a, td.filename a, [data-qa="file-name"] a, ' +
'a.Link--primary[title]'
);
const files = [];
fileEls.forEach(el => {
const name = el.textContent.trim();
if (name && !name.includes(' ') && name.length < 80) files.push(name);
});
const uniqueFiles = [...new Set(files)];
if (uniqueFiles.length) parts.push(`Files in root: ${uniqueFiles.join(', ')}`);
// 5. Sidebar stats
const statsItems = document.querySelectorAll('.BorderGrid-cell');
statsItems.forEach(cell => {
const text = cell.textContent.trim().replace(/\s+/g, ' ');
if (text.includes('star')) {
const m = text.match(/([\d,.kKmM]+)\s*stars?/i);
if (m) parts.push(`Stars: ${m[1]}`);
}
if (text.includes('fork')) {
const m = text.match(/([\d,.kKmM]+)\s*forks?/i);
if (m) parts.push(`Forks: ${m[1]}`);
}
if (text.includes('License') || text.includes('license')) {
const m = text.match(/(MIT|Apache|GPL|BSD|ISC|MPL|LGPL|AGPL|Unlicense)[^\n]*/i);
if (m) parts.push(`License: ${m[0].trim()}`);
}
});
// 6. Languages bar
const langEls = document.querySelectorAll('[aria-label="Repository languages"] li, .repository-lang-stats-graph span, .Progress + ul li');
const langs = [];
langEls.forEach(el => {
const text = el.textContent.trim().replace(/\s+/g, ' ');
if (text) langs.push(text);
});
if (langs.length) parts.push(`Languages: ${langs.join(', ')}`);
// 7. README text
const readmeText = getReadmeText();
if (readmeText) parts.push(`README:\n${readmeText}`);
return parts.join('\n') || null;
}
async function getRepoContext(repoInfo, stackInfo) {
// Try GitHub API first (richer data, no DOM fragility)
if (repoInfo.platform === 'github') {
const apiContext = await fetchRepoContextAPI(repoInfo.owner, repoInfo.repo);
if (apiContext) return apiContext;
}
// Fallback to DOM scraping
return getRepoContextDOM(repoInfo, stackInfo);
}
// --- Quick Summary ---
function getBasicSummary(repoInfo, stackInfo) {
const aboutEl = document.querySelector('.f4.my-3, .BorderGrid-cell p, [itemprop="about"]');
const about = aboutEl ? aboutEl.textContent.trim() : '';
const readme = document.querySelector('#readme, [data-testid="readme"], .readme-content');
let firstPara = '';
if (readme) {
const p = readme.querySelector('p');
if (p) firstPara = p.textContent.trim().slice(0, 200);
}
const stacks = stackInfo.stacks.length > 0 ? `Stack: ${stackInfo.stacks.join(', ')}` : '';
let summary = '';
if (about) summary += about + '\n\n';
if (firstPara && firstPara !== about) summary += firstPara + '\n\n';
if (stacks) summary += stacks;
return summary.trim() || 'No description available for this repository.';
}
function showRepoSummary(dropdown, repoInfo, stackInfo) {
// Toggle existing panel
const existing = dropdown.querySelector('.ai-install-summary-panel');
if (existing) { existing.remove(); return; }
const panel = document.createElement('div');
panel.className = 'ai-install-summary-panel';
panel.style.position = 'relative';
const closeBtn = document.createElement('button');
closeBtn.className = 'ai-install-panel-close';
closeBtn.textContent = '\u00D7';
closeBtn.addEventListener('click', (e) => { e.stopPropagation(); panel.remove(); });
panel.appendChild(closeBtn);
const cacheKey = `summary_${repoInfo.owner}_${repoInfo.repo}`;
// Insert before chat panel if it exists, otherwise append
const chatPanel = dropdown.querySelector('.ai-install-chat-panel');
if (chatPanel) {
dropdown.insertBefore(panel, chatPanel);
} else {
dropdown.appendChild(panel);
}
function setPanelText(text) {
// Remove everything except close button, then add text
[...panel.childNodes].forEach(n => { if (n !== closeBtn) n.remove(); });
const content = document.createElement('span');
content.textContent = text;
panel.appendChild(content);
}
// Check cache first
chrome.storage.local.get([cacheKey], async (data) => {
const cached = data[cacheKey];
if (cached && (Date.now() - cached.ts < 24 * 60 * 60 * 1000)) {
setPanelText(cached.text);
return;
}
// Show loading
[...panel.childNodes].forEach(n => { if (n !== closeBtn) n.remove(); });
const spinner = document.createElement('div');
spinner.className = 'ai-install-summary-loading';
spinner.textContent = 'Generating summary...';
panel.appendChild(spinner);
const context = await getRepoContext(repoInfo, stackInfo);
if (!context) {
setPanelText('No repo info found on this page.');
return;
}
chrome.runtime.sendMessage({
action: 'summarize',
readmeText: context,
repoName: `${repoInfo.owner}/${repoInfo.repo}`,
userLang: navigator.language || 'en',
}, (response) => {
if (response && response.summary) {
setPanelText(response.summary);
chrome.storage.local.set({ [cacheKey]: { text: response.summary, ts: Date.now() } });
} else {
const basic = getBasicSummary(repoInfo, stackInfo);
setPanelText(basic);
if (response?.error) {
const hint = document.createElement('div');
hint.className = 'ai-install-summary-hint';
hint.textContent = response.error;
panel.appendChild(hint);
}
}
});
});
}
// --- Repo Chat ---
function showRepoChat(dropdown, repoInfo, stackInfo) {
const existing = dropdown.querySelector('.ai-install-chat-panel');
if (existing) { existing.remove(); return; }
const panel = document.createElement('div');
panel.className = 'ai-install-chat-panel';
panel.style.position = 'relative';
const closeBtn = document.createElement('button');
closeBtn.className = 'ai-install-panel-close';
closeBtn.textContent = '✕';
closeBtn.addEventListener('click', (e) => {
e.stopPropagation();
panel.remove();
});
panel.appendChild(closeBtn);
// Model selector bar
const modelBar = document.createElement('div');
modelBar.className = 'ai-install-chat-model-bar';
let selectedModel = 'haiku';
chrome.runtime.sendMessage({ action: 'get-models' }, (resp) => {
if (!resp?.models) return;
resp.models.forEach((m) => {
const btn = document.createElement('button');
btn.className = 'ai-install-chat-model-btn';
if (m.id === selectedModel) btn.classList.add('ai-install-chat-model-active');
btn.textContent = m.label;
if (!m.available) {
btn.classList.add('ai-install-chat-model-locked');
btn.title = 'Requires API key in settings';
}
btn.addEventListener('click', (e) => {
e.stopPropagation();
if (!m.available) {
btn.style.animation = 'none';
btn.offsetHeight; // force reflow
btn.style.animation = 'ai-install-shake 0.3s ease';
addMessage('assistant', `🔑 ${m.label} requires your Claude API key. Add it in extension settings.`);
return;
}
selectedModel = m.id;
modelBar.querySelectorAll('.ai-install-chat-model-btn').forEach(b => b.classList.remove('ai-install-chat-model-active'));
btn.classList.add('ai-install-chat-model-active');
addMessage('assistant', `Switched to ${m.label}`);
});
modelBar.appendChild(btn);
});
});
const messages = document.createElement('div');
messages.className = 'ai-install-chat-messages';
const inputRow = document.createElement('div');
inputRow.className = 'ai-install-chat-input-row';
const input = document.createElement('input');
input.type = 'text';
input.className = 'ai-install-chat-input';
input.placeholder = 'Ask about this repo...';
const sendBtn = document.createElement('button');
sendBtn.className = 'ai-install-chat-send';
sendBtn.textContent = '→';
inputRow.append(input, sendBtn);
panel.append(modelBar, messages, inputRow);
dropdown.appendChild(panel);
let repoContext = '';
const repoContextReady = getRepoContext(repoInfo, stackInfo).then(ctx => { repoContext = ctx || ''; });
const conversationHistory = [];
function renderMarkdown(text) {
return text
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
.replace(/`(.+?)`/g, '<code>$1</code>')
.replace(/\n• /g, '<br><span class="ai-install-chat-bullet">•</span> ')
.replace(/\n\n/g, '<br><br>')
.replace(/\n/g, '<br>');
}
function addMessage(role, text) {
const msg = document.createElement('div');
msg.className = `ai-install-chat-msg ai-install-chat-${role}`;
if (role === 'assistant') {
msg.innerHTML = renderMarkdown(text);
} else {
msg.textContent = text;
}
messages.appendChild(msg);
messages.scrollTop = messages.scrollHeight;
}
function addTyping() {
const msg = document.createElement('div');
msg.className = 'ai-install-chat-msg ai-install-chat-assistant ai-install-chat-typing';
msg.textContent = '...';
messages.appendChild(msg);
messages.scrollTop = messages.scrollHeight;
return msg;
}
async function sendMessage() {
const text = input.value.trim();
if (!text) return;
input.value = '';
addMessage('user', text);
conversationHistory.push({ role: 'user', content: text });
const typingEl = addTyping();
chrome.runtime.sendMessage({
action: 'chat',
messages: conversationHistory,
readmeText: repoContext,
repoName: `${repoInfo.owner}/${repoInfo.repo}`,
stacks: stackInfo.stacks,
model: selectedModel,
}, (response) => {
typingEl.remove();
if (response && response.reply) {
addMessage('assistant', response.reply);
conversationHistory.push({ role: 'assistant', content: response.reply });
} else {
addMessage('assistant', response?.error || 'Failed to get response.');
}
});
}
sendBtn.addEventListener('click', (e) => { e.stopPropagation(); sendMessage(); });
input.addEventListener('keydown', (e) => {
e.stopPropagation();
if (e.key === 'Enter') sendMessage();
});
input.addEventListener('click', (e) => e.stopPropagation());
addMessage('assistant', 'Loading repo context...');
repoContextReady.then(() => {
// Replace loading message with actual status
const lastMsg = messages.querySelector('.ai-install-chat-assistant:last-child');
if (lastMsg) {
const hasContext = !!repoContext;
lastMsg.innerHTML = renderMarkdown(hasContext
? `Ready! I've analyzed ${repoInfo.owner}/${repoInfo.repo} — files, README, topics, languages. Ask me anything.`
: `No repo info found on this page. I can only answer general questions about ${repoInfo.owner}/${repoInfo.repo}.`);
}
});
setTimeout(() => input.focus(), 100);
}
// --- Dropdown ---
function closeDropdown() {
const existing = document.getElementById(DROPDOWN_ID);
if (existing) existing.remove();
}
function createDropdown(repoInfo, anchorBtn, options = {}) {
closeDropdown();
const dropdown = document.createElement('div');
dropdown.id = DROPDOWN_ID;