@duckmind/dm-darwin-x64 0.43.8 → 0.49.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.
Files changed (62) hide show
  1. package/dm +0 -0
  2. package/extensions/.dm-extensions.json +147 -218
  3. package/extensions/dm-9router-ext/package.json +0 -6
  4. package/extensions/dm-9router-ext/src/index.js +1 -1
  5. package/extensions/dm-ask-user/package.json +0 -4
  6. package/extensions/dm-caveman/LICENSE +21 -0
  7. package/extensions/dm-caveman/extensions/caveman.js +29 -0
  8. package/extensions/dm-caveman/package.json +20 -0
  9. package/extensions/dm-cli-anything/index.js +5 -5
  10. package/extensions/dm-cli-anything/package.json +0 -7
  11. package/extensions/dm-cli-anything/skills/cli-anything/SKILL.md +1 -3
  12. package/extensions/dm-context/package.json +0 -1
  13. package/extensions/dm-cua/package.json +0 -7
  14. package/extensions/dm-fff/package.json +0 -6
  15. package/extensions/dm-goal/package.json +0 -8
  16. package/extensions/dm-grill-me/index.js +2 -2
  17. package/extensions/dm-grill-me/package.json +0 -7
  18. package/extensions/dm-image2/package.json +0 -8
  19. package/extensions/dm-subagents/package.json +0 -11
  20. package/extensions/dm-tasks/package.json +0 -7
  21. package/extensions/dm-usage/package.json +0 -7
  22. package/extensions/greedysearch-dm/bin/cdp-greedy.mjs +1 -8
  23. package/extensions/greedysearch-dm/bin/gschrome.mjs +3 -3
  24. package/extensions/greedysearch-dm/bin/launch-visible.mjs +3 -3
  25. package/extensions/greedysearch-dm/bin/launch.mjs +4 -4
  26. package/extensions/greedysearch-dm/bin/search.mjs +106 -106
  27. package/extensions/greedysearch-dm/extractors/consensus.mjs +35 -35
  28. package/extensions/greedysearch-dm/extractors/gemini.mjs +38 -38
  29. package/extensions/greedysearch-dm/extractors/logically.mjs +35 -35
  30. package/extensions/greedysearch-dm/package.json +0 -10
  31. package/extensions/greedysearch-dm/src/search/chrome.mjs +23 -23
  32. package/extensions/greedysearch-dm/src/search/fetch-source.mjs +35 -35
  33. package/extensions/greedysearch-dm/src/search/research.mjs +77 -77
  34. package/extensions/greedysearch-dm/src/search/synthesis-runner.mjs +10 -10
  35. package/package.json +1 -1
  36. package/extensions/dm-9router-ext/README.md +0 -142
  37. package/extensions/dm-9router-ext/tsconfig.json +0 -17
  38. package/extensions/dm-ask-user/README.md +0 -226
  39. package/extensions/dm-cli-anything/README.md +0 -33
  40. package/extensions/dm-cli-anything/vendor/UPSTREAM.md +0 -14
  41. package/extensions/dm-context/AGENTS.md +0 -41
  42. package/extensions/dm-context/README.md +0 -18
  43. package/extensions/dm-context/tsconfig.json +0 -16
  44. package/extensions/dm-cua/README.md +0 -24
  45. package/extensions/dm-fff/README.md +0 -36
  46. package/extensions/dm-fff/tsconfig.json +0 -13
  47. package/extensions/dm-goal/CHANGELOG.md +0 -12
  48. package/extensions/dm-goal/README.md +0 -29
  49. package/extensions/dm-goal/tsconfig.json +0 -15
  50. package/extensions/dm-grill-me/DESIGN.md +0 -301
  51. package/extensions/dm-grill-me/README.md +0 -82
  52. package/extensions/dm-grill-me/tsconfig.json +0 -17
  53. package/extensions/dm-image2/README.md +0 -33
  54. package/extensions/dm-subagents/CHANGELOG.md +0 -1211
  55. package/extensions/dm-subagents/README.md +0 -29
  56. package/extensions/dm-subagents/biome.json +0 -26
  57. package/extensions/dm-subagents/tsconfig.json +0 -18
  58. package/extensions/dm-tasks/README.md +0 -30
  59. package/extensions/dm-tasks/biome.json +0 -26
  60. package/extensions/dm-tasks/tsconfig.json +0 -14
  61. package/extensions/dm-usage/README.md +0 -29
  62. package/extensions/greedysearch-dm/README.md +0 -222
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
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:`
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:`
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 En}from"node:crypto";import{spawn as dn}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 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`
212
+ `})])}var F={postNav:800,postNavSlow:1200,postClick:300,postType:300,inputPoll:400,copyPoll:600,afterVerify:1500};function O(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`
213
213
  new Promise((resolve) => {
214
- const _deadline = Date.now() + ${f};
215
- const _baseInterval = ${u};
214
+ const _deadline = Date.now() + ${u};
215
+ const _baseInterval = ${f};
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 En}from"node:crypto";import{spawn as dn}from"node:child_proc
228
228
 
229
229
  _poll();
230
230
  })
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}
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}
233
233
  `)}process.stderr.write(`Error: ${n.message}
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(", ")}
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 Dr,unlinkSync as j,writeFileSync as P}from"node:fs";import bn from"node:http";import{platform as wn,tmpdir as Mr}from"node:os";import{join as Or}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 x}from"node:path";function h(n){let r=or()==="win32",u=process.env.SystemRoot||"C:\\Windows",f={win32:{powershell:x(u,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:x(u,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:x(u,"System32","netstat.exe"),taskkill:x(u,"System32","taskkill.exe"),tasklist:x(u,"System32","tasklist.exe"),cmd:x(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=x(u,"Sysnative","netstat.exe");if(Bn(g))return g}return n}import{existsSync as Y,mkdirSync as lr,readFileSync as an,writeFileSync as er}from"node:fs";import{homedir as br}from"node:os";import{join as Vn}from"node:path";import{tmpdir as z}from"node:os";var w=9222,q=`${z().replaceAll("\\","/")}/greedysearch-chrome-profile`,N=`${q}/DevToolsActivePort`,wr=`${z().replaceAll("\\","/")}/cdp-pages.json`,B=`${z().replaceAll("\\","/")}/greedysearch-chrome-mode`,_u=`${z().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,nn=Vn(br(),".dm"),W=Vn(nn,"greedyconfig"),rn=["perplexity","google","chatgpt"],un="gemini";function hr(){try{if(Y(W)){let n=an(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(", ")}
235
235
  [greedysearch] Available engines: ${Object.keys(d).join(", ")}
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}
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(!Y(nn))lr(nn,{recursive:!0});if(!Y(W))er(W,JSON.stringify({engines:rn,synthesizer:un},null,2)+`
238
+ `,"utf8")}catch{}}$r();var _n=["gemini","chatgpt"];function cr(){try{if(Y(W)){let n=an(W,"utf8"),r=JSON.parse(n);if(typeof r.synthesizer==="string"){let u=r.synthesizer.toLowerCase();if(_n.includes(u))return u;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${r.synthesizer}" in ${W}
239
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}
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"},au=hr();var Vu=cr(),Nu=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=q;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 _r({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 ar({env:n=process.env,platformName:r=yn(),procVersionText:u=null,resolvConfText:f=null}={}){let t=["localhost","127.0.0.1"];if(_r({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 Vr({env:n=process.env,hosts:r=ar({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 Vr(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}
242
242
  ${r.pathname}${r.search}
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,`(() => {
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 a,writeFileSync as V}from"node:fs";import{platform as gn,tmpdir as On}from"node:os";var U=On().replaceAll("\\","/"),G=`${U}/greedysearch-chrome-metadata.json`,_=`${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:q,clientPids:n?[n]:[],sessionMode:r,lastActivity:u,launchedAt:0}}catch{return null}}function C(n){try{V(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)V(R,String(n.browserPid),"utf8")}catch{}try{V(T,n.sessionMode,"utf8")}catch{}try{V(y,String(n.lastActivity),"utf8")}catch{}}function Dn(){try{a(G)}catch{}try{a(R)}catch{}try{a(T)}catch{}try{a(y)}catch{}}function Yn(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 V(y,String(r),"utf8")}catch{}}var Yu=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var Mn=!1;function zn(){if(Mn)return;Mn=!0;let n=s();if(!n)return;if(n.browserPid){if(!K(n.browserPid)){vn(n.browserPid),Dn();return}if(!An(n.browserPid,n.tempDir,n.debugPort))Dn();else C({...n,clientPids:n.clientPids.filter((t)=>K(t))})}let r=Ar();if(r&&r!==n.browserPid)if(An(r,q,w))C({browserPid:r,debugPort:w,tempDir:q,clientPids:[r],sessionMode:n.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else vn(r)}function mn(){Kr(On(),{recursive:!0});try{let n=JSON.stringify({pid:process.pid,ts:Date.now()});return V(_,n,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let r=k(_,"utf8");if(JSON.parse(r).pid===process.pid)a(_)}catch{}}}}catch(n){if(n?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let n=k(_,"utf8"),r=JSON.parse(n),u=Date.now()-(r.ts||0);if(!K(r.pid)||u>Ur){try{a(_)}catch{}try{let t=JSON.stringify({pid:process.pid,ts:Date.now()});return V(_,t,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{a(_)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var Yr=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),Tn=Mr().replaceAll("\\","/"),p=`${Tn}/greedysearch-chrome.pid`,A=`${Tn}/greedysearch-chrome-last-activity`,zr=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{j(p)}catch{}try{j(A)}catch{}try{j(B)}catch{}return!1}let r=await Cr(1500);try{j(p)}catch{}try{j(A)}catch{}try{j(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()?zr: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)},Q=Number($?.ts)||0;if(Q>0&&Date.now()-Q>5000)try{j(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 Q=bn.get(`http://localhost:${w}/json/version`,(Z)=>{let v="";Z.on("data",(D)=>v+=D),Z.on("end",()=>e(v))});Q.on("error",$),Q.setTimeout(3000,()=>{Q.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{j(N)}catch{}Dr(r,N)}}catch{}finally{if(t)try{j(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}zn();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),Yn(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=[Or(Yr,"..","..","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]}).on("close",(Z)=>Z===0?e():$(Error("launch.mjs failed")))})}finally{g.release()}}var Fr="https://logically.app/research-assistant/",J={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,`(() => {
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 nf(n){return await b(["eval",n,`(() => {
257
+ })()`],5000).catch(()=>"error")}async function dr(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,8 +262,8 @@ ${l}`,"utf8");try{Q(a)}catch{}Or(r,a)}}catch{}finally{if(g)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 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
- const inputs = Array.from(document.querySelectorAll('${Z.input}'));
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,`(() => {
266
+ const inputs = Array.from(document.querySelectorAll('${J.input}'));
267
267
  const input = inputs.find((el) => {
268
268
  const r = el.getBoundingClientRect();
269
269
  return r.width > 20 && r.height > 5;
@@ -272,14 +272,14 @@ ${l}`,"utf8");try{Q(a)}catch{}Or(r,a)}}catch{}finally{if(g)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(!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`
275
+ })()`]);if(!u)throw Error("Logically visible input not found");let f=JSON.parse(u);if(await b(["click",n,J.input]).catch(()=>null),await new Promise((i)=>setTimeout(i,O(120))),await b(["clickxy",n,String(f.x),String(f.y)]),await new Promise((i)=>setTimeout(i,O(F.postClick))),await S(["type",n,"--stdin"],r),await new Promise((i)=>setTimeout(i,O(F.postType))),await b(["eval",n,`Array.from(document.querySelectorAll('${J.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`
276
276
  new Promise((resolve, reject) => {
277
277
  const deadline = Date.now() + ${r};
278
278
  let last = '';
279
279
  let stable = 0;
280
280
  function poll() {
281
281
  try {
282
- const answer = document.querySelector('${Z.answerContainer}');
282
+ const answer = document.querySelector('${J.answerContainer}');
283
283
  const text = (answer?.innerText || '').trim();
284
284
  const body = document.body.innerText || '';
285
285
  const stillGenerating = /Generating answer|Thinking\.\.\.|Searching the internet|Discovered \d+/.test(body) && text.length < 200;
@@ -293,8 +293,8 @@ ${l}`,"utf8");try{Q(a)}catch{}Or(r,a)}}catch{}finally{if(g)try{Q(n)}catch{}}}asy
293
293
  } catch (e) { reject(e); }
294
294
  }
295
295
  poll();
296
- })`;return b(["eval",n,f],r+1e4)}async function gf(n){let r=`(() => {
297
- const el = document.querySelector('${Z.answerContainer}');
296
+ })`;return b(["eval",n,u],r+1e4)}async function fu(n){let r=`(() => {
297
+ const el = document.querySelector('${J.answerContainer}');
298
298
  if (!el) return JSON.stringify({ answer: '', answerHtml: '' });
299
299
  const clone = el.cloneNode(true);
300
300
  clone.querySelectorAll('svg').forEach((n) => n.remove());
@@ -305,7 +305,7 @@ ${l}`,"utf8");try{Q(a)}catch{}Or(r,a)}}catch{}finally{if(g)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 tf(n){let r=String.raw`
308
+ })()`;return JSON.parse(await b(["eval",n,r],1e4))}async function tu(n){let r=String.raw`
309
309
  (async () => {
310
310
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
311
311
 
@@ -445,10 +445,10 @@ ${l}`,"utf8");try{Q(a)}catch{}Or(r,a)}}catch{}finally{if(g)try{Q(n)}catch{}}}asy
445
445
  webCaptured: webSources.length,
446
446
  },
447
447
  });
448
- })()`,f=await b(["eval",n,r],20000);return JSON.parse(f)}async function of(n){let r=String.raw`
448
+ })()`,u=await b(["eval",n,r],20000);return JSON.parse(u)}async function iu(n){let r=String.raw`
449
449
  (async () => {
450
450
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
451
- const answer = document.querySelector('${Z.answerContainer}');
451
+ const answer = document.querySelector('${J.answerContainer}');
452
452
  if (!answer) return JSON.stringify([]);
453
453
 
454
454
  function parseUrlFromId(id) {
@@ -549,5 +549,5 @@ ${l}`,"utf8");try{Q(a)}catch{}Or(r,a)}}catch{}finally{if(g)try{Q(n)}catch{}}}asy
549
549
  }
550
550
  }
551
551
  return JSON.stringify(sources);
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();
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 X=new URL(l).hostname.toLowerCase();e=X==="logically.app"||X.endsWith(".logically.app")}catch{}if(!e)c(g,"nav",t),await b(["nav",o,Fr],25000),await new Promise((X)=>setTimeout(X,900));c(g,"new-chat",t),await Er(o),await new Promise((X)=>setTimeout(X,700)),c(g,"input-wait",t);let $=await Wn(o,J.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('${J.submitButton}'); if (!btn) return 'missing'; btn.click(); return 'clicked'; })()`])!=="clicked")throw Error("Logically submit button not found");if(await new Promise((X)=>setTimeout(X,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:Z,answerHtml:v}=await fu(o);if(!Z)throw Error("No answer extracted — Logically may not have responded");c(g,"extract-inline-citations",t);let D=await iu(o);c(g,"extract-full-citations",t);let M=await tu(o),In=M.sources?.length?M.sources:D,Sn=await b(["eval",o,"document.location.href"]).catch(()=>"");g.durationMs=Date.now()-t,g.sourcePath=M.sources?.length?"citations-popover":"inline-citation-popovers",c(g,"done",t),Zn({query:r,url:Sn,answer:Jn(Z,f),answerHtml:v,sources:In,inlineSources:D,citationSummary:M.summary,_envelope:E(g)})}catch(o){g.durationMs=Date.now()-t,xn(o,E(g))}}ou();
@@ -11,16 +11,6 @@
11
11
  ],
12
12
  "author": "Apostolos Mantzaris",
13
13
  "license": "MIT",
14
- "files": [
15
- "index.ts",
16
- "bin/",
17
- "src/",
18
- "skills/",
19
- "extractors/",
20
- "test/",
21
- "README.md",
22
- "LICENSE"
23
- ],
24
14
  "dm": {
25
15
  "extensions": [
26
16
  "./index.js"
@@ -1,4 +1,4 @@
1
- import{spawn as Qt,execFileSync as Ve,execSync as ge}from"node:child_process";import{existsSync as C,readFileSync as X,renameSync as Ht,unlinkSync as d,writeFileSync as G}from"node:fs";import de from"node:http";import{platform as me,tmpdir as qt}from"node:os";import{join as fe}from"node:path";import{spawn as Ie}from"node:child_process";import{dirname as Ee,join as Fe}from"node:path";import{fileURLToPath as ze}from"node:url";import{basename as et}from"node:path";function tt(e=process.env,t=process.execPath){let r=e.GREEDY_SEARCH_NODE||e.NODE_BINARY||e.NODE;if(r?.trim())return r.trim();let n=et(t||"").toLowerCase();if(n==="node"||n==="node.exe")return t;return"node"}var rt=Ee(ze(import.meta.url)),nt=Fe(rt,"..","bin","cdp.mjs");function I(e,t=30000){return it(e,null,t)}function it(e,t=null,r=30000){return new Promise((n,i)=>{let a=Ie(tt(),[nt,...e],{stdio:[t==null?"ignore":"pipe","pipe","pipe"]});if(t!=null)a.stdin.write(t),a.stdin.end();let u="",s="";a.stdout.on("data",(l)=>u+=l),a.stderr.on("data",(l)=>s+=l);let o=setTimeout(()=>{a.kill(),i(Error(`cdp timeout: ${e[0]}`))},r);a.on("close",(l)=>{if(clearTimeout(o),l===0)n(u.trim());else i(Error(s.trim()||`cdp exit ${l}`))})})}async function E(e){await I(["evalraw",e,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
1
+ import{spawn as Bt,execFileSync as qe,execSync as pe}from"node:child_process";import{existsSync as U,readFileSync as T,renameSync as Qt,unlinkSync as d,writeFileSync as L}from"node:fs";import ge from"node:http";import{platform as de,tmpdir as Ht}from"node:os";import{join as qt}from"node:path";import{spawn as Ge}from"node:child_process";import{dirname as Ee,join as Ie}from"node:path";import{fileURLToPath as Fe}from"node:url";import{basename as ze}from"node:path";function et(e=process.env,t=process.execPath){let r=e.GREEDY_SEARCH_NODE||e.NODE_BINARY||e.NODE;if(r?.trim())return r.trim();let n=ze(t||"").toLowerCase();if(n==="node"||n==="node.exe")return t;return"node"}var tt=Ee(Fe(import.meta.url)),rt=Ie(tt,"..","bin","cdp.mjs");function G(e,t=30000){return nt(e,null,t)}function nt(e,t=null,r=30000){return new Promise((n,i)=>{let a=Ge(et(),[rt,...e],{stdio:[t==null?"ignore":"pipe","pipe","pipe"]});if(t!=null)a.stdin.write(t),a.stdin.end();let u="",s="";a.stdout.on("data",(l)=>u+=l),a.stderr.on("data",(l)=>s+=l);let o=setTimeout(()=>{a.kill(),i(Error(`cdp timeout: ${e[0]}`))},r);a.on("close",(l)=>{if(clearTimeout(o),l===0)n(u.trim());else i(Error(s.trim()||`cdp exit ${l}`))})})}async function E(e){await G(["evalraw",e,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
2
2
  (function() {
3
3
  // ── Runtime.enable / CDP detection masking ──────────────
4
4
  try { delete window.__REBROWSER_RUNTIME_ENABLE; } catch(_) {}
@@ -206,29 +206,29 @@ import{spawn as Qt,execFileSync as Ve,execSync as ge}from"node:child_process";im
206
206
  };
207
207
  } catch(_) {}
208
208
  })();
209
- `})])}import{basename as at}from"node:path";function ye(e=process.env,t=process.execPath){let r=e.GREEDY_SEARCH_NODE||e.NODE_BINARY||e.NODE;if(r?.trim())return r.trim();let n=at(t||"").toLowerCase();if(n==="node"||n==="node.exe")return t;return"node"}import{existsSync as ve}from"node:fs";import{platform as ot}from"node:os";import{join as y}from"node:path";function f(e){let t=ot()==="win32",r=process.env.SystemRoot||"C:\\Windows",n={win32:{powershell:y(r,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:y(r,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:y(r,"System32","netstat.exe"),taskkill:y(r,"System32","taskkill.exe"),tasklist:y(r,"System32","tasklist.exe"),cmd:y(r,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},i=t?n.win32:n.unix,a=e.toLowerCase();if(i[a]&&ve(i[a]))return i[a];if(t&&a==="netstat"){let u=y(r,"Sysnative","netstat.exe");if(ve(u))return u}return e}import{existsSync as B,mkdirSync as st,readFileSync as $e,writeFileSync as lt}from"node:fs";import{homedir as ut}from"node:os";import{join as Pe}from"node:path";import{tmpdir as Q}from"node:os";var c=9222,k=`${Q().replaceAll("\\","/")}/greedysearch-chrome-profile`,A=`${k}/DevToolsActivePort`,re=`${Q().replaceAll("\\","/")}/cdp-pages.json`,v=`${Q().replaceAll("\\","/")}/greedysearch-chrome-mode`,hr=`${Q().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,z=Pe(ut(),".dm"),p=Pe(z,"greedyconfig"),ee=["perplexity","google","chatgpt"],te="gemini";function ct(){try{if(B(p)){let e=$e(p,"utf8"),t=JSON.parse(e);if(Array.isArray(t.engines)&&t.engines.length>0&&t.engines.every((r)=>typeof r==="string")){let r=t.engines.filter((i)=>F[i]),n=t.engines.filter((i)=>!F[i]);if(n.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${p}: ${n.join(", ")}
210
- [greedysearch] Available engines: ${Object.keys(F).join(", ")}
211
- `);if(r.length>0)return r;process.stderr.write(`[greedysearch] Warning: no valid engines in ${p}, falling back to defaults: ${ee.join(", ")}
212
- `)}}}catch{}return ee}function ft(){try{if(!B(z))st(z,{recursive:!0});if(!B(p))lt(p,JSON.stringify({engines:ee,synthesizer:te},null,2)+`
213
- `,"utf8")}catch{}}ft();var _e=["gemini","chatgpt"];function pt(){try{if(B(p)){let e=$e(p,"utf8"),t=JSON.parse(e);if(typeof t.synthesizer==="string"){let r=t.synthesizer.toLowerCase();if(_e.includes(r))return r;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${t.synthesizer}" in ${p}
214
- [greedysearch] Available synthesizers: ${_e.join(", ")}
215
- [greedysearch] Falling back to default: ${te}
216
- `)}}}catch{}return te}var F={perplexity:"perplexity.mjs",p:"perplexity.mjs",bing:"bing-copilot.mjs",b:"bing-copilot.mjs",google:"google-ai.mjs",g:"google-ai.mjs",gemini:"gemini.mjs",gem:"gemini.mjs",chatgpt:"chatgpt.mjs",gpt:"chatgpt.mjs","semantic-scholar":"semantic-scholar.mjs",semanticscholar:"semantic-scholar.mjs",s2:"semantic-scholar.mjs",logically:"logically.mjs",log:"logically.mjs"},wr=ct();var br=pt(),yr=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=k;import{existsSync as $r,mkdirSync as gt,readFileSync as Ae,renameSync as dt,unlinkSync as mt,writeFileSync as De}from"node:fs";import ht from"node:http";import{platform as Se}from"node:os";import{dirname as wt}from"node:path";var Ne=[9222,9223],bt=/^(0|false|no|off)$/i;function yt(e){return[...new Set(e.filter(Boolean))]}function xe(e,t="explicit"){let r=new URL(e),n=r.protocol==="wss:"?"wss:":"ws:",i=r.port?Number.parseInt(r.port,10):n==="wss:"?443:80;return{source:t,wsUrl:`${n}//${r.host}${r.pathname}${r.search}`,host:r.hostname,port:i,path:`${r.pathname}${r.search}`,httpUrl:`http://${r.hostname}:${i}`}}function Ce(e=process.env){return![e.GREEDY_SEARCH_REUSE_EXISTING_BROWSER,e.DM_CUA_REUSE_EXISTING_BROWSER].some((t)=>t!==void 0&&bt.test(String(t)))}function ne(e){let t=Number.parseInt(String(e??""),10);return Number.isInteger(t)&&t>0&&t<65536?t:null}function vt(e){if(!e)return null;let t=String(e).trim();if(!t)return null;let r=new URL(t.includes("://")?t:`http://${t}`),n=ne(r.port)||(r.protocol==="https:"?443:80);return{host:r.hostname,port:n,source:`env:${t}`}}function _t(e){if(!e)return[];return String(e).split(/[,\s]+/).map(ne).filter(Boolean)}function $t({env:e=process.env,platformName:t=Se(),procVersionText:r=null}={}){if(t!=="linux")return!1;if(e.WSL_DISTRO_NAME||e.WSL_INTEROP)return!0;let n=r??(()=>{try{return Ae("/proc/version","utf8")}catch{return""}})();return/microsoft|wsl/i.test(n)}function Pt({env:e=process.env,platformName:t=Se(),procVersionText:r=null,resolvConfText:n=null}={}){let i=["localhost","127.0.0.1"];if($t({env:e,platformName:t,procVersionText:r})){let a=(n??(()=>{try{return Ae("/etc/resolv.conf","utf8")}catch{return""}})()).match(/^\s*nameserver\s+([^\s#]+)/m);if(a)i.push(a[1]);i.push("host.docker.internal")}return yt(i)}function xt({env:e=process.env,hosts:t=Pt({env:e}),autoPorts:r=Ne,excludePorts:n=[]}={}){let i=[];for(let o of["GREEDY_SEARCH_CDP_WS_URL","DM_CUA_CDP_WS_URL","CDP_WS_URL"])if(e[o])i.push({wsUrl:e[o],source:`env:${o}`});for(let o of["GREEDY_SEARCH_CDP_URL","DM_CUA_CDP_URL","CDP_URL"])try{let l=vt(e[o]);if(l)i.push(l)}catch{}for(let o of["GREEDY_SEARCH_EXISTING_CDP_PORT","DM_CUA_EXISTING_CDP_PORT","GREEDY_SEARCH_CDP_PORT","DM_CUA_CDP_PORT"]){let l=ne(e[o]);if(!l)continue;for(let h of t)i.push({host:h,port:l,source:`env:${o}`})}let a=_t(e.GREEDY_SEARCH_EXISTING_CDP_PORTS);for(let o of a)for(let l of t)i.push({host:l,port:o,source:"env:GREEDY_SEARCH_EXISTING_CDP_PORTS"});let u=new Set(n.filter(Boolean));if(Ce(e))for(let o of r){if(u.has(o))continue;for(let l of t)i.push({host:l,port:o,source:"auto"})}let s=new Set;return i.filter((o)=>{let l=o.wsUrl||`${o.host}:${o.port}`;if(s.has(l))return!1;return s.add(l),!0})}async function At(e,{timeoutMs:t=700}={}){if(e.wsUrl)return xe(e.wsUrl,e.source);let r=e.host||"localhost",n=e.port;if(!n)return null;let i=await new Promise((a)=>{let u=ht.get({host:r,port:n,path:"/json/version",timeout:t},(s)=>{let o="";s.setEncoding("utf8"),s.on("data",(l)=>o+=l),s.on("end",()=>a(s.statusCode===200?o:null))});u.on("error",()=>a(null)),u.setTimeout(t,()=>{u.destroy(),a(null)})});if(!i)return null;try{let a=JSON.parse(i);if(!a.webSocketDebuggerUrl)return null;let u=xe(a.webSocketDebuggerUrl,e.source),s=u.path||new URL(a.webSocketDebuggerUrl).pathname;return{...u,host:r,port:n,httpUrl:`http://${r}:${n}`,wsUrl:`ws://${r}:${n}${s}`,path:s}}catch{return null}}async function Dt(e={}){for(let t of xt(e)){let r=await At(t,e);if(r)return r}return null}function St(e){if(!e)throw Error("missing CDP endpoint");let t=new URL(e.wsUrl);return`${t.host}
209
+ `})])}import{basename as it}from"node:path";function be(e=process.env,t=process.execPath){let r=e.GREEDY_SEARCH_NODE||e.NODE_BINARY||e.NODE;if(r?.trim())return r.trim();let n=it(t||"").toLowerCase();if(n==="node"||n==="node.exe")return t;return"node"}import{existsSync as ye}from"node:fs";import{platform as at}from"node:os";import{join as y}from"node:path";function f(e){let t=at()==="win32",r=process.env.SystemRoot||"C:\\Windows",n={win32:{powershell:y(r,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:y(r,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:y(r,"System32","netstat.exe"),taskkill:y(r,"System32","taskkill.exe"),tasklist:y(r,"System32","tasklist.exe"),cmd:y(r,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},i=t?n.win32:n.unix,a=e.toLowerCase();if(i[a]&&ye(i[a]))return i[a];if(t&&a==="netstat"){let u=y(r,"Sysnative","netstat.exe");if(ye(u))return u}return e}import{existsSync as j,mkdirSync as ot,readFileSync as _e,writeFileSync as st}from"node:fs";import{homedir as lt}from"node:os";import{join as $e}from"node:path";import{tmpdir as B}from"node:os";var c=9222,te=`${B().replaceAll("\\","/")}/greedysearch-chrome-profile`,A=`${te}/DevToolsActivePort`,re=`${B().replaceAll("\\","/")}/cdp-pages.json`,v=`${B().replaceAll("\\","/")}/greedysearch-chrome-mode`,mr=`${B().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,F=$e(lt(),".dm"),p=$e(F,"greedyconfig"),z=["perplexity","google","chatgpt"],ee="gemini";function ut(){try{if(j(p)){let e=_e(p,"utf8"),t=JSON.parse(e);if(Array.isArray(t.engines)&&t.engines.length>0&&t.engines.every((r)=>typeof r==="string")){let r=t.engines.filter((i)=>I[i]),n=t.engines.filter((i)=>!I[i]);if(n.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${p}: ${n.join(", ")}
210
+ [greedysearch] Available engines: ${Object.keys(I).join(", ")}
211
+ `);if(r.length>0)return r;process.stderr.write(`[greedysearch] Warning: no valid engines in ${p}, falling back to defaults: ${z.join(", ")}
212
+ `)}}}catch{}return z}function ct(){try{if(!j(F))ot(F,{recursive:!0});if(!j(p))st(p,JSON.stringify({engines:z,synthesizer:ee},null,2)+`
213
+ `,"utf8")}catch{}}ct();var ve=["gemini","chatgpt"];function ft(){try{if(j(p)){let e=_e(p,"utf8"),t=JSON.parse(e);if(typeof t.synthesizer==="string"){let r=t.synthesizer.toLowerCase();if(ve.includes(r))return r;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${t.synthesizer}" in ${p}
214
+ [greedysearch] Available synthesizers: ${ve.join(", ")}
215
+ [greedysearch] Falling back to default: ${ee}
216
+ `)}}}catch{}return ee}var I={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"},hr=ut();var wr=ft(),br=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=te;import{existsSync as _r,mkdirSync as pt,readFileSync as xe,renameSync as gt,unlinkSync as dt,writeFileSync as Ae}from"node:fs";import mt from"node:http";import{platform as De}from"node:os";import{dirname as ht}from"node:path";var Se=[9222,9223],wt=/^(0|false|no|off)$/i;function bt(e){return[...new Set(e.filter(Boolean))]}function Pe(e,t="explicit"){let r=new URL(e),n=r.protocol==="wss:"?"wss:":"ws:",i=r.port?Number.parseInt(r.port,10):n==="wss:"?443:80;return{source:t,wsUrl:`${n}//${r.host}${r.pathname}${r.search}`,host:r.hostname,port:i,path:`${r.pathname}${r.search}`,httpUrl:`http://${r.hostname}:${i}`}}function Ne(e=process.env){return![e.GREEDY_SEARCH_REUSE_EXISTING_BROWSER,e.DM_CUA_REUSE_EXISTING_BROWSER].some((t)=>t!==void 0&&wt.test(String(t)))}function ne(e){let t=Number.parseInt(String(e??""),10);return Number.isInteger(t)&&t>0&&t<65536?t:null}function yt(e){if(!e)return null;let t=String(e).trim();if(!t)return null;let r=new URL(t.includes("://")?t:`http://${t}`),n=ne(r.port)||(r.protocol==="https:"?443:80);return{host:r.hostname,port:n,source:`env:${t}`}}function vt(e){if(!e)return[];return String(e).split(/[,\s]+/).map(ne).filter(Boolean)}function _t({env:e=process.env,platformName:t=De(),procVersionText:r=null}={}){if(t!=="linux")return!1;if(e.WSL_DISTRO_NAME||e.WSL_INTEROP)return!0;let n=r??(()=>{try{return xe("/proc/version","utf8")}catch{return""}})();return/microsoft|wsl/i.test(n)}function $t({env:e=process.env,platformName:t=De(),procVersionText:r=null,resolvConfText:n=null}={}){let i=["localhost","127.0.0.1"];if(_t({env:e,platformName:t,procVersionText:r})){let a=(n??(()=>{try{return xe("/etc/resolv.conf","utf8")}catch{return""}})()).match(/^\s*nameserver\s+([^\s#]+)/m);if(a)i.push(a[1]);i.push("host.docker.internal")}return bt(i)}function Pt({env:e=process.env,hosts:t=$t({env:e}),autoPorts:r=Se,excludePorts:n=[]}={}){let i=[];for(let o of["GREEDY_SEARCH_CDP_WS_URL","DM_CUA_CDP_WS_URL","CDP_WS_URL"])if(e[o])i.push({wsUrl:e[o],source:`env:${o}`});for(let o of["GREEDY_SEARCH_CDP_URL","DM_CUA_CDP_URL","CDP_URL"])try{let l=yt(e[o]);if(l)i.push(l)}catch{}for(let o of["GREEDY_SEARCH_EXISTING_CDP_PORT","DM_CUA_EXISTING_CDP_PORT","GREEDY_SEARCH_CDP_PORT","DM_CUA_CDP_PORT"]){let l=ne(e[o]);if(!l)continue;for(let h of t)i.push({host:h,port:l,source:`env:${o}`})}let a=vt(e.GREEDY_SEARCH_EXISTING_CDP_PORTS);for(let o of a)for(let l of t)i.push({host:l,port:o,source:"env:GREEDY_SEARCH_EXISTING_CDP_PORTS"});let u=new Set(n.filter(Boolean));if(Ne(e))for(let o of r){if(u.has(o))continue;for(let l of t)i.push({host:l,port:o,source:"auto"})}let s=new Set;return i.filter((o)=>{let l=o.wsUrl||`${o.host}:${o.port}`;if(s.has(l))return!1;return s.add(l),!0})}async function xt(e,{timeoutMs:t=700}={}){if(e.wsUrl)return Pe(e.wsUrl,e.source);let r=e.host||"localhost",n=e.port;if(!n)return null;let i=await new Promise((a)=>{let u=mt.get({host:r,port:n,path:"/json/version",timeout:t},(s)=>{let o="";s.setEncoding("utf8"),s.on("data",(l)=>o+=l),s.on("end",()=>a(s.statusCode===200?o:null))});u.on("error",()=>a(null)),u.setTimeout(t,()=>{u.destroy(),a(null)})});if(!i)return null;try{let a=JSON.parse(i);if(!a.webSocketDebuggerUrl)return null;let u=Pe(a.webSocketDebuggerUrl,e.source),s=u.path||new URL(a.webSocketDebuggerUrl).pathname;return{...u,host:r,port:n,httpUrl:`http://${r}:${n}`,wsUrl:`ws://${r}:${n}${s}`,path:s}}catch{return null}}async function At(e={}){for(let t of Pt(e)){let r=await xt(t,e);if(r)return r}return null}function Dt(e){if(!e)throw Error("missing CDP endpoint");let t=new URL(e.wsUrl);return`${t.host}
217
217
  ${t.pathname}${t.search}
218
- `}function Nt(e,t){gt(wt(e),{recursive:!0});let r=`${e}.tmp-${process.pid}`;De(r,St(t),"utf8");try{mt(e)}catch{}dt(r,e)}async function ke({activePortFile:e,modeFile:t,env:r=process.env,excludePorts:n=[],autoPorts:i=Ne}={}){if(!Ce(r))return null;let a=await Dt({env:r,excludePorts:n,autoPorts:i});if(!a)return null;if(Nt(e,a),t)De(t,"existing","utf8");return a}import{execFileSync as We,execSync as ae}from"node:child_process";import{existsSync as H,mkdirSync as Ct,readFileSync as D,unlinkSync as P,writeFileSync as x}from"node:fs";import{platform as ue,tmpdir as Xe}from"node:os";import{existsSync as q,mkdirSync as kt,readFileSync as je,writeFileSync as Wt}from"node:fs";import{homedir as Jt}from"node:os";import{join as Be}from"node:path";import{tmpdir as L}from"node:os";import{existsSync as Me}from"node:fs";import{platform as Ot}from"node:os";import{join as _}from"node:path";var S=9222,W=`${L().replaceAll("\\","/")}/greedysearch-chrome-profile`,Rr=`${W}/DevToolsActivePort`,Ur=`${L().replaceAll("\\","/")}/cdp-pages.json`,Or=`${L().replaceAll("\\","/")}/greedysearch-chrome-mode`,Tr=`${L().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,oe=Be(Jt(),".dm"),g=Be(oe,"greedyconfig"),se=["perplexity","google","chatgpt"],le="gemini";function Mt(){try{if(q(g)){let e=je(g,"utf8"),t=JSON.parse(e);if(Array.isArray(t.engines)&&t.engines.length>0&&t.engines.every((r)=>typeof r==="string")){let r=t.engines.filter((i)=>ie[i]),n=t.engines.filter((i)=>!ie[i]);if(n.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${g}: ${n.join(", ")}
218
+ `}function St(e,t){pt(ht(e),{recursive:!0});let r=`${e}.tmp-${process.pid}`;Ae(r,Dt(t),"utf8");try{dt(e)}catch{}gt(r,e)}async function Ce({activePortFile:e,modeFile:t,env:r=process.env,excludePorts:n=[],autoPorts:i=Se}={}){if(!Ne(r))return null;let a=await At({env:r,excludePorts:n,autoPorts:i});if(!a)return null;if(St(e,a),t)Ae(t,"existing","utf8");return a}import{execFileSync as ke,execSync as ae}from"node:child_process";import{existsSync as Q,mkdirSync as Nt,readFileSync as D,unlinkSync as P,writeFileSync as x}from"node:fs";import{platform as ue,tmpdir as Te}from"node:os";import{existsSync as H,mkdirSync as Ct,readFileSync as Xe,writeFileSync as kt}from"node:fs";import{homedir as Rt}from"node:os";import{join as je}from"node:path";import{tmpdir as K}from"node:os";import{existsSync as We}from"node:fs";import{platform as Ot}from"node:os";import{join as _}from"node:path";var S=9222,C=`${K().replaceAll("\\","/")}/greedysearch-chrome-profile`,Jr=`${C}/DevToolsActivePort`,Mr=`${K().replaceAll("\\","/")}/cdp-pages.json`,Or=`${K().replaceAll("\\","/")}/greedysearch-chrome-mode`,Ur=`${K().replaceAll("\\","/")}/greedysearch-visible-recovery.jsonl`,oe=je(Rt(),".dm"),g=je(oe,"greedyconfig"),se=["perplexity","google","chatgpt"],le="gemini";function Wt(){try{if(H(g)){let e=Xe(g,"utf8"),t=JSON.parse(e);if(Array.isArray(t.engines)&&t.engines.length>0&&t.engines.every((r)=>typeof r==="string")){let r=t.engines.filter((i)=>ie[i]),n=t.engines.filter((i)=>!ie[i]);if(n.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${g}: ${n.join(", ")}
219
219
  [greedysearch] Available engines: ${Object.keys(ie).join(", ")}
220
220
  `);if(r.length>0)return r;process.stderr.write(`[greedysearch] Warning: no valid engines in ${g}, falling back to defaults: ${se.join(", ")}
221
- `)}}}catch{}return se}function Rt(){try{if(!q(oe))kt(oe,{recursive:!0});if(!q(g))Wt(g,JSON.stringify({engines:se,synthesizer:le},null,2)+`
222
- `,"utf8")}catch{}}Rt();var Je=["gemini","chatgpt"];function Ut(){try{if(q(g)){let e=je(g,"utf8"),t=JSON.parse(e);if(typeof t.synthesizer==="string"){let r=t.synthesizer.toLowerCase();if(Je.includes(r))return r;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${t.synthesizer}" in ${g}
223
- [greedysearch] Available synthesizers: ${Je.join(", ")}
221
+ `)}}}catch{}return se}function Jt(){try{if(!H(oe))Ct(oe,{recursive:!0});if(!H(g))kt(g,JSON.stringify({engines:se,synthesizer:le},null,2)+`
222
+ `,"utf8")}catch{}}Jt();var Re=["gemini","chatgpt"];function Mt(){try{if(H(g)){let e=Xe(g,"utf8"),t=JSON.parse(e);if(typeof t.synthesizer==="string"){let r=t.synthesizer.toLowerCase();if(Re.includes(r))return r;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${t.synthesizer}" in ${g}
223
+ [greedysearch] Available synthesizers: ${Re.join(", ")}
224
224
  [greedysearch] Falling back to default: ${le}
225
- `)}}}catch{}return le}var ie={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"},Xr=Mt(),jr=Ut(),Br=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=W;function w(e){let t=Ot()==="win32",r=process.env.SystemRoot||"C:\\Windows",n={win32:{powershell:_(r,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:_(r,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:_(r,"System32","netstat.exe"),taskkill:_(r,"System32","taskkill.exe"),tasklist:_(r,"System32","tasklist.exe"),cmd:_(r,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},i=t?n.win32:n.unix,a=e.toLowerCase();if(i[a]&&Me(i[a]))return i[a];if(t&&a==="netstat"){let u=_(r,"Sysnative","netstat.exe");if(Me(u))return u}return e}var R=Xe().replaceAll("\\","/"),V=`${R}/greedysearch-chrome-metadata.json`,$=`${R}/greedysearch-chrome-launch.lock`,Tt=15000,Z=`${R}/greedysearch-chrome.pid`,Y=`${R}/greedysearch-chrome-mode`,J=`${R}/greedysearch-chrome-last-activity`;function M(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Xt(e){if(!M(e))return null;try{if(ue()==="win32")return We(w("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return We(w("ps"),["-p",String(e),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function jt(e,t,r=S){if(!e)return!1;let n=(u)=>String(u||"").replaceAll("\\","/").toLowerCase(),i=n(e),a=n(t);return i.includes(a)&&i.includes(`--remote-debugging-port=${r}`)&&!i.includes("--type=")}function Re(e,t,r=S){return jt(Xt(e),t,r)}function Bt(e=S){try{if(ue()==="win32"){let r=ae(`${w("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),n=new RegExp(String.raw`TCP\s+\S+:${e}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),i=r.match(n);return i?Number.parseInt(i[1],10):null}let t=ae(`${w("lsof")} -i :${e} -t 2>/dev/null || ${w("ss")} -tlnp 2>/dev/null | ${w("grep")} :${e} | ${w("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return t?Number.parseInt(t.split(`
226
- `)[0],10):null}catch{return null}}function Ue(e){try{if(ue()==="win32")ae(`${w("taskkill")} /F /T /PID ${e}`,{stdio:"ignore"});else{try{process.kill(-e,"SIGKILL")}catch{}try{process.kill(e,"SIGKILL")}catch{}}return!0}catch{return!1}}function U(){try{if(H(V)){let e=D(V,"utf8"),t=JSON.parse(e);if(t&&typeof t.tempDir==="string"&&typeof t.debugPort==="number")return{browserPid:Number.isInteger(t.browserPid)?t.browserPid:void 0,debugPort:t.debugPort,tempDir:t.tempDir,clientPids:Array.isArray(t.clientPids)?t.clientPids.filter((r)=>Number.isInteger(r)&&r>0):[],sessionMode:t.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(t.lastActivity)?t.lastActivity:0,launchedAt:Number.isFinite(t.launchedAt)?t.launchedAt:0}}}catch{}try{let e=H(Z)?Number.parseInt(D(Z,"utf8").trim(),10)||void 0:void 0,t=H(Y)?D(Y,"utf8").trim()==="visible"?"visible":"headless":"headless",r=H(J)?Number.parseInt(D(J,"utf8").trim(),10)||0:0;return{browserPid:e,debugPort:S,tempDir:W,clientPids:e?[e]:[],sessionMode:t,lastActivity:r,launchedAt:0}}catch{return null}}function K(e){try{x(V,JSON.stringify({browserPid:e.browserPid,debugPort:e.debugPort,tempDir:e.tempDir,clientPids:[...new Set(e.clientPids.filter((t)=>t>0))],sessionMode:e.sessionMode,lastActivity:e.lastActivity,launchedAt:e.launchedAt},null,2),"utf8")}catch{}try{if(e.browserPid)x(Z,String(e.browserPid),"utf8")}catch{}try{x(Y,e.sessionMode,"utf8")}catch{}try{x(J,String(e.lastActivity),"utf8")}catch{}}function Oe(){try{P(V)}catch{}try{P(Z)}catch{}try{P(Y)}catch{}try{P(J)}catch{}}function Qe(e){if(!e)return e;let t={...e,clientPids:[...new Set([...e.clientPids,process.pid].filter((r)=>M(r)||r===process.pid))]};return K(t),t}function ce(e){let t=Date.now();try{if(e)K({...e,lastActivity:t});else x(J,String(t),"utf8")}catch{}}var Vr=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var Te=!1;function He(){if(Te)return;Te=!0;let e=U();if(!e)return;if(e.browserPid){if(!M(e.browserPid)){Ue(e.browserPid),Oe();return}if(!Re(e.browserPid,e.tempDir,e.debugPort))Oe();else K({...e,clientPids:e.clientPids.filter((r)=>M(r))})}let t=Bt();if(t&&t!==e.browserPid)if(Re(t,W,S))K({browserPid:t,debugPort:S,tempDir:W,clientPids:[t],sessionMode:e.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else Ue(t)}function qe(){Ct(Xe(),{recursive:!0});try{let e=JSON.stringify({pid:process.pid,ts:Date.now()});return x($,e,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let t=D($,"utf8");if(JSON.parse(t).pid===process.pid)P($)}catch{}}}}catch(e){if(e?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let e=D($,"utf8"),t=JSON.parse(e),r=Date.now()-(t.ts||0);if(!M(t.pid)||r>Tt){try{P($)}catch{}try{let n=JSON.stringify({pid:process.pid,ts:Date.now()});return x($,n,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{P($)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var Vt=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1");function Zt(e=Vt){let t=[fe(e,"launch.mjs"),fe(e,"..","bin","launch.mjs"),fe(e,"..","..","bin","launch.mjs")];for(let r of t)if(C(r))return r;return t[t.length-1]}var Ye=qt().replaceAll("\\","/"),O=`${Ye}/greedysearch-chrome.pid`,T=`${Ye}/greedysearch-chrome-last-activity`,Yt=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,Kt=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;function Lt(e,t=c){let r=String(e||"").toLowerCase();if(!r.includes(`--remote-debugging-port=${t}`)||r.includes("--type="))return null;return r.includes("--headless")}function Ke(){try{let e=he(),t=e?It(e):null,r=Lt(t);if(r!==null){try{G(v,r?"headless":"visible","utf8")}catch{}return r}}catch{}try{if(!C(v))return!0;return X(v,"utf8").trim()==="headless"}catch{return!0}}function Gt(){try{G(T,String(Date.now()),"utf8")}catch{}try{let e=U();if(e)ce(e)}catch{}}function It(e){try{if(me()==="win32")return Ve(f("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return Ve(f("ps"),["-p",String(e),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function he(){try{if(me()==="win32"){let t=ge(`${f("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),r=new RegExp(String.raw`TCP\s+\S+:${c}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),n=t.match(r);return n?Number.parseInt(n[1],10):null}let e=ge(`${f("lsof")} -i :${c} -t 2>/dev/null || ${f("ss")} -tlnp 2>/dev/null | ${f("grep")} :${c} | ${f("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return e?Number.parseInt(e.split(`
227
- `)[0],10):null}catch{return null}}async function Et(e=1500){try{let r=await new Promise((i,a)=>{let u=de.get(`http://localhost:${c}/json/version`,(s)=>{let o="";s.on("data",(l)=>o+=l),s.on("end",()=>{try{i(JSON.parse(o))}catch{a(Error("bad JSON"))}})});u.on("error",a),u.setTimeout(1000,()=>{u.destroy(),a(Error("timeout"))})}),n=new globalThis.WebSocket(r.webSocketDebuggerUrl);await new Promise((i)=>{n.onopen=()=>{n.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{n.close(),i()},200)},n.onerror=()=>i(),setTimeout(i,1000)})}catch{}let t=Date.now()+e;while(Date.now()<t){if(!he())return!0;await new Promise((n)=>setTimeout(n,150))}return Ft()}function Ft(){try{let e=he();if(!e&&C(O))e=Number.parseInt(X(O,"utf8").trim(),10)||null;if(!e)return!1;if(me()==="win32")ge(`${f("taskkill")} /F /PID ${e}`,{stdio:"ignore"});else process.kill(e,"SIGKILL");return!0}catch{return!1}}async function Le(){if(!await N(500)){try{d(O)}catch{}try{d(T)}catch{}try{d(v)}catch{}return!1}let t=await Et(1500);try{d(O)}catch{}try{d(T)}catch{}try{d(v)}catch{}if(t)process.stderr.write(`[greedysearch] Killed Chrome on port ${c}.
228
- `);return t}var Ze=Le;async function zt(){let t=Ke()?Yt:Kt;if(t<=0)return!1;if(!C(T))return Gt(),!1;try{let r=Number.parseInt(X(T,"utf8").trim(),10);if(!r)return!1;if((Date.now()-r)/60000>=t)return Le()}catch{}return!1}var m=I;async function we(){let t=(await m(["list"])).split(`
229
- `)[0];if(!t)throw Error("No Chrome tabs found");return t.slice(0,8)}async function nn(e="about:blank"){let t=await we(),r=new URL(e).hostname;if(r==="copilot.microsoft.com"||r==="www.perplexity.ai"||r==="perplexity.ai"||r.endsWith(".perplexity.ai")){let u=await m(["evalraw",t,"Target.createTarget",JSON.stringify({url:"about:blank"})]),{targetId:s}=JSON.parse(u),o=s.slice(0,8);if(await m(["list"]).catch(()=>null),r==="copilot.microsoft.com")await E(o);else E(o).catch(()=>{});return await m(["list"]).catch(()=>null),s}let i=await m(["evalraw",t,"Target.createTarget",JSON.stringify({url:e})]),{targetId:a}=JSON.parse(i);return await m(["list"]).catch(()=>null),a}async function an(e){try{let t=await we();await m(["evalraw",t,"Target.activateTarget",JSON.stringify({targetId:e})])}catch{}}async function er(e){try{let t=await we();await m(["evalraw",t,"Target.closeTarget",JSON.stringify({targetId:e})])}catch{}}async function on(e=[]){if(await Promise.all(e.filter(Boolean).map((t)=>er(t).catch(()=>{}))),e.length>0)await m(["list"]).catch(()=>null)}function sn(e,t){try{if(!C(re))return null;let n=JSON.parse(X(re,"utf8")).find((i)=>i.url.includes(t[e]));return n?n.targetId:null}catch{return null}}function N(e=3000){return new Promise((t)=>{let r=de.get(`http://localhost:${c}/json/version`,(n)=>{n.resume(),t(n.statusCode===200)});r.on("error",()=>t(!1)),r.setTimeout(e,()=>{r.destroy(),t(!1)})})}async function pe(){let e=`${A}.lock`,t=`${A}.tmp`,r=5000,n=1000,i=await new Promise((a)=>{let u=Date.now(),s=()=>{try{let o=JSON.stringify({pid:process.pid,ts:Date.now()});G(e,o,{encoding:"utf8",flag:"wx"}),a(!0)}catch(o){if(o?.code!=="EEXIST"){if(Date.now()-u<1000)setTimeout(s,50);else a(!1);return}try{let l=X(e,"utf8").trim(),h=l.startsWith("{")?JSON.parse(l):{ts:Number(l)},b=Number(h?.ts)||0;if(b>0&&Date.now()-b>5000)try{d(e)}catch{}if(Date.now()-u<1000)setTimeout(s,50);else a(!1)}catch{if(Date.now()-u<1000)setTimeout(s,50);else a(!1)}}};s()});try{let a=await new Promise((l,h)=>{let b=de.get(`http://localhost:${c}/json/version`,(j)=>{let be="";j.on("data",(Ge)=>be+=Ge),j.on("end",()=>l(be))});b.on("error",h),b.setTimeout(3000,()=>{b.destroy(),h(Error("timeout"))})}),{webSocketDebuggerUrl:u}=JSON.parse(a),s=new URL(u),o=`${s.pathname}${s.search}`;if(i){G(t,`localhost:${c}
230
- ${o}`,"utf8");try{d(A)}catch{}Ht(t,A)}}catch{}finally{if(i)try{d(e)}catch{}}}async function ln(){let e=C(O)||!!U(),t=await ke({activePortFile:A,modeFile:v,excludePorts:e?[c]:[]});if(t){process.stderr.write(`[greedysearch] Reusing existing browser CDP endpoint ${t.httpUrl} (${t.source}).
231
- `);return}He();let r=await zt(),n=r?!1:await N();if(!n&&!r)await new Promise((s)=>setTimeout(s,500)),n=await N();let i=!1;if(n){let s=Ke(),o=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!o&&!s)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
232
- `),await Ze(),await new Promise((l)=>setTimeout(l,1000)),i=!0;else if(o&&s)process.stderr.write(`[greedysearch] Headless Chrome detected — switching to visible mode...
233
- `),await Ze(),await new Promise((l)=>setTimeout(l,1000)),i=!0}if(i?!1:await N()){await pe();try{let s=U();if(s)ce(s),Qe(s)}catch{}return}let u=qe();if(!u.acquired){if(await new Promise((o)=>setTimeout(o,3000)),await N(5000)){await pe();return}}try{if(await N(1000)){await pe();return}process.stderr.write(`GreedySearch Chrome not running on port ${c} — auto-launching...
234
- `);let o=[Zt()];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")o.push("--headless");await new Promise((l,h)=>{Qt(ye(),o,{stdio:["ignore",process.stderr,process.stderr],env:{...process.env,CDP_PROFILE_DIR:k,GREEDY_SEARCH_PROFILE_DIR:k}}).on("close",(j)=>j===0?l():h(Error("launch.mjs failed")))})}finally{u.release()}}export{Gt as touchActivity,Zt as resolveGreedySearchLaunchScript,pe as refreshPortFile,N as probeGreedyChrome,nn as openNewTab,Ze as killHeadlessChrome,Le as killChrome,Ke as isChromeHeadless,sn as getFullTabFromCache,we as getAnyTab,ln as ensureChrome,Lt as detectHeadlessFromChromeCommandLine,on as closeTabs,er as closeTab,zt as checkAndKillIdle,m as cdp,an as activateTab};
225
+ `)}}}catch{}return le}var ie={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"},Tr=Wt(),Xr=Mt(),jr=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=C;function w(e){let t=Ot()==="win32",r=process.env.SystemRoot||"C:\\Windows",n={win32:{powershell:_(r,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:_(r,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:_(r,"System32","netstat.exe"),taskkill:_(r,"System32","taskkill.exe"),tasklist:_(r,"System32","tasklist.exe"),cmd:_(r,"System32","cmd.exe")},unix:{ps:"/usr/bin/ps",lsof:"/usr/bin/lsof",ss:"/usr/sbin/ss",grep:"/usr/bin/grep",kill:"/usr/bin/kill"}},i=t?n.win32:n.unix,a=e.toLowerCase();if(i[a]&&We(i[a]))return i[a];if(t&&a==="netstat"){let u=_(r,"Sysnative","netstat.exe");if(We(u))return u}return e}var W=Te().replaceAll("\\","/"),q=`${W}/greedysearch-chrome-metadata.json`,$=`${W}/greedysearch-chrome-launch.lock`,Ut=15000,V=`${W}/greedysearch-chrome.pid`,Z=`${W}/greedysearch-chrome-mode`,k=`${W}/greedysearch-chrome-last-activity`;function R(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Tt(e){if(!R(e))return null;try{if(ue()==="win32")return ke(w("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return ke(w("ps"),["-p",String(e),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Xt(e,t,r=S){if(!e)return!1;let n=(u)=>String(u||"").replaceAll("\\","/").toLowerCase(),i=n(e),a=n(t);return i.includes(a)&&i.includes(`--remote-debugging-port=${r}`)&&!i.includes("--type=")}function Je(e,t,r=S){return Xt(Tt(e),t,r)}function jt(e=S){try{if(ue()==="win32"){let r=ae(`${w("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),n=new RegExp(String.raw`TCP\s+\S+:${e}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),i=r.match(n);return i?Number.parseInt(i[1],10):null}let t=ae(`${w("lsof")} -i :${e} -t 2>/dev/null || ${w("ss")} -tlnp 2>/dev/null | ${w("grep")} :${e} | ${w("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return t?Number.parseInt(t.split(`
226
+ `)[0],10):null}catch{return null}}function Me(e){try{if(ue()==="win32")ae(`${w("taskkill")} /F /T /PID ${e}`,{stdio:"ignore"});else{try{process.kill(-e,"SIGKILL")}catch{}try{process.kill(e,"SIGKILL")}catch{}}return!0}catch{return!1}}function J(){try{if(Q(q)){let e=D(q,"utf8"),t=JSON.parse(e);if(t&&typeof t.tempDir==="string"&&typeof t.debugPort==="number")return{browserPid:Number.isInteger(t.browserPid)?t.browserPid:void 0,debugPort:t.debugPort,tempDir:t.tempDir,clientPids:Array.isArray(t.clientPids)?t.clientPids.filter((r)=>Number.isInteger(r)&&r>0):[],sessionMode:t.sessionMode==="visible"?"visible":"headless",lastActivity:Number.isFinite(t.lastActivity)?t.lastActivity:0,launchedAt:Number.isFinite(t.launchedAt)?t.launchedAt:0}}}catch{}try{let e=Q(V)?Number.parseInt(D(V,"utf8").trim(),10)||void 0:void 0,t=Q(Z)?D(Z,"utf8").trim()==="visible"?"visible":"headless":"headless",r=Q(k)?Number.parseInt(D(k,"utf8").trim(),10)||0:0;return{browserPid:e,debugPort:S,tempDir:C,clientPids:e?[e]:[],sessionMode:t,lastActivity:r,launchedAt:0}}catch{return null}}function Y(e){try{x(q,JSON.stringify({browserPid:e.browserPid,debugPort:e.debugPort,tempDir:e.tempDir,clientPids:[...new Set(e.clientPids.filter((t)=>t>0))],sessionMode:e.sessionMode,lastActivity:e.lastActivity,launchedAt:e.launchedAt},null,2),"utf8")}catch{}try{if(e.browserPid)x(V,String(e.browserPid),"utf8")}catch{}try{x(Z,e.sessionMode,"utf8")}catch{}try{x(k,String(e.lastActivity),"utf8")}catch{}}function Oe(){try{P(q)}catch{}try{P(V)}catch{}try{P(Z)}catch{}try{P(k)}catch{}}function Be(e){if(!e)return e;let t={...e,clientPids:[...new Set([...e.clientPids,process.pid].filter((r)=>R(r)||r===process.pid))]};return Y(t),t}function ce(e){let t=Date.now();try{if(e)Y({...e,lastActivity:t});else x(k,String(t),"utf8")}catch{}}var qr=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var Ue=!1;function Qe(){if(Ue)return;Ue=!0;let e=J();if(!e)return;if(e.browserPid){if(!R(e.browserPid)){Me(e.browserPid),Oe();return}if(!Je(e.browserPid,e.tempDir,e.debugPort))Oe();else Y({...e,clientPids:e.clientPids.filter((r)=>R(r))})}let t=jt();if(t&&t!==e.browserPid)if(Je(t,C,S))Y({browserPid:t,debugPort:S,tempDir:C,clientPids:[t],sessionMode:e.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else Me(t)}function He(){Nt(Te(),{recursive:!0});try{let e=JSON.stringify({pid:process.pid,ts:Date.now()});return x($,e,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let t=D($,"utf8");if(JSON.parse(t).pid===process.pid)P($)}catch{}}}}catch(e){if(e?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let e=D($,"utf8"),t=JSON.parse(e),r=Date.now()-(t.ts||0);if(!R(t.pid)||r>Ut){try{P($)}catch{}try{let n=JSON.stringify({pid:process.pid,ts:Date.now()});return x($,n,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{P($)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var Vt=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),Ze=Ht().replaceAll("\\","/"),M=`${Ze}/greedysearch-chrome.pid`,O=`${Ze}/greedysearch-chrome-last-activity`,Zt=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,Yt=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;function Kt(e,t=c){let r=String(e||"").toLowerCase();if(!r.includes(`--remote-debugging-port=${t}`)||r.includes("--type="))return null;return r.includes("--headless")}function Ye(){try{let e=me(),t=e?Gt(e):null,r=Kt(t);if(r!==null){try{L(v,r?"headless":"visible","utf8")}catch{}return r}}catch{}try{if(!U(v))return!0;return T(v,"utf8").trim()==="headless"}catch{return!0}}function Lt(){try{L(O,String(Date.now()),"utf8")}catch{}try{let e=J();if(e)ce(e)}catch{}}function Gt(e){try{if(de()==="win32")return qe(f("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return qe(f("ps"),["-p",String(e),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function me(){try{if(de()==="win32"){let t=pe(`${f("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),r=new RegExp(String.raw`TCP\s+\S+:${c}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),n=t.match(r);return n?Number.parseInt(n[1],10):null}let e=pe(`${f("lsof")} -i :${c} -t 2>/dev/null || ${f("ss")} -tlnp 2>/dev/null | ${f("grep")} :${c} | ${f("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return e?Number.parseInt(e.split(`
227
+ `)[0],10):null}catch{return null}}async function Et(e=1500){try{let r=await new Promise((i,a)=>{let u=ge.get(`http://localhost:${c}/json/version`,(s)=>{let o="";s.on("data",(l)=>o+=l),s.on("end",()=>{try{i(JSON.parse(o))}catch{a(Error("bad JSON"))}})});u.on("error",a),u.setTimeout(1000,()=>{u.destroy(),a(Error("timeout"))})}),n=new globalThis.WebSocket(r.webSocketDebuggerUrl);await new Promise((i)=>{n.onopen=()=>{n.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{n.close(),i()},200)},n.onerror=()=>i(),setTimeout(i,1000)})}catch{}let t=Date.now()+e;while(Date.now()<t){if(!me())return!0;await new Promise((n)=>setTimeout(n,150))}return It()}function It(){try{let e=me();if(!e&&U(M))e=Number.parseInt(T(M,"utf8").trim(),10)||null;if(!e)return!1;if(de()==="win32")pe(`${f("taskkill")} /F /PID ${e}`,{stdio:"ignore"});else process.kill(e,"SIGKILL");return!0}catch{return!1}}async function Ke(){if(!await N(500)){try{d(M)}catch{}try{d(O)}catch{}try{d(v)}catch{}return!1}let t=await Et(1500);try{d(M)}catch{}try{d(O)}catch{}try{d(v)}catch{}if(t)process.stderr.write(`[greedysearch] Killed Chrome on port ${c}.
228
+ `);return t}var Ve=Ke;async function Ft(){let t=Ye()?Zt:Yt;if(t<=0)return!1;if(!U(O))return Lt(),!1;try{let r=Number.parseInt(T(O,"utf8").trim(),10);if(!r)return!1;if((Date.now()-r)/60000>=t)return Ke()}catch{}return!1}var m=G;async function he(){let t=(await m(["list"])).split(`
229
+ `)[0];if(!t)throw Error("No Chrome tabs found");return t.slice(0,8)}async function rn(e="about:blank"){let t=await he(),r=new URL(e).hostname;if(r==="copilot.microsoft.com"||r==="www.perplexity.ai"||r==="perplexity.ai"||r.endsWith(".perplexity.ai")){let u=await m(["evalraw",t,"Target.createTarget",JSON.stringify({url:"about:blank"})]),{targetId:s}=JSON.parse(u),o=s.slice(0,8);if(await m(["list"]).catch(()=>null),r==="copilot.microsoft.com")await E(o);else E(o).catch(()=>{});return await m(["list"]).catch(()=>null),s}let i=await m(["evalraw",t,"Target.createTarget",JSON.stringify({url:e})]),{targetId:a}=JSON.parse(i);return await m(["list"]).catch(()=>null),a}async function nn(e){try{let t=await he();await m(["evalraw",t,"Target.activateTarget",JSON.stringify({targetId:e})])}catch{}}async function zt(e){try{let t=await he();await m(["evalraw",t,"Target.closeTarget",JSON.stringify({targetId:e})])}catch{}}async function an(e=[]){if(await Promise.all(e.filter(Boolean).map((t)=>zt(t).catch(()=>{}))),e.length>0)await m(["list"]).catch(()=>null)}function on(e,t){try{if(!U(re))return null;let n=JSON.parse(T(re,"utf8")).find((i)=>i.url.includes(t[e]));return n?n.targetId:null}catch{return null}}function N(e=3000){return new Promise((t)=>{let r=ge.get(`http://localhost:${c}/json/version`,(n)=>{n.resume(),t(n.statusCode===200)});r.on("error",()=>t(!1)),r.setTimeout(e,()=>{r.destroy(),t(!1)})})}async function fe(){let e=`${A}.lock`,t=`${A}.tmp`,r=5000,n=1000,i=await new Promise((a)=>{let u=Date.now(),s=()=>{try{let o=JSON.stringify({pid:process.pid,ts:Date.now()});L(e,o,{encoding:"utf8",flag:"wx"}),a(!0)}catch(o){if(o?.code!=="EEXIST"){if(Date.now()-u<1000)setTimeout(s,50);else a(!1);return}try{let l=T(e,"utf8").trim(),h=l.startsWith("{")?JSON.parse(l):{ts:Number(l)},b=Number(h?.ts)||0;if(b>0&&Date.now()-b>5000)try{d(e)}catch{}if(Date.now()-u<1000)setTimeout(s,50);else a(!1)}catch{if(Date.now()-u<1000)setTimeout(s,50);else a(!1)}}};s()});try{let a=await new Promise((l,h)=>{let b=ge.get(`http://localhost:${c}/json/version`,(X)=>{let we="";X.on("data",(Le)=>we+=Le),X.on("end",()=>l(we))});b.on("error",h),b.setTimeout(3000,()=>{b.destroy(),h(Error("timeout"))})}),{webSocketDebuggerUrl:u}=JSON.parse(a),s=new URL(u),o=`${s.pathname}${s.search}`;if(i){L(t,`localhost:${c}
230
+ ${o}`,"utf8");try{d(A)}catch{}Qt(t,A)}}catch{}finally{if(i)try{d(e)}catch{}}}async function sn(){let e=U(M)||!!J(),t=await Ce({activePortFile:A,modeFile:v,excludePorts:e?[c]:[]});if(t){process.stderr.write(`[greedysearch] Reusing existing browser CDP endpoint ${t.httpUrl} (${t.source}).
231
+ `);return}Qe();let r=await Ft(),n=r?!1:await N();if(!n&&!r)await new Promise((s)=>setTimeout(s,500)),n=await N();let i=!1;if(n){let s=Ye(),o=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!o&&!s)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
232
+ `),await Ve(),await new Promise((l)=>setTimeout(l,1000)),i=!0;else if(o&&s)process.stderr.write(`[greedysearch] Headless Chrome detected — switching to visible mode...
233
+ `),await Ve(),await new Promise((l)=>setTimeout(l,1000)),i=!0}if(i?!1:await N()){await fe();try{let s=J();if(s)ce(s),Be(s)}catch{}return}let u=He();if(!u.acquired){if(await new Promise((o)=>setTimeout(o,3000)),await N(5000)){await fe();return}}try{if(await N(1000)){await fe();return}process.stderr.write(`GreedySearch Chrome not running on port ${c} — auto-launching...
234
+ `);let o=[qt(Vt,"..","..","bin","launch.mjs")];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")o.push("--headless");await new Promise((l,h)=>{Bt(be(),o,{stdio:["ignore",process.stderr,process.stderr]}).on("close",(X)=>X===0?l():h(Error("launch.mjs failed")))})}finally{u.release()}}export{Lt as touchActivity,fe as refreshPortFile,N as probeGreedyChrome,rn as openNewTab,Ve as killHeadlessChrome,Ke as killChrome,Ye as isChromeHeadless,on as getFullTabFromCache,he as getAnyTab,sn as ensureChrome,Kt as detectHeadlessFromChromeCommandLine,an as closeTabs,zt as closeTab,Ft as checkAndKillIdle,m as cdp,nn as activateTab};