@duckmind/dm-windows-x64 0.59.9 → 0.60.4

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,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import{randomInt as at}from"node:crypto";import{spawn as lt}from"node:child_process";import{basename as ut}from"node:path";import{dirname as ct,join as ft}from"node:path";import{fileURLToPath as gt}from"node:url";function st(e=process.env,t=process.execPath){let n=e.GREEDY_SEARCH_NODE||e.NODE_BINARY||e.NODE;if(n?.trim())return n.trim();let i=ut(t||"").toLowerCase();if(i==="node"||i==="node.exe")return t;return"node"}var ht=ct(gt(import.meta.url)),pt=ft(ht,"..","bin","cdp.mjs"),mt=new Set(["list","snap","eval","shot","html","nav","net","click","clickxy","type","loadall","evalraw","browse","stop","--tab"]);function yt(e){if(!Array.isArray(e)||e.length===0)throw Error("cdp: args must be a non-empty array");if(e[0]==="test")return e.map((t,n)=>pe(t,n));if(!mt.has(e[0]))throw Error(`cdp: unknown subcommand '${e[0]}'`);return e.map((t,n)=>pe(t,n))}function pe(e,t){if(typeof e!=="string")throw Error(`cdp: argv[${t}] must be a string (got ${typeof e})`);if(e.includes("\x00"))throw Error(`cdp: argv[${t}] contains a null byte`);return e}function h(e,t=30000){return ee(e,null,t)}function ee(e,t=null,n=30000){let i=yt(e);return new Promise((r,o)=>{let a=lt(st(),[pt,...i],{stdio:[t==null?"ignore":"pipe","pipe","pipe"]});if(t!=null)a.stdin.write(t),a.stdin.end();let l="",u="";a.stdout.on("data",(s)=>l+=s),a.stderr.on("data",(s)=>u+=s);let f=setTimeout(()=>{a.kill(),o(Error(`cdp timeout: ${e[0]}`))},n);a.on("close",(s)=>{if(clearTimeout(f),s===0)r(l.trim());else o(Error(u.trim()||`cdp exit ${s}`))})})}function me(e,t){let n=(a)=>String(a??"").replace(/\s+/g," ").trim(),i=n(e),r=n(t);if(!r)return!1;if(i.length<Math.ceil(r.length*0.8))return!1;let o=Math.min(40,r.length);return i.includes(r.slice(0,o))&&i.includes(r.slice(-o))}async function ye(e){if(e)return e;let t=(await h(["list"])).split(`
3
- `)[0]?.slice(0,8);if(!t)throw Error("No Chrome tabs found. Is Chrome running with --remote-debugging-port=9222?");let n=await h(["evalraw",t,"Target.createTarget",'{"url":"about:blank"}']),i;try{i=JSON.parse(n)}catch(a){throw Error(`Target.createTarget returned invalid JSON: ${a.message}`)}let{targetId:r}=i;if(!r)throw Error("Target.createTarget did not return a targetId");await h(["list"]);let o=r.slice(0,8);try{await be(o)}catch(a){process.stderr.write(`[getOrOpenTab] stealth injection failed: ${a.message}
4
- `)}return o}async function de(e,t){let n=`
2
+ import{randomInt as ut}from"node:crypto";import{spawn as st}from"node:child_process";import{basename as ct}from"node:path";import{dirname as gt,join as ht}from"node:path";import{fileURLToPath as pt}from"node:url";function ft(e=process.env,t=process.execPath){let n=e.GREEDY_SEARCH_NODE||e.NODE_BINARY||e.NODE;if(n?.trim())return n.trim();let r=ct(t||"").toLowerCase();if(r==="node"||r==="node.exe")return t;return"node"}var mt=gt(pt(import.meta.url)),yt=ht(mt,"..","bin","cdp.mjs"),vt=new Set(["list","snap","eval","shot","html","nav","net","click","clickxy","type","loadall","evalraw","browse","stop","--tab"]);function dt(e){if(!Array.isArray(e)||e.length===0)throw Error("cdp: args must be a non-empty array");if(e[0]==="test")return e.map((t,n)=>ye(t,n));if(!vt.has(e[0]))throw Error(`cdp: unknown subcommand '${e[0]}'`);return e.map((t,n)=>ye(t,n))}function ye(e,t){if(typeof e!=="string")throw Error(`cdp: argv[${t}] must be a string (got ${typeof e})`);if(e.includes("\x00"))throw Error(`cdp: argv[${t}] contains a null byte`);return e}function h(e,t=30000){return ne(e,null,t)}function ne(e,t=null,n=30000){let r=dt(e);return new Promise((i,o)=>{let a=st(ft(),[yt,...r],{stdio:[t==null?"ignore":"pipe","pipe","pipe"]});if(t!=null)a.stdin.write(t),a.stdin.end();let l="",u="";a.stdout.on("data",(s)=>l+=s),a.stderr.on("data",(s)=>u+=s);let f=setTimeout(()=>{a.kill(),o(Error(`cdp timeout: ${e[0]}`))},n);a.on("close",(s)=>{if(clearTimeout(f),s===0)i(l.trim());else o(Error(u.trim()||`cdp exit ${s}`))})})}function ve(e,t){let n=(a)=>String(a??"").replace(/\s+/g," ").trim(),r=n(e),i=n(t);if(!i)return!1;if(r.length<Math.ceil(i.length*0.8))return!1;let o=Math.min(40,i.length);return r.includes(i.slice(0,o))&&r.includes(i.slice(-o))}async function de(e){if(e)return e;let t=(await h(["list"])).split(`
3
+ `)[0]?.slice(0,8);if(!t)throw Error("No Chrome tabs found. Is Chrome running with --remote-debugging-port=9222?");let n=await h(["evalraw",t,"Target.createTarget",'{"url":"about:blank"}']),r;try{r=JSON.parse(n)}catch(a){throw Error(`Target.createTarget returned invalid JSON: ${a.message}`)}let{targetId:i}=r;if(!i)throw Error("Target.createTarget did not return a targetId");await h(["list"]);let o=i.slice(0,8);try{await we(o)}catch(a){process.stderr.write(`[getOrOpenTab] stealth injection failed: ${a.message}
4
+ `)}return o}async function be(e,t){let n=`
5
5
  (() => {
6
6
  window.${t} = null;
7
7
  const _clipboard = navigator.clipboard;
@@ -38,9 +38,9 @@ import{randomInt as at}from"node:crypto";import{spawn as lt}from"node:child_proc
38
38
  catch (_) { return undefined; }
39
39
  };
40
40
  })();
41
- `;await h(["eval",e,n])}async function te(e,t,n,i={}){let{timeoutMs:r=2600}=i,o=i.retryClick!=null?i.retryClick:Math.floor(r*0.4),a=String.raw`
41
+ `;await h(["eval",e,n])}async function re(e,t,n,r={}){let{timeoutMs:i=2600}=r,o=r.retryClick!=null?r.retryClick:Math.floor(i*0.4),a=String.raw`
42
42
  new Promise((resolve) => {
43
- const _deadline = Date.now() + ${r};
43
+ const _deadline = Date.now() + ${i};
44
44
  const _retryAt = Date.now() + ${o};
45
45
  let _retried = false;
46
46
  function _click() { try { ${t}; } catch(_) {} }
@@ -57,7 +57,7 @@ import{randomInt as at}from"node:crypto";import{spawn as lt}from"node:child_proc
57
57
  _click();
58
58
  _poll();
59
59
  })
