@duckmind/dm-darwin-x64 0.42.7 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
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}
4
- `)}return i}async function bt(t,e){let n=`
2
+ import{randomInt as ie}from"node:crypto";import{spawn as oe}from"node:child_process";import{dirname as ue,join as le}from"node:path";import{fileURLToPath as ae}from"node:url";import{basename as fe}from"node:path";function ce(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=fe(e||"").toLowerCase();if(r==="node"||r==="node.exe")return e;return"node"}var ge=ue(ae(import.meta.url)),se=le(ge,"..","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=oe(ce(),[se,...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 bt(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 yt(i)}catch(o){process.stderr.write(`[getOrOpenTab] stealth injection failed: ${o.message}
4
+ `)}return i}async function ht(t,e){let n=`
5
5
  (() => {
6
6
  window.${e} = null;
7
7
  const _clipboard = navigator.clipboard;
@@ -38,7 +38,7 @@ import{randomInt as re}from"node:crypto";import{spawn as ie}from"node:child_proc
38
38
  catch (_) { return undefined; }
39
39
  };
40
40
  })();
41
- `;await g(["eval",t,n])}async function ht(t){await g(["evalraw",t,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
41
+ `;await g(["eval",t,n])}async function yt(t){await g(["evalraw",t,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
42
42
  (function() {
43
43
  // ── Runtime.enable / CDP detection masking ──────────────
44
44
  try { delete window.__REBROWSER_RUNTIME_ENABLE; } catch(_) {}
@@ -246,7 +246,7 @@ 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 wt(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 M={postNav:800,postNavSlow:1200,postClick:300,postType:300,inputPoll:400,copyPoll:600,afterVerify:1500};function B(t){let e=t*0.4,n=ie(-Math.floor(e),Math.floor(e)+1);return Math.max(50,Math.round(t+n))}async function mt(t,e={}){let{timeout:n=20000,interval:r=600,stableRounds:i=3,selector:o="document.body",minLength:u=0}=e,a=String.raw`
250
250
  new Promise((resolve, reject) => {
251
251
  const _deadline = Date.now() + ${n};
252
252
  const _baseInterval = ${r};
@@ -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,a],n+1e4),f=parseInt(l,10)||0;if(f>=u)return f;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 pt(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 xt(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 $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 kt(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 S,readFileSync as P,renameSync as de,unlinkSync as x,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 $}from"node:path";function y(t){let e=be()==="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=e?r.win32:r.unix,o=t.toLowerCase();if(i[o]&&Nt(i[o]))return i[o];if(e&&o==="netstat"){let u=$(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,p=`${U().replaceAll("\\","/")}/greedysearch-chrome-profile`,X=`${p}/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(", ")}
309
+ `),process.exit(1)}import{spawn as Ye,execFileSync as St,execSync as ut}from"node:child_process";import{existsSync as T,readFileSync as P,renameSync as ze,unlinkSync as x,writeFileSync as S}from"node:fs";import lt from"node:http";import{platform as at,tmpdir as de}from"node:os";import{join as it}from"node:path";import{basename as be}from"node:path";function Nt(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=be(e||"").toLowerCase();if(r==="node"||r==="node.exe")return e;return"node"}import{existsSync as Xt}from"node:fs";import{platform as he}from"node:os";import{join as $}from"node:path";function y(t){let e=he()==="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=e?r.win32:r.unix,o=t.toLowerCase();if(i[o]&&Xt(i[o]))return i[o];if(e&&o==="netstat"){let u=$(n,"Sysnative","netstat.exe");if(Xt(u))return u}return t}import{existsSync as U,mkdirSync as ye,readFileSync as Qt,writeFileSync as we}from"node:fs";import{homedir as me}from"node:os";import{join as jt}from"node:path";import{tmpdir as K}from"node:os";var h=9222,p=`${K().replaceAll("\\","/")}/greedysearch-chrome-profile`,X=`${p}/DevToolsActivePort`,ve=`${K().replaceAll("\\","/")}/cdp-pages.json`,J=`${K().replaceAll("\\","/")}/greedysearch-chrome-mode`,_n=`${K().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,I=jt(me(),".dm"),v=jt(I,"greedyconfig"),F=["perplexity","google","chatgpt"],E="gemini";function pe(){try{if(U(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
310
  [greedysearch] Available engines: ${Object.keys(L).join(", ")}
311
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(", ")}
312
+ `)}}}catch{}return F}function xe(){try{if(!U(I))ye(I,{recursive:!0});if(!U(v))we(v,JSON.stringify({engines:F,synthesizer:E},null,2)+`
313
+ `,"utf8")}catch{}}xe();var qt=["gemini","chatgpt"];function $e(){try{if(U(v)){let t=Qt(v,"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 ${v}
314
+ [greedysearch] Available synthesizers: ${qt.join(", ")}
315
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=p;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}
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"},An=pe();var Tn=$e(),Mn=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=p;import{existsSync as Cn,mkdirSync as Je,readFileSync as Zt,renameSync as ke,unlinkSync as We,writeFileSync as Ht}from"node:fs";import Ne from"node:http";import{platform as Vt}from"node:os";import{dirname as Xe}from"node:path";var Ot=[9222,9223],qe=/^(0|false|no|off)$/i;function Qe(t){return[...new Set(t.filter(Boolean))]}function Bt(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 _t(t=process.env){return![t.GREEDY_SEARCH_REUSE_EXISTING_BROWSER,t.DM_CUA_REUSE_EXISTING_BROWSER].some((e)=>e!==void 0&&qe.test(String(e)))}function tt(t){let e=Number.parseInt(String(t??""),10);return Number.isInteger(e)&&e>0&&e<65536?e:null}function je(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 Be(t){if(!t)return[];return String(t).split(/[,\s]+/).map(tt).filter(Boolean)}function Ze({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 Zt("/proc/version","utf8")}catch{return""}})();return/microsoft|wsl/i.test(r)}function He({env:t=process.env,platformName:e=Vt(),procVersionText:n=null,resolvConfText:r=null}={}){let i=["localhost","127.0.0.1"];if(Ze({env:t,platformName:e,procVersionText:n})){let u=(r??(()=>{try{return Zt("/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 Ve({env:t=process.env,hosts:e=He({env:t}),autoPorts:n=Ot,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=je(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=Be(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(_t(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 Oe(t,{timeoutMs:e=700}={}){if(t.wsUrl)return Bt(t.wsUrl,t.source);let n=t.host||"localhost",r=t.port;if(!r)return null;let i=await new Promise((o)=>{let u=Ne.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=Bt(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 _e(t={}){for(let e of Ve(t)){let n=await Oe(e,t);if(n)return n}return null}function Ae(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:p,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,p,h))Y({browserPid:e,debugPort:h,tempDir:p,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 Se=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),Pt=Ye().replaceAll("\\","/"),_=`${Pt}/greedysearch-chrome.pid`,A=`${Pt}/greedysearch-chrome-last-activity`,Pe=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,Re=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 Rt(){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(!S(J))return!0;return P(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&&S(_))t=Number.parseInt(P(_,"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{x(_)}catch{}try{x(A)}catch{}try{x(J)}catch{}return!1}let e=await Fe(1500);try{x(_)}catch{}try{x(A)}catch{}try{x(J)}catch{}if(e)process.stderr.write(`[greedysearch] Killed Chrome on port ${h}.
321
- `);return e}var St=Gt;async function tn(){let e=Rt()?Pe:Re;if(e<=0)return!1;if(!S(A))return Le(),!1;try{let n=Number.parseInt(P(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=P(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{x(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",(R)=>m+=R),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{x(X)}catch{}de(e,X)}}catch{}finally{if(i)try{x(t)}catch{}}}async function Lt(){let t=S(_)||!!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=Rt(),l=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!l&&!a)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
324
- `),await St(),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 St(),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(Se,"..","..","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],env:{...process.env,CDP_PROFILE_DIR:p,GREEDY_SEARCH_PROFILE_DIR:p}}).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 Te(t,e){Je(Xe(t),{recursive:!0});let n=`${t}.tmp-${process.pid}`;Ht(n,Ae(e),"utf8");try{We(t)}catch{}ke(n,t)}async function At({activePortFile:t,modeFile:e,env:n=process.env,excludePorts:r=[],autoPorts:i=Ot}={}){if(!_t(n))return null;let o=await _e({env:n,excludePorts:r,autoPorts:i});if(!o)return null;if(Te(t,o),e)Ht(e,"existing","utf8");return o}import{execFileSync as Tt,execSync as et}from"node:child_process";import{existsSync as C,mkdirSync as Me,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`,Ue=15000,Y=`${V}/greedysearch-chrome.pid`,z=`${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 Ke(t){if(!H(t))return null;try{if(nt()==="win32")return Tt(y("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${t}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return Tt(y("ps"),["-p",String(t),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Ce(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 Mt(t,e,n=h){return Ce(Ke(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 Ut(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(C(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=C(Y)?Number.parseInt(q(Y,"utf8").trim(),10)||void 0:void 0,e=C(z)?q(z,"utf8").trim()==="visible"?"visible":"headless":"headless",n=C(Z)?Number.parseInt(q(Z,"utf8").trim(),10)||0:0;return{browserPid:t,debugPort:h,tempDir:p,clientPids:t?[t]:[],sessionMode:e,lastActivity:n,launchedAt:0}}catch{return null}}function d(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(Y,String(t.browserPid),"utf8")}catch{}try{N(z,t.sessionMode,"utf8")}catch{}try{N(Z,String(t.lastActivity),"utf8")}catch{}}function Kt(){try{W(D)}catch{}try{W(Y)}catch{}try{W(z)}catch{}try{W(Z)}catch{}}function Yt(t){if(!t)return t;let e={...t,clientPids:[...new Set([...t.clientPids,process.pid].filter((n)=>H(n)||n===process.pid))]};return d(e),e}function rt(t){let e=Date.now();try{if(t)d({...t,lastActivity:e});else N(Z,String(e),"utf8")}catch{}}var In=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var Ct=!1;function zt(){if(Ct)return;Ct=!0;let t=O();if(!t)return;if(t.browserPid){if(!H(t.browserPid)){Ut(t.browserPid),Kt();return}if(!Mt(t.browserPid,t.tempDir,t.debugPort))Kt();else d({...t,clientPids:t.clientPids.filter((i)=>H(i))})}let e=De();if(e&&e!==t.browserPid)if(Mt(e,p,h))d({browserPid:e,debugPort:h,tempDir:p,clientPids:[e],sessionMode:t.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else Ut(e)}function dt(){Me(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>Ue){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 Se=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1");function Pe(t=Se){let e=[it(t,"launch.mjs"),it(t,"..","bin","launch.mjs"),it(t,"..","..","bin","launch.mjs")];for(let n of e)if(T(n))return n;return e[e.length-1]}var Rt=de().replaceAll("\\","/"),_=`${Rt}/greedysearch-chrome.pid`,A=`${Rt}/greedysearch-chrome-last-activity`,Re=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,Ge=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;function Le(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 Gt(){try{let t=ft(),e=t?Fe(t):null,n=Le(e);if(n!==null){try{S(J,n?"headless":"visible","utf8")}catch{}return n}}catch{}try{if(!T(J))return!0;return P(J,"utf8").trim()==="headless"}catch{return!0}}function Ie(){try{S(A,String(Date.now()),"utf8")}catch{}try{let t=O();if(t)rt(t)}catch{}}function Fe(t){try{if(at()==="win32")return St(y("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${t}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return St(y("ps"),["-p",String(t),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function ft(){try{if(at()==="win32"){let e=ut(`${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=ut(`${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 Ee(t=1500){try{let n=await new Promise((i,o)=>{let u=lt.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(!ft())return!0;await new Promise((r)=>setTimeout(r,150))}return tn()}function tn(){try{let t=ft();if(!t&&T(_))t=Number.parseInt(P(_,"utf8").trim(),10)||null;if(!t)return!1;if(at()==="win32")ut(`${y("taskkill")} /F /PID ${t}`,{stdio:"ignore"});else process.kill(t,"SIGKILL");return!0}catch{return!1}}async function Lt(){if(!await Q(500)){try{x(_)}catch{}try{x(A)}catch{}try{x(J)}catch{}return!1}let e=await Ee(1500);try{x(_)}catch{}try{x(A)}catch{}try{x(J)}catch{}if(e)process.stderr.write(`[greedysearch] Killed Chrome on port ${h}.
321
+ `);return e}var Pt=Lt;async function en(){let e=Gt()?Re:Ge;if(e<=0)return!1;if(!T(A))return Ie(),!1;try{let n=Number.parseInt(P(A,"utf8").trim(),10);if(!n)return!1;if((Date.now()-n)/60000>=e)return Lt()}catch{}return!1}function Q(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=`${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()});S(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=P(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{x(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=lt.get(`http://localhost:${h}/json/version`,(s)=>{let m="";s.on("data",(R)=>m+=R),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){S(e,`localhost:${h}
322
+ ${l}`,"utf8");try{x(X)}catch{}ze(e,X)}}catch{}finally{if(i)try{x(t)}catch{}}}async function It(){let t=T(_)||!!O(),e=await At({activePortFile:X,modeFile:J,excludePorts:t?[h]:[]});if(e){process.stderr.write(`[greedysearch] Reusing existing browser CDP endpoint ${e.httpUrl} (${e.source}).
323
+ `);return}zt();let n=await en(),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=Gt(),l=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!l&&!a)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
324
+ `),await Pt(),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 Pt(),await new Promise((f)=>setTimeout(f,1000)),i=!0}if(i?!1:await Q()){await ot();try{let a=O();if(a)rt(a),Yt(a)}catch{}return}let u=dt();if(!u.acquired){if(await new Promise((l)=>setTimeout(l,3000)),await Q(5000)){await ot();return}}try{if(await Q(1000)){await ot();return}process.stderr.write(`GreedySearch Chrome not running on port ${h} — auto-launching...
326
+ `);let l=[Pe()];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")l.push("--headless");await new Promise((f,c)=>{Ye(Nt(),l,{stdio:["ignore",process.stderr,process.stderr],env:{...process.env,CDP_PROFILE_DIR:p,GREEDY_SEARCH_PROFILE_DIR:p}}).on("close",(s)=>s===0?f():c(Error("launch.mjs failed")))})}finally{u.release()}}import{randomInt as nn}from"node:crypto";import{existsSync as rn,readFileSync as on}from"node:fs";import un from"node:http";var ln=`
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{x(X)}catch{}de(e,X)}}catch{}finally{if(i)try{x(t)}catch{}}}asy
340
340
 
341
341
  return null;
342
342
  })()
343
- `,ln=`
343
+ `,an=`
344
344
  (function() {
345
345
  var url = document.location.href;
346
346
 
@@ -410,7 +410,7 @@ ${l}`,"utf8");try{x(X)}catch{}de(e,X)}}catch{}finally{if(i)try{x(t)}catch{}}}asy
410
410
 
411
411
  return null;
412
412
  })()
413
- `,an=`
413
+ `,fn=`
414
414
  (function() {
415
415
  var url = document.location.href;
416
416
  var isVerifyPage = url.includes('/sorry/') ||
@@ -444,26 +444,26 @@ ${l}`,"utf8");try{x(X)}catch{}de(e,X)}}catch{}finally{if(i)try{x(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((R)=>{let ct=++a,gt=(ne)=>{if(JSON.parse(ne.data).id===ct)u.removeEventListener("message",gt),R()};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 Et(t,e){let n=await e(["eval",t,ln]).catch(()=>null);if(n&&n!=="null")await new Promise((r)=>setTimeout(r,1500))}function w(t,e){return nn(t*1000,e*1000)/1000}async function cn(t,e){if(!globalThis.WebSocket)return;let n=process.env.CDP_PROFILE_DIR;if(!n)return;let r=`${n.replaceAll("\\","/")}/DevToolsActivePort`;if(!rn(r))return;let i=on(r,"utf8").trim().split(`
448
+ `)[0],o=await new Promise((l,f)=>{let c=un.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((R)=>{let gt=++a,st=(re)=>{if(JSON.parse(re.data).id===gt)u.removeEventListener("message",st),R()};u.addEventListener("message",st),u.send(JSON.stringify({id:gt,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 te(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 cn(i,o).catch(()=>{}),await new Promise((m)=>setTimeout(m,w(100,300))),`human-clicked at (${i.toFixed(0)}, ${o.toFixed(0)})`}async function gn(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() {
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 te(t,e,o,u)}async function Ft(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 gn(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 te(t,e,r.x,r.y),!0}}catch{}return!1}async function sn(t,e){let n=await e(["eval",t,an]).catch(()=>null);return n&&n!=="null"?n:null}async function ee(t,e,n=30000){let r=await sn(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 Ft(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,fn]).catch(()=>null);if(o==="cleared"||!o||o==="null")return process.stderr.write(`[greedysearch] Verification cleared.
457
+ `),"clicked";if(o!=="still-verifying")await Ft(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 ne={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=ne.gemini,ct="__geminiClipboard";async function bn(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
459
  var el = document.querySelector('${j.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 hn(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 yn(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{x(X)}catch{}de(e,X)}}catch{}finally{if(i)try{x(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 wn(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();
@@ -506,12 +506,12 @@ ${l}`,"utf8");try{x(X)}catch{}de(e,X)}}catch{}finally{if(i)try{x(t)}catch{}}}asy
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 o=await g(["eval",t,`window.${ct} || ''`]);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,`(() => {
510
510
  const resp = document.querySelector('model-response');
511
511
  if (!resp) return 'no-model-response';
512
512
  const btn = resp.querySelector('${j.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)),o=await g(["eval",t,`window.${ct} || ''`]);let u=null;if(!o||n&&(o.toLowerCase().trim()===n||o.trim().length<n.length)){if(u=await yn(t),u.answer)o=u.answer}if(!o)throw Error("Gemini returned no answer — model-response never rendered content");let a=wt(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 mn=`Usage: node extractors/gemini.mjs "<query>" [--tab <prefix>]
517
+ `;async function vn(){let t=await pt(process.argv.slice(2));$t(t,mn);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 It();try{await g(["list"]);let i=await bt(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 Et(i,g),await ee(i,g,1e4),await vt(i,j.input,8000,M.inputPoll),await new Promise((s)=>setTimeout(s,B(M.postClick))),await ht(i,ct),await bn(i,e),await new Promise((s)=>setTimeout(s,B(M.postType))),await g(["eval",i,`document.querySelector('${j.sendButton}')?.click()`]);let a=0,l=setInterval(()=>{if(++a%10===0)hn(i).catch(()=>null)},6000);try{await mt(i,{timeout:45000,minLength:50})}finally{clearInterval(l)}let{answer:f,sources:c}=await wn(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");kt({query:e,url:b,answer:Jt(f,r),sources:c})}catch(i){Wt(i)}}vn();
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import{randomInt as Fn}from"node:crypto";import{spawn as En}from"node:child_process";import{dirname as dn,join as nr}from"node:path";import{fileURLToPath as rr}from"node:url";import{basename as ur}from"node:path";function fr(n=process.env,r=process.execPath){let u=n.GREEDY_SEARCH_NODE||n.NODE_BINARY||n.NODE;if(u?.trim())return u.trim();let f=ur(r||"").toLowerCase();if(f==="node"||f==="node.exe")return r;return"node"}var tr=dn(rr(import.meta.url)),ir=nr(tr,"..","bin","cdp.mjs");function b(n,r=30000){return S(n,null,r)}function S(n,r=null,u=30000){return new Promise((f,t)=>{let i=En(fr(),[ir,...n],{stdio:[r==null?"ignore":"pipe","pipe","pipe"]});if(r!=null)i.stdin.write(r),i.stdin.end();let g="",o="";i.stdout.on("data",(e)=>g+=e),i.stderr.on("data",(e)=>o+=e);let l=setTimeout(()=>{i.kill(),t(Error(`cdp timeout: ${n[0]}`))},u);i.on("close",(e)=>{if(clearTimeout(l),e===0)f(g.trim());else t(Error(o.trim()||`cdp exit ${e}`))})})}async function $n(n){if(n)return n;let r=(await b(["list"])).split(`
3
- `)[0]?.slice(0,8);if(!r)throw Error("No Chrome tabs found. Is Chrome running with --remote-debugging-port=9222?");let u=await b(["evalraw",r,"Target.createTarget",'{"url":"about:blank"}']),{targetId:f}=JSON.parse(u);await b(["list"]);let t=f.slice(0,8);try{await cn(t)}catch(i){process.stderr.write(`[getOrOpenTab] stealth injection failed: ${i.message}
4
- `)}return t}async function cn(n){await b(["evalraw",n,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
2
+ import{randomInt as En}from"node:crypto";import{spawn as dn}from"node:child_process";import{dirname as nr,join as rr}from"node:path";import{fileURLToPath as fr}from"node:url";import{basename as ur}from"node:path";function gr(n=process.env,r=process.execPath){let f=n.GREEDY_SEARCH_NODE||n.NODE_BINARY||n.NODE;if(f?.trim())return f.trim();let u=ur(r||"").toLowerCase();if(u==="node"||u==="node.exe")return r;return"node"}var tr=nr(fr(import.meta.url)),ir=rr(tr,"..","bin","cdp.mjs");function b(n,r=30000){return S(n,null,r)}function S(n,r=null,f=30000){return new Promise((u,g)=>{let t=dn(gr(),[ir,...n],{stdio:[r==null?"ignore":"pipe","pipe","pipe"]});if(r!=null)t.stdin.write(r),t.stdin.end();let i="",o="";t.stdout.on("data",(e)=>i+=e),t.stderr.on("data",(e)=>o+=e);let l=setTimeout(()=>{t.kill(),g(Error(`cdp timeout: ${n[0]}`))},f);t.on("close",(e)=>{if(clearTimeout(l),e===0)u(i.trim());else g(Error(o.trim()||`cdp exit ${e}`))})})}async function cn(n){if(n)return n;let r=(await b(["list"])).split(`
3
+ `)[0]?.slice(0,8);if(!r)throw Error("No Chrome tabs found. Is Chrome running with --remote-debugging-port=9222?");let f=await b(["evalraw",r,"Target.createTarget",'{"url":"about:blank"}']),{targetId:u}=JSON.parse(f);await b(["list"]);let g=u.slice(0,8);try{await Wn(g)}catch(t){process.stderr.write(`[getOrOpenTab] stealth injection failed: ${t.message}
4
+ `)}return g}async function Wn(n){await b(["evalraw",n,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
5
5
  (function() {
6
6
  // ── Runtime.enable / CDP detection masking ──────────────
7
7
  try { delete window.__REBROWSER_RUNTIME_ENABLE; } catch(_) {}
@@ -209,10 +209,10 @@ import{randomInt as Fn}from"node:crypto";import{spawn as En}from"node:child_proc
209
209
  };
210
210
  } catch(_) {}
211
211
  })();
212
- `})])}var F={postNav:800,postNavSlow:1200,postClick:300,postType:300,inputPoll:400,copyPoll:600,afterVerify:1500};function D(n){let r=n*0.4,u=Fn(-Math.floor(r),Math.floor(r)+1);return Math.max(50,Math.round(n+u))}async function Wn(n,r,u=15000,f=500){let t=String.raw`
212
+ `})])}var F={postNav:800,postNavSlow:1200,postClick:300,postType:300,inputPoll:400,copyPoll:600,afterVerify:1500};function z(n){let r=n*0.4,f=En(-Math.floor(r),Math.floor(r)+1);return Math.max(50,Math.round(n+f))}async function jn(n,r,f=15000,u=500){let g=String.raw`
213
213
  new Promise((resolve) => {
214
- const _deadline = Date.now() + ${u};
215
- const _baseInterval = ${f};
214
+ const _deadline = Date.now() + ${f};
215
+ const _baseInterval = ${u};
216
216
 
217
217
  function _jitter(ms) {
218
218
  return Math.max(50, ms + (Math.random() * ms * 0.4 - ms * 0.2));
@@ -228,33 +228,33 @@ import{randomInt as Fn}from"node:crypto";import{spawn as En}from"node:child_proc
228
228
 
229
229
  _poll();
230
230
  })
231
- `;return await b(["eval",n,t],u+5000)==="true"}async function jn(n){let r=n.indexOf("--stdin");if(r===-1)return n;let u=await new Promise((t)=>{let i="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(g)=>i+=g),process.stdin.on("end",()=>t(i.trim()))}),f=[...n];return f[r]=u,f}function Qn(n){let r=n.includes("--short"),u=n.filter((o)=>o!=="--short"),f=u.indexOf("--tab"),t=f===-1?null:u[f+1];if(f!==-1)u=u.filter((o,l)=>l!==f&&l!==f+1);let i=u.indexOf("--locale"),g=i===-1?null:u[i+1];if(i!==-1)u=u.filter((o,l)=>l!==i&&l!==i+1);return{query:u.join(" "),tabPrefix:t,short:r,locale:g}}function Xn(n,r){if(!n.length||n[0]==="--help")process.stderr.write(r),process.exit(1)}function Jn(n,r,u=300){if(!r||n.length<=u)return n;let f=n.slice(0,u),t=f.lastIndexOf(" ");return t>0?`${f.slice(0,t)}…`:`${f}…`}function Zn(n){process.stdout.write(`${JSON.stringify(n,null,2)}
232
- `)}function c(n,r,u=null){if(!n||typeof n!=="object")return;let f=u?` (+${Date.now()-u}ms)`:"";if(n.lastStage=r,!Array.isArray(n.stages))n.stages=[];n.stages.push({stage:r,at:Date.now()});let t=n.engine||"extractor";console.error(`[${t}] stage: ${r}${f}`)}function E({engine:n,mode:r="headless",clipboardEmpty:u=null,fallbackUsed:f=null,blockedBy:t=null,verificationResult:i=null,inputReady:g=null,durationMs:o=null,lastStage:l=null,stages:e=null}={}){return{engine:n,mode:r,clipboardEmpty:u,fallbackUsed:f,blockedBy:t,verificationResult:i,inputReady:g,durationMs:o,lastStage:l,stages:e}}function xn(n,r=null){if(r){let u=JSON.stringify({_envelope:r,error:n.message});process.stdout.write(`${u}
231
+ `;return await b(["eval",n,g],f+5000)==="true"}async function Qn(n){let r=n.indexOf("--stdin");if(r===-1)return n;let f=await new Promise((g)=>{let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(i)=>t+=i),process.stdin.on("end",()=>g(t.trim()))}),u=[...n];return u[r]=f,u}function Xn(n){let r=n.includes("--short"),f=n.filter((o)=>o!=="--short"),u=f.indexOf("--tab"),g=u===-1?null:f[u+1];if(u!==-1)f=f.filter((o,l)=>l!==u&&l!==u+1);let t=f.indexOf("--locale"),i=t===-1?null:f[t+1];if(t!==-1)f=f.filter((o,l)=>l!==t&&l!==t+1);return{query:f.join(" "),tabPrefix:g,short:r,locale:i}}function Jn(n,r){if(!n.length||n[0]==="--help")process.stderr.write(r),process.exit(1)}function Zn(n,r,f=300){if(!r||n.length<=f)return n;let u=n.slice(0,f),g=u.lastIndexOf(" ");return g>0?`${u.slice(0,g)}…`:`${u}…`}function xn(n){process.stdout.write(`${JSON.stringify(n,null,2)}
232
+ `)}function c(n,r,f=null){if(!n||typeof n!=="object")return;let u=f?` (+${Date.now()-f}ms)`:"";if(n.lastStage=r,!Array.isArray(n.stages))n.stages=[];n.stages.push({stage:r,at:Date.now()});let g=n.engine||"extractor";console.error(`[${g}] stage: ${r}${u}`)}function E({engine:n,mode:r="headless",clipboardEmpty:f=null,fallbackUsed:u=null,blockedBy:g=null,verificationResult:t=null,inputReady:i=null,durationMs:o=null,lastStage:l=null,stages:e=null}={}){return{engine:n,mode:r,clipboardEmpty:f,fallbackUsed:u,blockedBy:g,verificationResult:t,inputReady:i,durationMs:o,lastStage:l,stages:e}}function qn(n,r=null){if(r){let f=JSON.stringify({_envelope:r,error:n.message});process.stdout.write(`${f}
233
233
  `)}process.stderr.write(`Error: ${n.message}
234
- `),process.exit(1)}import{readFileSync as Ir}from"node:fs";import{tmpdir as Sr}from"node:os";import{spawn as vr,execFileSync as Gn,execSync as en}from"node:child_process";import{existsSync as L,readFileSync as I,renameSync as Mr,unlinkSync as Q,writeFileSync as P}from"node:fs";import bn from"node:http";import{platform as wn,tmpdir as Or}from"node:os";import{join as Dr}from"node:path";import{basename as gr}from"node:path";function qn(n=process.env,r=process.execPath){let u=n.GREEDY_SEARCH_NODE||n.NODE_BINARY||n.NODE;if(u?.trim())return u.trim();let f=gr(r||"").toLowerCase();if(f==="node"||f==="node.exe")return r;return"node"}import{existsSync as Bn}from"node:fs";import{platform as or}from"node:os";import{join as q}from"node:path";function h(n){let r=or()==="win32",u=process.env.SystemRoot||"C:\\Windows",f={win32:{powershell:q(u,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:q(u,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:q(u,"System32","netstat.exe"),taskkill:q(u,"System32","taskkill.exe"),tasklist:q(u,"System32","tasklist.exe"),cmd:q(u,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},t=r?f.win32:f.unix,i=n.toLowerCase();if(t[i]&&Bn(t[i]))return t[i];if(r&&i==="netstat"){let g=q(u,"Sysnative","netstat.exe");if(Bn(g))return g}return n}import{existsSync as z,mkdirSync as lr,readFileSync as Vn,writeFileSync as er}from"node:fs";import{homedir as br}from"node:os";import{join as _n}from"node:path";import{tmpdir as Y}from"node:os";var w=9222,j=`${Y().replaceAll("\\","/")}/greedysearch-chrome-profile`,N=`${j}/DevToolsActivePort`,wr=`${Y().replaceAll("\\","/")}/cdp-pages.json`,B=`${Y().replaceAll("\\","/")}/greedysearch-chrome-mode`,au=`${Y().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,nn=_n(br(),".dm"),W=_n(nn,"greedyconfig"),rn=["perplexity","google","chatgpt"],un="gemini";function hr(){try{if(z(W)){let n=Vn(W,"utf8"),r=JSON.parse(n);if(Array.isArray(r.engines)&&r.engines.length>0&&r.engines.every((u)=>typeof u==="string")){let u=r.engines.filter((t)=>d[t]),f=r.engines.filter((t)=>!d[t]);if(f.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${W}: ${f.join(", ")}
234
+ `),process.exit(1)}import{readFileSync as Sr}from"node:fs";import{tmpdir as Fr}from"node:os";import{spawn as Mr,execFileSync as Rn,execSync as bn}from"node:child_process";import{existsSync as s,readFileSync as I,renameSync as Or,unlinkSync as Q,writeFileSync as L}from"node:fs";import wn from"node:http";import{platform as hn,tmpdir as Dr}from"node:os";import{join as ln}from"node:path";import{basename as or}from"node:path";function Bn(n=process.env,r=process.execPath){let f=n.GREEDY_SEARCH_NODE||n.NODE_BINARY||n.NODE;if(f?.trim())return f.trim();let u=or(r||"").toLowerCase();if(u==="node"||u==="node.exe")return r;return"node"}import{existsSync as Vn}from"node:fs";import{platform as lr}from"node:os";import{join as q}from"node:path";function h(n){let r=lr()==="win32",f=process.env.SystemRoot||"C:\\Windows",u={win32:{powershell:q(f,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:q(f,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:q(f,"System32","netstat.exe"),taskkill:q(f,"System32","taskkill.exe"),tasklist:q(f,"System32","tasklist.exe"),cmd:q(f,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},g=r?u.win32:u.unix,t=n.toLowerCase();if(g[t]&&Vn(g[t]))return g[t];if(r&&t==="netstat"){let i=q(f,"Sysnative","netstat.exe");if(Vn(i))return i}return n}import{existsSync as Y,mkdirSync as er,readFileSync as Nn,writeFileSync as br}from"node:fs";import{homedir as wr}from"node:os";import{join as an}from"node:path";import{tmpdir as G}from"node:os";var w=9222,j=`${G().replaceAll("\\","/")}/greedysearch-chrome-profile`,a=`${j}/DevToolsActivePort`,hr=`${G().replaceAll("\\","/")}/cdp-pages.json`,B=`${G().replaceAll("\\","/")}/greedysearch-chrome-mode`,Nf=`${G().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,nn=an(wr(),".dm"),W=an(nn,"greedyconfig"),rn=["perplexity","google","chatgpt"],fn="gemini";function $r(){try{if(Y(W)){let n=Nn(W,"utf8"),r=JSON.parse(n);if(Array.isArray(r.engines)&&r.engines.length>0&&r.engines.every((f)=>typeof f==="string")){let f=r.engines.filter((g)=>d[g]),u=r.engines.filter((g)=>!d[g]);if(u.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${W}: ${u.join(", ")}
235
235
  [greedysearch] Available engines: ${Object.keys(d).join(", ")}
236
- `);if(u.length>0)return u;process.stderr.write(`[greedysearch] Warning: no valid engines in ${W}, falling back to defaults: ${rn.join(", ")}
237
- `)}}}catch{}return rn}function $r(){try{if(!z(nn))lr(nn,{recursive:!0});if(!z(W))er(W,JSON.stringify({engines:rn,synthesizer:un},null,2)+`
238
- `,"utf8")}catch{}}$r();var an=["gemini","chatgpt"];function cr(){try{if(z(W)){let n=Vn(W,"utf8"),r=JSON.parse(n);if(typeof r.synthesizer==="string"){let u=r.synthesizer.toLowerCase();if(an.includes(u))return u;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${r.synthesizer}" in ${W}
239
- [greedysearch] Available synthesizers: ${an.join(", ")}
240
- [greedysearch] Falling back to default: ${un}
241
- `)}}}catch{}return un}var d={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"},Vu=hr();var _u=cr(),Nu=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=j;import{existsSync as yu,mkdirSync as Wr,readFileSync as kn,renameSync as jr,unlinkSync as Qr,writeFileSync as Hn}from"node:fs";import Xr from"node:http";import{platform as yn}from"node:os";import{dirname as Jr}from"node:path";var Kn=[9222,9223],Zr=/^(0|false|no|off)$/i;function xr(n){return[...new Set(n.filter(Boolean))]}function Nn(n,r="explicit"){let u=new URL(n),f=u.protocol==="wss:"?"wss:":"ws:",t=u.port?Number.parseInt(u.port,10):f==="wss:"?443:80;return{source:r,wsUrl:`${f}//${u.host}${u.pathname}${u.search}`,host:u.hostname,port:t,path:`${u.pathname}${u.search}`,httpUrl:`http://${u.hostname}:${t}`}}function Un(n=process.env){return![n.GREEDY_SEARCH_REUSE_EXISTING_BROWSER,n.DM_CUA_REUSE_EXISTING_BROWSER].some((r)=>r!==void 0&&Zr.test(String(r)))}function fn(n){let r=Number.parseInt(String(n??""),10);return Number.isInteger(r)&&r>0&&r<65536?r:null}function qr(n){if(!n)return null;let r=String(n).trim();if(!r)return null;let u=new URL(r.includes("://")?r:`http://${r}`),f=fn(u.port)||(u.protocol==="https:"?443:80);return{host:u.hostname,port:f,source:`env:${r}`}}function Br(n){if(!n)return[];return String(n).split(/[,\s]+/).map(fn).filter(Boolean)}function ar({env:n=process.env,platformName:r=yn(),procVersionText:u=null}={}){if(r!=="linux")return!1;if(n.WSL_DISTRO_NAME||n.WSL_INTEROP)return!0;let f=u??(()=>{try{return kn("/proc/version","utf8")}catch{return""}})();return/microsoft|wsl/i.test(f)}function Vr({env:n=process.env,platformName:r=yn(),procVersionText:u=null,resolvConfText:f=null}={}){let t=["localhost","127.0.0.1"];if(ar({env:n,platformName:r,procVersionText:u})){let g=(f??(()=>{try{return kn("/etc/resolv.conf","utf8")}catch{return""}})()).match(/^\s*nameserver\s+([^\s#]+)/m);if(g)t.push(g[1]);t.push("host.docker.internal")}return xr(t)}function _r({env:n=process.env,hosts:r=Vr({env:n}),autoPorts:u=Kn,excludePorts:f=[]}={}){let t=[];for(let l of["GREEDY_SEARCH_CDP_WS_URL","DM_CUA_CDP_WS_URL","CDP_WS_URL"])if(n[l])t.push({wsUrl:n[l],source:`env:${l}`});for(let l of["GREEDY_SEARCH_CDP_URL","DM_CUA_CDP_URL","CDP_URL"])try{let e=qr(n[l]);if(e)t.push(e)}catch{}for(let l of["GREEDY_SEARCH_EXISTING_CDP_PORT","DM_CUA_EXISTING_CDP_PORT","GREEDY_SEARCH_CDP_PORT","DM_CUA_CDP_PORT"]){let e=fn(n[l]);if(!e)continue;for(let $ of r)t.push({host:$,port:e,source:`env:${l}`})}let i=Br(n.GREEDY_SEARCH_EXISTING_CDP_PORTS);for(let l of i)for(let e of r)t.push({host:e,port:l,source:"env:GREEDY_SEARCH_EXISTING_CDP_PORTS"});let g=new Set(f.filter(Boolean));if(Un(n))for(let l of u){if(g.has(l))continue;for(let e of r)t.push({host:e,port:l,source:"auto"})}let o=new Set;return t.filter((l)=>{let e=l.wsUrl||`${l.host}:${l.port}`;if(o.has(e))return!1;return o.add(e),!0})}async function Nr(n,{timeoutMs:r=700}={}){if(n.wsUrl)return Nn(n.wsUrl,n.source);let u=n.host||"localhost",f=n.port;if(!f)return null;let t=await new Promise((i)=>{let g=Xr.get({host:u,port:f,path:"/json/version",timeout:r},(o)=>{let l="";o.setEncoding("utf8"),o.on("data",(e)=>l+=e),o.on("end",()=>i(o.statusCode===200?l:null))});g.on("error",()=>i(null)),g.setTimeout(r,()=>{g.destroy(),i(null)})});if(!t)return null;try{let i=JSON.parse(t);if(!i.webSocketDebuggerUrl)return null;let g=Nn(i.webSocketDebuggerUrl,n.source),o=g.path||new URL(i.webSocketDebuggerUrl).pathname;return{...g,host:u,port:f,httpUrl:`http://${u}:${f}`,wsUrl:`ws://${u}:${f}${o}`,path:o}}catch{return null}}async function kr(n={}){for(let r of _r(n)){let u=await Nr(r,n);if(u)return u}return null}function Hr(n){if(!n)throw Error("missing CDP endpoint");let r=new URL(n.wsUrl);return`${r.host}
236
+ `);if(f.length>0)return f;process.stderr.write(`[greedysearch] Warning: no valid engines in ${W}, falling back to defaults: ${rn.join(", ")}
237
+ `)}}}catch{}return rn}function cr(){try{if(!Y(nn))er(nn,{recursive:!0});if(!Y(W))br(W,JSON.stringify({engines:rn,synthesizer:fn},null,2)+`
238
+ `,"utf8")}catch{}}cr();var _n=["gemini","chatgpt"];function Wr(){try{if(Y(W)){let n=Nn(W,"utf8"),r=JSON.parse(n);if(typeof r.synthesizer==="string"){let f=r.synthesizer.toLowerCase();if(_n.includes(f))return f;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${r.synthesizer}" in ${W}
239
+ [greedysearch] Available synthesizers: ${_n.join(", ")}
240
+ [greedysearch] Falling back to default: ${fn}
241
+ `)}}}catch{}return fn}var d={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"},af=$r();var kf=Wr(),Hf=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=j;import{existsSync as Uf,mkdirSync as jr,readFileSync as Hn,renameSync as Qr,unlinkSync as Xr,writeFileSync as yn}from"node:fs";import Jr from"node:http";import{platform as Kn}from"node:os";import{dirname as Zr}from"node:path";var Un=[9222,9223],xr=/^(0|false|no|off)$/i;function qr(n){return[...new Set(n.filter(Boolean))]}function kn(n,r="explicit"){let f=new URL(n),u=f.protocol==="wss:"?"wss:":"ws:",g=f.port?Number.parseInt(f.port,10):u==="wss:"?443:80;return{source:r,wsUrl:`${u}//${f.host}${f.pathname}${f.search}`,host:f.hostname,port:g,path:`${f.pathname}${f.search}`,httpUrl:`http://${f.hostname}:${g}`}}function pn(n=process.env){return![n.GREEDY_SEARCH_REUSE_EXISTING_BROWSER,n.DM_CUA_REUSE_EXISTING_BROWSER].some((r)=>r!==void 0&&xr.test(String(r)))}function un(n){let r=Number.parseInt(String(n??""),10);return Number.isInteger(r)&&r>0&&r<65536?r:null}function Br(n){if(!n)return null;let r=String(n).trim();if(!r)return null;let f=new URL(r.includes("://")?r:`http://${r}`),u=un(f.port)||(f.protocol==="https:"?443:80);return{host:f.hostname,port:u,source:`env:${r}`}}function Vr(n){if(!n)return[];return String(n).split(/[,\s]+/).map(un).filter(Boolean)}function _r({env:n=process.env,platformName:r=Kn(),procVersionText:f=null}={}){if(r!=="linux")return!1;if(n.WSL_DISTRO_NAME||n.WSL_INTEROP)return!0;let u=f??(()=>{try{return Hn("/proc/version","utf8")}catch{return""}})();return/microsoft|wsl/i.test(u)}function Nr({env:n=process.env,platformName:r=Kn(),procVersionText:f=null,resolvConfText:u=null}={}){let g=["localhost","127.0.0.1"];if(_r({env:n,platformName:r,procVersionText:f})){let i=(u??(()=>{try{return Hn("/etc/resolv.conf","utf8")}catch{return""}})()).match(/^\s*nameserver\s+([^\s#]+)/m);if(i)g.push(i[1]);g.push("host.docker.internal")}return qr(g)}function ar({env:n=process.env,hosts:r=Nr({env:n}),autoPorts:f=Un,excludePorts:u=[]}={}){let g=[];for(let l of["GREEDY_SEARCH_CDP_WS_URL","DM_CUA_CDP_WS_URL","CDP_WS_URL"])if(n[l])g.push({wsUrl:n[l],source:`env:${l}`});for(let l of["GREEDY_SEARCH_CDP_URL","DM_CUA_CDP_URL","CDP_URL"])try{let e=Br(n[l]);if(e)g.push(e)}catch{}for(let l of["GREEDY_SEARCH_EXISTING_CDP_PORT","DM_CUA_EXISTING_CDP_PORT","GREEDY_SEARCH_CDP_PORT","DM_CUA_CDP_PORT"]){let e=un(n[l]);if(!e)continue;for(let $ of r)g.push({host:$,port:e,source:`env:${l}`})}let t=Vr(n.GREEDY_SEARCH_EXISTING_CDP_PORTS);for(let l of t)for(let e of r)g.push({host:e,port:l,source:"env:GREEDY_SEARCH_EXISTING_CDP_PORTS"});let i=new Set(u.filter(Boolean));if(pn(n))for(let l of f){if(i.has(l))continue;for(let e of r)g.push({host:e,port:l,source:"auto"})}let o=new Set;return g.filter((l)=>{let e=l.wsUrl||`${l.host}:${l.port}`;if(o.has(e))return!1;return o.add(e),!0})}async function kr(n,{timeoutMs:r=700}={}){if(n.wsUrl)return kn(n.wsUrl,n.source);let f=n.host||"localhost",u=n.port;if(!u)return null;let g=await new Promise((t)=>{let i=Jr.get({host:f,port:u,path:"/json/version",timeout:r},(o)=>{let l="";o.setEncoding("utf8"),o.on("data",(e)=>l+=e),o.on("end",()=>t(o.statusCode===200?l:null))});i.on("error",()=>t(null)),i.setTimeout(r,()=>{i.destroy(),t(null)})});if(!g)return null;try{let t=JSON.parse(g);if(!t.webSocketDebuggerUrl)return null;let i=kn(t.webSocketDebuggerUrl,n.source),o=i.path||new URL(t.webSocketDebuggerUrl).pathname;return{...i,host:f,port:u,httpUrl:`http://${f}:${u}`,wsUrl:`ws://${f}:${u}${o}`,path:o}}catch{return null}}async function Hr(n={}){for(let r of ar(n)){let f=await kr(r,n);if(f)return f}return null}function yr(n){if(!n)throw Error("missing CDP endpoint");let r=new URL(n.wsUrl);return`${r.host}
242
242
  ${r.pathname}${r.search}
243
- `}function yr(n,r){Wr(Jr(n),{recursive:!0});let u=`${n}.tmp-${process.pid}`;Hn(u,Hr(r),"utf8");try{Qr(n)}catch{}jr(u,n)}async function sn({activePortFile:n,modeFile:r,env:u=process.env,excludePorts:f=[],autoPorts:t=Kn}={}){if(!Un(u))return null;let i=await kr({env:u,excludePorts:f,autoPorts:t});if(!i)return null;if(yr(n,i),r)Hn(r,"existing","utf8");return i}import{execFileSync as pn,execSync as tn}from"node:child_process";import{existsSync as m,mkdirSync as Kr,readFileSync as k,unlinkSync as V,writeFileSync as _}from"node:fs";import{platform as gn,tmpdir as Dn}from"node:os";var U=Dn().replaceAll("\\","/"),G=`${U}/greedysearch-chrome-metadata.json`,a=`${U}/greedysearch-chrome-launch.lock`,Ur=15000,R=`${U}/greedysearch-chrome.pid`,T=`${U}/greedysearch-chrome-mode`,y=`${U}/greedysearch-chrome-last-activity`;function K(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch{return!1}}function sr(n){if(!K(n))return null;try{if(gn()==="win32")return pn(h("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${n}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return pn(h("ps"),["-p",String(n),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function pr(n,r,u=w){if(!n)return!1;let f=(g)=>String(g||"").replaceAll("\\","/").toLowerCase(),t=f(n),i=f(r);return t.includes(i)&&t.includes(`--remote-debugging-port=${u}`)&&!t.includes("--type=")}function An(n,r,u=w){return pr(sr(n),r,u)}function Ar(n=w){try{if(gn()==="win32"){let u=tn(`${h("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),f=new RegExp(String.raw`TCP\s+\S+:${n}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),t=u.match(f);return t?Number.parseInt(t[1],10):null}let r=tn(`${h("lsof")} -i :${n} -t 2>/dev/null || ${h("ss")} -tlnp 2>/dev/null | ${h("grep")} :${n} | ${h("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return r?Number.parseInt(r.split(`
244
- `)[0],10):null}catch{return null}}function vn(n){try{if(gn()==="win32")tn(`${h("taskkill")} /F /T /PID ${n}`,{stdio:"ignore"});else{try{process.kill(-n,"SIGKILL")}catch{}try{process.kill(n,"SIGKILL")}catch{}}return!0}catch{return!1}}function s(){try{if(m(G)){let n=k(G,"utf8"),r=JSON.parse(n);if(r&&typeof r.tempDir==="string"&&typeof r.debugPort==="number")return{browserPid:Number.isInteger(r.browserPid)?r.browserPid:void 0,debugPort:r.debugPort,tempDir:r.tempDir,clientPids:Array.isArray(r.clientPids)?r.clientPids.filter((u)=>Number.isInteger(u)&&u>0):[],sessionMode:r.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(r.lastActivity)?r.lastActivity:0,launchedAt:Number.isFinite(r.launchedAt)?r.launchedAt:0}}}catch{}try{let n=m(R)?Number.parseInt(k(R,"utf8").trim(),10)||void 0:void 0,r=m(T)?k(T,"utf8").trim()==="visible"?"visible":"headless":"headless",u=m(y)?Number.parseInt(k(y,"utf8").trim(),10)||0:0;return{browserPid:n,debugPort:w,tempDir:j,clientPids:n?[n]:[],sessionMode:r,lastActivity:u,launchedAt:0}}catch{return null}}function C(n){try{_(G,JSON.stringify({browserPid:n.browserPid,debugPort:n.debugPort,tempDir:n.tempDir,clientPids:[...new Set(n.clientPids.filter((r)=>r>0))],sessionMode:n.sessionMode,lastActivity:n.lastActivity,launchedAt:n.launchedAt},null,2),"utf8")}catch{}try{if(n.browserPid)_(R,String(n.browserPid),"utf8")}catch{}try{_(T,n.sessionMode,"utf8")}catch{}try{_(y,String(n.lastActivity),"utf8")}catch{}}function Mn(){try{V(G)}catch{}try{V(R)}catch{}try{V(T)}catch{}try{V(y)}catch{}}function zn(n){if(!n)return n;let r={...n,clientPids:[...new Set([...n.clientPids,process.pid].filter((u)=>K(u)||u===process.pid))]};return C(r),r}function on(n){let r=Date.now();try{if(n)C({...n,lastActivity:r});else _(y,String(r),"utf8")}catch{}}var zu=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var On=!1;function Yn(){if(On)return;On=!0;let n=s();if(!n)return;if(n.browserPid){if(!K(n.browserPid)){vn(n.browserPid),Mn();return}if(!An(n.browserPid,n.tempDir,n.debugPort))Mn();else C({...n,clientPids:n.clientPids.filter((t)=>K(t))})}let r=Ar();if(r&&r!==n.browserPid)if(An(r,j,w))C({browserPid:r,debugPort:w,tempDir:j,clientPids:[r],sessionMode:n.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else vn(r)}function mn(){Kr(Dn(),{recursive:!0});try{let n=JSON.stringify({pid:process.pid,ts:Date.now()});return _(a,n,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let r=k(a,"utf8");if(JSON.parse(r).pid===process.pid)V(a)}catch{}}}}catch(n){if(n?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let n=k(a,"utf8"),r=JSON.parse(n),u=Date.now()-(r.ts||0);if(!K(r.pid)||u>Ur){try{V(a)}catch{}try{let t=JSON.stringify({pid:process.pid,ts:Date.now()});return _(a,t,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{V(a)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var zr=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),Tn=Or().replaceAll("\\","/"),p=`${Tn}/greedysearch-chrome.pid`,A=`${Tn}/greedysearch-chrome-last-activity`,Yr=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,mr=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;function Gr(n,r=w){let u=String(n||"").toLowerCase();if(!u.includes(`--remote-debugging-port=${r}`)||u.includes("--type="))return null;return u.includes("--headless")}function Cn(){try{let n=hn(),r=n?Tr(n):null,u=Gr(r);if(u!==null){try{P(B,u?"headless":"visible","utf8")}catch{}return u}}catch{}try{if(!L(B))return!0;return I(B,"utf8").trim()==="headless"}catch{return!0}}function Rr(){try{P(A,String(Date.now()),"utf8")}catch{}try{let n=s();if(n)on(n)}catch{}}function Tr(n){try{if(wn()==="win32")return Gn(h("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${n}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return Gn(h("ps"),["-p",String(n),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function hn(){try{if(wn()==="win32"){let r=en(`${h("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),u=new RegExp(String.raw`TCP\s+\S+:${w}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),f=r.match(u);return f?Number.parseInt(f[1],10):null}let n=en(`${h("lsof")} -i :${w} -t 2>/dev/null || ${h("ss")} -tlnp 2>/dev/null | ${h("grep")} :${w} | ${h("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return n?Number.parseInt(n.split(`
245
- `)[0],10):null}catch{return null}}async function Cr(n=1500){try{let u=await new Promise((t,i)=>{let g=bn.get(`http://localhost:${w}/json/version`,(o)=>{let l="";o.on("data",(e)=>l+=e),o.on("end",()=>{try{t(JSON.parse(l))}catch{i(Error("bad JSON"))}})});g.on("error",i),g.setTimeout(1000,()=>{g.destroy(),i(Error("timeout"))})}),f=new globalThis.WebSocket(u.webSocketDebuggerUrl);await new Promise((t)=>{f.onopen=()=>{f.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{f.close(),t()},200)},f.onerror=()=>t(),setTimeout(t,1000)})}catch{}let r=Date.now()+n;while(Date.now()<r){if(!hn())return!0;await new Promise((f)=>setTimeout(f,150))}return Pr()}function Pr(){try{let n=hn();if(!n&&L(p))n=Number.parseInt(I(p,"utf8").trim(),10)||null;if(!n)return!1;if(wn()==="win32")en(`${h("taskkill")} /F /PID ${n}`,{stdio:"ignore"});else process.kill(n,"SIGKILL");return!0}catch{return!1}}async function Pn(){if(!await H(500)){try{Q(p)}catch{}try{Q(A)}catch{}try{Q(B)}catch{}return!1}let r=await Cr(1500);try{Q(p)}catch{}try{Q(A)}catch{}try{Q(B)}catch{}if(r)process.stderr.write(`[greedysearch] Killed Chrome on port ${w}.
246
- `);return r}var Rn=Pn;async function Lr(){let r=Cn()?Yr:mr;if(r<=0)return!1;if(!L(A))return Rr(),!1;try{let u=Number.parseInt(I(A,"utf8").trim(),10);if(!u)return!1;if((Date.now()-u)/60000>=r)return Pn()}catch{}return!1}function H(n=3000){return new Promise((r)=>{let u=bn.get(`http://localhost:${w}/json/version`,(f)=>{f.resume(),r(f.statusCode===200)});u.on("error",()=>r(!1)),u.setTimeout(n,()=>{u.destroy(),r(!1)})})}async function ln(){let n=`${N}.lock`,r=`${N}.tmp`,u=5000,f=1000,t=await new Promise((i)=>{let g=Date.now(),o=()=>{try{let l=JSON.stringify({pid:process.pid,ts:Date.now()});P(n,l,{encoding:"utf8",flag:"wx"}),i(!0)}catch(l){if(l?.code!=="EEXIST"){if(Date.now()-g<1000)setTimeout(o,50);else i(!1);return}try{let e=I(n,"utf8").trim(),$=e.startsWith("{")?JSON.parse(e):{ts:Number(e)},X=Number($?.ts)||0;if(X>0&&Date.now()-X>5000)try{Q(n)}catch{}if(Date.now()-g<1000)setTimeout(o,50);else i(!1)}catch{if(Date.now()-g<1000)setTimeout(o,50);else i(!1)}}};o()});try{let i=await new Promise((e,$)=>{let X=bn.get(`http://localhost:${w}/json/version`,(x)=>{let v="";x.on("data",(M)=>v+=M),x.on("end",()=>e(v))});X.on("error",$),X.setTimeout(3000,()=>{X.destroy(),$(Error("timeout"))})}),{webSocketDebuggerUrl:g}=JSON.parse(i),o=new URL(g),l=`${o.pathname}${o.search}`;if(t){P(r,`localhost:${w}
247
- ${l}`,"utf8");try{Q(N)}catch{}Mr(r,N)}}catch{}finally{if(t)try{Q(n)}catch{}}}async function Ln(){let n=L(p)||!!s(),r=await sn({activePortFile:N,modeFile:B,excludePorts:n?[w]:[]});if(r){process.stderr.write(`[greedysearch] Reusing existing browser CDP endpoint ${r.httpUrl} (${r.source}).
248
- `);return}Yn();let u=await Lr(),f=u?!1:await H();if(!f&&!u)await new Promise((o)=>setTimeout(o,500)),f=await H();let t=!1;if(f){let o=Cn(),l=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!l&&!o)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
249
- `),await Rn(),await new Promise((e)=>setTimeout(e,1000)),t=!0;else if(l&&o)process.stderr.write(`[greedysearch] Headless Chrome detected — switching to visible mode...
250
- `),await Rn(),await new Promise((e)=>setTimeout(e,1000)),t=!0}if(t?!1:await H()){await ln();try{let o=s();if(o)on(o),zn(o)}catch{}return}let g=mn();if(!g.acquired){if(await new Promise((l)=>setTimeout(l,3000)),await H(5000)){await ln();return}}try{if(await H(1000)){await ln();return}process.stderr.write(`GreedySearch Chrome not running on port ${w} — auto-launching...
251
- `);let l=[Dr(zr,"..","..","bin","launch.mjs")];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")l.push("--headless");await new Promise((e,$)=>{vr(qn(),l,{stdio:["ignore",process.stderr,process.stderr],env:{...process.env,CDP_PROFILE_DIR:j,GREEDY_SEARCH_PROFILE_DIR:j}}).on("close",(x)=>x===0?e():$(Error("launch.mjs failed")))})}finally{g.release()}}var Fr="https://logically.app/research-assistant/",Z={input:'.chat-control div.ProseMirror[contenteditable="true"][role="textbox"]',submitButton:'.chat-control button[class*="MuiButton-black"]',answerContainer:"#last-message .chat-content",citationSpan:"#last-message .chat-content span[title]"};async function Er(n){return b(["eval",n,`(() => {
243
+ `}function Kr(n,r){jr(Zr(n),{recursive:!0});let f=`${n}.tmp-${process.pid}`;yn(f,yr(r),"utf8");try{Xr(n)}catch{}Qr(f,n)}async function An({activePortFile:n,modeFile:r,env:f=process.env,excludePorts:u=[],autoPorts:g=Un}={}){if(!pn(f))return null;let t=await Hr({env:f,excludePorts:u,autoPorts:g});if(!t)return null;if(Kr(n,t),r)yn(r,"existing","utf8");return t}import{execFileSync as vn,execSync as gn}from"node:child_process";import{existsSync as m,mkdirSync as Ur,readFileSync as k,unlinkSync as _,writeFileSync as N}from"node:fs";import{platform as tn,tmpdir as zn}from"node:os";var U=zn().replaceAll("\\","/"),R=`${U}/greedysearch-chrome-metadata.json`,V=`${U}/greedysearch-chrome-launch.lock`,pr=15000,T=`${U}/greedysearch-chrome.pid`,C=`${U}/greedysearch-chrome-mode`,y=`${U}/greedysearch-chrome-last-activity`;function K(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch{return!1}}function Ar(n){if(!K(n))return null;try{if(tn()==="win32")return vn(h("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${n}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return vn(h("ps"),["-p",String(n),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function vr(n,r,f=w){if(!n)return!1;let u=(i)=>String(i||"").replaceAll("\\","/").toLowerCase(),g=u(n),t=u(r);return g.includes(t)&&g.includes(`--remote-debugging-port=${f}`)&&!g.includes("--type=")}function sn(n,r,f=w){return vr(Ar(n),r,f)}function sr(n=w){try{if(tn()==="win32"){let f=gn(`${h("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),u=new RegExp(String.raw`TCP\s+\S+:${n}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),g=f.match(u);return g?Number.parseInt(g[1],10):null}let r=gn(`${h("lsof")} -i :${n} -t 2>/dev/null || ${h("ss")} -tlnp 2>/dev/null | ${h("grep")} :${n} | ${h("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return r?Number.parseInt(r.split(`
244
+ `)[0],10):null}catch{return null}}function Mn(n){try{if(tn()==="win32")gn(`${h("taskkill")} /F /T /PID ${n}`,{stdio:"ignore"});else{try{process.kill(-n,"SIGKILL")}catch{}try{process.kill(n,"SIGKILL")}catch{}}return!0}catch{return!1}}function p(){try{if(m(R)){let n=k(R,"utf8"),r=JSON.parse(n);if(r&&typeof r.tempDir==="string"&&typeof r.debugPort==="number")return{browserPid:Number.isInteger(r.browserPid)?r.browserPid:void 0,debugPort:r.debugPort,tempDir:r.tempDir,clientPids:Array.isArray(r.clientPids)?r.clientPids.filter((f)=>Number.isInteger(f)&&f>0):[],sessionMode:r.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(r.lastActivity)?r.lastActivity:0,launchedAt:Number.isFinite(r.launchedAt)?r.launchedAt:0}}}catch{}try{let n=m(T)?Number.parseInt(k(T,"utf8").trim(),10)||void 0:void 0,r=m(C)?k(C,"utf8").trim()==="visible"?"visible":"headless":"headless",f=m(y)?Number.parseInt(k(y,"utf8").trim(),10)||0:0;return{browserPid:n,debugPort:w,tempDir:j,clientPids:n?[n]:[],sessionMode:r,lastActivity:f,launchedAt:0}}catch{return null}}function P(n){try{N(R,JSON.stringify({browserPid:n.browserPid,debugPort:n.debugPort,tempDir:n.tempDir,clientPids:[...new Set(n.clientPids.filter((r)=>r>0))],sessionMode:n.sessionMode,lastActivity:n.lastActivity,launchedAt:n.launchedAt},null,2),"utf8")}catch{}try{if(n.browserPid)N(T,String(n.browserPid),"utf8")}catch{}try{N(C,n.sessionMode,"utf8")}catch{}try{N(y,String(n.lastActivity),"utf8")}catch{}}function On(){try{_(R)}catch{}try{_(T)}catch{}try{_(C)}catch{}try{_(y)}catch{}}function Yn(n){if(!n)return n;let r={...n,clientPids:[...new Set([...n.clientPids,process.pid].filter((f)=>K(f)||f===process.pid))]};return P(r),r}function on(n){let r=Date.now();try{if(n)P({...n,lastActivity:r});else N(y,String(r),"utf8")}catch{}}var Gf=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var Dn=!1;function Gn(){if(Dn)return;Dn=!0;let n=p();if(!n)return;if(n.browserPid){if(!K(n.browserPid)){Mn(n.browserPid),On();return}if(!sn(n.browserPid,n.tempDir,n.debugPort))On();else P({...n,clientPids:n.clientPids.filter((g)=>K(g))})}let r=sr();if(r&&r!==n.browserPid)if(sn(r,j,w))P({browserPid:r,debugPort:w,tempDir:j,clientPids:[r],sessionMode:n.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else Mn(r)}function mn(){Ur(zn(),{recursive:!0});try{let n=JSON.stringify({pid:process.pid,ts:Date.now()});return N(V,n,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let r=k(V,"utf8");if(JSON.parse(r).pid===process.pid)_(V)}catch{}}}}catch(n){if(n?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let n=k(V,"utf8"),r=JSON.parse(n),f=Date.now()-(r.ts||0);if(!K(r.pid)||f>pr){try{_(V)}catch{}try{let g=JSON.stringify({pid:process.pid,ts:Date.now()});return N(V,g,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{_(V)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var zr=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1");function Yr(n=zr){let r=[ln(n,"launch.mjs"),ln(n,"..","bin","launch.mjs"),ln(n,"..","..","bin","launch.mjs")];for(let f of r)if(s(f))return f;return r[r.length-1]}var Cn=Dr().replaceAll("\\","/"),A=`${Cn}/greedysearch-chrome.pid`,v=`${Cn}/greedysearch-chrome-last-activity`,Gr=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,mr=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;function Rr(n,r=w){let f=String(n||"").toLowerCase();if(!f.includes(`--remote-debugging-port=${r}`)||f.includes("--type="))return null;return f.includes("--headless")}function Pn(){try{let n=$n(),r=n?Cr(n):null,f=Rr(r);if(f!==null){try{L(B,f?"headless":"visible","utf8")}catch{}return f}}catch{}try{if(!s(B))return!0;return I(B,"utf8").trim()==="headless"}catch{return!0}}function Tr(){try{L(v,String(Date.now()),"utf8")}catch{}try{let n=p();if(n)on(n)}catch{}}function Cr(n){try{if(hn()==="win32")return Rn(h("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${n}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return Rn(h("ps"),["-p",String(n),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function $n(){try{if(hn()==="win32"){let r=bn(`${h("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),f=new RegExp(String.raw`TCP\s+\S+:${w}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),u=r.match(f);return u?Number.parseInt(u[1],10):null}let n=bn(`${h("lsof")} -i :${w} -t 2>/dev/null || ${h("ss")} -tlnp 2>/dev/null | ${h("grep")} :${w} | ${h("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return n?Number.parseInt(n.split(`
245
+ `)[0],10):null}catch{return null}}async function Pr(n=1500){try{let f=await new Promise((g,t)=>{let i=wn.get(`http://localhost:${w}/json/version`,(o)=>{let l="";o.on("data",(e)=>l+=e),o.on("end",()=>{try{g(JSON.parse(l))}catch{t(Error("bad JSON"))}})});i.on("error",t),i.setTimeout(1000,()=>{i.destroy(),t(Error("timeout"))})}),u=new globalThis.WebSocket(f.webSocketDebuggerUrl);await new Promise((g)=>{u.onopen=()=>{u.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{u.close(),g()},200)},u.onerror=()=>g(),setTimeout(g,1000)})}catch{}let r=Date.now()+n;while(Date.now()<r){if(!$n())return!0;await new Promise((u)=>setTimeout(u,150))}return Lr()}function Lr(){try{let n=$n();if(!n&&s(A))n=Number.parseInt(I(A,"utf8").trim(),10)||null;if(!n)return!1;if(hn()==="win32")bn(`${h("taskkill")} /F /PID ${n}`,{stdio:"ignore"});else process.kill(n,"SIGKILL");return!0}catch{return!1}}async function Ln(){if(!await H(500)){try{Q(A)}catch{}try{Q(v)}catch{}try{Q(B)}catch{}return!1}let r=await Pr(1500);try{Q(A)}catch{}try{Q(v)}catch{}try{Q(B)}catch{}if(r)process.stderr.write(`[greedysearch] Killed Chrome on port ${w}.
246
+ `);return r}var Tn=Ln;async function Ir(){let r=Pn()?Gr:mr;if(r<=0)return!1;if(!s(v))return Tr(),!1;try{let f=Number.parseInt(I(v,"utf8").trim(),10);if(!f)return!1;if((Date.now()-f)/60000>=r)return Ln()}catch{}return!1}function H(n=3000){return new Promise((r)=>{let f=wn.get(`http://localhost:${w}/json/version`,(u)=>{u.resume(),r(u.statusCode===200)});f.on("error",()=>r(!1)),f.setTimeout(n,()=>{f.destroy(),r(!1)})})}async function en(){let n=`${a}.lock`,r=`${a}.tmp`,f=5000,u=1000,g=await new Promise((t)=>{let i=Date.now(),o=()=>{try{let l=JSON.stringify({pid:process.pid,ts:Date.now()});L(n,l,{encoding:"utf8",flag:"wx"}),t(!0)}catch(l){if(l?.code!=="EEXIST"){if(Date.now()-i<1000)setTimeout(o,50);else t(!1);return}try{let e=I(n,"utf8").trim(),$=e.startsWith("{")?JSON.parse(e):{ts:Number(e)},X=Number($?.ts)||0;if(X>0&&Date.now()-X>5000)try{Q(n)}catch{}if(Date.now()-i<1000)setTimeout(o,50);else t(!1)}catch{if(Date.now()-i<1000)setTimeout(o,50);else t(!1)}}};o()});try{let t=await new Promise((e,$)=>{let X=wn.get(`http://localhost:${w}/json/version`,(x)=>{let M="";x.on("data",(O)=>M+=O),x.on("end",()=>e(M))});X.on("error",$),X.setTimeout(3000,()=>{X.destroy(),$(Error("timeout"))})}),{webSocketDebuggerUrl:i}=JSON.parse(t),o=new URL(i),l=`${o.pathname}${o.search}`;if(g){L(r,`localhost:${w}
247
+ ${l}`,"utf8");try{Q(a)}catch{}Or(r,a)}}catch{}finally{if(g)try{Q(n)}catch{}}}async function In(){let n=s(A)||!!p(),r=await An({activePortFile:a,modeFile:B,excludePorts:n?[w]:[]});if(r){process.stderr.write(`[greedysearch] Reusing existing browser CDP endpoint ${r.httpUrl} (${r.source}).
248
+ `);return}Gn();let f=await Ir(),u=f?!1:await H();if(!u&&!f)await new Promise((o)=>setTimeout(o,500)),u=await H();let g=!1;if(u){let o=Pn(),l=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!l&&!o)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
249
+ `),await Tn(),await new Promise((e)=>setTimeout(e,1000)),g=!0;else if(l&&o)process.stderr.write(`[greedysearch] Headless Chrome detected — switching to visible mode...
250
+ `),await Tn(),await new Promise((e)=>setTimeout(e,1000)),g=!0}if(g?!1:await H()){await en();try{let o=p();if(o)on(o),Yn(o)}catch{}return}let i=mn();if(!i.acquired){if(await new Promise((l)=>setTimeout(l,3000)),await H(5000)){await en();return}}try{if(await H(1000)){await en();return}process.stderr.write(`GreedySearch Chrome not running on port ${w} — auto-launching...
251
+ `);let l=[Yr()];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")l.push("--headless");await new Promise((e,$)=>{Mr(Bn(),l,{stdio:["ignore",process.stderr,process.stderr],env:{...process.env,CDP_PROFILE_DIR:j,GREEDY_SEARCH_PROFILE_DIR:j}}).on("close",(x)=>x===0?e():$(Error("launch.mjs failed")))})}finally{i.release()}}var Er="https://logically.app/research-assistant/",Z={input:'.chat-control div.ProseMirror[contenteditable="true"][role="textbox"]',submitButton:'.chat-control button[class*="MuiButton-black"]',answerContainer:"#last-message .chat-content",citationSpan:"#last-message .chat-content span[title]"};async function dr(n){return b(["eval",n,`(() => {
252
252
  const buttons = Array.from(document.querySelectorAll('button'));
253
253
  const create = buttons.find((b) => (b.innerText || '').trim() === 'Create');
254
254
  if (!create) return 'missing';
255
255
  create.click();
256
256
  return 'clicked';
257
- })()`],5000).catch(()=>"error")}async function dr(n){return await b(["eval",n,`(() => {
257
+ })()`],5000).catch(()=>"error")}async function nf(n){return await b(["eval",n,`(() => {
258
258
  const url = document.location.href || '';
259
259
  if (url.includes('/login') || url.includes('/signup') || url.includes('/sign-up')) return true;
260
260
  const modalText = Array.from(document.querySelectorAll('[role="dialog"], .MuiModal-root'))
@@ -262,7 +262,7 @@ ${l}`,"utf8");try{Q(N)}catch{}Mr(r,N)}}catch{}finally{if(t)try{Q(n)}catch{}}}asy
262
262
  .join('
263
263
  ');
264
264
  return /create a free account|continue with google|have an account[?] log in|log in|sign up/i.test(modalText);
265
- })()`],5000).catch(()=>"false")==="true"}async function nu(n){try{await b(["list"]);let r=`${Sr().replaceAll("\\\\","/")}/cdp-pages.json`,f=JSON.parse(Ir(r,"utf8")).find((t)=>t.targetId?.startsWith(n))?.targetId;if(f)await b(["browse",n,"Target.activateTarget",JSON.stringify({targetId:f})]).catch(()=>null),await new Promise((t)=>setTimeout(t,250))}catch{}}async function ru(n,r){await nu(n);let u=await b(["eval",n,`(() => {
265
+ })()`],5000).catch(()=>"false")==="true"}async function rf(n){try{await b(["list"]);let r=`${Fr().replaceAll("\\\\","/")}/cdp-pages.json`,u=JSON.parse(Sr(r,"utf8")).find((g)=>g.targetId?.startsWith(n))?.targetId;if(u)await b(["browse",n,"Target.activateTarget",JSON.stringify({targetId:u})]).catch(()=>null),await new Promise((g)=>setTimeout(g,250))}catch{}}async function ff(n,r){await rf(n);let f=await b(["eval",n,`(() => {
266
266
  const inputs = Array.from(document.querySelectorAll('${Z.input}'));
267
267
  const input = inputs.find((el) => {
268
268
  const r = el.getBoundingClientRect();
@@ -272,7 +272,7 @@ ${l}`,"utf8");try{Q(N)}catch{}Mr(r,N)}}catch{}finally{if(t)try{Q(n)}catch{}}}asy
272
272
  input.scrollIntoView({ block: 'center', inline: 'center' });
273
273
  const r = input.getBoundingClientRect();
274
274
  return JSON.stringify({ x: Math.round(r.left + Math.min(80, r.width / 2)), y: Math.round(r.top + r.height / 2) });
275
- })()`]);if(!u)throw Error("Logically visible input not found");let f=JSON.parse(u);if(await b(["click",n,Z.input]).catch(()=>null),await new Promise((i)=>setTimeout(i,D(120))),await b(["clickxy",n,String(f.x),String(f.y)]),await new Promise((i)=>setTimeout(i,D(F.postClick))),await S(["type",n,"--stdin"],r),await new Promise((i)=>setTimeout(i,D(F.postType))),await b(["eval",n,`Array.from(document.querySelectorAll('${Z.input}')).some((el) => (el.innerText || '').length >= ${Math.floor(r.length*0.8)})`])!=="true")throw Error("Logically input did not accept text — input verification failed")}async function uu(n,r=90000){let u=String.raw`
275
+ })()`]);if(!f)throw Error("Logically visible input not found");let u=JSON.parse(f);if(await b(["click",n,Z.input]).catch(()=>null),await new Promise((t)=>setTimeout(t,z(120))),await b(["clickxy",n,String(u.x),String(u.y)]),await new Promise((t)=>setTimeout(t,z(F.postClick))),await S(["type",n,"--stdin"],r),await new Promise((t)=>setTimeout(t,z(F.postType))),await b(["eval",n,`Array.from(document.querySelectorAll('${Z.input}')).some((el) => (el.innerText || '').length >= ${Math.floor(r.length*0.8)})`])!=="true")throw Error("Logically input did not accept text — input verification failed")}async function uf(n,r=90000){let f=String.raw`
276
276
  new Promise((resolve, reject) => {
277
277
  const deadline = Date.now() + ${r};
278
278
  let last = '';
@@ -293,7 +293,7 @@ ${l}`,"utf8");try{Q(N)}catch{}Mr(r,N)}}catch{}finally{if(t)try{Q(n)}catch{}}}asy
293
293
  } catch (e) { reject(e); }
294
294
  }
295
295
  poll();
296
- })`;return b(["eval",n,u],r+1e4)}async function fu(n){let r=`(() => {
296
+ })`;return b(["eval",n,f],r+1e4)}async function gf(n){let r=`(() => {
297
297
  const el = document.querySelector('${Z.answerContainer}');
298
298
  if (!el) return JSON.stringify({ answer: '', answerHtml: '' });
299
299
  const clone = el.cloneNode(true);
@@ -305,7 +305,7 @@ ${l}`,"utf8");try{Q(N)}catch{}Mr(r,N)}}catch{}finally{if(t)try{Q(n)}catch{}}}asy
305
305
  answer: (el.innerText || '').trim(),
306
306
  answerHtml: clone.innerHTML,
307
307
  });
308
- })()`;return JSON.parse(await b(["eval",n,r],1e4))}async function tu(n){let r=String.raw`
308
+ })()`;return JSON.parse(await b(["eval",n,r],1e4))}async function tf(n){let r=String.raw`
309
309
  (async () => {
310
310
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
311
311
 
@@ -445,7 +445,7 @@ ${l}`,"utf8");try{Q(N)}catch{}Mr(r,N)}}catch{}finally{if(t)try{Q(n)}catch{}}}asy
445
445
  webCaptured: webSources.length,
446
446
  },
447
447
  });
448
- })()`,u=await b(["eval",n,r],20000);return JSON.parse(u)}async function iu(n){let r=String.raw`
448
+ })()`,f=await b(["eval",n,r],20000);return JSON.parse(f)}async function of(n){let r=String.raw`
449
449
  (async () => {
450
450
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
451
451
  const answer = document.querySelector('${Z.answerContainer}');
@@ -549,5 +549,5 @@ ${l}`,"utf8");try{Q(N)}catch{}Mr(r,N)}}catch{}finally{if(t)try{Q(n)}catch{}}}asy
549
549
  }
550
550
  }
551
551
  return JSON.stringify(sources);
552
- })()`,u=await b(["eval",n,r],45000);return JSON.parse(u)}var gu=`Usage: node extractors/logically.mjs "<query>" [--tab <prefix>]
553
- `;async function ou(){let n=await jn(process.argv.slice(2));Xn(n,gu);let{query:r,tabPrefix:u,short:f}=Qn(n),t=Date.now(),g={engine:"logically",mode:process.env.GREEDY_SEARCH_VISIBLE==="1"?"visible":"headless",clipboardEmpty:null,fallbackUsed:null,blockedBy:null,verificationResult:null,inputReady:null};try{if(process.env.GREEDY_SEARCH_VISIBLE!=="1"&&process.env.GREEDY_SEARCH_ALWAYS_VISIBLE!=="1")process.env.GREEDY_SEARCH_HEADLESS="1";if(await Ln(),!u)await b(["list"]);let o=await $n(u),l=await b(["eval",o,"document.location.href"]).catch(()=>""),e=!1;try{let J=new URL(l).hostname.toLowerCase();e=J==="logically.app"||J.endsWith(".logically.app")}catch{}if(!e)c(g,"nav",t),await b(["nav",o,Fr],25000),await new Promise((J)=>setTimeout(J,900));c(g,"new-chat",t),await Er(o),await new Promise((J)=>setTimeout(J,700)),c(g,"input-wait",t);let $=await Wn(o,Z.input,20000,400);if(g.inputReady=$,!$)throw Error("Logically input not found — page may not have loaded or is in unexpected state");if(c(g,"type-and-submit",t),await ru(o,r),await b(["eval",o,`(() => { const btn = document.querySelector('${Z.submitButton}'); if (!btn) return 'missing'; btn.click(); return 'clicked'; })()`])!=="clicked")throw Error("Logically submit button not found");if(await new Promise((J)=>setTimeout(J,1500)),await dr(o))throw g.blockedBy="signin",g.verificationResult="needs-human",Error("Logically login required — please log in or create a free account in the visible browser window. Once signed in, cookies persist for future runs.");c(g,"answer-wait",t),await uu(o,90000),c(g,"extract-answer-html",t);let{answer:x,answerHtml:v}=await fu(o);if(!x)throw Error("No answer extracted — Logically may not have responded");c(g,"extract-inline-citations",t);let M=await iu(o);c(g,"extract-full-citations",t);let O=await tu(o),In=O.sources?.length?O.sources:M,Sn=await b(["eval",o,"document.location.href"]).catch(()=>"");g.durationMs=Date.now()-t,g.sourcePath=O.sources?.length?"citations-popover":"inline-citation-popovers",c(g,"done",t),Zn({query:r,url:Sn,answer:Jn(x,f),answerHtml:v,sources:In,inlineSources:M,citationSummary:O.summary,_envelope:E(g)})}catch(o){g.durationMs=Date.now()-t,xn(o,E(g))}}ou();
552
+ })()`,f=await b(["eval",n,r],45000);return JSON.parse(f)}var lf=`Usage: node extractors/logically.mjs "<query>" [--tab <prefix>]
553
+ `;async function ef(){let n=await Qn(process.argv.slice(2));Jn(n,lf);let{query:r,tabPrefix:f,short:u}=Xn(n),g=Date.now(),i={engine:"logically",mode:process.env.GREEDY_SEARCH_VISIBLE==="1"?"visible":"headless",clipboardEmpty:null,fallbackUsed:null,blockedBy:null,verificationResult:null,inputReady:null};try{if(process.env.GREEDY_SEARCH_VISIBLE!=="1"&&process.env.GREEDY_SEARCH_ALWAYS_VISIBLE!=="1")process.env.GREEDY_SEARCH_HEADLESS="1";if(await In(),!f)await b(["list"]);let o=await cn(f),l=await b(["eval",o,"document.location.href"]).catch(()=>""),e=!1;try{let J=new URL(l).hostname.toLowerCase();e=J==="logically.app"||J.endsWith(".logically.app")}catch{}if(!e)c(i,"nav",g),await b(["nav",o,Er],25000),await new Promise((J)=>setTimeout(J,900));c(i,"new-chat",g),await dr(o),await new Promise((J)=>setTimeout(J,700)),c(i,"input-wait",g);let $=await jn(o,Z.input,20000,400);if(i.inputReady=$,!$)throw Error("Logically input not found — page may not have loaded or is in unexpected state");if(c(i,"type-and-submit",g),await ff(o,r),await b(["eval",o,`(() => { const btn = document.querySelector('${Z.submitButton}'); if (!btn) return 'missing'; btn.click(); return 'clicked'; })()`])!=="clicked")throw Error("Logically submit button not found");if(await new Promise((J)=>setTimeout(J,1500)),await nf(o))throw i.blockedBy="signin",i.verificationResult="needs-human",Error("Logically login required — please log in or create a free account in the visible browser window. Once signed in, cookies persist for future runs.");c(i,"answer-wait",g),await uf(o,90000),c(i,"extract-answer-html",g);let{answer:x,answerHtml:M}=await gf(o);if(!x)throw Error("No answer extracted — Logically may not have responded");c(i,"extract-inline-citations",g);let O=await of(o);c(i,"extract-full-citations",g);let D=await tf(o),Sn=D.sources?.length?D.sources:O,Fn=await b(["eval",o,"document.location.href"]).catch(()=>"");i.durationMs=Date.now()-g,i.sourcePath=D.sources?.length?"citations-popover":"inline-citation-popovers",c(i,"done",g),xn({query:r,url:Fn,answer:Zn(x,u),answerHtml:M,sources:Sn,inlineSources:O,citationSummary:D.summary,_envelope:E(i)})}catch(o){i.durationMs=Date.now()-g,qn(o,E(i))}}ef();