Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
1552 lines (1361 loc) · 59.7 KB
/
Copy pathbackground.js
File metadata and controls
1552 lines (1361 loc) · 59.7 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
// background.js - Chrome Extension Service Worker
// OpenAI-compatible API calls + File System Access API for vault
const STORAGE_KEYS = {
API_KEY: 'claude_api_key',
MODEL: 'claude_model',
PROVIDER: 'claude_provider',
BASE_URL: 'openagent_base_url',
SYSTEM_PROMPT: 'claude_system_prompt',
THEME: 'claude_theme',
PRESET: 'claude_preset',
LANGUAGE: 'claude_language',
VAULT_NAME: 'openagent_vault_name',
VAULT_API_URL: 'openagent_vault_api_url',
VAULT_API_TOKEN: 'openagent_vault_api_token',
VAULT_HANDLE: 'openagent_vault_handle',
AUTO_VAULT: 'openagent_auto_vault',
FONT_SIZE: 'openagent_font_size',
WEB_SEARCH: 'openagent_web_search',
WEB_SEARCH_PROVIDER: 'openagent_web_search_provider',
WEB_SEARCH_API_KEY: 'openagent_web_search_api_key',
};
const DEFAULT_BASE_URL = 'https://openrouter.ai/api/v1';
function normalizeBaseUrl(url) {
if (!url) return DEFAULT_BASE_URL;
return url.replace(/\/+$/, '');
}
function isOpenRouter(baseUrl) {
return normalizeBaseUrl(baseUrl) === DEFAULT_BASE_URL || normalizeBaseUrl(baseUrl).includes('openrouter.ai');
}
const HTTPS_RE = /^https?:\/\//;
const injectedTabs = new Set();
// ─── Loop Detection ───────────────────────────────────────────────────────────
const LOOP_WINDOW = 10;
const LOOP_FINGERPRINT_AGE_MS = 30000;
let _actionHistory = [];
let _pageFingerprints = [];
function _hashStr(str) {
let h = 0;
for (let i = 0; i < str.length; i++) {
h = ((h << 5) - h) + str.charCodeAt(i);
h = h & h;
}
return String(h >>> 0);
}
function _computeFingerprint(domTree, pageContext) {
if (!domTree?.elements) return null;
const sigs = domTree.elements
.filter(el => el.highlightIndex != null)
.slice(0, 20)
.map(el => `${el.highlightIndex}:${el.tagName}:${(el.text || '').slice(0, 20)}`)
.join('|');
return _hashStr(sigs + (pageContext?.metadata?.url || ''));
}
function _computeActionHash(tag) {
const m = tag.match(/^(\w+:\d*):?/);
return _hashStr(m ? m[1] : tag);
}
function _checkLoop(tag, domTree, pageContext) {
const now = Date.now();
const actHash = _computeActionHash(tag);
const fp = _computeFingerprint(domTree, pageContext);
_pageFingerprints = _pageFingerprints.filter(p => now - p.t < LOOP_FINGERPRINT_AGE_MS);
const recent = _actionHistory.filter(a => now - a.t < LOOP_FINGERPRINT_AGE_MS);
const sameCount = recent.filter(a => a.h === actHash).length;
const pageSame = fp && _pageFingerprints.some(p => p.f === fp && p.u === (pageContext?.metadata?.url || ''));
if ((sameCount >= 3 && pageSame) || sameCount >= 5) {
return {
isLoop: true,
reason: sameCount >= 5
? `Same action "${tag}" repeated ${sameCount}x. Consider a different approach.`
: `Same action "${tag}" repeated ${sameCount}x with no page change. Try scrolling or a different element.`
};
}
_actionHistory.push({ h: actHash, t: now });
_actionHistory = _actionHistory.slice(-LOOP_WINDOW);
if (fp) {
_pageFingerprints.push({ f: fp, u: pageContext?.metadata?.url || '', t: now });
_pageFingerprints = _pageFingerprints.slice(-LOOP_WINDOW);
}
return { isLoop: false };
}
function _resetLoopState() {
_actionHistory = [];
}
// ─── Message Compaction ───────────────────────────────────────────────────────
const COMPACTION_THRESHOLD = 25;
const COMPACTION_BLOCK = 10;
async function _compactHistory(history, apiKey, baseUrl) {
if (!history || history.length < COMPACTION_THRESHOLD) return history;
const sys = history.filter(m => m.role === 'system');
const conv = history.filter(m => m.role === 'user' || m.role === 'assistant');
if (conv.length < COMPACTION_THRESHOLD) return history;
const compact = [...sys];
const toCompact = conv.slice(0, -COMPACTION_BLOCK);
const kept = conv.slice(-COMPACTION_BLOCK);
for (let i = 0; i < toCompact.length; i += COMPACTION_BLOCK) {
const block = toCompact.slice(i, i + COMPACTION_BLOCK);
const text = block.map(m => `${m.role}: ${typeof m.content === 'string' ? m.content.slice(0, 500) : '[content]'}`).join('\n');
try {
const resp = await fetch(baseUrl + '/chat/completions', {
method: 'POST',
headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'openai/gpt-4o-mini',
messages: [{ role: 'user', content: `Summarize this in 2-3 sentences. Return ONLY the summary text:\n\n${text}` }],
max_tokens: 150,
}),
});
const data = await resp.json();
const summary = data.choices?.[0]?.message?.content?.trim() || '[earlier conversation]';
compact.push({ role: 'system', content: `[Earlier: ${summary}]` });
} catch {
compact.push(...block);
}
}
compact.push(...kept);
return compact;
}
chrome.tabs.onRemoved.addListener((tabId) => {
injectedTabs.delete(tabId);
});
const DEFAULT_SYSTEM_PROMPT = "You are OpenAgent, an AI browser assistant. Your primary purpose is to help users with the currently open webpage. When a user asks a question, use the page context provided. You can read page content, execute browser actions, and help with web-related tasks. If no page context is provided, explain that you work best when viewing a webpage. NEVER offer to save information, NEVER ask if something should be saved, and NEVER list \"save options\" at the end of responses. The conversation is saved automatically when Obsidian is connected. Focus entirely on answering the user's question.";
chrome.tabs.onActivated.addListener(async (activeInfo) => {
if (!injectedTabs.has(activeInfo.tabId)) {
await injectIntoTab(activeInfo.tabId);
}
const tab = await chrome.tabs.get(activeInfo.tabId).catch(() => null);
await notifyContextRefresh(activeInfo.tabId, tab?.url);
});
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete' && tab.active && tab.url?.startsWith('http')) {
await notifyContextRefresh(tabId, tab.url);
}
});
if (chrome.webNavigation && chrome.webNavigation.onCompleted) {
chrome.webNavigation.onCompleted.addListener(async (details) => {
if (!details.frameId && !injectedTabs.has(details.tabId)) {
await injectIntoTab(details.tabId);
await notifyContextRefresh(details.tabId, details.url);
}
}, { url: [{ schemes: ['http', 'https'] }] });
// SPA URL changes are detected by the content script via history API interception.
// It sends context.refresh on its own. No need for duplicate listeners here.
}
async function notifyContextRefresh(tabId, newUrl) {
if (!newUrl || !newUrl.startsWith('http')) return;
chrome.runtime.sendMessage({ type: 'context.refresh' }).catch(() => {});
}
chrome.tabs.query({ url: ['http://*/*', 'https://*/*'] }, async (tabs) => {
for (const tab of tabs) {
if (!injectedTabs.has(tab.id)) {
await injectIntoTab(tab.id);
}
}
});
async function injectIntoTab(tabId) {
if (!tabId) return;
if (injectedTabs.has(tabId)) return; // already injected, skip
injectedTabs.add(tabId);
try {
const tab = await chrome.tabs.get(tabId);
if (!tab.url || !tab.url.startsWith('http')) return;
// Don't inject into Chrome internal pages (webstore, settings, etc.)
if (tab.url.includes('chrome://') || tab.url.includes('chrome.google.com/webstore')) return;
await chrome.scripting.executeScript({
target: { tabId },
files: ['content.js'],
});
} catch (err) {
if (err.message && !err.message.includes('Cannot access contents') && !err.message.includes('gallery')) {
// Silent fail for cross-origin tabs
}
}
}
// ─── Helpers ────────────────────────────────────────────────────────────────
async function getWebTab() {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
return tab?.url?.startsWith('http') ? tab : null;
}
// ─── Message Router ───────────────────────────────────────────────────────────
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
const handlers = {
'settings.load': () => loadSettings(),
'settings.save': () => saveSettings(message.data),
'inject.content': () => injectContentScript(),
'page.collect': () => sendToContentScript('page.collect'),
'page.dom.snapshot': () => sendToContentScript('page.dom.snapshot'),
'page.dom.perform': () => sendToContentScript('page.dom.perform', { steps: message.steps }),
'page.highlight': () => sendToContentScript('page.highlight', { elements: message.elements }),
'page.highlight.remove': () => sendToContentScript('page.highlight.remove'),
'page.navigate': () => sendNavigateAction(message.url),
'prompt.send': () => handlePromptSend(message, sendResponse),
'conversation.clear': () => ({ ok: true }),
'context.tabs.list': () => listOpenTabs(),
'context.history.search': () => searchHistory(message.query),
'stream.start': () => startStream(message, sendResponse),
'vault.read': () => handleVaultRead(message),
'vault.write': () => handleVaultWrite(message),
'vault.pick': () => pickVaultDirectory(),
'autovault.load': () => loadAutoVault(),
'autovault.save': () => saveAutoVault(message.enabled),
'page.screenshot': () => capturePageScreenshot(),
'memory.load': () => handleMemoryLoad(message),
'memory.save': () => handleMemorySave(message),
'vault.api.test': () => vaultApiTest(message),
'vault.api.read': () => vaultApiRead(message),
'vault.api.write': () => vaultApiWrite(message),
'context.refresh': () => ({ ok: true }),
};
const handler = handlers[message.type];
if (!handler) return false;
const result = handler();
if (result instanceof Promise) {
result.then(sendResponse).catch((err) => sendResponse({ error: err.message }));
return true;
}
if (result !== undefined) sendResponse(result);
return true;
});
// ─── Content Script Communication ──────────────────────────────────────────────
async function injectContentScript() {
const tab = await getWebTab();
if (!tab?.id) return { error: 'No active web page tab found' };
try {
await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ['content.js'] });
return { ok: true, tabId: tab.id };
} catch (err) {
return { ok: true, tabId: tab.id };
}
}
async function sendToContentScript(type, payload) {
const tab = await getWebTab();
if (!tab?.id) return { error: 'No active web page tab found' };
try {
return await chrome.tabs.sendMessage(tab.id, { type, ...payload });
} catch (err) {
try {
await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ['content.js'] });
} catch (e) {}
try {
return await chrome.tabs.sendMessage(tab.id, { type, ...payload });
} catch (e) {
return { error: 'Cannot communicate with page. Try reloading the page.' };
}
}
}
async function sendNavigateAction(url) {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab?.id) return { error: 'No active tab found' };
try {
await chrome.tabs.update(tab.id, { url });
return { ok: true };
} catch (err) {
return { error: `Cannot navigate: ${err.message}` };
}
}
// ─── Screenshot ────────────────────────────────────────────────────────────────
async function capturePageScreenshot() {
const tab = await getWebTab();
if (!tab?.id) return { error: 'No active web page tab found' };
try {
const dataUrl = await chrome.tabs.captureVisibleTab(tab.windowId, { format: 'jpeg', quality: 70 });
return { ok: true, dataUrl };
} catch (err) {
return { error: `Screenshot failed: ${err.message}` };
}
}
// ─── Settings ─────────────────────────────────────────────────────────────────
async function loadSettings() {
const result = await chrome.storage.local.get(Object.values(STORAGE_KEYS));
return {
apiKey: result[STORAGE_KEYS.API_KEY] || '',
model: result[STORAGE_KEYS.MODEL] || '',
provider: result[STORAGE_KEYS.PROVIDER] || 'openrouter',
baseUrl: normalizeBaseUrl(result[STORAGE_KEYS.BASE_URL] || DEFAULT_BASE_URL),
systemPrompt: result[STORAGE_KEYS.SYSTEM_PROMPT] || '',
theme: result[STORAGE_KEYS.THEME] || 'dark',
preset: result[STORAGE_KEYS.PRESET] || 'default',
language: result[STORAGE_KEYS.LANGUAGE] || 'en',
vaultName: result[STORAGE_KEYS.VAULT_NAME] || '',
vaultApiUrl: result[STORAGE_KEYS.VAULT_API_URL] || '',
vaultApiToken: result[STORAGE_KEYS.VAULT_API_TOKEN] || '',
autoVault: result[STORAGE_KEYS.AUTO_VAULT] || false,
fontSize: result[STORAGE_KEYS.FONT_SIZE] || 'medium',
webSearch: result[STORAGE_KEYS.WEB_SEARCH] || false,
webSearchProvider: result[STORAGE_KEYS.WEB_SEARCH_PROVIDER] || 'openrouter',
webSearchApiKey: result[STORAGE_KEYS.WEB_SEARCH_API_KEY] || '',
};
}
async function saveSettings(data) {
await chrome.storage.local.set({
[STORAGE_KEYS.API_KEY]: data.apiKey || '',
[STORAGE_KEYS.MODEL]: data.model || '',
[STORAGE_KEYS.PROVIDER]: data.provider || 'openrouter',
[STORAGE_KEYS.BASE_URL]: normalizeBaseUrl(data.baseUrl || DEFAULT_BASE_URL),
[STORAGE_KEYS.SYSTEM_PROMPT]: data.systemPrompt || '',
[STORAGE_KEYS.THEME]: data.theme || 'dark',
[STORAGE_KEYS.PRESET]: data.preset || 'default',
[STORAGE_KEYS.LANGUAGE]: data.language || 'en',
[STORAGE_KEYS.VAULT_NAME]: data.vaultName || '',
[STORAGE_KEYS.VAULT_API_URL]: data.vaultApiUrl || '',
[STORAGE_KEYS.VAULT_API_TOKEN]: data.vaultApiToken || '',
[STORAGE_KEYS.FONT_SIZE]: data.fontSize || 'medium',
[STORAGE_KEYS.WEB_SEARCH]: data.webSearch || false,
[STORAGE_KEYS.WEB_SEARCH_PROVIDER]: data.webSearchProvider || 'openrouter',
[STORAGE_KEYS.WEB_SEARCH_API_KEY]: data.webSearchApiKey || '',
});
return { ok: true };
}
// ─── Web Search ──────────────────────────────────────────────────────────────
async function bravesearch(query, apiKey) {
try {
const resp = await fetch('https://api.search.brave.com/res/v1/web/search?q=' + encodeURIComponent(query) + '&count=5', {
headers: {
'Accept': 'application/json',
'Accept-Encoding': 'gzip',
'X-Subscription-Token': apiKey,
},
});
if (!resp.ok) return null;
const data = await resp.json();
const results = (data.web?.results || []).slice(0, 5);
if (results.length === 0) return null;
return '## Web Search Results (Brave)\n\n' + results.map((r, i) =>
`${i + 1}. **${r.title || 'Untitled'}**\n ${r.description || ''}\n URL: ${r.url || ''}`
).join('\n\n');
} catch {
return null;
}
}
async function serpapiSearch(query, apiKey) {
try {
const resp = await fetch('https://serpapi.com/search?q=' + encodeURIComponent(query) + '&api_key=' + encodeURIComponent(apiKey) + '&num=5');
if (!resp.ok) return null;
const data = await resp.json();
const results = (data.organic_results || []).slice(0, 5);
if (results.length === 0) return null;
return '## Web Search Results (SerpAPI)\n\n' + results.map((r, i) =>
`${i + 1}. **${r.title || 'Untitled'}**\n ${r.snippet || ''}\n URL: ${r.link || ''}`
).join('\n\n');
} catch {
return null;
}
}
async function tavilySearch(query, apiKey) {
try {
const resp = await fetch('https://api.tavily.com/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
body: JSON.stringify({ query, max_results: 5, include_answer: true, include_raw_content: false }),
});
if (!resp.ok) return null;
const data = await resp.json();
const results = (data.results || []).slice(0, 5);
if (results.length === 0 && !data.answer) return null;
let output = '## Web Search Results (Tavily)\n\n';
if (data.answer) output += `**AI Answer:** ${data.answer}\n\n`;
output += results.map((r, i) =>
`${i + 1}. **${r.title || 'Untitled'}**\n ${r.content || ''}\n URL: ${r.url || ''}`
).join('\n\n');
return output;
} catch {
return null;
}
}
async function performWebSearch(provider, query, apiKey) {
switch (provider) {
case 'brave': return await bravesearch(query, apiKey);
case 'serpapi': return await serpapiSearch(query, apiKey);
case 'tavily': return await tavilySearch(query, apiKey);
default: return null;
}
}
// ─── Prompt / Chat ─────────────────────────────────────────────────────────────
async function handlePromptSend(message, sendResponse) {
_resetLoopState();
const settings = await loadSettings();
if (!settings.apiKey) {
sendResponse({ error: 'API key not configured. Please set it in Settings.' });
return;
}
const { conversationHistory, pageContext, pageScreenshot, autoVault, vaultConnected, vaultName, vaultFilename, memoryContext, webSearch, vaultIntent, pageLinks, domTree } = message;
const compactHistory = await _compactHistory(conversationHistory, settings.apiKey, settings.baseUrl);
const msgs = await buildMessages(compactHistory, pageContext, pageScreenshot, settings.systemPrompt, autoVault, vaultConnected, vaultName, vaultFilename, memoryContext, webSearch, pageLinks, domTree);
const useOpenRouter = isOpenRouter(settings.baseUrl);
const webSearchProvider = settings.webSearchProvider || 'openrouter';
let tools = [];
if (webSearch && webSearchProvider === 'openrouter' && useOpenRouter) {
tools = [{
type: 'openrouter:web_search',
parameters: {
max_results: 5,
max_total_results: 15,
search_context_size: 'medium',
},
}];
} else if (webSearch) {
const apiKey = settings.webSearchApiKey || '';
if (apiKey) {
tools = [{
type: 'function',
function: {
name: 'web_search',
description: 'Search the web for current information. Use this when you need up-to-date facts, recent events, real-time data, or information beyond your training knowledge. Only call when the user asks about current or factual topics.',
parameters: {
type: 'object',
properties: {
query: {
type: 'string',
description: 'The search query. Be specific and concise for best results.'
}
},
required: ['query']
}
}
}];
}
}
const hasTools = tools.length > 0;
const headers = {
'Authorization': `Bearer ${settings.apiKey}`,
'Content-Type': 'application/json',
};
if (useOpenRouter) {
headers['HTTP-Referer'] = chrome.runtime.getURL('/');
headers['X-Title'] = 'OpenAgent Chrome Extension';
}
try {
// First API call
const response = await fetch(settings.baseUrl + '/chat/completions', {
method: 'POST',
headers,
body: JSON.stringify({
model: settings.model || 'openai/gpt-4o',
messages: msgs,
tools: hasTools ? tools : undefined,
tool_choice: hasTools ? 'auto' : undefined,
}),
});
if (!response.ok) {
const text = await response.text();
const errJson = (() => { try { return JSON.parse(text); } catch { return null; } })();
sendResponse({ error: `API error (${response.status}): ${errJson?.error?.message || text}` });
return;
}
let data = await response.json();
let message = data.choices?.[0]?.message;
// Handle tool calls — OpenRouter server tools (e.g. web_search) execute server-side
let maxIterations = 5;
while (message?.tool_calls && message.tool_calls.length > 0 && maxIterations > 0) {
maxIterations--;
let hasClientTool = false;
for (const toolCall of message.tool_calls) {
const toolName = toolCall.function?.name || toolCall.name || '';
const toolType = toolCall.type || '';
if (toolType === 'openrouter:web_search' || toolName === 'openrouter:web_search') {
const args = (() => { try { return JSON.parse(toolCall.function?.arguments || '{}'); } catch { return {}; } })();
msgs.push(message);
msgs.push({
role: 'tool',
tool_call_id: toolCall.id,
content: `Search executed for query: "${args.query || 'unknown'}". Results returned via OpenRouter server tool.`,
});
} else if (toolName === 'web_search') {
hasClientTool = true;
const args = (() => { try { return JSON.parse(toolCall.function?.arguments || '{}'); } catch { return {}; } })();
const apiKey = settings.webSearchApiKey || '';
const query = args.query || '';
let result = null;
if (apiKey && query) {
result = await performWebSearch(webSearchProvider, query, apiKey);
}
msgs.push(message);
msgs.push({
role: 'tool',
tool_call_id: toolCall.id,
content: result || `No results found for query: "${query}".`,
});
}
}
// Skip follow-up if all tool calls were OpenRouter server tools (handled server-side)
const allServerTools = message.tool_calls.every(tc => {
const n = tc.function?.name || tc.name || '';
const tp = tc.type || '';
return tp === 'openrouter:web_search' || n === 'openrouter:web_search';
});
if (!hasClientTool && allServerTools) {
// Server tool: follow-up to get the final response
const followUp = await fetch(settings.baseUrl + '/chat/completions', {
method: 'POST',
headers,
body: JSON.stringify({
model: settings.model || 'openai/gpt-4o',
messages: msgs,
tools: tools.length > 0 ? tools : undefined,
}),
});
if (!followUp.ok) {
const text = await followUp.text();
const errJson = (() => { try { return JSON.parse(text); } catch { return null; } })();
sendResponse({ error: `API error (${followUp.status}): ${errJson?.error?.message || text}` });
return;
}
data = await followUp.json();
message = data.choices?.[0]?.message;
continue;
}
// Client tool: follow-up with tool results
const followUp = await fetch(settings.baseUrl + '/chat/completions', {
method: 'POST',
headers,
body: JSON.stringify({
model: settings.model || 'openai/gpt-4o',
messages: msgs,
}),
});
if (!followUp.ok) {
const text = await followUp.text();
const errJson = (() => { try { return JSON.parse(text); } catch { return null; } })();
sendResponse({ error: `API error (${followUp.status}): ${errJson?.error?.message || text}` });
return;
}
data = await followUp.json();
message = data.choices?.[0]?.message;
}
const content = message?.content || '';
const actionResult = await parseAndExecuteAction(content, pageLinks, domTree, pageContext);
sendResponse({ content, actionResult });
} catch (err) {
sendResponse({ error: `Request failed: ${err.message}` });
}
}
// ─── Action Tag Parser ─────────────────────────────────────────────────────────
const ACTION_TAG_RE = /<action>([^<]+)<\/action>/gi;
function buildSelectors(element) {
const selectors = [];
if (element.href) {
selectors.push(`a[href="${element.href}"]`);
selectors.push(`a[href*="${element.href.split('/').pop()}"]`);
}
if (element.id) {
selectors.push(`#${element.id}`);
if (element.tagName) selectors.push(`#${element.id}${element.tagName.toLowerCase()}`);
}
if (element['data-testid']) selectors.push(`[data-testid="${element['data-testid']}"]`);
if (element['data-cy']) selectors.push(`[data-cy="${element['data-cy']}"]`);
if (element['data-test']) selectors.push(`[data-test="${element['data-test']}"]`);
if (element.type && element.tagName === 'input') selectors.push(`input[type="${element.type}"]`);
if (element.name) selectors.push(`[name="${element.name}"]`);
if (element.placeholder) selectors.push(`[placeholder="${element.placeholder}"]`);
if (element.role) selectors.push(`[role="${element.role}"]`);
if (element['aria-label']) selectors.push(`[aria-label="${element['aria-label']}"]`);
if (element.tagName) {
const tag = element.tagName.toLowerCase();
selectors.push(tag);
if (element.class) {
const classes = element.class.split(' ').filter(c => c.length > 0).slice(0, 2);
if (classes.length > 0) {
selectors.push(`${tag}.${classes.join('.')}`);
selectors.push(`${tag}[class*="${classes[0]}"]`);
}
}
}
if (element.xpath) {
selectors.push(element.xpath);
const simpleXPath = simplifyXPath(element.xpath);
if (simpleXPath !== element.xpath) selectors.push(simpleXPath);
}
if (element.href && element.text) {
selectors.push(`a[href="${element.href}"]:contains("${element.text.slice(0, 30)}")`);
}
return selectors;
}
function simplifyXPath(xpath) {
const parts = xpath.split('/').filter(p => p.length > 0);
if (parts.length <= 3) return xpath;
const idPart = parts.find(p => p.includes('@id'));
if (idPart) {
const idMatch = idPart.match(/@id="([^"]+)"/);
if (idMatch) return `//*[@id="${idMatch[1]}"]`;
}
return '/' + parts.slice(-3).join('/');
}
async function attemptAction(tabId, action, selector, highlightIndex) {
const actionLabels = { click: 'Click', hover: 'Hover', type: 'Type' };
const actionLabel = actionLabels[action] || action;
const safeSend = (tabId, msg) => {
return chrome.tabs.sendMessage(tabId, msg).catch(e => {
if (e?.message?.includes('No tab with given id')) return null;
throw e;
});
};
try {
await safeSend(tabId, { type: 'page.highlight.setState', highlightIndex, state: 'loading' });
} catch (e) {}
try {
const result = await safeSend(tabId, {
type: 'page.dom.perform',
steps: [{ action, selector }],
});
try {
const state = result?.ok ? 'success' : 'error';
await safeSend(tabId, { type: 'page.highlight.setState', highlightIndex, state });
} catch (e) {}
if (result?.ok) {
return { ok: true, message: `${actionLabel} successful on element ${highlightIndex}` };
} else {
return {
ok: false,
error: `${actionLabel} failed on element ${highlightIndex}: ${result?.message || 'Unknown error'}. Selector used: ${selector?.slice(0, 100)}`,
selector,
elementIndex: highlightIndex
};
}
} catch (e) {
try {
await safeSend(tabId, { type: 'page.highlight.setState', highlightIndex, state: 'error' });
} catch (e) {}
return {
ok: false,
error: `${actionLabel} failed on element ${highlightIndex}: ${e.message}. The page may have changed or the element is no longer available. Try scrolling or refreshing the page context.`,
selector,
elementIndex: highlightIndex
};
}
}
async function parseAndExecuteAction(content, pageLinks, domTree, pageContext) {
if (!content) return null;
const matches = [...content.matchAll(ACTION_TAG_RE)];
if (matches.length === 0) return null;
const results = [];
let currentDomTree = domTree;
let tabId = null;
for (const match of matches) {
const tag = match[1].trim();
const colonIdx = tag.indexOf(':');
if (colonIdx === -1) continue;
const loop = _checkLoop(tag, currentDomTree, pageContext);
if (loop.isLoop) {
results.push({ ok: false, loopWarning: loop.reason });
continue;
}
const type = tag.slice(0, colonIdx).toLowerCase();
const args = tag.slice(colonIdx + 1);
const result = await executeAction(type, args, pageLinks, currentDomTree, tabId);
if (result) {
const innerResult = result.result;
let isOk = false;
let msg = '';
let err = '';
if (innerResult && typeof innerResult === 'object') {
isOk = innerResult.ok === true;
msg = innerResult.message || innerResult.summary || '';
err = innerResult.error || '';
}
if (!isOk && result.ok === true) {
isOk = true;
msg = result.message || result.summary || '';
}
if (!isOk) {
err = result.error || result.message || 'Unknown error';
}
const actionMsg = { ok: isOk, message: msg, error: err };
if (result.domTree) currentDomTree = result.domTree;
if (result.tabId) tabId = result.tabId;
results.push(actionMsg);
} else {
results.push(null);
}
}
return results.length > 0 ? results : null;
}
async function executeAction(type, args, pageLinks, domTree, tabId) {
try {
if (!tabId) {
const tab = await getWebTab();
tabId = tab?.id;
}
if (!tabId) return { ok: false, error: 'No active tab' };
let currentDomTree = domTree;
switch (type) {
case 'click': {
const index = parseInt(args, 10);
if (isNaN(index) || index < 1) return { ok: false, error: 'Invalid click index' };
let selector = null;
let targetElement = null;
if (currentDomTree?.elements) {
targetElement = currentDomTree.elements.find(el => el.highlightIndex === index);
if (targetElement) {
const selectors = buildSelectors(targetElement);
for (const sel of selectors) {
const result = await attemptAction(tabId, 'click', sel, index);
if (result?.ok) {
await new Promise(r => setTimeout(r, 800));
const newDomTree = await chrome.tabs.sendMessage(tabId, { type: 'page.dom.tree' }).catch(() => null);
if (newDomTree && !newDomTree.error) {
currentDomTree = newDomTree;
}
return { result, domTree: currentDomTree, tabId };
}
}
} else {
}
}
return { ok: false, error: `Click failed for element ${index}` };
}
case 'scroll': {
const direction = args.toLowerCase();
if (!['up', 'down'].includes(direction)) return { ok: false, error: 'Invalid scroll direction' };
const result = await chrome.tabs.sendMessage(tabId, {
type: 'page.dom.perform',
steps: [{ action: 'scroll', direction }],
});
return { ok: true };
}
case 'navigate': {
const url = args.trim();
if (!url) return { ok: false, error: 'No URL provided' };
if (!HTTPS_RE.test(url)) return { ok: false, error: 'Only HTTP(S) URLs supported' };
await chrome.tabs.update(tabId, { url });
return { ok: true };
}
case 'type': {
const parts = args.split(':');
if (parts.length < 2) return { ok: false, error: 'Invalid type format. Use: type:N:text' };
const index = parseInt(parts[0], 10);
const text = parts.slice(1).join(':');
if (isNaN(index) || index < 1) return { ok: false, error: 'Invalid input index' };
let selector = null;
if (currentDomTree?.elements) {
const element = currentDomTree.elements.find(el => el.highlightIndex === index && (el.tagName === 'input' || el.tagName === 'textarea' || el.getAttribute('contenteditable') || el.attributes?.contenteditable));
if (element) {
if (element.xpath) {
selector = element.xpath;
} else {
const attrs = [];
if (element.type) attrs.push(`type="${element.type}"`);
if (element.name) attrs.push(`name="${element.name}"`);
if (element.placeholder) attrs.push(`placeholder="${element.placeholder}"`);
selector = `input[${attrs.join('][')}]`;
}
}
}
if (!selector) {
selector = `input:nth-of-type(${index})`;
}
const result = await chrome.tabs.sendMessage(tabId, {
type: 'page.dom.perform',
steps: [{ action: 'type', selector, value: text }],
});
if (!result?.ok) {
const fallbackSelectors = [
'[role="textbox"]',
'[aria-label*="wiadomość"]',
'[aria-label*="message"]',
'[placeholder*="Odpowiedz"]',
'[placeholder*="Reply"]',
'textarea[name="message"]',
'div[contenteditable="true"]'
];
for (const fallback of fallbackSelectors) {
const fallbackResult = await chrome.tabs.sendMessage(tabId, {
type: 'page.dom.perform',
steps: [{ action: 'type', selector: fallback, value: text }],
});
if (fallbackResult?.ok) {
return fallbackResult;
}
}
}
return result || { ok: false, error: 'Type failed' };
}
case 'hover': {
const index = parseInt(args, 10);
if (isNaN(index) || index < 1) return { ok: false, error: 'Invalid hover index. Use: hover:N' };
if (currentDomTree?.elements) {
const targetElement = currentDomTree.elements.find(el => el.highlightIndex === index);
if (targetElement) {
const selectors = buildSelectors(targetElement);
for (const sel of selectors) {
const result = await attemptAction(tabId, 'hover', sel, index);
if (result?.ok) return { result, domTree: currentDomTree, tabId };
}
}
return { ok: false, error: `Hover failed for element ${index} - element not found or not hoverable` };
}
return { ok: false, error: 'No DOM tree available for element lookup' };
}
case 'scroll_to': {
const index = parseInt(args, 10);
if (isNaN(index) || index < 1) return { ok: false, error: 'Invalid scroll_to index. Use: scroll_to:N' };
if (currentDomTree?.elements) {
const targetElement = currentDomTree.elements.find(el => el.highlightIndex === index);
if (targetElement) {
const selectors = buildSelectors(targetElement);
for (const sel of selectors) {
const result = await chrome.tabs.sendMessage(tabId, {
type: 'page.dom.perform',
steps: [{ action: 'scroll_to', selector: sel }],
});
if (result?.ok) return { result, domTree: currentDomTree, tabId };
}
}
return { ok: false, error: `Scroll to element ${index} failed - element not found` };
}
return { ok: false, error: 'No DOM tree available for element lookup' };
}
case 'drag': {
const parts = args.split(':');
if (parts.length < 2) return { ok: false, error: 'Invalid drag format. Use: drag:SOURCE:TARGET' };
const sourceIndex = parseInt(parts[0], 10);
const targetIndex = parseInt(parts[1], 10);
if (isNaN(sourceIndex) || sourceIndex < 1) return { ok: false, error: 'Invalid drag source index' };
if (currentDomTree?.elements) {
const sourceElement = currentDomTree.elements.find(el => el.highlightIndex === sourceIndex);
const targetElement = targetIndex ? currentDomTree.elements.find(el => el.highlightIndex === targetIndex) : null;
if (sourceElement) {
const sourceSelectors = buildSelectors(sourceElement);
let targetSelector = null;
if (targetElement) {
const targetSelectors = buildSelectors(targetElement);
targetSelector = targetSelectors[0];
}
for (const sel of sourceSelectors) {
const result = await chrome.tabs.sendMessage(tabId, {
type: 'page.dom.perform',
steps: [{ action: 'drag', selector: sel, target: targetSelector || `offset:100:100` }],
});
if (result?.ok) return { result, domTree: currentDomTree, tabId };
}
}
return { ok: false, error: `Drag failed for element ${sourceIndex} - source element not found` };
}
return { ok: false, error: 'No DOM tree available for element lookup' };
}
case 'go_back': {
const result = await chrome.tabs.sendMessage(tabId, {
type: 'page.dom.perform',
steps: [{ action: 'go_back' }],
});
return result || { ok: true, message: 'Navigated back' };
}
case 'refresh': {
const result = await chrome.tabs.sendMessage(tabId, {
type: 'page.dom.perform',
steps: [{ action: 'refresh' }],
});
return result || { ok: true, message: 'Page refreshed' };
}
case 'select': {
const parts = args.split(':');
if (parts.length < 2) return { ok: false, error: 'Invalid select format. Use: select:N:value or select:N:label:labelText' };
const index = parseInt(parts[0], 10);
const value = parts.slice(1).join(':');
if (isNaN(index) || index < 1) return { ok: false, error: 'Invalid select index' };
if (currentDomTree?.elements) {
const targetElement = currentDomTree.elements.find(el => el.highlightIndex === index && el.tagName === 'select');
if (targetElement) {
const selectors = buildSelectors(targetElement);
for (const sel of selectors) {
const result = await chrome.tabs.sendMessage(tabId, {
type: 'page.dom.perform',
steps: [{ action: 'select', selector: sel, value }],
});
if (result?.ok) return { result, domTree: currentDomTree, tabId };
}
}
return { ok: false, error: `Select failed for element ${index} - element not found or not a select` };
}
return { ok: false, error: 'No DOM tree available for element lookup' };
}
default:
return { ok: false, error: `Unknown action: ${type}` };
}
} catch (err) {
return { ok: false, error: err.message };
}
}
async function buildMessages(history, pageContext, pageScreenshot, systemPrompt, autoVault, vaultConnected, vaultName, vaultFilename, memoryContext, webSearch, pageLinks, domTree) {