60
- `;return await h(["eval",e,a],r+5000).catch(()=>"")}async function be(e){await h(["evalraw",e,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
60
+ `;return await h(["eval",e,a],i+5000).catch(()=>"")}async function we(e){await h(["evalraw",e,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
61
61
  (function() {
62
62
  // ── Runtime.enable / CDP detection masking ──────────────
63
63
  try { delete window.__REBROWSER_RUNTIME_ENABLE; } catch(_) {}
@@ -342,11 +342,11 @@ import{randomInt as at}from"node:crypto";import{spawn as lt}from"node:child_proc
342
342
  };
343
343
  } catch(_) {}
344
344
  })();
345
- `})])}function ve(e){if(!e)return[];let t=[],n=0;while(n<e.length&&t.length<10){let i=e.indexOf("[",n);if(i===-1)break;let r=e.indexOf("](",i);if(r===-1)break;let o=r+2,a=-1;for(let l=o;l<e.length;l++){let u=e[l];if(u===")"){a=l;break}if(/\s/.test(u))break}if(a!==-1){let l=e.slice(i+1,r),u=e.slice(o,a);if(/^https?:\/\//i.test(u)&&l){if(!t.some((f)=>f.url===u))t.push({title:l,url:u})}n=a+1}else n=i+1}return t}var Q={postNav:800,postNavSlow:1200,postClick:300,postType:300,inputPoll:400,copyPoll:600,afterVerify:1500};function B(e){let t=e*0.2,n=at(-Math.floor(t),Math.floor(t)+1);return Math.max(50,Math.round(e+n))}async function we(e,t={}){let{timeout:n=20000,interval:i=600,stableRounds:r=3,selector:o="document.body",minLength:a=0,isStreamingExpr:l="false"}=t,u=String.raw`
345
+ `})])}function xe(e){if(!e)return[];let t=[],n=0;while(n<e.length&&t.length<10){let r=e.indexOf("[",n);if(r===-1)break;let i=e.indexOf("](",r);if(i===-1)break;let o=i+2,a=-1;for(let l=o;l<e.length;l++){let u=e[l];if(u===")"){a=l;break}if(/\s/.test(u))break}if(a!==-1){let l=e.slice(r+1,i),u=e.slice(o,a);if(/^https?:\/\//i.test(u)&&l){if(!t.some((f)=>f.url===u))t.push({title:l,url:u})}n=a+1}else n=r+1}return t}var Q={postNav:800,postNavSlow:1200,postClick:300,postType:300,inputPoll:400,copyPoll:600,afterVerify:1500};function O(e){let t=e*0.2,n=ut(-Math.floor(t),Math.floor(t)+1);return Math.max(50,Math.round(e+n))}async function $e(e,t={}){let{timeout:n=20000,interval:r=600,stableRounds:i=3,selector:o="document.body",minLength:a=0,isStreamingExpr:l="false"}=t,u=String.raw`
346
346
  new Promise((resolve, reject) => {
347
347
  const _deadline = Date.now() + ${n};
348
- const _baseInterval = ${i};
349
- const _stableRounds = ${r};
348
+ const _baseInterval = ${r};
349
+ const _stableRounds = ${i};
350
350
  const _minLength = ${a};
351
351
  let _lastLen = -1;
352
352
  let _stableCount = 0;
@@ -384,10 +384,10 @@ import{randomInt as at}from"node:crypto";import{spawn as lt}from"node:child_proc
384
384
 
385
385
  _poll();
386
386
  })
387
- `,f=await h(["eval",e,u],n+1e4),s=parseInt(f,10)||0;if(s>=a)return s;throw Error(`Generation did not stabilise within ${n}ms`)}async function xe(e,t,n=15000,i=500){let r=String.raw`
387
+ `,f=await h(["eval",e,u],n+1e4),s=parseInt(f,10)||0;if(s>=a)return s;throw Error(`Generation did not stabilise within ${n}ms`)}async function _e(e,t,n=15000,r=500){let i=String.raw`
388
388
  new Promise((resolve) => {
389
389
  const _deadline = Date.now() + ${n};
390
- const _baseInterval = ${i};
390
+ const _baseInterval = ${r};
391
391
 
392
392
  function _jitter(ms) {
393
393
  return Math.max(50, ms + (Math.random() * ms * 0.4 - ms * 0.2));
@@ -403,26 +403,25 @@ import{randomInt as at}from"node:crypto";import{spawn as lt}from"node:child_proc
403
403
 
404
404
  _poll();
405
405
  })
406
- `;return await h(["eval",e,r],n+5000)==="true"}async function $e(e){let t=e.indexOf("--stdin");if(t===-1)return e;let n=await new Promise((r)=>{let o="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(a)=>o+=a),process.stdin.on("end",()=>r(o.trim()))}),i=[...e];return i[t]=n,i}function ke(e){let t=e.includes("--short"),n=e.filter((l)=>l!=="--short"),i=n.indexOf("--tab"),r=i===-1?null:n[i+1];if(i!==-1)n=n.filter((l,u)=>u!==i&&u!==i+1);let o=n.indexOf("--locale"),a=o===-1?null:n[o+1];if(o!==-1)n=n.filter((l,u)=>u!==o&&u!==o+1);return{query:n.join(" "),tabPrefix:r,short:t,locale:a}}function _e(e,t){if(!e.length||e[0]==="--help")process.stderr.write(t),process.exit(1)}function Je(e,t,n=300){if(!t||e.length<=n)return e;let i=e.slice(0,n),r=i.lastIndexOf(" ");return r>0?`${i.slice(0,r)}…`:`${i}…`}function Ne(e){process.stdout.write(`${JSON.stringify(e,null,2)}
407
- `)}function We(e,t=null){if(t){let n=JSON.stringify({_envelope:t,error:e.message});process.stdout.write(`${n}
406
+ `;return await h(["eval",e,i],n+5000)==="true"}async function ke(e){let t=e.indexOf("--stdin");if(t===-1)return e;let n=await new Promise((i)=>{let o="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(a)=>o+=a),process.stdin.on("end",()=>i(o.trim()))}),r=[...e];return r[t]=n,r}function Ne(e){let t=e.includes("--short"),n=e.filter((l)=>l!=="--short"),r=n.indexOf("--tab"),i=r===-1?null:n[r+1];if(r!==-1)n=n.filter((l,u)=>u!==r&&u!==r+1);let o=n.indexOf("--locale"),a=o===-1?null:n[o+1];if(o!==-1)n=n.filter((l,u)=>u!==o&&u!==o+1);return{query:n.join(" "),tabPrefix:i,short:t,locale:a}}function Je(e,t){if(!e.length||e[0]==="--help")process.stderr.write(t),process.exit(1)}function We(e,t,n=300){if(!t||e.length<=n)return e;let r=e.slice(0,n),i=r.lastIndexOf(" ");return i>0?`${r.slice(0,i)}…`:`${r}…`}function je(e){process.stdout.write(`${JSON.stringify(e,null,2)}
407
+ `)}function Te(e,t=null){if(t){let n=JSON.stringify({_envelope:t,error:e.message});process.stdout.write(`${n}
408
408
  `)}process.stderr.write(`Error: ${e.message}
409
- `),process.exit(1)}import{spawn as Ut,execFileSync as ue,execSync as Ln}from"node:child_process";import{basename as dt}from"node:path";function Te(e=process.env,t=process.execPath){let n=e.GREEDY_SEARCH_NODE||e.NODE_BINARY||e.NODE;if(n?.trim())return n.trim();let i=dt(t||"").toLowerCase();if(i==="node"||i==="node.exe")return t;return"node"}import{existsSync as Ye,readFileSync as se,renameSync as Pt,unlinkSync as w,writeFileSync as F}from"node:fs";import ce from"node:http";import{platform as Re}from"node:os";import{join as zt}from"node:path";import{existsSync as je}from"node:fs";import{platform as bt}from"node:os";import{join as k}from"node:path";function b(e){let t=bt()==="win32",n=process.env.SystemRoot||"C:\\Windows",i={win32:{powershell:k(n,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:k(n,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:k(n,"System32","netstat.exe"),taskkill:k(n,"System32","taskkill.exe"),tasklist:k(n,"System32","tasklist.exe"),cmd:k(n,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},r=t?i.win32:i.unix,o=e.toLowerCase();if(r[o]&&je(r[o]))return r[o];if(t&&o==="netstat"){let a=k(n,"Sysnative","netstat.exe");if(je(a))return a}return e}import{execFileSync as vt}from"node:child_process";import{platform as wt}from"node:os";function xt(e,t){return vt(b(e),t,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000})}function $t(e){let t=String(e||"").match(/\b(\d+)\b/);return t?Number.parseInt(t[1],10):null}function kt(e){return $t(e)}function _t(e,t){for(let n of String(e||"").split(/\r?\n/)){if(!/\bLISTEN\b/i.test(n))continue;if(!n.trim().split(/\s+/).slice(0,6).some((o)=>o.endsWith(`:${t}`)))continue;let r=n.match(/\bpid=(\d+)\b/);if(r)return Number.parseInt(r[1],10)}return null}function Jt(e,t){for(let n of String(e||"").split(/\r?\n/)){let i=n.trim().split(/\s+/);if(i.length<5||i[0].toUpperCase()!=="TCP")continue;if(!i.at(-2)?.toUpperCase().startsWith("LISTEN"))continue;if(!i[1].endsWith(`:${t}`))continue;let r=Number.parseInt(i.at(-1),10);if(Number.isInteger(r)&&r>0)return r}return null}function ne(e,t,n){try{return e(t,n)}catch{return null}}function qe(e,{platformName:t=wt(),run:n=xt}={}){if(t==="win32")return Jt(ne(n,"netstat",["-ano","-p","TCP"]),e);let i=ne(n,"lsof",["-nP",`-iTCP:${e}`,"-sTCP:LISTEN","-t"]),r=kt(i);if(r)return r;if(t!=="linux")return null;return _t(ne(n,"ss",["-ltnp"]),e)}import{existsSync as C,mkdirSync as Nt,readFileSync as Be,writeFileSync as Wt}from"node:fs";import{homedir as Tt}from"node:os";import{join as He}from"node:path";import{tmpdir as jt}from"node:os";function qt(e,t=9222){let n=Number.parseInt(String(e??""),10);return Number.isInteger(n)&&n>1024&&n<65535?n:t}var Ot=jt().replaceAll("\\","/"),m=qt(process.env.GREEDY_SEARCH_PORT),y=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${Ot}/greedysearch-chrome-profile`).replaceAll("\\","/"),H=`${y}/DevToolsActivePort`,U=process.env.GREEDY_SEARCH_PID_FILE||`${y}/browser.pid`,Bt=process.env.CDP_PAGES_CACHE||`${y}/cdp-pages.json`,$=process.env.GREEDY_SEARCH_MODE_FILE||`${y}/browser-mode`,Ve=process.env.GREEDY_SEARCH_METADATA_FILE||`${y}/browser-metadata.json`,Me=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${y}/browser-launch.lock`,P=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${y}/browser-last-activity`,Sn=(process.env.CDP_SOCKET_DIR||`${y}/cdp-sockets`).replaceAll("\\","/"),Zn=`${y}/visible-recovery.jsonl`,ie=He(Tt(),".dm"),v=He(ie,"greedyconfig"),oe=["perplexity","google","chatgpt","gemini"],ae="gemini";function Ht(){try{if(C(v)){let e=Be(v,"utf8"),t=JSON.parse(e);if(Array.isArray(t.engines)&&t.engines.length>0&&t.engines.every((n)=>typeof n==="string")){let n=t.engines.filter((r)=>re[r]),i=t.engines.filter((r)=>!re[r]);if(i.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${v}: ${i.join(", ")}
410
- [greedysearch] Available engines: ${Object.keys(re).join(", ")}
411
- `);if(n.length>0)return n;process.stderr.write(`[greedysearch] Warning: no valid engines in ${v}, falling back to defaults: ${oe.join(", ")}
412
- `)}}}catch{}return oe}function Vt(){try{if(!C(ie))Nt(ie,{recursive:!0});if(!C(v))Wt(v,JSON.stringify({engines:oe,synthesizer:ae},null,2)+`
413
- `,"utf8")}catch{}}Vt();var Oe=["gemini","chatgpt"];function Mt(){try{if(C(v)){let e=Be(v,"utf8"),t=JSON.parse(e);if(typeof t.synthesizer==="string"){let n=t.synthesizer.toLowerCase();if(Oe.includes(n))return n;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${t.synthesizer}" in ${v}
414
- [greedysearch] Available synthesizers: ${Oe.join(", ")}
415
- [greedysearch] Falling back to default: ${ae}
416
- `)}}}catch{}return ae}var re={perplexity:"perplexity.mjs",p:"perplexity.mjs",bing:"bing-copilot.mjs",b:"bing-copilot.mjs",google:"google-ai.mjs",g:"google-ai.mjs",gemini:"gemini.mjs",gem:"gemini.mjs",chatgpt:"chatgpt.mjs",gpt:"chatgpt.mjs","semantic-scholar":"semantic-scholar.mjs",semanticscholar:"semantic-scholar.mjs",s2:"semantic-scholar.mjs",logically:"logically.mjs",log:"logically.mjs"},Qn=Ht();var Cn=Mt(),Un=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=y;import{execFileSync as Xe,execSync as Se}from"node:child_process";import{existsSync as z,mkdirSync as Xt,readFileSync as j,unlinkSync as J,writeFileSync as N}from"node:fs";import{platform as Ue}from"node:os";var A=Ve,_=Me,St=15000,D=U,K=$,V=P;function M(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Zt(e){if(!M(e))return null;try{if(Ue()==="win32")return Xe(b("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return Xe(b("ps"),["-p",String(e),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Qt(e,t,n=m){if(!e)return!1;let i=(a)=>String(a||"").replaceAll("\\","/").toLowerCase(),r=i(e),o=i(t);return r.includes(o)&&r.includes(`--remote-debugging-port=${n}`)&&!r.includes("--type=")}function Ze(e,t,n=m){return Qt(Zt(e),t,n)}function Ct(e=m){try{if(Ue()==="win32"){let n=Se(`${b("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),i=new RegExp(String.raw`TCP\s+\S+:${e}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),r=n.match(i);return r?Number.parseInt(r[1],10):null}let t=Se(`${b("lsof")} -i :${e} -t 2>/dev/null || ${b("ss")} -tlnp 2>/dev/null | ${b("grep")} :${e} | ${b("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return t?Number.parseInt(t.split(`
417
- `)[0],10):null}catch{return null}}function X(){try{if(z(A)){let e=j(A,"utf8"),t=JSON.parse(e);if(t&&typeof t.tempDir==="string"&&typeof t.debugPort==="number")return{browserPid:Number.isInteger(t.browserPid)?t.browserPid:void 0,debugPort:t.debugPort,tempDir:t.tempDir,clientPids:Array.isArray(t.clientPids)?t.clientPids.filter((n)=>Number.isInteger(n)&&n>0):[],sessionMode:t.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(t.lastActivity)?t.lastActivity:0,launchedAt:Number.isFinite(t.launchedAt)?t.launchedAt:0}}}catch{}try{let e=z(D)?Number.parseInt(j(D,"utf8").trim(),10)||void 0:void 0,t=z(K)?j(K,"utf8").trim()==="visible"?"visible":"headless":"headless",n=z(V)?Number.parseInt(j(V,"utf8").trim(),10)||0:0;return{browserPid:e,debugPort:m,tempDir:y,clientPids:e?[e]:[],sessionMode:t,lastActivity:n,launchedAt:0}}catch{return null}}function Y(e){try{N(A,JSON.stringify({browserPid:e.browserPid,debugPort:e.debugPort,tempDir:e.tempDir,clientPids:[...new Set(e.clientPids.filter((t)=>t>0))],sessionMode:e.sessionMode,lastActivity:e.lastActivity,launchedAt:e.launchedAt},null,2),"utf8")}catch{}try{if(e.browserPid)N(D,String(e.browserPid),"utf8")}catch{}try{N(K,e.sessionMode,"utf8")}catch{}try{N(V,String(e.lastActivity),"utf8")}catch{}}function Qe(){try{J(A)}catch{}try{J(D)}catch{}try{J(K)}catch{}try{J(V)}catch{}}function le(e){if(!e)return e;let t={...e,clientPids:[...new Set([...e.clientPids,process.pid].filter((n)=>M(n)||n===process.pid))]};return Y(t),t}function R(e){let t=Date.now();try{if(e)Y({...e,lastActivity:t});else N(V,String(t),"utf8")}catch{}}var Rn=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var Ce=!1;function Pe(){if(process.env.GREEDY_SEARCH_RESEARCH_CHILD)return;if(Ce)return;Ce=!0;let e=X();if(!e)return;if(e.browserPid){if(!M(e.browserPid)){Qe();return}if(!Ze(e.browserPid,e.tempDir,e.debugPort))Qe();else Y({...e,clientPids:e.clientPids.filter((r)=>M(r))})}let t=Ct();if(t&&t!==e.browserPid)if(Ze(t,y,m))Y({browserPid:t,debugPort:m,tempDir:y,clientPids:[t],sessionMode:e.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else process.stderr.write(`[greedysearch] Refusing to kill unverified listener ${t} on port ${m}.
418
- `)}function ze(){Xt(y,{recursive:!0});try{let e=JSON.stringify({pid:process.pid,ts:Date.now()});return N(_,e,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let t=j(_,"utf8");if(JSON.parse(t).pid===process.pid)J(_)}catch{}}}}catch(e){if(e?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let e=j(_,"utf8"),t=JSON.parse(e),n=Date.now()-(t.ts||0);if(!M(t.pid)||n>St){try{J(_)}catch{}try{let r=JSON.stringify({pid:process.pid,ts:Date.now()});return N(_,r,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{J(_)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var At=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),Ae=U,S=P,Dt=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,Kt=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;function Yt(e,t=m){let n=String(e||"").toLowerCase();if(!n.includes(`--remote-debugging-port=${t}`)||n.includes("--type="))return null;return n.includes("--headless")}function Ge(){try{let e=I(),t=e?Fe(e):null,n=Yt(t);if(n!==null){try{F($,n?"headless":"visible","utf8")}catch{}return n}}catch{}try{if(!Ye($))return!0;return se($,"utf8").trim()==="headless"}catch{return!0}}function Rt(){try{F(S,String(Date.now()),"utf8")}catch{}try{let e=X();if(e)R(e)}catch{}}function Fe(e){try{if(Re()==="win32")return ue(b("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return ue(b("ps"),["-p",String(e),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Gt(e){let t=String(e||"").replaceAll("\\","/"),n=y.replaceAll("\\","/");return t.includes(`--remote-debugging-port=${m}`)&&t.includes(`--user-data-dir=${n}`)&&!t.includes("--type=")}function I(){return qe(m)}function L(){let e=I();return e&&Gt(Fe(e))?e:null}async function Ft(e=1500){let t=L();if(!t)return process.stderr.write(`[greedysearch] Refusing to close an unverified listener.
419
- `),!1;try{let i=await new Promise((o,a)=>{let l=ce.get(`http://localhost:${m}/json/version`,(u)=>{let f="";u.on("data",(s)=>f+=s),u.on("end",()=>{try{o(JSON.parse(f))}catch{a(Error("bad JSON"))}})});l.on("error",a),l.setTimeout(1000,()=>{l.destroy(),a(Error("timeout"))})}),r=new globalThis.WebSocket(i.webSocketDebuggerUrl);await new Promise((o)=>{r.onopen=()=>{if(L()!==t){r.close(),o();return}r.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{r.close(),o()},200)},r.onerror=()=>o(),setTimeout(o,1000)})}catch{}let n=Date.now()+e;while(Date.now()<n){let i=I();if(!i)return!0;if(i!==t)return!1;await new Promise((r)=>setTimeout(r,150))}return Lt(t)}function Lt(e=null){try{let t=L();if(!t||e&&t!==e)return!1;if(Re()==="win32")ue(b("taskkill"),["/F","/PID",String(t)],{stdio:"ignore",windowsHide:!0});else process.kill(t,"SIGKILL");return!0}catch{return!1}}async function Le(){if(!L()){if(I())process.stderr.write(`[greedysearch] Refusing to kill an unverified listener.
420
- `);return!1}if(!await x(500)){try{w(Ae)}catch{}try{w(S)}catch{}try{w($)}catch{}return!1}let t=await Ft(1500);try{w(Ae)}catch{}try{w(S)}catch{}try{w($)}catch{}if(t)process.stderr.write(`[greedysearch] Killed Chrome on port ${m}.
421
- `);return t}var De=Le;async function It(){let t=Ge()?Dt:Kt;if(t<=0)return!1;if(!Ye(S))return Rt(),!1;try{let n=Number.parseInt(se(S,"utf8").trim(),10);if(!n)return!1;if((Date.now()-n)/60000>=t)return Le()}catch{}return!1}function x(e=3000){return new Promise((t)=>{let n=ce.get(`http://localhost:${m}/json/version`,(i)=>{i.resume(),t(i.statusCode===200)});n.on("error",()=>t(!1)),n.setTimeout(e,()=>{n.destroy(),t(!1)})})}async function Ke(e=3000,t=200){let n=Date.now()+e;while(Date.now()<n){if(!await x(300))return!0;await new Promise((i)=>setTimeout(i,t))}return!await x(300)}async function G(){let e=`${H}.lock`,t=`${H}.tmp`,n=5000,i=1000,r=await new Promise((o)=>{let a=Date.now(),l=()=>{try{let u=JSON.stringify({pid:process.pid,ts:Date.now()});F(e,u,{encoding:"utf8",flag:"wx"}),o(!0)}catch(u){if(u?.code!=="EEXIST"){if(Date.now()-a<1000)setTimeout(l,50);else o(!1);return}try{let f=se(e,"utf8").trim(),s=f.startsWith("{")?JSON.parse(f):{ts:Number(f)},g=Number(s?.ts)||0;if(g>0&&Date.now()-g>5000)try{w(e)}catch{}if(Date.now()-a<1000)setTimeout(l,50);else o(!1)}catch{if(Date.now()-a<1000)setTimeout(l,50);else o(!1)}}};l()});try{let o=await new Promise((u,f)=>{let s=ce.get(`http://localhost:${m}/json/version`,(g)=>{let p="";g.on("data",(c)=>p+=c),g.on("end",()=>u(p))});s.on("error",f),s.setTimeout(3000,()=>{s.destroy(),f(Error("timeout"))})}),{webSocketDebuggerUrl:a}=JSON.parse(o),l=new URL(a).pathname;if(r){F(t,`${m}
422
- ${l}`,"utf8");try{w(H)}catch{}Pt(t,H)}}catch{}finally{if(r)try{w(e)}catch{}}}async function Ie(){if(process.env.GREEDY_SEARCH_RESEARCH_CHILD&&await x()){await G();try{let o=X();if(o)R(o),le(o)}catch{}return}Pe();let e=await It(),t=e?!1:await x();if(!t&&!e)await new Promise((o)=>setTimeout(o,500)),t=await x();let n=!1;if(t){let o=Ge(),a=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!a&&!o)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
423
- `),await De(),await Ke(),n=!0;else if(a&&o)process.stderr.write(`[greedysearch] Headless Chrome detected — switching to visible mode...
424
- `),await De(),await Ke(),n=!0}if(n?!1:await x()){await G();try{let o=X();if(o)R(o),le(o)}catch{}return}let r=ze();if(!r.acquired){let o=Date.now()+12000,a=!1;while(Date.now()<o){if(a=await x(500),a)break;await new Promise((l)=>setTimeout(l,250))}if(a){await G();return}}try{if(await x(1000)){await G();return}process.stderr.write(`GreedySearch Chrome not running on port ${m} — auto-launching...
425
- `);let a=[zt(At,"..","..","bin","launch.mjs")];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")a.push("--headless");await new Promise((l,u)=>{Ut(Te(),a,{stdio:["ignore",process.stderr,process.stderr]}).on("close",(s)=>s===0?l():u(Error("launch.mjs failed")))})}finally{r.release()}}import{randomInt as Et}from"node:crypto";import{existsSync as en,readFileSync as tn}from"node:fs";import nn from"node:http";var rn=`
409
+ `),process.exit(1)}import{spawn as Yt,execFileSync as ce,execSync as ur}from"node:child_process";import{basename as bt}from"node:path";function Se(e=process.env,t=process.execPath){let n=e.GREEDY_SEARCH_NODE||e.NODE_BINARY||e.NODE;if(n?.trim())return n.trim();let r=bt(t||"").toLowerCase();if(r==="node"||r==="node.exe")return t;return"node"}import{existsSync as Ge,readFileSync as fe,renameSync as Rt,unlinkSync as w,writeFileSync as I}from"node:fs";import ge from"node:http";import{platform as Fe}from"node:os";import{existsSync as qe}from"node:fs";import{platform as wt}from"node:os";import{join as _}from"node:path";function d(e){let t=wt()==="win32",n=process.env.SystemRoot||"C:\\Windows",r={win32:{powershell:_(n,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:_(n,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:_(n,"System32","netstat.exe"),taskkill:_(n,"System32","taskkill.exe"),tasklist:_(n,"System32","tasklist.exe"),cmd:_(n,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},i=t?r.win32:r.unix,o=e.toLowerCase();if(i[o]&&qe(i[o]))return i[o];if(t&&o==="netstat"){let a=_(n,"Sysnative","netstat.exe");if(qe(a))return a}return e}import{execFileSync as xt}from"node:child_process";import{platform as $t}from"node:os";function _t(e,t){return xt(d(e),t,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000})}function kt(e){let t=String(e||"").match(/\b(\d+)\b/);return t?Number.parseInt(t[1],10):null}function Nt(e){return kt(e)}function Jt(e,t){for(let n of String(e||"").split(/\r?\n/)){if(!/\bLISTEN\b/i.test(n))continue;if(!n.trim().split(/\s+/).slice(0,6).some((o)=>o.endsWith(`:${t}`)))continue;let i=n.match(/\bpid=(\d+)\b/);if(i)return Number.parseInt(i[1],10)}return null}function Wt(e,t){for(let n of String(e||"").split(/\r?\n/)){let r=n.trim().split(/\s+/);if(r.length<5||r[0].toUpperCase()!=="TCP")continue;if(!r.at(-2)?.toUpperCase().startsWith("LISTEN"))continue;if(!r[1].endsWith(`:${t}`))continue;let i=Number.parseInt(r.at(-1),10);if(Number.isInteger(i)&&i>0)return i}return null}function ie(e,t,n){try{return e(t,n)}catch{return null}}function U(e,{platformName:t=$t(),run:n=_t}={}){if(t==="win32")return Wt(ie(n,"netstat",["-ano","-p","TCP"]),e);let r=ie(n,"lsof",["-nP",`-iTCP:${e}`,"-sTCP:LISTEN","-t"]),i=Nt(r);if(i)return i;if(t!=="linux")return null;return Jt(ie(n,"ss",["-ltnp"]),e)}import{existsSync as Oe}from"node:fs";import{dirname as jt,join as B}from"node:path";import{fileURLToPath as Tt}from"node:url";function Be(e){return Tt(new URL(".",e)).replace(/^\/([A-Z]:)/,"$1")}function St(e,t=Oe){let n=new Set;for(let r of e.filter(Boolean)){if(n.has(r))continue;if(n.add(r),t(r))return r}return e.filter(Boolean).at(-1)}function He({moduleDir:e,entrypoint:t=process.argv[1],env:n=process.env,exists:r=Oe}={}){let i=t?jt(t):null,o=n.GREEDY_SEARCH_EXTENSION_DIR?.trim()||null;return St([e?B(e,"..","..","bin","launch.mjs"):null,e?B(e,"launch.mjs"):null,o?B(o,"bin","launch.mjs"):null,i?B(i,"launch.mjs"):null,i?B(i,"..","bin","launch.mjs"):null],r)}import{existsSync as z,mkdirSync as qt,readFileSync as Ve,writeFileSync as Ot}from"node:fs";import{homedir as Bt}from"node:os";import{join as Me}from"node:path";import{tmpdir as Ht}from"node:os";function Xt(e,t=9222){let n=Number.parseInt(String(e??""),10);return Number.isInteger(n)&&n>1024&&n<65535?n:t}var Vt=Ht().replaceAll("\\","/"),m=Xt(process.env.GREEDY_SEARCH_PORT),y=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${Vt}/greedysearch-chrome-profile`).replaceAll("\\","/"),H=`${y}/DevToolsActivePort`,P=process.env.GREEDY_SEARCH_PID_FILE||`${y}/browser.pid`,Mt=process.env.CDP_PAGES_CACHE||`${y}/cdp-pages.json`,$=process.env.GREEDY_SEARCH_MODE_FILE||`${y}/browser-mode`,Ze=process.env.GREEDY_SEARCH_METADATA_FILE||`${y}/browser-metadata.json`,Ce=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${y}/browser-launch.lock`,A=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${y}/browser-last-activity`,Kn=(process.env.CDP_SOCKET_DIR||`${y}/cdp-sockets`).replaceAll("\\","/"),Yn=`${y}/visible-recovery.jsonl`,ae=Me(Bt(),".dm"),b=Me(ae,"greedyconfig"),le=["perplexity","google","chatgpt","gemini"],ue="gemini";function Zt(){try{if(z(b)){let e=Ve(b,"utf8"),t=JSON.parse(e);if(Array.isArray(t.engines)&&t.engines.length>0&&t.engines.every((n)=>typeof n==="string")){let n=t.engines.filter((i)=>oe[i]),r=t.engines.filter((i)=>!oe[i]);if(r.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${b}: ${r.join(", ")}
410
+ [greedysearch] Available engines: ${Object.keys(oe).join(", ")}
411
+ `);if(n.length>0)return n;process.stderr.write(`[greedysearch] Warning: no valid engines in ${b}, falling back to defaults: ${le.join(", ")}
412
+ `)}}}catch{}return le}function Ct(){try{if(!z(ae))qt(ae,{recursive:!0});if(!z(b))Ot(b,JSON.stringify({engines:le,synthesizer:ue},null,2)+`
413
+ `,"utf8")}catch{}}Ct();var Xe=["gemini","chatgpt"];function Qt(){try{if(z(b)){let e=Ve(b,"utf8"),t=JSON.parse(e);if(typeof t.synthesizer==="string"){let n=t.synthesizer.toLowerCase();if(Xe.includes(n))return n;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${t.synthesizer}" in ${b}
414
+ [greedysearch] Available synthesizers: ${Xe.join(", ")}
415
+ [greedysearch] Falling back to default: ${ue}
416
+ `)}}}catch{}return ue}var oe={perplexity:"perplexity.mjs",p:"perplexity.mjs",bing:"bing-copilot.mjs",b:"bing-copilot.mjs",google:"google-ai.mjs",g:"google-ai.mjs",gemini:"gemini.mjs",gem:"gemini.mjs",chatgpt:"chatgpt.mjs",gpt:"chatgpt.mjs","semantic-scholar":"semantic-scholar.mjs",semanticscholar:"semantic-scholar.mjs",s2:"semantic-scholar.mjs",logically:"logically.mjs",log:"logically.mjs"},Rn=Zt();var Gn=Qt(),Fn=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=y;import{execFileSync as Qe,execSync as En}from"node:child_process";import{existsSync as D,mkdirSync as Ut,readFileSync as T,unlinkSync as N,writeFileSync as J}from"node:fs";import{platform as zt}from"node:os";var K=Ze,k=Ce,Pt=15000,Y=P,R=$,X=A;function V(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function At(e){if(!V(e))return null;try{if(zt()==="win32")return Qe(d("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return Qe(d("ps"),["-p",String(e),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Dt(e,t,n=m){if(!e)return!1;let r=(a)=>String(a||"").replaceAll("\\","/").toLowerCase(),i=r(e),o=r(t);return i.includes(o)&&i.includes(`--remote-debugging-port=${n}`)&&!i.includes("--type=")}function Ue(e,t,n=m){return Dt(At(e),t,n)}function Kt(e=m){return U(e)}function M(){try{if(D(K)){let e=T(K,"utf8"),t=JSON.parse(e);if(t&&typeof t.tempDir==="string"&&typeof t.debugPort==="number")return{browserPid:Number.isInteger(t.browserPid)?t.browserPid:void 0,debugPort:t.debugPort,tempDir:t.tempDir,clientPids:Array.isArray(t.clientPids)?t.clientPids.filter((n)=>Number.isInteger(n)&&n>0):[],sessionMode:t.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(t.lastActivity)?t.lastActivity:0,launchedAt:Number.isFinite(t.launchedAt)?t.launchedAt:0}}}catch{}try{let e=D(Y)?Number.parseInt(T(Y,"utf8").trim(),10)||void 0:void 0,t=D(R)?T(R,"utf8").trim()==="visible"?"visible":"headless":"headless",n=D(X)?Number.parseInt(T(X,"utf8").trim(),10)||0:0;return{browserPid:e,debugPort:m,tempDir:y,clientPids:e?[e]:[],sessionMode:t,lastActivity:n,launchedAt:0}}catch{return null}}function G(e){try{J(K,JSON.stringify({browserPid:e.browserPid,debugPort:e.debugPort,tempDir:e.tempDir,clientPids:[...new Set(e.clientPids.filter((t)=>t>0))],sessionMode:e.sessionMode,lastActivity:e.lastActivity,launchedAt:e.launchedAt},null,2),"utf8")}catch{}try{if(e.browserPid)J(Y,String(e.browserPid),"utf8")}catch{}try{J(R,e.sessionMode,"utf8")}catch{}try{J(X,String(e.lastActivity),"utf8")}catch{}}function ze(){try{N(K)}catch{}try{N(Y)}catch{}try{N(R)}catch{}try{N(X)}catch{}}function se(e){if(!e)return e;let t={...e,clientPids:[...new Set([...e.clientPids,process.pid].filter((n)=>V(n)||n===process.pid))]};return G(t),t}function F(e){let t=Date.now();try{if(e)G({...e,lastActivity:t});else J(X,String(t),"utf8")}catch{}}var or=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var Pe=!1;function Ae(){if(process.env.GREEDY_SEARCH_RESEARCH_CHILD)return;if(Pe)return;Pe=!0;let e=M();if(!e)return;if(e.browserPid){if(!V(e.browserPid)){ze();return}if(!Ue(e.browserPid,e.tempDir,e.debugPort))ze();else G({...e,clientPids:e.clientPids.filter((i)=>V(i))})}let t=Kt();if(t&&t!==e.browserPid)if(Ue(t,y,m))G({browserPid:t,debugPort:m,tempDir:y,clientPids:[t],sessionMode:e.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else process.stderr.write(`[greedysearch] Refusing to kill unverified listener ${t} on port ${m}.
417
+ `)}function De(){Ut(y,{recursive:!0});try{let e=JSON.stringify({pid:process.pid,ts:Date.now()});return J(k,e,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let t=T(k,"utf8");if(JSON.parse(t).pid===process.pid)N(k)}catch{}}}}catch(e){if(e?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let e=T(k,"utf8"),t=JSON.parse(e),n=Date.now()-(t.ts||0);if(!V(t.pid)||n>Pt){try{N(k)}catch{}try{let i=JSON.stringify({pid:process.pid,ts:Date.now()});return J(k,i,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{N(k)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var Gt=Be(import.meta.url),Ke=P,Z=A,Ft=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,Lt=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;function It(e,t=m){let n=String(e||"").toLowerCase();if(!n.includes(`--remote-debugging-port=${t}`)||n.includes("--type="))return null;return n.includes("--headless")}function Le(){try{let e=ee(),t=e?Ie(e):null,n=It(t);if(n!==null){try{I($,n?"headless":"visible","utf8")}catch{}return n}}catch{}try{if(!Ge($))return!0;return fe($,"utf8").trim()==="headless"}catch{return!0}}function Et(){try{I(Z,String(Date.now()),"utf8")}catch{}try{let e=M();if(e)F(e)}catch{}}function Ie(e){try{if(Fe()==="win32")return ce(d("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return ce(d("ps"),["-p",String(e),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function en(e){let t=String(e||"").replaceAll("\\","/"),n=y.replaceAll("\\","/");return t.includes(`--remote-debugging-port=${m}`)&&t.includes(`--user-data-dir=${n}`)&&!t.includes("--type=")}function ee(){return U(m)}function E(){let e=ee();return e&&en(Ie(e))?e:null}async function tn(e=1500){let t=E();if(!t)return process.stderr.write(`[greedysearch] Refusing to close an unverified listener.
418
+ `),!1;try{let r=await new Promise((o,a)=>{let l=ge.get(`http://localhost:${m}/json/version`,(u)=>{let f="";u.on("data",(s)=>f+=s),u.on("end",()=>{try{o(JSON.parse(f))}catch{a(Error("bad JSON"))}})});l.on("error",a),l.setTimeout(1000,()=>{l.destroy(),a(Error("timeout"))})}),i=new globalThis.WebSocket(r.webSocketDebuggerUrl);await new Promise((o)=>{i.onopen=()=>{if(E()!==t){i.close(),o();return}i.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{i.close(),o()},200)},i.onerror=()=>o(),setTimeout(o,1000)})}catch{}let n=Date.now()+e;while(Date.now()<n){let r=ee();if(!r)return!0;if(r!==t)return!1;await new Promise((i)=>setTimeout(i,150))}return nn(t)}function nn(e=null){try{let t=E();if(!t||e&&t!==e)return!1;if(Fe()==="win32")ce(d("taskkill"),["/F","/PID",String(t)],{stdio:"ignore",windowsHide:!0});else process.kill(t,"SIGKILL");return!0}catch{return!1}}async function Ee(){if(!E()){if(ee())process.stderr.write(`[greedysearch] Refusing to kill an unverified listener.
419
+ `);return!1}if(!await x(500)){try{w(Ke)}catch{}try{w(Z)}catch{}try{w($)}catch{}return!1}let t=await tn(1500);try{w(Ke)}catch{}try{w(Z)}catch{}try{w($)}catch{}if(t)process.stderr.write(`[greedysearch] Killed Chrome on port ${m}.
420
+ `);return t}var Ye=Ee;async function rn(){let t=Le()?Ft:Lt;if(t<=0)return!1;if(!Ge(Z))return Et(),!1;try{let n=Number.parseInt(fe(Z,"utf8").trim(),10);if(!n)return!1;if((Date.now()-n)/60000>=t)return Ee()}catch{}return!1}function x(e=3000){return new Promise((t)=>{let n=ge.get(`http://localhost:${m}/json/version`,(r)=>{r.resume(),t(r.statusCode===200)});n.on("error",()=>t(!1)),n.setTimeout(e,()=>{n.destroy(),t(!1)})})}async function Re(e=3000,t=200){let n=Date.now()+e;while(Date.now()<n){if(!await x(300))return!0;await new Promise((r)=>setTimeout(r,t))}return!await x(300)}async function L(){let e=`${H}.lock`,t=`${H}.tmp`,n=5000,r=1000,i=await new Promise((o)=>{let a=Date.now(),l=()=>{try{let u=JSON.stringify({pid:process.pid,ts:Date.now()});I(e,u,{encoding:"utf8",flag:"wx"}),o(!0)}catch(u){if(u?.code!=="EEXIST"){if(Date.now()-a<1000)setTimeout(l,50);else o(!1);return}try{let f=fe(e,"utf8").trim(),s=f.startsWith("{")?JSON.parse(f):{ts:Number(f)},g=Number(s?.ts)||0;if(g>0&&Date.now()-g>5000)try{w(e)}catch{}if(Date.now()-a<1000)setTimeout(l,50);else o(!1)}catch{if(Date.now()-a<1000)setTimeout(l,50);else o(!1)}}};l()});try{let o=await new Promise((u,f)=>{let s=ge.get(`http://localhost:${m}/json/version`,(g)=>{let p="";g.on("data",(c)=>p+=c),g.on("end",()=>u(p))});s.on("error",f),s.setTimeout(3000,()=>{s.destroy(),f(Error("timeout"))})}),{webSocketDebuggerUrl:a}=JSON.parse(o),l=new URL(a).pathname;if(i){I(t,`${m}
421
+ ${l}`,"utf8");try{w(H)}catch{}Rt(t,H)}}catch{}finally{if(i)try{w(e)}catch{}}}async function et(){if(process.env.GREEDY_SEARCH_RESEARCH_CHILD&&await x()){await L();try{let o=M();if(o)F(o),se(o)}catch{}return}Ae();let e=await rn(),t=e?!1:await x();if(!t&&!e)await new Promise((o)=>setTimeout(o,500)),t=await x();let n=!1;if(t){let o=Le(),a=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!a&&!o)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
422
+ `),await Ye(),await Re(),n=!0;else if(a&&o)process.stderr.write(`[greedysearch] Headless Chrome detected — switching to visible mode...
423
+ `),await Ye(),await Re(),n=!0}if(n?!1:await x()){await L();try{let o=M();if(o)F(o),se(o)}catch{}return}let i=De();if(!i.acquired){let o=Date.now()+12000,a=!1;while(Date.now()<o){if(a=await x(500),a)break;await new Promise((l)=>setTimeout(l,250))}if(a){await L();return}}try{if(await x(1000)){await L();return}process.stderr.write(`GreedySearch Chrome not running on port ${m} — auto-launching...
424
+ `);let l=[He({moduleDir:Gt,entrypoint:process.argv[1],env:process.env})];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")l.push("--headless");await new Promise((u,f)=>{Yt(Se(),l,{stdio:["ignore",process.stderr,process.stderr]}).on("close",(g)=>g===0?u():f(Error("launch.mjs failed")))})}finally{i.release()}}import{randomInt as on}from"node:crypto";import{existsSync as an,readFileSync as ln}from"node:fs";import un from"node:http";var sn=`
426
425
  (function() {
427
426
  // Google consent page (consent.google.com)
428
427
  var g = document.querySelector('#L2AGLb, button[jsname="b3VHJd"], .tHlp8d');
@@ -439,7 +438,7 @@ ${l}`,"utf8");try{w(H)}catch{}Pt(t,H)}}catch{}finally{if(r)try{w(e)}catch{}}}asy
439
438
 
440
439
  return null;
441
440
  })()
442
- `,on=`
441
+ `,cn=`
443
442
  (function() {
444
443
  var url = document.location.href;
445
444
 
@@ -534,7 +533,7 @@ ${l}`,"utf8");try{w(H)}catch{}Pt(t,H)}}catch{}finally{if(r)try{w(e)}catch{}}}asy
534
533
 
535
534
  return null;
536
535
  })()
537
- `,an=`
536
+ `,fn=`
538
537
  (function() {
539
538
  var url = document.location.href;
540
539
  var isVerifyPage = url.includes('/sorry/') ||
@@ -568,24 +567,24 @@ ${l}`,"utf8");try{w(H)}catch{}Pt(t,H)}}catch{}finally{if(r)try{w(e)}catch{}}}asy
568
567
 
569
568
  return 'still-verifying';
570
569
  })()
571
- `;async function et(e,t){let n=await t(["eval",e,rn]).catch(()=>null);if(n&&n!=="null")await new Promise((i)=>setTimeout(i,1500))}function d(e,t){return Et(e*1000,t*1000)/1000}async function ln(e,t){if(!globalThis.WebSocket)return;let n=process.env.CDP_PROFILE_DIR;if(!n)return;let i=`${n.replaceAll("\\","/")}/DevToolsActivePort`;if(!en(i))return;let r=tn(i,"utf8").trim().split(`
572
- `)[0],o=await new Promise((u,f)=>{let s=nn.get(`http://localhost:${r}/json/version`,(g)=>{let p="";g.on("data",(c)=>p+=c),g.on("end",()=>{try{u(JSON.parse(p))}catch{f(Error("bad JSON"))}})});s.on("error",f),s.setTimeout(1000,()=>{s.destroy(),f(Error("timeout"))})}),a=new globalThis.WebSocket(o.webSocketDebuggerUrl),l=0;await new Promise((u)=>{a.onopen=async()=>{let f=(p,c)=>new Promise((Z)=>{let W=++l,T=(O)=>{if(JSON.parse(O.data).id===W)a.removeEventListener("message",T),Z()};a.addEventListener("message",T),a.send(JSON.stringify({id:W,method:p,params:c}))}),s=e+d(-2,2),g=t+d(-2,2);await f("Input.dispatchMouseEvent",{type:"mouseMoved",x:s,y:g,button:"none"}),await new Promise((p)=>setTimeout(p,d(80,160))),await f("Input.dispatchMouseEvent",{type:"mousePressed",x:s,y:g,button:"left",clickCount:1}),await new Promise((p)=>setTimeout(p,d(30,80))),await f("Input.dispatchMouseEvent",{type:"mouseReleased",x:s+d(-1,1),y:g+d(-1,1),button:"left",clickCount:1}),setTimeout(()=>{a.close(),u()},200)},a.onerror=()=>u(),setTimeout(u,3000)})}async function tt(e,t,n,i){let r=Number.parseFloat(n),o=Number.parseFloat(i);if(Number.isNaN(r)||Number.isNaN(o))throw Error(`humanClickXY: invalid coordinates (${n}, ${i})`);let a={button:"left",clickCount:1,modifiers:0},l=r+d(-3,3),u=o+d(-3,3);await t(["evalraw",e,"Input.dispatchMouseEvent",JSON.stringify({...a,type:"mouseMoved",x:l,y:u})]),await new Promise((c)=>setTimeout(c,d(80,180)));let f=r+d(-2,2),s=o+d(-2,2);await t(["evalraw",e,"Input.dispatchMouseEvent",JSON.stringify({...a,type:"mousePressed",x:f,y:s})]),await new Promise((c)=>setTimeout(c,d(30,90)));let g=f+d(-1,1),p=s+d(-1,1);return await t(["evalraw",e,"Input.dispatchMouseEvent",JSON.stringify({...a,type:"mouseReleased",x:g,y:p})]),await ln(r,o).catch(()=>{}),await new Promise((c)=>setTimeout(c,d(100,300))),`human-clicked at (${r.toFixed(0)}, ${o.toFixed(0)})`}async function un(e,t,n){let i=await t(["eval",e,`(function() {
570
+ `;async function nt(e,t){let n=await t(["eval",e,sn]).catch(()=>null);if(n&&n!=="null")await new Promise((r)=>setTimeout(r,1500))}function v(e,t){return on(e*1000,t*1000)/1000}async function gn(e,t){if(!globalThis.WebSocket)return;let n=process.env.CDP_PROFILE_DIR;if(!n)return;let r=`${n.replaceAll("\\","/")}/DevToolsActivePort`;if(!an(r))return;let i=ln(r,"utf8").trim().split(`
571
+ `)[0],o=await new Promise((u,f)=>{let s=un.get(`http://localhost:${i}/json/version`,(g)=>{let p="";g.on("data",(c)=>p+=c),g.on("end",()=>{try{u(JSON.parse(p))}catch{f(Error("bad JSON"))}})});s.on("error",f),s.setTimeout(1000,()=>{s.destroy(),f(Error("timeout"))})}),a=new globalThis.WebSocket(o.webSocketDebuggerUrl),l=0;await new Promise((u)=>{a.onopen=async()=>{let f=(p,c)=>new Promise((C)=>{let W=++l,j=(q)=>{if(JSON.parse(q.data).id===W)a.removeEventListener("message",j),C()};a.addEventListener("message",j),a.send(JSON.stringify({id:W,method:p,params:c}))}),s=e+v(-2,2),g=t+v(-2,2);await f("Input.dispatchMouseEvent",{type:"mouseMoved",x:s,y:g,button:"none"}),await new Promise((p)=>setTimeout(p,v(80,160))),await f("Input.dispatchMouseEvent",{type:"mousePressed",x:s,y:g,button:"left",clickCount:1}),await new Promise((p)=>setTimeout(p,v(30,80))),await f("Input.dispatchMouseEvent",{type:"mouseReleased",x:s+v(-1,1),y:g+v(-1,1),button:"left",clickCount:1}),setTimeout(()=>{a.close(),u()},200)},a.onerror=()=>u(),setTimeout(u,3000)})}async function rt(e,t,n,r){let i=Number.parseFloat(n),o=Number.parseFloat(r);if(Number.isNaN(i)||Number.isNaN(o))throw Error(`humanClickXY: invalid coordinates (${n}, ${r})`);let a={button:"left",clickCount:1,modifiers:0},l=i+v(-3,3),u=o+v(-3,3);await t(["evalraw",e,"Input.dispatchMouseEvent",JSON.stringify({...a,type:"mouseMoved",x:l,y:u})]),await new Promise((c)=>setTimeout(c,v(80,180)));let f=i+v(-2,2),s=o+v(-2,2);await t(["evalraw",e,"Input.dispatchMouseEvent",JSON.stringify({...a,type:"mousePressed",x:f,y:s})]),await new Promise((c)=>setTimeout(c,v(30,90)));let g=f+v(-1,1),p=s+v(-1,1);return await t(["evalraw",e,"Input.dispatchMouseEvent",JSON.stringify({...a,type:"mouseReleased",x:g,y:p})]),await gn(i,o).catch(()=>{}),await new Promise((c)=>setTimeout(c,v(100,300))),`human-clicked at (${i.toFixed(0)}, ${o.toFixed(0)})`}async function hn(e,t,n){let r=await t(["eval",e,`(function() {
573
572
  var el = document.querySelector('${n.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}');
574
573
  if (!el) return 'null';
575
574
  var r = el.getBoundingClientRect();
576
575
  return JSON.stringify({x: r.left + r.width / 2, y: r.top + r.height / 2, w: r.width, h: r.height});
577
- })()`]).catch(()=>"null");if(!i||i==="null")return null;let r=JSON.parse(i);if(r.w===0||r.h===0||r.x===0&&r.y===0)return null;let{x:o,y:a}=r;return tt(e,t,o,a)}function Ee(e,t,n){if(!n||n==="null"||n==="cleared"||n==="still-verifying"||n==="cf-closed-shadow-dom")return Promise.resolve("no-challenge");try{let i=JSON.parse(n);if(i.t==="sel"&&i.s)return process.stderr.write(`[greedysearch] Human-clicking "${i.txt}" via CDP...
578
- `),un(e,t,i.s).then((r)=>r!==null?"clicked":"cant-click");if(i.t==="xy"){if(!i.x&&!i.y)return Promise.resolve("cant-click");return process.stderr.write(`[greedysearch] Human-clicking at (${i.x.toFixed(0)}, ${i.y.toFixed(0)})...
579
- `),tt(e,t,i.x,i.y).then(()=>"clicked")}}catch{}return Promise.resolve("no-challenge")}async function sn(e,t){let n=await t(["eval",e,on]).catch(()=>null);if(n==="cf-closed-shadow-dom"){let i=await cn(e,t).catch(()=>null);if(i)return i;return n}if(n&&n!=="null")return n;return null}async function cn(e,t){if(typeof t!=="function")return null;await t(["evalraw",e,"DOM.enable","{}"]).catch(()=>{});let n=await t(["evalraw",e,"DOM.getDocument",JSON.stringify({depth:-1,pierce:!0})]).catch(()=>null);if(!n)return null;let i;try{i=JSON.parse(n)}catch{return null}if(i.error||!i.root)return null;let r=i.root;return await nt(r,e,t)}async function nt(e,t,n){if(!e)return null;let i=[];if(e.shadowRoots&&e.shadowRoots.length>0)for(let r of e.shadowRoots)i.push(r);if(e.children)for(let r of e.children)i.push(r);for(let r of i){if(r.nodeName==="IFRAME"){let a=r.attributes||[],l=a.indexOf("src"),u=l>=0?a[l+1]:"";if(u&&/challenges\.cloudflare\.com|turnstile/i.test(u)&&r.backendNodeId){let f=await n(["evalraw",t,"DOM.getBoxModel",JSON.stringify({backendNodeId:r.backendNodeId})]).catch(()=>null);if(!f)continue;let s;try{s=JSON.parse(f)}catch{continue}let g=s?.model?.content||s?.result?.model?.content;if(!g||g.length<8)continue;let p=g[0],c=g[1],Z=g[4],W=g[5],T=Z-p,O=W-c;if(T<50||O<20)continue;let ge=p+T*0.25,he=c+O*0.5;return process.stderr.write(`[greedysearch] Found CF iframe via CDP pierce at (${p.toFixed(0)}, ${c.toFixed(0)}) ${T.toFixed(0)}x${O.toFixed(0)}, clicking checkbox at (${ge.toFixed(0)}, ${he.toFixed(0)})
580
- `),JSON.stringify({t:"xy",x:ge,y:he})}}let o=await nt(r,t,n);if(o)return o}return null}async function rt(e,t,n=30000){let i=await sn(e,t);if(!i)return"clear";if(i==="sorry-page"){process.stderr.write(`[greedysearch] Google CAPTCHA detected — please solve it in the browser window (waiting up to ${Math.floor(n/1000)}s)...
581
- `);let o=Date.now()+n;while(Date.now()<o)if(await new Promise((a)=>setTimeout(a,2000)),!(await t(["eval",e,"document.location.href"]).catch(()=>"")).includes("/sorry/"))return"cleared-by-user";return"needs-human"}let r=await Ee(e,t,i);if(r==="clicked"){await new Promise((a)=>setTimeout(a,2000));let o=Date.now()+n;while(Date.now()<o){let a=await t(["eval",e,an]).catch(()=>null);if(a==="cleared"||!a||a==="null")return process.stderr.write(`[greedysearch] Verification cleared.
582
- `),"clicked";if(a!=="still-verifying")await Ee(e,t,a),await new Promise((l)=>setTimeout(l,2000));else await new Promise((l)=>setTimeout(l,1500))}return process.stderr.write(`[greedysearch] Verification may require manual intervention.
583
- `),"needs-human"}if(r==="cant-click")return process.stderr.write(`[greedysearch] Verification challenge detected but cannot be auto-clicked — please solve it manually in the visible browser window.
584
- `),"needs-human";return"clear"}var it={perplexity:{input:"#ask-input",copyButton:null,sourceItem:"[data-pplx-citation-url]",sourceLink:"a",consent:"#onetrust-accept-btn-handler"},bing:{input:"#userInput",copyButton:'button[data-testid="copy-ai-message-button"]',sourceLink:'a[href^="http"][target="_blank"]',sourceExclude:"copilot.microsoft.com",consent:"#onetrust-accept-btn-handler"},google:{answerContainer:".pWvJNd",sourceLink:'a[href^="http"]',sourceExclude:["google.","gstatic","googleapis"],sourceHeadingParent:"[data-snhf]",consent:'#L2AGLb, button[jsname="b3VHJd"], .tHlp8d'},gemini:{input:"rich-textarea .ql-editor",copyButton:'button:has(mat-icon[data-mat-icon-name="copy"])',sendButton:'button:has(mat-icon[data-mat-icon-name="arrow_upward"]), [data-test-id="send-button"], .send-button',sourcesSidebarButton:"button.legacy-sources-sidebar-button",sourcesExclude:["gemini.google","gstatic","google.com/search"],citationButtonPattern:'button[aria-label*="citation from"]',citationNameRegex:/from\s{1,20}([^.]{1,200})\.\s/}};var q=it.gemini,E="__geminiClipboard";async function fn(e,t){await h(["click",e,q.input]),await new Promise((a)=>setTimeout(a,B(200)));let n=async()=>{await ee(["type",e,"--stdin"],t),await new Promise((a)=>setTimeout(a,B(300)))},i=async()=>{let a=await h(["eval",e,`(() => {
585
- const el = document.querySelector('${q.input}');
576
+ })()`]).catch(()=>"null");if(!r||r==="null")return null;let i=JSON.parse(r);if(i.w===0||i.h===0||i.x===0&&i.y===0)return null;let{x:o,y:a}=i;return rt(e,t,o,a)}function tt(e,t,n){if(!n||n==="null"||n==="cleared"||n==="still-verifying"||n==="cf-closed-shadow-dom")return Promise.resolve("no-challenge");try{let r=JSON.parse(n);if(r.t==="sel"&&r.s)return process.stderr.write(`[greedysearch] Human-clicking "${r.txt}" via CDP...
577
+ `),hn(e,t,r.s).then((i)=>i!==null?"clicked":"cant-click");if(r.t==="xy"){if(!r.x&&!r.y)return Promise.resolve("cant-click");return process.stderr.write(`[greedysearch] Human-clicking at (${r.x.toFixed(0)}, ${r.y.toFixed(0)})...
578
+ `),rt(e,t,r.x,r.y).then(()=>"clicked")}}catch{}return Promise.resolve("no-challenge")}async function pn(e,t){let n=await t(["eval",e,cn]).catch(()=>null);if(n==="cf-closed-shadow-dom"){let r=await mn(e,t).catch(()=>null);if(r)return r;return n}if(n&&n!=="null")return n;return null}async function mn(e,t){if(typeof t!=="function")return null;await t(["evalraw",e,"DOM.enable","{}"]).catch(()=>{});let n=await t(["evalraw",e,"DOM.getDocument",JSON.stringify({depth:-1,pierce:!0})]).catch(()=>null);if(!n)return null;let r;try{r=JSON.parse(n)}catch{return null}if(r.error||!r.root)return null;let i=r.root;return await it(i,e,t)}async function it(e,t,n){if(!e)return null;let r=[];if(e.shadowRoots&&e.shadowRoots.length>0)for(let i of e.shadowRoots)r.push(i);if(e.children)for(let i of e.children)r.push(i);for(let i of r){if(i.nodeName==="IFRAME"){let a=i.attributes||[],l=a.indexOf("src"),u=l>=0?a[l+1]:"";if(u&&/challenges\.cloudflare\.com|turnstile/i.test(u)&&i.backendNodeId){let f=await n(["evalraw",t,"DOM.getBoxModel",JSON.stringify({backendNodeId:i.backendNodeId})]).catch(()=>null);if(!f)continue;let s;try{s=JSON.parse(f)}catch{continue}let g=s?.model?.content||s?.result?.model?.content;if(!g||g.length<8)continue;let p=g[0],c=g[1],C=g[4],W=g[5],j=C-p,q=W-c;if(j<50||q<20)continue;let pe=p+j*0.25,me=c+q*0.5;return process.stderr.write(`[greedysearch] Found CF iframe via CDP pierce at (${p.toFixed(0)}, ${c.toFixed(0)}) ${j.toFixed(0)}x${q.toFixed(0)}, clicking checkbox at (${pe.toFixed(0)}, ${me.toFixed(0)})
579
+ `),JSON.stringify({t:"xy",x:pe,y:me})}}let o=await it(i,t,n);if(o)return o}return null}async function ot(e,t,n=30000){let r=await pn(e,t);if(!r)return"clear";if(r==="sorry-page"){process.stderr.write(`[greedysearch] Google CAPTCHA detected — please solve it in the browser window (waiting up to ${Math.floor(n/1000)}s)...
580
+ `);let o=Date.now()+n;while(Date.now()<o)if(await new Promise((a)=>setTimeout(a,2000)),!(await t(["eval",e,"document.location.href"]).catch(()=>"")).includes("/sorry/"))return"cleared-by-user";return"needs-human"}let i=await tt(e,t,r);if(i==="clicked"){await new Promise((a)=>setTimeout(a,2000));let o=Date.now()+n;while(Date.now()<o){let a=await t(["eval",e,fn]).catch(()=>null);if(a==="cleared"||!a||a==="null")return process.stderr.write(`[greedysearch] Verification cleared.
581
+ `),"clicked";if(a!=="still-verifying")await tt(e,t,a),await new Promise((l)=>setTimeout(l,2000));else await new Promise((l)=>setTimeout(l,1500))}return process.stderr.write(`[greedysearch] Verification may require manual intervention.
582
+ `),"needs-human"}if(i==="cant-click")return process.stderr.write(`[greedysearch] Verification challenge detected but cannot be auto-clicked — please solve it manually in the visible browser window.
583
+ `),"needs-human";return"clear"}var at={perplexity:{input:"#ask-input",copyButton:null,sourceItem:"[data-pplx-citation-url]",sourceLink:"a",consent:"#onetrust-accept-btn-handler"},bing:{input:"#userInput",copyButton:'button[data-testid="copy-ai-message-button"]',sourceLink:'a[href^="http"][target="_blank"]',sourceExclude:"copilot.microsoft.com",consent:"#onetrust-accept-btn-handler"},google:{answerContainer:".pWvJNd",sourceLink:'a[href^="http"]',sourceExclude:["google.","gstatic","googleapis"],sourceHeadingParent:"[data-snhf]",consent:'#L2AGLb, button[jsname="b3VHJd"], .tHlp8d'},gemini:{input:"rich-textarea .ql-editor",copyButton:'button:has(mat-icon[data-mat-icon-name="copy"])',sendButton:'button:has(mat-icon[data-mat-icon-name="arrow_upward"]), [data-test-id="send-button"], .send-button',sourcesSidebarButton:"button.legacy-sources-sidebar-button",sourcesExclude:["gemini.google","gstatic","google.com/search"],citationButtonPattern:'button[aria-label*="citation from"]',citationNameRegex:/from\s{1,20}([^.]{1,200})\.\s/}};var S=at.gemini,te="__geminiClipboard";async function yn(e,t){await h(["click",e,S.input]),await new Promise((a)=>setTimeout(a,O(200)));let n=async()=>{await ne(["type",e,"--stdin"],t),await new Promise((a)=>setTimeout(a,O(300)))},r=async()=>{let a=await h(["eval",e,`(() => {
584
+ const el = document.querySelector('${S.input}');
586
585
  return JSON.stringify(el ? el.innerText || el.textContent || '' : '');
587
- })()`]);try{return JSON.parse(a)}catch{return a}},r=async()=>me(await i(),t),o=async()=>{await h(["eval",e,`(() => {
588
- const el = document.querySelector('${q.input}');
586
+ })()`]);try{return JSON.parse(a)}catch{return a}},i=async()=>ve(await r(),t),o=async()=>{await h(["eval",e,`(() => {
587
+ const el = document.querySelector('${S.input}');
589
588
  if (!el) return false;
590
589
  el.focus();
591
590
  const range = document.createRange();
@@ -595,10 +594,10 @@ ${l}`,"utf8");try{w(H)}catch{}Pt(t,H)}}catch{}finally{if(r)try{w(e)}catch{}}}asy
595
594
  selection.addRange(range);
596
595
  document.execCommand('delete');
597
596
  return true;
598
- })()`])};if(await n(),await r())return;if(await o(),await n(),!await r())throw Error("Gemini input field did not accept text — input verification failed")}async function fe(e,{required:t=!1}={}){try{return await h(["evalraw",e,"Page.bringToFront","{}"],5000),!0}catch(n){if(console.error(`[gemini] bringToFront failed: ${n.message}`),t)throw n;return!1}}async function gn(e){await h(["eval",e,`(function() {
597
+ })()`])};if(await n(),await i())return;if(await o(),await n(),!await i())throw Error("Gemini input field did not accept text — input verification failed")}async function he(e,{required:t=!1}={}){try{return await h(["evalraw",e,"Page.bringToFront","{}"],5000),!0}catch(n){if(console.error(`[gemini] bringToFront failed: ${n.message}`),t)throw n;return!1}}async function vn(e){await h(["eval",e,`(function() {
599
598
  const chat = document.querySelector('chat-window, [role="main"], main') || document.body;
600
599
  chat.scrollTo ? chat.scrollTo({ top: chat.scrollHeight, behavior: 'smooth' }) : window.scrollTo(0, document.body.scrollHeight);
601
- })()`])}async function hn(e){let t=await h(["eval",e,String.raw`
600
+ })()`])}async function dn(e){let t=await h(["eval",e,String.raw`
602
601
  new Promise((resolve) => {
603
602
  const _deadline = Date.now() + 6000;
604
603
  function _tryExtract() {
@@ -630,16 +629,16 @@ ${l}`,"utf8");try{w(H)}catch{}Pt(t,H)}}catch{}finally{if(r)try{w(e)}catch{}}}asy
630
629
  }
631
630
  _tryExtract();
632
631
  })
633
- `],8000);try{return JSON.parse(t)}catch(n){return console.error(`[gemini] DOM fallback JSON parse failed (${t.length} chars): ${n.message}`),{answer:"",sources:[]}}}var ot=`(() => {
634
- window.${E} = '';
632
+ `],8000);try{return JSON.parse(t)}catch(n){return console.error(`[gemini] DOM fallback JSON parse failed (${t.length} chars): ${n.message}`),{answer:"",sources:[]}}}var lt=`(() => {
633
+ window.${te} = '';
635
634
  const responses = Array.from(document.querySelectorAll('model-response'));
636
635
  const resp = responses[responses.length - 1];
637
636
  if (!resp) return;
638
- const buttons = Array.from(resp.querySelectorAll('${q.copyButton}'));
637
+ const buttons = Array.from(resp.querySelectorAll('${S.copyButton}'));
639
638
  const nonCodeButtons = buttons.filter((btn) => !btn.closest('pre, code, code-block, .code-block, .code-container'));
640
639
  const btn = nonCodeButtons[nonCodeButtons.length - 1] || buttons[buttons.length - 1];
641
640
  if (btn) btn.click();
642
- })()`;async function pn(e,t="",n=!1){let i=t.toLowerCase().trim(),r=!1;if(n)r=await h(["eval",e,String.raw`(() => {
641
+ })()`;async function bn(e,t="",n=!1){let r=t.toLowerCase().trim(),i=!1;if(n)i=await h(["eval",e,String.raw`(() => {
643
642
  const responses = Array.from(document.querySelectorAll('model-response'));
644
643
  const r = responses[responses.length - 1];
645
644
  return !!r && (r.innerText || '').trim().length > 60;
@@ -652,5 +651,5 @@ ${l}`,"utf8");try{w(H)}catch{}Pt(t,H)}}catch{}finally{if(r)try{w(e)}catch{}}}asy
652
651
  // ("Gemini said" / "Το Gemini είπε" / etc.) and ideally
653
652
  // a copy button rendered on the response.
654
653
  return t.length > 60;
655
- })()`])==="true"){r=!0;break}await new Promise((W)=>setTimeout(W,800))}}if(!r)console.error("[gemini] Warning: model-response did not render content");let o=await te(e,ot,E,{timeoutMs:600,retryClick:600});if(o&&i&&(o.toLowerCase().trim()===i||o.trim().length<i.length))console.error("[gemini] Clipboard echoed query, retrying in 2s..."),await new Promise((c)=>setTimeout(c,2000)),o=await te(e,ot,E,{timeoutMs:600,retryClick:600});let a=null,l=o?.trim()||"",u=i&&(l.toLowerCase()===i||l.length<i.length);if(!(l.length>500&&!u)){a=await hn(e);let c=l&&a.answer.includes(l)&&a.answer.length>l.length*2;if(a.answer&&(!l||u||c))o=a.answer}if(!o)throw Error("Gemini returned no answer — model-response never rendered content");let s=ve(o),g=new Map;for(let c of[...a?.sources||[],...s])if(c?.url&&!g.has(c.url))g.set(c.url,c);let p=Array.from(g.values()).slice(0,10);return{answer:o.trim(),sources:p}}var mn=`Usage: node extractors/gemini.mjs "<query>" [--tab <prefix>]
656
- `;async function yn(){let e=await $e(process.argv.slice(2));_e(e,mn);let{query:t,tabPrefix:n,short:i}=ke(e);if(process.env.GREEDY_SEARCH_VISIBLE!=="1"&&process.env.GREEDY_SEARCH_ALWAYS_VISIBLE!=="1")process.env.GREEDY_SEARCH_HEADLESS="1";await Ie();try{await h(["list"]);let r=await ye(n),o=await h(["eval",r,"document.location.href"]).catch(()=>""),a=!1;try{let c=new URL(o).hostname.toLowerCase();a=c==="gemini.google.com"||c.endsWith(".gemini.google.com")}catch{}if(!a)await h(["nav",r,"https://gemini.google.com/app"],20000),await new Promise((c)=>setTimeout(c,600));await et(r,h),await rt(r,h,1e4),await xe(r,q.input,8000,Q.inputPoll),await new Promise((c)=>setTimeout(c,B(Q.postClick))),await fe(r,{required:!0}),await de(r,E),await fn(r,t),await new Promise((c)=>setTimeout(c,B(Q.postType))),await h(["eval",r,`document.querySelector('${q.sendButton}')?.click()`]),await fe(r);let l=0,u=setInterval(()=>{if(fe(r).catch(()=>null),++l%10===0)gn(r).catch(()=>null)},6000),f=!0;try{await we(r,{timeout:45000,stableRounds:5,minLength:60,selector:"(() => { const responses = Array.from(document.querySelectorAll('model-response')); return responses[responses.length - 1]; })()"})}catch{f=!1}finally{clearInterval(u)}let{answer:s,sources:g}=await pn(r,t,f);if(!s)throw Error("No answer captured from Gemini clipboard");let p=await h(["eval",r,"document.location.href"]).catch(()=>"https://gemini.google.com/app");Ne({query:t,url:p,answer:Je(s,i),sources:g})}catch(r){We(r)}}yn();
654
+ })()`])==="true"){i=!0;break}await new Promise((W)=>setTimeout(W,800))}}if(!i)console.error("[gemini] Warning: model-response did not render content");let o=await re(e,lt,te,{timeoutMs:600,retryClick:600});if(o&&r&&(o.toLowerCase().trim()===r||o.trim().length<r.length))console.error("[gemini] Clipboard echoed query, retrying in 2s..."),await new Promise((c)=>setTimeout(c,2000)),o=await re(e,lt,te,{timeoutMs:600,retryClick:600});let a=null,l=o?.trim()||"",u=r&&(l.toLowerCase()===r||l.length<r.length);if(!(l.length>500&&!u)){a=await dn(e);let c=l&&a.answer.includes(l)&&a.answer.length>l.length*2;if(a.answer&&(!l||u||c))o=a.answer}if(!o)throw Error("Gemini returned no answer — model-response never rendered content");let s=xe(o),g=new Map;for(let c of[...a?.sources||[],...s])if(c?.url&&!g.has(c.url))g.set(c.url,c);let p=Array.from(g.values()).slice(0,10);return{answer:o.trim(),sources:p}}var wn=`Usage: node extractors/gemini.mjs "<query>" [--tab <prefix>]
655
+ `;async function xn(){let e=await ke(process.argv.slice(2));Je(e,wn);let{query:t,tabPrefix:n,short:r}=Ne(e);if(process.env.GREEDY_SEARCH_VISIBLE!=="1"&&process.env.GREEDY_SEARCH_ALWAYS_VISIBLE!=="1")process.env.GREEDY_SEARCH_HEADLESS="1";await et();try{await h(["list"]);let i=await de(n),o=await h(["eval",i,"document.location.href"]).catch(()=>""),a=!1;try{let c=new URL(o).hostname.toLowerCase();a=c==="gemini.google.com"||c.endsWith(".gemini.google.com")}catch{}if(!a)await h(["nav",i,"https://gemini.google.com/app"],20000),await new Promise((c)=>setTimeout(c,600));await nt(i,h),await ot(i,h,1e4),await _e(i,S.input,8000,Q.inputPoll),await new Promise((c)=>setTimeout(c,O(Q.postClick))),await he(i,{required:!0}),await be(i,te),await yn(i,t),await new Promise((c)=>setTimeout(c,O(Q.postType))),await h(["eval",i,`document.querySelector('${S.sendButton}')?.click()`]),await he(i);let l=0,u=setInterval(()=>{if(he(i).catch(()=>null),++l%10===0)vn(i).catch(()=>null)},6000),f=!0;try{await $e(i,{timeout:45000,stableRounds:5,minLength:60,selector:"(() => { const responses = Array.from(document.querySelectorAll('model-response')); return responses[responses.length - 1]; })()"})}catch{f=!1}finally{clearInterval(u)}let{answer:s,sources:g}=await bn(i,t,f);if(!s)throw Error("No answer captured from Gemini clipboard");let p=await h(["eval",i,"document.location.href"]).catch(()=>"https://gemini.google.com/app");je({query:t,url:p,answer:We(s,r),sources:g})}catch(i){Te(i)}}xn();