@duckmind/dm-darwin-arm64 0.52.3 → 0.52.6

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.
Files changed (25) hide show
  1. package/dm +0 -0
  2. package/extensions/.dm-extensions.json +6 -3
  3. package/extensions/greedysearch-dm/bin/gschrome.mjs +5 -7
  4. package/extensions/greedysearch-dm/bin/launch-visible.mjs +2 -4
  5. package/extensions/greedysearch-dm/bin/launch.mjs +11 -5
  6. package/extensions/greedysearch-dm/bin/search.mjs +122 -120
  7. package/extensions/greedysearch-dm/extractors/consensus.mjs +43 -43
  8. package/extensions/greedysearch-dm/extractors/gemini.mjs +44 -44
  9. package/extensions/greedysearch-dm/extractors/logically.mjs +41 -41
  10. package/extensions/greedysearch-dm/index.js +18 -18
  11. package/extensions/greedysearch-dm/src/search/browser-lifecycle.mjs +8 -9
  12. package/extensions/greedysearch-dm/src/search/chrome.mjs +25 -25
  13. package/extensions/greedysearch-dm/src/search/constants.mjs +8 -8
  14. package/extensions/greedysearch-dm/src/search/engines.mjs +9 -9
  15. package/extensions/greedysearch-dm/src/search/fetch-source.mjs +49 -49
  16. package/extensions/greedysearch-dm/src/search/launcher-paths.mjs +3 -0
  17. package/extensions/greedysearch-dm/src/search/partial-output.mjs +1 -0
  18. package/extensions/greedysearch-dm/src/search/port-pid.mjs +1 -0
  19. package/extensions/greedysearch-dm/src/search/recovery.mjs +1 -1
  20. package/extensions/greedysearch-dm/src/search/research.mjs +101 -101
  21. package/extensions/greedysearch-dm/src/search/synthesis-runner.mjs +11 -11
  22. package/extensions/greedysearch-dm/src/search/synthesis.mjs +10 -10
  23. package/extensions/greedysearch-dm/src/tools/greedy-search-handler.js +18 -18
  24. package/extensions/greedysearch-dm/src/tools/shared.js +9 -9
  25. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{randomInt as re}from"node:crypto";import{spawn as ie}from"node:child_process";import{dirname as oe,join as ue}from"node:path";import{fileURLToPath as le}from"node:url";import{basename as ae}from"node:path";function fe(t=process.env,e=process.execPath){let n=t.GREEDY_SEARCH_NODE||t.NODE_BINARY||t.NODE;if(n?.trim())return n.trim();let r=ae(e||"").toLowerCase();if(r==="node"||r==="node.exe")return e;return"node"}var ce=oe(le(import.meta.url)),ge=ue(ce,"..","bin","cdp.mjs");function g(t,e=30000){return G(t,null,e)}function G(t,e=null,n=30000){return new Promise((r,i)=>{let o=ie(fe(),[ge,...t],{stdio:[e==null?"ignore":"pipe","pipe","pipe"]});if(e!=null)o.stdin.write(e),o.stdin.end();let u="",a="";o.stdout.on("data",(f)=>u+=f),o.stderr.on("data",(f)=>a+=f);let l=setTimeout(()=>{o.kill(),i(Error(`cdp timeout: ${t[0]}`))},n);o.on("close",(f)=>{if(clearTimeout(l),f===0)r(u.trim());else i(Error(a.trim()||`cdp exit ${f}`))})})}async function st(t){if(t)return t;let e=(await g(["list"])).split(`
3
- `)[0]?.slice(0,8);if(!e)throw Error("No Chrome tabs found. Is Chrome running with --remote-debugging-port=9222?");let n=await g(["evalraw",e,"Target.createTarget",'{"url":"about:blank"}']),{targetId:r}=JSON.parse(n);await g(["list"]);let i=r.slice(0,8);try{await ht(i)}catch(o){process.stderr.write(`[getOrOpenTab] stealth injection failed: ${o.message}
2
+ import{randomInt as oe}from"node:crypto";import{spawn as le}from"node:child_process";import{dirname as fe,join as ae}from"node:path";import{fileURLToPath as ce}from"node:url";import{basename as ge}from"node:path";function se(t=process.env,e=process.execPath){let n=t.GREEDY_SEARCH_NODE||t.NODE_BINARY||t.NODE;if(n?.trim())return n.trim();let r=ge(e||"").toLowerCase();if(r==="node"||r==="node.exe")return e;return"node"}var be=fe(ce(import.meta.url)),he=ae(be,"..","bin","cdp.mjs");function g(t,e=30000){return d(t,null,e)}function d(t,e=null,n=30000){return new Promise((r,i)=>{let u=le(se(),[he,...t],{stdio:[e==null?"ignore":"pipe","pipe","pipe"]});if(e!=null)u.stdin.write(e),u.stdin.end();let o="",f="";u.stdout.on("data",(a)=>o+=a),u.stderr.on("data",(a)=>f+=a);let l=setTimeout(()=>{u.kill(),i(Error(`cdp timeout: ${t[0]}`))},n);u.on("close",(a)=>{if(clearTimeout(l),a===0)r(o.trim());else i(Error(f.trim()||`cdp exit ${a}`))})})}async function st(t){if(t)return t;let e=(await g(["list"])).split(`
3
+ `)[0]?.slice(0,8);if(!e)throw Error("No Chrome tabs found. Is Chrome running with --remote-debugging-port=9222?");let n=await g(["evalraw",e,"Target.createTarget",'{"url":"about:blank"}']),{targetId:r}=JSON.parse(n);await g(["list"]);let i=r.slice(0,8);try{await ht(i)}catch(u){process.stderr.write(`[getOrOpenTab] stealth injection failed: ${u.message}
4
4
  `)}return i}async function bt(t,e){let n=`
5
5
  (() => {
6
6
  window.${e} = null;
@@ -246,12 +246,12 @@ import{randomInt as re}from"node:crypto";import{spawn as ie}from"node:child_proc
246
246
  };
247
247
  } catch(_) {}
248
248
  })();
249
- `})])}function yt(t){if(!t)return[];let e=[],n=0;while(n<t.length&&e.length<10){let r=t.indexOf("[",n);if(r===-1)break;let i=t.indexOf("](",r);if(i===-1)break;let o=i+2,u=-1;for(let a=o;a<t.length;a++){let l=t[a];if(l===")"){u=a;break}if(/\s/.test(l))break}if(u!==-1){let a=t.slice(r+1,i),l=t.slice(o,u);if(/^https?:\/\//i.test(l)&&a){if(!e.some((f)=>f.url===l))e.push({title:a,url:l})}n=u+1}else n=r+1}return e}var T={postNav:800,postNavSlow:1200,postClick:300,postType:300,inputPoll:400,copyPoll:600,afterVerify:1500};function B(t){let e=t*0.4,n=re(-Math.floor(e),Math.floor(e)+1);return Math.max(50,Math.round(t+n))}async function wt(t,e={}){let{timeout:n=20000,interval:r=600,stableRounds:i=3,selector:o="document.body",minLength:u=0}=e,a=String.raw`
249
+ `})])}function yt(t){if(!t)return[];let e=[],n=0;while(n<t.length&&e.length<10){let r=t.indexOf("[",n);if(r===-1)break;let i=t.indexOf("](",r);if(i===-1)break;let u=i+2,o=-1;for(let f=u;f<t.length;f++){let l=t[f];if(l===")"){o=f;break}if(/\s/.test(l))break}if(o!==-1){let f=t.slice(r+1,i),l=t.slice(u,o);if(/^https?:\/\//i.test(l)&&f){if(!e.some((a)=>a.url===l))e.push({title:f,url:l})}n=o+1}else n=r+1}return e}var C={postNav:800,postNavSlow:1200,postClick:300,postType:300,inputPoll:400,copyPoll:600,afterVerify:1500};function j(t){let e=t*0.4,n=oe(-Math.floor(e),Math.floor(e)+1);return Math.max(50,Math.round(t+n))}async function wt(t,e={}){let{timeout:n=20000,interval:r=600,stableRounds:i=3,selector:u="document.body",minLength:o=0}=e,f=String.raw`
250
250
  new Promise((resolve, reject) => {
251
251
  const _deadline = Date.now() + ${n};
252
252
  const _baseInterval = ${r};
253
253
  const _stableRounds = ${i};
254
- const _minLength = ${u};
254
+ const _minLength = ${o};
255
255
  let _lastLen = -1;
256
256
  let _stableCount = 0;
257
257
 
@@ -262,7 +262,7 @@ import{randomInt as re}from"node:crypto";import{spawn as ie}from"node:child_proc
262
262
  function _poll() {
263
263
  try {
264
264
  // Re-query DOM each tick — element may not exist at eval start
265
- const el = ${o};
265
+ const el = ${u};
266
266
  const cur = el?.innerText?.length ?? 0;
267
267
  if (cur >= _minLength) {
268
268
  if (cur === _lastLen) {
@@ -284,7 +284,7 @@ import{randomInt as re}from"node:crypto";import{spawn as ie}from"node:child_proc
284
284
 
285
285
  _poll();
286
286
  })
287
- `,l=await g(["eval",t,a],n+1e4),f=parseInt(l,10)||0;if(f>=u)return f;throw Error(`Generation did not stabilise within ${n}ms`)}async function mt(t,e,n=15000,r=500){let i=String.raw`
287
+ `,l=await g(["eval",t,f],n+1e4),a=parseInt(l,10)||0;if(a>=o)return a;throw Error(`Generation did not stabilise within ${n}ms`)}async function vt(t,e,n=15000,r=500){let i=String.raw`
288
288
  new Promise((resolve) => {
289
289
  const _deadline = Date.now() + ${n};
290
290
  const _baseInterval = ${r};
@@ -303,27 +303,27 @@ import{randomInt as re}from"node:crypto";import{spawn as ie}from"node:child_proc
303
303
 
304
304
  _poll();
305
305
  })
306
- `;return await g(["eval",t,i],n+5000)==="true"}async function vt(t){let e=t.indexOf("--stdin");if(e===-1)return t;let n=await new Promise((i)=>{let o="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(u)=>o+=u),process.stdin.on("end",()=>i(o.trim()))}),r=[...t];return r[e]=n,r}function pt(t){let e=t.includes("--short"),n=t.filter((a)=>a!=="--short"),r=n.indexOf("--tab"),i=r===-1?null:n[r+1];if(r!==-1)n=n.filter((a,l)=>l!==r&&l!==r+1);let o=n.indexOf("--locale"),u=o===-1?null:n[o+1];if(o!==-1)n=n.filter((a,l)=>l!==o&&l!==o+1);return{query:n.join(" "),tabPrefix:i,short:e,locale:u}}function xt(t,e){if(!t.length||t[0]==="--help")process.stderr.write(e),process.exit(1)}function $t(t,e,n=300){if(!e||t.length<=n)return t;let r=t.slice(0,n),i=r.lastIndexOf(" ");return i>0?`${r.slice(0,i)}…`:`${r}…`}function Jt(t){process.stdout.write(`${JSON.stringify(t,null,2)}
307
- `)}function kt(t,e=null){if(e){let n=JSON.stringify({_envelope:e,error:t.message});process.stdout.write(`${n}
306
+ `;return await g(["eval",t,i],n+5000)==="true"}async function mt(t){let e=t.indexOf("--stdin");if(e===-1)return t;let n=await new Promise((i)=>{let u="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(o)=>u+=o),process.stdin.on("end",()=>i(u.trim()))}),r=[...t];return r[e]=n,r}function xt(t){let e=t.includes("--short"),n=t.filter((f)=>f!=="--short"),r=n.indexOf("--tab"),i=r===-1?null:n[r+1];if(r!==-1)n=n.filter((f,l)=>l!==r&&l!==r+1);let u=n.indexOf("--locale"),o=u===-1?null:n[u+1];if(u!==-1)n=n.filter((f,l)=>l!==u&&l!==u+1);return{query:n.join(" "),tabPrefix:i,short:e,locale:o}}function $t(t,e){if(!t.length||t[0]==="--help")process.stderr.write(e),process.exit(1)}function Jt(t,e,n=300){if(!e||t.length<=n)return t;let r=t.slice(0,n),i=r.lastIndexOf(" ");return i>0?`${r.slice(0,i)}…`:`${r}…`}function pt(t){process.stdout.write(`${JSON.stringify(t,null,2)}
307
+ `)}function Wt(t,e=null){if(e){let n=JSON.stringify({_envelope:e,error:t.message});process.stdout.write(`${n}
308
308
  `)}process.stderr.write(`Error: ${t.message}
309
- `),process.exit(1)}import{spawn as Ce,execFileSync as zt,execSync as ot}from"node:child_process";import{existsSync as R,readFileSync as S,renameSync as de,unlinkSync as p,writeFileSync as z}from"node:fs";import ut from"node:http";import{platform as lt,tmpdir as Ye}from"node:os";import{join as ze}from"node:path";import{basename as se}from"node:path";function Wt(t=process.env,e=process.execPath){let n=t.GREEDY_SEARCH_NODE||t.NODE_BINARY||t.NODE;if(n?.trim())return n.trim();let r=se(e||"").toLowerCase();if(r==="node"||r==="node.exe")return e;return"node"}import{existsSync as Nt}from"node:fs";import{platform as be}from"node:os";import{join as x}from"node:path";function y(t){let e=be()==="win32",n=process.env.SystemRoot||"C:\\Windows",r={win32:{powershell:x(n,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:x(n,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:x(n,"System32","netstat.exe"),taskkill:x(n,"System32","taskkill.exe"),tasklist:x(n,"System32","tasklist.exe"),cmd:x(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=e?r.win32:r.unix,o=t.toLowerCase();if(i[o]&&Nt(i[o]))return i[o];if(e&&o==="netstat"){let u=x(n,"Sysnative","netstat.exe");if(Nt(u))return u}return t}import{existsSync as M,mkdirSync as he,readFileSync as qt,writeFileSync as ye}from"node:fs";import{homedir as we}from"node:os";import{join as Qt}from"node:path";import{tmpdir as U}from"node:os";var h=9222,$=`${U().replaceAll("\\","/")}/greedysearch-chrome-profile`,X=`${$}/DevToolsActivePort`,me=`${U().replaceAll("\\","/")}/cdp-pages.json`,J=`${U().replaceAll("\\","/")}/greedysearch-chrome-mode`,On=`${U().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,I=Qt(we(),".dm"),v=Qt(I,"greedyconfig"),F=["perplexity","google","chatgpt"],E="gemini";function ve(){try{if(M(v)){let t=qt(v,"utf8"),e=JSON.parse(t);if(Array.isArray(e.engines)&&e.engines.length>0&&e.engines.every((n)=>typeof n==="string")){let n=e.engines.filter((i)=>L[i]),r=e.engines.filter((i)=>!L[i]);if(r.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${v}: ${r.join(", ")}
310
- [greedysearch] Available engines: ${Object.keys(L).join(", ")}
311
- `);if(n.length>0)return n;process.stderr.write(`[greedysearch] Warning: no valid engines in ${v}, falling back to defaults: ${F.join(", ")}
312
- `)}}}catch{}return F}function pe(){try{if(!M(I))he(I,{recursive:!0});if(!M(v))ye(v,JSON.stringify({engines:F,synthesizer:E},null,2)+`
313
- `,"utf8")}catch{}}pe();var Xt=["gemini","chatgpt"];function xe(){try{if(M(v)){let t=qt(v,"utf8"),e=JSON.parse(t);if(typeof e.synthesizer==="string"){let n=e.synthesizer.toLowerCase();if(Xt.includes(n))return n;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${e.synthesizer}" in ${v}
314
- [greedysearch] Available synthesizers: ${Xt.join(", ")}
315
- [greedysearch] Falling back to default: ${E}
316
- `)}}}catch{}return E}var L={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"},_n=ve();var An=xe(),Tn=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=$;import{existsSync as Kn,mkdirSync as $e,readFileSync as Bt,renameSync as Je,unlinkSync as ke,writeFileSync as Zt}from"node:fs";import We from"node:http";import{platform as Ht}from"node:os";import{dirname as Ne}from"node:path";var Vt=[9222,9223],Xe=/^(0|false|no|off)$/i;function qe(t){return[...new Set(t.filter(Boolean))]}function jt(t,e="explicit"){let n=new URL(t),r=n.protocol==="wss:"?"wss:":"ws:",i=n.port?Number.parseInt(n.port,10):r==="wss:"?443:80;return{source:e,wsUrl:`${r}//${n.host}${n.pathname}${n.search}`,host:n.hostname,port:i,path:`${n.pathname}${n.search}`,httpUrl:`http://${n.hostname}:${i}`}}function Ot(t=process.env){return![t.GREEDY_SEARCH_REUSE_EXISTING_BROWSER,t.DM_CUA_REUSE_EXISTING_BROWSER].some((e)=>e!==void 0&&Xe.test(String(e)))}function tt(t){let e=Number.parseInt(String(t??""),10);return Number.isInteger(e)&&e>0&&e<65536?e:null}function Qe(t){if(!t)return null;let e=String(t).trim();if(!e)return null;let n=new URL(e.includes("://")?e:`http://${e}`),r=tt(n.port)||(n.protocol==="https:"?443:80);return{host:n.hostname,port:r,source:`env:${e}`}}function je(t){if(!t)return[];return String(t).split(/[,\s]+/).map(tt).filter(Boolean)}function Be({env:t=process.env,platformName:e=Ht(),procVersionText:n=null}={}){if(e!=="linux")return!1;if(t.WSL_DISTRO_NAME||t.WSL_INTEROP)return!0;let r=n??(()=>{try{return Bt("/proc/version","utf8")}catch{return""}})();return/microsoft|wsl/i.test(r)}function Ze({env:t=process.env,platformName:e=Ht(),procVersionText:n=null,resolvConfText:r=null}={}){let i=["localhost","127.0.0.1"];if(Be({env:t,platformName:e,procVersionText:n})){let u=(r??(()=>{try{return Bt("/etc/resolv.conf","utf8")}catch{return""}})()).match(/^\s*nameserver\s+([^\s#]+)/m);if(u)i.push(u[1]);i.push("host.docker.internal")}return qe(i)}function He({env:t=process.env,hosts:e=Ze({env:t}),autoPorts:n=Vt,excludePorts:r=[]}={}){let i=[];for(let l of["GREEDY_SEARCH_CDP_WS_URL","DM_CUA_CDP_WS_URL","CDP_WS_URL"])if(t[l])i.push({wsUrl:t[l],source:`env:${l}`});for(let l of["GREEDY_SEARCH_CDP_URL","DM_CUA_CDP_URL","CDP_URL"])try{let f=Qe(t[l]);if(f)i.push(f)}catch{}for(let l of["GREEDY_SEARCH_EXISTING_CDP_PORT","DM_CUA_EXISTING_CDP_PORT","GREEDY_SEARCH_CDP_PORT","DM_CUA_CDP_PORT"]){let f=tt(t[l]);if(!f)continue;for(let c of e)i.push({host:c,port:f,source:`env:${l}`})}let o=je(t.GREEDY_SEARCH_EXISTING_CDP_PORTS);for(let l of o)for(let f of e)i.push({host:f,port:l,source:"env:GREEDY_SEARCH_EXISTING_CDP_PORTS"});let u=new Set(r.filter(Boolean));if(Ot(t))for(let l of n){if(u.has(l))continue;for(let f of e)i.push({host:f,port:l,source:"auto"})}let a=new Set;return i.filter((l)=>{let f=l.wsUrl||`${l.host}:${l.port}`;if(a.has(f))return!1;return a.add(f),!0})}async function Ve(t,{timeoutMs:e=700}={}){if(t.wsUrl)return jt(t.wsUrl,t.source);let n=t.host||"localhost",r=t.port;if(!r)return null;let i=await new Promise((o)=>{let u=We.get({host:n,port:r,path:"/json/version",timeout:e},(a)=>{let l="";a.setEncoding("utf8"),a.on("data",(f)=>l+=f),a.on("end",()=>o(a.statusCode===200?l:null))});u.on("error",()=>o(null)),u.setTimeout(e,()=>{u.destroy(),o(null)})});if(!i)return null;try{let o=JSON.parse(i);if(!o.webSocketDebuggerUrl)return null;let u=jt(o.webSocketDebuggerUrl,t.source),a=u.path||new URL(o.webSocketDebuggerUrl).pathname;return{...u,host:n,port:r,httpUrl:`http://${n}:${r}`,wsUrl:`ws://${n}:${r}${a}`,path:a}}catch{return null}}async function Oe(t={}){for(let e of He(t)){let n=await Ve(e,t);if(n)return n}return null}function _e(t){if(!t)throw Error("missing CDP endpoint");let e=new URL(t.wsUrl);return`${e.host}
309
+ `),process.exit(1)}import{spawn as rn,execFileSync as Dt,execSync as un}from"node:child_process";import{existsSync as G,readFileSync as L,renameSync as on,unlinkSync as x,writeFileSync as P}from"node:fs";import lt from"node:http";import{platform as Pt,tmpdir as ln}from"node:os";import{basename as ye}from"node:path";function kt(t=process.env,e=process.execPath){let n=t.GREEDY_SEARCH_NODE||t.NODE_BINARY||t.NODE;if(n?.trim())return n.trim();let r=ye(e||"").toLowerCase();if(r==="node"||r==="node.exe")return e;return"node"}import{existsSync as Xt}from"node:fs";import{platform as we}from"node:os";import{join as J}from"node:path";function v(t){let e=we()==="win32",n=process.env.SystemRoot||"C:\\Windows",r={win32:{powershell:J(n,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:J(n,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:J(n,"System32","netstat.exe"),taskkill:J(n,"System32","taskkill.exe"),tasklist:J(n,"System32","tasklist.exe"),cmd:J(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=e?r.win32:r.unix,u=t.toLowerCase();if(i[u]&&Xt(i[u]))return i[u];if(e&&u==="netstat"){let o=J(n,"Sysnative","netstat.exe");if(Xt(o))return o}return t}import{existsSync as z,mkdirSync as ve,readFileSync as Nt,writeFileSync as me}from"node:fs";import{homedir as xe}from"node:os";import{join as Qt}from"node:path";import{tmpdir as S}from"node:os";function $e(t,e=9222){let n=Number.parseInt(String(t??""),10);return Number.isInteger(n)&&n>1024&&n<65535?n:e}var h=$e(process.env.GREEDY_SEARCH_PORT,9222),$=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${S().replaceAll("\\","/")}/greedysearch-chrome-profile`).replaceAll("\\","/"),N=`${$}/DevToolsActivePort`,Je=`${S().replaceAll("\\","/")}/cdp-pages.json`,p=process.env.GREEDY_SEARCH_MODE_FILE||`${S().replaceAll("\\","/")}/greedysearch-chrome-mode`,Gn=`${S().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,E=Qt(xe(),".dm"),m=Qt(E,"greedyconfig"),tt=["perplexity","google","chatgpt"],et="gemini";function pe(){try{if(z(m)){let t=Nt(m,"utf8"),e=JSON.parse(t);if(Array.isArray(e.engines)&&e.engines.length>0&&e.engines.every((n)=>typeof n==="string")){let n=e.engines.filter((i)=>F[i]),r=e.engines.filter((i)=>!F[i]);if(r.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${m}: ${r.join(", ")}
310
+ [greedysearch] Available engines: ${Object.keys(F).join(", ")}
311
+ `);if(n.length>0)return n;process.stderr.write(`[greedysearch] Warning: no valid engines in ${m}, falling back to defaults: ${tt.join(", ")}
312
+ `)}}}catch{}return tt}function We(){try{if(!z(E))ve(E,{recursive:!0});if(!z(m))me(m,JSON.stringify({engines:tt,synthesizer:et},null,2)+`
313
+ `,"utf8")}catch{}}We();var qt=["gemini","chatgpt"];function ke(){try{if(z(m)){let t=Nt(m,"utf8"),e=JSON.parse(t);if(typeof e.synthesizer==="string"){let n=e.synthesizer.toLowerCase();if(qt.includes(n))return n;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${e.synthesizer}" in ${m}
314
+ [greedysearch] Available synthesizers: ${qt.join(", ")}
315
+ [greedysearch] Falling back to default: ${et}
316
+ `)}}}catch{}return et}var F={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"},Ln=pe();var In=ke(),dn=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=$;import{existsSync as tr,mkdirSync as Xe,readFileSync as Bt,renameSync as qe,unlinkSync as Ne,writeFileSync as Zt}from"node:fs";import Qe from"node:http";import{platform as Vt}from"node:os";import{dirname as He}from"node:path";var jt=[9222,9223],Be=/^(0|false|no|off)$/i;function Ze(t){return[...new Set(t.filter(Boolean))]}function Ht(t,e="explicit"){let n=new URL(t),r=n.protocol==="wss:"?"wss:":"ws:",i=n.port?Number.parseInt(n.port,10):r==="wss:"?443:80;return{source:e,wsUrl:`${r}//${n.host}${n.pathname}${n.search}`,host:n.hostname,port:i,path:`${n.pathname}${n.search}`,httpUrl:`http://${n.hostname}:${i}`}}function Ot(t=process.env){return![t.GREEDY_SEARCH_REUSE_EXISTING_BROWSER,t.DM_CUA_REUSE_EXISTING_BROWSER].some((e)=>e!==void 0&&Be.test(String(e)))}function nt(t){let e=Number.parseInt(String(t??""),10);return Number.isInteger(e)&&e>0&&e<65536?e:null}function Ve(t){if(!t)return null;let e=String(t).trim();if(!e)return null;let n=new URL(e.includes("://")?e:`http://${e}`),r=nt(n.port)||(n.protocol==="https:"?443:80);return{host:n.hostname,port:r,source:`env:${e}`}}function je(t){if(!t)return[];return String(t).split(/[,\s]+/).map(nt).filter(Boolean)}function Oe({env:t=process.env,platformName:e=Vt(),procVersionText:n=null}={}){if(e!=="linux")return!1;if(t.WSL_DISTRO_NAME||t.WSL_INTEROP)return!0;let r=n??(()=>{try{return Bt("/proc/version","utf8")}catch{return""}})();return/microsoft|wsl/i.test(r)}function _e({env:t=process.env,platformName:e=Vt(),procVersionText:n=null,resolvConfText:r=null}={}){let i=["localhost","127.0.0.1"];if(Oe({env:t,platformName:e,procVersionText:n})){let o=(r??(()=>{try{return Bt("/etc/resolv.conf","utf8")}catch{return""}})()).match(/^\s*nameserver\s+([^\s#]+)/m);if(o)i.push(o[1]);i.push("host.docker.internal")}return Ze(i)}function Ae({env:t=process.env,hosts:e=_e({env:t}),autoPorts:n=jt,excludePorts:r=[]}={}){let i=[];for(let l of["GREEDY_SEARCH_CDP_WS_URL","DM_CUA_CDP_WS_URL","CDP_WS_URL"])if(t[l])i.push({wsUrl:t[l],source:`env:${l}`});for(let l of["GREEDY_SEARCH_CDP_URL","DM_CUA_CDP_URL","CDP_URL"])try{let a=Ve(t[l]);if(a)i.push(a)}catch{}for(let l of["GREEDY_SEARCH_EXISTING_CDP_PORT","DM_CUA_EXISTING_CDP_PORT","GREEDY_SEARCH_CDP_PORT","DM_CUA_CDP_PORT"]){let a=nt(t[l]);if(!a)continue;for(let c of e)i.push({host:c,port:a,source:`env:${l}`})}let u=je(t.GREEDY_SEARCH_EXISTING_CDP_PORTS);for(let l of u)for(let a of e)i.push({host:a,port:l,source:"env:GREEDY_SEARCH_EXISTING_CDP_PORTS"});let o=new Set(r.filter(Boolean));if(Ot(t))for(let l of n){if(o.has(l))continue;for(let a of e)i.push({host:a,port:l,source:"auto"})}let f=new Set;return i.filter((l)=>{let a=l.wsUrl||`${l.host}:${l.port}`;if(f.has(a))return!1;return f.add(a),!0})}async function Te(t,{timeoutMs:e=700}={}){if(t.wsUrl)return Ht(t.wsUrl,t.source);let n=t.host||"localhost",r=t.port;if(!r)return null;let i=await new Promise((u)=>{let o=Qe.get({host:n,port:r,path:"/json/version",timeout:e},(f)=>{let l="";f.setEncoding("utf8"),f.on("data",(a)=>l+=a),f.on("end",()=>u(f.statusCode===200?l:null))});o.on("error",()=>u(null)),o.setTimeout(e,()=>{o.destroy(),u(null)})});if(!i)return null;try{let u=JSON.parse(i);if(!u.webSocketDebuggerUrl)return null;let o=Ht(u.webSocketDebuggerUrl,t.source),f=o.path||new URL(u.webSocketDebuggerUrl).pathname;return{...o,host:n,port:r,httpUrl:`http://${n}:${r}`,wsUrl:`ws://${n}:${r}${f}`,path:f}}catch{return null}}async function Ke(t={}){for(let e of Ae(t)){let n=await Te(e,t);if(n)return n}return null}function Ue(t){if(!t)throw Error("missing CDP endpoint");let e=new URL(t.wsUrl);return`${e.host}
317
317
  ${e.pathname}${e.search}
318
- `}function Ae(t,e){$e(Ne(t),{recursive:!0});let n=`${t}.tmp-${process.pid}`;Zt(n,_e(e),"utf8");try{ke(t)}catch{}Je(n,t)}async function _t({activePortFile:t,modeFile:e,env:n=process.env,excludePorts:r=[],autoPorts:i=Vt}={}){if(!Ot(n))return null;let o=await Oe({env:n,excludePorts:r,autoPorts:i});if(!o)return null;if(Ae(t,o),e)Zt(e,"existing","utf8");return o}import{execFileSync as At,execSync as et}from"node:child_process";import{existsSync as K,mkdirSync as Te,readFileSync as q,unlinkSync as W,writeFileSync as N}from"node:fs";import{platform as nt,tmpdir as Dt}from"node:os";var V=Dt().replaceAll("\\","/"),D=`${V}/greedysearch-chrome-metadata.json`,k=`${V}/greedysearch-chrome-launch.lock`,Me=15000,C=`${V}/greedysearch-chrome.pid`,d=`${V}/greedysearch-chrome-mode`,Z=`${V}/greedysearch-chrome-last-activity`;function H(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch{return!1}}function Ue(t){if(!H(t))return null;try{if(nt()==="win32")return At(y("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${t}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return At(y("ps"),["-p",String(t),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Ke(t,e,n=h){if(!t)return!1;let r=(u)=>String(u||"").replaceAll("\\","/").toLowerCase(),i=r(t),o=r(e);return i.includes(o)&&i.includes(`--remote-debugging-port=${n}`)&&!i.includes("--type=")}function Tt(t,e,n=h){return Ke(Ue(t),e,n)}function De(t=h){try{if(nt()==="win32"){let n=et(`${y("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),r=new RegExp(String.raw`TCP\s+\S+:${t}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),i=n.match(r);return i?Number.parseInt(i[1],10):null}let e=et(`${y("lsof")} -i :${t} -t 2>/dev/null || ${y("ss")} -tlnp 2>/dev/null | ${y("grep")} :${t} | ${y("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return e?Number.parseInt(e.split(`
319
- `)[0],10):null}catch{return null}}function Mt(t){try{if(nt()==="win32")et(`${y("taskkill")} /F /T /PID ${t}`,{stdio:"ignore"});else{try{process.kill(-t,"SIGKILL")}catch{}try{process.kill(t,"SIGKILL")}catch{}}return!0}catch{return!1}}function O(){try{if(K(D)){let t=q(D,"utf8"),e=JSON.parse(t);if(e&&typeof e.tempDir==="string"&&typeof e.debugPort==="number")return{browserPid:Number.isInteger(e.browserPid)?e.browserPid:void 0,debugPort:e.debugPort,tempDir:e.tempDir,clientPids:Array.isArray(e.clientPids)?e.clientPids.filter((n)=>Number.isInteger(n)&&n>0):[],sessionMode:e.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(e.lastActivity)?e.lastActivity:0,launchedAt:Number.isFinite(e.launchedAt)?e.launchedAt:0}}}catch{}try{let t=K(C)?Number.parseInt(q(C,"utf8").trim(),10)||void 0:void 0,e=K(d)?q(d,"utf8").trim()==="visible"?"visible":"headless":"headless",n=K(Z)?Number.parseInt(q(Z,"utf8").trim(),10)||0:0;return{browserPid:t,debugPort:h,tempDir:$,clientPids:t?[t]:[],sessionMode:e,lastActivity:n,launchedAt:0}}catch{return null}}function Y(t){try{N(D,JSON.stringify({browserPid:t.browserPid,debugPort:t.debugPort,tempDir:t.tempDir,clientPids:[...new Set(t.clientPids.filter((e)=>e>0))],sessionMode:t.sessionMode,lastActivity:t.lastActivity,launchedAt:t.launchedAt},null,2),"utf8")}catch{}try{if(t.browserPid)N(C,String(t.browserPid),"utf8")}catch{}try{N(d,t.sessionMode,"utf8")}catch{}try{N(Z,String(t.lastActivity),"utf8")}catch{}}function Ut(){try{W(D)}catch{}try{W(C)}catch{}try{W(d)}catch{}try{W(Z)}catch{}}function Ct(t){if(!t)return t;let e={...t,clientPids:[...new Set([...t.clientPids,process.pid].filter((n)=>H(n)||n===process.pid))]};return Y(e),e}function rt(t){let e=Date.now();try{if(t)Y({...t,lastActivity:e});else N(Z,String(e),"utf8")}catch{}}var Ln=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var Kt=!1;function dt(){if(Kt)return;Kt=!0;let t=O();if(!t)return;if(t.browserPid){if(!H(t.browserPid)){Mt(t.browserPid),Ut();return}if(!Tt(t.browserPid,t.tempDir,t.debugPort))Ut();else Y({...t,clientPids:t.clientPids.filter((i)=>H(i))})}let e=De();if(e&&e!==t.browserPid)if(Tt(e,$,h))Y({browserPid:e,debugPort:h,tempDir:$,clientPids:[e],sessionMode:t.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else Mt(e)}function Yt(){Te(Dt(),{recursive:!0});try{let t=JSON.stringify({pid:process.pid,ts:Date.now()});return N(k,t,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let e=q(k,"utf8");if(JSON.parse(e).pid===process.pid)W(k)}catch{}}}}catch(t){if(t?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let t=q(k,"utf8"),e=JSON.parse(t),n=Date.now()-(e.ts||0);if(!H(e.pid)||n>Me){try{W(k)}catch{}try{let i=JSON.stringify({pid:process.pid,ts:Date.now()});return N(k,i,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{W(k)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var Re=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),St=Ye().replaceAll("\\","/"),_=`${St}/greedysearch-chrome.pid`,A=`${St}/greedysearch-chrome-last-activity`,Se=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,Pe=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;function Ge(t,e=h){let n=String(t||"").toLowerCase();if(!n.includes(`--remote-debugging-port=${e}`)||n.includes("--type="))return null;return n.includes("--headless")}function Pt(){try{let t=at(),e=t?Ie(t):null,n=Ge(e);if(n!==null){try{z(J,n?"headless":"visible","utf8")}catch{}return n}}catch{}try{if(!R(J))return!0;return S(J,"utf8").trim()==="headless"}catch{return!0}}function Le(){try{z(A,String(Date.now()),"utf8")}catch{}try{let t=O();if(t)rt(t)}catch{}}function Ie(t){try{if(lt()==="win32")return zt(y("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${t}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return zt(y("ps"),["-p",String(t),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function at(){try{if(lt()==="win32"){let e=ot(`${y("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),n=new RegExp(String.raw`TCP\s+\S+:${h}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),r=e.match(n);return r?Number.parseInt(r[1],10):null}let t=ot(`${y("lsof")} -i :${h} -t 2>/dev/null || ${y("ss")} -tlnp 2>/dev/null | ${y("grep")} :${h} | ${y("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return t?Number.parseInt(t.split(`
320
- `)[0],10):null}catch{return null}}async function Fe(t=1500){try{let n=await new Promise((i,o)=>{let u=ut.get(`http://localhost:${h}/json/version`,(a)=>{let l="";a.on("data",(f)=>l+=f),a.on("end",()=>{try{i(JSON.parse(l))}catch{o(Error("bad JSON"))}})});u.on("error",o),u.setTimeout(1000,()=>{u.destroy(),o(Error("timeout"))})}),r=new globalThis.WebSocket(n.webSocketDebuggerUrl);await new Promise((i)=>{r.onopen=()=>{r.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{r.close(),i()},200)},r.onerror=()=>i(),setTimeout(i,1000)})}catch{}let e=Date.now()+t;while(Date.now()<e){if(!at())return!0;await new Promise((r)=>setTimeout(r,150))}return Ee()}function Ee(){try{let t=at();if(!t&&R(_))t=Number.parseInt(S(_,"utf8").trim(),10)||null;if(!t)return!1;if(lt()==="win32")ot(`${y("taskkill")} /F /PID ${t}`,{stdio:"ignore"});else process.kill(t,"SIGKILL");return!0}catch{return!1}}async function Gt(){if(!await Q(500)){try{p(_)}catch{}try{p(A)}catch{}try{p(J)}catch{}return!1}let e=await Fe(1500);try{p(_)}catch{}try{p(A)}catch{}try{p(J)}catch{}if(e)process.stderr.write(`[greedysearch] Killed Chrome on port ${h}.
321
- `);return e}var Rt=Gt;async function tn(){let e=Pt()?Se:Pe;if(e<=0)return!1;if(!R(A))return Le(),!1;try{let n=Number.parseInt(S(A,"utf8").trim(),10);if(!n)return!1;if((Date.now()-n)/60000>=e)return Gt()}catch{}return!1}function Q(t=3000){return new Promise((e)=>{let n=ut.get(`http://localhost:${h}/json/version`,(r)=>{r.resume(),e(r.statusCode===200)});n.on("error",()=>e(!1)),n.setTimeout(t,()=>{n.destroy(),e(!1)})})}async function it(){let t=`${X}.lock`,e=`${X}.tmp`,n=5000,r=1000,i=await new Promise((o)=>{let u=Date.now(),a=()=>{try{let l=JSON.stringify({pid:process.pid,ts:Date.now()});z(t,l,{encoding:"utf8",flag:"wx"}),o(!0)}catch(l){if(l?.code!=="EEXIST"){if(Date.now()-u<1000)setTimeout(a,50);else o(!1);return}try{let f=S(t,"utf8").trim(),c=f.startsWith("{")?JSON.parse(f):{ts:Number(f)},b=Number(c?.ts)||0;if(b>0&&Date.now()-b>5000)try{p(t)}catch{}if(Date.now()-u<1000)setTimeout(a,50);else o(!1)}catch{if(Date.now()-u<1000)setTimeout(a,50);else o(!1)}}};a()});try{let o=await new Promise((f,c)=>{let b=ut.get(`http://localhost:${h}/json/version`,(s)=>{let m="";s.on("data",(P)=>m+=P),s.on("end",()=>f(m))});b.on("error",c),b.setTimeout(3000,()=>{b.destroy(),c(Error("timeout"))})}),{webSocketDebuggerUrl:u}=JSON.parse(o),a=new URL(u),l=`${a.pathname}${a.search}`;if(i){z(e,`localhost:${h}
322
- ${l}`,"utf8");try{p(X)}catch{}de(e,X)}}catch{}finally{if(i)try{p(t)}catch{}}}async function Lt(){let t=R(_)||!!O(),e=await _t({activePortFile:X,modeFile:J,excludePorts:t?[h]:[]});if(e){process.stderr.write(`[greedysearch] Reusing existing browser CDP endpoint ${e.httpUrl} (${e.source}).
323
- `);return}dt();let n=await tn(),r=n?!1:await Q();if(!r&&!n)await new Promise((a)=>setTimeout(a,500)),r=await Q();let i=!1;if(r){let a=Pt(),l=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!l&&!a)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
324
- `),await Rt(),await new Promise((f)=>setTimeout(f,1000)),i=!0;else if(l&&a)process.stderr.write(`[greedysearch] Headless Chrome detected — switching to visible mode...
325
- `),await Rt(),await new Promise((f)=>setTimeout(f,1000)),i=!0}if(i?!1:await Q()){await it();try{let a=O();if(a)rt(a),Ct(a)}catch{}return}let u=Yt();if(!u.acquired){if(await new Promise((l)=>setTimeout(l,3000)),await Q(5000)){await it();return}}try{if(await Q(1000)){await it();return}process.stderr.write(`GreedySearch Chrome not running on port ${h} — auto-launching...
326
- `);let l=[ze(Re,"..","..","bin","launch.mjs")];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")l.push("--headless");await new Promise((f,c)=>{Ce(Wt(),l,{stdio:["ignore",process.stderr,process.stderr]}).on("close",(s)=>s===0?f():c(Error("launch.mjs failed")))})}finally{u.release()}}import{randomInt as en}from"node:crypto";import{existsSync as nn,readFileSync as rn}from"node:fs";import on from"node:http";var un=`
318
+ `}function Me(t,e){Xe(He(t),{recursive:!0});let n=`${t}.tmp-${process.pid}`;Zt(n,Ue(e),"utf8");try{Ne(t)}catch{}qe(n,t)}async function _t({activePortFile:t,modeFile:e,env:n=process.env,excludePorts:r=[],autoPorts:i=jt}={}){if(!Ot(n))return null;let u=await Ke({env:n,excludePorts:r,autoPorts:i});if(!u)return null;if(Me(t,u),e)Zt(e,"existing","utf8");return u}import{existsSync as Ce}from"node:fs";import{dirname as ze,join as Q}from"node:path";function Se(t){let e=new Set;return t.filter((n)=>{if(!n||e.has(n))return!1;return e.add(n),!0})}function Ye({moduleDir:t,entrypoint:e=process.argv[1],env:n=process.env}={}){let r=e?ze(e):null,i=n.GREEDY_SEARCH_EXTENSION_DIR?.trim()||null;return Se([i?Q(i,"bin","launch.mjs"):null,t?Q(t,"launch.mjs"):null,t?Q(t,"..","bin","launch.mjs"):null,t?Q(t,"..","..","bin","launch.mjs"):null,r?Q(r,"launch.mjs"):null,r?Q(r,"..","bin","launch.mjs"):null])}function At({moduleDir:t,entrypoint:e=process.argv[1],env:n=process.env,exists:r=Ce}={}){let i=Ye({moduleDir:t,entrypoint:e,env:n}),u=i.find((o)=>r(o));if(u)return u;throw Error(`GreedySearch launcher not found. Checked candidates:
319
+ ${i.map((o)=>`- ${o}`).join(`
320
+ `)}`)}import{execFileSync as De}from"node:child_process";import{platform as Re}from"node:os";function Pe(t,e){return De(v(t),e,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000})}function Ge(t){let e=String(t||"").match(/\b(\d+)\b/);return e?Number.parseInt(e[1],10):null}function Le(t){return Ge(t)}function Ie(t,e){for(let n of String(t||"").split(/\r?\n/)){if(!/\bLISTEN\b/i.test(n))continue;if(!n.trim().split(/\s+/).slice(0,6).some((u)=>u.endsWith(`:${e}`)))continue;let i=n.match(/\bpid=(\d+)\b/);if(i)return Number.parseInt(i[1],10)}return null}function de(t,e){for(let n of String(t||"").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(`:${e}`))continue;let u=Number.parseInt(r.at(-1),10);if(Number.isInteger(u)&&u>0)return u}return null}function rt(t,e,n){try{return t(e,n)}catch{return null}}function Y(t,{platformName:e=Re(),run:n=Pe}={}){if(e==="win32")return de(rt(n,"netstat",["-ano","-p","TCP"]),t);let r=rt(n,"lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"]),i=Le(r);if(i)return i;if(e!=="linux")return null;return Ie(rt(n,"ss",["-ltnp"]),t)}import{execFileSync as Tt,execSync as br}from"node:child_process";import{existsSync as W,mkdirSync as Fe,readFileSync as H,unlinkSync as X,writeFileSync as q}from"node:fs";import{platform as Ee,tmpdir as Ct}from"node:os";var T=Ct().replaceAll("\\","/"),D=`${T}/greedysearch-chrome-metadata.json`,k=`${T}/greedysearch-chrome-launch.lock`,tn=15000,O=`${T}/greedysearch-chrome.pid`,_=`${T}/greedysearch-chrome-mode`,B=`${T}/greedysearch-chrome-last-activity`;function A(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch{return!1}}function en(t){if(!A(t))return null;try{if(Ee()==="win32")return Tt(v("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${t}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return Tt(v("ps"),["-p",String(t),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function it(t,e,n=h){if(!t)return!1;let r=(o)=>String(o||"").replaceAll("\\","/").toLowerCase(),i=r(t),u=r(e);return i.includes(u)&&i.includes(`--remote-debugging-port=${n}`)&&!i.includes("--type=")}function Kt(t,e,n=h){return it(en(t),e,n)}function nn(t=h){return Y(t)}function K(){try{if(W(D)){let t=H(D,"utf8"),e=JSON.parse(t);if(e&&typeof e.tempDir==="string"&&typeof e.debugPort==="number")return{browserPid:Number.isInteger(e.browserPid)?e.browserPid:void 0,debugPort:e.debugPort,tempDir:e.tempDir,clientPids:Array.isArray(e.clientPids)?e.clientPids.filter((n)=>Number.isInteger(n)&&n>0):[],sessionMode:e.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(e.lastActivity)?e.lastActivity:0,launchedAt:Number.isFinite(e.launchedAt)?e.launchedAt:0}}}catch{}try{if(!(W(O)||W(_)||W(B)))return null;let e=W(O)?Number.parseInt(H(O,"utf8").trim(),10)||void 0:void 0,n=W(_)?H(_,"utf8").trim()==="visible"?"visible":"headless":"headless",r=W(B)?Number.parseInt(H(B,"utf8").trim(),10)||0:0;return{browserPid:e,debugPort:h,tempDir:$,clientPids:e?[e]:[],sessionMode:n,lastActivity:r,launchedAt:0}}catch{return null}}function R(t){try{q(D,JSON.stringify({browserPid:t.browserPid,debugPort:t.debugPort,tempDir:t.tempDir,clientPids:[...new Set(t.clientPids.filter((e)=>e>0))],sessionMode:t.sessionMode,lastActivity:t.lastActivity,launchedAt:t.launchedAt},null,2),"utf8")}catch{}try{if(t.browserPid)q(O,String(t.browserPid),"utf8")}catch{}try{q(_,t.sessionMode,"utf8")}catch{}try{q(B,String(t.lastActivity),"utf8")}catch{}}function Ut(){try{X(D)}catch{}try{X(O)}catch{}try{X(_)}catch{}try{X(B)}catch{}}function zt(t){if(!t)return t;let e={...t,clientPids:[...new Set([...t.clientPids,process.pid].filter((n)=>A(n)||n===process.pid))]};return R(e),e}function ut(t){let e=Date.now();try{if(t)R({...t,lastActivity:e});else q(B,String(e),"utf8")}catch{}}var xr=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var Mt=!1;function St(){if(Mt)return;Mt=!0;let t=K();if(!t)return;if(t.browserPid){if(!A(t.browserPid)){Ut();return}if(!Kt(t.browserPid,t.tempDir,t.debugPort))Ut();else R({...t,clientPids:t.clientPids.filter((i)=>A(i))})}let e=nn();if(e&&e!==t.browserPid)if(Kt(e,$,h))R({browserPid:e,debugPort:h,tempDir:$,clientPids:[e],sessionMode:t.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else return}function Yt(){Fe(Ct(),{recursive:!0});try{let t=JSON.stringify({pid:process.pid,ts:Date.now()});return q(k,t,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let e=H(k,"utf8");if(JSON.parse(e).pid===process.pid)X(k)}catch{}}}}catch(t){if(t?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let t=H(k,"utf8"),e=JSON.parse(t),n=Date.now()-(e.ts||0);if(!A(e.pid)||n>tn){try{X(k)}catch{}try{let i=JSON.stringify({pid:process.pid,ts:Date.now()});return q(k,i,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{X(k)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var fn=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),Gt=ln().replaceAll("\\","/"),U=`${Gt}/greedysearch-chrome.pid`,M=`${Gt}/greedysearch-chrome-last-activity`,an=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,cn=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;function gn(t,e=h){let n=String(t||"").toLowerCase();if(!n.includes(`--remote-debugging-port=${e}`)||n.includes("--type="))return null;return n.includes("--headless")}function Lt(){try{let t=ft(),e=t?It(t):null,n=gn(e);if(n!==null){try{P(p,n?"headless":"visible","utf8")}catch{}return n}}catch{}try{if(!G(p))return!0;return L(p,"utf8").trim()==="headless"}catch{return!0}}function sn(){try{P(M,String(Date.now()),"utf8")}catch{}try{let t=K();if(t)ut(t)}catch{}}function It(t){try{if(Pt()==="win32")return Dt(v("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${t}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return Dt(v("ps"),["-p",String(t),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function ft(){return Y(h)}function dt(){let t=[ft()];if(G(U))t.push(Number.parseInt(L(U,"utf8").trim(),10)||null);for(let e of t){if(!e)continue;if(it(It(e),$,h))return e}return null}async function bn(t=1500){let e=dt();if(!e)return!1;try{let r=await new Promise((u,o)=>{let f=lt.get(`http://localhost:${h}/json/version`,(l)=>{let a="";l.on("data",(c)=>a+=c),l.on("end",()=>{try{u(JSON.parse(a))}catch{o(Error("bad JSON"))}})});f.on("error",o),f.setTimeout(1000,()=>{f.destroy(),o(Error("timeout"))})}),i=new globalThis.WebSocket(r.webSocketDebuggerUrl);await new Promise((u)=>{i.onopen=()=>{i.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{i.close(),u()},200)},i.onerror=()=>u(),setTimeout(u,1000)})}catch{}let n=Date.now()+t;while(Date.now()<n){let r=ft();if(!r)return!0;if(r!==e)return!0;await new Promise((i)=>setTimeout(i,150))}return hn()}function hn(){try{let t=dt();if(!t)return!1;if(Pt()==="win32")un(`${v("taskkill")} /F /PID ${t}`,{stdio:"ignore"});else process.kill(t,"SIGKILL");return!0}catch{return!1}}async function Ft(){if(!await Z(500)){try{x(U)}catch{}try{x(M)}catch{}try{x(p)}catch{}return!1}let e=await bn(1500);try{x(U)}catch{}try{x(M)}catch{}try{x(p)}catch{}if(e)process.stderr.write(`[greedysearch] Killed Chrome on port ${h}.
321
+ `);return e}var Rt=Ft;async function yn(){let e=Lt()?an:cn;if(e<=0)return!1;if(!G(M))return sn(),!1;try{let n=Number.parseInt(L(M,"utf8").trim(),10);if(!n)return!1;if((Date.now()-n)/60000>=e)return Ft()}catch{}return!1}function Z(t=3000){return new Promise((e)=>{let n=lt.get(`http://localhost:${h}/json/version`,(r)=>{r.resume(),e(r.statusCode===200)});n.on("error",()=>e(!1)),n.setTimeout(t,()=>{n.destroy(),e(!1)})})}async function ot(){let t=`${N}.lock`,e=`${N}.tmp`,n=5000,r=1000,i=await new Promise((u)=>{let o=Date.now(),f=()=>{try{let l=JSON.stringify({pid:process.pid,ts:Date.now()});P(t,l,{encoding:"utf8",flag:"wx"}),u(!0)}catch(l){if(l?.code!=="EEXIST"){if(Date.now()-o<1000)setTimeout(f,50);else u(!1);return}try{let a=L(t,"utf8").trim(),c=a.startsWith("{")?JSON.parse(a):{ts:Number(a)},b=Number(c?.ts)||0;if(b>0&&Date.now()-b>5000)try{x(t)}catch{}if(Date.now()-o<1000)setTimeout(f,50);else u(!1)}catch{if(Date.now()-o<1000)setTimeout(f,50);else u(!1)}}};f()});try{let u=await new Promise((a,c)=>{let b=lt.get(`http://localhost:${h}/json/version`,(s)=>{let w="";s.on("data",(I)=>w+=I),s.on("end",()=>a(w))});b.on("error",c),b.setTimeout(3000,()=>{b.destroy(),c(Error("timeout"))})}),{webSocketDebuggerUrl:o}=JSON.parse(u),f=new URL(o),l=`${f.pathname}${f.search}`;if(i){P(e,`localhost:${h}
322
+ ${l}`,"utf8");try{x(N)}catch{}on(e,N)}}catch{}finally{if(i)try{x(t)}catch{}}}async function Et(){let t=G(U)||!!K(),e=await _t({activePortFile:N,modeFile:p,excludePorts:t?[h]:[]});if(e){process.stderr.write(`[greedysearch] Reusing existing browser CDP endpoint ${e.httpUrl} (${e.source}).
323
+ `);return}St();let n=await yn(),r=n?!1:await Z();if(!r&&!n)await new Promise((f)=>setTimeout(f,500)),r=await Z();let i=!1;if(r){let f=Lt(),l=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!l&&!f)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
324
+ `),await Rt(),await new Promise((a)=>setTimeout(a,1000)),i=!0;else if(l&&f)process.stderr.write(`[greedysearch] Headless Chrome detected — switching to visible mode...
325
+ `),await Rt(),await new Promise((a)=>setTimeout(a,1000)),i=!0}if(i?!1:await Z()){await ot();try{let f=K();if(f)ut(f),zt(f)}catch{}return}let o=Yt();if(!o.acquired){let f=Date.now()+15000;while(Date.now()<f)if(await new Promise((l)=>setTimeout(l,250)),await Z(1000)){await ot();return}throw Error(`Timed out waiting for another GreedySearch launcher on port ${h}`)}try{if(await Z(1000)){await ot();return}process.stderr.write(`GreedySearch Chrome not running on port ${h} — auto-launching...
326
+ `);let l=[At({moduleDir:fn,entrypoint:process.argv[1]})];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")l.push("--headless");await new Promise((a,c)=>{rn(kt(),l,{stdio:["ignore",process.stderr,process.stderr]}).on("close",(s)=>s===0?a():c(Error("launch.mjs failed")))})}finally{o.release()}}import{randomInt as wn}from"node:crypto";import{existsSync as vn,readFileSync as mn}from"node:fs";import xn from"node:http";var $n=`
327
327
  (function() {
328
328
  // Google consent page (consent.google.com)
329
329
  var g = document.querySelector('#L2AGLb, button[jsname="b3VHJd"], .tHlp8d');
@@ -340,7 +340,7 @@ ${l}`,"utf8");try{p(X)}catch{}de(e,X)}}catch{}finally{if(i)try{p(t)}catch{}}}asy
340
340
 
341
341
  return null;
342
342
  })()
343
- `,ln=`
343
+ `,Jn=`
344
344
  (function() {
345
345
  var url = document.location.href;
346
346
 
@@ -410,7 +410,7 @@ ${l}`,"utf8");try{p(X)}catch{}de(e,X)}}catch{}finally{if(i)try{p(t)}catch{}}}asy
410
410
 
411
411
  return null;
412
412
  })()
413
- `,an=`
413
+ `,pn=`
414
414
  (function() {
415
415
  var url = document.location.href;
416
416
  var isVerifyPage = url.includes('/sorry/') ||
@@ -444,26 +444,26 @@ ${l}`,"utf8");try{p(X)}catch{}de(e,X)}}catch{}finally{if(i)try{p(t)}catch{}}}asy
444
444
 
445
445
  return 'still-verifying';
446
446
  })()
447
- `;async function Ft(t,e){let n=await e(["eval",t,un]).catch(()=>null);if(n&&n!=="null")await new Promise((r)=>setTimeout(r,1500))}function w(t,e){return en(t*1000,e*1000)/1000}async function fn(t,e){if(!globalThis.WebSocket)return;let n=process.env.CDP_PROFILE_DIR;if(!n)return;let r=`${n.replaceAll("\\","/")}/DevToolsActivePort`;if(!nn(r))return;let i=rn(r,"utf8").trim().split(`
448
- `)[0],o=await new Promise((l,f)=>{let c=on.get(`http://localhost:${i}/json/version`,(b)=>{let s="";b.on("data",(m)=>s+=m),b.on("end",()=>{try{l(JSON.parse(s))}catch{f(Error("bad JSON"))}})});c.on("error",f),c.setTimeout(1000,()=>{c.destroy(),f(Error("timeout"))})}),u=new globalThis.WebSocket(o.webSocketDebuggerUrl),a=0;await new Promise((l)=>{u.onopen=async()=>{let f=(s,m)=>new Promise((P)=>{let ct=++a,gt=(ne)=>{if(JSON.parse(ne.data).id===ct)u.removeEventListener("message",gt),P()};u.addEventListener("message",gt),u.send(JSON.stringify({id:ct,method:s,params:m}))}),c=t+w(-2,2),b=e+w(-2,2);await f("Input.dispatchMouseEvent",{type:"mouseMoved",x:c,y:b,button:"none"}),await new Promise((s)=>setTimeout(s,w(80,160))),await f("Input.dispatchMouseEvent",{type:"mousePressed",x:c,y:b,button:"left",clickCount:1}),await new Promise((s)=>setTimeout(s,w(30,80))),await f("Input.dispatchMouseEvent",{type:"mouseReleased",x:c+w(-1,1),y:b+w(-1,1),button:"left",clickCount:1}),setTimeout(()=>{u.close(),l()},200)},u.onerror=()=>l(),setTimeout(l,3000)})}async function Et(t,e,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 u={button:"left",clickCount:1,modifiers:0},a=i+w(-3,3),l=o+w(-3,3);await e(["evalraw",t,"Input.dispatchMouseEvent",JSON.stringify({...u,type:"mouseMoved",x:a,y:l})]),await new Promise((m)=>setTimeout(m,w(80,180)));let f=i+w(-2,2),c=o+w(-2,2);await e(["evalraw",t,"Input.dispatchMouseEvent",JSON.stringify({...u,type:"mousePressed",x:f,y:c})]),await new Promise((m)=>setTimeout(m,w(30,90)));let b=f+w(-1,1),s=c+w(-1,1);return await e(["evalraw",t,"Input.dispatchMouseEvent",JSON.stringify({...u,type:"mouseReleased",x:b,y:s})]),await fn(i,o).catch(()=>{}),await new Promise((m)=>setTimeout(m,w(100,300))),`human-clicked at (${i.toFixed(0)}, ${o.toFixed(0)})`}async function cn(t,e,n){let r=await e(["eval",t,`(function() {
447
+ `;async function ee(t,e){let n=await e(["eval",t,$n]).catch(()=>null);if(n&&n!=="null")await new Promise((r)=>setTimeout(r,1500))}function y(t,e){return wn(t*1000,e*1000)/1000}async function Wn(t,e){if(!globalThis.WebSocket)return;let n=process.env.CDP_PROFILE_DIR;if(!n)return;let r=`${n.replaceAll("\\","/")}/DevToolsActivePort`;if(!vn(r))return;let i=mn(r,"utf8").trim().split(`
448
+ `)[0],u=await new Promise((l,a)=>{let c=xn.get(`http://localhost:${i}/json/version`,(b)=>{let s="";b.on("data",(w)=>s+=w),b.on("end",()=>{try{l(JSON.parse(s))}catch{a(Error("bad JSON"))}})});c.on("error",a),c.setTimeout(1000,()=>{c.destroy(),a(Error("timeout"))})}),o=new globalThis.WebSocket(u.webSocketDebuggerUrl),f=0;await new Promise((l)=>{o.onopen=async()=>{let a=(s,w)=>new Promise((I)=>{let ct=++f,gt=(ue)=>{if(JSON.parse(ue.data).id===ct)o.removeEventListener("message",gt),I()};o.addEventListener("message",gt),o.send(JSON.stringify({id:ct,method:s,params:w}))}),c=t+y(-2,2),b=e+y(-2,2);await a("Input.dispatchMouseEvent",{type:"mouseMoved",x:c,y:b,button:"none"}),await new Promise((s)=>setTimeout(s,y(80,160))),await a("Input.dispatchMouseEvent",{type:"mousePressed",x:c,y:b,button:"left",clickCount:1}),await new Promise((s)=>setTimeout(s,y(30,80))),await a("Input.dispatchMouseEvent",{type:"mouseReleased",x:c+y(-1,1),y:b+y(-1,1),button:"left",clickCount:1}),setTimeout(()=>{o.close(),l()},200)},o.onerror=()=>l(),setTimeout(l,3000)})}async function ne(t,e,n,r){let i=Number.parseFloat(n),u=Number.parseFloat(r);if(Number.isNaN(i)||Number.isNaN(u))throw Error(`humanClickXY: invalid coordinates (${n}, ${r})`);let o={button:"left",clickCount:1,modifiers:0},f=i+y(-3,3),l=u+y(-3,3);await e(["evalraw",t,"Input.dispatchMouseEvent",JSON.stringify({...o,type:"mouseMoved",x:f,y:l})]),await new Promise((w)=>setTimeout(w,y(80,180)));let a=i+y(-2,2),c=u+y(-2,2);await e(["evalraw",t,"Input.dispatchMouseEvent",JSON.stringify({...o,type:"mousePressed",x:a,y:c})]),await new Promise((w)=>setTimeout(w,y(30,90)));let b=a+y(-1,1),s=c+y(-1,1);return await e(["evalraw",t,"Input.dispatchMouseEvent",JSON.stringify({...o,type:"mouseReleased",x:b,y:s})]),await Wn(i,u).catch(()=>{}),await new Promise((w)=>setTimeout(w,y(100,300))),`human-clicked at (${i.toFixed(0)}, ${u.toFixed(0)})`}async function kn(t,e,n){let r=await e(["eval",t,`(function() {
449
449
  var el = document.querySelector('${n.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}');
450
450
  if (!el) return 'null';
451
451
  var r = el.getBoundingClientRect();
452
452
  return JSON.stringify({x: r.left + r.width / 2, y: r.top + r.height / 2, w: r.width, h: r.height});
453
- })()`]).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:u}=i;return Et(t,e,o,u)}async function It(t,e,n){if(!n||n==="null"||n==="cleared"||n==="still-verifying")return!1;try{let r=JSON.parse(n);if(r.t==="sel"&&r.s)return process.stderr.write(`[greedysearch] Human-clicking "${r.txt}" via CDP...
454
- `),await cn(t,e,r.s)!==null;if(r.t==="xy"){if(!r.x&&!r.y)return!1;return process.stderr.write(`[greedysearch] Human-clicking at (${r.x.toFixed(0)}, ${r.y.toFixed(0)})...
455
- `),await Et(t,e,r.x,r.y),!0}}catch{}return!1}async function gn(t,e){let n=await e(["eval",t,ln]).catch(()=>null);return n&&n!=="null"?n:null}async function te(t,e,n=30000){let r=await gn(t,e);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)...
456
- `);let i=Date.now()+n;while(Date.now()<i)if(await new Promise((o)=>setTimeout(o,2000)),!(await e(["eval",t,"document.location.href"]).catch(()=>"")).includes("/sorry/"))return"cleared-by-user";return"needs-human"}if(await It(t,e,r)){await new Promise((o)=>setTimeout(o,2000));let i=Date.now()+n;while(Date.now()<i){let o=await e(["eval",t,an]).catch(()=>null);if(o==="cleared"||!o||o==="null")return process.stderr.write(`[greedysearch] Verification cleared.
457
- `),"clicked";if(o!=="still-verifying")await It(t,e,o),await new Promise((u)=>setTimeout(u,2000));else await new Promise((u)=>setTimeout(u,1500))}return process.stderr.write(`[greedysearch] Verification may require manual intervention.
458
- `),"needs-human"}return"clear"}var ee={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 j=ee.gemini,ft="__geminiClipboard";async function sn(t,e){if(await g(["click",t,j.input]),await new Promise((r)=>setTimeout(r,B(200))),await G(["type",t,"--stdin"],e),await new Promise((r)=>setTimeout(r,B(300))),await g(["eval",t,`(function() {
459
- var el = document.querySelector('${j.input}');
453
+ })()`]).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:u,y:o}=i;return ne(t,e,u,o)}async function te(t,e,n){if(!n||n==="null"||n==="cleared"||n==="still-verifying")return!1;try{let r=JSON.parse(n);if(r.t==="sel"&&r.s)return process.stderr.write(`[greedysearch] Human-clicking "${r.txt}" via CDP...
454
+ `),await kn(t,e,r.s)!==null;if(r.t==="xy"){if(!r.x&&!r.y)return!1;return process.stderr.write(`[greedysearch] Human-clicking at (${r.x.toFixed(0)}, ${r.y.toFixed(0)})...
455
+ `),await ne(t,e,r.x,r.y),!0}}catch{}return!1}async function Xn(t,e){let n=await e(["eval",t,Jn]).catch(()=>null);return n&&n!=="null"?n:null}async function re(t,e,n=30000){let r=await Xn(t,e);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)...
456
+ `);let i=Date.now()+n;while(Date.now()<i)if(await new Promise((u)=>setTimeout(u,2000)),!(await e(["eval",t,"document.location.href"]).catch(()=>"")).includes("/sorry/"))return"cleared-by-user";return"needs-human"}if(await te(t,e,r)){await new Promise((u)=>setTimeout(u,2000));let i=Date.now()+n;while(Date.now()<i){let u=await e(["eval",t,pn]).catch(()=>null);if(u==="cleared"||!u||u==="null")return process.stderr.write(`[greedysearch] Verification cleared.
457
+ `),"clicked";if(u!=="still-verifying")await te(t,e,u),await new Promise((o)=>setTimeout(o,2000));else await new Promise((o)=>setTimeout(o,1500))}return process.stderr.write(`[greedysearch] Verification may require manual intervention.
458
+ `),"needs-human"}return"clear"}var ie={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 V=ie.gemini,at="__geminiClipboard";async function qn(t,e){if(await g(["click",t,V.input]),await new Promise((r)=>setTimeout(r,j(200))),await d(["type",t,"--stdin"],e),await new Promise((r)=>setTimeout(r,j(300))),await g(["eval",t,`(function() {
459
+ var el = document.querySelector('${V.input}');
460
460
  if (!el) return false;
461
461
  var content = el.innerText || el.textContent || '';
462
462
  return content.trim().length >= ${Math.floor(e.length*0.8)};
463
- })()`])!=="true")throw Error("Gemini input field did not accept text — input verification failed")}async function bn(t){await g(["eval",t,`(function() {
463
+ })()`])!=="true")throw Error("Gemini input field did not accept text — input verification failed")}async function Nn(t){await g(["eval",t,`(function() {
464
464
  const chat = document.querySelector('chat-window, [role="main"], main') || document.body;
465
465
  chat.scrollTo ? chat.scrollTo({ top: chat.scrollHeight, behavior: 'smooth' }) : window.scrollTo(0, document.body.scrollHeight);
466
- })()`])}async function hn(t){let e=await g(["eval",t,String.raw`
466
+ })()`])}async function Qn(t){let e=await g(["eval",t,String.raw`
467
467
  (() => {
468
468
  // The model-response element is a custom element <model-response>.
469
469
  // Its innerText starts with the "Gemini said" label in the
@@ -491,7 +491,7 @@ ${l}`,"utf8");try{p(X)}catch{}de(e,X)}}catch{}finally{if(i)try{p(t)}catch{}}}asy
491
491
  }
492
492
  return JSON.stringify({ answer, sources });
493
493
  })()
494
- `]);try{return JSON.parse(e)}catch{return{answer:"",sources:[]}}}async function yn(t,e=""){let n=e.toLowerCase().trim(),r=!1,i=Date.now()+12000;while(Date.now()<i){if(await g(["eval",t,String.raw`(() => {
494
+ `]);try{return JSON.parse(e)}catch{return{answer:"",sources:[]}}}async function Hn(t,e=""){let n=e.toLowerCase().trim(),r=!1,i=Date.now()+12000;while(Date.now()<i){if(await g(["eval",t,String.raw`(() => {
495
495
  const r = document.querySelector('model-response');
496
496
  if (!r) return false;
497
497
  const t = (r.innerText || '').trim();
@@ -502,16 +502,16 @@ ${l}`,"utf8");try{p(X)}catch{}de(e,X)}}catch{}finally{if(i)try{p(t)}catch{}}}asy
502
502
  })()`])===!0){r=!0;break}await new Promise((b)=>setTimeout(b,800))}if(!r)console.error("[gemini] Warning: model-response did not render content");await g(["eval",t,`(() => {
503
503
  const resp = document.querySelector('model-response');
504
504
  if (!resp) return 'no-model-response';
505
- const btn = resp.querySelector('${j.copyButton}');
505
+ const btn = resp.querySelector('${V.copyButton}');
506
506
  if (!btn) return 'no-copy-button';
507
507
  btn.click();
508
508
  return 'clicked';
509
- })()`]),await new Promise((c)=>setTimeout(c,600));let o=await g(["eval",t,`window.${ft} || ''`]);if(o&&n&&(o.toLowerCase().trim()===n||o.trim().length<n.length))console.error("[gemini] Clipboard echoed query, retrying in 2s..."),await new Promise((c)=>setTimeout(c,2000)),await g(["eval",t,`(() => {
509
+ })()`]),await new Promise((c)=>setTimeout(c,600));let u=await g(["eval",t,`window.${at} || ''`]);if(u&&n&&(u.toLowerCase().trim()===n||u.trim().length<n.length))console.error("[gemini] Clipboard echoed query, retrying in 2s..."),await new Promise((c)=>setTimeout(c,2000)),await g(["eval",t,`(() => {
510
510
  const resp = document.querySelector('model-response');
511
511
  if (!resp) return 'no-model-response';
512
- const btn = resp.querySelector('${j.copyButton}');
512
+ const btn = resp.querySelector('${V.copyButton}');
513
513
  if (!btn) return 'no-copy-button';
514
514
  btn.click();
515
515
  return 'clicked';
516
- })()`]),await new Promise((c)=>setTimeout(c,600)),o=await g(["eval",t,`window.${ft} || ''`]);let u=null;if(!o||n&&(o.toLowerCase().trim()===n||o.trim().length<n.length)){if(u=await hn(t),u.answer)o=u.answer}if(!o)throw Error("Gemini returned no answer — model-response never rendered content");let a=yt(o),l=new Map;for(let c of[...u?.sources||[],...a])if(c?.url&&!l.has(c.url))l.set(c.url,c);let f=Array.from(l.values()).slice(0,10);return{answer:o.trim(),sources:f}}var wn=`Usage: node extractors/gemini.mjs "<query>" [--tab <prefix>]
517
- `;async function mn(){let t=await vt(process.argv.slice(2));xt(t,wn);let{query:e,tabPrefix:n,short:r}=pt(t);if(process.env.GREEDY_SEARCH_VISIBLE!=="1"&&process.env.GREEDY_SEARCH_ALWAYS_VISIBLE!=="1")process.env.GREEDY_SEARCH_HEADLESS="1";await Lt();try{await g(["list"]);let i=await st(n),o=await g(["eval",i,"document.location.href"]).catch(()=>""),u=!1;try{let s=new URL(o).hostname.toLowerCase();u=s==="gemini.google.com"||s.endsWith(".gemini.google.com")}catch{}if(!u)await g(["nav",i,"https://gemini.google.com/app"],20000),await new Promise((s)=>setTimeout(s,600));await Ft(i,g),await te(i,g,1e4),await mt(i,j.input,8000,T.inputPoll),await new Promise((s)=>setTimeout(s,B(T.postClick))),await bt(i,ft),await sn(i,e),await new Promise((s)=>setTimeout(s,B(T.postType))),await g(["eval",i,`document.querySelector('${j.sendButton}')?.click()`]);let a=0,l=setInterval(()=>{if(++a%10===0)bn(i).catch(()=>null)},6000);try{await wt(i,{timeout:45000,minLength:50})}finally{clearInterval(l)}let{answer:f,sources:c}=await yn(i,e);if(!f)throw Error("No answer captured from Gemini clipboard");let b=await g(["eval",i,"document.location.href"]).catch(()=>"https://gemini.google.com/app");Jt({query:e,url:b,answer:$t(f,r),sources:c})}catch(i){kt(i)}}mn();
516
+ })()`]),await new Promise((c)=>setTimeout(c,600)),u=await g(["eval",t,`window.${at} || ''`]);let o=null;if(!u||n&&(u.toLowerCase().trim()===n||u.trim().length<n.length)){if(o=await Qn(t),o.answer)u=o.answer}if(!u)throw Error("Gemini returned no answer — model-response never rendered content");let f=yt(u),l=new Map;for(let c of[...o?.sources||[],...f])if(c?.url&&!l.has(c.url))l.set(c.url,c);let a=Array.from(l.values()).slice(0,10);return{answer:u.trim(),sources:a}}var Bn=`Usage: node extractors/gemini.mjs "<query>" [--tab <prefix>]
517
+ `;async function Zn(){let t=await mt(process.argv.slice(2));$t(t,Bn);let{query:e,tabPrefix:n,short:r}=xt(t);if(process.env.GREEDY_SEARCH_VISIBLE!=="1"&&process.env.GREEDY_SEARCH_ALWAYS_VISIBLE!=="1")process.env.GREEDY_SEARCH_HEADLESS="1";await Et();try{await g(["list"]);let i=await st(n),u=await g(["eval",i,"document.location.href"]).catch(()=>""),o=!1;try{let s=new URL(u).hostname.toLowerCase();o=s==="gemini.google.com"||s.endsWith(".gemini.google.com")}catch{}if(!o)await g(["nav",i,"https://gemini.google.com/app"],20000),await new Promise((s)=>setTimeout(s,600));await ee(i,g),await re(i,g,1e4),await vt(i,V.input,8000,C.inputPoll),await new Promise((s)=>setTimeout(s,j(C.postClick))),await bt(i,at),await qn(i,e),await new Promise((s)=>setTimeout(s,j(C.postType))),await g(["eval",i,`document.querySelector('${V.sendButton}')?.click()`]);let f=0,l=setInterval(()=>{if(++f%10===0)Nn(i).catch(()=>null)},6000);try{await wt(i,{timeout:45000,minLength:50})}finally{clearInterval(l)}let{answer:a,sources:c}=await Hn(i,e);if(!a)throw Error("No answer captured from Gemini clipboard");let b=await g(["eval",i,"document.location.href"]).catch(()=>"https://gemini.google.com/app");pt({query:e,url:b,answer:Jt(a,r),sources:c})}catch(i){Wt(i)}}Zn();