@duckmind/dm-windows-x64 0.59.9 → 0.60.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{spawn as Jt,execFileSync as se,execSync as Zr}from"node:child_process";import{basename as Be}from"node:path";function pe(e=process.env,t=process.execPath){let r=e.GREEDY_SEARCH_NODE||e.NODE_BINARY||e.NODE;if(r?.trim())return r.trim();let i=Be(t||"").toLowerCase();if(i==="node"||i==="node.exe")return t;return"node"}import{existsSync as le,readFileSync as z,renameSync as Ht,unlinkSync as h,writeFileSync as V}from"node:fs";import ue from"node:http";import{platform as Je}from"node:os";import{join as qt}from"node:path";import{spawn as Ze}from"node:child_process";import{basename as Qe}from"node:path";import{dirname as Re,join as ze}from"node:path";import{fileURLToPath as Le}from"node:url";function Ve(e=process.env,t=process.execPath){let r=e.GREEDY_SEARCH_NODE||e.NODE_BINARY||e.NODE;if(r?.trim())return r.trim();let i=Qe(t||"").toLowerCase();if(i==="node"||i==="node.exe")return t;return"node"}var Ie=Re(Le(import.meta.url)),Ye=ze(Ie,"..","bin","cdp.mjs"),Ee=new Set(["list","snap","eval","shot","html","nav","net","click","clickxy","type","loadall","evalraw","browse","stop","--tab"]);function Ge(e){if(!Array.isArray(e)||e.length===0)throw Error("cdp: args must be a non-empty array");if(e[0]==="test")return e.map((t,r)=>ge(t,r));if(!Ee.has(e[0]))throw Error(`cdp: unknown subcommand '${e[0]}'`);return e.map((t,r)=>ge(t,r))}function ge(e,t){if(typeof e!=="string")throw Error(`cdp: argv[${t}] must be a string (got ${typeof e})`);if(e.includes("\x00"))throw Error(`cdp: argv[${t}] contains a null byte`);return e}function I(e,t=30000){return Fe(e,null,t)}function Fe(e,t=null,r=30000){let i=Ge(e);return new Promise((n,a)=>{let o=Ze(Ve(),[Ye,...i],{stdio:[t==null?"ignore":"pipe","pipe","pipe"]});if(t!=null)o.stdin.write(t),o.stdin.end();let s="",l="";o.stdout.on("data",(u)=>s+=u),o.stderr.on("data",(u)=>l+=u);let f=setTimeout(()=>{o.kill(),a(Error(`cdp timeout: ${e[0]}`))},r);o.on("close",(u)=>{if(clearTimeout(f),u===0)n(s.trim());else a(Error(l.trim()||`cdp exit ${u}`))})})}async function Y(e){await I(["evalraw",e,"Page.addScriptToEvaluateOnNewDocument",JSON.stringify({source:`
1
+ import{spawn as Gt,execFileSync as ue,execSync as cn}from"node:child_process";import{basename as Re}from"node:path";function de(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=Re(t||"").toLowerCase();if(n==="node"||n==="node.exe")return t;return"node"}import{existsSync as ce,readFileSync as V,renameSync as Ft,unlinkSync as h,writeFileSync as R}from"node:fs";import fe from"node:http";import{platform as Ue}from"node:os";import{spawn as Le}from"node:child_process";import{basename as Ve}from"node:path";import{dirname as Ie,join as Ee}from"node:path";import{fileURLToPath as Ye}from"node:url";function ze(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=Ve(t||"").toLowerCase();if(n==="node"||n==="node.exe")return t;return"node"}var Ge=Ie(Ye(import.meta.url)),Fe=Ee(Ge,"..","bin","cdp.mjs"),Ke=new Set(["list","snap","eval","shot","html","nav","net","click","clickxy","type","loadall","evalraw","browse","stop","--tab"]);function et(e){if(!Array.isArray(e)||e.length===0)throw Error("cdp: args must be a non-empty array");if(e[0]==="test")return e.map((t,r)=>me(t,r));if(!Ke.has(e[0]))throw Error(`cdp: unknown subcommand '${e[0]}'`);return e.map((t,r)=>me(t,r))}function me(e,t){if(typeof e!=="string")throw Error(`cdp: argv[${t}] must be a string (got ${typeof e})`);if(e.includes("\x00"))throw Error(`cdp: argv[${t}] contains a null byte`);return e}function I(e,t=30000){return tt(e,null,t)}function tt(e,t=null,r=30000){let n=et(e);return new Promise((i,a)=>{let o=Le(ze(),[Fe,...n],{stdio:[t==null?"ignore":"pipe","pipe","pipe"]});if(t!=null)o.stdin.write(t),o.stdin.end();let s="",l="";o.stdout.on("data",(u)=>s+=u),o.stderr.on("data",(u)=>l+=u);let f=setTimeout(()=>{o.kill(),a(Error(`cdp timeout: ${e[0]}`))},r);o.on("close",(u)=>{if(clearTimeout(f),u===0)i(s.trim());else a(Error(l.trim()||`cdp exit ${u}`))})})}async function E(e){await I(["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(_) {}
@@ -283,28 +283,27 @@ import{spawn as Jt,execFileSync as se,execSync as Zr}from"node:child_process";im
283
283
  };
284
284
  } catch(_) {}
285
285
  })();
286
- `})])}import{existsSync as de}from"node:fs";import{platform as Ke}from"node:os";import{join as w}from"node:path";function C(e){let t=Ke()==="win32",r=process.env.SystemRoot||"C:\\Windows",i={win32:{powershell:w(r,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:w(r,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:w(r,"System32","netstat.exe"),taskkill:w(r,"System32","taskkill.exe"),tasklist:w(r,"System32","tasklist.exe"),cmd:w(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"}},n=t?i.win32:i.unix,a=e.toLowerCase();if(n[a]&&de(n[a]))return n[a];if(t&&a==="netstat"){let o=w(r,"Sysnative","netstat.exe");if(de(o))return o}return e}import{execFileSync as et}from"node:child_process";import{platform as tt}from"node:os";function rt(e,t){return et(C(e),t,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000})}function nt(e){let t=String(e||"").match(/\b(\d+)\b/);return t?Number.parseInt(t[1],10):null}function it(e){return nt(e)}function at(e,t){for(let r of String(e||"").split(/\r?\n/)){if(!/\bLISTEN\b/i.test(r))continue;if(!r.trim().split(/\s+/).slice(0,6).some((a)=>a.endsWith(`:${t}`)))continue;let n=r.match(/\bpid=(\d+)\b/);if(n)return Number.parseInt(n[1],10)}return null}function ot(e,t){for(let r of String(e||"").split(/\r?\n/)){let i=r.trim().split(/\s+/);if(i.length<5||i[0].toUpperCase()!=="TCP")continue;if(!i.at(-2)?.toUpperCase().startsWith("LISTEN"))continue;if(!i[1].endsWith(`:${t}`))continue;let n=Number.parseInt(i.at(-1),10);if(Number.isInteger(n)&&n>0)return n}return null}function E(e,t,r){try{return e(t,r)}catch{return null}}function me(e,{platformName:t=tt(),run:r=rt}={}){if(t==="win32")return ot(E(r,"netstat",["-ano","-p","TCP"]),e);let i=E(r,"lsof",["-nP",`-iTCP:${e}`,"-sTCP:LISTEN","-t"]),n=it(i);if(n)return n;if(t!=="linux")return null;return at(E(r,"ss",["-ltnp"]),e)}import{existsSync as O,mkdirSync as st,readFileSync as ye,writeFileSync as lt}from"node:fs";import{homedir as ut}from"node:os";import{join as be}from"node:path";import{tmpdir as ct}from"node:os";function ft(e,t=9222){let r=Number.parseInt(String(e??""),10);return Number.isInteger(r)&&r>1024&&r<65535?r:t}var pt=ct().replaceAll("\\","/"),g=ft(process.env.GREEDY_SEARCH_PORT),p=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${pt}/greedysearch-chrome-profile`).replaceAll("\\","/"),j=`${p}/DevToolsActivePort`,we=process.env.GREEDY_SEARCH_PID_FILE||`${p}/browser.pid`,te=process.env.CDP_PAGES_CACHE||`${p}/cdp-pages.json`,k=process.env.GREEDY_SEARCH_MODE_FILE||`${p}/browser-mode`,dr=process.env.GREEDY_SEARCH_METADATA_FILE||`${p}/browser-metadata.json`,mr=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${p}/browser-launch.lock`,_e=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${p}/browser-last-activity`,hr=(process.env.CDP_SOCKET_DIR||`${p}/cdp-sockets`).replaceAll("\\","/"),yr=`${p}/visible-recovery.jsonl`,F=be(ut(),".dm"),d=be(F,"greedyconfig"),K=["perplexity","google","chatgpt","gemini"],ee="gemini";function gt(){try{if(O(d)){let e=ye(d,"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((n)=>G[n]),i=t.engines.filter((n)=>!G[n]);if(i.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${d}: ${i.join(", ")}
286
+ `})])}import{existsSync as he}from"node:fs";import{platform as rt}from"node:os";import{join as _}from"node:path";function C(e){let t=rt()==="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]&&he(i[a]))return i[a];if(t&&a==="netstat"){let o=_(r,"Sysnative","netstat.exe");if(he(o))return o}return e}import{execFileSync as nt}from"node:child_process";import{platform as it}from"node:os";function at(e,t){return nt(C(e),t,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000})}function ot(e){let t=String(e||"").match(/\b(\d+)\b/);return t?Number.parseInt(t[1],10):null}function st(e){return ot(e)}function lt(e,t){for(let r of String(e||"").split(/\r?\n/)){if(!/\bLISTEN\b/i.test(r))continue;if(!r.trim().split(/\s+/).slice(0,6).some((a)=>a.endsWith(`:${t}`)))continue;let i=r.match(/\bpid=(\d+)\b/);if(i)return Number.parseInt(i[1],10)}return null}function ut(e,t){for(let r of String(e||"").split(/\r?\n/)){let n=r.trim().split(/\s+/);if(n.length<5||n[0].toUpperCase()!=="TCP")continue;if(!n.at(-2)?.toUpperCase().startsWith("LISTEN"))continue;if(!n[1].endsWith(`:${t}`))continue;let i=Number.parseInt(n.at(-1),10);if(Number.isInteger(i)&&i>0)return i}return null}function Y(e,t,r){try{return e(t,r)}catch{return null}}function ye(e,{platformName:t=it(),run:r=at}={}){if(t==="win32")return ut(Y(r,"netstat",["-ano","-p","TCP"]),e);let n=Y(r,"lsof",["-nP",`-iTCP:${e}`,"-sTCP:LISTEN","-t"]),i=st(n);if(i)return i;if(t!=="linux")return null;return lt(Y(r,"ss",["-ltnp"]),e)}import{existsSync as be}from"node:fs";import{dirname as ct,join as k}from"node:path";import{fileURLToPath as ft}from"node:url";function we(e){return ft(new URL(".",e)).replace(/^\/([A-Z]:)/,"$1")}function pt(e,t=be){let r=new Set;for(let n of e.filter(Boolean)){if(r.has(n))continue;if(r.add(n),t(n))return n}return e.filter(Boolean).at(-1)}function _e({moduleDir:e,entrypoint:t=process.argv[1],env:r=process.env,exists:n=be}={}){let i=t?ct(t):null,a=r.GREEDY_SEARCH_EXTENSION_DIR?.trim()||null;return pt([e?k(e,"..","..","bin","launch.mjs"):null,e?k(e,"launch.mjs"):null,a?k(a,"bin","launch.mjs"):null,i?k(i,"launch.mjs"):null,i?k(i,"..","bin","launch.mjs"):null],n)}import{existsSync as O,mkdirSync as gt,readFileSync as xe,writeFileSync as dt}from"node:fs";import{homedir as mt}from"node:os";import{join as Pe}from"node:path";import{tmpdir as ht}from"node:os";function yt(e,t=9222){let r=Number.parseInt(String(e??""),10);return Number.isInteger(r)&&r>1024&&r<65535?r:t}var bt=ht().replaceAll("\\","/"),g=yt(process.env.GREEDY_SEARCH_PORT),p=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${bt}/greedysearch-chrome-profile`).replaceAll("\\","/"),D=`${p}/DevToolsActivePort`,Ae=process.env.GREEDY_SEARCH_PID_FILE||`${p}/browser.pid`,te=process.env.CDP_PAGES_CACHE||`${p}/cdp-pages.json`,j=process.env.GREEDY_SEARCH_MODE_FILE||`${p}/browser-mode`,Tr=process.env.GREEDY_SEARCH_METADATA_FILE||`${p}/browser-metadata.json`,Wr=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${p}/browser-launch.lock`,Se=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${p}/browser-last-activity`,Mr=(process.env.CDP_SOCKET_DIR||`${p}/cdp-sockets`).replaceAll("\\","/"),Or=`${p}/visible-recovery.jsonl`,F=Pe(mt(),".dm"),d=Pe(F,"greedyconfig"),K=["perplexity","google","chatgpt","gemini"],ee="gemini";function wt(){try{if(O(d)){let e=xe(d,"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)=>G[i]),n=t.engines.filter((i)=>!G[i]);if(n.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${d}: ${n.join(", ")}
287
287
  [greedysearch] Available engines: ${Object.keys(G).join(", ")}
288
288
  `);if(r.length>0)return r;process.stderr.write(`[greedysearch] Warning: no valid engines in ${d}, falling back to defaults: ${K.join(", ")}
289
- `)}}}catch{}return K}function dt(){try{if(!O(F))st(F,{recursive:!0});if(!O(d))lt(d,JSON.stringify({engines:K,synthesizer:ee},null,2)+`
290
- `,"utf8")}catch{}}dt();var he=["gemini","chatgpt"];function mt(){try{if(O(d)){let e=ye(d,"utf8"),t=JSON.parse(e);if(typeof t.synthesizer==="string"){let r=t.synthesizer.toLowerCase();if(he.includes(r))return r;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${t.synthesizer}" in ${d}
291
- [greedysearch] Available synthesizers: ${he.join(", ")}
289
+ `)}}}catch{}return K}function _t(){try{if(!O(F))gt(F,{recursive:!0});if(!O(d))dt(d,JSON.stringify({engines:K,synthesizer:ee},null,2)+`
290
+ `,"utf8")}catch{}}_t();var ve=["gemini","chatgpt"];function vt(){try{if(O(d)){let e=xe(d,"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 ${d}
291
+ [greedysearch] Available synthesizers: ${ve.join(", ")}
292
292
  [greedysearch] Falling back to default: ${ee}
293
- `)}}}catch{}return ee}var G={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"},br=gt();var wr=mt(),_r=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=p;import{execFileSync as ve,execSync as xe}from"node:child_process";import{existsSync as J,mkdirSync as ht,readFileSync as S,unlinkSync as P,writeFileSync as $}from"node:fs";import{platform as Se}from"node:os";import{existsSync as H,mkdirSync as yt,readFileSync as De,writeFileSync as bt}from"node:fs";import{homedir as wt}from"node:os";import{join as je}from"node:path";import{tmpdir as _t}from"node:os";import{existsSync as $e}from"node:fs";import{platform as Nt}from"node:os";import{join as _}from"node:path";function vt(e,t=9222){let r=Number.parseInt(String(e??""),10);return Number.isInteger(r)&&r>1024&&r<65535?r:t}var xt=_t().replaceAll("\\","/"),A=vt(process.env.GREEDY_SEARCH_PORT),c=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${xt}/greedysearch-chrome-profile`).replaceAll("\\","/"),Dr=`${c}/DevToolsActivePort`,Pt=process.env.GREEDY_SEARCH_PID_FILE||`${c}/browser.pid`,jr=process.env.CDP_PAGES_CACHE||`${c}/cdp-pages.json`,$t=process.env.GREEDY_SEARCH_MODE_FILE||`${c}/browser-mode`,At=process.env.GREEDY_SEARCH_METADATA_FILE||`${c}/browser-metadata.json`,Ct=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${c}/browser-launch.lock`,kt=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${c}/browser-last-activity`,Nr=(process.env.CDP_SOCKET_DIR||`${c}/cdp-sockets`).replaceAll("\\","/"),Tr=`${c}/visible-recovery.jsonl`,ne=je(wt(),".dm"),m=je(ne,"greedyconfig"),ie=["perplexity","google","chatgpt","gemini"],ae="gemini";function St(){try{if(H(m)){let e=De(m,"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((n)=>re[n]),i=t.engines.filter((n)=>!re[n]);if(i.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${m}: ${i.join(", ")}
293
+ `)}}}catch{}return ee}var G={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"},Jr=wt();var qr=vt(),Hr=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=p;import{execFileSync as Ce,execSync as Br}from"node:child_process";import{existsSync as J,mkdirSync as xt,readFileSync as $,unlinkSync as P,writeFileSync as A}from"node:fs";import{platform as Pt}from"node:os";import{existsSync as q,mkdirSync as At,readFileSync as Te,writeFileSync as St}from"node:fs";import{homedir as Ct}from"node:os";import{join as We}from"node:path";import{tmpdir as jt}from"node:os";import{existsSync as $e}from"node:fs";import{platform as Ht}from"node:os";import{join as v}from"node:path";import{execFileSync as Ut}from"node:child_process";import{platform as Xt}from"node:os";function $t(e,t=9222){let r=Number.parseInt(String(e??""),10);return Number.isInteger(r)&&r>1024&&r<65535?r:t}var kt=jt().replaceAll("\\","/"),S=$t(process.env.GREEDY_SEARCH_PORT),c=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${kt}/greedysearch-chrome-profile`).replaceAll("\\","/"),Ir=`${c}/DevToolsActivePort`,Dt=process.env.GREEDY_SEARCH_PID_FILE||`${c}/browser.pid`,Er=process.env.CDP_PAGES_CACHE||`${c}/cdp-pages.json`,Nt=process.env.GREEDY_SEARCH_MODE_FILE||`${c}/browser-mode`,Tt=process.env.GREEDY_SEARCH_METADATA_FILE||`${c}/browser-metadata.json`,Wt=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${c}/browser-launch.lock`,Mt=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${c}/browser-last-activity`,Yr=(process.env.CDP_SOCKET_DIR||`${c}/cdp-sockets`).replaceAll("\\","/"),Gr=`${c}/visible-recovery.jsonl`,ie=We(Ct(),".dm"),m=We(ie,"greedyconfig"),ae=["perplexity","google","chatgpt","gemini"],oe="gemini";function Ot(){try{if(q(m)){let e=Te(m,"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)=>re[i]),n=t.engines.filter((i)=>!re[i]);if(n.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${m}: ${n.join(", ")}
294
294
  [greedysearch] Available engines: ${Object.keys(re).join(", ")}
295
- `);if(r.length>0)return r;process.stderr.write(`[greedysearch] Warning: no valid engines in ${m}, falling back to defaults: ${ie.join(", ")}
296
- `)}}}catch{}return ie}function Dt(){try{if(!H(ne))yt(ne,{recursive:!0});if(!H(m))bt(m,JSON.stringify({engines:ie,synthesizer:ae},null,2)+`
297
- `,"utf8")}catch{}}Dt();var Pe=["gemini","chatgpt"];function jt(){try{if(H(m)){let e=De(m,"utf8"),t=JSON.parse(e);if(typeof t.synthesizer==="string"){let r=t.synthesizer.toLowerCase();if(Pe.includes(r))return r;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${t.synthesizer}" in ${m}
298
- [greedysearch] Available synthesizers: ${Pe.join(", ")}
299
- [greedysearch] Falling back to default: ${ae}
300
- `)}}}catch{}return ae}var re={perplexity:"perplexity.mjs",p:"perplexity.mjs",bing:"bing-copilot.mjs",b:"bing-copilot.mjs",google:"google-ai.mjs",g:"google-ai.mjs",gemini:"gemini.mjs",gem:"gemini.mjs",chatgpt:"chatgpt.mjs",gpt:"chatgpt.mjs","semantic-scholar":"semantic-scholar.mjs",semanticscholar:"semantic-scholar.mjs",s2:"semantic-scholar.mjs",logically:"logically.mjs",log:"logically.mjs"},Mr=St(),Wr=jt(),Or=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=c;function x(e){let t=Nt()==="win32",r=process.env.SystemRoot||"C:\\Windows",i={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"}},n=t?i.win32:i.unix,a=e.toLowerCase();if(n[a]&&$e(n[a]))return n[a];if(t&&a==="netstat"){let o=_(r,"Sysnative","netstat.exe");if($e(o))return o}return e}var q=At,v=Ct,Tt=15000,X=Pt,U=$t,N=kt;function T(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Mt(e){if(!T(e))return null;try{if(Se()==="win32")return ve(x("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return ve(x("ps"),["-p",String(e),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Wt(e,t,r=A){if(!e)return!1;let i=(o)=>String(o||"").replaceAll("\\","/").toLowerCase(),n=i(e),a=i(t);return n.includes(a)&&n.includes(`--remote-debugging-port=${r}`)&&!n.includes("--type=")}function Ae(e,t,r=A){return Wt(Mt(e),t,r)}function Ot(e=A){try{if(Se()==="win32"){let r=xe(`${x("netstat")} -ano -p TCP 2>nul`,{encoding:"utf8"}),i=new RegExp(String.raw`TCP\s+\S+:${e}\s+\S+:0\s+LISTENING\s+(\d+)`,"i"),n=r.match(i);return n?Number.parseInt(n[1],10):null}let t=xe(`${x("lsof")} -i :${e} -t 2>/dev/null || ${x("ss")} -tlnp 2>/dev/null | ${x("grep")} :${e} | ${x("grep")} -oP 'pid=\\K\\d+'`,{encoding:"utf8"}).trim();return t?Number.parseInt(t.split(`
301
- `)[0],10):null}catch{return null}}function M(){try{if(J(q)){let e=S(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=J(X)?Number.parseInt(S(X,"utf8").trim(),10)||void 0:void 0,t=J(U)?S(U,"utf8").trim()==="visible"?"visible":"headless":"headless",r=J(N)?Number.parseInt(S(N,"utf8").trim(),10)||0:0;return{browserPid:e,debugPort:A,tempDir:c,clientPids:e?[e]:[],sessionMode:t,lastActivity:r,launchedAt:0}}catch{return null}}function B(e){try{$(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,String(e.browserPid),"utf8")}catch{}try{$(U,e.sessionMode,"utf8")}catch{}try{$(N,String(e.lastActivity),"utf8")}catch{}}function Ce(){try{P(q)}catch{}try{P(X)}catch{}try{P(U)}catch{}try{P(N)}catch{}}function oe(e){if(!e)return e;let t={...e,clientPids:[...new Set([...e.clientPids,process.pid].filter((r)=>T(r)||r===process.pid))]};return B(t),t}function Z(e){let t=Date.now();try{if(e)B({...e,lastActivity:t});else $(N,String(t),"utf8")}catch{}}var Xr=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var ke=!1;function Ne(){if(process.env.GREEDY_SEARCH_RESEARCH_CHILD)return;if(ke)return;ke=!0;let e=M();if(!e)return;if(e.browserPid){if(!T(e.browserPid)){Ce();return}if(!Ae(e.browserPid,e.tempDir,e.debugPort))Ce();else B({...e,clientPids:e.clientPids.filter((r)=>T(r))})}let t=Ot();if(t&&t!==e.browserPid)if(Ae(t,c,A))B({browserPid:t,debugPort:A,tempDir:c,clientPids:[t],sessionMode:e.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else process.stderr.write(`[greedysearch] Refusing to kill unverified listener ${t} on port ${A}.
302
- `)}function Te(){ht(c,{recursive:!0});try{let e=JSON.stringify({pid:process.pid,ts:Date.now()});return $(v,e,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let t=S(v,"utf8");if(JSON.parse(t).pid===process.pid)P(v)}catch{}}}}catch(e){if(e?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let e=S(v,"utf8"),t=JSON.parse(e),r=Date.now()-(t.ts||0);if(!T(t.pid)||r>Tt){try{P(v)}catch{}try{let i=JSON.stringify({pid:process.pid,ts:Date.now()});return $(v,i,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{P(v)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var Xt=import.meta.dirname||new URL(".",import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"),Me=we,W=_e,Ut=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,Bt=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;function Zt(e,t=g){let r=String(e||"").toLowerCase();if(!r.includes(`--remote-debugging-port=${t}`)||r.includes("--type="))return null;return r.includes("--headless")}function He(){try{let e=L(),t=e?qe(e):null,r=Zt(t);if(r!==null){try{V(k,r?"headless":"visible","utf8")}catch{}return r}}catch{}try{if(!le(k))return!0;return z(k,"utf8").trim()==="headless"}catch{return!0}}function Qt(){try{V(W,String(Date.now()),"utf8")}catch{}try{let e=M();if(e)Z(e)}catch{}}function qe(e){try{if(Je()==="win32")return se(C("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return se(C("ps"),["-p",String(e),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Vt(e){let t=String(e||"").replaceAll("\\","/"),r=p.replaceAll("\\","/");return t.includes(`--remote-debugging-port=${g}`)&&t.includes(`--user-data-dir=${r}`)&&!t.includes("--type=")}function L(){return me(g)}function R(){let e=L();return e&&Vt(qe(e))?e:null}async function Rt(e=1500){let t=R();if(!t)return process.stderr.write(`[greedysearch] Refusing to close an unverified listener.
303
- `),!1;try{let i=await new Promise((a,o)=>{let s=ue.get(`http://localhost:${g}/json/version`,(l)=>{let f="";l.on("data",(u)=>f+=u),l.on("end",()=>{try{a(JSON.parse(f))}catch{o(Error("bad JSON"))}})});s.on("error",o),s.setTimeout(1000,()=>{s.destroy(),o(Error("timeout"))})}),n=new globalThis.WebSocket(i.webSocketDebuggerUrl);await new Promise((a)=>{n.onopen=()=>{if(R()!==t){n.close(),a();return}n.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{n.close(),a()},200)},n.onerror=()=>a(),setTimeout(a,1000)})}catch{}let r=Date.now()+e;while(Date.now()<r){let i=L();if(!i)return!0;if(i!==t)return!1;await new Promise((n)=>setTimeout(n,150))}return zt(t)}function zt(e=null){try{let t=R();if(!t||e&&t!==e)return!1;if(Je()==="win32")se(C("taskkill"),["/F","/PID",String(t)],{stdio:"ignore",windowsHide:!0});else process.kill(t,"SIGKILL");return!0}catch{return!1}}async function Xe(){if(!R()){if(L())process.stderr.write(`[greedysearch] Refusing to kill an unverified listener.
304
- `);return!1}if(!await y(500)){try{h(Me)}catch{}try{h(W)}catch{}try{h(k)}catch{}return!1}let t=await Rt(1500);try{h(Me)}catch{}try{h(W)}catch{}try{h(k)}catch{}if(t)process.stderr.write(`[greedysearch] Killed Chrome on port ${g}.
305
- `);return t}var We=Xe;async function Lt(){let t=He()?Ut:Bt;if(t<=0)return!1;if(!le(W))return Qt(),!1;try{let r=Number.parseInt(z(W,"utf8").trim(),10);if(!r)return!1;if((Date.now()-r)/60000>=t)return Xe()}catch{}return!1}var b=I;async function ce(){let t=(await b(["list"])).split(`
306
- `)[0];if(!t)throw Error("No Chrome tabs found");return t.slice(0,8)}async function Kr(e="about:blank"){let t=await ce(),r=new URL(e).hostname;if(r==="copilot.microsoft.com"||r==="www.perplexity.ai"||r==="perplexity.ai"||r.endsWith(".perplexity.ai")){let o=await b(["evalraw",t,"Target.createTarget",JSON.stringify({url:"about:blank"})]),{targetId:s}=JSON.parse(o),l=s.slice(0,8);if(await b(["list"]).catch(()=>null),r==="copilot.microsoft.com")await Y(l);else Y(l).catch(()=>{});return await b(["list"]).catch(()=>null),s}let n=await b(["evalraw",t,"Target.createTarget",JSON.stringify({url:e})]),{targetId:a}=JSON.parse(n);return await b(["list"]).catch(()=>null),a}async function en(e){try{let t=await ce();await b(["evalraw",t,"Target.activateTarget",JSON.stringify({targetId:e})])}catch{}}async function It(e){try{let t=await ce();await b(["evalraw",t,"Target.closeTarget",JSON.stringify({targetId:e})])}catch{}}async function tn(e=[]){if(await Promise.all(e.filter(Boolean).map((t)=>It(t).catch(()=>{}))),e.length>0)await b(["list"]).catch(()=>null)}function rn(e,t){try{if(!le(te))return null;let i=JSON.parse(z(te,"utf8")).find((n)=>n.url.includes(t[e]));return i?i.targetId:null}catch{return null}}function y(e=3000){return new Promise((t)=>{let r=ue.get(`http://localhost:${g}/json/version`,(i)=>{i.resume(),t(i.statusCode===200)});r.on("error",()=>t(!1)),r.setTimeout(e,()=>{r.destroy(),t(!1)})})}async function Oe(e=3000,t=200){let r=Date.now()+e;while(Date.now()<r){if(!await y(300))return!0;await new Promise((i)=>setTimeout(i,t))}return!await y(300)}async function Q(){let e=`${j}.lock`,t=`${j}.tmp`,r=5000,i=1000,n=await new Promise((a)=>{let o=Date.now(),s=()=>{try{let l=JSON.stringify({pid:process.pid,ts:Date.now()});V(e,l,{encoding:"utf8",flag:"wx"}),a(!0)}catch(l){if(l?.code!=="EEXIST"){if(Date.now()-o<1000)setTimeout(s,50);else a(!1);return}try{let f=z(e,"utf8").trim(),u=f.startsWith("{")?JSON.parse(f):{ts:Number(f)},D=Number(u?.ts)||0;if(D>0&&Date.now()-D>5000)try{h(e)}catch{}if(Date.now()-o<1000)setTimeout(s,50);else a(!1)}catch{if(Date.now()-o<1000)setTimeout(s,50);else a(!1)}}};s()});try{let a=await new Promise((l,f)=>{let u=ue.get(`http://localhost:${g}/json/version`,(D)=>{let fe="";D.on("data",(Ue)=>fe+=Ue),D.on("end",()=>l(fe))});u.on("error",f),u.setTimeout(3000,()=>{u.destroy(),f(Error("timeout"))})}),{webSocketDebuggerUrl:o}=JSON.parse(a),s=new URL(o).pathname;if(n){V(t,`${g}
307
- ${s}`,"utf8");try{h(j)}catch{}Ht(t,j)}}catch{}finally{if(n)try{h(e)}catch{}}}async function nn(){if(process.env.GREEDY_SEARCH_RESEARCH_CHILD&&await y()){await Q();try{let a=M();if(a)Z(a),oe(a)}catch{}return}Ne();let e=await Lt(),t=e?!1:await y();if(!t&&!e)await new Promise((a)=>setTimeout(a,500)),t=await y();let r=!1;if(t){let a=He(),o=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!o&&!a)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
308
- `),await We(),await Oe(),r=!0;else if(o&&a)process.stderr.write(`[greedysearch] Headless Chrome detected — switching to visible mode...
309
- `),await We(),await Oe(),r=!0}if(r?!1:await y()){await Q();try{let a=M();if(a)Z(a),oe(a)}catch{}return}let n=Te();if(!n.acquired){let a=Date.now()+12000,o=!1;while(Date.now()<a){if(o=await y(500),o)break;await new Promise((s)=>setTimeout(s,250))}if(o){await Q();return}}try{if(await y(1000)){await Q();return}process.stderr.write(`GreedySearch Chrome not running on port ${g} — auto-launching...
310
- `);let o=[qt(Xt,"..","..","bin","launch.mjs")];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")o.push("--headless");await new Promise((s,l)=>{Jt(pe(),o,{stdio:["ignore",process.stderr,process.stderr]}).on("close",(u)=>u===0?s():l(Error("launch.mjs failed")))})}finally{n.release()}}export{Qt as touchActivity,Q as refreshPortFile,y as probeGreedyChrome,Kr as openNewTab,We as killHeadlessChrome,Xe as killChrome,He as isChromeHeadless,rn as getFullTabFromCache,ce as getAnyTab,nn as ensureChrome,Zt as detectHeadlessFromChromeCommandLine,tn as closeTabs,It as closeTab,Lt as checkAndKillIdle,b as cdp,en as activateTab};
295
+ `);if(r.length>0)return r;process.stderr.write(`[greedysearch] Warning: no valid engines in ${m}, falling back to defaults: ${ae.join(", ")}
296
+ `)}}}catch{}return ae}function Jt(){try{if(!q(ie))At(ie,{recursive:!0});if(!q(m))St(m,JSON.stringify({engines:ae,synthesizer:oe},null,2)+`
297
+ `,"utf8")}catch{}}Jt();var je=["gemini","chatgpt"];function qt(){try{if(q(m)){let e=Te(m,"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 ${m}
298
+ [greedysearch] Available synthesizers: ${je.join(", ")}
299
+ [greedysearch] Falling back to default: ${oe}
300
+ `)}}}catch{}return oe}var re={perplexity:"perplexity.mjs",p:"perplexity.mjs",bing:"bing-copilot.mjs",b:"bing-copilot.mjs",google:"google-ai.mjs",g:"google-ai.mjs",gemini:"gemini.mjs",gem:"gemini.mjs",chatgpt:"chatgpt.mjs",gpt:"chatgpt.mjs","semantic-scholar":"semantic-scholar.mjs",semanticscholar:"semantic-scholar.mjs",s2:"semantic-scholar.mjs",logically:"logically.mjs",log:"logically.mjs"},Fr=Ot(),Kr=qt(),en=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=c;function se(e){let t=Ht()==="win32",r=process.env.SystemRoot||"C:\\Windows",n={win32:{powershell:v(r,"System32","WindowsPowerShell","v1.0","powershell.exe"),powershell_ise:v(r,"System32","WindowsPowerShell","v1.0","powershell_ise.exe"),netstat:v(r,"System32","netstat.exe"),taskkill:v(r,"System32","taskkill.exe"),tasklist:v(r,"System32","tasklist.exe"),cmd:v(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]&&$e(i[a]))return i[a];if(t&&a==="netstat"){let o=v(r,"Sysnative","netstat.exe");if($e(o))return o}return e}function Bt(e,t){return Ut(se(e),t,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000})}function Qt(e){let t=String(e||"").match(/\b(\d+)\b/);return t?Number.parseInt(t[1],10):null}function Zt(e){return Qt(e)}function Rt(e,t){for(let r of String(e||"").split(/\r?\n/)){if(!/\bLISTEN\b/i.test(r))continue;if(!r.trim().split(/\s+/).slice(0,6).some((i)=>i.endsWith(`:${t}`)))continue;let n=r.match(/\bpid=(\d+)\b/);if(n)return Number.parseInt(n[1],10)}return null}function Lt(e,t){for(let r of String(e||"").split(/\r?\n/)){let n=r.trim().split(/\s+/);if(n.length<5||n[0].toUpperCase()!=="TCP")continue;if(!n.at(-2)?.toUpperCase().startsWith("LISTEN"))continue;if(!n[1].endsWith(`:${t}`))continue;let i=Number.parseInt(n.at(-1),10);if(Number.isInteger(i)&&i>0)return i}return null}function ne(e,t,r){try{return e(t,r)}catch{return null}}function Vt(e,{platformName:t=Xt(),run:r=Bt}={}){if(t==="win32")return Lt(ne(r,"netstat",["-ano","-p","TCP"]),e);let n=ne(r,"lsof",["-nP",`-iTCP:${e}`,"-sTCP:LISTEN","-t"]),i=Zt(n);if(i)return i;if(t!=="linux")return null;return Rt(ne(r,"ss",["-ltnp"]),e)}var H=Tt,x=Wt,zt=15000,U=Dt,X=Nt,N=Mt;function T(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function It(e){if(!T(e))return null;try{if(Pt()==="win32")return Ce(se("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return Ce(se("ps"),["-p",String(e),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function Et(e,t,r=S){if(!e)return!1;let n=(o)=>String(o||"").replaceAll("\\","/").toLowerCase(),i=n(e),a=n(t);return i.includes(a)&&i.includes(`--remote-debugging-port=${r}`)&&!i.includes("--type=")}function ke(e,t,r=S){return Et(It(e),t,r)}function Yt(e=S){return Vt(e)}function W(){try{if(J(H)){let e=$(H,"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=J(U)?Number.parseInt($(U,"utf8").trim(),10)||void 0:void 0,t=J(X)?$(X,"utf8").trim()==="visible"?"visible":"headless":"headless",r=J(N)?Number.parseInt($(N,"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 B(e){try{A(H,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)A(U,String(e.browserPid),"utf8")}catch{}try{A(X,e.sessionMode,"utf8")}catch{}try{A(N,String(e.lastActivity),"utf8")}catch{}}function De(){try{P(H)}catch{}try{P(U)}catch{}try{P(X)}catch{}try{P(N)}catch{}}function le(e){if(!e)return e;let t={...e,clientPids:[...new Set([...e.clientPids,process.pid].filter((r)=>T(r)||r===process.pid))]};return B(t),t}function Q(e){let t=Date.now();try{if(e)B({...e,lastActivity:t});else A(N,String(t),"utf8")}catch{}}var sn=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5;var Ne=!1;function Me(){if(process.env.GREEDY_SEARCH_RESEARCH_CHILD)return;if(Ne)return;Ne=!0;let e=W();if(!e)return;if(e.browserPid){if(!T(e.browserPid)){De();return}if(!ke(e.browserPid,e.tempDir,e.debugPort))De();else B({...e,clientPids:e.clientPids.filter((r)=>T(r))})}let t=Yt();if(t&&t!==e.browserPid)if(ke(t,c,S))B({browserPid:t,debugPort:S,tempDir:c,clientPids:[t],sessionMode:e.sessionMode,lastActivity:Date.now(),launchedAt:Date.now()});else process.stderr.write(`[greedysearch] Refusing to kill unverified listener ${t} on port ${S}.
301
+ `)}function Oe(){xt(c,{recursive:!0});try{let e=JSON.stringify({pid:process.pid,ts:Date.now()});return A(x,e,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{let t=$(x,"utf8");if(JSON.parse(t).pid===process.pid)P(x)}catch{}}}}catch(e){if(e?.code!=="EEXIST")return{acquired:!1,release:()=>{}}}try{let e=$(x,"utf8"),t=JSON.parse(e),r=Date.now()-(t.ts||0);if(!T(t.pid)||r>zt){try{P(x)}catch{}try{let n=JSON.stringify({pid:process.pid,ts:Date.now()});return A(x,n,{encoding:"utf8",flag:"wx"}),{acquired:!0,release:()=>{try{P(x)}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}}catch{}return{acquired:!1,release:()=>{}}}var Kt=we(import.meta.url),Je=Ae,M=Se,er=Number.parseInt(process.env.GREEDY_SEARCH_IDLE_TIMEOUT_MINUTES||"5",10)||5,tr=Number.parseInt(process.env.GREEDY_SEARCH_VISIBLE_IDLE_TIMEOUT_MINUTES||"60",10)||60;function rr(e,t=g){let r=String(e||"").toLowerCase();if(!r.includes(`--remote-debugging-port=${t}`)||r.includes("--type="))return null;return r.includes("--headless")}function Xe(){try{let e=z(),t=e?Be(e):null,r=rr(t);if(r!==null){try{R(j,r?"headless":"visible","utf8")}catch{}return r}}catch{}try{if(!ce(j))return!0;return V(j,"utf8").trim()==="headless"}catch{return!0}}function nr(){try{R(M,String(Date.now()),"utf8")}catch{}try{let e=W();if(e)Q(e)}catch{}}function Be(e){try{if(Ue()==="win32")return ue(C("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:5000}).trim()||null;return ue(C("ps"),["-p",String(e),"-o","command="],{encoding:"utf8",timeout:5000}).trim()||null}catch{return null}}function ir(e){let t=String(e||"").replaceAll("\\","/"),r=p.replaceAll("\\","/");return t.includes(`--remote-debugging-port=${g}`)&&t.includes(`--user-data-dir=${r}`)&&!t.includes("--type=")}function z(){return ye(g)}function L(){let e=z();return e&&ir(Be(e))?e:null}async function ar(e=1500){let t=L();if(!t)return process.stderr.write(`[greedysearch] Refusing to close an unverified listener.
302
+ `),!1;try{let n=await new Promise((a,o)=>{let s=fe.get(`http://localhost:${g}/json/version`,(l)=>{let f="";l.on("data",(u)=>f+=u),l.on("end",()=>{try{a(JSON.parse(f))}catch{o(Error("bad JSON"))}})});s.on("error",o),s.setTimeout(1000,()=>{s.destroy(),o(Error("timeout"))})}),i=new globalThis.WebSocket(n.webSocketDebuggerUrl);await new Promise((a)=>{i.onopen=()=>{if(L()!==t){i.close(),a();return}i.send(JSON.stringify({id:1,method:"Browser.close"})),setTimeout(()=>{i.close(),a()},200)},i.onerror=()=>a(),setTimeout(a,1000)})}catch{}let r=Date.now()+e;while(Date.now()<r){let n=z();if(!n)return!0;if(n!==t)return!1;await new Promise((i)=>setTimeout(i,150))}return or(t)}function or(e=null){try{let t=L();if(!t||e&&t!==e)return!1;if(Ue()==="win32")ue(C("taskkill"),["/F","/PID",String(t)],{stdio:"ignore",windowsHide:!0});else process.kill(t,"SIGKILL");return!0}catch{return!1}}async function Qe(){if(!L()){if(z())process.stderr.write(`[greedysearch] Refusing to kill an unverified listener.
303
+ `);return!1}if(!await y(500)){try{h(Je)}catch{}try{h(M)}catch{}try{h(j)}catch{}return!1}let t=await ar(1500);try{h(Je)}catch{}try{h(M)}catch{}try{h(j)}catch{}if(t)process.stderr.write(`[greedysearch] Killed Chrome on port ${g}.
304
+ `);return t}var qe=Qe;async function sr(){let t=Xe()?er:tr;if(t<=0)return!1;if(!ce(M))return nr(),!1;try{let r=Number.parseInt(V(M,"utf8").trim(),10);if(!r)return!1;if((Date.now()-r)/60000>=t)return Qe()}catch{}return!1}var b=I;async function pe(){let t=(await b(["list"])).split(`
305
+ `)[0];if(!t)throw Error("No Chrome tabs found");return t.slice(0,8)}async function vn(e="about:blank"){let t=await pe(),r=new URL(e).hostname;if(r==="copilot.microsoft.com"||r==="www.perplexity.ai"||r==="perplexity.ai"||r.endsWith(".perplexity.ai")){let o=await b(["evalraw",t,"Target.createTarget",JSON.stringify({url:"about:blank"})]),{targetId:s}=JSON.parse(o),l=s.slice(0,8);if(await b(["list"]).catch(()=>null),r==="copilot.microsoft.com")await E(l);else E(l).catch(()=>{});return await b(["list"]).catch(()=>null),s}let i=await b(["evalraw",t,"Target.createTarget",JSON.stringify({url:e})]),{targetId:a}=JSON.parse(i);return await b(["list"]).catch(()=>null),a}async function xn(e){try{let t=await pe();await b(["evalraw",t,"Target.activateTarget",JSON.stringify({targetId:e})])}catch{}}async function lr(e){try{let t=await pe();await b(["evalraw",t,"Target.closeTarget",JSON.stringify({targetId:e})])}catch{}}async function Pn(e=[]){if(await Promise.all(e.filter(Boolean).map((t)=>lr(t).catch(()=>{}))),e.length>0)await b(["list"]).catch(()=>null)}function An(e,t){try{if(!ce(te))return null;let n=JSON.parse(V(te,"utf8")).find((i)=>i.url.includes(t[e]));return n?n.targetId:null}catch{return null}}function y(e=3000){return new Promise((t)=>{let r=fe.get(`http://localhost:${g}/json/version`,(n)=>{n.resume(),t(n.statusCode===200)});r.on("error",()=>t(!1)),r.setTimeout(e,()=>{r.destroy(),t(!1)})})}async function He(e=3000,t=200){let r=Date.now()+e;while(Date.now()<r){if(!await y(300))return!0;await new Promise((n)=>setTimeout(n,t))}return!await y(300)}async function Z(){let e=`${D}.lock`,t=`${D}.tmp`,r=5000,n=1000,i=await new Promise((a)=>{let o=Date.now(),s=()=>{try{let l=JSON.stringify({pid:process.pid,ts:Date.now()});R(e,l,{encoding:"utf8",flag:"wx"}),a(!0)}catch(l){if(l?.code!=="EEXIST"){if(Date.now()-o<1000)setTimeout(s,50);else a(!1);return}try{let f=V(e,"utf8").trim(),u=f.startsWith("{")?JSON.parse(f):{ts:Number(f)},w=Number(u?.ts)||0;if(w>0&&Date.now()-w>5000)try{h(e)}catch{}if(Date.now()-o<1000)setTimeout(s,50);else a(!1)}catch{if(Date.now()-o<1000)setTimeout(s,50);else a(!1)}}};s()});try{let a=await new Promise((l,f)=>{let u=fe.get(`http://localhost:${g}/json/version`,(w)=>{let ge="";w.on("data",(Ze)=>ge+=Ze),w.on("end",()=>l(ge))});u.on("error",f),u.setTimeout(3000,()=>{u.destroy(),f(Error("timeout"))})}),{webSocketDebuggerUrl:o}=JSON.parse(a),s=new URL(o).pathname;if(i){R(t,`${g}
306
+ ${s}`,"utf8");try{h(D)}catch{}Ft(t,D)}}catch{}finally{if(i)try{h(e)}catch{}}}async function Sn(){if(process.env.GREEDY_SEARCH_RESEARCH_CHILD&&await y()){await Z();try{let a=W();if(a)Q(a),le(a)}catch{}return}Me();let e=await sr(),t=e?!1:await y();if(!t&&!e)await new Promise((a)=>setTimeout(a,500)),t=await y();let r=!1;if(t){let a=Xe(),o=process.env.GREEDY_SEARCH_VISIBLE==="1";if(!o&&!a)process.stderr.write(`[greedysearch] Visible Chrome detected — switching to headless mode...
307
+ `),await qe(),await He(),r=!0;else if(o&&a)process.stderr.write(`[greedysearch] Headless Chrome detected — switching to visible mode...
308
+ `),await qe(),await He(),r=!0}if(r?!1:await y()){await Z();try{let a=W();if(a)Q(a),le(a)}catch{}return}let i=Oe();if(!i.acquired){let a=Date.now()+12000,o=!1;while(Date.now()<a){if(o=await y(500),o)break;await new Promise((s)=>setTimeout(s,250))}if(o){await Z();return}}try{if(await y(1000)){await Z();return}process.stderr.write(`GreedySearch Chrome not running on port ${g} — auto-launching...
309
+ `);let s=[_e({moduleDir:Kt,entrypoint:process.argv[1],env:process.env})];if(process.env.GREEDY_SEARCH_VISIBLE!=="1")s.push("--headless");await new Promise((l,f)=>{Gt(de(),s,{stdio:["ignore",process.stderr,process.stderr]}).on("close",(w)=>w===0?l():f(Error("launch.mjs failed")))})}finally{i.release()}}export{nr as touchActivity,Z as refreshPortFile,y as probeGreedyChrome,vn as openNewTab,qe as killHeadlessChrome,Qe as killChrome,Xe as isChromeHeadless,An as getFullTabFromCache,pe as getAnyTab,Sn as ensureChrome,rr as detectHeadlessFromChromeCommandLine,Pn as closeTabs,lr as closeTab,sr as checkAndKillIdle,b as cdp,xn as activateTab};
@@ -1,9 +1,9 @@
1
- import{spawn as J}from"node:child_process";import{basename as w}from"node:path";function L(s=process.env,e=process.execPath){let n=s.GREEDY_SEARCH_NODE||s.NODE_BINARY||s.NODE;if(n?.trim())return n.trim();let i=w(e||"").toLowerCase();if(i==="node"||i==="node.exe")return e;return"node"}import{existsSync as C,mkdirSync as v,readFileSync as N,writeFileSync as P}from"node:fs";import{homedir as j}from"node:os";import{join as Y}from"node:path";import{tmpdir as U}from"node:os";function k(s,e=9222){let n=Number.parseInt(String(s??""),10);return Number.isInteger(n)&&n>1024&&n<65535?n:e}var x=U().replaceAll("\\","/"),ns=k(process.env.GREEDY_SEARCH_PORT),r=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${x}/greedysearch-chrome-profile`).replaceAll("\\","/"),es=`${r}/DevToolsActivePort`,is=process.env.GREEDY_SEARCH_PID_FILE||`${r}/browser.pid`,rs=process.env.CDP_PAGES_CACHE||`${r}/cdp-pages.json`,Es=process.env.GREEDY_SEARCH_MODE_FILE||`${r}/browser-mode`,as=process.env.GREEDY_SEARCH_METADATA_FILE||`${r}/browser-metadata.json`,os=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${r}/browser-launch.lock`,gs=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${r}/browser-last-activity`,ls=(process.env.CDP_SOCKET_DIR||`${r}/cdp-sockets`).replaceAll("\\","/"),ts=`${r}/visible-recovery.jsonl`,D=Y(j(),".dm"),o=Y(D,"greedyconfig"),h=["perplexity","google","chatgpt","gemini"],p="gemini";function b(){try{if(C(o)){let s=N(o,"utf8"),e=JSON.parse(s);if(Array.isArray(e.engines)&&e.engines.length>0&&e.engines.every((n)=>typeof n==="string")){let n=e.engines.filter((E)=>y[E]),i=e.engines.filter((E)=>!y[E]);if(i.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${o}: ${i.join(", ")}
1
+ import{spawn as J}from"node:child_process";import{basename as v}from"node:path";function u(n=process.env,e=process.execPath){let s=n.GREEDY_SEARCH_NODE||n.NODE_BINARY||n.NODE;if(s?.trim())return s.trim();let i=v(e||"").toLowerCase();if(i==="node"||i==="node.exe")return e;return"node"}import{existsSync as S,mkdirSync as j,readFileSync as N,writeFileSync as w}from"node:fs";import{homedir as P}from"node:os";import{join as T}from"node:path";import{tmpdir as b}from"node:os";function x(n,e=9222){let s=Number.parseInt(String(n??""),10);return Number.isInteger(s)&&s>1024&&s<65535?s:e}var U=b().replaceAll("\\","/"),sn=x(process.env.GREEDY_SEARCH_PORT),r=(process.env.GREEDY_SEARCH_PROFILE_DIR||process.env.CDP_PROFILE_DIR||`${U}/greedysearch-chrome-profile`).replaceAll("\\","/"),en=`${r}/DevToolsActivePort`,rn=process.env.GREEDY_SEARCH_PID_FILE||`${r}/browser.pid`,an=process.env.CDP_PAGES_CACHE||`${r}/cdp-pages.json`,En=process.env.GREEDY_SEARCH_MODE_FILE||`${r}/browser-mode`,ln=process.env.GREEDY_SEARCH_METADATA_FILE||`${r}/browser-metadata.json`,on=process.env.GREEDY_SEARCH_LAUNCH_LOCK_FILE||`${r}/browser-launch.lock`,tn=process.env.GREEDY_SEARCH_ACTIVITY_FILE||`${r}/browser-last-activity`,gn=(process.env.CDP_SOCKET_DIR||`${r}/cdp-sockets`).replaceAll("\\","/"),cn=`${r}/visible-recovery.jsonl`,A=T(P(),".dm"),l=T(A,"greedyconfig"),D=["perplexity","google","chatgpt","gemini"],p="gemini";function k(){try{if(S(l)){let n=N(l,"utf8"),e=JSON.parse(n);if(Array.isArray(e.engines)&&e.engines.length>0&&e.engines.every((s)=>typeof s==="string")){let s=e.engines.filter((a)=>y[a]),i=e.engines.filter((a)=>!y[a]);if(i.length>0)process.stderr.write(`[greedysearch] Warning: ignoring unknown engine(s) in ${l}: ${i.join(", ")}
2
2
  [greedysearch] Available engines: ${Object.keys(y).join(", ")}
3
- `);if(n.length>0)return n;process.stderr.write(`[greedysearch] Warning: no valid engines in ${o}, falling back to defaults: ${h.join(", ")}
4
- `)}}}catch{}return h}function z(){try{if(!C(D))v(D,{recursive:!0});if(!C(o))P(o,JSON.stringify({engines:h,synthesizer:p},null,2)+`
5
- `,"utf8")}catch{}}z();var T=["gemini","chatgpt"];function V(){try{if(C(o)){let s=N(o,"utf8"),e=JSON.parse(s);if(typeof e.synthesizer==="string"){let n=e.synthesizer.toLowerCase();if(T.includes(n))return n;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${e.synthesizer}" in ${o}
6
- [greedysearch] Available synthesizers: ${T.join(", ")}
3
+ `);if(s.length>0)return s;process.stderr.write(`[greedysearch] Warning: no valid engines in ${l}, falling back to defaults: ${D.join(", ")}
4
+ `)}}}catch{}return D}function z(){try{if(!S(A))j(A,{recursive:!0});if(!S(l))w(l,JSON.stringify({engines:D,synthesizer:p},null,2)+`
5
+ `,"utf8")}catch{}}z();var L=["gemini","chatgpt"];function V(){try{if(S(l)){let n=N(l,"utf8"),e=JSON.parse(n);if(typeof e.synthesizer==="string"){let s=e.synthesizer.toLowerCase();if(L.includes(s))return s;process.stderr.write(`[greedysearch] Warning: unknown synthesizer "${e.synthesizer}" in ${l}
6
+ [greedysearch] Available synthesizers: ${L.join(", ")}
7
7
  [greedysearch] Falling back to default: ${p}
8
- `)}}}catch{}return p}var y={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"},cs=b();var _s=V(),Rs=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=r;import{existsSync as G}from"node:fs";import{dirname as B,join as S}from"node:path";import{fileURLToPath as K}from"node:url";function F(s){return K(new URL(".",s)).replace(/^\/([A-Z]:)/,"$1")}function Z(s,e=G){let n=new Set;for(let i of s.filter(Boolean)){if(n.has(i))continue;if(n.add(i),e(i))return i}return s.filter(Boolean).at(-1)}function $(s,{moduleDir:e,entrypoint:n=process.argv[1],env:i=process.env,exists:E=G}={}){let R=n?B(n):null,m=i.GREEDY_SEARCH_EXTENSION_DIR?.trim()||null;return Z([e?S(e,"..","..","extractors",s):null,e?S(e,"..","extractors",s):null,m?S(m,"extractors",s):null,R?S(R,"..","extractors",s):null],E)}var W=F(import.meta.url);function ps(s,e,n=null,i=!1,E=null,R=null){if(E===null)E=s.includes("logically")?120000:s.includes("chatgpt")?80000:s.includes("gemini")?70000:60000;let m=[...n?["--tab",n]:[],...i?["--short"]:[],...R?["--locale",R]:[]];return new Promise((H,f)=>{let O=$(s,{moduleDir:W}),c=J(L(),[O,"--stdin",...m],{stdio:["pipe","pipe","pipe"],env:{...process.env,CDP_PROFILE_DIR:r}});c.stdin.write(e),c.stdin.end();let _="",A="";c.stdout.on("data",(a)=>_+=a),c.stderr.on("data",(a)=>{if(A+=a,process.env.GREEDY_SEARCH_CHILD_STDERR!=="0")process.stderr.write(a)});let u=setTimeout(()=>{c.kill();let a=(t,I=20)=>String(t??"").split(/\r?\n/).filter(Boolean).slice(-I).join(`
9
- `),g=null;try{let t=JSON.parse(_.trim());if(t._envelope)g=t._envelope}catch{}let l=Error(`${s} timed out after ${E/1000}s`+(g?.lastStage?` (last stage: ${g.lastStage})`:""));l.engineScript=s,l.lastStage=g?.lastStage||null,l.partialErr=a(A),l.partialOut=a(_),f(l)},E);c.on("close",(a)=>{if(clearTimeout(u),a===0)try{H(JSON.parse(_.trim()))}catch{f(Error(`bad JSON from ${s}: ${_.slice(0,100)}`))}else{let g=null;try{let I=JSON.parse(_.trim());if(I._envelope)g=I._envelope}catch{}let l=A.trim()||`extractor exit ${a}`,t=Error(l);if(g)t.envelope=g;f(t)}})})}export{ps as runExtractor,y as ENGINES};
8
+ `)}}}catch{}return p}var y={perplexity:"perplexity.mjs",p:"perplexity.mjs",bing:"bing-copilot.mjs",b:"bing-copilot.mjs",google:"google-ai.mjs",g:"google-ai.mjs",gemini:"gemini.mjs",gem:"gemini.mjs",chatgpt:"chatgpt.mjs",gpt:"chatgpt.mjs","semantic-scholar":"semantic-scholar.mjs",semanticscholar:"semantic-scholar.mjs",s2:"semantic-scholar.mjs",logically:"logically.mjs",log:"logically.mjs"},_n=k();var Rn=V(),mn=Math.max(1,Number.parseInt(process.env.GREEDY_FETCH_CONCURRENCY||"5",10)||5);process.env.CDP_PROFILE_DIR=r;import{existsSync as Y}from"node:fs";import{dirname as B,join as h}from"node:path";import{fileURLToPath as K}from"node:url";function G(n){return K(new URL(".",n)).replace(/^\/([A-Z]:)/,"$1")}function Z(n,e=Y){let s=new Set;for(let i of n.filter(Boolean)){if(s.has(i))continue;if(s.add(i),e(i))return i}return n.filter(Boolean).at(-1)}function F(n,{moduleDir:e,entrypoint:s=process.argv[1],env:i=process.env,exists:a=Y}={}){let R=s?B(s):null,m=i.GREEDY_SEARCH_EXTENSION_DIR?.trim()||null;return Z([e?h(e,"..","..","extractors",n):null,e?h(e,"..","extractors",n):null,m?h(m,"extractors",n):null,R?h(R,"..","extractors",n):null],a)}var W=G(import.meta.url);function un(n,e,s=null,i=!1,a=null,R=null){if(a===null)a=n.includes("logically")?120000:n.includes("chatgpt")?80000:n.includes("gemini")?70000:60000;let m=[...s?["--tab",s]:[],...i?["--short"]:[],...R?["--locale",R]:[]];return new Promise((H,C)=>{let $=F(n,{moduleDir:W}),c=J(u(),[$,"--stdin",...m],{stdio:["pipe","pipe","pipe"],env:{...process.env,CDP_PROFILE_DIR:r}});c.stdin.write(e),c.stdin.end();let _="",f="";c.stdout.on("data",(E)=>_+=E),c.stderr.on("data",(E)=>{if(f+=E,process.env.GREEDY_SEARCH_CHILD_STDERR!=="0")process.stderr.write(E)});let O=setTimeout(()=>{c.kill();let E=(g,I=20)=>String(g??"").split(/\r?\n/).filter(Boolean).slice(-I).join(`
9
+ `),o=null;try{let g=JSON.parse(_.trim());if(g._envelope)o=g._envelope}catch{}let t=Error(`${n} timed out after ${a/1000}s`+(o?.lastStage?` (last stage: ${o.lastStage})`:""));t.engineScript=n,t.lastStage=o?.lastStage||null,t.partialErr=E(f),t.partialOut=E(_),C(t)},a);c.on("close",(E)=>{if(clearTimeout(O),E===0)try{H(JSON.parse(_.trim()))}catch{C(Error(`bad JSON from ${n}: ${_.slice(0,100)}`))}else{let o=null;try{let I=JSON.parse(_.trim());if(I._envelope)o=I._envelope}catch{}let t=f.trim()||`extractor exit ${E}`,g=Error(t);if(o)g.envelope=o;C(g)}})})}export{un as runExtractor,y as ENGINES};