@apmantza/greedysearch-pi 1.4.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,162 +1,156 @@
1
- #!/usr/bin/env node
2
- // extractors/google-ai.mjs
3
- // Navigate Google AI Mode (udm=50), wait for answer, return clean answer + sources.
4
- //
5
- // Usage:
6
- // node extractors/google-ai.mjs "<query>" [--tab <prefix>]
7
- //
8
- // Output (stdout): JSON { answer, sources, query, url }
9
- // Errors go to stderr only stdout is always clean JSON for piping.
10
-
11
- import { readFileSync, existsSync } from 'fs';
12
- import { spawn } from 'child_process';
13
- import { tmpdir } from 'os';
14
- import { join, dirname } from 'path';
15
- import { fileURLToPath } from 'url';
16
- import { dismissConsent, handleVerification } from './consent.mjs';
17
- import { SELECTORS } from './selectors.mjs';
18
-
19
- const __dir = dirname(fileURLToPath(import.meta.url));
20
- const CDP = join(__dir, '..', 'cdp.mjs');
21
- const PAGES_CACHE = `${tmpdir().replace(/\\/g, '/')}/cdp-pages.json`;
22
-
23
- const STREAM_POLL_INTERVAL = 600;
24
- const STREAM_STABLE_ROUNDS = 3;
25
- const STREAM_TIMEOUT = 45000;
26
- const MIN_ANSWER_LENGTH = 50;
27
-
28
- const S = SELECTORS.google;
29
-
30
- // ---------------------------------------------------------------------------
31
-
32
- function cdp(args, timeoutMs = 30000) {
33
- return new Promise((resolve, reject) => {
34
- const proc = spawn('node', [CDP, ...args], { stdio: ['ignore', 'pipe', 'pipe'] });
35
- let out = '';
36
- let err = '';
37
- proc.stdout.on('data', d => out += d);
38
- proc.stderr.on('data', d => err += d);
39
- const timer = setTimeout(() => { proc.kill(); reject(new Error(`cdp timeout: ${args[0]}`)); }, timeoutMs);
40
- proc.on('close', code => {
41
- clearTimeout(timer);
42
- if (code !== 0) reject(new Error(err.trim() || `cdp exit ${code}`));
43
- else resolve(out.trim());
44
- });
45
- });
46
- }
47
-
48
- async function getOrOpenTab(tabPrefix) {
49
- if (tabPrefix) return tabPrefix;
50
- // Always open a fresh tab to avoid SPA navigation issues
51
- const list = await cdp(['list']);
52
- const anchor = list.split('\n')[0]?.slice(0, 8);
53
- if (!anchor) throw new Error('No Chrome tabs found. Is Chrome running with --remote-debugging-port=9222?');
54
- const raw = await cdp(['evalraw', anchor, 'Target.createTarget', '{"url":"about:blank"}']);
55
- const { targetId } = JSON.parse(raw);
56
- await cdp(['list']); // refresh cache
57
- return targetId.slice(0, 8);
58
- }
59
-
60
- async function waitForStreamComplete(tab) {
61
- const deadline = Date.now() + STREAM_TIMEOUT;
62
- let stableCount = 0;
63
- let lastLen = -1;
64
-
65
- while (Date.now() < deadline) {
66
- await new Promise(r => setTimeout(r, STREAM_POLL_INTERVAL));
67
-
68
- const lenStr = await cdp(['eval', tab,
69
- `(document.querySelector('${S.answerContainer}')?.innerText?.length || 0) + ''`
70
- ]).catch(() => '0');
71
-
72
- const len = parseInt(lenStr) || 0;
73
-
74
- if (len >= MIN_ANSWER_LENGTH && len === lastLen) {
75
- stableCount++;
76
- if (stableCount >= STREAM_STABLE_ROUNDS) return len;
77
- } else {
78
- stableCount = 0;
79
- lastLen = len;
80
- }
81
- }
82
-
83
- if (lastLen >= MIN_ANSWER_LENGTH) return lastLen;
84
- throw new Error(`Google AI answer did not stabilise within ${STREAM_TIMEOUT}ms`);
85
- }
86
-
87
- async function extractAnswer(tab) {
88
- const excludeFilter = S.sourceExclude.map(e => `!a.href.includes('${e}')`).join(' && ');
89
- const raw = await cdp(['eval', tab, `
90
- (function() {
91
- var el = document.querySelector('${S.answerContainer}');
92
- if (!el) return JSON.stringify({ answer: '', sources: [] });
93
- var answer = el.innerText.trim();
94
- var sources = Array.from(document.querySelectorAll('${S.sourceLink}'))
95
- .filter(a => ${excludeFilter})
96
- .map(a => ({ url: a.href.split('#')[0], title: (a.closest('${S.sourceHeadingParent}')?.querySelector('h3, [role=heading]')?.innerText || a.innerText?.trim().split('\\n')[0] || '').slice(0, 100) }))
97
- .filter(s => s.url && s.url.length > 10)
98
- .filter((v, i, arr) => arr.findIndex(x => x.url === v.url) === i)
99
- .slice(0, 10);
100
- return JSON.stringify({ answer, sources });
101
- })()
102
- `]);
103
- return JSON.parse(raw);
104
- }
105
-
106
- // ---------------------------------------------------------------------------
107
-
108
- async function main() {
109
- const args = process.argv.slice(2);
110
- if (!args.length || args[0] === '--help') {
111
- process.stderr.write('Usage: node extractors/google-ai.mjs "<query>" [--tab <prefix>]\n');
112
- process.exit(1);
113
- }
114
-
115
- const short = args.includes('--short');
116
- const rest = args.filter(a => a !== '--short');
117
- const tabFlagIdx = rest.indexOf('--tab');
118
- const tabPrefix = tabFlagIdx !== -1 ? rest[tabFlagIdx + 1] : null;
119
- const query = tabFlagIdx !== -1
120
- ? rest.filter((_, i) => i !== tabFlagIdx && i !== tabFlagIdx + 1).join(' ')
121
- : rest.join(' ');
122
-
123
- try {
124
- await cdp(['list']);
125
- const tab = await getOrOpenTab(tabPrefix);
126
-
127
- const url = `https://www.google.com/search?q=${encodeURIComponent(query)}&udm=50`;
128
- await cdp(['nav', tab, url], 35000);
129
- await new Promise(r => setTimeout(r, 1500));
130
- await dismissConsent(tab, cdp);
131
-
132
- // If consent redirected us away, navigate back
133
- const currentUrl = await cdp(['eval', tab, 'document.location.href']).catch(() => '');
134
- if (!currentUrl.includes('google.com/search')) {
135
- await cdp(['nav', tab, url], 35000);
136
- await new Promise(r => setTimeout(r, 1500));
137
- }
138
-
139
- // Handle "verify you're human"auto-click simple buttons, wait for user on hard CAPTCHA
140
- const verifyResult = await handleVerification(tab, cdp, 60000);
141
- if (verifyResult === 'needs-human') throw new Error('Google verification required — could not be completed automatically');
142
- if (verifyResult === 'clicked' || verifyResult === 'cleared-by-user') {
143
- // Re-navigate to the search URL after verification
144
- await cdp(['nav', tab, url], 35000);
145
- await new Promise(r => setTimeout(r, 1500));
146
- }
147
-
148
- await waitForStreamComplete(tab);
149
-
150
- const { answer, sources } = await extractAnswer(tab);
151
- if (!answer) throw new Error('No answer extracted — Google AI Mode may not have responded');
152
- const out = short ? answer.slice(0, 300).replace(/\s+\S*$/, '') + '…' : answer;
153
-
154
- const finalUrl = await cdp(['eval', tab, 'document.location.href']).catch(() => url);
155
- process.stdout.write(JSON.stringify({ query, url: finalUrl, answer: out, sources }, null, 2) + '\n');
156
- } catch (e) {
157
- process.stderr.write(`Error: ${e.message}\n`);
158
- process.exit(1);
159
- }
160
- }
161
-
162
- main();
1
+ #!/usr/bin/env node
2
+
3
+ // extractors/google-ai.mjs
4
+ // Navigate Google AI Mode (udm=50), wait for answer, return clean answer + sources.
5
+ //
6
+ // Usage:
7
+ // node extractors/google-ai.mjs "<query>" [--tab <prefix>]
8
+ //
9
+ // Output (stdout): JSON { answer, sources, query, url }
10
+ // Errors go to stderr only — stdout is always clean JSON for piping.
11
+
12
+ import {
13
+ cdp,
14
+ formatAnswer,
15
+ getOrOpenTab,
16
+ handleError,
17
+ outputJson,
18
+ parseArgs,
19
+ validateQuery,
20
+ } from "./common.mjs";
21
+ import { dismissConsent, handleVerification } from "./consent.mjs";
22
+ import { SELECTORS } from "./selectors.mjs";
23
+
24
+ const S = SELECTORS.google;
25
+
26
+ const STREAM_POLL_INTERVAL = 600;
27
+ const STREAM_STABLE_ROUNDS = 3;
28
+ const STREAM_TIMEOUT = 45000;
29
+ const MIN_ANSWER_LENGTH = 50;
30
+
31
+ // ============================================================================
32
+ // Google AI-specific helpers
33
+ // ============================================================================
34
+
35
+ async function waitForGoogleStreamComplete(tab) {
36
+ const deadline = Date.now() + STREAM_TIMEOUT;
37
+ let stableCount = 0;
38
+ let lastLen = -1;
39
+
40
+ while (Date.now() < deadline) {
41
+ await new Promise((r) => setTimeout(r, STREAM_POLL_INTERVAL));
42
+
43
+ const lenStr = await cdp([
44
+ "eval",
45
+ tab,
46
+ `(document.querySelector('${S.answerContainer}')?.innerText?.length || 0) + ''`,
47
+ ]).catch(() => "0");
48
+
49
+ const len = parseInt(lenStr, 10) || 0;
50
+
51
+ if (len >= MIN_ANSWER_LENGTH && len === lastLen) {
52
+ stableCount++;
53
+ if (stableCount >= STREAM_STABLE_ROUNDS) return len;
54
+ } else {
55
+ stableCount = 0;
56
+ lastLen = len;
57
+ }
58
+ }
59
+
60
+ if (lastLen >= MIN_ANSWER_LENGTH) return lastLen;
61
+ throw new Error(
62
+ `Google AI answer did not stabilise within ${STREAM_TIMEOUT}ms`,
63
+ );
64
+ }
65
+
66
+ async function extractAnswer(tab) {
67
+ const excludeFilter = S.sourceExclude
68
+ .map((e) => `!a.href.includes('${e}')`)
69
+ .join(" && ");
70
+ const raw = await cdp([
71
+ "eval",
72
+ tab,
73
+ `
74
+ (function() {
75
+ var el = document.querySelector('${S.answerContainer}');
76
+ if (!el) return JSON.stringify({ answer: '', sources: [] });
77
+ var answer = el.innerText.trim();
78
+ var sources = Array.from(document.querySelectorAll('${S.sourceLink}'))
79
+ .filter(a => ${excludeFilter})
80
+ .map(a => ({ url: a.href.split('#')[0], title: (a.closest('${S.sourceHeadingParent}')?.querySelector('h3, [role=heading]')?.innerText || a.innerText?.trim().split('\\n')[0] || '').slice(0, 100) }))
81
+ .filter(s => s.url && s.url.length > 10)
82
+ .filter((v, i, arr) => arr.findIndex(x => x.url === v.url) === i)
83
+ .slice(0, 10);
84
+ return JSON.stringify({ answer, sources });
85
+ })()
86
+ `,
87
+ ]);
88
+ return JSON.parse(raw);
89
+ }
90
+
91
+ // ============================================================================
92
+ // Main
93
+ // ============================================================================
94
+
95
+ const USAGE =
96
+ 'Usage: node extractors/google-ai.mjs "<query>" [--tab <prefix>]\n';
97
+
98
+ async function main() {
99
+ const args = process.argv.slice(2);
100
+ validateQuery(args, USAGE);
101
+
102
+ const { query, tabPrefix, short } = parseArgs(args);
103
+
104
+ try {
105
+ await cdp(["list"]);
106
+ const tab = await getOrOpenTab(tabPrefix);
107
+
108
+ const url = `https://www.google.com/search?q=${encodeURIComponent(query)}&udm=50`;
109
+ await cdp(["nav", tab, url], 35000);
110
+ await new Promise((r) => setTimeout(r, 1500));
111
+ await dismissConsent(tab, cdp);
112
+
113
+ // If consent redirected us away, navigate back
114
+ const currentUrl = await cdp(["eval", tab, "document.location.href"]).catch(
115
+ () => "",
116
+ );
117
+ if (!currentUrl.includes("google.com/search")) {
118
+ await cdp(["nav", tab, url], 35000);
119
+ await new Promise((r) => setTimeout(r, 1500));
120
+ }
121
+
122
+ // Handle "verify you're human" — auto-click simple buttons, wait for user on hard CAPTCHA
123
+ const verifyResult = await handleVerification(tab, cdp, 60000);
124
+ if (verifyResult === "needs-human")
125
+ throw new Error(
126
+ "Google verification required — could not be completed automatically",
127
+ );
128
+ if (verifyResult === "clicked" || verifyResult === "cleared-by-user") {
129
+ // Re-navigate to the search URL after verification
130
+ await cdp(["nav", tab, url], 35000);
131
+ await new Promise((r) => setTimeout(r, 1500));
132
+ }
133
+
134
+ await waitForGoogleStreamComplete(tab);
135
+
136
+ const { answer, sources } = await extractAnswer(tab);
137
+ if (!answer)
138
+ throw new Error(
139
+ "No answer extractedGoogle AI Mode may not have responded",
140
+ );
141
+
142
+ const finalUrl = await cdp(["eval", tab, "document.location.href"]).catch(
143
+ () => url,
144
+ );
145
+ outputJson({
146
+ query,
147
+ url: finalUrl,
148
+ answer: formatAnswer(answer, short),
149
+ sources,
150
+ });
151
+ } catch (e) {
152
+ handleError(e);
153
+ }
154
+ }
155
+
156
+ main();
@@ -1,181 +1,126 @@
1
- #!/usr/bin/env node
2
- // extractors/perplexity.mjs
3
- // Navigate Perplexity, wait for streaming to complete, return clean answer + sources.
4
- //
5
- // Usage:
6
- // node extractors/perplexity.mjs "<query>" [--tab <prefix>]
7
- //
8
- // Output (stdout): JSON { answer, sources, query, url }
9
- // Errors go to stderr only stdout is always clean JSON for piping.
10
-
11
- import { readFileSync, existsSync } from 'fs';
12
- import { spawn } from 'child_process';
13
- import { tmpdir } from 'os';
14
- import { join, dirname } from 'path';
15
- import { fileURLToPath } from 'url';
16
- import { dismissConsent } from './consent.mjs';
17
- import { SELECTORS } from './selectors.mjs';
18
-
19
- const __dir = dirname(fileURLToPath(import.meta.url));
20
- const CDP = join(__dir, '..', 'cdp.mjs');
21
- const PAGES_CACHE = `${tmpdir().replace(/\\/g, '/')}/cdp-pages.json`;
22
-
23
- const COPY_POLL_INTERVAL = 600;
24
- const COPY_TIMEOUT = 30000;
25
-
26
- const S = SELECTORS.perplexity;
27
-
28
- // ---------------------------------------------------------------------------
29
-
30
- function cdp(args, timeoutMs = 30000) {
31
- return new Promise((resolve, reject) => {
32
- const proc = spawn('node', [CDP, ...args], { stdio: ['ignore', 'pipe', 'pipe'] });
33
- let out = '';
34
- let err = '';
35
- proc.stdout.on('data', d => out += d);
36
- proc.stderr.on('data', d => err += d);
37
- const timer = setTimeout(() => { proc.kill(); reject(new Error(`cdp timeout: ${args[0]}`)); }, timeoutMs);
38
- proc.on('close', code => {
39
- clearTimeout(timer);
40
- if (code !== 0) reject(new Error(err.trim() || `cdp exit ${code}`));
41
- else resolve(out.trim());
42
- });
43
- });
44
- }
45
-
46
- async function getOrOpenTab(tabPrefix) {
47
- if (tabPrefix) return tabPrefix;
48
- // Always open a fresh tab to avoid SPA navigation issues
49
- const list = await cdp(['list']);
50
- const anchor = list.split('\n')[0]?.slice(0, 8);
51
- if (!anchor) throw new Error('No Chrome tabs found. Is Chrome running with --remote-debugging-port=9222?');
52
- const raw = await cdp(['evalraw', anchor, 'Target.createTarget', '{"url":"about:blank"}']);
53
- const { targetId } = JSON.parse(raw);
54
- await cdp(['list']); // refresh cache so cdp nav can find the new tab
55
- return targetId.slice(0, 8);
56
- }
57
-
58
- async function injectClipboardInterceptor(tab) {
59
- await cdp(['eval', tab, `
60
- window.__pplxClipboard = null;
61
- const _origWriteText = navigator.clipboard.writeText.bind(navigator.clipboard);
62
- navigator.clipboard.writeText = function(text) {
63
- window.__pplxClipboard = text;
64
- return _origWriteText(text);
65
- };
66
- const _origWrite = navigator.clipboard.write.bind(navigator.clipboard);
67
- navigator.clipboard.write = async function(items) {
68
- try {
69
- for (const item of items) {
70
- if (item.types && item.types.includes('text/plain')) {
71
- const blob = await item.getType('text/plain');
72
- window.__pplxClipboard = await blob.text();
73
- break;
74
- }
75
- }
76
- } catch(e) {}
77
- return _origWrite(items);
78
- };
79
- `]);
80
- }
81
-
82
- async function waitForGenerationToFinish(tab) {
83
- const deadline = Date.now() + COPY_TIMEOUT;
84
- let lastLen = -1;
85
- let stableCount = 0;
86
- while (Date.now() < deadline) {
87
- await new Promise(r => setTimeout(r, COPY_POLL_INTERVAL));
88
- const lenStr = await cdp(['eval', tab, 'document.body.innerText.length']).catch(() => '0');
89
- const currentLen = parseInt(lenStr) || 0;
90
- if (currentLen > 0) {
91
- if (currentLen === lastLen) {
92
- stableCount++;
93
- if (stableCount >= 3) return;
94
- } else {
95
- lastLen = currentLen;
96
- stableCount = 0;
97
- }
98
- }
99
- }
100
- throw new Error(`Perplexity generation did not finish within ${COPY_TIMEOUT}ms`);
101
- }
102
-
103
- async function extractAnswer(tab) {
104
- await cdp(['eval', tab, `document.querySelector('${S.copyButton}')?.click()`]);
105
- await new Promise(r => setTimeout(r, 400));
106
-
107
- const answer = await cdp(['eval', tab, `window.__pplxClipboard || ''`]);
108
- if (!answer) throw new Error('Clipboard interceptor returned empty text');
109
-
110
- // Regex parse Markdown links from clipboard — robust against DOM changes
111
- const sources = Array.from(answer.matchAll(/\[([^\]]+)\]\((https?:\/\/[^\s\)]+)\)/g))
112
- .map(m => ({ title: m[1], url: m[2] }))
113
- .filter((v, i, arr) => arr.findIndex(x => x.url === v.url) === i)
114
- .slice(0, 10);
115
-
116
- return { answer: answer.trim(), sources };
117
- }
118
-
119
- // ---------------------------------------------------------------------------
120
-
121
- async function main() {
122
- const args = process.argv.slice(2);
123
- if (!args.length || args[0] === '--help') {
124
- process.stderr.write('Usage: node extractors/perplexity.mjs "<query>" [--tab <prefix>]\n');
125
- process.exit(1);
126
- }
127
-
128
- const short = args.includes('--short');
129
- const rest = args.filter(a => a !== '--short');
130
- const tabFlagIdx = rest.indexOf('--tab');
131
- const tabPrefix = tabFlagIdx !== -1 ? rest[tabFlagIdx + 1] : null;
132
- const query = tabFlagIdx !== -1
133
- ? rest.filter((_, i) => i !== tabFlagIdx && i !== tabFlagIdx + 1).join(' ')
134
- : rest.join(' ');
135
-
136
-
137
- try {
138
- // Refresh page list so cache is current
139
- await cdp(['list']);
140
-
141
- const tab = await getOrOpenTab(tabPrefix);
142
-
143
- // Navigate to homepage and use the search box (direct ?q= URLs trigger bot redirect)
144
- await cdp(['nav', tab, 'https://www.perplexity.ai/'], 35000);
145
- await dismissConsent(tab, cdp);
146
-
147
- // Wait for React app to mount input (up to 8s)
148
- const deadline = Date.now() + 8000;
149
- while (Date.now() < deadline) {
150
- const found = await cdp(['eval', tab, `!!document.querySelector('${S.input}')`]).catch(() => 'false');
151
- if (found === 'true') break;
152
- await new Promise(r => setTimeout(r, 400));
153
- }
154
- await new Promise(r => setTimeout(r, 300));
155
-
156
- await injectClipboardInterceptor(tab);
157
- await cdp(['click', tab, S.input]);
158
- await new Promise(r => setTimeout(r, 400));
159
- await cdp(['type', tab, query]);
160
- await new Promise(r => setTimeout(r, 400));
161
- // Submit with Enter (most reliable across Chrome instances)
162
- await cdp(['eval', tab,
163
- `document.querySelector('${S.input}')?.dispatchEvent(new KeyboardEvent('keydown',{key:'Enter',bubbles:true,keyCode:13})), 'ok'`
164
- ]);
165
-
166
- await waitForGenerationToFinish(tab);
167
-
168
- const { answer, sources } = await extractAnswer(tab);
169
-
170
- if (!answer) throw new Error('No answer extracted — Perplexity may not have responded');
171
- const out = short ? answer.slice(0, 300).replace(/\s+\S*$/, '') + '…' : answer;
172
-
173
- const finalUrl = await cdp(['eval', tab, 'document.location.href']).catch(() => '');
174
- process.stdout.write(JSON.stringify({ query, url: finalUrl, answer: out, sources }, null, 2) + '\n');
175
- } catch (e) {
176
- process.stderr.write(`Error: ${e.message}\n`);
177
- process.exit(1);
178
- }
179
- }
180
-
181
- main();
1
+ #!/usr/bin/env node
2
+
3
+ // extractors/perplexity.mjs
4
+ // Navigate Perplexity, wait for streaming to complete, return clean answer + sources.
5
+ //
6
+ // Usage:
7
+ // node extractors/perplexity.mjs "<query>" [--tab <prefix>]
8
+ //
9
+ // Output (stdout): JSON { answer, sources, query, url }
10
+ // Errors go to stderr only — stdout is always clean JSON for piping.
11
+
12
+ import {
13
+ cdp,
14
+ formatAnswer,
15
+ getOrOpenTab,
16
+ handleError,
17
+ injectClipboardInterceptor,
18
+ outputJson,
19
+ parseArgs,
20
+ parseSourcesFromMarkdown,
21
+ validateQuery,
22
+ waitForStreamComplete,
23
+ } from "./common.mjs";
24
+ import { dismissConsent } from "./consent.mjs";
25
+ import { SELECTORS } from "./selectors.mjs";
26
+
27
+ const S = SELECTORS.perplexity;
28
+ const GLOBAL_VAR = "__pplxClipboard";
29
+
30
+ // ============================================================================
31
+ // Extraction
32
+ // ============================================================================
33
+
34
+ async function extractAnswer(tab) {
35
+ await cdp([
36
+ "eval",
37
+ tab,
38
+ `document.querySelector('${S.copyButton}')?.click()`,
39
+ ]);
40
+ await new Promise((r) => setTimeout(r, 400));
41
+
42
+ const answer = await cdp(["eval", tab, `window.${GLOBAL_VAR} || ''`]);
43
+ if (!answer) throw new Error("Clipboard interceptor returned empty text");
44
+
45
+ const sources = parseSourcesFromMarkdown(answer);
46
+ return { answer: answer.trim(), sources };
47
+ }
48
+
49
+ // ============================================================================
50
+ // Main
51
+ // ============================================================================
52
+
53
+ const USAGE =
54
+ 'Usage: node extractors/perplexity.mjs "<query>" [--tab <prefix>]\n';
55
+
56
+ async function main() {
57
+ const args = process.argv.slice(2);
58
+ validateQuery(args, USAGE);
59
+
60
+ const { query, tabPrefix, short } = parseArgs(args);
61
+
62
+ try {
63
+ // Refresh page list so cache is current
64
+ await cdp(["list"]);
65
+
66
+ const tab = await getOrOpenTab(tabPrefix);
67
+
68
+ // Navigate to homepage and use the search box (direct ?q= URLs trigger bot redirect)
69
+ await cdp(["nav", tab, "https://www.perplexity.ai/"], 35000);
70
+ await dismissConsent(tab, cdp);
71
+
72
+ // Wait for React app to mount input (up to 8s)
73
+ const deadline = Date.now() + 8000;
74
+ while (Date.now() < deadline) {
75
+ const found = await cdp([
76
+ "eval",
77
+ tab,
78
+ `!!document.querySelector('${S.input}')`,
79
+ ]).catch(() => "false");
80
+ if (found === "true") break;
81
+ await new Promise((r) => setTimeout(r, 400));
82
+ }
83
+ await new Promise((r) => setTimeout(r, 300));
84
+
85
+ await injectClipboardInterceptor(tab, GLOBAL_VAR);
86
+ await cdp(["click", tab, S.input]);
87
+ await new Promise((r) => setTimeout(r, 400));
88
+ await cdp(["type", tab, query]);
89
+ await new Promise((r) => setTimeout(r, 400));
90
+
91
+ // Submit with Enter (most reliable across Chrome instances)
92
+ await cdp([
93
+ "eval",
94
+ tab,
95
+ `document.querySelector('${S.input}')?.dispatchEvent(new KeyboardEvent('keydown',{key:'Enter',bubbles:true,keyCode:13})), 'ok'`,
96
+ ]);
97
+
98
+ await waitForStreamComplete(tab, {
99
+ timeout: 30000,
100
+ interval: 600,
101
+ stableRounds: 3,
102
+ selector: "document.body",
103
+ });
104
+
105
+ const { answer, sources } = await extractAnswer(tab);
106
+
107
+ if (!answer)
108
+ throw new Error(
109
+ "No answer extracted — Perplexity may not have responded",
110
+ );
111
+
112
+ const finalUrl = await cdp(["eval", tab, "document.location.href"]).catch(
113
+ () => "",
114
+ );
115
+ outputJson({
116
+ query,
117
+ url: finalUrl,
118
+ answer: formatAnswer(answer, short),
119
+ sources,
120
+ });
121
+ } catch (e) {
122
+ handleError(e);
123
+ }
124
+ }
125
+
126
+ main();